(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = global || self, factory(global.Potree = {})); }(this, (function (exports) { 'use strict'; // threejs.org/license var REVISION='124';var MOUSE={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2};var TOUCH={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3};var CullFaceNone=0;var CullFaceBack=1;var CullFaceFront=2;var CullFaceFrontBack=3;var BasicShadowMap=0;var PCFShadowMap=1;var PCFSoftShadowMap=2;var VSMShadowMap=3;var FrontSide=0;var BackSide=1;var DoubleSide=2;var FlatShading$1=1;var SmoothShading=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 CineonToneMapping=3;var ACESFilmicToneMapping=4;var CustomToneMapping=5;var UVMapping=300;var CubeReflectionMapping=301;var CubeRefractionMapping=302;var EquirectangularReflectionMapping=303;var EquirectangularRefractionMapping=304;var CubeUVReflectionMapping=306;var CubeUVRefractionMapping=307;var RepeatWrapping=1000;var ClampToEdgeWrapping=1001;var MirroredRepeatWrapping=1002;var NearestFilter=1003;var NearestMipmapNearestFilter=1004;var NearestMipMapNearestFilter=1004;var NearestMipmapLinearFilter=1005;var NearestMipMapLinearFilter=1005;var LinearFilter=1006;var LinearMipmapNearestFilter=1007;var LinearMipMapNearestFilter=1007;var LinearMipmapLinearFilter=1008;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$1=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 RedFormat=1028;var RedIntegerFormat=1029;var RGFormat=1030;var RGIntegerFormat=1031;var RGBIntegerFormat=1032;var RGBAIntegerFormat=1033;var RGB_S3TC_DXT1_Format=33776;var RGBA_S3TC_DXT1_Format$1=33777;var RGBA_S3TC_DXT3_Format=33778;var RGBA_S3TC_DXT5_Format$1=33779;var RGB_PVRTC_4BPPV1_Format=35840;var RGB_PVRTC_2BPPV1_Format=35841;var RGBA_PVRTC_4BPPV1_Format=35842;var RGBA_PVRTC_2BPPV1_Format=35843;var RGB_ETC1_Format=36196;var RGB_ETC2_Format=37492;var RGBA_ETC2_EAC_Format=37496;var RGBA_ASTC_4x4_Format=37808;var RGBA_ASTC_5x4_Format=37809;var RGBA_ASTC_5x5_Format=37810;var RGBA_ASTC_6x5_Format=37811;var RGBA_ASTC_6x6_Format=37812;var RGBA_ASTC_8x5_Format=37813;var RGBA_ASTC_8x6_Format=37814;var RGBA_ASTC_8x8_Format=37815;var RGBA_ASTC_10x5_Format=37816;var RGBA_ASTC_10x6_Format=37817;var RGBA_ASTC_10x8_Format=37818;var RGBA_ASTC_10x10_Format=37819;var RGBA_ASTC_12x10_Format=37820;var RGBA_ASTC_12x12_Format=37821;var RGBA_BPTC_Format=36492;var SRGB8_ALPHA8_ASTC_4x4_Format=37840;var SRGB8_ALPHA8_ASTC_5x4_Format=37841;var SRGB8_ALPHA8_ASTC_5x5_Format=37842;var SRGB8_ALPHA8_ASTC_6x5_Format=37843;var SRGB8_ALPHA8_ASTC_6x6_Format=37844;var SRGB8_ALPHA8_ASTC_8x5_Format=37845;var SRGB8_ALPHA8_ASTC_8x6_Format=37846;var SRGB8_ALPHA8_ASTC_8x8_Format=37847;var SRGB8_ALPHA8_ASTC_10x5_Format=37848;var SRGB8_ALPHA8_ASTC_10x6_Format=37849;var SRGB8_ALPHA8_ASTC_10x8_Format=37850;var SRGB8_ALPHA8_ASTC_10x10_Format=37851;var SRGB8_ALPHA8_ASTC_12x10_Format=37852;var SRGB8_ALPHA8_ASTC_12x12_Format=37853;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 NormalAnimationBlendMode=2500;var AdditiveAnimationBlendMode=2501;var TrianglesDrawMode=0;var TriangleStripDrawMode=1;var TriangleFanDrawMode=2;var LinearEncoding=3000;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 TangentSpaceNormalMap=0;var ObjectSpaceNormalMap=1;var ZeroStencilOp=0;var KeepStencilOp=7680;var ReplaceStencilOp=7681;var IncrementStencilOp=7682;var DecrementStencilOp=7683;var IncrementWrapStencilOp=34055;var DecrementWrapStencilOp=34056;var InvertStencilOp=5386;var NeverStencilFunc=512;var LessStencilFunc=513;var EqualStencilFunc=514;var LessEqualStencilFunc=515;var GreaterStencilFunc=516;var NotEqualStencilFunc=517;var GreaterEqualStencilFunc=518;var AlwaysStencilFunc=519;var StaticDrawUsage=35044;var DynamicDrawUsage=35048;var StreamDrawUsage=35040;var StaticReadUsage=35045;var DynamicReadUsage=35049;var StreamReadUsage=35041;var StaticCopyUsage=35046;var DynamicCopyUsage=35050;var StreamCopyUsage=35042;var GLSL1='100';var GLSL3='300 es';/** * https://github.com/mrdoob/eventdispatcher.js/ */function EventDispatcher(){}Object.assign(EventDispatcher.prototype,{addEventListener:function addEventListener(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 hasEventListener(type,listener){if(this._listeners===undefined)return false;var listeners=this._listeners;return listeners[type]!==undefined&&listeners[type].indexOf(listener)!==-1;},dispatchEvent:function dispatchEvent(event){if(this._listeners===undefined)return;var listeners=this._listeners;var listenerArray=listeners[event.type];if(listenerArray!==undefined){event.target=this;// Make a copy, in case listeners are removed while iterating. var array=listenerArray.slice(0);for(var i=0,l=array.length;i>8&0xff]+_lut[d0>>16&0xff]+_lut[d0>>24&0xff]+'-'+_lut[d1&0xff]+_lut[d1>>8&0xff]+'-'+_lut[d1>>16&0x0f|0x40]+_lut[d1>>24&0xff]+'-'+_lut[d2&0x3f|0x80]+_lut[d2>>8&0xff]+'-'+_lut[d2>>16&0xff]+_lut[d2>>24&0xff]+_lut[d3&0xff]+_lut[d3>>8&0xff]+_lut[d3>>16&0xff]+_lut[d3>>24&0xff];// .toUpperCase() here flattens concatenated strings to save heap memory space. return uuid.toUpperCase();},clamp:function clamp(value,min,max){return Math.max(min,Math.min(max,value));},// compute euclidian modulo of m % n // https://en.wikipedia.org/wiki/Modulo_operation euclideanModulo:function euclideanModulo(n,m){return (n%m+m)%m;},// Linear mapping from range to range mapLinear:function mapLinear(x,a1,a2,b1,b2){return b1+(x-a1)*(b2-b1)/(a2-a1);},// https://en.wikipedia.org/wiki/Linear_interpolation lerp:function lerp(x,y,t){return (1-t)*x+t*y;},// http://en.wikipedia.org/wiki/Smoothstep smoothstep:function smoothstep(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 smootherstep(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);},// Random integer from interval randInt:function randInt(low,high){return low+Math.floor(Math.random()*(high-low+1));},// Random float from interval randFloat:function randFloat(low,high){return low+Math.random()*(high-low);},// Random float from <-range/2, range/2> interval randFloatSpread:function randFloatSpread(range){return range*(0.5-Math.random());},// Deterministic pseudo-random float in the interval [ 0, 1 ] seededRandom:function seededRandom(s){if(s!==undefined)_seed=s%2147483647;// Park-Miller algorithm _seed=_seed*16807%2147483647;return (_seed-1)/2147483646;},degToRad:function degToRad(degrees){return degrees*MathUtils.DEG2RAD;},radToDeg:function radToDeg(radians){return radians*MathUtils.RAD2DEG;},isPowerOfTwo:function isPowerOfTwo(value){return (value&value-1)===0&&value!==0;},ceilPowerOfTwo:function ceilPowerOfTwo(value){return Math.pow(2,Math.ceil(Math.log(value)/Math.LN2));},floorPowerOfTwo:function floorPowerOfTwo(value){return Math.pow(2,Math.floor(Math.log(value)/Math.LN2));},setQuaternionFromProperEuler:function setQuaternionFromProperEuler(q,a,b,c,order){// Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles // rotations are applied to the axes in the order specified by 'order' // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c' // angles are in radians var cos=Math.cos;var sin=Math.sin;var c2=cos(b/2);var s2=sin(b/2);var c13=cos((a+c)/2);var s13=sin((a+c)/2);var c1_3=cos((a-c)/2);var s1_3=sin((a-c)/2);var c3_1=cos((c-a)/2);var s3_1=sin((c-a)/2);switch(order){case'XYX':q.set(c2*s13,s2*c1_3,s2*s1_3,c2*c13);break;case'YZY':q.set(s2*s1_3,c2*s13,s2*c1_3,c2*c13);break;case'ZXZ':q.set(s2*c1_3,s2*s1_3,c2*s13,c2*c13);break;case'XZX':q.set(c2*s13,s2*s3_1,s2*c3_1,c2*c13);break;case'YXY':q.set(s2*c3_1,c2*s13,s2*s3_1,c2*c13);break;case'ZYZ':q.set(s2*s3_1,s2*c3_1,c2*s13,c2*c13);break;default:console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: '+order);}}};class Vector2{constructor(){var x=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;Object.defineProperty(this,'isVector2',{value:true});this.x=x;this.y=y;}get width(){return this.x;}set width(value){this.x=value;}get height(){return this.y;}set height(value){this.y=value;}set(x,y){this.x=x;this.y=y;return this;}setScalar(scalar){this.x=scalar;this.y=scalar;return this;}setX(x){this.x=x;return this;}setY(y){this.y=y;return this;}setComponent(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(index){switch(index){case 0:return this.x;case 1:return this.y;default:throw new Error('index is out of range: '+index);}}clone(){return new this.constructor(this.x,this.y);}copy(v){this.x=v.x;this.y=v.y;return this;}add(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(s){this.x+=s;this.y+=s;return this;}addVectors(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this;}addScaledVector(v,s){this.x+=v.x*s;this.y+=v.y*s;return this;}sub(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(s){this.x-=s;this.y-=s;return this;}subVectors(a,b){this.x=a.x-b.x;this.y=a.y-b.y;return this;}multiply(v){this.x*=v.x;this.y*=v.y;return this;}multiplyScalar(scalar){this.x*=scalar;this.y*=scalar;return this;}divide(v){this.x/=v.x;this.y/=v.y;return this;}divideScalar(scalar){return this.multiplyScalar(1/scalar);}applyMatrix3(m){var x=this.x,y=this.y;var e=m.elements;this.x=e[0]*x+e[3]*y+e[6];this.y=e[1]*x+e[4]*y+e[7];return this;}min(v){this.x=Math.min(this.x,v.x);this.y=Math.min(this.y,v.y);return this;}max(v){this.x=Math.max(this.x,v.x);this.y=Math.max(this.y,v.y);return this;}clamp(min,max){// assumes min < max, componentwise 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(minVal,maxVal){this.x=Math.max(minVal,Math.min(maxVal,this.x));this.y=Math.max(minVal,Math.min(maxVal,this.y));return this;}clampLength(min,max){var length=this.length();return this.divideScalar(length||1).multiplyScalar(Math.max(min,Math.min(max,length)));}floor(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this;}ceil(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this;}round(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this;}roundToZero(){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(){this.x=-this.x;this.y=-this.y;return this;}dot(v){return this.x*v.x+this.y*v.y;}cross(v){return this.x*v.y-this.y*v.x;}lengthSq(){return this.x*this.x+this.y*this.y;}length(){return Math.sqrt(this.x*this.x+this.y*this.y);}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y);}normalize(){return this.divideScalar(this.length()||1);}angle(){// computes the angle in radians with respect to the positive x-axis var angle=Math.atan2(-this.y,-this.x)+Math.PI;return angle;}distanceTo(v){return Math.sqrt(this.distanceToSquared(v));}distanceToSquared(v){var dx=this.x-v.x,dy=this.y-v.y;return dx*dx+dy*dy;}manhattanDistanceTo(v){return Math.abs(this.x-v.x)+Math.abs(this.y-v.y);}setLength(length){return this.normalize().multiplyScalar(length);}lerp(v,alpha){this.x+=(v.x-this.x)*alpha;this.y+=(v.y-this.y)*alpha;return this;}lerpVectors(v1,v2,alpha){this.x=v1.x+(v2.x-v1.x)*alpha;this.y=v1.y+(v2.y-v1.y)*alpha;return this;}equals(v){return v.x===this.x&&v.y===this.y;}fromArray(array){var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;this.x=array[offset];this.y=array[offset+1];return this;}toArray(){var array=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;array[offset]=this.x;array[offset+1]=this.y;return array;}fromBufferAttribute(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(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;}random(){this.x=Math.random();this.y=Math.random();return this;}}class Matrix3{constructor(){Object.defineProperty(this,'isMatrix3',{value:true});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.');}}set(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(){this.set(1,0,0,0,1,0,0,0,1);return this;}clone(){return new this.constructor().fromArray(this.elements);}copy(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;}extractBasis(xAxis,yAxis,zAxis){xAxis.setFromMatrix3Column(this,0);yAxis.setFromMatrix3Column(this,1);zAxis.setFromMatrix3Column(this,2);return this;}setFromMatrix4(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;}multiply(m){return this.multiplyMatrices(this,m);}premultiply(m){return this.multiplyMatrices(m,this);}multiplyMatrices(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(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(){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;}invert(){var te=this.elements,n11=te[0],n21=te[1],n31=te[2],n12=te[3],n22=te[4],n32=te[5],n13=te[6],n23=te[7],n33=te[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)return this.set(0,0,0,0,0,0,0,0,0);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(){var tmp;var 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(matrix4){return this.setFromMatrix4(matrix4).copy(this).invert().transpose();}transposeIntoArray(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;}setUvTransform(tx,ty,sx,sy,rotation,cx,cy){var c=Math.cos(rotation);var s=Math.sin(rotation);this.set(sx*c,sx*s,-sx*(c*cx+s*cy)+cx+tx,-sy*s,sy*c,-sy*(-s*cx+c*cy)+cy+ty,0,0,1);return this;}scale(sx,sy){var te=this.elements;te[0]*=sx;te[3]*=sx;te[6]*=sx;te[1]*=sy;te[4]*=sy;te[7]*=sy;return this;}rotate(theta){var c=Math.cos(theta);var s=Math.sin(theta);var te=this.elements;var a11=te[0],a12=te[3],a13=te[6];var a21=te[1],a22=te[4],a23=te[7];te[0]=c*a11+s*a21;te[3]=c*a12+s*a22;te[6]=c*a13+s*a23;te[1]=-s*a11+c*a21;te[4]=-s*a12+c*a22;te[7]=-s*a13+c*a23;return this;}translate(tx,ty){var te=this.elements;te[0]+=tx*te[2];te[3]+=tx*te[5];te[6]+=tx*te[8];te[1]+=ty*te[2];te[4]+=ty*te[5];te[7]+=ty*te[8];return this;}equals(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(array){var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;for(var _i2=0;_i2<9;_i2++){this.elements[_i2]=array[_i2+offset];}return this;}toArray(){var array=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]: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;}}var _canvas;var ImageUtils={getDataURL:function getDataURL(image){if(/^data:/i.test(image.src)){return image.src;}if(typeof HTMLCanvasElement=='undefined'){return image.src;}var canvas;if(image instanceof HTMLCanvasElement){canvas=image;}else {if(_canvas===undefined)_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);}canvas=_canvas;}if(canvas.width>2048||canvas.height>2048){return canvas.toDataURL('image/jpeg',0.6);}else {return canvas.toDataURL('image/png');}}};var textureId=0;function Texture(){var image=arguments.length>0&&arguments[0]!==undefined?arguments[0]:Texture.DEFAULT_IMAGE;var mapping=arguments.length>1&&arguments[1]!==undefined?arguments[1]:Texture.DEFAULT_MAPPING;var wrapS=arguments.length>2&&arguments[2]!==undefined?arguments[2]:ClampToEdgeWrapping;var wrapT=arguments.length>3&&arguments[3]!==undefined?arguments[3]:ClampToEdgeWrapping;var magFilter=arguments.length>4&&arguments[4]!==undefined?arguments[4]:LinearFilter;var minFilter=arguments.length>5&&arguments[5]!==undefined?arguments[5]:LinearMipmapLinearFilter;var format=arguments.length>6&&arguments[6]!==undefined?arguments[6]:RGBAFormat;var type=arguments.length>7&&arguments[7]!==undefined?arguments[7]:UnsignedByteType;var anisotropy=arguments.length>8&&arguments[8]!==undefined?arguments[8]:1;var encoding=arguments.length>9&&arguments[9]!==undefined?arguments[9]:LinearEncoding;Object.defineProperty(this,'id',{value:textureId++});this.uuid=MathUtils.generateUUID();this.name='';this.image=image;this.mipmaps=[];this.mapping=mapping;this.wrapS=wrapS;this.wrapT=wrapT;this.magFilter=magFilter;this.minFilter=minFilter;this.anisotropy=anisotropy;this.format=format;this.internalFormat=null;this.type=type;this.offset=new Vector2(0,0);this.repeat=new Vector2(1,1);this.center=new Vector2(0,0);this.rotation=0;this.matrixAutoUpdate=true;this.matrix=new Matrix3();this.generateMipmaps=true;this.premultiplyAlpha=false;this.flipY=true;this.unpackAlignment=4;// valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml) // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap. // // Also changing the encoding after already used by a Material will not automatically make the Material // update. You need to explicitly call Material.needsUpdate to trigger it to recompile. this.encoding=encoding;this.version=0;this.onUpdate=null;}Texture.DEFAULT_IMAGE=undefined;Texture.DEFAULT_MAPPING=UVMapping;Texture.prototype=Object.assign(Object.create(EventDispatcher.prototype),{constructor:Texture,isTexture:true,updateMatrix:function updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y);},clone:function clone(){return new this.constructor().copy(this);},copy:function copy(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.internalFormat=source.internalFormat;this.type=source.type;this.offset.copy(source.offset);this.repeat.copy(source.repeat);this.center.copy(source.center);this.rotation=source.rotation;this.matrixAutoUpdate=source.matrixAutoUpdate;this.matrix.copy(source.matrix);this.generateMipmaps=source.generateMipmaps;this.premultiplyAlpha=source.premultiplyAlpha;this.flipY=source.flipY;this.unpackAlignment=source.unpackAlignment;this.encoding=source.encoding;return this;},toJSON:function toJSON(meta){var isRootObject=meta===undefined||typeof meta==='string';if(!isRootObject&&meta.textures[this.uuid]!==undefined){return meta.textures[this.uuid];}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],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,type:this.type,encoding:this.encoding,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};if(this.image!==undefined){// TODO: Move to THREE.Image var image=this.image;if(image.uuid===undefined){image.uuid=MathUtils.generateUUID();// UGH }if(!isRootObject&&meta.images[image.uuid]===undefined){var url;if(Array.isArray(image)){// process array of images e.g. CubeTexture url=[];for(var _i3=0,l=image.length;_i31){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;}return uv;}});Object.defineProperty(Texture.prototype,'needsUpdate',{set:function set(value){if(value===true)this.version++;}});function serializeImage(image){if(typeof HTMLImageElement!=='undefined'&&image instanceof HTMLImageElement||typeof HTMLCanvasElement!=='undefined'&&image instanceof HTMLCanvasElement||typeof ImageBitmap!=='undefined'&&image instanceof ImageBitmap){// default images return ImageUtils.getDataURL(image);}else {if(image.data){// images of DataTexture return {data:Array.prototype.slice.call(image.data),width:image.width,height:image.height,type:image.data.constructor.name};}else {console.warn('THREE.Texture: Unable to serialize Texture.');return {};}}}class Vector4{constructor(){var x=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var z=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var w=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;Object.defineProperty(this,'isVector4',{value:true});this.x=x;this.y=y;this.z=z;this.w=w;}get width(){return this.z;}set width(value){this.z=value;}get height(){return this.w;}set height(value){this.w=value;}set(x,y,z,w){this.x=x;this.y=y;this.z=z;this.w=w;return this;}setScalar(scalar){this.x=scalar;this.y=scalar;this.z=scalar;this.w=scalar;return this;}setX(x){this.x=x;return this;}setY(y){this.y=y;return this;}setZ(z){this.z=z;return this;}setW(w){this.w=w;return this;}setComponent(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(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(){return new this.constructor(this.x,this.y,this.z,this.w);}copy(v){this.x=v.x;this.y=v.y;this.z=v.z;this.w=v.w!==undefined?v.w:1;return this;}add(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(s){this.x+=s;this.y+=s;this.z+=s;this.w+=s;return this;}addVectors(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(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(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(s){this.x-=s;this.y-=s;this.z-=s;this.w-=s;return this;}subVectors(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(scalar){this.x*=scalar;this.y*=scalar;this.z*=scalar;this.w*=scalar;return this;}applyMatrix4(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(scalar){return this.multiplyScalar(1/scalar);}setAxisAngleFromQuaternion(q){// http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm // q is assumed to be normalized this.w=2*Math.acos(q.w);var s=Math.sqrt(1-q.w*q.w);if(s<0.0001){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(m){// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) var angle,x,y,z;// variables for result var epsilon=0.01,// margin to allow for rounding errors epsilon2=0.1,// margin to distinguish between 0 and 180 degrees 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)yy&&xx>zz){// m11 is the largest diagonal term if(xxzz){// m22 is the largest diagonal term if(yy1&&arguments[1]!==undefined?arguments[1]:0;this.x=array[offset];this.y=array[offset+1];this.z=array[offset+2];this.w=array[offset+3];return this;}toArray(){var array=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;array[offset]=this.x;array[offset+1]=this.y;array[offset+2]=this.z;array[offset+3]=this.w;return array;}fromBufferAttribute(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;}random(){this.x=Math.random();this.y=Math.random();this.z=Math.random();this.w=Math.random();return this;}}/* In options, we can specify: * Texture parameters for an auto-generated target texture * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers */function WebGLRenderTarget(width,height,options){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||{};this.texture=new Texture(undefined,options.mapping,options.wrapS,options.wrapT,options.magFilter,options.minFilter,options.format,options.type,options.anisotropy,options.encoding);this.texture.image={};this.texture.image.width=width;this.texture.image.height=height;this.texture.generateMipmaps=options.generateMipmaps!==undefined?options.generateMipmaps:false;this.texture.minFilter=options.minFilter!==undefined?options.minFilter:LinearFilter;this.depthBuffer=options.depthBuffer!==undefined?options.depthBuffer:true;this.stencilBuffer=options.stencilBuffer!==undefined?options.stencilBuffer:false;this.depthTexture=options.depthTexture!==undefined?options.depthTexture:null;}WebGLRenderTarget.prototype=Object.assign(Object.create(EventDispatcher.prototype),{constructor:WebGLRenderTarget,isWebGLRenderTarget:true,setSize:function setSize(width,height){if(this.width!==width||this.height!==height){this.width=width;this.height=height;this.texture.image.width=width;this.texture.image.height=height;this.dispose();}this.viewport.set(0,0,width,height);this.scissor.set(0,0,width,height);},clone:function clone(){return new this.constructor().copy(this);},copy:function copy(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 dispose(){this.dispatchEvent({type:'dispose'});}});function WebGLMultisampleRenderTarget(width,height,options){WebGLRenderTarget.call(this,width,height,options);this.samples=4;}WebGLMultisampleRenderTarget.prototype=Object.assign(Object.create(WebGLRenderTarget.prototype),{constructor:WebGLMultisampleRenderTarget,isWebGLMultisampleRenderTarget:true,copy:function copy(source){WebGLRenderTarget.prototype.copy.call(this,source);this.samples=source.samples;return this;}});class Quaternion{constructor(){var x=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var z=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var w=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;Object.defineProperty(this,'isQuaternion',{value:true});this._x=x;this._y=y;this._z=z;this._w=w;}static slerp(qa,qb,qm,t){return qm.copy(qa).slerp(qb,t);}static slerpFlat(dst,dstOffset,src0,srcOffset0,src1,srcOffset1,t){// fuzz-free, array-based Quaternion SLERP operation var x0=src0[srcOffset0+0],y0=src0[srcOffset0+1],z0=src0[srcOffset0+2],w0=src0[srcOffset0+3];var 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;var cos=x0*x1+y0*y1+z0*z1+w0*w1,dir=cos>=0?1:-1,sqrSin=1-cos*cos;// Skip the Slerp for tiny steps to avoid numeric problems: 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;// Normalize in case we just did a lerp: 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;}static multiplyQuaternionsFlat(dst,dstOffset,src0,srcOffset0,src1,srcOffset1){var x0=src0[srcOffset0];var y0=src0[srcOffset0+1];var z0=src0[srcOffset0+2];var w0=src0[srcOffset0+3];var x1=src1[srcOffset1];var y1=src1[srcOffset1+1];var z1=src1[srcOffset1+2];var w1=src1[srcOffset1+3];dst[dstOffset]=x0*w1+w0*x1+y0*z1-z0*y1;dst[dstOffset+1]=y0*w1+w0*y1+z0*x1-x0*z1;dst[dstOffset+2]=z0*w1+w0*z1+x0*y1-y0*x1;dst[dstOffset+3]=w0*w1-x0*x1-y0*y1-z0*z1;return dst;}get x(){return this._x;}set x(value){this._x=value;this._onChangeCallback();}get y(){return this._y;}set y(value){this._y=value;this._onChangeCallback();}get z(){return this._z;}set z(value){this._z=value;this._onChangeCallback();}get w(){return this._w;}set w(value){this._w=value;this._onChangeCallback();}set(x,y,z,w){this._x=x;this._y=y;this._z=z;this._w=w;this._onChangeCallback();return this;}clone(){return new this.constructor(this._x,this._y,this._z,this._w);}copy(quaternion){this._x=quaternion.x;this._y=quaternion.y;this._z=quaternion.z;this._w=quaternion.w;this._onChangeCallback();return this;}setFromEuler(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;// http://www.mathworks.com/matlabcentral/fileexchange/ // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ // content/SpinCalc.m 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);switch(order){case'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;break;case'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;break;case'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;break;case'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;break;case'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;break;case'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;break;default:console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: '+order);}if(update!==false)this._onChangeCallback();return this;}setFromAxisAngle(axis,angle){// http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm // assumes axis is normalized 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(m){// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) 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;if(trace>0){var s=0.5/Math.sqrt(trace+1.0);this._w=0.25/s;this._x=(m32-m23)*s;this._y=(m13-m31)*s;this._z=(m21-m12)*s;}else if(m11>m22&&m11>m33){var _s=2.0*Math.sqrt(1.0+m11-m22-m33);this._w=(m32-m23)/_s;this._x=0.25*_s;this._y=(m12+m21)/_s;this._z=(m13+m31)/_s;}else if(m22>m33){var _s2=2.0*Math.sqrt(1.0+m22-m11-m33);this._w=(m13-m31)/_s2;this._x=(m12+m21)/_s2;this._y=0.25*_s2;this._z=(m23+m32)/_s2;}else {var _s3=2.0*Math.sqrt(1.0+m33-m11-m22);this._w=(m21-m12)/_s3;this._x=(m13+m31)/_s3;this._y=(m23+m32)/_s3;this._z=0.25*_s3;}this._onChangeCallback();return this;}setFromUnitVectors(vFrom,vTo){// assumes direction vectors vFrom and vTo are normalized var EPS=0.000001;var r=vFrom.dot(vTo)+1;if(rMath.abs(vFrom.z)){this._x=-vFrom.y;this._y=vFrom.x;this._z=0;this._w=r;}else {this._x=0;this._y=-vFrom.z;this._z=vFrom.y;this._w=r;}}else {// crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3 this._x=vFrom.y*vTo.z-vFrom.z*vTo.y;this._y=vFrom.z*vTo.x-vFrom.x*vTo.z;this._z=vFrom.x*vTo.y-vFrom.y*vTo.x;this._w=r;}return this.normalize();}angleTo(q){return 2*Math.acos(Math.abs(MathUtils.clamp(this.dot(q),-1,1)));}rotateTowards(q,step){var angle=this.angleTo(q);if(angle===0)return this;var t=Math.min(1,step/angle);this.slerp(q,t);return this;}identity(){return this.set(0,0,0,1);}invert(){// quaternion is assumed to have unit length return this.conjugate();}conjugate(){this._x*=-1;this._y*=-1;this._z*=-1;this._onChangeCallback();return this;}dot(v){return this._x*v._x+this._y*v._y+this._z*v._z+this._w*v._w;}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w;}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w);}normalize(){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(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(q){return this.multiplyQuaternions(q,this);}multiplyQuaternions(a,b){// from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm 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(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;// http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ 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.0){this._w=w;this._x=x;this._y=y;this._z=z;return this;}var sqrSinHalfTheta=1.0-cosHalfTheta*cosHalfTheta;if(sqrSinHalfTheta<=Number.EPSILON){var s=1-t;this._w=s*w+t*this._w;this._x=s*x+t*this._x;this._y=s*y+t*this._y;this._z=s*z+t*this._z;this.normalize();this._onChangeCallback();return this;}var sinHalfTheta=Math.sqrt(sqrSinHalfTheta);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(quaternion){return quaternion._x===this._x&&quaternion._y===this._y&&quaternion._z===this._z&&quaternion._w===this._w;}fromArray(array){var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]: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(){var array=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;array[offset]=this._x;array[offset+1]=this._y;array[offset+2]=this._z;array[offset+3]=this._w;return array;}fromBufferAttribute(attribute,index){this._x=attribute.getX(index);this._y=attribute.getY(index);this._z=attribute.getZ(index);this._w=attribute.getW(index);return this;}_onChange(callback){this._onChangeCallback=callback;return this;}_onChangeCallback(){}}class Vector3{constructor(){var x=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var z=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;Object.defineProperty(this,'isVector3',{value:true});this.x=x;this.y=y;this.z=z;}set(x,y,z){if(z===undefined)z=this.z;// sprite.scale.set(x,y) this.x=x;this.y=y;this.z=z;return this;}setScalar(scalar){this.x=scalar;this.y=scalar;this.z=scalar;return this;}setX(x){this.x=x;return this;}setY(y){this.y=y;return this;}setZ(z){this.z=z;return this;}setComponent(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(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(){return new this.constructor(this.x,this.y,this.z);}copy(v){this.x=v.x;this.y=v.y;this.z=v.z;return this;}add(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(s){this.x+=s;this.y+=s;this.z+=s;return this;}addVectors(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this;}addScaledVector(v,s){this.x+=v.x*s;this.y+=v.y*s;this.z+=v.z*s;return this;}sub(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(s){this.x-=s;this.y-=s;this.z-=s;return this;}subVectors(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;return this;}multiply(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(scalar){this.x*=scalar;this.y*=scalar;this.z*=scalar;return this;}multiplyVectors(a,b){this.x=a.x*b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this;}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(axis,angle){return this.applyQuaternion(_quaternion.setFromAxisAngle(axis,angle));}applyMatrix3(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;}applyNormalMatrix(m){return this.applyMatrix3(m).normalize();}applyMatrix4(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(q){var x=this.x,y=this.y,z=this.z;var qx=q.x,qy=q.y,qz=q.z,qw=q.w;// calculate quat * vector 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;// calculate result * inverse quat 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(camera){return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);}unproject(camera){return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);}transformDirection(m){// input: THREE.Matrix4 affine matrix // vector interpreted as a direction 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(v){this.x/=v.x;this.y/=v.y;this.z/=v.z;return this;}divideScalar(scalar){return this.multiplyScalar(1/scalar);}min(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(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(min,max){// assumes min < max, componentwise 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(minVal,maxVal){this.x=Math.max(minVal,Math.min(maxVal,this.x));this.y=Math.max(minVal,Math.min(maxVal,this.y));this.z=Math.max(minVal,Math.min(maxVal,this.z));return this;}clampLength(min,max){var length=this.length();return this.divideScalar(length||1).multiplyScalar(Math.max(min,Math.min(max,length)));}floor(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);return this;}ceil(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this;}round(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);return this;}roundToZero(){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(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this;}dot(v){return this.x*v.x+this.y*v.y+this.z*v.z;}// TODO lengthSquared? lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z;}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z);}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z);}normalize(){return this.divideScalar(this.length()||1);}setLength(length){return this.normalize().multiplyScalar(length);}lerp(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(v1,v2,alpha){this.x=v1.x+(v2.x-v1.x)*alpha;this.y=v1.y+(v2.y-v1.y)*alpha;this.z=v1.z+(v2.z-v1.z)*alpha;return this;}cross(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);}return this.crossVectors(this,v);}crossVectors(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(v){var denominator=v.lengthSq();if(denominator===0)return this.set(0,0,0);var scalar=v.dot(this)/denominator;return this.copy(v).multiplyScalar(scalar);}projectOnPlane(planeNormal){_vector.copy(this).projectOnVector(planeNormal);return this.sub(_vector);}reflect(normal){// reflect incident vector off plane orthogonal to normal // normal is assumed to have unit length return this.sub(_vector.copy(normal).multiplyScalar(2*this.dot(normal)));}angleTo(v){var denominator=Math.sqrt(this.lengthSq()*v.lengthSq());if(denominator===0)return Math.PI/2;var theta=this.dot(v)/denominator;// clamp, to handle numerical problems return Math.acos(MathUtils.clamp(theta,-1,1));}distanceTo(v){return Math.sqrt(this.distanceToSquared(v));}distanceToSquared(v){var dx=this.x-v.x,dy=this.y-v.y,dz=this.z-v.z;return dx*dx+dy*dy+dz*dz;}manhattanDistanceTo(v){return Math.abs(this.x-v.x)+Math.abs(this.y-v.y)+Math.abs(this.z-v.z);}setFromSpherical(s){return this.setFromSphericalCoords(s.radius,s.phi,s.theta);}setFromSphericalCoords(radius,phi,theta){var sinPhiRadius=Math.sin(phi)*radius;this.x=sinPhiRadius*Math.sin(theta);this.y=Math.cos(phi)*radius;this.z=sinPhiRadius*Math.cos(theta);return this;}setFromCylindrical(c){return this.setFromCylindricalCoords(c.radius,c.theta,c.y);}setFromCylindricalCoords(radius,theta,y){this.x=radius*Math.sin(theta);this.y=y;this.z=radius*Math.cos(theta);return this;}setFromMatrixPosition(m){var e=m.elements;this.x=e[12];this.y=e[13];this.z=e[14];return this;}setFromMatrixScale(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(m,index){return this.fromArray(m.elements,index*4);}setFromMatrix3Column(m,index){return this.fromArray(m.elements,index*3);}equals(v){return v.x===this.x&&v.y===this.y&&v.z===this.z;}fromArray(array){var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;this.x=array[offset];this.y=array[offset+1];this.z=array[offset+2];return this;}toArray(){var array=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;array[offset]=this.x;array[offset+1]=this.y;array[offset+2]=this.z;return array;}fromBufferAttribute(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;}random(){this.x=Math.random();this.y=Math.random();this.z=Math.random();return this;}}var _vector=/*@__PURE__*/new Vector3();var _quaternion=/*@__PURE__*/new Quaternion();class Box3{constructor(min,max){Object.defineProperty(this,'isBox3',{value:true});this.min=min!==undefined?min:new Vector3(+Infinity,+Infinity,+Infinity);this.max=max!==undefined?max:new Vector3(-Infinity,-Infinity,-Infinity);}set(min,max){this.min.copy(min);this.max.copy(max);return this;}setFromArray(array){var minX=+Infinity;var minY=+Infinity;var minZ=+Infinity;var maxX=-Infinity;var maxY=-Infinity;var maxZ=-Infinity;for(var _i4=0,l=array.length;_i4maxX)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(attribute){var minX=+Infinity;var minY=+Infinity;var minZ=+Infinity;var maxX=-Infinity;var maxY=-Infinity;var maxZ=-Infinity;for(var _i5=0,l=attribute.count;_i5maxX)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(points){this.makeEmpty();for(var _i6=0,il=points.length;_i6this.max.x||point.ythis.max.y||point.zthis.max.z?false:true;}containsBox(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(point,target){// This can potentially have a divide by zero if the box // has a size dimension of 0. if(target===undefined){console.warn('THREE.Box3: .getParameter() target is now required');target=new Vector3();}return target.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(box){// using 6 splitting planes to rule out intersections. return box.max.xthis.max.x||box.max.ythis.max.y||box.max.zthis.max.z?false:true;}intersectsSphere(sphere){// Find the point on the AABB closest to the sphere center. this.clampPoint(sphere.center,_vector$1);// If that point is inside the sphere, the AABB and sphere intersect. return _vector$1.distanceToSquared(sphere.center)<=sphere.radius*sphere.radius;}intersectsPlane(plane){// We compute the minimum and maximum dot product values. If those values // are on the same side (back or front) of the plane, then there is no intersection. 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;}intersectsTriangle(triangle){if(this.isEmpty()){return false;}// compute box center and extents this.getCenter(_center);_extents.subVectors(this.max,_center);// translate triangle to aabb origin _v0.subVectors(triangle.a,_center);_v1.subVectors(triangle.b,_center);_v2.subVectors(triangle.c,_center);// compute edge vectors for triangle _f0.subVectors(_v1,_v0);_f1.subVectors(_v2,_v1);_f2.subVectors(_v0,_v2);// test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned) var axes=[0,-_f0.z,_f0.y,0,-_f1.z,_f1.y,0,-_f2.z,_f2.y,_f0.z,0,-_f0.x,_f1.z,0,-_f1.x,_f2.z,0,-_f2.x,-_f0.y,_f0.x,0,-_f1.y,_f1.x,0,-_f2.y,_f2.x,0];if(!satForAxes(axes,_v0,_v1,_v2,_extents)){return false;}// test 3 face normals from the aabb axes=[1,0,0,0,1,0,0,0,1];if(!satForAxes(axes,_v0,_v1,_v2,_extents)){return false;}// finally testing the face normal of the triangle // use already existing triangle edge vectors here _triangleNormal.crossVectors(_f0,_f1);axes=[_triangleNormal.x,_triangleNormal.y,_triangleNormal.z];return satForAxes(axes,_v0,_v1,_v2,_extents);}clampPoint(point,target){if(target===undefined){console.warn('THREE.Box3: .clampPoint() target is now required');target=new Vector3();}return target.copy(point).clamp(this.min,this.max);}distanceToPoint(point){var clampedPoint=_vector$1.copy(point).clamp(this.min,this.max);return clampedPoint.sub(point).length();}getBoundingSphere(target){if(target===undefined){console.error('THREE.Box3: .getBoundingSphere() target is now required');//target = new Sphere(); // removed to avoid cyclic dependency }this.getCenter(target.center);target.radius=this.getSize(_vector$1).length()*0.5;return target;}intersect(box){this.min.max(box.min);this.max.min(box.max);// ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values. if(this.isEmpty())this.makeEmpty();return this;}union(box){this.min.min(box.min);this.max.max(box.max);return this;}applyMatrix4(matrix){// transform of empty box is an empty box. if(this.isEmpty())return this;// NOTE: I am using a binary pattern to specify all 2^3 combinations below _points[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(matrix);// 000 _points[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(matrix);// 001 _points[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(matrix);// 010 _points[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(matrix);// 011 _points[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(matrix);// 100 _points[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(matrix);// 101 _points[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(matrix);// 110 _points[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(matrix);// 111 this.setFromPoints(_points);return this;}translate(offset){this.min.add(offset);this.max.add(offset);return this;}equals(box){return box.min.equals(this.min)&&box.max.equals(this.max);}}function satForAxes(axes,v0,v1,v2,extents){for(var _i8=0,j=axes.length-3;_i8<=j;_i8+=3){_testAxis.fromArray(axes,_i8);// project the aabb onto the seperating axis var r=extents.x*Math.abs(_testAxis.x)+extents.y*Math.abs(_testAxis.y)+extents.z*Math.abs(_testAxis.z);// project all 3 vertices of the triangle onto the seperating axis var p0=v0.dot(_testAxis);var p1=v1.dot(_testAxis);var p2=v2.dot(_testAxis);// actual test, basically see if either of the most extreme of the triangle points intersects r if(Math.max(-Math.max(p0,p1,p2),Math.min(p0,p1,p2))>r){// points of the projected triangle are outside the projected half-length of the aabb // the axis is seperating and we can exit return false;}}return true;}var _points=[/*@__PURE__*/new Vector3(),/*@__PURE__*/new Vector3(),/*@__PURE__*/new Vector3(),/*@__PURE__*/new Vector3(),/*@__PURE__*/new Vector3(),/*@__PURE__*/new Vector3(),/*@__PURE__*/new Vector3(),/*@__PURE__*/new Vector3()];var _vector$1=/*@__PURE__*/new Vector3();var _box=/*@__PURE__*/new Box3();// triangle centered vertices var _v0=/*@__PURE__*/new Vector3();var _v1=/*@__PURE__*/new Vector3();var _v2=/*@__PURE__*/new Vector3();// triangle edge vectors var _f0=/*@__PURE__*/new Vector3();var _f1=/*@__PURE__*/new Vector3();var _f2=/*@__PURE__*/new Vector3();var _center=/*@__PURE__*/new Vector3();var _extents=/*@__PURE__*/new Vector3();var _triangleNormal=/*@__PURE__*/new Vector3();var _testAxis=/*@__PURE__*/new Vector3();var _box$1=/*@__PURE__*/new Box3();class Sphere{constructor(center,radius){this.center=center!==undefined?center:new Vector3();this.radius=radius!==undefined?radius:-1;}set(center,radius){this.center.copy(center);this.radius=radius;return this;}setFromPoints(points,optionalCenter){var center=this.center;if(optionalCenter!==undefined){center.copy(optionalCenter);}else {_box$1.setFromPoints(points).getCenter(center);}var maxRadiusSq=0;for(var _i9=0,il=points.length;_i9this.radius*this.radius){target.sub(this.center).normalize();target.multiplyScalar(this.radius).add(this.center);}return target;}getBoundingBox(target){if(target===undefined){console.warn('THREE.Sphere: .getBoundingBox() target is now required');target=new Box3();}if(this.isEmpty()){// Empty sphere produces empty bounding box target.makeEmpty();return target;}target.set(this.center,this.center);target.expandByScalar(this.radius);return target;}applyMatrix4(matrix){this.center.applyMatrix4(matrix);this.radius=this.radius*matrix.getMaxScaleOnAxis();return this;}translate(offset){this.center.add(offset);return this;}equals(sphere){return sphere.center.equals(this.center)&&sphere.radius===this.radius;}}var _vector$2=/*@__PURE__*/new Vector3();var _segCenter=/*@__PURE__*/new Vector3();var _segDir=/*@__PURE__*/new Vector3();var _diff=/*@__PURE__*/new Vector3();var _edge1=/*@__PURE__*/new Vector3();var _edge2=/*@__PURE__*/new Vector3();var _normal=/*@__PURE__*/new Vector3();class Ray{constructor(origin,direction){this.origin=origin!==undefined?origin:new Vector3();this.direction=direction!==undefined?direction:new Vector3(0,0,-1);}set(origin,direction){this.origin.copy(origin);this.direction.copy(direction);return this;}clone(){return new this.constructor().copy(this);}copy(ray){this.origin.copy(ray.origin);this.direction.copy(ray.direction);return this;}at(t,target){if(target===undefined){console.warn('THREE.Ray: .at() target is now required');target=new Vector3();}return target.copy(this.direction).multiplyScalar(t).add(this.origin);}lookAt(v){this.direction.copy(v).sub(this.origin).normalize();return this;}recast(t){this.origin.copy(this.at(t,_vector$2));return this;}closestPointToPoint(point,target){if(target===undefined){console.warn('THREE.Ray: .closestPointToPoint() target is now required');target=new Vector3();}target.subVectors(point,this.origin);var directionDistance=target.dot(this.direction);if(directionDistance<0){return target.copy(this.origin);}return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);}distanceToPoint(point){return Math.sqrt(this.distanceSqToPoint(point));}distanceSqToPoint(point){var directionDistance=_vector$2.subVectors(point,this.origin).dot(this.direction);// point behind the ray if(directionDistance<0){return this.origin.distanceToSquared(point);}_vector$2.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);return _vector$2.distanceToSquared(point);}distanceSqToSegment(v0,v1,optionalPointOnRay,optionalPointOnSegment){// from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h // It returns the min distance between the ray and the segment // defined by v0 and v1 // It can also set two optional targets : // - The closest point on the ray // - The closest point on the segment _segCenter.copy(v0).add(v1).multiplyScalar(0.5);_segDir.copy(v1).sub(v0).normalize();_diff.copy(this.origin).sub(_segCenter);var segExtent=v0.distanceTo(v1)*0.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){// The ray and segment are not parallel. s0=a01*b1-b0;s1=a01*b0-b1;extDet=segExtent*det;if(s0>=0){if(s1>=-extDet){if(s1<=extDet){// region 0 // Minimum at interior points of ray and segment. var invDet=1/det;s0*=invDet;s1*=invDet;sqrDist=s0*(s0+a01*s1+2*b0)+s1*(a01*s0+s1+2*b1)+c;}else {// region 1 s1=segExtent;s0=Math.max(0,-(a01*s1+b0));sqrDist=-s0*s0+s1*(s1+2*b1)+c;}}else {// region 5 s1=-segExtent;s0=Math.max(0,-(a01*s1+b0));sqrDist=-s0*s0+s1*(s1+2*b1)+c;}}else {if(s1<=-extDet){// region 4 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){// region 3 s0=0;s1=Math.min(Math.max(-segExtent,-b1),segExtent);sqrDist=s1*(s1+2*b1)+c;}else {// region 2 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 {// Ray and segment are parallel. 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(sphere,target){_vector$2.subVectors(sphere.center,this.origin);var tca=_vector$2.dot(this.direction);var d2=_vector$2.dot(_vector$2)-tca*tca;var radius2=sphere.radius*sphere.radius;if(d2>radius2)return null;var thc=Math.sqrt(radius2-d2);// t0 = first intersect point - entrance on front of sphere var t0=tca-thc;// t1 = second intersect point - exit point on back of sphere var t1=tca+thc;// test to see if both t0 and t1 are behind the ray - if so, return null if(t0<0&&t1<0)return null;// test to see if t0 is behind the ray: // if it is, the ray is inside the sphere, so return the second exit point scaled by t1, // in order to always return an intersect point that is in front of the ray. if(t0<0)return this.at(t1,target);// else t0 is in front of the ray, so return the first collision point scaled by t0 return this.at(t0,target);}intersectsSphere(sphere){return this.distanceSqToPoint(sphere.center)<=sphere.radius*sphere.radius;}distanceToPlane(plane){var denominator=plane.normal.dot(this.direction);if(denominator===0){// line is coplanar, return origin if(plane.distanceToPoint(this.origin)===0){return 0;}// Null is preferable to undefined since undefined means.... it is undefined return null;}var t=-(this.origin.dot(plane.normal)+plane.constant)/denominator;// Return if the ray never intersects the plane return t>=0?t:null;}intersectPlane(plane,target){var t=this.distanceToPlane(plane);if(t===null){return null;}return this.at(t,target);}intersectsPlane(plane){// check if the ray lies on the plane first var distToPoint=plane.distanceToPoint(this.origin);if(distToPoint===0){return true;}var denominator=plane.normal.dot(this.direction);if(denominator*distToPoint<0){return true;}// ray origin is behind the plane (and is pointing behind it) return false;}intersectBox(box,target){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;// These lines also handle the case where tmin or tmax is NaN // (result of 0 * Infinity). x !== x returns true if x is NaN if(tymin>tmin||tmin!==tmin)tmin=tymin;if(tymax=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=0?tmin:tmax,target);}intersectsBox(box){return this.intersectBox(box,_vector$2)!==null;}intersectTriangle(a,b,c,backfaceCulling,target){// Compute the offset origin, edges, and normal. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h _edge1.subVectors(b,a);_edge2.subVectors(c,a);_normal.crossVectors(_edge1,_edge2);// Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) 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));// b1 < 0, no intersection if(DdQxE2<0){return null;}var DdE1xQ=sign*this.direction.dot(_edge1.cross(_diff));// b2 < 0, no intersection if(DdE1xQ<0){return null;}// b1+b2 > 1, no intersection if(DdQxE2+DdE1xQ>DdN){return null;}// Line intersects triangle, check if ray does. var QdN=-sign*_diff.dot(_normal);// t < 0, no intersection if(QdN<0){return null;}// Ray intersects triangle. return this.at(QdN/DdN,target);}applyMatrix4(matrix4){this.origin.applyMatrix4(matrix4);this.direction.transformDirection(matrix4);return this;}equals(ray){return ray.origin.equals(this.origin)&&ray.direction.equals(this.direction);}}class Matrix4{constructor(){Object.defineProperty(this,'isMatrix4',{value:true});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.');}}set(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(){this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return this;}clone(){return new Matrix4().fromArray(this.elements);}copy(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(m){var te=this.elements,me=m.elements;te[12]=me[12];te[13]=me[13];te[14]=me[14];return this;}extractBasis(xAxis,yAxis,zAxis){xAxis.setFromMatrixColumn(this,0);yAxis.setFromMatrixColumn(this,1);zAxis.setFromMatrixColumn(this,2);return this;}makeBasis(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(m){// this method does not support reflection matrices var te=this.elements;var me=m.elements;var scaleX=1/_v1$1.setFromMatrixColumn(m,0).length();var scaleY=1/_v1$1.setFromMatrixColumn(m,1).length();var scaleZ=1/_v1$1.setFromMatrixColumn(m,2).length();te[0]=me[0]*scaleX;te[1]=me[1]*scaleX;te[2]=me[2]*scaleX;te[3]=0;te[4]=me[4]*scaleY;te[5]=me[5]*scaleY;te[6]=me[6]*scaleY;te[7]=0;te[8]=me[8]*scaleZ;te[9]=me[9]*scaleZ;te[10]=me[10]*scaleZ;te[11]=0;te[12]=0;te[13]=0;te[14]=0;te[15]=1;return this;}makeRotationFromEuler(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;}// bottom row te[3]=0;te[7]=0;te[11]=0;// last column te[12]=0;te[13]=0;te[14]=0;te[15]=1;return this;}makeRotationFromQuaternion(q){return this.compose(_zero,q,_one);}lookAt(eye,target,up){var te=this.elements;_z.subVectors(eye,target);if(_z.lengthSq()===0){// eye and target are in the same position _z.z=1;}_z.normalize();_x.crossVectors(up,_z);if(_x.lengthSq()===0){// up and z are parallel if(Math.abs(up.z)===1){_z.x+=0.0001;}else {_z.z+=0.0001;}_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(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(m){return this.multiplyMatrices(m,this);}multiplyMatrices(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(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;}determinant(){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];//TODO: make this more efficient //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) 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(){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(x,y,z){var te=this.elements;if(x.isVector3){te[12]=x.x;te[13]=x.y;te[14]=x.z;}else {te[12]=x;te[13]=y;te[14]=z;}return this;}invert(){// based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm var te=this.elements,n11=te[0],n21=te[1],n31=te[2],n41=te[3],n12=te[4],n22=te[5],n32=te[6],n42=te[7],n13=te[8],n23=te[9],n33=te[10],n43=te[11],n14=te[12],n24=te[13],n34=te[14],n44=te[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)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);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(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(){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(x,y,z){this.set(1,0,0,x,0,1,0,y,0,0,1,z,0,0,0,1);return this;}makeRotationX(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(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(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(axis,angle){// Based on http://www.gamedev.net/reference/articles/article1199.asp 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(x,y,z){this.set(x,0,0,0,0,y,0,0,0,0,z,0,0,0,0,1);return this;}makeShear(x,y,z){this.set(1,y,z,0,x,1,z,0,x,y,1,0,0,0,0,1);return this;}compose(position,quaternion,scale){var te=this.elements;var x=quaternion._x,y=quaternion._y,z=quaternion._z,w=quaternion._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;var sx=scale.x,sy=scale.y,sz=scale.z;te[0]=(1-(yy+zz))*sx;te[1]=(xy+wz)*sx;te[2]=(xz-wy)*sx;te[3]=0;te[4]=(xy-wz)*sy;te[5]=(1-(xx+zz))*sy;te[6]=(yz+wx)*sy;te[7]=0;te[8]=(xz+wy)*sz;te[9]=(yz-wx)*sz;te[10]=(1-(xx+yy))*sz;te[11]=0;te[12]=position.x;te[13]=position.y;te[14]=position.z;te[15]=1;return this;}decompose(position,quaternion,scale){var te=this.elements;var sx=_v1$1.set(te[0],te[1],te[2]).length();var sy=_v1$1.set(te[4],te[5],te[6]).length();var sz=_v1$1.set(te[8],te[9],te[10]).length();// if determine is negative, we need to invert one scale var det=this.determinant();if(det<0)sx=-sx;position.x=te[12];position.y=te[13];position.z=te[14];// scale the rotation part _m1.copy(this);var invSX=1/sx;var invSY=1/sy;var invSZ=1/sz;_m1.elements[0]*=invSX;_m1.elements[1]*=invSX;_m1.elements[2]*=invSX;_m1.elements[4]*=invSY;_m1.elements[5]*=invSY;_m1.elements[6]*=invSY;_m1.elements[8]*=invSZ;_m1.elements[9]*=invSZ;_m1.elements[10]*=invSZ;quaternion.setFromRotationMatrix(_m1);scale.x=sx;scale.y=sy;scale.z=sz;return this;}makePerspective(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(left,right,top,bottom,near,far){var te=this.elements;var w=1.0/(right-left);var h=1.0/(top-bottom);var p=1.0/(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(matrix){var te=this.elements;var me=matrix.elements;for(var _i10=0;_i10<16;_i10++){if(te[_i10]!==me[_i10])return false;}return true;}fromArray(array){var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;for(var _i11=0;_i11<16;_i11++){this.elements[_i11]=array[_i11+offset];}return this;}toArray(){var array=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]: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;}}var _v1$1=/*@__PURE__*/new Vector3();var _m1=/*@__PURE__*/new Matrix4();var _zero=/*@__PURE__*/new Vector3(0,0,0);var _one=/*@__PURE__*/new Vector3(1,1,1);var _x=/*@__PURE__*/new Vector3();var _y=/*@__PURE__*/new Vector3();var _z=/*@__PURE__*/new Vector3();class Euler{constructor(){var x=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var z=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var order=arguments.length>3&&arguments[3]!==undefined?arguments[3]:Euler.DefaultOrder;Object.defineProperty(this,'isEuler',{value:true});this._x=x;this._y=y;this._z=z;this._order=order;}get x(){return this._x;}set x(value){this._x=value;this._onChangeCallback();}get y(){return this._y;}set y(value){this._y=value;this._onChangeCallback();}get z(){return this._z;}set z(value){this._z=value;this._onChangeCallback();}get order(){return this._order;}set order(value){this._order=value;this._onChangeCallback();}set(x,y,z,order){this._x=x;this._y=y;this._z=z;this._order=order||this._order;this._onChangeCallback();return this;}clone(){return new this.constructor(this._x,this._y,this._z,this._order);}copy(euler){this._x=euler._x;this._y=euler._y;this._z=euler._z;this._order=euler._order;this._onChangeCallback();return this;}setFromRotationMatrix(m,order,update){var clamp=MathUtils.clamp;// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) 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;switch(order){case'XYZ':this._y=Math.asin(clamp(m13,-1,1));if(Math.abs(m13)<0.9999999){this._x=Math.atan2(-m23,m33);this._z=Math.atan2(-m12,m11);}else {this._x=Math.atan2(m32,m22);this._z=0;}break;case'YXZ':this._x=Math.asin(-clamp(m23,-1,1));if(Math.abs(m23)<0.9999999){this._y=Math.atan2(m13,m33);this._z=Math.atan2(m21,m22);}else {this._y=Math.atan2(-m31,m11);this._z=0;}break;case'ZXY':this._x=Math.asin(clamp(m32,-1,1));if(Math.abs(m32)<0.9999999){this._y=Math.atan2(-m31,m33);this._z=Math.atan2(-m12,m22);}else {this._y=0;this._z=Math.atan2(m21,m11);}break;case'ZYX':this._y=Math.asin(-clamp(m31,-1,1));if(Math.abs(m31)<0.9999999){this._x=Math.atan2(m32,m33);this._z=Math.atan2(m21,m11);}else {this._x=0;this._z=Math.atan2(-m12,m22);}break;case'YZX':this._z=Math.asin(clamp(m21,-1,1));if(Math.abs(m21)<0.9999999){this._x=Math.atan2(-m23,m22);this._y=Math.atan2(-m31,m11);}else {this._x=0;this._y=Math.atan2(m13,m33);}break;case'XZY':this._z=Math.asin(-clamp(m12,-1,1));if(Math.abs(m12)<0.9999999){this._x=Math.atan2(m32,m22);this._y=Math.atan2(m13,m11);}else {this._x=Math.atan2(-m23,m33);this._y=0;}break;default:console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: '+order);}this._order=order;if(update!==false)this._onChangeCallback();return this;}setFromQuaternion(q,order,update){_matrix.makeRotationFromQuaternion(q);return this.setFromRotationMatrix(_matrix,order,update);}setFromVector3(v,order){return this.set(v.x,v.y,v.z,order||this._order);}reorder(newOrder){// WARNING: this discards revolution information -bhouston _quaternion$1.setFromEuler(this);return this.setFromQuaternion(_quaternion$1,newOrder);}equals(euler){return euler._x===this._x&&euler._y===this._y&&euler._z===this._z&&euler._order===this._order;}fromArray(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(){var array=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;array[offset]=this._x;array[offset+1]=this._y;array[offset+2]=this._z;array[offset+3]=this._order;return array;}toVector3(optionalResult){if(optionalResult){return optionalResult.set(this._x,this._y,this._z);}else {return new Vector3(this._x,this._y,this._z);}}_onChange(callback){this._onChangeCallback=callback;return this;}_onChangeCallback(){}}Euler.DefaultOrder='XYZ';Euler.RotationOrders=['XYZ','YZX','ZXY','XZY','YXZ','ZYX'];var _matrix=/*@__PURE__*/new Matrix4();var _quaternion$1=/*@__PURE__*/new Quaternion();class Layers{constructor(){this.mask=1|0;}set(channel){this.mask=1<1){for(var _i12=0;_i121){for(var _i13=0;_i130){object.children=[];for(var _i22=0;_i220){object.animations=[];for(var _i23=0;_i230)output.geometries=geometries;if(materials.length>0)output.materials=materials;if(textures.length>0)output.textures=textures;if(images.length>0)output.images=images;if(_shapes.length>0)output.shapes=_shapes;if(skeletons.length>0)output.skeletons=skeletons;if(animations.length>0)output.animations=animations;}output.object=object;return output;// extract data from the cache hash // remove metadata on each item // and return as array function extractFromCache(cache){var values=[];for(var key in cache){var data=cache[key];delete data.metadata;values.push(data);}return values;}},clone:function clone(recursive){return new this.constructor().copy(this,recursive);},copy:function copy(source){var recursive=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;this.name=source.name;this.up.copy(source.up);this.position.copy(source.position);this.rotation.order=source.rotation.order;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 _i24=0;_i241){return undefined;}return target.copy(direction).multiplyScalar(t).add(line.start);}intersectsLine(line){// Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. var startSign=this.distanceToPoint(line.start);var endSign=this.distanceToPoint(line.end);return startSign<0&&endSign>0||endSign<0&&startSign>0;}intersectsBox(box){return box.intersectsPlane(this);}intersectsSphere(sphere){return sphere.intersectsPlane(this);}coplanarPoint(target){if(target===undefined){console.warn('THREE.Plane: .coplanarPoint() target is now required');target=new Vector3();}return target.copy(this.normal).multiplyScalar(-this.constant);}applyMatrix4(matrix,optionalNormalMatrix){var normalMatrix=optionalNormalMatrix||_normalMatrix.getNormalMatrix(matrix);var referencePoint=this.coplanarPoint(_vector1).applyMatrix4(matrix);var normal=this.normal.applyMatrix3(normalMatrix).normalize();this.constant=-referencePoint.dot(normal);return this;}translate(offset){this.constant-=offset.dot(this.normal);return this;}equals(plane){return plane.normal.equals(this.normal)&&plane.constant===this.constant;}}var _v0$1=/*@__PURE__*/new Vector3();var _v1$3=/*@__PURE__*/new Vector3();var _v2$1=/*@__PURE__*/new Vector3();var _v3=/*@__PURE__*/new Vector3();var _vab=/*@__PURE__*/new Vector3();var _vac=/*@__PURE__*/new Vector3();var _vbc=/*@__PURE__*/new Vector3();var _vap=/*@__PURE__*/new Vector3();var _vbp=/*@__PURE__*/new Vector3();var _vcp=/*@__PURE__*/new Vector3();class Triangle{constructor(a,b,c){this.a=a!==undefined?a:new Vector3();this.b=b!==undefined?b:new Vector3();this.c=c!==undefined?c:new Vector3();}static getNormal(a,b,c,target){if(target===undefined){console.warn('THREE.Triangle: .getNormal() target is now required');target=new Vector3();}target.subVectors(c,b);_v0$1.subVectors(a,b);target.cross(_v0$1);var targetLengthSq=target.lengthSq();if(targetLengthSq>0){return target.multiplyScalar(1/Math.sqrt(targetLengthSq));}return target.set(0,0,0);}// static/instance method to calculate barycentric coordinates // based on: http://www.blackpawn.com/texts/pointinpoly/default.html static getBarycoord(point,a,b,c,target){_v0$1.subVectors(c,a);_v1$3.subVectors(b,a);_v2$1.subVectors(point,a);var dot00=_v0$1.dot(_v0$1);var dot01=_v0$1.dot(_v1$3);var dot02=_v0$1.dot(_v2$1);var dot11=_v1$3.dot(_v1$3);var dot12=_v1$3.dot(_v2$1);var denom=dot00*dot11-dot01*dot01;if(target===undefined){console.warn('THREE.Triangle: .getBarycoord() target is now required');target=new Vector3();}// collinear or singular triangle if(denom===0){// arbitrary location outside of triangle? // not sure if this is the best idea, maybe should be returning undefined return target.set(-2,-1,-1);}var invDenom=1/denom;var u=(dot11*dot02-dot01*dot12)*invDenom;var v=(dot00*dot12-dot01*dot02)*invDenom;// barycentric coordinates must always sum to 1 return target.set(1-u-v,v,u);}static containsPoint(point,a,b,c){this.getBarycoord(point,a,b,c,_v3);return _v3.x>=0&&_v3.y>=0&&_v3.x+_v3.y<=1;}static getUV(point,p1,p2,p3,uv1,uv2,uv3,target){this.getBarycoord(point,p1,p2,p3,_v3);target.set(0,0);target.addScaledVector(uv1,_v3.x);target.addScaledVector(uv2,_v3.y);target.addScaledVector(uv3,_v3.z);return target;}static isFrontFacing(a,b,c,direction){_v0$1.subVectors(c,b);_v1$3.subVectors(a,b);// strictly front facing return _v0$1.cross(_v1$3).dot(direction)<0?true:false;}set(a,b,c){this.a.copy(a);this.b.copy(b);this.c.copy(c);return this;}setFromPointsAndIndices(points,i0,i1,i2){this.a.copy(points[i0]);this.b.copy(points[i1]);this.c.copy(points[i2]);return this;}clone(){return new this.constructor().copy(this);}copy(triangle){this.a.copy(triangle.a);this.b.copy(triangle.b);this.c.copy(triangle.c);return this;}getArea(){_v0$1.subVectors(this.c,this.b);_v1$3.subVectors(this.a,this.b);return _v0$1.cross(_v1$3).length()*0.5;}getMidpoint(target){if(target===undefined){console.warn('THREE.Triangle: .getMidpoint() target is now required');target=new Vector3();}return target.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3);}getNormal(target){return Triangle.getNormal(this.a,this.b,this.c,target);}getPlane(target){if(target===undefined){console.warn('THREE.Triangle: .getPlane() target is now required');target=new Plane();}return target.setFromCoplanarPoints(this.a,this.b,this.c);}getBarycoord(point,target){return Triangle.getBarycoord(point,this.a,this.b,this.c,target);}getUV(point,uv1,uv2,uv3,target){return Triangle.getUV(point,this.a,this.b,this.c,uv1,uv2,uv3,target);}containsPoint(point){return Triangle.containsPoint(point,this.a,this.b,this.c);}isFrontFacing(direction){return Triangle.isFrontFacing(this.a,this.b,this.c,direction);}intersectsBox(box){return box.intersectsTriangle(this);}closestPointToPoint(p,target){if(target===undefined){console.warn('THREE.Triangle: .closestPointToPoint() target is now required');target=new Vector3();}var a=this.a,b=this.b,c=this.c;var v,w;// algorithm thanks to Real-Time Collision Detection by Christer Ericson, // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc., // under the accompanying license; see chapter 5.1.5 for detailed explanation. // basically, we're distinguishing which of the voronoi regions of the triangle // the point lies in with the minimum amount of redundant computation. _vab.subVectors(b,a);_vac.subVectors(c,a);_vap.subVectors(p,a);var d1=_vab.dot(_vap);var d2=_vac.dot(_vap);if(d1<=0&&d2<=0){// vertex region of A; barycentric coords (1, 0, 0) return target.copy(a);}_vbp.subVectors(p,b);var d3=_vab.dot(_vbp);var d4=_vac.dot(_vbp);if(d3>=0&&d4<=d3){// vertex region of B; barycentric coords (0, 1, 0) return target.copy(b);}var vc=d1*d4-d3*d2;if(vc<=0&&d1>=0&&d3<=0){v=d1/(d1-d3);// edge region of AB; barycentric coords (1-v, v, 0) return target.copy(a).addScaledVector(_vab,v);}_vcp.subVectors(p,c);var d5=_vab.dot(_vcp);var d6=_vac.dot(_vcp);if(d6>=0&&d5<=d6){// vertex region of C; barycentric coords (0, 0, 1) return target.copy(c);}var vb=d5*d2-d1*d6;if(vb<=0&&d2>=0&&d6<=0){w=d2/(d2-d6);// edge region of AC; barycentric coords (1-w, 0, w) return target.copy(a).addScaledVector(_vac,w);}var va=d3*d6-d5*d4;if(va<=0&&d4-d3>=0&&d5-d6>=0){_vbc.subVectors(c,b);w=(d4-d3)/(d4-d3+(d5-d6));// edge region of BC; barycentric coords (0, 1-w, w) return target.copy(b).addScaledVector(_vbc,w);// edge region of BC }// face region var denom=1/(va+vb+vc);// u = va * denom v=vb*denom;w=vc*denom;return target.copy(a).addScaledVector(_vab,v).addScaledVector(_vac,w);}equals(triangle){return triangle.a.equals(this.a)&&triangle.b.equals(this.b)&&triangle.c.equals(this.c);}}var _colorKeywords={'aliceblue':0xF0F8FF,'antiquewhite':0xFAEBD7,'aqua':0x00FFFF,'aquamarine':0x7FFFD4,'azure':0xF0FFFF,'beige':0xF5F5DC,'bisque':0xFFE4C4,'black':0x000000,'blanchedalmond':0xFFEBCD,'blue':0x0000FF,'blueviolet':0x8A2BE2,'brown':0xA52A2A,'burlywood':0xDEB887,'cadetblue':0x5F9EA0,'chartreuse':0x7FFF00,'chocolate':0xD2691E,'coral':0xFF7F50,'cornflowerblue':0x6495ED,'cornsilk':0xFFF8DC,'crimson':0xDC143C,'cyan':0x00FFFF,'darkblue':0x00008B,'darkcyan':0x008B8B,'darkgoldenrod':0xB8860B,'darkgray':0xA9A9A9,'darkgreen':0x006400,'darkgrey':0xA9A9A9,'darkkhaki':0xBDB76B,'darkmagenta':0x8B008B,'darkolivegreen':0x556B2F,'darkorange':0xFF8C00,'darkorchid':0x9932CC,'darkred':0x8B0000,'darksalmon':0xE9967A,'darkseagreen':0x8FBC8F,'darkslateblue':0x483D8B,'darkslategray':0x2F4F4F,'darkslategrey':0x2F4F4F,'darkturquoise':0x00CED1,'darkviolet':0x9400D3,'deeppink':0xFF1493,'deepskyblue':0x00BFFF,'dimgray':0x696969,'dimgrey':0x696969,'dodgerblue':0x1E90FF,'firebrick':0xB22222,'floralwhite':0xFFFAF0,'forestgreen':0x228B22,'fuchsia':0xFF00FF,'gainsboro':0xDCDCDC,'ghostwhite':0xF8F8FF,'gold':0xFFD700,'goldenrod':0xDAA520,'gray':0x808080,'green':0x008000,'greenyellow':0xADFF2F,'grey':0x808080,'honeydew':0xF0FFF0,'hotpink':0xFF69B4,'indianred':0xCD5C5C,'indigo':0x4B0082,'ivory':0xFFFFF0,'khaki':0xF0E68C,'lavender':0xE6E6FA,'lavenderblush':0xFFF0F5,'lawngreen':0x7CFC00,'lemonchiffon':0xFFFACD,'lightblue':0xADD8E6,'lightcoral':0xF08080,'lightcyan':0xE0FFFF,'lightgoldenrodyellow':0xFAFAD2,'lightgray':0xD3D3D3,'lightgreen':0x90EE90,'lightgrey':0xD3D3D3,'lightpink':0xFFB6C1,'lightsalmon':0xFFA07A,'lightseagreen':0x20B2AA,'lightskyblue':0x87CEFA,'lightslategray':0x778899,'lightslategrey':0x778899,'lightsteelblue':0xB0C4DE,'lightyellow':0xFFFFE0,'lime':0x00FF00,'limegreen':0x32CD32,'linen':0xFAF0E6,'magenta':0xFF00FF,'maroon':0x800000,'mediumaquamarine':0x66CDAA,'mediumblue':0x0000CD,'mediumorchid':0xBA55D3,'mediumpurple':0x9370DB,'mediumseagreen':0x3CB371,'mediumslateblue':0x7B68EE,'mediumspringgreen':0x00FA9A,'mediumturquoise':0x48D1CC,'mediumvioletred':0xC71585,'midnightblue':0x191970,'mintcream':0xF5FFFA,'mistyrose':0xFFE4E1,'moccasin':0xFFE4B5,'navajowhite':0xFFDEAD,'navy':0x000080,'oldlace':0xFDF5E6,'olive':0x808000,'olivedrab':0x6B8E23,'orange':0xFFA500,'orangered':0xFF4500,'orchid':0xDA70D6,'palegoldenrod':0xEEE8AA,'palegreen':0x98FB98,'paleturquoise':0xAFEEEE,'palevioletred':0xDB7093,'papayawhip':0xFFEFD5,'peachpuff':0xFFDAB9,'peru':0xCD853F,'pink':0xFFC0CB,'plum':0xDDA0DD,'powderblue':0xB0E0E6,'purple':0x800080,'rebeccapurple':0x663399,'red':0xFF0000,'rosybrown':0xBC8F8F,'royalblue':0x4169E1,'saddlebrown':0x8B4513,'salmon':0xFA8072,'sandybrown':0xF4A460,'seagreen':0x2E8B57,'seashell':0xFFF5EE,'sienna':0xA0522D,'silver':0xC0C0C0,'skyblue':0x87CEEB,'slateblue':0x6A5ACD,'slategray':0x708090,'slategrey':0x708090,'snow':0xFFFAFA,'springgreen':0x00FF7F,'steelblue':0x4682B4,'tan':0xD2B48C,'teal':0x008080,'thistle':0xD8BFD8,'tomato':0xFF6347,'turquoise':0x40E0D0,'violet':0xEE82EE,'wheat':0xF5DEB3,'white':0xFFFFFF,'whitesmoke':0xF5F5F5,'yellow':0xFFFF00,'yellowgreen':0x9ACD32};var _hslA={h:0,s:0,l:0};var _hslB={h:0,s:0,l:0};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;}function SRGBToLinear(c){return c<0.04045?c*0.0773993808:Math.pow(c*0.9478672986+0.0521327014,2.4);}function LinearToSRGB(c){return c<0.0031308?c*12.92:1.055*Math.pow(c,0.41666)-0.055;}class Color{constructor(r,g,b){Object.defineProperty(this,'isColor',{value:true});if(g===undefined&&b===undefined){// r is THREE.Color, hex or string return this.set(r);}return this.setRGB(r,g,b);}set(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(scalar){this.r=scalar;this.g=scalar;this.b=scalar;return this;}setHex(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(r,g,b){this.r=r;this.g=g;this.b=b;return this;}setHSL(h,s,l){// h,s,l ranges are in 0.0 - 1.0 h=MathUtils.euclideanModulo(h,1);s=MathUtils.clamp(s,0,1);l=MathUtils.clamp(l,0,1);if(s===0){this.r=this.g=this.b=l;}else {var p=l<=0.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(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)){// rgb / hsl 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*(\d*\.?\d+)\s*)?$/.exec(components)){// rgb(255,0,0) rgba(255,0,0,0.5) 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[4]);return this;}if(color=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)){// rgb(100%,0%,0%) rgba(100%,0%,0%,0.5) 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[4]);return this;}break;case'hsl':case'hsla':if(color=/^(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)){// hsl(120,50%,50%) hsla(120,50%,50%,0.5) var h=parseFloat(color[1])/360;var s=parseInt(color[2],10)/100;var l=parseInt(color[3],10)/100;handleAlpha(color[4]);return this.setHSL(h,s,l);}break;}}else if(m=/^\#([A-Fa-f\d]+)$/.exec(style)){// hex color var hex=m[1];var size=hex.length;if(size===3){// #ff0 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){// #ff0000 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){return this.setColorName(style);}return this;}setColorName(style){// color keywords var hex=_colorKeywords[style];if(hex!==undefined){// red this.setHex(hex);}else {// unknown color console.warn('THREE.Color: Unknown color '+style);}return this;}clone(){return new this.constructor(this.r,this.g,this.b);}copy(color){this.r=color.r;this.g=color.g;this.b=color.b;return this;}copyGammaToLinear(color){var gammaFactor=arguments.length>1&&arguments[1]!==undefined?arguments[1]:2.0;this.r=Math.pow(color.r,gammaFactor);this.g=Math.pow(color.g,gammaFactor);this.b=Math.pow(color.b,gammaFactor);return this;}copyLinearToGamma(color){var gammaFactor=arguments.length>1&&arguments[1]!==undefined?arguments[1]:2.0;var safeInverse=gammaFactor>0?1.0/gammaFactor:1.0;this.r=Math.pow(color.r,safeInverse);this.g=Math.pow(color.g,safeInverse);this.b=Math.pow(color.b,safeInverse);return this;}convertGammaToLinear(gammaFactor){this.copyGammaToLinear(this,gammaFactor);return this;}convertLinearToGamma(gammaFactor){this.copyLinearToGamma(this,gammaFactor);return this;}copySRGBToLinear(color){this.r=SRGBToLinear(color.r);this.g=SRGBToLinear(color.g);this.b=SRGBToLinear(color.b);return this;}copyLinearToSRGB(color){this.r=LinearToSRGB(color.r);this.g=LinearToSRGB(color.g);this.b=LinearToSRGB(color.b);return this;}convertSRGBToLinear(){this.copySRGBToLinear(this);return this;}convertLinearToSRGB(){this.copyLinearToSRGB(this);return this;}getHex(){return this.r*255<<16^this.g*255<<8^this.b*255<<0;}getHexString(){return ('000000'+this.getHex().toString(16)).slice(-6);}getHSL(target){// h,s,l ranges are in 0.0 - 1.0 if(target===undefined){console.warn('THREE.Color: .getHSL() target is now required');target={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.0;if(min===max){hue=0;saturation=0;}else {var delta=max-min;saturation=lightness<=0.5?delta/(max+min):delta/(2-max-min);switch(max){case r:hue=(g-b)/delta+(g1&&arguments[1]!==undefined?arguments[1]:0;this.r=array[offset];this.g=array[offset+1];this.b=array[offset+2];return this;}toArray(){var array=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;array[offset]=this.r;array[offset+1]=this.g;array[offset+2]=this.b;return array;}fromBufferAttribute(attribute,index){this.r=attribute.getX(index);this.g=attribute.getY(index);this.b=attribute.getZ(index);if(attribute.normalized===true){// assuming Uint8Array this.r/=255;this.g/=255;this.b/=255;}return this;}toJSON(){return this.getHex();}}Color.NAMES=_colorKeywords;Color.prototype.r=1;Color.prototype.g=1;Color.prototype.b=1;class Face3{constructor(a,b,c,normal,color){var materialIndex=arguments.length>5&&arguments[5]!==undefined?arguments[5]:0;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;}clone(){return new this.constructor().copy(this);}copy(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 _i25=0,il=source.vertexNormals.length;_i250)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.morphNormals===true)data.morphNormals=true;if(this.skinning===true)data.skinning=true;if(this.visible===false)data.visible=false;if(this.toneMapped===false)data.toneMapped=false;if(JSON.stringify(this.userData)!=='{}')data.userData=this.userData;// TODO: Copied from Object3D.toJSON 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 clone(){return new this.constructor().copy(this);},copy:function copy(source){this.name=source.name;this.fog=source.fog;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.stencilWriteMask=source.stencilWriteMask;this.stencilFunc=source.stencilFunc;this.stencilRef=source.stencilRef;this.stencilFuncMask=source.stencilFuncMask;this.stencilFail=source.stencilFail;this.stencilZFail=source.stencilZFail;this.stencilZPass=source.stencilZPass;this.stencilWrite=source.stencilWrite;var srcPlanes=source.clippingPlanes;var dstPlanes=null;if(srcPlanes!==null){var n=srcPlanes.length;dstPlanes=new Array(n);for(var _i27=0;_i27!==n;++_i27){dstPlanes[_i27]=srcPlanes[_i27].clone();}}this.clippingPlanes=dstPlanes;this.clipIntersection=source.clipIntersection;this.clipShadows=source.clipShadows;this.shadowSide=source.shadowSide;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.visible=source.visible;this.toneMapped=source.toneMapped;this.userData=JSON.parse(JSON.stringify(source.userData));return this;},dispose:function dispose(){this.dispatchEvent({type:'dispose'});}});Object.defineProperty(Material.prototype,'needsUpdate',{set:function set(value){if(value===true)this.version++;}});/** * parameters = { * color: , * opacity: , * map: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * specularMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), * combine: THREE.Multiply, * reflectivity: , * refractionRatio: , * * depthTest: , * depthWrite: , * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: * } */function MeshBasicMaterial(parameters){Material.call(this);this.type='MeshBasicMaterial';this.color=new Color(0xffffff);// emissive this.map=null;this.lightMap=null;this.lightMapIntensity=1.0;this.aoMap=null;this.aoMapIntensity=1.0;this.specularMap=null;this.alphaMap=null;this.envMap=null;this.combine=MultiplyOperation;this.reflectivity=1;this.refractionRatio=0.98;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap='round';this.wireframeLinejoin='round';this.skinning=false;this.morphTargets=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;};var _vector$3=new Vector3();var _vector2$1=new Vector2();function BufferAttribute(array,itemSize,normalized){if(Array.isArray(array)){throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');}this.name='';this.array=array;this.itemSize=itemSize;this.count=array!==undefined?array.length/itemSize:0;this.normalized=normalized===true;this.usage=StaticDrawUsage;this.updateRange={offset:0,count:-1};this.version=0;}Object.defineProperty(BufferAttribute.prototype,'needsUpdate',{set:function set(value){if(value===true)this.version++;}});Object.assign(BufferAttribute.prototype,{isBufferAttribute:true,onUploadCallback:function onUploadCallback(){},setUsage:function setUsage(value){this.usage=value;return this;},copy:function copy(source){this.name=source.name;this.array=new source.array.constructor(source.array);this.itemSize=source.itemSize;this.count=source.count;this.normalized=source.normalized;this.usage=source.usage;return this;},copyAt:function copyAt(index1,attribute,index2){index1*=this.itemSize;index2*=attribute.itemSize;for(var _i28=0,l=this.itemSize;_i281&&arguments[1]!==undefined?arguments[1]:0;this.array.set(value,offset);return this;},getX:function getX(index){return this.array[index*this.itemSize];},setX:function setX(index,x){this.array[index*this.itemSize]=x;return this;},getY:function getY(index){return this.array[index*this.itemSize+1];},setY:function setY(index,y){this.array[index*this.itemSize+1]=y;return this;},getZ:function getZ(index){return this.array[index*this.itemSize+2];},setZ:function setZ(index,z){this.array[index*this.itemSize+2]=z;return this;},getW:function getW(index){return this.array[index*this.itemSize+3];},setW:function setW(index,w){this.array[index*this.itemSize+3]=w;return this;},setXY:function setXY(index,x,y){index*=this.itemSize;this.array[index+0]=x;this.array[index+1]=y;return this;},setXYZ:function setXYZ(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 setXYZW(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 onUpload(callback){this.onUploadCallback=callback;return this;},clone:function clone(){return new this.constructor(this.array,this.itemSize).copy(this);},toJSON:function toJSON(){return {itemSize:this.itemSize,type:this.array.constructor.name,array:Array.prototype.slice.call(this.array),normalized:this.normalized};}});// function Int8BufferAttribute(array,itemSize,normalized){BufferAttribute.call(this,new Int8Array(array),itemSize,normalized);}Int8BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Int8BufferAttribute.prototype.constructor=Int8BufferAttribute;function Uint8BufferAttribute(array,itemSize,normalized){BufferAttribute.call(this,new Uint8Array(array),itemSize,normalized);}Uint8BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Uint8BufferAttribute.prototype.constructor=Uint8BufferAttribute;function Uint8ClampedBufferAttribute(array,itemSize,normalized){BufferAttribute.call(this,new Uint8ClampedArray(array),itemSize,normalized);}Uint8ClampedBufferAttribute.prototype=Object.create(BufferAttribute.prototype);Uint8ClampedBufferAttribute.prototype.constructor=Uint8ClampedBufferAttribute;function Int16BufferAttribute(array,itemSize,normalized){BufferAttribute.call(this,new Int16Array(array),itemSize,normalized);}Int16BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Int16BufferAttribute.prototype.constructor=Int16BufferAttribute;function Uint16BufferAttribute(array,itemSize,normalized){BufferAttribute.call(this,new Uint16Array(array),itemSize,normalized);}Uint16BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Uint16BufferAttribute.prototype.constructor=Uint16BufferAttribute;function Int32BufferAttribute(array,itemSize,normalized){BufferAttribute.call(this,new Int32Array(array),itemSize,normalized);}Int32BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Int32BufferAttribute.prototype.constructor=Int32BufferAttribute;function Uint32BufferAttribute(array,itemSize,normalized){BufferAttribute.call(this,new Uint32Array(array),itemSize,normalized);}Uint32BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Uint32BufferAttribute.prototype.constructor=Uint32BufferAttribute;function Float16BufferAttribute(array,itemSize,normalized){BufferAttribute.call(this,new Uint16Array(array),itemSize,normalized);}Float16BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Float16BufferAttribute.prototype.constructor=Float16BufferAttribute;Float16BufferAttribute.prototype.isFloat16BufferAttribute=true;function Float32BufferAttribute(array,itemSize,normalized){BufferAttribute.call(this,new Float32Array(array),itemSize,normalized);}Float32BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Float32BufferAttribute.prototype.constructor=Float32BufferAttribute;function Float64BufferAttribute(array,itemSize,normalized){BufferAttribute.call(this,new Float64Array(array),itemSize,normalized);}Float64BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Float64BufferAttribute.prototype.constructor=Float64BufferAttribute;class DirectGeometry{constructor(){this.vertices=[];this.normals=[];this.colors=[];this.uvs=[];this.uvs2=[];this.groups=[];this.morphTargets={};this.skinWeights=[];this.skinIndices=[];// this.lineDistances = []; this.boundingBox=null;this.boundingSphere=null;// update flags this.verticesNeedUpdate=false;this.normalsNeedUpdate=false;this.colorsNeedUpdate=false;this.uvsNeedUpdate=false;this.groupsNeedUpdate=false;}computeGroups(geometry){var groups=[];var group,i;var materialIndex=undefined;var faces=geometry.faces;for(i=0;i0;var hasFaceVertexUv2=faceVertexUvs[1]&&faceVertexUvs[1].length>0;// morphs var morphTargets=geometry.morphTargets;var morphTargetsLength=morphTargets.length;var morphTargetsPosition;if(morphTargetsLength>0){morphTargetsPosition=[];for(var _i38=0;_i380){morphTargetsNormal=[];for(var _i39=0;_i390&&faces.length===0){console.error('THREE.DirectGeometry: Faceless geometries are not supported.');}for(var _i40=0;_i40max)max=array[_i41];}return max;}var TYPED_ARRAYS={Int8Array:Int8Array,Uint8Array:Uint8Array,// Workaround for IE11 pre KB2929437. See #11440 Uint8ClampedArray:typeof Uint8ClampedArray!=='undefined'?Uint8ClampedArray:Uint8Array,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function getTypedArray(type,buffer){return new TYPED_ARRAYS[type](buffer);}var _bufferGeometryId=1;// BufferGeometry uses odd numbers as Id var _m1$2=new Matrix4();var _obj=new Object3D();var _offset=new Vector3();var _box$2=new Box3();var _boxMorphTargets=new Box3();var _vector$4=new Vector3();function BufferGeometry(){Object.defineProperty(this,'id',{value:_bufferGeometryId+=2});this.uuid=MathUtils.generateUUID();this.name='';this.type='BufferGeometry';this.index=null;this.attributes={};this.morphAttributes={};this.morphTargetsRelative=false;this.groups=[];this.boundingBox=null;this.boundingSphere=null;this.drawRange={start:0,count:Infinity};this.userData={};}BufferGeometry.prototype=Object.assign(Object.create(EventDispatcher.prototype),{constructor:BufferGeometry,isBufferGeometry:true,getIndex:function getIndex(){return this.index;},setIndex:function setIndex(index){if(Array.isArray(index)){this.index=new(arrayMax(index)>65535?Uint32BufferAttribute:Uint16BufferAttribute)(index,1);}else {this.index=index;}return this;},getAttribute:function getAttribute(name){return this.attributes[name];},setAttribute:function setAttribute(name,attribute){this.attributes[name]=attribute;return this;},deleteAttribute:function deleteAttribute(name){delete this.attributes[name];return this;},hasAttribute:function hasAttribute(name){return this.attributes[name]!==undefined;},addGroup:function addGroup(start,count){var materialIndex=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;this.groups.push({start:start,count:count,materialIndex:materialIndex});},clearGroups:function clearGroups(){this.groups=[];},setDrawRange:function setDrawRange(start,count){this.drawRange.start=start;this.drawRange.count=count;},applyMatrix4:function applyMatrix4(matrix){var position=this.attributes.position;if(position!==undefined){position.applyMatrix4(matrix);position.needsUpdate=true;}var normal=this.attributes.normal;if(normal!==undefined){var normalMatrix=new Matrix3().getNormalMatrix(matrix);normal.applyNormalMatrix(normalMatrix);normal.needsUpdate=true;}var tangent=this.attributes.tangent;if(tangent!==undefined){tangent.transformDirection(matrix);tangent.needsUpdate=true;}if(this.boundingBox!==null){this.computeBoundingBox();}if(this.boundingSphere!==null){this.computeBoundingSphere();}return this;},rotateX:function rotateX(angle){// rotate geometry around world x-axis _m1$2.makeRotationX(angle);this.applyMatrix4(_m1$2);return this;},rotateY:function rotateY(angle){// rotate geometry around world y-axis _m1$2.makeRotationY(angle);this.applyMatrix4(_m1$2);return this;},rotateZ:function rotateZ(angle){// rotate geometry around world z-axis _m1$2.makeRotationZ(angle);this.applyMatrix4(_m1$2);return this;},translate:function translate(x,y,z){// translate geometry _m1$2.makeTranslation(x,y,z);this.applyMatrix4(_m1$2);return this;},scale:function scale(x,y,z){// scale geometry _m1$2.makeScale(x,y,z);this.applyMatrix4(_m1$2);return this;},lookAt:function lookAt(vector){_obj.lookAt(vector);_obj.updateMatrix();this.applyMatrix4(_obj.matrix);return this;},center:function center(){this.computeBoundingBox();this.boundingBox.getCenter(_offset).negate();this.translate(_offset.x,_offset.y,_offset.z);return this;},setFromObject:function setFromObject(object){// console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this ); 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.setAttribute('position',positions.copyVector3sArray(geometry.vertices));this.setAttribute('color',colors.copyColorsArray(geometry.colors));if(geometry.lineDistances&&geometry.lineDistances.length===geometry.vertices.length){var lineDistances=new Float32BufferAttribute(geometry.lineDistances.length,1);this.setAttribute('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;},setFromPoints:function setFromPoints(points){var position=[];for(var _i42=0,l=points.length;_i420){var normals=new Float32Array(geometry.normals.length*3);this.setAttribute('normal',new BufferAttribute(normals,3).copyVector3sArray(geometry.normals));}if(geometry.colors.length>0){var colors=new Float32Array(geometry.colors.length*3);this.setAttribute('color',new BufferAttribute(colors,3).copyColorsArray(geometry.colors));}if(geometry.uvs.length>0){var uvs=new Float32Array(geometry.uvs.length*2);this.setAttribute('uv',new BufferAttribute(uvs,2).copyVector2sArray(geometry.uvs));}if(geometry.uvs2.length>0){var uvs2=new Float32Array(geometry.uvs2.length*2);this.setAttribute('uv2',new BufferAttribute(uvs2,2).copyVector2sArray(geometry.uvs2));}// groups this.groups=geometry.groups;// morphs for(var name in geometry.morphTargets){var array=[];var morphTargets=geometry.morphTargets[name];for(var _i43=0,l=morphTargets.length;_i430){var skinIndices=new Float32BufferAttribute(geometry.skinIndices.length*4,4);this.setAttribute('skinIndex',skinIndices.copyVector4sArray(geometry.skinIndices));}if(geometry.skinWeights.length>0){var skinWeights=new Float32BufferAttribute(geometry.skinWeights.length*4,4);this.setAttribute('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 computeBoundingBox(){if(this.boundingBox===null){this.boundingBox=new Box3();}var position=this.attributes.position;var morphAttributesPosition=this.morphAttributes.position;if(position&&position.isGLBufferAttribute){console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".',this);this.boundingBox.set(new Vector3(-Infinity,-Infinity,-Infinity),new Vector3(+Infinity,+Infinity,+Infinity));return;}if(position!==undefined){this.boundingBox.setFromBufferAttribute(position);// process morph attributes if present if(morphAttributesPosition){for(var _i44=0,il=morphAttributesPosition.length;_i440)data.userData=this.userData;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){data.data.index={type:index.array.constructor.name,array:Array.prototype.slice.call(index.array)};}var attributes=this.attributes;for(var _key in attributes){var attribute=attributes[_key];var attributeData=attribute.toJSON(data.data);if(attribute.name!=='')attributeData.name=attribute.name;data.data.attributes[_key]=attributeData;}var morphAttributes={};var hasMorphAttributes=false;for(var _key2 in this.morphAttributes){var attributeArray=this.morphAttributes[_key2];var array=[];for(var _i56=0,il=attributeArray.length;_i560){morphAttributes[_key2]=array;hasMorphAttributes=true;}}if(hasMorphAttributes){data.data.morphAttributes=morphAttributes;data.data.morphTargetsRelative=this.morphTargetsRelative;}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 clone(){/* // Handle primitives const parameters = this.parameters; if ( parameters !== undefined ) { const values = []; for ( const key in parameters ) { values.push( parameters[ key ] ); } const geometry = Object.create( this.constructor.prototype ); this.constructor.apply( geometry, values ); return geometry; } return new this.constructor().copy( this ); */return new BufferGeometry().copy(this);},copy:function copy(source){// reset this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingBox=null;this.boundingSphere=null;// used for storing cloned, shared data var data={};// name this.name=source.name;// index var index=source.index;if(index!==null){this.setIndex(index.clone(data));}// attributes var attributes=source.attributes;for(var name in attributes){var attribute=attributes[name];this.setAttribute(name,attribute.clone(data));}// morph attributes var morphAttributes=source.morphAttributes;for(var _name2 in morphAttributes){var array=[];var morphAttribute=morphAttributes[_name2];// morphAttribute: array of Float32BufferAttributes for(var _i57=0,l=morphAttribute.length;_i570&&arguments[0]!==undefined?arguments[0]:new BufferGeometry();var material=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new MeshBasicMaterial();Object3D.call(this);this.type='Mesh';this.geometry=geometry;this.material=material;this.updateMorphTargets();}Mesh.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Mesh,isMesh:true,copy:function copy(source){Object3D.prototype.copy.call(this,source);if(source.morphTargetInfluences!==undefined){this.morphTargetInfluences=source.morphTargetInfluences.slice();}if(source.morphTargetDictionary!==undefined){this.morphTargetDictionary=Object.assign({},source.morphTargetDictionary);}this.material=source.material;this.geometry=source.geometry;return this;},updateMorphTargets:function updateMorphTargets(){var geometry=this.geometry;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(var m=0,ml=morphAttribute.length;m0){console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');}}},raycast:function raycast(raycaster,intersects){var geometry=this.geometry;var material=this.material;var matrixWorld=this.matrixWorld;if(material===undefined)return;// Checking boundingSphere distance to ray if(geometry.boundingSphere===null)geometry.computeBoundingSphere();_sphere.copy(geometry.boundingSphere);_sphere.applyMatrix4(matrixWorld);if(raycaster.ray.intersectsSphere(_sphere)===false)return;// _inverseMatrix.copy(matrixWorld).invert();_ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);// Check boundingBox before continuing if(geometry.boundingBox!==null){if(_ray.intersectsBox(geometry.boundingBox)===false)return;}var intersection;if(geometry.isBufferGeometry){var index=geometry.index;var position=geometry.attributes.position;var morphPosition=geometry.morphAttributes.position;var morphTargetsRelative=geometry.morphTargetsRelative;var uv=geometry.attributes.uv;var uv2=geometry.attributes.uv2;var groups=geometry.groups;var drawRange=geometry.drawRange;if(index!==null){// indexed buffer geometry if(Array.isArray(material)){for(var _i59=0,il=groups.length;_i590)uvs=faceVertexUvs;for(var f=0,fl=faces.length;fraycaster.far)return null;return {distance:distance,point:_intersectionPointWorld.clone(),object:object};}function checkBufferGeometryIntersection(object,material,raycaster,ray,position,morphPosition,morphTargetsRelative,uv,uv2,a,b,c){_vA.fromBufferAttribute(position,a);_vB.fromBufferAttribute(position,b);_vC.fromBufferAttribute(position,c);var morphInfluences=object.morphTargetInfluences;if(material.morphTargets&&morphPosition&&morphInfluences){_morphA.set(0,0,0);_morphB.set(0,0,0);_morphC.set(0,0,0);for(var _i63=0,il=morphPosition.length;_i630&&arguments[0]!==undefined?arguments[0]:1;var height=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var depth=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;var widthSegments=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;var heightSegments=arguments.length>4&&arguments[4]!==undefined?arguments[4]:1;var depthSegments=arguments.length>5&&arguments[5]!==undefined?arguments[5]:1;super();this.type='BoxBufferGeometry';this.parameters={width:width,height:height,depth:depth,widthSegments:widthSegments,heightSegments:heightSegments,depthSegments:depthSegments};var scope=this;// segments widthSegments=Math.floor(widthSegments);heightSegments=Math.floor(heightSegments);depthSegments=Math.floor(depthSegments);// buffers var indices=[];var vertices=[];var normals=[];var uvs=[];// helper variables var numberOfVertices=0;var groupStart=0;// build each side of the box geometry buildPlane('z','y','x',-1,-1,depth,height,width,depthSegments,heightSegments,0);// px buildPlane('z','y','x',1,-1,depth,height,-width,depthSegments,heightSegments,1);// nx buildPlane('x','z','y',1,1,width,depth,height,widthSegments,depthSegments,2);// py buildPlane('x','z','y',1,-1,width,depth,-height,widthSegments,depthSegments,3);// ny buildPlane('x','y','z',1,-1,width,height,depth,widthSegments,heightSegments,4);// pz buildPlane('x','y','z',-1,-1,width,height,-depth,widthSegments,heightSegments,5);// nz // build geometry this.setIndex(indices);this.setAttribute('position',new Float32BufferAttribute(vertices,3));this.setAttribute('normal',new Float32BufferAttribute(normals,3));this.setAttribute('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 vector=new Vector3();// generate vertices, normals and uvs for(var iy=0;iy0?1:-1;// now apply vector to normal buffer normals.push(vector.x,vector.y,vector.z);// uvs uvs.push(ix/gridX);uvs.push(1-iy/gridY);// counters vertexCounter+=1;}}// indices // 1. you need three indices to draw a single face // 2. a single segment consists of two faces // 3. so we need to generate six (2*3) indices per segment for(var _iy=0;_iy, * vertexShader: , * * wireframe: , * wireframeLinewidth: , * * lights: , * * skinning: , * morphTargets: , * morphNormals: * } */function ShaderMaterial(parameters){Material.call(this);this.type='ShaderMaterial';this.defines={};this.uniforms={};this.vertexShader=default_vertex;this.fragmentShader=default_fragment;this.linewidth=1;this.wireframe=false;this.wireframeLinewidth=1;this.fog=false;// set to use scene fog this.lights=false;// set to use scene lights this.clipping=false;// set to use user-defined clipping planes this.skinning=false;// set to use skinning attribute streams this.morphTargets=false;// set to use morph targets this.morphNormals=false;// set to use morph normals this.extensions={derivatives:false,// set to use derivatives fragDepth:false,// set to use fragment depth values drawBuffers:false,// set to use draw buffers shaderTextureLOD:false// set to use shader texture LOD };// When rendered geometry doesn't include these attributes but the material does, // use these default values in WebGL. This avoids errors when buffer data is missing. this.defaultAttributeValues={'color':[1,1,1],'uv':[0,0],'uv2':[0,0]};this.index0AttributeName=undefined;this.uniformsNeedUpdate=false;this.glslVersion=null;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=cloneUniforms(source.uniforms);this.defines=Object.assign({},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=Object.assign({},source.extensions);this.glslVersion=source.glslVersion;return this;};ShaderMaterial.prototype.toJSON=function(meta){var data=Material.prototype.toJSON.call(this,meta);data.glslVersion=this.glslVersion;data.uniforms={};for(var name in this.uniforms){var uniform=this.uniforms[name];var value=uniform.value;if(value&&value.isTexture){data.uniforms[name]={type:'t',value:value.toJSON(meta).uuid};}else if(value&&value.isColor){data.uniforms[name]={type:'c',value:value.getHex()};}else if(value&&value.isVector2){data.uniforms[name]={type:'v2',value:value.toArray()};}else if(value&&value.isVector3){data.uniforms[name]={type:'v3',value:value.toArray()};}else if(value&&value.isVector4){data.uniforms[name]={type:'v4',value:value.toArray()};}else if(value&&value.isMatrix3){data.uniforms[name]={type:'m3',value:value.toArray()};}else if(value&&value.isMatrix4){data.uniforms[name]={type:'m4',value:value.toArray()};}else {data.uniforms[name]={value:value};// note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far }}if(Object.keys(this.defines).length>0)data.defines=this.defines;data.vertexShader=this.vertexShader;data.fragmentShader=this.fragmentShader;var extensions={};for(var key in this.extensions){if(this.extensions[key]===true)extensions[key]=true;}if(Object.keys(extensions).length>0)data.extensions=extensions;return data;};function Camera(){Object3D.call(this);this.type='Camera';this.matrixWorldInverse=new Matrix4();this.projectionMatrix=new Matrix4();this.projectionMatrixInverse=new Matrix4();}Camera.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Camera,isCamera:true,copy:function copy(source,recursive){Object3D.prototype.copy.call(this,source,recursive);this.matrixWorldInverse.copy(source.matrixWorldInverse);this.projectionMatrix.copy(source.projectionMatrix);this.projectionMatrixInverse.copy(source.projectionMatrixInverse);return this;},getWorldDirection:function getWorldDirection(target){if(target===undefined){console.warn('THREE.Camera: .getWorldDirection() target is now required');target=new Vector3();}this.updateWorldMatrix(true,false);var e=this.matrixWorld.elements;return target.set(-e[8],-e[9],-e[10]).normalize();},updateMatrixWorld:function updateMatrixWorld(force){Object3D.prototype.updateMatrixWorld.call(this,force);this.matrixWorldInverse.copy(this.matrixWorld).invert();},updateWorldMatrix:function updateWorldMatrix(updateParents,updateChildren){Object3D.prototype.updateWorldMatrix.call(this,updateParents,updateChildren);this.matrixWorldInverse.copy(this.matrixWorld).invert();},clone:function clone(){return new this.constructor().copy(this);}});function PerspectiveCamera(){var fov=arguments.length>0&&arguments[0]!==undefined?arguments[0]:50;var aspect=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var near=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0.1;var far=arguments.length>3&&arguments[3]!==undefined?arguments[3]:2000;Camera.call(this);this.type='PerspectiveCamera';this.fov=fov;this.zoom=1;this.near=near;this.far=far;this.focus=10;this.aspect=aspect;this.view=null;this.filmGauge=35;// width of the film (default in millimeters) this.filmOffset=0;// horizontal film offset (same unit as gauge) this.updateProjectionMatrix();}PerspectiveCamera.prototype=Object.assign(Object.create(Camera.prototype),{constructor:PerspectiveCamera,isPerspectiveCamera:true,copy:function copy(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;},/** * Sets the FOV by focal length in respect to the current .filmGauge. * * The default film gauge is 35, so that the focal length can be specified for * a 35mm (full frame) camera. * * Values for focal length and film gauge must have the same unit. */setFocalLength:function setFocalLength(focalLength){// see http://www.bobatkins.com/photography/technical/field_of_view.html var vExtentSlope=0.5*this.getFilmHeight()/focalLength;this.fov=MathUtils.RAD2DEG*2*Math.atan(vExtentSlope);this.updateProjectionMatrix();},/** * Calculates the focal length from the current .fov and .filmGauge. */getFocalLength:function getFocalLength(){var vExtentSlope=Math.tan(MathUtils.DEG2RAD*0.5*this.fov);return 0.5*this.getFilmHeight()/vExtentSlope;},getEffectiveFOV:function getEffectiveFOV(){return MathUtils.RAD2DEG*2*Math.atan(Math.tan(MathUtils.DEG2RAD*0.5*this.fov)/this.zoom);},getFilmWidth:function getFilmWidth(){// film not completely covered in portrait format (aspect < 1) return this.filmGauge*Math.min(this.aspect,1);},getFilmHeight:function getFilmHeight(){// film not completely covered in landscape format (aspect > 1) return this.filmGauge/Math.max(this.aspect,1);},/** * Sets an offset in a larger frustum. This is useful for multi-window or * multi-monitor/multi-machine setups. * * For example, if you have 3x2 monitors and each monitor is 1920x1080 and * the monitors are in grid like this * * +---+---+---+ * | A | B | C | * +---+---+---+ * | D | E | F | * +---+---+---+ * * then for each monitor you would call it like this * * const w = 1920; * const h = 1080; * const fullWidth = w * 3; * const fullHeight = h * 2; * * --A-- * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); * --B-- * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); * --C-- * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); * --D-- * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); * --E-- * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); * --F-- * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); * * Note there is no reason monitors have to be the same size or in a grid. */setViewOffset:function setViewOffset(fullWidth,fullHeight,x,y,width,height){this.aspect=fullWidth/fullHeight;if(this.view===null){this.view={enabled:true,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1};}this.view.enabled=true;this.view.fullWidth=fullWidth;this.view.fullHeight=fullHeight;this.view.offsetX=x;this.view.offsetY=y;this.view.width=width;this.view.height=height;this.updateProjectionMatrix();},clearViewOffset:function clearViewOffset(){if(this.view!==null){this.view.enabled=false;}this.updateProjectionMatrix();},updateProjectionMatrix:function updateProjectionMatrix(){var near=this.near;var top=near*Math.tan(MathUtils.DEG2RAD*0.5*this.fov)/this.zoom;var height=2*top;var width=this.aspect*height;var left=-0.5*width;var view=this.view;if(this.view!==null&&this.view.enabled){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);this.projectionMatrixInverse.copy(this.projectionMatrix).invert();},toJSON:function toJSON(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;}});var fov=90,aspect=1;function CubeCamera(near,far,renderTarget){Object3D.call(this);this.type='CubeCamera';if(renderTarget.isWebGLCubeRenderTarget!==true){console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');return;}this.renderTarget=renderTarget;var cameraPX=new PerspectiveCamera(fov,aspect,near,far);cameraPX.layers=this.layers;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.layers=this.layers;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.layers=this.layers;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.layers=this.layers;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.layers=this.layers;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.layers=this.layers;cameraNZ.up.set(0,-1,0);cameraNZ.lookAt(new Vector3(0,0,-1));this.add(cameraNZ);this.update=function(renderer,scene){if(this.parent===null)this.updateMatrixWorld();var currentXrEnabled=renderer.xr.enabled;var currentRenderTarget=renderer.getRenderTarget();renderer.xr.enabled=false;var generateMipmaps=renderTarget.texture.generateMipmaps;renderTarget.texture.generateMipmaps=false;renderer.setRenderTarget(renderTarget,0);renderer.render(scene,cameraPX);renderer.setRenderTarget(renderTarget,1);renderer.render(scene,cameraNX);renderer.setRenderTarget(renderTarget,2);renderer.render(scene,cameraPY);renderer.setRenderTarget(renderTarget,3);renderer.render(scene,cameraNY);renderer.setRenderTarget(renderTarget,4);renderer.render(scene,cameraPZ);renderTarget.texture.generateMipmaps=generateMipmaps;renderer.setRenderTarget(renderTarget,5);renderer.render(scene,cameraNZ);renderer.setRenderTarget(currentRenderTarget);renderer.xr.enabled=currentXrEnabled;};}CubeCamera.prototype=Object.create(Object3D.prototype);CubeCamera.prototype.constructor=CubeCamera;function CubeTexture(images,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding){images=images!==undefined?images:[];mapping=mapping!==undefined?mapping:CubeReflectionMapping;format=format!==undefined?format:RGBFormat;Texture.call(this,images,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding);this.flipY=false;// Why CubeTexture._needsFlipEnvMap is necessary: // // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js) // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words, // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false) // when using WebGLCubeRenderTarget.texture as a cube texture. this._needsFlipEnvMap=true;}CubeTexture.prototype=Object.create(Texture.prototype);CubeTexture.prototype.constructor=CubeTexture;CubeTexture.prototype.isCubeTexture=true;Object.defineProperty(CubeTexture.prototype,'images',{get:function get(){return this.image;},set:function set(value){this.image=value;}});function WebGLCubeRenderTarget(size,options,dummy){if(Number.isInteger(options)){console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');options=dummy;}WebGLRenderTarget.call(this,size,size,options);options=options||{};this.texture=new CubeTexture(undefined,options.mapping,options.wrapS,options.wrapT,options.magFilter,options.minFilter,options.format,options.type,options.anisotropy,options.encoding);this.texture._needsFlipEnvMap=false;}WebGLCubeRenderTarget.prototype=Object.create(WebGLRenderTarget.prototype);WebGLCubeRenderTarget.prototype.constructor=WebGLCubeRenderTarget;WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget=true;WebGLCubeRenderTarget.prototype.fromEquirectangularTexture=function(renderer,texture){this.texture.type=texture.type;this.texture.format=RGBAFormat;// see #18859 this.texture.encoding=texture.encoding;this.texture.generateMipmaps=texture.generateMipmaps;this.texture.minFilter=texture.minFilter;this.texture.magFilter=texture.magFilter;var shader={uniforms:{tEquirect:{value:null}},vertexShader:/* glsl */"\n\n\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t#include \n\t\t\t\t#include \n\n\t\t\t}\n\t\t",fragmentShader:/* glsl */"\n\n\t\t\tuniform sampler2D tEquirect;\n\n\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t#include \n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t}\n\t\t"};var geometry=new BoxBufferGeometry(5,5,5);var material=new ShaderMaterial({name:'CubemapFromEquirect',uniforms:cloneUniforms(shader.uniforms),vertexShader:shader.vertexShader,fragmentShader:shader.fragmentShader,side:BackSide,blending:NoBlending});material.uniforms.tEquirect.value=texture;var mesh=new Mesh(geometry,material);var currentMinFilter=texture.minFilter;// Avoid blurred poles if(texture.minFilter===LinearMipmapLinearFilter)texture.minFilter=LinearFilter;var camera=new CubeCamera(1,10,this);camera.update(renderer,mesh);texture.minFilter=currentMinFilter;mesh.geometry.dispose();mesh.material.dispose();return this;};WebGLCubeRenderTarget.prototype.clear=function(renderer,color,depth,stencil){var currentRenderTarget=renderer.getRenderTarget();for(var _i64=0;_i64<6;_i64++){renderer.setRenderTarget(this,_i64);renderer.clear(color,depth,stencil);}renderer.setRenderTarget(currentRenderTarget);};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||null,width:width||1,height:height||1};this.magFilter=magFilter!==undefined?magFilter:NearestFilter;this.minFilter=minFilter!==undefined?minFilter:NearestFilter;this.generateMipmaps=false;this.flipY=false;this.unpackAlignment=1;this.needsUpdate=true;}DataTexture.prototype=Object.create(Texture.prototype);DataTexture.prototype.constructor=DataTexture;DataTexture.prototype.isDataTexture=true;var _sphere$1=/*@__PURE__*/new Sphere();var _vector$5=/*@__PURE__*/new Vector3();class Frustum{constructor(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()];}set(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(){return new this.constructor().copy(this);}copy(frustum){var planes=this.planes;for(var _i65=0;_i65<6;_i65++){planes[_i65].copy(frustum.planes[_i65]);}return this;}setFromProjectionMatrix(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(object){var geometry=object.geometry;if(geometry.boundingSphere===null)geometry.computeBoundingSphere();_sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);return this.intersectsSphere(_sphere$1);}intersectsSprite(sprite){_sphere$1.center.set(0,0,0);_sphere$1.radius=0.7071067811865476;_sphere$1.applyMatrix4(sprite.matrixWorld);return this.intersectsSphere(_sphere$1);}intersectsSphere(sphere){var planes=this.planes;var center=sphere.center;var negRadius=-sphere.radius;for(var _i66=0;_i66<6;_i66++){var distance=planes[_i66].distanceToPoint(center);if(distance0?box.max.x:box.min.x;_vector$5.y=plane.normal.y>0?box.max.y:box.min.y;_vector$5.z=plane.normal.z>0?box.max.z:box.min.z;if(plane.distanceToPoint(_vector$5)<0){return false;}}return true;}containsPoint(point){var planes=this.planes;for(var _i68=0;_i68<6;_i68++){if(planes[_i68].distanceToPoint(point)<0){return false;}}return true;}}function WebGLAnimation(){var context=null;var isAnimating=false;var animationLoop=null;var requestId=null;function onAnimationFrame(time,frame){animationLoop(time,frame);requestId=context.requestAnimationFrame(onAnimationFrame);}return {start:function start(){if(isAnimating===true)return;if(animationLoop===null)return;requestId=context.requestAnimationFrame(onAnimationFrame);isAnimating=true;},stop:function stop(){context.cancelAnimationFrame(requestId);isAnimating=false;},setAnimationLoop:function setAnimationLoop(callback){animationLoop=callback;},setContext:function setContext(value){context=value;}};}function WebGLAttributes(gl,capabilities){var isWebGL2=capabilities.isWebGL2;var buffers=new WeakMap();function createBuffer(attribute,bufferType){var array=attribute.array;var usage=attribute.usage;var buffer=gl.createBuffer();gl.bindBuffer(bufferType,buffer);gl.bufferData(bufferType,array,usage);attribute.onUploadCallback();var type=5126;if(array instanceof Float32Array){type=5126;}else if(array instanceof Float64Array){console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');}else if(array instanceof Uint16Array){if(attribute.isFloat16BufferAttribute){if(isWebGL2){type=5131;}else {console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');}}else {type=5123;}}else if(array instanceof Int16Array){type=5122;}else if(array instanceof Uint32Array){type=5125;}else if(array instanceof Int32Array){type=5124;}else if(array instanceof Int8Array){type=5120;}else if(array instanceof Uint8Array){type=5121;}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(updateRange.count===-1){// Not using update ranges gl.bufferSubData(bufferType,0,array);}else {if(isWebGL2){gl.bufferSubData(bufferType,updateRange.offset*array.BYTES_PER_ELEMENT,array,updateRange.offset,updateRange.count);}else {gl.bufferSubData(bufferType,updateRange.offset*array.BYTES_PER_ELEMENT,array.subarray(updateRange.offset,updateRange.offset+updateRange.count));}updateRange.count=-1;// reset range }}// function get(attribute){if(attribute.isInterleavedBufferAttribute)attribute=attribute.data;return buffers.get(attribute);}function remove(attribute){if(attribute.isInterleavedBufferAttribute)attribute=attribute.data;var data=buffers.get(attribute);if(data){gl.deleteBuffer(data.buffer);buffers.delete(attribute);}}function update(attribute,bufferType){if(attribute.isGLBufferAttribute){var cached=buffers.get(attribute);if(!cached||cached.version0&&arguments[0]!==undefined?arguments[0]:1;var height=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var widthSegments=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;var heightSegments=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;super();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);var gridY=Math.floor(heightSegments);var gridX1=gridX+1;var gridY1=gridY+1;var segment_width=width/gridX;var segment_height=height/gridY;// var indices=[];var vertices=[];var normals=[];var uvs=[];for(var iy=0;iy1&&arguments[1]!==undefined?arguments[1]:1;clearColor.set(color);clearAlpha=alpha;setClear(clearColor,clearAlpha);},getClearAlpha:function getClearAlpha(){return clearAlpha;},setClearAlpha:function setClearAlpha(alpha){clearAlpha=alpha;setClear(clearColor,clearAlpha);},render:render};}function WebGLBindingStates(gl,extensions,attributes,capabilities){var maxVertexAttributes=gl.getParameter(34921);var extension=capabilities.isWebGL2?null:extensions.get('OES_vertex_array_object');var vaoAvailable=capabilities.isWebGL2||extension!==null;var bindingStates={};var defaultState=createBindingState(null);var currentState=defaultState;function setup(object,material,program,geometry,index){var updateBuffers=false;if(vaoAvailable){var state=getBindingState(geometry,program,material);if(currentState!==state){currentState=state;bindVertexArrayObject(currentState.object);}updateBuffers=needsUpdate(geometry,index);if(updateBuffers)saveCache(geometry,index);}else {var wireframe=material.wireframe===true;if(currentState.geometry!==geometry.id||currentState.program!==program.id||currentState.wireframe!==wireframe){currentState.geometry=geometry.id;currentState.program=program.id;currentState.wireframe=wireframe;updateBuffers=true;}}if(object.isInstancedMesh===true){updateBuffers=true;}if(index!==null){attributes.update(index,34963);}if(updateBuffers){setupVertexAttributes(object,material,program,geometry);if(index!==null){gl.bindBuffer(34963,attributes.get(index).buffer);}}}function createVertexArrayObject(){if(capabilities.isWebGL2)return gl.createVertexArray();return extension.createVertexArrayOES();}function bindVertexArrayObject(vao){if(capabilities.isWebGL2)return gl.bindVertexArray(vao);return extension.bindVertexArrayOES(vao);}function deleteVertexArrayObject(vao){if(capabilities.isWebGL2)return gl.deleteVertexArray(vao);return extension.deleteVertexArrayOES(vao);}function getBindingState(geometry,program,material){var wireframe=material.wireframe===true;var programMap=bindingStates[geometry.id];if(programMap===undefined){programMap={};bindingStates[geometry.id]=programMap;}var stateMap=programMap[program.id];if(stateMap===undefined){stateMap={};programMap[program.id]=stateMap;}var state=stateMap[wireframe];if(state===undefined){state=createBindingState(createVertexArrayObject());stateMap[wireframe]=state;}return state;}function createBindingState(vao){var newAttributes=[];var enabledAttributes=[];var attributeDivisors=[];for(var _i69=0;_i69=0){var geometryAttribute=geometryAttributes[name];if(geometryAttribute!==undefined){var normalized=geometryAttribute.normalized;var size=geometryAttribute.itemSize;var attribute=attributes.get(geometryAttribute);// TODO Attribute may not be available on context restore 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){enableAttributeAndDivisor(programAttribute,data.meshPerAttribute);if(geometry._maxInstanceCount===undefined){geometry._maxInstanceCount=data.meshPerAttribute*data.count;}}else {enableAttribute(programAttribute);}gl.bindBuffer(34962,buffer);vertexAttribPointer(programAttribute,size,type,normalized,stride*bytesPerElement,offset*bytesPerElement);}else {if(geometryAttribute.isInstancedBufferAttribute){enableAttributeAndDivisor(programAttribute,geometryAttribute.meshPerAttribute);if(geometry._maxInstanceCount===undefined){geometry._maxInstanceCount=geometryAttribute.meshPerAttribute*geometryAttribute.count;}}else {enableAttribute(programAttribute);}gl.bindBuffer(34962,buffer);vertexAttribPointer(programAttribute,size,type,normalized,0,0);}}else if(name==='instanceMatrix'){var _attribute7=attributes.get(object.instanceMatrix);// TODO Attribute may not be available on context restore if(_attribute7===undefined)continue;var _buffer=_attribute7.buffer;var _type=_attribute7.type;enableAttributeAndDivisor(programAttribute+0,1);enableAttributeAndDivisor(programAttribute+1,1);enableAttributeAndDivisor(programAttribute+2,1);enableAttributeAndDivisor(programAttribute+3,1);gl.bindBuffer(34962,_buffer);gl.vertexAttribPointer(programAttribute+0,4,_type,false,64,0);gl.vertexAttribPointer(programAttribute+1,4,_type,false,64,16);gl.vertexAttribPointer(programAttribute+2,4,_type,false,64,32);gl.vertexAttribPointer(programAttribute+3,4,_type,false,64,48);}else if(name==='instanceColor'){var _attribute8=attributes.get(object.instanceColor);// TODO Attribute may not be available on context restore if(_attribute8===undefined)continue;var _buffer2=_attribute8.buffer;var _type2=_attribute8.type;enableAttributeAndDivisor(programAttribute,1);gl.bindBuffer(34962,_buffer2);gl.vertexAttribPointer(programAttribute,3,_type2,false,12,0);}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);}}}}}disableUnusedAttributes();}function dispose(){reset();for(var geometryId in bindingStates){var programMap=bindingStates[geometryId];for(var programId in programMap){var stateMap=programMap[programId];for(var wireframe in stateMap){deleteVertexArrayObject(stateMap[wireframe].object);delete stateMap[wireframe];}delete programMap[programId];}delete bindingStates[geometryId];}}function releaseStatesOfGeometry(geometry){if(bindingStates[geometry.id]===undefined)return;var programMap=bindingStates[geometry.id];for(var programId in programMap){var stateMap=programMap[programId];for(var wireframe in stateMap){deleteVertexArrayObject(stateMap[wireframe].object);delete stateMap[wireframe];}delete programMap[programId];}delete bindingStates[geometry.id];}function releaseStatesOfProgram(program){for(var geometryId in bindingStates){var programMap=bindingStates[geometryId];if(programMap[program.id]===undefined)continue;var stateMap=programMap[program.id];for(var wireframe in stateMap){deleteVertexArrayObject(stateMap[wireframe].object);delete stateMap[wireframe];}delete programMap[program.id];}}function reset(){resetDefaultState();if(currentState===defaultState)return;currentState=defaultState;bindVertexArrayObject(currentState.object);}// for backward-compatilibity function resetDefaultState(){defaultState.geometry=null;defaultState.program=null;defaultState.wireframe=false;}return {setup:setup,reset:reset,resetDefaultState:resetDefaultState,dispose:dispose,releaseStatesOfGeometry:releaseStatesOfGeometry,releaseStatesOfProgram:releaseStatesOfProgram,initAttributes:initAttributes,enableAttribute:enableAttribute,disableUnusedAttributes:disableUnusedAttributes};}function WebGLBufferRenderer(gl,extensions,info,capabilities){var isWebGL2=capabilities.isWebGL2;var mode;function setMode(value){mode=value;}function render(start,count){gl.drawArrays(mode,start,count);info.update(count,mode,1);}function renderInstances(start,count,primcount){if(primcount===0)return;var extension,methodName;if(isWebGL2){extension=gl;methodName='drawArraysInstanced';}else {extension=extensions.get('ANGLE_instanced_arrays');methodName='drawArraysInstancedANGLE';if(extension===null){console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');return;}}extension[methodName](mode,start,count,primcount);info.update(count,mode,primcount);}// this.setMode=setMode;this.render=render;this.renderInstances=renderInstances;}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(35633,36338).precision>0&&gl.getShaderPrecisionFormat(35632,36338).precision>0){return 'highp';}precision='mediump';}if(precision==='mediump'){if(gl.getShaderPrecisionFormat(35633,36337).precision>0&&gl.getShaderPrecisionFormat(35632,36337).precision>0){return 'mediump';}}return 'lowp';}/* eslint-disable no-undef */var isWebGL2=typeof WebGL2RenderingContext!=='undefined'&&gl instanceof WebGL2RenderingContext||typeof WebGL2ComputeRenderingContext!=='undefined'&&gl instanceof WebGL2ComputeRenderingContext;/* eslint-enable no-undef */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;var maxTextures=gl.getParameter(34930);var maxVertexTextures=gl.getParameter(35660);var maxTextureSize=gl.getParameter(3379);var maxCubemapSize=gl.getParameter(34076);var maxAttributes=gl.getParameter(34921);var maxVertexUniforms=gl.getParameter(36347);var maxVaryings=gl.getParameter(36348);var maxFragmentUniforms=gl.getParameter(36349);var vertexTextures=maxVertexTextures>0;var floatFragmentTextures=isWebGL2||!!extensions.get('OES_texture_float');var floatVertexTextures=vertexTextures&&floatFragmentTextures;var maxSamples=isWebGL2?gl.getParameter(36183):0;return {isWebGL2:isWebGL2,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,maxSamples:maxSamples};}function WebGLClipping(properties){var scope=this;var globalState=null,numGlobalPlanes=0,localClippingEnabled=false,renderingShadows=false;var 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||// enable state of previous frame - the clipping code has to // run another frame in order to reset the state: 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(material,camera,useCache){var planes=material.clippingPlanes,clipIntersection=material.clipIntersection,clipShadows=material.clipShadows;var materialProperties=properties.get(material);if(!localClippingEnabled||planes===null||planes.length===0||renderingShadows&&!clipShadows){// there's no local clipping if(renderingShadows){// there's no global clipping projectPlanes(null);}else {resetGlobalState();}}else {var nGlobal=renderingShadows?0:numGlobalPlanes,lGlobal=nGlobal*4;var dstArray=materialProperties.clippingState||null;uniform.value=dstArray;// ensure unique state dstArray=projectPlanes(planes,camera,lGlobal,useCache);for(var _i72=0;_i72!==lGlobal;++_i72){dstArray[_i72]=globalState[_i72];}materialProperties.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;var 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.length0){var currentRenderList=renderer.getRenderList();var currentRenderTarget=renderer.getRenderTarget();var renderTarget=new WebGLCubeRenderTarget(image.height/2);renderTarget.fromEquirectangularTexture(renderer,texture);cubemaps.set(texture,renderTarget);renderer.setRenderTarget(currentRenderTarget);renderer.setRenderList(currentRenderList);texture.addEventListener('dispose',onTextureDispose);return mapTextureMapping(renderTarget.texture,texture.mapping);}else {// image not yet ready. try the conversion next frame return null;}}}}return texture;}function onTextureDispose(event){var texture=event.target;texture.removeEventListener('dispose',onTextureDispose);var cubemap=cubemaps.get(texture);if(cubemap!==undefined){cubemaps.delete(texture);cubemap.dispose();}}function dispose(){cubemaps=new WeakMap();}return {get:get,dispose:dispose};}function WebGLExtensions(gl){var extensions={};return {has:function has(name){if(extensions[name]!==undefined){return extensions[name]!==null;}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;default:extension=gl.getExtension(name);}extensions[name]=extension;return extension!==null;},get:function get(name){if(!this.has(name)){console.warn('THREE.WebGLRenderer: '+name+' extension not supported.');}return extensions[name];}};}function WebGLGeometries(gl,attributes,info,bindingStates){var geometries=new WeakMap();var wireframeAttributes=new WeakMap();function onGeometryDispose(event){var geometry=event.target;var buffergeometry=geometries.get(geometry);if(buffergeometry.index!==null){attributes.remove(buffergeometry.index);}for(var name in buffergeometry.attributes){attributes.remove(buffergeometry.attributes[name]);}geometry.removeEventListener('dispose',onGeometryDispose);geometries.delete(geometry);var attribute=wireframeAttributes.get(buffergeometry);if(attribute){attributes.remove(attribute);wireframeAttributes.delete(buffergeometry);}bindingStates.releaseStatesOfGeometry(buffergeometry);if(geometry.isInstancedBufferGeometry===true){delete geometry._maxInstanceCount;}// info.memory.geometries--;}function get(object,geometry){var buffergeometry=geometries.get(geometry);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.set(geometry,buffergeometry);info.memory.geometries++;return buffergeometry;}function update(geometry){var geometryAttributes=geometry.attributes;// Updating index buffer in VAO now. See WebGLBindingStates. for(var name in geometryAttributes){attributes.update(geometryAttributes[name],34962);}// morph targets var morphAttributes=geometry.morphAttributes;for(var _name3 in morphAttributes){var array=morphAttributes[_name3];for(var _i74=0,l=array.length;_i7465535?Uint32BufferAttribute:Uint16BufferAttribute)(indices,1);attribute.version=version;// Updating index buffer in VAO now. See WebGLBindingStates // var previousAttribute=wireframeAttributes.get(geometry);if(previousAttribute)attributes.remove(previousAttribute);// wireframeAttributes.set(geometry,attribute);}function getWireframeAttribute(geometry){var currentAttribute=wireframeAttributes.get(geometry);if(currentAttribute){var geometryIndex=geometry.index;if(geometryIndex!==null){// if the attribute is obsolete, create a new one if(currentAttribute.version0&&arguments[0]!==undefined?arguments[0]:null;var width=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var height=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;var depth=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;Texture.call(this,null);this.image={data,width,height,depth};this.magFilter=NearestFilter;this.minFilter=NearestFilter;this.wrapR=ClampToEdgeWrapping;this.generateMipmaps=false;this.flipY=false;this.needsUpdate=true;}DataTexture2DArray.prototype=Object.create(Texture.prototype);DataTexture2DArray.prototype.constructor=DataTexture2DArray;DataTexture2DArray.prototype.isDataTexture2DArray=true;function DataTexture3D(){var data=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;var width=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var height=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;var depth=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;// We're going to add .setXXX() methods for setting properties later. // Users can still set in DataTexture3D directly. // // const texture = new THREE.DataTexture3D( data, width, height, depth ); // texture.anisotropy = 16; // // See #14839 Texture.call(this,null);this.image={data,width,height,depth};this.magFilter=NearestFilter;this.minFilter=NearestFilter;this.wrapR=ClampToEdgeWrapping;this.generateMipmaps=false;this.flipY=false;this.needsUpdate=true;}DataTexture3D.prototype=Object.create(Texture.prototype);DataTexture3D.prototype.constructor=DataTexture3D;DataTexture3D.prototype.isDataTexture3D=true;/** * Uniforms of a program. * Those form a tree structure with a special top-level container for the root, * which you get by calling 'new WebGLUniforms( gl, program )'. * * * Properties of inner nodes including the top-level container: * * .seq - array of nested uniforms * .map - nested uniforms by name * * * Methods of all nodes except the top-level container: * * .setValue( gl, value, [textures] ) * * uploads a uniform value(s) * the 'textures' parameter is needed for sampler uniforms * * * Static methods of the top-level container (textures factorizations): * * .upload( gl, seq, values, textures ) * * sets uniforms in 'seq' to 'values[id].value' * * .seqWithValue( seq, values ) : filteredSeq * * filters 'seq' entries with corresponding entry in values * * * Methods of the top-level container (textures factorizations): * * .setValue( gl, name, value, textures ) * * sets uniform with name 'name' to 'value' * * .setOptional( gl, obj, prop ) * * like .set for an optional property of the object * */var emptyTexture=new Texture();var emptyTexture2dArray=new DataTexture2DArray();var emptyTexture3d=new DataTexture3D();var emptyCubeTexture=new CubeTexture();// --- Utilities --- // Array Caches (provide typed arrays for temporary by size) var arrayCacheF32=[];var arrayCacheI32=[];// Float32Array caches used for uploading Matrix uniforms var mat4array=new Float32Array(16);var mat3array=new Float32Array(9);var mat2array=new Float32Array(4);// Flattening for arrays of vectors and matrices function flatten(array,nBlocks,blockSize){var firstElem=array[0];if(firstElem<=0||firstElem>0)return array;// unoptimized: ! isNaN( firstElem ) // see http://jacksondunstan.com/articles/983 var n=nBlocks*blockSize;var r=arrayCacheF32[n];if(r===undefined){r=new Float32Array(n);arrayCacheF32[n]=r;}if(nBlocks!==0){firstElem.toArray(r,0);for(var _i82=1,offset=0;_i82!==nBlocks;++_i82){offset+=blockSize;array[_i82].toArray(r,offset);}}return r;}function arraysEqual(a,b){if(a.length!==b.length)return false;for(var _i83=0,l=a.length;_i83/gm;function resolveIncludes(string){return string.replace(includePattern,includeReplacer);}function includeReplacer(match,include){var string=ShaderChunk[include];if(string===undefined){throw new Error('Can not resolve #include <'+include+'>');}return resolveIncludes(string);}// Unroll Loops var deprecatedUnrollLoopPattern=/#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;var unrollLoopPattern=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function unrollLoops(string){return string.replace(unrollLoopPattern,loopReplacer).replace(deprecatedUnrollLoopPattern,deprecatedLoopReplacer);}function deprecatedLoopReplacer(match,start,end,snippet){console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');return loopReplacer(match,start,end,snippet);}function loopReplacer(match,start,end,snippet){var string='';for(var _i94=parseInt(start);_i940?renderer.gammaFactor:1.0;var customExtensions=parameters.isWebGL2?'':generateExtensions(parameters);var customDefines=generateDefines(defines);var program=gl.createProgram();var prefixVertex,prefixFragment;var versionString=parameters.glslVersion?'#version '+parameters.glslVersion+'\n':'';if(parameters.isRawShaderMaterial){prefixVertex=[customDefines].filter(filterEmptyLine).join('\n');if(prefixVertex.length>0){prefixVertex+='\n';}prefixFragment=[customExtensions,customDefines].filter(filterEmptyLine).join('\n');if(prefixFragment.length>0){prefixFragment+='\n';}}else {prefixVertex=[generatePrecision(parameters),'#define SHADER_NAME '+parameters.shaderName,customDefines,parameters.instancing?'#define USE_INSTANCING':'',parameters.instancingColor?'#define USE_INSTANCING_COLOR':'',parameters.supportsVertexTextures?'#define VERTEX_TEXTURES':'','#define GAMMA_FACTOR '+gammaFactorDefine,'#define MAX_BONES '+parameters.maxBones,parameters.useFog&¶meters.fog?'#define USE_FOG':'',parameters.useFog&¶meters.fogExp2?'#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.normalMap&¶meters.objectSpaceNormalMap?'#define OBJECTSPACE_NORMALMAP':'',parameters.normalMap&¶meters.tangentSpaceNormalMap?'#define TANGENTSPACE_NORMALMAP':'',parameters.clearcoatMap?'#define USE_CLEARCOATMAP':'',parameters.clearcoatRoughnessMap?'#define USE_CLEARCOAT_ROUGHNESSMAP':'',parameters.clearcoatNormalMap?'#define USE_CLEARCOAT_NORMALMAP':'',parameters.displacementMap&¶meters.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.transmissionMap?'#define USE_TRANSMISSIONMAP':'',parameters.vertexTangents?'#define USE_TANGENT':'',parameters.vertexColors?'#define USE_COLOR':'',parameters.vertexUvs?'#define USE_UV':'',parameters.uvsVertexOnly?'#define UVS_VERTEX_ONLY':'',parameters.flatShading?'#define FLAT_SHADED':'',parameters.skinning?'#define USE_SKINNING':'',parameters.useVertexTexture?'#define BONE_TEXTURE':'',parameters.morphTargets?'#define USE_MORPHTARGETS':'',parameters.morphNormals&¶meters.flatShading===false?'#define USE_MORPHNORMALS':'',parameters.doubleSided?'#define DOUBLE_SIDED':'',parameters.flipSided?'#define FLIP_SIDED':'',parameters.shadowMapEnabled?'#define USE_SHADOWMAP':'',parameters.shadowMapEnabled?'#define '+shadowMapTypeDefine:'',parameters.sizeAttenuation?'#define USE_SIZEATTENUATION':'',parameters.logarithmicDepthBuffer?'#define USE_LOGDEPTHBUF':'',parameters.logarithmicDepthBuffer&¶meters.rendererExtensionFragDepth?'#define USE_LOGDEPTHBUF_EXT':'','uniform mat4 modelMatrix;','uniform mat4 modelViewMatrix;','uniform mat4 projectionMatrix;','uniform mat4 viewMatrix;','uniform mat3 normalMatrix;','uniform vec3 cameraPosition;','uniform bool isOrthographic;','#ifdef USE_INSTANCING',' attribute mat4 instanceMatrix;','#endif','#ifdef USE_INSTANCING_COLOR',' attribute vec3 instanceColor;','#endif','attribute vec3 position;','attribute vec3 normal;','attribute vec2 uv;','#ifdef USE_TANGENT',' attribute vec4 tangent;','#endif','#ifdef USE_COLOR',' attribute vec3 color;','#endif','#ifdef USE_MORPHTARGETS',' attribute vec3 morphTarget0;',' attribute vec3 morphTarget1;',' attribute vec3 morphTarget2;',' attribute vec3 morphTarget3;',' #ifdef USE_MORPHNORMALS',' attribute vec3 morphNormal0;',' attribute vec3 morphNormal1;',' attribute vec3 morphNormal2;',' attribute vec3 morphNormal3;',' #else',' attribute vec3 morphTarget4;',' attribute vec3 morphTarget5;',' attribute vec3 morphTarget6;',' attribute vec3 morphTarget7;',' #endif','#endif','#ifdef USE_SKINNING',' attribute vec4 skinIndex;',' attribute vec4 skinWeight;','#endif','\n'].filter(filterEmptyLine).join('\n');prefixFragment=[customExtensions,generatePrecision(parameters),'#define SHADER_NAME '+parameters.shaderName,customDefines,parameters.alphaTest?'#define ALPHATEST '+parameters.alphaTest+(parameters.alphaTest%1?'':'.0'):'',// add '.0' if integer '#define GAMMA_FACTOR '+gammaFactorDefine,parameters.useFog&¶meters.fog?'#define USE_FOG':'',parameters.useFog&¶meters.fogExp2?'#define FOG_EXP2':'',parameters.map?'#define USE_MAP':'',parameters.matcap?'#define USE_MATCAP':'',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.normalMap&¶meters.objectSpaceNormalMap?'#define OBJECTSPACE_NORMALMAP':'',parameters.normalMap&¶meters.tangentSpaceNormalMap?'#define TANGENTSPACE_NORMALMAP':'',parameters.clearcoatMap?'#define USE_CLEARCOATMAP':'',parameters.clearcoatRoughnessMap?'#define USE_CLEARCOAT_ROUGHNESSMAP':'',parameters.clearcoatNormalMap?'#define USE_CLEARCOAT_NORMALMAP':'',parameters.specularMap?'#define USE_SPECULARMAP':'',parameters.roughnessMap?'#define USE_ROUGHNESSMAP':'',parameters.metalnessMap?'#define USE_METALNESSMAP':'',parameters.alphaMap?'#define USE_ALPHAMAP':'',parameters.sheen?'#define USE_SHEEN':'',parameters.transmissionMap?'#define USE_TRANSMISSIONMAP':'',parameters.vertexTangents?'#define USE_TANGENT':'',parameters.vertexColors||parameters.instancingColor?'#define USE_COLOR':'',parameters.vertexUvs?'#define USE_UV':'',parameters.uvsVertexOnly?'#define UVS_VERTEX_ONLY':'',parameters.gradientMap?'#define USE_GRADIENTMAP':'',parameters.flatShading?'#define FLAT_SHADED':'',parameters.doubleSided?'#define DOUBLE_SIDED':'',parameters.flipSided?'#define FLIP_SIDED':'',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&¶meters.rendererExtensionFragDepth?'#define USE_LOGDEPTHBUF_EXT':'',(parameters.extensionShaderTextureLOD||parameters.envMap)&¶meters.rendererExtensionShaderTextureLod?'#define TEXTURE_LOD_EXT':'','uniform mat4 viewMatrix;','uniform vec3 cameraPosition;','uniform bool isOrthographic;',parameters.toneMapping!==NoToneMapping?'#define TONE_MAPPING':'',parameters.toneMapping!==NoToneMapping?ShaderChunk['tonemapping_pars_fragment']:'',// this code is required here because it is used by the toneMapping() function defined below parameters.toneMapping!==NoToneMapping?getToneMappingFunction('toneMapping',parameters.toneMapping):'',parameters.dithering?'#define DITHERING':'',ShaderChunk['encodings_pars_fragment'],// this code is required here because it is used by the various encoding/decoding function defined below parameters.map?getTexelDecodingFunction('mapTexelToLinear',parameters.mapEncoding):'',parameters.matcap?getTexelDecodingFunction('matcapTexelToLinear',parameters.matcapEncoding):'',parameters.envMap?getTexelDecodingFunction('envMapTexelToLinear',parameters.envMapEncoding):'',parameters.emissiveMap?getTexelDecodingFunction('emissiveMapTexelToLinear',parameters.emissiveMapEncoding):'',parameters.lightMap?getTexelDecodingFunction('lightMapTexelToLinear',parameters.lightMapEncoding):'',getTexelEncodingFunction('linearToOutputTexel',parameters.outputEncoding),parameters.depthPacking?'#define DEPTH_PACKING '+parameters.depthPacking:'','\n'].filter(filterEmptyLine).join('\n');}vertexShader=resolveIncludes(vertexShader);vertexShader=replaceLightNums(vertexShader,parameters);vertexShader=replaceClippingPlaneNums(vertexShader,parameters);fragmentShader=resolveIncludes(fragmentShader);fragmentShader=replaceLightNums(fragmentShader,parameters);fragmentShader=replaceClippingPlaneNums(fragmentShader,parameters);vertexShader=unrollLoops(vertexShader);fragmentShader=unrollLoops(fragmentShader);if(parameters.isWebGL2&¶meters.isRawShaderMaterial!==true){// GLSL 3.0 conversion for built-in materials and ShaderMaterial versionString='#version 300 es\n';prefixVertex=['#define attribute in','#define varying out','#define texture2D texture'].join('\n')+'\n'+prefixVertex;prefixFragment=['#define varying in',parameters.glslVersion===GLSL3?'':'out highp vec4 pc_fragColor;',parameters.glslVersion===GLSL3?'':'#define gl_FragColor pc_fragColor','#define gl_FragDepthEXT gl_FragDepth','#define texture2D texture','#define textureCube texture','#define texture2DProj textureProj','#define texture2DLodEXT textureLod','#define texture2DProjLodEXT textureProjLod','#define textureCubeLodEXT textureLod','#define texture2DGradEXT textureGrad','#define texture2DProjGradEXT textureProjGrad','#define textureCubeGradEXT textureGrad'].join('\n')+'\n'+prefixFragment;}var vertexGlsl=versionString+prefixVertex+vertexShader;var fragmentGlsl=versionString+prefixFragment+fragmentShader;// console.log( '*VERTEX*', vertexGlsl ); // console.log( '*FRAGMENT*', fragmentGlsl ); var glVertexShader=WebGLShader(gl,35633,vertexGlsl);var glFragmentShader=WebGLShader(gl,35632,fragmentGlsl);gl.attachShader(program,glVertexShader);gl.attachShader(program,glFragmentShader);// Force a particular attribute to index 0. if(parameters.index0AttributeName!==undefined){gl.bindAttribLocation(program,0,parameters.index0AttributeName);}else if(parameters.morphTargets===true){// programs with morphTargets displace position out of attribute 0 gl.bindAttribLocation(program,0,'position');}gl.linkProgram(program);// check for link errors if(renderer.debug.checkShaderErrors){var programLog=gl.getProgramInfoLog(program).trim();var vertexLog=gl.getShaderInfoLog(glVertexShader).trim();var fragmentLog=gl.getShaderInfoLog(glFragmentShader).trim();var runnable=true;var haveDiagnostics=true;if(gl.getProgramParameter(program,35714)===false){runnable=false;var vertexErrors=getShaderErrors(gl,glVertexShader,'vertex');var fragmentErrors=getShaderErrors(gl,glFragmentShader,'fragment');console.error('THREE.WebGLProgram: shader error: ',gl.getError(),'35715',gl.getProgramParameter(program,35715),'gl.getProgramInfoLog',programLog,vertexErrors,fragmentErrors);//add: if(fragmentErrors){console.log(fragmentGlsl.split("\n").map((a,i)=>"".concat(i+1).padEnd(5)+a).join("\n"));}else {console.log(vertexGlsl.split("\n").map((a,i)=>"".concat(i+1).padEnd(5)+a).join("\n"));}}else if(programLog!==''){console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()',programLog);}else if(vertexLog===''||fragmentLog===''){haveDiagnostics=false;}if(haveDiagnostics){this.diagnostics={runnable:runnable,programLog:programLog,vertexShader:{log:vertexLog,prefix:prefixVertex},fragmentShader:{log:fragmentLog,prefix:prefixFragment}};}}// Clean up // Crashes in iOS9 and iOS10. #18402 // gl.detachShader( program, glVertexShader ); // gl.detachShader( program, glFragmentShader ); gl.deleteShader(glVertexShader);gl.deleteShader(glFragmentShader);// set up caching for uniform locations var cachedUniforms;this.getUniforms=function(){if(cachedUniforms===undefined){cachedUniforms=new WebGLUniforms(gl,program);}return cachedUniforms;};// set up caching for attribute locations var cachedAttributes;this.getAttributes=function(){if(cachedAttributes===undefined){cachedAttributes=fetchAttributeLocations(gl,program);}return cachedAttributes;};// free resource this.destroy=function(){bindingStates.releaseStatesOfProgram(this);gl.deleteProgram(program);this.program=undefined;};// this.name=parameters.shaderName;this.id=programIdCount++;this.cacheKey=cacheKey;this.usedTimes=1;this.program=program;this.vertexShader=glVertexShader;this.fragmentShader=glFragmentShader;return this;}function WebGLPrograms(renderer,cubemaps,extensions,capabilities,bindingStates,clipping){var programs=[];var isWebGL2=capabilities.isWebGL2;var logarithmicDepthBuffer=capabilities.logarithmicDepthBuffer;var floatVertexTextures=capabilities.floatVertexTextures;var maxVertexUniforms=capabilities.maxVertexUniforms;var vertexTextures=capabilities.vertexTextures;var precision=capabilities.precision;var shaderIDs={MeshDepthMaterial:'depth',MeshDistanceMaterial:'distanceRGBA',MeshNormalMaterial:'normal',MeshBasicMaterial:'basic',MeshLambertMaterial:'lambert',MeshPhongMaterial:'phong',MeshToonMaterial:'toon',MeshStandardMaterial:'physical',MeshPhysicalMaterial:'physical',MeshMatcapMaterial:'matcap',LineBasicMaterial:'basic',LineDashedMaterial:'dashed',PointsMaterial:'points',ShadowMaterial:'shadow',SpriteMaterial:'sprite'};var parameterNames=['precision','isWebGL2','supportsVertexTextures','outputEncoding','instancing','instancingColor','map','mapEncoding','matcap','matcapEncoding','envMap','envMapMode','envMapEncoding','envMapCubeUV','lightMap','lightMapEncoding','aoMap','emissiveMap','emissiveMapEncoding','bumpMap','normalMap','objectSpaceNormalMap','tangentSpaceNormalMap','clearcoatMap','clearcoatRoughnessMap','clearcoatNormalMap','displacementMap','specularMap','roughnessMap','metalnessMap','gradientMap','alphaMap','combine','vertexColors','vertexTangents','vertexUvs','uvsVertexOnly','fog','useFog','fogExp2','flatShading','sizeAttenuation','logarithmicDepthBuffer','skinning','maxBones','useVertexTexture','morphTargets','morphNormals','maxMorphTargets','maxMorphNormals','premultipliedAlpha','numDirLights','numPointLights','numSpotLights','numHemiLights','numRectAreaLights','numDirLightShadows','numPointLightShadows','numSpotLightShadows','shadowMapEnabled','shadowMapType','toneMapping','physicallyCorrectLights','alphaTest','doubleSided','flipSided','numClippingPlanes','numClipIntersection','depthPacking','dithering','sheen','transmissionMap'];function getMaxBones(object){var skeleton=object.skeleton;var bones=skeleton.bones;if(floatVertexTextures){return 1024;}else {// default for when object is not specified // ( for example when prebuilding shader to be used with multiple objects ) // // - leave some extra space for other uniforms // - limit here is ANGLE's 254 max uniform vectors // (up to 54 should be safe) var nVertexUniforms=maxVertexUniforms;var nVertexMatrices=Math.floor((nVertexUniforms-20)/4);var maxBones=Math.min(nVertexMatrices,bones.length);if(maxBones0,maxBones:maxBones,useVertexTexture: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,numDirLightShadows:lights.directionalShadowMap.length,numPointLightShadows:lights.pointShadowMap.length,numSpotLightShadows:lights.spotShadowMap.length,numClippingPlanes:clipping.numPlanes,numClipIntersection:clipping.numIntersection,dithering:material.dithering,shadowMapEnabled:renderer.shadowMap.enabled&&shadows.length>0,shadowMapType:renderer.shadowMap.type,toneMapping:material.toneMapped?renderer.toneMapping:NoToneMapping,physicallyCorrectLights:renderer.physicallyCorrectLights,premultipliedAlpha:material.premultipliedAlpha,alphaTest:material.alphaTest,doubleSided:material.side===DoubleSide,flipSided:material.side===BackSide,depthPacking:material.depthPacking!==undefined?material.depthPacking:false,index0AttributeName:material.index0AttributeName,extensionDerivatives:material.extensions&&material.extensions.derivatives,extensionFragDepth:material.extensions&&material.extensions.fragDepth,extensionDrawBuffers:material.extensions&&material.extensions.drawBuffers,extensionShaderTextureLOD:material.extensions&&material.extensions.shaderTextureLOD,rendererExtensionFragDepth:isWebGL2||extensions.has('EXT_frag_depth'),rendererExtensionDrawBuffers:isWebGL2||extensions.has('WEBGL_draw_buffers'),rendererExtensionShaderTextureLod:isWebGL2||extensions.has('EXT_shader_texture_lod'),customProgramCacheKey:material.customProgramCacheKey()};return parameters;}function getProgramCacheKey(parameters){var array=[];if(parameters.shaderID){array.push(parameters.shaderID);}else {array.push(parameters.fragmentShader);array.push(parameters.vertexShader);}if(parameters.defines!==undefined){for(var name in parameters.defines){array.push(name);array.push(parameters.defines[name]);}}if(parameters.isRawShaderMaterial===false){for(var _i95=0;_i951)opaque.sort(customOpaqueSort||painterSortStable);if(transparent.length>1)transparent.sort(customTransparentSort||reversePainterSortStable);}function finish(){// Clear references from inactive renderItems in the list for(var _i97=renderItemsIndex,il=renderItems.length;_i970){if(capabilities.isWebGL2){// WebGL 2 state.rectAreaLTC1=UniformsLib.LTC_FLOAT_1;state.rectAreaLTC2=UniformsLib.LTC_FLOAT_2;}else {// WebGL 1 if(extensions.has('OES_texture_float_linear')===true){state.rectAreaLTC1=UniformsLib.LTC_FLOAT_1;state.rectAreaLTC2=UniformsLib.LTC_FLOAT_2;}else if(extensions.has('OES_texture_half_float_linear')===true){state.rectAreaLTC1=UniformsLib.LTC_HALF_1;state.rectAreaLTC2=UniformsLib.LTC_HALF_2;}else {console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');}}}state.ambient[0]=r;state.ambient[1]=g;state.ambient[2]=b;var hash=state.hash;if(hash.directionalLength!==directionalLength||hash.pointLength!==pointLength||hash.spotLength!==spotLength||hash.rectAreaLength!==rectAreaLength||hash.hemiLength!==hemiLength||hash.numDirectionalShadows!==numDirectionalShadows||hash.numPointShadows!==numPointShadows||hash.numSpotShadows!==numSpotShadows){state.directional.length=directionalLength;state.spot.length=spotLength;state.rectArea.length=rectAreaLength;state.point.length=pointLength;state.hemi.length=hemiLength;state.directionalShadow.length=numDirectionalShadows;state.directionalShadowMap.length=numDirectionalShadows;state.pointShadow.length=numPointShadows;state.pointShadowMap.length=numPointShadows;state.spotShadow.length=numSpotShadows;state.spotShadowMap.length=numSpotShadows;state.directionalShadowMatrix.length=numDirectionalShadows;state.pointShadowMatrix.length=numPointShadows;state.spotShadowMatrix.length=numSpotShadows;hash.directionalLength=directionalLength;hash.pointLength=pointLength;hash.spotLength=spotLength;hash.rectAreaLength=rectAreaLength;hash.hemiLength=hemiLength;hash.numDirectionalShadows=numDirectionalShadows;hash.numPointShadows=numPointShadows;hash.numSpotShadows=numSpotShadows;state.version=nextVersion++;}}function setupView(lights,camera){var directionalLength=0;var pointLength=0;var spotLength=0;var rectAreaLength=0;var hemiLength=0;var viewMatrix=camera.matrixWorldInverse;for(var _i101=0,l=lights.length;_i1011&&arguments[1]!==undefined?arguments[1]:0;var renderState;if(renderStates.has(scene)===false){renderState=new WebGLRenderState(extensions,capabilities);renderStates.set(scene,[]);renderStates.get(scene).push(renderState);}else {if(renderCallDepth>=renderStates.get(scene).length){renderState=new WebGLRenderState(extensions,capabilities);renderStates.get(scene).push(renderState);}else {renderState=renderStates.get(scene)[renderCallDepth];}}return renderState;}function dispose(){renderStates=new WeakMap();}return {get:get,dispose:dispose};}/** * parameters = { * * opacity: , * * map: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * wireframe: , * wireframeLinewidth: * } */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.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;};/** * parameters = { * * referencePosition: , * nearDistance: , * farDistance: , * * skinning: , * morphTargets: , * * map: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: * * } */function MeshDistanceMaterial(parameters){Material.call(this);this.type='MeshDistanceMaterial';this.referencePosition=new Vector3();this.nearDistance=1;this.farDistance=1000;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.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;};var vsm_frag="uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\tfor ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean * HALF_SAMPLE_RATE;\n\tsquared_mean = squared_mean * HALF_SAMPLE_RATE;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";var vsm_vert="void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";function WebGLShadowMap(_renderer,_objects,maxTextureSize){var _frustum=new Frustum();var _shadowMapSize=new Vector2(),_viewportSize=new Vector2(),_viewport=new Vector4(),_depthMaterials=[],_distanceMaterials=[],_materialCache={};var shadowSide={0:BackSide,1:FrontSide,2:DoubleSide};var shadowMaterialVertical=new ShaderMaterial({defines:{SAMPLE_RATE:2.0/8.0,HALF_SAMPLE_RATE:1.0/8.0},uniforms:{shadow_pass:{value:null},resolution:{value:new Vector2()},radius:{value:4.0}},vertexShader:vsm_vert,fragmentShader:vsm_frag});var shadowMaterialHorizontal=shadowMaterialVertical.clone();shadowMaterialHorizontal.defines.HORIZONTAL_PASS=1;var fullScreenTri=new BufferGeometry();fullScreenTri.setAttribute('position',new BufferAttribute(new Float32Array([-1,-1,0.5,3,-1,0.5,-1,3,0.5]),3));var fullScreenMesh=new Mesh(fullScreenTri,shadowMaterialVertical);var scope=this;this.enabled=false;this.autoUpdate=true;this.needsUpdate=false;this.type=PCFShadowMap;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 currentRenderTarget=_renderer.getRenderTarget();var activeCubeFace=_renderer.getActiveCubeFace();var activeMipmapLevel=_renderer.getActiveMipmapLevel();var _state=_renderer.state;// Set GL state for depth map. _state.setBlending(NoBlending);_state.buffers.color.setClear(1,1,1,1);_state.buffers.depth.setTest(true);_state.setScissorTest(false);// render depth map for(var _i102=0,il=lights.length;_i102maxTextureSize||_shadowMapSize.y>maxTextureSize){if(_shadowMapSize.x>maxTextureSize){_viewportSize.x=Math.floor(maxTextureSize/shadowFrameExtents.x);_shadowMapSize.x=_viewportSize.x*shadowFrameExtents.x;shadow.mapSize.x=_viewportSize.x;}if(_shadowMapSize.y>maxTextureSize){_viewportSize.y=Math.floor(maxTextureSize/shadowFrameExtents.y);_shadowMapSize.y=_viewportSize.y*shadowFrameExtents.y;shadow.mapSize.y=_viewportSize.y;}}if(shadow.map===null&&!shadow.isPointLightShadow&&this.type===VSMShadowMap){var pars={minFilter:LinearFilter,magFilter:LinearFilter,format:RGBAFormat};shadow.map=new WebGLRenderTarget(_shadowMapSize.x,_shadowMapSize.y,pars);shadow.map.texture.name=light.name+'.shadowMap';shadow.mapPass=new WebGLRenderTarget(_shadowMapSize.x,_shadowMapSize.y,pars);shadow.camera.updateProjectionMatrix();}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';shadow.camera.updateProjectionMatrix();}_renderer.setRenderTarget(shadow.map);_renderer.clear();var viewportCount=shadow.getViewportCount();for(var vp=0;vp0;}var useSkinning=false;if(object.isSkinnedMesh===true){if(material.skinning===true){useSkinning=true;}else {console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:',object);}}var useInstancing=object.isInstancedMesh===true;result=getMaterialVariant(useMorphing,useSkinning,useInstancing);}else {result=customMaterial;}if(_renderer.localClippingEnabled&&material.clipShadows===true&&material.clippingPlanes.length!==0){// in this case we need a unique material instance reflecting the // appropriate state 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;if(type===VSMShadowMap){result.side=material.shadowSide!==null?material.shadowSide:material.side;}else {result.side=material.shadowSide!==null?material.shadowSide:shadowSide[material.side];}result.clipShadows=material.clipShadows;result.clippingPlanes=material.clippingPlanes;result.clipIntersection=material.clipIntersection;result.wireframeLinewidth=material.wireframeLinewidth;result.linewidth=material.linewidth;if(light.isPointLight===true&&result.isMeshDistanceMaterial===true){result.referencePosition.setFromMatrixPosition(light.matrixWorld);result.nearDistance=shadowCameraNear;result.farDistance=shadowCameraFar;}return result;}function renderObject(object,camera,shadowCamera,light,type){if(object.visible===false)return;var visible=object.layers.test(camera.layers);if(visible&&(object.isMesh||object.isLine||object.isPoints)){if((object.castShadow||object.receiveShadow&&type===VSMShadowMap)&&(!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=1.0;}else if(glVersion.indexOf('OpenGL ES')!==-1){version=parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);lineWidthAvailable=version>=2.0;}var currentTextureSlot=null;var currentBoundTextures={};var currentScissor=new Vector4();var currentViewport=new Vector4();function createTexture(type,target,count){var data=new Uint8Array(4);// 4 is required to match default unpack alignment of 4. var texture=gl.createTexture();gl.bindTexture(type,texture);gl.texParameteri(type,10241,9728);gl.texParameteri(type,10240,9728);for(var _i104=0;_i104maxSize||image.height>maxSize){scale=maxSize/Math.max(image.width,image.height);}// only perform resize if necessary if(scale<1||needsPowerOfTwo===true){// only perform resize for certain image types if(typeof HTMLImageElement!=='undefined'&&image instanceof HTMLImageElement||typeof HTMLCanvasElement!=='undefined'&&image instanceof HTMLCanvasElement||typeof ImageBitmap!=='undefined'&&image instanceof ImageBitmap){var floor=needsPowerOfTwo?MathUtils.floorPowerOfTwo:Math.floor;var width=floor(scale*image.width);var height=floor(scale*image.height);if(_canvas===undefined)_canvas=createCanvas(width,height);// cube textures can't reuse the same canvas var canvas=needsNewCanvas?createCanvas(width,height):_canvas;canvas.width=width;canvas.height=height;var context=canvas.getContext('2d');context.drawImage(image,0,0,width,height);console.warn('THREE.WebGLRenderer: Texture has been resized from ('+image.width+'x'+image.height+') to ('+width+'x'+height+').');return canvas;}else {if('data'in image){console.warn('THREE.WebGLRenderer: Image in DataTexture is too big ('+image.width+'x'+image.height+').');}return image;}}return image;}function isPowerOfTwo(image){return MathUtils.isPowerOfTwo(image.width)&&MathUtils.isPowerOfTwo(image.height);}function textureNeedsPowerOfTwo(texture){if(isWebGL2)return false;return texture.wrapS!==ClampToEdgeWrapping||texture.wrapT!==ClampToEdgeWrapping||texture.minFilter!==NearestFilter&&texture.minFilter!==LinearFilter;}function textureNeedsGenerateMipmaps(texture,supportsMips){return texture.generateMipmaps&&supportsMips&&texture.minFilter!==NearestFilter&&texture.minFilter!==LinearFilter;}function generateMipmap(target,texture,width,height){_gl.generateMipmap(target);var textureProperties=properties.get(texture);// Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11 textureProperties.__maxMipLevel=Math.log(Math.max(width,height))*Math.LOG2E;}function getInternalFormat(internalFormatName,glFormat,glType){if(isWebGL2===false)return glFormat;if(internalFormatName!==null){if(_gl[internalFormatName]!==undefined)return _gl[internalFormatName];console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \''+internalFormatName+'\'');}var internalFormat=glFormat;if(glFormat===6403){if(glType===5126)internalFormat=33326;if(glType===5131)internalFormat=33325;if(glType===5121)internalFormat=33321;}if(glFormat===6407){if(glType===5126)internalFormat=34837;if(glType===5131)internalFormat=34843;if(glType===5121)internalFormat=32849;}if(glFormat===6408){if(glType===5126)internalFormat=34836;if(glType===5131)internalFormat=34842;if(glType===5121)internalFormat=32856;}if(internalFormat===33325||internalFormat===33326||internalFormat===34842||internalFormat===34836){extensions.get('EXT_color_buffer_float');}return internalFormat;}// Fallback filters for non-power-of-2 textures function filterFallback(f){if(f===NearestFilter||f===NearestMipmapNearestFilter||f===NearestMipmapLinearFilter){return 9728;}return 9729;}// function onTextureDispose(event){var texture=event.target;texture.removeEventListener('dispose',onTextureDispose);deallocateTexture(texture);if(texture.isVideoTexture){_videoTextures.delete(texture);}info.memory.textures--;}function onRenderTargetDispose(event){var renderTarget=event.target;renderTarget.removeEventListener('dispose',onRenderTargetDispose);deallocateRenderTarget(renderTarget);info.memory.textures--;}// function deallocateTexture(texture){var textureProperties=properties.get(texture);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.isWebGLCubeRenderTarget){for(var _i105=0;_i105<6;_i105++){_gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[_i105]);if(renderTargetProperties.__webglDepthbuffer)_gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[_i105]);}}else {_gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);if(renderTargetProperties.__webglDepthbuffer)_gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);if(renderTargetProperties.__webglMultisampledFramebuffer)_gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);if(renderTargetProperties.__webglColorRenderbuffer)_gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);if(renderTargetProperties.__webglDepthRenderbuffer)_gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);}properties.remove(renderTarget.texture);properties.remove(renderTarget);}// var textureUnits=0;function resetTextureUnits(){textureUnits=0;}function allocateTextureUnit(){var textureUnit=textureUnits;if(textureUnit>=maxTextures){console.warn('THREE.WebGLTextures: Trying to use '+textureUnit+' texture units while this GPU supports only '+maxTextures);}textureUnits+=1;return textureUnit;}// function setTexture2D(texture,slot){var textureProperties=properties.get(texture);if(texture.isVideoTexture)updateVideoTexture(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');}else if(image.complete===false){console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');}else {uploadTexture(textureProperties,texture,slot);return;}}state.activeTexture(33984+slot);state.bindTexture(3553,textureProperties.__webglTexture);}function setTexture2DArray(texture,slot){var textureProperties=properties.get(texture);if(texture.version>0&&textureProperties.__version!==texture.version){uploadTexture(textureProperties,texture,slot);return;}state.activeTexture(33984+slot);state.bindTexture(35866,textureProperties.__webglTexture);}function setTexture3D(texture,slot){var textureProperties=properties.get(texture);if(texture.version>0&&textureProperties.__version!==texture.version){uploadTexture(textureProperties,texture,slot);return;}state.activeTexture(33984+slot);state.bindTexture(32879,textureProperties.__webglTexture);}function setTextureCube(texture,slot){var textureProperties=properties.get(texture);if(texture.version>0&&textureProperties.__version!==texture.version){uploadCubeTexture(textureProperties,texture,slot);return;}state.activeTexture(33984+slot);state.bindTexture(34067,textureProperties.__webglTexture);}var wrappingToGL={[RepeatWrapping]:10497,[ClampToEdgeWrapping]:33071,[MirroredRepeatWrapping]:33648};var filterToGL={[NearestFilter]:9728,[NearestMipmapNearestFilter]:9984,[NearestMipmapLinearFilter]:9986,[LinearFilter]:9729,[LinearMipmapNearestFilter]:9985,[LinearMipmapLinearFilter]:9987};function setTextureParameters(textureType,texture,supportsMips){if(supportsMips){_gl.texParameteri(textureType,10242,wrappingToGL[texture.wrapS]);_gl.texParameteri(textureType,10243,wrappingToGL[texture.wrapT]);if(textureType===32879||textureType===35866){_gl.texParameteri(textureType,32882,wrappingToGL[texture.wrapR]);}_gl.texParameteri(textureType,10240,filterToGL[texture.magFilter]);_gl.texParameteri(textureType,10241,filterToGL[texture.minFilter]);}else {_gl.texParameteri(textureType,10242,33071);_gl.texParameteri(textureType,10243,33071);if(textureType===32879||textureType===35866){_gl.texParameteri(textureType,32882,33071);}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.');}_gl.texParameteri(textureType,10240,filterFallback(texture.magFilter));_gl.texParameteri(textureType,10241,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.');}}var 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&&(isWebGL2||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 initTexture(textureProperties,texture){if(textureProperties.__webglInit===undefined){textureProperties.__webglInit=true;texture.addEventListener('dispose',onTextureDispose);textureProperties.__webglTexture=_gl.createTexture();info.memory.textures++;}}function uploadTexture(textureProperties,texture,slot){var textureType=3553;if(texture.isDataTexture2DArray)textureType=35866;if(texture.isDataTexture3D)textureType=32879;initTexture(textureProperties,texture);state.activeTexture(33984+slot);state.bindTexture(textureType,textureProperties.__webglTexture);_gl.pixelStorei(37440,texture.flipY);_gl.pixelStorei(37441,texture.premultiplyAlpha);_gl.pixelStorei(3317,texture.unpackAlignment);var needsPowerOfTwo=textureNeedsPowerOfTwo(texture)&&isPowerOfTwo(texture.image)===false;var image=resizeImage(texture.image,needsPowerOfTwo,false,maxTextureSize);var supportsMips=isPowerOfTwo(image)||isWebGL2,glFormat=utils.convert(texture.format);var glType=utils.convert(texture.type),glInternalFormat=getInternalFormat(texture.internalFormat,glFormat,glType);setTextureParameters(textureType,texture,supportsMips);var mipmap;var mipmaps=texture.mipmaps;if(texture.isDepthTexture){// populate depth texture with dummy data glInternalFormat=6402;if(isWebGL2){if(texture.type===FloatType){glInternalFormat=36012;}else if(texture.type===UnsignedIntType){glInternalFormat=33190;}else if(texture.type===UnsignedInt248Type$1){glInternalFormat=35056;}else {glInternalFormat=33189;// WebGL2 requires sized internalformat for glTexImage2D }}else {if(texture.type===FloatType){console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');}}// validation checks for WebGL 1 if(texture.format===DepthFormat&&glInternalFormat===6402){// The error INVALID_OPERATION is generated by texImage2D if format and internalformat are // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) 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&&glInternalFormat===6402){// Depth stencil textures need the DEPTH_STENCIL internal format // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) glInternalFormat=34041;// The error INVALID_OPERATION is generated by texImage2D if format and internalformat are // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) if(texture.type!==UnsignedInt248Type$1){console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');texture.type=UnsignedInt248Type$1;glType=utils.convert(texture.type);}}// state.texImage2D(3553,0,glInternalFormat,image.width,image.height,0,glFormat,glType,null);}else if(texture.isDataTexture){// use manually created mipmaps if available // if there are no manual mipmaps // set 0 level mipmap and then use GL to generate other mipmap levels if(mipmaps.length>0&&supportsMips){for(var _i106=0,il=mipmaps.length;_i1060&&supportsMips){for(var _i108=0,_il10=mipmaps.length;_i108<_il10;_i108++){mipmap=mipmaps[_i108];state.texImage2D(3553,_i108,glInternalFormat,glFormat,glType,mipmap);}texture.generateMipmaps=false;textureProperties.__maxMipLevel=mipmaps.length-1;}else {state.texImage2D(3553,0,glInternalFormat,glFormat,glType,image);textureProperties.__maxMipLevel=0;}}if(textureNeedsGenerateMipmaps(texture,supportsMips)){generateMipmap(textureType,texture,image.width,image.height);}textureProperties.__version=texture.version;if(texture.onUpdate)texture.onUpdate(texture);}function uploadCubeTexture(textureProperties,texture,slot){if(texture.image.length!==6)return;initTexture(textureProperties,texture);state.activeTexture(33984+slot);state.bindTexture(34067,textureProperties.__webglTexture);_gl.pixelStorei(37440,texture.flipY);var isCompressed=texture&&(texture.isCompressedTexture||texture.image[0].isCompressedTexture);var isDataTexture=texture.image[0]&&texture.image[0].isDataTexture;var cubeImage=[];for(var _i109=0;_i109<6;_i109++){if(!isCompressed&&!isDataTexture){cubeImage[_i109]=resizeImage(texture.image[_i109],false,true,maxCubemapSize);}else {cubeImage[_i109]=isDataTexture?texture.image[_i109].image:texture.image[_i109];}}var image=cubeImage[0],supportsMips=isPowerOfTwo(image)||isWebGL2,glFormat=utils.convert(texture.format),glType=utils.convert(texture.type),glInternalFormat=getInternalFormat(texture.internalFormat,glFormat,glType);setTextureParameters(34067,texture,supportsMips);var mipmaps;if(isCompressed){for(var _i110=0;_i110<6;_i110++){mipmaps=cubeImage[_i110].mipmaps;for(var j=0;j0&&arguments[0]!==undefined?arguments[0]:[];PerspectiveCamera.call(this);this.cameras=array;}ArrayCamera.prototype=Object.assign(Object.create(PerspectiveCamera.prototype),{constructor:ArrayCamera,isArrayCamera:true});function Group(){Object3D.call(this);this.type='Group';}Group.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Group,isGroup:true});function WebXRController(){this._targetRay=null;this._grip=null;this._hand=null;}Object.assign(WebXRController.prototype,{constructor:WebXRController,getHandSpace:function getHandSpace(){if(this._hand===null){this._hand=new Group();this._hand.matrixAutoUpdate=false;this._hand.visible=false;this._hand.joints=[];this._hand.inputState={pinching:false};if(window.XRHand){for(var _i115=0;_i115<=window.XRHand.LITTLE_PHALANX_TIP;_i115++){// The transform of this joint will be updated with the joint pose on each frame var joint=new Group();joint.matrixAutoUpdate=false;joint.visible=false;this._hand.joints.push(joint);// ?? this._hand.add(joint);}}}return this._hand;},getTargetRaySpace:function getTargetRaySpace(){if(this._targetRay===null){this._targetRay=new Group();this._targetRay.matrixAutoUpdate=false;this._targetRay.visible=false;}return this._targetRay;},getGripSpace:function getGripSpace(){if(this._grip===null){this._grip=new Group();this._grip.matrixAutoUpdate=false;this._grip.visible=false;}return this._grip;},dispatchEvent:function dispatchEvent(event){if(this._targetRay!==null){this._targetRay.dispatchEvent(event);}if(this._grip!==null){this._grip.dispatchEvent(event);}if(this._hand!==null){this._hand.dispatchEvent(event);}return this;},disconnect:function disconnect(inputSource){this.dispatchEvent({type:'disconnected',data:inputSource});if(this._targetRay!==null){this._targetRay.visible=false;}if(this._grip!==null){this._grip.visible=false;}if(this._hand!==null){this._hand.visible=false;}return this;},update:function update(inputSource,frame,referenceSpace){var inputPose=null;var gripPose=null;var handPose=null;var targetRay=this._targetRay;var grip=this._grip;var hand=this._hand;if(inputSource&&frame.session.visibilityState!=='visible-blurred'){if(hand&&inputSource.hand){handPose=true;for(var _i116=0;_i116<=window.XRHand.LITTLE_PHALANX_TIP;_i116++){if(inputSource.hand[_i116]){// Update the joints groups with the XRJoint poses var jointPose=frame.getJointPose(inputSource.hand[_i116],referenceSpace);var joint=hand.joints[_i116];if(jointPose!==null){joint.matrix.fromArray(jointPose.transform.matrix);joint.matrix.decompose(joint.position,joint.rotation,joint.scale);joint.jointRadius=jointPose.radius;}joint.visible=jointPose!==null;// Custom events // Check pinch var indexTip=hand.joints[window.XRHand.INDEX_PHALANX_TIP];var thumbTip=hand.joints[window.XRHand.THUMB_PHALANX_TIP];var distance=indexTip.position.distanceTo(thumbTip.position);var distanceToPinch=0.02;var threshold=0.005;if(hand.inputState.pinching&&distance>distanceToPinch+threshold){hand.inputState.pinching=false;this.dispatchEvent({type:'pinchend',handedness:inputSource.handedness,target:this});}else if(!hand.inputState.pinching&&distance<=distanceToPinch-threshold){hand.inputState.pinching=true;this.dispatchEvent({type:'pinchstart',handedness:inputSource.handedness,target:this});}}}}else {if(targetRay!==null){inputPose=frame.getPose(inputSource.targetRaySpace,referenceSpace);if(inputPose!==null){targetRay.matrix.fromArray(inputPose.transform.matrix);targetRay.matrix.decompose(targetRay.position,targetRay.rotation,targetRay.scale);}}if(grip!==null&&inputSource.gripSpace){gripPose=frame.getPose(inputSource.gripSpace,referenceSpace);if(gripPose!==null){grip.matrix.fromArray(gripPose.transform.matrix);grip.matrix.decompose(grip.position,grip.rotation,grip.scale);}}}}if(targetRay!==null){targetRay.visible=inputPose!==null;}if(grip!==null){grip.visible=gripPose!==null;}if(hand!==null){hand.visible=handPose!==null;}return this;}});function WebXRManager(renderer,gl){var scope=this;var session=null;var framebufferScaleFactor=1.0;var referenceSpace=null;var referenceSpaceType='local-floor';var pose=null;var controllers=[];var inputSourcesMap=new Map();// var cameraL=new PerspectiveCamera();cameraL.layers.enable(1);cameraL.viewport=new Vector4();var cameraR=new PerspectiveCamera();cameraR.layers.enable(2);cameraR.viewport=new Vector4();var cameras=[cameraL,cameraR];var cameraVR=new ArrayCamera();cameraVR.layers.enable(1);cameraVR.layers.enable(2);var _currentDepthNear=null;var _currentDepthFar=null;// this.enabled=false;this.isPresenting=false;this.getController=function(index){var controller=controllers[index];if(controller===undefined){controller=new WebXRController();controllers[index]=controller;}return controller.getTargetRaySpace();};this.getControllerGrip=function(index){var controller=controllers[index];if(controller===undefined){controller=new WebXRController();controllers[index]=controller;}return controller.getGripSpace();};this.getHand=function(index){var controller=controllers[index];if(controller===undefined){controller=new WebXRController();controllers[index]=controller;}return controller.getHandSpace();};// function onSessionEvent(event){var controller=inputSourcesMap.get(event.inputSource);if(controller){controller.dispatchEvent({type:event.type,data:event.inputSource});}}function onSessionEnd(){inputSourcesMap.forEach(function(controller,inputSource){controller.disconnect(inputSource);});inputSourcesMap.clear();// renderer.setFramebuffer(null);renderer.setRenderTarget(renderer.getRenderTarget());// Hack #15830 animation.stop();scope.isPresenting=false;scope.dispatchEvent({type:'sessionend'});}function onRequestReferenceSpace(value){referenceSpace=value;animation.setContext(session);animation.start();scope.isPresenting=true;scope.dispatchEvent({type:'sessionstart'});}this.setFramebufferScaleFactor=function(value){framebufferScaleFactor=value;if(scope.isPresenting===true){console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');}};this.setReferenceSpaceType=function(value){referenceSpaceType=value;if(scope.isPresenting===true){console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');}};this.getReferenceSpace=function(){return referenceSpace;};this.getSession=function(){return session;};this.setSession=function(value){session=value;if(session!==null){session.addEventListener('select',onSessionEvent);session.addEventListener('selectstart',onSessionEvent);session.addEventListener('selectend',onSessionEvent);session.addEventListener('squeeze',onSessionEvent);session.addEventListener('squeezestart',onSessionEvent);session.addEventListener('squeezeend',onSessionEvent);session.addEventListener('end',onSessionEnd);var attributes=gl.getContextAttributes();if(attributes.xrCompatible!==true){gl.makeXRCompatible();}var layerInit={antialias:attributes.antialias,alpha:attributes.alpha,depth:attributes.depth,stencil:attributes.stencil,framebufferScaleFactor:framebufferScaleFactor};// eslint-disable-next-line no-undef var baseLayer=new XRWebGLLayer(session,gl,layerInit);session.updateRenderState({baseLayer:baseLayer});session.requestReferenceSpace(referenceSpaceType).then(onRequestReferenceSpace);// session.addEventListener('inputsourceschange',updateInputSources);}};function updateInputSources(event){var inputSources=session.inputSources;// Assign inputSources to available controllers for(var _i117=0;_i1170)renderObjects(opaqueObjects,scene,camera);if(transparentObjects.length>0)renderObjects(transparentObjects,scene,camera);// if(scene.isScene===true)scene.onAfterRender(_this,scene,camera);// if(_currentRenderTarget!==null){// Generate mipmap if we're using any kind of mipmap filtering textures.updateRenderTargetMipmap(_currentRenderTarget);// resolve multisample renderbuffers to a single-sample texture if necessary textures.updateMultisampleRenderTarget(_currentRenderTarget);}// Ensure depth buffer writing is enabled so it can be cleared on next render state.buffers.depth.setTest(true);state.buffers.depth.setMask(true);state.buffers.color.setMask(true);state.setPolygonOffset(false);// _gl.finish(); renderStateStack.pop();if(renderStateStack.length>0){currentRenderState=renderStateStack[renderStateStack.length-1];}else {currentRenderState=null;}currentRenderList=null;};function projectObject(object,camera,groupOrder,sortObjects){if(object.visible===false)return;var visible=object.layers.test(camera.layers);if(visible){if(object.isGroup){groupOrder=object.renderOrder;}else if(object.isLOD){if(object.autoUpdate===true)object.update(camera);}else if(object.isLight){currentRenderState.pushLight(object);if(object.castShadow){currentRenderState.pushShadow(object);}}else if(object.isSprite){if(!object.frustumCulled||_frustum.intersectsSprite(object)){if(sortObjects){_vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);}var geometry=objects.update(object);var material=object.material;if(material.visible){currentRenderList.push(object,geometry,material,groupOrder,_vector3.z,null);}}}else if(object.isImmediateRenderObject){if(sortObjects){_vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);}currentRenderList.push(object,null,object.material,groupOrder,_vector3.z,null);}else if(object.isMesh||object.isLine||object.isPoints){if(object.isSkinnedMesh){// update skeleton only once in a frame if(object.skeleton.frame!==info.render.frame){object.skeleton.update();object.skeleton.frame=info.render.frame;}}if(!object.frustumCulled||_frustum.intersectsObject(object)){if(sortObjects){_vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);}var _geometry2=objects.update(object);var _material=object.material;if(Array.isArray(_material)){var groups=_geometry2.groups;for(var _i126=0,l=groups.length;_i126 column1, column2, column3, column4) // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8) // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16) // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32) // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64) var size=Math.sqrt(bones.length*4);// 4 pixels needed for 1 matrix size=MathUtils.ceilPowerOfTwo(size);size=Math.max(size,4);var boneMatrices=new Float32Array(size*size*4);// 4 floats per RGBA pixel boneMatrices.set(skeleton.boneMatrices);// copy current values 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,textures);p_uniforms.setValue(_gl,'boneTextureSize',skeleton.boneTextureSize);}else {p_uniforms.setOptional(_gl,skeleton,'boneMatrices');}}}if(refreshMaterial||materialProperties.receiveShadow!==object.receiveShadow){materialProperties.receiveShadow=object.receiveShadow;p_uniforms.setValue(_gl,'receiveShadow',object.receiveShadow);}if(refreshMaterial){p_uniforms.setValue(_gl,'toneMappingExposure',_this.toneMappingExposure);if(materialProperties.needsLights){// the current material requires lighting info // note: all lighting uniforms are always set correctly // they simply reference the renderer's state for their // values // // use the current material's .needsUpdate flags to set // the GL state when required markUniformsLightsNeedsUpdate(m_uniforms,refreshLights);}// refresh uniforms common to several materials if(fog&&material.fog){materials.refreshFogUniforms(m_uniforms,fog);}materials.refreshMaterialUniforms(m_uniforms,material,_pixelRatio,_height);WebGLUniforms.upload(_gl,materialProperties.uniformsList,m_uniforms,textures);}if(material.isShaderMaterial&&material.uniformsNeedUpdate===true){WebGLUniforms.upload(_gl,materialProperties.uniformsList,m_uniforms,textures);material.uniformsNeedUpdate=false;}if(material.isSpriteMaterial){p_uniforms.setValue(_gl,'center',object.center);}// common matrices p_uniforms.setValue(_gl,'modelViewMatrix',object.modelViewMatrix);p_uniforms.setValue(_gl,'normalMatrix',object.normalMatrix);p_uniforms.setValue(_gl,'modelMatrix',object.matrixWorld);return program;}// If uniforms are marked as clean, they don't need to be loaded to the GPU. function markUniformsLightsNeedsUpdate(uniforms,value){uniforms.ambientLightColor.needsUpdate=value;uniforms.lightProbe.needsUpdate=value;uniforms.directionalLights.needsUpdate=value;uniforms.directionalLightShadows.needsUpdate=value;uniforms.pointLights.needsUpdate=value;uniforms.pointLightShadows.needsUpdate=value;uniforms.spotLights.needsUpdate=value;uniforms.spotLightShadows.needsUpdate=value;uniforms.rectAreaLights.needsUpdate=value;uniforms.hemisphereLights.needsUpdate=value;}function materialNeedsLights(material){return material.isMeshLambertMaterial||material.isMeshToonMaterial||material.isMeshPhongMaterial||material.isMeshStandardMaterial||material.isShadowMaterial||material.isShaderMaterial&&material.lights===true;}// this.setFramebuffer=function(value){if(_framebuffer!==value&&_currentRenderTarget===null)_gl.bindFramebuffer(36160,value);_framebuffer=value;};this.getActiveCubeFace=function(){return _currentActiveCubeFace;};this.getActiveMipmapLevel=function(){return _currentActiveMipmapLevel;};this.getRenderList=function(){return currentRenderList;};this.setRenderList=function(renderList){currentRenderList=renderList;};this.getRenderTarget=function(){return _currentRenderTarget;};this.setRenderTarget=function(renderTarget){var activeCubeFace=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var activeMipmapLevel=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;_currentRenderTarget=renderTarget;_currentActiveCubeFace=activeCubeFace;_currentActiveMipmapLevel=activeMipmapLevel;if(renderTarget&&properties.get(renderTarget).__webglFramebuffer===undefined){textures.setupRenderTarget(renderTarget);}var framebuffer=_framebuffer;var isCube=false;if(renderTarget){var __webglFramebuffer=properties.get(renderTarget).__webglFramebuffer;if(renderTarget.isWebGLCubeRenderTarget){framebuffer=__webglFramebuffer[activeCubeFace];isCube=true;}else if(renderTarget.isWebGLMultisampleRenderTarget){framebuffer=properties.get(renderTarget).__webglMultisampledFramebuffer;}else {framebuffer=__webglFramebuffer;}_currentViewport.copy(renderTarget.viewport);_currentScissor.copy(renderTarget.scissor);_currentScissorTest=renderTarget.scissorTest;}else {_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();_currentScissorTest=_scissorTest;}if(_currentFramebuffer!==framebuffer){_gl.bindFramebuffer(36160,framebuffer);_currentFramebuffer=framebuffer;}state.viewport(_currentViewport);state.scissor(_currentScissor);state.setScissorTest(_currentScissorTest);if(isCube){var textureProperties=properties.get(renderTarget.texture);_gl.framebufferTexture2D(36160,36064,34069+activeCubeFace,textureProperties.__webglTexture,activeMipmapLevel);}};this.readRenderTargetPixels=function(renderTarget,x,y,width,height,buffer,activeCubeFaceIndex){if(!(renderTarget&&renderTarget.isWebGLRenderTarget)){console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');return;}var framebuffer=properties.get(renderTarget).__webglFramebuffer;if(renderTarget.isWebGLCubeRenderTarget&&activeCubeFaceIndex!==undefined){framebuffer=framebuffer[activeCubeFaceIndex];}if(framebuffer){var restore=false;if(framebuffer!==_currentFramebuffer){_gl.bindFramebuffer(36160,framebuffer);restore=true;}try{var texture=renderTarget.texture;var textureFormat=texture.format;var textureType=texture.type;if(textureFormat!==RGBAFormat&&utils.convert(textureFormat)!==_gl.getParameter(35739)){console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');return;}if(textureType!==UnsignedByteType&&utils.convert(textureType)!==_gl.getParameter(35738)&&// IE11, Edge and Chrome Mac < 52 (#9513) !(textureType===FloatType&&(capabilities.isWebGL2||extensions.get('OES_texture_float')||extensions.get('WEBGL_color_buffer_float')))&&// Chrome Mac >= 52 and Firefox !(textureType===HalfFloatType&&(capabilities.isWebGL2?extensions.get('EXT_color_buffer_float'):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(36160)===36053){// the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) 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(36160,_currentFramebuffer);}}}};this.copyFramebufferToTexture=function(position,texture){var level=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var levelScale=Math.pow(2,-level);var width=Math.floor(texture.image.width*levelScale);var height=Math.floor(texture.image.height*levelScale);var glFormat=utils.convert(texture.format);textures.setTexture2D(texture,0);_gl.copyTexImage2D(3553,level,glFormat,position.x,position.y,width,height,0);state.unbindTexture();};this.copyTextureToTexture=function(position,srcTexture,dstTexture){var level=arguments.length>3&&arguments[3]!==undefined?arguments[3]:0;var width=srcTexture.image.width;var height=srcTexture.image.height;var glFormat=utils.convert(dstTexture.format);var glType=utils.convert(dstTexture.type);textures.setTexture2D(dstTexture,0);// As another texture upload may have changed pixelStorei // parameters, make sure they are correct for the dstTexture _gl.pixelStorei(37440,dstTexture.flipY);_gl.pixelStorei(37441,dstTexture.premultiplyAlpha);_gl.pixelStorei(3317,dstTexture.unpackAlignment);if(srcTexture.isDataTexture){_gl.texSubImage2D(3553,level,position.x,position.y,width,height,glFormat,glType,srcTexture.image.data);}else {if(srcTexture.isCompressedTexture){_gl.compressedTexSubImage2D(3553,level,position.x,position.y,srcTexture.mipmaps[0].width,srcTexture.mipmaps[0].height,glFormat,srcTexture.mipmaps[0].data);}else {_gl.texSubImage2D(3553,level,position.x,position.y,glFormat,glType,srcTexture.image);}}// Generate mipmaps only when copying level 0 if(level===0&&dstTexture.generateMipmaps)_gl.generateMipmap(3553);state.unbindTexture();};this.initTexture=function(texture){textures.setTexture2D(texture,0);state.unbindTexture();};this.resetState=function(){state.reset();bindingStates.reset();};if(typeof __THREE_DEVTOOLS__!=='undefined'){__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe',{detail:this}));// eslint-disable-line no-undef }}function WebGL1Renderer(parameters){WebGLRenderer.call(this,parameters);}WebGL1Renderer.prototype=Object.assign(Object.create(WebGLRenderer.prototype),{constructor:WebGL1Renderer,isWebGL1Renderer:true});class FogExp2{constructor(color,density){Object.defineProperty(this,'isFogExp2',{value:true});this.name='';this.color=new Color(color);this.density=density!==undefined?density:0.00025;}clone(){return new FogExp2(this.color,this.density);}toJSON(/* meta */){return {type:'FogExp2',color:this.color.getHex(),density:this.density};}}class Fog{constructor(color,near,far){Object.defineProperty(this,'isFog',{value:true});this.name='';this.color=new Color(color);this.near=near!==undefined?near:1;this.far=far!==undefined?far:1000;}clone(){return new Fog(this.color,this.near,this.far);}toJSON(/* meta */){return {type:'Fog',color:this.color.getHex(),near:this.near,far:this.far};}}class Scene extends Object3D{constructor(){super();Object.defineProperty(this,'isScene',{value:true});this.type='Scene';this.background=null;this.environment=null;this.fog=null;this.overrideMaterial=null;this.autoUpdate=true;// checked by the renderer if(typeof __THREE_DEVTOOLS__!=='undefined'){__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe',{detail:this}));// eslint-disable-line no-undef }}copy(source,recursive){super.copy(source,recursive);if(source.background!==null)this.background=source.background.clone();if(source.environment!==null)this.environment=source.environment.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(meta){var data=super.toJSON(meta);if(this.background!==null)data.object.background=this.background.toJSON(meta);if(this.environment!==null)data.object.environment=this.environment.toJSON(meta);if(this.fog!==null)data.object.fog=this.fog.toJSON();return data;}}function InterleavedBuffer(array,stride){this.array=array;this.stride=stride;this.count=array!==undefined?array.length/stride:0;this.usage=StaticDrawUsage;this.updateRange={offset:0,count:-1};this.version=0;this.uuid=MathUtils.generateUUID();}Object.defineProperty(InterleavedBuffer.prototype,'needsUpdate',{set:function set(value){if(value===true)this.version++;}});Object.assign(InterleavedBuffer.prototype,{isInterleavedBuffer:true,onUploadCallback:function onUploadCallback(){},setUsage:function setUsage(value){this.usage=value;return this;},copy:function copy(source){this.array=new source.array.constructor(source.array);this.count=source.count;this.stride=source.stride;this.usage=source.usage;return this;},copyAt:function copyAt(index1,attribute,index2){index1*=this.stride;index2*=attribute.stride;for(var _i129=0,l=this.stride;_i1291&&arguments[1]!==undefined?arguments[1]:0;this.array.set(value,offset);return this;},clone:function clone(data){if(data.arrayBuffers===undefined){data.arrayBuffers={};}if(this.array.buffer._uuid===undefined){this.array.buffer._uuid=MathUtils.generateUUID();}if(data.arrayBuffers[this.array.buffer._uuid]===undefined){data.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer;}var array=new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);var ib=new InterleavedBuffer(array,this.stride);ib.setUsage(this.usage);return ib;},onUpload:function onUpload(callback){this.onUploadCallback=callback;return this;},toJSON:function toJSON(data){if(data.arrayBuffers===undefined){data.arrayBuffers={};}// generate UUID for array buffer if necessary if(this.array.buffer._uuid===undefined){this.array.buffer._uuid=MathUtils.generateUUID();}if(data.arrayBuffers[this.array.buffer._uuid]===undefined){data.arrayBuffers[this.array.buffer._uuid]=Array.prototype.slice.call(new Uint32Array(this.array.buffer));}// return {uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride};}});var _vector$6=new Vector3();function InterleavedBufferAttribute(interleavedBuffer,itemSize,offset,normalized){this.name='';this.data=interleavedBuffer;this.itemSize=itemSize;this.offset=offset;this.normalized=normalized===true;}Object.defineProperties(InterleavedBufferAttribute.prototype,{count:{get:function get(){return this.data.count;}},array:{get:function get(){return this.data.array;}},needsUpdate:{set:function set(value){this.data.needsUpdate=value;}}});Object.assign(InterleavedBufferAttribute.prototype,{isInterleavedBufferAttribute:true,applyMatrix4:function applyMatrix4(m){for(var _i130=0,l=this.data.count;_i130, * map: new THREE.Texture( ), * alphaMap: new THREE.Texture( ), * rotation: , * sizeAttenuation: * } */function SpriteMaterial(parameters){Material.call(this);this.type='SpriteMaterial';this.color=new Color(0xffffff);this.map=null;this.alphaMap=null;this.rotation=0;this.sizeAttenuation=true;this.transparent=true;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.alphaMap=source.alphaMap;this.rotation=source.rotation;this.sizeAttenuation=source.sizeAttenuation;return this;};var _geometry;var _intersectPoint=new Vector3();var _worldScale=new Vector3();var _mvPosition=new Vector3();var _alignedPosition=new Vector2();var _rotatedPosition=new Vector2();var _viewWorldMatrix=new Matrix4();var _vA$1=new Vector3();var _vB$1=new Vector3();var _vC$1=new Vector3();var _uvA$1=new Vector2();var _uvB$1=new Vector2();var _uvC$1=new Vector2();function Sprite$1(material){Object3D.call(this);this.type='Sprite';if(_geometry===undefined){_geometry=new BufferGeometry();var float32Array=new Float32Array([-0.5,-0.5,0,0,0,0.5,-0.5,0,1,0,0.5,0.5,0,1,1,-0.5,0.5,0,0,1]);var interleavedBuffer=new InterleavedBuffer(float32Array,5);_geometry.setIndex([0,1,2,0,2,3]);_geometry.setAttribute('position',new InterleavedBufferAttribute(interleavedBuffer,3,0,false));_geometry.setAttribute('uv',new InterleavedBufferAttribute(interleavedBuffer,2,3,false));}this.geometry=_geometry;this.material=material!==undefined?material:new SpriteMaterial();this.center=new Vector2(0.5,0.5);}Sprite$1.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Sprite$1,isSprite:true,raycast:function raycast(raycaster,intersects){if(raycaster.camera===null){console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');}_worldScale.setFromMatrixScale(this.matrixWorld);_viewWorldMatrix.copy(raycaster.camera.matrixWorld);this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse,this.matrixWorld);_mvPosition.setFromMatrixPosition(this.modelViewMatrix);if(raycaster.camera.isPerspectiveCamera&&this.material.sizeAttenuation===false){_worldScale.multiplyScalar(-_mvPosition.z);}var rotation=this.material.rotation;var sin,cos;if(rotation!==0){cos=Math.cos(rotation);sin=Math.sin(rotation);}var center=this.center;transformVertex(_vA$1.set(-0.5,-0.5,0),_mvPosition,center,_worldScale,sin,cos);transformVertex(_vB$1.set(0.5,-0.5,0),_mvPosition,center,_worldScale,sin,cos);transformVertex(_vC$1.set(0.5,0.5,0),_mvPosition,center,_worldScale,sin,cos);_uvA$1.set(0,0);_uvB$1.set(1,0);_uvC$1.set(1,1);// check first triangle var intersect=raycaster.ray.intersectTriangle(_vA$1,_vB$1,_vC$1,false,_intersectPoint);if(intersect===null){// check second triangle transformVertex(_vB$1.set(-0.5,0.5,0),_mvPosition,center,_worldScale,sin,cos);_uvB$1.set(0,1);intersect=raycaster.ray.intersectTriangle(_vA$1,_vC$1,_vB$1,false,_intersectPoint);if(intersect===null){return;}}var distance=raycaster.ray.origin.distanceTo(_intersectPoint);if(distanceraycaster.far)return;intersects.push({distance:distance,point:_intersectPoint.clone(),uv:Triangle.getUV(_intersectPoint,_vA$1,_vB$1,_vC$1,_uvA$1,_uvB$1,_uvC$1,new Vector2()),face:null,object:this});},copy:function copy(source){Object3D.prototype.copy.call(this,source);if(source.center!==undefined)this.center.copy(source.center);this.material=source.material;return this;}});function transformVertex(vertexPosition,mvPosition,center,scale,sin,cos){// compute position in camera space _alignedPosition.subVectors(vertexPosition,center).addScalar(0.5).multiply(scale);// to check if rotation is not zero if(sin!==undefined){_rotatedPosition.x=cos*_alignedPosition.x-sin*_alignedPosition.y;_rotatedPosition.y=sin*_alignedPosition.x+cos*_alignedPosition.y;}else {_rotatedPosition.copy(_alignedPosition);}vertexPosition.copy(mvPosition);vertexPosition.x+=_rotatedPosition.x;vertexPosition.y+=_rotatedPosition.y;// transform to world space vertexPosition.applyMatrix4(_viewWorldMatrix);}var _v1$4=new Vector3();var _v2$2=new Vector3();function LOD(){Object3D.call(this);this._currentLevel=0;this.type='LOD';Object.defineProperties(this,{levels:{enumerable:true,value:[]}});this.autoUpdate=true;}LOD.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:LOD,isLOD:true,copy:function copy(source){Object3D.prototype.copy.call(this,source,false);var levels=source.levels;for(var _i133=0,l=levels.length;_i1331&&arguments[1]!==undefined?arguments[1]:0;distance=Math.abs(distance);var levels=this.levels;var l;for(l=0;l0){var _i134,l;for(_i134=1,l=levels.length;_i1340){_v1$4.setFromMatrixPosition(this.matrixWorld);var distance=raycaster.ray.origin.distanceTo(_v1$4);this.getObjectForDistance(distance).raycast(raycaster,intersects);}},update:function update(camera){var levels=this.levels;if(levels.length>1){_v1$4.setFromMatrixPosition(camera.matrixWorld);_v2$2.setFromMatrixPosition(this.matrixWorld);var distance=_v1$4.distanceTo(_v2$2)/camera.zoom;levels[0].object.visible=true;var _i135,l;for(_i135=1,l=levels.length;_i135=levels[_i135].distance){levels[_i135-1].object.visible=false;levels[_i135].object.visible=true;}else {break;}}this._currentLevel=_i135-1;for(;_i1350&&arguments[0]!==undefined?arguments[0]:[];var boneInverses=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];this.uuid=MathUtils.generateUUID();this.bones=bones.slice(0);this.boneInverses=boneInverses;this.boneMatrices=null;this.boneTexture=null;this.boneTextureSize=0;this.frame=-1;this.init();}Object.assign(Skeleton.prototype,{init:function init(){var bones=this.bones;var boneInverses=this.boneInverses;this.boneMatrices=new Float32Array(bones.length*16);// calculate inverse bone matrices if necessary if(boneInverses.length===0){this.calculateInverses();}else {// handle special case if(bones.length!==boneInverses.length){console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');this.boneInverses=[];for(var _i139=0,il=this.bones.length;_i139, * opacity: , * * linewidth: , * linecap: "round", * linejoin: "round" * } */function LineBasicMaterial(parameters){Material.call(this);this.type='LineBasicMaterial';this.color=new Color(0xffffff);this.linewidth=1;this.linecap='round';this.linejoin='round';this.morphTargets=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;this.morphTargets=source.morphTargets;return this;};var _start=new Vector3();var _end=new Vector3();var _inverseMatrix$1=new Matrix4();var _ray$1=new Ray();var _sphere$2=new Sphere();function Line(){var geometry=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new BufferGeometry();var material=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new LineBasicMaterial();Object3D.call(this);this.type='Line';this.geometry=geometry;this.material=material;this.updateMorphTargets();}Line.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Line,isLine:true,copy:function copy(source){Object3D.prototype.copy.call(this,source);this.material=source.material;this.geometry=source.geometry;return this;},computeLineDistances:function computeLineDistances(){var geometry=this.geometry;if(geometry.isBufferGeometry){// we assume non-indexed geometry if(geometry.index===null){var positionAttribute=geometry.attributes.position;var lineDistances=[0];for(var _i148=1,l=positionAttribute.count;_i148localThresholdSq)continue;interRay.applyMatrix4(this.matrixWorld);//Move back to world space for distance calculation var distance=raycaster.ray.origin.distanceTo(interRay);if(distanceraycaster.far)continue;intersects.push({distance:distance,// What do we want? intersection point on the ray or on the segment?? // point: raycaster.ray.at( distance ), point:interSegment.clone().applyMatrix4(this.matrixWorld),index:_i150,face:null,faceIndex:null,object:this});}}else {for(var _i151=0,_l7=positionAttribute.count-1;_i151<_l7;_i151+=step){vStart.fromBufferAttribute(positionAttribute,_i151);vEnd.fromBufferAttribute(positionAttribute,_i151+1);var _distSq=_ray$1.distanceSqToSegment(vStart,vEnd,interRay,interSegment);if(_distSq>localThresholdSq)continue;interRay.applyMatrix4(this.matrixWorld);//Move back to world space for distance calculation var _distance=raycaster.ray.origin.distanceTo(interRay);if(_distanceraycaster.far)continue;intersects.push({distance:_distance,// What do we want? intersection point on the ray or on the segment?? // point: raycaster.ray.at( distance ), point:interSegment.clone().applyMatrix4(this.matrixWorld),index:_i151,face:null,faceIndex:null,object:this});}}}else if(geometry.isGeometry){var vertices=geometry.vertices;var nbVertices=vertices.length;for(var _i152=0;_i152localThresholdSq)continue;interRay.applyMatrix4(this.matrixWorld);//Move back to world space for distance calculation var _distance2=raycaster.ray.origin.distanceTo(interRay);if(_distance2raycaster.far)continue;intersects.push({distance:_distance2,// What do we want? intersection point on the ray or on the segment?? // point: raycaster.ray.at( distance ), point:interSegment.clone().applyMatrix4(this.matrixWorld),index:_i152,face:null,faceIndex:null,object:this});}}},updateMorphTargets:function updateMorphTargets(){var geometry=this.geometry;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(var m=0,ml=morphAttribute.length;m0){console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');}}}});var _start$1=new Vector3();var _end$1=new Vector3();function LineSegments(geometry,material){Line.call(this,geometry,material);this.type='LineSegments';}LineSegments.prototype=Object.assign(Object.create(Line.prototype),{constructor:LineSegments,isLineSegments:true,computeLineDistances:function computeLineDistances(){var geometry=this.geometry;if(geometry.isBufferGeometry){// we assume non-indexed geometry if(geometry.index===null){var positionAttribute=geometry.attributes.position;var lineDistances=[];for(var _i153=0,l=positionAttribute.count;_i153, * opacity: , * map: new THREE.Texture( ), * alphaMap: new THREE.Texture( ), * * size: , * sizeAttenuation: * * morphTargets: * } */function PointsMaterial(parameters){Material.call(this);this.type='PointsMaterial';this.color=new Color(0xffffff);this.map=null;this.alphaMap=null;this.size=1;this.sizeAttenuation=true;this.morphTargets=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.alphaMap=source.alphaMap;this.size=source.size;this.sizeAttenuation=source.sizeAttenuation;this.morphTargets=source.morphTargets;return this;};var _inverseMatrix$2=new Matrix4();var _ray$2=new Ray();var _sphere$3=new Sphere();var _position$1=new Vector3();function Points(){var geometry=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new BufferGeometry();var material=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new PointsMaterial();Object3D.call(this);this.type='Points';this.geometry=geometry;this.material=material;this.updateMorphTargets();}Points.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Points,isPoints:true,copy:function copy(source){Object3D.prototype.copy.call(this,source);this.material=source.material;this.geometry=source.geometry;return this;},raycast:function raycast(raycaster,intersects){var geometry=this.geometry;var matrixWorld=this.matrixWorld;var threshold=raycaster.params.Points.threshold;// Checking boundingSphere distance to ray if(geometry.boundingSphere===null)geometry.computeBoundingSphere();_sphere$3.copy(geometry.boundingSphere);_sphere$3.applyMatrix4(matrixWorld);_sphere$3.radius+=threshold;if(raycaster.ray.intersectsSphere(_sphere$3)===false)return;// _inverseMatrix$2.copy(matrixWorld).invert();_ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);var localThreshold=threshold/((this.scale.x+this.scale.y+this.scale.z)/3);var localThresholdSq=localThreshold*localThreshold;if(geometry.isBufferGeometry){var index=geometry.index;var attributes=geometry.attributes;var positionAttribute=attributes.position;if(index!==null){var indices=index.array;for(var _i155=0,il=indices.length;_i1550){var morphAttribute=morphAttributes[keys[0]];if(morphAttribute!==undefined){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(var m=0,ml=morphAttribute.length;m0){console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');}}}});function testPoint(point,index,localThresholdSq,matrixWorld,raycaster,intersects,object){var rayPointDistanceSq=_ray$2.distanceSqToPoint(point);if(rayPointDistanceSqraycaster.far)return;intersects.push({distance:distance,distanceToRay:Math.sqrt(rayPointDistanceSq),point:intersectPoint,index:index,face:null,object:object});}}function VideoTexture(video,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy){Texture.call(this,video,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy);this.format=format!==undefined?format:RGBFormat;this.minFilter=minFilter!==undefined?minFilter:LinearFilter;this.magFilter=magFilter!==undefined?magFilter:LinearFilter;this.generateMipmaps=false;var scope=this;function updateVideo(){scope.needsUpdate=true;video.requestVideoFrameCallback(updateVideo);}if('requestVideoFrameCallback'in video){video.requestVideoFrameCallback(updateVideo);}}VideoTexture.prototype=Object.assign(Object.create(Texture.prototype),{constructor:VideoTexture,clone:function clone(){return new this.constructor(this.image).copy(this);},isVideoTexture:true,update:function update(){var video=this.image;var hasVideoFrameCallback='requestVideoFrameCallback'in video;if(hasVideoFrameCallback===false&&video.readyState>=video.HAVE_CURRENT_DATA){this.needsUpdate=true;}}});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;// no flipping for cube textures // (also flipping doesn't work for compressed textures ) this.flipY=false;// can't generate mipmaps for compressed textures // mips must be embedded in DDS files this.generateMipmaps=false;}CompressedTexture.prototype=Object.create(Texture.prototype);CompressedTexture.prototype.constructor=CompressedTexture;CompressedTexture.prototype.isCompressedTexture=true;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;CanvasTexture.prototype.isCanvasTexture=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$1;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;var _geometryId=0;// Geometry uses even numbers as Id var _m1$3=new Matrix4();var _obj$1=new Object3D();var _offset$1=new Vector3();function Geometry(){Object.defineProperty(this,'id',{value:_geometryId+=2});this.uuid=MathUtils.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;// update flags this.elementsNeedUpdate=false;this.verticesNeedUpdate=false;this.uvsNeedUpdate=false;this.normalsNeedUpdate=false;this.colorsNeedUpdate=false;this.lineDistancesNeedUpdate=false;this.groupsNeedUpdate=false;}Geometry.prototype=Object.assign(Object.create(EventDispatcher.prototype),{constructor:Geometry,isGeometry:true,applyMatrix4:function applyMatrix4(matrix){var normalMatrix=new Matrix3().getNormalMatrix(matrix);for(var _i158=0,il=this.vertices.length;_i1580){for(var _i161=0;_i1610&&arguments[0]!==undefined?arguments[0]:true;var vertices=new Array(this.vertices.length);for(var v=0,vl=this.vertices.length;v0){this.normalsNeedUpdate=true;}},computeFlatVertexNormals:function computeFlatVertexNormals(){this.computeFaceNormals();for(var f=0,fl=this.faces.length;f0){this.normalsNeedUpdate=true;}},computeMorphNormals:function computeMorphNormals(){// save original normals // - create temp variables on first access // otherwise just copy (for faster repeated calls) for(var f=0,fl=this.faces.length;f2&&arguments[2]!==undefined?arguments[2]:0;if(!(geometry&&geometry.isGeometry)){console.error('THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.',geometry);return;}var normalMatrix;var vertexOffset=this.vertices.length,vertices1=this.vertices,vertices2=geometry.vertices,faces1=this.faces,faces2=geometry.faces,colors1=this.colors,colors2=geometry.colors;if(matrix!==undefined){normalMatrix=new Matrix3().getNormalMatrix(matrix);}// vertices for(var _i166=0,il=vertices2.length;_i1660&&arguments[0]!==undefined?arguments[0]:4;var verticesMap={};// Hashmap for looking up vertices by position coordinates (and making sure they are unique) var unique=[],changes=[];var precision=Math.pow(10,precisionPoints);for(var _i170=0,il=this.vertices.length;_i170=0;_i172--){var idx=faceIndicesToRemove[_i172];this.faces.splice(idx,1);for(var j=0,jl=this.faceVertexUvs.length;j0;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);// isQuad 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][_i177];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<0)data.data.colors=colors;if(uvs.length>0)data.data.uvs=[uvs];// temporal backward compatibility data.data.faces=faces;return data;},clone:function clone(){/* // Handle primitives const parameters = this.parameters; if ( parameters !== undefined ) { const values = []; for ( const key in parameters ) { values.push( parameters[ key ] ); } const geometry = Object.create( this.constructor.prototype ); this.constructor.apply( geometry, values ); return geometry; } return new this.constructor().copy( this ); */return new Geometry().copy(this);},copy:function copy(source){// reset this.vertices=[];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=[];this.skinIndices=[];this.lineDistances=[];this.boundingBox=null;this.boundingSphere=null;// name this.name=source.name;// vertices var vertices=source.vertices;for(var _i178=0,il=vertices.length;_i1780&&arguments[0]!==undefined?arguments[0]:1;var segments=arguments.length>1&&arguments[1]!==undefined?arguments[1]:8;var thetaStart=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var thetaLength=arguments.length>3&&arguments[3]!==undefined?arguments[3]:Math.PI*2;super();this.type='CircleBufferGeometry';this.parameters={radius:radius,segments:segments,thetaStart:thetaStart,thetaLength:thetaLength};segments=Math.max(3,segments);// buffers var indices=[];var vertices=[];var normals=[];var uvs=[];// helper variables var vertex=new Vector3();var uv=new Vector2();// center point vertices.push(0,0,0);normals.push(0,0,1);uvs.push(0.5,0.5);for(var s=0,_i187=3;s<=segments;s++,_i187+=3){var segment=thetaStart+s/segments*thetaLength;// vertex vertex.x=radius*Math.cos(segment);vertex.y=radius*Math.sin(segment);vertices.push(vertex.x,vertex.y,vertex.z);// normal normals.push(0,0,1);// uvs uv.x=(vertices[_i187]/radius+1)/2;uv.y=(vertices[_i187+1]/radius+1)/2;uvs.push(uv.x,uv.y);}// indices for(var _i188=1;_i188<=segments;_i188++){indices.push(_i188,_i188+1,0);}// build geometry this.setIndex(indices);this.setAttribute('position',new Float32BufferAttribute(vertices,3));this.setAttribute('normal',new Float32BufferAttribute(normals,3));this.setAttribute('uv',new Float32BufferAttribute(uvs,2));}}class CircleGeometry extends Geometry{constructor(radius,segments,thetaStart,thetaLength){super();this.type='CircleGeometry';this.parameters={radius:radius,segments:segments,thetaStart:thetaStart,thetaLength:thetaLength};this.fromBufferGeometry(new CircleBufferGeometry(radius,segments,thetaStart,thetaLength));this.mergeVertices();}}class CylinderBufferGeometry extends BufferGeometry{constructor(){var radiusTop=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;var radiusBottom=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var height=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;var radialSegments=arguments.length>3&&arguments[3]!==undefined?arguments[3]:8;var heightSegments=arguments.length>4&&arguments[4]!==undefined?arguments[4]:1;var openEnded=arguments.length>5&&arguments[5]!==undefined?arguments[5]:false;var thetaStart=arguments.length>6&&arguments[6]!==undefined?arguments[6]:0;var thetaLength=arguments.length>7&&arguments[7]!==undefined?arguments[7]:Math.PI*2;super();this.type='CylinderBufferGeometry';this.parameters={radiusTop:radiusTop,radiusBottom:radiusBottom,height:height,radialSegments:radialSegments,heightSegments:heightSegments,openEnded:openEnded,thetaStart:thetaStart,thetaLength:thetaLength};var scope=this;radialSegments=Math.floor(radialSegments);heightSegments=Math.floor(heightSegments);// buffers var indices=[];var vertices=[];var normals=[];var uvs=[];// helper variables var index=0;var indexArray=[];var halfHeight=height/2;var groupStart=0;// generate geometry generateTorso();if(openEnded===false){if(radiusTop>0)generateCap(true);if(radiusBottom>0)generateCap(false);}// build geometry this.setIndex(indices);this.setAttribute('position',new Float32BufferAttribute(vertices,3));this.setAttribute('normal',new Float32BufferAttribute(normals,3));this.setAttribute('uv',new Float32BufferAttribute(uvs,2));function generateTorso(){var normal=new Vector3();var vertex=new Vector3();var groupCount=0;// this will be used to calculate the normal var slope=(radiusBottom-radiusTop)/height;// generate vertices, normals and uvs for(var y=0;y<=heightSegments;y++){var indexRow=[];var v=y/heightSegments;// calculate the radius of the current row var radius=v*(radiusBottom-radiusTop)+radiusTop;for(var 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 vertex.x=radius*sinTheta;vertex.y=-v*height+halfHeight;vertex.z=radius*cosTheta;vertices.push(vertex.x,vertex.y,vertex.z);// normal normal.set(sinTheta,slope,cosTheta).normalize();normals.push(normal.x,normal.y,normal.z);// uv uvs.push(u,1-v);// save index of vertex in respective row indexRow.push(index++);}// now save vertices of the row in our index array indexArray.push(indexRow);}// generate indices for(var _x2=0;_x20&&arguments[0]!==undefined?arguments[0]:1;var height=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var radialSegments=arguments.length>2&&arguments[2]!==undefined?arguments[2]:8;var heightSegments=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;var openEnded=arguments.length>4&&arguments[4]!==undefined?arguments[4]:false;var thetaStart=arguments.length>5&&arguments[5]!==undefined?arguments[5]:0;var thetaLength=arguments.length>6&&arguments[6]!==undefined?arguments[6]:Math.PI*2;super(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};}}class PolyhedronBufferGeometry extends BufferGeometry{constructor(vertices,indices){var radius=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;var detail=arguments.length>3&&arguments[3]!==undefined?arguments[3]:0;super();this.type='PolyhedronBufferGeometry';this.parameters={vertices:vertices,indices:indices,radius:radius,detail:detail};// default buffer data var vertexBuffer=[];var uvBuffer=[];// the subdivision creates the vertex buffer data subdivide(detail);// all vertices should lie on a conceptual sphere with a given radius applyRadius(radius);// finally, create the uv data generateUVs();// build non-indexed geometry this.setAttribute('position',new Float32BufferAttribute(vertexBuffer,3));this.setAttribute('normal',new Float32BufferAttribute(vertexBuffer.slice(),3));this.setAttribute('uv',new Float32BufferAttribute(uvBuffer,2));if(detail===0){this.computeVertexNormals();// flat normals }else {this.normalizeNormals();// smooth normals }// helper functions function subdivide(detail){var a=new Vector3();var b=new Vector3();var c=new Vector3();// iterate over all faces and apply a subdivison with the given detail value for(var _i190=0;_i1900.9&&min<0.1){if(x0<0.2)uvBuffer[_i195+0]+=1;if(x1<0.2)uvBuffer[_i195+2]+=1;if(x2<0.2)uvBuffer[_i195+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 _i196=0,j=0;_i1960&&arguments[0]!==undefined?arguments[0]:1;var detail=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;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,1,1,1,// (0, ±1/φ, ±φ) 0,-r,-t,0,-r,t,0,r,-t,0,r,t,// (±1/φ, ±φ, 0) -r,-t,0,-r,t,0,r,-t,0,r,t,0,// (±φ, 0, ±1/φ) -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];super(vertices,indices,radius,detail);this.type='DodecahedronBufferGeometry';this.parameters={radius:radius,detail:detail};}}class DodecahedronGeometry extends Geometry{constructor(radius,detail){super();this.type='DodecahedronGeometry';this.parameters={radius:radius,detail:detail};this.fromBufferGeometry(new DodecahedronBufferGeometry(radius,detail));this.mergeVertices();}}var _v0$2=new Vector3();var _v1$5=new Vector3();var _normal$1=new Vector3();var _triangle=new Triangle();class EdgesGeometry extends BufferGeometry{constructor(geometry,thresholdAngle){super();this.type='EdgesGeometry';this.parameters={thresholdAngle:thresholdAngle};thresholdAngle=thresholdAngle!==undefined?thresholdAngle:1;if(geometry.isGeometry){geometry=new BufferGeometry().fromGeometry(geometry);}var precisionPoints=4;var precision=Math.pow(10,precisionPoints);var thresholdDot=Math.cos(MathUtils.DEG2RAD*thresholdAngle);var indexAttr=geometry.getIndex();var positionAttr=geometry.getAttribute('position');var indexCount=indexAttr?indexAttr.count:positionAttr.count;var indexArr=[0,0,0];var vertKeys=['a','b','c'];var hashes=new Array(3);var edgeData={};var vertices=[];for(var _i197=0;_i19780*dim){minX=maxX=data[0];minY=maxY=data[1];for(var _i198=dim;_i198maxX)maxX=x;if(y>maxY)maxY=y;}// minX, minY and invSize are later used to transform coords into integers for z-order calculation invSize=Math.max(maxX-minX,maxY-minY);invSize=invSize!==0?1/invSize:0;}earcutLinked(outerNode,triangles,dim,minX,minY,invSize);return triangles;}};// create a circular doubly linked list from polygon points in the specified winding order function linkedList(data,start,end,dim,clockwise){var i,last;if(clockwise===signedArea(data,start,end,dim)>0){for(i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);}if(last&&equals(last,last.next)){removeNode(last);last=last.next;}return last;}// eliminate colinear or duplicate points function filterPoints(start,end){if(!start)return start;if(!end)end=start;var p=start,again;do{again=false;if(!p.steiner&&(equals(p,p.next)||area(p.prev,p,p.next)===0)){removeNode(p);p=end=p.prev;if(p===p.next)break;again=true;}else {p=p.next;}}while(again||p!==end);return end;}// main ear slicing loop which triangulates a polygon (given as a linked list) function earcutLinked(ear,triangles,dim,minX,minY,invSize,pass){if(!ear)return;// interlink polygon nodes in z-order if(!pass&&invSize)indexCurve(ear,minX,minY,invSize);var stop=ear,prev,next;// iterate through ears, slicing them one by one while(ear.prev!==ear.next){prev=ear.prev;next=ear.next;if(invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear)){// cut off the triangle triangles.push(prev.i/dim);triangles.push(ear.i/dim);triangles.push(next.i/dim);removeNode(ear);// skipping the next vertex leads to less sliver triangles ear=next.next;stop=next.next;continue;}ear=next;// if we looped through the whole remaining polygon and can't find any more ears if(ear===stop){// try filtering points and slicing again if(!pass){earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);// if this didn't work, try curing all small self-intersections locally }else if(pass===1){ear=cureLocalIntersections(filterPoints(ear),triangles,dim);earcutLinked(ear,triangles,dim,minX,minY,invSize,2);// as a last resort, try splitting the remaining polygon into two }else if(pass===2){splitEarcut(ear,triangles,dim,minX,minY,invSize);}break;}}}// check whether a polygon node forms a valid ear with adjacent nodes function isEar(ear){var a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return false;// reflex, can't be an ear // now make sure we don't have other points inside the potential ear var p=ear.next.next;while(p!==ear.prev){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.next;}return true;}function isEarHashed(ear,minX,minY,invSize){var a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return false;// reflex, can't be an ear // triangle bbox; min & max are calculated like this for speed var minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y;// z-order range for the current triangle bbox; var minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);var p=ear.prevZ,n=ear.nextZ;// look for points inside the triangle in both directions while(p&&p.z>=minZ&&n&&n.z<=maxZ){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.prevZ;if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return false;n=n.nextZ;}// look for remaining points in decreasing z-order while(p&&p.z>=minZ){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.prevZ;}// look for remaining points in increasing z-order while(n&&n.z<=maxZ){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return false;n=n.nextZ;}return true;}// go through all polygon nodes and cure small local self-intersections function cureLocalIntersections(start,triangles,dim){var p=start;do{var a=p.prev,b=p.next.next;if(!equals(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)){triangles.push(a.i/dim);triangles.push(p.i/dim);triangles.push(b.i/dim);// remove two nodes involved removeNode(p);removeNode(p.next);p=start=b;}p=p.next;}while(p!==start);return filterPoints(p);}// try splitting polygon into two and triangulate them independently function splitEarcut(start,triangles,dim,minX,minY,invSize){// look for a valid diagonal that divides the polygon into two var a=start;do{var b=a.next.next;while(b!==a.prev){if(a.i!==b.i&&isValidDiagonal(a,b)){// split the polygon in two by the diagonal var c=splitPolygon(a,b);// filter colinear points around the cuts a=filterPoints(a,a.next);c=filterPoints(c,c.next);// run earcut on each half earcutLinked(a,triangles,dim,minX,minY,invSize);earcutLinked(c,triangles,dim,minX,minY,invSize);return;}b=b.next;}a=a.next;}while(a!==start);}// link every hole into the outer loop, producing a single-ring polygon without holes function eliminateHoles(data,holeIndices,outerNode,dim){var queue=[];var i,len,start,end,list;for(i=0,len=holeIndices.length;i=p.next.y&&p.next.y!==p.y){var x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){qx=x;if(x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next;}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))){m=p;tanMin=tan;}}p=p.next;}while(p!==stop);return m;}// whether sector in vertex m contains sector in vertex p in the same coordinates function sectorContainsSector(m,p){return area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0;}// interlink polygon nodes in z-order function indexCurve(start,minX,minY,invSize){var p=start;do{if(p.z===null)p.z=zOrder(p.x,p.y,minX,minY,invSize);p.prevZ=p.prev;p.nextZ=p.next;p=p.next;}while(p!==start);p.prevZ.nextZ=null;p.prevZ=null;sortLinked(p);}// Simon Tatham's linked list merge sort algorithm // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html function sortLinked(list){var i,p,q,e,tail,numMerges,pSize,qSize,inSize=1;do{p=list;list=null;tail=null;numMerges=0;while(p){numMerges++;q=p;pSize=0;for(i=0;i0||qSize>0&&q){if(pSize!==0&&(qSize===0||!q||p.z<=q.z)){e=p;p=p.nextZ;pSize--;}else {e=q;q=q.nextZ;qSize--;}if(tail)tail.nextZ=e;else list=e;e.prevZ=tail;tail=e;}p=q;}tail.nextZ=null;inSize*=2;}while(numMerges>1);return list;}// z-order of a point given coords and inverse of the longer side of data bbox function zOrder(x,y,minX,minY,invSize){// coords are transformed into non-negative 15-bit integer range x=32767*(x-minX)*invSize;y=32767*(y-minY)*invSize;x=(x|x<<8)&0x00FF00FF;x=(x|x<<4)&0x0F0F0F0F;x=(x|x<<2)&0x33333333;x=(x|x<<1)&0x55555555;y=(y|y<<8)&0x00FF00FF;y=(y|y<<4)&0x0F0F0F0F;y=(y|y<<2)&0x33333333;y=(y|y<<1)&0x55555555;return x|y<<1;}// find the leftmost node of a polygon ring function getLeftmost(start){var p=start,leftmost=start;do{if(p.x=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0;}// check if a diagonal between two polygon nodes is valid (lies in polygon interior) function isValidDiagonal(a,b){return a.next.i!==b.i&&a.prev.i!==b.i&&!intersectsPolygon(a,b)&&(// dones't intersect other edges locallyInside(a,b)&&locallyInside(b,a)&&middleInside(a,b)&&(// locally visible area(a.prev,a,b.prev)||area(a,b.prev,b))||// does not create opposite-facing sectors equals(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0);// special zero-length case }// signed area of a triangle function area(p,q,r){return (q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y);}// check if two points are equal function equals(p1,p2){return p1.x===p2.x&&p1.y===p2.y;}// check if two segments intersect function intersects(p1,q1,p2,q2){var o1=sign(area(p1,q1,p2));var o2=sign(area(p1,q1,q2));var o3=sign(area(p2,q2,p1));var o4=sign(area(p2,q2,q1));if(o1!==o2&&o3!==o4)return true;// general case if(o1===0&&onSegment(p1,p2,q1))return true;// p1, q1 and p2 are collinear and p2 lies on p1q1 if(o2===0&&onSegment(p1,q2,q1))return true;// p1, q1 and q2 are collinear and q2 lies on p1q1 if(o3===0&&onSegment(p2,p1,q2))return true;// p2, q2 and p1 are collinear and p1 lies on p2q2 if(o4===0&&onSegment(p2,q1,q2))return true;// p2, q2 and q1 are collinear and q1 lies on p2q2 return false;}// for collinear points p, q, r, check if point q lies on segment pr function onSegment(p,q,r){return q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y);}function sign(num){return num>0?1:num<0?-1:0;}// check if a polygon diagonal intersects any polygon segments function intersectsPolygon(a,b){var p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return true;p=p.next;}while(p!==a);return false;}// check if a polygon diagonal is locally inside the polygon function locallyInside(a,b){return area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0;}// check if the middle point of a polygon diagonal is inside the polygon function middleInside(a,b){var p=a,inside=false;var px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{if(p.y>py!==p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x)inside=!inside;p=p.next;}while(p!==a);return inside;}// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; // if one belongs to the outer ring and another to a hole, it merges it into a single ring function splitPolygon(a,b){var a2=new Node(a.i,a.x,a.y),b2=new Node(b.i,b.x,b.y),an=a.next,bp=b.prev;a.next=b;b.prev=a;a2.next=an;an.prev=a2;b2.next=a2;a2.prev=b2;bp.next=b2;b2.prev=bp;return b2;}// create a node and optionally link it with previous one (in a circular doubly linked list) function insertNode(i,x,y,last){var p=new Node(i,x,y);if(!last){p.prev=p;p.next=p;}else {p.next=last.next;p.prev=last;last.next.prev=p;last.next=p;}return p;}function removeNode(p){p.next.prev=p.prev;p.prev.next=p.next;if(p.prevZ)p.prevZ.nextZ=p.nextZ;if(p.nextZ)p.nextZ.prevZ=p.prevZ;}function Node(i,x,y){// vertex index in coordinates array this.i=i;// vertex coordinates this.x=x;this.y=y;// previous and next vertex nodes in a polygon ring this.prev=null;this.next=null;// z-order curve value this.z=null;// previous and next nodes in z-order this.prevZ=null;this.nextZ=null;// indicates whether this is a steiner point this.steiner=false;}function signedArea(data,start,end,dim){var sum=0;for(var _i199=start,j=end-dim;_i1992&&points[l-1].equals(points[0])){points.pop();}}function addContour(vertices,contour){for(var _i202=0;_i202, // number of points on the curves * steps: , // number of points for z-side extrusions / used for subdividing segments of extrude spline too * depth: , // Depth to extrude the shape * * bevelEnabled: , // turn on bevel * bevelThickness: , // how deep into the original shape bevel goes * bevelSize: , // how far from shape outline (including bevelOffset) is bevel * bevelOffset: , // how far from shape outline does bevel start * bevelSegments: , // number of bevel layers * * extrudePath: // curve to extrude shape along * * UVGenerator: // object that provides UV generator functions * * } */class ExtrudeBufferGeometry extends BufferGeometry{constructor(shapes,options){super();this.type='ExtrudeBufferGeometry';this.parameters={shapes:shapes,options:options};shapes=Array.isArray(shapes)?shapes:[shapes];var scope=this;var verticesArray=[];var uvArray=[];for(var _i203=0,l=shapes.length;_i203Number.EPSILON){// not collinear // length of vectors for normalizing 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);// shift adjacent points by unit vectors to the left 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;// scaling factor for v_prev to intersection point 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);// vector from inPt to intersection point v_trans_x=ptPrevShift_x+v_prev_x*sf-inPt.x;v_trans_y=ptPrevShift_y+v_prev_y*sf-inPt.y;// Don't normalize!, otherwise sharp corners become ugly // but prevent crazy spikes 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 {// handle special case of collinear edges var direction_eq=false;// assumes: opposite 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){// console.log("Warning: lines are a straight sequence"); v_trans_x=-v_prev_y;v_trans_y=v_prev_x;shrink_by=Math.sqrt(v_prev_lensq);}else {// console.log("Warning: lines are a straight spike"); 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 _i204=0,il=contour.length,j=il-1,k=_i204+1;_i204 0; b -- ) { var t=b/bevelSegments;var z=bevelThickness*Math.cos(t*Math.PI/2);var _bs=bevelSize*Math.sin(t*Math.PI/2)+bevelOffset;// contract shape for(var _i206=0,_il27=contour.length;_i206<_il27;_i206++){var vert=scalePt2(contour[_i206],contourMovements[_i206],_bs);v(vert.x,vert.y,-z);}// expand holes for(var _h3=0,_hl3=holes.length;_h3<_hl3;_h3++){var _ahole3=holes[_h3];oneHoleMovements=holesMovements[_h3];for(var _i207=0,_il28=_ahole3.length;_i207<_il28;_i207++){var _vert=scalePt2(_ahole3[_i207],oneHoleMovements[_i207],_bs);v(_vert.x,_vert.y,-z);}}}var bs=bevelSize+bevelOffset;// Back facing vertices for(var _i208=0;_i208=0;_b5--){var _t=_b5/bevelSegments;var _z2=bevelThickness*Math.cos(_t*Math.PI/2);var _bs2=bevelSize*Math.sin(_t*Math.PI/2)+bevelOffset;// contract shape for(var _i210=0,_il29=contour.length;_i210<_il29;_i210++){var _vert4=scalePt2(contour[_i210],contourMovements[_i210],_bs2);v(_vert4.x,_vert4.y,depth+_z2);}// expand holes for(var _h4=0,_hl4=holes.length;_h4<_hl4;_h4++){var _ahole4=holes[_h4];oneHoleMovements=holesMovements[_h4];for(var _i211=0,_il30=_ahole4.length;_i211<_il30;_i211++){var _vert5=scalePt2(_ahole4[_i211],oneHoleMovements[_i211],_bs2);if(!extrudeByPath){v(_vert5.x,_vert5.y,depth+_z2);}else {v(_vert5.x,_vert5.y+extrudePts[steps-1].y,extrudePts[steps-1].x+_z2);}}}}/* Faces */ // Top and bottom faces if(!options.openEnded){//xzw add 可以选择开口,不创建Top and bottom faces buildLidFaces();}// Sides faces buildSideFaces();///// Internal functions function buildLidFaces(){var start=verticesArray.length/3;if(bevelEnabled){var layer=0;// steps + 1 var offset=vlen*layer;// Bottom faces for(var _i212=0;_i212=0){if(shapeDontClose&&i==0)break;//xzw add var _j13=i;var _k2=i-1;if(_k2<0)_k2=contour.length-1;//console.log('b', i,j, i-1, k,vertices.length); for(var _s4=0,sl=steps+bevelSegments*2;_s4, // number of points on the curves * steps: , // number of points for z-side extrusions / used for subdividing segments of extrude spline too * depth: , // Depth to extrude the shape * * bevelEnabled: , // turn on bevel * bevelThickness: , // how deep into the original shape bevel goes * bevelSize: , // how far from shape outline (including bevelOffset) is bevel * bevelOffset: , // how far from shape outline does bevel start * bevelSegments: , // number of bevel layers * * extrudePath: // curve to extrude shape along * * UVGenerator: // object that provides UV generator functions * * } */class ExtrudeGeometry extends Geometry{constructor(shapes,options){super();this.type='ExtrudeGeometry';this.parameters={shapes:shapes,options:options};this.fromBufferGeometry(new ExtrudeBufferGeometry(shapes,options));this.mergeVertices();}toJSON(){var data=super.toJSON();var shapes=this.parameters.shapes;var options=this.parameters.options;return toJSON$1(shapes,options,data);}}function toJSON$1(shapes,options,data){data.shapes=[];if(Array.isArray(shapes)){for(var _i217=0,l=shapes.length;_i2170&&arguments[0]!==undefined?arguments[0]:1;var detail=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;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];super(vertices,indices,radius,detail);this.type='IcosahedronBufferGeometry';this.parameters={radius:radius,detail:detail};}}class IcosahedronGeometry extends Geometry{constructor(radius,detail){super();this.type='IcosahedronGeometry';this.parameters={radius:radius,detail:detail};this.fromBufferGeometry(new IcosahedronBufferGeometry(radius,detail));this.mergeVertices();}}class LatheBufferGeometry extends BufferGeometry{constructor(points){var segments=arguments.length>1&&arguments[1]!==undefined?arguments[1]:12;var phiStart=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var phiLength=arguments.length>3&&arguments[3]!==undefined?arguments[3]:Math.PI*2;super();this.type='LatheBufferGeometry';this.parameters={points:points,segments:segments,phiStart:phiStart,phiLength:phiLength};segments=Math.floor(segments);// clamp phiLength so it's in range of [ 0, 2PI ] phiLength=MathUtils.clamp(phiLength,0,Math.PI*2);// buffers var indices=[];var vertices=[];var uvs=[];// helper variables var inverseSegments=1.0/segments;var vertex=new Vector3();var uv=new Vector2();// generate vertices and uvs for(var _i218=0;_i218<=segments;_i218++){var phi=phiStart+_i218*inverseSegments*phiLength;var sin=Math.sin(phi);var cos=Math.cos(phi);for(var j=0;j<=points.length-1;j++){// vertex 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 uv.x=_i218/segments;uv.y=j/(points.length-1);uvs.push(uv.x,uv.y);}}// indices for(var _i219=0;_i2190&&arguments[0]!==undefined?arguments[0]:1;var detail=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;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];super(vertices,indices,radius,detail);this.type='OctahedronBufferGeometry';this.parameters={radius:radius,detail:detail};}}class OctahedronGeometry extends Geometry{constructor(radius,detail){super();this.type='OctahedronGeometry';this.parameters={radius:radius,detail:detail};this.fromBufferGeometry(new OctahedronBufferGeometry(radius,detail));this.mergeVertices();}}/** * Parametric Surfaces Geometry * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html */function ParametricBufferGeometry(func,slices,stacks){BufferGeometry.call(this);this.type='ParametricBufferGeometry';this.parameters={func:func,slices:slices,stacks:stacks};// buffers var indices=[];var vertices=[];var normals=[];var uvs=[];var EPS=0.00001;var normal=new Vector3();var p0=new Vector3(),p1=new Vector3();var pu=new Vector3(),pv=new Vector3();if(func.length<3){console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');}// generate vertices, normals and uvs var sliceCount=slices+1;for(var _i221=0;_i221<=stacks;_i221++){var v=_i221/stacks;for(var j=0;j<=slices;j++){var u=j/slices;// vertex func(u,v,p0);vertices.push(p0.x,p0.y,p0.z);// normal // approximate tangent vectors via finite differences if(u-EPS>=0){func(u-EPS,v,p1);pu.subVectors(p0,p1);}else {func(u+EPS,v,p1);pu.subVectors(p1,p0);}if(v-EPS>=0){func(u,v-EPS,p1);pv.subVectors(p0,p1);}else {func(u,v+EPS,p1);pv.subVectors(p1,p0);}// cross product of tangent vectors returns surface normal normal.crossVectors(pu,pv).normalize();normals.push(normal.x,normal.y,normal.z);// uv uvs.push(u,v);}}// generate indices for(var _i222=0;_i2220&&arguments[0]!==undefined?arguments[0]:0.5;var outerRadius=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var thetaSegments=arguments.length>2&&arguments[2]!==undefined?arguments[2]:8;var phiSegments=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;var thetaStart=arguments.length>4&&arguments[4]!==undefined?arguments[4]:0;var thetaLength=arguments.length>5&&arguments[5]!==undefined?arguments[5]:Math.PI*2;super();this.type='RingBufferGeometry';this.parameters={innerRadius:innerRadius,outerRadius:outerRadius,thetaSegments:thetaSegments,phiSegments:phiSegments,thetaStart:thetaStart,thetaLength:thetaLength};thetaSegments=Math.max(3,thetaSegments);phiSegments=Math.max(1,phiSegments);// buffers var indices=[];var vertices=[];var normals=[];var uvs=[];// some helper variables var radius=innerRadius;var radiusStep=(outerRadius-innerRadius)/phiSegments;var vertex=new Vector3();var uv=new Vector2();// generate vertices, normals and uvs for(var j=0;j<=phiSegments;j++){for(var _i223=0;_i223<=thetaSegments;_i223++){// values are generate from the inside of the ring to the outside var segment=thetaStart+_i223/thetaSegments*thetaLength;// vertex vertex.x=radius*Math.cos(segment);vertex.y=radius*Math.sin(segment);vertices.push(vertex.x,vertex.y,vertex.z);// normal normals.push(0,0,1);// uv uv.x=(vertex.x/outerRadius+1)/2;uv.y=(vertex.y/outerRadius+1)/2;uvs.push(uv.x,uv.y);}// increase the radius for next row of vertices radius+=radiusStep;}// indices for(var _j17=0;_j171&&arguments[1]!==undefined?arguments[1]:12;super();this.type='ShapeBufferGeometry';this.parameters={shapes:shapes,curveSegments:curveSegments};// buffers var indices=[];var vertices=[];var normals=[];var uvs=[];// helper variables var groupStart=0;var groupCount=0;// allow single and array values for "shapes" parameter if(Array.isArray(shapes)===false){addShape(shapes);}else {for(var _i225=0;_i2250&&arguments[0]!==undefined?arguments[0]:1;var widthSegments=arguments.length>1&&arguments[1]!==undefined?arguments[1]:8;var heightSegments=arguments.length>2&&arguments[2]!==undefined?arguments[2]:6;var phiStart=arguments.length>3&&arguments[3]!==undefined?arguments[3]:0;var phiLength=arguments.length>4&&arguments[4]!==undefined?arguments[4]:Math.PI*2;var thetaStart=arguments.length>5&&arguments[5]!==undefined?arguments[5]:0;var thetaLength=arguments.length>6&&arguments[6]!==undefined?arguments[6]:Math.PI;super();this.type='SphereBufferGeometry';this.parameters={radius:radius,widthSegments:widthSegments,heightSegments:heightSegments,phiStart:phiStart,phiLength:phiLength,thetaStart:thetaStart,thetaLength:thetaLength};widthSegments=Math.max(3,Math.floor(widthSegments));heightSegments=Math.max(2,Math.floor(heightSegments));var thetaEnd=Math.min(thetaStart+thetaLength,Math.PI);var index=0;var grid=[];var vertex=new Vector3();var normal=new Vector3();// buffers var indices=[];var vertices=[];var normals=[];var uvs=[];// generate vertices, normals and uvs for(var iy=0;iy<=heightSegments;iy++){var verticesRow=[];var v=iy/heightSegments;// special case for the poles var uOffset=0;if(iy==0&&thetaStart==0){uOffset=0.5/widthSegments;}else if(iy==heightSegments&&thetaEnd==Math.PI){uOffset=-0.5/widthSegments;}for(var ix=0;ix<=widthSegments;ix++){var u=ix/widthSegments;// vertex 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 normal.copy(vertex).normalize();normals.push(normal.x,normal.y,normal.z);// uv uvs.push(u+uOffset,1-v);verticesRow.push(index++);}grid.push(verticesRow);}// indices for(var _iy3=0;_iy30)indices.push(a,b,d);if(_iy3!==heightSegments-1||thetaEnd0&&arguments[0]!==undefined?arguments[0]:1;var detail=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;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];super(vertices,indices,radius,detail);this.type='TetrahedronBufferGeometry';this.parameters={radius:radius,detail:detail};}}class TetrahedronGeometry extends Geometry{constructor(radius,detail){super();this.type='TetrahedronGeometry';this.parameters={radius:radius,detail:detail};this.fromBufferGeometry(new TetrahedronBufferGeometry(radius,detail));this.mergeVertices();}}/** * Text = 3D Text * * parameters = { * font: , // font * * size: , // size of the text * height: , // thickness to extrude text * curveSegments: , // number of points on the curves * * bevelEnabled: , // turn on bevel * bevelThickness: , // how deep into text bevel goes * bevelSize: , // how far from text outline (including bevelOffset) is bevel * bevelOffset: // how far from text outline does bevel start * } */class TextBufferGeometry extends ExtrudeBufferGeometry{constructor(text){var parameters=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var font=parameters.font;if(!(font&&font.isFont)){console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');return new BufferGeometry();}var shapes=font.generateShapes(text,parameters.size);// translate parameters to ExtrudeGeometry API parameters.depth=parameters.height!==undefined?parameters.height:50;// defaults if(parameters.bevelThickness===undefined)parameters.bevelThickness=10;if(parameters.bevelSize===undefined)parameters.bevelSize=8;if(parameters.bevelEnabled===undefined)parameters.bevelEnabled=false;super(shapes,parameters);this.type='TextBufferGeometry';}}/** * Text = 3D Text * * parameters = { * font: , // font * * size: , // size of the text * height: , // thickness to extrude text * curveSegments: , // number of points on the curves * * bevelEnabled: , // turn on bevel * bevelThickness: , // how deep into text bevel goes * bevelSize: , // how far from text outline (including bevelOffset) is bevel * bevelOffset: // how far from text outline does bevel start * } */class TextGeometry extends Geometry{constructor(text,parameters){super();this.type='TextGeometry';this.parameters={text:text,parameters:parameters};this.fromBufferGeometry(new TextBufferGeometry(text,parameters));this.mergeVertices();}}class TorusBufferGeometry extends BufferGeometry{constructor(){var radius=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;var tube=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0.4;var radialSegments=arguments.length>2&&arguments[2]!==undefined?arguments[2]:8;var tubularSegments=arguments.length>3&&arguments[3]!==undefined?arguments[3]:6;var arc=arguments.length>4&&arguments[4]!==undefined?arguments[4]:Math.PI*2;super();this.type='TorusBufferGeometry';this.parameters={radius:radius,tube:tube,radialSegments:radialSegments,tubularSegments:tubularSegments,arc:arc};radialSegments=Math.floor(radialSegments);tubularSegments=Math.floor(tubularSegments);// buffers var indices=[];var vertices=[];var normals=[];var uvs=[];// helper variables var center=new Vector3();var vertex=new Vector3();var normal=new Vector3();// generate vertices, normals and uvs for(var j=0;j<=radialSegments;j++){for(var _i232=0;_i232<=tubularSegments;_i232++){var u=_i232/tubularSegments*arc;var v=j/radialSegments*Math.PI*2;// vertex 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);// normal 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);// uv uvs.push(_i232/tubularSegments);uvs.push(j/radialSegments);}}// generate indices for(var _j18=1;_j18<=radialSegments;_j18++){for(var _i233=1;_i233<=tubularSegments;_i233++){// indices var a=(tubularSegments+1)*_j18+_i233-1;var b=(tubularSegments+1)*(_j18-1)+_i233-1;var c=(tubularSegments+1)*(_j18-1)+_i233;var d=(tubularSegments+1)*_j18+_i233;// faces indices.push(a,b,d);indices.push(b,c,d);}}// build geometry this.setIndex(indices);this.setAttribute('position',new Float32BufferAttribute(vertices,3));this.setAttribute('normal',new Float32BufferAttribute(normals,3));this.setAttribute('uv',new Float32BufferAttribute(uvs,2));}}class TorusGeometry extends Geometry{constructor(radius,tube,radialSegments,tubularSegments,arc){super();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();}}class TorusKnotBufferGeometry extends BufferGeometry{constructor(){var radius=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;var tube=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0.4;var tubularSegments=arguments.length>2&&arguments[2]!==undefined?arguments[2]:64;var radialSegments=arguments.length>3&&arguments[3]!==undefined?arguments[3]:8;var p=arguments.length>4&&arguments[4]!==undefined?arguments[4]:2;var q=arguments.length>5&&arguments[5]!==undefined?arguments[5]:3;super();this.type='TorusKnotBufferGeometry';this.parameters={radius:radius,tube:tube,tubularSegments:tubularSegments,radialSegments:radialSegments,p:p,q:q};tubularSegments=Math.floor(tubularSegments);radialSegments=Math.floor(radialSegments);// buffers var indices=[];var vertices=[];var normals=[];var uvs=[];// helper variables 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();// generate vertices, normals and uvs for(var _i234=0;_i234<=tubularSegments;++_i234){// the radian "u" is used to calculate the position on the torus curve of the current tubular segement var u=_i234/tubularSegments*p*Math.PI*2;// now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions calculatePositionOnCurve(u,p,q,radius,P1);calculatePositionOnCurve(u+0.01,p,q,radius,P2);// calculate orthonormal basis T.subVectors(P2,P1);N.addVectors(P2,P1);B.crossVectors(T,N);N.crossVectors(B,T);// normalize B, N. T can be ignored, we don't use it B.normalize();N.normalize();for(var j=0;j<=radialSegments;++j){// now calculate the vertices. they are nothing more than an extrusion of the torus curve. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value. var v=j/radialSegments*Math.PI*2;var cx=-tube*Math.cos(v);var cy=tube*Math.sin(v);// now calculate the final vertex position. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve 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 (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal) normal.subVectors(vertex,P1).normalize();normals.push(normal.x,normal.y,normal.z);// uv uvs.push(_i234/tubularSegments);uvs.push(j/radialSegments);}}// generate indices for(var _j19=1;_j19<=tubularSegments;_j19++){for(var _i235=1;_i235<=radialSegments;_i235++){// indices var a=(radialSegments+1)*(_j19-1)+(_i235-1);var b=(radialSegments+1)*_j19+(_i235-1);var c=(radialSegments+1)*_j19+_i235;var d=(radialSegments+1)*(_j19-1)+_i235;// faces indices.push(a,b,d);indices.push(b,c,d);}}// build geometry this.setIndex(indices);this.setAttribute('position',new Float32BufferAttribute(vertices,3));this.setAttribute('normal',new Float32BufferAttribute(normals,3));this.setAttribute('uv',new Float32BufferAttribute(uvs,2));// this function calculates the current position on the torus curve 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)*0.5*cu;position.y=radius*(2+cs)*su*0.5;position.z=radius*Math.sin(quOverP)*0.5;}}}class TorusKnotGeometry extends Geometry{constructor(radius,tube,tubularSegments,radialSegments,p,q,heightScale){super();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();}}class TubeBufferGeometry extends BufferGeometry{constructor(path){var tubularSegments=arguments.length>1&&arguments[1]!==undefined?arguments[1]:64;var radius=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;var radialSegments=arguments.length>3&&arguments[3]!==undefined?arguments[3]:8;var closed=arguments.length>4&&arguments[4]!==undefined?arguments[4]:false;super();this.type='TubeBufferGeometry';this.parameters={path:path,tubularSegments:tubularSegments,radius:radius,radialSegments:radialSegments,closed:closed};var frames=path.computeFrenetFrames(tubularSegments,closed);// expose internals this.tangents=frames.tangents;this.normals=frames.normals;this.binormals=frames.binormals;// helper variables var vertex=new Vector3();var normal=new Vector3();var uv=new Vector2();var P=new Vector3();// buffer var vertices=[];var normals=[];var uvs=[];var indices=[];// create buffer data generateBufferData();// build geometry this.setIndex(indices);this.setAttribute('position',new Float32BufferAttribute(vertices,3));this.setAttribute('normal',new Float32BufferAttribute(normals,3));this.setAttribute('uv',new Float32BufferAttribute(uvs,2));// functions function generateBufferData(){for(var _i236=0;_i236 * } */function ShadowMaterial(parameters){Material.call(this);this.type='ShadowMaterial';this.color=new Color(0x000000);this.transparent=true;this.setValues(parameters);}ShadowMaterial.prototype=Object.create(Material.prototype);ShadowMaterial.prototype.constructor=ShadowMaterial;ShadowMaterial.prototype.isShadowMaterial=true;ShadowMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);return this;};function RawShaderMaterial(parameters){ShaderMaterial.call(this,parameters);this.type='RawShaderMaterial';}RawShaderMaterial.prototype=Object.create(ShaderMaterial.prototype);RawShaderMaterial.prototype.constructor=RawShaderMaterial;RawShaderMaterial.prototype.isRawShaderMaterial=true;/** * parameters = { * color: , * roughness: , * metalness: , * opacity: , * * map: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * emissive: , * emissiveIntensity: * emissiveMap: new THREE.Texture( ), * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * roughnessMap: new THREE.Texture( ), * * metalnessMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), * envMapIntensity: * * refractionRatio: , * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: , * morphNormals: * } */function MeshStandardMaterial(parameters){Material.call(this);this.defines={'STANDARD':''};this.type='MeshStandardMaterial';this.color=new Color(0xffffff);// diffuse this.roughness=1.0;this.metalness=0.0;this.map=null;this.lightMap=null;this.lightMapIntensity=1.0;this.aoMap=null;this.aoMapIntensity=1.0;this.emissive=new Color(0x000000);this.emissiveIntensity=1.0;this.emissiveMap=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;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.0;this.refractionRatio=0.98;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap='round';this.wireframeLinejoin='round';this.skinning=false;this.morphTargets=false;this.morphNormals=false;this.vertexTangents=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.normalMapType=source.normalMapType;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;this.vertexTangents=source.vertexTangents;return this;};/** * parameters = { * clearcoat: , * clearcoatMap: new THREE.Texture( ), * clearcoatRoughness: , * clearcoatRoughnessMap: new THREE.Texture( ), * clearcoatNormalScale: , * clearcoatNormalMap: new THREE.Texture( ), * * reflectivity: , * ior: , * * sheen: , * * transmission: , * transmissionMap: new THREE.Texture( ) * } */function MeshPhysicalMaterial(parameters){MeshStandardMaterial.call(this);this.defines={'STANDARD':'','PHYSICAL':''};this.type='MeshPhysicalMaterial';this.clearcoat=0.0;this.clearcoatMap=null;this.clearcoatRoughness=0.0;this.clearcoatRoughnessMap=null;this.clearcoatNormalScale=new Vector2(1,1);this.clearcoatNormalMap=null;this.reflectivity=0.5;// maps to F0 = 0.04 Object.defineProperty(this,'ior',{get:function get(){return (1+0.4*this.reflectivity)/(1-0.4*this.reflectivity);},set:function set(ior){this.reflectivity=MathUtils.clamp(2.5*(ior-1)/(ior+1),0,1);}});this.sheen=null;// null will disable sheen bsdf this.transmission=0.0;this.transmissionMap=null;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={'STANDARD':'','PHYSICAL':''};this.clearcoat=source.clearcoat;this.clearcoatMap=source.clearcoatMap;this.clearcoatRoughness=source.clearcoatRoughness;this.clearcoatRoughnessMap=source.clearcoatRoughnessMap;this.clearcoatNormalMap=source.clearcoatNormalMap;this.clearcoatNormalScale.copy(source.clearcoatNormalScale);this.reflectivity=source.reflectivity;if(source.sheen){this.sheen=(this.sheen||new Color()).copy(source.sheen);}else {this.sheen=null;}this.transmission=source.transmission;this.transmissionMap=source.transmissionMap;return this;};/** * parameters = { * color: , * specular: , * shininess: , * opacity: , * * map: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * emissive: , * emissiveIntensity: * emissiveMap: new THREE.Texture( ), * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * specularMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), * combine: THREE.MultiplyOperation, * reflectivity: , * refractionRatio: , * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: , * morphNormals: * } */function MeshPhongMaterial(parameters){Material.call(this);this.type='MeshPhongMaterial';this.color=new Color(0xffffff);// diffuse this.specular=new Color(0x111111);this.shininess=30;this.map=null;this.lightMap=null;this.lightMapIntensity=1.0;this.aoMap=null;this.aoMapIntensity=1.0;this.emissive=new Color(0x000000);this.emissiveIntensity=1.0;this.emissiveMap=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;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=0.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.normalMapType=source.normalMapType;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;};/** * parameters = { * color: , * * map: new THREE.Texture( ), * gradientMap: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * emissive: , * emissiveIntensity: * emissiveMap: new THREE.Texture( ), * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * alphaMap: new THREE.Texture( ), * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: , * morphNormals: * } */function MeshToonMaterial(parameters){Material.call(this);this.defines={'TOON':''};this.type='MeshToonMaterial';this.color=new Color(0xffffff);this.map=null;this.gradientMap=null;this.lightMap=null;this.lightMapIntensity=1.0;this.aoMap=null;this.aoMapIntensity=1.0;this.emissive=new Color(0x000000);this.emissiveIntensity=1.0;this.emissiveMap=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.alphaMap=null;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap='round';this.wireframeLinejoin='round';this.skinning=false;this.morphTargets=false;this.morphNormals=false;this.setValues(parameters);}MeshToonMaterial.prototype=Object.create(Material.prototype);MeshToonMaterial.prototype.constructor=MeshToonMaterial;MeshToonMaterial.prototype.isMeshToonMaterial=true;MeshToonMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);this.map=source.map;this.gradientMap=source.gradientMap;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.normalMapType=source.normalMapType;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.alphaMap=source.alphaMap;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;};/** * parameters = { * opacity: , * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * wireframe: , * wireframeLinewidth: * * skinning: , * morphTargets: , * morphNormals: * } */function MeshNormalMaterial(parameters){Material.call(this);this.type='MeshNormalMaterial';this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;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.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.normalMapType=source.normalMapType;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;};/** * parameters = { * color: , * opacity: , * * map: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * emissive: , * emissiveIntensity: * emissiveMap: new THREE.Texture( ), * * specularMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), * combine: THREE.Multiply, * reflectivity: , * refractionRatio: , * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: , * morphNormals: * } */function MeshLambertMaterial(parameters){Material.call(this);this.type='MeshLambertMaterial';this.color=new Color(0xffffff);// diffuse this.map=null;this.lightMap=null;this.lightMapIntensity=1.0;this.aoMap=null;this.aoMapIntensity=1.0;this.emissive=new Color(0x000000);this.emissiveIntensity=1.0;this.emissiveMap=null;this.specularMap=null;this.alphaMap=null;this.envMap=null;this.combine=MultiplyOperation;this.reflectivity=1;this.refractionRatio=0.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;};/** * parameters = { * color: , * opacity: , * * matcap: new THREE.Texture( ), * * map: new THREE.Texture( ), * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * alphaMap: new THREE.Texture( ), * * skinning: , * morphTargets: , * morphNormals: * } */function MeshMatcapMaterial(parameters){Material.call(this);this.defines={'MATCAP':''};this.type='MeshMatcapMaterial';this.color=new Color(0xffffff);// diffuse this.matcap=null;this.map=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.alphaMap=null;this.skinning=false;this.morphTargets=false;this.morphNormals=false;this.setValues(parameters);}MeshMatcapMaterial.prototype=Object.create(Material.prototype);MeshMatcapMaterial.prototype.constructor=MeshMatcapMaterial;MeshMatcapMaterial.prototype.isMeshMatcapMaterial=true;MeshMatcapMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.defines={'MATCAP':''};this.color.copy(source.color);this.matcap=source.matcap;this.map=source.map;this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalMapType=source.normalMapType;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.alphaMap=source.alphaMap;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.morphNormals=source.morphNormals;return this;};/** * parameters = { * color: , * opacity: , * * linewidth: , * * scale: , * dashSize: , * gapSize: * } */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=/*#__PURE__*/Object.freeze({__proto__:null,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,MeshMatcapMaterial:MeshMatcapMaterial,LineDashedMaterial:LineDashedMaterial,LineBasicMaterial:LineBasicMaterial,Material:Material});var AnimationUtils={// same as Array.prototype.slice, but also works on typed arrays arraySlice:function arraySlice(array,from,to){if(AnimationUtils.isTypedArray(array)){// in ios9 array.subarray(from, undefined) will return empty array // but array.subarray(from) or array.subarray(from, len) is correct return new array.constructor(array.subarray(from,to!==undefined?to:array.length));}return array.slice(from,to);},// converts an array to a specific type convertArray:function convertArray(array,type,forceClone){if(!array||// let 'undefined' and 'null' pass !forceClone&&array.constructor===type)return array;if(typeof type.BYTES_PER_ELEMENT==='number'){return new type(array);// create typed array }return Array.prototype.slice.call(array);// create Array },isTypedArray:function isTypedArray(object){return ArrayBuffer.isView(object)&&!(object instanceof DataView);},// returns an array by which times and values can be sorted getKeyframeOrder:function getKeyframeOrder(times){function compareTime(i,j){return times[i]-times[j];}var n=times.length;var result=new Array(n);for(var _i242=0;_i242!==n;++_i242)result[_i242]=_i242;result.sort(compareTime);return result;},// uses the array previously returned by 'getKeyframeOrder' to sort data sortedArray:function sortedArray(values,stride,order){var nValues=values.length;var result=new values.constructor(nValues);for(var _i243=0,dstOffset=0;dstOffset!==nValues;++_i243){var srcOffset=order[_i243]*stride;for(var j=0;j!==stride;++j){result[dstOffset++]=values[srcOffset+j];}}return result;},// function for parsing AOS keyframe formats flattenJSON:function flattenJSON(jsonKeys,times,values,valuePropertyName){var i=1,key=jsonKeys[0];while(key!==undefined&&key[valuePropertyName]===undefined){key=jsonKeys[i++];}if(key===undefined)return;// no data var value=key[valuePropertyName];if(value===undefined)return;// no data if(Array.isArray(value)){do{value=key[valuePropertyName];if(value!==undefined){times.push(key.time);values.push.apply(values,value);// push all elements }key=jsonKeys[i++];}while(key!==undefined);}else if(value.toArray!==undefined){// ...assume THREE.Math-ish do{value=key[valuePropertyName];if(value!==undefined){times.push(key.time);value.toArray(values,values.length);}key=jsonKeys[i++];}while(key!==undefined);}else {// otherwise push as-is do{value=key[valuePropertyName];if(value!==undefined){times.push(key.time);values.push(value);}key=jsonKeys[i++];}while(key!==undefined);}},subclip:function subclip(sourceClip,name,startFrame,endFrame){var fps=arguments.length>4&&arguments[4]!==undefined?arguments[4]:30;var clip=sourceClip.clone();clip.name=name;var tracks=[];for(var _i244=0;_i244=endFrame)continue;times.push(track.times[j]);for(var k=0;kclip.tracks[_i245].times[0]){minStartTime=clip.tracks[_i245].times[0];}}// shift all tracks such that clip begins at t=0 for(var _i246=0;_i2461&&arguments[1]!==undefined?arguments[1]:0;var referenceClip=arguments.length>2&&arguments[2]!==undefined?arguments[2]:targetClip;var fps=arguments.length>3&&arguments[3]!==undefined?arguments[3]:30;if(fps<=0)fps=30;var numTracks=referenceClip.tracks.length;var referenceTime=referenceFrame/fps;// Make each track's values relative to the values at the reference frame var _loop=function _loop(){var referenceTrack=referenceClip.tracks[_i247];var referenceTrackType=referenceTrack.ValueTypeName;// Skip this track if it's non-numeric if(referenceTrackType==='bool'||referenceTrackType==='string')return 0;// continue // Find the track in the target clip whose name and type matches the reference track var targetTrack=targetClip.tracks.find(function(track){return track.name===referenceTrack.name&&track.ValueTypeName===referenceTrackType;});if(targetTrack===undefined)return 0;// continue var referenceOffset=0;var referenceValueSize=referenceTrack.getValueSize();if(referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline){referenceOffset=referenceValueSize/3;}var targetOffset=0;var targetValueSize=targetTrack.getValueSize();if(targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline){targetOffset=targetValueSize/3;}var lastIndex=referenceTrack.times.length-1;var referenceValue;// Find the value to subtract out of the track if(referenceTime<=referenceTrack.times[0]){// Reference frame is earlier than the first keyframe, so just use the first keyframe var startIndex=referenceOffset;var endIndex=referenceValueSize-referenceOffset;referenceValue=AnimationUtils.arraySlice(referenceTrack.values,startIndex,endIndex);}else if(referenceTime>=referenceTrack.times[lastIndex]){// Reference frame is after the last keyframe, so just use the last keyframe var _startIndex=lastIndex*referenceValueSize+referenceOffset;var _endIndex=_startIndex+referenceValueSize-referenceOffset;referenceValue=AnimationUtils.arraySlice(referenceTrack.values,_startIndex,_endIndex);}else {// Interpolate to the reference value var interpolant=referenceTrack.createInterpolant();var _startIndex2=referenceOffset;var _endIndex2=referenceValueSize-referenceOffset;interpolant.evaluate(referenceTime);referenceValue=AnimationUtils.arraySlice(interpolant.resultBuffer,_startIndex2,_endIndex2);}// Conjugate the quaternion if(referenceTrackType==='quaternion'){var referenceQuat=new Quaternion().fromArray(referenceValue).normalize().conjugate();referenceQuat.toArray(referenceValue);}// Subtract the reference value from all of the track values var numTimes=targetTrack.times.length;for(var j=0;j= t1 || t1 === undefined ) { forward_scan:if(!(t=t0)){// looping? var t1global=pp[1];if(t=t0){// we have arrived at the sought interval break seek;}}// prepare binary search on the left side of the index right=i1;i1=0;break linear_scan;}// the interval is valid break validate_interval;}// linear scan // binary search while(i1>>1;if(t seconds conversions) scale:function scale(timeScale){if(timeScale!==1.0){var times=this.times;for(var _i252=0,n=times.length;_i252!==n;++_i252){times[_i252]*=timeScale;}}return this;},// removes keyframes before and after animation without changing any values within the range [startTime, endTime]. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values trim:function trim(startTime,endTime){var times=this.times,nKeys=times.length;var from=0,to=nKeys-1;while(from!==nKeys&×[from]endTime){--to;}++to;// inclusive -> exclusive bound if(from!==0||to!==nKeys){// empty tracks are forbidden, so keep at least one keyframe 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;},// ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable validate:function validate(){var valid=true;var valueSize=this.getValueSize();if(valueSize-Math.floor(valueSize)!==0){console.error('THREE.KeyframeTrack: Invalid value size in track.',this);valid=false;}var times=this.times,values=this.values,nKeys=times.length;if(nKeys===0){console.error('THREE.KeyframeTrack: Track is empty.',this);valid=false;}var prevTime=null;for(var _i253=0;_i253!==nKeys;_i253++){var currTime=times[_i253];if(typeof currTime==='number'&&isNaN(currTime)){console.error('THREE.KeyframeTrack: Time is not a valid number.',this,_i253,currTime);valid=false;break;}if(prevTime!==null&&prevTime>currTime){console.error('THREE.KeyframeTrack: Out of order keys.',this,_i253,currTime,prevTime);valid=false;break;}prevTime=currTime;}if(values!==undefined){if(AnimationUtils.isTypedArray(values)){for(var _i254=0,n=values.length;_i254!==n;++_i254){var value=values[_i254];if(isNaN(value)){console.error('THREE.KeyframeTrack: Value is not a valid number.',this,_i254,value);valid=false;break;}}}}return valid;},// removes equivalent sequential keys as common in morph target sequences // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0) optimize:function optimize(){// times or values may be shared with other tracks, so overwriting is unsafe var times=AnimationUtils.arraySlice(this.times),values=AnimationUtils.arraySlice(this.values),stride=this.getValueSize(),smoothInterpolation=this.getInterpolation()===InterpolateSmooth,lastIndex=times.length-1;var writeIndex=1;for(var _i255=1;_i2550){times[writeIndex]=times[lastIndex];for(var _readOffset=lastIndex*stride,_writeOffset=writeIndex*stride,_j23=0;_j23!==stride;++_j23){values[_writeOffset+_j23]=values[_readOffset+_j23];}++writeIndex;}if(writeIndex!==times.length){this.times=AnimationUtils.arraySlice(times,0,writeIndex);this.values=AnimationUtils.arraySlice(values,0,writeIndex*stride);}else {this.times=times;this.values=values;}return this;},clone:function clone(){var times=AnimationUtils.arraySlice(this.times,0);var values=AnimationUtils.arraySlice(this.values,0);var TypedKeyframeTrack=this.constructor;var track=new TypedKeyframeTrack(this.name,times,values);// Interpolant argument to constructor is not saved, so copy the factory method directly. track.createInterpolant=this.createInterpolant;return track;}});/** * A Track of Boolean keyframe values. */function BooleanKeyframeTrack(name,times,values){KeyframeTrack.call(this,name,times,values);}BooleanKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrack.prototype),{constructor:BooleanKeyframeTrack,ValueTypeName:'bool',ValueBufferType:Array,DefaultInterpolation:InterpolateDiscrete,InterpolantFactoryMethodLinear:undefined,InterpolantFactoryMethodSmooth:undefined// Note: Actually this track could have a optimized / compressed // representation of a single value and a custom interpolant that // computes "firstValue ^ isOdd( index )". });/** * A Track of keyframe values that represent color. */function ColorKeyframeTrack(name,times,values,interpolation){KeyframeTrack.call(this,name,times,values,interpolation);}ColorKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrack.prototype),{constructor:ColorKeyframeTrack,ValueTypeName:'color'// ValueBufferType is inherited // DefaultInterpolation is inherited // Note: Very basic implementation and nothing special yet. // However, this is the place for color space parameterization. });/** * A Track of numeric keyframe values. */function NumberKeyframeTrack(name,times,values,interpolation){KeyframeTrack.call(this,name,times,values,interpolation);}NumberKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrack.prototype),{constructor:NumberKeyframeTrack,ValueTypeName:'number'// ValueBufferType is inherited // DefaultInterpolation is inherited });/** * Spherical linear unit quaternion interpolant. */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 interpolate_(i1,t0,t,t1){var result=this.resultBuffer,values=this.sampleValues,stride=this.valueSize,alpha=(t-t0)/(t1-t0);var offset=i1*stride;for(var end=offset+stride;offset!==end;offset+=4){Quaternion.slerpFlat(result,0,values,offset-stride,values,offset,alpha);}return result;}});/** * A Track of quaternion keyframe values. */function QuaternionKeyframeTrack(name,times,values,interpolation){KeyframeTrack.call(this,name,times,values,interpolation);}QuaternionKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrack.prototype),{constructor:QuaternionKeyframeTrack,ValueTypeName:'quaternion',// ValueBufferType is inherited DefaultInterpolation:InterpolateLinear,InterpolantFactoryMethodLinear:function InterpolantFactoryMethodLinear(result){return new QuaternionLinearInterpolant(this.times,this.values,this.getValueSize(),result);},InterpolantFactoryMethodSmooth:undefined// not yet implemented });/** * A Track that interpolates Strings */function StringKeyframeTrack(name,times,values,interpolation){KeyframeTrack.call(this,name,times,values,interpolation);}StringKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrack.prototype),{constructor:StringKeyframeTrack,ValueTypeName:'string',ValueBufferType:Array,DefaultInterpolation:InterpolateDiscrete,InterpolantFactoryMethodLinear:undefined,InterpolantFactoryMethodSmooth:undefined});/** * A Track of vectored keyframe values. */function VectorKeyframeTrack(name,times,values,interpolation){KeyframeTrack.call(this,name,times,values,interpolation);}VectorKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrack.prototype),{constructor:VectorKeyframeTrack,ValueTypeName:'vector'// ValueBufferType is inherited // DefaultInterpolation is inherited });function AnimationClip(name){var duration=arguments.length>1&&arguments[1]!==undefined?arguments[1]:-1;var tracks=arguments.length>2?arguments[2]:undefined;var blendMode=arguments.length>3&&arguments[3]!==undefined?arguments[3]:NormalAnimationBlendMode;this.name=name;this.tracks=tracks;this.duration=duration;this.blendMode=blendMode;this.uuid=MathUtils.generateUUID();// this means it should figure out its duration by scanning the tracks if(this.duration<0){this.resetDuration();}}function getTrackTypeForValueTypeName(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('THREE.KeyframeTrack: Unsupported typeName: '+typeName);}function parseKeyframeTrack(json){if(json.type===undefined){throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');}var trackType=getTrackTypeForValueTypeName(json.type);if(json.times===undefined){var times=[],values=[];AnimationUtils.flattenJSON(json.keys,times,values,'value');json.times=times;json.values=values;}// derived classes can define a static parse method if(trackType.parse!==undefined){return trackType.parse(json);}else {// by default, we assume a constructor compatible with the base return new trackType(json.name,json.times,json.values,json.interpolation);}}Object.assign(AnimationClip,{parse:function parse(json){var tracks=[],jsonTracks=json.tracks,frameTime=1.0/(json.fps||1.0);for(var _i256=0,n=jsonTracks.length;_i256!==n;++_i256){tracks.push(parseKeyframeTrack(jsonTracks[_i256]).scale(frameTime));}var clip=new AnimationClip(json.name,json.duration,tracks,json.blendMode);clip.uuid=json.uuid;return clip;},toJSON:function toJSON(clip){var tracks=[],clipTracks=clip.tracks;var json={'name':clip.name,'duration':clip.duration,'tracks':tracks,'uuid':clip.uuid,'blendMode':clip.blendMode};for(var _i257=0,n=clipTracks.length;_i257!==n;++_i257){tracks.push(KeyframeTrack.toJSON(clipTracks[_i257]));}return json;},CreateFromMorphTargetSequence:function CreateFromMorphTargetSequence(name,morphTargetSequence,fps,noLoop){var numMorphTargets=morphTargetSequence.length;var tracks=[];for(var _i258=0;_i2581){var name=parts[1];var animationMorphTargets=animationToMorphTargets[name];if(!animationMorphTargets){animationToMorphTargets[name]=animationMorphTargets=[];}animationMorphTargets.push(morphTarget);}}var clips=[];for(var _name4 in animationToMorphTargets){clips.push(AnimationClip.CreateFromMorphTargetSequence(_name4,animationToMorphTargets[_name4],fps,noLoop));}return clips;},// parse the animation.hierarchy format parseAnimation:function parseAnimation(animation,bones){if(!animation){console.error('THREE.AnimationClip: No animation in JSONLoader data.');return null;}var addNonemptyTrack=function addNonemptyTrack(trackType,trackName,animationKeys,propertyName,destTracks){// only return track if there are actually keys. if(animationKeys.length!==0){var times=[];var values=[];AnimationUtils.flattenJSON(animationKeys,times,values,propertyName);// empty keys are filtered out, so check again if(times.length!==0){destTracks.push(new trackType(trackName,times,values));}}};var tracks=[];var clipName=animation.name||'default';var fps=animation.fps||30;var blendMode=animation.blendMode;// automatic length determination in AnimationClip. var duration=animation.length||-1;var hierarchyTracks=animation.hierarchy||[];for(var h=0;h0||url.search(/^data\:image\/jpeg/)===0;texture.format=isJPEG?RGBFormat:RGBAFormat;texture.needsUpdate=true;if(onLoad!==undefined){onLoad(texture);}},onProgress,onError);return texture;}});/** * Extensible curve object. * * Some common of curve methods: * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget ) * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget ) * .getPoints(), .getSpacedPoints() * .getLength() * .updateArcLengths() * * This following curves inherit from THREE.Curve: * * -- 2D curves -- * THREE.ArcCurve * THREE.CubicBezierCurve * THREE.EllipseCurve * THREE.LineCurve * THREE.QuadraticBezierCurve * THREE.SplineCurve * * -- 3D curves -- * THREE.CatmullRomCurve3 * THREE.CubicBezierCurve3 * THREE.LineCurve3 * THREE.QuadraticBezierCurve3 * * A series of curves can be represented as a THREE.CurvePath. * **/function Curve(){this.type='Curve';this.arcLengthDivisions=200;}Object.assign(Curve.prototype,{// Virtual base class method to overwrite and implement in subclasses // - t [0 .. 1] getPoint:function getPoint(/* t, optionalTarget */){console.warn('THREE.Curve: .getPoint() not implemented.');return null;},// Get point at relative position in curve according to arc length // - u [0 .. 1] getPointAt:function getPointAt(u,optionalTarget){var t=this.getUtoTmapping(u);return this.getPoint(t,optionalTarget);},// Get sequence of points using getPoint( t ) getPoints:function getPoints(){var divisions=arguments.length>0&&arguments[0]!==undefined?arguments[0]:5;var points=[];for(var d=0;d<=divisions;d++){points.push(this.getPoint(d/divisions));}return points;},// Get sequence of points using getPointAt( u ) getSpacedPoints:function getSpacedPoints(){var divisions=arguments.length>0&&arguments[0]!==undefined?arguments[0]:5;var points=[];for(var d=0;d<=divisions;d++){points.push(this.getPointAt(d/divisions));}return points;},// Get total curve arc length getLength:function getLength(){var lengths=this.getLengths();return lengths[lengths.length-1];},// Get list of cumulative segment lengths getLengths:function getLengths(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 sum=0;cache.push(0);for(var p=1;p<=divisions;p++){current=this.getPoint(p/divisions);sum+=current.distanceTo(last);cache.push(sum);last=current;}this.cacheArcLengths=cache;return cache;// { sums: cache, sum: sum }; Sum is in the last element. },updateArcLengths:function updateArcLengths(){this.needsUpdate=true;this.getLengths();},// Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant getUtoTmapping:function getUtoTmapping(u,distance){var arcLengths=this.getLengths();var i=0;var il=arcLengths.length;var targetArcLength;// The targeted u distance value to get if(distance){targetArcLength=distance;}else {targetArcLength=u*arcLengths[il-1];}// binary search for the index with largest value smaller than target u distance var low=0,high=il-1,comparison;while(low<=high){i=Math.floor(low+(high-low)/2);// less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats comparison=arcLengths[i]-targetArcLength;if(comparison<0){low=i+1;}else if(comparison>0){high=i-1;}else {high=i;break;// DONE }}i=high;if(arcLengths[i]===targetArcLength){return i/(il-1);}// we could get finer grain at lengths, or use simple interpolation between two points var lengthBefore=arcLengths[i];var lengthAfter=arcLengths[i+1];var segmentLength=lengthAfter-lengthBefore;// determine where we are between the 'before' and 'after' points var segmentFraction=(targetArcLength-lengthBefore)/segmentLength;// add that fractional amount to t var t=(i+segmentFraction)/(il-1);return t;},// Returns a unit vector tangent at t // In case any sub curve does not implement its tangent derivation, // 2 points a small delta apart will be used to find its gradient // which seems to give a reasonable approximation getTangent:function getTangent(t,optionalTarget){var delta=0.0001;var t1=t-delta;var t2=t+delta;// Capping in case of danger if(t1<0)t1=0;if(t2>1)t2=1;var pt1=this.getPoint(t1);var pt2=this.getPoint(t2);var tangent=optionalTarget||(pt1.isVector2?new Vector2():new Vector3());tangent.copy(pt2).sub(pt1).normalize();return tangent;},getTangentAt:function getTangentAt(u,optionalTarget){var t=this.getUtoTmapping(u);return this.getTangent(t,optionalTarget);},computeFrenetFrames:function computeFrenetFrames(segments,closed){// see http://www.cs.indiana.edu/pub/techreports/TR425.pdf var normal=new Vector3();var tangents=[];var normals=[];var binormals=[];var vec=new Vector3();var mat=new Matrix4();// compute the tangent vectors for each segment on the curve for(var _i277=0;_i277<=segments;_i277++){var u=_i277/segments;tangents[_i277]=this.getTangentAt(u,new Vector3());tangents[_i277].normalize();}// select an initial normal vector perpendicular to the first tangent vector, // and in the direction of the minimum tangent xyz component 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]);// compute the slowly-varying normal and binormal vectors for each segment on the curve for(var _i278=1;_i278<=segments;_i278++){normals[_i278]=normals[_i278-1].clone();binormals[_i278]=binormals[_i278-1].clone();vec.crossVectors(tangents[_i278-1],tangents[_i278]);if(vec.length()>Number.EPSILON){vec.normalize();var theta=Math.acos(MathUtils.clamp(tangents[_i278-1].dot(tangents[_i278]),-1,1));// clamp for floating pt errors normals[_i278].applyMatrix4(mat.makeRotationAxis(vec,theta));}binormals[_i278].crossVectors(tangents[_i278],normals[_i278]);}// if the curve is closed, postprocess the vectors so the first and last normal vectors are the same if(closed===true){var _theta=Math.acos(MathUtils.clamp(normals[0].dot(normals[segments]),-1,1));_theta/=segments;if(tangents[0].dot(vec.crossVectors(normals[0],normals[segments]))>0){_theta=-_theta;}for(var _i279=1;_i279<=segments;_i279++){// twist a little... normals[_i279].applyMatrix4(mat.makeRotationAxis(tangents[_i279],_theta*_i279));binormals[_i279].crossVectors(tangents[_i279],normals[_i279]);}}return {tangents:tangents,normals:normals,binormals:binormals};},clone:function clone(){return new this.constructor().copy(this);},copy:function copy(source){this.arcLengthDivisions=source.arcLengthDivisions;return this;},toJSON:function toJSON(){var data={metadata:{version:4.5,type:'Curve',generator:'Curve.toJSON'}};data.arcLengthDivisions=this.arcLengthDivisions;data.type=this.type;return data;},fromJSON:function fromJSON(json){this.arcLengthDivisions=json.arcLengthDivisions;return this;}});function EllipseCurve(aX,aY,xRadius,yRadius,aStartAngle,aEndAngle,aClockwise,aRotation){Curve.call(this);this.type='EllipseCurve';this.aX=aX||0;this.aY=aY||0;this.xRadius=xRadius||1;this.yRadius=yRadius||1;this.aStartAngle=aStartAngle||0;this.aEndAngle=aEndAngle||2*Math.PI;this.aClockwise=aClockwise||false;this.aRotation=aRotation||0;}EllipseCurve.prototype=Object.create(Curve.prototype);EllipseCurve.prototype.constructor=EllipseCurve;EllipseCurve.prototype.isEllipseCurve=true;EllipseCurve.prototype.getPoint=function(t,optionalTarget){var point=optionalTarget||new Vector2();var twoPi=Math.PI*2;var deltaAngle=this.aEndAngle-this.aStartAngle;var samePoints=Math.abs(deltaAngle)twoPi)deltaAngle-=twoPi;if(deltaAngle0&&arguments[0]!==undefined?arguments[0]:[];var closed=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var curveType=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'centripetal';var tension=arguments.length>3&&arguments[3]!==undefined?arguments[3]:0.5;Curve.call(this);this.type='CatmullRomCurve3';this.points=points;this.closed=closed;this.curveType=curveType;this.tension=tension;}CatmullRomCurve3.prototype=Object.create(Curve.prototype);CatmullRomCurve3.prototype.constructor=CatmullRomCurve3;CatmullRomCurve3.prototype.isCatmullRomCurve3=true;CatmullRomCurve3.prototype.getPoint=function(t){var optionalTarget=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector3();var point=optionalTarget;var points=this.points;var l=points.length;var p=(l-(this.closed?0:1))*t;var intPoint=Math.floor(p);var weight=p-intPoint;if(this.closed){intPoint+=intPoint>0?0:(Math.floor(Math.abs(intPoint)/l)+1)*l;}else if(weight===0&&intPoint===l-1){intPoint=l-2;weight=1;}var p0,p3;// 4 points (p1 & p2 defined below) if(this.closed||intPoint>0){p0=points[(intPoint-1)%l];}else {// extrapolate first point tmp.subVectors(points[0],points[1]).add(points[0]);p0=tmp;}var p1=points[intPoint%l];var p2=points[(intPoint+1)%l];if(this.closed||intPoint+20&&arguments[0]!==undefined?arguments[0]:new Vector2();var v1=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector2();var v2=arguments.length>2&&arguments[2]!==undefined?arguments[2]:new Vector2();var v3=arguments.length>3&&arguments[3]!==undefined?arguments[3]:new Vector2();Curve.call(this);this.type='CubicBezierCurve';this.v0=v0;this.v1=v1;this.v2=v2;this.v3=v3;}CubicBezierCurve.prototype=Object.create(Curve.prototype);CubicBezierCurve.prototype.constructor=CubicBezierCurve;CubicBezierCurve.prototype.isCubicBezierCurve=true;CubicBezierCurve.prototype.getPoint=function(t){var optionalTarget=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector2();var point=optionalTarget;var v0=this.v0,v1=this.v1,v2=this.v2,v3=this.v3;point.set(CubicBezier(t,v0.x,v1.x,v2.x,v3.x),CubicBezier(t,v0.y,v1.y,v2.y,v3.y));return point;};CubicBezierCurve.prototype.copy=function(source){Curve.prototype.copy.call(this,source);this.v0.copy(source.v0);this.v1.copy(source.v1);this.v2.copy(source.v2);this.v3.copy(source.v3);return this;};CubicBezierCurve.prototype.toJSON=function(){var data=Curve.prototype.toJSON.call(this);data.v0=this.v0.toArray();data.v1=this.v1.toArray();data.v2=this.v2.toArray();data.v3=this.v3.toArray();return data;};CubicBezierCurve.prototype.fromJSON=function(json){Curve.prototype.fromJSON.call(this,json);this.v0.fromArray(json.v0);this.v1.fromArray(json.v1);this.v2.fromArray(json.v2);this.v3.fromArray(json.v3);return this;};function CubicBezierCurve3(){var v0=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new Vector3();var v1=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector3();var v2=arguments.length>2&&arguments[2]!==undefined?arguments[2]:new Vector3();var v3=arguments.length>3&&arguments[3]!==undefined?arguments[3]:new Vector3();Curve.call(this);this.type='CubicBezierCurve3';this.v0=v0;this.v1=v1;this.v2=v2;this.v3=v3;}CubicBezierCurve3.prototype=Object.create(Curve.prototype);CubicBezierCurve3.prototype.constructor=CubicBezierCurve3;CubicBezierCurve3.prototype.isCubicBezierCurve3=true;CubicBezierCurve3.prototype.getPoint=function(t){var optionalTarget=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector3();var point=optionalTarget;var v0=this.v0,v1=this.v1,v2=this.v2,v3=this.v3;point.set(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));return point;};CubicBezierCurve3.prototype.copy=function(source){Curve.prototype.copy.call(this,source);this.v0.copy(source.v0);this.v1.copy(source.v1);this.v2.copy(source.v2);this.v3.copy(source.v3);return this;};CubicBezierCurve3.prototype.toJSON=function(){var data=Curve.prototype.toJSON.call(this);data.v0=this.v0.toArray();data.v1=this.v1.toArray();data.v2=this.v2.toArray();data.v3=this.v3.toArray();return data;};CubicBezierCurve3.prototype.fromJSON=function(json){Curve.prototype.fromJSON.call(this,json);this.v0.fromArray(json.v0);this.v1.fromArray(json.v1);this.v2.fromArray(json.v2);this.v3.fromArray(json.v3);return this;};function LineCurve(){var v1=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new Vector2();var v2=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector2();Curve.call(this);this.type='LineCurve';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){var optionalTarget=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector2();var point=optionalTarget;if(t===1){point.copy(this.v2);}else {point.copy(this.v2).sub(this.v1);point.multiplyScalar(t).add(this.v1);}return point;};// Line curve is linear, so we can overwrite default getPointAt LineCurve.prototype.getPointAt=function(u,optionalTarget){return this.getPoint(u,optionalTarget);};LineCurve.prototype.getTangent=function(t,optionalTarget){var tangent=optionalTarget||new Vector2();tangent.copy(this.v2).sub(this.v1).normalize();return tangent;};LineCurve.prototype.copy=function(source){Curve.prototype.copy.call(this,source);this.v1.copy(source.v1);this.v2.copy(source.v2);return this;};LineCurve.prototype.toJSON=function(){var data=Curve.prototype.toJSON.call(this);data.v1=this.v1.toArray();data.v2=this.v2.toArray();return data;};LineCurve.prototype.fromJSON=function(json){Curve.prototype.fromJSON.call(this,json);this.v1.fromArray(json.v1);this.v2.fromArray(json.v2);return this;};function LineCurve3(){var v1=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new Vector3();var v2=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector3();Curve.call(this);this.type='LineCurve3';this.v1=v1;this.v2=v2;}LineCurve3.prototype=Object.create(Curve.prototype);LineCurve3.prototype.constructor=LineCurve3;LineCurve3.prototype.isLineCurve3=true;LineCurve3.prototype.getPoint=function(t){var optionalTarget=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector3();var point=optionalTarget;if(t===1){point.copy(this.v2);}else {point.copy(this.v2).sub(this.v1);point.multiplyScalar(t).add(this.v1);}return point;};// Line curve is linear, so we can overwrite default getPointAt LineCurve3.prototype.getPointAt=function(u,optionalTarget){return this.getPoint(u,optionalTarget);};LineCurve3.prototype.copy=function(source){Curve.prototype.copy.call(this,source);this.v1.copy(source.v1);this.v2.copy(source.v2);return this;};LineCurve3.prototype.toJSON=function(){var data=Curve.prototype.toJSON.call(this);data.v1=this.v1.toArray();data.v2=this.v2.toArray();return data;};LineCurve3.prototype.fromJSON=function(json){Curve.prototype.fromJSON.call(this,json);this.v1.fromArray(json.v1);this.v2.fromArray(json.v2);return this;};function QuadraticBezierCurve(){var v0=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new Vector2();var v1=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector2();var v2=arguments.length>2&&arguments[2]!==undefined?arguments[2]:new Vector2();Curve.call(this);this.type='QuadraticBezierCurve';this.v0=v0;this.v1=v1;this.v2=v2;}QuadraticBezierCurve.prototype=Object.create(Curve.prototype);QuadraticBezierCurve.prototype.constructor=QuadraticBezierCurve;QuadraticBezierCurve.prototype.isQuadraticBezierCurve=true;QuadraticBezierCurve.prototype.getPoint=function(t){var optionalTarget=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector2();var point=optionalTarget;var v0=this.v0,v1=this.v1,v2=this.v2;point.set(QuadraticBezier(t,v0.x,v1.x,v2.x),QuadraticBezier(t,v0.y,v1.y,v2.y));return point;};QuadraticBezierCurve.prototype.copy=function(source){Curve.prototype.copy.call(this,source);this.v0.copy(source.v0);this.v1.copy(source.v1);this.v2.copy(source.v2);return this;};QuadraticBezierCurve.prototype.toJSON=function(){var data=Curve.prototype.toJSON.call(this);data.v0=this.v0.toArray();data.v1=this.v1.toArray();data.v2=this.v2.toArray();return data;};QuadraticBezierCurve.prototype.fromJSON=function(json){Curve.prototype.fromJSON.call(this,json);this.v0.fromArray(json.v0);this.v1.fromArray(json.v1);this.v2.fromArray(json.v2);return this;};function QuadraticBezierCurve3(){var v0=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new Vector3();var v1=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector3();var v2=arguments.length>2&&arguments[2]!==undefined?arguments[2]:new Vector3();Curve.call(this);this.type='QuadraticBezierCurve3';this.v0=v0;this.v1=v1;this.v2=v2;}QuadraticBezierCurve3.prototype=Object.create(Curve.prototype);QuadraticBezierCurve3.prototype.constructor=QuadraticBezierCurve3;QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3=true;QuadraticBezierCurve3.prototype.getPoint=function(t){var optionalTarget=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector3();var point=optionalTarget;var v0=this.v0,v1=this.v1,v2=this.v2;point.set(QuadraticBezier(t,v0.x,v1.x,v2.x),QuadraticBezier(t,v0.y,v1.y,v2.y),QuadraticBezier(t,v0.z,v1.z,v2.z));return point;};QuadraticBezierCurve3.prototype.copy=function(source){Curve.prototype.copy.call(this,source);this.v0.copy(source.v0);this.v1.copy(source.v1);this.v2.copy(source.v2);return this;};QuadraticBezierCurve3.prototype.toJSON=function(){var data=Curve.prototype.toJSON.call(this);data.v0=this.v0.toArray();data.v1=this.v1.toArray();data.v2=this.v2.toArray();return data;};QuadraticBezierCurve3.prototype.fromJSON=function(json){Curve.prototype.fromJSON.call(this,json);this.v0.fromArray(json.v0);this.v1.fromArray(json.v1);this.v2.fromArray(json.v2);return this;};function SplineCurve(){var points=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];Curve.call(this);this.type='SplineCurve';this.points=points;}SplineCurve.prototype=Object.create(Curve.prototype);SplineCurve.prototype.constructor=SplineCurve;SplineCurve.prototype.isSplineCurve=true;SplineCurve.prototype.getPoint=function(t){var optionalTarget=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector2();var point=optionalTarget;var points=this.points;var p=(points.length-1)*t;var intPoint=Math.floor(p);var weight=p-intPoint;var p0=points[intPoint===0?intPoint:intPoint-1];var p1=points[intPoint];var p2=points[intPoint>points.length-2?points.length-1:intPoint+1];var p3=points[intPoint>points.length-3?points.length-1:intPoint+2];point.set(CatmullRom(weight,p0.x,p1.x,p2.x,p3.x),CatmullRom(weight,p0.y,p1.y,p2.y,p3.y));return point;};SplineCurve.prototype.copy=function(source){Curve.prototype.copy.call(this,source);this.points=[];for(var _i283=0,l=source.points.length;_i283=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;// loop where sum != 0, sum > d , sum+1 0&&arguments[0]!==undefined?arguments[0]:40;var points=[];for(var _i287=0;_i287<=divisions;_i287++){points.push(this.getPoint(_i287/divisions));}if(this.autoClose){points.push(points[0]);}return points;},getPoints:function getPoints(){var divisions=arguments.length>0&&arguments[0]!==undefined?arguments[0]:12;var points=[];var last;for(var _i288=0,curves=this.curves;_i2881&&!points[points.length-1].equals(points[0])){points.push(points[0]);}return points;},copy:function copy(source){Curve.prototype.copy.call(this,source);this.curves=[];for(var _i289=0,l=source.curves.length;_i2890){// if a previous curve is present, attempt to join 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);return this;},copy:function copy(source){CurvePath.prototype.copy.call(this,source);this.currentPoint.copy(source.currentPoint);return this;},toJSON:function toJSON(){var data=CurvePath.prototype.toJSON.call(this);data.currentPoint=this.currentPoint.toArray();return data;},fromJSON:function fromJSON(json){CurvePath.prototype.fromJSON.call(this,json);this.currentPoint.fromArray(json.currentPoint);return this;}});function Shape(points){Path.call(this,points);this.uuid=MathUtils.generateUUID();this.type='Shape';this.holes=[];}Shape.prototype=Object.assign(Object.create(Path.prototype),{constructor:Shape,getPointsHoles:function getPointsHoles(divisions){var holesPts=[];for(var _i293=0,l=this.holes.length;_i2931&&arguments[1]!==undefined?arguments[1]:1;Object3D.call(this);this.type='Light';this.color=new Color(color);this.intensity=intensity;}Light.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Light,isLight:true,copy:function copy(source){Object3D.prototype.copy.call(this,source);this.color.copy(source.color);this.intensity=source.intensity;return this;},toJSON:function toJSON(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.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 copy(source){Light.prototype.copy.call(this,source);this.groundColor.copy(source.groundColor);return this;}});function LightShadow(camera){this.camera=camera;this.bias=0;this.normalBias=0;this.radius=1;this.mapSize=new Vector2(512,512);this.map=null;this.mapPass=null;this.matrix=new Matrix4();this.autoUpdate=true;this.needsUpdate=false;this._frustum=new Frustum();this._frameExtents=new Vector2(1,1);this._viewportCount=1;this._viewports=[new Vector4(0,0,1,1)];}Object.assign(LightShadow.prototype,{_projScreenMatrix:new Matrix4(),_lightPositionWorld:new Vector3(),_lookTarget:new Vector3(),getViewportCount:function getViewportCount(){return this._viewportCount;},getFrustum:function getFrustum(){return this._frustum;},updateMatrices:function updateMatrices(light){var shadowCamera=this.camera,shadowMatrix=this.matrix,projScreenMatrix=this._projScreenMatrix,lookTarget=this._lookTarget,lightPositionWorld=this._lightPositionWorld;lightPositionWorld.setFromMatrixPosition(light.matrixWorld);shadowCamera.position.copy(lightPositionWorld);lookTarget.setFromMatrixPosition(light.target.matrixWorld);shadowCamera.lookAt(lookTarget);shadowCamera.updateMatrixWorld();projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix,shadowCamera.matrixWorldInverse);this._frustum.setFromProjectionMatrix(projScreenMatrix);shadowMatrix.set(0.5,0.0,0.0,0.5,0.0,0.5,0.0,0.5,0.0,0.0,0.5,0.5,0.0,0.0,0.0,1.0);shadowMatrix.multiply(shadowCamera.projectionMatrix);shadowMatrix.multiply(shadowCamera.matrixWorldInverse);},getViewport:function getViewport(viewportIndex){return this._viewports[viewportIndex];},getFrameExtents:function getFrameExtents(){return this._frameExtents;},copy:function copy(source){this.camera=source.camera.clone();this.bias=source.bias;this.radius=source.radius;this.mapSize.copy(source.mapSize);return this;},clone:function clone(){return new this.constructor().copy(this);},toJSON:function toJSON(){var object={};if(this.bias!==0)object.bias=this.bias;if(this.normalBias!==0)object.normalBias=this.normalBias;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,0.5,500));this.focus=1;}SpotLightShadow.prototype=Object.assign(Object.create(LightShadow.prototype),{constructor:SpotLightShadow,isSpotLightShadow:true,updateMatrices:function updateMatrices(light){var camera=this.camera;var fov=MathUtils.RAD2DEG*2*light.angle*this.focus;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();}LightShadow.prototype.updateMatrices.call(this,light);}});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 get(){// intensity = power per solid angle. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf return this.intensity*Math.PI;},set:function set(power){// intensity = power per solid angle. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf 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;// for physically correct lights, should be 2. this.shadow=new SpotLightShadow();}SpotLight.prototype=Object.assign(Object.create(Light.prototype),{constructor:SpotLight,isSpotLight:true,copy:function copy(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 PointLightShadow(){LightShadow.call(this,new PerspectiveCamera(90,1,0.5,500));this._frameExtents=new Vector2(4,2);this._viewportCount=6;this._viewports=[// These viewports map a cube-map onto a 2D texture with the // following orientation: // // xzXZ // y Y // // X - Positive x direction // x - Negative x direction // Y - Positive y direction // y - Negative y direction // Z - Positive z direction // z - Negative z direction // positive X new Vector4(2,1,1,1),// negative X new Vector4(0,1,1,1),// positive Z new Vector4(3,1,1,1),// negative Z new Vector4(1,1,1,1),// positive Y new Vector4(3,0,1,1),// negative Y new Vector4(1,0,1,1)];this._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)];this._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)];}PointLightShadow.prototype=Object.assign(Object.create(LightShadow.prototype),{constructor:PointLightShadow,isPointLightShadow:true,updateMatrices:function updateMatrices(light){var viewportIndex=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var camera=this.camera,shadowMatrix=this.matrix,lightPositionWorld=this._lightPositionWorld,lookTarget=this._lookTarget,projScreenMatrix=this._projScreenMatrix;lightPositionWorld.setFromMatrixPosition(light.matrixWorld);camera.position.copy(lightPositionWorld);lookTarget.copy(camera.position);lookTarget.add(this._cubeDirections[viewportIndex]);camera.up.copy(this._cubeUps[viewportIndex]);camera.lookAt(lookTarget);camera.updateMatrixWorld();shadowMatrix.makeTranslation(-lightPositionWorld.x,-lightPositionWorld.y,-lightPositionWorld.z);projScreenMatrix.multiplyMatrices(camera.projectionMatrix,camera.matrixWorldInverse);this._frustum.setFromProjectionMatrix(projScreenMatrix);}});function PointLight(color,intensity,distance,decay){Light.call(this,color,intensity);this.type='PointLight';Object.defineProperty(this,'power',{get:function get(){// intensity = power per solid angle. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf return this.intensity*4*Math.PI;},set:function set(power){// intensity = power per solid angle. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf this.intensity=power/(4*Math.PI);}});this.distance=distance!==undefined?distance:0;this.decay=decay!==undefined?decay:1;// for physically correct lights, should be 2. this.shadow=new PointLightShadow();}PointLight.prototype=Object.assign(Object.create(Light.prototype),{constructor:PointLight,isPointLight:true,copy:function copy(source){Light.prototype.copy.call(this,source);this.distance=source.distance;this.decay=source.decay;this.shadow=source.shadow.clone();return this;}});function OrthographicCamera(){var left=arguments.length>0&&arguments[0]!==undefined?arguments[0]:-1;var right=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var top=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;var bottom=arguments.length>3&&arguments[3]!==undefined?arguments[3]:-1;var near=arguments.length>4&&arguments[4]!==undefined?arguments[4]:0.1;var far=arguments.length>5&&arguments[5]!==undefined?arguments[5]:2000;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;this.far=far;this.updateProjectionMatrix();}OrthographicCamera.prototype=Object.assign(Object.create(Camera.prototype),{constructor:OrthographicCamera,isOrthographicCamera:true,copy:function copy(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 setViewOffset(fullWidth,fullHeight,x,y,width,height){if(this.view===null){this.view={enabled:true,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1};}this.view.enabled=true;this.view.fullWidth=fullWidth;this.view.fullHeight=fullHeight;this.view.offsetX=x;this.view.offsetY=y;this.view.width=width;this.view.height=height;this.updateProjectionMatrix();},clearViewOffset:function clearViewOffset(){if(this.view!==null){this.view.enabled=false;}this.updateProjectionMatrix();},updateProjectionMatrix:function updateProjectionMatrix(){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&&this.view.enabled){var scaleW=(this.right-this.left)/this.view.fullWidth/this.zoom;var scaleH=(this.top-this.bottom)/this.view.fullHeight/this.zoom;left+=scaleW*this.view.offsetX;right=left+scaleW*this.view.width;top-=scaleH*this.view.offsetY;bottom=top-scaleH*this.view.height;}this.projectionMatrix.makeOrthographic(left,right,top,bottom,this.near,this.far);this.projectionMatrixInverse.copy(this.projectionMatrix).invert();},toJSON:function toJSON(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 DirectionalLightShadow(){LightShadow.call(this,new OrthographicCamera(-5,5,5,-5,0.5,500));}DirectionalLightShadow.prototype=Object.assign(Object.create(LightShadow.prototype),{constructor:DirectionalLightShadow,isDirectionalLightShadow:true,updateMatrices:function updateMatrices(light){LightShadow.prototype.updateMatrices.call(this,light);}});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 copy(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';}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.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 copy(source){Light.prototype.copy.call(this,source);this.width=source.width;this.height=source.height;return this;},toJSON:function toJSON(meta){var data=Light.prototype.toJSON.call(this,meta);data.object.width=this.width;data.object.height=this.height;return data;}});/** * Primary reference: * https://graphics.stanford.edu/papers/envmap/envmap.pdf * * Secondary reference: * https://www.ppsloan.org/publications/StupidSH36.pdf */ // 3-band SH defined by 9 coefficients class SphericalHarmonics3{constructor(){Object.defineProperty(this,'isSphericalHarmonics3',{value:true});this.coefficients=[];for(var _i297=0;_i297<9;_i297++){this.coefficients.push(new Vector3());}}set(coefficients){for(var _i298=0;_i298<9;_i298++){this.coefficients[_i298].copy(coefficients[_i298]);}return this;}zero(){for(var _i299=0;_i299<9;_i299++){this.coefficients[_i299].set(0,0,0);}return this;}// get the radiance in the direction of the normal // target is a Vector3 getAt(normal,target){// normal is assumed to be unit length var x=normal.x,y=normal.y,z=normal.z;var coeff=this.coefficients;// band 0 target.copy(coeff[0]).multiplyScalar(0.282095);// band 1 target.addScaledVector(coeff[1],0.488603*y);target.addScaledVector(coeff[2],0.488603*z);target.addScaledVector(coeff[3],0.488603*x);// band 2 target.addScaledVector(coeff[4],1.092548*(x*y));target.addScaledVector(coeff[5],1.092548*(y*z));target.addScaledVector(coeff[6],0.315392*(3.0*z*z-1.0));target.addScaledVector(coeff[7],1.092548*(x*z));target.addScaledVector(coeff[8],0.546274*(x*x-y*y));return target;}// get the irradiance (radiance convolved with cosine lobe) in the direction of the normal // target is a Vector3 // https://graphics.stanford.edu/papers/envmap/envmap.pdf getIrradianceAt(normal,target){// normal is assumed to be unit length var x=normal.x,y=normal.y,z=normal.z;var coeff=this.coefficients;// band 0 target.copy(coeff[0]).multiplyScalar(0.886227);// π * 0.282095 // band 1 target.addScaledVector(coeff[1],2.0*0.511664*y);// ( 2 * π / 3 ) * 0.488603 target.addScaledVector(coeff[2],2.0*0.511664*z);target.addScaledVector(coeff[3],2.0*0.511664*x);// band 2 target.addScaledVector(coeff[4],2.0*0.429043*x*y);// ( π / 4 ) * 1.092548 target.addScaledVector(coeff[5],2.0*0.429043*y*z);target.addScaledVector(coeff[6],0.743125*z*z-0.247708);// ( π / 4 ) * 0.315392 * 3 target.addScaledVector(coeff[7],2.0*0.429043*x*z);target.addScaledVector(coeff[8],0.429043*(x*x-y*y));// ( π / 4 ) * 0.546274 return target;}add(sh){for(var _i300=0;_i300<9;_i300++){this.coefficients[_i300].add(sh.coefficients[_i300]);}return this;}addScaledSH(sh,s){for(var _i301=0;_i301<9;_i301++){this.coefficients[_i301].addScaledVector(sh.coefficients[_i301],s);}return this;}scale(s){for(var _i302=0;_i302<9;_i302++){this.coefficients[_i302].multiplyScalar(s);}return this;}lerp(sh,alpha){for(var _i303=0;_i303<9;_i303++){this.coefficients[_i303].lerp(sh.coefficients[_i303],alpha);}return this;}equals(sh){for(var _i304=0;_i304<9;_i304++){if(!this.coefficients[_i304].equals(sh.coefficients[_i304])){return false;}}return true;}copy(sh){return this.set(sh.coefficients);}clone(){return new this.constructor().copy(this);}fromArray(array){var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var coefficients=this.coefficients;for(var _i305=0;_i305<9;_i305++){coefficients[_i305].fromArray(array,offset+_i305*3);}return this;}toArray(){var array=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var coefficients=this.coefficients;for(var _i306=0;_i306<9;_i306++){coefficients[_i306].toArray(array,offset+_i306*3);}return array;}// evaluate the basis functions // shBasis is an Array[ 9 ] static getBasisAt(normal,shBasis){// normal is assumed to be unit length var x=normal.x,y=normal.y,z=normal.z;// band 0 shBasis[0]=0.282095;// band 1 shBasis[1]=0.488603*y;shBasis[2]=0.488603*z;shBasis[3]=0.488603*x;// band 2 shBasis[4]=1.092548*x*y;shBasis[5]=1.092548*y*z;shBasis[6]=0.315392*(3*z*z-1);shBasis[7]=1.092548*x*z;shBasis[8]=0.546274*(x*x-y*y);}}function LightProbe(sh,intensity){Light.call(this,undefined,intensity);this.type='LightProbe';this.sh=sh!==undefined?sh:new SphericalHarmonics3();}LightProbe.prototype=Object.assign(Object.create(Light.prototype),{constructor:LightProbe,isLightProbe:true,copy:function copy(source){Light.prototype.copy.call(this,source);this.sh.copy(source.sh);return this;},fromJSON:function fromJSON(json){this.intensity=json.intensity;// TODO: Move this bit to Light.fromJSON(); this.sh.fromArray(json.sh);return this;},toJSON:function toJSON(meta){var data=Light.prototype.toJSON.call(this,meta);data.object.sh=this.sh.toArray();return data;}});function MaterialLoader(manager){Loader.call(this,manager);this.textures={};}MaterialLoader.prototype=Object.assign(Object.create(Loader.prototype),{constructor:MaterialLoader,load:function load(url,onLoad,onProgress,onError){var scope=this;var loader=new FileLoader(scope.manager);loader.setPath(scope.path);loader.setRequestHeader(scope.requestHeader);loader.setWithCredentials(scope.withCredentials);loader.load(url,function(text){try{onLoad(scope.parse(JSON.parse(text)));}catch(e){if(onError){onError(e);}else {console.error(e);}scope.manager.itemError(url);}},onProgress,onError);},parse:function parse(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!==undefined)material.color.setHex(json.color);if(json.roughness!==undefined)material.roughness=json.roughness;if(json.metalness!==undefined)material.metalness=json.metalness;if(json.sheen!==undefined)material.sheen=new Color().setHex(json.sheen);if(json.emissive!==undefined&&material.emissive!==undefined)material.emissive.setHex(json.emissive);if(json.specular!==undefined&&material.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.fog!==undefined)material.fog=json.fog;if(json.flatShading!==undefined)material.flatShading=json.flatShading;if(json.blending!==undefined)material.blending=json.blending;if(json.combine!==undefined)material.combine=json.combine;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.stencilWrite!==undefined)material.stencilWrite=json.stencilWrite;if(json.stencilWriteMask!==undefined)material.stencilWriteMask=json.stencilWriteMask;if(json.stencilFunc!==undefined)material.stencilFunc=json.stencilFunc;if(json.stencilRef!==undefined)material.stencilRef=json.stencilRef;if(json.stencilFuncMask!==undefined)material.stencilFuncMask=json.stencilFuncMask;if(json.stencilFail!==undefined)material.stencilFail=json.stencilFail;if(json.stencilZFail!==undefined)material.stencilZFail=json.stencilZFail;if(json.stencilZPass!==undefined)material.stencilZPass=json.stencilZPass;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.rotation!==undefined)material.rotation=json.rotation;if(json.linewidth!==1)material.linewidth=json.linewidth;if(json.dashSize!==undefined)material.dashSize=json.dashSize;if(json.gapSize!==undefined)material.gapSize=json.gapSize;if(json.scale!==undefined)material.scale=json.scale;if(json.polygonOffset!==undefined)material.polygonOffset=json.polygonOffset;if(json.polygonOffsetFactor!==undefined)material.polygonOffsetFactor=json.polygonOffsetFactor;if(json.polygonOffsetUnits!==undefined)material.polygonOffsetUnits=json.polygonOffsetUnits;if(json.skinning!==undefined)material.skinning=json.skinning;if(json.morphTargets!==undefined)material.morphTargets=json.morphTargets;if(json.morphNormals!==undefined)material.morphNormals=json.morphNormals;if(json.dithering!==undefined)material.dithering=json.dithering;if(json.vertexTangents!==undefined)material.vertexTangents=json.vertexTangents;if(json.visible!==undefined)material.visible=json.visible;if(json.toneMapped!==undefined)material.toneMapped=json.toneMapped;if(json.userData!==undefined)material.userData=json.userData;if(json.vertexColors!==undefined){if(typeof json.vertexColors==='number'){material.vertexColors=json.vertexColors>0?true:false;}else {material.vertexColors=json.vertexColors;}}// Shader Material if(json.uniforms!==undefined){for(var name in json.uniforms){var uniform=json.uniforms[name];material.uniforms[name]={};switch(uniform.type){case't':material.uniforms[name].value=getTexture(uniform.value);break;case'c':material.uniforms[name].value=new Color().setHex(uniform.value);break;case'v2':material.uniforms[name].value=new Vector2().fromArray(uniform.value);break;case'v3':material.uniforms[name].value=new Vector3().fromArray(uniform.value);break;case'v4':material.uniforms[name].value=new Vector4().fromArray(uniform.value);break;case'm3':material.uniforms[name].value=new Matrix3().fromArray(uniform.value);break;case'm4':material.uniforms[name].value=new Matrix4().fromArray(uniform.value);break;default:material.uniforms[name].value=uniform.value;}}}if(json.defines!==undefined)material.defines=json.defines;if(json.vertexShader!==undefined)material.vertexShader=json.vertexShader;if(json.fragmentShader!==undefined)material.fragmentShader=json.fragmentShader;if(json.extensions!==undefined){for(var key in json.extensions){material.extensions[key]=json.extensions[key];}}// Deprecated if(json.shading!==undefined)material.flatShading=json.shading===1;// THREE.FlatShading // for PointsMaterial if(json.size!==undefined)material.size=json.size;if(json.sizeAttenuation!==undefined)material.sizeAttenuation=json.sizeAttenuation;// maps if(json.map!==undefined)material.map=getTexture(json.map);if(json.matcap!==undefined)material.matcap=getTexture(json.matcap);if(json.alphaMap!==undefined)material.alphaMap=getTexture(json.alphaMap);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.normalMapType!==undefined)material.normalMapType=json.normalMapType;if(json.normalScale!==undefined){var normalScale=json.normalScale;if(Array.isArray(normalScale)===false){// Blender exporter used to export a scalar. See #7459 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.envMapIntensity!==undefined)material.envMapIntensity=json.envMapIntensity;if(json.reflectivity!==undefined)material.reflectivity=json.reflectivity;if(json.refractionRatio!==undefined)material.refractionRatio=json.refractionRatio;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);if(json.clearcoatMap!==undefined)material.clearcoatMap=getTexture(json.clearcoatMap);if(json.clearcoatRoughnessMap!==undefined)material.clearcoatRoughnessMap=getTexture(json.clearcoatRoughnessMap);if(json.clearcoatNormalMap!==undefined)material.clearcoatNormalMap=getTexture(json.clearcoatNormalMap);if(json.clearcoatNormalScale!==undefined)material.clearcoatNormalScale=new Vector2().fromArray(json.clearcoatNormalScale);if(json.transmission!==undefined)material.transmission=json.transmission;if(json.transmissionMap!==undefined)material.transmissionMap=getTexture(json.transmissionMap);return material;},setTextures:function setTextures(value){this.textures=value;return this;}});var LoaderUtils={decodeText:function decodeText(array){if(typeof TextDecoder!=='undefined'){return new TextDecoder().decode(array);}// Avoid the String.fromCharCode.apply(null, array) shortcut, which // throws a "maximum call stack size exceeded" error for large arrays. var s='';for(var _i307=0,il=array.length;_i3070){var manager=new LoadingManager(onLoad);loader=new ImageLoader(manager);loader.setCrossOrigin(this.crossOrigin);for(var _i315=0,il=json.length;_i315 immediate success or // toggling of inside/outside at every single! intersection point of an edge // with the horizontal line through inPt, left of inPt // not counting lowerY endpoints of edges and whole edges on that line var inside=false;for(var p=polyLen-1,q=0;qNumber.EPSILON){// not parallel if(edgeDy<0){edgeLowPt=inPolygon[q];edgeDx=-edgeDx;edgeHighPt=inPolygon[p];edgeDy=-edgeDy;}if(inPt.yedgeHighPt.y)continue;if(inPt.y===edgeLowPt.y){if(inPt.x===edgeLowPt.x)return true;// inPt is on contour ? // continue; // no intersection or edgeLowPt => doesn't count !!! }else {var perpEdge=edgeDy*(inPt.x-edgeLowPt.x)-edgeDx*(inPt.y-edgeLowPt.y);if(perpEdge===0)return true;// inPt is on contour ? if(perpEdge<0)continue;inside=!inside;// true intersection left of inPt }}else {// parallel or collinear if(inPt.y!==edgeLowPt.y)continue;// parallel // edge lies on the same horizontal line as inPt if(edgeHighPt.x<=inPt.x&&inPt.x<=edgeLowPt.x||edgeLowPt.x<=inPt.x&&inPt.x<=edgeHighPt.x)return true;// inPt: Point on contour ! // continue; }}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;var 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;// console.log("Holes first", holesFirst); var betterShapeHoles=[];var newShapes=[];var newShapeHoles=[];var mainIdx=0;var tmpPoints;newShapes[mainIdx]=undefined;newShapeHoles[mainIdx]=[];for(var _i321=0,l=subPaths.length;_i321 probably all Shapes with wrong orientation if(!newShapes[0])return toShapesNoHoles(subPaths);if(newShapes.length>1){var ambiguous=false;var toChange=[];for(var sIdx=0,sLen=newShapes.length;sIdx0){// console.log("to change: ", toChange); if(!ambiguous)newShapeHoles=betterShapeHoles;}}var tmpHoles;for(var _i322=0,il=newShapes.length;_i3221&&arguments[1]!==undefined?arguments[1]:100;var shapes=[];var paths=createPaths(text,size,this.data);for(var p=0,pl=paths.length;p0&&arguments[0]!==undefined?arguments[0]:0;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;}this._startedAt=this.context.currentTime+delay;var source=this.context.createBufferSource();source.buffer=this.buffer;source.loop=this.loop;source.loopStart=this.loopStart;source.loopEnd=this.loopEnd;source.onended=this.onEnded.bind(this);source.start(this._startedAt,this._progress+this.offset,this.duration);this.isPlaying=true;this.source=source;this.setDetune(this.detune);this.setPlaybackRate(this.playbackRate);return this.connect();}pause(){if(this.hasPlaybackControl===false){console.warn('THREE.Audio: this Audio has no playback control.');return;}if(this.isPlaying===true){// update current progress this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate;if(this.loop===true){// ensure _progress does not exceed duration with looped audios this._progress=this._progress%(this.duration||this.buffer.duration);}this.source.stop();this.source.onended=null;this.isPlaying=false;}return this;}stop(){if(this.hasPlaybackControl===false){console.warn('THREE.Audio: this Audio has no playback control.');return;}this._progress=0;this.source.stop();this.source.onended=null;this.isPlaying=false;return this;}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(var _i325=1,l=this.filters.length;_i3250){this.source.disconnect(this.filters[0]);for(var _i326=1,l=this.filters.length;_i3261&&arguments[1]!==undefined?arguments[1]:2048;this.analyser=audio.context.createAnalyser();this.analyser.fftSize=fftSize;this.data=new Uint8Array(this.analyser.frequencyBinCount);audio.getOutput().connect(this.analyser);}getFrequencyData(){this.analyser.getByteFrequencyData(this.data);return this.data;}getAverageFrequency(){var value=0;var data=this.getFrequencyData();for(var _i327=0;_i327' accumulate:function accumulate(accuIndex,weight){// note: happily accumulating nothing when weight = 0, the caller knows // the weight and shouldn't have made the call in the first place var buffer=this.buffer,stride=this.valueSize,offset=accuIndex*stride+stride;var currentWeight=this.cumulativeWeight;if(currentWeight===0){// accuN := incoming * weight for(var _i328=0;_i328!==stride;++_i328){buffer[offset+_i328]=buffer[_i328];}currentWeight=weight;}else {// accuN := accuN + incoming * weight currentWeight+=weight;var mix=weight/currentWeight;this._mixBufferRegion(buffer,offset,0,mix,stride);}this.cumulativeWeight=currentWeight;},// accumulate data in the 'incoming' region into 'add' accumulateAdditive:function accumulateAdditive(weight){var buffer=this.buffer,stride=this.valueSize,offset=stride*this._addIndex;if(this.cumulativeWeightAdditive===0){// add = identity this._setIdentity();}// add := add + incoming * weight this._mixBufferRegionAdditive(buffer,offset,0,weight,stride);this.cumulativeWeightAdditive+=weight;},// apply the state of 'accu' to the binding when accus differ apply:function apply(accuIndex){var stride=this.valueSize,buffer=this.buffer,offset=accuIndex*stride+stride,weight=this.cumulativeWeight,weightAdditive=this.cumulativeWeightAdditive,binding=this.binding;this.cumulativeWeight=0;this.cumulativeWeightAdditive=0;if(weight<1){// accuN := accuN + original * ( 1 - cumulativeWeight ) var originalValueOffset=stride*this._origIndex;this._mixBufferRegion(buffer,offset,originalValueOffset,1-weight,stride);}if(weightAdditive>0){// accuN := accuN + additive accuN this._mixBufferRegionAdditive(buffer,offset,this._addIndex*stride,1,stride);}for(var _i329=stride,e=stride+stride;_i329!==e;++_i329){if(buffer[_i329]!==buffer[_i329+stride]){// value has changed -> update scene graph binding.setValue(buffer,offset);break;}}},// remember the state of the bound property and copy it to both accus saveOriginalState:function saveOriginalState(){var binding=this.binding;var buffer=this.buffer,stride=this.valueSize,originalValueOffset=stride*this._origIndex;binding.getValue(buffer,originalValueOffset);// accu[0..1] := orig -- initially detect changes against the original for(var _i330=stride,e=originalValueOffset;_i330!==e;++_i330){buffer[_i330]=buffer[originalValueOffset+_i330%stride];}// Add to identity for additive this._setIdentity();this.cumulativeWeight=0;this.cumulativeWeightAdditive=0;},// apply the state previously taken via 'saveOriginalState' to the binding restoreOriginalState:function restoreOriginalState(){var originalValueOffset=this.valueSize*3;this.binding.setValue(this.buffer,originalValueOffset);},_setAdditiveIdentityNumeric:function _setAdditiveIdentityNumeric(){var startIndex=this._addIndex*this.valueSize;var endIndex=startIndex+this.valueSize;for(var _i331=startIndex;_i331=0.5){for(var _i333=0;_i333!==stride;++_i333){buffer[dstOffset+_i333]=buffer[srcOffset+_i333];}}},_slerp:function _slerp(buffer,dstOffset,srcOffset,t){Quaternion.slerpFlat(buffer,dstOffset,buffer,dstOffset,buffer,srcOffset,t);},_slerpAdditive:function _slerpAdditive(buffer,dstOffset,srcOffset,t,stride){var workOffset=this._workIndex*stride;// Store result in intermediate buffer offset Quaternion.multiplyQuaternionsFlat(buffer,workOffset,buffer,dstOffset,buffer,srcOffset);// Slerp to the intermediate result Quaternion.slerpFlat(buffer,dstOffset,buffer,dstOffset,buffer,workOffset,t);},_lerp:function _lerp(buffer,dstOffset,srcOffset,t,stride){var s=1-t;for(var _i334=0;_i334!==stride;++_i334){var j=dstOffset+_i334;buffer[j]=buffer[j]*s+buffer[srcOffset+_i334]*t;}},_lerpAdditive:function _lerpAdditive(buffer,dstOffset,srcOffset,t,stride){for(var _i335=0;_i335!==stride;++_i335){var j=dstOffset+_i335;buffer[j]=buffer[j]+buffer[srcOffset+_i335]*t;}}});// Characters [].:/ are reserved for track binding syntax. var _RESERVED_CHARS_RE='\\[\\]\\.:\\/';var _reservedRe=new RegExp('['+_RESERVED_CHARS_RE+']','g');// Attempts to allow node names from any language. ES5's `\w` regexp matches // only latin characters, and the unicode \p{L} is not yet supported. So // instead, we exclude reserved characters and match everything else. var _wordChar='[^'+_RESERVED_CHARS_RE+']';var _wordCharOrDot='[^'+_RESERVED_CHARS_RE.replace('\\.','')+']';// Parent directories, delimited by '/' or ':'. Currently unused, but must // be matched to parse the rest of the track name. var _directoryRe=/((?:WC+[\/:])*)/.source.replace('WC',_wordChar);// Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'. var _nodeRe=/(WCOD+)?/.source.replace('WCOD',_wordCharOrDot);// Object on target node, and accessor. May not contain reserved // characters. Accessor may contain any character except closing bracket. var _objectRe=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC',_wordChar);// Property and accessor. May not contain reserved characters. Accessor may // contain any non-bracket characters. var _propertyRe=/\.(WC+)(?:\[(.+)\])?/.source.replace('WC',_wordChar);var _trackRe=new RegExp(''+'^'+_directoryRe+_nodeRe+_objectRe+_propertyRe+'$');var _supportedObjectNames=['material','materials','bones'];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 getValue(array,offset){this.bind();// bind all binding var firstValidIndex=this._targetGroup.nCachedObjects_,binding=this._bindings[firstValidIndex];// and only call .getValue on the first if(binding!==undefined)binding.getValue(array,offset);},setValue:function setValue(array,offset){var bindings=this._bindings;for(var _i336=this._targetGroup.nCachedObjects_,n=bindings.length;_i336!==n;++_i336){bindings[_i336].setValue(array,offset);}},bind:function bind(){var bindings=this._bindings;for(var _i337=this._targetGroup.nCachedObjects_,n=bindings.length;_i337!==n;++_i337){bindings[_i337].bind();}},unbind:function unbind(){var bindings=this._bindings;for(var _i338=this._targetGroup.nCachedObjects_,n=bindings.length;_i338!==n;++_i338){bindings[_i338].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 create(root,path,parsedPath){if(!(root&&root.isAnimationObjectGroup)){return new PropertyBinding(root,path,parsedPath);}else {return new PropertyBinding.Composite(root,path,parsedPath);}},/** * Replaces spaces with underscores and removes unsupported characters from * node names, to ensure compatibility with parseTrackName(). * * @param {string} name Node name to be sanitized. * @return {string} */sanitizeNodeName:function sanitizeNodeName(name){return name.replace(/\s/g,'_').replace(_reservedRe,'');},parseTrackName:function parseTrackName(trackName){var matches=_trackRe.exec(trackName);if(!matches){throw new Error('PropertyBinding: Cannot parse trackName: '+trackName);}var results={// directoryName: matches[ 1 ], // (tschw) currently unused nodeName:matches[2],objectName:matches[3],objectIndex:matches[4],propertyName:matches[5],// required propertyIndex:matches[6]};var lastDot=results.nodeName&&results.nodeName.lastIndexOf('.');if(lastDot!==undefined&&lastDot!==-1){var objectName=results.nodeName.substring(lastDot+1);// Object names must be checked against an allowlist. Otherwise, there // is no way to parse 'foo.bar.baz': 'baz' must be a property, but // 'bar' could be the objectName, or part of a nodeName (which can // include '.' characters). 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 findNode(root,nodeName){if(!nodeName||nodeName===''||nodeName==='.'||nodeName===-1||nodeName===root.name||nodeName===root.uuid){return root;}// search into skeleton bones. if(root.skeleton){var bone=root.skeleton.getBoneByName(nodeName);if(bone!==undefined){return bone;}}// search into node subtree. if(root.children){var _searchNodeSubtree=function searchNodeSubtree(children){for(var _i339=0;_i339 this._bindingsIndicesByPath={};// inside: indices in these arrays 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 add(){var objects=this._objects,indicesByUUID=this._indicesByUUID,paths=this._paths,parsedPaths=this._parsedPaths,bindings=this._bindings,nBindings=bindings.length;var knownObject=undefined,nObjects=objects.length,nCachedObjects=this.nCachedObjects_;for(var _i346=0,n=arguments.length;_i346!==n;++_i346){var object=arguments[_i346],uuid=object.uuid;var index=indicesByUUID[uuid];if(index===undefined){// unknown object -> add it to the ACTIVE region index=nObjects++;indicesByUUID[uuid]=index;objects.push(object);// accounting is done, now do the same for all bindings for(var j=0,m=nBindings;j!==m;++j){bindings[j].push(new PropertyBinding(object,paths[j],parsedPaths[j]));}}else if(index=nCachedObjects){// move existing object into the CACHED region var lastCachedIndex=nCachedObjects++,firstActiveObject=objects[lastCachedIndex];indicesByUUID[firstActiveObject.uuid]=index;objects[index]=firstActiveObject;indicesByUUID[uuid]=lastCachedIndex;objects[lastCachedIndex]=object;// accounting is done, now do the same for all bindings 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;}}}// for arguments this.nCachedObjects_=nCachedObjects;},// remove & forget uncache:function uncache(){var objects=this._objects,indicesByUUID=this._indicesByUUID,bindings=this._bindings,nBindings=bindings.length;var nCachedObjects=this.nCachedObjects_,nObjects=objects.length;for(var _i348=0,n=arguments.length;_i348!==n;++_i348){var object=arguments[_i348],uuid=object.uuid,index=indicesByUUID[uuid];if(index!==undefined){delete indicesByUUID[uuid];if(index0){indicesByUUID[_lastObject.uuid]=index;}objects[index]=_lastObject;objects.pop();// accounting is done, now do the same for all bindings for(var _j26=0,_m3=nBindings;_j26!==_m3;++_j26){var _bindingsForPath=bindings[_j26];_bindingsForPath[index]=_bindingsForPath[_lastIndex];_bindingsForPath.pop();}}// cached or active }// if object is known }// for arguments this.nCachedObjects_=nCachedObjects;},// Internal interface used by befriended PropertyBinding.Composite: subscribe_:function subscribe_(path,parsedPath){// returns an array of bindings for the given path that is changed // according to the contained objects in the group var indicesByPath=this._bindingsIndicesByPath;var index=indicesByPath[path];var 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 _i349=nCachedObjects,n=objects.length;_i349!==n;++_i349){var object=objects[_i349];bindingsForPath[_i349]=new PropertyBinding(object,path,parsedPath);}return bindingsForPath;},unsubscribe_:function unsubscribe_(path){// tells the group to forget about a property path and no longer // update the array previously obtained with 'subscribe_' 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();}}});class AnimationAction{constructor(mixer,clip){var localRoot=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;var blendMode=arguments.length>3&&arguments[3]!==undefined?arguments[3]:clip.blendMode;this._mixer=mixer;this._clip=clip;this._localRoot=localRoot;this.blendMode=blendMode;var tracks=clip.tracks,nTracks=tracks.length,interpolants=new Array(nTracks);var interpolantSettings={endingStart:ZeroCurvatureEnding,endingEnd:ZeroCurvatureEnding};for(var _i350=0;_i350!==nTracks;++_i350){var interpolant=tracks[_i350].createInterpolant(null);interpolants[_i350]=interpolant;interpolant.settings=interpolantSettings;}this._interpolantSettings=interpolantSettings;this._interpolants=interpolants;// bound by the mixer // inside: PropertyMixer (managed by the mixer) this._propertyBindings=new Array(nTracks);this._cacheIndex=null;// for the memory manager this._byClipCacheIndex=null;// for the memory manager this._timeScaleInterpolant=null;this._weightInterpolant=null;this.loop=LoopRepeat;this._loopCount=-1;// global mixer time when the action is to be started // it's set back to 'null' upon start of the action this._startTime=null;// scaled local time of the action // gets clamped or wrapped to 0..clip.duration according to loop this.time=0;this.timeScale=1;this._effectiveTimeScale=1;this.weight=1;this._effectiveWeight=1;this.repetitions=Infinity;// no. of repetitions when looping this.paused=false;// true -> zero effective time scale this.enabled=true;// false -> zero effective weight this.clampWhenFinished=false;// keep feeding the last frame? this.zeroSlopeAtStart=true;// for smooth interpolation w/o separate this.zeroSlopeAtEnd=true;// clips for start, loop and end }// State & Scheduling play(){this._mixer._activateAction(this);return this;}stop(){this._mixer._deactivateAction(this);return this.reset();}reset(){this.paused=false;this.enabled=true;this.time=0;// restart clip this._loopCount=-1;// forget previous loops this._startTime=null;// forget scheduling return this.stopFading().stopWarping();}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this);}// return true when play has been called isScheduled(){return this._mixer._isActiveAction(this);}startAt(time){this._startTime=time;return this;}setLoop(mode,repetitions){this.loop=mode;this.repetitions=repetitions;return this;}// Weight // set the weight stopping any scheduled fading // although .enabled = false yields an effective weight of zero, this // method does *not* change .enabled, because it would be confusing setEffectiveWeight(weight){this.weight=weight;// note: same logic as when updated at runtime this._effectiveWeight=this.enabled?weight:0;return this.stopFading();}// return the weight considering fading and .enabled getEffectiveWeight(){return this._effectiveWeight;}fadeIn(duration){return this._scheduleFading(duration,0,1);}fadeOut(duration){return this._scheduleFading(duration,1,0);}crossFadeFrom(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.0,startEndRatio,duration);this.warp(endStartRatio,1.0,duration);}return this;}crossFadeTo(fadeInAction,duration,warp){return fadeInAction.crossFadeFrom(this,duration,warp);}stopFading(){var weightInterpolant=this._weightInterpolant;if(weightInterpolant!==null){this._weightInterpolant=null;this._mixer._takeBackControlInterpolant(weightInterpolant);}return this;}// Time Scale Control // set the time scale stopping any scheduled warping // although .paused = true yields an effective time scale of zero, this // method does *not* change .paused, because it would be confusing setEffectiveTimeScale(timeScale){this.timeScale=timeScale;this._effectiveTimeScale=this.paused?0:timeScale;return this.stopWarping();}// return the time scale considering warping and .paused getEffectiveTimeScale(){return this._effectiveTimeScale;}setDuration(duration){this.timeScale=this._clip.duration/duration;return this.stopWarping();}syncWith(action){this.time=action.time;this.timeScale=action.timeScale;return this.stopWarping();}halt(duration){return this.warp(this._effectiveTimeScale,0,duration);}warp(startTimeScale,endTimeScale,duration){var mixer=this._mixer,now=mixer.time,timeScale=this.timeScale;var interpolant=this._timeScaleInterpolant;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(){var timeScaleInterpolant=this._timeScaleInterpolant;if(timeScaleInterpolant!==null){this._timeScaleInterpolant=null;this._mixer._takeBackControlInterpolant(timeScaleInterpolant);}return this;}// Object Accessors getMixer(){return this._mixer;}getClip(){return this._clip;}getRoot(){return this._localRoot||this._mixer._root;}// Interna _update(time,deltaTime,timeDirection,accuIndex){// called by the mixer if(!this.enabled){// call ._updateWeight() to update ._effectiveWeight this._updateWeight(time);return;}var startTime=this._startTime;if(startTime!==null){// check for scheduled start of action var timeRunning=(time-startTime)*timeDirection;if(timeRunning<0||timeDirection===0){return;// yet to come / don't decide when delta = 0 }// start this._startTime=null;// unschedule deltaTime=timeDirection*timeRunning;}// apply time scale and advance time deltaTime*=this._updateTimeScale(time);var clipTime=this._updateTime(deltaTime);// note: _updateTime may disable the action resulting in // an effective weight of 0 var weight=this._updateWeight(time);if(weight>0){var interpolants=this._interpolants;var propertyMixers=this._propertyBindings;switch(this.blendMode){case AdditiveAnimationBlendMode:for(var j=0,m=interpolants.length;j!==m;++j){interpolants[j].evaluate(clipTime);propertyMixers[j].accumulateAdditive(weight);}break;case NormalAnimationBlendMode:default:for(var _j27=0,_m4=interpolants.length;_j27!==_m4;++_j27){interpolants[_j27].evaluate(clipTime);propertyMixers[_j27].accumulate(accuIndex,weight);}}}}_updateWeight(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){// faded out, disable this.enabled=false;}}}}this._effectiveWeight=weight;return weight;}_updateTimeScale(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){// motion has halted, pause this.paused=true;}else {// warp done - apply final time scale this.timeScale=timeScale;}}}}this._effectiveTimeScale=timeScale;return timeScale;}_updateTime(deltaTime){var duration=this._clip.duration;var loop=this.loop;var time=this.time+deltaTime;var loopCount=this._loopCount;var pingPong=loop===LoopPingPong;if(deltaTime===0){if(loopCount===-1)return time;return pingPong&&(loopCount&1)===1?duration-time:time;}if(loop===LoopOnce){if(loopCount===-1){// just started this._loopCount=0;this._setEndings(true,true,false);}handle_stop:{if(time>=duration){time=duration;}else if(time<0){time=0;}else {this.time=time;break handle_stop;}if(this.clampWhenFinished)this.paused=true;else this.enabled=false;this.time=time;this._mixer.dispatchEvent({type:'finished',action:this,direction:deltaTime<0?-1:1});}}else {// repetitive Repeat or PingPong if(loopCount===-1){// just started if(deltaTime>=0){loopCount=0;this._setEndings(true,this.repetitions===0,pingPong);}else {// when looping in reverse direction, the initial // transition through zero counts as a repetition, // so leave loopCount at -1 this._setEndings(this.repetitions===0,true,pingPong);}}if(time>=duration||time<0){// wrap around var loopDelta=Math.floor(time/duration);// signed time-=duration*loopDelta;loopCount+=Math.abs(loopDelta);var pending=this.repetitions-loopCount;if(pending<=0){// have to stop (switch state, clamp time, fire event) if(this.clampWhenFinished)this.paused=true;else this.enabled=false;time=deltaTime>0?duration:0;this.time=time;this._mixer.dispatchEvent({type:'finished',action:this,direction:deltaTime>0?1:-1});}else {// keep running if(pending===1){// entering the last round var atStart=deltaTime<0;this._setEndings(atStart,!atStart,pingPong);}else {this._setEndings(false,false,pingPong);}this._loopCount=loopCount;this.time=time;this._mixer.dispatchEvent({type:'loop',action:this,loopDelta:loopDelta});}}else {this.time=time;}if(pingPong&&(loopCount&1)===1){// invert time for the "pong round" return duration-time;}}return time;}_setEndings(atStart,atEnd,pingPong){var settings=this._interpolantSettings;if(pingPong){settings.endingStart=ZeroSlopeEnding;settings.endingEnd=ZeroSlopeEnding;}else {// assuming for LoopOnce atStart == atEnd == true 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(duration,weightNow,weightThen){var mixer=this._mixer,now=mixer.time;var 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.0;}AnimationMixer.prototype=Object.assign(Object.create(EventDispatcher.prototype),{constructor:AnimationMixer,_bindAction:function _bindAction(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;var bindingsByName=bindingsByRoot[rootUuid];if(bindingsByName===undefined){bindingsByName={};bindingsByRoot[rootUuid]=bindingsByName;}for(var _i351=0;_i351!==nTracks;++_i351){var track=tracks[_i351],trackName=track.name;var binding=bindingsByName[trackName];if(binding!==undefined){bindings[_i351]=binding;}else {binding=bindings[_i351];if(binding!==undefined){// existing binding, make sure the cache knows if(binding._cacheIndex===null){++binding.referenceCount;this._addInactiveBinding(binding,rootUuid,trackName);}continue;}var path=prototypeAction&&prototypeAction._propertyBindings[_i351].binding.parsedPath;binding=new PropertyMixer(PropertyBinding.create(root,trackName,path),track.ValueTypeName,track.getValueSize());++binding.referenceCount;this._addInactiveBinding(binding,rootUuid,trackName);bindings[_i351]=binding;}interpolants[_i351].resultBuffer=binding.buffer;}},_activateAction:function _activateAction(action){if(!this._isActiveAction(action)){if(action._cacheIndex===null){// this action has been forgotten by the cache, but the user // appears to be still using it -> rebind 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;// increment reference counts / sort out state for(var _i352=0,n=bindings.length;_i352!==n;++_i352){var binding=bindings[_i352];if(binding.useCount++===0){this._lendBinding(binding);binding.saveOriginalState();}}this._lendAction(action);}},_deactivateAction:function _deactivateAction(action){if(this._isActiveAction(action)){var bindings=action._propertyBindings;// decrement reference counts / sort out state for(var _i353=0,n=bindings.length;_i353!==n;++_i353){var binding=bindings[_i353];if(--binding.useCount===0){binding.restoreOriginalState();this._takeBackBinding(binding);}}this._takeBackAction(action);}},// Memory manager _initMemoryManager:function _initMemoryManager(){this._actions=[];// 'nActiveActions' followed by inactive ones this._nActiveActions=0;this._actionsByClip={};// inside: // { // knownActions: Array< AnimationAction > - used as prototypes // actionByRoot: AnimationAction - lookup // } this._bindings=[];// 'nActiveBindings' followed by inactive ones this._nActiveBindings=0;this._bindingsByRootAndName={};// inside: Map< name, PropertyMixer > this._controlInterpolants=[];// same game as above 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;}}};},// Memory management for AnimationAction objects _isActiveAction:function _isActiveAction(action){var index=action._cacheIndex;return index!==null&&index| inactive actions ] // s a // <-swap-> // a s 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 _takeBackAction(action){// [ active actions | inactive actions ] // [ active actions |< inactive actions ] // a s // <-swap-> // s a 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;},// Memory management for PropertyMixer objects _addInactiveBinding:function _addInactiveBinding(binding,rootUuid,trackName){var bindingsByRoot=this._bindingsByRootAndName,bindings=this._bindings;var bindingByName=bindingsByRoot[rootUuid];if(bindingByName===undefined){bindingByName={};bindingsByRoot[rootUuid]=bindingByName;}bindingByName[trackName]=binding;binding._cacheIndex=bindings.length;bindings.push(binding);},_removeInactiveBinding:function _removeInactiveBinding(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];if(Object.keys(bindingByName).length===0){delete bindingsByRoot[rootUuid];}},_lendBinding:function _lendBinding(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 _takeBackBinding(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;},// Memory management of Interpolants for weight and time scale _lendControlInterpolant:function _lendControlInterpolant(){var interpolants=this._controlInterpolants,lastActiveIndex=this._nActiveControlInterpolants++;var 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 _takeBackControlInterpolant(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),// return an action for a clip optionally using a custom root target // object (this method allocates a lot of dynamic memory in case a // previously unknown clip/root combination is specified) clipAction:function clipAction(clip,optionalRoot,blendMode){var root=optionalRoot||this._root,rootUuid=root.uuid;var clipObject=typeof clip==='string'?AnimationClip.findByName(root,clip):clip;var clipUuid=clipObject!==null?clipObject.uuid:clip;var actionsForClip=this._actionsByClip[clipUuid];var prototypeAction=null;if(blendMode===undefined){if(clipObject!==null){blendMode=clipObject.blendMode;}else {blendMode=NormalAnimationBlendMode;}}if(actionsForClip!==undefined){var existingAction=actionsForClip.actionByRoot[rootUuid];if(existingAction!==undefined&&existingAction.blendMode===blendMode){return existingAction;}// we know the clip, so we don't have to parse all // the bindings again but can just copy prototypeAction=actionsForClip.knownActions[0];// also, take the clip from the prototype action if(clipObject===null)clipObject=prototypeAction._clip;}// clip must be known when specified via string if(clipObject===null)return null;// allocate all resources required to run it var newAction=new AnimationAction(this,clipObject,optionalRoot,blendMode);this._bindAction(newAction,prototypeAction);// and make the action known to the memory manager this._addInactiveAction(newAction,clipUuid,rootUuid);return newAction;},// get an existing action existingAction:function existingAction(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;},// deactivates all previously scheduled actions stopAllAction:function stopAllAction(){var actions=this._actions,nActions=this._nActiveActions;for(var _i355=nActions-1;_i355>=0;--_i355){actions[_i355].stop();}return this;},// advance the time and update apply the animation update:function update(deltaTime){deltaTime*=this.timeScale;var actions=this._actions,nActions=this._nActiveActions,time=this.time+=deltaTime,timeDirection=Math.sign(deltaTime),accuIndex=this._accuIndex^=1;// run active actions for(var _i356=0;_i356!==nActions;++_i356){var action=actions[_i356];action._update(time,deltaTime,timeDirection,accuIndex);}// update scene graph var bindings=this._bindings,nBindings=this._nActiveBindings;for(var _i357=0;_i357!==nBindings;++_i357){bindings[_i357].apply(accuIndex);}return this;},// Allows you to seek to a specific time in an animation. setTime:function setTime(timeInSeconds){this.time=0;// Zero out time attribute for AnimationMixer object; for(var _i358=0;_i3580&&arguments[0]!==undefined?arguments[0]:1;var phi=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var theta=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;this.radius=radius;this.phi=phi;// polar angle this.theta=theta;// azimuthal angle return this;}set(radius,phi,theta){this.radius=radius;this.phi=phi;this.theta=theta;return this;}clone(){return new this.constructor().copy(this);}copy(other){this.radius=other.radius;this.phi=other.phi;this.theta=other.theta;return this;}// restrict phi to be betwee EPS and PI-EPS makeSafe(){var EPS=0.000001;this.phi=Math.max(EPS,Math.min(Math.PI-EPS,this.phi));return this;}setFromVector3(v){return this.setFromCartesianCoords(v.x,v.y,v.z);}setFromCartesianCoords(x,y,z){this.radius=Math.sqrt(x*x+y*y+z*z);if(this.radius===0){this.theta=0;this.phi=0;}else {this.theta=Math.atan2(x,z);this.phi=Math.acos(MathUtils.clamp(y/this.radius,-1,1));}return this;}}/** * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system */class Cylindrical{constructor(radius,theta,y){this.radius=radius!==undefined?radius:1.0;// distance from the origin to a point in the x-z plane this.theta=theta!==undefined?theta:0;// counterclockwise angle in the x-z plane measured in radians from the positive z-axis this.y=y!==undefined?y:0;// height above the x-z plane return this;}set(radius,theta,y){this.radius=radius;this.theta=theta;this.y=y;return this;}clone(){return new this.constructor().copy(this);}copy(other){this.radius=other.radius;this.theta=other.theta;this.y=other.y;return this;}setFromVector3(v){return this.setFromCartesianCoords(v.x,v.y,v.z);}setFromCartesianCoords(x,y,z){this.radius=Math.sqrt(x*x+z*z);this.theta=Math.atan2(x,z);this.y=y;return this;}}var _vector$8=/*@__PURE__*/new Vector2();class Box2{constructor(min,max){Object.defineProperty(this,'isBox2',{value:true});this.min=min!==undefined?min:new Vector2(+Infinity,+Infinity);this.max=max!==undefined?max:new Vector2(-Infinity,-Infinity);}set(min,max){this.min.copy(min);this.max.copy(max);return this;}setFromPoints(points){this.makeEmpty();for(var _i362=0,il=points.length;_i362this.max.x||point.ythis.max.y?false:true;}containsBox(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(point,target){// This can potentially have a divide by zero if the box // has a size dimension of 0. if(target===undefined){console.warn('THREE.Box2: .getParameter() target is now required');target=new Vector2();}return target.set((point.x-this.min.x)/(this.max.x-this.min.x),(point.y-this.min.y)/(this.max.y-this.min.y));}intersectsBox(box){// using 4 splitting planes to rule out intersections return box.max.xthis.max.x||box.max.ythis.max.y?false:true;}clampPoint(point,target){if(target===undefined){console.warn('THREE.Box2: .clampPoint() target is now required');target=new Vector2();}return target.copy(point).clamp(this.min,this.max);}distanceToPoint(point){var clampedPoint=_vector$8.copy(point).clamp(this.min,this.max);return clampedPoint.sub(point).length();}intersect(box){this.min.max(box.min);this.max.min(box.max);return this;}union(box){this.min.min(box.min);this.max.max(box.max);return this;}translate(offset){this.min.add(offset);this.max.add(offset);return this;}equals(box){return box.min.equals(this.min)&&box.max.equals(this.max);}}var _startP=/*@__PURE__*/new Vector3();var _startEnd=/*@__PURE__*/new Vector3();class Line3{constructor(start,end){this.start=start!==undefined?start:new Vector3();this.end=end!==undefined?end:new Vector3();}set(start,end){this.start.copy(start);this.end.copy(end);return this;}clone(){return new this.constructor().copy(this);}copy(line){this.start.copy(line.start);this.end.copy(line.end);return this;}getCenter(target){if(target===undefined){console.warn('THREE.Line3: .getCenter() target is now required');target=new Vector3();}return target.addVectors(this.start,this.end).multiplyScalar(0.5);}delta(target){if(target===undefined){console.warn('THREE.Line3: .delta() target is now required');target=new Vector3();}return target.subVectors(this.end,this.start);}distanceSq(){return this.start.distanceToSquared(this.end);}distance(){return this.start.distanceTo(this.end);}at(t,target){if(target===undefined){console.warn('THREE.Line3: .at() target is now required');target=new Vector3();}return this.delta(target).multiplyScalar(t).add(this.start);}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=MathUtils.clamp(t,0,1);}return t;}closestPointToPoint(point,clampToLine,target){var t=this.closestPointToPointParameter(point,clampToLine);if(target===undefined){console.warn('THREE.Line3: .closestPointToPoint() target is now required');target=new Vector3();}return this.delta(target).multiplyScalar(t).add(this.start);}applyMatrix4(matrix){this.start.applyMatrix4(matrix);this.end.applyMatrix4(matrix);return this;}equals(line){return line.start.equals(this.start)&&line.end.equals(this.end);}}function ImmediateRenderObject(material){Object3D.call(this);this.material=material;this.render=function/* renderCallback */(){};this.hasPositions=false;this.hasNormals=false;this.hasColors=false;this.hasUvs=false;this.positionArray=null;this.normalArray=null;this.colorArray=null;this.uvArray=null;this.count=0;}ImmediateRenderObject.prototype=Object.create(Object3D.prototype);ImmediateRenderObject.prototype.constructor=ImmediateRenderObject;ImmediateRenderObject.prototype.isImmediateRenderObject=true;var _vector$9=/*@__PURE__*/new Vector3();class SpotLightHelper extends Object3D{constructor(light,color){super();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 _i363=0,j=1,l=32;_i3630&&arguments[0]!==undefined?arguments[0]:10;var divisions=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;var color1=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0x444444;var color2=arguments.length>3&&arguments[3]!==undefined?arguments[3]:0x888888;color1=new Color(color1);color2=new Color(color2);var center=divisions/2;var step=size/divisions;var halfSize=size/2;var vertices=[],colors=[];for(var _i368=0,j=0,k=-halfSize;_i368<=divisions;_i368++,k+=step){vertices.push(-halfSize,0,k,halfSize,0,k);vertices.push(k,0,-halfSize,k,0,halfSize);var color=_i368===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.setAttribute('position',new Float32BufferAttribute(vertices,3));geometry.setAttribute('color',new Float32BufferAttribute(colors,3));var material=new LineBasicMaterial({vertexColors:true,toneMapped:false});super(geometry,material);this.type='GridHelper';}}class PolarGridHelper extends LineSegments{constructor(){var radius=arguments.length>0&&arguments[0]!==undefined?arguments[0]:10;var radials=arguments.length>1&&arguments[1]!==undefined?arguments[1]:16;var circles=arguments.length>2&&arguments[2]!==undefined?arguments[2]:8;var divisions=arguments.length>3&&arguments[3]!==undefined?arguments[3]:64;var color1=arguments.length>4&&arguments[4]!==undefined?arguments[4]:0x444444;var color2=arguments.length>5&&arguments[5]!==undefined?arguments[5]:0x888888;color1=new Color(color1);color2=new Color(color2);var vertices=[];var colors=[];// create the radials for(var _i369=0;_i369<=radials;_i369++){var v=_i369/radials*(Math.PI*2);var x=Math.sin(v)*radius;var z=Math.cos(v)*radius;vertices.push(0,0,0);vertices.push(x,0,z);var color=_i369&1?color1:color2;colors.push(color.r,color.g,color.b);colors.push(color.r,color.g,color.b);}// create the circles for(var _i370=0;_i370<=circles;_i370++){var _color=_i370&1?color1:color2;var r=radius-radius/circles*_i370;for(var j=0;j1&&arguments[1]!==undefined?arguments[1]:0xffff00;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.setAttribute('position',new BufferAttribute(positions,3));super(geometry,new LineBasicMaterial({color:color,toneMapped:false}));this.object=object;this.type='BoxHelper';this.matrixAutoUpdate=false;this.update();}update(object){if(object!==undefined){console.warn('THREE.BoxHelper: .update() has no longer arguments.');}if(this.object!==undefined){_box$3.setFromObject(this.object);}if(_box$3.isEmpty())return;var min=_box$3.min;var max=_box$3.max;/* 5____4 1/___0/| | 6__|_7 2/___3/ 0: max.x, max.y, max.z 1: min.x, max.y, max.z 2: min.x, min.y, max.z 3: max.x, min.y, max.z 4: max.x, max.y, min.z 5: min.x, max.y, min.z 6: min.x, min.y, min.z 7: max.x, min.y, min.z */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();}setFromObject(object){this.object=object;this.update();return this;}copy(source){LineSegments.prototype.copy.call(this,source);this.object=source.object;return this;}}class Box3Helper extends LineSegments{constructor(box){var color=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0xffff00;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.setAttribute('position',new Float32BufferAttribute(positions,3));super(geometry,new LineBasicMaterial({color:color,toneMapped:false}));this.box=box;this.type='Box3Helper';this.geometry.computeBoundingSphere();}updateMatrixWorld(force){var box=this.box;if(box.isEmpty())return;box.getCenter(this.position);box.getSize(this.scale);this.scale.multiplyScalar(0.5);super.updateMatrixWorld(force);}}class PlaneHelper extends Line{constructor(plane){var size=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var hex=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0xffff00;var color=hex;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.setAttribute('position',new Float32BufferAttribute(positions,3));geometry.computeBoundingSphere();super(geometry,new LineBasicMaterial({color:color,toneMapped:false}));this.type='PlaneHelper';this.plane=plane;this.size=size;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.setAttribute('position',new Float32BufferAttribute(positions2,3));geometry2.computeBoundingSphere();this.add(new Mesh(geometry2,new MeshBasicMaterial({color:color,opacity:0.2,transparent:true,depthWrite:false,toneMapped:false})));}updateMatrixWorld(force){var scale=-this.plane.constant;if(Math.abs(scale)<1e-8)scale=1e-8;// sign does not matter this.scale.set(0.5*this.size,0.5*this.size,scale);this.children[0].material.side=scale<0?BackSide:FrontSide;// renderer flips side when determinant < 0; flipping not wanted here this.lookAt(this.plane.normal);super.updateMatrixWorld(force);}}var _axis$1=/*@__PURE__*/new Vector3();var _lineGeometry,_coneGeometry;class ArrowHelper extends Object3D{constructor(dir,origin,length,color,headLength,headWidth){super();// dir is assumed to be normalized this.type='ArrowHelper';if(dir===undefined)dir=new Vector3(0,0,1);if(origin===undefined)origin=new Vector3(0,0,0);if(length===undefined)length=1;if(color===undefined)color=0xffff00;if(headLength===undefined)headLength=0.2*length;if(headWidth===undefined)headWidth=0.2*headLength;if(_lineGeometry===undefined){_lineGeometry=new BufferGeometry();_lineGeometry.setAttribute('position',new Float32BufferAttribute([0,0,0,0,1,0],3));_coneGeometry=new CylinderBufferGeometry(0,0.5,1,5,1);_coneGeometry.translate(0,-0.5,0);}this.position.copy(origin);this.line=new Line(_lineGeometry,new LineBasicMaterial({color:color,toneMapped:false}));this.line.matrixAutoUpdate=false;this.add(this.line);this.cone=new Mesh(_coneGeometry,new MeshBasicMaterial({color:color,toneMapped:false}));this.cone.matrixAutoUpdate=false;this.add(this.cone);this.setDirection(dir);this.setLength(length,headLength,headWidth);}setDirection(dir){// dir is assumed to be normalized if(dir.y>0.99999){this.quaternion.set(0,0,0,1);}else if(dir.y<-0.99999){this.quaternion.set(1,0,0,0);}else {_axis$1.set(dir.z,0,-dir.x).normalize();var radians=Math.acos(dir.y);this.quaternion.setFromAxisAngle(_axis$1,radians);}}setLength(length,headLength,headWidth){if(headLength===undefined)headLength=0.2*length;if(headWidth===undefined)headWidth=0.2*headLength;this.line.scale.set(1,Math.max(0.0001,length-headLength),1);// see #17458 this.line.updateMatrix();this.cone.scale.set(headWidth,headLength,headWidth);this.cone.position.y=length;this.cone.updateMatrix();}setColor(color){this.line.material.color.set(color);this.cone.material.color.set(color);}copy(source){super.copy(source,false);this.line.copy(source.line);this.cone.copy(source.cone);return this;}}class AxesHelper extends LineSegments{constructor(){var size=arguments.length>0&&arguments[0]!==undefined?arguments[0]: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,0.6,0,0,1,0,0.6,1,0,0,0,1,0,0.6,1];var geometry=new BufferGeometry();geometry.setAttribute('position',new Float32BufferAttribute(vertices,3));geometry.setAttribute('color',new Float32BufferAttribute(colors,3));var material=new LineBasicMaterial({vertexColors:true,toneMapped:false});super(geometry,material);this.type='AxesHelper';}}var _floatView=new Float32Array(1);var _int32View=new Int32Array(_floatView.buffer);var DataUtils={// Converts float32 to float16 (stored as uint16 value). toHalfFloat:function toHalfFloat(val){// Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410 /* This method is faster than the OpenEXR implementation (very often * used, eg. in Ogre), with the additional benefit of rounding, inspired * by James Tursa?s half-precision code. */_floatView[0]=val;var x=_int32View[0];var bits=x>>16&0x8000;/* Get the sign */var m=x>>12&0x07ff;/* Keep one extra bit for rounding */var e=x>>23&0xff;/* Using int is faster here */ /* If zero, or denormal, or exponent underflows too much for a denormal * half, return signed zero. */if(e<103)return bits;/* If NaN, return NaN. If Inf or exponent overflow, return Inf. */if(e>142){bits|=0x7c00;/* If exponent was 0xff and one mantissa bit was set, it means NaN, * not Inf, so make sure we set one mantissa bit too. */bits|=(e==255?0:1)&&x&0x007fffff;return bits;}/* If exponent underflows but not too much, return a denormal */if(e<113){m|=0x0800;/* Extra rounding may overflow and set mantissa to 0 and exponent * to 1, which is OK. */bits|=(m>>114-e)+(m>>113-e&1);return bits;}bits|=e-112<<10|m>>1;/* Extra rounding. An overflow will set mantissa to 0 and increment * the exponent, which is OK. */bits+=m&1;return bits;}};var LOD_MIN=4;var LOD_MAX=8;var SIZE_MAX=Math.pow(2,LOD_MAX);// The standard deviations (radians) associated with the extra mips. These are // chosen to approximate a Trowbridge-Reitz distribution function times the // geometric shadowing function. These sigma values squared must match the // variance #defines in cube_uv_reflection_fragment.glsl.js. var EXTRA_LOD_SIGMA=[0.125,0.215,0.35,0.446,0.526,0.582];var TOTAL_LODS=LOD_MAX-LOD_MIN+1+EXTRA_LOD_SIGMA.length;// The maximum length of the blur for loop. Smaller sigmas will use fewer // samples and exit early, but not recompile the shader. var MAX_SAMPLES=20;var ENCODINGS={[LinearEncoding]:0,[sRGBEncoding]:1,[RGBEEncoding]:2,[RGBM7Encoding]:3,[RGBM16Encoding]:4,[RGBDEncoding]:5,[GammaEncoding]:6};var _flatCamera=/*@__PURE__*/new OrthographicCamera();var{_lodPlanes,_sizeLods,_sigmas}=/*@__PURE__*/_createPlanes();var _clearColor=/*@__PURE__*/new Color();var _oldTarget=null;// Golden Ratio var PHI=(1+Math.sqrt(5))/2;var INV_PHI=1/PHI;// Vertices of a dodecahedron (except the opposites, which represent the // same axis), used as axis directions evenly spread on a sphere. var _axisDirections=[/*@__PURE__*/new Vector3(1,1,1),/*@__PURE__*/new Vector3(-1,1,1),/*@__PURE__*/new Vector3(1,1,-1),/*@__PURE__*/new Vector3(-1,1,-1),/*@__PURE__*/new Vector3(0,PHI,INV_PHI),/*@__PURE__*/new Vector3(0,PHI,-INV_PHI),/*@__PURE__*/new Vector3(INV_PHI,0,PHI),/*@__PURE__*/new Vector3(-INV_PHI,0,PHI),/*@__PURE__*/new Vector3(PHI,INV_PHI,0),/*@__PURE__*/new Vector3(-PHI,INV_PHI,0)];/** * This class generates a Prefiltered, Mipmapped Radiance Environment Map * (PMREM) from a cubeMap environment texture. This allows different levels of * blur to be quickly accessed based on material roughness. It is packed into a * special CubeUV format that allows us to perform custom interpolation so that * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap * chain, it only goes down to the LOD_MIN level (above), and then creates extra * even more filtered 'mips' at the same LOD_MIN resolution, associated with * higher roughness levels. In this way we maintain resolution to smoothly * interpolate diffuse lighting while limiting sampling computation. */class PMREMGenerator{constructor(renderer){this._renderer=renderer;this._pingPongRenderTarget=null;this._blurMaterial=_getBlurShader(MAX_SAMPLES);this._equirectShader=null;this._cubemapShader=null;this._compileMaterial(this._blurMaterial);}/** * Generates a PMREM from a supplied Scene, which can be faster than using an * image if networking bandwidth is low. Optional sigma specifies a blur radius * in radians to be applied to the scene before PMREM generation. Optional near * and far planes ensure the scene is rendered in its entirety (the cubeCamera * is placed at the origin). */fromScene(scene){var sigma=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var near=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0.1;var far=arguments.length>3&&arguments[3]!==undefined?arguments[3]:100;_oldTarget=this._renderer.getRenderTarget();var cubeUVRenderTarget=this._allocateTargets();this._sceneToCubeUV(scene,near,far,cubeUVRenderTarget);if(sigma>0){this._blur(cubeUVRenderTarget,0,0,sigma);}this._applyPMREM(cubeUVRenderTarget);this._cleanup(cubeUVRenderTarget);return cubeUVRenderTarget;}/** * Generates a PMREM from an equirectangular texture, which can be either LDR * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512), * as this matches best with the 256 x 256 cubemap output. */fromEquirectangular(equirectangular){return this._fromTexture(equirectangular);}/** * Generates a PMREM from an cubemap texture, which can be either LDR * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256, * as this matches best with the 256 x 256 cubemap output. */fromCubemap(cubemap){return this._fromTexture(cubemap);}/** * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during * your texture's network fetch for increased concurrency. */compileCubemapShader(){if(this._cubemapShader===null){this._cubemapShader=_getCubemapShader();this._compileMaterial(this._cubemapShader);}}/** * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during * your texture's network fetch for increased concurrency. */compileEquirectangularShader(){if(this._equirectShader===null){this._equirectShader=_getEquirectShader();this._compileMaterial(this._equirectShader);}}/** * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on * one of them will cause any others to also become unusable. */dispose(){this._blurMaterial.dispose();if(this._cubemapShader!==null)this._cubemapShader.dispose();if(this._equirectShader!==null)this._equirectShader.dispose();for(var _i372=0;_i372<_lodPlanes.length;_i372++){_lodPlanes[_i372].dispose();}}// private interface _cleanup(outputTarget){this._pingPongRenderTarget.dispose();this._renderer.setRenderTarget(_oldTarget);outputTarget.scissorTest=false;_setViewport(outputTarget,0,0,outputTarget.width,outputTarget.height);}_fromTexture(texture){_oldTarget=this._renderer.getRenderTarget();var cubeUVRenderTarget=this._allocateTargets(texture);this._textureToCubeUV(texture,cubeUVRenderTarget);this._applyPMREM(cubeUVRenderTarget);this._cleanup(cubeUVRenderTarget);return cubeUVRenderTarget;}_allocateTargets(texture){// warning: null texture is valid var params={magFilter:NearestFilter,minFilter:NearestFilter,generateMipmaps:false,type:UnsignedByteType,format:RGBEFormat,encoding:_isLDR(texture)?texture.encoding:RGBEEncoding,depthBuffer:false};var cubeUVRenderTarget=_createRenderTarget(params);cubeUVRenderTarget.depthBuffer=texture?false:true;this._pingPongRenderTarget=_createRenderTarget(params);return cubeUVRenderTarget;}_compileMaterial(material){var tmpMesh=new Mesh(_lodPlanes[0],material);this._renderer.compile(tmpMesh,_flatCamera);}_sceneToCubeUV(scene,near,far,cubeUVRenderTarget){var fov=90;var aspect=1;var cubeCamera=new PerspectiveCamera(fov,aspect,near,far);var upSign=[1,-1,1,1,1,1];var forwardSign=[1,1,1,-1,-1,-1];var renderer=this._renderer;var outputEncoding=renderer.outputEncoding;var toneMapping=renderer.toneMapping;renderer.getClearColor(_clearColor);var clearAlpha=renderer.getClearAlpha();renderer.toneMapping=NoToneMapping;renderer.outputEncoding=LinearEncoding;var background=scene.background;if(background&&background.isColor){background.convertSRGBToLinear();// Convert linear to RGBE var maxComponent=Math.max(background.r,background.g,background.b);var fExp=Math.min(Math.max(Math.ceil(Math.log2(maxComponent)),-128.0),127.0);background=background.multiplyScalar(Math.pow(2.0,-fExp));var alpha=(fExp+128.0)/255.0;renderer.setClearColor(background,alpha);scene.background=null;}for(var _i373=0;_i373<6;_i373++){var col=_i373%3;if(col==0){cubeCamera.up.set(0,upSign[_i373],0);cubeCamera.lookAt(forwardSign[_i373],0,0);}else if(col==1){cubeCamera.up.set(0,0,upSign[_i373]);cubeCamera.lookAt(0,forwardSign[_i373],0);}else {cubeCamera.up.set(0,upSign[_i373],0);cubeCamera.lookAt(0,0,forwardSign[_i373]);}_setViewport(cubeUVRenderTarget,col*SIZE_MAX,_i373>2?SIZE_MAX:0,SIZE_MAX,SIZE_MAX);renderer.setRenderTarget(cubeUVRenderTarget);renderer.render(scene,cubeCamera);}renderer.toneMapping=toneMapping;renderer.outputEncoding=outputEncoding;renderer.setClearColor(_clearColor,clearAlpha);}_textureToCubeUV(texture,cubeUVRenderTarget){var renderer=this._renderer;if(texture.isCubeTexture){if(this._cubemapShader==null){this._cubemapShader=_getCubemapShader();}}else {if(this._equirectShader==null){this._equirectShader=_getEquirectShader();}}var material=texture.isCubeTexture?this._cubemapShader:this._equirectShader;var mesh=new Mesh(_lodPlanes[0],material);var uniforms=material.uniforms;uniforms['envMap'].value=texture;if(!texture.isCubeTexture){uniforms['texelSize'].value.set(1.0/texture.image.width,1.0/texture.image.height);}uniforms['inputEncoding'].value=ENCODINGS[texture.encoding];uniforms['outputEncoding'].value=ENCODINGS[cubeUVRenderTarget.texture.encoding];_setViewport(cubeUVRenderTarget,0,0,3*SIZE_MAX,2*SIZE_MAX);renderer.setRenderTarget(cubeUVRenderTarget);renderer.render(mesh,_flatCamera);}_applyPMREM(cubeUVRenderTarget){var renderer=this._renderer;var autoClear=renderer.autoClear;renderer.autoClear=false;for(var _i374=1;_i374MAX_SAMPLES){console.warn("sigmaRadians, ".concat(sigmaRadians,", is too large and will clip, as it requested ").concat(samples," samples when the maximum is set to ").concat(MAX_SAMPLES));}var weights=[];var sum=0;for(var _i375=0;_i375LOD_MAX-LOD_MIN?lodOut-LOD_MAX+LOD_MIN:0);_setViewport(targetOut,x,y,3*outputSize,2*outputSize);renderer.setRenderTarget(targetOut);renderer.render(blurMesh,_flatCamera);}}function _isLDR(texture){if(texture===undefined||texture.type!==UnsignedByteType)return false;return texture.encoding===LinearEncoding||texture.encoding===sRGBEncoding||texture.encoding===GammaEncoding;}function _createPlanes(){var _lodPlanes=[];var _sizeLods=[];var _sigmas=[];var lod=LOD_MAX;for(var _i377=0;_i377LOD_MAX-LOD_MIN){sigma=EXTRA_LOD_SIGMA[_i377-LOD_MAX+LOD_MIN-1];}else if(_i377==0){sigma=0;}_sigmas.push(sigma);var texelSize=1.0/(sizeLod-1);var min=-texelSize/2;var max=1+texelSize/2;var uv1=[min,min,max,min,max,max,min,min,max,max,min,max];var cubeFaces=6;var vertices=6;var positionSize=3;var uvSize=2;var faceIndexSize=1;var position=new Float32Array(positionSize*vertices*cubeFaces);var uv=new Float32Array(uvSize*vertices*cubeFaces);var faceIndex=new Float32Array(faceIndexSize*vertices*cubeFaces);for(var face=0;face2?0:-1;var coordinates=[x,y,0,x+2/3,y,0,x+2/3,y+1,0,x,y,0,x+2/3,y+1,0,x,y+1,0];position.set(coordinates,positionSize*vertices*face);uv.set(uv1,uvSize*vertices*face);var fill=[face,face,face,face,face,face];faceIndex.set(fill,faceIndexSize*vertices*face);}var planes=new BufferGeometry();planes.setAttribute('position',new BufferAttribute(position,positionSize));planes.setAttribute('uv',new BufferAttribute(uv,uvSize));planes.setAttribute('faceIndex',new BufferAttribute(faceIndex,faceIndexSize));_lodPlanes.push(planes);if(lod>LOD_MIN){lod--;}}return {_lodPlanes,_sizeLods,_sigmas};}function _createRenderTarget(params){var cubeUVRenderTarget=new WebGLRenderTarget(3*SIZE_MAX,3*SIZE_MAX,params);cubeUVRenderTarget.texture.mapping=CubeUVReflectionMapping;cubeUVRenderTarget.texture.name='PMREM.cubeUv';cubeUVRenderTarget.scissorTest=true;return cubeUVRenderTarget;}function _setViewport(target,x,y,width,height){target.viewport.set(x,y,width,height);target.scissor.set(x,y,width,height);}function _getBlurShader(maxSamples){var weights=new Float32Array(maxSamples);var poleAxis=new Vector3(0,1,0);var shaderMaterial=new RawShaderMaterial({name:'SphericalGaussianBlur',defines:{'n':maxSamples},uniforms:{'envMap':{value:null},'samples':{value:1},'weights':{value:weights},'latitudinal':{value:false},'dTheta':{value:0},'mipInt':{value:0},'poleAxis':{value:poleAxis},'inputEncoding':{value:ENCODINGS[LinearEncoding]},'outputEncoding':{value:ENCODINGS[LinearEncoding]}},vertexShader:_getCommonVertexShader(),fragmentShader:/* glsl */"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t".concat(_getEncodings(),"\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include \n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t"),blending:NoBlending,depthTest:false,depthWrite:false});return shaderMaterial;}function _getEquirectShader(){var texelSize=new Vector2(1,1);var shaderMaterial=new RawShaderMaterial({name:'EquirectangularToCubeUV',uniforms:{'envMap':{value:null},'texelSize':{value:texelSize},'inputEncoding':{value:ENCODINGS[LinearEncoding]},'outputEncoding':{value:ENCODINGS[LinearEncoding]}},vertexShader:_getCommonVertexShader(),fragmentShader:/* glsl */"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform vec2 texelSize;\n\n\t\t\t".concat(_getEncodings(),"\n\n\t\t\t#include \n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tvec2 f = fract( uv / texelSize - 0.5 );\n\t\t\t\tuv -= f * texelSize;\n\t\t\t\tvec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.x += texelSize.x;\n\t\t\t\tvec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.y += texelSize.y;\n\t\t\t\tvec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.x -= texelSize.x;\n\t\t\t\tvec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\n\t\t\t\tvec3 tm = mix( tl, tr, f.x );\n\t\t\t\tvec3 bm = mix( bl, br, f.x );\n\t\t\t\tgl_FragColor.rgb = mix( tm, bm, f.y );\n\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t"),blending:NoBlending,depthTest:false,depthWrite:false});return shaderMaterial;}function _getCubemapShader(){var shaderMaterial=new RawShaderMaterial({name:'CubemapToCubeUV',uniforms:{'envMap':{value:null},'inputEncoding':{value:ENCODINGS[LinearEncoding]},'outputEncoding':{value:ENCODINGS[LinearEncoding]}},vertexShader:_getCommonVertexShader(),fragmentShader:/* glsl */"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\t".concat(_getEncodings(),"\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t"),blending:NoBlending,depthTest:false,depthWrite:false});return shaderMaterial;}function _getCommonVertexShader(){return/* glsl */"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute vec3 position;\n\t\tattribute vec2 uv;\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t";}function _getEncodings(){return/* glsl */"\n\n\t\tuniform int inputEncoding;\n\t\tuniform int outputEncoding;\n\n\t\t#include \n\n\t\tvec4 inputTexelToLinear( vec4 value ) {\n\n\t\t\tif ( inputEncoding == 0 ) {\n\n\t\t\t\treturn value;\n\n\t\t\t} else if ( inputEncoding == 1 ) {\n\n\t\t\t\treturn sRGBToLinear( value );\n\n\t\t\t} else if ( inputEncoding == 2 ) {\n\n\t\t\t\treturn RGBEToLinear( value );\n\n\t\t\t} else if ( inputEncoding == 3 ) {\n\n\t\t\t\treturn RGBMToLinear( value, 7.0 );\n\n\t\t\t} else if ( inputEncoding == 4 ) {\n\n\t\t\t\treturn RGBMToLinear( value, 16.0 );\n\n\t\t\t} else if ( inputEncoding == 5 ) {\n\n\t\t\t\treturn RGBDToLinear( value, 256.0 );\n\n\t\t\t} else {\n\n\t\t\t\treturn GammaToLinear( value, 2.2 );\n\n\t\t\t}\n\n\t\t}\n\n\t\tvec4 linearToOutputTexel( vec4 value ) {\n\n\t\t\tif ( outputEncoding == 0 ) {\n\n\t\t\t\treturn value;\n\n\t\t\t} else if ( outputEncoding == 1 ) {\n\n\t\t\t\treturn LinearTosRGB( value );\n\n\t\t\t} else if ( outputEncoding == 2 ) {\n\n\t\t\t\treturn LinearToRGBE( value );\n\n\t\t\t} else if ( outputEncoding == 3 ) {\n\n\t\t\t\treturn LinearToRGBM( value, 7.0 );\n\n\t\t\t} else if ( outputEncoding == 4 ) {\n\n\t\t\t\treturn LinearToRGBM( value, 16.0 );\n\n\t\t\t} else if ( outputEncoding == 5 ) {\n\n\t\t\t\treturn LinearToRGBD( value, 256.0 );\n\n\t\t\t} else {\n\n\t\t\t\treturn LinearToGamma( value, 2.2 );\n\n\t\t\t}\n\n\t\t}\n\n\t\tvec4 envMapTexelToLinear( vec4 color ) {\n\n\t\t\treturn inputTexelToLinear( color );\n\n\t\t}\n\t";}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;var NoColors=0;var FaceColors=1;var VertexColors=2;function MeshFaceMaterial(materials){console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');return materials;}function MultiMaterial(){var materials=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];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$1(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().setUsage( THREE.DynamicDrawUsage ) instead.');return new BufferAttribute(array,itemSize).setUsage(DynamicDrawUsage);}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;};// Object.assign(CurvePath.prototype,{createPointsGeometry:function createPointsGeometry(divisions){console.warn('THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');// generate geometry from path points (for Line or Points objects) var pts=this.getPoints(divisions);return this.createGeometry(pts);},createSpacedPointsGeometry:function createSpacedPointsGeometry(divisions){console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');// generate geometry from equidistant sampling along the path var pts=this.getSpacedPoints(divisions);return this.createGeometry(pts);},createGeometry:function createGeometry(points){console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');var geometry=new Geometry();for(var _i378=0,l=points.length;_i378 p.ids.includes(o));else { point = points.find(p => math.closeTo(p.x, o.x, precision) && math.closeTo(p.y, o.y, precision)); if (!point) point = new Point(o.x, o.y, { record: true, id: o.id }, type);else { //console.log('addPoint', point, o) point.addPoint(o.id); } } if (!point) { console.log("no point!"); } return point; }; var getLine = function getLine(id) { return lines.find(line => line.ids.includes(id)); }; var getAngleInfo = function getAngleInfo(points) { var info = {}; info.angle = points[1].clone().sub(points[0]).angle(); if (math.closeTo(info.angle, Math.PI * 2)) { //如360-0.01 info.angle -= Math.PI * 2; //有可能得到负数-0.001 } else if (info.angle > Math.PI || math.closeTo(info.angle, Math.PI)) { //如180+-0.01 info.angle -= Math.PI; info.reverse = true; } return info; //结果大约是 0 - 3.14 }; class Point extends Vector2 { constructor(x, y) { var o = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; super(x, y); if (o.record) { this.id = o.id; if (this.id == void 0) this.id = "add_" + points.length; this.ids = [this.id]; //存储拥有该坐标的点原始数据的id points.push(this); } this.type = o.type || ""; this.lines = []; } addPoint(id) { this.ids.push(id); } searchLineByFactor(dir, type, comeLine) { var lines = this.lines.filter(line => line.searchTime < 2); if (lines.length == 0) return;else if (lines.length == 1) return lines[0];else lines = lines.filter(line => line != comeLine); if (lines.length == 1) return lines[0]; var result; lines.forEach(line => { var vec = line.getVector(); if (line.points[1] == this) vec.negate(); var factor = math.getVec2Angle(dir, vec); if (new Vector3(dir.x, dir.y, 0).cross(new Vector3(vec.x, vec.y, 0)).z < 0) factor *= -1; ///// if (!result) { result = { line, factor }; } else { if (type == "min" && factor < result.factor || type == "max" && factor > result.factor) result = { line, factor }; } }); return result.line; } } var lineLen = 0; class Line$1 { constructor(o) { if (o.points[0] == o.points[1]) return; this.points = o.points; this.type = o.type || 'line'; if (this.type == 'line') { var oldLine = lines.find(line => line.points.includes(o.points[0]) && line.points.includes(o.points[1])); if (oldLine) { o.id != void 0 && oldLine.ids.push(o.id); return oldLine; } this.id = o.id == void 0 ? "line" + lineLen++ : o.id; this.ids = [this.id]; o.dontWriteToPoint || this.points.forEach(point => { point.lines.push(this); }); o.isChild || lines.push(this); this.searchTime = 0; // 最多两次 } this.children = []; //分割 this.parents = []; //分割 this.match = []; } getAngleInfo() { var angleInfo = getAngleInfo(this.points); this.angle = angleInfo.angle; this.reverse = angleInfo.reverse; } getIntersectWithLine(line, precision) { var joint = line.points.find(point => this.points.includes(point)); if (joint) return { point: joint, type: "joint" }; var intersect = math.isLineIntersect(line.points, this.points, false, precision); if (intersect) return { point: intersect, type: "intersect" }; } writeToPoint() { this.points.forEach(point => { point.lines.includes(this) || point.lines.push(this); }); } checkIfParent(line) { if (this == line) { return true; //原因就是slice的点和端点很近 误差导致 } else return this.parents.find(e => e.checkIfParent(line)); } splitByPoint(point) { var line1 = new Line$1({ points: [point, this.points[0]], dontWriteToPoint: true, hasntsure: true }); var line2 = new Line$1({ points: [point, this.points[1]], dontWriteToPoint: true, hasntsure: true }); if (!line1.points || !line2.points) { //有至少一个是点相同的,没写到group.lines里 console.warn('splitByPoint 线有点相同'); return; } if (this.checkIfParent(line1) || this.checkIfParent(line2) || line1.checkIfParent(this) || line2.checkIfParent(this)) { console.warn("splitByPoint 发现parent和children一样"); //,请检查getSliceWalls,尤其 if(math.closeTo(line1.angle,line2.angle)){ 处 return; } var deal = line => { this.children.push(line); line.parents.push(this); if (!lines.includes(line)) lines.push(line); line.writeToPoint(); }; deal(line1); deal(line2); var index = this.points[0].lines.indexOf(this); index > -1 && this.points[0].lines.splice(index, 1); var index = this.points[1].lines.indexOf(this); index > -1 && this.points[1].lines.splice(index, 1); return [line1, line2]; } splitByPoints(points) { points = points.map(point => { return { dis: point.distanceTo(this.points[0]), point: point }; }); points.sort((point1, point2) => { return point1.dis - point2.dis; }); var children = []; points.forEach((point, index) => { var line1 = new Line$1({ points: [point.point, index == 0 ? this.points[0] : points[index - 1].point], group: this.group, dontWriteToPoint: true, hasntsure: true }); children.push(line1); }); var line2 = new Line$1({ points: [points[points.length - 1].point, this.points[1]], group: this.group, dontWriteToPoint: true, hasntsure: true }); children.push(line2); var a = children.find(line => !line.points || this.checkIfParent(line) || line.checkIfParent(this)); if (a) { console.error("splitByPoints return"); return; } children.forEach(line => { this.children.push(line); line.parents.push(this); if (!lines.includes(line)) lines.push(line); line.writeToPoint(); line.writeToPoint(); }); var index = this.points[0].lines.indexOf(this); index > -1 && this.points[0].lines.splice(index, 1); var index = this.points[1].lines.indexOf(this); index > -1 && this.points[1].lines.splice(index, 1); } getAllSlices() { //如果有被分割的片段 就返回片段,否则返回自身 var children = []; var _traverse = function traverse(elem) { if (elem.children.length == 0) children.push(elem);else elem.children.forEach(_traverse); }; _traverse(this); return children; } getVector() { return this.points[1].clone().sub(this.points[0]); } getLength() { return this.points[0].distanceTo(this.points[1]); } getCenter() { return this.points[1].clone().add(this.points[0]).multiplyScalar(.5); } } var getMixedSet = function getMixedSet(arr1, arr2) { //交集 return arr1.filter(item => arr2.includes(item)); }; var getUnionSet = function getUnionSet(arr1, arr2) { //并集 return arr1.concat(arr2.filter(item => !arr1.includes(item))); }; var getDifferenceSet = function getDifferenceSet(arr1, arr2) { //差集 var arr11 = arr1.filter(item => !arr2.includes(item)); var arr22 = arr2.filter(item => !arr1.includes(item)); return arr11.concat(arr22); }; var getDifferenceSetMuti = function getDifferenceSetMuti(arr) { //收集绝对没有重复的元素,也就是判断出现次数=1的 var set = []; arr.forEach(arr1 => { arr1.forEach(item => { var index = set.indexOf(item); if (index > -1) { set.splice(index, 1); } else { set.push(item); } }); }); return set; }; function DoorAtWhichLine(points, lines) { var mid = points[0].clone().add(points[1]).multiplyScalar(0.5); lines = lines.filter(line => math.ifPointAtLineBound(mid, line.points, precision)); if (lines.length == 0) return; var result = { line: null, dis: Infinity }; lines.forEach(line => { var foot = math.getFootPoint(mid, line.points[0], line.points[1]); var dis = foot.distanceTo(mid); if (dis < result.dis) { result.line = line; result.dis = dis; } }); return result; } var ringLen = 0; class Ring { constructor(o) { this.id = ringLen++; this.type = o.type || 'normal'; this.points = o.points; this.lines = o.lines; rings.push(this); this.child = []; //包含的环 this.parent = []; //被包含的环 this.smallNeibours = []; //相邻最小环(存在和它有一个以上的相同边的最小环) var area = math.getArea(this.points); this.area = Math.abs(area); this.isClockwise = area < 0; //是否逆时针。一般都是逆时针得到的,如果是顺时针,可能是贪吃蛇的情况,可能不是最小环,需要去掉。 } } var findLine = function findLine(p1, p2) { return lines.find(line => line.points.includes(p1) && line.points.includes(p2)); }; var ifSamePart = function ifSamePart(checkPart, part) { //checkPart中所包含的part片段是否和基准part的顺序一样(逆序也可以, 中间有其他数也可以,起始不同也行。比如 01234和204一样的) var axis, startIndex, newCheckPart = []; for (var j = 0, len1 = checkPart.length; j < len1; j++) { //将checkPart中比part多的数除去,使两个数组中包含的数完全相同。 if (part.indexOf(checkPart[j]) > -1) newCheckPart.push(checkPart[j]); } for (var i = 0, len = part.length; i < len; i++) { var index = newCheckPart.indexOf(part[i]); if (index == -1) return false; if (i == 0) startIndex = index; //标记第一个查找点对应的index else if (i == 1) { //标记查找顺序是正还是逆 axis = index - startIndex; if (axis == len - 1) axis = -1; //刚好是首和尾 else if (axis == 1 - len) axis = 1; if (axis != -1 && axis != 1) { return false; } } else { //判断是否是按顺序的 if (index != (startIndex + axis * i + len) % len) return false; } } return { sameAxis: axis > 0 }; //如果一样的话返回正逆是否相同 }; //或者判断是否有相同边(但是相同点是可以组成不同环) var ifSameRing = function ifSameRing(ring1, ring2) { //判断两个环是否相等。 除了可以逆向外顺序要对 if (ring1 instanceof Ring) ring1 = ring1.points; if (ring2 instanceof Ring) ring2 = ring2.points; if (ring1.length != ring2.length) return false; if (ring1.lines && ring2.lines) { if (getDifferenceSet(ring1.lines, ring2.lines).length == 0) return true; //差集个数为0 } else { if (ifSamePart(ring1, ring2)) return true; } }; var _atWhichChildLine = function atWhichChildLine(point, line, precision) { if (line.children.length == 0) { //这里可能要放低精度 保证能找到 if (math.ifPointAtLineBound(point, line.points, precision)) return line; } else { for (var i = 0; i < line.children.length; i++) { var at = _atWhichChildLine(point, line.children[i], precision); if (at) return at; } } }; function getSliceLines() { var len = lines.length; var _deal = function deal(line1, line2) { if (line1 == line2) return; if (line1.angle == void 0) line1.getAngleInfo(); if (line2.angle == void 0) line2.getAngleInfo(); var intersect = line1.getIntersectWithLine(line2, precision); if (intersect) { var point; //得到交点 if (intersect.type == "intersect") { point = getPoint(intersect.point, "whenGetSliceLines"); var line1_ = _atWhichChildLine(point, line1); var line2_ = _atWhichChildLine(point, line2); //重合的情况还没考虑(平行) if (!line1_) line1_ = _atWhichChildLine(point, line1, precision); //降低精度 if (!line1_) line1_ = _atWhichChildLine(point, line1, precision * 2); //降低精度 if (!line2_) line2_ = _atWhichChildLine(point, line2, precision); if (!line2_) line2_ = _atWhichChildLine(point, line2, precision * 2); //降低精度 //拆分线条: //如果还报错,找不到ChildLine,就直接返回吧 或者搞个循环 逐渐降低精度 if (!line1_ || !line2_) { console.warn("atWhichChildLine仍旧找不到 :" + line1.id + ',' + line2.id + ", pointId: " + point.id); line1_ || console.warn("找不到line1"); line2_ || console.warn("找不到line2"); return; } if (line1_.points.find(p => p == point) && line2_.points.find(p => p == point)) {//这个点是line1_、 line2_端点,不做处理 //console.log("joint型 "+point.id) } else if (line1_.points.find(p => p == point)) { //T型交叉 line2_.splitByPoint(point); //加入到母线中,之后还先用母线判断交点 //console.log("T型交叉1 "+point.id) } else if (line2_.points.find(p => p == point)) { //T型交叉 line1_.splitByPoint(point); //console.log("T型交叉2 "+point.id) } else { //十字交叉 line1_.splitByPoint(point); line2_.splitByPoint(point); } } else { point = intersect.point; //交点是端点 if (math.closeTo(line1.angle, line2.angle)) { //重合一部分 var children1 = line1.getAllSlices(); var children2 = line2.getAllSlices(); if (children1.length > 1 || children2.length > 1) { //使用最小分割片段来比较 children1.forEach(child1 => { children2.forEach(child2 => { _deal(child1, child2); }); }); return; } var anotherPoint1 = line1.points.find(point_ => point_ != point); var anotherPoint2 = line2.points.find(point_ => point_ != point); if (math.ifPointAtLineBound(anotherPoint1, line2.points)) { line2.splitByPoint(anotherPoint1); } else if (math.ifPointAtLineBound(anotherPoint2, line1.points)) { line1.splitByPoint(anotherPoint2); } } } } else if (math.closeTo(line1.angle, line2.angle)) { var vec1 = line1.getVector(); var vec = line1.points[0].clone().sub(line2.points[0]); var cos = math.getVec2Cos(vec1, vec); if (math.closeTo(cos, -1, 1e-4) || math.closeTo(cos, 1, 1e-4)) { //共线 var children1 = line1.getAllSlices(); var children2 = line2.getAllSlices(); if (children1.length > 1 || children2.length > 1) { //使用最小分割片段来比较 children1.forEach(child1 => { children2.forEach(child2 => { _deal(child1, child2); }); }); return; } //判断是否重叠 var A = line1.points[0]; var C = line1.reverse == line2.reverse ? line2.points[0] : line2.points[1]; var B = line1.points[1]; var D = line1.reverse == line2.reverse ? line2.points[1] : line2.points[0]; var BC = C.clone().sub(B); var AD = D.clone().sub(A); if (BC.length() < AD.length()) { var BA = A.clone().sub(B); if (math.getVec2Angle(BC, BA) >= 1.57) return; //没有重叠部分 } else { var AB = B.clone().sub(A); if (math.getVec2Angle(AD, AB) >= 1.57) return; } var f = function f(line1, line2) { var one = math.ifPointAtLineBound(line1.points[0], line2.points); var two = math.ifPointAtLineBound(line1.points[1], line2.points); if (one && two) { //line1在line2上 line2.splitByPoints(line1.points); return true; } else if (one || two) { //错开 var point1 = one ? line1.points[0] : line1.points[1]; var anotherPoint1 = one ? line1.points[1] : line1.points[0]; var dis1 = line2.points[0].distanceTo(anotherPoint1); var dis2 = line2.points[1].distanceTo(anotherPoint1); var point2 = dis1 < dis2 ? line2.points[0] : line2.points[1]; line1.splitByPoint(point2); line2.splitByPoint(point1); return true; } }; f(line1, line2) || f(line2, line1); } } }; for (var i = 0; i < len; i++) { var line1 = lines[i]; for (var j = i + 1; j < len; j++) { var line2 = lines[j]; _deal(line1, line2); } } //console.log("原有线条个数:"+len) //lines = lines.filter((line)=>{return line.children.length == 0}) //console.log("现有线条个数:"+lines.length) } var bound = new Box2(); var build = function build(o) { //融合了相近点 //根据bound 处理precision o.points.forEach(p => { bound.expandByPoint(new Vector2(p.x, p.y)); }); if (o.precision != void 0) { precision = o.precision; } else { var boundSize = bound.getSize(new Vector2()); precision = MathUtils.clamp(Math.max(boundSize.x, boundSize.y) / 70, 0.2, 2); } o.points.forEach(point => getPoint(point)); //{x:..,y:..} o.lines.forEach(line => { //{p1:id1. p2:id2} new Line$1({ points: [getPoint(line.p1), getPoint(line.p2)], id: line.id }); }); //注意:不能出现一条线的两个点坐标一致,否则寻路时方向出错。 所以手动融合下相近点。 }; var searchRings = function searchRings() { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; points = []; lines = []; rings = []; lineLen = ringLen = 0; o.points = o.points || []; o.lines = o.lines || []; build(o); if (!o.dontSliceLines) { getSliceLines(); } //查找最小回路: //参考: 引入方向因子的最小回路、最大回路搜索算法.pdf //方法: 逆时针寻找(标记)最外层大环 -->从走过的点开始逆时针寻找最小环(直到所有可走的路被走过两次)-->逆时针寻找最外层大环(直到所有可走的路被走过两次)-->.. //其中找大环时选择方向因子最小的路, 而小环则相反(但只有开始第一条路是一样的, 都是选择最左边的点的因子最小的路)。 //标记方法: 每条线需要被搜索两次才算完毕。搜索完毕的线退出搜索。(依据:搜索完全部最小回路后 , 在无向图中删除搜索过 2 次的边及孤立节点得到退化图 , 恰好构成最大回路。) var searchTime = 0; var addRingJudgeCount = 0; var addRingJudge = function addRingJudge(ring, lines, connectedLines, type) { // 处理拣出的片段 addRingJudgeCount++; //console.log("addRingJudge points("+ type+"):"+ ring.map(point=>point.id) ) if (o.onlyGetOutRing && type == "small") return; if (type == "small" || o.onlyGetOutRing) { //挑出回路: var newRings = []; while (ring.length) { var road = []; var turnBack = false; for (var i = 0; i < ring.length; i++) { if (road.includes(ring[i])) { //如果走到方才的点,可能形成回路。 无论是不是回路都要摘去这段。 var index = road.indexOf(ring[i]); var pointArr = ring.slice(index, i); var linesArr = lines.slice(index, i); ring.splice(index, i - index); lines.splice(index, i - index); if (pointArr.length > 2) { // 如果只有两个数,代表原路返回, 如 1->2(->1) if (!rings.find(ring_ => ifSameRing(pointArr, ring_))) newRings.push(new Ring({ points: pointArr, lines: linesArr })); } turnBack = true; break; } else { road.push(ring[i]); turnBack = false; } } if (!turnBack) { //没有重复的点,那么就直接处理整条。 if (ring.length > 2) { // 如果只有两个数,代表原路返回, 如 1->2(->1) if (!rings.find(ring_ => ifSameRing(ring, ring_))) newRings.push(new Ring({ points: ring, lines })); } break; } } if (type != 'small') { newRings.forEach(e => e.isOutRing = true); } //console.log(newRings) } else { return ring; } }; var _search = function search(point2d, comeRoad, type, connectedLines) { searchTime++; var goLine; var direction; if (type.includes("big")) { if (!comeRoad) { if (type.includes("Left")) { //逆时针 direction = new Vector2(1, 0); } else { direction = new Vector2(-1, 0); } goLine = point2d.searchLineByFactor(direction, "min"); } else { var lastPoint = comeRoad.points[comeRoad.points.length - 1]; direction = point2d.clone().sub(lastPoint); goLine = point2d.searchLineByFactor(direction, "min", findLine(point2d, lastPoint)); } } else { if (!comeRoad) { //似乎找最小环时,第一条线也是找最小的因子,这样才能保证逆时针(除非只有顺时针一条路) direction = new Vector2(1, 0); goLine = point2d.searchLineByFactor(direction, "min"); } else { var lastPoint = comeRoad.points[comeRoad.points.length - 1]; direction = point2d.clone().sub(lastPoint); goLine = point2d.searchLineByFactor(direction, "max", findLine(point2d, lastPoint)); } } if (!goLine) return; goLine.searchTime++; connectedLines.includes(goLine) || connectedLines.push(goLine); var nextPoint = goLine.points.find(point => point2d != point); //if( comeRoad && comeRoad.points[comeRoad.points.length - 1] == nextPoint ) return;//不能查找来时的方向(反方向) //走不通就原路返回 var roadPoints = comeRoad ? comeRoad.points.concat([point2d]) : [point2d]; //每个分叉都能构成一条新的road var roadLines = comeRoad ? comeRoad.lines.concat([goLine]) : [goLine]; //走到第一个点就算停止,这时候可能得到一个环、或者一段走了两遍的线、或者一条线上带了些环。 if (nextPoint == roadPoints[0]) return addRingJudge(roadPoints, roadLines, connectedLines, type); //形成环 else { /* var len = roadPoints.indexOf(nextPoint); if( len > -1){ //走到走过的路的某一点 构成这段路的回路 var points = roadPoints.slice(len, roadPoints.length); var lines = roadLines.slice(len, roadPoints.length); addRingJudge(points, lines) }else{ */ return _search(nextPoint, { lines: roadLines, points: roadPoints }, type, connectedLines); //继续寻路 //} } }; while (1) { //搜寻一次大环 var connectedLines = []; //被搜寻过的且searchTime<2的线。一旦全部搜完就说明该连通区域搜寻完毕,继续查下一个连通区域。 var startPoint = null; points.forEach(point => { //找出x最小的点 if (!point.lines.find(line => line.searchTime < 2)) return; if (!startPoint) startPoint = point;else if (point.x < startPoint.x) startPoint = point; }); if (!startPoint) break; //说明全部找完 var ring = _search(startPoint, null, "bigLeft", connectedLines); //逆时针 //search(startPoint, null, "bigRight", connectedLines);//顺时针(为了防止最外层不是回路之前写了顺时针,但如果是回路就会走重复。后来发现只要逆时针即可,因为走完后剩下的可以再次找大环) connectedLines = connectedLines.filter(line => line.searchTime < 2); var _loop = function _loop() { //目标是顺着connectedLines把所有连通的小环都找到 var points_ = []; //connectedLines中所有的点 connectedLines.forEach(line => line.points.forEach(point => { if (!points_.includes(point)) points_.push(point); })); startPoint = null; points_.forEach(point => { //找出x最小的点 if (!point.lines.find(line => line.searchTime < 2)) return; if (!startPoint) startPoint = point;else if (point.x < startPoint.x) startPoint = point; }); if (!startPoint) return 1; // break _search(startPoint, null, "small", connectedLines); connectedLines = connectedLines.filter(line => line.searchTime < 2); }, startPoint; while (connectedLines.length > 0) { if (_loop()) break; } } /* if(o.onlyGetOutRing){ rings = rings.filter(e=>e.isOutRing) } */ //console.log("searchTime "+searchTime + ", addRingJudgeCount " +addRingJudgeCount) //找出所有的相邻关系,包括公共边 var len = rings.length; for (var i = 0; i < len; i++) { var ring1 = rings[i]; for (var j = i + 1; j < len; j++) { var ring2 = rings[j]; var bothHasLines = getMixedSet(ring1.lines, ring2.lines); if (bothHasLines.length) { //ring1oíring2?àáú ring1.smallNeibours.push(ring2); ring2.smallNeibours.push(ring1); } else {} } } rings.forEach(ring1 => { for (var _i = 0; _i < len; _i++) { var ring2 = rings[_i]; if (ring1 == ring2 || ring1.smallNeibours.includes(ring2)) continue; var inside = void 0; for (var u = 0; u < ring1.points.length; u++) { inside = math.isPointInArea(ring2.points, null, ring1.points[u]); if (!inside) break;else if (inside && !inside.atLine) { break; } } if (inside) { //只要其中一个点在ring2内,就说明ring1是内环 if (inside.atLine) { //(还是会存在点全在线上的情况,这时候判断中心点) var center = math.getCenterOfGravityPoint(ring1.points); var inside1 = math.isPointInArea(ring2.points, null, center); if (!inside1) { continue; } } ring2.child.push(ring1); ring1.parent.push(ring2); } } }); //去除非最小的ring 是否应该检测parent child? /* like this: |———————————————————————| |———|———————|———————| | | | | | | | |———————|———————| | |———————————————————————| */ var wiseRings = rings.filter(r => !r.isClockwise); //一般都是逆时针得到的,如果是顺时针,可能是贪吃蛇的情况,可能不是最小环,需要去掉。 if (wiseRings.length > 0) { //console.log('%c存在非最小的ring! 进行处理:',"color:#00f"); wiseRings.forEach(ring => { //(此案例验证出smallNeibours就是它的最小构成,可以再看看别的案例) if (ring.smallNeibours.length > 0) { //另:如果内部只有一个,说明它是最小环,不需要处理 var is = false; var difference = getDifferenceSet(ring.lines, getDifferenceSetMuti(ring.smallNeibours.concat(ring.child).map(ring => ring.lines))); //获取所有smallNeibours和child的边中没有重复过的边(就是outline) 和该ring的线比较 is = difference.every(line => ring.child.find(r => r.lines.includes(line))); //多出的线只能是child中的线 if (is) { console.log('%c删除非最小环 ring' + ring.id, "color:#00f"); console.log(ring); rings.splice(rings.indexOf(ring), 1); ring.child.forEach(c => { var index = c.parent.indexOf(ring); index > -1 && c.parent.splice(index, 1); }); ring.parent.forEach(c => { var index = c.child.indexOf(ring); index > -1 && c.child.splice(index, 1); }); ring.smallNeibours.forEach(c => { var index = c.smallNeibours.indexOf(ring); index > -1 && c.smallNeibours.splice(index, 1); }); } } }); } /* rings = rings.filter(ring=>{ rings = rings.filter(ring=>{ var enoughSize = ring.area > 0.5 if(!enoughSize){console.log('因面积过小去除ring '+ring.id + " , area: "+ring.area)} return enoughSize }) rings.forEach(ring=>{ if(ring.closetChilds){ ring.closetChilds = ring.closetChilds.filter(e=>rings.includes(e)) } }) return rings }) */ //在dealRings前不能随意删除rings,因为判断是否是最小环时需要全部的环 rings.forEach(ring => { //这里和cad中的不太一样, cad中双数个parent算外环,单数内环; 这里不分内外, 只看有无parent child if (ring.parent.length) { ring.closetParent = ring.parent.find(ring_ => ring_.parent.length == ring.parent.length - 1); //最近一层的大环就是比它的parent个数少一的 ring.closetParent.closetChilds || (ring.closetParent.closetChilds = []); //内环可能多个 ring.closetParent.closetChilds.push(ring); } }); //console.log(rings) var _ring = rings.map(ring => { var data = { id: ring.id, points: ring.points.map(point => { return { id: point.ids[0], x: point.x, y: point.y }; }), /* doors : o.doors.filter(door=>{ if(ring.closetChilds){ var childOutLines = getDifferenceSetMuti(ring.closetChilds.map(ring=>ring.lines)) //最近子环的外边 return ring.lines.concat(childOutLines).includes(door.atLine) }else{ return ring.lines.includes(door.atLine) } }), */ area: ring.area, closetParent: ring.closetParent && ring.closetParent.id, closetChilds: ring.closetChilds && ring.closetChilds.map(e => e.id) }; return data; }); //console.log(JSON.stringify(_ring)) return _ring; }; var easing = {}; //渐变曲线函数,反应加速度的变化 //currentTime:x轴当前时间(从0-到duration), startY:起始点, duration:总时长, wholeY:路程 (即endY-startY) //参数基本是 x, 0, 1, 1 /* easeOut 基本是y= m * (x-dur)^k + n, 若k为偶数,m<0, 若k为奇数,m>0; (因为偶数的话必须开口向下才能获得斜率递减的递增的那段,而奇数是对称的,单调递增. ) 根据x=0时y=0, x=dur时y=S , 得 n = S,m = -S/(-dur)^k */ easing.getEaseOut = function (k) { // k 是>=2的整数. 越大变化率越大, 相同初始速度所需要时间越久 var easeFun; k = Math.round(k); if (k < 2) { k = Math.PI / 2; easeFun = easing.easeOutSine; } else { easeFun = function easeFun(currentTime, startY, wholeY, duration) { if (k > 2) { console.log(k); } return -wholeY / Math.pow(-duration, k) * Math.pow(currentTime - duration, k) + wholeY; }; } return { k, easeFun }; }; easing.linearTween = function (currentTime, startY, wholeY, duration) { return wholeY * currentTime / duration + startY; }, easing.easeInQuad = function (currentTime, startY, wholeY, duration) { return currentTime /= duration, wholeY * currentTime * currentTime + startY; }, easing.easeOutQuad = function (currentTime, startY, wholeY, duration) { // 如套上实际的距离S和时长dur, y = - S / dur *(x^2-2x) 当s为1,dur为1时,是 y = -(x-1)^2 + 1 , 在0-1中是斜率递减的递增函数. 导数- S / dur *(2x-2 ) 可求出实时速度 故在0这一时刻,速度为 2S/dur return currentTime /= duration, -wholeY * currentTime * (currentTime - 2) + startY; }, easing.easeInOutQuad = function (currentTime, startY, wholeY, duration) { return currentTime /= duration / 2, currentTime < 1 ? wholeY / 2 * currentTime * currentTime + startY : (currentTime--, -wholeY / 2 * (currentTime * (currentTime - 2) - 1) + startY); }, easing.easeInCubic = function (currentTime, startY, wholeY, duration) { return currentTime /= duration, wholeY * currentTime * currentTime * currentTime + startY; }, easing.easeOutCubic = function (currentTime, startY, wholeY, duration) { // y = S / dur^3 *(x-dur)^3 + S,对称中心是(dur,S),从0-dur是 斜率递减的递增函数,导数为3S/dur^3 * (x-dur)^2, 0时速度为3S/dur return currentTime /= duration, currentTime--, wholeY * (currentTime * currentTime * currentTime + 1) + startY; }, easing.easeInOutCubic = function (currentTime, startY, wholeY, duration) { return currentTime /= duration / 2, currentTime < 1 ? wholeY / 2 * currentTime * currentTime * currentTime + startY : (currentTime -= 2, wholeY / 2 * (currentTime * currentTime * currentTime + 2) + startY); }, easing.easeInQuart = function (currentTime, startY, wholeY, duration) { return currentTime /= duration, wholeY * currentTime * currentTime * currentTime * currentTime + startY; }, easing.easeOutQuart = function (currentTime, startY, wholeY, duration) { //根据上面的计算,估计0时速度应该是4S/dur吧…… return currentTime /= duration, currentTime--, -wholeY * (currentTime * currentTime * currentTime * currentTime - 1) + startY; }, easing.easeInOutQuart = function (currentTime, startY, wholeY, duration) { return currentTime /= duration / 2, currentTime < 1 ? wholeY / 2 * currentTime * currentTime * currentTime * currentTime + startY : (currentTime -= 2, -wholeY / 2 * (currentTime * currentTime * currentTime * currentTime - 2) + startY); }, easing.easeInQuint = function (currentTime, startY, wholeY, duration) { return currentTime /= duration, wholeY * currentTime * currentTime * currentTime * currentTime * currentTime + startY; }, easing.easeOutQuint = function (currentTime, startY, wholeY, duration) { return currentTime /= duration, currentTime--, wholeY * (currentTime * currentTime * currentTime * currentTime * currentTime + 1) + startY; }, easing.easeInOutQuint = function (currentTime, startY, wholeY, duration) { return currentTime /= duration / 2, currentTime < 1 ? wholeY / 2 * currentTime * currentTime * currentTime * currentTime * currentTime + startY : (currentTime -= 2, wholeY / 2 * (currentTime * currentTime * currentTime * currentTime * currentTime + 2) + startY); }, easing.easeInSine = function (currentTime, startY, wholeY, duration) { return -wholeY * Math.cos(currentTime / duration * (Math.PI / 2)) + wholeY + startY; }, easing.easeOutSine = function (currentTime, startY, wholeY, duration) { // y' = S * PI / 2 / dur * cos(PI/2/dur * x) return wholeY * Math.sin(currentTime / duration * (Math.PI / 2)) + startY; }, easing.easeInOutSine = function (currentTime, startY, wholeY, duration) { return -wholeY / 2 * (Math.cos(Math.PI * currentTime / duration) - 1) + startY; }, easing.easeInExpo = function (currentTime, startY, wholeY, duration) { return wholeY * Math.pow(2, 10 * (currentTime / duration - 1)) + startY; }, easing.easeOutExpo = function (currentTime, startY, wholeY, duration) { return wholeY * (-Math.pow(2, -10 * currentTime / duration) + 1) + startY; }, easing.easeInOutExpo = function (currentTime, startY, wholeY, duration) { return currentTime /= duration / 2, currentTime < 1 ? wholeY / 2 * Math.pow(2, 10 * (currentTime - 1)) + startY : (currentTime--, wholeY / 2 * (-Math.pow(2, -10 * currentTime) + 2) + startY); }, easing.easeInCirc = function (currentTime, startY, wholeY, duration) { return currentTime /= duration, -wholeY * (Math.sqrt(1 - currentTime * currentTime) - 1) + startY; }, easing.easeOutCirc = function (currentTime, startY, wholeY, duration) { return currentTime /= duration, currentTime--, wholeY * Math.sqrt(1 - currentTime * currentTime) + startY; }, easing.easeInOutCirc = function (currentTime, startY, wholeY, duration) { return currentTime /= duration / 2, currentTime < 1 ? -wholeY / 2 * (Math.sqrt(1 - currentTime * currentTime) - 1) + startY : (currentTime -= 2, wholeY / 2 * (Math.sqrt(1 - currentTime * currentTime) + 1) + startY); }, easing.easeInElastic = function (currentTime, startY, wholeY, duration) { var r = 1.70158, o = 0, a = wholeY; return 0 === currentTime ? startY : 1 === (currentTime /= duration) ? startY + wholeY : (o || (o = .3 * duration), a < Math.abs(wholeY) ? (a = wholeY, r = o / 4) : r = o / (2 * Math.PI) * Math.asin(wholeY / a), -(a * Math.pow(2, 10 * (currentTime -= 1)) * Math.sin((currentTime * duration - r) * (2 * Math.PI) / o)) + startY); }, easing.easeOutElastic = function (currentTime, startY, wholeY, duration) { var r = 1.70158, o = 0, a = wholeY; return 0 === currentTime ? startY : 1 === (currentTime /= duration) ? startY + wholeY : (o || (o = .3 * duration), a < Math.abs(wholeY) ? (a = wholeY, r = o / 4) : r = o / (2 * Math.PI) * Math.asin(wholeY / a), a * Math.pow(2, -10 * currentTime) * Math.sin((currentTime * duration - r) * (2 * Math.PI) / o) + wholeY + startY); }, easing.easeInOutElastic = function (currentTime, startY, wholeY, duration) { var r = 1.70158, o = 0, a = wholeY; return 0 === currentTime ? startY : 2 === (currentTime /= duration / 2) ? startY + wholeY : (o || (o = duration * (.3 * 1.5)), a < Math.abs(wholeY) ? (a = wholeY, r = o / 4) : r = o / (2 * Math.PI) * Math.asin(wholeY / a), currentTime < 1 ? -.5 * (a * Math.pow(2, 10 * (currentTime -= 1)) * Math.sin((currentTime * duration - r) * (2 * Math.PI) / o)) + startY : a * Math.pow(2, -10 * (currentTime -= 1)) * Math.sin((currentTime * duration - r) * (2 * Math.PI) / o) * .5 + wholeY + startY); }, easing.easeInBack = function (currentTime, startY, wholeY, duration, r) { return void 0 === r && (r = 1.70158), wholeY * (currentTime /= duration) * currentTime * ((r + 1) * currentTime - r) + startY; }, easing.easeOutBack = function (currentTime, startY, wholeY, duration, r) { return void 0 === r && (r = 1.70158), wholeY * ((currentTime = currentTime / duration - 1) * currentTime * ((r + 1) * currentTime + r) + 1) + startY; }, easing.easeInOutBack = function (currentTime, startY, wholeY, duration, r) { return void 0 === r && (r = 1.70158), (currentTime /= duration / 2) < 1 ? wholeY / 2 * (currentTime * currentTime * (((r *= 1.525) + 1) * currentTime - r)) + startY : wholeY / 2 * ((currentTime -= 2) * currentTime * (((r *= 1.525) + 1) * currentTime + r) + 2) + startY; }, easing.easeOutBounce = function (currentTime, startY, wholeY, duration) { return (currentTime /= duration) < 1 / 2.75 ? wholeY * (7.5625 * currentTime * currentTime) + startY : currentTime < 2 / 2.75 ? wholeY * (7.5625 * (currentTime -= 1.5 / 2.75) * currentTime + .75) + startY : currentTime < 2.5 / 2.75 ? wholeY * (7.5625 * (currentTime -= 2.25 / 2.75) * currentTime + .9375) + startY : wholeY * (7.5625 * (currentTime -= 2.625 / 2.75) * currentTime + .984375) + startY; }, easing.easeInBounce = function (currentTime, startY, wholeY, r) { return wholeY - easing.easeOutBounce(r - currentTime, 0, wholeY, r) + startY; }, easing.easeInOutBounce = function (currentTime, startY, wholeY, r) { return currentTime < r / 2 ? .5 * easing.easeInBounce(2 * currentTime, 0, wholeY, r) + startY : .5 * easing.easeOutBounce(x, 2 * currentTime - r, 0, wholeY, r) + .5 * wholeY + startY; }; var lerp = { /* vector: function(currentTime, startY, f) {//xzw change, add f var wholeY = currentTime.clone(); return startY = startY.clone(), function(duration) { currentTime.set(wholeY.x * (1 - duration) + startY.x * duration, wholeY.y * (1 - duration) + startY.y * duration, wholeY.z * (1 - duration) + startY.z * duration) f && f(currentTime,duration); } }, quaternion: function(currentTime, startY, f) {//xzw change, add f var wholeY = currentTime.clone(); return function(duration) { currentTime.copy(wholeY).slerp(startY, duration); f && f(currentTime,duration); } }, property: function(currentTime, startY, wholeY, duration) { var r = currentTime[startY]; return function(o) { currentTime[startY] = r * (1 - o) + wholeY * o, duration && duration(currentTime[startY]) } }, uniform: function(currentTime, startY, wholeY) { var duration = currentTime.material.uniforms[startY].value; return function(r) { try{ currentTime.material.uniforms[startY] && (currentTime.material.uniforms[startY].value = duration * (1 - r) + wholeY * r) }catch(currentTime){ console.log(1) } } }, matrix4: function(currentTime, startY) { var wholeY = currentTime.clone(); return function(duration) { for (var r = currentTime.elements, o = wholeY.elements, a = startY.elements, s = 0; s < 16; s++) r[s] = o[s] * (1 - duration) + a[s] * duration } }, allUniforms: function(currentTime, startY, wholeY) { var duration = currentTime.map(function(currentTime) { return this.uniform(currentTime, startY, wholeY) } .bind(this)); return function(currentTime) { duration.forEach(function(startY) { startY(currentTime) }) } } */ vector: function vector(t, i, f) { //xzw change, add f var n = t.clone(); return i = i.clone(), function (e, delta) { t.set(n.x * (1 - e) + i.x * e, n.y * (1 - e) + i.y * e, n.z * (1 - e) + i.z * e); f && f(t, e, delta); }; }, quaternion: function quaternion(t, i, f) { //xzw change, add f var n = t.clone(); return function (e) { t.copy(n).slerp(i, e); f && f(t, e); }; }, property: function property(t, i, n, r) { var o = t[i]; return function (e) { t[i] = o * (1 - e) + n * e, r && r(t[i]); }; }, uniform: function uniform(t, i, n) { var r = t.material.uniforms[i].value; return function (e) { t.material.uniforms[i] && (t.material.uniforms[i].value = r * (1 - e) + n * e); }; }, matrix4: function matrix4(o, a) { var s = o.clone(); return function (e) { for (var t = o.elements, i = s.elements, n = a.elements, r = 0; r < 16; r++) t[r] = i[r] * (1 - e) + n[r] * e; }; }, allUniforms: function allUniforms(e, t, i) { var n = e.map(function (e) { return this.uniform(e, t, i); }.bind(this)); return function (t) { n.forEach(function (e) { e(t); }); }; } }; /* 渐变 */ var transitions$1 = { globalDone: null, funcs: [], counter: 0, uniqueID: 0, start: function start(func, duration, done, delay, ease, name, id, cancelFun) { var ignoreFirstFrame = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : true; return delay = delay || 0, this.funcs.push({ func: func, current: -delay * Math.abs(duration), //当前时间 duration: (1 - Math.max(delay, 0)) * Math.abs(duration), //总时长 done: done, easing: ease || easing.linearTween, //渐变曲线 cycling: duration < 0, running: !0, debug: delay < 0, name: name || "T" + this.counter, id: void 0 === id ? this.counter : id, paused: !1, cancelFun: cancelFun, //取消时执行的函数 updateCount: 0, ignoreFirstFrame }), func(0, 16), this.counter += 1, func; }, trigger: function trigger(e) { var t = void 0 === e.delayRatio ? 0 : e.delayRatio, u = e.func || function () {}, r = void 0 === e.duration ? 0 : e.duration; void 0 !== e.cycling && e.cycling && (r = -Math.abs(r)); var o = e.done || null, a = e.easing || easing.linearTween, s = e.name || "R" + this.counter, l = void 0 === e.id ? this.counter : e.id; return this.start(u, r, o, t, a, s, l); }, setTimeout: function setTimeout(e, t, u) { var duration = void 0 === u ? this.counter : u; return this.trigger({ done: e, duration: void 0 === t ? 0 : t, name: "O" + this.counter, id: duration }); }, pause: function pause() { this.paused = !0; }, resume: function resume() { this.paused = !1; }, update: function update(e) { this.funcs.forEach(function (t) { if (t.updateCount++ == 0 && t.ignoreFirstFrame) return; //add start可能发生在一帧中任意时刻,而每次update的是在一帧中的固定时刻,所以从start到第一次update的时间并不是所传入的delta,该delta 是上一帧的update到这一帧的update的耗时。 故去掉了第一次的update,相当于延迟一帧再update. if (!(t.paused || (t.current += 1e3 * e, t.current < 0))) { if (t.current >= t.duration && !t.cycling) { var u = t.easing(1, 0, 1, 1); t.func(u, 1e3 * e), t.done && t.done(), t.running = !1; } else { var duration = t.easing(t.current % t.duration / t.duration, 0, 1, 1), r = t.func(duration, 1e3 * e) || !1; r && (t.done && t.done(), t.running = !1); } } }); var t = this.funcs.length; this.funcs = this.funcs.filter(function (e) { return e.running; }); var u = this.funcs.length; if (t > 0 && 0 === u && this.globalDone) { var duration = this.globalDone; this.globalDone = null, duration(); } }, adjustSpeed: function adjustSpeed(e, t) { for (var u = this.getById(e), n = 0; n < u.length; n++) { var r = u[n]; r.duration /= t, r.current /= t; } }, getById: function getById(e) { return this.funcs.filter(function (t) { return e === t.id; }); }, get: function get(e) { for (var t = 0; t < this.funcs.length; t += 1) if (this.funcs[t].func === e) return this.funcs[t]; return null; }, isRunning: function isRunning(e) { var t = this.get(e); return null !== t && t.running; }, countActive: function countActive() { for (var e = 0, t = 0; t < this.funcs.length; t += 1) e += this.funcs[t].running; return e; }, listActive: function listActive() { for (var e = [], t = 0; t < this.funcs.length; t += 1) this.funcs[t].running && e.push(this.funcs[t].name); return e; }, done: function done(e) { this.globalDone = e; }, cancelById: function cancelById(e, dealCancelFun) { //xzw add dealDone var t = void 0 === e ? 0 : e; var cancels = []; this.funcs = this.funcs.filter(function (e) { var is = e.id == t; if (is && dealCancelFun) { e.cancelFun && cancels.push(e.cancelFun); //e.cancelFun && e.cancelFun() } return !is; }); cancels.forEach(e => { e(); }); //先从funcs中去除后再执行 }, cancel: function cancel(e) { this.funcs = this.funcs.filter(function (t) { return t.func !== e; }); }, getUniqueId: function getUniqueId() { return this.uniqueID -= 1, this.uniqueID; } }; //THREE.Vector2.name2 = 'Common' var Common = { sortByScore: function sortByScore(list, request, rank) { var i = request ? Common.filterAll(list, request) : list; return 0 === i.length ? [] : i = i.map(function (e) { var results = rank.map(function (f) { return f(e); }); var scores = results.map(e => e.score != void 0 ? e.score : e); var logs = results.map(e => e.log); return { item: e, scores, logs, score: scores.reduce(function (t, i) { //总分 return t + i; }, 0) }; }).sort(function (e, t) { return t.score - e.score; }); }, filterAll: function filterAll(e, t) { return e.filter(function (e) { return t.every(function (t) { return t(e); }); }); }, //--------------- find: function find(list, request, rank, sortByScore) { if (sortByScore) { var r = this.sortByScore(list, request, rank); return r[0] && r[0].item; } else { var i = request ? Common.filterAll(list, request) : list; return 0 === i.length ? null : (rank && rank.forEach(function (e) { i = Common.stableSort(i, e); }), i[0]); } }, stableSort: function stableSort(e, f) { //用到排序函数,涉及到两个item相减 return e.map(function (e, i) { return { value: e, index: i }; }).sort(function (e, u) { var n = f(e.value, u.value); return 0 !== n ? n : e.index - u.index; //似乎就是加多了这一步:若差距为0,按照原顺序 }).map(function (e) { return e.value; }); }, average: function average(e, t) { if (0 === e.length) return null; for (var i = 0, n = 0, r = 0; r < e.length; r++) { var o = t ? e[r][t] : e[r]; i += o, n++; } return i / n; }, //--------------------------- getMixedSet: function getMixedSet(arr1, arr2) { //交集 return arr1.filter(item => arr2.includes(item)); }, getUnionSet: function getUnionSet(arr1, arr2) { //并集 return arr1.concat(arr2.filter(item => !arr1.includes(item))); }, getDifferenceSet: function getDifferenceSet(arr1, arr2) { //差集 不能识别重复的,如getDifferenceSet([1,2,2],[1,1,2]) 为空 var arr11 = arr1.filter(item => !arr2.includes(item)); var arr22 = arr2.filter(item => !arr1.includes(item)); return arr11.concat(arr22); }, getDifferenceSetMuti: function getDifferenceSetMuti(arr) { //收集绝对没有重复的元素,也就是判断出现次数=1的 var set = []; arr.forEach(arr1 => { arr1.forEach(item => { var index = set.indexOf(item); if (index > -1) { set.splice(index, 1); } else { set.push(item); } }); }); return set; }, CloneJson: function CloneJson(data) { var str = JSON.stringify(data); return JSON.parse(str); }, CloneObject: function CloneObject(copyObj, isSimpleCopy) { var simpleCopyList = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; var judgeSimpleCopyFun = arguments.length > 3 ? arguments[3] : undefined; //isSimpleCopy 只复制最外层 //复制json result的可能:普通数字或字符串、普通数组、复杂对象 judgeSimpleCopyFun || (judgeSimpleCopyFun = () => {}); if (!copyObj || typeof copyObj == 'number' || typeof copyObj == 'string' || copyObj.isObject3D || copyObj instanceof Function || simpleCopyList.some(className => copyObj instanceof className) || judgeSimpleCopyFun(copyObj)) { return copyObj; } if (copyObj instanceof Array) { return copyObj.map(e => { return this.CloneObject(e, isSimpleCopy, simpleCopyList, judgeSimpleCopyFun); }); } else { if (copyObj.clone instanceof Function) { //解决一部分 return copyObj.clone(); } } var result = {}; for (var key in copyObj) { if (copyObj[key] instanceof Object && !isSimpleCopy) result[key] = this.CloneObject(copyObj[key], isSimpleCopy, simpleCopyList, judgeSimpleCopyFun);else result[key] = copyObj[key]; //如果是函数类同基本数据,即复制引用 } return result; }, CloneClassObject: function CloneClassObject(copyObj) { var { ignoreList = [], simpleCopyList = [] } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; //复杂类对象 var newobj = new copyObj.constructor(); this.CopyClassObject(newobj, copyObj, { ignoreList, simpleCopyList }); return newobj; }, CopyClassObject: function CopyClassObject(targetObj, copyObj) { var { ignoreList = [], simpleCopyList = [] } = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; //复杂类对象 for (var i in copyObj) { if (i in copyObj.__proto__) break; //到函数了跳出 if (ignoreList.includes(i)) { continue; } else if (simpleCopyList.includes(i)) { targetObj[i] = copyObj[i]; } else { targetObj[i] = this.CloneObject(copyObj[i], false, simpleCopyList); } /* else if(copyObj[i].clone instanceof Function ){ targetObj[i] = copyObj[i].clone() }else{ targetObj[i] = copyObj[i]; } */ } }, ifSame: function ifSame(object1, object2) { var simpleEqualClass = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; //对于复杂的类对象,若能简单判断就直接写进simpleEqualClass if (object1 == object2) return true; // 0 != undefined , 0 == '' else if (!object1 || !object2) return false;else if (object1.constructor != object2.constructor) { return false; } else if (simpleEqualClass.some(className => object1 instanceof className)) { return object1 == object2; } else if (object1 instanceof Array) { if (object1.length != object2.length) return false; var _object2 = object2.slice(0); var _loop = function _loop(i) { u = _object2.find(e => Common.ifSame(object1[i], e, simpleEqualClass)); if (u == void 0 && !_object2.includes(u) && !object1.includes(u)) return { v: false };else { var index = _object2.indexOf(u); _object2.splice(index, 1); } }, u, _ret; for (var i = 0; i < object1.length; i++) { _ret = _loop(i); if (_ret) return _ret.v; } return true; } else if (object1.equals instanceof Function) { //复杂数据仅支持这种,其他的可能卡住? return object1.equals(object2); } else if (typeof object1 == 'number' || typeof object1 == 'string') { if (isNaN(object1) && isNaN(object2)) return true;else return object1 == object2; } else if (typeof object1 == "object") { var keys1 = Object.keys(object1); var keys2 = Object.keys(object2); if (!Common.ifSame(keys1, keys2, simpleEqualClass)) return false; for (var _i in object1) { var same = Common.ifSame(object1[_i], object2[_i], simpleEqualClass); if (!same) return false; } return true; } else { console.log('isSame出现例外'); } }, downloadFile: function downloadFile(data, filename, cb) { var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a'); save_link.href = data; save_link.download = filename; var event = document.createEvent('MouseEvents'); event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); save_link.dispatchEvent(event); cb && cb(); }, replaceAll: function replaceAll(str, f, e) { //f全部替换成e /* if(str.replaceAll ) return str.replaceAll(f, e) else{ */ var reg = new RegExp(f, "g"); //创建正则RegExp对象 return str.replace(reg, e); //str.split(f).join(e); //} }, dealURL(url) { var urlNew = this.replaceAll(url, "\\+", "%2B"); // 浏览器似乎不支持访问带+的地址 urlNew = this.replaceAll(urlNew, "/.//", "/"); //去除双斜杠(/.//) //urlNew = encodeURIComponent(url) return urlNew; }, getNameFromURL(url) { if (!url) return ''; var get = e => { return e.split('/').pop(); }; if (url instanceof Array) { return url.map(e => get(e)); } return get(url); }, //--------------------------- intervalTool: { //延时update,防止卡顿 list: [], /* isWaiting:function(name, func, delayTime){ if(!this.list.includes(name)){ //如果没有该项, 则开始判断 var needWait = func(); //触发了改变,则等待一段时间后再自动判断 if(needWait){ this.list.push(name); setTimeout(()=>{ var a = this.list.indexOf(name); this.list.splice(a,1); this.isWaiting(name, func, delayTime) //循环 },delayTime) } } }, */ isWaiting: function isWaiting(name, func, delayTime /* , autoCycle */) { var item = this.list.find(e => e.name == name); if (!item) { //如果没有该项, 则加入循环 var ifContinue = func(); item = { name, func, delayTime }; this.list.push(item); setTimeout(() => { var a = this.list.indexOf(item); this.list.splice(a, 1); var { func, delayTime } = item; if (item.requestUpdate || ifContinue) this.isWaiting(name, func, delayTime); //循环 }, delayTime); } else { //如果有该项,说明现在请求下一次继续更新 //if(delayTime == 0){//想立刻更新一次 // func() //}else{ //更新属性 item.func = func; item.delayTime = delayTime; item.requestUpdate = true; //} } } }, pushToGroupAuto: function pushToGroupAuto(items, groups, recognizeFunction, recognizeGroup) { //自动分组。 items是将分到一起的组合。items.length = 1 or 2. recognizeFunction = recognizeFunction || function () {}; if (recognizeGroup) { //有更复杂的识别处理,直接传递整个组 var atGroups = groups.filter(group => recognizeGroup(group, items)); } else { var atGroups = groups.filter(group => group.find(item => items[0] == item || recognizeFunction(item, items[0]) || items[1] == item || items[1] && recognizeFunction(item, items[1]))); } if (atGroups.length) { //在不同组 //因为items是一组的,所以先都放入组1 items.forEach(item => { if (!atGroups[0].includes(item)) atGroups[0].push(item); }); if (atGroups.length > 1) { //如果在不同组,说明这两个组需要合并 var combineGroup = []; atGroups.forEach(group => { combineGroup = Common.getUnionSet(combineGroup, group); groups.splice(groups.indexOf(group), 1); }); groups.push(combineGroup); } } else { //直接加入为一组 groups.push(items); } }, getBestCount: function () { var lastCount = {}; return function (name) { var minCount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var maxCount = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 6; var durBound1 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1.2; var durBound2 = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 10; var ifLog = arguments.length > 5 ? arguments[5] : undefined; var maxHistory = arguments.length > 6 ? arguments[6] : undefined; var timeStamp = performance.getEntriesByName("loop-start"); var count; if (timeStamp.length) { var dur = performance.now() - timeStamp[timeStamp.length - 1].startTime; //dur在iphoneX中静止有7,pc是2 count = Math.round(math.linearClamp(dur, [durBound1, durBound2], [maxCount, minCount])); if (maxHistory) { if (!lastCount[name]) lastCount[name] = []; if (count == 0 && lastCount[name].length > maxHistory - 1 && !lastCount[name].some(e => e > 0)) { count = 1; } lastCount[name].push(count); if (lastCount[name].length > maxHistory) lastCount[name].splice(0, 1); } if (ifLog) { //注意,console.log本身用时挺高, 降4倍时可能占用0.5毫秒 name && count && console.log(name, count, ' ,dur:', dur.toFixed(3)); } } else { count = maxCount; // ? } //主要在手机端有效果。 return count; }; }(), batchHandling: { //分批处理 lists: [], getSlice: function getSlice(name, items, _ref) { var { stopWhenAllUsed, min = 5, max = 100, durBound1, durBound2, useEquals, maxUseCount } = _ref; if (items.length == 0 || (maxUseCount = maxUseCount == void 0 ? Common.getBestCount(name, min, max, durBound1, durBound2 /* , true */) : maxUseCount, !maxUseCount) //本次最多可以使用的个数 ) { return { list: [] }; } if (!this.lists[name]) this.lists[name] = { list: [] }; //更新列表项目,但不变原来的顺序 var list = this.lists[name].list.filter(a => items.some(item => useEquals ? a.item.equals(item) : a.item == item)); //去掉已经不在items里的项目 this.lists[name].list = list; items.forEach(item => { //增加新的项目。 if (!list.some(a => useEquals ? a.item.equals(item) : a.item == item)) { list.push({ item, count: 0 }); } }); //至此,在后排的都是未使用的 var unUsed = list.filter(e => e.count == 0); //未使用的项目(count为0)优先 var result = []; unUsed.slice(0, maxUseCount).forEach(e => { result.push(e.item); e.count++; }); if (unUsed.length > maxUseCount) { //还是剩有未使用的项目,等待下一次 } else { //所有项目都能使用一次 if (!stopWhenAllUsed) { //若不是全部使用就停止 var wholeCount = Math.min(items.length, maxUseCount); var restCount = wholeCount - result.length; //补齐 list.slice(0, restCount).forEach(e => { result.push(e.item); e.count++; }); } list.forEach(e => e.count--); //复原,等待新的循环 } /* result.forEach((e,i)=>{//有重复的 if( result.slice(0,i).some(a=>a.equals(e)) || result.slice(i+1).some(a=>a.equals(e)) ) { console.log(e) } }) */ return { list: result }; } }, getRootWindow() { //获取包含Potree的根window var win = window; try { while (win.parent != win && win.parent.Potree) { win = win.parent; } if (window != win) return win; } catch (e) { //console.log(e) //可能跨域,从而win.parent.Potree报错 console.log('getRootWindow 跨域'); return; } }, watch: function watch(object, propName, initialValue) { //监听某个属性的变化 var v = initialValue; Object.defineProperty(object, propName, { get: function get() { return v; }, set: function set(e) { console.warn('watch:', propName, e); v = e; } }); }, imgAddLabel: function imgAddLabel(img, labelImg) { var labelInfo = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; //图上加另一张小图,用于添加水印 var canvas; if (img instanceof Image) { canvas = document.createElement('canvas'); } else { canvas = img; } var context = canvas.getContext('2d'); var marginLeft = labelInfo.bgMargin && labelInfo.bgMargin.left || 0; var marginRight = labelInfo.bgMargin && labelInfo.bgMargin.right || 0; var marginTop = labelInfo.bgMargin && labelInfo.bgMargin.top || 0; var marginBottom = labelInfo.bgMargin && labelInfo.bgMargin.bottom || 0; if (img instanceof Image) { //如果img是canvas,说明已绘制在canvas上了就不用绘制了 var width = img.width + marginLeft + marginRight; var height = img.height + marginTop + marginBottom; canvas.width = width; canvas.height = height; if (labelInfo.bgColor) { context.fillStyle = 'rgba(' + labelInfo.bgColor.r + ',' + labelInfo.bgColor.g + ',' + labelInfo.bgColor.b + ',' + labelInfo.bgColor.a + ')'; context.fillRect(0, 0, width, height); } context.drawImage(img, marginLeft, marginTop, img.width, img.height); } var labelWidth = labelInfo.widthRatioToImg ? img.width * labelInfo.widthRatioToImg : labelImg.width; //widthRatioToImg:label的width占img的width的比例 var labelHeight = labelWidth * labelImg.height / labelImg.width; if (labelInfo.leftRatioToImg == void 0 && labelInfo.rightRatioToImg != void 0) { labelInfo.leftRatioToImg = 1 - labelInfo.rightRatioToImg - (labelInfo.widthRatioToImg || labelImg.width / img.width); } if (labelInfo.topRatioToImg == void 0 && labelInfo.bottomRatioToImg != void 0) { labelInfo.topRatioToImg = 1 - labelInfo.bottomRatioToImg - labelHeight / img.height; } var labelLeft = img.width * labelInfo.leftRatioToImg + marginLeft; //leftRatioToImg:label的left占img的width的比例 var labelTop = img.height * labelInfo.topRatioToImg + marginTop; //topRatioToImg:label的top占img的height的比例 context.globalAlpha = labelInfo.opacity != void 0 ? labelInfo.opacity : 1; context.drawImage(labelImg, labelLeft, labelTop, labelWidth, labelHeight); if (labelInfo.outputCanvas) { return canvas; } var dataUrl = canvas.toDataURL('image/png', labelInfo.compressRatio); //Common.downloadFile(dataUrl, 'screenshot.png') context.clearRect(0, 0, canvas.width, canvas.height); return dataUrl; }, /* changeShaderToWebgl2(vs, fs, matType, otherReplaces=[]){//部分shader要根据webgl版本作更改 if(!Potree.settings.isWebgl2)return {vs, fs} let turnTo300 = matType != 'ShaderMaterial' && (vs.includes('gl_FragDepthEXT') || fs.includes('gl_FragDepthEXT') ) let addV300 = turnTo300 && matType != 'RawShaderMaterial' // RawShaderMaterial直接material.glslVersion = '300 es' 以加在define之前 let change = (shader, shaderType)=>{ let newShader = shader if(turnTo300){ //非shaderMaterial需要手动改为300 es的写法 addV300 && (newShader = '#version 300 es \n' + newShader) //需要加 #version 300 es。 three.js自带的渲染会自动加所以不用 newShader = newShader.replaceAll('varying ', shaderType == 'vs' ? 'out ' : 'in ') newShader = newShader.replaceAll('attribute ', 'in ') if(shaderType == 'fs'){ newShader = newShader.replaceAll('gl_FragColor', 'fragColor') newShader = newShader.replace('void main', 'out vec4 fragColor;\n void main' )//在void main前加入这个声明 } newShader = newShader.replaceAll('gl_FragDepthEXT','gl_FragDepth') newShader = newShader.replaceAll('texture2D','texture') newShader = newShader.replaceAll('textureCube','texture') } newShader = newShader.replace('#extension GL_EXT_frag_depth : enable','') newShader = newShader.replaceAll('defined(GL_EXT_frag_depth) &&','') otherReplaces.forEach(({oldStr,newStr})=>{ newShader = newShader.replaceAll(oldStr,newStr) }) return newShader } vs = change(vs,'vs') fs = change(fs,'fs') //console.log('成功替换为webgl2' ) return {vs,fs} }//three.js的shaderMaterial也有替换功能,搜 '#define gl_FragDepthEXT gl_FragDepth', */ changeShaderToWebgl2(vs, fs, matType) { var otherReplaces = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; //部分shader要根据webgl版本作更改 if (!Potree.settings.isWebgl2) return { vs, fs }; var turnTo300 = matType != 'ShaderMaterial' && (vs.includes('gl_FragDepthEXT') || fs.includes('gl_FragDepthEXT')); var addV300 = turnTo300 && matType != 'RawShaderMaterial'; // RawShaderMaterial直接material.glslVersion = '300 es' 以加在define之前 var change = (shader, shaderType) => { var newShader = shader; if (turnTo300) { //非shaderMaterial需要手动改为300 es的写法 addV300 && (newShader = '#version 300 es \n' + newShader); //需要加 #version 300 es。 three.js自带的渲染会自动加所以不用 newShader = this.replaceAll(newShader, 'varying ', shaderType == 'vs' ? 'out ' : 'in '); newShader = this.replaceAll(newShader, 'attribute ', 'in '); if (shaderType == 'fs') { newShader = this.replaceAll(newShader, 'gl_FragColor', 'fragColor'); newShader = newShader.replace('void main', 'out vec4 fragColor;\n void main'); //在void main前加入这个声明 } newShader = this.replaceAll(newShader, 'gl_FragDepthEXT', 'gl_FragDepth'); newShader = this.replaceAll(newShader, 'texture2D', 'texture'); newShader = this.replaceAll(newShader, 'textureCube', 'texture'); } newShader = newShader.replace('#extension GL_EXT_frag_depth : enable', ''); newShader = this.replaceAll(newShader, 'defined(GL_EXT_frag_depth) &&', ''); otherReplaces.forEach(_ref2 => { var { oldStr, newStr } = _ref2; newShader = this.replaceAll(newShader, oldStr, newStr); }); return newShader; }; vs = change(vs, 'vs'); fs = change(fs, 'fs'); //console.log('成功替换为webgl2' ) return { vs, fs }; } //three.js的shaderMaterial也有替换功能,搜 '#define gl_FragDepthEXT gl_FragDepth', }; Potree.Common = Common; class View { //base constructor() { this.position = new Vector3(0, 0, 0); this.yaw = Math.PI / 4; this._pitch = -Math.PI / 4; this.radius = 1; this.maxPitch = Math.PI / 2; this.minPitch = -Math.PI / 2; } clone() { var c = new View(); c.yaw = this.yaw; c._pitch = this.pitch; c.radius = this.radius; c.maxPitch = this.maxPitch; c.minPitch = this.minPitch; return c; } get pitch() { return this._pitch; } set pitch(angle) { this._pitch = Math.max(Math.min(angle, this.maxPitch), this.minPitch); } get direction() { var dir = new Vector3(0, 1, 0); dir.applyAxisAngle(new Vector3(1, 0, 0), this.pitch); dir.applyAxisAngle(new Vector3(0, 0, 1), this.yaw); return dir; } set direction(dir) { dir = dir.clone().normalize(); //add if (dir.x === 0 && dir.y === 0) { this.pitch = Math.PI / 2 * Math.sign(dir.z); //this.yaw = 0 //add:还是要指定一下, 否则不统一 } else { var yaw = Math.atan2(dir.y, dir.x) - Math.PI / 2; var pitch = Math.atan2(dir.z, Math.sqrt(dir.x * dir.x + dir.y * dir.y)); this.yaw = yaw; this.pitch = pitch; } } lookAt(t) { //setPivot var V; if (arguments.length === 1) { V = new Vector3().subVectors(t, this.position); } else if (arguments.length === 3) { V = new Vector3().subVectors(new Vector3(...arguments), this.position); } var radius = V.length(); var dir = V.normalize(); this.radius = radius; this.direction = dir; } getPivot() { return new Vector3().addVectors(this.position, this.direction.multiplyScalar(this.radius)); } getSide() { var side = new Vector3(1, 0, 0); side.applyAxisAngle(new Vector3(0, 0, 1), this.yaw); return side; } pan(x, y) { var dir = new Vector3(0, 1, 0); dir.applyAxisAngle(new Vector3(1, 0, 0), this.pitch); dir.applyAxisAngle(new Vector3(0, 0, 1), this.yaw); // let side = new THREE.Vector3(1, 0, 0); // side.applyAxisAngle(new THREE.Vector3(0, 0, 1), this.yaw); var side = this.getSide(); var up = side.clone().cross(dir); var pan = side.multiplyScalar(x).add(up.multiplyScalar(y)); this.position = this.position.add(pan); // this.target = this.target.add(pan); } translate(x, y, z) { var dir = new Vector3(0, 1, 0); dir.applyAxisAngle(new Vector3(1, 0, 0), this.pitch); dir.applyAxisAngle(new Vector3(0, 0, 1), this.yaw); var side = new Vector3(1, 0, 0); side.applyAxisAngle(new Vector3(0, 0, 1), this.yaw); var up = side.clone().cross(dir); var t = side.multiplyScalar(x).add(dir.multiplyScalar(y)).add(up.multiplyScalar(z)); this.position = this.position.add(t); } translateWorld(x, y, z) { this.position.x += x; this.position.y += y; this.position.z += z; } setView(position, target) { var duration = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var callback = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var endPosition = null; if (position instanceof Array) { endPosition = new Vector3(...position); } else if (position.x != null) { endPosition = position.clone(); } var endTarget = null; if (target instanceof Array) { endTarget = new Vector3(...target); } else if (target.x != null) { endTarget = target.clone(); } var startPosition = this.position.clone(); var startTarget = this.getPivot(); //const endPosition = position.clone(); //const endTarget = target.clone(); var easing = TWEEN.Easing.Quartic.Out; if (duration === 0) { this.position.copy(endPosition); this.lookAt(endTarget); } else { var value = { x: 0 }; var tween = new TWEEN.Tween(value).to({ x: 1 }, duration); tween.easing(easing); //this.tweens.push(tween); tween.onUpdate(() => { var t = value.x; //console.log(t); var pos = new Vector3((1 - t) * startPosition.x + t * endPosition.x, (1 - t) * startPosition.y + t * endPosition.y, (1 - t) * startPosition.z + t * endPosition.z); var target = new Vector3((1 - t) * startTarget.x + t * endTarget.x, (1 - t) * startTarget.y + t * endTarget.y, (1 - t) * startTarget.z + t * endTarget.z); this.position.copy(pos); this.lookAt(target); }); tween.start(); tween.onComplete(() => { if (callback) { callback(); } }); } } } ; var sid = 0; class ExtendView extends View { constructor() { super(); this.yaw = 0; //Math.PI / 4; // = 4dkk lon + 90 this._pitch = 0; //-Math.PI / 4; //上下旋转 = 4dkk lat this.sid = sid++; this.LookTransition = 'LookTransition' + this.sid; this.FlyTransition = 'FlyTransition' + this.sid; } //add------ applyToCamera(camera) { camera.position.copy(this.position); camera.rotation.copy(this.rotation); camera.updateMatrix(); camera.updateMatrixWorld(); //camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); } get rotation() { var rotation = new Euler(); rotation.order = "ZXY"; rotation.x = Math.PI / 2 + this.pitch; rotation.z = this.yaw; return rotation; } set rotation(rotation) { if (rotation.y != 0) { //因为 rotation的y不一定是0 , 所以不能直接逆着get rotation写。 //console.error('set rotation y不为0!!!!?', rotation ) //过渡时因为quaternion lerp所以不为0。没办法了orz this.direction = new Vector3(0, 0, -1).applyEuler(rotation); //转回direction有损耗,在俯视时的(dir.x==dir.y==0), 丢失yaw信息从而 yaw无法获取(希望不要遇到这种情况,如果有的话,考虑先计算yaw,似乎好像可以算) } else { //尽量不用direction this.pitch = rotation.x - Math.PI / 2; this.yaw = rotation.z; } } get quaternion() { return new Quaternion().setFromEuler(this.rotation); } set quaternion(q) { this.rotation = new Euler().setFromQuaternion(q); } copy(a) { Common.CopyClassObject(this, a, { ignoreList: ['_listeners'] }); } clone() { return Common.CloneClassObject(this, { ignoreList: ['_listeners'] }); } //---------- setCubeView(dir) { switch (dir) { case "front": this.yaw = 0; this.pitch = 0; break; case "back": this.yaw = Math.PI; this.pitch = 0; break; case "left": this.yaw = -Math.PI / 2; this.pitch = 0; break; case "right": this.yaw = Math.PI / 2; this.pitch = 0; break; case "top": this.yaw = 0; this.pitch = -Math.PI / 2; break; case "bottom": this.yaw = -Math.PI; this.pitch = Math.PI / 2; break; } } /* pan (x, y) { let dir = new THREE.Vector3(0, 1, 0); dir.applyAxisAngle(new THREE.Vector3(1, 0, 0), this.pitch); dir.applyAxisAngle(new THREE.Vector3(0, 0, 1), this.yaw); // let side = new THREE.Vector3(1, 0, 0); // side.applyAxisAngle(new THREE.Vector3(0, 0, 1), this.yaw); let side = this.getSide(); let up = side.clone().cross(dir); let pan = side.multiplyScalar(x).add(up.multiplyScalar(y)); this.position = this.position.add(pan); // this.target = this.target.add(pan); } */ pan(x, y) { //发现pan其实就是translate this.translate(x, 0, y); } translate(x, y, z, forceHorizon) { //相机方向 var dir = new Vector3(0, 1, 0); dir.applyAxisAngle(new Vector3(1, 0, 0), forceHorizon ? 0 : this.pitch); //上下角度 dir.applyAxisAngle(new Vector3(0, 0, 1), this.yaw); //水平角度 var side = new Vector3(1, 0, 0); side.applyAxisAngle(new Vector3(0, 0, 1), this.yaw); //垂直于相机当前水平朝向的 左右方向 var up = side.clone().cross(dir); //垂直于相机当前水平朝向的 向上方向 var t = side.multiplyScalar(x) //x影响 左右分量 .add(dir.multiplyScalar(y)) //y影响 前后分量 .add(up.multiplyScalar(z)); //z影响 上下分量 this.position = this.position.add(t); if ((!math.closeTo(x, 0, 1e-2) || !math.closeTo(y, 0, 1e-2) || !math.closeTo(z, 0, 1e-2)) && Potree.settings.displayMode != 'showPanos') { this.cancelFlying('pos'); } this.restrictPos(); } translateWorld(x, y, z) { super.translateWorld(x, y, z); if ((!math.closeTo(x, 0, 1e-2) || !math.closeTo(y, 0, 1e-2) || !math.closeTo(z, 0, 1e-2)) && Potree.settings.displayMode != 'showPanos') { this.cancelFlying('pos'); } this.restrictPos(); } restrictPos(position) { //add if (this.limitBound) { (position || this.position).clamp(this.limitBound.min, this.limitBound.max); } } isFlying() { var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'all'; var a = transitions$1.getById(this.FlyTransition).length > 0; var b = transitions$1.getById(this.LookTransition).length > 0; return type == 'pos' ? a : type == 'rotate' ? b : a || b; } cancelFlying() { var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'all'; var dealCancel = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; //外界只能通过这个来cancel type == 'pos' ? transitions$1.cancelById(this.FlyTransition, dealCancel) : type == 'rotate' ? transitions$1.cancelById(this.LookTransition, dealCancel) : (transitions$1.cancelById(this.FlyTransition, dealCancel), transitions$1.cancelById(this.LookTransition, dealCancel)); //console.log('cancelFlying ' , this.sid, type) } setView() { var info = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; // position, target, duration = 0, callback = null, onUpdate = null, Easing='', cancelFun this.cancelFlying(); var posWaitDone, rotWaitDone, dir; var posDone = () => { rotWaitDone || done(); posWaitDone = false; }; var rotDone = () => { if (endTarget) { this.lookAt(endTarget); //compute radius for orbitcontrol } else if (endQuaternion) { this.rotation = new Euler().setFromQuaternion(endQuaternion); } else if (endYaw != void 0) { this.yaw = endYaw, this.pitch = endPitch; } //if(dir.x == 0 && dir.y == 0)this.yaw = 0 //统一一下 朝上的话是正的。朝下的一般不是0,会保留一个接近0的小数所以不用管 posWaitDone || done(); rotWaitDone = false; }; var done = () => { //一定要旋转和位移都结束了才能执行 var f = () => { this.position.copy(endPosition); //因为延时1后control的update会导致位置改变 info.callback && info.callback(); this.dispatchEvent('flyingDone'); }; if (info.duration) { setTimeout(f, 1); //延迟是为了使isFlying先为false } else { f(); //有的需要迅速执行回调 } }; var endPosition = new Vector3().copy(info.position); var startPosition = this.position.clone(); var startQuaternion, endQuaternion, endTarget = info.target && new Vector3().copy(info.target), endYaw, startYaw, endPitch, startPitch; this.restrictPos(endPosition); if (info.endYaw == void 0) { if (info.target) { endQuaternion = math.getQuaFromPosAim(endPosition, endTarget); //若为垂直,会自动偏向x负的方向 } else if (info.quaternion) { endQuaternion = info.quaternion.clone(); } if (endQuaternion && math.closeTo(Math.abs(this.direction.z), 1, 1e-4)) { //在垂直的视角下的quaternion刚开始突变的厉害,这时候可能渐变yaw比较好(如俯视时点击测量线) var a = this.clone(); a.quaternion = endQuaternion; info.endYaw = a.yaw; info.endPitch = a.pitch; //console.log('turn to yaw') } } if (info.endYaw != void 0) { startPitch = this.pitch; endPitch = info.endPitch; startYaw = this.yaw; endYaw = info.endYaw; if (Math.abs(startYaw - endYaw) > Math.PI) { //如果差距大于半个圆,就要反个方向转(把大的那个数字减去360度) startYaw > endYaw ? startYaw -= Math.PI * 2 : endYaw -= Math.PI * 2; } //console.log('startYaw', startYaw, 'endYaw', endYaw) } if (endQuaternion) { startQuaternion = this.quaternion; } if (!info.duration) { this.position.copy(endPosition); this.restrictPos(); posWaitDone = true, rotWaitDone = true; info.onUpdate && info.onUpdate(1); posDone(); rotDone(); } else { info.onUpdate && info.onUpdate(0); //初始化progress var posChange = !this.position.equals(endPosition); if (posChange) { posWaitDone = true; transitions$1.start(lerp.vector(this.position, endPosition, (pos, progress, delta) => { info.onUpdate && info.onUpdate(progress, delta); }), info.duration, posDone, 0, info.Easing ? easing[info.Easing] : easing.easeInOutSine, null, this.FlyTransition, () => { //中途取消 if (rotWaitDone) { /* endPosition = new THREE.Vector3().copy(this.position)//更改旋转的endQuaternion endQuaternion = math.getQuaFromPosAim(endPosition,endTarget) */ //直接改变endQuaternion会突变,所以还是cancel吧 this.cancelFlying('rotate'); } else { this.dispatchEvent('flyCancel'); } posWaitDone = false; info.cancelFun && info.cancelFun(); }, info.ignoreFirstFrame); } if (endQuaternion || endYaw != void 0) { rotWaitDone = true; transitions$1.start((progress, delta) => { if (endYaw != void 0) { this.yaw = startYaw * (1 - progress) + endYaw * progress; this.pitch = startPitch * (1 - progress) + endPitch * progress; } else { var quaternion = new Quaternion().copy(startQuaternion); lerp.quaternion(quaternion, endQuaternion)(progress); //在垂直的视角下的角度突变的厉害,这时候可能渐变yaw比较好 this.quaternion = quaternion; //console.log(quaternion,this.yaw) } posChange || info.onUpdate && info.onUpdate(progress, delta); }, info.duration, rotDone, 0, info.Easing ? easing[info.Easing] : easing.easeInOutSine, null, this.LookTransition, () => { //中途取消 rotWaitDone = false; info.cancelFun && info.cancelFun(); this.dispatchEvent('flyCancel'); }, info.ignoreFirstFrame); } if (!posWaitDone && !rotWaitDone) { //已经到达目标 info.onUpdate && info.onUpdate(1); done(); } /* transitions.start(lerp.vector(this.position, endPosition, (pos, progress)=>{ let t = progress if(endQuaternion){ let quaternion = (new THREE.Quaternion()).copy(startQuaternion) lerp.quaternion(quaternion, endQuaternion)(progress), this.rotation = new THREE.Euler().setFromQuaternion(quaternion) } this.restrictPos() //console.log('setView flying') info.onUpdate && info.onUpdate(t)//add }), info.duration, done, 0, info.Easing ? easing[info.Easing] : easing.easeInOutSine ,null, this.LookTransition, info.cancelFun); //easeInOutQuad */ } } //平移Ortho相机 moveOrthoCamera(viewport, info, duration, easeName) { //boundSize优先于endZoom。 var camera = info.camera || viewport.camera; var startZoom = camera.zoom; var endPosition = info.endPosition; var boundSize = info.boundSize; var endZoom = info.endZoom; var margin = info.margin || { x: 0, y: 0 }; /* 200 */ //像素 var _onUpdate = info.onUpdate; if (info.bound) { //需要修改boundSize以适应相机的旋转,当相机不在xy水平面上朝向z时 endPosition = endPosition || info.bound.getCenter(new Vector3()); var matrixRot = new Matrix4().makeRotationFromEuler(this.rotation).invert(); var boundingBox = info.bound.clone().applyMatrix4(matrixRot); boundSize = boundingBox.getSize(new Vector3()); } if (boundSize && boundSize.x == 0 && boundSize.y == 0) { boundSize.set(1, 1); //避免infinity } this.setView(Object.assign(info, { position: endPosition, duration, onUpdate: (progress, delta) => { if (boundSize || endZoom) { if (boundSize) { var aspect = boundSize.x / boundSize.y; var w, h; if (camera.aspect > aspect) { //视野更宽则用bound的纵向来决定 h = boundSize.y; endZoom = (viewport.resolution.y - margin.y) / h; //注意,要在resolution不为0时执行 } else { w = boundSize.x; endZoom = (viewport.resolution.x - margin.x) / w; } //onUpdate时更新endzoom是因为画布大小可能更改 } this.zoom = camera.zoom = endZoom * progress + startZoom * (1 - progress); //view里也加一下,有些地方需要记录,如截图 camera.updateProjectionMatrix(); _onUpdate && _onUpdate(progress, delta); } }, Easing: easeName })); } zoomOrthoCamera(camera, endZoom, pointer, duration, onProgress) { //定点缩放 var startZoom = camera.zoom; var pointerPos = new Vector3(pointer.x, pointer.y, 0.5); transitions$1.start(progress => { var oldPos = pointerPos.clone().unproject(camera); this.zoom = camera.zoom = endZoom * progress + startZoom * (1 - progress); camera.updateProjectionMatrix(); var newPos = pointerPos.clone().unproject(camera); //定点缩放, 恢复一下鼠标所在位置的位置改变量 var moveVec = new Vector3().subVectors(newPos, oldPos); camera.position.sub(moveVec); this.position.copy(camera.position); onProgress && onProgress(); }, duration, null /* done */, 0, easing.easeInOutSine, null, "zoomInView" /* , info.cancelFun */); } tranCamera(viewport, info, duration, easeName) { viewport.camera = info.midCamera; //viewport.camera.matrixWorld = info.endCamera.matrixWorld //viewer.setCameraMode(CameraMode.ORTHOGRAPHIC) info.midCamera.projectionMatrix.copy(info.startCamera.projectionMatrix); var onUpdate = info.onUpdate; info.onUpdate = (progress, delta) => { lerp.matrix4(info.midCamera.projectionMatrix, info.endCamera.projectionMatrix)(progress); onUpdate && onUpdate(progress, delta); }; var callback = info.callback; info.callback = () => { viewport.camera = info.endCamera; viewer.scene.measurements.forEach(e => { Potree.Utils.updateVisible(e, 'tranCamera', true); }); this.applyToCamera(viewport.camera); viewer.dispatchEvent({ type: 'camera_changed', viewport: viewer.mainViewport, changeInfo: {} }); //update sprite callback && callback(); }; //info.forbitCancel = true info.camera = info.endCamera; if (info.camera.type == "OrthographicCamera") { this.moveOrthoCamera(viewport, info, duration, easeName); } else { this.setView(Object.assign(info, { duration })); } } } ; var math = { getBaseLog(x, y) { //返回以 x 为底 y 的对数(即 logx y) . Math.log 返回一个数的自然对数 return Math.log(y) / Math.log(x); }, convertVector: { ZupToYup: function ZupToYup(e) { //navvis -> 4dkk return new Vector3(e.x, e.z, -e.y); }, YupToZup: function YupToZup(e) { //4dkk -> navvis return new Vector3(e.x, -e.z, e.y); } }, convertQuaternion: { ZupToYup: function ZupToYup(e) { //navvis -> 4dkk //不同于convertVisionQuaternion var rotation = new Euler(-Math.PI / 2, 0, 0); var quaternion = new Quaternion().setFromEuler(rotation); return e.clone().premultiply(quaternion); //return new THREE.Quaternion(e.x,e.z,-e.y,e.w).multiply((new THREE.Quaternion).setFromAxisAngle(new THREE.Vector3(1,0,0), THREE.Math.degToRad(90))) }, YupToZup: function YupToZup(e) { //4dkk -> navvis var rotation = new Euler(Math.PI / 2, 0, 0); var quaternion = new Quaternion().setFromEuler(rotation); return e.clone().premultiply(quaternion); } }, convertVisionQuaternion: function convertVisionQuaternion(e) { return new Quaternion(e.x, e.z, -e.y, e.w).multiply(new Quaternion().setFromAxisAngle(new Vector3(0, 1, 0), MathUtils.degToRad(90))); }, invertVisionQuaternion: function invertVisionQuaternion(e) { //反转给算法部 var a = e.clone().multiply(new Quaternion().setFromAxisAngle(new Vector3(0, 1, 0), MathUtils.degToRad(-90))); return new Quaternion(a.x, -a.z, a.y, a.w); }, //------------ getVec2Angle: function getVec2Angle(dir1, dir2) { return Math.acos(MathUtils.clamp(this.getVec2Cos(dir1, dir2), -1, 1)); }, getVec2Cos: function getVec2Cos(dir1, dir2) { return dir1.dot(dir2) / dir1.length() / dir2.length(); }, getAngle: function getAngle(vec1, vec2) { var axis = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'z'; //带方向的角度 vector3 if (!vec1.isVector3) { vec1 = new Vector3(vec1.x, vec1.y, 0); vec2 = new Vector3(vec2.x, vec2.y, 0); } var angle = vec1.angleTo(vec2); var axis_ = vec1.clone().cross(vec2); if (typeof axis == 'string') { if (axis_[axis] < 0) { angle *= -1; } } else { //vector3 if (axis_.dot(axis) < 0) { angle *= -1; } } return angle; }, closeTo: function closeTo(a, b) { var precision = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1e-6; var f = (a, b) => { return Math.abs(a - b) < precision; }; if (typeof a == 'number') { return f(a, b); } else { var judge = name => { if (a[name] == void 0) return true; //有值就判断,没值就不判断 else return f(a[name], b[name]); }; return judge('x') && judge('y') && judge('z') && judge('w'); } }, toPrecision: function toPrecision(e, t) { //xzw change 保留小数 var f = function f(e, t) { var i = Math.pow(10, t); return Math.round(e * i) / i; }; if (e instanceof Array) { for (var s = 0; s < e.length; s++) { e[s] = f(e[s], t); } return e; } else if (e instanceof Object) { for (var s in e) { e[s] = f(e[s], t); } return e; } else if (typeof e == 'number') { return f(e, t); } else { return e; } }, isEmptyQuaternion: function isEmptyQuaternion(e) { return 0 === Math.abs(e.x) && 0 === Math.abs(e.y) && 0 === Math.abs(e.z) && 0 === Math.abs(e.w); }, projectPositionToCanvas: function projectPositionToCanvas(e, t, i) { i = i || new Vector3(), i.copy(e); var r = .5 * $('#player').width(), o = .5 * $('#player').height(); return i.project(t), i.x = i.x * r + r, i.y = -(i.y * o) + o, i; }, handelPadResize: false, /* handelPadding : function () { //去除player左边和上面的宽高,因为pc的player左上有其他element 许钟文 var pads = [];//记录下来避免反复计算 var index = []; var resetPad = function(){ pads = []; index = []; math.handelPadResize = false; //switchview时resized为true } if(config.isEdit && !config.isMobile){ window.addEventListener('resize',resetPad); } return function(x, y, domE){ if(!config.isEdit || config.isMobile) { return { x: x, y: y } } if(this.handelPadResize)resetPad(); domE = domE || $('#player')[0]; var pad; var i = index.indexOf(domE); if (i == -1){ index.push(domE); pad = { x: this.getOffset("left", domE), y: this.getOffset("top", domE) } pads.push(pad) } else pad = pads[i]; return { x: x - pad.x, y: y - pad.y } } }(), */ getOffset: function getOffset(type, element, parent) { //获取元素的边距 许钟文 var offset = type == "left" ? element.offsetLeft : element.offsetTop; if (!parent) parent = $("body")[0]; while (element = element.offsetParent) { if (element == parent) break; offset += type == "left" ? element.offsetLeft : element.offsetTop; } return offset; }, constrainedTurn: function constrainedTurn(e) { var t = e % (2 * Math.PI); return t = t > Math.PI ? t -= 2 * Math.PI : t < -Math.PI ? t += 2 * Math.PI : t; }, getFOVDotThreshold: function getFOVDotThreshold(e) { return Math.cos(MathUtils.degToRad(e / 2)); }, transform2DForwardVectorByCubeFace: function transform2DForwardVectorByCubeFace(e, t, i, n) { switch (e) { case GLCubeFaces.GL_TEXTURE_CUBE_MAP_POSITIVE_X: i.set(1, t.y, t.x); break; case GLCubeFaces.GL_TEXTURE_CUBE_MAP_NEGATIVE_X: i.set(-1, t.y, -t.x); break; case GLCubeFaces.GL_TEXTURE_CUBE_MAP_POSITIVE_Y: i.set(-t.x, 1, -t.y); break; case GLCubeFaces.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: i.set(-t.x, -1, t.y); break; case GLCubeFaces.GL_TEXTURE_CUBE_MAP_POSITIVE_Z: i.set(-t.x, t.y, 1); break; case GLCubeFaces.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: i.set(t.x, t.y, -1); } n && i.normalize(); }, getFootPoint: function getFootPoint(oldPos, p1, p2, restricInline) { //找oldPos在线段p1, p2上的垂足 /* if(isWorld){//输出全局坐标 需要考虑meshGroup.position p1 = p1.clone(); p2 = p2.clone(); p1.y += mainDesign.meshGroup.position.y; p2.y += mainDesign.meshGroup.position.y; } */ if (p1.equals(p2)) return p1.clone(); var op1 = oldPos.clone().sub(p1); var p1p2 = p1.clone().sub(p2); var p1p2Len = p1p2.length(); var leftLen = op1.dot(p1p2) / p1p2Len; var pos = p1.clone().add(p1p2.multiplyScalar(leftLen / p1p2Len)); if (restricInline && pos.clone().sub(p1).dot(pos.clone().sub(p2)) > 0) { //foot不在线段上 if (pos.distanceTo(p1) < pos.distanceTo(p2)) pos = p1.clone();else pos = p2.clone(); } return pos; }, /** * 计算多边形的重心 * @param {*} points */ getCenterOfGravityPoint: function getCenterOfGravityPoint(mPoints) { var area = 0.0; //多边形面积 var Gx = 0.0, Gy = 0.0; // 重心的x、y for (var i = 1; i <= mPoints.length; i++) { var ix = mPoints[i % mPoints.length].x; var iy = mPoints[i % mPoints.length].y; var nx = mPoints[i - 1].x; var ny = mPoints[i - 1].y; var temp = (ix * ny - iy * nx) / 2.0; area += temp; Gx += temp * (ix + nx) / 3.0; Gy += temp * (iy + ny) / 3.0; } Gx = Gx / area; Gy = Gy / area; return { x: Gx, y: Gy }; }, getBound: function getBound(ring) { var bound = new Box2(); for (var j = 0, len = ring.length; j < len; j++) { bound.expandByPoint(ring[j]); } return bound; }, isPointInArea: function isPointInArea(ring, holes, point, ifAtLine) { //判断点是否在某个环内, 若传递了holes代表还要不能在内环内 var bound = this.getBound(ring); if (point.x < bound.min.x || point.x > bound.max.x || point.y < bound.min.y || point.y > bound.max.y) return false; var inside = false; var x = point.x, y = point.y; for (var i = 0, j = ring.length - 1; i < ring.length; j = i++) { var xi = ring[i].x, yi = ring[i].y; var xj = ring[j].x, yj = ring[j].y; if ((xi - x) * (yj - y) == (xi - x) * (yi - y) && x >= Math.min(xi, xj) && x <= Math.max(xi, xj) //xzw add && y >= Math.min(yi, yj) && y <= Math.max(yi, yj)) { //return !!ifAtLine;//在线段上,则判断为…… (默认在外) return { atLine: true }; } if (yi > y != yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi) { inside = !inside; } } if (inside && holes) { return !holes.some(ring => this.isPointInArea(ring, null, point, ifAtLine)); //不能存在于任何一个二级内环内 } else { return inside; } }, getArea: function getArea(ring) { //求面积 顺时针为正 来自three shape for (var t = ring.length, i = 0, n = t - 1, r = 0; r < t; n = r++) i += ring[n].x * ring[r].y - ring[r].x * ring[n].y; return -.5 * i; }, getVolume: function getVolume(faceArr) {//求三角多面体的体积。和求面积同理都用鞋带计算法 https://blog.csdn.net/weixin_43414513/article/details/123758897 //问题:怎么确定方向 //每个三角形的顺序必须是右手螺旋法则指向物体外(外向里看为逆时针),分别为ABC,则每个三角形和原点O构成的三棱锥体积为 (OA cross OB) dot(OC) / 6 . 结果一般朝向原点的为负,反之为正 }, isInBetween: function isInBetween(a, b, c, precision) { // 如果b几乎等于a或c,返回false.为了避免浮点运行时两值几乎相等,但存在相差0.00000...0001的这种情况出现使用下面方式进行避免 /* if (Math.abs(a - b) < 0.000001 || Math.abs(b - c) < 0.000001) { return false; } return (a <= b && b <= c) || (c <= b && b <= a);*/ //更改:如果b和a或c中一个接近 就算在a和c之间 return a <= b && b <= c || c <= b && b <= a || this.closeTo(a, b, precision) || this.closeTo(b, c, precision); }, ifPointAtLineBound: function ifPointAtLineBound(point, linePoints, precision) { //待验证 横线和竖线比较特殊 return math.isInBetween(linePoints[0].x, point.x, linePoints[1].x, precision) && math.isInBetween(linePoints[0].y, point.y, linePoints[1].y, precision); }, isLineIntersect: function isLineIntersect(line1, line2, notSegment, precision) { //线段和线段是否有交点. notSegment代表是直线而不是线段 var a1 = line1[1].y - line1[0].y; var b1 = line1[0].x - line1[1].x; var c1 = a1 * line1[0].x + b1 * line1[0].y; //转换成一般式: Ax+By = C var a2 = line2[1].y - line2[0].y; var b2 = line2[0].x - line2[1].x; var c2 = a2 * line2[0].x + b2 * line2[0].y; // 计算交点 var d = a1 * b2 - a2 * b1; // 当d==0时,两线平行 if (d == 0) { return false; } else { var x = (b2 * c1 - b1 * c2) / d; var y = (a1 * c2 - a2 * c1) / d; // 检测交点是否在两条线段上 /* if (notSegment || (isInBetween(line1[0].x, x, line1[1].x) || isInBetween(line1[0].y, y, line1[1].y)) && (isInBetween(line2[0].x, x, line2[1].x) || isInBetween(line2[0].y, y, line2[1].y))) { return {x,y}; } */ if (notSegment || math.ifPointAtLineBound({ x, y }, line1, precision) && math.ifPointAtLineBound({ x, y }, line2, precision)) { return { x, y }; } } }, getNormal2d: function getNormal2d() { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; //获取二维法向量 方向向内 var x, y, x1, y1; //line2d的向量 if (o.vec) { x1 = o.vec.x; y1 = o.vec.y; } else { x1 = o.p1.x - o.p2.x; y1 = o.p1.y - o.p2.y; } //假设法向量的x或y固定为1或-1 if (y1 != 0) { x = 1; y = -(x1 * x) / y1; } else if (x1 != 0) { //y如果为0,正常情况x不会是0 y = 1; x = -(y1 * y) / x1; } else { console.log("两个点一样"); return null; } //判断方向里或者外: var vNormal = new Vector3(x, 0, y); var vLine = new Vector3(x1, 0, y1); var vDir = vNormal.cross(vLine); if (vDir.y > 0) { x *= -1; y *= -1; } return new Vector2(x, y).normalize(); }, getQuaBetween2Vector: function getQuaBetween2Vector(oriVec, newVec, upVec) { //获取从oriVec旋转到newVec可以应用的quaternion var angle = oriVec.angleTo(newVec); var axis = oriVec.clone().cross(newVec).normalize(); //两个up之间 if (axis.length() == 0) { //当夹角为180 或 0 度时,得到的axis为(0,0,0),故使用备用的指定upVec return new Quaternion().setFromAxisAngle(upVec, angle); } return new Quaternion().setFromAxisAngle(axis, angle); }, /* getQuaBetween2Vector2 : function(oriVec, newVec ){//not camera var _ = (new THREE.Matrix4).lookAt( oriVec, new THREE.Vector3, new THREE.Vector3(0,1,0)) var aimQua = (new THREE.Quaternion).setFromRotationMatrix(_) var _2 = (new THREE.Matrix4).lookAt( newVec, new THREE.Vector3, new THREE.Vector3(0,1,0)) var aimQua2 = (new THREE.Quaternion).setFromRotationMatrix(_2) return aimQua2.multiply(aimQua.clone().inverse()) } */ getQuaByAim: function getQuaByAim(aim) { var center = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Vector3(); var forward = new Vector3(0, 1, 0); var qua1 = new Quaternion().setFromUnitVectors(forward, aim.clone().sub(center).normalize()); /* var _ = (new THREE.Matrix4).lookAt(center,aim, new THREE.Vector3(0,1,0)); let qua2 = (new THREE.Quaternion).setFromRotationMatrix(_); let rot1 = new THREE.Euler().setFromQuaternion(qua1) let rot2 = new THREE.Euler().setFromQuaternion(qua2) //奇怪,qua2怎么都不对 console.log(rot1,rot2) */ return qua1; }, getAimByQua: function getAimByQua(quaternion) { var center = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Vector3(); return new Vector3(0, 0, -1).applyQuaternion(quaternion).add(center); }, getScaleForConstantSize: function () { //获得规定二维大小的mesh的scale值。可以避免因camera的projection造成的mesh视觉大小改变。 来源:tag.updateDisc var w; var i = new Vector3(), o = new Vector3(), l = new Vector3(), c = new Vector3(), h = new Vector3(); return function () { var op = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (op.width2d) w = op.width2d; //如果恒定二维宽度 else { //否则考虑上距离,加一丢丢近大远小的效果 var currentDis, nearBound, farBound; if (op.camera.type == "OrthographicCamera") { currentDis = 200 / op.camera.zoom; //(op.camera.right - op.camera.left) / op.camera.zoom } else { currentDis = op.position.distanceTo(op.camera.position); } w = op.maxSize - (op.maxSize - op.minSize) * MathUtils.smoothstep(currentDis, op.nearBound, op.farBound); //maxSize : mesh要表现的最大像素宽度; nearBound: 最近距离,若比nearBound近,则使用maxSize } i.copy(op.position).project(op.camera); //tag中心在屏幕上的二维坐标 o.set(op.resolution.x / 2, op.resolution.y / 2, 1).multiply(i); //转化成px -w/2 到 w/2的范围 l.set(w / 2, 0, 0).add(o); //加上tag宽度的一半 c.set(2 / op.resolution.x, 2 / op.resolution.y, 1).multiply(l); //再转回 -1 到 1的范围 h.copy(c).unproject(op.camera); //再转成三维坐标,求得tag边缘的位置 var g = h.distanceTo(op.position); //就能得到tag的三维半径 //这里使用的都是resolution2, 好处是手机端不会太小, 坏处是pc更改网页显示百分比时显示的大小会变(或许可以自己算出设备真实的deviceRatio, 因window.screen是不会改变的),但考虑到用户可以自行调节字大小也许是好的 return g; //可能NAN 当相机和position重叠时 }; }(), //W , H, left, top分别是rect的宽、高、左、上 getCrossPointAtRect: function getCrossPointAtRect(p1, aim, W, H, left, top) { //求射线p1-aim在rect边界上的交点,其中aim在rect范围内,p1则不一定(交点在aim这边的延长线上) var x, y, borderX; var r = (aim.x - p1.x) / (aim.y - p1.y); //根据相似三角形原理先求出这个比值 var getX = function getX(y) { return r * (y - p1.y) + p1.x; }; var getY = function getY(x) { return 1 / r * (x - p1.x) + p1.y; }; if (aim.x >= p1.x) { borderX = W + left; } else { borderX = left; } x = borderX; y = getY(x); if (y < top || y > top + H) { if (y < top) { y = top; } else { y = top + H; } x = getX(y); } return new Vector2(x, y); }, getDirFromUV: function getDirFromUV(uv) { //获取dir 反向计算 - - 二维转三维比较麻烦 var dirB; //所求 单位向量 var y = Math.cos(uv.y * Math.PI); //uv中纵向可以直接确定y, 根据上面getUVfromDir的反向计算 // 故 uv.y * Math.PI 就是到垂直线(向上)的夹角 var angle = 2 * Math.PI * uv.x - Math.PI; //x/z代表的是角度 var axisX, axisZ; //axis为1代表是正,-1是负数 if (-Math.PI <= angle && angle < 0) { axisX = -1; //下半圆 } else { axisX = 1; //上半圆 } if (-Math.PI / 2 <= angle && angle < Math.PI / 2) { axisZ = 1; //右半圆 } else { axisZ = -1; //左半圆 } var XDivideZ = Math.tan(angle); var z = Math.sqrt((1 - y * y) / (1 + XDivideZ * XDivideZ)); var x = XDivideZ * z; if (z * axisZ < 0) { //异号 z *= -1; x *= -1; if (x * axisX < 0) { // console.log("wrong!!!!!??????????") } } x *= -1; //计算完成后这里不能漏掉 *= -1 dirB = this.convertVector.YupToZup(new Vector3(x, y, z)); //理想状态下x和z和anotherDir相同 return dirB; }, getUVfromDir: function getUVfromDir(dir) { //获取UV 同shader里的计算 var dir = this.convertVector.ZupToYup(dir); dir.x *= -1; //计算前这里不能漏掉 *= -1 见shader var tx = Math.atan2(dir.x, dir.z) / (Math.PI * 2.0) + 0.5; //atan2(y,x) 返回从 X 轴正向逆时针旋转到点 (x,y) 时经过的角度。区间是-PI 到 PI 之间的值 var ty = Math.acos(dir.y) / Math.PI; return new Vector2(tx, ty); //理想状态下tx相同 }, getDirByLonLat: function getDirByLonLat(lon, lat) { var dir = new Vector3(); var phi = MathUtils.degToRad(90 - lat); var theta = MathUtils.degToRad(lon); dir.x = Math.sin(phi) * Math.cos(theta); dir.y = Math.cos(phi); dir.z = Math.sin(phi) * Math.sin(theta); return dir; } //0,0 => (1,0,0) 270=>(0,0,-1) , projectPointAtPlane: function projectPointAtPlane() { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; //获取一个点在一个面上的投影 {facePoints:[a,b,c], point:} var plane = new Plane().setFromCoplanarPoints(...o.facePoints); return plane.projectPoint(o.point, new Vector3()); }, getPolygonsMixedRings: function getPolygonsMixedRings(polygons, onlyGetOutRing) { //{points:[vector2,...],holes:[[],[]]} var points = []; var lines = []; var i = 0; polygons.forEach(e => points.push(...e.map(a => new Vector2().copy(a)))); polygons.forEach((ps, j) => { var length = ps.length; var index = 0; while (index < length) { lines.push({ p1: index + i, p2: (index + 1) % length + i }); index++; } i += length; }); points.forEach((p, j) => { p.id = j; }); var rings = searchRings({ points, lines, onlyGetOutRing }); //console.log(rings) rings = rings.filter(e => e.closetParent == void 0); // 子环不加,被外环包含了 return rings; }, getQuaFromPosAim(position, target) { /* let matrix = (new THREE.Matrix4).lookAt(position, target, new THREE.Vector3(0,0,1)) //这里垂直的话会默认给一个右向所以不这么写 return (new THREE.Quaternion).setFromRotationMatrix(matrix) */ var view = new ExtendView(); view.direction = new Vector3().subVectors(target, position); return view.quaternion; }, getBoundByPoints(points, minSize) { var bound = new Box3(); points.forEach(point => { bound.expandByPoint(point); }); var center = bound.getCenter(new Vector3()); if (minSize) { var minBound = new Box3().setFromCenterAndSize(center, minSize); bound.union(minBound); } return { bounding: bound, size: bound.getSize(new Vector3()), center }; }, /* linearClamp(value, x1,x2, y1, y2){//x为bound.min, bound.max value = THREE.Math.clamp(value, x1,x2) return y1 + ( y2 - y1) * (value - x1) / (x2 - x1) } */ linearClamp(value, xArr, yArr) { //xArr需要按顺序从小到大,yArr对应xArr中的值 var len = xArr.length; if (value <= xArr[0]) return yArr[0]; if (value >= xArr[len - 1]) return yArr[len - 1]; var i = 0; while (++i < len) { if (value < xArr[i]) { var x1 = xArr[i - 1], x2 = xArr[i], y1 = yArr[i - 1], y2 = yArr[i]; value = y1 + (y2 - y1) * (value - x1) / (x2 - x1); break; } } return value; } }; /* 如何将若干个点拟合出线段 // 假设你有一个点数组,每个点表示为一个包含x和y坐标的对象 const points = [ { x: 1, y: 2 }, { x: 2, y: 3 }, { x: 3, y: 4 }, { x: 4, y: 5 }, // ... 更多点 ]; // 定义用于计算最小二乘法参数的函数 function leastSquares( ) { let sumX = 0; let sumY = 0; let sumXY = 0; let sumX2 = 0; let n = points.length; for (const point of points) { sumX += point.x; sumY += point.y; sumXY += point.x * point.y; sumX2 += point.x * point.x; } const k = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX); //不知道为何这样算,自己解不出来(使点到直线距离之和平方最小),但测了下似乎是准的 const b = (sumY - k * sumX) / n; return { k, b }; } // 使用上述函数计算拟合直线的参数 const { k, b } = leastSquares(points); // 现在你可以使用这些参数来表示拟合出的线段 console.log(`拟合线段的方程为: y = ${k}x + ${b}`); */ Potree.math = math; function mobileVersion(e, t) { //ios的版本 var i = window.navigator.userAgent, n = i.match(e); return n = n ? n[1].split(t) : [], { major: parseInt(n[0]) || 0, minor: parseInt(n[1]) || 0, patch: parseInt(n[2]) || 0 }; } var browser = { isFullscreen: function isFullscreen() { return document.fullscreenElement || document.mozFullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement; }, supportsFullscreen: function supportsFullscreen() { return document.fullscreenEnabled || document.mozFullscreenEnabled || document.mozFullScreenEnabled || document.webkitFullscreenEnabled || document.msFullscreenEnabled; }, isPointerLocked: function isPointerLocked() { return document.pointerLockElement || document.mozPointerLockElement || document.webkitPointerLockElement; }, requestFullscreen: function requestFullscreen(dom, t) { dom.requestFullscreen ? dom.requestFullscreen() : dom.mozRequestFullScreen ? dom.mozRequestFullScreen() : dom.webkitRequestFullscreen ? dom.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT) : dom.msRequestFullscreen && dom.msRequestFullscreen(), t && $(document).on("fullscreenchange webkitfullscreenchange mozfullscreenchange MSFullscreenChange", browser.requestPointerLock); }, requestPointerLock: function requestPointerLock() { var e; if (document.fullscreenElement) e = document.fullscreenElement();else if (document.mozFullscreenElement) e = document.mozFullscreenElement();else if (document.mozFullScreenElement) e = document.mozFullScreenElement();else { if (!document.webkitFullscreenElement) return; e = document.webkitFullscreenElement(); } ; e.requestPointerLock = e.requestPointerLock || e.mozRequestPointerLock || e.webkitRequestPointerLock, e.requestPointerLock(), $(document).off("fullscreenchange webkitfullscreenchange mozfullscreenchange MSFullscreenChange", this); }, exitPointerLock: function exitPointerLock() { ; document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock, document.exitPointerLock(); }, exitFullscreen: function exitFullscreen() { document.exitFullscreen ? document.exitFullscreen() : document.msExitFullscreen ? document.msExitFullscreen() : document.mozCancelFullScreen ? document.mozCancelFullScreen() : document.webkitExitFullscreen && document.webkitExitFullscreen(); }, details: function details() { var e = navigator.userAgent.match("(Firefox|Chrome|Safari)/([\\d]+)"); return e ? { name: e[1], version: parseInt(e[2]), platform: navigator.platform } : {}; }, is: function is(e) { return this.details() && this.details().name === e; }, inIframe: function inIframe() { return window.parent !== window; }, aspectRatio: function aspectRatio($elem) { $elem = $elem || $("#player"); var e = $elem.width() / $elem.height(); return isFinite(e) ? e : 0; }, userAgent: function userAgent() { return window.navigator.userAgent; }, isMobile: function isMobile() { var e = navigator.userAgent || navigator.vendor || window.opera; return /(android|bb\d+|meego).+mobile|android|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0, 4)); }, isLandscape: function isLandscape() { return this.isMobile && this.aspectRatio() > 1; }, isSmallScreen: function isSmallScreen() { var e = screen.width / window.devicePixelRatio; return e < 240; }, detectIE: function detectIE() { var e = window.navigator.userAgent, t = e.indexOf("MSIE "); return t !== -1 || !!navigator.userAgent.match(/Trident.*rv\:11\./); }, detectSafari: function detectSafari() { var e = window.navigator.userAgent, t = e.indexOf("Safari"); return t !== -1 && !this.detectOpera() && !this.detectChrome(); //xzw add detectOpera }, detectFirefox: function detectFirefox() { var e = window.navigator.userAgent; return e.indexOf("Firefox") !== -1; }, detectChrome: function detectChrome() { var e = window.navigator.userAgent; return e.indexOf("Chrome") !== -1 && !this.detectOpera(); }, detectOpera: function detectOpera() { var e = window.navigator.userAgent; return e.indexOf("OPR") !== -1; }, detectIOS: function detectIOS() { return this.detectIPhone() || this.detectIPad() || this.detectIPod(); }, detectIPad: function detectIPad() { var e = window.navigator.userAgent, t = /iPad/; return t.test(e); }, detectIPod: function detectIPod() { var e = window.navigator.userAgent, t = /iPod/; return t.test(e); }, detectIPhone: function detectIPhone() { var e = window.navigator.userAgent, t = /iPhone/; return t.test(e); }, detectAndroid: function detectAndroid() { var e = window.navigator.userAgent; return e.indexOf("Android") !== -1; }, detectAndroidMobile: function detectAndroidMobile() { var e = window.navigator.userAgent; return this.detectAndroid() && e.indexOf("Mobile") !== -1; }, detectSamsungNative: function detectSamsungNative() { var e = window.navigator.userAgent; return e.indexOf("SM-G900H") !== -1 || e.indexOf("GT-I9500") !== -1 || e.indexOf("SM-N900") !== -1; }, detectSamsungS6: function detectSamsungS6() { var e = window.navigator.userAgent; return e.indexOf("SM-G92") !== -1; }, /************************************************************徐世廷*************************************************************/ detectHUAWEI5X: function detectHUAWEI5X() { return -1 !== window.navigator.userAgent.indexOf("KIW-TL00H"); }, /*******************************************************************************************************************************/ detectWebVR: function detectWebVR() { return !(!window.navigator.getVRDisplays || !window.VRDisplay); }, getVRDisplay: function getVRDisplay() { var e = $.Deferred(); return this.detectWebVR() ? (navigator.getVRDisplays().then(function (t) { t.length >= 1 && e.resolve(t[0]), e.reject(null); }), e) : e.reject(null); }, iosVersion: function iosVersion() { if (!this.detectIOS()) throw new DeviceMismatchException("Did not detect an iDevice"); var e = /((?:\d+\_?){1,3}) like Mac OS/, t = "_"; return mobileVersion(e, t); }, androidVersion: function androidVersion() { if (!this.detectAndroid()) throw new DeviceMismatchException("Did not detect an Android based device"); var e = /Android ((?:\d+\.?){1,3})/, t = "."; return mobileVersion(e, t); }, valueFromCookie: function valueFromCookie(e, t) { var i = new RegExp(e + "=([0-9a-f]+)(; ?|$)").exec(document.cookie); if (!i) return t; var n = i[1]; return "boolean" == typeof t ? "true" === n || "1" === n : "number" == typeof t ? parseFloat(n) : n; }, valueFromHash: function valueFromHash(e, t) { var i = new RegExp("[#&?]" + e + "=([^#&?]*)"), n = i.exec(window.location.href); if (!n) return t; var r = n[1]; return "boolean" == typeof t ? "true" === r || "1" === r : "number" == typeof t ? parseFloat(r) : window.decodeURIComponent(r); }, //-------许钟文:------------------------------------------------- getProjectNum: function getProjectNum() { //获取场景projectNum if (window.__ProjectNum && window.__ProjectNum != "__ProjectNum__") { return window.__ProjectNum; } var number = window.location.href.substring(window.location.href.indexOf("=") + 1); if (number.indexOf("&") != -1) { number = number.substring(0, number.indexOf("&")); } if (number.indexOf("#") != -1) { number = number.substring(0, number.indexOf("#")); } return number; }, urlHasValue: function urlHasValue(key, isGetValue) { var querys = window.location.search.substr(1).split("&"); if (isGetValue) { for (var i = 0; i < querys.length; i++) { var keypair = querys[i].split("="); if (keypair.length === 2 && keypair[0] === key) { return keypair[1]; } } return ""; } else { for (var _i = 0; _i < querys.length; _i++) { var _keypair = querys[_i].split("="); if (_keypair[0] == key) { return true; } } return false; } }, /** * 获取查询参数的值 * @param {String} key * @returns String */ urlQueryValue(key) { return this.urlHasValue(key, true) || ""; }, /** * 判断是否存在hash * @param {String} key * @returns Boolean */ urlIsHasHash(key) { var querys = window.location.hash.substr(1).replace('/?', '').split("&"); return querys.includes(key); }, islongPhone: function islongPhone() { //是否是刘海全面屏幕 仅仅根据比例判断 - - //screen.height == 812 && screen.width == 375) var r = screen.height / screen.width; //可能横屏 return this.isMobile() && (r > 1.99 || r < 0.502512); //18/9=2.165 //??? }, detectWeixin: function detectWeixin() { //微信 包括PC的微信 return window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == "micromessenger"; }, detectWeixinMiniProgram: function detectWeixinMiniProgram() { return window.navigator.userAgent.match("miniProgram"); }, detectEdge: function detectEdge() { return window.navigator.userAgent.indexOf("Edge") > -1; }, detectApp: function detectApp() { return this.urlHasValue("app"); }, /** * 判断标签页是否切换状态 */ isTabHidden: function isTabHidden() { var prefixes = ["webkit", "moz", "ms", "o"]; if ("hidden" in document) return document.hidden; for (var i = 0; i < prefixes.length; i++) { if (prefixes[i] + "Hidden" in document) return document[prefixes[i] + "Hidden"]; } return false; } }; WebGLRenderer.prototype.paramThreeToGL = function (e) { var t, i = this.extensions, r = this.getContext(); //context; if (e === RepeatWrapping) return r.REPEAT; if (e === ClampToEdgeWrapping) return r.CLAMP_TO_EDGE; if (e === MirroredRepeatWrapping) return r.MIRRORED_REPEAT; if (e === NearestFilter) return r.NEAREST; if (e === NearestMipMapNearestFilter) return r.NEAREST_MIPMAP_NEAREST; if (e === NearestMipMapLinearFilter) return r.NEAREST_MIPMAP_LINEAR; if (e === LinearFilter) return r.LINEAR; if (e === LinearMipMapNearestFilter) return r.LINEAR_MIPMAP_NEAREST; if (e === LinearMipMapLinearFilter) return r.LINEAR_MIPMAP_LINEAR; if (e === UnsignedByteType) return r.UNSIGNED_BYTE; if (e === UnsignedShort4444Type) return r.UNSIGNED_SHORT_4_4_4_4; if (e === UnsignedShort5551Type) return r.UNSIGNED_SHORT_5_5_5_1; if (e === UnsignedShort565Type) return r.UNSIGNED_SHORT_5_6_5; if (e === ByteType) return r.BYTE; if (e === ShortType) return r.SHORT; if (e === UnsignedShortType) return r.UNSIGNED_SHORT; if (e === IntType) return r.INT; if (e === UnsignedIntType) return r.UNSIGNED_INT; if (e === FloatType) return r.FLOAT; if (t = i.get("OES_texture_half_float"), null !== t && e === HalfFloatType) return t.HALF_FLOAT_OES; if (e === AlphaFormat) return r.ALPHA; if (e === RGBFormat) return r.RGB; if (e === RGBAFormat) return r.RGBA; if (e === LuminanceFormat) return r.LUMINANCE; if (e === LuminanceAlphaFormat) return r.LUMINANCE_ALPHA; if (e === AddEquation) return r.FUNC_ADD; if (e === SubtractEquation) return r.FUNC_SUBTRACT; if (e === ReverseSubtractEquation) return r.FUNC_REVERSE_SUBTRACT; if (e === ZeroFactor) return r.ZERO; if (e === OneFactor) return r.ONE; if (e === SrcColorFactor) return r.SRC_COLOR; if (e === OneMinusSrcColorFactor) return r.ONE_MINUS_SRC_COLOR; if (e === SrcAlphaFactor) return r.SRC_ALPHA; if (e === OneMinusSrcAlphaFactor) return r.ONE_MINUS_SRC_ALPHA; if (e === DstAlphaFactor) return r.DST_ALPHA; if (e === OneMinusDstAlphaFactor) return r.ONE_MINUS_DST_ALPHA; if (e === DstColorFactor) return r.DST_COLOR; if (e === OneMinusDstColorFactor) return r.ONE_MINUS_DST_COLOR; if (e === SrcAlphaSaturateFactor) return r.SRC_ALPHA_SATURATE; if (t = i.get("WEBGL_compressed_texture_s3tc"), null !== t) { if (e === RGB_S3TC_DXT1_Format) return t.COMPRESSED_RGB_S3TC_DXT1_EXT; if (e === RGBA_S3TC_DXT1_Format$1) return t.COMPRESSED_RGBA_S3TC_DXT1_EXT; if (e === RGBA_S3TC_DXT3_Format) return t.COMPRESSED_RGBA_S3TC_DXT3_EXT; if (e === RGBA_S3TC_DXT5_Format$1) return t.COMPRESSED_RGBA_S3TC_DXT5_EXT; } if (t = i.get("WEBGL_compressed_texture_pvrtc"), null !== t) { if (e === RGB_PVRTC_4BPPV1_Format) return t.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; if (e === RGB_PVRTC_2BPPV1_Format) return t.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; if (e === RGBA_PVRTC_4BPPV1_Format) return t.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; if (e === RGBA_PVRTC_2BPPV1_Format) return t.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; } if (t = i.get("WEBGL_compressed_texture_etc1"), null !== t && e === RGB_ETC1_Format) return t.COMPRESSED_RGB_ETC1_WEBGL; if (t = i.get("EXT_blend_minmax"), null !== t) { if (e === MinEquation) return t.MIN_EXT; if (e === MaxEquation) return t.MAX_EXT; } return 0; }; EventDispatcher.prototype.addEventListener = function (type, listener) { var { importance = 0, once } = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; //add importance if (this._listeners === undefined) this._listeners = {}; var listeners = this._listeners; if (listeners[type] === undefined) { listeners[type] = []; } /* if(type == 'flyingDone'){ console.log('addEventListener flyingDone') } */ if (!listeners[type].some(e => e.listener == listener)) { listeners[type].push({ listener, importance, once }); listeners[type] = listeners[type].sort((e, a) => a.importance - e.importance); //add } }; EventDispatcher.prototype.hasEventListener = function (type, listener) { if (this._listeners === undefined) return false; var listeners = this._listeners; return listeners[type] !== undefined && listeners[type].some(e => e.listener == listener); }; EventDispatcher.prototype.removeEventListener = function (type, listener) { if (this._listeners === undefined) return; var listeners = this._listeners; var listenerArray = listeners[type]; if (listenerArray !== undefined) { /* const index = listenerArray.indexOf( listener ); if ( index !== - 1 ) { listenerArray.splice( index, 1 ); } */ var item = listenerArray.find(e => e.listener == listener); item && listenerArray.splice(listenerArray.indexOf(item), 1); } }; EventDispatcher.prototype.removeEventListeners = function (type) { //add if (this._listeners && this._listeners[type] !== undefined) { delete this._listeners[type]; } }; EventDispatcher.prototype.removeAllListeners = function () { //add this._listeners = {}; }; EventDispatcher.prototype.dispatchEvent = function (event) { if (typeof event == 'string') { //add event = { type: event }; } if (this._listeners === undefined) return; var listeners = this._listeners; var listenerArray = listeners[event.type]; if (listenerArray !== undefined) { event.target = this; // Make a copy, in case listeners are removed while iterating. for (var { listener, once } of listenerArray.slice(0)) { if (once) { this.removeEventListener(event.type, listener); } var result = listener.call(this, event); //add stopContinue if (result && result.stopContinue) { break; } } } }; EventDispatcher.prototype.traverse = function (callback) { var result = callback(this); if (result && result.stopContinue) { //xzw add return; } var children = this.children; if (children) { for (var i = 0, l = children.length; i < l; i++) { children[i].traverse(callback); } } }; Object3D.prototype.traverse = function (callback) { var result = callback(this); if (result && result.stopContinue) { //xzw add return; } var children = this.children; for (var i = 0, l = children.length; i < l; i++) { children[i] && children[i].traverse(callback); } }; Material.prototype.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; } // for backward compatability if shading is set in the constructor 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 ) { //-----主要删了这段,否则很难和 set 一起使用 //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 { this[key] = newValue; } } }; function ascSort$1(a, b) { return a.distance - b.distance; } function intersectObject(object, raycaster, intersects, recursive, ignoreUnvisible) { if (ignoreUnvisible && !object.visible) return; //add if (object.layers.test(raycaster.layers)) { 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, ignoreUnvisible); } } } Raycaster.prototype.intersectObject = function (object, recursive, optionalTarget, ignoreUnvisible) { var intersects = optionalTarget || []; intersectObject(object, this, intersects, recursive, ignoreUnvisible); intersects.sort(ascSort$1); return intersects; }; Raycaster.prototype.intersectObjects = function (objects, recursive, optionalTarget, ignoreUnvisible) { //add ignoreUnvisible 跳过不可见 var intersects = optionalTarget || []; 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, ignoreUnvisible); } intersects.sort(ascSort$1); return intersects; }; Object3D.prototype.realVisible = function () { var v = true; var parent = this; var lastParent; while (parent) { if (parent.visible === false) { v = false; break; } lastParent = parent; parent = parent.parent; } if (v && !(lastParent instanceof Scene)) { //已被删除 v = false; } return v; }; var MathLight = {}; MathLight.RADIANS_PER_DEGREE = Math.PI / 180; MathLight.DEGREES_PER_RADIAN = 180 / Math.PI; MathLight.Vector3 = function (e, t, i) { this.x = e || 0, this.y = t || 0, this.z = i || 0; }; MathLight.Matrix4 = function () { this.elements = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]), arguments.length > 0 && console.error("MathLight.Matrix4: the constructor no longer reads arguments. use .set() instead."); }; MathLight.Matrix4.prototype = { identity: function identity() { return this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1), this; }, copy: function copy(e) { return this.elements.set(e.elements), this; }, applyToVector3: function applyToVector3(e) { var t = e.x, i = e.y, n = e.z, r = this.elements; return e.x = r[0] * t + r[4] * i + r[8] * n + r[12], e.y = r[1] * t + r[5] * i + r[9] * n + r[13], e.z = r[2] * t + r[6] * i + r[10] * n + r[14], this; }, getInverse: function getInverse(e, t) { var i = this.elements, n = e.elements, r = n[0], o = n[1], a = n[2], s = n[3], l = n[4], c = n[5], h = n[6], u = n[7], d = n[8], p = n[9], f = n[10], g = n[11], m = n[12], v = n[13], A = n[14], y = n[15], C = p * A * u - v * f * u + v * h * g - c * A * g - p * h * y + c * f * y, I = m * f * u - d * A * u - m * h * g + l * A * g + d * h * y - l * f * y, E = d * v * u - m * p * u + m * c * g - l * v * g - d * c * y + l * p * y, b = m * p * h - d * v * h - m * c * f + l * v * f + d * c * A - l * p * A, w = r * C + o * I + a * E + s * b; if (0 === w) { var _ = "MathLight.Matrix4.getInverse(): can't invert matrix, determinant is 0"; if (t) throw new Error(_); return console.warn(_), this.identity(); } var T = 1 / w; return i[0] = C * T, i[1] = (v * f * s - p * A * s - v * a * g + o * A * g + p * a * y - o * f * y) * T, i[2] = (c * A * s - v * h * s + v * a * u - o * A * u - c * a * y + o * h * y) * T, i[3] = (p * h * s - c * f * s - p * a * u + o * f * u + c * a * g - o * h * g) * T, i[4] = I * T, i[5] = (d * A * s - m * f * s + m * a * g - r * A * g - d * a * y + r * f * y) * T, i[6] = (m * h * s - l * A * s - m * a * u + r * A * u + l * a * y - r * h * y) * T, i[7] = (l * f * s - d * h * s + d * a * u - r * f * u - l * a * g + r * h * g) * T, i[8] = E * T, i[9] = (m * p * s - d * v * s - m * o * g + r * v * g + d * o * y - r * p * y) * T, i[10] = (l * v * s - m * c * s + m * o * u - r * v * u - l * o * y + r * c * y) * T, i[11] = (d * c * s - l * p * s - d * o * u + r * p * u + l * o * g - r * c * g) * T, i[12] = b * T, i[13] = (d * v * a - m * p * a + m * o * f - r * v * f - d * o * A + r * p * A) * T, i[14] = (m * c * a - l * v * a - m * o * h + r * v * h + l * o * A - r * c * A) * T, i[15] = (l * p * a - d * c * a + d * o * h - r * p * h - l * o * f + r * c * f) * T, this; }, makeRotationFromQuaternion: function makeRotationFromQuaternion(e) { var t = this.elements, i = e.x, n = e.y, r = e.z, o = e.w, a = i + i, s = n + n, l = r + r, c = i * a, h = i * s, u = i * l, d = n * s, p = n * l, f = r * l, g = o * a, m = o * s, v = o * l; return t[0] = 1 - (d + f), t[4] = h - v, t[8] = u + m, t[1] = h + v, t[5] = 1 - (c + f), t[9] = p - g, t[2] = u - m, t[6] = p + g, t[10] = 1 - (c + d), t[3] = 0, t[7] = 0, t[11] = 0, t[12] = 0, t[13] = 0, t[14] = 0, t[15] = 1, this; } }; MathLight.Quaternion = function (e, t, i, n) { this._x = e || 0, this._y = t || 0, this._z = i || 0, this._w = void 0 !== n ? n : 1; }; MathLight.Quaternion.prototype = { get x() { return this._x; }, set x(e) { this._x = e; }, get y() { return this._y; }, set y(e) { this._y = e; }, get z() { return this._z; }, set z(e) { this._z = e; }, get w() { return this._w; }, set w(e) { this._w = e; }, copy: function copy(e) { this._x = e.x, this._y = e.y, this._z = e.z, this._w = e.w; }, inverse: function inverse() { return this.conjugate().normalize(); }, conjugate: function conjugate() { return this._x *= -1, this._y *= -1, this._z *= -1, this; }, length: function length() { return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w); }, normalize: function normalize() { var e = this.length(); return 0 === e ? (this._x = 0, this._y = 0, this._z = 0, this._w = 1) : (e = 1 / e, this._x = this._x * e, this._y = this._y * e, this._z = this._z * e, this._w = this._w * e), this; }, setFromAxisAngle: function setFromAxisAngle(e, t) { var i = t / 2, n = Math.sin(i); return this._x = e.x * n, this._y = e.y * n, this._z = e.z * n, this._w = Math.cos(i), this; }, setFromUnitVectors: function () { var e, t, i = 1e-6; return function (n, o) { return void 0 === e && (e = new MathLight.Vector3()), t = MathLight.dot(n, o) + 1, t < i ? (t = 0, Math.abs(n.x) > Math.abs(n.z) ? MathLight.setVector(e, -n.y, n.x, 0) : MathLight.setVector(e, 0, -n.z, n.y)) : MathLight.cross(n, o, e), this._x = e.x, this._y = e.y, this._z = e.z, this._w = t, this.normalize(); }; }(), multiply: function multiply(e) { return this.multiplyQuaternions(this, e); }, premultiply: function premultiply(e) { return this.multiplyQuaternions(e, this); }, multiplyQuaternions: function multiplyQuaternions(e, t) { var i = e._x, n = e._y, r = e._z, o = e._w, a = t._x, s = t._y, l = t._z, c = t._w; return this._x = i * c + o * a + n * l - r * s, this._y = n * c + o * s + r * a - i * l, this._z = r * c + o * l + i * s - n * a, this._w = o * c - i * a - n * s - r * l, this; } }; MathLight.convertWorkshopVector = function (e) { return new MathLight.Vector3(-e.x, e.y, e.z); }; MathLight.convertWorkshopQuaternion = function (e) { return new MathLight.Quaternion(-e.x, e.y, e.z, -e.w).multiply(new MathLight.Quaternion(Math.sqrt(2) / 2, Math.sqrt(2) / 2, 0, 0)); }; MathLight.convertWorkshopOrthoZoom = function (e) { //return e === -1 ? -1 : e / 16 * ($('#player').width() / $('#player').height()) / n.workshopApsect return e === -1 ? -1 : e * ($("#player").width() / $("#player").height()); }; MathLight.convertWorkshopPanoramaQuaternion = function (e) { return new MathLight.Quaternion(e.x, -e.y, -e.z, e.w).normalize().multiply(new MathLight.Quaternion().setFromAxisAngle(new MathLight.Vector3(0, 1, 0), 270 * MathLight.RADIANS_PER_DEGREE)); }; MathLight.normalize = function (e) { var t = e.x * e.x + e.y * e.y + e.z * e.z, i = Math.sqrt(t); e.x /= i, e.y /= i, e.z /= i; }; MathLight.dot = function (e, t) { return e.x * t.x + e.y * t.y + e.z * t.z; }; MathLight.cross = function (e, t, i) { var n = e.x, r = e.y, o = e.z; i.x = r * t.z - o * t.y, i.y = o * t.x - n * t.z, i.z = n * t.y - r * t.x; }; MathLight.setVector = function (e, t, i, n) { e.x = t, e.y = i, e.z = n; }; MathLight.copyVector = function (e, t) { t.x = e.x, t.y = e.y, t.z = e.z; }; MathLight.addVector = function (e, t) { e.x += t.x, e.y += t.y, e.z += t.z; }; MathLight.subVector = function (e, t) { e.x -= t.x, e.y -= t.y, e.z -= t.z; }; MathLight.applyQuaternionToVector = function (e, t) { var i = t.x, n = t.y, r = t.z, o = e.x, a = e.y, s = e.z, l = e.w, c = l * i + a * r - s * n, h = l * n + s * i - o * r, u = l * r + o * n - a * i, d = -o * i - a * n - s * r; t.x = c * l + d * -o + h * -s - u * -a, t.y = h * l + d * -a + u * -o - c * -s, t.z = u * l + d * -s + c * -a - h * -o; }; MathLight.angleBetweenVectors = function (e, t) { return Math.acos(MathLight.dot(e, t)); }; var cameraLight = { clampVFOV: function clampVFOV(currentFov, maxHFov, width, height) { //限制currentFov, 使之造成的横向fov不大于指定值maxHFov var r = cameraLight.getHFOVFromVFOV(currentFov, width, height); return r > maxHFov ? cameraLight.getVFOVFromHFOV(maxHFov, width, height) : currentFov; }, getHFOVForCamera: function getHFOVForCamera(camera, getRad) { return cameraLight.getHFOVByScreenPrecent(camera.fov, camera.aspect, getRad); }, //add getHFOVByScreenPrecent: function getHFOVByScreenPrecent(fov, percent, getRad) { //当fov为占比百分百时,percent代表在屏幕上从中心到边缘的占比 var rad = 2 * Math.atan(percent * Math.tan(fov * MathLight.RADIANS_PER_DEGREE / 2)); if (getRad) return rad;else return rad * MathLight.DEGREES_PER_RADIAN; } }; var XHRFactory = { config: { withCredentials: false, customHeaders: [{ header: null, value: null }] }, createXMLHttpRequest: function createXMLHttpRequest() { var xhr = new XMLHttpRequest(); if (this.config.customHeaders && Array.isArray(this.config.customHeaders) && this.config.customHeaders.length > 0) { var baseOpen = xhr.open; var customHeaders = this.config.customHeaders; xhr.open = function () { baseOpen.apply(this, [].slice.call(arguments)); customHeaders.forEach(function (customHeader) { if (!!customHeader.header && !!customHeader.value) { xhr.setRequestHeader(customHeader.header, customHeader.value); } }); }; } return xhr; } }; // /** class TextSprite$1 extends Object3D { //old constructor(text) { super(); var texture = new Texture(); texture.minFilter = LinearFilter; texture.magFilter = LinearFilter; var spriteMaterial = new SpriteMaterial({ map: texture, depthTest: false, depthWrite: false }); this.texture = texture; this.material = spriteMaterial; //this.material = getRawMaterial(texture); this.sprite = new Sprite$1(this.material); this.add(this.sprite); this.borderThickness = 4; this.fontface = 'Arial'; this.fontsize = 28; this.borderColor = { r: 0, g: 0, b: 0, a: 1.0 }; this.backgroundColor = { r: 255, g: 255, b: 255, a: 1.0 }; this.textColor = { r: 255, g: 255, b: 255, a: 1.0 }; this.text = ''; this.setText(text); } setText(text) { if (this.text !== text) { this.text = text; this.update(); } } setTextColor(color) { this.textColor = color; this.update(); } setBorderColor(color) { this.borderColor = color; this.update(); } setBackgroundColor(color) { this.backgroundColor = color; this.update(); } update() { var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); context.font = 'Bold ' + this.fontsize + 'px ' + this.fontface; // get size data (height depends only on font size) var metrics = context.measureText(this.text); var textWidth = metrics.width; var margin = 5; var spriteWidth = 2 * margin + textWidth + 2 * this.borderThickness; var spriteHeight = this.fontsize * 1.4 + 2 * this.borderThickness; context.canvas.width = spriteWidth; context.canvas.height = spriteHeight; context.font = 'Bold ' + this.fontsize + 'px ' + this.fontface; // background color context.fillStyle = 'rgba(' + this.backgroundColor.r + ',' + this.backgroundColor.g + ',' + this.backgroundColor.b + ',' + this.backgroundColor.a + ')'; // border color context.strokeStyle = 'rgba(' + this.borderColor.r + ',' + this.borderColor.g + ',' + this.borderColor.b + ',' + this.borderColor.a + ')'; context.lineWidth = this.borderThickness; this.roundRect(context, this.borderThickness / 2, this.borderThickness / 2, textWidth + this.borderThickness + 2 * margin, this.fontsize * 1.4 + this.borderThickness, 6); // text color context.strokeStyle = 'rgba(0, 0, 0, 1.0)'; context.strokeText(this.text, this.borderThickness + margin, this.fontsize + this.borderThickness); context.fillStyle = 'rgba(' + this.textColor.r + ',' + this.textColor.g + ',' + this.textColor.b + ',' + this.textColor.a + ')'; context.fillText(this.text, this.borderThickness + margin, this.fontsize + this.borderThickness); var texture = new Texture(canvas); texture.minFilter = LinearFilter; texture.magFilter = LinearFilter; texture.needsUpdate = true; //this.material.needsUpdate = true; // { // screen-space sprite // let [screenWidth, screenHeight] = [1620, 937]; // let uniforms = this.sprite.material.uniforms; // let aspect = spriteHeight / spriteWidth; // let factor = 0.5; // let w = spriteWidth / screenWidth; // let h = spriteHeight / screenHeight; // uniforms.uScale.value = [2 * w, 2 * h]; // //uniforms.uScale.value = [factor * 1, factor * aspect]; // this.sprite.material.uniforms.map.value = texture; // } this.sprite.material.map = texture; this.texture = texture; this.sprite.scale.set(spriteWidth * 0.01, spriteHeight * 0.01, 1.0); } roundRect(ctx, x, y, w, h, r) { ctx.beginPath(); ctx.moveTo(x + r, y); ctx.lineTo(x + w - r, y); ctx.quadraticCurveTo(x + w, y, x + w, y + r); ctx.lineTo(x + w, y + h - r); ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h); ctx.lineTo(x + r, y + h); ctx.quadraticCurveTo(x, y + h, x, y + h - r); ctx.lineTo(x, y + r); ctx.quadraticCurveTo(x, y, x + r, y); ctx.closePath(); ctx.fill(); ctx.stroke(); } } class Volume extends Object3D { constructor() { var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(); if (this.constructor.name === "Volume") { console.warn("Can't create object of class Volume directly. Use classes BoxVolume or SphereVolume instead."); } //console.log(this); //console.log(this.constructor); //console.log(this.constructor.name); this._clip = args.clip || false; this._visible = true; this.showVolumeLabel = true; this._modifiable = args.modifiable || true; this.label = new TextSprite$1('0'); this.label.setBorderColor({ r: 0, g: 255, b: 0, a: 0.0 }); this.label.setBackgroundColor({ r: 0, g: 255, b: 0, a: 0.0 }); this.label.material.depthTest = false; this.label.material.depthWrite = false; this.label.material.transparent = true; this.label.position.y -= 0.5; this.add(this.label); this.label.updateMatrixWorld = () => { var volumeWorldPos = new Vector3(); volumeWorldPos.setFromMatrixPosition(this.matrixWorld); this.label.position.copy(volumeWorldPos); this.label.updateMatrix(); this.label.matrixWorld.copy(this.label.matrix); this.label.matrixWorldNeedsUpdate = false; for (var i = 0, l = this.label.children.length; i < l; i++) { this.label.children[i].updateMatrixWorld(true); } }; { // event listeners this.addEventListener('select', e => {}); this.addEventListener('deselect', e => {}); } } get visible() { return this._visible; } set visible(value) { if (this._visible !== value) { this._visible = value; this.dispatchEvent({ type: "visibility_changed", object: this }); } } getVolume() { console.warn("override this in subclass"); } update() {} raycast(raycaster, intersects) {} get clip() { return this._clip; } set clip(value) { if (this._clip !== value) { this._clip = value; this.update(); this.dispatchEvent({ type: "clip_changed", object: this }); } } get modifieable() { return this._modifiable; } set modifieable(value) { this._modifiable = value; this.update(); } } ; class BoxVolume extends Volume { constructor() { var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(args); this.constructor.counter = this.constructor.counter === undefined ? 0 : this.constructor.counter + 1; this.name = 'box_' + this.constructor.counter; var boxGeometry = new BoxGeometry(1, 1, 1); boxGeometry.computeBoundingBox(); var boxFrameGeometry = new Geometry(); { var Vector3$1 = Vector3; boxFrameGeometry.vertices.push( // bottom new Vector3$1(-0.5, -0.5, 0.5), new Vector3$1(0.5, -0.5, 0.5), new Vector3$1(0.5, -0.5, 0.5), new Vector3$1(0.5, -0.5, -0.5), new Vector3$1(0.5, -0.5, -0.5), new Vector3$1(-0.5, -0.5, -0.5), new Vector3$1(-0.5, -0.5, -0.5), new Vector3$1(-0.5, -0.5, 0.5), // top new Vector3$1(-0.5, 0.5, 0.5), new Vector3$1(0.5, 0.5, 0.5), new Vector3$1(0.5, 0.5, 0.5), new Vector3$1(0.5, 0.5, -0.5), new Vector3$1(0.5, 0.5, -0.5), new Vector3$1(-0.5, 0.5, -0.5), new Vector3$1(-0.5, 0.5, -0.5), new Vector3$1(-0.5, 0.5, 0.5), // sides new Vector3$1(-0.5, -0.5, 0.5), new Vector3$1(-0.5, 0.5, 0.5), new Vector3$1(0.5, -0.5, 0.5), new Vector3$1(0.5, 0.5, 0.5), new Vector3$1(0.5, -0.5, -0.5), new Vector3$1(0.5, 0.5, -0.5), new Vector3$1(-0.5, -0.5, -0.5), new Vector3$1(-0.5, 0.5, -0.5)); } this.material = new MeshBasicMaterial({ color: 0x00ff00, transparent: true, opacity: 0.3, depthTest: true, depthWrite: false }); this.box = new Mesh(boxGeometry, this.material); this.box.geometry.computeBoundingBox(); this.boundingBox = this.box.geometry.boundingBox; this.add(this.box); this.frame = new LineSegments(boxFrameGeometry, new LineBasicMaterial({ color: 0x000000 })); // this.frame.mode = THREE.Lines; this.add(this.frame); this.update(); } update() { this.boundingBox = this.box.geometry.boundingBox; this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere()); if (this._clip) { this.box.visible = false; this.label.visible = false; } else { this.box.visible = true; this.label.visible = this.showVolumeLabel; } } raycast(raycaster, intersects) { var is = []; this.box.raycast(raycaster, is); if (is.length > 0) { var I = is[0]; intersects.push({ distance: I.distance, object: this, point: I.point.clone() }); } } getVolume() { return Math.abs(this.scale.x * this.scale.y * this.scale.z); } } ; class SphereVolume$1 extends Volume { constructor() { var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(args); this.constructor.counter = this.constructor.counter === undefined ? 0 : this.constructor.counter + 1; this.name = 'sphere_' + this.constructor.counter; var sphereGeometry = new SphereGeometry(1, 32, 32); sphereGeometry.computeBoundingBox(); this.material = new MeshBasicMaterial({ color: 0x00ff00, transparent: true, opacity: 0.3, depthTest: true, depthWrite: false }); this.sphere = new Mesh(sphereGeometry, this.material); this.sphere.visible = false; this.sphere.geometry.computeBoundingBox(); this.boundingBox = this.sphere.geometry.boundingBox; this.add(this.sphere); this.label.visible = false; var frameGeometry = new Geometry(); { var steps = 64; var uSegments = 8; var vSegments = 5; var r = 1; for (var uSegment = 0; uSegment < uSegments; uSegment++) { var alpha = uSegment / uSegments * Math.PI * 2; var dirx = Math.cos(alpha); var diry = Math.sin(alpha); for (var i = 0; i <= steps; i++) { var v = i / steps * Math.PI * 2; var vNext = v + 2 * Math.PI / steps; var height = Math.sin(v); var xyAmount = Math.cos(v); var heightNext = Math.sin(vNext); var xyAmountNext = Math.cos(vNext); var vertex = new Vector3(dirx * xyAmount, diry * xyAmount, height); frameGeometry.vertices.push(vertex); var vertexNext = new Vector3(dirx * xyAmountNext, diry * xyAmountNext, heightNext); frameGeometry.vertices.push(vertexNext); } } // creates rings at poles, just because it's easier to implement for (var vSegment = 0; vSegment <= vSegments + 1; vSegment++) { //let height = (vSegment / (vSegments + 1)) * 2 - 1; // -1 to 1 var uh = vSegment / (vSegments + 1); // -1 to 1 uh = (1 - uh) * (-Math.PI / 2) + uh * (Math.PI / 2); var _height = Math.sin(uh); console.log(uh, _height); for (var _i = 0; _i <= steps; _i++) { var u = _i / steps * Math.PI * 2; var uNext = u + 2 * Math.PI / steps; var _dirx = Math.cos(u); var _diry = Math.sin(u); var dirxNext = Math.cos(uNext); var diryNext = Math.sin(uNext); var _xyAmount = Math.sqrt(1 - _height * _height); var _vertex = new Vector3(_dirx * _xyAmount, _diry * _xyAmount, _height); frameGeometry.vertices.push(_vertex); var _vertexNext = new Vector3(dirxNext * _xyAmount, diryNext * _xyAmount, _height); frameGeometry.vertices.push(_vertexNext); } } } this.frame = new LineSegments(frameGeometry, new LineBasicMaterial({ color: 0x000000 })); this.add(this.frame); var frameMaterial = new MeshBasicMaterial({ wireframe: true, color: 0x000000 }); this.frame = new Mesh(sphereGeometry, frameMaterial); //this.add(this.frame); //this.frame = new THREE.LineSegments(boxFrameGeometry, new THREE.LineBasicMaterial({color: 0x000000})); // this.frame.mode = THREE.Lines; //this.add(this.frame); this.update(); } update() { this.boundingBox = this.sphere.geometry.boundingBox; this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere()); //if (this._clip) { // this.sphere.visible = false; // this.label.visible = false; //} else { // this.sphere.visible = true; // this.label.visible = this.showVolumeLabel; //} } raycast(raycaster, intersects) { var is = []; this.sphere.raycast(raycaster, is); if (is.length > 0) { var I = is[0]; intersects.push({ distance: I.distance, object: this, point: I.point.clone() }); } } // see https://en.wikipedia.org/wiki/Ellipsoid#Volume getVolume() { return 4 / 3 * Math.PI * this.scale.x * this.scale.y * this.scale.z; } } ; class Profile extends Object3D { constructor() { super(); this.constructor.counter = this.constructor.counter === undefined ? 0 : this.constructor.counter + 1; this.name = 'Profile_' + this.constructor.counter; this.points = []; this.spheres = []; this.edges = []; this.boxes = []; this.width = 1; this.height = 20; this._modifiable = true; this.sphereGeometry = new SphereGeometry(0.4, 10, 10); this.color = new Color(0xff0000); this.lineColor = new Color(0xff0000); } createSphereMaterial() { var sphereMaterial = new MeshLambertMaterial({ //shading: THREE.SmoothShading, color: 0xff0000, depthTest: false, depthWrite: false }); return sphereMaterial; } getSegments() { var segments = []; for (var i = 0; i < this.points.length - 1; i++) { var start = this.points[i].clone(); var end = this.points[i + 1].clone(); segments.push({ start: start, end: end }); } return segments; } getSegmentMatrices() { var segments = this.getSegments(); var matrices = []; for (var segment of segments) { var { start, end } = segment; var box = new Object3D(); var length = start.clone().setZ(0).distanceTo(end.clone().setZ(0)); box.scale.set(length, 10000, this.width); box.up.set(0, 0, 1); var center = new Vector3().addVectors(start, end).multiplyScalar(0.5); var diff = new Vector3().subVectors(end, start); var target = new Vector3(diff.y, -diff.x, 0); box.position.set(0, 0, 0); box.lookAt(target); box.position.copy(center); box.updateMatrixWorld(); matrices.push(box.matrixWorld); } return matrices; } addMarker(point) { this.points.push(point); var sphere = new Mesh(this.sphereGeometry, this.createSphereMaterial()); this.add(sphere); this.spheres.push(sphere); // edges & boxes if (this.points.length > 1) { var lineGeometry = new Geometry(); lineGeometry.vertices.push(new Vector3(), new Vector3()); lineGeometry.colors.push(this.lineColor, this.lineColor, this.lineColor); var lineMaterial = new LineBasicMaterial({ vertexColors: VertexColors, linewidth: 2, transparent: true, opacity: 0.4 }); lineMaterial.depthTest = false; var edge = new Line(lineGeometry, lineMaterial); edge.visible = false; this.add(edge); this.edges.push(edge); var boxGeometry = new BoxGeometry(1, 1, 1); var boxMaterial = new MeshBasicMaterial({ color: 0xff0000, transparent: true, opacity: 0.2 }); var box = new Mesh(boxGeometry, boxMaterial); box.visible = false; this.add(box); this.boxes.push(box); } { // event listeners var drag = e => { var I = Utils.getMousePointCloudIntersection(e.drag.end, e.viewer.scene.getActiveCamera(), e.viewer, e.viewer.scene.pointclouds); if (I) { var i = this.spheres.indexOf(e.drag.object); if (i !== -1) { this.setPosition(i, I.location); //this.dispatchEvent({ // 'type': 'marker_moved', // 'profile': this, // 'index': i //}); } } }; var drop = e => { var i = this.spheres.indexOf(e.drag.object); if (i !== -1) { this.dispatchEvent({ 'type': 'marker_dropped', 'profile': this, 'index': i }); } }; var mouseover = e => e.object.material.emissive.setHex(0x888888); var mouseleave = e => e.object.material.emissive.setHex(0x000000); sphere.addEventListener('drag', drag); sphere.addEventListener('drop', drop); sphere.addEventListener('mouseover', mouseover); sphere.addEventListener('mouseleave', mouseleave); } var event = { type: 'marker_added', profile: this, sphere: sphere }; this.dispatchEvent(event); this.setPosition(this.points.length - 1, point); } removeMarker(index) { this.points.splice(index, 1); this.remove(this.spheres[index]); var edgeIndex = index === 0 ? 0 : index - 1; this.remove(this.edges[edgeIndex]); this.edges.splice(edgeIndex, 1); this.remove(this.boxes[edgeIndex]); this.boxes.splice(edgeIndex, 1); this.spheres.splice(index, 1); this.update(); this.dispatchEvent({ 'type': 'marker_removed', 'profile': this }); } setPosition(index, position) { var point = this.points[index]; point.copy(position); var event = { type: 'marker_moved', profile: this, index: index, position: point.clone() }; this.dispatchEvent(event); this.update(); } setWidth(width) { this.width = width; var event = { type: 'width_changed', profile: this, width: width }; this.dispatchEvent(event); this.update(); } getWidth() { return this.width; } update() { if (this.points.length === 0) { return; } else if (this.points.length === 1) { var point = this.points[0]; this.spheres[0].position.copy(point); return; } var min = this.points[0].clone(); var max = this.points[0].clone(); var centroid = new Vector3(); var lastIndex = this.points.length - 1; for (var i = 0; i <= lastIndex; i++) { var _point = this.points[i]; var sphere = this.spheres[i]; var leftIndex = i === 0 ? lastIndex : i - 1; // let rightIndex = (i === lastIndex) ? 0 : i + 1; var leftVertex = this.points[leftIndex]; // let rightVertex = this.points[rightIndex]; var leftEdge = this.edges[leftIndex]; var rightEdge = this.edges[i]; var leftBox = this.boxes[leftIndex]; // rightBox = this.boxes[i]; // let leftEdgeLength = point.distanceTo(leftVertex); // let rightEdgeLength = point.distanceTo(rightVertex); // let leftEdgeCenter = new THREE.Vector3().addVectors(leftVertex, point).multiplyScalar(0.5); // let rightEdgeCenter = new THREE.Vector3().addVectors(point, rightVertex).multiplyScalar(0.5); sphere.position.copy(_point); if (this._modifiable) { sphere.visible = true; } else { sphere.visible = false; } if (leftEdge) { leftEdge.geometry.vertices[1].copy(_point); leftEdge.geometry.verticesNeedUpdate = true; leftEdge.geometry.computeBoundingSphere(); } if (rightEdge) { rightEdge.geometry.vertices[0].copy(_point); rightEdge.geometry.verticesNeedUpdate = true; rightEdge.geometry.computeBoundingSphere(); } if (leftBox) { var start = leftVertex; var end = _point; var length = start.clone().setZ(0).distanceTo(end.clone().setZ(0)); leftBox.scale.set(length, 1000000, this.width); leftBox.up.set(0, 0, 1); var center = new Vector3().addVectors(start, end).multiplyScalar(0.5); var diff = new Vector3().subVectors(end, start); var target = new Vector3(diff.y, -diff.x, 0); leftBox.position.set(0, 0, 0); leftBox.lookAt(target); leftBox.position.copy(center); } centroid.add(_point); min.min(_point); max.max(_point); } centroid.multiplyScalar(1 / this.points.length); for (var _i = 0; _i < this.boxes.length; _i++) { var box = this.boxes[_i]; box.position.z = min.z + (max.z - min.z) / 2; } } raycast(raycaster, intersects) { for (var i = 0; i < this.points.length; i++) { var sphere = this.spheres[i]; sphere.raycast(raycaster, intersects); } // recalculate distances because they are not necessarely correct // for scaled objects. // see https://github.com/mrdoob/three.js/issues/5827 // TODO: remove this once the bug has been fixed for (var _i2 = 0; _i2 < intersects.length; _i2++) { var I = intersects[_i2]; I.distance = raycaster.ray.origin.distanceTo(I.point); } intersects.sort(function (a, b) { return a.distance - b.distance; }); } get modifiable() { return this._modifiable; } set modifiable(value) { this._modifiable = value; this.update(); } } var _box$4 = new Box3(); var _vector$d = new Vector3(); class LineSegmentsGeometry extends InstancedBufferGeometry { constructor() { super(); this.isLineSegmentsGeometry = true; this.type = 'LineSegmentsGeometry'; var positions = [-1, 2, 0, 1, 2, 0, -1, 1, 0, 1, 1, 0, -1, 0, 0, 1, 0, 0, -1, -1, 0, 1, -1, 0]; var uvs = [-1, 2, 1, 2, -1, 1, 1, 1, -1, -1, 1, -1, -1, -2, 1, -2]; var index = [0, 2, 1, 2, 3, 1, 2, 4, 3, 4, 5, 3, 4, 6, 5, 6, 7, 5]; this.setIndex(index); this.setAttribute('position', new Float32BufferAttribute(positions, 3)); this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); } applyMatrix4(matrix) { var start = this.attributes.instanceStart; var end = this.attributes.instanceEnd; if (start !== undefined) { start.applyMatrix4(matrix); end.applyMatrix4(matrix); start.needsUpdate = true; } if (this.boundingBox !== null) { this.computeBoundingBox(); } if (this.boundingSphere !== null) { this.computeBoundingSphere(); } return this; } setPositions(array) { var lineSegments; if (array instanceof Float32Array) { lineSegments = array; } else if (Array.isArray(array)) { lineSegments = new Float32Array(array); } var instanceBuffer = new InstancedInterleavedBuffer(lineSegments, 6, 1); // xyz, xyz this.setAttribute('instanceStart', new InterleavedBufferAttribute(instanceBuffer, 3, 0)); // xyz this.setAttribute('instanceEnd', new InterleavedBufferAttribute(instanceBuffer, 3, 3)); // xyz // this.computeBoundingBox(); this.computeBoundingSphere(); return this; } setColors(array) { var colors; if (array instanceof Float32Array) { colors = array; } else if (Array.isArray(array)) { colors = new Float32Array(array); } var instanceColorBuffer = new InstancedInterleavedBuffer(colors, 6, 1); // rgb, rgb this.setAttribute('instanceColorStart', new InterleavedBufferAttribute(instanceColorBuffer, 3, 0)); // rgb this.setAttribute('instanceColorEnd', new InterleavedBufferAttribute(instanceColorBuffer, 3, 3)); // rgb return this; } fromWireframeGeometry(geometry) { this.setPositions(geometry.attributes.position.array); return this; } fromEdgesGeometry(geometry) { this.setPositions(geometry.attributes.position.array); return this; } fromMesh(mesh) { this.fromWireframeGeometry(new WireframeGeometry(mesh.geometry)); // set colors, maybe return this; } fromLineSegments(lineSegments) { var geometry = lineSegments.geometry; this.setPositions(geometry.attributes.position.array); // assumes non-indexed // set colors, maybe return this; } computeBoundingBox() { if (this.boundingBox === null) { this.boundingBox = new Box3(); } var start = this.attributes.instanceStart; var end = this.attributes.instanceEnd; if (start !== undefined && end !== undefined) { this.boundingBox.setFromBufferAttribute(start); _box$4.setFromBufferAttribute(end); this.boundingBox.union(_box$4); } } computeBoundingSphere() { if (this.boundingSphere === null) { this.boundingSphere = new Sphere(); } if (this.boundingBox === null) { this.computeBoundingBox(); } var start = this.attributes.instanceStart; var end = this.attributes.instanceEnd; if (start !== undefined && end !== undefined) { var center = this.boundingSphere.center; this.boundingBox.getCenter(center); var maxRadiusSq = 0; for (var i = 0, il = start.count; i < il; i++) { _vector$d.fromBufferAttribute(start, i); maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$d)); _vector$d.fromBufferAttribute(end, i); maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$d)); } this.boundingSphere.radius = Math.sqrt(maxRadiusSq); if (isNaN(this.boundingSphere.radius)) { console.error('THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.', this); } } } toJSON() { // todo } applyMatrix(matrix) { console.warn('THREE.LineSegmentsGeometry: applyMatrix() has been renamed to applyMatrix4().'); return this.applyMatrix4(matrix); } } /** * parameters = { * color: , * lineWidth: , * dashed: , * dashScale: , * dashSize: , * dashOffset: , * gapSize: , * resolution: , // to be set by renderer * } */ UniformsLib.line = { /* worldUnits: { value: 1 }, lineWidth: { value: 1 }, resolution: { value: new Vector2( 1, 1 ) }, dashOffset: { value: 0 }, dashScale: { value: 1 }, dashSize: { value: 1 }, gapSize: { value: 1 } // todo FIX - maybe change to totalSize */ worldUnits: { value: 1 }, lineWidth: { value: 1 }, resolution: { value: new Vector2(1, 1) }, viewportOffset: { value: new Vector2(0, 0) }, //left, top devicePixelRatio: { value: window.devicePixelRatio }, dashScale: { value: 1 }, dashSize: { value: 1 }, dashOffset: { value: 0 }, gapSize: { value: 1 }, opacity: { value: 1 }, backColor: { type: 'v3', value: new Color("#ddd") }, clipDistance: { type: 'f', value: 4 }, //消失距离 occlusionDistance: { type: 'f', value: 1 }, //变为backColor距离 maxClipFactor: { type: 'f', value: 1 }, //0-1 maxOcclusionFactor: { type: 'f', value: 1 }, //0-1 depthTexture: { value: null }, nearPlane: { value: 0.1 }, farPlane: { value: 100000 } //uUseOrthographicCamera:{ type: "b", value: false }, }; ShaderLib['line'] = { uniforms: UniformsUtils.merge([UniformsLib.common, UniformsLib.fog, UniformsLib.line]), vertexShader: /* glsl */"\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\n\t\tuniform float lineWidth;\n\t\tuniform vec2 resolution;\n uniform float devicePixelRatio; //add\n \n \n\t\tattribute vec3 instanceStart;\n\t\tattribute vec3 instanceEnd;\n\n\t\tattribute vec3 instanceColorStart;\n\t\tattribute vec3 instanceColorEnd;\n\n\t\t#ifdef WORLD_UNITS\n\n\t\t\tvarying vec4 worldPos;\n\t\t\tvarying vec3 worldStart;\n\t\t\tvarying vec3 worldEnd;\n\n\t\t\t#ifdef USE_DASH\n\n\t\t\t\tvarying vec2 vUv;\n\n\t\t\t#endif\n\n\t\t#else\n\n\t\t\tvarying vec2 vUv;\n\n\t\t#endif\n\n\t\t#ifdef USE_DASH\n\n\t\t\tuniform float dashScale;\n\t\t\tattribute float instanceDistanceStart;\n\t\t\tattribute float instanceDistanceEnd;\n\t\t\tvarying float vLineDistance;\n\n\t\t#endif\n\n\t\tvoid trimSegment( const in vec4 start, inout vec4 end ) {\n\n\t\t\t// trim end segment so it terminates between the camera plane and the near plane\n\n\t\t\t// conservative estimate of the near plane\n\t\t\tfloat a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column\n\t\t\tfloat b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column\n\t\t\tfloat nearEstimate = - 0.5 * b / a;\n\n\t\t\tfloat alpha = ( nearEstimate - start.z ) / ( end.z - start.z );\n\n\t\t\tend.xyz = mix( start.xyz, end.xyz, alpha );\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\t#ifdef USE_COLOR\n\n\t\t\t\tvColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;\n\n\t\t\t#endif\n\n\t\t\t#ifdef USE_DASH\n\n\t\t\t\tvLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;\n\t\t\t\tvUv = uv;\n\n\t\t\t#endif\n\n\t\t\tfloat aspect = resolution.x / resolution.y;\n\n\t\t\t// camera space\n\t\t\tvec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );\n\t\t\tvec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );\n\n\t\t\t#ifdef WORLD_UNITS\n\n\t\t\t\tworldStart = start.xyz;\n\t\t\t\tworldEnd = end.xyz;\n\n\t\t\t#else\n\n\t\t\t\tvUv = uv;\n\n\t\t\t#endif\n\n\t\t\t// special case for perspective projection, and segments that terminate either in, or behind, the camera plane\n\t\t\t// clearly the gpu firmware has a way of addressing this issue when projecting into ndc space\n\t\t\t// but we need to perform ndc-space calculations in the shader, so we must address this issue directly\n\t\t\t// perhaps there is a more elegant solution -- WestLangley\n\n\t\t\tbool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column\n\n\t\t\tif ( perspective ) {\n\n\t\t\t\tif ( start.z < 0.0 && end.z >= 0.0 ) {\n\n\t\t\t\t\ttrimSegment( start, end );\n\n\t\t\t\t} else if ( end.z < 0.0 && start.z >= 0.0 ) {\n\n\t\t\t\t\ttrimSegment( end, start );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// clip space\n\t\t\tvec4 clipStart = projectionMatrix * start;\n\t\t\tvec4 clipEnd = projectionMatrix * end;\n\n\t\t\t// ndc space\n\t\t\tvec3 ndcStart = clipStart.xyz / clipStart.w;\n\t\t\tvec3 ndcEnd = clipEnd.xyz / clipEnd.w;\n\n\t\t\t// direction\n\t\t\tvec2 dir = ndcEnd.xy - ndcStart.xy;\n\n\t\t\t// account for clip-space aspect ratio\n\t\t\tdir.x *= aspect;\n\t\t\tdir = normalize( dir );\n\n\t\t\t#ifdef WORLD_UNITS\n\n\t\t\t\t// get the offset direction as perpendicular to the view vector\n\t\t\t\tvec3 worldDir = normalize( end.xyz - start.xyz );\n\t\t\t\tvec3 offset;\n\t\t\t\tif ( position.y < 0.5 ) {\n\n\t\t\t\t\toffset = normalize( cross( start.xyz, worldDir ) );\n\n\t\t\t\t} else {\n\n\t\t\t\t\toffset = normalize( cross( end.xyz, worldDir ) );\n\n\t\t\t\t}\n\n\t\t\t\t// sign flip\n\t\t\t\tif ( position.x < 0.0 ) offset *= - 1.0;\n\n\t\t\t\tfloat forwardOffset = dot( worldDir, vec3( 0.0, 0.0, 1.0 ) );\n\n\t\t\t\t// don't extend the line if we're rendering dashes because we\n\t\t\t\t// won't be rendering the endcaps\n\t\t\t\t#ifndef USE_DASH\n\n\t\t\t\t\t// extend the line bounds to encompass endcaps\n\t\t\t\t\tstart.xyz += - worldDir * lineWidth * 0.5;\n\t\t\t\t\tend.xyz += worldDir * lineWidth * 0.5;\n\n\t\t\t\t\t// shift the position of the quad so it hugs the forward edge of the line\n\t\t\t\t\toffset.xy -= dir * forwardOffset;\n\t\t\t\t\toffset.z += 0.5;\n\n\t\t\t\t#endif\n\n\t\t\t\t// endcaps\n\t\t\t\tif ( position.y > 1.0 || position.y < 0.0 ) {\n\n\t\t\t\t\toffset.xy += dir * 2.0 * forwardOffset;\n\n\t\t\t\t}\n\n\t\t\t\t// adjust for lineWidth\n\t\t\t\toffset *= lineWidth * 0.5;\n\n\t\t\t\t// set the world position\n\t\t\t\tworldPos = ( position.y < 0.5 ) ? start : end;\n\t\t\t\tworldPos.xyz += offset;\n\n\t\t\t\t// project the worldpos\n\t\t\t\tvec4 clip = projectionMatrix * worldPos;\n\n\t\t\t\t// shift the depth of the projected points so the line\n\t\t\t\t// segments overlap neatly\n\t\t\t\tvec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;\n\t\t\t\tclip.z = clipPose.z * clip.w;\n\n\t\t\t#else\n\n\t\t\t\tvec2 offset = vec2( dir.y, - dir.x );\n\t\t\t\t// undo aspect ratio adjustment\n\t\t\t\tdir.x /= aspect;\n\t\t\t\toffset.x /= aspect;\n\n\t\t\t\t// sign flip\n\t\t\t\tif ( position.x < 0.0 ) offset *= - 1.0;\n\n\t\t\t\t// endcaps\n\t\t\t\tif ( position.y < 0.0 ) {\n\n\t\t\t\t\toffset += - dir;\n\n\t\t\t\t} else if ( position.y > 1.0 ) {\n\n\t\t\t\t\toffset += dir;\n\n\t\t\t\t}\n\n\t\t\t\t// adjust for lineWidth\n\t\t\t\toffset *= lineWidth;\n\n\t\t\t\t// adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...\n\t\t\t\toffset /= resolution.y; //* devicePixelRatio;\n\n\t\t\t\t// select end\n\t\t\t\tvec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;\n\n\t\t\t\t// back to clip space\n\t\t\t\toffset *= clip.w;\n\n\t\t\t\tclip.xy += offset;\n\n\t\t\t#endif\n\n\t\t\tgl_Position = clip;\n\n\t\t\tvec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation\n\n\t\t\t#include \n\t\t\t#include \n\t\t\t#include \n\n\t\t}\n\t\t", fragmentShader: /* glsl */"\n\t\tuniform vec3 diffuse;\n\t\tuniform float opacity;\n\t\tuniform float lineWidth;\n uniform bool uUseOrthographicCamera; \n\t\t#ifdef USE_DASH\n\n\t\t\tuniform float dashOffset;\n\t\t\tuniform float dashSize;\n\t\t\tuniform float gapSize; \n\t\t#endif\n \n //\u52A0\n #if defined(GL_EXT_frag_depth) && defined(useDepth) \n uniform sampler2D depthTexture;\n uniform float nearPlane;\n uniform float farPlane; \n uniform vec2 resolution;\n uniform vec2 viewportOffset;\n uniform vec3 backColor;\n uniform float occlusionDistance;\n uniform float clipDistance;\n uniform float maxClipFactor;\n uniform float maxOcclusionFactor;\n #endif\n\n\n\n\t\tvarying float vLineDistance;\n\n\t\t#ifdef WORLD_UNITS\n\n\t\t\tvarying vec4 worldPos;\n\t\t\tvarying vec3 worldStart;\n\t\t\tvarying vec3 worldEnd;\n\n\t\t\t#ifdef USE_DASH\n\n\t\t\t\tvarying vec2 vUv;\n\n\t\t\t#endif\n\n\t\t#else\n\n\t\t\tvarying vec2 vUv;\n\n\t\t#endif\n\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\n\n #if defined(GL_EXT_frag_depth) && defined(useDepth) \n float convertToLinear(float zValue)\n {\n //if(uUseOrthographicCamera){\n // return zValue*(farPlane-nearPlane)+nearPlane;\n //}else{ \n float z = zValue * 2.0 - 1.0;\n return (2.0 * nearPlane * farPlane) / (farPlane + nearPlane - z * (farPlane - nearPlane));\n //} \n }\n #endif\n\n\n\n\t\tvec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {\n\n\t\t\tfloat mua;\n\t\t\tfloat mub;\n\n\t\t\tvec3 p13 = p1 - p3;\n\t\t\tvec3 p43 = p4 - p3;\n\n\t\t\tvec3 p21 = p2 - p1;\n\n\t\t\tfloat d1343 = dot( p13, p43 );\n\t\t\tfloat d4321 = dot( p43, p21 );\n\t\t\tfloat d1321 = dot( p13, p21 );\n\t\t\tfloat d4343 = dot( p43, p43 );\n\t\t\tfloat d2121 = dot( p21, p21 );\n\n\t\t\tfloat denom = d2121 * d4343 - d4321 * d4321;\n\n\t\t\tfloat numer = d1343 * d4321 - d1321 * d4343;\n\n\t\t\tmua = numer / denom;\n\t\t\tmua = clamp( mua, 0.0, 1.0 );\n\t\t\tmub = ( d1343 + d4321 * ( mua ) ) / d4343;\n\t\t\tmub = clamp( mub, 0.0, 1.0 );\n\n\t\t\treturn vec2( mua, mub );\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\t#include \n\n\t\t\t/*#ifdef USE_DASH\n\n\t\t\t\tif ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps\n\n\t\t\t\tif ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX\n\n\t\t\t#endif*/\n \n\t\t\t#ifdef USE_DASH\n\n\t\t\t\tif ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps\n \n \n bool unvisible = mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize;\n //\u52A0\n #ifdef DASH_with_depth\n \n #else \n if (unvisible) discard; // todo - FIX\n #endif\n\t\t\t#endif\n \n\n\t\t\tfloat alpha = opacity;\n\n\t\t\t#ifdef WORLD_UNITS\n\n\t\t\t\t// Find the closest points on the view ray and the line segment\n\t\t\t\tvec3 rayEnd = normalize( worldPos.xyz ) * 1e5;\n\t\t\t\tvec3 lineDir = worldEnd - worldStart;\n\t\t\t\tvec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );\n\n\t\t\t\tvec3 p1 = worldStart + lineDir * params.x;\n\t\t\t\tvec3 p2 = rayEnd * params.y;\n\t\t\t\tvec3 delta = p1 - p2;\n\t\t\t\tfloat len = length( delta );\n\t\t\t\tfloat norm = len / lineWidth;\n\n\t\t\t\t#ifndef USE_DASH\n\n\t\t\t\t\t#ifdef USE_ALPHA_TO_COVERAGE\n\n\t\t\t\t\t\tfloat dnorm = fwidth( norm );\n\t\t\t\t\t\talpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );\n\n\t\t\t\t\t#else\n\n\t\t\t\t\t\tif ( norm > 0.5 ) {\n\n\t\t\t\t\t\t\tdiscard;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t#endif\n\n\t\t\t\t#endif\n\n\t\t\t#else\n\n\t\t\t\t#ifdef USE_ALPHA_TO_COVERAGE\n\n\t\t\t\t\t// artifacts appear on some hardware if a derivative is taken within a conditional\n\t\t\t\t\tfloat a = vUv.x;\n\t\t\t\t\tfloat b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;\n\t\t\t\t\tfloat len2 = a * a + b * b;\n\t\t\t\t\tfloat dlen = fwidth( len2 );\n\n\t\t\t\t\tif ( abs( vUv.y ) > 1.0 ) {\n\n\t\t\t\t\t\talpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );\n\n\t\t\t\t\t}\n\n\t\t\t\t#else\n\n\t\t\t\t\tif ( abs( vUv.y ) > 1.0 ) {\n\n\t\t\t\t\t\tfloat a = vUv.x;\n\t\t\t\t\t\tfloat b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;\n\t\t\t\t\t\tfloat len2 = a * a + b * b;\n\n\t\t\t\t\t\tif ( len2 > 1.0 ) discard;\n\n\t\t\t\t\t}\n\n\t\t\t\t#endif\n\n\t\t\t#endif\n\n\t\t\tvec4 diffuseColor = vec4( diffuse, alpha );\n\n\n //\u52A0\n #if defined(GL_EXT_frag_depth) && defined(useDepth) \n \n float mixFactor = 0.0;\n float clipFactor = 0.0;\n\n float fragDepth = convertToLinear(gl_FragCoord.z);\n //gl_FragCoord\u5927\u5C0F\u4E3A viewport client\u5927\u5C0F \n vec2 depthTxtCoords = vec2(gl_FragCoord.x - viewportOffset.x, gl_FragCoord.y - viewportOffset.y) / resolution;\n\n float textureDepth = convertToLinear(texture2D(depthTexture, depthTxtCoords).r);\n\n float delta = fragDepth - textureDepth;\n\n if (delta > 0.0)\n {\n \n mixFactor = clamp(delta / occlusionDistance, 0.0, maxOcclusionFactor);\n clipFactor = clamp(delta / clipDistance, 0.0, maxClipFactor);\n }\n \n if (clipFactor == 1.0)\n {\n discard;\n }\n \n vec4 backColor_ = vec4(backColor, opacity); //vec4(0.8,0.8,0.8, 0.8*opacity);\n \n #ifdef DASH_with_depth \n // \u53EA\u5728\u88AB\u906E\u4F4F\u7684\u90E8\u5206\u663E\u793A\u865A\u7EBF, \u6240\u4EE5\u82E5\u540C\u65F6\u662F\u865A\u7EBF\u4E0D\u53EF\u89C1\u90E8\u5206\u548C\u88AB\u906E\u4F4F\u65F6\uFF0C a\u4E3A0\n if(unvisible) backColor_.a = 0.0;\n #endif \n \n //vec4 diffuseColor = vec4(mix(diffuse, backColor_, mixFactor), opacity*(1.0 - clipFactor));\n \n \n \n diffuseColor = mix(diffuseColor, backColor_ , mixFactor); \n \n \n diffuseColor.a *= (1.0 - clipFactor); \n \n #endif\n\n\n\n\t\t\t#include \n\t\t\t#include \n\n\t\t\t//gl_FragColor = vec4( diffuseColor.rgb, alpha );\n\t\t\tgl_FragColor = vec4( diffuseColor.rgb, diffuseColor.a );\n\t\t\t#include \n\t\t\t#include \n\t\t\t#include \n\t\t\t#include \n\n\t\t}\n\t\t" }; class LineMaterial extends ShaderMaterial { constructor(parameters) { var { vs, fs } = Potree.Common.changeShaderToWebgl2(ShaderLib['line'].vertexShader, ShaderLib['line'].fragmentShader, 'ShaderMaterial'); super({ type: 'LineMaterial', uniforms: UniformsUtils.clone(ShaderLib['line'].uniforms), vertexShader: vs, fragmentShader: fs, clipping: true // required for clipping support }); this.isLineMaterial = true; this.lineWidth_ = 0; this.supportExtDepth = parameters.supportExtDepth; this.depthTestWhenPick = false; //pick时是否识别点云等 if (parameters.color) { this.color = new Color(parameters.color); } if (parameters.backColor) { this.uniforms.backColor.value = new Color(parameters.backColor); } if (parameters.clipDistance) { this.uniforms.clipDistance.value = parameters.clipDistance; } if (parameters.occlusionDistance) { this.uniforms.occlusionDistance.value = parameters.occlusionDistance; } if (parameters.maxClipFactor) { this.uniforms.maxClipFactor.value = parameters.maxClipFactor; } Object.defineProperties(this, { color: { enumerable: true, get: function get() { return this.uniforms.diffuse.value; }, set: function set(value) { this.uniforms.diffuse.value = value; } }, worldUnits: { enumerable: true, get: function get() { return 'WORLD_UNITS' in this.defines; }, set: function set(value) { if (value === true) { this.defines.WORLD_UNITS = ''; } else { delete this.defines.WORLD_UNITS; } } }, lineWidth: { enumerable: true, get: function get() { return this.lineWidth_; //this.uniforms.lineWidth.value; }, set: function set(value) { this.uniforms.lineWidth.value = value * window.devicePixelRatio; this.lineWidth_ = value; } }, dashed: { enumerable: true, get: function get() { return Boolean('USE_DASH' in this.defines); }, set(value) { if (Boolean(value) !== Boolean('USE_DASH' in this.defines)) { this.needsUpdate = true; } if (value === true) { this.defines.USE_DASH = ''; } else { delete this.defines.USE_DASH; } } }, dashScale: { enumerable: true, get: function get() { return this.uniforms.dashScale.value; }, set: function set(value) { this.uniforms.dashScale.value = value; } }, dashSize: { enumerable: true, get: function get() { return this.uniforms.dashSize.value; }, set: function set(value) { this.uniforms.dashSize.value = value; } }, dashOffset: { enumerable: true, get: function get() { return this.uniforms.dashOffset.value; }, set: function set(value) { this.uniforms.dashOffset.value = value; } }, gapSize: { enumerable: true, get: function get() { return this.uniforms.gapSize.value; }, set: function set(value) { this.uniforms.gapSize.value = value; } }, opacity: { enumerable: true, get: function get() { return this.uniforms.opacity.value; }, set: function set(value) { this.uniforms.opacity.value = value; } }, resolution: { enumerable: true, get: function get() { return this.uniforms.resolution.value; }, set: function set(value) { this.uniforms.resolution.value.copy(value); } }, alphaToCoverage: { enumerable: true, get: function get() { return Boolean('USE_ALPHA_TO_COVERAGE' in this.defines); }, set: function set(value) { if (Boolean(value) !== Boolean('USE_ALPHA_TO_COVERAGE' in this.defines)) { this.needsUpdate = true; } if (value === true) { this.defines.USE_ALPHA_TO_COVERAGE = ''; this.extensions.derivatives = true; } else { delete this.defines.USE_ALPHA_TO_COVERAGE; this.extensions.derivatives = false; } } }, dashWithDepth: { //add enumerable: true, get: function get() { return 'DASH_with_depth' in this.defines; }, set: function set(value) { value = value && !!this.supportExtDepth; if (value != this.dashWithDepth) { if (value) { this.defines.DASH_with_depth = ''; } else { delete this.defines.DASH_with_depth; } this.needsUpdate = true; } } } }); this.events = { setSize: e => { //如果出现横条状的异常,往往是viewportOffset出错 //地图不需要 var viewport = e.viewport; //console.log(viewport.name, viewport.resolution2) this.uniforms.resolution.value.copy(viewport.resolution2); this.uniforms.devicePixelRatio.value = window.devicePixelRatio; this.lineWidth = this.lineWidth_; //update if (!this.realUseDepth || !e.viewport) return; var viewportOffset = viewport.offset || new THREE.Vector2(); this.uniforms.viewportOffset.value.copy(viewportOffset); }, render: e => { //before render 如果有大于两个viewport的话,不同viewport用不同的depthTex this.useDepth && this.updateDepthParams(e); var viewport = e.viewport || viewer.mainViewport; if (viewport != this.lastViewport) { //当mapViewer要渲染测量线后,就需要变viewport this.events.setSize({ viewport }); } this.lastViewport = viewport; } }; this.setValues(parameters); var viewport = viewer.mainViewport; this.events.setSize({ viewport }); viewer.addEventListener('resize', this.events.setSize); viewer.addEventListener("render.begin", this.events.render); } get useDepth() { return this.useDepth_; } set useDepth(value) { value = value && this.supportExtDepth; //如果不支持 EXT_DEPTH 的话会失效 if (this.useDepth_ != value) { this.setRealDepth(value); this.useDepth_ = value; } } setRealDepth(useDepth, viewport) { //确实使用到depthTex if (this.realUseDepth != useDepth) { if (useDepth) { this.defines.useDepth = ''; } else { delete this.defines.useDepth; } this.realUseDepth = useDepth; if (this.autoDepthTest) this.depthWrite = this.depthTest = !useDepth; //如果useDepth = false,使用原始的depthTest this.needsUpdate = true; if (!viewport) viewport = viewer.mainViewport; //暂时这么设置 useDepth && this.events.setSize({ viewport }); } } updateDepthParams() { var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var viewport = e.viewport || viewer.mainViewport; var camera = viewport.camera; var hasDepth = this.useDepth && camera.isPerspectiveCamera && (Potree.settings.pointEnableRT || Potree.settings.displayMode == 'showPanos' || viewer.useEDL); this.setRealDepth(hasDepth, viewport); if (hasDepth) { this.uniforms.depthTexture.value = viewer.getPRenderer().getRtEDL(viewport).depthTexture; //其实只赋值一次就行 this.uniforms.nearPlane.value = camera.near; this.uniforms.farPlane.value = camera.far; } //this.uniforms.uUseOrthographicCamera.value = !camera.isPerspectiveCamera } } var _start$2 = new Vector3(); var _end$2 = new Vector3(); var _start4 = new Vector4(); var _end4 = new Vector4(); var _ssOrigin = new Vector4(); var _ssOrigin3 = new Vector3(); var _mvMatrix = new Matrix4(); var _line = new Line3(); var _closestPoint = new Vector3(); var _box$5 = new Box3(); var _sphere$4 = new Sphere(); var _clipToWorldVector = new Vector4(); var _ray$3, _instanceStart, _instanceEnd, _lineWidth; // Returns the margin required to expand by in world space given the distance from the camera, // line width, resolution, and camera projection function getWorldSpaceHalfWidth(camera, distance, resolution) { // transform into clip space, adjust the x and y values by the pixel width offset, then // transform back into world space to get world offset. Note clip space is [-1, 1] so full // width does not need to be halved. _clipToWorldVector.set(0, 0, -distance, 1.0).applyMatrix4(camera.projectionMatrix); _clipToWorldVector.multiplyScalar(1.0 / _clipToWorldVector.w); _clipToWorldVector.x = _lineWidth / resolution.width; _clipToWorldVector.y = _lineWidth / resolution.height; _clipToWorldVector.applyMatrix4(camera.projectionMatrixInverse); _clipToWorldVector.multiplyScalar(1.0 / _clipToWorldVector.w); return Math.abs(Math.max(_clipToWorldVector.x, _clipToWorldVector.y)); } function raycastWorldUnits(lineSegments, intersects) { for (var i = 0, l = _instanceStart.count; i < l; i++) { _line.start.fromBufferAttribute(_instanceStart, i); _line.end.fromBufferAttribute(_instanceEnd, i); var pointOnLine = new Vector3(); var point = new Vector3(); _ray$3.distanceSqToSegment(_line.start, _line.end, point, pointOnLine); var isInside = point.distanceTo(pointOnLine) < _lineWidth * 0.5; if (isInside) { intersects.push({ point, pointOnLine, distance: _ray$3.origin.distanceTo(point), object: lineSegments, face: null, faceIndex: i, uv: null, uv2: null }); } } } function raycastScreenSpace(lineSegments, camera, intersects) { var projectionMatrix = camera.projectionMatrix; var material = lineSegments.material; var resolution = material.resolution; var matrixWorld = lineSegments.matrixWorld; var geometry = lineSegments.geometry; var instanceStart = geometry.attributes.instanceStart; var instanceEnd = geometry.attributes.instanceEnd; var near = -camera.near; // // pick a point 1 unit out along the ray to avoid the ray origin // sitting at the camera origin which will cause "w" to be 0 when // applying the projection matrix. _ray$3.at(1, _ssOrigin); // ndc space [ - 1.0, 1.0 ] _ssOrigin.w = 1; _ssOrigin.applyMatrix4(camera.matrixWorldInverse); _ssOrigin.applyMatrix4(projectionMatrix); _ssOrigin.multiplyScalar(1 / _ssOrigin.w); // screen space _ssOrigin.x *= resolution.x / 2; _ssOrigin.y *= resolution.y / 2; _ssOrigin.z = 0; _ssOrigin3.copy(_ssOrigin); _mvMatrix.multiplyMatrices(camera.matrixWorldInverse, matrixWorld); for (var i = 0, l = instanceStart.count; i < l; i++) { _start4.fromBufferAttribute(instanceStart, i); _end4.fromBufferAttribute(instanceEnd, i); _start4.w = 1; _end4.w = 1; // camera space _start4.applyMatrix4(_mvMatrix); _end4.applyMatrix4(_mvMatrix); // skip the segment if it's entirely behind the camera var isBehindCameraNear = _start4.z > near && _end4.z > near; if (isBehindCameraNear) { continue; } // trim the segment if it extends behind camera near if (_start4.z > near) { var deltaDist = _start4.z - _end4.z; var t = (_start4.z - near) / deltaDist; _start4.lerp(_end4, t); } else if (_end4.z > near) { var _deltaDist = _end4.z - _start4.z; var _t = (_end4.z - near) / _deltaDist; _end4.lerp(_start4, _t); } // clip space _start4.applyMatrix4(projectionMatrix); _end4.applyMatrix4(projectionMatrix); // ndc space [ - 1.0, 1.0 ] _start4.multiplyScalar(1 / _start4.w); _end4.multiplyScalar(1 / _end4.w); // screen space _start4.x *= resolution.x / 2; _start4.y *= resolution.y / 2; _end4.x *= resolution.x / 2; _end4.y *= resolution.y / 2; // create 2d segment _line.start.copy(_start4); _line.start.z = 0; _line.end.copy(_end4); _line.end.z = 0; // get closest point on ray to segment var param = _line.closestPointToPointParameter(_ssOrigin3, true); _line.at(param, _closestPoint); // check if the intersection point is within clip space var zPos = MathUtils.lerp(_start4.z, _end4.z, param); var isInClipSpace = zPos >= -1 && zPos <= 1; var isInside = _ssOrigin3.distanceTo(_closestPoint) < _lineWidth * 0.5; if (isInClipSpace && isInside) { _line.start.fromBufferAttribute(instanceStart, i); _line.end.fromBufferAttribute(instanceEnd, i); _line.start.applyMatrix4(matrixWorld); _line.end.applyMatrix4(matrixWorld); var pointOnLine = new Vector3(); var point = new Vector3(); _ray$3.distanceSqToSegment(_line.start, _line.end, point, pointOnLine); intersects.push({ point: point, pointOnLine: pointOnLine, distance: _ray$3.origin.distanceTo(point), object: lineSegments, face: null, faceIndex: i, uv: null, uv2: null }); } } } class LineSegments2 extends Mesh { constructor() { var geometry = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new LineSegmentsGeometry(); var material = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new LineMaterial({ color: Math.random() * 0xffffff }); super(geometry, material); this.isLineSegments2 = true; this.type = 'LineSegments2'; } // for backwards-compatibility, but could be a method of LineSegmentsGeometry... computeLineDistances() { var geometry = this.geometry; var instanceStart = geometry.attributes.instanceStart; var instanceEnd = geometry.attributes.instanceEnd; var lineDistances = new Float32Array(2 * instanceStart.count); for (var i = 0, j = 0, l = instanceStart.count; i < l; i++, j += 2) { _start$2.fromBufferAttribute(instanceStart, i); _end$2.fromBufferAttribute(instanceEnd, i); lineDistances[j] = j === 0 ? 0 : lineDistances[j - 1]; lineDistances[j + 1] = lineDistances[j] + _start$2.distanceTo(_end$2); } var instanceDistanceBuffer = new InstancedInterleavedBuffer(lineDistances, 2, 1); // d0, d1 geometry.setAttribute('instanceDistanceStart', new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 0)); // d0 geometry.setAttribute('instanceDistanceEnd', new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 1)); // d1 return this; } raycast(raycaster, intersects) { var worldUnits = this.material.worldUnits; var camera = raycaster.camera; if (camera === null && !worldUnits) { console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.'); } var threshold = raycaster.params.Line2 !== undefined ? raycaster.params.Line2.threshold || 0 : 0; _ray$3 = raycaster.ray; var matrixWorld = this.matrixWorld; var geometry = this.geometry; var material = this.material; _lineWidth = material.lineWidth + threshold; _instanceStart = geometry.attributes.instanceStart; _instanceEnd = geometry.attributes.instanceEnd; // check if we intersect the sphere bounds if (geometry.boundingSphere === null) { geometry.computeBoundingSphere(); } _sphere$4.copy(geometry.boundingSphere).applyMatrix4(matrixWorld); // increase the sphere bounds by the worst case line screen space width var sphereMargin; if (worldUnits) { sphereMargin = _lineWidth * 0.5; } else { var distanceToSphere = Math.max(camera.near, _sphere$4.distanceToPoint(_ray$3.origin)); sphereMargin = getWorldSpaceHalfWidth(camera, distanceToSphere, material.resolution); } _sphere$4.radius += sphereMargin; if (_ray$3.intersectsSphere(_sphere$4) === false) { return; } // check if we intersect the box bounds if (geometry.boundingBox === null) { geometry.computeBoundingBox(); } _box$5.copy(geometry.boundingBox).applyMatrix4(matrixWorld); // increase the box bounds by the worst case line width var boxMargin; if (worldUnits) { boxMargin = _lineWidth * 0.5; } else { var distanceToBox = Math.max(camera.near, _box$5.distanceToPoint(_ray$3.origin)); boxMargin = getWorldSpaceHalfWidth(camera, distanceToBox, material.resolution); } _box$5.expandByScalar(boxMargin); if (_ray$3.intersectsBox(_box$5) === false) { return; } if (worldUnits) { raycastWorldUnits(this, intersects); } else { raycastScreenSpace(this, camera, intersects); } } } class LineGeometry extends LineSegmentsGeometry { constructor() { super(); this.isLineGeometry = true; this.type = 'LineGeometry'; } setPositions(array) { //见potree.shim.js // converts [ x1, y1, z1, x2, y2, z2, ... ] to pairs format var length = array.length - 3; var points = new Float32Array(2 * length); for (var i = 0; i < length; i += 3) { points[2 * i] = array[i]; points[2 * i + 1] = array[i + 1]; points[2 * i + 2] = array[i + 2]; points[2 * i + 3] = array[i + 3]; points[2 * i + 4] = array[i + 4]; points[2 * i + 5] = array[i + 5]; } super.setPositions(points); return this; } setColors(array) { // converts [ r1, g1, b1, r2, g2, b2, ... ] to pairs format var length = array.length - 3; var colors = new Float32Array(2 * length); for (var i = 0; i < length; i += 3) { colors[2 * i] = array[i]; colors[2 * i + 1] = array[i + 1]; colors[2 * i + 2] = array[i + 2]; colors[2 * i + 3] = array[i + 3]; colors[2 * i + 4] = array[i + 4]; colors[2 * i + 5] = array[i + 5]; } super.setColors(colors); return this; } fromLine(line) { var geometry = line.geometry; this.setPositions(geometry.attributes.position.array); // assumes non-indexed // set colors, maybe return this; } } class Line2 extends LineSegments2 { constructor() { var geometry = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new LineGeometry(); var material = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new LineMaterial({ color: Math.random() * 0xffffff }); super(geometry, material); this.isLine2 = true; this.type = 'Line2'; } } //old function createHeightLine() { var lineGeometry = new LineGeometry(); lineGeometry.setPositions([0, 0, 0, 0, 0, 0]); var lineMaterial = new LineMaterial({ color: 0x00ff00, dashSize: 5, gapSize: 2, linewidth: 2, resolution: new Vector2(1000, 1000) }); lineMaterial.depthTest = false; var heightEdge = new Line2(lineGeometry, lineMaterial); heightEdge.visible = false; //this.add(this.heightEdge); return heightEdge; } function createHeightLabel() { var heightLabel = new TextSprite$1(''); heightLabel.setTextColor({ r: 140, g: 250, b: 140, a: 1.0 }); heightLabel.setBorderColor({ r: 0, g: 0, b: 0, a: 1.0 }); heightLabel.setBackgroundColor({ r: 0, g: 0, b: 0, a: 1.0 }); heightLabel.fontsize = 16; heightLabel.material.depthTest = false; heightLabel.material.opacity = 1; heightLabel.visible = false; return heightLabel; } function createAreaLabel() { var areaLabel = new TextSprite$1(''); areaLabel.setTextColor({ r: 140, g: 250, b: 140, a: 1.0 }); areaLabel.setBorderColor({ r: 0, g: 0, b: 0, a: 1.0 }); areaLabel.setBackgroundColor({ r: 0, g: 0, b: 0, a: 1.0 }); areaLabel.fontsize = 16; areaLabel.material.depthTest = false; areaLabel.material.opacity = 1; areaLabel.visible = false; return areaLabel; } function createCircleRadiusLabel() { var circleRadiusLabel = new TextSprite$1(""); circleRadiusLabel.setTextColor({ r: 140, g: 250, b: 140, a: 1.0 }); circleRadiusLabel.setBorderColor({ r: 0, g: 0, b: 0, a: 1.0 }); circleRadiusLabel.setBackgroundColor({ r: 0, g: 0, b: 0, a: 1.0 }); circleRadiusLabel.fontsize = 16; circleRadiusLabel.material.depthTest = false; circleRadiusLabel.material.opacity = 1; circleRadiusLabel.visible = false; return circleRadiusLabel; } function createCircleRadiusLine() { var lineGeometry = new LineGeometry(); lineGeometry.setPositions([0, 0, 0, 0, 0, 0]); var lineMaterial = new LineMaterial({ color: 0xff0000, linewidth: 2, resolution: new Vector2(1000, 1000), gapSize: 1, dashed: true }); lineMaterial.depthTest = false; var circleRadiusLine = new Line2(lineGeometry, lineMaterial); circleRadiusLine.visible = false; return circleRadiusLine; } function createCircleLine() { var coordinates = []; var n = 128; for (var i = 0; i <= n; i++) { var u0 = 2 * Math.PI * (i / n); var u1 = 2 * Math.PI * (i + 1) / n; var p0 = new Vector3(Math.cos(u0), Math.sin(u0), 0); var p1 = new Vector3(Math.cos(u1), Math.sin(u1), 0); coordinates.push(...p0.toArray(), ...p1.toArray()); } var geometry = new LineGeometry(); geometry.setPositions(coordinates); var material = new LineMaterial({ color: 0xff0000, dashSize: 5, gapSize: 2, linewidth: 2, resolution: new Vector2(1000, 1000) }); material.depthTest = false; var circleLine = new Line2(geometry, material); circleLine.visible = false; circleLine.computeLineDistances(); return circleLine; } function createCircleCenter() { var sg = new SphereGeometry(1, 32, 32); var sm = new MeshNormalMaterial(); var circleCenter = new Mesh(sg, sm); circleCenter.visible = false; return circleCenter; } function createLine() { var geometry = new LineGeometry(); geometry.setPositions([0, 0, 0, 0, 0, 0]); var material = new LineMaterial({ color: 0xff0000, linewidth: 2, resolution: new Vector2(1000, 1000), gapSize: 1, dashed: true }); material.depthTest = false; var line = new Line2(geometry, material); return line; } function createCircle() { var coordinates = []; var n = 128; for (var i = 0; i <= n; i++) { var u0 = 2 * Math.PI * (i / n); var u1 = 2 * Math.PI * (i + 1) / n; var p0 = new Vector3(Math.cos(u0), Math.sin(u0), 0); var p1 = new Vector3(Math.cos(u1), Math.sin(u1), 0); coordinates.push(...p0.toArray(), ...p1.toArray()); } var geometry = new LineGeometry(); geometry.setPositions(coordinates); var material = new LineMaterial({ color: 0xff0000, dashSize: 5, gapSize: 2, linewidth: 2, resolution: new Vector2(1000, 1000) }); material.depthTest = false; var line = new Line2(geometry, material); line.computeLineDistances(); return line; } function createAzimuth() { var azimuth = { label: null, center: null, target: null, north: null, centerToNorth: null, centerToTarget: null, centerToTargetground: null, targetgroundToTarget: null, circle: null, node: null }; var sg = new SphereGeometry(1, 32, 32); var sm = new MeshNormalMaterial(); { var label = new TextSprite$1(""); label.setTextColor({ r: 140, g: 250, b: 140, a: 1.0 }); label.setBorderColor({ r: 0, g: 0, b: 0, a: 1.0 }); label.setBackgroundColor({ r: 0, g: 0, b: 0, a: 1.0 }); label.fontsize = 16; label.material.depthTest = false; label.material.opacity = 1; azimuth.label = label; } azimuth.center = new Mesh(sg, sm); azimuth.target = new Mesh(sg, sm); azimuth.north = new Mesh(sg, sm); azimuth.centerToNorth = createLine(); azimuth.centerToTarget = createLine(); azimuth.centerToTargetground = createLine(); azimuth.targetgroundToTarget = createLine(); azimuth.circle = createCircle(); azimuth.node = new Object3D(); azimuth.node.add(azimuth.centerToNorth, azimuth.centerToTarget, azimuth.centerToTargetground, azimuth.targetgroundToTarget, azimuth.circle, azimuth.label, azimuth.center, azimuth.target, azimuth.north); return azimuth; } class Measure extends Object3D { constructor() { super(); this.constructor.counter = this.constructor.counter === undefined ? 0 : this.constructor.counter + 1; this.name = 'Measure_' + this.constructor.counter; this.points = []; this._showDistances = true; this._showCoordinates = false; this._showArea = false; this._closed = true; this._showAngles = false; this._showCircle = false; this._showHeight = false; this._showEdges = true; this._showAzimuth = false; this.maxMarkers = Number.MAX_SAFE_INTEGER; this.sphereGeometry = new SphereGeometry(0.4, 10, 10); this.color = new Color(0xff0000); this.spheres = []; this.edges = []; this.sphereLabels = []; this.edgeLabels = []; this.angleLabels = []; this.coordinateLabels = []; this.heightEdge = createHeightLine(); this.heightLabel = createHeightLabel(); this.areaLabel = createAreaLabel(); this.circleRadiusLabel = createCircleRadiusLabel(); this.circleRadiusLine = createCircleRadiusLine(); this.circleLine = createCircleLine(); this.circleCenter = createCircleCenter(); this.azimuth = createAzimuth(); this.add(this.heightEdge); this.add(this.heightLabel); this.add(this.areaLabel); this.add(this.circleRadiusLabel); this.add(this.circleRadiusLine); this.add(this.circleLine); this.add(this.circleCenter); this.add(this.azimuth.node); } createSphereMaterial() { var sphereMaterial = new MeshLambertMaterial({ //shading: THREE.SmoothShading, color: this.color, depthTest: false, depthWrite: false }); return sphereMaterial; } addMarker(point) { if (point.x != null) { point = { position: point }; } else if (point instanceof Array) { point = { position: new Vector3(...point) }; } this.points.push(point); // sphere var sphere = new Mesh(this.sphereGeometry, this.createSphereMaterial()); this.add(sphere); this.spheres.push(sphere); { // edges var lineGeometry = new LineGeometry(); lineGeometry.setPositions([0, 0, 0, 0, 0, 0]); var lineMaterial = new LineMaterial({ color: 0xff0000, linewidth: 2, resolution: new Vector2(1000, 1000) }); lineMaterial.depthTest = false; var edge = new Line2(lineGeometry, lineMaterial); edge.visible = true; this.add(edge); this.edges.push(edge); } { // edge labels var edgeLabel = new TextSprite$1(); edgeLabel.setBorderColor({ r: 0, g: 0, b: 0, a: 1.0 }); edgeLabel.setBackgroundColor({ r: 0, g: 0, b: 0, a: 1.0 }); edgeLabel.material.depthTest = false; edgeLabel.visible = false; edgeLabel.fontsize = 16; this.edgeLabels.push(edgeLabel); this.add(edgeLabel); } { // angle labels var angleLabel = new TextSprite$1(); angleLabel.setBorderColor({ r: 0, g: 0, b: 0, a: 1.0 }); angleLabel.setBackgroundColor({ r: 0, g: 0, b: 0, a: 1.0 }); angleLabel.fontsize = 16; angleLabel.material.depthTest = false; angleLabel.material.opacity = 1; angleLabel.visible = false; this.angleLabels.push(angleLabel); this.add(angleLabel); } { // coordinate labels var coordinateLabel = new TextSprite$1(); coordinateLabel.setBorderColor({ r: 0, g: 0, b: 0, a: 1.0 }); coordinateLabel.setBackgroundColor({ r: 0, g: 0, b: 0, a: 1.0 }); coordinateLabel.fontsize = 16; coordinateLabel.material.depthTest = false; coordinateLabel.material.opacity = 1; coordinateLabel.visible = false; this.coordinateLabels.push(coordinateLabel); this.add(coordinateLabel); } { // Event Listeners var drag = e => { var I = Utils.getMousePointCloudIntersection(e.drag.end, e.viewer.scene.getActiveCamera(), e.viewer, e.viewer.scene.pointclouds, { pickClipped: true }); if (I) { var i = this.spheres.indexOf(e.drag.object); if (i !== -1) { var _point = this.points[i]; // loop through current keys and cleanup ones that will be orphaned for (var key of Object.keys(_point)) { if (!I.point[key]) { delete _point[key]; } } for (var _key of Object.keys(I.point).filter(e => e !== 'position')) { _point[_key] = I.point[_key]; } this.setPosition(i, I.location); } } }; var drop = e => { var i = this.spheres.indexOf(e.drag.object); if (i !== -1) { this.dispatchEvent({ 'type': 'marker_dropped', 'measurement': this, 'index': i }); } }; var mouseover = e => e.object.material.emissive.setHex(0x888888); var mouseleave = e => e.object.material.emissive.setHex(0x000000); sphere.addEventListener('drag', drag); sphere.addEventListener('drop', drop); sphere.addEventListener('mouseover', mouseover); sphere.addEventListener('mouseleave', mouseleave); } var event = { type: 'marker_added', measurement: this, sphere: sphere }; this.dispatchEvent(event); this.setMarker(this.points.length - 1, point); } removeMarker(index) { this.points.splice(index, 1); this.remove(this.spheres[index]); var edgeIndex = index === 0 ? 0 : index - 1; this.remove(this.edges[edgeIndex]); this.edges.splice(edgeIndex, 1); this.remove(this.edgeLabels[edgeIndex]); this.edgeLabels.splice(edgeIndex, 1); this.coordinateLabels.splice(index, 1); this.remove(this.angleLabels[index]); this.angleLabels.splice(index, 1); this.spheres.splice(index, 1); this.update(); this.dispatchEvent({ type: 'marker_removed', measurement: this }); } setMarker(index, point) { this.points[index] = point; var event = { type: 'marker_moved', measure: this, index: index, position: point.position.clone() }; this.dispatchEvent(event); this.update(); } setPosition(index, position) { var point = this.points[index]; point.position.copy(position); var event = { type: 'marker_moved', measure: this, index: index, position: position.clone() }; this.dispatchEvent(event); this.update(); } getArea() { var area = 0; var j = this.points.length - 1; for (var i = 0; i < this.points.length; i++) { var p1 = this.points[i].position; var p2 = this.points[j].position; area += (p2.x + p1.x) * (p1.y - p2.y); j = i; } return Math.abs(area / 2); } getTotalDistance() { if (this.points.length === 0) { return 0; } var distance = 0; for (var i = 1; i < this.points.length; i++) { var prev = this.points[i - 1].position; var curr = this.points[i].position; var d = prev.distanceTo(curr); distance += d; } if (this.closed && this.points.length > 1) { var first = this.points[0].position; var last = this.points[this.points.length - 1].position; var _d = last.distanceTo(first); distance += _d; } return distance; } getAngleBetweenLines(cornerPoint, point1, point2) { var v1 = new Vector3().subVectors(point1.position, cornerPoint.position); var v2 = new Vector3().subVectors(point2.position, cornerPoint.position); // avoid the error printed by threejs if denominator is 0 var denominator = Math.sqrt(v1.lengthSq() * v2.lengthSq()); if (denominator === 0) { return 0; } else { return v1.angleTo(v2); } } getAngle(index) { if (this.points.length < 3 || index >= this.points.length) { return 0; } var previous = index === 0 ? this.points[this.points.length - 1] : this.points[index - 1]; var point = this.points[index]; var next = this.points[(index + 1) % this.points.length]; return this.getAngleBetweenLines(point, previous, next); } // updateAzimuth(){ // // if(this.points.length !== 2){ // // return; // // } // // const azimuth = this.azimuth; // // const [p0, p1] = this.points; // // const r = p0.position.distanceTo(p1.position); // } update() { if (this.points.length === 0) { return; } else if (this.points.length === 1) { var point = this.points[0]; var position = point.position; this.spheres[0].position.copy(position); { // coordinate labels var coordinateLabel = this.coordinateLabels[0]; var msg = position.toArray().map(p => Utils.addCommas(p.toFixed(2))).join(" / "); coordinateLabel.setText(msg); coordinateLabel.visible = this.showCoordinates; } return; } var lastIndex = this.points.length - 1; var centroid = new Vector3(); for (var i = 0; i <= lastIndex; i++) { var _point2 = this.points[i]; centroid.add(_point2.position); } centroid.divideScalar(this.points.length); for (var _i = 0; _i <= lastIndex; _i++) { var index = _i; var nextIndex = _i + 1 > lastIndex ? 0 : _i + 1; var previousIndex = _i === 0 ? lastIndex : _i - 1; var _point3 = this.points[index]; var nextPoint = this.points[nextIndex]; var previousPoint = this.points[previousIndex]; var sphere = this.spheres[index]; // spheres sphere.position.copy(_point3.position); sphere.material.color = this.color; { // edges var edge = this.edges[index]; edge.material.color = this.color; edge.position.copy(_point3.position); edge.geometry.setPositions([0, 0, 0, ...nextPoint.position.clone().sub(_point3.position).toArray()]); edge.geometry.verticesNeedUpdate = true; edge.geometry.computeBoundingSphere(); edge.computeLineDistances(); edge.visible = index < lastIndex || this.closed; if (!this.showEdges) { edge.visible = false; } } { // edge labels var edgeLabel = this.edgeLabels[_i]; var center = new Vector3().add(_point3.position); center.add(nextPoint.position); center = center.multiplyScalar(0.5); var distance = _point3.position.distanceTo(nextPoint.position); edgeLabel.position.copy(center); var suffix = ""; if (this.lengthUnit != null && this.lengthUnitDisplay != null) { distance = distance / this.lengthUnit.unitspermeter * this.lengthUnitDisplay.unitspermeter; //convert to meters then to the display unit suffix = this.lengthUnitDisplay.code; } var txtLength = Utils.addCommas(distance.toFixed(2)); edgeLabel.setText("".concat(txtLength, " ").concat(suffix)); edgeLabel.visible = this.showDistances && (index < lastIndex || this.closed) && this.points.length >= 2 && distance > 0; } { // angle labels var angleLabel = this.angleLabels[_i]; var angle = this.getAngleBetweenLines(_point3, previousPoint, nextPoint); var dir = nextPoint.position.clone().sub(previousPoint.position); dir.multiplyScalar(0.5); dir = previousPoint.position.clone().add(dir).sub(_point3.position).normalize(); var dist = Math.min(_point3.position.distanceTo(previousPoint.position), _point3.position.distanceTo(nextPoint.position)); dist = dist / 9; var labelPos = _point3.position.clone().add(dir.multiplyScalar(dist)); angleLabel.position.copy(labelPos); var _msg = Utils.addCommas((angle * (180.0 / Math.PI)).toFixed(1)) + '\u00B0'; angleLabel.setText(_msg); angleLabel.visible = this.showAngles && (index < lastIndex || this.closed) && this.points.length >= 3 && angle > 0; } } { // update height stuff var heightEdge = this.heightEdge; heightEdge.visible = this.showHeight; this.heightLabel.visible = this.showHeight; if (this.showHeight) { var sorted = this.points.slice().sort((a, b) => a.position.z - b.position.z); var lowPoint = sorted[0].position.clone(); var highPoint = sorted[sorted.length - 1].position.clone(); var min = lowPoint.z; var max = highPoint.z; var height = max - min; var start = new Vector3(highPoint.x, highPoint.y, min); var end = new Vector3(highPoint.x, highPoint.y, max); heightEdge.position.copy(lowPoint); heightEdge.geometry.setPositions([0, 0, 0, ...start.clone().sub(lowPoint).toArray(), ...start.clone().sub(lowPoint).toArray(), ...end.clone().sub(lowPoint).toArray()]); heightEdge.geometry.verticesNeedUpdate = true; // heightEdge.geometry.computeLineDistances(); // heightEdge.geometry.lineDistancesNeedUpdate = true; heightEdge.geometry.computeBoundingSphere(); heightEdge.computeLineDistances(); // heightEdge.material.dashSize = height / 40; // heightEdge.material.gapSize = height / 40; var heightLabelPosition = start.clone().add(end).multiplyScalar(0.5); this.heightLabel.position.copy(heightLabelPosition); var _suffix = ""; if (this.lengthUnit != null && this.lengthUnitDisplay != null) { height = height / this.lengthUnit.unitspermeter * this.lengthUnitDisplay.unitspermeter; //convert to meters then to the display unit _suffix = this.lengthUnitDisplay.code; } var txtHeight = Utils.addCommas(height.toFixed(2)); var _msg2 = "".concat(txtHeight, " ").concat(_suffix); this.heightLabel.setText(_msg2); } } { // update circle stuff var circleRadiusLabel = this.circleRadiusLabel; var circleRadiusLine = this.circleRadiusLine; var circleLine = this.circleLine; var circleCenter = this.circleCenter; var circleOkay = this.points.length === 3; circleRadiusLabel.visible = this.showCircle && circleOkay; circleRadiusLine.visible = this.showCircle && circleOkay; circleLine.visible = this.showCircle && circleOkay; circleCenter.visible = this.showCircle && circleOkay; if (this.showCircle && circleOkay) { var A = this.points[0].position; var B = this.points[1].position; var C = this.points[2].position; var AB = B.clone().sub(A); var AC = C.clone().sub(A); var N = AC.clone().cross(AB).normalize(); var _center = Potree.Utils.computeCircleCenter(A, B, C); var radius = _center.distanceTo(A); var scale = radius / 20; circleCenter.position.copy(_center); circleCenter.scale.set(scale, scale, scale); //circleRadiusLine.geometry.vertices[0].set(0, 0, 0); //circleRadiusLine.geometry.vertices[1].copy(B.clone().sub(center)); circleRadiusLine.geometry.setPositions([0, 0, 0, ...B.clone().sub(_center).toArray()]); circleRadiusLine.geometry.verticesNeedUpdate = true; circleRadiusLine.geometry.computeBoundingSphere(); circleRadiusLine.position.copy(_center); circleRadiusLine.computeLineDistances(); var target = _center.clone().add(N); circleLine.position.copy(_center); circleLine.scale.set(radius, radius, radius); circleLine.lookAt(target); circleRadiusLabel.visible = true; circleRadiusLabel.position.copy(_center.clone().add(B).multiplyScalar(0.5)); circleRadiusLabel.setText("".concat(radius.toFixed(3))); } } { // update area label this.areaLabel.position.copy(centroid); this.areaLabel.visible = this.showArea && this.points.length >= 3; var area = this.getArea(); var _suffix2 = ""; if (this.lengthUnit != null && this.lengthUnitDisplay != null) { area = area / Math.pow(this.lengthUnit.unitspermeter, 2) * Math.pow(this.lengthUnitDisplay.unitspermeter, 2); //convert to square meters then to the square display unit _suffix2 = this.lengthUnitDisplay.code; } var txtArea = Utils.addCommas(area.toFixed(1)); var _msg3 = "".concat(txtArea, " ").concat(_suffix2, "\xB2"); this.areaLabel.setText(_msg3); } // this.updateAzimuth(); } raycast(raycaster, intersects) { for (var i = 0; i < this.points.length; i++) { var sphere = this.spheres[i]; sphere.raycast(raycaster, intersects); } // recalculate distances because they are not necessarely correct // for scaled objects. // see https://github.com/mrdoob/three.js/issues/5827 // TODO: remove this once the bug has been fixed for (var _i2 = 0; _i2 < intersects.length; _i2++) { var I = intersects[_i2]; I.distance = raycaster.ray.origin.distanceTo(I.point); } intersects.sort(function (a, b) { return a.distance - b.distance; }); } get showCoordinates() { return this._showCoordinates; } set showCoordinates(value) { this._showCoordinates = value; this.update(); } get showAngles() { return this._showAngles; } set showAngles(value) { this._showAngles = value; this.update(); } get showCircle() { return this._showCircle; } set showCircle(value) { this._showCircle = value; this.update(); } get showAzimuth() { return this._showAzimuth; } set showAzimuth(value) { this._showAzimuth = value; this.update(); } get showEdges() { return this._showEdges; } set showEdges(value) { this._showEdges = value; this.update(); } get showHeight() { return this._showHeight; } set showHeight(value) { this._showHeight = value; this.update(); } get showArea() { return this._showArea; } set showArea(value) { this._showArea = value; this.update(); } get closed() { return this._closed; } set closed(value) { this._closed = value; this.update(); } get showDistances() { return this._showDistances; } set showDistances(value) { this._showDistances = value; this.update(); } } class PolygonClipVolume extends Object3D { constructor(camera) { super(); this.constructor.counter = this.constructor.counter === undefined ? 0 : this.constructor.counter + 1; this.name = "polygon_clip_volume_" + this.constructor.counter; this.camera = camera.clone(); this.camera.rotation.set(...camera.rotation.toArray()); // [r85] workaround because camera.clone() doesn't work on rotation this.camera.rotation.order = camera.rotation.order; this.camera.updateMatrixWorld(); this.camera.updateProjectionMatrix(); this.camera.matrixWorldInverse.copy(this.camera.matrixWorld).invert(); this.viewMatrix = this.camera.matrixWorldInverse.clone(); this.projMatrix = this.camera.projectionMatrix.clone(); // projected markers this.markers = []; this.initialized = false; } addMarker() { var marker = new Mesh(); var cancel; var drag = e => { var size = e.viewer.renderer.getSize(new Vector2()); var projectedPos = new Vector3(2.0 * (e.drag.end.x / size.width) - 1.0, -2.0 * (e.drag.end.y / size.height) + 1.0, 0); marker.position.copy(projectedPos); }; var drop = e => { cancel(); }; cancel = e => { marker.removeEventListener("drag", drag); marker.removeEventListener("drop", drop); }; marker.addEventListener("drag", drag); marker.addEventListener("drop", drop); this.markers.push(marker); } removeLastMarker() { if (this.markers.length > 0) { this.markers.splice(this.markers.length - 1, 1); } } } ; class Utils { static async loadShapefileFeatures(file, callback) { var features = []; var handleFinish = () => { callback(features); }; var source = await shapefile.open(file); while (true) { var result = await source.read(); if (result.done) { handleFinish(); break; } if (result.value && result.value.type === 'Feature' && result.value.geometry !== undefined) { features.push(result.value); } } } static toString(value) { if (value.x != null) { return value.x.toFixed(2) + ', ' + value.y.toFixed(2) + ', ' + value.z.toFixed(2); } else { return '' + value + ''; } } static normalizeURL(url) { var u = new URL(url); return u.protocol + '//' + u.hostname + u.pathname.replace(/\/+/g, '/'); } static pathExists(url) { var req = XHRFactory.createXMLHttpRequest(); req.open('GET', url, false); req.send(null); if (req.status !== 200) { return false; } return true; } static debugSphere(parent, position, scale, color) { var geometry = new SphereGeometry(1, 8, 8); var material; if (color !== undefined) { material = new MeshBasicMaterial({ color: color }); } else { material = new MeshNormalMaterial(); } var sphere = new Mesh(geometry, material); sphere.position.copy(position); sphere.scale.set(scale, scale, scale); parent.add(sphere); return sphere; } static debugLine(parent, start, end, color) { var material = new LineBasicMaterial({ color: color }); var geometry = new Geometry(); var p1 = new Vector3(0, 0, 0); var p2 = end.clone().sub(start); geometry.vertices.push(p1, p2); var tl = new Line(geometry, material); tl.position.copy(start); parent.add(tl); var line = { node: tl, set: (start, end) => { geometry.vertices[0].copy(start); geometry.vertices[1].copy(end); geometry.verticesNeedUpdate = true; } }; return line; } static debugCircle(parent, center, radius, normal, color) { var material = new LineBasicMaterial({ color: color }); var geometry = new Geometry(); var n = 32; for (var i = 0; i <= n; i++) { var u0 = 2 * Math.PI * (i / n); var u1 = 2 * Math.PI * (i + 1) / n; var p0 = new Vector3(Math.cos(u0), Math.sin(u0), 0); var p1 = new Vector3(Math.cos(u1), Math.sin(u1), 0); geometry.vertices.push(p0, p1); } var tl = new Line(geometry, material); tl.position.copy(center); tl.scale.set(radius, radius, radius); parent.add(tl); } static debugBox(parent, box) { var transform = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Matrix4(); var color = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0xFFFF00; var vertices = [[box.min.x, box.min.y, box.min.z], [box.min.x, box.min.y, box.max.z], [box.min.x, box.max.y, box.min.z], [box.min.x, box.max.y, box.max.z], [box.max.x, box.min.y, box.min.z], [box.max.x, box.min.y, box.max.z], [box.max.x, box.max.y, box.min.z], [box.max.x, box.max.y, box.max.z]].map(v => new Vector3(...v)); var edges = [[0, 4], [4, 5], [5, 1], [1, 0], [2, 6], [6, 7], [7, 3], [3, 2], [0, 2], [4, 6], [5, 7], [1, 3]]; var center = box.getCenter(new Vector3()); var centroids = [{ position: [box.min.x, center.y, center.z], color: 0xFF0000 }, { position: [box.max.x, center.y, center.z], color: 0x880000 }, { position: [center.x, box.min.y, center.z], color: 0x00FF00 }, { position: [center.x, box.max.y, center.z], color: 0x008800 }, { position: [center.x, center.y, box.min.z], color: 0x0000FF }, { position: [center.x, center.y, box.max.z], color: 0x000088 }]; for (var vertex of vertices) { var pos = vertex.clone().applyMatrix4(transform); Utils.debugSphere(parent, pos, 0.1, 0xFF0000); } for (var edge of edges) { var start = vertices[edge[0]].clone().applyMatrix4(transform); var end = vertices[edge[1]].clone().applyMatrix4(transform); Utils.debugLine(parent, start, end, color); } for (var centroid of centroids) { var _pos = new Vector3(...centroid.position).applyMatrix4(transform); Utils.debugSphere(parent, _pos, 0.1, centroid.color); } } static debugPlane(parent, plane) { var size = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; var color = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0x0000FF; var planehelper = new PlaneHelper(plane, size, color); parent.add(planehelper); } /** * adapted from mhluska at https://github.com/mrdoob/three.js/issues/1561 */ static computeTransformedBoundingBox(box, transform) { var vertices = [new Vector3(box.min.x, box.min.y, box.min.z).applyMatrix4(transform), new Vector3(box.min.x, box.min.y, box.min.z).applyMatrix4(transform), new Vector3(box.max.x, box.min.y, box.min.z).applyMatrix4(transform), new Vector3(box.min.x, box.max.y, box.min.z).applyMatrix4(transform), new Vector3(box.min.x, box.min.y, box.max.z).applyMatrix4(transform), new Vector3(box.min.x, box.max.y, box.max.z).applyMatrix4(transform), new Vector3(box.max.x, box.max.y, box.min.z).applyMatrix4(transform), new Vector3(box.max.x, box.min.y, box.max.z).applyMatrix4(transform), new Vector3(box.max.x, box.max.y, box.max.z).applyMatrix4(transform)]; var boundingBox = new Box3(); boundingBox.setFromPoints(vertices); return boundingBox; } //感觉就是bound.applyMatrix4(transform) /** * add separators to large numbers * * @param nStr * @returns */ static addCommas(nStr) { nStr += ''; var x = nStr.split('.'); var x1 = x[0]; var x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; } static removeCommas(str) { return str.replace(/,/g, ''); } /** * create worker from a string * * code from http://stackoverflow.com/questions/10343913/how-to-create-a-web-worker-from-a-string */ static createWorker(code) { var blob = new Blob([code], { type: 'application/javascript' }); var worker = new Worker(URL.createObjectURL(blob)); return worker; } static moveTo(scene, endPosition, endTarget) { var view = scene.view; var camera = scene.getActiveCamera(); var animationDuration = 500; var easing = TWEEN.Easing.Quartic.Out; { // animate camera position var tween = new TWEEN.Tween(view.position).to(endPosition, animationDuration); tween.easing(easing); tween.start(); } { // animate camera target var camTargetDistance = camera.position.distanceTo(endTarget); var target = new Vector3().addVectors(camera.position, camera.getWorldDirection(new Vector3()).clone().multiplyScalar(camTargetDistance)); var _tween = new TWEEN.Tween(target).to(endTarget, animationDuration); _tween.easing(easing); _tween.onUpdate(() => { view.lookAt(target); }); _tween.onComplete(() => { view.lookAt(target); }); _tween.start(); } } static loadSkybox(path) { var parent = new Object3D("skybox_root"); var camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 100000); camera.up.set(0, 0, 1); var scene = new Scene(); var format = '.jpg'; var urls = [path + 'px' + format, path + 'nx' + format, path + 'py' + format, path + 'ny' + format, path + 'pz' + format, path + 'nz' + format]; var materialArray = []; { var _loop = function _loop() { var material = new MeshBasicMaterial({ map: null, side: BackSide, depthTest: false, depthWrite: false, color: 0x424556 }); materialArray.push(material); var loader = new TextureLoader(); loader.load(urls[i], function loaded(texture) { material.map = texture; material.needsUpdate = true; material.color.setHex(0xffffff); }, function progress(xhr) { // console.log( (xhr.loaded / xhr.total * 100) + '% loaded' ); }, function error(xhr) { console.log('An error happened', xhr); }); }; for (var i = 0; i < 6; i++) { _loop(); } } var skyGeometry = new BoxGeometry(700, 700, 700); var skybox = new Mesh(skyGeometry, materialArray); scene.add(skybox); scene.traverse(n => n.frustumCulled = false); // z up scene.rotation.x = Math.PI / 2; parent.children.push(camera); camera.parent = parent; return { camera, scene, parent }; } static createGrid(width, length, spacing, color) { var material = new LineBasicMaterial({ color: color || 0x888888 }); var geometry = new Geometry(); for (var i = 0; i <= length; i++) { geometry.vertices.push(new Vector3(-(spacing * width) / 2, i * spacing - spacing * length / 2, 0)); geometry.vertices.push(new Vector3(+(spacing * width) / 2, i * spacing - spacing * length / 2, 0)); } for (var _i = 0; _i <= width; _i++) { geometry.vertices.push(new Vector3(_i * spacing - spacing * width / 2, -(spacing * length) / 2, 0)); geometry.vertices.push(new Vector3(_i * spacing - spacing * width / 2, +(spacing * length) / 2, 0)); } var line = new LineSegments(geometry, material, LinePieces); line.receiveShadow = true; return line; } static createBackgroundTexture(width, height) { function gauss(x, y) { return 1 / (2 * Math.PI) * Math.exp(-(x * x + y * y) / 2); } ; // map.magFilter = THREE.NearestFilter; var size = width * height; var data = new Uint8Array(3 * size); var chroma = [1, 1.5, 1.7]; var max = gauss(0, 0); for (var x = 0; x < width; x++) { for (var y = 0; y < height; y++) { var u = 2 * (x / width) - 1; var v = 2 * (y / height) - 1; var i = x + width * y; var d = gauss(2 * u, 2 * v) / max; var r = (Math.random() + Math.random() + Math.random()) / 3; r = (d * 0.5 + 0.5) * r * 0.03; r = r * 0.4; // d = Math.pow(d, 0.6); data[3 * i + 0] = 255 * (d / 15 + 0.05 + r) * chroma[0]; data[3 * i + 1] = 255 * (d / 15 + 0.05 + r) * chroma[1]; data[3 * i + 2] = 255 * (d / 15 + 0.05 + r) * chroma[2]; } } var texture = new DataTexture(data, width, height, RGBFormat); texture.needsUpdate = true; return texture; } static getMousePointCloudIntersection(mouse, camera, viewer, pointclouds) { var params = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; var renderer = viewer.renderer; var nmouse = { x: mouse.x / renderer.domElement.clientWidth * 2 - 1, y: -(mouse.y / renderer.domElement.clientHeight) * 2 + 1 }; var pickParams = {}; if (params.pickClipped) { pickParams.pickClipped = params.pickClipped; } pickParams.x = mouse.x; pickParams.y = renderer.domElement.clientHeight - mouse.y; var raycaster = new Raycaster(); raycaster.setFromCamera(nmouse, camera); var ray = raycaster.ray; var selectedPointcloud = null; var closestDistance = Infinity; var closestIntersection = null; var closestPoint = null; for (var pointcloud of pointclouds) { var point = pointcloud.pick(viewer, camera, ray, pickParams); if (!point) { continue; } var distance = camera.position.distanceTo(point.position); if (distance < closestDistance) { closestDistance = distance; selectedPointcloud = pointcloud; closestIntersection = point.position; closestPoint = point; } } if (selectedPointcloud) { return { location: closestIntersection, distance: closestDistance, pointcloud: selectedPointcloud, point: closestPoint }; } else { return null; } } static pixelsArrayToImage(pixels, width, height) { var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; var context = canvas.getContext('2d'); pixels = new pixels.constructor(pixels); for (var i = 0; i < pixels.length; i++) { pixels[i * 4 + 3] = 255; } var imageData = context.createImageData(width, height); imageData.data.set(pixels); context.putImageData(imageData, 0, 0); var img = new Image(); img.src = canvas.toDataURL(); // img.style.transform = "scaleY(-1)"; return img; } static pixelsArrayToDataUrl(pixels, width, height) { var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; var context = canvas.getContext('2d'); pixels = new pixels.constructor(pixels); for (var i = 0; i < pixels.length; i++) { pixels[i * 4 + 3] = 255; } var imageData = context.createImageData(width, height); imageData.data.set(pixels); context.putImageData(imageData, 0, 0); var dataURL = canvas.toDataURL(); return dataURL; } static pixelsArrayToCanvas(pixels, width, height) { var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; var context = canvas.getContext('2d'); pixels = new pixels.constructor(pixels); //for (let i = 0; i < pixels.length; i++) { // pixels[i * 4 + 3] = 255; //} // flip vertically var bytesPerLine = width * 4; for (var i = 0; i < parseInt(height / 2); i++) { var j = height - i - 1; var lineI = pixels.slice(i * bytesPerLine, i * bytesPerLine + bytesPerLine); var lineJ = pixels.slice(j * bytesPerLine, j * bytesPerLine + bytesPerLine); pixels.set(lineJ, i * bytesPerLine); pixels.set(lineI, j * bytesPerLine); } var imageData = context.createImageData(width, height); imageData.data.set(pixels); context.putImageData(imageData, 0, 0); return canvas; } static removeListeners(dispatcher, type) { if (dispatcher._listeners === undefined) { return; } if (dispatcher._listeners[type]) { delete dispatcher._listeners[type]; } } static mouseToRay(mouse, camera, width, height) { var normalizedMouse = { x: mouse.x / width * 2 - 1, y: -(mouse.y / height) * 2 + 1 }; var vector = new Vector3(normalizedMouse.x, normalizedMouse.y, 0.5); var origin = camera.position.clone(); vector.unproject(camera); var direction = new Vector3().subVectors(vector, origin).normalize(); var ray = new Ray(origin, direction); return ray; } static projectedRadius(radius, camera, distance, screenWidth, screenHeight) { if (camera instanceof OrthographicCamera) { return Utils.projectedRadiusOrtho(radius, camera.projectionMatrix, screenWidth, screenHeight); } else if (camera instanceof PerspectiveCamera) { return Utils.projectedRadiusPerspective(radius, camera.fov * Math.PI / 180, distance, screenHeight); } else { throw new Error("invalid parameters"); } } static projectedRadiusPerspective(radius, fov, distance, screenHeight) { var projFactor = 1 / Math.tan(fov / 2) / distance; projFactor = projFactor * screenHeight / 2; return radius * projFactor; } static projectedRadiusOrtho(radius, proj, screenWidth, screenHeight) { var p1 = new Vector4(0); var p2 = new Vector4(radius); p1.applyMatrix4(proj); p2.applyMatrix4(proj); p1 = new Vector3(p1.x, p1.y, p1.z); p2 = new Vector3(p2.x, p2.y, p2.z); p1.x = (p1.x + 1.0) * 0.5 * screenWidth; p1.y = (p1.y + 1.0) * 0.5 * screenHeight; p2.x = (p2.x + 1.0) * 0.5 * screenWidth; p2.y = (p2.y + 1.0) * 0.5 * screenHeight; return p1.distanceTo(p2); } static topView(camera, node) { camera.position.set(0, 1, 0); camera.rotation.set(-Math.PI / 2, 0, 0); camera.zoomTo(node, 1); } static frontView(camera, node) { camera.position.set(0, 0, 1); camera.rotation.set(0, 0, 0); camera.zoomTo(node, 1); } static leftView(camera, node) { camera.position.set(-1, 0, 0); camera.rotation.set(0, -Math.PI / 2, 0); camera.zoomTo(node, 1); } static rightView(camera, node) { camera.position.set(1, 0, 0); camera.rotation.set(0, Math.PI / 2, 0); camera.zoomTo(node, 1); } static findClosestGpsTime(target, viewer) { var start = performance.now(); var nodes = []; for (var pc of viewer.scene.pointclouds) { nodes.push(pc.root); for (var child of pc.root.children) { if (child) { nodes.push(child); } } } var closestNode = null; var closestIndex = Infinity; var closestDistance = Infinity; var closestValue = 0; for (var node of nodes) { var isOkay = node.geometryNode != null && node.geometryNode.geometry != null && node.sceneNode != null; if (!isOkay) { continue; } var _geometry = node.geometryNode.geometry; var gpsTime = _geometry.attributes["gps-time"]; var range = gpsTime.potree.range; for (var i = 0; i < gpsTime.array.length; i++) { var value = gpsTime.array[i]; value = value * (range[1] - range[0]) + range[0]; var distance = Math.abs(target - value); if (distance < closestDistance) { closestIndex = i; closestDistance = distance; closestValue = value; closestNode = node; //console.log("found a closer one: " + value); } } } var geometry = closestNode.geometryNode.geometry; var position = new Vector3(geometry.attributes.position.array[3 * closestIndex + 0], geometry.attributes.position.array[3 * closestIndex + 1], geometry.attributes.position.array[3 * closestIndex + 2]); position.applyMatrix4(closestNode.sceneNode.matrixWorld); var end = performance.now(); var duration = end - start; console.log("duration: ".concat(duration.toFixed(3), "ms")); return { node: closestNode, index: closestIndex, position: position }; } /** * * 0: no intersection * 1: intersection * 2: fully inside */ static frustumSphereIntersection(frustum, sphere) { var planes = frustum.planes; var center = sphere.center; var negRadius = -sphere.radius; var minDistance = Number.MAX_VALUE; for (var i = 0; i < 6; i++) { var distance = planes[i].distanceToPoint(center); if (distance < negRadius) { return 0; } minDistance = Math.min(minDistance, distance); } return minDistance >= sphere.radius ? 2 : 1; } // code taken from three.js // ImageUtils - generateDataTexture() static generateDataTexture(width, height, color) { var size = width * height; var data = new Uint8Array(4 * width * height); var r = Math.floor(color.r * 255); var g = Math.floor(color.g * 255); var b = Math.floor(color.b * 255); for (var i = 0; i < size; i++) { data[i * 3] = r; data[i * 3 + 1] = g; data[i * 3 + 2] = b; } var texture = new DataTexture(data, width, height, RGBAFormat); texture.needsUpdate = true; texture.magFilter = NearestFilter; return texture; } // from http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript static getParameterByName(name) { name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]'); var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'); var results = regex.exec(document.location.search); return results === null ? null : decodeURIComponent(results[1].replace(/\+/g, ' ')); } static setParameter(name, value) { // value = encodeURIComponent(value); name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]'); var regex = new RegExp('([\\?&])(' + name + '=([^&#]*))'); var results = regex.exec(document.location.search); var url = window.location.href; if (results === null) { if (window.location.search.length === 0) { url = url + '?'; } else { url = url + '&'; } url = url + name + '=' + value; } else { var newValue = name + '=' + value; url = url.replace(results[2], newValue); } window.history.replaceState({}, '', url); } static createChildAABB(aabb, index) { var min = aabb.min.clone(); var max = aabb.max.clone(); var size = new Vector3().subVectors(max, min); if ((index & 0b0001) > 0) { min.z += size.z / 2; } else { max.z -= size.z / 2; } if ((index & 0b0010) > 0) { min.y += size.y / 2; } else { max.y -= size.y / 2; } if ((index & 0b0100) > 0) { min.x += size.x / 2; } else { max.x -= size.x / 2; } return new Box3(min, max); } // see https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript static clipboardCopy(text) { var textArea = document.createElement("textarea"); textArea.style.position = 'fixed'; textArea.style.top = 0; textArea.style.left = 0; textArea.style.width = '2em'; textArea.style.height = '2em'; textArea.style.padding = 0; textArea.style.border = 'none'; textArea.style.outline = 'none'; textArea.style.boxShadow = 'none'; textArea.style.background = 'transparent'; textArea.value = text; document.body.appendChild(textArea); textArea.select(); try { var success = document.execCommand('copy'); if (success) { console.log("copied text to clipboard"); } else { console.log("copy to clipboard failed"); } } catch (err) { console.log("error while trying to copy to clipboard"); } document.body.removeChild(textArea); } static getMeasurementIcon(measurement) { if (measurement instanceof Measure) { if (measurement.showDistances && !measurement.showArea && !measurement.showAngles) { return "".concat(Potree.resourcePath, "/icons/distance.svg"); } else if (measurement.showDistances && measurement.showArea && !measurement.showAngles) { return "".concat(Potree.resourcePath, "/icons/area.svg"); } else if (measurement.maxMarkers === 1) { return "".concat(Potree.resourcePath, "/icons/point.svg"); } else if (!measurement.showDistances && !measurement.showArea && measurement.showAngles) { return "".concat(Potree.resourcePath, "/icons/angle.png"); } else if (measurement.showHeight) { return "".concat(Potree.resourcePath, "/icons/height.svg"); } else { return "".concat(Potree.resourcePath, "/icons/distance.svg"); } } else if (measurement instanceof Profile) { return "".concat(Potree.resourcePath, "/icons/profile.svg"); } else if (measurement instanceof Volume) { return "".concat(Potree.resourcePath, "/icons/volume.svg"); } else if (measurement instanceof PolygonClipVolume) { return "".concat(Potree.resourcePath, "/icons/clip-polygon.svg"); } } static lineToLineIntersection(P0, P1, P2, P3) { var P = [P0, P1, P2, P3]; var d = (m, n, o, p) => { var result = (P[m].x - P[n].x) * (P[o].x - P[p].x) + (P[m].y - P[n].y) * (P[o].y - P[p].y) + (P[m].z - P[n].z) * (P[o].z - P[p].z); return result; }; var mua = (d(0, 2, 3, 2) * d(3, 2, 1, 0) - d(0, 2, 1, 0) * d(3, 2, 3, 2) /**-----------------------------------------------------------------**/) / (d(1, 0, 1, 0) * d(3, 2, 3, 2) - d(3, 2, 1, 0) * d(3, 2, 1, 0)); var mub = (d(0, 2, 3, 2) + mua * d(3, 2, 1, 0) /**--------------------------------------**/) / d(3, 2, 3, 2); var P01 = P1.clone().sub(P0); var P23 = P3.clone().sub(P2); var Pa = P0.clone().add(P01.multiplyScalar(mua)); var Pb = P2.clone().add(P23.multiplyScalar(mub)); var center = Pa.clone().add(Pb).multiplyScalar(0.5); return center; } static computeCircleCenter(A, B, C) { var AB = B.clone().sub(A); var AC = C.clone().sub(A); var N = AC.clone().cross(AB).normalize(); var ab_dir = AB.clone().cross(N).normalize(); var ac_dir = AC.clone().cross(N).normalize(); var ab_origin = A.clone().add(B).multiplyScalar(0.5); var ac_origin = A.clone().add(C).multiplyScalar(0.5); var P0 = ab_origin; var P1 = ab_origin.clone().add(ab_dir); var P2 = ac_origin; var P3 = ac_origin.clone().add(ac_dir); var center = Utils.lineToLineIntersection(P0, P1, P2, P3); return center; // Potree.Utils.debugLine(viewer.scene.scene, P0, P1, 0x00ff00); // Potree.Utils.debugLine(viewer.scene.scene, P2, P3, 0x0000ff); // Potree.Utils.debugSphere(viewer.scene.scene, center, 0.03, 0xff00ff); // const radius = center.distanceTo(A); // Potree.Utils.debugCircle(viewer.scene.scene, center, radius, new THREE.Vector3(0, 0, 1), 0xff00ff); } static getNorthVec(p1, distance, projection) { if (projection) { // if there is a projection, transform coordinates to WGS84 // and compute angle to north there proj4.defs("pointcloud", projection); var transform = proj4("pointcloud", "WGS84"); var llP1 = transform.forward(p1.toArray()); var llP2 = transform.forward([p1.x, p1.y + distance]); var polarRadius = Math.sqrt((llP2[0] - llP1[0]) ** 2 + (llP2[1] - llP1[1]) ** 2); llP2 = [llP1[0], llP1[1] + polarRadius]; var northVec = transform.inverse(llP2); return new Vector3(...northVec, p1.z).sub(p1); } else { // if there is no projection, assume [0, 1, 0] as north direction var vec = new Vector3(0, 1, 0).multiplyScalar(distance); return vec; } } static computeAzimuth(p1, p2, projection) { var azimuth = 0; if (projection) { // if there is a projection, transform coordinates to WGS84 // and compute angle to north there var transform; if (projection.includes('EPSG')) { transform = proj4(projection, "WGS84"); } else { proj4.defs("pointcloud", projection); transform = proj4("pointcloud", "WGS84"); } var llP1 = transform.forward(p1.toArray()); var llP2 = transform.forward(p2.toArray()); var dir = [llP2[0] - llP1[0], llP2[1] - llP1[1]]; azimuth = Math.atan2(dir[1], dir[0]) - Math.PI / 2; } else { // if there is no projection, assume [0, 1, 0] as north direction var _dir = [p2.x - p1.x, p2.y - p1.y]; azimuth = Math.atan2(_dir[1], _dir[0]) - Math.PI / 2; } // make clockwise azimuth = -azimuth; return azimuth; } static async loadScript(url) { return new Promise(resolve => { var element = document.getElementById(url); if (element) { resolve(); } else { var script = document.createElement("script"); script.id = url; script.onload = () => { resolve(); }; script.src = url; document.body.appendChild(script); } }); } static createSvgGradient(scheme) { // this is what we are creating: // // // // // // ... // // // // // // var gradientId = "".concat(Math.random(), "_").concat(Date.now()); var svgn = "http://www.w3.org/2000/svg"; var svg = document.createElementNS(svgn, "svg"); svg.setAttributeNS(null, "width", "2em"); svg.setAttributeNS(null, "height", "3em"); { // var defs = document.createElementNS(svgn, "defs"); var linearGradient = document.createElementNS(svgn, "linearGradient"); linearGradient.setAttributeNS(null, "id", gradientId); linearGradient.setAttributeNS(null, "gradientTransform", "rotate(90)"); for (var i = scheme.length - 1; i >= 0; i--) { var stopVal = scheme[i]; var percent = parseInt(100 - stopVal[0] * 100); var [r, g, b] = stopVal[1].toArray().map(v => parseInt(v * 255)); var stop = document.createElementNS(svgn, "stop"); stop.setAttributeNS(null, "offset", "".concat(percent, "%")); stop.setAttributeNS(null, "stop-color", "rgb(".concat(r, ", ").concat(g, ", ").concat(b, ")")); linearGradient.appendChild(stop); } defs.appendChild(linearGradient); svg.appendChild(defs); } var rect = document.createElementNS(svgn, "rect"); rect.setAttributeNS(null, "width", "100%"); rect.setAttributeNS(null, "height", "100%"); rect.setAttributeNS(null, "fill", "url(\"#".concat(gradientId, "\")")); rect.setAttributeNS(null, "stroke", "black"); rect.setAttributeNS(null, "stroke-width", "0.1em"); svg.appendChild(rect); return svg; } static async waitAny(promises) { return new Promise(resolve => { promises.map(promise => { promise.then(() => { resolve(); }); }); }); } } Utils.screenPass = new function () { this.screenScene = new Scene(); this.screenQuad = new Mesh(new PlaneBufferGeometry(2, 2, 1)); this.screenQuad.material.depthTest = true; this.screenQuad.material.depthWrite = true; this.screenQuad.material.transparent = true; this.screenScene.add(this.screenQuad); this.camera = new Camera(); this.render = function (renderer, material, target) { this.screenQuad.material = material; if (typeof target === 'undefined') { renderer.render(this.screenScene, this.camera); } else { renderer.render(this.screenScene, this.camera, target); } }; }(); class Version { constructor(version) { this.version = version; var vmLength = version.indexOf('.') === -1 ? version.length : version.indexOf('.'); this.versionMajor = parseInt(version.substr(0, vmLength)); this.versionMinor = parseInt(version.substr(vmLength + 1)); if (this.versionMinor.length === 0) { this.versionMinor = 0; } } newerThan(version) { var v = new Version(version); if (this.versionMajor > v.versionMajor) { return true; } else if (this.versionMajor === v.versionMajor && this.versionMinor > v.versionMinor) { return true; } else { return false; } } equalOrHigher(version) { var v = new Version(version); if (this.versionMajor > v.versionMajor) { return true; } else if (this.versionMajor === v.versionMajor && this.versionMinor >= v.versionMinor) { return true; } else { return false; } } upTo(version) { return !this.newerThan(version); } } //加载 解析点云 class BinaryLoader { constructor(version, boundingBox, scale) { if (typeof version === 'string') { this.version = new Version(version); } else { this.version = version; } this.boundingBox = boundingBox; this.scale = scale; } load(node) { if (node.loaded) { return; } var url = node.getURL(); if (this.version.equalOrHigher('1.4')) { url += '.bin'; } var xhr = XHRFactory.createXMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'arraybuffer'; xhr.overrideMimeType('text/plain; charset=x-user-defined'); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if ((xhr.status === 200 || xhr.status === 0) && xhr.response !== null) { var buffer = xhr.response; this.parse(node, buffer); } else { //console.error(`Failed to load file! HTTP status: ${xhr.status}, file: ${url}`); throw new Error("Failed to load file! HTTP status: ".concat(xhr.status, ", file: ").concat(url)); } } }; try { xhr.send(null); } catch (e) { console.log('fehler beim laden der punktwolke: ' + e); } } parse(node, buffer, callback) { var pointAttributes = node.pcoGeometry.pointAttributes; var numPoints = buffer.byteLength / node.pcoGeometry.pointAttributes.byteSize; if (this.version.upTo('1.5')) { node.numPoints = numPoints; } var workerPath = Potree.scriptPath + '/workers/BinaryDecoderWorker.js'; var worker = Potree.workerPool.getWorker(workerPath); worker.onmessage = function (e) { var data = e.data; var buffers = data.attributeBuffers; var tightBoundingBox = new Box3(new Vector3().fromArray(data.tightBoundingBox.min), new Vector3().fromArray(data.tightBoundingBox.max)); Potree.workerPool.returnWorker(workerPath, worker); var geometry = new BufferGeometry(); var _loop = function _loop() { var buffer = buffers[property].buffer; var batchAttribute = buffers[property].attribute; if (property === "POSITION_CARTESIAN") { geometry.setAttribute('position', new BufferAttribute(new Float32Array(buffer), 3)); } else if (property === "rgba") { geometry.setAttribute("rgba", new BufferAttribute(new Uint8Array(buffer), 4, true)); } else if (property === "NORMAL_SPHEREMAPPED") { geometry.setAttribute('normal', new BufferAttribute(new Float32Array(buffer), 3)); } else if (property === "NORMAL_OCT16") { geometry.setAttribute('normal', new BufferAttribute(new Float32Array(buffer), 3)); } else if (property === "NORMAL") { geometry.setAttribute('normal', new BufferAttribute(new Float32Array(buffer), 3)); } else if (property === "INDICES") { var bufferAttribute = new BufferAttribute(new Uint8Array(buffer), 4); bufferAttribute.normalized = true; geometry.setAttribute('indices', bufferAttribute); } else if (property === "SPACING") { var _bufferAttribute = new BufferAttribute(new Float32Array(buffer), 1); geometry.setAttribute('spacing', _bufferAttribute); } else { var _bufferAttribute2 = new BufferAttribute(new Float32Array(buffer), 1); _bufferAttribute2.potree = { offset: buffers[property].offset, scale: buffers[property].scale, preciseBuffer: buffers[property].preciseBuffer, range: batchAttribute.range }; geometry.setAttribute(property, _bufferAttribute2); var attribute = pointAttributes.attributes.find(a => a.name === batchAttribute.name); attribute.range[0] = Math.min(attribute.range[0], batchAttribute.range[0]); attribute.range[1] = Math.max(attribute.range[1], batchAttribute.range[1]); if (node.getLevel() === 0) { attribute.initialRange = batchAttribute.range; } } }; for (var property in buffers) { _loop(); } tightBoundingBox.max.sub(tightBoundingBox.min); tightBoundingBox.min.set(0, 0, 0); var numPoints = e.data.buffer.byteLength / pointAttributes.byteSize; node.numPoints = numPoints; node.geometry = geometry; node.mean = new Vector3(...data.mean); node.tightBoundingBox = tightBoundingBox; node.loaded = true; node.loading = false; node.estimatedSpacing = data.estimatedSpacing; Potree.numNodesLoading--; callback(); //add }; var message = { buffer: buffer, pointAttributes: pointAttributes, version: this.version.version, min: [node.boundingBox.min.x, node.boundingBox.min.y, node.boundingBox.min.z], offset: [node.pcoGeometry.offset.x, node.pcoGeometry.offset.y, node.pcoGeometry.offset.z], scale: this.scale, spacing: node.spacing, hasChildren: node.hasChildren, name: node.name }; worker.postMessage(message, [message.buffer]); } } var ftCanvas = document.createElement('canvas'); var Features = function () { var gl = ftCanvas.getContext('webgl') || ftCanvas.getContext('experimental-webgl'); if (gl === null) { return {}; } // -- code taken from THREE.WebGLRenderer -- var _vertexShaderPrecisionHighpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT); var _vertexShaderPrecisionMediumpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT); // Unused: let _vertexShaderPrecisionLowpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_FLOAT); var _fragmentShaderPrecisionHighpFloat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT); var _fragmentShaderPrecisionMediumpFloat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT); // Unused: let _fragmentShaderPrecisionLowpFloat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT); var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0; var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0; // ----------------------------------------- var precision; if (highpAvailable) { precision = 'highp'; } else if (mediumpAvailable) { precision = 'mediump'; } else { precision = 'lowp'; } return { SHADER_INTERPOLATION: { isSupported: function isSupported() { var supported = true; supported = supported && gl.getExtension('EXT_frag_depth'); supported = supported && gl.getParameter(gl.MAX_VARYING_VECTORS) >= 8; return supported; } }, SHADER_SPLATS: { isSupported: function isSupported() { var supported = true; supported = supported && gl.getExtension('EXT_frag_depth'); supported = supported && gl.getExtension('OES_texture_float'); supported = supported && gl.getParameter(gl.MAX_VARYING_VECTORS) >= 8; return supported; } }, SHADER_EDL: { isSupported: function isSupported() { var supported = true; supported = supported && gl.getExtension('EXT_frag_depth'); supported = supported && gl.getExtension('OES_texture_float'); supported = supported && gl.getParameter(gl.MAX_VARYING_VECTORS) >= 8; //supported = supported || (gl instanceof WebGL2RenderingContext); return supported; } }, //WEBGL2: { // isSupported: function(){ // return typeof WebGL2RenderingContext != 'undefined' && gl instanceof WebGL2RenderingContext; // } //}, precision: precision }; }(); /** * Some types of possible point attribute data formats * * @class */ var PointAttributeTypes = { DATA_TYPE_DOUBLE: { ordinal: 0, name: "double", size: 8 }, DATA_TYPE_FLOAT: { ordinal: 1, name: "float", size: 4 }, DATA_TYPE_INT8: { ordinal: 2, name: "int8", size: 1 }, DATA_TYPE_UINT8: { ordinal: 3, name: "uint8", size: 1 }, DATA_TYPE_INT16: { ordinal: 4, name: "int16", size: 2 }, DATA_TYPE_UINT16: { ordinal: 5, name: "uint16", size: 2 }, DATA_TYPE_INT32: { ordinal: 6, name: "int32", size: 4 }, DATA_TYPE_UINT32: { ordinal: 7, name: "uint32", size: 4 }, DATA_TYPE_INT64: { ordinal: 8, name: "int64", size: 8 }, DATA_TYPE_UINT64: { ordinal: 9, name: "uint64", size: 8 } }; var i$1 = 0; for (var obj in PointAttributeTypes) { PointAttributeTypes[i$1] = PointAttributeTypes[obj]; i$1++; } class PointAttribute { constructor(name, type, numElements) { this.name = name; this.type = type; this.numElements = numElements; this.byteSize = this.numElements * this.type.size; this.description = ""; this.range = [Infinity, -Infinity]; } } ; PointAttribute.POSITION_CARTESIAN = new PointAttribute("POSITION_CARTESIAN", PointAttributeTypes.DATA_TYPE_FLOAT, 3); PointAttribute.RGBA_PACKED = new PointAttribute("COLOR_PACKED", PointAttributeTypes.DATA_TYPE_INT8, 4); PointAttribute.COLOR_PACKED = PointAttribute.RGBA_PACKED; PointAttribute.RGB_PACKED = new PointAttribute("COLOR_PACKED", PointAttributeTypes.DATA_TYPE_INT8, 3); PointAttribute.NORMAL_FLOATS = new PointAttribute("NORMAL_FLOATS", PointAttributeTypes.DATA_TYPE_FLOAT, 3); PointAttribute.INTENSITY = new PointAttribute("INTENSITY", PointAttributeTypes.DATA_TYPE_UINT16, 1); PointAttribute.CLASSIFICATION = new PointAttribute("CLASSIFICATION", PointAttributeTypes.DATA_TYPE_UINT8, 1); PointAttribute.NORMAL_SPHEREMAPPED = new PointAttribute("NORMAL_SPHEREMAPPED", PointAttributeTypes.DATA_TYPE_UINT8, 2); PointAttribute.NORMAL_OCT16 = new PointAttribute("NORMAL_OCT16", PointAttributeTypes.DATA_TYPE_UINT8, 2); PointAttribute.NORMAL = new PointAttribute("NORMAL", PointAttributeTypes.DATA_TYPE_FLOAT, 3); PointAttribute.RETURN_NUMBER = new PointAttribute("RETURN_NUMBER", PointAttributeTypes.DATA_TYPE_UINT8, 1); PointAttribute.NUMBER_OF_RETURNS = new PointAttribute("NUMBER_OF_RETURNS", PointAttributeTypes.DATA_TYPE_UINT8, 1); PointAttribute.SOURCE_ID = new PointAttribute("SOURCE_ID", PointAttributeTypes.DATA_TYPE_UINT16, 1); PointAttribute.INDICES = new PointAttribute("INDICES", PointAttributeTypes.DATA_TYPE_UINT32, 1); PointAttribute.SPACING = new PointAttribute("SPACING", PointAttributeTypes.DATA_TYPE_FLOAT, 1); PointAttribute.GPS_TIME = new PointAttribute("GPS_TIME", PointAttributeTypes.DATA_TYPE_DOUBLE, 1); class PointAttributes { constructor(pointAttributes) { this.attributes = []; this.byteSize = 0; this.size = 0; this.vectors = []; if (pointAttributes != null) { for (var _i = 0; _i < pointAttributes.length; _i++) { var pointAttributeName = pointAttributes[_i]; var pointAttribute = PointAttribute[pointAttributeName]; this.attributes.push(pointAttribute); this.byteSize += pointAttribute.byteSize; this.size++; } } } add(pointAttribute) { this.attributes.push(pointAttribute); this.byteSize += pointAttribute.byteSize; this.size++; } addVector(vector) { this.vectors.push(vector); } hasNormals() { for (var name in this.attributes) { var pointAttribute = this.attributes[name]; if (pointAttribute === PointAttribute.NORMAL_SPHEREMAPPED || pointAttribute === PointAttribute.NORMAL_FLOATS || pointAttribute === PointAttribute.NORMAL || pointAttribute === PointAttribute.NORMAL_OCT16) { return true; } } return false; } } class Points$1 { constructor() { this.boundingBox = new Box3(); this.numPoints = 0; this.data = {}; } add(points) { var currentSize = this.numPoints; var additionalSize = points.numPoints; var newSize = currentSize + additionalSize; var thisAttributes = Object.keys(this.data); var otherAttributes = Object.keys(points.data); var attributes = new Set([...thisAttributes, ...otherAttributes]); for (var attribute of attributes) { if (thisAttributes.includes(attribute) && otherAttributes.includes(attribute)) { // attribute in both, merge var Type = this.data[attribute].constructor; var merged = new Type(this.data[attribute].length + points.data[attribute].length); merged.set(this.data[attribute], 0); merged.set(points.data[attribute], this.data[attribute].length); this.data[attribute] = merged; } else if (thisAttributes.includes(attribute) && !otherAttributes.includes(attribute)) { // attribute only in this; take over this and expand to new size var elementsPerPoint = this.data[attribute].length / this.numPoints; var _Type = this.data[attribute].constructor; var expanded = new _Type(elementsPerPoint * newSize); expanded.set(this.data[attribute], 0); this.data[attribute] = expanded; } else if (!thisAttributes.includes(attribute) && otherAttributes.includes(attribute)) { // attribute only in points to be added; take over new points and expand to new size var _elementsPerPoint = points.data[attribute].length / points.numPoints; var _Type2 = points.data[attribute].constructor; var _expanded = new _Type2(_elementsPerPoint * newSize); _expanded.set(points.data[attribute], _elementsPerPoint * currentSize); this.data[attribute] = _expanded; } } this.numPoints = newSize; this.boundingBox.union(points.boundingBox); } } class CSVExporter { static toString(points) { var string = ''; var attributes = Object.keys(points.data).filter(a => a !== 'normal').sort((a, b) => { if (a === 'position') return -1; if (b === 'position') return 1; if (a === 'rgba') return -1; if (b === 'rgba') return 1; }); var headerValues = []; for (var attribute of attributes) { var itemSize = points.data[attribute].length / points.numPoints; if (attribute === 'position') { headerValues = headerValues.concat(['x', 'y', 'z']); } else if (attribute === 'rgba') { headerValues = headerValues.concat(['r', 'g', 'b', 'a']); } else if (itemSize > 1) { for (var i = 0; i < itemSize; i++) { headerValues.push("".concat(attribute, "_").concat(i)); } } else { headerValues.push(attribute); } } string = headerValues.join(', ') + '\n'; for (var _i = 0; _i < points.numPoints; _i++) { var values = []; for (var _attribute of attributes) { var _itemSize = points.data[_attribute].length / points.numPoints; var value = points.data[_attribute].subarray(_itemSize * _i, _itemSize * _i + _itemSize).join(', '); values.push(value); } string += values.join(', ') + '\n'; } return string; } } ; class LASExporter { static toLAS(points) { // TODO Unused: let string = ''; var boundingBox = points.boundingBox; var offset = boundingBox.min.clone(); var diagonal = boundingBox.min.distanceTo(boundingBox.max); var scale = new Vector3(0.001, 0.001, 0.001); if (diagonal > 1000 * 1000) { scale = new Vector3(0.01, 0.01, 0.01); } else { scale = new Vector3(0.001, 0.001, 0.001); } var setString = function setString(string, offset, buffer) { var view = new Uint8Array(buffer); for (var i = 0; i < string.length; i++) { var charCode = string.charCodeAt(i); view[offset + i] = charCode; } }; var buffer = new ArrayBuffer(227 + 28 * points.numPoints); var view = new DataView(buffer); var u8View = new Uint8Array(buffer); // let u16View = new Uint16Array(buffer); setString('LASF', 0, buffer); u8View[24] = 1; u8View[25] = 2; // system identifier o:26 l:32 // generating software o:58 l:32 setString('Potree 1.7', 58, buffer); // file creation day of year o:90 l:2 // file creation year o:92 l:2 // header size o:94 l:2 view.setUint16(94, 227, true); // offset to point data o:96 l:4 view.setUint32(96, 227, true); // number of letiable length records o:100 l:4 // point data record format 104 1 u8View[104] = 2; // point data record length 105 2 view.setUint16(105, 28, true); // number of point records 107 4 view.setUint32(107, points.numPoints, true); // number of points by return 111 20 // x scale factor 131 8 view.setFloat64(131, scale.x, true); // y scale factor 139 8 view.setFloat64(139, scale.y, true); // z scale factor 147 8 view.setFloat64(147, scale.z, true); // x offset 155 8 view.setFloat64(155, offset.x, true); // y offset 163 8 view.setFloat64(163, offset.y, true); // z offset 171 8 view.setFloat64(171, offset.z, true); // max x 179 8 view.setFloat64(179, boundingBox.max.x, true); // min x 187 8 view.setFloat64(187, boundingBox.min.x, true); // max y 195 8 view.setFloat64(195, boundingBox.max.y, true); // min y 203 8 view.setFloat64(203, boundingBox.min.y, true); // max z 211 8 view.setFloat64(211, boundingBox.max.z, true); // min z 219 8 view.setFloat64(219, boundingBox.min.z, true); var boffset = 227; for (var i = 0; i < points.numPoints; i++) { var px = points.data.position[3 * i + 0]; var py = points.data.position[3 * i + 1]; var pz = points.data.position[3 * i + 2]; var ux = parseInt((px - offset.x) / scale.x); var uy = parseInt((py - offset.y) / scale.y); var uz = parseInt((pz - offset.z) / scale.z); view.setUint32(boffset + 0, ux, true); view.setUint32(boffset + 4, uy, true); view.setUint32(boffset + 8, uz, true); if (points.data.intensity) { view.setUint16(boffset + 12, points.data.intensity[i], true); } var rt = 0; if (points.data.returnNumber) { rt += points.data.returnNumber[i]; } if (points.data.numberOfReturns) { rt += points.data.numberOfReturns[i] << 3; } view.setUint8(boffset + 14, rt); if (points.data.classification) { view.setUint8(boffset + 15, points.data.classification[i]); } // scan angle rank // user data // point source id if (points.data.pointSourceID) { view.setUint16(boffset + 18, points.data.pointSourceID[i]); } if (points.data.rgba) { var rgba = points.data.rgba; view.setUint16(boffset + 20, rgba[4 * i + 0] * 255, true); view.setUint16(boffset + 22, rgba[4 * i + 1] * 255, true); view.setUint16(boffset + 24, rgba[4 * i + 2] * 255, true); } boffset += 28; } return buffer; } } /** * @author mrdoob / http://mrdoob.com/ https://github.com/mrdoob/eventdispatcher.js * * with slight modifications by mschuetz, http://potree.org * */ // The MIT License // // Copyright (c) 2011 Mr.doob // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. class EventDispatcher$1 { constructor() { this._listeners = {}; } addEventListener(type, listener) { var listeners = this._listeners; if (listeners[type] === undefined) { listeners[type] = []; } if (listeners[type].indexOf(listener) === -1) { listeners[type].push(listener); } } hasEventListener(type, listener) { var listeners = this._listeners; return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1; } removeEventListener(type, listener) { var listeners = this._listeners; var listenerArray = listeners[type]; if (listenerArray !== undefined) { var index = listenerArray.indexOf(listener); if (index !== -1) { listenerArray.splice(index, 1); } } } removeEventListeners(type) { if (this._listeners[type] !== undefined) { delete this._listeners[type]; } } dispatchEvent(event) { var listeners = this._listeners; var listenerArray = listeners[event.type]; if (listenerArray !== undefined) { event.target = this; for (var listener of listenerArray.slice(0)) { listener.call(this, event); } } } } class PointCloudTreeNode extends EventDispatcher$1 { constructor() { super(); this.needsTransformUpdate = true; } getChildren() { throw new Error('override function'); } getBoundingBox() { throw new Error('override function'); } isLoaded() { throw new Error('override function'); } isGeometryNode() { throw new Error('override function'); } isTreeNode() { throw new Error('override function'); } getLevel() { throw new Error('override function'); } getBoundingSphere() { throw new Error('override function'); } } ; class PointCloudTree extends Object3D { constructor() { super(); //this.spriteGroup = new THREE.Object3D //add } initialized() { return this.root !== null; } } ; class PointCloudOctreeGeometry { constructor() { this.url = null; this.octreeDir = null; this.spacing = 0; this.boundingBox = null; this.root = null; this.nodes = null; this.pointAttributes = null; this.hierarchyStepSize = -1; this.loader = null; } } class PointCloudOctreeGeometryNode extends PointCloudTreeNode { constructor(name, pcoGeometry, boundingBox) { super(); this.id = PointCloudOctreeGeometryNode.IDCount++; this.name = name; this.index = parseInt(name.charAt(name.length - 1)); this.pcoGeometry = pcoGeometry; this.geometry = null; this.boundingBox = boundingBox; this.boundingSphere = boundingBox.getBoundingSphere(new Sphere()); this.children = {}; this.numPoints = 0; this.level = null; this.loaded = false; this.oneTimeDisposeHandlers = []; } isGeometryNode() { return true; } getLevel() { return this.level; } isTreeNode() { return false; } isLoaded() { return this.loaded; } getBoundingSphere() { return this.boundingSphere; } getBoundingBox() { return this.boundingBox; } getChildren() { var children = []; for (var i = 0; i < 8; i++) { if (this.children[i]) { children.push(this.children[i]); } } return children; } getBoundingBox() { return this.boundingBox; } getURL() { var url = ''; var version = this.pcoGeometry.loader.version; if (version.equalOrHigher('1.5')) { url = this.pcoGeometry.octreeDir + '/' + this.getHierarchyPath() + '/' + this.name; } else if (version.equalOrHigher('1.4')) { url = this.pcoGeometry.octreeDir + '/' + this.name; } else if (version.upTo('1.3')) { url = this.pcoGeometry.octreeDir + '/' + this.name; } return url; } getHierarchyPath() { var path = 'r/'; var hierarchyStepSize = this.pcoGeometry.hierarchyStepSize; var indices = this.name.substr(1); var numParts = Math.floor(indices.length / hierarchyStepSize); for (var i = 0; i < numParts; i++) { path += indices.substr(i * hierarchyStepSize, hierarchyStepSize) + '/'; } path = path.slice(0, -1); return path; } addChild(child) { this.children[child.index] = child; child.parent = this; } load() { if (this.loading === true || this.loaded === true || Potree.numNodesLoading >= Potree.maxNodesLoading) { return; } this.loading = true; Potree.numNodesLoading++; if (this.pcoGeometry.loader.version.equalOrHigher('1.5')) { if (this.level % this.pcoGeometry.hierarchyStepSize === 0 && this.hasChildren) { this.loadHierachyThenPoints(); } else { this.loadPoints(); } } else { this.pcoGeometry.dispatchEvent({ type: 'updateNodeMaxLevel', level: this.level }); //add this.loadPoints(); } } loadPoints() { this.pcoGeometry.loader.load(this); } loadHierachyThenPoints() { var node = this; // load hierarchy var callback = function callback(node, hbuffer) { var tStart = performance.now(); var view = new DataView(hbuffer); var stack = []; var children = view.getUint8(0); var numPoints = view.getUint32(1, true); node.numPoints = numPoints; stack.push({ children: children, numPoints: numPoints, name: node.name }); var decoded = []; var offset = 5; while (stack.length > 0) { var snode = stack.shift(); var mask = 1; for (var i = 0; i < 8; i++) { if ((snode.children & mask) !== 0) { var childName = snode.name + i; var childChildren = view.getUint8(offset); var childNumPoints = view.getUint32(offset + 1, true); stack.push({ children: childChildren, numPoints: childNumPoints, name: childName }); decoded.push({ children: childChildren, numPoints: childNumPoints, name: childName }); offset += 5; } mask = mask * 2; } if (offset === hbuffer.byteLength) { break; } } // console.log(decoded); var nodes = {}; nodes[node.name] = node; var pco = node.pcoGeometry; for (var _i = 0; _i < decoded.length; _i++) { var name = decoded[_i].name; var decodedNumPoints = decoded[_i].numPoints; var index = parseInt(name.charAt(name.length - 1)); var parentName = name.substring(0, name.length - 1); var parentNode = nodes[parentName]; var level = name.length - 1; var boundingBox = Utils.createChildAABB(parentNode.boundingBox, index); var currentNode = new PointCloudOctreeGeometryNode(name, pco, boundingBox); currentNode.level = level; currentNode.numPoints = decodedNumPoints; currentNode.hasChildren = decoded[_i].children > 0; currentNode.spacing = pco.spacing / Math.pow(2, level); parentNode.addChild(currentNode); nodes[name] = currentNode; } var duration = performance.now() - tStart; if (duration > 5) { var msg = "duration: ".concat(duration, "ms, numNodes: ").concat(decoded.length); console.log(msg); } node.loadPoints(); }; if (node.level % node.pcoGeometry.hierarchyStepSize === 0) { // let hurl = node.pcoGeometry.octreeDir + "/../hierarchy/" + node.name + ".hrc"; var hurl = node.pcoGeometry.octreeDir + '/' + node.getHierarchyPath() + '/' + node.name + '.hrc'; var xhr = XHRFactory.createXMLHttpRequest(); xhr.open('GET', hurl, true); xhr.responseType = 'arraybuffer'; xhr.overrideMimeType('text/plain; charset=x-user-defined'); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status === 200 || xhr.status === 0) { var hbuffer = xhr.response; callback(node, hbuffer); } else { console.log('Failed to load file! HTTP status: ' + xhr.status + ', file: ' + hurl); Potree.numNodesLoading--; } } }; try { xhr.send(null); } catch (e) { console.log('fehler beim laden der punktwolke: ' + e); } } } getNumPoints() { return this.numPoints; } dispose() { if (this.geometry && this.parent != null) { this.geometry.dispose(); this.geometry = null; this.loaded = false; this.dispatchEvent({ type: 'dispose' }); for (var i = 0; i < this.oneTimeDisposeHandlers.length; i++) { var handler = this.oneTimeDisposeHandlers[i]; handler(); } this.oneTimeDisposeHandlers = []; } } } PointCloudOctreeGeometryNode.IDCount = 0; // ------------------------------------------- // to get a ready to use gradient array from a chroma.js gradient: // http://gka.github.io/chroma.js/ // ------------------------------------------- // // let stops = []; // for(let i = 0; i <= 10; i++){ // let range = chroma.scale(['yellow', 'navy']).mode('lch').domain([10,0])(i)._rgb // .slice(0, 3) // .map(v => (v / 255).toFixed(4)) // .join(", "); // // let line = `[${i / 10}, new THREE.Color(${range})],`; // // stops.push(line); // } // stops.join("\n"); // // // // ------------------------------------------- // to get a ready to use gradient array from matplotlib: // ------------------------------------------- // import matplotlib.pyplot as plt // import matplotlib.colors as colors // // norm = colors.Normalize(vmin=0,vmax=1) // cmap = plt.cm.viridis // // for i in range(0,11): // u = i / 10 // rgb = cmap(norm(u))[0:3] // rgb = ["{0:.3f}".format(v) for v in rgb] // rgb = "[" + str(u) + ", new THREE.Color(" + ", ".join(rgb) + ")]," // print(rgb) var Gradients = { // From chroma spectral http://gka.github.io/chroma.js/ SPECTRAL: [[0, new Color(0.3686, 0.3098, 0.6353)], [0.1, new Color(0.1961, 0.5333, 0.7412)], [0.2, new Color(0.4000, 0.7608, 0.6471)], [0.3, new Color(0.6706, 0.8667, 0.6431)], [0.4, new Color(0.9020, 0.9608, 0.5961)], [0.5, new Color(1.0000, 1.0000, 0.7490)], [0.6, new Color(0.9961, 0.8784, 0.5451)], [0.7, new Color(0.9922, 0.6824, 0.3804)], [0.8, new Color(0.9569, 0.4275, 0.2627)], [0.9, new Color(0.8353, 0.2431, 0.3098)], [1, new Color(0.6196, 0.0039, 0.2588)]], PLASMA: [[0.0, new Color(0.241, 0.015, 0.610)], [0.1, new Color(0.387, 0.001, 0.654)], [0.2, new Color(0.524, 0.025, 0.653)], [0.3, new Color(0.651, 0.125, 0.596)], [0.4, new Color(0.752, 0.227, 0.513)], [0.5, new Color(0.837, 0.329, 0.431)], [0.6, new Color(0.907, 0.435, 0.353)], [0.7, new Color(0.963, 0.554, 0.272)], [0.8, new Color(0.992, 0.681, 0.195)], [0.9, new Color(0.987, 0.822, 0.144)], [1.0, new Color(0.940, 0.975, 0.131)]], YELLOW_GREEN: [[0, new Color(0.1647, 0.2824, 0.3451)], [0.1, new Color(0.1338, 0.3555, 0.4227)], [0.2, new Color(0.0610, 0.4319, 0.4864)], [0.3, new Color(0.0000, 0.5099, 0.5319)], [0.4, new Color(0.0000, 0.5881, 0.5569)], [0.5, new Color(0.1370, 0.6650, 0.5614)], [0.6, new Color(0.2906, 0.7395, 0.5477)], [0.7, new Color(0.4453, 0.8099, 0.5201)], [0.8, new Color(0.6102, 0.8748, 0.4850)], [0.9, new Color(0.7883, 0.9323, 0.4514)], [1, new Color(0.9804, 0.9804, 0.4314)]], VIRIDIS: [[0.0, new Color(0.267, 0.005, 0.329)], [0.1, new Color(0.283, 0.141, 0.458)], [0.2, new Color(0.254, 0.265, 0.530)], [0.3, new Color(0.207, 0.372, 0.553)], [0.4, new Color(0.164, 0.471, 0.558)], [0.5, new Color(0.128, 0.567, 0.551)], [0.6, new Color(0.135, 0.659, 0.518)], [0.7, new Color(0.267, 0.749, 0.441)], [0.8, new Color(0.478, 0.821, 0.318)], [0.9, new Color(0.741, 0.873, 0.150)], [1.0, new Color(0.993, 0.906, 0.144)]], INFERNO: [[0.0, new Color(0.077, 0.042, 0.206)], [0.1, new Color(0.225, 0.036, 0.388)], [0.2, new Color(0.373, 0.074, 0.432)], [0.3, new Color(0.522, 0.128, 0.420)], [0.4, new Color(0.665, 0.182, 0.370)], [0.5, new Color(0.797, 0.255, 0.287)], [0.6, new Color(0.902, 0.364, 0.184)], [0.7, new Color(0.969, 0.516, 0.063)], [0.8, new Color(0.988, 0.683, 0.072)], [0.9, new Color(0.961, 0.859, 0.298)], [1.0, new Color(0.988, 0.998, 0.645)]], GRAYSCALE: [[0, new Color(0, 0, 0)], [1, new Color(1, 1, 1)]], // 16 samples of the TURBU color scheme // values taken from: https://gist.github.com/mikhailov-work/ee72ba4191942acecc03fe6da94fc73f // original file licensed under Apache-2.0 TURBO: [[0.00, new Color(0.18995, 0.07176, 0.23217)], [0.07, new Color(0.25107, 0.25237, 0.63374)], [0.13, new Color(0.27628, 0.42118, 0.89123)], [0.20, new Color(0.25862, 0.57958, 0.99876)], [0.27, new Color(0.15844, 0.73551, 0.92305)], [0.33, new Color(0.09267, 0.86554, 0.7623)], [0.40, new Color(0.19659, 0.94901, 0.59466)], [0.47, new Color(0.42778, 0.99419, 0.38575)], [0.53, new Color(0.64362, 0.98999, 0.23356)], [0.60, new Color(0.80473, 0.92452, 0.20459)], [0.67, new Color(0.93301, 0.81236, 0.22667)], [0.73, new Color(0.99314, 0.67408, 0.20348)], [0.80, new Color(0.9836, 0.49291, 0.12849)], [0.87, new Color(0.92105, 0.31489, 0.05475)], [0.93, new Color(0.81608, 0.18462, 0.01809)], [1.00, new Color(0.66449, 0.08436, 0.00424)]], RAINBOW: [[0, new Color(0.278, 0, 0.714)], [1 / 6, new Color(0, 0, 1)], [2 / 6, new Color(0, 1, 1)], [3 / 6, new Color(0, 1, 0)], [4 / 6, new Color(1, 1, 0)], [5 / 6, new Color(1, 0.64, 0)], [1, new Color(1, 0, 0)]], CONTOUR: [[0.00, new Color(0, 0, 0)], [0.03, new Color(0, 0, 0)], [0.04, new Color(1, 1, 1)], [1.00, new Color(1, 1, 1)]] }; var Shaders = {}; Shaders["pointcloud_new.vs"] = "\nprecision highp float;\nprecision highp int;\n \n#define PI 3.141592653589793\n\n \n\n\n\n#if defined(usePanoMap) \n \n uniform samplerCube pano0Map; //\u968F\u4FBF\u8BBE\u7F6E\u4E00\u4E2AsamplerCube\u53BB\u4F7F\u7528\u90FD\u4F1A\u8BA9\u70B9\u4E91\u6D88\u5931\n uniform samplerCube pano1Map;\n \n uniform float progress;\n uniform float easeInOutRatio;\n\n \n uniform vec3 pano0Position;\n uniform mat4 pano0Matrix; \n uniform vec3 pano1Position;\n uniform mat4 pano1Matrix;\n /*\n varying vec3 vWorldPosition0;\n varying vec3 vWorldPosition1;\n */\n#endif \n\n\n\n\n \n\n//--------------\n\n\n\n\n\nattribute vec3 position;\nattribute vec3 color;\nattribute float intensity;\nattribute float classification;\nattribute float returnNumber;\nattribute float numberOfReturns;\nattribute float pointSourceID;\nattribute vec4 indices; //\u6BCF\u4E2A\u70B9\u7684index\nattribute float spacing;\nattribute float gpsTime;\nattribute vec3 normal;\nattribute float aExtra;\n\nuniform mat4 modelMatrix;\nuniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nuniform mat4 viewMatrix;\nuniform mat4 uViewInv;\n\n//uniform float uScreenWidth;\n//uniform float uScreenHeight;\nuniform vec2 resolution;\n\n\nuniform float fov;\nuniform float near;\nuniform float far;\n\n\n\n\nuniform bool uDebug;\n\nuniform bool uUseOrthographicCamera;\nuniform float uOrthoWidth;\nuniform float uOrthoHeight;\n\n#define CLIPTASK_NONE 0\n#define CLIPTASK_HIGHLIGHT 1\n#define CLIPTASK_SHOW_INSIDE 2\n#define CLIPTASK_SHOW_OUTSIDE 3\n\n#define CLIPMETHOD_INSIDE_ANY 0\n#define CLIPMETHOD_INSIDE_ALL 1\n\n//\u6700\u5916\u5C42\u88C1\u526A\uFF08\u4E0B\u8F7D\uFF09\n#if defined(bigClipInBox)\n\tuniform mat4 clipBoxBig_in;\n#endif\n//\u5185\u5C42\u88C1\u526A\n#if defined(num_in_clipboxes) && num_in_clipboxes > 0\n\tuniform mat4 clipBoxes_in[num_in_clipboxes];\n#endif\n#if defined(num_out_clipboxes) && num_out_clipboxes > 0\n\tuniform mat4 clipBoxes_out[num_out_clipboxes];\n#endif\n\n\n#if defined(num_clipspheres) && num_clipspheres > 0\n\tuniform mat4 uClipSpheres[num_clipspheres];\n#endif\n\n \n#if defined(num_highlightBox) && num_highlightBox > 0\n uniform mat4 boxes_highlight[num_highlightBox]; \n#endif \n\t\t \n\n#if defined(num_prism) && num_prism > 0\n uniform mat3 prismList[num_prism];\n uniform vec2 prismPoints[prismPointCountSum]; \n#endif \n\n#if defined(showBaseHeight) \n uniform sampler2D baseHeightAreaMap ;\n uniform vec2 baseHeightBoundZ;\n uniform vec4 baseHeightBoundXY; \n#endif \n\nuniform float size;\nuniform float minSize;\nuniform float maxSize; \nuniform float orthoMaxSize;//add\n\n\nuniform float uPCIndex;\nuniform float uOctreeSpacing;\nuniform float uNodeSpacing;\nuniform float uOctreeSize;\nuniform vec3 uBBSize;\nuniform float uLevel;\nuniform float levelPercent;//add\nuniform float uVNStart;\nuniform bool uIsLeafNode;\n\nuniform vec3 uColor;\nuniform float uOpacity; \nvarying float vOpacity; //add\n\n\n\nuniform vec2 elevationRange;\nuniform vec2 intensityRange;\n\nuniform vec2 uFilterReturnNumberRange;\nuniform vec2 uFilterNumberOfReturnsRange;\nuniform vec2 uFilterPointSourceIDClipRange;\nuniform vec2 uFilterGPSTimeClipRange;\n//uniform float ufilterByNormalThreshold; \n\nuniform float uGpsScale;\nuniform float uGpsOffset;\n\nuniform vec2 uNormalizedGpsBufferRange;\n\nuniform vec3 uIntensity_gbc;\nuniform vec3 uRGB_gbc;\nuniform vec3 uExtra_gbc;\n\nuniform float uTransition;\nuniform float wRGB;\nuniform float wIntensity;\nuniform float wElevation;\nuniform float wClassification;\nuniform float wReturnNumber;\nuniform float wSourceID;\n\nuniform vec2 uExtraNormalizedRange;\nuniform vec2 uExtraRange;\nuniform float uExtraScale;\nuniform float uExtraOffset;\n\nuniform vec3 uShadowColor;\n\nuniform sampler2D visibleNodes;\nuniform sampler2D gradient;\nuniform sampler2D classificationLUT;\n\n#if defined(color_type_matcap)\nuniform sampler2D matcapTextureUniform;\n#endif\nuniform bool backfaceCulling;\n\n#if defined(num_shadowmaps) && num_shadowmaps > 0\nuniform sampler2D uShadowMap[num_shadowmaps];\nuniform mat4 uShadowWorldView[num_shadowmaps];\nuniform mat4 uShadowProj[num_shadowmaps];\n#endif\n\n\n\nvarying vec3\tvColor;\nvarying float\tvLogDepth;\nvarying vec3\tvViewPosition;\nvarying float \tvRadius;\nvarying float \tvPointSize;\n\n\nfloat Round(float number){\n\treturn floor(number + 0.5);\n}\n\n// \n// ### ######## ### ######## ######## #### ## ## ######## ###### #### ######## ######## ###### \n// ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## \n// ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## \n// ## ## ## ## ## ## ######## ## ## ## ## ###### ###### ## ## ###### ###### \n// ######### ## ## ######### ## ## ## ## ## ## ## ## ## ## ## \n// ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## \n// ## ## ######## ## ## ## ## #### ### ######## ###### #### ######## ######## ###### \n// \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\n\n// ---------------------\n// OCTREE\n// ---------------------\n\n#if (defined(adaptive_point_size) || defined(color_type_level_of_detail)) && defined(tree_type_octree)\n/**\n * number of 1-bits up to inclusive index position\n * number is treated as if it were an integer in the range 0-255\n *\n */\nint numberOfOnes(int number, int index){\n\tint numOnes = 0;\n\tint tmp = 128;\n\tfor(int i = 7; i >= 0; i--){\n\t\t\n\t\tif(number >= tmp){\n\t\t\tnumber = number - tmp;\n\n\t\t\tif(i <= index){\n\t\t\t\tnumOnes++;\n\t\t\t}\n\t\t}\n\t\t\n\t\ttmp = tmp / 2;\n\t}\n\n\treturn numOnes;\n}\n\n\n/**\n * checks whether the bit at index is 1\n * number is treated as if it were an integer in the range 0-255\n *\n */\nbool isBitSet(int number, int index){\n\n\t// weird multi else if due to lack of proper array, int and bitwise support in WebGL 1.0\n\tint powi = 1;\n\tif(index == 0){\n\t\tpowi = 1;\n\t}else if(index == 1){\n\t\tpowi = 2;\n\t}else if(index == 2){\n\t\tpowi = 4;\n\t}else if(index == 3){\n\t\tpowi = 8;\n\t}else if(index == 4){\n\t\tpowi = 16;\n\t}else if(index == 5){\n\t\tpowi = 32;\n\t}else if(index == 6){\n\t\tpowi = 64;\n\t}else if(index == 7){\n\t\tpowi = 128;\n\t}else{\n\t\treturn false;\n\t}\n\n\tint ndp = number / powi;\n\n\treturn mod(float(ndp), 2.0) != 0.0;\n}\n\n\n/**\n * find the LOD at the point position\n */\nfloat getLOD(){//////we use this\n\t \n\tvec3 offset = vec3(0.0, 0.0, 0.0);\n\tint iOffset = int(uVNStart);\n\tfloat depth = uLevel;\n\tfor(float i = 0.0; i <= 30.0; i++){\n\t\tfloat nodeSizeAtLevel = uOctreeSize / pow(2.0, i + uLevel + 0.0);\n\t\t\n\t\tvec3 index3d = (position-offset) / nodeSizeAtLevel;\n\t\tindex3d = floor(index3d + 0.5);\n\t\tint index = int(Round(4.0 * index3d.x + 2.0 * index3d.y + index3d.z));\n\t\t\n\t\tvec4 value = texture2D(visibleNodes, vec2(float(iOffset) / 2048.0, 0.0));\n\t\tint mask = int(Round(value.r * 255.0));\n\n\t\tif(isBitSet(mask, index)){\n\t\t\t// there are more visible child nodes at this position\n\t\t\tint advanceG = int(Round(value.g * 255.0)) * 256;\n\t\t\tint advanceB = int(Round(value.b * 255.0));\n\t\t\tint advanceChild = numberOfOnes(mask, index - 1);\n\t\t\tint advance = advanceG + advanceB + advanceChild;\n\n\t\t\tiOffset = iOffset + advance;\n\t\t\t\n\t\t\tdepth++;\n\t\t}else{\n\t\t\t// no more visible child nodes at this position\n\t\t\t//return value.a * 255.0;\n\n\t\t\tfloat lodOffset = (255.0 * value.a) / 10.0 - 10.0;\n\n\t\t\treturn depth + lodOffset;\n\t\t}\n\t\t\n\t\toffset = offset + (vec3(1.0, 1.0, 1.0) * nodeSizeAtLevel * 0.5) * index3d;\n\t}\n\t\t\n\treturn depth;\n}\n\nfloat getSpacing(){\n\tvec3 offset = vec3(0.0, 0.0, 0.0);\n\tint iOffset = int(uVNStart);\n\tfloat depth = uLevel;\n\tfloat spacing = uNodeSpacing;\n\tfor(float i = 0.0; i <= 30.0; i++){\n\t\tfloat nodeSizeAtLevel = uOctreeSize / pow(2.0, i + uLevel + 0.0);\n\t\t\n\t\tvec3 index3d = (position-offset) / nodeSizeAtLevel;\n\t\tindex3d = floor(index3d + 0.5);\n\t\tint index = int(Round(4.0 * index3d.x + 2.0 * index3d.y + index3d.z));\n\t\t\n\t\tvec4 value = texture2D(visibleNodes, vec2(float(iOffset) / 2048.0, 0.0));\n\t\tint mask = int(Round(value.r * 255.0));\n\t\tfloat spacingFactor = value.a;\n\n\t\tif(i > 0.0){\n\t\t\tspacing = spacing / (255.0 * spacingFactor);\n\t\t}\n\t\t\n\n\t\tif(isBitSet(mask, index)){\n\t\t\t// there are more visible child nodes at this position\n\t\t\tint advanceG = int(Round(value.g * 255.0)) * 256;\n\t\t\tint advanceB = int(Round(value.b * 255.0));\n\t\t\tint advanceChild = numberOfOnes(mask, index - 1);\n\t\t\tint advance = advanceG + advanceB + advanceChild;\n\n\t\t\tiOffset = iOffset + advance;\n\n\t\t\t//spacing = spacing / (255.0 * spacingFactor);\n\t\t\t//spacing = spacing / 3.0;\n\t\t\t\n\t\t\tdepth++;\n\t\t}else{\n\t\t\t// no more visible child nodes at this position\n\t\t\treturn spacing;\n\t\t}\n\t\t\n\t\toffset = offset + (vec3(1.0, 1.0, 1.0) * nodeSizeAtLevel * 0.5) * index3d;\n\t}\n\t\t\n\treturn spacing;\n}\n\nfloat getPointSizeAttenuation(){\n\treturn pow(2.0, getLOD());\n}\n\n\n#endif\n\n\n// ---------------------\n// KD-TREE\n// ---------------------\n\n#if (defined(adaptive_point_size) || defined(color_type_level_of_detail)) && defined(tree_type_kdtree)\n\nfloat getLOD(){\n\tvec3 offset = vec3(0.0, 0.0, 0.0);\n\tfloat iOffset = 0.0;\n\tfloat depth = 0.0;\n\t\t\n\t\t\n\tvec3 size = uBBSize;\t\n\tvec3 pos = position;\n\t\t\n\tfor(float i = 0.0; i <= 1000.0; i++){\n\t\t\n\t\tvec4 value = texture2D(visibleNodes, vec2(iOffset / 2048.0, 0.0));\n\t\t\n\t\tint children = int(value.r * 255.0);\n\t\tfloat next = value.g * 255.0;\n\t\tint split = int(value.b * 255.0);\n\t\t\n\t\tif(next == 0.0){\n\t\t \treturn depth;\n\t\t}\n\t\t\n\t\tvec3 splitv = vec3(0.0, 0.0, 0.0);\n\t\tif(split == 1){\n\t\t\tsplitv.x = 1.0;\n\t\t}else if(split == 2){\n\t\t \tsplitv.y = 1.0;\n\t\t}else if(split == 4){\n\t\t \tsplitv.z = 1.0;\n\t\t}\n\t\t\n\t\tiOffset = iOffset + next;\n\t\t\n\t\tfloat factor = length(pos * splitv / size);\n\t\tif(factor < 0.5){\n\t\t\t// left\n\t\tif(children == 0 || children == 2){\n\t\t\t\treturn depth;\n\t\t\t}\n\t\t}else{\n\t\t\t// right\n\t\t\tpos = pos - size * splitv * 0.5;\n\t\t\tif(children == 0 || children == 1){\n\t\t\t\treturn depth;\n\t\t\t}\n\t\t\tif(children == 3){\n\t\t\t\tiOffset = iOffset + 1.0;\n\t\t\t}\n\t\t}\n\t\tsize = size * ((1.0 - (splitv + 1.0) / 2.0) + 0.5);\n\t\t\n\t\tdepth++;\n\t}\n\t\t\n\t\t\n\treturn depth;\t\n}\n\nfloat getPointSizeAttenuation(){\n\treturn 0.5 * pow(1.3, getLOD());\n}\n\n#endif\n\n\n\n// \n// ### ######## ######## ######## #### ######## ## ## ######## ######## ###### \n// ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## \n// ## ## ## ## ## ## ## ## ## ## ## ## ## ## \n// ## ## ## ## ######## ## ######## ## ## ## ###### ###### \n// ######### ## ## ## ## ## ## ## ## ## ## ## ## \n// ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## \n// ## ## ## ## ## ## #### ######## ####### ## ######## ###### \n// \n\n\n\n// formula adapted from: http://www.dfstudios.co.uk/articles/programming/image-programming-algorithms/image-processing-algorithms-part-5-contrast-adjustment/\nfloat getContrastFactor(float contrast){\n\treturn (1.0158730158730156 * (contrast + 1.0)) / (1.0158730158730156 - contrast);\n}\n\nvec3 getRGB(){\n\tvec3 rgb = color;\n\t\n\trgb = pow(rgb, vec3(uRGB_gbc.x));\n\trgb = rgb + uRGB_gbc.y;\n\trgb = (rgb - 0.5) * getContrastFactor(uRGB_gbc.z) + 0.5;\n\trgb = clamp(rgb, 0.0, 1.0);\n\n\treturn rgb;\n}\n\nfloat getIntensity(){\n\tfloat w = (intensity - intensityRange.x) / (intensityRange.y - intensityRange.x);\n\tw = pow(w, uIntensity_gbc.x);\n\tw = w + uIntensity_gbc.y;\n\tw = (w - 0.5) * getContrastFactor(uIntensity_gbc.z) + 0.5;\n\tw = clamp(w, 0.0, 1.0);\n\n\treturn w;\n}\n\nvec3 getGpsTime(){\n\n\tfloat w = (gpsTime + uGpsOffset) * uGpsScale;\n\n\n\tvec3 c = texture2D(gradient, vec2(w, 1.0 - w)).rgb;\n\n\n\t// vec2 r = uNormalizedGpsBufferRange;\n\t// float w = gpsTime * (r.y - r.x) + r.x;\n\t// w = clamp(w, 0.0, 1.0);\n\t// vec3 c = texture2D(gradient, vec2(w,1.0-w)).rgb;\n\t\n\treturn c;\n}\n\nvec3 getElevation(vec4 world){ \n\tfloat w = (world.z - elevationRange.x) / (elevationRange.y - elevationRange.x);\n\tvec3 cElevation = texture2D(gradient, vec2(w,1.0-w)).rgb;\n\treturn cElevation;\n}\n\nvec4 getClassification(){\n\tvec2 uv = vec2(classification / 255.0, 0.5);\n\tvec4 classColor = texture2D(classificationLUT, uv);\n\t\n\treturn classColor;\n}\n\nvec3 getReturns(){\n\n\t// 0b 00_000_111\n\tfloat rn = mod(returnNumber, 8.0);\n\t// 0b 00_111_000\n\tfloat nr = mod(returnNumber / 8.0, 8.0);\n\n\tif(nr <= 1.0){\n\t\treturn vec3(1.0, 0.0, 0.0);\n\t}else{\n\t\treturn vec3(0.0, 1.0, 0.0);\n\t}\n\n\t// return vec3(nr / 4.0, 0.0, 0.0);\n\n\t// if(nr == 1.0){\n\t// \treturn vec3(1.0, 1.0, 0.0);\n\t// }else{\n\t// \tif(rn == 1.0){\n\t// \t\treturn vec3(1.0, 0.0, 0.0);\n\t// \t}else if(rn == nr){\n\t// \t\treturn vec3(0.0, 0.0, 1.0);\n\t// \t}else{\n\t// \t\treturn vec3(0.0, 1.0, 0.0);\n\t// \t}\n\t// }\n\n\t// if(numberOfReturns == 1.0){\n\t// \treturn vec3(1.0, 1.0, 0.0);\n\t// }else{\n\t// \tif(returnNumber == 1.0){\n\t// \t\treturn vec3(1.0, 0.0, 0.0);\n\t// \t}else if(returnNumber == numberOfReturns){\n\t// \t\treturn vec3(0.0, 0.0, 1.0);\n\t// \t}else{\n\t// \t\treturn vec3(0.0, 1.0, 0.0);\n\t// \t}\n\t// }\n}\n\nvec3 getReturnNumber(){\n\tif(numberOfReturns == 1.0){\n\t\treturn vec3(1.0, 1.0, 0.0);\n\t}else{\n\t\tif(returnNumber == 1.0){\n\t\t\treturn vec3(1.0, 0.0, 0.0);\n\t\t}else if(returnNumber == numberOfReturns){\n\t\t\treturn vec3(0.0, 0.0, 1.0);\n\t\t}else{\n\t\t\treturn vec3(0.0, 1.0, 0.0);\n\t\t}\n\t}\n}\n\nvec3 getNumberOfReturns(){\n\tfloat value = numberOfReturns;\n\n\tfloat w = value / 6.0;\n\n\tvec3 color = texture2D(gradient, vec2(w, 1.0 - w)).rgb;\n\n\treturn color;\n}\n\nvec3 getSourceID(){\n\tfloat w = mod(pointSourceID, 10.0) / 10.0;\n\treturn texture2D(gradient, vec2(w,1.0 - w)).rgb;\n}\n\nvec3 getCompositeColor(vec4 world){\n\tvec3 c;\n\tfloat w;\n\n\tc += wRGB * getRGB();\n\tw += wRGB;\n\t\n\tc += wIntensity * getIntensity() * vec3(1.0, 1.0, 1.0);\n\tw += wIntensity;\n\t\n\tc += wElevation * getElevation(world);\n\tw += wElevation;\n\t\n\tc += wReturnNumber * getReturnNumber();\n\tw += wReturnNumber;\n\t\n\tc += wSourceID * getSourceID();\n\tw += wSourceID;\n\t\n\tvec4 cl = wClassification * getClassification();\n\tc += cl.a * cl.rgb;\n\tw += wClassification * cl.a;\n\n\tc = c / w;\n\t\n\tif(w == 0.0){\n\t\t//c = color;\n\t\tgl_Position = vec4(100.0, 100.0, 100.0, 0.0);\n\t}\n\t\n\treturn c;\n}\n\n\nvec3 getNormal(){\n\t//vec3 n_hsv = vec3( modelMatrix * vec4( normal, 0.0 )) * 0.5 + 0.5; // (n_world.xyz + vec3(1.,1.,1.)) / 2.;\n\tvec3 n_view = normalize( vec3(modelViewMatrix * vec4( normal, 0.0 )) );\n\treturn n_view;\n}\nbool applyBackfaceCulling() {\n\t// Black not facing vertices / Backface culling\n \n\tvec3 e = normalize(vec3(modelViewMatrix * vec4( position, 1. )));\n\tvec3 n = getNormal(); // normalize( vec3(modelViewMatrix * vec4( normal, 0.0 )) );\n\n\tif((uUseOrthographicCamera && n.z <= 0.) || (!uUseOrthographicCamera && dot( n, e ) >= 0.)) { \n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}\n\n#if defined(color_type_matcap)\n// Matcap Material\nvec3 getMatcap(){ \n\tvec3 eye = normalize( vec3( modelViewMatrix * vec4( position, 1. ) ) ); \n\tif(uUseOrthographicCamera) { \n\t\teye = vec3(0., 0., -1.);\n\t}\n\tvec3 r_en = reflect( eye, getNormal() ); // or r_en = e - 2. * dot( n, e ) * n;\n\tfloat m = 2. * sqrt(pow( r_en.x, 2. ) + pow( r_en.y, 2. ) + pow( r_en.z + 1., 2. ));\n\tvec2 vN = r_en.xy / m + .5;\n\treturn texture2D(matcapTextureUniform, vN).rgb; \n}\n#endif\n\nvec3 getExtra(){\n\n\tfloat w = (aExtra + uExtraOffset) * uExtraScale;\n\tw = clamp(w, 0.0, 1.0);\n\n\tvec3 color = texture2D(gradient, vec2(w,1.0-w)).rgb;\n\n\t// vec2 r = uExtraNormalizedRange;\n\n\t// float w = aExtra * (r.y - r.x) + r.x;\n\n\t// w = (w - uExtraRange.x) / (uExtraRange.y - uExtraRange.x);\n\n\t// w = clamp(w, 0.0, 1.0);\n\n\t// vec3 color = texture2D(gradient, vec2(w,1.0-w)).rgb;\n\n\treturn color;\n}\n\nvec3 getColor(vec4 world){\n\tvec3 color;\n\t\n\t#ifdef color_type_rgba\n\t\tcolor = getRGB();\n \n \n\t#elif defined color_type_height || defined color_type_elevation\n\t\tcolor = getElevation(world);\n\t#elif defined color_type_rgb_height\n\t\tvec3 cHeight = getElevation();\n\t\tcolor = (1.0 - uTransition) * getRGB() + uTransition * cHeight;\n\t#elif defined color_type_depth\n\t\tfloat linearDepth = gl_Position.w;\n\t\tfloat expDepth = (gl_Position.z / gl_Position.w) * 0.5 + 0.5;\n\t\tcolor = vec3(linearDepth, expDepth, 0.0);\n\t\t//color = vec3(1.0, 0.5, 0.3);\n\t#elif defined color_type_intensity\n\t\tfloat w = getIntensity();\n\t\tcolor = vec3(w, w, w);\n\t#elif defined color_type_gps_time\n\t\tcolor = getGpsTime();\n\t#elif defined color_type_intensity_gradient\n\t\tfloat w = getIntensity();\n\t\tcolor = texture2D(gradient, vec2(w,1.0-w)).rgb;\n\t#elif defined color_type_color\n\t\tcolor = uColor;\n\t#elif defined color_type_level_of_detail\n\t\tfloat depth = getLOD();\n\t\tfloat w = depth / 10.0;\n\t\tcolor = texture2D(gradient, vec2(w,1.0-w)).rgb;\n\t#elif defined color_type_indices\n\t\tcolor = indices.rgb;\n\t#elif defined color_type_classification\n\t\tvec4 cl = getClassification(); \n\t\tcolor = cl.rgb;\n\t#elif defined color_type_return_number\n\t\tcolor = getReturnNumber();\n\t#elif defined color_type_returns\n\t\tcolor = getReturns();\n\t#elif defined color_type_number_of_returns\n\t\tcolor = getNumberOfReturns();\n\t#elif defined color_type_source_id\n\t\tcolor = getSourceID();\n\t#elif defined color_type_point_source_id\n\t\tcolor = getSourceID();\n\t#elif defined color_type_normal\n\t\tcolor = (modelMatrix * vec4(normal, 0.0)).xyz;\n\t#elif defined color_type_phong\n\t\tcolor = color;\n\t#elif defined color_type_composite\n\t\tcolor = getCompositeColor(world);\n\t#elif defined color_type_matcap\n\t\tcolor = getMatcap();\n\t#elif defined color_type_heightCpt //add\n color = vec3(0.0,0.0,0.0);\n #else\n\t\tcolor = getExtra();\n\t#endif\n\t\n\tif (backfaceCulling && applyBackfaceCulling()){\n //color = vec3(0.);\n }\n //applyBackfaceCulling\u76F4\u63A5\u8FD4\u56DEfalse\u6216\u8005\u6CE8\u91CAcolor = vec3(0.);\u90FD\u6CA1\u95EE\u9898\n\treturn color;\n}\n\nfloat getPointSize(){\n\tfloat pointSize = 1.0;\n\tfloat maxSize_ = maxSize;\n\tfloat slope = tan(fov / 2.0);\n\tfloat projFactor = -0.5 * resolution.y / (slope * vViewPosition.z);\n \n \n \n /*\n\tfloat scale = length(\n\t\tmodelViewMatrix * vec4(0, 0, 0, 1) - \n\t\tmodelViewMatrix * vec4(uOctreeSpacing, 0, 0, 1)\n\t) / uOctreeSpacing;\n \n\tprojFactor = projFactor * scale;\n\t*/\n \n \n\tfloat r = uOctreeSpacing * 1.7;\n\t//vRadius = r;\n \n \n\t#if defined fixed_point_size\n\t\tpointSize = size;\n\t#elif defined attenuated_point_size\n\t\tif(uUseOrthographicCamera){ \n pointSize = size / uOrthoWidth * resolution.x; //\u6539\u6210\u8FD1\u4F3Cadaptive_point_size\u6839\u636E\u7A97\u53E3\u7F29\u653E\u3002\u5176\u5B9E\u5C31\u662Fsize * zoom (size\u5355\u4F4D\u8F6C\u5316\u4E3A\u7C73\uFF0C\u5982size\u4E3A1\u4EE3\u8868\u4E00\u4E2A\u70B9\u4E91\u5728\u573A\u666F\u4E2D1\u7C73\u5BBD,zoom\u4EE3\u88681px=1/zoom\u7C73)\n maxSize_ = orthoMaxSize; //for panoEditor, when zoom in, need more details, rather than always same size\n\n\t\t}else{ //\u8FD1\u5927\u8FDC\u5C0F\uFF0C\u6A21\u62DF\u771F\u5B9Emesh\uFF0C\u8FB9\u7F18\u653E\u5927\n\t\t\t//pointSize = size * spacing * projFactor; //spacing\u662Fattribute \u4E3A\u7A7A \u5982\u679C\u6709\u8FD9\u4E2A\u503C\u5C31\u80FD\u66F4\u81EA\u9002\u5E94\u586B\u8865\n //pointSize = size * uOctreeSpacing * projFactor / 18.0; //\u76F4\u63A5\u7528cloud\u7684spacing\u91CC\uFF0C\u4E0D\u8FC7\u56E0\u4E3A\u90FD\u4E00\u6837\u6240\u4EE5\u53EF\u80FD\u6CA1\u6709\u4EC0\u4E48\u610F\u4E49\n\t\t\t//pointSize = pointSize * projFactor;\n pointSize = size * projFactor ;\n\t\t}\n \n\t#elif defined adaptive_point_size\n\t\tif(uUseOrthographicCamera) {\n\t\t\tfloat worldSpaceSize = 1.0 * size * r / getPointSizeAttenuation();\n\t\t\tpointSize = (worldSpaceSize / uOrthoWidth) * resolution.x; //uScreenWidth;\n maxSize_ = orthoMaxSize;\n\t\t} else {\n\t\t\tfloat worldSpaceSize = 1.0 * size * r / getPointSizeAttenuation();\n\t\t\tpointSize = worldSpaceSize * projFactor;\n\t\t}\n \n\t#endif\n\n\tpointSize = max(minSize, pointSize);\n\tpointSize = min(maxSize_, pointSize);\n\t\n\tvRadius = pointSize / projFactor;\n\n\treturn pointSize;\n} \n\n\nbool insideBox(mat4 clipBox, vec4 worldPos){//add\n vec4 clipPosition = clipBox * worldPos;\n bool inside = -0.5 <= clipPosition.x && clipPosition.x <= 0.5;\n inside = inside && -0.5 <= clipPosition.y && clipPosition.y <= 0.5;\n inside = inside && -0.5 <= clipPosition.z && clipPosition.z <= 0.5;\n\n return inside;\n}\n\n\n\n#if defined(color_type_heightCpt)\n vec3 percentToByte(float num){\n //\u8F93\u51FA\u662F0-1\uFF0C shader\u7CBE\u5EA6\u4E0D\u591F\uFF0C\u53EA\u591F\u5B583\u4E2A\u6570\n float a = 1.0;\n float result[4];\n for(int i=0;i<3;i++){\n a = i == 2 ? a/255.0 : a / 256.0 ; \n //\u5206\u6210256\u4EFD\uFF0C\u5176\u4E2D255\u4EFD\u7ED9\u5F53\u524D\u4F4D\u7F6E\uFF0C\u6700\u540E\u4E00\u4EFD\u7ED9\u540E\u4E00\u4E2A\u4F4D\u7F6E\uFF0C\u800C\u5230\u4E86\u6700\u540E\u4E00\u4E2A\u4F4D\u7F6E\u65F6\u6CA1\u6709\u4E0B\u4E00\u4E2A\u4F4D\u7F6E\u4E86\u6240\u4EE5\u53EA\u5206\u6210255\u4EFD\n if(num > a){\n float c = num / a;\n float r = floor(c);\n r = min(255.0, r);\n result[i] = r;\n num -= r * a;\n }else{\n result[i] = 0.0;\n }\n } \n return vec3(result[0]/255.0, result[1]/255.0,result[2]/255.0); \n \n //\u9664\u4EE5\u591A\u5C11255\u8FD8\u662F256? \u53C2\u8003uPCIndex / 255.0 \u5E94\u8BE5\u662F255\n } \n#endif\n\n \n\n#if defined(num_prism) && num_prism > 0\n \n \n int insidePrism(mat3 prismInfo, int pointIndexStart, vec4 worldPos){//\u662F\u5426\u5728\u68F1\u67F1\u91CC \n \n float zMin = prismInfo[0][0];\n float zMid = prismInfo[0][1];\n float zMax = prismInfo[0][2]; \n float xMin = prismInfo[1][0];\n float xMax = prismInfo[1][1];\n float yMin = prismInfo[1][2];\n float yMax = prismInfo[2][0]; \n\n int pointCount = int(Round(prismInfo[2][1]));\n \n if( worldPos.x < xMin || worldPos.x > xMax || worldPos.y < yMin || worldPos.y > yMax)return 0;\n #ifndef showBaseHeight\n if( worldPos.z < zMin || worldPos.z > zMax) return 0;\n #endif\n \n \n bool inside = false;\n \n int j=pointCount-1;\n \n for(int i=0; i=pointCount)break;\n float xi = prismPoints[i+pointIndexStart].x, yi = prismPoints[i+pointIndexStart].y, xj = prismPoints[j+pointIndexStart].x, yj = prismPoints[j+pointIndexStart].y;\n\n if(((yi > worldPos.y) != (yj > worldPos.y)) && (worldPos.x < (xj - xi) * (worldPos.y - yi) / (yj - yi) + xi)){\n inside = !inside;\n }\n j=i; \n }\n \n if(inside){\n #ifdef showBaseHeight\n return 1;\n #else \n #ifdef color_type_heightCpt \n vColor = percentToByte((worldPos.z - zMin) / (zMax - zMin)); \n #endif \n #endif\n \n return worldPos.z < zMid ? 1 : 2;\n }else return 0; \n } \n \n#endif\n\n#ifdef showBaseHeight\n float byteToFloat(vec3 color){ \n float percent = 0.0;\n float a = 1.0; \n for(int i=0;i<3;i++){\n a = i == 2 ? a/255.0 : a/256.0; \n percent += a * color[i] ;\n }\n return percent * 255.0 ; \n } \n \n#endif\n\n\n \n\n\nvoid doClipping(vec4 world){\n\n\t{\n\t\tvec4 cl = getClassification(); \n\t\tif(cl.a == 0.0){\n\t\t\tgl_Position = vec4(100.0, 100.0, 100.0, 0.0);\n\t\t\t\n\t\t\treturn;\n\t\t}\n\t}\n\n\t#if defined(clip_return_number_enabled)\n\t{ // return number filter\n\t\tvec2 range = uFilterReturnNumberRange;\n\t\tif(returnNumber < range.x || returnNumber > range.y){\n\t\t\tgl_Position = vec4(100.0, 100.0, 100.0, 0.0);\n\t\t\t\n\t\t\treturn;\n\t\t}\n\t}\n\t#endif\n\n\t#if defined(clip_number_of_returns_enabled)\n\t{ // number of return filter\n\t\tvec2 range = uFilterNumberOfReturnsRange;\n\t\tif(numberOfReturns < range.x || numberOfReturns > range.y){\n\t\t\tgl_Position = vec4(100.0, 100.0, 100.0, 0.0);\n\t\t\t\n\t\t\treturn;\n\t\t}\n\t}\n\t#endif\n\n\t#if defined(clip_gps_enabled)\n\t{ // GPS time filter\n\t\tfloat time = (gpsTime + uGpsOffset) * uGpsScale;\n\t\tvec2 range = uFilterGPSTimeClipRange;\n\n\t\tif(time < range.x || time > range.y){\n\t\t\tgl_Position = vec4(100.0, 100.0, 100.0, 0.0);\n\t\t\t\n\t\t\treturn;\n\t\t}\n\t}\n\t#endif\n\n\t#if defined(clip_point_source_id_enabled)\n\t{ // point source id filter\n\t\tvec2 range = uFilterPointSourceIDClipRange;\n\t\tif(pointSourceID < range.x || pointSourceID > range.y){\n\t\t\tgl_Position = vec4(100.0, 100.0, 100.0, 0.0);\n\t\t\t\n\t\t\treturn;\n\t\t}\n\t}\n\t#endif\n\n\t \n\n\n //\u603B\u5171\u4E09\u79CDbox : \u6700\u5916\u5C42\u53EF\u89C1\u3001\u5185\u5C42\u53EF\u89C1\u548C\u4E0D\u53EF\u89C1(\u5916\u5C42\u53EF\u89C1\u548C\u5185\u5C42\u53EF\u89C1\u662F\u4EA4\u96C6\uFF0C\u5185\u5C42\u53EF\u89C1\u548C\u5185\u5C42\u4E0D\u53EF\u89C1\u662F\u5E76\u96C6)\n \n #if defined(bigClipInBox) \n if(!insideBox(clipBoxBig_in, world)){ \n gl_Position = vec4(100.0, 100.0, 100.0, 1.0);\n return;;\n } \n #endif \n \n #if defined(num_in_clipboxes) && num_in_clipboxes > 0\n //\u5F53\u6709\u53EF\u89C1box\u65F6\uFF0C\u9700\u8981\u5728\u4EFB\u4E00\u53EF\u89C1box\u5185\u624D\u53EF\u89C1\n bool visi1 = false;\n\t\tfor(int i = 0; i < num_in_clipboxes; i++){ \n if(insideBox(clipBoxes_in[i], world)){\n visi1 = true;\n break;\n } \n\t\t}\n if(!visi1){\n gl_Position = vec4(100.0, 100.0, 100.0, 1.0);\n return;\n }\n\t#endif\n\n\n #if defined(num_out_clipboxes) && num_out_clipboxes > 0\n //\u5F53\u6709\u4E0D\u53EF\u89C1box\u65F6\uFF0C\u4E0D\u5728\u6240\u6709\u4E0D\u53EF\u89C1box\u5185\u624D\u53EF\u89C1\n bool visi2 = true;\n\t\tfor(int i = 0; i < num_out_clipboxes; i++){ \n if(insideBox(clipBoxes_out[i], world)){\n visi2 = false;\n break;\n } \n\t\t}\n if(!visi2){\n gl_Position = vec4(100.0, 100.0, 100.0, 1.0);\n return;\n }\n\t#endif \n \n \n #if defined(num_highlightBox) && num_highlightBox > 0\n //\u5F53\u6709\u9AD8\u4EAEbox\u65F6\uFF0C\u9700\u8981\u5728\u4EFB\u4E00\u53EF\u89C1\u9AD8\u4EAE\u5185\u90FD\u9AD8\u5BBD\n bool highlight = false;\n\t\tfor(int i = 0; i < num_highlightBox; i++){ \n if(insideBox(boxes_highlight[i], world)){\n highlight = true;\n break;\n } \n\t\t}\n if(highlight){\n vColor.r += 0.5; \n }\n\t#endif\n \n \n \n int highlight_ = 0; \n \n #if defined(num_prism) && num_prism > 0 \n //\u57FA\u4E8Eprism\u68F1\u67F1\u7684\u571F\u65B9\u91CF\u663E\u793A\u6216\u8BA1\u7B97\n \n int pointIndexStart = 0;\n\t\tfor(int i = 0; i < num_prism; i++){ \n highlight_ = insidePrism(prismList[i], pointIndexStart, world);\n \n if(highlight_>0){ \n #if !defined(showBaseHeight) && !defined(color_type_heightCpt)\n if(highlight_ == 1){\n vColor.r += 0.5; \n }else if(highlight_ == 2){\n vColor.g += 0.5;\n }\n #endif\n \n break;\n }\n \n \n pointIndexStart += int(Round(prismList[i][2][1])); \n\t\t} \n \n #ifdef color_type_heightCpt \n if(highlight_==0){ \n gl_Position = vec4(100.0, 100.0, 100.0, 1.0); //unvisible\n return;\n }\n #endif \n \n\t#endif\n \n \n \n \n #ifdef showBaseHeight\n //\u57FA\u4E8E\u6A21\u578B\u7684\u571F\u65B9\u91CF\u663E\u793A\u6216\u8BA1\u7B97\n bool outsidePrism = false;\n #if defined(num_prism) && num_prism > 0//\u9AD8\u4EAE\u4EA4\u96C6\n if( highlight_ == 0 ){\n outsidePrism = true;\n }\n #endif \n \n if(!outsidePrism){\n \n float zMin = baseHeightBoundZ.x; \n float zMax = baseHeightBoundZ.y; \n float xMin = baseHeightBoundXY.x;\n float xMax = baseHeightBoundXY.y;\n float yMin = baseHeightBoundXY.z;\n float yMax = baseHeightBoundXY.w; \n \n bool inside = false;\n if(world.z < zMin || world.z > zMax || world.x < xMin || world.x > xMax || world.y < yMin || world.y > yMax){\n inside = false;\n }else{\n vec2 uv = vec2((world.x - xMin) / (xMax - xMin), (world.y - yMin) / (yMax - yMin) );\n \n vec4 color = texture2D(baseHeightAreaMap,uv);\n //\u6297\u952F\u9F7F\u5F85\u5199\n \n \n if(color.a==1.0){ \n \n float currentHeight = (world.z - zMin) / (zMax - zMin) ; \n \n #ifdef color_type_heightCpt\n /*float diff = currentHeight - baseHeight;\n if(diff<0.0){\n diff = -diff;\n vOpacity = 0.5;//\u9700\u8981\u900F\u660E\u901A\u9053\uFF0C\u5BB9\u6613\u51FA\u9519\n }else{\n vOpacity = 1.0;\n }\n vColor = percentToByte(diff); \n */ \n vColor = percentToByte(currentHeight);\n //vColor = color.rgb;\n vOpacity = 1.0;\n \n #else\n //vColor = color.rgb;\n float baseHeight = byteToFloat(color.rgb);\n if(currentHeight > baseHeight){\n vColor.g += 0.5; \n }else{\n vColor.r += 0.5; \n }\n #endif\n \n inside = true;\n }else{\n inside = false;\n }\n \n \n \n } \n \n if(inside == false){\n #ifdef color_type_heightCpt\n gl_Position = vec4(100.0, 100.0, 100.0, 1.0); //unvisible\n return;\n #endif\n }\n \n }\n\t#endif\n}\n\n\n\n// \n// ## ## ### #### ## ## \n// ### ### ## ## ## ### ## \n// #### #### ## ## ## #### ## \n// ## ### ## ## ## ## ## ## ## \n// ## ## ######### ## ## #### \n// ## ## ## ## ## ## ### \n// ## ## ## ## #### ## ## \n//\n\n\nvec2 getSamplerCoord( vec3 direction ) \n{\n direction = normalize(direction);\n float tx=atan(direction.x,-direction.y)/(PI*2.0)+0.5;\n float ty=acos(direction.z)/PI;\n\n return vec2(tx,ty);\n} \n\nvec3 transformAxis( vec3 direction ) //navvis->4dkk\n{\n float y = direction.y;\n direction.y = direction.z;\n direction.z = -y;\n return direction;\n}\n\nvoid main() {\n //bool filtered_by_normal = false; \n float normalZ = 0.0;\n\n\n\n #ifdef use_filter_by_normal\n /*if(abs(getNormal().z) > 0.4) { //ufilterByNormalThreshold \u6682\u5B9A 3\n\t\t\t// Move point outside clip space space to discard it.\n\t\t\t//gl_Position = vec4(0.0, 0.0, 2.0, 1.0); //gl_Position\u7684\u53EF\u89C6\u533A\u57DF\u662F x,y,z\u90FD\u662F[-1,1] \n //return;\n //filtered_by_normal = true; //\u6807\u8BB0\u4E00\u4E0B\u3002\u4E0D\u76F4\u63A5\u4E0D\u7ED8\u5236\uFF0C\u56E0\u4E3A\u6709\u7684\u6CD5\u7EBF\u90FD\u662F\u5782\u76F4\u5411\u4E0A\n \n\t\t}*/\n \n normalZ = abs(getNormal().z);\n #endif\n \n \n vec4 worldPos = modelMatrix * vec4(position, 1.0); \n vec4 mvPosition = modelViewMatrix * vec4(position, 1.0 ); //vec4 mvPosition = viewMatrix * worldPos;\n vViewPosition = mvPosition.xyz;\n gl_Position = projectionMatrix * mvPosition;\n vLogDepth = log2(-mvPosition.z);\n \n \n \n // COLOR\n //\u52A0-------------------\n #if defined(usePanoMap)\n \n vec3 positionLocalToPanoCenter0 = worldPos.xyz - pano0Position;\n vec3 vWorldPosition0 = (vec4(positionLocalToPanoCenter0, 1.0) * pano0Matrix).xyz; \n vWorldPosition0.x *= -1.0;\n vWorldPosition0 = transformAxis(vWorldPosition0);\n \n vec3 positionLocalToPanoCenter1 = worldPos.xyz - pano1Position;\n vec3 vWorldPosition1 = (vec4(positionLocalToPanoCenter1, 1.0) * pano1Matrix).xyz; \n vWorldPosition1.x *= -1.0;\n vWorldPosition1 = transformAxis(vWorldPosition1);\n \n /*\n vec2 samplerCoord0 = getSamplerCoord(vWorldPosition0.xyz);\n vec2 samplerCoord1 = getSamplerCoord(vWorldPosition1.xyz); \n vec4 colorFromPano0 = texture2D(pano0Map,samplerCoord0);\n vec4 colorFromPano1 = texture2D(pano1Map,samplerCoord1);\n */\n \n \n \n \n vec4 colorFromPano0=textureCube(pano0Map,vWorldPosition0.xyz);\n vec4 colorFromPano1=textureCube(pano1Map,vWorldPosition1.xyz);\n\n vColor = mix(colorFromPano0,colorFromPano1,progress).xyz; \n\n \n //float easeInOutRatio = 0.0; //\u7F13\u51B2\uFF0C\u6E10\u53D8\u70B9\u4E91\u5230\u8D34\u56FE\u7684\u989C\u8272 \n if(progress < easeInOutRatio){\n float easeProgress = (easeInOutRatio - progress) / easeInOutRatio;\n vec3 vColor1 = getColor(worldPos);\n vColor = mix(vColor,vColor1,easeProgress); \n }else if(progress > 1.0 - easeInOutRatio){ \n float easeProgress = (progress - (1.0 - easeInOutRatio) ) / easeInOutRatio;\n vec3 vColor1 = getColor(worldPos);\n vColor = mix(vColor,vColor1,easeProgress); \n }\n \n\n #else\n \n vColor = getColor(worldPos);\n \n #endif\n \n \n //------------------- \n \n if(uOpacity>=1.0 || uUseOrthographicCamera){ \n vOpacity = uOpacity; \n \n \n if(uOpacity<1.0){ //uUseOrthographicCamera \n //\u9632\u6B62\u7F29\u5C0F\u540E\u70B9\u4E91\u51E0\u4E4E\u770B\u4E0D\u89C1 \n vOpacity *= 4.0-3.0 * levelPercent; \n \n }\n \n }else{ //#ifdef attenuated_opacity zoom\u4E0D\u4F1A\u6539\u53D8z \u6240\u4EE5\u8FD9\u5E76\u4E0D\u662F\u7528\u5728\u5206\u5C4F\u65F6\u5019\u7684\n float v = -gl_Position.z-1.0 ; // \u8303\u56F4\u4ECE-2\u52300\uFF0C e\u7684-2\u52300\u6B21\u65B9\u7684\u8303\u56F4\u662F0.818\u52301 \n //vOpacity = uOpacity * exp(v/ (levelPercent * 20.0 ) ); \n \n //\u8FD1\u5904\u52A0\u6DF1\uFF0C\u8FDC\u5904\u53D8\u6DE1 gl_Position.z\u4F3C\u4E4E\u671D\u5411\u5C4F\u5E55\u91CC\u4E3A\u6B63\n float r = clamp( pow(1.1, v/10.0 ), 0.1, 1.0 ); //\u9664\u4EE5\u7684\u6570\u5B57\u8D8A\u5927\uFF0C\u8FD1\u9AD8\u8FDC\u4F4E\u7684\u7A0B\u5EA6\u8D8A\u5C0F\uFF0C\u8303\u56F4\u8D8A\u957F\u3002 \u7A0B\u5EA6\u592A\u9AD8\u8FDC\u5904\u5355\u8584\u7684\u533A\u57DF\u770B\u4E0D\u89C1 pow\u7684\u5E95\u6570\u8D8A\u5927\u6539\u53D8\u7387\u8D8A\u5927\n vOpacity = uOpacity * r ;\n \n \n } \n \n vOpacity *= max(0.3, pow((1.0 - normalZ),5.0));//\u5782\u76F4\u671D\u76F8\u673A\u65F6\u964D\u4F4E\u900F\u660E\u5EA6 \n //vOpacity = clamp(vOpacity, 0.0, 1.0); \n\n\n\n // POINT SIZE\n float pointSize = getPointSize();\n \n gl_PointSize = pointSize;\n vPointSize = pointSize;\n\n \n \n \n \n\n // only for \"replacing\" approaches\n // if(getLOD() != uLevel){\n // \tgl_Position = vec4(10.0, 10.0, 10.0, 1.0);\n // }\n\n\n #if defined hq_depth_pass\n float originalDepth = gl_Position.w;\n float adjustedDepth = originalDepth + 2.0 * vRadius;\n float adjust = adjustedDepth / originalDepth;\n\n mvPosition.xyz = mvPosition.xyz * adjust;\n gl_Position = projectionMatrix * mvPosition;\n #endif\n\n\n // CLIPPING\n doClipping(worldPos);\n\n #if defined(num_clipspheres) && num_clipspheres > 0\n for(int i = 0; i < num_clipspheres; i++){\n vec4 sphereLocal = uClipSpheres[i] * mvPosition;\n\n float distance = length(sphereLocal.xyz);\n\n if(distance < 1.0){\n float w = distance;\n vec3 cGradient = texture2D(gradient, vec2(w, 1.0 - w)).rgb;\n \n vColor = cGradient;\n //vColor = cGradient * 0.7 + vColor * 0.3;\n }\n }\n #endif\n\n #if defined(num_shadowmaps) && num_shadowmaps > 0\n\n const float sm_near = 0.1;\n const float sm_far = 10000.0;\n\n for(int i = 0; i < num_shadowmaps; i++){\n vec3 viewPos = (uShadowWorldView[i] * vec4(position, 1.0)).xyz;\n float distanceToLight = abs(viewPos.z);\n \n vec4 projPos = uShadowProj[i] * uShadowWorldView[i] * vec4(position, 1);\n vec3 nc = projPos.xyz / projPos.w;\n \n float u = nc.x * 0.5 + 0.5;\n float v = nc.y * 0.5 + 0.5;\n\n vec2 sampleStep = vec2(1.0 / (2.0*1024.0), 1.0 / (2.0*1024.0)) * 1.5;\n vec2 sampleLocations[9];\n sampleLocations[0] = vec2(0.0, 0.0);\n sampleLocations[1] = sampleStep;\n sampleLocations[2] = -sampleStep;\n sampleLocations[3] = vec2(sampleStep.x, -sampleStep.y);\n sampleLocations[4] = vec2(-sampleStep.x, sampleStep.y);\n\n sampleLocations[5] = vec2(0.0, sampleStep.y);\n sampleLocations[6] = vec2(0.0, -sampleStep.y);\n sampleLocations[7] = vec2(sampleStep.x, 0.0);\n sampleLocations[8] = vec2(-sampleStep.x, 0.0);\n\n float visibleSamples = 0.0;\n float numSamples = 0.0;\n\n float bias = vRadius * 2.0;\n\n for(int j = 0; j < 9; j++){\n vec4 depthMapValue = texture2D(uShadowMap[i], vec2(u, v) + sampleLocations[j]);\n\n float linearDepthFromSM = depthMapValue.x + bias;\n float linearDepthFromViewer = distanceToLight;\n\n if(linearDepthFromSM > linearDepthFromViewer){\n visibleSamples += 1.0;\n }\n\n numSamples += 1.0;\n }\n\n float visibility = visibleSamples / numSamples;\n\n if(u < 0.0 || u > 1.0 || v < 0.0 || v > 1.0 || nc.x < -1.0 || nc.x > 1.0 || nc.y < -1.0 || nc.y > 1.0 || nc.z < -1.0 || nc.z > 1.0){\n //vColor = vec3(0.0, 0.0, 0.2);\n }else{\n //vColor = vec3(1.0, 1.0, 1.0) * visibility + vec3(1.0, 1.0, 1.0) * vec3(0.5, 0.0, 0.0) * (1.0 - visibility);\n vColor = vColor * visibility + vColor * uShadowColor * (1.0 - visibility);\n }\n\n\n }\n\n #endif\n\n \n \n}\n"; Shaders["pointcloud_new.fs"] = "\n#if defined paraboloid_point_shape\n\t#extension GL_EXT_frag_depth : enable\n#endif\n#define PI 3.141592653589793\n\n\n\nprecision highp float;\nprecision highp int;\n\n/*\n#if defined(usePanoMap) \n \n uniform samplerCube pano0Map; //\u968F\u4FBF\u8BBE\u7F6E\u4E00\u4E2AsamplerCube\u53BB\u4F7F\u7528\u90FD\u4F1A\u8BA9\u70B9\u4E91\u6D88\u5931\n uniform samplerCube pano1Map;\n \n uniform float progress;\n uniform float easeInOutRatio;\n\n \n uniform vec3 pano0Position;\n uniform mat4 pano0Matrix; \n uniform vec3 pano1Position;\n uniform mat4 pano1Matrix;\n varying vec3 vWorldPosition0;\n varying vec3 vWorldPosition1;\n\n#endif \n*/\n\n\n\n//------------\n\n\n\n\n\nuniform mat4 viewMatrix;\nuniform mat4 uViewInv;\nuniform mat4 uProjInv;\nuniform vec3 cameraPosition;\n\n\nuniform mat4 projectionMatrix;\n//uniform float uOpacity;\nvarying float vOpacity; //add\n\nuniform float blendHardness;\nuniform float blendDepthSupplement;\nuniform float fov;\nuniform float uSpacing;\nuniform float near;\nuniform float far;\nuniform float uPCIndex;\nuniform float uScreenWidth;\nuniform float uScreenHeight;\n\nvarying vec3\tvColor;\nvarying float\tvLogDepth;\nvarying vec3\tvViewPosition;\nvarying float\tvRadius;\nvarying float \tvPointSize;\nvarying vec3 \tvPosition;\n\n\nfloat specularStrength = 1.0;\n\n\nvec2 getSamplerCoord( vec3 direction ) \n{\n direction = normalize(direction);\n float tx=atan(direction.x,-direction.y)/(PI*2.0)+0.5;\n float ty=acos(direction.z)/PI;\n\n return vec2(tx,ty);\n} \n\n\n\n\nvoid main() {\n\n vec3 color = vColor; \n\t \n \n /*#if defined(usePanoMap) //\u52A0 \u7ECF\u6D4B\u8BD5\uFF0C\u5373\u4F7F\u5168\u90E8\u5199\u5728fragment\u91CC\u4E5F\u662F\u65E0\u8BBApointsize\u591A\u5927\u90FD\u662F\u4E00\u4E2A\u70B9\u4E00\u4E2A\u989C\u8272\uFF0C\u6240\u4EE5\u5E72\u8106\u5199\u5728vectex\u91CC\n \n \n vec4 colorFromPano0=textureCube(pano0Map,vWorldPosition0.xyz);\n vec4 colorFromPano1=textureCube(pano1Map,vWorldPosition1.xyz);\n \n color = mix(colorFromPano0,colorFromPano1,progress).xyz; \n \n \n //float easeInOutRatio = 0.0; //\u7F13\u51B2\uFF0C\u6E10\u53D8\u70B9\u4E91\u5230\u8D34\u56FE\u7684\u989C\u8272 \n if(progress < easeInOutRatio){\n float easeProgress = (easeInOutRatio - progress) / easeInOutRatio; \n color = mix(color,vColor,easeProgress); \n }else if(progress > 1.0 - easeInOutRatio){ \n float easeProgress = (progress - (1.0 - easeInOutRatio) ) / easeInOutRatio; \n color = mix(color,vColor,easeProgress); \n }\n \n \n #else \n color = vColor;\n #endif*/\n \n \n \n\tfloat depth = gl_FragCoord.z;\n\n\t#if defined(circle_point_shape) || defined(paraboloid_point_shape) \n\t\tfloat u = 2.0 * gl_PointCoord.x - 1.0;\n\t\tfloat v = 2.0 * gl_PointCoord.y - 1.0;\n\t#endif\n\t\n\t#if defined(circle_point_shape) \n\t\tfloat cc = u*u + v*v;\n\t\tif(cc > 1.0){\n\t\t\tdiscard;\n\t\t}\n\t#endif\n\t\n\n \n\n\t\n \n #if defined color_type_indices //pick point recognize\n\t\tgl_FragColor = vec4(color, uPCIndex / 255.0); //uPCIndex : node Index\n\t#else\n\t\tgl_FragColor = vec4(color, vOpacity);\n\t#endif\n \n \n \n \n \n \n \n \n\n\t#if defined paraboloid_point_shape\n\t\tfloat wi = 0.0 - ( u*u + v*v);\n\t\tvec4 pos = vec4(vViewPosition, 1.0);\n\t\tpos.z += wi * vRadius;\n\t\tfloat linearDepth = -pos.z;\n\t\tpos = projectionMatrix * pos;\n\t\tpos = pos / pos.w;\n\t\tfloat expDepth = pos.z;\n\t\tdepth = (pos.z + 1.0) / 2.0;\n\t\tgl_FragDepthEXT = depth;\n\t\tgl_FragDepthEXT = clamp(gl_FragDepthEXT, 0.0, 1.0); //add\n \n \n\t\t#if defined(color_type_depth)\n\t\t\tcolor.r = linearDepth;\n\t\t\tcolor.g = expDepth;\n\t\t#endif\n\t\t\n\t\t#if defined(use_edl)\n\t\t\tgl_FragColor.a = log2(linearDepth);\n\t\t#endif\n\t\t\n\t#else\n\t\t#if defined(use_edl)\n\t\t\tgl_FragColor.a = vLogDepth;\n\t\t#endif\n\t#endif\n\n\t#if defined(weighted_splats)\n\t\tfloat distance = 2.0 * length(gl_PointCoord.xy - 0.5);\n\t\tfloat weight = max(0.0, 1.0 - distance);\n\t\tweight = pow(weight, 1.5);\n\n\t\tgl_FragColor.a = weight;\n\t\tgl_FragColor.xyz = gl_FragColor.xyz * weight;\n\t#endif\n\n\t//gl_FragColor = vec4(0.0, 0.7, 0.0, 1.0);\n\t\n}\n\n\n"; Shaders["pointcloud_sm.vs"] = "\nprecision mediump float;\nprecision mediump int;\n\nattribute vec3 position;\nattribute vec3 color;\n\nuniform mat4 modelMatrix;\nuniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nuniform mat4 viewMatrix;\n\nuniform float uScreenWidth;\nuniform float uScreenHeight;\nuniform float near;\nuniform float far;\n\nuniform float uSpacing;\nuniform float uOctreeSize;\nuniform float uLevel;\nuniform float uVNStart;\n\nuniform sampler2D visibleNodes;\n\nvarying float vLinearDepth;\nvarying vec3 vColor;\n\n#define PI 3.141592653589793\n\n\n\n// ---------------------\n// OCTREE\n// ---------------------\n\n#if defined(adaptive_point_size)\n/**\n * number of 1-bits up to inclusive index position\n * number is treated as if it were an integer in the range 0-255\n *\n */\nfloat numberOfOnes(float number, float index){\n\tfloat tmp = mod(number, pow(2.0, index + 1.0));\n\tfloat numOnes = 0.0;\n\tfor(float i = 0.0; i < 8.0; i++){\n\t\tif(mod(tmp, 2.0) != 0.0){\n\t\t\tnumOnes++;\n\t\t}\n\t\ttmp = floor(tmp / 2.0);\n\t}\n\treturn numOnes;\n}\n\n\n/**\n * checks whether the bit at index is 1\n * number is treated as if it were an integer in the range 0-255\n *\n */\nbool isBitSet(float number, float index){\n\treturn mod(floor(number / pow(2.0, index)), 2.0) != 0.0;\n}\n\n\n/**\n * find the LOD at the point position\n */\nfloat getLOD(){\n\t\n\tvec3 offset = vec3(0.0, 0.0, 0.0);\n\tfloat iOffset = uVNStart;\n\tfloat depth = uLevel;\n\tfor(float i = 0.0; i <= 30.0; i++){\n\t\tfloat nodeSizeAtLevel = uOctreeSize / pow(2.0, i + uLevel + 0.0);\n\t\t\n\t\tvec3 index3d = (position-offset) / nodeSizeAtLevel;\n\t\tindex3d = floor(index3d + 0.5);\n\t\tfloat index = 4.0 * index3d.x + 2.0 * index3d.y + index3d.z;\n\t\t\n\t\tvec4 value = texture2D(visibleNodes, vec2(iOffset / 2048.0, 0.0));\n\t\tfloat mask = value.r * 255.0;\n\t\tif(isBitSet(mask, index)){\n\t\t\t// there are more visible child nodes at this position\n\t\t\tiOffset = iOffset + value.g * 255.0 * 256.0 + value.b * 255.0 + numberOfOnes(mask, index - 1.0);\n\t\t\tdepth++;\n\t\t}else{\n\t\t\t// no more visible child nodes at this position\n\t\t\treturn depth;\n\t\t}\n\t\t\n\t\toffset = offset + (vec3(1.0, 1.0, 1.0) * nodeSizeAtLevel * 0.5) * index3d;\n\t}\n\t\t\n\treturn depth;\n}\n\n#endif\n\nfloat getPointSize(){\n\tfloat pointSize = 1.0;\n\t\n\tfloat slope = tan(fov / 2.0);\n\tfloat projFactor = -0.5 * uScreenHeight / (slope * vViewPosition.z);\n\t\n\tfloat r = uOctreeSpacing * 1.5;\n\tvRadius = r;\n\t#if defined fixed_point_size\n\t\tpointSize = size;\n\t#elif defined attenuated_point_size\n\t\tif(uUseOrthographicCamera){\n\t\t\tpointSize = size;\t\t\t\n\t\t}else{\n\t\t\tpointSize = pointSize * projFactor;\n\t\t}\n\t#elif defined adaptive_point_size\n\t\tif(uUseOrthographicCamera) {\n\t\t\tfloat worldSpaceSize = 1.5 * size * r / getPointSizeAttenuation();\n\t\t\tpointSize = (worldSpaceSize / uOrthoWidth) * uScreenWidth;\n\t\t} else {\n\t\t\tfloat worldSpaceSize = 1.5 * size * r / getPointSizeAttenuation();\n\t\t\tpointSize = worldSpaceSize * projFactor;\n\t\t}\n\t#endif\n\n\tpointSize = max(minSize, pointSize);\n\tpointSize = min(maxSize, pointSize);\n\t\n\tvRadius = pointSize / projFactor;\n\n\treturn pointSize;\n}\n\n\nvoid main() {\n\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tvLinearDepth = gl_Position.w;\n\n\tfloat pointSize = getPointSize();\n\tgl_PointSize = pointSize;\n\n}\n"; Shaders["pointcloud_sm.fs"] = "\nprecision mediump float;\nprecision mediump int;\n\nvarying vec3 vColor;\nvarying float vLinearDepth;\n\nvoid main() {\n\n\t//gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n\t//gl_FragColor = vec4(vColor, 1.0);\n\t//gl_FragColor = vec4(vLinearDepth, pow(vLinearDepth, 2.0), 0.0, 1.0);\n\tgl_FragColor = vec4(vLinearDepth, vLinearDepth / 30.0, vLinearDepth / 30.0, 1.0);\n\t\n}\n\n\n"; Shaders["normalize.vs"] = "\nprecision mediump float;\nprecision mediump int;\n\nattribute vec3 position;\nattribute vec2 uv;\n\nuniform mat4 projectionMatrix;\nuniform mat4 modelViewMatrix;\n\nvarying vec2 vUv;\n\nvoid main() {\n\tvUv = uv;\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);\n}"; Shaders["normalize.fs"] = "\n#extension GL_EXT_frag_depth : enable\n\nprecision mediump float;\nprecision mediump int;\n\nuniform sampler2D uWeightMap;\nuniform sampler2D uDepthMap;\n\nvarying vec2 vUv;\n\nvoid main() {\n\tfloat depth = texture2D(uDepthMap, vUv).r;\n\t\n\tif(depth >= 1.0){\n\t\tdiscard;\n\t}\n\n\tgl_FragColor = vec4(depth, 1.0, 0.0, 1.0);\n\n\tvec4 color = texture2D(uWeightMap, vUv); \n\tcolor = color / color.w;\n\t\n\tgl_FragColor = vec4(color.xyz, 1.0); \n\t\n\tgl_FragDepthEXT = depth;\n\n\n}"; Shaders["normalize_and_edl.fs"] = "\n#extension GL_EXT_frag_depth : enable\n\n// \n// adapted from the EDL shader code from Christian Boucheny in cloud compare:\n// https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL\n//\n\nprecision mediump float;\nprecision mediump int;\n\nuniform sampler2D uWeightMap;\nuniform sampler2D uEDLMap;\nuniform sampler2D uDepthMap;\n\nuniform float screenWidth;\nuniform float screenHeight;\nuniform vec2 neighbours[NEIGHBOUR_COUNT];\nuniform float edlStrength;\nuniform float radius;\n\nvarying vec2 vUv;\n\nfloat response(float depth){\n\tvec2 uvRadius = radius / vec2(screenWidth, screenHeight);\n\t\n\tfloat sum = 0.0;\n\t\n\tfor(int i = 0; i < NEIGHBOUR_COUNT; i++){\n\t\tvec2 uvNeighbor = vUv + uvRadius * neighbours[i];\n\t\t\n\t\tfloat neighbourDepth = texture2D(uEDLMap, uvNeighbor).a;\n\n\t\tif(neighbourDepth != 0.0){\n\t\t\tif(depth == 0.0){\n\t\t\t\tsum += 100.0;\n\t\t\t}else{\n\t\t\t\tsum += max(0.0, depth - neighbourDepth);\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn sum / float(NEIGHBOUR_COUNT);\n}\n\nvoid main() {\n\n\tfloat edlDepth = texture2D(uEDLMap, vUv).a;\n\tfloat res = response(edlDepth);\n\tfloat shade = exp(-res * 300.0 * edlStrength);\n\n\tfloat depth = texture2D(uDepthMap, vUv).r;\n\tif(depth >= 1.0 && res == 0.0){\n\t\tdiscard;\n\t}\n\t\n\tvec4 color = texture2D(uWeightMap, vUv); \n\tcolor = color / color.w;\n\tcolor = color * shade;\n\n\tgl_FragColor = vec4(color.xyz, 1.0); \n\n\tgl_FragDepthEXT = depth;\n}"; Shaders["edl_new.vs"] = "\nprecision mediump float;\nprecision mediump int;\n\nattribute vec3 position;\nattribute vec2 uv;\n\nuniform mat4 projectionMatrix;\nuniform mat4 modelViewMatrix;\n\nvarying vec2 vUv;\n\nvoid main() {\n\tvUv = uv;\n\t\n\tvec4 mvPosition = modelViewMatrix * vec4(position,1.0);\n\n\tgl_Position = projectionMatrix * mvPosition;\n}"; Shaders["edl_new.fs"] = "\n#extension GL_EXT_frag_depth : enable\n\n// \n// adapted from the EDL shader code from Christian Boucheny in cloud compare:\n// https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL\n//\n\nprecision mediump float;\nprecision mediump int;\n\n//uniform float screenWidth;\n//uniform float screenHeight;\nuniform vec2 resolution;\n\n\nuniform vec2 neighbours[NEIGHBOUR_COUNT];\nuniform float edlStrength;\nuniform float radius;\nuniform float opacity;\n\n//uniform float uNear;\n//uniform float uFar;\n\nuniform mat4 uProj;\n\nuniform sampler2D uEDLColor;\nuniform sampler2D uEDLDepth;\n\nvarying vec2 vUv;\n\nuniform int useEDL;\n\nfloat response(float depth){\n\tvec2 uvRadius = radius / resolution; //vec2(screenWidth, screenHeight);\n\t\n\tfloat sum = 0.0;\n\t\n\tfor(int i = 0; i < NEIGHBOUR_COUNT; i++){\n\t\tvec2 uvNeighbor = vUv + uvRadius * neighbours[i];\n\t\t//\u83B7\u53D6\u5468\u56F4\u516B\u4E2A\u683C\u5B50\u7684\u503C\n\t\tfloat neighbourDepth = texture2D(uEDLColor, uvNeighbor).a;\n\t\tneighbourDepth = (neighbourDepth == 1.0) ? 0.0 : neighbourDepth;\n\n\t\tif(neighbourDepth != 0.0){\n\t\t\t //if(depth == 0.0){\n\t\t\t //\tsum += 100.0;\n\t\t\t //}else{\n\t\t\t\tsum += max(0.0, depth - neighbourDepth); //\u83B7\u53D6\u5DEE\u503C\n\t\t\t //}\n\t\t}\n\t}\n\t\n\treturn sum / float(NEIGHBOUR_COUNT);\n}\n\nvoid main(){\n\tvec4 cEDL = texture2D(uEDLColor, vUv);\n\t\n\tfloat depth = cEDL.a;\n\tdepth = (depth == 1.0) ? 0.0 : depth;\n \n if(depth == 0.0){ //\u53BB\u6389\u8FD9\u53E5\u5C31\u80FD\u5728\u65E0\u70B9\u4E91\u50CF\u7D20\u7684\u5730\u65B9\u6E32\u67D3outline\uFF0C\u4F46\u4F1A\u906E\u4F4F\u5176\u4ED6mesh\n\t\tdiscard;\n\t}\n \n \n if(useEDL == 1){\n float res = response(depth); \n float shade = exp(-res * 300.0 * edlStrength); //\u81EA\u7136\u5E38\u6570e\u4E3A\u5E95\u7684\u6307\u6570\u51FD\u6570 \n const float min = 0.2; //add \u4F7F\u8FB9\u7F18\u8272\u53D8\u6D45 \u8303\u56F4\u4ECE0-1 \u53D8\u4E3Amin-1\n shade = shade * (1.0-min) + min;\n gl_FragColor = vec4(cEDL.rgb * shade, opacity); \n }else{//\u52A0 \u4E0D\u6539\u989C\u8272\u7684\u60C5\u51B5 \n gl_FragColor = vec4(cEDL.rgb, opacity);\n } \n //\u6CE8\u610F\uFF0CedlStrength\u8D8A\u5F3A\uFF0C\u5728\u76F8\u540Cdepth\u7684\u53E0\u653E\u7684\u70B9\u4E91\u95F4\u7684\u8F6E\u5ED3\u7EBF\u989C\u8272\u8D8A\u6DF1\n //\u4F5C\u7528\uFF1A\u52FE\u52D2\u8FB9\u7F18\uFF0C\u5F3A\u5316\u6DF1\u5EA6\u5DEE\u5F02\uFF0C\u6A21\u62DF\u9634\u5F71\uFF0C\u52A0\u5F3A\u7ED3\u6784\u7ACB\u4F53\u611F\n \n { // write regular hyperbolic depth values to depth buffer \u4FEE\u6539\u6DF1\u5EA6\n float dl = pow(2.0, depth);\n\n vec4 dp = uProj * vec4(0.0, 0.0, -dl, 1.0);\n float pz = dp.z / dp.w;\n float fragDepth = (pz + 1.0) / 2.0;\n\n gl_FragDepthEXT = fragDepth;\n }\n\t\n}\n"; Shaders["blur.vs"] = "\nvarying vec2 vUv;\n\nvoid main() {\n\tvUv = uv;\n\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);\n}"; Shaders["blur.fs"] = "\nuniform mat4 projectionMatrix;\n\nuniform float screenWidth;\nuniform float screenHeight;\nuniform float near;\nuniform float far;\n\nuniform sampler2D map;\n\nvarying vec2 vUv;\n\nvoid main() {\n\n\tfloat dx = 1.0 / screenWidth;\n\tfloat dy = 1.0 / screenHeight;\n\n\tvec3 color = vec3(0.0, 0.0, 0.0);\n\tcolor += texture2D(map, vUv + vec2(-dx, -dy)).rgb;\n\tcolor += texture2D(map, vUv + vec2( 0, -dy)).rgb;\n\tcolor += texture2D(map, vUv + vec2(+dx, -dy)).rgb;\n\tcolor += texture2D(map, vUv + vec2(-dx, 0)).rgb;\n\tcolor += texture2D(map, vUv + vec2( 0, 0)).rgb;\n\tcolor += texture2D(map, vUv + vec2(+dx, 0)).rgb;\n\tcolor += texture2D(map, vUv + vec2(-dx, dy)).rgb;\n\tcolor += texture2D(map, vUv + vec2( 0, dy)).rgb;\n\tcolor += texture2D(map, vUv + vec2(+dx, dy)).rgb;\n\n\tcolor = color / 9.0;\n\t\n\tgl_FragColor = vec4(color, 1.0);\n}"; Shaders["depthBasic.vs"] = "\n \n\nvarying vec2 vUv;\nvoid main() {\n \n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n} \n "; Shaders["depthBasic.fs"] = "varying vec2 vUv;\nuniform float opacity;\nuniform float mapScale;\nuniform vec3 baseColor;\n\n#if defined use_map\n uniform sampler2D map; \n \n vec4 getMapColor(vec4 color){ \n if(mapScale == 1.0){\n color = texture2D(map, vUv) * color; \n return color;\n }else{ \n vec2 uv = (vUv - 0.5) / mapScale + 0.5; \n if(uv.x > 1.0 || uv.y > 1.0 || uv.x < 0.0 || uv.y < 0.0){\n //color = vec4(0.0,0.0,0.0,0.0);\n discard;\n }else{\n color = texture2D(map, uv) * color; \n }\n return color; \n }\n }\n#endif\n \n\n #if defined(GL_EXT_frag_depth) && defined(useDepth)\n //\u4F3C\u4E4E\u901A\u8FC7gl.getExtension('EXT_frag_depth')\u5F97\u5230\u7684GL_EXT_frag_depth\n \n uniform sampler2D depthTexture;\n uniform float nearPlane;\n uniform float farPlane; \n uniform vec2 resolution;\n uniform vec2 viewportOffset; // viewportOffset \u8303\u56F4\u4ECE0-\u6574\u4E2A\u753B\u5E03\u7684\u50CF\u7D20\n uniform vec3 backColor;\n uniform float occlusionDistance;\n uniform float clipDistance;\n uniform float maxClipFactor;\n uniform float maxOcclusionFactor;\n //uniform bool uUseOrthographicCamera; \n\n float convertToLinear(float zValue)\n {\n //if(uUseOrthographicCamera){\n // return zValue*(farPlane-nearPlane)+nearPlane;\n //}else{ \n float z = zValue * 2.0 - 1.0;\n return (2.0 * nearPlane * farPlane) / (farPlane + nearPlane - z * (farPlane - nearPlane));\n //} \n }\n#endif\n \n \n \nvoid main() {\n \n \n vec4 color = vec4(baseColor, opacity);\n \n \n \n #if defined(GL_EXT_frag_depth) && defined(useDepth) \n // mixFactor and clipFactor define the color mixing proportion between the states of\n // full visibility and occluded visibility\n // and\n // full visibility and total invisibility\n \n float mixFactor = 0.0;\n float clipFactor = 0.0;\n \n \n // The linear depth value of the current fragment\n float fragDepth = convertToLinear(gl_FragCoord.z);\n\n // The coordinates of the current fragment in the depth texture\n vec2 depthTxtCoords = vec2(gl_FragCoord.x-viewportOffset.x, gl_FragCoord.y - viewportOffset.y) / resolution;\n //gl_FragCoord\u5927\u5C0F\u4E3A viewport client\u5927\u5C0F \n \n // The linear depth value of the pixel occupied by this fragment in the depth buffer\n float textureDepth = convertToLinear(texture2D(depthTexture, depthTxtCoords).r);\n\n // The difference between the two depths\n float delta = fragDepth - textureDepth;\n\n if (delta > 0.0)//\u5DEE\u8DDD\n {\n // occlusionDistance and clipDistance define the width of the respective zones and\n // mixFactor and clipFactor express the interpolation between the two colors depending on the position\n // of the current fragment withing those zones.\n \n \n mixFactor = clamp(delta / occlusionDistance, 0.0, maxOcclusionFactor);\n clipFactor = clamp(delta / clipDistance, 0.0, maxClipFactor);\n }\n \n // If the fragment is totally transparent, don't bother drawing it\n if (clipFactor == 1.0)\n {\n discard;\n }else{\n \n #if defined use_map\n color = getMapColor(color); \n #endif\n \n \n color = vec4(mix(color.rgb, backColor, mixFactor), color.a * (1.0 - clipFactor));\n }\n \n #else\n #if defined use_map\n color = getMapColor(color); \n #endif \n #endif\n \n gl_FragColor = color;\n \n}\n"; Shaders["copyCubeMap.vs"] = "varying vec3 vWorldPos;\nvec3 transformAxis( vec3 direction ) //navvis->4dkk\n{\n float y = direction.y;\n direction.y = direction.z;\n direction.z = -y;\n return direction;\n}\nvoid main() {\n vWorldPos = vec3(-position.x, -position.y, position.z);\n //vWorldPos = transformAxis(vWorldPos);\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n} \n "; Shaders["copyCubeMap.fs"] = "varying vec3 vWorldPos;\nuniform float alpha;\nuniform samplerCube tDiffuse;\n\n\nvoid main() {\n vec4 texColor = textureCube(tDiffuse, vWorldPos);\n gl_FragColor = vec4(texColor.rgb, texColor.a * alpha);\n} \n "; Shaders["basicTextured.vs"] = "varying vec2 vUv;\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n} \n "; Shaders["basicTextured.fs"] = "varying vec2 vUv;\nuniform float opacity;\n \n\n#ifdef HasMap\n uniform sampler2D map; \n#endif\n#ifdef HasColor\n uniform vec3 color;\n#endif\n\nvoid main() {\n vec4 color_;\n #ifdef HasColor\n color_ = vec4(color, opacity); \n #else\n color_ = vec4(1.0,1.0,1.0, opacity);\n #endif\n \n #ifdef HasMap\n vec4 texColor = texture2D(map, vUv); \n gl_FragColor = texColor * color_;\n \n /*#ifdef InverseColor\n bool inverse = false; //gl_FragColor.r < 0.3 || gl_FragColor.g < 0.3 || gl_FragColor.b < 0.3 ||\n \n //\u6DF1\u8272\u5B57\u548C\u767D\u8272\u5730\u9762\u8981\u53CD\u8F6C\n \n if(gl_FragColor.r > 0.9 && gl_FragColor.g > 0.9 && gl_FragColor.b > 0.9){\n //gl_FragColor.r = 1.0 - gl_FragColor.r;\n //gl_FragColor.g = 1.0 - gl_FragColor.g;\n //gl_FragColor.b = 1.0 - gl_FragColor.b; \n gl_FragColor = vec4(0.07,0.22, 0.5,1.0);\n }else{//\u6D77\u548C\u8349\u576A\u989C\u8272\u52A0\u6DF1\n \n gl_FragColor = texColor * vec4(0.3,0.5,0.7,1.0);\n } \n \n #endif*/\n \n #else\n gl_FragColor = color_;\n #endif\n \n \n}\n"; Shaders["skybox.vs"] = "uniform mat4 matrix; \nvarying vec3 vWorldPosition;\n\n\n\nvoid main() \n{ \n \n vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz ; // - cameraPosition; \n vWorldPosition = (vec4(vWorldPosition, 1.0) * matrix).xyz;\n vWorldPosition.x *= -1.0;\n\n\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}"; Shaders["skybox.fs"] = "varying vec3 vWorldPosition;\nuniform sampler2D tDiffuse; \n\n#define PI 3.141592653 \n\n/*vec2 getSamplerCoord( vec3 direction ) \n{\n direction = normalize(direction);\n float tx=atan(direction.x,direction.z)/(PI*2.0)+0.5;\n float ty=acos(direction.y)/PI;\n\n return vec2(tx,ty);\n}*/\nvec2 getSamplerCoord( vec3 direction ) \n{\n direction = normalize(direction);\n float tx=atan(direction.x,-direction.y)/(PI*2.0)+0.5;\n float ty=acos(direction.z)/PI;\n\n return vec2(tx,ty);\n} \nvoid main() \n{\n vec2 samplerCoord = getSamplerCoord(vWorldPosition);\n vec4 color = texture2D(tDiffuse, samplerCoord);\n //gl_FragColor = RGBEToLinear( color ); //\u5BF9\u4E8Ehdr\u5FC5\u987B\u52A0\u8FD9\u4E00\u53E5\uFF0C\u5426\u5219\u6548\u679C\u5F88\u5947\u602A\u3002copy\u81EAmeshBasicMaterial\u91CC\u7684mat_fragment\u7684mapTexelToLinear\u51FD\u6570\uFF0C\u53EA\u8981\u6709map\u5C31\u4F1A\u4F7F\u7528\u8BE5\u51FD\u6570\n gl_FragColor = color;\n //#include \n //////#include \n\n} \n"; var ClassificationScheme = { DEFAULT: { 0: { visible: true, name: 'never classified', color: [0.5, 0.5, 0.5, 1.0] }, 1: { visible: true, name: 'unclassified', color: [0.5, 0.5, 0.5, 1.0] }, 2: { visible: true, name: 'ground', color: [0.63, 0.32, 0.18, 1.0] }, 3: { visible: true, name: 'low vegetation', color: [0.0, 1.0, 0.0, 1.0] }, 4: { visible: true, name: 'medium vegetation', color: [0.0, 0.8, 0.0, 1.0] }, 5: { visible: true, name: 'high vegetation', color: [0.0, 0.6, 0.0, 1.0] }, 6: { visible: true, name: 'building', color: [1.0, 0.66, 0.0, 1.0] }, 7: { visible: true, name: 'low point(noise)', color: [1.0, 0.0, 1.0, 1.0] }, 8: { visible: true, name: 'key-point', color: [1.0, 0.0, 0.0, 1.0] }, 9: { visible: true, name: 'water', color: [0.0, 0.0, 1.0, 1.0] }, 12: { visible: true, name: 'overlap', color: [1.0, 1.0, 0.0, 1.0] }, DEFAULT: { visible: true, name: 'default', color: [0.3, 0.6, 0.6, 0.5] } } }; Object.defineProperty(ClassificationScheme, 'RANDOM', { get: function get() { var scheme = {}; for (var i = 0; i <= 255; i++) { scheme[i] = new Vector4(Math.random(), Math.random(), Math.random()); } scheme["DEFAULT"] = new Vector4(Math.random(), Math.random(), Math.random()); return scheme; } }); class EnumItem { constructor(object) { for (var key of Object.keys(object)) { this[key] = object[key]; } } inspect() { return "Enum(".concat(this.name, ": ").concat(this.value, ")"); } } ; class Enum { constructor(object) { this.object = object; for (var key of Object.keys(object)) { var value = object[key]; if (typeof value === "object") { value.name = key; } else { value = { name: key, value: value }; } this[key] = new EnumItem(value); } } fromValue(value) { for (var key of Object.keys(this.object)) { if (this[key].value === value) { return this[key]; } } throw new Error("No enum for value: ".concat(value)); } } ; var CameraMode = { ORTHOGRAPHIC: 0, PERSPECTIVE: 1, VR: 2 }; var ClipTask = { NONE: 0, HIGHLIGHT: 1, SHOW_INSIDE: 2, SHOW_OUTSIDE: 3 }; var ClipMethod = { INSIDE_ANY: 0, INSIDE_ALL: 1 }; var ElevationGradientRepeat = { CLAMP: 0, REPEAT: 1, MIRRORED_REPEAT: 2 }; var MOUSE$1 = { LEFT: 0b0001, RIGHT: 0b0010, MIDDLE: 0b0100 }; var PointSizeType = { FIXED: 0, ATTENUATED: 1, ADAPTIVE: 2 }; var PointShape$1 = { SQUARE: 0, CIRCLE: 1, PARABOLOID: 2 }; var TreeType = { OCTREE: 0, KDTREE: 1 }; var LengthUnits = { METER: { code: 'm', unitspermeter: 1.0 }, FEET: { code: 'ft', unitspermeter: 3.28084 }, INCH: { code: '\u2033', unitspermeter: 39.3701 } }; // // how to calculate the radius of a projected sphere in screen space // http://stackoverflow.com/questions/21648630/radius-of-projected-sphere-in-screen-space // http://stackoverflow.com/questions/3717226/radius-of-projected-sphere // class PointCloudMaterial$1 extends RawShaderMaterial { //base constructor() { var parameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(); this.visibleNodesTexture = Utils.generateDataTexture(2048, 1, new Color(0xffffff)); this.visibleNodesTexture.minFilter = NearestFilter; this.visibleNodesTexture.magFilter = NearestFilter; var getValid = (a, b) => { if (a !== undefined) { return a; } else { return b; } }; var pointSize = getValid(parameters.size, 1.0); var minSize = getValid(parameters.minSize, 2.0); var maxSize = getValid(parameters.maxSize, 50.0); var treeType = getValid(parameters.treeType, TreeType.OCTREE); this._pointSizeType = PointSizeType.FIXED; this._shape = PointShape$1.SQUARE; this._useClipBox = false; this.clipBoxes = []; this.clipPolygons = []; this._weighted = false; this._gradient = Gradients.SPECTRAL; this.gradientTexture = PointCloudMaterial$1.generateGradientTexture(this._gradient); //this._matcap = "matcap.jpg"; //this.matcapTexture = PointCloudMaterial.generateMatcapTexture(this._matcap); this.lights = false; this.fog = false; this._treeType = treeType; this._useEDL = false; this.defines = new Map(); this.ranges = new Map(); this._activeAttributeName = null; this._defaultIntensityRangeChanged = false; this._defaultElevationRangeChanged = false; { var [width, height] = [256, 1]; var data = new Uint8Array(width * 4); var texture = new DataTexture(data, width, height, RGBAFormat); texture.magFilter = NearestFilter; texture.needsUpdate = true; this.classificationTexture = texture; } this.attributes = { position: { type: 'fv', value: [] }, color: { type: 'fv', value: [] }, normal: { type: 'fv', value: [] }, intensity: { type: 'f', value: [] }, classification: { type: 'f', value: [] }, returnNumber: { type: 'f', value: [] }, numberOfReturns: { type: 'f', value: [] }, pointSourceID: { type: 'f', value: [] }, indices: { type: 'fv', value: [] } }; this.uniforms = { level: { type: "f", value: 0.0 }, vnStart: { type: "f", value: 0.0 }, spacing: { type: "f", value: 1.0 }, blendHardness: { type: "f", value: 2.0 }, blendDepthSupplement: { type: "f", value: 0.0 }, fov: { type: "f", value: 1.0 }, screenWidth: { type: "f", value: 1.0 }, screenHeight: { type: "f", value: 1.0 }, near: { type: "f", value: 0.1 }, far: { type: "f", value: 1.0 }, uColor: { type: "c", value: new Color(0xffffff) }, uOpacity: { type: "f", value: 1.0 }, size: { type: "f", value: pointSize }, minSize: { type: "f", value: minSize }, maxSize: { type: "f", value: maxSize }, octreeSize: { type: "f", value: 0 }, bbSize: { type: "fv", value: [0, 0, 0] }, elevationRange: { type: "2fv", value: [0, 0] }, clipBoxCount: { type: "f", value: 0 }, //clipSphereCount: { type: "f", value: 0 }, clipPolygonCount: { type: "i", value: 0 }, clipBoxes: { type: "Matrix4fv", value: [] }, //clipSpheres: { type: "Matrix4fv", value: [] }, clipPolygons: { type: "3fv", value: [] }, clipPolygonVCount: { type: "iv", value: [] }, clipPolygonVP: { type: "Matrix4fv", value: [] }, visibleNodes: { type: "t", value: this.visibleNodesTexture }, pcIndex: { type: "f", value: 0 }, gradient: { type: "t", value: this.gradientTexture }, classificationLUT: { type: "t", value: this.classificationTexture }, uHQDepthMap: { type: "t", value: null }, toModel: { type: "Matrix4f", value: [] }, diffuse: { type: "fv", value: [1, 1, 1] }, transition: { type: "f", value: 0.5 }, intensityRange: { type: "fv", value: [Infinity, -Infinity] }, intensity_gbc: { type: "fv", value: [1, 0, 0] }, uRGB_gbc: { type: "fv", value: [1, 0, 0] }, // intensityGamma: { type: "f", value: 1 }, // intensityContrast: { type: "f", value: 0 }, // intensityBrightness:{ type: "f", value: 0 }, // rgbGamma: { type: "f", value: 1 }, // rgbContrast: { type: "f", value: 0 }, // rgbBrightness: { type: "f", value: 0 }, wRGB: { type: "f", value: 1 }, wIntensity: { type: "f", value: 0 }, wElevation: { type: "f", value: 0 }, wClassification: { type: "f", value: 0 }, wReturnNumber: { type: "f", value: 0 }, wSourceID: { type: "f", value: 0 }, useOrthographicCamera: { type: "b", value: false }, elevationGradientRepat: { type: "i", value: ElevationGradientRepeat.CLAMP }, clipTask: { type: "i", value: 1 }, clipMethod: { type: "i", value: 1 }, uShadowColor: { type: "3fv", value: [0, 0, 0] }, uExtraScale: { type: "f", value: 1 }, uExtraOffset: { type: "f", value: 0 }, uExtraRange: { type: "2fv", value: [0, 1] }, uExtraGammaBrightContr: { type: "3fv", value: [1, 0, 0] }, uFilterReturnNumberRange: { type: "fv", value: [0, 7] }, uFilterNumberOfReturnsRange: { type: "fv", value: [0, 7] }, uFilterGPSTimeClipRange: { type: "fv", value: [0, 7] }, uFilterPointSourceIDClipRange: { type: "fv", value: [0, 65535] }, //matcapTextureUniform: { type: "t", value: this.matcapTexture }, backfaceCulling: { type: "b", value: false } }; this.classification = ClassificationScheme.DEFAULT; this.defaultAttributeValues.normal = [0, 0, 0]; this.defaultAttributeValues.classification = [0, 0, 0]; this.defaultAttributeValues.indices = [0, 0, 0, 0]; this.vertexShader = Shaders['pointcloud.vs']; this.fragmentShader = Shaders['pointcloud.fs']; this.vertexColors = VertexColors; this.updateShaderSource(); } setDefine(key, value) { if (value !== undefined && value !== null) { if (this.defines.get(key) !== value) { this.defines.set(key, value); this.updateShaderSource(); } } else { this.removeDefine(key); } } removeDefine(key) { this.defines.delete(key); } updateShaderSource() { var vs = Shaders['pointcloud.vs']; var fs = Shaders['pointcloud.fs']; var definesString = this.getDefines(); var vsVersionIndex = vs.indexOf("#version "); var fsVersionIndex = fs.indexOf("#version "); if (vsVersionIndex >= 0) { vs = vs.replace(/(#version .*)/, "$1\n".concat(definesString)); } else { vs = "".concat(definesString, "\n").concat(vs); } if (fsVersionIndex >= 0) { fs = fs.replace(/(#version .*)/, "$1\n".concat(definesString)); } else { fs = "".concat(definesString, "\n").concat(fs); } this.vertexShader = vs; this.fragmentShader = fs; if (this.opacity === 1.0) { this.blending = NoBlending; this.transparent = false; this.depthTest = true; this.depthWrite = true; this.depthFunc = LessEqualDepth; } else if (this.opacity < 1.0 && !this.useEDL) { this.blending = AdditiveBlending; this.transparent = true; this.depthTest = false; this.depthWrite = true; this.depthFunc = AlwaysDepth; } if (this.weighted) { this.blending = AdditiveBlending; this.transparent = true; this.depthTest = true; this.depthWrite = false; } this.needsUpdate = true; } getDefines() { var defines = []; if (this.pointSizeType === PointSizeType.FIXED) { defines.push('#define fixed_point_size'); } else if (this.pointSizeType === PointSizeType.ATTENUATED) { defines.push('#define attenuated_point_size'); } else if (this.pointSizeType === PointSizeType.ADAPTIVE) { defines.push('#define adaptive_point_size'); } if (this.shape === PointShape$1.SQUARE) { defines.push('#define square_point_shape'); } else if (this.shape === PointShape$1.CIRCLE) { defines.push('#define circle_point_shape'); } else if (this.shape === PointShape$1.PARABOLOID) { defines.push('#define paraboloid_point_shape'); } if (this._useEDL) { defines.push('#define use_edl'); } if (this.activeAttributeName) { var attributeName = this.activeAttributeName.replace(/[^a-zA-Z0-9]/g, '_'); defines.push("#define color_type_".concat(attributeName)); } if (this._treeType === TreeType.OCTREE) { defines.push('#define tree_type_octree'); } else if (this._treeType === TreeType.KDTREE) { defines.push('#define tree_type_kdtree'); } if (this.weighted) { defines.push('#define weighted_splats'); } for (var [key, value] of this.defines) { defines.push(value); } return defines.join("\n"); } setClipBoxes(clipBoxes) { if (!clipBoxes) { return; } var doUpdate = this.clipBoxes.length !== clipBoxes.length && (clipBoxes.length === 0 || this.clipBoxes.length === 0); this.uniforms.clipBoxCount.value = this.clipBoxes.length; this.clipBoxes = clipBoxes; if (doUpdate) { this.updateShaderSource(); } this.uniforms.clipBoxes.value = new Float32Array(this.clipBoxes.length * 16); for (var i = 0; i < this.clipBoxes.length; i++) { var box = clipBoxes[i]; this.uniforms.clipBoxes.value.set(box.inverse.elements, 16 * i); } for (var _i = 0; _i < this.uniforms.clipBoxes.value.length; _i++) { if (Number.isNaN(this.uniforms.clipBoxes.value[_i])) { this.uniforms.clipBoxes.value[_i] = Infinity; } } } setClipPolygons(clipPolygons, maxPolygonVertices) { if (!clipPolygons) { return; } this.clipPolygons = clipPolygons; var doUpdate = this.clipPolygons.length !== clipPolygons.length; if (doUpdate) { this.updateShaderSource(); } } get gradient() { return this._gradient; } set gradient(value) { //海拔贴图 if (this._gradient !== value) { this._gradient = value; this.gradientTexture = PointCloudMaterial$1.generateGradientTexture(this._gradient); this.uniforms.gradient.value = this.gradientTexture; } } /* get matcap(){ return this._matcap; } set matcap (value) { if (this._matcap !== value) { this._matcap = value; this.matcapTexture = Potree.PointCloudMaterial.generateMatcapTexture(this._matcap); this.uniforms.matcapTextureUniform.value = this.matcapTexture; } } */ get useOrthographicCamera() { return this.uniforms.useOrthographicCamera.value; } set useOrthographicCamera(value) { if (this.uniforms.useOrthographicCamera.value !== value) { this.uniforms.useOrthographicCamera.value = value; } } get backfaceCulling() { return this.uniforms.backfaceCulling.value; } set backfaceCulling(value) { if (this.uniforms.backfaceCulling.value !== value) { this.uniforms.backfaceCulling.value = value; this.dispatchEvent({ type: 'backface_changed', target: this }); } } recomputeClassification() { var classification = this.classification; var data = this.classificationTexture.image.data; var width = 256; var black = [1, 1, 1, 1]; var valuesChanged = false; for (var i = 0; i < width; i++) { var color = void 0; var visible = true; if (classification[i]) { color = classification[i].color; visible = classification[i].visible; } else if (classification[i % 32]) { color = classification[i % 32].color; visible = classification[i % 32].visible; } else if (classification.DEFAULT) { color = classification.DEFAULT.color; visible = classification.DEFAULT.visible; } else { color = black; } var r = parseInt(255 * color[0]); var g = parseInt(255 * color[1]); var b = parseInt(255 * color[2]); var a = visible ? parseInt(255 * color[3]) : 0; if (data[4 * i + 0] !== r) { data[4 * i + 0] = r; valuesChanged = true; } if (data[4 * i + 1] !== g) { data[4 * i + 1] = g; valuesChanged = true; } if (data[4 * i + 2] !== b) { data[4 * i + 2] = b; valuesChanged = true; } if (data[4 * i + 3] !== a) { data[4 * i + 3] = a; valuesChanged = true; } } if (valuesChanged) { this.classificationTexture.needsUpdate = true; this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get spacing() { return this.uniforms.spacing.value; } set spacing(value) { if (this.uniforms.spacing.value !== value) { // 即 uOctreeSpacing 来自cloud.js里 this.uniforms.spacing.value = value; } } get useClipBox() { return this._useClipBox; } set useClipBox(value) { if (this._useClipBox !== value) { this._useClipBox = value; this.updateShaderSource(); } } get clipTask() { return this.uniforms.clipTask.value; } set clipTask(mode) { this.uniforms.clipTask.value = mode; } get elevationGradientRepat() { return this.uniforms.elevationGradientRepat.value; } set elevationGradientRepat(mode) { this.uniforms.elevationGradientRepat.value = mode; } get clipMethod() { return this.uniforms.clipMethod.value; } set clipMethod(mode) { this.uniforms.clipMethod.value = mode; } get weighted() { return this._weighted; } set weighted(value) { if (this._weighted !== value) { this._weighted = value; this.updateShaderSource(); } } get fov() { return this.uniforms.fov.value; } set fov(value) { if (this.uniforms.fov.value !== value) { this.uniforms.fov.value = value; // this.updateShaderSource(); } } get screenWidth() { return this.uniforms.screenWidth.value; } set screenWidth(value) { if (this.uniforms.screenWidth.value !== value) { this.uniforms.screenWidth.value = value; // this.updateShaderSource(); } } get screenHeight() { return this.uniforms.screenHeight.value; } set screenHeight(value) { if (this.uniforms.screenHeight.value !== value) { this.uniforms.screenHeight.value = value; // this.updateShaderSource(); } } get near() { return this.uniforms.near.value; } set near(value) { if (this.uniforms.near.value !== value) { this.uniforms.near.value = value; } } get far() { return this.uniforms.far.value; } set far(value) { if (this.uniforms.far.value !== value) { this.uniforms.far.value = value; } } get opacity() { return this.uniforms.uOpacity.value; } set opacity(value) { if (this.uniforms && this.uniforms.uOpacity) { if (this.uniforms.uOpacity.value !== value) { this.uniforms.uOpacity.value = value; this.updateShaderSource(); this.dispatchEvent({ type: 'opacity_changed', target: this }); this.dispatchEvent({ type: 'material_property_changed', target: this }); } } } get activeAttributeName() { return this._activeAttributeName; } set activeAttributeName(value) { if (this._activeAttributeName !== value) { this._activeAttributeName = value; this.updateShaderSource(); this.dispatchEvent({ type: 'active_attribute_changed', target: this }); this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get pointSizeType() { return this._pointSizeType; } set pointSizeType(value) { if (this._pointSizeType !== value) { this._pointSizeType = value; this.updateShaderSource(); //这句表明这个属性频繁更改会卡顿 this.dispatchEvent({ type: 'point_size_type_changed', target: this }); this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get useEDL() { return this._useEDL; } set useEDL(value) { if (this._useEDL !== value) { this._useEDL = value; this.updateShaderSource(); } } get color() { return this.uniforms.uColor.value; } set color(value) { if (!this.uniforms.uColor.value.equals(value)) { this.uniforms.uColor.value.copy(value); this.dispatchEvent({ type: 'color_changed', target: this }); this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get shape() { return this._shape; } set shape(value) { if (this._shape !== value) { this._shape = value; this.updateShaderSource(); this.dispatchEvent({ type: 'point_shape_changed', target: this }); this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get treeType() { return this._treeType; } set treeType(value) { if (this._treeType !== value) { this._treeType = value; this.updateShaderSource(); } } get bbSize() { return this.uniforms.bbSize.value; } set bbSize(value) { this.uniforms.bbSize.value = value; } get size() { return this.uniforms.size.value; } set size(value) { if (this.uniforms.size.value !== value) { this.uniforms.size.value = value; this.dispatchEvent({ type: 'point_size_changed', target: this }); this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get minSize() { return this.uniforms.minSize.value; } set minSize(value) { if (this.uniforms.minSize.value !== value) { this.uniforms.minSize.value = value; this.dispatchEvent({ type: 'point_size_changed', target: this }); this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get elevationRange() { return this.uniforms.elevationRange.value; } set elevationRange(value) { var changed = this.uniforms.elevationRange.value[0] !== value[0] || this.uniforms.elevationRange.value[1] !== value[1]; if (changed) { this.uniforms.elevationRange.value = value; this._defaultElevationRangeChanged = true; this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get heightMin() { return this.uniforms.elevationRange.value[0]; } set heightMin(value) { this.elevationRange = [value, this.elevationRange[1]]; } get heightMax() { return this.uniforms.elevationRange.value[1]; } set heightMax(value) { this.elevationRange = [this.elevationRange[0], value]; } get transition() { return this.uniforms.transition.value; } set transition(value) { this.uniforms.transition.value = value; } get intensityRange() { return this.uniforms.intensityRange.value; } set intensityRange(value) { if (!(value instanceof Array && value.length === 2)) { return; } if (value[0] === this.uniforms.intensityRange.value[0] && value[1] === this.uniforms.intensityRange.value[1]) { return; } this.uniforms.intensityRange.value = value; this._defaultIntensityRangeChanged = true; this.dispatchEvent({ type: 'material_property_changed', target: this }); } get intensityGamma() { return this.uniforms.intensity_gbc.value[0]; } set intensityGamma(value) { if (this.uniforms.intensity_gbc.value[0] !== value) { this.uniforms.intensity_gbc.value[0] = value; this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get intensityContrast() { return this.uniforms.intensity_gbc.value[2]; } set intensityContrast(value) { if (this.uniforms.intensity_gbc.value[2] !== value) { this.uniforms.intensity_gbc.value[2] = value; this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get intensityBrightness() { return this.uniforms.intensity_gbc.value[1]; } set intensityBrightness(value) { if (this.uniforms.intensity_gbc.value[1] !== value) { this.uniforms.intensity_gbc.value[1] = value; this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get rgbGamma() { return this.uniforms.uRGB_gbc.value[0]; } set rgbGamma(value) { if (this.uniforms.uRGB_gbc.value[0] !== value) { this.uniforms.uRGB_gbc.value[0] = value; this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get rgbContrast() { return this.uniforms.uRGB_gbc.value[2]; } set rgbContrast(value) { if (this.uniforms.uRGB_gbc.value[2] !== value) { this.uniforms.uRGB_gbc.value[2] = value; this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get rgbBrightness() { return this.uniforms.uRGB_gbc.value[1]; } set rgbBrightness(value) { if (this.uniforms.uRGB_gbc.value[1] !== value) { this.uniforms.uRGB_gbc.value[1] = value; this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get extraGamma() { return this.uniforms.uExtraGammaBrightContr.value[0]; } set extraGamma(value) { if (this.uniforms.uExtraGammaBrightContr.value[0] !== value) { this.uniforms.uExtraGammaBrightContr.value[0] = value; this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get extraBrightness() { return this.uniforms.uExtraGammaBrightContr.value[1]; } set extraBrightness(value) { if (this.uniforms.uExtraGammaBrightContr.value[1] !== value) { this.uniforms.uExtraGammaBrightContr.value[1] = value; this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get extraContrast() { return this.uniforms.uExtraGammaBrightContr.value[2]; } set extraContrast(value) { if (this.uniforms.uExtraGammaBrightContr.value[2] !== value) { this.uniforms.uExtraGammaBrightContr.value[2] = value; this.dispatchEvent({ type: 'material_property_changed', target: this }); } } getRange(attributeName) { return this.ranges.get(attributeName); } setRange(attributeName, newRange) { var rangeChanged = false; var oldRange = this.ranges.get(attributeName); if (oldRange != null && newRange != null) { rangeChanged = oldRange[0] !== newRange[0] || oldRange[1] !== newRange[1]; } else { rangeChanged = true; } this.ranges.set(attributeName, newRange); if (rangeChanged) { this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get extraRange() { return this.uniforms.uExtraRange.value; } set extraRange(value) { if (!(value instanceof Array && value.length === 2)) { return; } if (value[0] === this.uniforms.uExtraRange.value[0] && value[1] === this.uniforms.uExtraRange.value[1]) { return; } this.uniforms.uExtraRange.value = value; this._defaultExtraRangeChanged = true; this.dispatchEvent({ type: 'material_property_changed', target: this }); } get weightRGB() { return this.uniforms.wRGB.value; } set weightRGB(value) { if (this.uniforms.wRGB.value !== value) { this.uniforms.wRGB.value = value; this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get weightIntensity() { return this.uniforms.wIntensity.value; } set weightIntensity(value) { if (this.uniforms.wIntensity.value !== value) { this.uniforms.wIntensity.value = value; this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get weightElevation() { return this.uniforms.wElevation.value; } set weightElevation(value) { if (this.uniforms.wElevation.value !== value) { this.uniforms.wElevation.value = value; this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get weightClassification() { return this.uniforms.wClassification.value; } set weightClassification(value) { if (this.uniforms.wClassification.value !== value) { this.uniforms.wClassification.value = value; this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get weightReturnNumber() { return this.uniforms.wReturnNumber.value; } set weightReturnNumber(value) { if (this.uniforms.wReturnNumber.value !== value) { this.uniforms.wReturnNumber.value = value; this.dispatchEvent({ type: 'material_property_changed', target: this }); } } get weightSourceID() { return this.uniforms.wSourceID.value; } set weightSourceID(value) { if (this.uniforms.wSourceID.value !== value) { this.uniforms.wSourceID.value = value; this.dispatchEvent({ type: 'material_property_changed', target: this }); } } static generateGradientTexture(gradient) { var size = 64; // create canvas var canvas = document.createElement('canvas'); canvas.width = size; canvas.height = size; // get context var context = canvas.getContext('2d'); // draw gradient context.rect(0, 0, size, size); var ctxGradient = context.createLinearGradient(0, 0, size, size); for (var i = 0; i < gradient.length; i++) { var step = gradient[i]; ctxGradient.addColorStop(step[0], '#' + step[1].getHexString()); } context.fillStyle = ctxGradient; context.fill(); //let texture = new THREE.Texture(canvas); var texture = new CanvasTexture(canvas); texture.needsUpdate = true; texture.minFilter = LinearFilter; texture.wrap = RepeatWrapping; texture.repeat = 2; // textureImage = texture.image; return texture; } static generateMatcapTexture(matcap) { var url = new URL(Potree.resourcePath + "/textures/matcap/" + matcap).href; var texture = new TextureLoader().load(url); texture.magFilter = texture.minFilter = LinearFilter; texture.needsUpdate = true; // PotreeConverter_1.6_2018_07_29_windows_x64\PotreeConverter.exe autzen_xyzrgbXYZ_ascii.xyz -f xyzrgbXYZ -a RGB NORMAL -o autzen_xyzrgbXYZ_ascii_a -p index --overwrite // Switch matcap texture on the fly : viewer.scene.pointclouds[0].material.matcap = 'matcap1.jpg'; // For non power of 2, use LinearFilter and dont generate mipmaps, For power of 2, use NearestFilter and generate mipmaps : matcap2.jpg 1 2 8 11 12 13 return texture; } disableEvents() { if (this._hiddenListeners === undefined) { this._hiddenListeners = this._listeners; this._listeners = {}; } } enableEvents() { this._listeners = this._hiddenListeners; this._hiddenListeners = undefined; } } // copyFrom(from){ // var a = 10; // for(let name of Object.keys(this.uniforms)){ // this.uniforms[name].value = from.uniforms[name].value; // } // } // copy(from){ // this.copyFrom(from); // } //见ExtendPointCloudOctree class PointCloudOctreeNode extends PointCloudTreeNode { constructor() { super(); //this.children = {}; this.children = []; this.sceneNode = null; this.octree = null; } getNumPoints() { return this.geometryNode.numPoints; } isLoaded() { return true; } isTreeNode() { return true; } isGeometryNode() { return false; } getLevel() { return this.geometryNode.level; } getBoundingSphere() { return this.geometryNode.boundingSphere; } getBoundingBox() { return this.geometryNode.boundingBox; } getChildren() { var children = []; for (var i = 0; i < 8; i++) { if (this.children[i]) { children.push(this.children[i]); } } return children; } getPointsInBox(boxNode) { if (!this.sceneNode) { return null; } var buffer = this.geometryNode.buffer; var posOffset = buffer.offset("position"); var stride = buffer.stride; var view = new DataView(buffer.data); var worldToBox = boxNode.matrixWorld.clone().invert(); var objectToBox = new Matrix4().multiplyMatrices(worldToBox, this.sceneNode.matrixWorld); var inBox = []; var pos = new Vector4(); for (var i = 0; i < buffer.numElements; i++) { var x = view.getFloat32(i * stride + posOffset + 0, true); var y = view.getFloat32(i * stride + posOffset + 4, true); var z = view.getFloat32(i * stride + posOffset + 8, true); pos.set(x, y, z, 1); pos.applyMatrix4(objectToBox); if (-0.5 < pos.x && pos.x < 0.5) { if (-0.5 < pos.y && pos.y < 0.5) { if (-0.5 < pos.z && pos.z < 0.5) { pos.set(x, y, z, 1).applyMatrix4(this.sceneNode.matrixWorld); inBox.push(new Vector3(pos.x, pos.y, pos.z)); } } } } return inBox; } get name() { return this.geometryNode.name; } } ; class PointCloudOctree extends PointCloudTree { //base constructor(geometry, material) { var _this2; super(); _this2 = this; this.pointBudget = Infinity; //一直是这个值 this.pcoGeometry = geometry; this.boundingBox = this.pcoGeometry.boundingBox; this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere()); this.material = material || new PointCloudMaterial$1(); this.visiblePointsTarget = 2 * 1000 * 1000; this.minimumNodePixelSize = 150; this.level = 0; this.position.copy(geometry.offset); this.updateMatrix(); { var priorityQueue = ["rgba", "rgb", "intensity", "classification"]; var selected = "rgba"; var _loop = function _loop(attributeName) { var attribute = _this2.pcoGeometry.pointAttributes.attributes.find(a => a.name === attributeName); if (!attribute) { return 0; // continue } var min = attribute.range[0].constructor.name === "Array" ? attribute.range[0] : [attribute.range[0]]; var max = attribute.range[1].constructor.name === "Array" ? attribute.range[1] : [attribute.range[1]]; var range_min = new Vector3(...min); var range_max = new Vector3(...max); var range = range_min.distanceTo(range_max); if (range === 0) { return 0; // continue } selected = attributeName; return 1; // break }, _ret; for (var attributeName of priorityQueue) { _ret = _loop(attributeName); if (_ret === 0) continue; if (_ret === 1) break; } this.material.activeAttributeName = selected; } this.showBoundingBox = false; this.boundingBoxNodes = []; this.loadQueue = []; this.visibleBounds = new Box3(); this.visibleNodes = []; this.visibleGeometry = []; this.generateDEM = false; this.profileRequests = []; this.name = ''; this._visible = true; { var box = [this.pcoGeometry.tightBoundingBox, this.getBoundingBoxWorld()].find(v => v !== undefined); this.updateMatrixWorld(true); box = Utils.computeTransformedBoundingBox(box, this.matrixWorld); var bMin = box.min.z; var bMax = box.max.z; this.material.heightMin = bMin; this.material.heightMax = bMax; } // TODO read projection from file instead this.projection = geometry.projection; this.fallbackProjection = geometry.fallbackProjection; this.root = this.pcoGeometry.root; } setName(name) { if (this.name !== name) { this.name = name; this.dispatchEvent({ type: 'name_changed', name: name, pointcloud: this }); } } getName() { return this.name; } getAttribute(name) { var attribute = this.pcoGeometry.pointAttributes.attributes.find(a => a.name === name); if (attribute) { return attribute; } else { return null; } } getAttributes() { return this.pcoGeometry.pointAttributes; } toTreeNode(geometryNode, parent) { var node = new PointCloudOctreeNode(); // if(geometryNode.name === "r40206"){ // console.log("creating node for r40206"); // } var sceneNode = new Points(geometryNode.geometry, this.material); sceneNode.name = geometryNode.name; sceneNode.position.copy(geometryNode.boundingBox.min); sceneNode.frustumCulled = false; sceneNode.onBeforeRender = (_this, scene, camera, geometry, material, group) => { if (material.program) { _this.getContext().useProgram(material.program.program); if (material.program.getUniforms().map.level) { var level = geometryNode.getLevel(); material.uniforms.level.value = level; material.program.getUniforms().map.level.setValue(_this.getContext(), level); } if (this.visibleNodeTextureOffsets && material.program.getUniforms().map.vnStart) { var vnStart = this.visibleNodeTextureOffsets.get(node); material.uniforms.vnStart.value = vnStart; material.program.getUniforms().map.vnStart.setValue(_this.getContext(), vnStart); } if (material.program.getUniforms().map.pcIndex) { var i = node.pcIndex ? node.pcIndex : this.visibleNodes.indexOf(node); material.uniforms.pcIndex.value = i; material.program.getUniforms().map.pcIndex.setValue(_this.getContext(), i); } } }; // { // DEBUG // let sg = new THREE.SphereGeometry(1, 16, 16); // let sm = new THREE.MeshNormalMaterial(); // let s = new THREE.Mesh(sg, sm); // s.scale.set(5, 5, 5); // s.position.copy(geometryNode.mean) // .add(this.position) // .add(geometryNode.boundingBox.min); // // viewer.scene.scene.add(s); // } node.geometryNode = geometryNode; node.sceneNode = sceneNode; node.pointcloud = this; node.children = []; //for (let key in geometryNode.children) { // node.children[key] = geometryNode.children[key]; //} for (var i = 0; i < 8; i++) { node.children[i] = geometryNode.children[i]; } if (!parent) { this.root = node; this.add(sceneNode); } else { var childIndex = parseInt(geometryNode.name[geometryNode.name.length - 1]); parent.sceneNode.add(sceneNode); parent.children[childIndex] = node; } var disposeListener = function disposeListener() { var childIndex = parseInt(geometryNode.name[geometryNode.name.length - 1]); parent.sceneNode.remove(node.sceneNode); parent.children[childIndex] = geometryNode; }; geometryNode.oneTimeDisposeHandlers.push(disposeListener); return node; } updateVisibleBounds() { var leafNodes = []; for (var i = 0; i < this.visibleNodes.length; i++) { var node = this.visibleNodes[i]; var isLeaf = true; for (var j = 0; j < node.children.length; j++) { var child = node.children[j]; if (child instanceof PointCloudOctreeNode) { isLeaf = isLeaf && !child.sceneNode.visible; } else if (child instanceof PointCloudOctreeGeometryNode) { isLeaf = true; } } if (isLeaf) { leafNodes.push(node); } } this.visibleBounds.min = new Vector3(Infinity, Infinity, Infinity); this.visibleBounds.max = new Vector3(-Infinity, -Infinity, -Infinity); for (var _i = 0; _i < leafNodes.length; _i++) { var _node = leafNodes[_i]; this.visibleBounds.expandByPoint(_node.getBoundingBox().min); this.visibleBounds.expandByPoint(_node.getBoundingBox().max); } } updateMaterial(material, visibleNodes, camera, renderer) { material.fov = camera.fov * (Math.PI / 180); material.screenWidth = renderer.domElement.clientWidth; material.screenHeight = renderer.domElement.clientHeight; material.spacing = this.pcoGeometry.spacing; // * Math.max(this.scale.x, this.scale.y, this.scale.z); material.near = camera.near; material.far = camera.far; material.uniforms.octreeSize.value = this.pcoGeometry.boundingBox.getSize(new Vector3()).x; } computeVisibilityTextureData(nodes, camera) { if (Potree.measureTimings) performance.mark("computeVisibilityTextureData-start"); var data = new Uint8Array(nodes.length * 4); var visibleNodeTextureOffsets = new Map(); // copy array nodes = nodes.slice(); // sort by level and index, e.g. r, r0, r3, r4, r01, r07, r30, ... var sort = function sort(a, b) { var na = a.geometryNode.name; var nb = b.geometryNode.name; if (na.length !== nb.length) return na.length - nb.length; if (na < nb) return -1; if (na > nb) return 1; return 0; }; nodes.sort(sort); var worldDir = new Vector3(); var nodeMap = new Map(); var offsetsToChild = new Array(nodes.length).fill(Infinity); for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; nodeMap.set(node.name, node); visibleNodeTextureOffsets.set(node, i); if (i > 0) { var index = parseInt(node.name.slice(-1)); var parentName = node.name.slice(0, -1); var parent = nodeMap.get(parentName); var parentOffset = visibleNodeTextureOffsets.get(parent); var parentOffsetToChild = i - parentOffset; offsetsToChild[parentOffset] = Math.min(offsetsToChild[parentOffset], parentOffsetToChild); data[parentOffset * 4 + 0] = data[parentOffset * 4 + 0] | 1 << index; data[parentOffset * 4 + 1] = offsetsToChild[parentOffset] >> 8; data[parentOffset * 4 + 2] = offsetsToChild[parentOffset] % 256; } var density = node.geometryNode.density; if (typeof density === "number") { var lodOffset = Math.log2(density) / 2 - 1.5; var offsetUint8 = (lodOffset + 10) * 10; data[i * 4 + 3] = offsetUint8; } else { data[i * 4 + 3] = 100; } } if (Potree.measureTimings) { performance.mark("computeVisibilityTextureData-end"); performance.measure("render.computeVisibilityTextureData", "computeVisibilityTextureData-start", "computeVisibilityTextureData-end"); } return { data: data, offsets: visibleNodeTextureOffsets }; } nodeIntersectsProfile(node, profile) { var bbWorld = node.boundingBox.clone().applyMatrix4(this.matrixWorld); var bsWorld = bbWorld.getBoundingSphere(new Sphere()); var intersects = false; for (var i = 0; i < profile.points.length - 1; i++) { var start = new Vector3(profile.points[i + 0].x, profile.points[i + 0].y, bsWorld.center.z); var end = new Vector3(profile.points[i + 1].x, profile.points[i + 1].y, bsWorld.center.z); var closest = new Line3(start, end).closestPointToPoint(bsWorld.center, true, new Vector3()); var distance = closest.distanceTo(bsWorld.center); intersects = intersects || distance < bsWorld.radius + profile.width; } //console.log(`${node.name}: ${intersects}`); return intersects; } deepestNodeAt(position) { var toObjectSpace = this.matrixWorld.clone().invert(); var objPos = position.clone().applyMatrix4(toObjectSpace); var current = this.root; while (true) { var containingChild = null; for (var child of current.children) { if (child !== undefined) { if (child.getBoundingBox().containsPoint(objPos)) { containingChild = child; } } } if (containingChild !== null && containingChild instanceof PointCloudOctreeNode) { current = containingChild; } else { break; } } var deepest = current; return deepest; } nodesOnRay(nodes, ray) { var nodesOnRay = []; var _ray = ray.clone(); for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; var sphere = node.getBoundingSphere().clone().applyMatrix4(this.matrixWorld); if (_ray.intersectsSphere(sphere)) { nodesOnRay.push(node); } } return nodesOnRay; } updateMatrixWorld(force) { if (this.matrixAutoUpdate === true) this.updateMatrix(); if (this.matrixWorldNeedsUpdate === true || force === true) { if (!this.parent) { this.matrixWorld.copy(this.matrix); } else { this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); } this.matrixWorldNeedsUpdate = false; force = true; } } hideDescendants(object) { var stack = []; for (var i = 0; i < object.children.length; i++) { var child = object.children[i]; if (child.visible) { stack.push(child); } } while (stack.length > 0) { var _object = stack.shift(); _object.visible = false; for (var _i2 = 0; _i2 < _object.children.length; _i2++) { var _child = _object.children[_i2]; if (_child.visible) { stack.push(_child); } } } } moveToOrigin() { this.position.set(0, 0, 0); this.updateMatrixWorld(true); var box = this.boundingBox; var transform = this.matrixWorld; var tBox = Utils.computeTransformedBoundingBox(box, transform); this.position.set(0, 0, 0).sub(tBox.getCenter(new Vector3())); } moveToGroundPlane() { this.updateMatrixWorld(true); var box = this.boundingBox; var transform = this.matrixWorld; var tBox = Utils.computeTransformedBoundingBox(box, transform); this.position.y += -tBox.min.y; } getBoundingBoxWorld() { this.updateMatrixWorld(true); var box = this.boundingBox; var transform = this.matrixWorld; var tBox = Utils.computeTransformedBoundingBox(box, transform); return tBox; } /** * returns points inside the profile points * * maxDepth: search points up to the given octree depth * * * The return value is an array with all segments of the profile path * let segment = { * start: THREE.Vector3, * end: THREE.Vector3, * points: {} * project: function() * }; * * The project() function inside each segment can be used to transform * that segments point coordinates to line up along the x-axis. * * */ getPointsInProfile(profile, maxDepth, callback) { if (callback) { var request = new Potree.ProfileRequest(this, profile, maxDepth, callback); this.profileRequests.push(request); return request; } var points = { segments: [], boundingBox: new Box3(), projectedBoundingBox: new Box2() }; // evaluate segments for (var i = 0; i < profile.points.length - 1; i++) { var start = profile.points[i]; var end = profile.points[i + 1]; var ps = this.getProfile(start, end, profile.width, maxDepth); var segment = { start: start, end: end, points: ps, project: null }; points.segments.push(segment); points.boundingBox.expandByPoint(ps.boundingBox.min); points.boundingBox.expandByPoint(ps.boundingBox.max); } // add projection functions to the segments var mileage = new Vector3(); for (var _i3 = 0; _i3 < points.segments.length; _i3++) { var _segment = points.segments[_i3]; var _start2 = _segment.start; var _end2 = _segment.end; var project = function (_start, _end, _mileage, _boundingBox) { var start = _start; var end = _end; var mileage = _mileage; var boundingBox = _boundingBox; var xAxis = new Vector3(1, 0, 0); var dir = new Vector3().subVectors(end, start); dir.y = 0; dir.normalize(); var alpha = Math.acos(xAxis.dot(dir)); if (dir.z > 0) { alpha = -alpha; } return function (position) { var toOrigin = new Matrix4().makeTranslation(-start.x, -boundingBox.min.y, -start.z); var alignWithX = new Matrix4().makeRotationY(-alpha); var applyMileage = new Matrix4().makeTranslation(mileage.x, 0, 0); var pos = position.clone(); pos.applyMatrix4(toOrigin); pos.applyMatrix4(alignWithX); pos.applyMatrix4(applyMileage); return pos; }; }(_start2, _end2, mileage.clone(), points.boundingBox.clone()); _segment.project = project; mileage.x += new Vector3(_start2.x, 0, _start2.z).distanceTo(new Vector3(_end2.x, 0, _end2.z)); mileage.y += _end2.y - _start2.y; } points.projectedBoundingBox.min.x = 0; points.projectedBoundingBox.min.y = points.boundingBox.min.y; points.projectedBoundingBox.max.x = mileage.x; points.projectedBoundingBox.max.y = points.boundingBox.max.y; return points; } /** * returns points inside the given profile bounds. * * start: * end: * width: * depth: search points up to the given octree depth * callback: if specified, points are loaded before searching * * */ getProfile(start, end, width, depth, callback) { var request = new Potree.ProfileRequest(start, end, width, depth, callback); this.profileRequests.push(request); } getVisibleExtent() { return this.visibleBounds.applyMatrix4(this.matrixWorld); } intersectsPoint(position) { var rootAvailable = this.pcoGeometry.root && this.pcoGeometry.root.geometry; if (!rootAvailable) { return false; } if (typeof this.signedDistanceField === "undefined") { var resolution = 32; var field = new Float32Array(resolution ** 3).fill(Infinity); var positions = this.pcoGeometry.root.geometry.attributes.position; var boundingBox = this.boundingBox; var n = positions.count; for (var i = 0; i < n; i = i + 3) { var x = positions.array[3 * i + 0]; var y = positions.array[3 * i + 1]; var z = positions.array[3 * i + 2]; var ix = parseInt(Math.min(resolution * (x / boundingBox.max.x), resolution - 1)); var iy = parseInt(Math.min(resolution * (y / boundingBox.max.y), resolution - 1)); var iz = parseInt(Math.min(resolution * (z / boundingBox.max.z), resolution - 1)); var index = ix + iy * resolution + iz * resolution * resolution; field[index] = 0; } var sdf = { resolution: resolution, field: field }; this.signedDistanceField = sdf; } { var _sdf = this.signedDistanceField; var _boundingBox2 = this.boundingBox; var toObjectSpace = this.matrixWorld.clone().invert(); var objPos = position.clone().applyMatrix4(toObjectSpace); var _resolution = _sdf.resolution; var _ix = parseInt(_resolution * (objPos.x / _boundingBox2.max.x)); var _iy = parseInt(_resolution * (objPos.y / _boundingBox2.max.y)); var _iz = parseInt(_resolution * (objPos.z / _boundingBox2.max.z)); if (_ix < 0 || _iy < 0 || _iz < 0) { return false; } if (_ix >= _resolution || _iy >= _resolution || _iz >= _resolution) { return false; } var _index = _ix + _iy * _resolution + _iz * _resolution * _resolution; var value = _sdf.field[_index]; if (value === 0) { return true; } } return false; } /** * * * * params.pickWindowSize: Look for points inside a pixel window of this size. * Use odd values: 1, 3, 5, ... * * * TODO: only draw pixels that are actually read with readPixels(). * */ pick(viewer, camera, ray) { var params = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var renderer = viewer.renderer; var pRenderer = viewer.pRenderer; performance.mark("pick-start"); var getVal = (a, b) => a !== undefined ? a : b; var pickWindowSize = getVal(params.pickWindowSize, 65); var pickOutsideClipRegion = getVal(params.pickOutsideClipRegion, false); var size = renderer.getSize(new Vector2()); var width = Math.ceil(getVal(params.width, size.width)); var height = Math.ceil(getVal(params.height, size.height)); var pointSizeType = getVal(params.pointSizeType, this.material.pointSizeType); var pointSize = getVal(params.pointSize, this.material.size); var nodes = this.nodesOnRay(this.visibleNodes, ray); if (nodes.length === 0) { return null; } if (!this.pickState) { var scene = new Scene(); var material = new Potree.PointCloudMaterial(); material.activeAttributeName = "indices"; var renderTarget = new WebGLRenderTarget(1, 1, { minFilter: LinearFilter, magFilter: NearestFilter, format: RGBAFormat }); this.pickState = { renderTarget: renderTarget, material: material, scene: scene }; } ; var pickState = this.pickState; var pickMaterial = pickState.material; { // update pick material pickMaterial.pointSizeType = pointSizeType; //pickMaterial.shape = this.material.shape; pickMaterial.shape = Potree.PointShape.PARABOLOID; pickMaterial.uniforms.uFilterReturnNumberRange.value = this.material.uniforms.uFilterReturnNumberRange.value; pickMaterial.uniforms.uFilterNumberOfReturnsRange.value = this.material.uniforms.uFilterNumberOfReturnsRange.value; pickMaterial.uniforms.uFilterGPSTimeClipRange.value = this.material.uniforms.uFilterGPSTimeClipRange.value; pickMaterial.uniforms.uFilterPointSourceIDClipRange.value = this.material.uniforms.uFilterPointSourceIDClipRange.value; pickMaterial.activeAttributeName = "indices"; pickMaterial.size = pointSize; pickMaterial.uniforms.minSize.value = this.material.uniforms.minSize.value; pickMaterial.uniforms.maxSize.value = this.material.uniforms.maxSize.value; pickMaterial.classification = this.material.classification; pickMaterial.recomputeClassification(); if (params.pickClipped) { pickMaterial.clipBoxes = this.material.clipBoxes; pickMaterial.uniforms.clipBoxes = this.material.uniforms.clipBoxes; if (this.material.clipTask === Potree.ClipTask.HIGHLIGHT) { pickMaterial.clipTask = Potree.ClipTask.NONE; } else { pickMaterial.clipTask = this.material.clipTask; } pickMaterial.clipMethod = this.material.clipMethod; } else { pickMaterial.clipBoxes = []; } this.updateMaterial(pickMaterial, nodes, camera, renderer); } pickState.renderTarget.setSize(width, height); var pixelPos = new Vector2(params.x, params.y); var gl = renderer.getContext(); gl.enable(gl.SCISSOR_TEST); gl.scissor(parseInt(pixelPos.x - (pickWindowSize - 1) / 2), parseInt(pixelPos.y - (pickWindowSize - 1) / 2), parseInt(pickWindowSize), parseInt(pickWindowSize)); renderer.state.buffers.depth.setTest(pickMaterial.depthTest); renderer.state.buffers.depth.setMask(pickMaterial.depthWrite); renderer.state.setBlending(NoBlending); { // RENDER renderer.setRenderTarget(pickState.renderTarget); gl.clearColor(0, 0, 0, 0); renderer.clear(true, true, true); var tmp = this.material; this.material = pickMaterial; pRenderer.renderOctree(this, nodes, camera, pickState.renderTarget); this.material = tmp; } var clamp = (number, min, max) => Math.min(Math.max(min, number), max); var x = parseInt(clamp(pixelPos.x - (pickWindowSize - 1) / 2, 0, width)); var y = parseInt(clamp(pixelPos.y - (pickWindowSize - 1) / 2, 0, height)); var w = parseInt(Math.min(x + pickWindowSize, width) - x); var h = parseInt(Math.min(y + pickWindowSize, height) - y); var pixelCount = w * h; var buffer = new Uint8Array(4 * pixelCount); gl.readPixels(x, y, pickWindowSize, pickWindowSize, gl.RGBA, gl.UNSIGNED_BYTE, buffer); renderer.setRenderTarget(null); renderer.state.reset(); renderer.setScissorTest(false); gl.disable(gl.SCISSOR_TEST); var pixels = buffer; var ibuffer = new Uint32Array(buffer.buffer); // find closest hit inside pixelWindow boundaries var min = Number.MAX_VALUE; var hits = []; for (var u = 0; u < pickWindowSize; u++) { for (var v = 0; v < pickWindowSize; v++) { var offset = u + v * pickWindowSize; var distance = Math.pow(u - (pickWindowSize - 1) / 2, 2) + Math.pow(v - (pickWindowSize - 1) / 2, 2); var pcIndex = pixels[4 * offset + 3]; pixels[4 * offset + 3] = 0; var pIndex = ibuffer[offset]; if (!(pcIndex === 0 && pIndex === 0) && pcIndex !== undefined && pIndex !== undefined) { var hit = { pIndex: pIndex, pcIndex: pcIndex, distanceToCenter: distance }; if (params.all) { hits.push(hit); } else { if (hits.length > 0) { if (distance < hits[0].distanceToCenter) { hits[0] = hit; } } else { hits.push(hit); } } } } } // { // DEBUG: show panel with pick image // let img = Utils.pixelsArrayToImage(buffer, w, h); // let screenshot = img.src; // if(!this.debugDIV){ // this.debugDIV = $(` //
`); // $(document.body).append(this.debugDIV); // } // this.debugDIV.empty(); // this.debugDIV.append($(``)); // //$(this.debugWindow.document).append($(``)); // //this.debugWindow.document.write(''); // } for (var _hit of hits) { var point = {}; if (!nodes[_hit.pcIndex]) { return null; } var node = nodes[_hit.pcIndex]; var pc = node.sceneNode; var geometry = node.geometryNode.geometry; var _loop2 = function _loop2() { var attribute = geometry.attributes[attributeName]; if (attributeName === 'position') { var _x = attribute.array[3 * _hit.pIndex + 0]; var _y = attribute.array[3 * _hit.pIndex + 1]; var z = attribute.array[3 * _hit.pIndex + 2]; var position = new Vector3(_x, _y, z); position.applyMatrix4(pc.matrixWorld); point[attributeName] = position; } else if (attributeName === 'indices') {} else { var values = attribute.array.slice(attribute.itemSize * _hit.pIndex, attribute.itemSize * (_hit.pIndex + 1)); if (attribute.potree) { var { scale, offset: _offset } = attribute.potree; values = values.map(v => v / scale + _offset); } point[attributeName] = values; //debugger; //if (values.itemSize === 1) { // point[attribute.name] = values.array[hit.pIndex]; //} else { // let value = []; // for (let j = 0; j < values.itemSize; j++) { // value.push(values.array[values.itemSize * hit.pIndex + j]); // } // point[attribute.name] = value; //} } }; for (var attributeName in geometry.attributes) { _loop2(); } _hit.point = point; } performance.mark("pick-end"); performance.measure("pick", "pick-start", "pick-end"); if (params.all) { return hits.map(hit => hit.point); } else { if (hits.length === 0) { return null; } else { return hits[0].point; //let sorted = hits.sort( (a, b) => a.distanceToCenter - b.distanceToCenter); //return sorted[0].point; } } } *getFittedBoxGen(boxNode) { var start = performance.now(); var shrinkedLocalBounds = new Box3(); var worldToBox = boxNode.matrixWorld.clone().invert(); for (var node of this.visibleNodes) { if (!node.sceneNode) { continue; } var buffer = node.geometryNode.buffer; var posOffset = buffer.offset("position"); var stride = buffer.stride; var view = new DataView(buffer.data); var objectToBox = new Matrix4().multiplyMatrices(worldToBox, node.sceneNode.matrixWorld); var pos = new Vector4(); for (var i = 0; i < buffer.numElements; i++) { var x = view.getFloat32(i * stride + posOffset + 0, true); var y = view.getFloat32(i * stride + posOffset + 4, true); var z = view.getFloat32(i * stride + posOffset + 8, true); pos.set(x, y, z, 1); pos.applyMatrix4(objectToBox); if (-0.5 < pos.x && pos.x < 0.5) { if (-0.5 < pos.y && pos.y < 0.5) { if (-0.5 < pos.z && pos.z < 0.5) { shrinkedLocalBounds.expandByPoint(pos); } } } } yield; } var fittedPosition = shrinkedLocalBounds.getCenter(new Vector3()).applyMatrix4(boxNode.matrixWorld); var fitted = new Object3D(); fitted.position.copy(fittedPosition); fitted.scale.copy(boxNode.scale); fitted.rotation.copy(boxNode.rotation); var ds = new Vector3().subVectors(shrinkedLocalBounds.max, shrinkedLocalBounds.min); fitted.scale.multiply(ds); var duration = performance.now() - start; console.log("duration: ", duration); yield fitted; } getFittedBox(boxNode) { var maxLevel = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Infinity; maxLevel = Infinity; var start = performance.now(); var shrinkedLocalBounds = new Box3(); var worldToBox = boxNode.matrixWorld.clone().invert(); for (var node of this.visibleNodes) { if (!node.sceneNode || node.getLevel() > maxLevel) { continue; } var buffer = node.geometryNode.buffer; var posOffset = buffer.offset("position"); var stride = buffer.stride; var view = new DataView(buffer.data); var objectToBox = new Matrix4().multiplyMatrices(worldToBox, node.sceneNode.matrixWorld); var pos = new Vector4(); for (var i = 0; i < buffer.numElements; i++) { var x = view.getFloat32(i * stride + posOffset + 0, true); var y = view.getFloat32(i * stride + posOffset + 4, true); var z = view.getFloat32(i * stride + posOffset + 8, true); pos.set(x, y, z, 1); pos.applyMatrix4(objectToBox); if (-0.5 < pos.x && pos.x < 0.5) { if (-0.5 < pos.y && pos.y < 0.5) { if (-0.5 < pos.z && pos.z < 0.5) { shrinkedLocalBounds.expandByPoint(pos); } } } } } var fittedPosition = shrinkedLocalBounds.getCenter(new Vector3()).applyMatrix4(boxNode.matrixWorld); var fitted = new Object3D(); fitted.position.copy(fittedPosition); fitted.scale.copy(boxNode.scale); fitted.rotation.copy(boxNode.rotation); var ds = new Vector3().subVectors(shrinkedLocalBounds.max, shrinkedLocalBounds.min); fitted.scale.multiply(ds); var duration = performance.now() - start; console.log("duration: ", duration); return fitted; } get progress() { return this.visibleNodes.length / this.visibleGeometry.length; } find(name) { var node = null; for (var char of name) { if (char === "r") { node = this.root; } else { node = node.children[char]; } } return node; } get visible() { return this._visible; } set visible(value) { if (value !== this._visible) { this._visible = value; this.dispatchEvent({ type: 'visibility_changed', pointcloud: this }); } } } class PointCloudArena4DNode extends PointCloudTreeNode { constructor() { super(); this.left = null; this.right = null; this.sceneNode = null; this.kdtree = null; } getNumPoints() { return this.geometryNode.numPoints; } isLoaded() { return true; } isTreeNode() { return true; } isGeometryNode() { return false; } getLevel() { return this.geometryNode.level; } getBoundingSphere() { return this.geometryNode.boundingSphere; } getBoundingBox() { return this.geometryNode.boundingBox; } toTreeNode(child) { var geometryNode = null; if (this.left === child) { geometryNode = this.left; } else if (this.right === child) { geometryNode = this.right; } if (!geometryNode.loaded) { return; } var node = new PointCloudArena4DNode(); var sceneNode = PointCloud(geometryNode.geometry, this.kdtree.material); sceneNode.visible = false; node.kdtree = this.kdtree; node.geometryNode = geometryNode; node.sceneNode = sceneNode; node.parent = this; node.left = this.geometryNode.left; node.right = this.geometryNode.right; } getChildren() { var children = []; if (this.left) { children.push(this.left); } if (this.right) { children.push(this.right); } return children; } } ; class PointCloudArena4D$1 extends PointCloudTree { constructor(geometry) { super(); this.root = null; if (geometry.root) { this.root = geometry.root; } else { geometry.addEventListener('hierarchy_loaded', () => { this.root = geometry.root; }); } this.visiblePointsTarget = 2 * 1000 * 1000; this.minimumNodePixelSize = 150; this.position.sub(geometry.offset); this.updateMatrix(); this.numVisibleNodes = 0; this.numVisiblePoints = 0; this.boundingBoxNodes = []; this.loadQueue = []; this.visibleNodes = []; this.pcoGeometry = geometry; this.boundingBox = this.pcoGeometry.boundingBox; this.boundingSphere = this.pcoGeometry.boundingSphere; this.material = new PointCloudMaterial$1({ vertexColors: VertexColors, size: 0.05, treeType: TreeType.KDTREE }); this.material.sizeType = PointSizeType.ATTENUATED; this.material.size = 0.05; this.profileRequests = []; this.name = ''; } getBoundingBoxWorld() { this.updateMatrixWorld(true); var box = this.boundingBox; var transform = this.matrixWorld; var tBox = Utils.computeTransformedBoundingBox(box, transform); return tBox; } setName(name) { if (this.name !== name) { this.name = name; this.dispatchEvent({ type: 'name_changed', name: name, pointcloud: this }); } } getName() { return this.name; } getLevel() { return this.level; } toTreeNode(geometryNode, parent) { var node = new PointCloudArena4DNode(); var sceneNode = new Points(geometryNode.geometry, this.material); sceneNode.frustumCulled = false; sceneNode.onBeforeRender = (_this, scene, camera, geometry, material, group) => { if (material.program) { _this.getContext().useProgram(material.program.program); if (material.program.getUniforms().map.level) { var level = geometryNode.getLevel(); material.uniforms.level.value = level; material.program.getUniforms().map.level.setValue(_this.getContext(), level); } if (this.visibleNodeTextureOffsets && material.program.getUniforms().map.vnStart) { var vnStart = this.visibleNodeTextureOffsets.get(node); material.uniforms.vnStart.value = vnStart; material.program.getUniforms().map.vnStart.setValue(_this.getContext(), vnStart); } if (material.program.getUniforms().map.pcIndex) { var i = node.pcIndex ? node.pcIndex : this.visibleNodes.indexOf(node); material.uniforms.pcIndex.value = i; material.program.getUniforms().map.pcIndex.setValue(_this.getContext(), i); } } }; node.geometryNode = geometryNode; node.sceneNode = sceneNode; node.pointcloud = this; node.left = geometryNode.left; node.right = geometryNode.right; if (!parent) { this.root = node; this.add(sceneNode); } else { parent.sceneNode.add(sceneNode); if (parent.left === geometryNode) { parent.left = node; } else if (parent.right === geometryNode) { parent.right = node; } } var disposeListener = function disposeListener() { parent.sceneNode.remove(node.sceneNode); if (parent.left === node) { parent.left = geometryNode; } else if (parent.right === node) { parent.right = geometryNode; } }; geometryNode.oneTimeDisposeHandlers.push(disposeListener); return node; } updateMaterial(material, visibleNodes, camera, renderer) { material.fov = camera.fov * (Math.PI / 180); material.screenWidth = renderer.domElement.clientWidth; material.screenHeight = renderer.domElement.clientHeight; material.spacing = this.pcoGeometry.spacing; material.near = camera.near; material.far = camera.far; // reduce shader source updates by setting maxLevel slightly higher than actually necessary if (this.maxLevel > material.levels) { material.levels = this.maxLevel + 2; } // material.uniforms.octreeSize.value = this.boundingBox.size().x; var bbSize = this.boundingBox.getSize(new Vector3()); material.bbSize = [bbSize.x, bbSize.y, bbSize.z]; } updateVisibleBounds() {} hideDescendants(object) { var stack = []; for (var i = 0; i < object.children.length; i++) { var child = object.children[i]; if (child.visible) { stack.push(child); } } while (stack.length > 0) { var _child = stack.shift(); _child.visible = false; if (_child.boundingBoxNode) { _child.boundingBoxNode.visible = false; } for (var _i = 0; _i < _child.children.length; _i++) { var childOfChild = _child.children[_i]; if (childOfChild.visible) { stack.push(childOfChild); } } } } updateMatrixWorld(force) { // node.matrixWorld.multiplyMatrices( node.parent.matrixWorld, node.matrix ); if (this.matrixAutoUpdate === true) this.updateMatrix(); if (this.matrixWorldNeedsUpdate === true || force === true) { if (this.parent === undefined) { this.matrixWorld.copy(this.matrix); } else { this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); } this.matrixWorldNeedsUpdate = false; force = true; } } nodesOnRay(nodes, ray) { var nodesOnRay = []; var _ray = ray.clone(); for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; var sphere = node.getBoundingSphere().clone().applyMatrix4(node.sceneNode.matrixWorld); // TODO Unused: let box = node.getBoundingBox().clone().applyMatrix4(node.sceneNode.matrixWorld); if (_ray.intersectsSphere(sphere)) { nodesOnRay.push(node); } // if(_ray.isIntersectionBox(box)){ // nodesOnRay.push(node); // } } return nodesOnRay; } pick(viewer, camera, ray) { var params = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var renderer = viewer.renderer; var pRenderer = viewer.pRenderer; performance.mark("pick-start"); var getVal = (a, b) => a !== undefined ? a : b; var pickWindowSize = getVal(params.pickWindowSize, 17); var pickOutsideClipRegion = getVal(params.pickOutsideClipRegion, false); var size = renderer.getSize(new Vector2()); var width = Math.ceil(getVal(params.width, size.width)); var height = Math.ceil(getVal(params.height, size.height)); var pointSizeType = getVal(params.pointSizeType, this.material.pointSizeType); var pointSize = getVal(params.pointSize, this.material.size); var nodes = this.nodesOnRay(this.visibleNodes, ray); if (nodes.length === 0) { return null; } if (!this.pickState) { var scene = new Scene(); var material = new PointCloudMaterial$1(); material.activeAttributeName = "indices"; var renderTarget = new WebGLRenderTarget(1, 1, { minFilter: LinearFilter, magFilter: NearestFilter, format: RGBAFormat }); this.pickState = { renderTarget: renderTarget, material: material, scene: scene }; } ; var pickState = this.pickState; var pickMaterial = pickState.material; { // update pick material pickMaterial.pointSizeType = pointSizeType; pickMaterial.shape = this.material.shape; pickMaterial.size = pointSize; pickMaterial.uniforms.minSize.value = this.material.uniforms.minSize.value; pickMaterial.uniforms.maxSize.value = this.material.uniforms.maxSize.value; pickMaterial.classification = this.material.classification; if (params.pickClipped) { pickMaterial.clipBoxes = this.material.clipBoxes; if (this.material.clipTask === ClipTask.HIGHLIGHT) { pickMaterial.clipTask = ClipTask.NONE; } else { pickMaterial.clipTask = this.material.clipTask; } } else { pickMaterial.clipBoxes = []; } this.updateMaterial(pickMaterial, nodes, camera, renderer); } pickState.renderTarget.setSize(width, height); var pixelPos = new Vector2(params.x, params.y); var gl = renderer.getContext(); gl.enable(gl.SCISSOR_TEST); gl.scissor(parseInt(pixelPos.x - (pickWindowSize - 1) / 2), parseInt(pixelPos.y - (pickWindowSize - 1) / 2), parseInt(pickWindowSize), parseInt(pickWindowSize)); renderer.state.buffers.depth.setTest(pickMaterial.depthTest); renderer.state.buffers.depth.setMask(pickMaterial.depthWrite); renderer.state.setBlending(NoBlending); renderer.clearTarget(pickState.renderTarget, true, true, true); { // RENDER renderer.setRenderTarget(pickState.renderTarget); gl.clearColor(0, 0, 0, 0); renderer.clearTarget(pickState.renderTarget, true, true, true); var tmp = this.material; this.material = pickMaterial; pRenderer.renderOctree(this, nodes, camera, pickState.renderTarget); this.material = tmp; } var clamp = (number, min, max) => Math.min(Math.max(min, number), max); var x = parseInt(clamp(pixelPos.x - (pickWindowSize - 1) / 2, 0, width)); var y = parseInt(clamp(pixelPos.y - (pickWindowSize - 1) / 2, 0, height)); var w = parseInt(Math.min(x + pickWindowSize, width) - x); var h = parseInt(Math.min(y + pickWindowSize, height) - y); var pixelCount = w * h; var buffer = new Uint8Array(4 * pixelCount); gl.readPixels(x, y, pickWindowSize, pickWindowSize, gl.RGBA, gl.UNSIGNED_BYTE, buffer); renderer.setRenderTarget(null); renderer.state.reset(); renderer.setScissorTest(false); gl.disable(gl.SCISSOR_TEST); var pixels = buffer; var ibuffer = new Uint32Array(buffer.buffer); // find closest hit inside pixelWindow boundaries var min = Number.MAX_VALUE; var hits = []; for (var u = 0; u < pickWindowSize; u++) { for (var v = 0; v < pickWindowSize; v++) { var offset = u + v * pickWindowSize; var distance = Math.pow(u - (pickWindowSize - 1) / 2, 2) + Math.pow(v - (pickWindowSize - 1) / 2, 2); var pcIndex = pixels[4 * offset + 3]; pixels[4 * offset + 3] = 0; var pIndex = ibuffer[offset]; if (!(pcIndex === 0 && pIndex === 0) && pcIndex !== undefined && pIndex !== undefined) { var hit = { pIndex: pIndex, pcIndex: pcIndex, distanceToCenter: distance }; if (params.all) { hits.push(hit); } else { if (hits.length > 0) { if (distance < hits[0].distanceToCenter) { hits[0] = hit; } } else { hits.push(hit); } } } } } for (var _hit of hits) { var point = {}; if (!nodes[_hit.pcIndex]) { return null; } var node = nodes[_hit.pcIndex]; var pc = node.sceneNode; var geometry = node.geometryNode.geometry; for (var attributeName in geometry.attributes) { var attribute = geometry.attributes[attributeName]; if (attributeName === 'position') { var _x = attribute.array[3 * _hit.pIndex + 0]; var _y = attribute.array[3 * _hit.pIndex + 1]; var z = attribute.array[3 * _hit.pIndex + 2]; var position = new Vector3(_x, _y, z); position.applyMatrix4(pc.matrixWorld); point[attributeName] = position; } else if (attributeName === 'indices') {} else { //if (values.itemSize === 1) { // point[attribute.name] = values.array[hit.pIndex]; //} else { // let value = []; // for (let j = 0; j < values.itemSize; j++) { // value.push(values.array[values.itemSize * hit.pIndex + j]); // } // point[attribute.name] = value; //} } } _hit.point = point; } performance.mark("pick-end"); performance.measure("pick", "pick-start", "pick-end"); if (params.all) { return hits.map(hit => hit.point); } else { if (hits.length === 0) { return null; } else { return hits[0].point; } } } computeVisibilityTextureData(nodes) { if (exports.measureTimings) performance.mark("computeVisibilityTextureData-start"); var data = new Uint8Array(nodes.length * 3); var visibleNodeTextureOffsets = new Map(); // copy array nodes = nodes.slice(); // sort by level and number var sort = function sort(a, b) { var la = a.geometryNode.level; var lb = b.geometryNode.level; var na = a.geometryNode.number; var nb = b.geometryNode.number; if (la !== lb) return la - lb; if (na < nb) return -1; if (na > nb) return 1; return 0; }; nodes.sort(sort); var visibleNodeNames = []; for (var i = 0; i < nodes.length; i++) { visibleNodeNames.push(nodes[i].geometryNode.number); } for (var _i2 = 0; _i2 < nodes.length; _i2++) { var node = nodes[_i2]; visibleNodeTextureOffsets.set(node, _i2); var b1 = 0; // children var b2 = 0; // offset to first child var b3 = 0; // split if (node.geometryNode.left && visibleNodeNames.indexOf(node.geometryNode.left.number) > 0) { b1 += 1; b2 = visibleNodeNames.indexOf(node.geometryNode.left.number) - _i2; } if (node.geometryNode.right && visibleNodeNames.indexOf(node.geometryNode.right.number) > 0) { b1 += 2; b2 = b2 === 0 ? visibleNodeNames.indexOf(node.geometryNode.right.number) - _i2 : b2; } if (node.geometryNode.split === 'X') { b3 = 1; } else if (node.geometryNode.split === 'Y') { b3 = 2; } else if (node.geometryNode.split === 'Z') { b3 = 4; } data[_i2 * 3 + 0] = b1; data[_i2 * 3 + 1] = b2; data[_i2 * 3 + 2] = b3; } if (exports.measureTimings) { performance.mark("computeVisibilityTextureData-end"); performance.measure("render.computeVisibilityTextureData", "computeVisibilityTextureData-start", "computeVisibilityTextureData-end"); } return { data: data, offsets: visibleNodeTextureOffsets }; } get progress() { if (this.pcoGeometry.root) { return exports.numNodesLoading > 0 ? 0 : 1; } else { return 0; } } } ; // Copied from three.js: WebGLRenderer.js function paramThreeToGL(_gl, 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$1) 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$1) 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; } ; var attributeLocations = { "position": { name: "position", location: 0 }, "color": { name: "color", location: 1 }, "rgba": { name: "color", location: 1 }, "intensity": { name: "intensity", location: 2 }, "classification": { name: "classification", location: 3 }, "returnNumber": { name: "returnNumber", location: 4 }, "return number": { name: "returnNumber", location: 4 }, "returns": { name: "returnNumber", location: 4 }, "numberOfReturns": { name: "numberOfReturns", location: 5 }, "number of returns": { name: "numberOfReturns", location: 5 }, "pointSourceID": { name: "pointSourceID", location: 6 }, "source id": { name: "pointSourceID", location: 6 }, "point source id": { name: "pointSourceID", location: 6 }, "indices": { name: "indices", location: 7 }, "normal": { name: "normal", location: 8 }, "spacing": { name: "spacing", location: 9 }, "gps-time": { name: "gpsTime", location: 10 }, "aExtra": { name: "aExtra", location: 11 } }; class Shader { constructor(gl, name, vsSource, fsSource) { this.gl = gl; this.name = name; this.vsSource = vsSource; this.fsSource = fsSource; this.cache = new Map(); this.vs = null; this.fs = null; this.program = null; this.uniformLocations = {}; this.attributeLocations = {}; this.uniformBlockIndices = {}; this.uniformBlocks = {}; this.uniforms = {}; this.update(vsSource, fsSource); } update(vsSource, fsSource) { this.vsSource = vsSource; this.fsSource = fsSource; this.linkProgram(); } compileShader(shader, source) { var gl = this.gl; gl.shaderSource(shader, source); gl.compileShader(shader); var success = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (!success) { var info = gl.getShaderInfoLog(shader); var numberedSource = source.split("\n").map((a, i) => "".concat(i + 1).padEnd(5) + a).join("\n"); throw "could not compile shader ".concat(this.name, ": ").concat(info, ", \n").concat(numberedSource); } } linkProgram() { var tStart = performance.now(); var gl = this.gl; this.uniformLocations = {}; this.attributeLocations = {}; this.uniforms = {}; gl.useProgram(null); var cached = this.cache.get("".concat(this.vsSource, ", ").concat(this.fsSource)); if (cached) { this.program = cached.program; this.vs = cached.vs; this.fs = cached.fs; this.attributeLocations = cached.attributeLocations; this.uniformLocations = cached.uniformLocations; this.uniformBlocks = cached.uniformBlocks; this.uniforms = cached.uniforms; return; } else { this.vs = gl.createShader(gl.VERTEX_SHADER); this.fs = gl.createShader(gl.FRAGMENT_SHADER); this.program = gl.createProgram(); for (var name of Object.keys(attributeLocations)) { var location = attributeLocations[name].location; var glslName = attributeLocations[name].name; gl.bindAttribLocation(this.program, location, glslName); } this.compileShader(this.vs, this.vsSource); this.compileShader(this.fs, this.fsSource); var program = this.program; gl.attachShader(program, this.vs); gl.attachShader(program, this.fs); gl.linkProgram(program); gl.detachShader(program, this.vs); gl.detachShader(program, this.fs); var success = gl.getProgramParameter(program, gl.LINK_STATUS); if (!success) { var info = gl.getProgramInfoLog(program); throw "could not link program ".concat(this.name, ": ").concat(info); } { // attribute locations var numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); for (var i = 0; i < numAttributes; i++) { var attribute = gl.getActiveAttrib(program, i); var _location = gl.getAttribLocation(program, attribute.name); this.attributeLocations[attribute.name] = _location; } } { // uniform locations var numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); for (var _i = 0; _i < numUniforms; _i++) { var uniform = gl.getActiveUniform(program, _i); var _location2 = gl.getUniformLocation(program, uniform.name); this.uniformLocations[uniform.name] = _location2; this.uniforms[uniform.name] = { location: _location2, value: null }; } } // uniform blocks if (typeof WebGL2RenderingContext != 'undefined' && gl instanceof WebGL2RenderingContext) { var numBlocks = gl.getProgramParameter(program, gl.ACTIVE_UNIFORM_BLOCKS); for (var _i2 = 0; _i2 < numBlocks; _i2++) { var blockName = gl.getActiveUniformBlockName(program, _i2); var blockIndex = gl.getUniformBlockIndex(program, blockName); this.uniformBlockIndices[blockName] = blockIndex; gl.uniformBlockBinding(program, blockIndex, blockIndex); var dataSize = gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_DATA_SIZE); var uBuffer = gl.createBuffer(); gl.bindBuffer(gl.UNIFORM_BUFFER, uBuffer); gl.bufferData(gl.UNIFORM_BUFFER, dataSize, gl.DYNAMIC_READ); gl.bindBufferBase(gl.UNIFORM_BUFFER, blockIndex, uBuffer); gl.bindBuffer(gl.UNIFORM_BUFFER, null); this.uniformBlocks[blockName] = { name: blockName, index: blockIndex, dataSize: dataSize, buffer: uBuffer }; } } var _cached = { program: this.program, vs: this.vs, fs: this.fs, attributeLocations: this.attributeLocations, uniformLocations: this.uniformLocations, uniforms: this.uniforms, uniformBlocks: this.uniformBlocks }; this.cache.set("".concat(this.vsSource, ", ").concat(this.fsSource), _cached); } var tEnd = performance.now(); var duration = tEnd - tStart; console.log("shader compile duration: ".concat(duration.toFixed(3))); } setUniformMatrix4(name, value) { var gl = this.gl; var location = this.uniformLocations[name]; if (location == null) { return; } var tmp = new Float32Array(value.elements); gl.uniformMatrix4fv(location, false, tmp); } setUniform1f(name, value) { var gl = this.gl; var uniform = this.uniforms[name]; if (uniform === undefined) { return; } if (uniform.value === value) { return; } uniform.value = value; gl.uniform1f(uniform.location, value); } setUniformBoolean(name, value) { var gl = this.gl; var uniform = this.uniforms[name]; if (uniform === undefined) { return; } if (uniform.value === value) { return; } uniform.value = value; gl.uniform1i(uniform.location, value); } setUniformTexture(name, value) { var gl = this.gl; var location = this.uniformLocations[name]; if (location == null) { return; } gl.uniform1i(location, value); } setUniform2f(name, value) { var gl = this.gl; var location = this.uniformLocations[name]; if (location == null) { return; } gl.uniform2f(location, value[0], value[1]); } setUniform3f(name, value) { var gl = this.gl; var location = this.uniformLocations[name]; if (location == null) { return; } gl.uniform3f(location, value[0], value[1], value[2]); } setUniform(name, value) { if (value.constructor === Matrix4) { this.setUniformMatrix4(name, value); } else if (typeof value === "number") { this.setUniform1f(name, value); } else if (typeof value === "boolean") { this.setUniformBoolean(name, value); } else if (value instanceof WebGLTexture) { this.setUniformTexture(name, value); } else if (value instanceof Array) { if (value.length === 2) { this.setUniform2f(name, value); } else if (value.length === 3) { this.setUniform3f(name, value); } } else { console.error("unhandled uniform type: ", name, value); } } setUniform1i(name, value) { var gl = this.gl; var location = this.uniformLocations[name]; if (location == null) { return; } gl.uniform1i(location, value); } } ; class WebGLTexture { constructor(gl, texture) { this.gl = gl; this.texture = texture; this.id = gl.createTexture(); this.target = gl.TEXTURE_2D; this.version = -1; this.update(texture); } update() { if (!this.texture.image) { this.version = this.texture.version; return; } var gl = this.gl; var texture = this.texture; if (this.version === texture.version) { return; } this.target = gl.TEXTURE_2D; gl.bindTexture(this.target, this.id); var level = 0; var internalFormat = paramThreeToGL(gl, texture.format); var width = texture.image.width; var height = texture.image.height; var border = 0; var srcFormat = internalFormat; var srcType = paramThreeToGL(gl, texture.type); var data; 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); if (texture instanceof DataTexture) { data = texture.image.data; gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL(gl, texture.magFilter)); gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL(gl, texture.minFilter)); gl.texImage2D(this.target, level, internalFormat, width, height, border, srcFormat, srcType, data); } else if (texture instanceof CanvasTexture || texture instanceof Texture) { data = texture.image; gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, paramThreeToGL(gl, texture.wrapS)); gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, paramThreeToGL(gl, texture.wrapT)); gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL(gl, texture.magFilter)); gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL(gl, texture.minFilter)); gl.texImage2D(this.target, level, internalFormat, internalFormat, srcType, data); if (texture instanceof Texture) { gl.generateMipmap(gl.TEXTURE_2D); } } gl.bindTexture(this.target, null); this.version = texture.version; } } ; class WebGLBuffer { constructor() { this.numElements = 0; this.vao = null; this.vbos = new Map(); } } ; class Renderer { constructor(threeRenderer) { this.threeRenderer = threeRenderer; this.gl = this.threeRenderer.getContext(); this.buffers = new Map(); this.shaders = new Map(); this.textures = new Map(); this.glTypeMapping = new Map(); this.glTypeMapping.set(Float32Array, this.gl.FLOAT); this.glTypeMapping.set(Uint8Array, this.gl.UNSIGNED_BYTE); this.glTypeMapping.set(Uint16Array, this.gl.UNSIGNED_SHORT); this.toggle = 0; } deleteBuffer(geometry) { var gl = this.gl; var webglBuffer = this.buffers.get(geometry); if (webglBuffer != null) { for (var attributeName in geometry.attributes) { gl.deleteBuffer(webglBuffer.vbos.get(attributeName).handle); } this.buffers.delete(geometry); } } createBuffer(geometry) { var gl = this.gl; var webglBuffer = new WebGLBuffer(); webglBuffer.vao = gl.createVertexArray(); webglBuffer.numElements = geometry.attributes.position.count; gl.bindVertexArray(webglBuffer.vao); for (var attributeName in geometry.attributes) { var bufferAttribute = geometry.attributes[attributeName]; var vbo = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vbo); gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW); var normalized = bufferAttribute.normalized; var type = this.glTypeMapping.get(bufferAttribute.array.constructor); if (attributeLocations[attributeName] === undefined) { //attributeLocation = attributeLocations["aExtra"]; } else { var attributeLocation = attributeLocations[attributeName].location; gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0); gl.enableVertexAttribArray(attributeLocation); } webglBuffer.vbos.set(attributeName, { handle: vbo, name: attributeName, count: bufferAttribute.count, itemSize: bufferAttribute.itemSize, type: geometry.attributes.position.array.constructor, version: 0 }); } gl.bindBuffer(gl.ARRAY_BUFFER, null); gl.bindVertexArray(null); var disposeHandler = event => { this.deleteBuffer(geometry); geometry.removeEventListener("dispose", disposeHandler); }; geometry.addEventListener("dispose", disposeHandler); return webglBuffer; } updateBuffer(geometry) { var gl = this.gl; var webglBuffer = this.buffers.get(geometry); gl.bindVertexArray(webglBuffer.vao); for (var attributeName in geometry.attributes) { var bufferAttribute = geometry.attributes[attributeName]; var normalized = bufferAttribute.normalized; var type = this.glTypeMapping.get(bufferAttribute.array.constructor); var vbo = null; if (!webglBuffer.vbos.has(attributeName)) { vbo = gl.createBuffer(); webglBuffer.vbos.set(attributeName, { handle: vbo, name: attributeName, count: bufferAttribute.count, itemSize: bufferAttribute.itemSize, type: geometry.attributes.position.array.constructor, version: bufferAttribute.version }); } else { vbo = webglBuffer.vbos.get(attributeName).handle; webglBuffer.vbos.get(attributeName).version = bufferAttribute.version; } gl.bindBuffer(gl.ARRAY_BUFFER, vbo); gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW); if (attributeLocations[attributeName] === undefined) { //attributeLocation = attributeLocations["aExtra"]; } else { var attributeLocation = attributeLocations[attributeName].location; gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0); gl.enableVertexAttribArray(attributeLocation); } } gl.bindBuffer(gl.ARRAY_BUFFER, null); gl.bindVertexArray(null); } traverse(scene) { var octrees = []; var stack = [scene]; while (stack.length > 0) { var node = stack.pop(); if (node instanceof PointCloudTree) { octrees.push(node); continue; } var visibleChildren = node.children.filter(c => c.visible); stack.push(...visibleChildren); } var result = { octrees: octrees }; return result; } renderNodes(octree, nodes, visibilityTextureData, camera, target, shader, params) { var _this = this; if (exports.measureTimings) performance.mark("renderNodes-start"); var gl = this.gl; var material = params.material ? params.material : octree.material; var shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps; var view = camera.matrixWorldInverse; if (params.viewOverride) { view = params.viewOverride; } var worldView = new Matrix4(); var mat4holder = new Float32Array(16); var i = 0; var _loop = function _loop() { if (exports.debug.allowedNodes !== undefined) { if (!exports.debug.allowedNodes.includes(node.name)) { return 1; // continue } } var world = node.sceneNode.matrixWorld; worldView.multiplyMatrices(view, world); if (visibilityTextureData) { var vnStart = visibilityTextureData.offsets.get(node); shader.setUniform1f("uVNStart", vnStart); } var level = node.getLevel(); if (node.debug) { shader.setUniform("uDebug", true); } else { shader.setUniform("uDebug", false); } // let isLeaf = false; // if(node instanceof PointCloudOctreeNode){ // isLeaf = Object.keys(node.children).length === 0; // }else if(node instanceof PointCloudArena4DNode){ // isLeaf = node.geometryNode.isLeaf; // } // shader.setUniform("uIsLeafNode", isLeaf); // let isLeaf = node.children.filter(n => n != null).length === 0; // if(!isLeaf){ // continue; // } // TODO consider passing matrices in an array to avoid uniformMatrix4fv overhead var lModel = shader.uniformLocations["modelMatrix"]; if (lModel) { mat4holder.set(world.elements); gl.uniformMatrix4fv(lModel, false, mat4holder); } var lModelView = shader.uniformLocations["modelViewMatrix"]; //mat4holder.set(worldView.elements); // faster then set in chrome 63 for (var j = 0; j < 16; j++) { mat4holder[j] = worldView.elements[j]; } gl.uniformMatrix4fv(lModelView, false, mat4holder); { // Clip Polygons if (material.clipPolygons && material.clipPolygons.length > 0) { var clipPolygonVCount = []; var worldViewProjMatrices = []; for (var clipPolygon of material.clipPolygons) { var _view = clipPolygon.viewMatrix; var proj = clipPolygon.projMatrix; var worldViewProj = proj.clone().multiply(_view).multiply(world); clipPolygonVCount.push(clipPolygon.markers.length); worldViewProjMatrices.push(worldViewProj); } var flattenedMatrices = [].concat(...worldViewProjMatrices.map(m => m.elements)); var flattenedVertices = new Array(8 * 3 * material.clipPolygons.length); for (var _i3 = 0; _i3 < material.clipPolygons.length; _i3++) { var _clipPolygon = material.clipPolygons[_i3]; for (var _j = 0; _j < _clipPolygon.markers.length; _j++) { flattenedVertices[_i3 * 24 + (_j * 3 + 0)] = _clipPolygon.markers[_j].position.x; flattenedVertices[_i3 * 24 + (_j * 3 + 1)] = _clipPolygon.markers[_j].position.y; flattenedVertices[_i3 * 24 + (_j * 3 + 2)] = _clipPolygon.markers[_j].position.z; } } var lClipPolygonVCount = shader.uniformLocations["uClipPolygonVCount[0]"]; gl.uniform1iv(lClipPolygonVCount, clipPolygonVCount); var lClipPolygonVP = shader.uniformLocations["uClipPolygonWVP[0]"]; gl.uniformMatrix4fv(lClipPolygonVP, false, flattenedMatrices); var lClipPolygons = shader.uniformLocations["uClipPolygonVertices[0]"]; gl.uniform3fv(lClipPolygons, flattenedVertices); } } //shader.setUniformMatrix4("modelMatrix", world); //shader.setUniformMatrix4("modelViewMatrix", worldView); shader.setUniform1f("uLevel", level); shader.setUniform1f("uNodeSpacing", node.geometryNode.estimatedSpacing); shader.setUniform1f("uPCIndex", i); // uBBSize if (shadowMaps.length > 0) { var lShadowMap = shader.uniformLocations["uShadowMap[0]"]; shader.setUniform3f("uShadowColor", material.uniforms.uShadowColor.value); var bindingStart = 5; var bindingPoints = new Array(shadowMaps.length).fill(bindingStart).map((a, i) => a + i); gl.uniform1iv(lShadowMap, bindingPoints); for (var _i4 = 0; _i4 < shadowMaps.length; _i4++) { var shadowMap = shadowMaps[_i4]; var bindingPoint = bindingPoints[_i4]; var glTexture = _this.threeRenderer.properties.get(shadowMap.target.texture).__webglTexture; gl.activeTexture(gl["TEXTURE".concat(bindingPoint)]); gl.bindTexture(gl.TEXTURE_2D, glTexture); } { var worldViewMatrices = shadowMaps.map(sm => sm.camera.matrixWorldInverse).map(view => new Matrix4().multiplyMatrices(view, world)); var _flattenedMatrices = [].concat(...worldViewMatrices.map(c => c.elements)); var lWorldView = shader.uniformLocations["uShadowWorldView[0]"]; gl.uniformMatrix4fv(lWorldView, false, _flattenedMatrices); } { var _flattenedMatrices2 = [].concat(...shadowMaps.map(sm => sm.camera.projectionMatrix.elements)); var lProj = shader.uniformLocations["uShadowProj[0]"]; gl.uniformMatrix4fv(lProj, false, _flattenedMatrices2); } } var geometry = node.geometryNode.geometry; if (geometry.attributes["gps-time"]) { var bufferAttribute = geometry.attributes["gps-time"]; var attGPS = octree.getAttribute("gps-time"); var initialRange = attGPS.initialRange; var initialRangeSize = initialRange[1] - initialRange[0]; var globalRange = attGPS.range; var globalRangeSize = globalRange[1] - globalRange[0]; var scale = initialRangeSize / globalRangeSize; var offset = -(globalRange[0] - initialRange[0]) / initialRangeSize; scale = Number.isNaN(scale) ? 1 : scale; offset = Number.isNaN(offset) ? 0 : offset; shader.setUniform1f("uGpsScale", scale); shader.setUniform1f("uGpsOffset", offset); //shader.setUniform2f("uFilterGPSTimeClipRange", [-Infinity, Infinity]); var uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value; // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0] // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1] // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]); var normalizedClipRange = [(uFilterGPSTimeClipRange[0] - globalRange[0]) / globalRangeSize, (uFilterGPSTimeClipRange[1] - globalRange[0]) / globalRangeSize]; shader.setUniform2f("uFilterGPSTimeClipRange", normalizedClipRange); // // ranges in full gps coordinate system // const globalRange = attGPS.range; // const bufferRange = bufferAttribute.potree.range; // // ranges in [0, 1] // // normalizedGlobalRange = [0, 1] // // normalizedBufferRange: norm buffer within norm global range e.g. [0.2, 0.8] // const globalWidth = globalRange[1] - globalRange[0]; // const normalizedBufferRange = [ // (bufferRange[0] - globalRange[0]) / globalWidth, // (bufferRange[1] - globalRange[0]) / globalWidth, // ]; // shader.setUniform2f("uNormalizedGpsBufferRange", normalizedBufferRange); // let uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value; // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0] // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1] // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]); // shader.setUniform1f("uGpsScale", bufferAttribute.potree.scale); // shader.setUniform1f("uGpsOffset", bufferAttribute.potree.offset); } { var uFilterReturnNumberRange = material.uniforms.uFilterReturnNumberRange.value; var uFilterNumberOfReturnsRange = material.uniforms.uFilterNumberOfReturnsRange.value; var uFilterPointSourceIDClipRange = material.uniforms.uFilterPointSourceIDClipRange.value; shader.setUniform2f("uFilterReturnNumberRange", uFilterReturnNumberRange); shader.setUniform2f("uFilterNumberOfReturnsRange", uFilterNumberOfReturnsRange); shader.setUniform2f("uFilterPointSourceIDClipRange", uFilterPointSourceIDClipRange); } var webglBuffer = null; if (!_this.buffers.has(geometry)) { webglBuffer = _this.createBuffer(geometry); _this.buffers.set(geometry, webglBuffer); } else { webglBuffer = _this.buffers.get(geometry); for (var attributeName in geometry.attributes) { var attribute = geometry.attributes[attributeName]; if (attribute.version > webglBuffer.vbos.get(attributeName).version) { _this.updateBuffer(geometry); } } } gl.bindVertexArray(webglBuffer.vao); var isExtraAttribute = attributeLocations[material.activeAttributeName] === undefined && Object.keys(geometry.attributes).includes(material.activeAttributeName); if (isExtraAttribute) { var attributeLocation = attributeLocations["aExtra"].location; for (var _attributeName in geometry.attributes) { var _bufferAttribute = geometry.attributes[_attributeName]; var _vbo = webglBuffer.vbos.get(_attributeName); gl.bindBuffer(gl.ARRAY_BUFFER, _vbo.handle); gl.disableVertexAttribArray(attributeLocation); } var attName = material.activeAttributeName; var _bufferAttribute2 = geometry.attributes[attName]; var vbo = webglBuffer.vbos.get(attName); if (_bufferAttribute2 !== undefined && vbo !== undefined) { var type = _this.glTypeMapping.get(_bufferAttribute2.array.constructor); var normalized = _bufferAttribute2.normalized; gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle); gl.vertexAttribPointer(attributeLocation, _bufferAttribute2.itemSize, type, normalized, 0, 0); gl.enableVertexAttribArray(attributeLocation); } { var attExtra = octree.pcoGeometry.pointAttributes.attributes.find(a => a.name === attName); var range = material.getRange(attName); if (!range) { range = attExtra.range; } if (!range) { range = [0, 1]; } var _initialRange = attExtra.initialRange; var _initialRangeSize = _initialRange[1] - _initialRange[0]; var _globalRange = range; var _globalRangeSize = _globalRange[1] - _globalRange[0]; var _scale = _initialRangeSize / _globalRangeSize; var _offset = -(_globalRange[0] - _initialRange[0]) / _initialRangeSize; _scale = Number.isNaN(_scale) ? 1 : _scale; _offset = Number.isNaN(_offset) ? 0 : _offset; shader.setUniform1f("uExtraScale", _scale); shader.setUniform1f("uExtraOffset", _offset); } } else { for (var _attributeName2 in geometry.attributes) { var _bufferAttribute3 = geometry.attributes[_attributeName2]; var _vbo2 = webglBuffer.vbos.get(_attributeName2); if (attributeLocations[_attributeName2] !== undefined) { var _attributeLocation = attributeLocations[_attributeName2].location; var _type = _this.glTypeMapping.get(_bufferAttribute3.array.constructor); var _normalized = _bufferAttribute3.normalized; gl.bindBuffer(gl.ARRAY_BUFFER, _vbo2.handle); gl.vertexAttribPointer(_attributeLocation, _bufferAttribute3.itemSize, _type, _normalized, 0, 0); gl.enableVertexAttribArray(_attributeLocation); } } } var numPoints = webglBuffer.numElements; gl.drawArrays(gl.POINTS, 0, numPoints); i++; }; for (var node of nodes) { if (_loop()) continue; } gl.bindVertexArray(null); if (exports.measureTimings) { performance.mark("renderNodes-end"); performance.measure("render.renderNodes", "renderNodes-start", "renderNodes-end"); } } renderOctree(octree, nodes, camera, target) { var params = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; var gl = this.gl; var material = params.material ? params.material : octree.material; var shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps; var view = camera.matrixWorldInverse; var viewInv = camera.matrixWorld; if (params.viewOverride) { view = params.viewOverride; viewInv = view.clone().invert(); } var proj = camera.projectionMatrix; var projInv = proj.clone().invert(); //let worldView = new THREE.Matrix4(); var shader = null; var visibilityTextureData = null; var currentTextureBindingPoint = 0; if (material.pointSizeType >= 0) { if (material.pointSizeType === PointSizeType.ADAPTIVE || material.activeAttributeName === "level of detail") { var vnNodes = params.vnTextureNodes != null ? params.vnTextureNodes : nodes; visibilityTextureData = octree.computeVisibilityTextureData(vnNodes, camera); var vnt = material.visibleNodesTexture; var data = vnt.image.data; data.set(visibilityTextureData.data); vnt.needsUpdate = true; } } { // UPDATE SHADER AND TEXTURES if (!this.shaders.has(material)) { var [vs, fs] = [material.vertexShader, material.fragmentShader]; var _shader = new Shader(gl, "pointcloud", vs, fs); this.shaders.set(material, _shader); } shader = this.shaders.get(material); //if(material.needsUpdate){ { var [_vs, _fs] = [material.vertexShader, material.fragmentShader]; var numSnapshots = material.snapEnabled ? material.numSnapshots : 0; var numClipBoxes = material.clipBoxes && material.clipBoxes.length ? material.clipBoxes.length : 0; var numClipSpheres = params.clipSpheres && params.clipSpheres.length ? params.clipSpheres.length : 0; var numClipPolygons = material.clipPolygons && material.clipPolygons.length ? material.clipPolygons.length : 0; var defines = ["#define num_shadowmaps ".concat(shadowMaps.length), "#define num_snapshots ".concat(numSnapshots), "#define num_clipboxes ".concat(numClipBoxes), "#define num_clipspheres ".concat(numClipSpheres), "#define num_clippolygons ".concat(numClipPolygons)]; if (octree.pcoGeometry.root.isLoaded()) { var attributes = octree.pcoGeometry.root.geometry.attributes; if (attributes["gps-time"]) { defines.push("#define clip_gps_enabled"); } if (attributes["return number"]) { defines.push("#define clip_return_number_enabled"); } if (attributes["number of returns"]) { defines.push("#define clip_number_of_returns_enabled"); } if (attributes["source id"] || attributes["point source id"]) { defines.push("#define clip_point_source_id_enabled"); } } var definesString = defines.join("\n"); var vsVersionIndex = _vs.indexOf("#version "); var fsVersionIndex = _fs.indexOf("#version "); if (vsVersionIndex >= 0) { _vs = _vs.replace(/(#version .*)/, "$1\n".concat(definesString)); } else { _vs = "".concat(definesString, "\n").concat(_vs); } if (fsVersionIndex >= 0) { _fs = _fs.replace(/(#version .*)/, "$1\n".concat(definesString)); } else { _fs = "".concat(definesString, "\n").concat(_fs); } shader.update(_vs, _fs); material.needsUpdate = false; } for (var uniformName of Object.keys(material.uniforms)) { var uniform = material.uniforms[uniformName]; if (uniform.type == "t") { var texture = uniform.value; if (!texture) { continue; } if (!this.textures.has(texture)) { var webglTexture = new WebGLTexture(gl, texture); this.textures.set(texture, webglTexture); } var webGLTexture = this.textures.get(texture); webGLTexture.update(); } } } gl.useProgram(shader.program); var transparent = false; if (params.transparent !== undefined) { transparent = params.transparent && material.opacity < 1; } else { transparent = material.opacity < 1; } if (transparent) { gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE); gl.depthMask(false); gl.disable(gl.DEPTH_TEST); } else { gl.disable(gl.BLEND); gl.depthMask(true); gl.enable(gl.DEPTH_TEST); } if (params.blendFunc !== undefined) { gl.enable(gl.BLEND); gl.blendFunc(...params.blendFunc); } if (params.depthTest !== undefined) { if (params.depthTest === true) { gl.enable(gl.DEPTH_TEST); } else { gl.disable(gl.DEPTH_TEST); } } if (params.depthWrite !== undefined) { if (params.depthWrite === true) { gl.depthMask(true); } else { gl.depthMask(false); } } { // UPDATE UNIFORMS shader.setUniformMatrix4("projectionMatrix", proj); shader.setUniformMatrix4("viewMatrix", view); shader.setUniformMatrix4("uViewInv", viewInv); shader.setUniformMatrix4("uProjInv", projInv); var screenWidth = target ? target.width : material.screenWidth; var screenHeight = target ? target.height : material.screenHeight; shader.setUniform1f("uScreenWidth", screenWidth); shader.setUniform1f("uScreenHeight", screenHeight); shader.setUniform1f("fov", Math.PI * camera.fov / 180); shader.setUniform1f("near", camera.near); shader.setUniform1f("far", camera.far); if (camera instanceof OrthographicCamera) { shader.setUniform("uUseOrthographicCamera", true); shader.setUniform("uOrthoWidth", camera.right - camera.left); shader.setUniform("uOrthoHeight", camera.top - camera.bottom); } else { shader.setUniform("uUseOrthographicCamera", false); } if (material.clipBoxes.length + material.clipPolygons.length === 0) { shader.setUniform1i("clipTask", ClipTask.NONE); } else { shader.setUniform1i("clipTask", material.clipTask); } shader.setUniform1i("clipMethod", material.clipMethod); if (material.clipBoxes && material.clipBoxes.length > 0) { //let flattenedMatrices = [].concat(...material.clipBoxes.map(c => c.inverse.elements)); //const lClipBoxes = shader.uniformLocations["clipBoxes[0]"]; //gl.uniformMatrix4fv(lClipBoxes, false, flattenedMatrices); var lClipBoxes = shader.uniformLocations["clipBoxes[0]"]; gl.uniformMatrix4fv(lClipBoxes, false, material.uniforms.clipBoxes.value); } // TODO CLIPSPHERES if (params.clipSpheres && params.clipSpheres.length > 0) { var clipSpheres = params.clipSpheres; var matrices = []; for (var clipSphere of clipSpheres) { //let mScale = new THREE.Matrix4().makeScale(...clipSphere.scale.toArray()); //let mTranslate = new THREE.Matrix4().makeTranslation(...clipSphere.position.toArray()); //let clipToWorld = new THREE.Matrix4().multiplyMatrices(mTranslate, mScale); var clipToWorld = clipSphere.matrixWorld; var viewToWorld = camera.matrixWorld; var worldToClip = clipToWorld.clone().invert(); var viewToClip = new Matrix4().multiplyMatrices(worldToClip, viewToWorld); matrices.push(viewToClip); } var flattenedMatrices = [].concat(...matrices.map(matrix => matrix.elements)); var lClipSpheres = shader.uniformLocations["uClipSpheres[0]"]; gl.uniformMatrix4fv(lClipSpheres, false, flattenedMatrices); //const lClipSpheres = shader.uniformLocations["uClipSpheres[0]"]; //gl.uniformMatrix4fv(lClipSpheres, false, material.uniforms.clipSpheres.value); } shader.setUniform1f("size", material.size); shader.setUniform1f("maxSize", material.uniforms.maxSize.value); shader.setUniform1f("minSize", material.uniforms.minSize.value); // uniform float uPCIndex shader.setUniform1f("uOctreeSpacing", material.spacing); shader.setUniform("uOctreeSize", material.uniforms.octreeSize.value); //uniform vec3 uColor; shader.setUniform3f("uColor", material.color.toArray()); //uniform float opacity; shader.setUniform1f("uOpacity", material.opacity); shader.setUniform2f("elevationRange", material.elevationRange); shader.setUniform2f("intensityRange", material.intensityRange); shader.setUniform3f("uIntensity_gbc", [material.intensityGamma, material.intensityBrightness, material.intensityContrast]); shader.setUniform3f("uRGB_gbc", [material.rgbGamma, material.rgbBrightness, material.rgbContrast]); shader.setUniform1f("uTransition", material.transition); shader.setUniform1f("wRGB", material.weightRGB); shader.setUniform1f("wIntensity", material.weightIntensity); shader.setUniform1f("wElevation", material.weightElevation); shader.setUniform1f("wClassification", material.weightClassification); shader.setUniform1f("wReturnNumber", material.weightReturnNumber); shader.setUniform1f("wSourceID", material.weightSourceID); shader.setUniform("backfaceCulling", material.uniforms.backfaceCulling.value); var vnWebGLTexture = this.textures.get(material.visibleNodesTexture); if (vnWebGLTexture) { shader.setUniform1i("visibleNodesTexture", currentTextureBindingPoint); gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint); gl.bindTexture(vnWebGLTexture.target, vnWebGLTexture.id); currentTextureBindingPoint++; } var gradientTexture = this.textures.get(material.gradientTexture); shader.setUniform1i("gradient", currentTextureBindingPoint); gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint); gl.bindTexture(gradientTexture.target, gradientTexture.id); var repeat = material.elevationGradientRepeat; if (repeat === ElevationGradientRepeat.REPEAT) { gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.REPEAT); gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.REPEAT); } else if (repeat === ElevationGradientRepeat.MIRRORED_REPEAT) { gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); } else { gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); } currentTextureBindingPoint++; var classificationTexture = this.textures.get(material.classificationTexture); shader.setUniform1i("classificationLUT", currentTextureBindingPoint); gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint); gl.bindTexture(classificationTexture.target, classificationTexture.id); currentTextureBindingPoint++; var matcapTexture = this.textures.get(material.matcapTexture); shader.setUniform1i("matcapTextureUniform", currentTextureBindingPoint); gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint); gl.bindTexture(matcapTexture.target, matcapTexture.id); currentTextureBindingPoint++; if (material.snapEnabled === true) { { var lSnapshot = shader.uniformLocations["uSnapshot[0]"]; var lSnapshotDepth = shader.uniformLocations["uSnapshotDepth[0]"]; var bindingStart = currentTextureBindingPoint; var lSnapshotBindingPoints = new Array(5).fill(bindingStart).map((a, i) => a + i); var lSnapshotDepthBindingPoints = new Array(5).fill(1 + Math.max(...lSnapshotBindingPoints)).map((a, i) => a + i); currentTextureBindingPoint = 1 + Math.max(...lSnapshotDepthBindingPoints); gl.uniform1iv(lSnapshot, lSnapshotBindingPoints); gl.uniform1iv(lSnapshotDepth, lSnapshotDepthBindingPoints); for (var i = 0; i < 5; i++) { var _texture = material.uniforms["uSnapshot"].value[i]; var textureDepth = material.uniforms["uSnapshotDepth"].value[i]; if (!_texture) { break; } var snapTexture = this.threeRenderer.properties.get(_texture).__webglTexture; var snapTextureDepth = this.threeRenderer.properties.get(textureDepth).__webglTexture; var bindingPoint = lSnapshotBindingPoints[i]; var depthBindingPoint = lSnapshotDepthBindingPoints[i]; gl.activeTexture(gl["TEXTURE".concat(bindingPoint)]); gl.bindTexture(gl.TEXTURE_2D, snapTexture); gl.activeTexture(gl["TEXTURE".concat(depthBindingPoint)]); gl.bindTexture(gl.TEXTURE_2D, snapTextureDepth); } } { var _flattenedMatrices3 = [].concat(...material.uniforms.uSnapView.value.map(c => c.elements)); var lSnapView = shader.uniformLocations["uSnapView[0]"]; gl.uniformMatrix4fv(lSnapView, false, _flattenedMatrices3); } { var _flattenedMatrices4 = [].concat(...material.uniforms.uSnapProj.value.map(c => c.elements)); var lSnapProj = shader.uniformLocations["uSnapProj[0]"]; gl.uniformMatrix4fv(lSnapProj, false, _flattenedMatrices4); } { var _flattenedMatrices5 = [].concat(...material.uniforms.uSnapProjInv.value.map(c => c.elements)); var lSnapProjInv = shader.uniformLocations["uSnapProjInv[0]"]; gl.uniformMatrix4fv(lSnapProjInv, false, _flattenedMatrices5); } { var _flattenedMatrices6 = [].concat(...material.uniforms.uSnapViewInv.value.map(c => c.elements)); var lSnapViewInv = shader.uniformLocations["uSnapViewInv[0]"]; gl.uniformMatrix4fv(lSnapViewInv, false, _flattenedMatrices6); } } } this.renderNodes(octree, nodes, visibilityTextureData, camera, target, shader, params); gl.activeTexture(gl.TEXTURE2); gl.bindTexture(gl.TEXTURE_2D, null); gl.activeTexture(gl.TEXTURE0); } render(scene, camera) { var target = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var params = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var gl = this.gl; // PREPARE if (target != null) { this.threeRenderer.setRenderTarget(target); } //camera.updateProjectionMatrix(); // camera.matrixWorldInverse.invert(camera.matrixWorld); var traversalResult = this.traverse(scene); // RENDER for (var octree of traversalResult.octrees) { var nodes = octree.visibleNodes; this.renderOctree(octree, nodes, camera, target, params); } // CLEANUP gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, null); gl.bindBuffer(gl.ARRAY_BUFFER, null); gl.bindVertexArray(null); this.threeRenderer.resetState(); } } ; function copyMaterial(source, target) { for (var name of Object.keys(target.uniforms)) { target.uniforms[name].value = source.uniforms[name].value; } target.gradientTexture = source.gradientTexture; target.visibleNodesTexture = source.visibleNodesTexture; target.classificationTexture = source.classificationTexture; target.matcapTexture = source.matcapTexture; target.activeAttributeName = source.activeAttributeName; target.ranges = source.ranges; //target.updateShaderSource(); } class Batch { constructor(geometry, material) { this.geometry = geometry; this.material = material; this.sceneNode = new Points(geometry, material); this.geometryNode = { estimatedSpacing: 1.0, geometry: geometry }; } getLevel() { return 0; } } class ProfileFakeOctree extends PointCloudTree { constructor(octree) { super(); this.trueOctree = octree; this.pcoGeometry = octree.pcoGeometry; this.points = []; this.visibleNodes = []; //this.material = this.trueOctree.material; this.material = new PointCloudMaterial$1(); //this.material.copy(this.trueOctree.material); copyMaterial(this.trueOctree.material, this.material); this.material.pointSizeType = PointSizeType.FIXED; this.batchSize = 100 * 1000; this.currentBatch = null; } getAttribute(name) { return this.trueOctree.getAttribute(name); } dispose() { for (var node of this.visibleNodes) { node.geometry.dispose(); } this.visibleNodes = []; this.currentBatch = null; this.points = []; } addPoints(data) { // since each call to addPoints can deliver very very few points, // we're going to batch them into larger buffers for efficiency. if (this.currentBatch === null) { this.currentBatch = this.createNewBatch(data); } this.points.push(data); var updateRange = { start: this.currentBatch.geometry.drawRange.count, count: 0 }; var projectedBox = new Box3(); var truePos = new Vector3(); for (var i = 0; i < data.numPoints; i++) { if (updateRange.start + updateRange.count >= this.batchSize) { // current batch full, start new batch for (var key of Object.keys(this.currentBatch.geometry.attributes)) { var attribute = this.currentBatch.geometry.attributes[key]; attribute.updateRange.offset = updateRange.start; attribute.updateRange.count = updateRange.count; attribute.needsUpdate = true; } this.currentBatch.geometry.computeBoundingBox(); this.currentBatch.geometry.computeBoundingSphere(); this.currentBatch = this.createNewBatch(data); updateRange = { start: 0, count: 0 }; } truePos.set(data.data.position[3 * i + 0] + this.trueOctree.position.x, data.data.position[3 * i + 1] + this.trueOctree.position.y, data.data.position[3 * i + 2] + this.trueOctree.position.z); var x = data.data.mileage[i]; var y = 0; var z = truePos.z; projectedBox.expandByPoint(new Vector3(x, y, z)); var index = updateRange.start + updateRange.count; var geometry = this.currentBatch.geometry; for (var attributeName of Object.keys(data.data)) { var source = data.data[attributeName]; var target = geometry.attributes[attributeName]; var numElements = target.itemSize; for (var item = 0; item < numElements; item++) { target.array[numElements * index + item] = source[numElements * i + item]; } } { var position = geometry.attributes.position; position.array[3 * index + 0] = x; position.array[3 * index + 1] = y; position.array[3 * index + 2] = z; } updateRange.count++; this.currentBatch.geometry.drawRange.count++; } for (var _key of Object.keys(this.currentBatch.geometry.attributes)) { var _attribute = this.currentBatch.geometry.attributes[_key]; _attribute.updateRange.offset = updateRange.start; _attribute.updateRange.count = updateRange.count; _attribute.needsUpdate = true; } data.projectedBox = projectedBox; this.projectedBox = this.points.reduce((a, i) => a.union(i.projectedBox), new Box3()); } createNewBatch(data) { var geometry = new BufferGeometry(); // create new batches with batch_size elements of the same type as the attribute for (var attributeName of Object.keys(data.data)) { var buffer = data.data[attributeName]; var numElements = buffer.length / data.numPoints; // 3 for pos, 4 for col, 1 for scalars var _constructor = buffer.constructor; var normalized = false; if (this.trueOctree.root.sceneNode) { if (this.trueOctree.root.sceneNode.geometry.attributes[attributeName]) { normalized = this.trueOctree.root.sceneNode.geometry.attributes[attributeName].normalized; } } var batchBuffer = new _constructor(numElements * this.batchSize); var bufferAttribute = new BufferAttribute(batchBuffer, numElements, normalized); bufferAttribute.potree = { range: [0, 1] }; geometry.setAttribute(attributeName, bufferAttribute); } geometry.drawRange.start = 0; geometry.drawRange.count = 0; var batch = new Batch(geometry, this.material); this.visibleNodes.push(batch); return batch; } computeVisibilityTextureData() { var data = new Uint8Array(this.visibleNodes.length * 4); var offsets = new Map(); for (var i = 0; i < this.visibleNodes.length; i++) { var node = this.visibleNodes[i]; offsets[node] = i; } return { data: data, offsets: offsets }; } } class ProfileWindow extends EventDispatcher$1 { constructor(viewer) { super(); this.viewer = viewer; this.elRoot = $('#profile_window'); this.renderArea = this.elRoot.find('#profileCanvasContainer'); this.svg = d3.select('svg#profileSVG'); this.mouseIsDown = false; this.projectedBox = new Box3(); this.pointclouds = new Map(); this.numPoints = 0; this.lastAddPointsTimestamp = undefined; this.mouse = new Vector2(0, 0); this.scale = new Vector3(1, 1, 1); this.autoFitEnabled = true; // completely disable/enable this.autoFit = false; // internal var cwIcon = "".concat(exports.resourcePath, "/icons/arrow_cw.svg"); $('#potree_profile_rotate_cw').attr('src', cwIcon); var ccwIcon = "".concat(exports.resourcePath, "/icons/arrow_ccw.svg"); $('#potree_profile_rotate_ccw').attr('src', ccwIcon); var forwardIcon = "".concat(exports.resourcePath, "/icons/arrow_up.svg"); $('#potree_profile_move_forward').attr('src', forwardIcon); var backwardIcon = "".concat(exports.resourcePath, "/icons/arrow_down.svg"); $('#potree_profile_move_backward').attr('src', backwardIcon); var csvIcon = "".concat(exports.resourcePath, "/icons/file_csv_2d.svg"); $('#potree_download_csv_icon').attr('src', csvIcon); var lasIcon = "".concat(exports.resourcePath, "/icons/file_las_3d.svg"); $('#potree_download_las_icon').attr('src', lasIcon); var closeIcon = "".concat(exports.resourcePath, "/icons/close.svg"); $('#closeProfileContainer').attr("src", closeIcon); this.initTHREE(); this.initSVG(); this.initListeners(); this.pRenderer = new Renderer(this.renderer); this.elRoot.i18n(); } initListeners() { $(window).resize(() => { if (this.enabled) { this.render(); } }); this.renderArea.mousedown(e => { this.mouseIsDown = true; }); this.renderArea.mouseup(e => { this.mouseIsDown = false; }); var viewerPickSphereSizeHandler = () => { var camera = this.viewer.scene.getActiveCamera(); var domElement = this.viewer.renderer.domElement; var distance = this.viewerPickSphere.position.distanceTo(camera.position); var pr = Utils.projectedRadius(1, camera, distance, domElement.clientWidth, domElement.clientHeight); var scale = 10 / pr; this.viewerPickSphere.scale.set(scale, scale, scale); }; this.renderArea.mousemove(e => { if (this.pointclouds.size === 0) { return; } var rect = this.renderArea[0].getBoundingClientRect(); var x = e.clientX - rect.left; var y = e.clientY - rect.top; var newMouse = new Vector2(x, y); if (this.mouseIsDown) { // DRAG this.autoFit = false; this.lastDrag = new Date().getTime(); var cPos = [this.scaleX.invert(this.mouse.x), this.scaleY.invert(this.mouse.y)]; var ncPos = [this.scaleX.invert(newMouse.x), this.scaleY.invert(newMouse.y)]; this.camera.position.x -= ncPos[0] - cPos[0]; this.camera.position.z -= ncPos[1] - cPos[1]; this.render(); } else if (this.pointclouds.size > 0) { // FIND HOVERED POINT var radius = Math.abs(this.scaleX.invert(0) - this.scaleX.invert(40)); var mileage = this.scaleX.invert(newMouse.x); var elevation = this.scaleY.invert(newMouse.y); var closest = this.selectPoint(mileage, elevation, radius); if (closest) { var point = closest.point; var position = new Float64Array([point.position[0] + closest.pointcloud.position.x, point.position[1] + closest.pointcloud.position.y, point.position[2] + closest.pointcloud.position.z]); this.elRoot.find('#profileSelectionProperties').fadeIn(200); this.pickSphere.visible = true; this.pickSphere.scale.set(0.5 * radius, 0.5 * radius, 0.5 * radius); this.pickSphere.position.set(point.mileage, 0, position[2]); this.viewerPickSphere.position.set(...position); if (!this.viewer.scene.scene.children.includes(this.viewerPickSphere)) { this.viewer.scene.scene.add(this.viewerPickSphere); if (!this.viewer.hasEventListener("update", viewerPickSphereSizeHandler)) { this.viewer.addEventListener("update", viewerPickSphereSizeHandler); } } var info = this.elRoot.find('#profileSelectionProperties'); var html = ''; var _loop = function _loop() { var value = point[attributeName]; var attribute = closest.pointcloud.getAttribute(attributeName); var transform = value => value; if (attribute && attribute.type.size > 4) { var range = attribute.initialRange; var scale = 1 / (range[1] - range[0]); var offset = range[0]; transform = value => value / scale + offset; } if (attributeName === 'position') { var values = [...position].map(v => Utils.addCommas(v.toFixed(3))); html += "\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t"); } else if (attributeName === 'rgba') { html += "\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t"); } else if (attributeName === 'normal') { return 1; // continue } else if (attributeName === 'mileage') { html += "\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t"); } else { html += "\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t"); } }; for (var attributeName of Object.keys(point)) { if (_loop()) continue; } html += '
x".concat(values[0], "
y").concat(values[1], "
z").concat(values[2], "
".concat(attributeName, "").concat(value.join(', '), "
".concat(attributeName, "").concat(value.toFixed(3), "
".concat(attributeName, "").concat(transform(value), "
'; info.html(html); this.selectedPoint = point; } else { // this.pickSphere.visible = false; // this.selectedPoint = null; this.viewer.scene.scene.add(this.viewerPickSphere); var index = this.viewer.scene.scene.children.indexOf(this.viewerPickSphere); if (index >= 0) { this.viewer.scene.scene.children.splice(index, 1); } this.viewer.removeEventListener("update", viewerPickSphereSizeHandler); } this.render(); } this.mouse.copy(newMouse); }); var onWheel = e => { this.autoFit = false; var delta = 0; if (e.wheelDelta !== undefined) { // WebKit / Opera / Explorer 9 delta = e.wheelDelta; } else if (e.detail !== undefined) { // Firefox delta = -e.detail; } var ndelta = Math.sign(delta); var cPos = [this.scaleX.invert(this.mouse.x), this.scaleY.invert(this.mouse.y)]; if (ndelta > 0) { // + 10% this.scale.multiplyScalar(1.1); } else { // - 10% this.scale.multiplyScalar(100 / 110); } this.updateScales(); var ncPos = [this.scaleX.invert(this.mouse.x), this.scaleY.invert(this.mouse.y)]; this.camera.position.x -= ncPos[0] - cPos[0]; this.camera.position.z -= ncPos[1] - cPos[1]; this.render(); this.updateScales(); }; $(this.renderArea)[0].addEventListener('mousewheel', onWheel, false); $(this.renderArea)[0].addEventListener('DOMMouseScroll', onWheel, false); // Firefox $('#closeProfileContainer').click(() => { this.hide(); }); var getProfilePoints = () => { var points = new Points$1(); for (var [pointcloud, entry] of this.pointclouds) { for (var pointSet of entry.points) { var originPos = pointSet.data.position; var trueElevationPosition = new Float32Array(originPos); for (var i = 0; i < pointSet.numPoints; i++) { trueElevationPosition[3 * i + 2] += pointcloud.position.z; } pointSet.data.position = trueElevationPosition; points.add(pointSet); pointSet.data.position = originPos; } } return points; }; $('#potree_download_csv_icon').click(() => { var points = getProfilePoints(); var string = CSVExporter.toString(points); var blob = new Blob([string], { type: "text/string" }); $('#potree_download_profile_ortho_link').attr('href', URL.createObjectURL(blob)); }); $('#potree_download_las_icon').click(() => { var points = getProfilePoints(); var buffer = LASExporter.toLAS(points); var blob = new Blob([buffer], { type: "application/octet-binary" }); $('#potree_download_profile_link').attr('href', URL.createObjectURL(blob)); }); } selectPoint(mileage, elevation, radius) { var closest = { distance: Infinity, pointcloud: null, points: null, index: null }; var pointBox = new Box2(new Vector2(mileage - radius, elevation - radius), new Vector2(mileage + radius, elevation + radius)); var numTested = 0; var numSkipped = 0; var numTestedPoints = 0; var numSkippedPoints = 0; for (var [pointcloud, entry] of this.pointclouds) { for (var points of entry.points) { var collisionBox = new Box2(new Vector2(points.projectedBox.min.x, points.projectedBox.min.z), new Vector2(points.projectedBox.max.x, points.projectedBox.max.z)); var intersects = collisionBox.intersectsBox(pointBox); if (!intersects) { numSkipped++; numSkippedPoints += points.numPoints; continue; } numTested++; numTestedPoints += points.numPoints; for (var i = 0; i < points.numPoints; i++) { var m = points.data.mileage[i] - mileage; var e = points.data.position[3 * i + 2] - elevation + pointcloud.position.z; var r = Math.sqrt(m * m + e * e); var withinDistance = r < radius && r < closest.distance; var unfilteredClass = true; if (points.data.classification) { var classification = pointcloud.material.classification; var pointClassID = points.data.classification[i]; var pointClassValue = classification[pointClassID]; if (pointClassValue && (!pointClassValue.visible || pointClassValue.color.w === 0)) { unfilteredClass = false; } } if (withinDistance && unfilteredClass) { closest = { distance: r, pointcloud: pointcloud, points: points, index: i }; } } } } //console.log(`nodes: ${numTested}, ${numSkipped} || points: ${numTestedPoints}, ${numSkippedPoints}`); if (closest.distance < Infinity) { var _points = closest.points; var point = {}; var attributes = Object.keys(_points.data); for (var attribute of attributes) { var attributeData = _points.data[attribute]; var itemSize = attributeData.length / _points.numPoints; var value = attributeData.subarray(itemSize * closest.index, itemSize * closest.index + itemSize); if (value.length === 1) { point[attribute] = value[0]; } else { point[attribute] = value; } } closest.point = point; return closest; } else { return null; } } initTHREE() { this.renderer = new WebGLRenderer({ alpha: true, premultipliedAlpha: false }); this.renderer.setClearColor(0x000000, 0); this.renderer.setSize(10, 10); this.renderer.autoClear = false; this.renderArea.append($(this.renderer.domElement)); this.renderer.domElement.tabIndex = '2222'; $(this.renderer.domElement).css('width', '100%'); $(this.renderer.domElement).css('height', '100%'); { var gl = this.renderer.getContext(); if (gl.createVertexArray == null) { var extVAO = gl.getExtension('OES_vertex_array_object'); if (!extVAO) { throw new Error("OES_vertex_array_object extension not supported"); } gl.createVertexArray = extVAO.createVertexArrayOES.bind(extVAO); gl.bindVertexArray = extVAO.bindVertexArrayOES.bind(extVAO); } } this.camera = new OrthographicCamera(-1000, 1000, 1000, -1000, -1000, 1000); this.camera.up.set(0, 0, 1); this.camera.rotation.order = "ZXY"; this.camera.rotation.x = Math.PI / 2.0; this.scene = new Scene(); this.profileScene = new Scene(); var sg = new SphereGeometry(1, 16, 16); var sm = new MeshNormalMaterial(); this.pickSphere = new Mesh(sg, sm); this.scene.add(this.pickSphere); this.viewerPickSphere = new Mesh(sg, sm); } initSVG() { var width = this.renderArea[0].clientWidth; var height = this.renderArea[0].clientHeight; var marginLeft = this.renderArea[0].offsetLeft; this.svg.selectAll('*').remove(); this.scaleX = d3.scale.linear().domain([this.camera.left + this.camera.position.x, this.camera.right + this.camera.position.x]).range([0, width]); this.scaleY = d3.scale.linear().domain([this.camera.bottom + this.camera.position.z, this.camera.top + this.camera.position.z]).range([height, 0]); this.xAxis = d3.svg.axis().scale(this.scaleX).orient('bottom').innerTickSize(-height).outerTickSize(1).tickPadding(10).ticks(width / 50); this.yAxis = d3.svg.axis().scale(this.scaleY).orient('left').innerTickSize(-width).outerTickSize(1).tickPadding(10).ticks(height / 20); this.elXAxis = this.svg.append('g').attr('class', 'x axis').attr('transform', "translate(".concat(marginLeft, ", ").concat(height, ")")).call(this.xAxis); this.elYAxis = this.svg.append('g').attr('class', 'y axis').attr('transform', "translate(".concat(marginLeft, ", 0)")).call(this.yAxis); } addPoints(pointcloud, points) { if (points.numPoints === 0) { return; } var entry = this.pointclouds.get(pointcloud); if (!entry) { entry = new ProfileFakeOctree(pointcloud); this.pointclouds.set(pointcloud, entry); this.profileScene.add(entry); var materialChanged = () => { this.render(); }; materialChanged(); pointcloud.material.addEventListener('material_property_changed', materialChanged); this.addEventListener("on_reset_once", () => { pointcloud.material.removeEventListener('material_property_changed', materialChanged); }); } entry.addPoints(points); this.projectedBox.union(entry.projectedBox); if (this.autoFit && this.autoFitEnabled) { var width = this.renderArea[0].clientWidth; var height = this.renderArea[0].clientHeight; var size = this.projectedBox.getSize(new Vector3()); var sx = width / size.x; var sy = height / size.z; var scale = Math.min(sx, sy); var center = this.projectedBox.getCenter(new Vector3()); this.scale.set(scale, scale, 1); this.camera.position.copy(center); //console.log("camera: ", this.camera.position.toArray().join(", ")); } //console.log(entry); this.render(); var numPoints = 0; for (var [key, value] of this.pointclouds.entries()) { numPoints += value.points.reduce((a, i) => a + i.numPoints, 0); } $("#profile_num_points").html(Utils.addCommas(numPoints)); } reset() { this.lastReset = new Date().getTime(); this.dispatchEvent({ type: "on_reset_once" }); this.removeEventListeners("on_reset_once"); this.autoFit = true; this.projectedBox = new Box3(); for (var [key, entry] of this.pointclouds) { entry.dispose(); } this.pointclouds.clear(); this.mouseIsDown = false; this.mouse.set(0, 0); if (this.autoFitEnabled) { this.scale.set(1, 1, 1); } this.pickSphere.visible = false; this.elRoot.find('#profileSelectionProperties').hide(); this.render(); } show() { this.elRoot.fadeIn(); this.enabled = true; } hide() { this.elRoot.fadeOut(); this.enabled = false; } updateScales() { var width = this.renderArea[0].clientWidth; var height = this.renderArea[0].clientHeight; var left = -width / 2 / this.scale.x; var right = +width / 2 / this.scale.x; var top = +height / 2 / this.scale.y; var bottom = -height / 2 / this.scale.y; this.camera.left = left; this.camera.right = right; this.camera.top = top; this.camera.bottom = bottom; this.camera.updateProjectionMatrix(); this.scaleX.domain([this.camera.left + this.camera.position.x, this.camera.right + this.camera.position.x]).range([0, width]); this.scaleY.domain([this.camera.bottom + this.camera.position.z, this.camera.top + this.camera.position.z]).range([height, 0]); var marginLeft = this.renderArea[0].offsetLeft; this.xAxis.scale(this.scaleX).orient('bottom').innerTickSize(-height).outerTickSize(1).tickPadding(10).ticks(width / 50); this.yAxis.scale(this.scaleY).orient('left').innerTickSize(-width).outerTickSize(1).tickPadding(10).ticks(height / 20); this.elXAxis.attr('transform', "translate(".concat(marginLeft, ", ").concat(height, ")")).call(this.xAxis); this.elYAxis.attr('transform', "translate(".concat(marginLeft, ", 0)")).call(this.yAxis); } requestScaleUpdate() { var threshold = 100; var allowUpdate = this.lastReset === undefined || this.lastScaleUpdate === undefined || new Date().getTime() - this.lastReset > threshold && new Date().getTime() - this.lastScaleUpdate > threshold; if (allowUpdate) { this.updateScales(); this.lastScaleUpdate = new Date().getTime(); this.scaleUpdatePending = false; } else if (!this.scaleUpdatePending) { setTimeout(this.requestScaleUpdate.bind(this), 100); this.scaleUpdatePending = true; } } render() { var width = this.renderArea[0].clientWidth; var height = this.renderArea[0].clientHeight; var { renderer, pRenderer, camera, profileScene, scene } = this; var { scaleX, pickSphere } = this; renderer.setSize(width, height); renderer.setClearColor(0x000000, 0); renderer.clear(true, true, false); for (var pointcloud of this.pointclouds.keys()) { var source = pointcloud.material; var target = this.pointclouds.get(pointcloud).material; copyMaterial(source, target); target.size = 2; } pRenderer.render(profileScene, camera, null); var radius = Math.abs(scaleX.invert(0) - scaleX.invert(5)); if (radius === 0) { pickSphere.visible = false; } else { pickSphere.scale.set(radius, radius, radius); pickSphere.visible = true; } renderer.render(scene, camera); this.requestScaleUpdate(); } } ; class ProfileWindowController { constructor(viewer) { this.viewer = viewer; this.profileWindow = viewer.profileWindow; this.profile = null; this.numPoints = 0; this.threshold = 60 * 1000; this.rotateAmount = 10; this.scheduledRecomputeTime = null; this.enabled = true; this.requests = []; this._recompute = () => { this.recompute(); }; this.viewer.addEventListener("scene_changed", e => { e.oldScene.removeEventListener("pointcloud_added", this._recompute); e.scene.addEventListener("pointcloud_added", this._recompute); }); this.viewer.scene.addEventListener("pointcloud_added", this._recompute); $("#potree_profile_rotate_amount").val(parseInt(this.rotateAmount)); $("#potree_profile_rotate_amount").on("input", e => { var str = $("#potree_profile_rotate_amount").val(); if (!isNaN(str)) { var value = parseFloat(str); this.rotateAmount = value; $("#potree_profile_rotate_amount").css("background-color", ""); } else { $("#potree_profile_rotate_amount").css("background-color", "#ff9999"); } }); var rotate = radians => { var profile = this.profile; var points = profile.points; var start = points[0]; var end = points[points.length - 1]; var center = start.clone().add(end).multiplyScalar(0.5); var mMoveOrigin = new Matrix4().makeTranslation(-center.x, -center.y, -center.z); var mRotate = new Matrix4().makeRotationZ(radians); var mMoveBack = new Matrix4().makeTranslation(center.x, center.y, center.z); //const transform = mMoveOrigin.multiply(mRotate).multiply(mMoveBack); var transform = mMoveBack.multiply(mRotate).multiply(mMoveOrigin); var rotatedPoints = points.map(point => point.clone().applyMatrix4(transform)); this.profileWindow.autoFitEnabled = false; for (var i = 0; i < points.length; i++) { profile.setPosition(i, rotatedPoints[i]); } }; $("#potree_profile_rotate_cw").click(() => { var radians = MathUtils.degToRad(this.rotateAmount); rotate(-radians); }); $("#potree_profile_rotate_ccw").click(() => { var radians = MathUtils.degToRad(this.rotateAmount); rotate(radians); }); $("#potree_profile_move_forward").click(() => { var profile = this.profile; var points = profile.points; var start = points[0]; var end = points[points.length - 1]; var dir = end.clone().sub(start).normalize(); var up = new Vector3(0, 0, 1); var forward = up.cross(dir); var move = forward.clone().multiplyScalar(profile.width / 2); this.profileWindow.autoFitEnabled = false; for (var i = 0; i < points.length; i++) { profile.setPosition(i, points[i].clone().add(move)); } }); $("#potree_profile_move_backward").click(() => { var profile = this.profile; var points = profile.points; var start = points[0]; var end = points[points.length - 1]; var dir = end.clone().sub(start).normalize(); var up = new Vector3(0, 0, 1); var forward = up.cross(dir); var move = forward.clone().multiplyScalar(-profile.width / 2); this.profileWindow.autoFitEnabled = false; for (var i = 0; i < points.length; i++) { profile.setPosition(i, points[i].clone().add(move)); } }); } setProfile(profile) { if (this.profile !== null && this.profile !== profile) { this.profile.removeEventListener('marker_moved', this._recompute); this.profile.removeEventListener('marker_added', this._recompute); this.profile.removeEventListener('marker_removed', this._recompute); this.profile.removeEventListener('width_changed', this._recompute); } this.profile = profile; { this.profile.addEventListener('marker_moved', this._recompute); this.profile.addEventListener('marker_added', this._recompute); this.profile.addEventListener('marker_removed', this._recompute); this.profile.addEventListener('width_changed', this._recompute); } this.recompute(); } reset() { this.profileWindow.reset(); this.numPoints = 0; if (this.profile) { for (var request of this.requests) { request.cancel(); } } } progressHandler(pointcloud, progress) { for (var segment of progress.segments) { this.profileWindow.addPoints(pointcloud, segment.points); this.numPoints += segment.points.numPoints; } } cancel() { for (var request of this.requests) { request.cancel(); // request.finishLevelThenCancel(); } this.requests = []; } finishLevelThenCancel() { for (var request of this.requests) { request.finishLevelThenCancel(); } this.requests = []; } recompute() { var _this = this; if (!this.profile) { return; } if (this.scheduledRecomputeTime !== null && this.scheduledRecomputeTime > new Date().getTime()) { return; } else { this.scheduledRecomputeTime = new Date().getTime() + 100; } this.scheduledRecomputeTime = null; this.reset(); var _loop2 = function _loop2(pointcloud) { var request = pointcloud.getPointsInProfile(_this.profile, null, { 'onProgress': event => { if (!_this.enabled) { return; } _this.progressHandler(pointcloud, event.points); if (_this.numPoints > _this.threshold) { _this.finishLevelThenCancel(); } }, 'onFinish': event => { if (!_this.enabled) {} }, 'onCancel': () => { if (!_this.enabled) {} } }); _this.requests.push(request); }; for (var pointcloud of this.viewer.scene.pointclouds.filter(p => p.visible)) { _loop2(pointcloud); } } } ; //import { EventDispatcher } from "../EventDispatcher.js"; class VolumeTool extends EventDispatcher { constructor(viewer) { super(); this.viewer = viewer; this.renderer = viewer.renderer; this.addEventListener('start_inserting_volume', e => { this.viewer.dispatchEvent({ type: 'cancel_insertions' }); }); this.scene = new Scene(); this.scene.name = 'scene_volume'; this.viewer.inputHandler.registerInteractiveScene(this.scene); this.onRemove = e => { this.scene.remove(e.volume); }; this.onAdd = e => { this.scene.add(e.volume); }; for (var volume of viewer.scene.volumes) { this.onAdd({ volume: volume }); } this.viewer.inputHandler.addEventListener('delete', e => { var volumes = e.selection.filter(e => e instanceof Volume); volumes.forEach(e => this.viewer.scene.removeVolume(e)); }); viewer.addEventListener("update", this.update.bind(this)); viewer.addEventListener("render.pass.scene", e => this.render(e)); viewer.addEventListener("scene_changed", this.onSceneChange.bind(this)); viewer.scene.addEventListener('volume_added', this.onAdd); viewer.scene.addEventListener('volume_removed', this.onRemove); } onSceneChange(e) { if (e.oldScene) { e.oldScene.removeEventListeners('volume_added', this.onAdd); e.oldScene.removeEventListeners('volume_removed', this.onRemove); } e.scene.addEventListener('volume_added', this.onAdd); e.scene.addEventListener('volume_removed', this.onRemove); } startInsertion() { var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var volume; if (args.type) { volume = new args.type(); } else { volume = new BoxVolume(); } volume.clip = args.clip || false; volume.name = args.name || 'Volume'; this.dispatchEvent({ type: 'start_inserting_volume', volume: volume }); this.viewer.scene.addVolume(volume); this.scene.add(volume); var cancel = { callback: null }; var drag = e => { var camera = this.viewer.scene.getActiveCamera(); var I = Utils.getMousePointCloudIntersection(e.drag.end, this.viewer.scene.getActiveCamera(), this.viewer, this.viewer.scene.pointclouds, { pickClipped: false }); if (I) { volume.position.copy(I.location); var wp = volume.getWorldPosition(new Vector3()).applyMatrix4(camera.matrixWorldInverse); // let pp = new THREE.Vector4(wp.x, wp.y, wp.z).applyMatrix4(camera.projectionMatrix); var w = Math.abs(wp.z / 5); volume.scale.set(w, w, w); } }; var drop = e => { volume.removeEventListener('drag', drag); volume.removeEventListener('drop', drop); cancel.callback(); }; cancel.callback = e => { volume.removeEventListener('drag', drag); volume.removeEventListener('drop', drop); this.viewer.removeEventListener('cancel_insertions', cancel.callback); }; volume.addEventListener('drag', drag); volume.addEventListener('drop', drop); this.viewer.addEventListener('cancel_insertions', cancel.callback); this.viewer.inputHandler.startDragging(volume); return volume; } update() { if (!this.viewer.scene) { return; } var camera = this.viewer.scene.getActiveCamera(); var renderAreaSize = this.viewer.renderer.getSize(new Vector2()); var clientWidth = renderAreaSize.width; var clientHeight = renderAreaSize.height; var volumes = this.viewer.scene.volumes; for (var volume of volumes) { var label = volume.label; { var distance = label.position.distanceTo(camera.position); var pr = Utils.projectedRadius(1, camera, distance, clientWidth, clientHeight); var scale = 70 / pr; label.scale.set(scale, scale, scale); } var calculatedVolume = volume.getVolume(); calculatedVolume = calculatedVolume / Math.pow(this.viewer.lengthUnit.unitspermeter, 3) * Math.pow(this.viewer.lengthUnitDisplay.unitspermeter, 3); //convert to cubic meters then to the cubic display unit var text = Utils.addCommas(calculatedVolume.toFixed(3)) + ' ' + this.viewer.lengthUnitDisplay.code + '\u00B3'; label.setText(text); } } render(params) { var renderer = this.viewer.renderer; var oldTarget = renderer.getRenderTarget(); if (params.renderTarget) { renderer.setRenderTarget(params.renderTarget); } renderer.render(this.scene, this.viewer.scene.getActiveCamera()); renderer.setRenderTarget(oldTarget); } } /** * * code adapted from three.js BoxHelper.js * https://github.com/mrdoob/three.js/blob/dev/src/helpers/BoxHelper.js * * @author mrdoob / http://mrdoob.com/ * @author Mugen87 / http://github.com/Mugen87 * @author mschuetz / http://potree.org */ class Box3Helper$1 extends LineSegments { constructor(box, color) { var depthTest = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; if (color === undefined) color = 0xffff00; 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([box.min.x, box.min.y, box.min.z, box.max.x, box.min.y, box.min.z, box.max.x, box.min.y, box.max.z, box.min.x, box.min.y, box.max.z, box.min.x, box.max.y, box.min.z, box.max.x, box.max.y, box.min.z, box.max.x, box.max.y, box.max.z, box.min.x, box.max.y, box.max.z]); var geometry = new BufferGeometry(); geometry.setIndex(new BufferAttribute(indices, 1)); geometry.setAttribute('position', new BufferAttribute(positions, 3)); var material = new LineBasicMaterial({ color: color, depthTest }); super(geometry, material); } } var KeyCodes = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40, DELETE: 46, A: 'A'.charCodeAt(0), S: 'S'.charCodeAt(0), D: 'D'.charCodeAt(0), W: 'W'.charCodeAt(0), Q: 'Q'.charCodeAt(0), E: 'E'.charCodeAt(0), R: 'R'.charCodeAt(0), F: 'F'.charCodeAt(0) }; class NormalizationMaterial extends RawShaderMaterial { constructor() { var parameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(); var uniforms = { uDepthMap: { type: 't', value: null }, uWeightMap: { type: 't', value: null } }; this.setValues({ uniforms: uniforms, vertexShader: this.getDefines() + Shaders['normalize.vs'], fragmentShader: this.getDefines() + Shaders['normalize.fs'] }); } getDefines() { var defines = ''; return defines; } updateShaderSource() { var vs = this.getDefines() + Shaders['normalize.vs']; var fs = this.getDefines() + Shaders['normalize.fs']; this.setValues({ vertexShader: vs, fragmentShader: fs }); this.needsUpdate = true; } } class NormalizationEDLMaterial extends RawShaderMaterial { constructor() { var parameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(); var uniforms = { screenWidth: { type: 'f', value: 0 }, screenHeight: { type: 'f', value: 0 }, edlStrength: { type: 'f', value: 1.0 }, radius: { type: 'f', value: 1.0 }, neighbours: { type: '2fv', value: [] }, uEDLMap: { type: 't', value: null }, uDepthMap: { type: 't', value: null }, uWeightMap: { type: 't', value: null } }; this.setValues({ uniforms: uniforms, vertexShader: this.getDefines() + Shaders['normalize.vs'], fragmentShader: this.getDefines() + Shaders['normalize_and_edl.fs'] }); this.neighbourCount = 8; } getDefines() { var defines = ''; defines += '#define NEIGHBOUR_COUNT ' + this.neighbourCount + '\n'; return defines; } updateShaderSource() { var vs = this.getDefines() + Shaders['normalize.vs']; var fs = this.getDefines() + Shaders['normalize_and_edl.fs']; this.setValues({ vertexShader: vs, fragmentShader: fs }); this.uniforms.neighbours.value = this.neighbours; this.needsUpdate = true; } get neighbourCount() { return this._neighbourCount; } set neighbourCount(value) { if (this._neighbourCount !== value) { this._neighbourCount = value; this.neighbours = new Float32Array(this._neighbourCount * 2); for (var c = 0; c < this._neighbourCount; c++) { this.neighbours[2 * c + 0] = Math.cos(2 * c * Math.PI / this._neighbourCount); this.neighbours[2 * c + 1] = Math.sin(2 * c * Math.PI / this._neighbourCount); } this.updateShaderSource(); } } } //在potree.shim中修改。 。official中用不到且有bug class HQSplatRenderer { constructor(viewer) { this.viewer = viewer; this.depthMaterials = new Map(); this.attributeMaterials = new Map(); this.normalizationMaterial = null; this.rtDepth = null; this.rtAttribute = null; this.gl = viewer.renderer.getContext(); this.initialized = false; } init() { if (this.initialized) { return; } this.normalizationMaterial = new NormalizationMaterial(); this.normalizationMaterial.depthTest = true; this.normalizationMaterial.depthWrite = true; this.normalizationMaterial.transparent = true; this.normalizationEDLMaterial = new NormalizationEDLMaterial(); this.normalizationEDLMaterial.depthTest = true; this.normalizationEDLMaterial.depthWrite = true; this.normalizationEDLMaterial.transparent = true; this.rtDepth = new WebGLRenderTarget(1024, 1024, { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat, type: FloatType, depthTexture: new DepthTexture(undefined, undefined, UnsignedIntType) }); this.rtAttribute = new WebGLRenderTarget(1024, 1024, { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat, type: FloatType, depthTexture: this.rtDepth.depthTexture }); this.initialized = true; } resize(width, height) { this.rtDepth.setSize(width, height); this.rtAttribute.setSize(width, height); } clearTargets() { var viewer = this.viewer; var { renderer } = viewer; var oldTarget = renderer.getRenderTarget(); renderer.setClearColor(0x000000, 0); renderer.setRenderTarget(this.rtDepth); renderer.clear(true, true, true); renderer.setRenderTarget(this.rtAttribute); renderer.clear(true, true, true); renderer.setRenderTarget(oldTarget); } clear() { this.init(); var { renderer, background } = this.viewer; if (background === "skybox") { renderer.setClearColor(0x000000, 0); } else if (background === 'gradient') { renderer.setClearColor(0x000000, 0); } else if (background === 'black') { renderer.setClearColor(0x000000, 1); } else if (background === 'white') { renderer.setClearColor(0xFFFFFF, 1); } else { renderer.setClearColor(0x000000, 0); } renderer.clear(); this.clearTargets(); } render(params) { this.init(); var viewer = this.viewer; var camera = params.camera ? params.camera : viewer.scene.getActiveCamera(); var { width, height } = this.viewer.renderer.getSize(new Vector2()); viewer.dispatchEvent({ type: "render.pass.begin", viewer: viewer }); this.resize(width, height); var visiblePointClouds = viewer.scene.pointclouds.filter(pc => pc.visible); var originalMaterials = new Map(); for (var pointcloud of visiblePointClouds) { originalMaterials.set(pointcloud, pointcloud.material); if (!this.attributeMaterials.has(pointcloud)) { var attributeMaterial = new PointCloudMaterial$1(); this.attributeMaterials.set(pointcloud, attributeMaterial); } if (!this.depthMaterials.has(pointcloud)) { var depthMaterial = new PointCloudMaterial$1(); depthMaterial.setDefine("depth_pass", "#define hq_depth_pass"); depthMaterial.setDefine("use_edl", "#define use_edl"); this.depthMaterials.set(pointcloud, depthMaterial); } } { // DEPTH PASS for (var _pointcloud of visiblePointClouds) { var octreeSize = _pointcloud.pcoGeometry.boundingBox.getSize(new Vector3()).x; var material = originalMaterials.get(_pointcloud); var _depthMaterial = this.depthMaterials.get(_pointcloud); _depthMaterial.size = material.size; _depthMaterial.minSize = material.minSize; _depthMaterial.maxSize = material.maxSize; _depthMaterial.pointSizeType = material.pointSizeType; _depthMaterial.visibleNodesTexture = material.visibleNodesTexture; _depthMaterial.weighted = false; _depthMaterial.screenWidth = width; _depthMaterial.shape = PointShape$1.CIRCLE; _depthMaterial.screenHeight = height; _depthMaterial.uniforms.visibleNodes.value = material.visibleNodesTexture; _depthMaterial.uniforms.octreeSize.value = octreeSize; _depthMaterial.spacing = _pointcloud.pcoGeometry.spacing; // * Math.max(...pointcloud.scale.toArray()); _depthMaterial.classification = material.classification; _depthMaterial.uniforms.classificationLUT.value.image.data = material.uniforms.classificationLUT.value.image.data; _depthMaterial.classificationTexture.needsUpdate = true; _depthMaterial.uniforms.uFilterReturnNumberRange.value = material.uniforms.uFilterReturnNumberRange.value; _depthMaterial.uniforms.uFilterNumberOfReturnsRange.value = material.uniforms.uFilterNumberOfReturnsRange.value; _depthMaterial.uniforms.uFilterGPSTimeClipRange.value = material.uniforms.uFilterGPSTimeClipRange.value; _depthMaterial.uniforms.uFilterPointSourceIDClipRange.value = material.uniforms.uFilterPointSourceIDClipRange.value; _depthMaterial.clipTask = material.clipTask; _depthMaterial.clipMethod = material.clipMethod; _depthMaterial.setClipBoxes(material.clipBoxes); _depthMaterial.setClipPolygons(material.clipPolygons); _pointcloud.material = _depthMaterial; } viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, this.rtDepth, { clipSpheres: viewer.scene.volumes.filter(v => v instanceof SphereVolume$1) }); } { // ATTRIBUTE PASS for (var _pointcloud2 of visiblePointClouds) { var _octreeSize = _pointcloud2.pcoGeometry.boundingBox.getSize(new Vector3()).x; var _material = originalMaterials.get(_pointcloud2); var _attributeMaterial = this.attributeMaterials.get(_pointcloud2); _attributeMaterial.size = _material.size; _attributeMaterial.minSize = _material.minSize; _attributeMaterial.maxSize = _material.maxSize; _attributeMaterial.pointSizeType = _material.pointSizeType; _attributeMaterial.activeAttributeName = _material.activeAttributeName; _attributeMaterial.visibleNodesTexture = _material.visibleNodesTexture; _attributeMaterial.weighted = true; _attributeMaterial.screenWidth = width; _attributeMaterial.screenHeight = height; _attributeMaterial.shape = PointShape$1.CIRCLE; _attributeMaterial.uniforms.visibleNodes.value = _material.visibleNodesTexture; _attributeMaterial.uniforms.octreeSize.value = _octreeSize; _attributeMaterial.spacing = _pointcloud2.pcoGeometry.spacing; // * Math.max(...pointcloud.scale.toArray()); _attributeMaterial.classification = _material.classification; _attributeMaterial.uniforms.classificationLUT.value.image.data = _material.uniforms.classificationLUT.value.image.data; _attributeMaterial.classificationTexture.needsUpdate = true; _attributeMaterial.uniforms.uFilterReturnNumberRange.value = _material.uniforms.uFilterReturnNumberRange.value; _attributeMaterial.uniforms.uFilterNumberOfReturnsRange.value = _material.uniforms.uFilterNumberOfReturnsRange.value; _attributeMaterial.uniforms.uFilterGPSTimeClipRange.value = _material.uniforms.uFilterGPSTimeClipRange.value; _attributeMaterial.uniforms.uFilterPointSourceIDClipRange.value = _material.uniforms.uFilterPointSourceIDClipRange.value; _attributeMaterial.elevationGradientRepeat = _material.elevationGradientRepeat; _attributeMaterial.elevationRange = _material.elevationRange; _attributeMaterial.gradient = _material.gradient; _attributeMaterial.matcap = _material.matcap; _attributeMaterial.intensityRange = _material.intensityRange; _attributeMaterial.intensityGamma = _material.intensityGamma; _attributeMaterial.intensityContrast = _material.intensityContrast; _attributeMaterial.intensityBrightness = _material.intensityBrightness; _attributeMaterial.rgbGamma = _material.rgbGamma; _attributeMaterial.rgbContrast = _material.rgbContrast; _attributeMaterial.rgbBrightness = _material.rgbBrightness; _attributeMaterial.weightRGB = _material.weightRGB; _attributeMaterial.weightIntensity = _material.weightIntensity; _attributeMaterial.weightElevation = _material.weightElevation; _attributeMaterial.weightRGB = _material.weightRGB; _attributeMaterial.weightClassification = _material.weightClassification; _attributeMaterial.weightReturnNumber = _material.weightReturnNumber; _attributeMaterial.weightSourceID = _material.weightSourceID; _attributeMaterial.color = _material.color; _attributeMaterial.clipTask = _material.clipTask; _attributeMaterial.clipMethod = _material.clipMethod; _attributeMaterial.setClipBoxes(_material.clipBoxes); _attributeMaterial.setClipPolygons(_material.clipPolygons); _pointcloud2.material = _attributeMaterial; } var gl = this.gl; viewer.renderer.setRenderTarget(null); viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, this.rtAttribute, { clipSpheres: viewer.scene.volumes.filter(v => v instanceof SphereVolume$1), //material: this.attributeMaterial, blendFunc: [gl.SRC_ALPHA, gl.ONE], //depthTest: false, depthWrite: false }); } for (var [_pointcloud3, _material2] of originalMaterials) { _pointcloud3.material = _material2; } viewer.renderer.setRenderTarget(null); if (viewer.background === "skybox") { viewer.renderer.setClearColor(0x000000, 0); viewer.renderer.clear(); viewer.skybox.camera.rotation.copy(viewer.scene.cameraP.rotation); viewer.skybox.camera.fov = viewer.scene.cameraP.fov; viewer.skybox.camera.aspect = viewer.scene.cameraP.aspect; viewer.skybox.parent.rotation.x = 0; viewer.skybox.parent.updateMatrixWorld(); viewer.skybox.camera.updateProjectionMatrix(); viewer.renderer.render(viewer.skybox.scene, viewer.skybox.camera); } else if (viewer.background === 'gradient') { viewer.renderer.setClearColor(0x000000, 0); viewer.renderer.clear(); viewer.renderer.render(viewer.scene.sceneBG, viewer.scene.cameraBG); } else if (viewer.background === 'black') { viewer.renderer.setClearColor(0x000000, 1); viewer.renderer.clear(); } else if (viewer.background === 'white') { viewer.renderer.setClearColor(0xFFFFFF, 1); viewer.renderer.clear(); } else { viewer.renderer.setClearColor(0x000000, 0); viewer.renderer.clear(); } { // NORMALIZATION PASS var normalizationMaterial = this.useEDL ? this.normalizationEDLMaterial : this.normalizationMaterial; if (this.useEDL) { normalizationMaterial.uniforms.edlStrength.value = viewer.edlStrength; normalizationMaterial.uniforms.radius.value = viewer.edlRadius; normalizationMaterial.uniforms.screenWidth.value = width; normalizationMaterial.uniforms.screenHeight.value = height; normalizationMaterial.uniforms.uEDLMap.value = this.rtDepth.texture; } normalizationMaterial.uniforms.uWeightMap.value = this.rtAttribute.texture; normalizationMaterial.uniforms.uDepthMap.value = this.rtAttribute.depthTexture; Utils.screenPass.render(viewer.renderer, normalizationMaterial); } viewer.renderer.render(viewer.scene.scene, camera); viewer.dispatchEvent({ type: "render.pass.scene", viewer: viewer }); viewer.renderer.clearDepth(); viewer.transformationTool.update(); viewer.dispatchEvent({ type: "render.pass.perspective_overlay", viewer: viewer }); viewer.renderer.render(viewer.controls.sceneControls, camera); viewer.renderer.render(viewer.clippingTool.sceneVolume, camera); viewer.renderer.render(viewer.transformationTool.scene, camera); viewer.renderer.setViewport(width - viewer.navigationCube.width, height - viewer.navigationCube.width, viewer.navigationCube.width, viewer.navigationCube.width); viewer.renderer.render(viewer.navigationCube, viewer.navigationCube.camera); viewer.renderer.setViewport(0, 0, width, height); viewer.dispatchEvent({ type: "render.pass.end", viewer: viewer }); } } class LRUItem { constructor(node) { this.previous = null; this.next = null; this.node = node; } } /** * * @class A doubly-linked-list of the least recently used elements. */ class LRU { constructor() { //类似链表存储 // the least recently used item this.first = null; // the most recently used item this.last = null; // a list of all items in the lru list this.items = {}; //按node的id存储。(id为0的就是root,name='r') this.elements = 0; this.numPoints = 0; } size() { return this.elements; } contains(node) { return this.items[node.id] == null; } touch(node) { //链接node,并且永远放在最后. (每次updatePointClouds都要刷新一次链表) if (!node.loaded) { return; } var item; if (this.items[node.id] == null) { // add to list item = new LRUItem(node); item.previous = this.last; this.last = item; if (item.previous !== null) { item.previous.next = item; } this.items[node.id] = item; this.elements++; if (this.first === null) { this.first = item; } this.numPoints += node.numPoints; } else { // update in list item = this.items[node.id]; if (item.previous === null) { // handle touch on first element if (item.next !== null) { this.first = item.next; this.first.previous = null; item.previous = this.last; item.next = null; this.last = item; item.previous.next = item; } } else if (item.next === null) { // handle touch on last element } else { //从原来的位置挑出放最后 // handle touch on any other element item.previous.next = item.next; item.next.previous = item.previous; item.previous = this.last; item.next = null; this.last = item; item.previous.next = item; } } } //因为需要显示的都放末尾,所以不显示的部分都在前面,删除时从头删除。(但并不代表开头的一定是不显示的,所以如果第一个仍是显示的,它很可能是root,也就是name='r'的nodeGeo,删除它也就会删除全部) remove(node) { var lruItem = this.items[node.id]; if (lruItem) { if (this.elements === 1) { this.first = null; this.last = null; } else { if (!lruItem.previous) { this.first = lruItem.next; this.first.previous = null; } if (!lruItem.next) { this.last = lruItem.previous; this.last.next = null; } if (lruItem.previous && lruItem.next) { lruItem.previous.next = lruItem.next; lruItem.next.previous = lruItem.previous; } } delete this.items[node.id]; this.elements--; this.numPoints -= node.numPoints; } } getLRUItem() { if (this.first === null) { return null; } var lru = this.first; return lru.node; } toString() { var string = '{ '; var curr = this.first; while (curr !== null) { string += curr.node.id; if (curr.next !== null) { string += ', '; } curr = curr.next; } string += '}'; string += '(' + this.size() + ')'; return string; } freeMemory() { if (this.elements <= 1) { return; } while (this.numPoints > Potree.pointLoadLimit) { var element = this.first; var node = element.node; this.disposeDescendants(node); } } disposeDescendants(node) { var stack = []; stack.push(node); while (stack.length > 0) { var current = stack.pop(); // console.log(current); current.dispose(); //真正删除geometry等 this.remove(current); for (var key in current.children) { if (current.children.hasOwnProperty(key)) { var child = current.children[key]; if (child.loaded) { stack.push(current.children[key]); } } } } } } // // how to calculate the radius of a projected sphere in screen space // http://stackoverflow.com/questions/21648630/radius-of-projected-sphere-in-screen-space // http://stackoverflow.com/questions/3717226/radius-of-projected-sphere // class ExtendPointCloudMaterial extends PointCloudMaterial$1 { constructor() { var parameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(parameters); var getValid = (a, b) => { if (a !== undefined) { return a; } else { return b; } }; var maxSize = getValid(parameters.maxSize, 200.0); var orthoMaxSize = getValid(parameters.orthoMaxSize, 3.0); this._gradient = Gradients.RAINBOW; //Gradients.SPECTRAL;//海拔贴图种类 this.gradientTexture = ExtendPointCloudMaterial.generateGradientTexture(this._gradient); //this.matcapTexture = ExtendPointCloudMaterial.generateMatcapTexture(this._matcap); delete this.uniforms.screenWidth; delete this.uniforms.screenHeight; delete this.uniforms.clipBoxes; delete this.uniforms.clipPolygons; delete this.uniforms.clipPolygonVCount; delete this.uniforms.clipPolygonVP; delete this.uniforms.clipBoxCount; //注意:这里修改了uniforms后,还需要在PotreeRender中手动传递到shader, like: gl.uniformMatrix4fv(.... Object.assign(this.uniforms, { resolution: { type: 'v2', value: new Vector2() }, maxSize: { type: "f", value: maxSize }, orthoMaxSize: { type: "f", value: orthoMaxSize }, gradient: { type: "t", value: this.gradientTexture }, clipBoxes_in: { type: "Matrix4fv", value: [] }, clipBoxes_out: { type: "Matrix4fv", value: [] }, clipBoxBig_in: { type: "Matrix4fv", value: [] }, boxes_highlight: { type: "Matrix4fv", value: [] }, progress: { type: "f", value: 0 }, easeInOutRatio: { type: "f", value: 0.3 }, pano0Map: { type: "t", value: null }, pano0Position: { type: "v3", value: new Vector3() }, pano0Matrix: { type: "m4", value: new Matrix4() }, pano1Map: { type: "t", value: null }, pano1Position: { type: "v3", value: new Vector3() }, pano1Matrix: { type: "m4", value: new Matrix4() }, prismList: { type: "Matrix3fv", value: null }, prismPoints: { type: "vec2fv", value: null }, baseHeightAreaMap: { type: 't', value: null }, baseHeightBoundZ: { type: 'vec2', value: new Vector2() }, baseHeightBoundXY: { type: 'vec4', value: new Vector4() } }); delete this.clipBoxes; this.clipBoxes_in = []; this.clipBoxes_out = []; this.highlightBoxes = []; this.prisms = []; var { vs, fs } = Common.changeShaderToWebgl2(Shaders['pointcloud_new.vs'], Shaders['pointcloud_new.fs'], 'selfBuild'); Shaders['pointcloud_new.vs'] = vs; Shaders['pointcloud_new.fs'] = fs; this.updateShaderSource(); } updateShaderSource() { var vs = Shaders['pointcloud_new.vs']; //改 var fs = Shaders['pointcloud_new.fs']; //改 var definesString = this.getDefines(); var vsVersionIndex = vs.indexOf("#version "); var fsVersionIndex = fs.indexOf("#version "); if (vsVersionIndex >= 0) { vs = vs.replace(/(#version .*)/, "$1\n".concat(definesString)); } else { vs = "".concat(definesString, "\n").concat(vs); } if (fsVersionIndex >= 0) { fs = fs.replace(/(#version .*)/, "$1\n".concat(definesString)); } else { fs = "".concat(definesString, "\n").concat(fs); } this.vertexShader = vs; this.fragmentShader = fs; if (this.opacity === 1.0 && !this.useFilterByNormal) { //add useFilterByNormal this.blending = NoBlending; this.transparent = false; this.depthTest = true; this.depthWrite = true; this.depthFunc = LessEqualDepth; } else if ((this.opacity < 1.0 || this.useFilterByNormal) && !this.useEDL) { //add useFilterByNormal this.blending = AdditiveBlending; this.transparent = true; this.depthTest = false; this.depthWrite = true; this.depthFunc = AlwaysDepth; } if (this.weighted) { this.blending = AdditiveBlending; this.transparent = true; this.depthTest = true; this.depthWrite = false; } this.shaderNeedsUpdate = true; } getDefines() { var defines = []; if (this.pointSizeType === PointSizeType.FIXED) { defines.push('#define fixed_point_size'); } else if (this.pointSizeType === PointSizeType.ATTENUATED) { defines.push('#define attenuated_point_size'); } else if (this.pointSizeType === PointSizeType.ADAPTIVE) { defines.push('#define adaptive_point_size'); } if (!Features.EXT_DEPTH.isSupported(viewer.renderer.getContext()) && this.shape === PointShape$1.PARABOLOID) { this.shape = PointShape$1.SQUARE; //强行替换 } if (this.shape === PointShape$1.SQUARE) { defines.push('#define square_point_shape'); } else if (this.shape === PointShape$1.CIRCLE) { defines.push('#define circle_point_shape'); } else if (this.shape === PointShape$1.PARABOLOID) { defines.push('#define paraboloid_point_shape'); } //console.log('this.shape PARABOLOID', this.shape, this.shape === PointShape.PARABOLOID) if (this._useEDL || this.fakeEDL) { defines.push('#define use_edl'); } if (this.activeAttributeName) { var attributeName = this.activeAttributeName.replace(/[^a-zA-Z0-9]/g, '_'); defines.push("#define color_type_".concat(attributeName)); } if (this._treeType === TreeType.OCTREE) { defines.push('#define tree_type_octree'); } else if (this._treeType === TreeType.KDTREE) { defines.push('#define tree_type_kdtree'); } if (this.weighted) { defines.push('#define weighted_splats'); } for (var [key, value] of this.defines) { defines.push(value); } return defines.join("\n"); } get pointSizeType() { return this._pointSizeType; } set pointSizeType(value) { if (typeof value == 'string') value = PointSizeType[value]; super.pointSizeType = value; /* if (this._pointSizeType !== value) { this._pointSizeType = value; this.updateShaderSource(); //这句表明这个属性频繁更改会卡顿 this.dispatchEvent({ type: 'point_size_type_changed', target: this }); this.dispatchEvent({ type: 'material_property_changed', target: this }); } */ } get color() { return this.uniforms.uColor.value; } set color(value) { //改 if (value == this.color_) return; var color = value; //if (!this.uniforms.uColor.value.equals(value)) { if (typeof value == 'string') { var colorArr = Potree.config.colors[value]; if (!colorArr) { //console.warn('没找到该颜色值'+ value) } else { color = new Color().fromArray(colorArr).multiplyScalar(1 / 255); } } this.uniforms.uColor.value.set(color); //this.uniforms.uColor.value.copy(value); this.dispatchEvent({ type: 'color_changed', target: this }); this.dispatchEvent({ type: 'material_property_changed', target: this }); //} this.color_ = value; //记录下str } ////////////////////////add setProjectedPanos(pano0, pano1, progressValue, easeInOutRatio) { //this.uniforms.usePanoMap.value = 1 this.usePanoMap = true; progressValue != void 0 && (this.uniforms.progress.value = progressValue); //pano0.ensureSkyboxReadyForRender(); this.uniforms.pano0Map.value = pano0.getSkyboxTexture(); this.uniforms.pano0Position.value.copy(pano0.position); this.uniforms.pano0Matrix.value.copy(pano0.panoMatrix); //pano1.ensureSkyboxReadyForRender(); this.uniforms.easeInOutRatio.value = easeInOutRatio || 0; //之前做点云和全景混合时加的,为了让点云颜色柔和切换到全景颜色。如不混合就0 this.uniforms.pano1Map.value = pano1.getSkyboxTexture(); this.uniforms.pano1Position.value.copy(pano1.position); this.uniforms.pano1Matrix.value.copy(pano1.panoMatrix); //this.updateShaderSource() //this.needsUpdate = true; } stopProjectedPanos() { //this.uniforms.usePanoMap.value = 0 this.usePanoMap = false; } setClipBoxes(bigClipInBox, clipBoxes_in, clipBoxes_out, highlightBoxes) { var prismPolygons = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : []; if (!clipBoxes_in || !clipBoxes_out) { return; } this.uniforms.clipBoxBig_in.value = bigClipInBox && bigClipInBox.inverse; this.uniforms.clipBoxes_in.value = new Float32Array(clipBoxes_in.length * 16); this.uniforms.clipBoxes_out.value = new Float32Array(clipBoxes_out.length * 16); this.uniforms.boxes_highlight.value = new Float32Array(highlightBoxes.length * 16); for (var i = 0; i < clipBoxes_in.length; i++) { var box = clipBoxes_in[i]; this.uniforms.clipBoxes_in.value.set(box.inverse.elements, 16 * i); } for (var _i = 0; _i < clipBoxes_out.length; _i++) { var _box = clipBoxes_out[_i]; this.uniforms.clipBoxes_out.value.set(_box.inverse.elements, 16 * _i); } for (var _i2 = 0; _i2 < highlightBoxes.length; _i2++) { var _box2 = highlightBoxes[_i2]; this.uniforms.boxes_highlight.value.set(_box2.inverse.elements, 16 * _i2); } /* for (let i = 0; i < this.uniforms.clipBoxes.value.length; i++) {?? if (Number.isNaN(this.uniforms.clipBoxes.value[i])) { this.uniforms.clipBoxes.value[i] = Infinity; } } */ if (prismPolygons.length) { var pointsCount = prismPolygons.pointsCount = prismPolygons.reduce((w, c) => { return w + c.points.length; }, 0); this.uniforms.prismList.value = new Float32Array(9 * prismPolygons.length); this.uniforms.prismPoints.value = new Float32Array(2 * pointsCount); prismPolygons.maxPointsCount = 0; //单个prism最大点个数 var pointIndex = 0; for (var _i3 = 0; _i3 < prismPolygons.length; _i3++) { var bound = prismPolygons[_i3].prismBound; var z = prismPolygons[_i3].horizonZ; //z = Potree.browser.urlHasValue('zmin',true) || zs[0] this.uniforms.prismList.value.set([bound.min.z, z, bound.max.z, bound.min.x, bound.max.x, bound.min.y, bound.max.y, prismPolygons[_i3].points.length], 9 * _i3); for (var j = 0; j < prismPolygons[_i3].points.length; j++) { this.uniforms.prismPoints.value.set([prismPolygons[_i3].points[j].x, prismPolygons[_i3].points[j].y], 2 * j + pointIndex); } pointIndex += 2 * prismPolygons[_i3].points.length; prismPolygons.maxPointsCount = Math.max(prismPolygons.maxPointsCount, prismPolygons[_i3].points.length); } } var doUpdate = this.clipBoxes_in.length !== clipBoxes_in.length || this.clipBoxes_out.length != clipBoxes_out.length || this.highlightBoxes.length !== highlightBoxes.length || !this.bigClipInBox != !bigClipInBox || this.prisms.length != prismPolygons.length || this.prisms.maxPointsCount != prismPolygons.maxPointsCount; //this.clipBoxes = clipBoxes; if (doUpdate) { this.shaderNeedsUpdate = true; viewer.dispatchEvent('content_changed'); } this.bigClipInBox = bigClipInBox; this.clipBoxes_in = clipBoxes_in; this.clipBoxes_out = clipBoxes_out; this.highlightBoxes = highlightBoxes; this.prisms = prismPolygons; } } var defaultColor = new Color(1, 1, 1); //config.applicationName == "zhiHouse" ? Colors.zhiBlue : Colors.lightGreen; function dealPosArr(points) { //识别是否每个点都不一样,把连续点变为不连续的片段连接 var add = points => { var points2 = [], len = points.length; for (var i = 0; i < len - 1; i++) { points2.push(points[i], points[i + 1]); } return points2; }; if (points[0] && points[0] instanceof Array) { //多组,每组间连续,但组之间不连续 var points2 = []; points.forEach(ps => points2.push(...add(ps))); return points2; } else if (points.length > 2 && !points[2].equals(points[1])) { return add(points); } else return points; } var LineDraw = { createLine: function createLine(posArr) { var o = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; //多段普通线 (第二个点和第三个点之间是没有线段的, 所以不用在意线段顺序) var mat; if (o.mat) { mat = o.mat; } else { var prop = Object.assign({ lineWidth: o.lineWidth || 1, //windows无效。 似乎mac/ios上粗细有效 ? color: o.color || defaultColor }, o); if (o.deshed) { prop.dashSize = o.dashSize || 0.1, prop.gapSize = o.gapSize || 0.1; } mat = new THREE$1[o.deshed ? "LineDashedMaterial" : "LineBasicMaterial"](prop); } var line = new LineSegments(new BufferGeometry(), mat); line.renderOrder = o.renderOrder || Potree.config.renderOrders.lines; this.moveLine(line, posArr); return line; }, moveLine: function moveLine(line, posArr) { //if(posArr.length == 0)return if (!line.uncontinuous || posArr[0] && posArr[0] instanceof Array) posArr = dealPosArr(posArr); var position = []; posArr.forEach(e => position.push(e.x, e.y, e.z)); line.geometry.setAttribute('position', new Float32BufferAttribute( /* new Float32Array( */position /* ) */, 3)); line.geometry.attributes.position.needsUpdate = true; line.geometry.computeBoundingSphere(); if (line.material instanceof LineDashedMaterial) { line.computeLineDistances(); //line.geometry.attributes.lineDistance.needsUpdate = true; line.geometry.verticesNeedUpdate = true; //没用 } }, createFatLineMat: function createFatLineMat(o) { var supportExtDepth = !!Features.EXT_DEPTH.isSupported(); var params = $.extend({}, { //默认 lineWidth: 5, color: 0xffffff, transparent: true, depthWrite: false, depthTest: false, dashSize: 0.1, gapSize: 0.1 }, o, { //修正覆盖: dashed: o.dashWithDepth ? supportExtDepth && !!o.dashed : !!o.dashed, dashWithDepth: !!o.dashWithDepth, //只在被遮住的部分显示虚线 useDepth: !!o.useDepth, supportExtDepth }); var mat = new LineMaterial(params); //if(o.dashed)(mat.defines.USE_DASH = "") return mat; }, /* 创建可以改变粗细的线。 */ createFatLine: function createFatLine(posArr, o) { var geometry = new LineGeometry(); geometry.setColors(o.color || [1, 1, 1]); var matLine = o.mat || this.createFatLineMat(o); var line = new Line2(geometry, matLine); //line.computeLineDistances(); line.uncontinuous = o.uncontinuous; //线不连续,由线段组成 line.scale.set(1, 1, 1); line.renderOrder = Potree.config.renderOrders.lines; this.moveFatLine(line, posArr); return line; }, moveFatLine: function moveFatLine(line, posArr) { var geometry = line.geometry; var positions = []; if (!line.uncontinuous || posArr[0] && posArr[0] instanceof Array) posArr = dealPosArr(posArr); posArr.forEach(e => { positions.push(...e.toArray()); }); if (!geometry) { geometry = line.geometry = new LineGeometry(); } if (geometry.attributes.instanceEnd && geometry.attributes.instanceEnd.data.array.length != positions.length) { //positions个数改变会有部分显示不出来,所以重建 geometry.dispose(); geometry = new LineGeometry(); line.geometry = geometry; } geometry.setPositions(positions); if (line.material.defines.USE_DASH != void 0) { //line.geometry.verticesNeedUpdate = true; //没用 line.geometry.computeBoundingSphere(); //for raycaster line.computeLineDistances(); } }, updateLine: function updateLine(line, posArr) { if (line instanceof Line2) { LineDraw.moveFatLine(line, posArr); } else { LineDraw.moveLine(line, posArr); } }, /* 为line创建用于检测鼠标的透明mesh,实际是个1-2段圆台。 由于近大远小的原因,假设没有透视畸变、创建的是等粗的圆柱的话, 所看到的线上每个位置的粗细应该和距离成反比。所以将圆柱改为根据距离线性渐变其截面半径的圆台,在最近点(相机到线的垂足)最细。如果最近点在线段上,则分成两段圆台,否则一段。 */ createBoldLine: function createBoldLine(points, o) { o = o || {}; var cylinder = o && o.cylinder; var CD = points[1].clone().sub(points[0]); var rotate = function rotate() { //根据端点旋转好模型 cylinder.lastVector = CD; //记录本次的端点向量 var AB = new Vector3(0, -1, 0); var axisVec = AB.clone().cross(CD).normalize(); //得到垂直于它们的向量,也就是旋转轴 var rotationAngle = AB.angleTo(CD); cylinder.quaternion.setFromAxisAngle(axisVec, rotationAngle); }; if (o && o.type == "init") { cylinder = new Mesh(); cylinder.material = o.mat; if (CD.length() == 0) return cylinder; rotate(); } if (CD.length() == 0) return cylinder; if (o.type != "update") { var CDcenter = points[0].clone().add(points[1]).multiplyScalar(.5); cylinder.position.copy(CDcenter); if (!cylinder.lastVector || o.type == "moveAndRotate") rotate();else if (cylinder.lastVector && CD.angleTo(cylinder.lastVector) > 0) rotate(); //线方向改了or线反向了 重新旋转一下模型 if (config.isEdit && !objects.mainDesign.editing) return cylinder; //节省初始加载时间? } //为了保证线段任何地方的可检测点击范围看起来一样大,更新圆台的结构(但是在镜头边缘会比中心看起来大) var height = points[0].distanceTo(points[1]); var standPos = o && o.standPos || objects.player.position; var k = config.isMobile ? 20 : 40; var dis1 = points[0].distanceTo(standPos); var dis2 = points[1].distanceTo(standPos); var foot = math.getFootPoint(standPos, points[0], points[1]); //垂足 if (o.constantBold || objects.player.mode != "panorama") { var width = 0.1; //0.08; var pts = [new Vector2(width, height / 2), new Vector2(width, -height / 2)]; } else if (foot.clone().sub(points[0]).dot(foot.clone().sub(points[1])) > 0) { //foot不在线段上 var pts = [new Vector2(dis1 / k, height / 2), new Vector2(dis2 / k, -height / 2)]; } else { //在线段上的话,要在垂足这加一个节点,因它距离站位最近,而两端较远 var dis3 = foot.distanceTo(standPos); var len = foot.distanceTo(points[0]); var pts = [new Vector2(dis1 / k, height / 2), new Vector2(dis3 / k, height / 2 - len), new Vector2(dis2 / k, -height / 2)]; } cylinder.geometry && cylinder.geometry.dispose(); //若不删除会占用内存 cylinder.geometry = new LatheBufferGeometry(pts, 4 /* Math.min(dis1,dis2)<10?4:3 */); cylinder.renderOrder = 2; return cylinder; }, updateBoldLine: function updateBoldLine(cylinder, points, type, standPos, constantBold) { this.createBoldLine(points, { type: type, cylinder: cylinder, standPos: standPos, constantBold }); //type:move:平移 会改长短 , type:update根据距离和角度更新 不改长短 } }; var MeshDraw = { getShape: function getShape(shapes, holes) { //不一定闭合 暂时所有shapes共享holes。如果要单独的话, shapes改为[{shape:[],holes:[]},{}]的形式 if (shapes[0] && !(shapes[0] instanceof Array)) { //仅是一个shape的点 shapes = [shapes]; } var holesArr = []; if (holes) { //挖空 holes.forEach(points => { var holePath = new Path(); holePath.moveTo(points[0].x, points[0].y); for (var i = 1, len = points.length; i < len; i++) { holePath.lineTo(points[i].x, points[i].y); } holesArr.push(holePath); }); } var shapesArr = shapes.map(points => { var shape = new Shape(); shape.moveTo(points[0].x, points[0].y); for (var i = 1, len = points.length; i < len; i++) { shape.lineTo(points[i].x, points[i].y); } shape.holes.push(...holesArr); shape.dontClose = points.dontClose; //add 有的shape不需要闭合 return shape; }); return shapesArr; }, /* getShape:function(shapes, holes){ var shape = new THREE.Shape(); if(shapes[0] && !(shapes[0] instanceof Array) ){//仅是一个shape的点 shapes = [shapes] } shapes.forEach((points)=>{ shape.moveTo( points[0].x, points[0].y ); for(var i=1,len=points.length; i{ var holePath = new THREE.Path() holePath.moveTo( points[0].x, points[0].y ) for(var i=1,len=points.length; i 2 && arguments[2] !== undefined ? arguments[2] : { openEnded: false, shapeDontClose: false }; //获得挤出棱柱,可以选择传递height,或者extrudePath var shape = this.getShape(shapes, holes); //points是横截面 [vector2,...] if (options.extrudePath) { // 路径 :[vector3,...] var length = options.extrudePath.reduce((total, currentValue, currentIndex, arr) => { if (currentIndex == 0) return 0; return total + currentValue.distanceTo(arr[currentIndex - 1]); }, 0); //options.extrudePath = new THREE.CatmullRomCurve3(options.extrudePath) if (options.extrudePath.length == 2) { options.tension = 0; //否则一端扭曲 options.steps = 1; } { //去掉重复的点 var path = []; var minDis = options.dontSmooth ? 0 : 0.2; //CatmullRomCurve3 经常扭曲,如果两个点靠得很近可能会扭曲,这里去除靠的太近的点。但去除后依旧会出现一定扭曲. options.extrudePath.forEach((p, i) => { if (i == 0 || i == options.extrudePath.length - 1) return path.push(p); //首尾直接加入 var last = path[path.length - 1]; //和上一个比 var dis = last.distanceTo(p); if (dis <= minDis) { console.log("\u7B2C".concat(i, "\u4E2A\u70B9(").concat(p.toArray(), ")\u56E0\u4E3A\u548C\u4E0A\u4E00\u4E2A\u6570\u636E(").concat(last.toArray(), ")\u592A\u63A5\u8FD1(dis:").concat(dis, ")\u6240\u4EE5\u5220\u9664")); } else if (i == options.extrudePath.length - 2) { //因为最后一个必定加入,所以倒数第二个还也不能太靠近最后一个 last = options.extrudePath[options.extrudePath.length - 1]; //和下一个(最后一个比) if (dis <= minDis) { console.log("\u7B2C".concat(i, "\u4E2A\u70B9(").concat(p.toArray(), ")\u56E0\u4E3A\u548C\u4E0B\u4E00\u4E2A\u6570\u636E(").concat(last.toArray(), ")\u592A\u63A5\u8FD1(dis:").concat(dis, ")\u6240\u4EE5\u5220\u9664")); } else { path.push(p); } } else { path.push(p); } }); options.extrudePath = path; } if (options.dontSmooth) { var curvePath = new CurvePath(); //通用的曲线路径对象,它可以包含直线段和曲线段。在这里只做折线 for (var i = 0; i < options.extrudePath.length - 1; i++) { var curve3 = new LineCurve3(options.extrudePath[i], options.extrudePath[i + 1]); //添加线段 curvePath.add(curve3); } options.extrudePath = curvePath; } else { //平滑连续的曲线(但经常会有扭曲的问题,tension:0能缓解, 另外shape和path都最好在原点附近,也就是点需减去bound.min ) options.extrudePath = new CatmullRomCurve3(options.extrudePath, options.closed, 'catmullrom' /* 'centripetal' */, options.tension); //tension:拐弯剧烈程度,但随着长度增长,该值需要减小,否则会扭曲 } } var extrudeSettings = $.extend(options, { steps: options.steps != void 0 ? options.steps : options.extrudePath ? Math.round(length / (options.spaceDis || 0.3)) : 1, //分成几段 spaceDis每段长度 bevelEnabled: false //不加的话,height为0时会有圆弧高度 //openEnded默认false }); var geometry = new ExtrudeBufferGeometry(shape, extrudeSettings); //修改了three.js文件, buildLidFaces处,创建顶底面加了选项,可以选择开口。 return geometry; }, getUnPosPlaneGeo: function () { //获取还没有赋值位置的plane geometry var e = new Uint16Array([0, 1, 2, 0, 2, 3]) // , t = new Float32Array([-.5, -.5, 0, .5, -.5, 0, .5, .5, 0, -.5, .5, 0]) , i = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]), g = new BufferGeometry(); g.setIndex(new BufferAttribute(e, 1)), //g.addAttribute("position", new n.BufferAttribute(t, 3)), g.setAttribute("uv", new BufferAttribute(i, 2)); return function () { return g; }; }(), getPlaneGeo: function getPlaneGeo(A, B, C, D) { var geo = this.getUnPosPlaneGeo().clone(); var pos = [A.x, A.y, A.z, B.x, B.y, B.z, C.x, C.y, C.z, D.x, D.y, D.z]; //geo.addAttribute("position", new THREE.BufferAttribute(pos, 3)) geo.setAttribute('position', new Float32BufferAttribute(pos, 3)); geo.computeVertexNormals(); geo.computeBoundingSphere(); //for raycaster return geo; }, drawPlane: function drawPlane(A, B, C, D, material) { var wall = new Mesh(this.getPlaneGeo(A, B, C, D), material); return wall; }, movePlane: function movePlane(mesh, A, B, C, D) { var pos = new Float32Array([A.x, A.y, A.z, B.x, B.y, B.z, C.x, C.y, C.z, D.x, D.y, D.z]); mesh.geometry.addAttribute("position", new BufferAttribute(pos, 3)); mesh.geometry.computeBoundingSphere(); //for checkIntersect }, createGeometry: function createGeometry(posArr, faceArr, uvArr, normalArr) { //创建复杂mesh. faceArr:[[0,1,2],[0,2,3]] var geo = new BufferGeometry(); var positions = []; posArr.forEach(p => positions.push(p.x, p.y, p.z)); geo.setAttribute('position', new Float32BufferAttribute(positions, 3)); if (faceArr) { var indice = []; faceArr.forEach(f => indice.push(...f)); geo.setIndex(indice); // auto set Uint16BufferAttribute or Uint32BufferAttribute } if (uvArr) { var uvs = []; uvArr.forEach(uv => uvs.push(uv.x, uv.y)); geo.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); } if (normalArr) { var normals = []; normalArr.forEach(n => normals.push(n.x, n.y, n.z)); geo.setAttribute("normal", new Float32BufferAttribute(normals, 3)); } /* geo.computeVertexNormals() geo.computeBoundingSphere() //for raycaster */ return geo; }, updateGeometry: function updateGeometry(geo, posArr, faceArr, uvArr, normalArr) { //创建复杂mesh. faceArr:[[0,1,2],[0,2,3]] var positions = []; posArr.forEach(p => positions.push(p.x, p.y, p.z)); geo.setAttribute('position', new Float32BufferAttribute(positions, 3)); geo.attributes.position.needsUpdate = true; if (faceArr) { var indice = []; faceArr.forEach(f => indice.push(...f)); geo.setIndex(indice); // auto set Uint16BufferAttribute or Uint32BufferAttribute } if (uvArr) { var uvs = []; uvArr.forEach(uv => uvs.push(uv.x, uv.y)); geo.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); } if (normalArr) { var normals = []; normalArr.forEach(n => normals.push(n.x, n.y, n.z)); geo.setAttribute("normal", new Float32BufferAttribute(normals, 3)); } /* geo.computeVertexNormals() */ geo.computeBoundingSphere(); //for raycaster and visi return geo; } }; class DepthBasicMaterial extends ShaderMaterial { constructor() { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var { width, height } = viewer.renderer.getSize(new Vector2()); var uniforms = { resolution: { type: 'v2', value: new Vector2(width, height) }, viewportOffset: { type: 'v2', value: new Vector2(0, 0) }, //left, top //uUseOrthographicCamera:{ type: "b", value: false }, nearPlane: { type: 'f', value: 0.1 }, farPlane: { type: 'f', value: 10000 }, depthTexture: { type: 't', value: null }, opacity: { type: 'f', value: 1 }, map: { type: 't', value: o.map }, baseColor: { type: 'v3', value: o.color ? new Color(o.color) : new Color("#ffffff") }, backColor: { type: 'v3', value: o.backColor ? new Color(o.backColor) : new Color("#ddd") }, clipDistance: { type: 'f', value: o.clipDistance || 4 }, //消失距离 occlusionDistance: { type: 'f', value: o.occlusionDistance || 1 }, //变为backColor距离 maxClipFactor: { type: 'f', value: o.maxClipFactor || 1 }, //0-1 maxOcclusionFactor: { type: 'f', value: o.maxOcclusionFactor || 1 }, //0-1 mapScale: { type: 'f', value: o.mapScale || 1 } //0-1 }; var { vs, fs } = Common.changeShaderToWebgl2(Shaders['depthBasic.vs'], Shaders['depthBasic.fs'], 'ShaderMaterial'); super({ uniforms, vertexShader: vs, fragmentShader: fs, depthWrite: false, depthTest: false, transparent: o.transparent == void 0 ? true : o.transparent, side: o.side || 0 /* THREE.DoubleSide */ }); this.events = { setSize: e => { //如果出现横条状的异常,往往是viewportOffset出错 //地图不需要 if (!this.realUseDepth || !e.viewport) return; var viewport = e.viewport; var viewportOffset = viewport.offset || new Vector2(); this.uniforms.resolution.value.copy(viewport.resolution2); //2023.6.12突然发现ratio>1的用resolution不对,得用2才对。但是之前明明记得不是这样 this.uniforms.viewportOffset.value.copy(viewportOffset); }, render: e => { //before render 如果有大于两个viewport的话,不同viewport用不同的depthTex this.updateDepthParams(e); } /* cameraChange:(e)=>{ if(e.changeInfo.projectionChanged){//resize时也会触发。虽然保守起见的话加上resize比较好//所以当时为何不用resize //console.log('projectionChanged') this.events.setSize(e) } } */ }; //-----其他---- this.autoDepthTest = o.autoDepthTest; if (o.opacity != void 0) { this.opacity = o.opacity; } this.useDepth = o.useDepth; this.map = o.map; } get useDepth() { return this.useDepth_; } set useDepth(value) { value = value && Features.EXT_DEPTH.isSupported(); //如果不支持 EXT_DEPTH 的话会失效 if (this.useDepth_ != value) { this.setRealDepth(value); this.useDepth_ = value; if (value) { viewer.addEventListener("render.begin", this.events.render); //viewer.addEventListener('camera_changed', this.events.cameraChange) viewer.addEventListener('resize', this.events.setSize); this.updateDepthParams(); } else { viewer.removeEventListener("render.begin", this.events.render); viewer.removeEventListener('resize', this.events.setSize); } } } setRealDepth(useDepth, viewport) { //确实使用到depthTex if (this.realUseDepth != useDepth) { if (useDepth) { this.defines.useDepth = ''; } else { delete this.defines.useDepth; } this.realUseDepth = useDepth; if (this.autoDepthTest) this.depthWrite = this.depthTest = !useDepth; //如果useDepth = false,使用原始的depthTest this.needsUpdate = true; if (!viewport) viewport = viewer.mainViewport; //暂时这么设置 useDepth && this.events.setSize({ viewport }); } } get map() { return this.uniforms.map.value; } set map(map) { this.uniforms.map.value = map; if (map) { this.defines.use_map = ''; } else { delete this.defines.use_map; } } get opacity() { return this.uniforms.opacity.value; } set opacity(o) { this.uniforms && (this.uniforms.opacity.value = o); } get color() { return this.uniforms.baseColor.value; } set color(c) { this.uniforms && this.uniforms.baseColor.value.set(c); } /* dispose(){ super.dispose() viewer.depthBasic } */ copy(source) { super.copy(source); this.useDepth = source.useDepth; this.map = source.map; return this; } updateDepthParams() { var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; //主要用于点云遮住mesh var viewport = e.viewport || viewer.mainViewport; var camera = viewport.camera; var hasDepth = this.useDepth && camera.isPerspectiveCamera && (Potree.settings.pointEnableRT || Potree.settings.displayMode == 'showPanos' || viewer.useEDL); this.setRealDepth(hasDepth, viewport); if (hasDepth) { this.uniforms.depthTexture.value = viewer.getPRenderer().getRtEDL(viewport).depthTexture; //其实只赋值一次就行 this.uniforms.nearPlane.value = camera.near; this.uniforms.farPlane.value = camera.far; } //this.uniforms.uUseOrthographicCamera.value = !camera.isPerspectiveCamera } } var geo = new PlaneBufferGeometry(1, 1); class Sprite$2 extends Mesh { constructor() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(geo, options.mat || new DepthBasicMaterial(options)); /* ({map:options.map, useDepth:options.useDepth})) */ this.root = options.root || this; this.renderOrder = options.renderOrder != void 0 ? options.renderOrder : 4; this.pickOrder = options.pickOrder || 0; this.sizeInfo = options.sizeInfo; this.dontFixOrient = options.dontFixOrient; this.options = options; this.position.y = options.disToLine || 0; //离线距离 this.matrixAutoUpdate = false; this.matrixMap = new Map(); if (this.root != this) { this.matrixMapRoot = new Map(); this.root.matrixAutoUpdate = false; } this.visiMap = new Map(); this.name = options.name || 'sprite'; this.useViewport = null; this.viewports = options.viewports; //指定更新的viewports this.visible_ = true; var clear = e => { this.matrixMap.clear(); //清空后在所有viewport上都必须更新才能渲染 //this.needsUpdate = true }; viewer.mapViewer && viewer.mapViewer.addEventListener("camera_changed", clear); viewer.addEventListener("camera_changed", clear); /* if(viewer.viewports.length == 1){//直接更新。如果有多个不在这更新,在"render.begin" this.update(e) } */ var applyMatrix = e => { this.applyMatrix(e); }; viewer.addEventListener("raycaster", applyMatrix); //before render viewer.addEventListener("render.begin", applyMatrix); //before render viewer.addEventListener("render.begin2", applyMatrix); viewer.addEventListener("cameraSetLayers", applyMatrix); this.addEventListener('dispose', () => { viewer.mapViewer && viewer.mapViewer.removeEventListener("camera_changed", clear); viewer.removeEventListener("camera_changed", clear); viewer.removeEventListener("raycaster", applyMatrix); //before render viewer.removeEventListener("render.begin", applyMatrix); viewer.removeEventListener("render.begin2", applyMatrix); }); } set visible(v) { var oldV = this.visible_; this.visible_ = v; if (v && !oldV) { this.matrixMap && this.matrixMap.clear(); //this.update() //update内有unableCompute会无限回调 } } get visible() { return this.visible_; } realVisible(viewport, interactables /* , raycaster */) { if (interactables) { if (!interactables.some(object => { //interactables中是否能找到this var finded; object.traverse(object => { if (object == this) { finded = true; return { stopContinue: true }; } }); return finded; })) return; } /* if(interactables && viewport.name == 'mapViewport'){ console.log(this) } */ if (!( /* raycaster || */viewport.camera).layers.test(this.layers)) { //如地图上一般不可见测量线 return false; } if (!this.visible && this.unvisibleReasons && this.unvisibleReasons.some(e => e.reason != 'unableCompute')) { return false; } var v = true; var parent = this.parent; var lastParent = this; while (parent) { if (parent.visible === false) { v = false; break; } lastParent = parent; parent = parent.parent; } if (v && !(lastParent instanceof Scene)) { //已被删除 v = false; } /* if(!this.latestRealVisi && v){//变为可见后先update this.latestRealVisi = true setTimeout(()=>{ this.update() },1)//延迟 防止无限调用 return false } this.latestRealVisi = v */ return v; } waitUpdate() { this.matrixMap.clear(); //清空后在所有viewport上都必须更新才能渲染 //viewer.dispatchEvent('content_changed') } update() { var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (!e.viewport) { var viewports = this.viewports || viewer.viewports; if (!viewports) return; viewports.forEach(view => { this.update({ viewport: view }); }); return; } if (!this.root || !this.realVisible(e.viewport, e.interactables) /* this.visible */) return; if (this.viewports && !this.viewports.includes(e.viewport)) return; if (e.viewport.name == 'magnifier') return; var camera = e.viewport.camera; //rotation if (!this.dontFixOrient) { //orthoCamera一般要加dontFixOrient var orient2dAngle; if (this.root.lineDir) { this.root.updateMatrix(); //先更新,getWorldPosition才能得到正确的 this.root.updateMatrixWorld(true); var center = this.root.getWorldPosition(new Vector3()); //由于两个端点容易在屏幕外,所以使用center和center加dir var setVisi = state => { this.visiMap.set(e.viewport, state); Potree.Utils.updateVisible(this, 'unableCompute', !!state); }; var renderer = e.viewer ? e.viewer.renderer : e.renderer; var r1 = Potree.Utils.getPos2d(center, e.viewport, renderer.domElement.parentElement, renderer); //let r1 = Potree.Utils.getPos2d(center, e.viewport, viewer.renderArea, viewer.renderer); if (!r1.trueSide) return setVisi(false); // 但这句会使realVisible为false从而无法更新//console.error('!r1.trueSide') //中心点如果在背面直接不渲染了 var r2, point2; var p2State = '', len = 1, p2StateHistory = []; while (p2State != 'got' && p2StateHistory.length < 10) { point2 = center.clone().add(this.root.lineDir.clone().multiplyScalar(len)); r2 = Potree.Utils.getPos2d(point2, e.viewport, renderer.domElement.parentElement, renderer); if (!r2.trueSide) { //很少遇到点2在背面的 if (!p2StateHistory.includes('tooLong-reverse')) { p2State = 'tooLong-reverse'; //先尝试反向 len = -len; } else { p2State = 'tooLong'; len = len / 2; } } else { var _dis = r2.pos.distanceTo(r1.pos); if (math.closeTo(_dis, 0)) { //console.log('dis == 0') setVisi(false); return; break; } if (_dis < 10 && !p2StateHistory.includes('tooLong')) { //和r1的屏幕距离太近,要加长,否则精度过低 p2State = 'tooShort'; len = 100 / _dis * len; } else { p2State = 'got'; break; } } p2StateHistory.push(p2State); } //console.log(p2StateHistory,len) if (!r2.trueSide) { return setVisi(false); //, console.log(' !r2.trueSide', ) } var p1 = r1.pos, p2 = r2.pos; if (p2StateHistory.filter(e => e == 'tooLong-reverse').length % 2 == 1) { //反,for marker p2 = r1.pos, p1 = r2.pos; } var vec = new Vector2().subVectors(p1, p2); orient2dAngle = -vec.angle(); //根据测量线在屏幕上的角度在旋转label,使之和屏幕上的二维线平行。 var y = Math.abs(this.position.y); var facePlane = this.root.measure && this.root.measure.facePlane; var eyeDir = new Vector3().subVectors(center, camera.position); var clockWise = facePlane && facePlane.normal.dot(eyeDir /* e.viewport.view.direction */) < 0; if (p1.x < p2.x) { orient2dAngle += Math.PI; //避免字是倒着的情况。(使字一直在线的下方) clockWise != void 0 && (this.position.y = clockWise ? y : -y); } else { clockWise != void 0 && (this.position.y = clockWise ? -y : y); //使area类型的edgeLabel都在外侧 } //this.parent.text && console.log(this.parent.text, clockWise, this.position.y, e.viewport.name /* THREE.Math.radToDeg(angle), p1.x < p2.x */ ) setVisi(true); } var parentQua = this.root.parent.getWorldQuaternion(new Quaternion()); this.root.quaternion.multiplyQuaternions(parentQua.invert(), camera.quaternion); //乘上parentQua.invert()是为了中和掉父结点的qua,使只剩下camera.quaternion if (orient2dAngle) { var qua = new Quaternion().setFromAxisAngle(new Vector3(0, 0, 1), orient2dAngle); this.root.quaternion.multiply(qua); } } //scale var info = this.sizeInfo; if (info) { this.root.updateMatrix(); //先更新,getWorldPosition才能得到正确的 this.root.updateMatrixWorld(true); var scale; if (info.nearBound == void 0 && info.farBound != void 0 || info.nearBound != void 0 && info.farBound == void 0) { //仅限制最大或最小的话,不判断像素大小,直接限制mesh的scale //这个判断也可以写到getScaleForConstantSize里,可以更严谨控制像素宽度,这里只简单计算大小 var dis = camera.position.distanceTo(this.root.getWorldPosition(new Vector3())); if (info.farBound == void 0 && dis < info.nearBound) { scale = info.scale * dis / info.nearBound; } else if (info.nearBound == void 0 && dis > info.farBound) { scale = info.scale * dis / info.farBound; } else { scale = info.scale; } } else { scale = math.getScaleForConstantSize($.extend(info, { //规定下最小最大像素 camera, position: this.root.getWorldPosition(new Vector3()), resolution: e.viewport.resolution //2 })); } if (!isNaN(scale)) { this.root.scale.set(scale, scale, scale); } } this.updateMatrix(); //this.root.updateMatrixWorld(true) //console.log(this.root.text, this.root.matrix.elements) this.matrixMap.set(e.viewport, this.matrix.clone()); if (this.root != this) { this.root.updateMatrix(); //因this.position可能在两个viewport不同 this.matrixMapRoot.set(e.viewport, this.root.matrix.clone()); } this.needsUpdate = false; this.useViewport = e.viewport; } applyMatrix(e) { if (!e) e = { viewport: viewer.mainViewport }; //随便写一个viewport var visi = this.visiMap.get(e.viewport); //还原可见性 Potree.Utils.updateVisible(this, 'unableCompute', visi == false ? false : true); /* if(e.viewport.name == 'mapViewport' && visi && this.visiMap.get(viewer.mainViewport) == false){ console.log(1) } */ if (e.viewport.name == 'magnifier') return; if (this.viewports && !this.viewports.includes(e.viewport)) return; if (!this.root || !this.realVisible(e.viewport, e.interactables)) return; var matrix = this.matrixMap.get(e.viewport); if (!matrix) { this.update(e); matrix = this.matrixMap.get(e.viewport); if (!matrix) return; } if (e.viewport == this.useViewport) { return; } this.useViewport = e.viewport; this.matrix.copy(matrix); if (this.root != this) { var matrix2 = this.matrixMapRoot.get(e.viewport); this.root.matrix.copy(matrix2); } e.raycaster && this.root.updateMatrixWorld(true); //渲染前会自动updateMatrixWorld,但raycaster不会 //console.log(this.root.name + e.viewport.name + " : "+this.root.matrixWorld.elements) } setUniforms(name, value) { this.material.setUniforms(name, value); } dispose() { this.removeAllListeners(); this.parent && this.parent.remove(this); this.dispatchEvent('dispose'); } } /* let orient2d if(this.lineDir){ this.root.updateMatrix();//先更新,getWorldPosition才能得到正确的 this.root.updateMatrixWorld(true) let center = this.root.getWorldPosition(new THREE.Vector3()) //由于两个端点容易在屏幕外,所以使用center和center加dir let lineDir = this.lineDir.clone(); let r1 = Potree.Utils.getPos2d(center, camera, viewer.renderArea, e.viewport); if(!r1.trueSide)return Potree.Utils.updateVisible(this, 'unableCompute', false);// 但这句会使realVisible为false从而无法更新//console.error('!r1.trueSide') //中心点如果在背面直接不渲染了 let r2, point2 let p2State = '', len=1, p2StateHistory = [] while(p2State != 'got' && p2StateHistory.length<10){ point2 = center.clone().add(lineDir.multiplyScalar(len)); r2 = Potree.Utils.getPos2d(point2, camera, viewer.renderArea, e.viewport); if(!r2.trueSide){ //很少遇到点2在背面的 if(!p2StateHistory.includes('tooLong-reverse')){ p2State = 'tooLong-reverse' //先尝试反向 len = -len }else{ p2State = 'tooLong' len = len / 2 } }else{ let dis = r2.pos.distanceTo(r1.pos) if(dis == 0){ //console.log('dis == 0') Potree.Utils.updateVisible(this, 'unableCompute', false) return break } if(dis<10 && !p2StateHistory.includes('tooLong')){//和r1的屏幕距离太近,要加长,否则精度过低 p2State = 'tooShort' len = 100/dis * len }else{ p2State = 'got'; break; } } p2StateHistory.push(p2State) } //console.log(p2StateHistory,len) if(!r2.trueSide){ return Potree.Utils.updateVisible(this, 'unableCompute', false)//, console.log(' !r2.trueSide', ) } Potree.Utils.updateVisible(this, 'unableCompute', true) let p1 = r1.pos, p2 = r2.pos let vec = new THREE.Vector2().subVectors(p1,p2); let angle = -vec.angle() //根据测量线在屏幕上的角度在旋转label,使之和屏幕上的二维线平行。 if(p1.x < p2.x) angle += Math.PI //避免字是倒着的情况 orient2d = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,0,1), angle) //console.log(this.parent.text, THREE.Math.radToDeg(angle), p1.x < p2.x ) } let parentQua = this.root.parent.getWorldQuaternion(new THREE.Quaternion) this.root.quaternion.multiplyQuaternions(parentQua.invert(),camera.quaternion) //乘上parentQua.invert()是为了中和掉父结点的qua,使只剩下camera.quaternion if(this.lineDir){ this.root.quaternion.multiply(orient2d) } */ // /** //可能还是要用html写,因为要加按钮和图片 class TextSprite$2 extends Object3D { //注:为了分两层控制scale,不直接extend Sprite constructor() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(); var map = new Texture(); map.minFilter = LinearFilter; map.magFilter = LinearFilter; this.sprite = new Sprite$2(Object.assign({ root: this }, options, { map })); this.add(this.sprite); this.fontWeight = options.fontWeight == void 0 ? 'Bold' : options.fontWeight; this.rectBorderThick = options.rectBorderThick || 0; this.textBorderThick = options.textBorderThick || 0; this.fontface = 'Arial'; this.fontsize = options.fontsize || 16; this.textBorderColor = options.textBorderColor ? Common.CloneObject(options.textBorderColor) : { r: 0, g: 0, b: 0, a: 0.0 }; this.backgroundColor = options.backgroundColor ? Common.CloneObject(options.backgroundColor) : { r: 255, g: 255, b: 255, a: 1.0 }; this.textColor = options.textColor ? Common.CloneObject(options.textColor) : { r: 0, g: 0, b: 0, a: 1.0 }; this.borderColor = options.borderColor ? Common.CloneObject(options.borderColor) : { r: 0, g: 0, b: 0, a: 0.0 }; this.borderRadius = options.borderRadius || 6; this.margin = options.margin; this.setText(options.text); this.name = options.name; //this.setText(text); } setText(text) { if (text == void 0) text = ''; if (this.text !== text) { if (!(text instanceof Array)) { this.text = [text + '']; } else this.text = text; this.updateTexture(); this.sprite.waitUpdate(); //重新计算各个viewport的matrix } } setTextColor(color) { this.textColor = Common.CloneObject(color); this.updateTexture(); } setBorderColor(color) { this.borderColor = Common.CloneObject(color); this.updateTexture(); } setBackgroundColor(color) { this.backgroundColor = Common.CloneObject(color); this.updateTexture(); } setPos(pos) { this.position.copy(pos); this.sprite.waitUpdate(); } update() { this.sprite.waitUpdate(); } /* setVisible(v){ Potree.Utils.updateVisible(this, 'setVisible', v) } */ setUniforms(name, value) { this.sprite.setUniforms(name, value); } updateTexture1() { var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); var r = window.devicePixelRatio; context.font = this.fontWeight + ' ' + this.fontsize * r + 'px ' + this.fontface; //context["font-weight"] = 100; //语法与 CSS font 属性相同。 //this.text = '啊啊啊啊啊啊fag' var metrics = context.measureText(this.text); var textWidth = metrics.width; var margin = (this.margin ? new Vector2().copy(this.margin) : new Vector2(this.fontsize, Math.max(this.fontsize * 0.4, 10))).clone().multiplyScalar(r); var spriteWidth = 2 * margin.x + textWidth + 2 * this.rectBorderThick * r; var spriteHeight = 2 * margin.y + this.fontsize * r + 2 * this.rectBorderThick * r; context.canvas.width = spriteWidth; context.canvas.height = spriteHeight; context.font = this.fontWeight + ' ' + this.fontsize * r + 'px ' + this.fontface; /* let diff = 2//针对英文大部分在baseLine之上所以降低一点(metrics.fontBoundingBoxAscent - metrics.fontBoundingBoxDescent) / 2 context.textBaseline = "middle" */ var expand = Math.max(1, Math.pow(this.fontsize / 16, 1.3)) * r; // 针对英文大部分在baseLine之上所以降低一点,或者可以识别当不包含jgqp时才加这个值 //canvas原点在左上角 context.textBaseline = 'alphabetic'; // "middle" //设置文字基线。当起点y设置为0时,只有该线以下的部分被绘制出来。middle时文字显示一半(但是对该字体所有字的一半,有的字是不一定显示一半的,尤其汉字),alphabetic时是英文字母的那条基线。 //let actualHeight = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent; // 当前文本字符串在这个字体下用的实际高度 //文字y向距离从textBaseline向上算 var actualBoundingBoxAscent = metrics.actualBoundingBoxAscent == void 0 ? this.fontsize * r * 0.8 : metrics.actualBoundingBoxAscent; //有的流览器没有。只能大概给一个 var y = actualBoundingBoxAscent + margin.y + expand; //console.log(this.text, 'y' , y, 'actualBoundingBoxAscent', metrics.actualBoundingBoxAscent,'expand',expand ) // border color context.strokeStyle = 'rgba(' + this.borderColor.r + ',' + this.borderColor.g + ',' + this.borderColor.b + ',' + this.borderColor.a + ')'; var rectBorderThick = this.rectBorderThick * r; context.lineWidth = rectBorderThick; // background color context.fillStyle = 'rgba(' + this.backgroundColor.r + ',' + this.backgroundColor.g + ',' + this.backgroundColor.b + ',' + this.backgroundColor.a + ')'; this.roundRect(context, rectBorderThick / 2, rectBorderThick / 2, spriteWidth - rectBorderThick, spriteHeight - rectBorderThick, this.borderRadius * r); // text color if (this.textBorderThick) { context.strokeStyle = 'rgba(' + this.textBorderColor.r + ',' + this.textBorderColor.g + ',' + this.textBorderColor.b + ',' + this.textBorderColor.a + ')'; context.lineWidth = this.textBorderThick * r; context.strokeText(this.text, rectBorderThick + margin.x, y /* spriteHeight/2 + diff */); } context.fillStyle = 'rgba(' + this.textColor.r + ',' + this.textColor.g + ',' + this.textColor.b + ',' + this.textColor.a + ')'; context.fillText(this.text, rectBorderThick + margin.x, y /* spriteHeight/2 + diff */); //x,y var texture = new Texture(canvas); texture.minFilter = LinearFilter; texture.magFilter = LinearFilter; texture.needsUpdate = true; //this.material.needsUpdate = true; if (this.sprite.material.map) { this.sprite.material.map.dispose(); } this.sprite.material.map = texture; this.sprite.scale.set(spriteWidth * 0.01 / r, spriteHeight * 0.01 / r, 1.0); } updateTexture() { var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); var r = window.devicePixelRatio; context.font = this.fontWeight + ' ' + this.fontsize * r + 'px ' + this.fontface; //context["font-weight"] = 100; //语法与 CSS font 属性相同。 //this.text = '啊啊啊啊啊啊fag' var textMaxWidth = 0, infos = []; for (var text of this.text) { var metrics = context.measureText(text); var textWidth = metrics.width; infos.push(metrics); textMaxWidth = Math.max(textMaxWidth, textWidth); } var margin = (this.margin ? new Vector2().copy(this.margin) : new Vector2(this.fontsize, Math.max(this.fontsize * 0.4, 10))).clone().multiplyScalar(r); var lineSpace = (this.fontsize + margin.y) * 0.5; var spriteWidth = 2 * margin.x + textMaxWidth + 2 * (this.rectBorderThick + this.textBorderThick) * r; //还要考虑this.textshadowColor,太麻烦了不写了 var spriteHeight = 2 * margin.y + (this.fontsize + this.textBorderThick * 2) * r * this.text.length + 2 * this.rectBorderThick * r + lineSpace * (this.text.length - 1); context.canvas.width = spriteWidth; context.canvas.height = spriteHeight; context.font = this.fontWeight + ' ' + this.fontsize * r + 'px ' + this.fontface; if (spriteWidth > 4000) { console.error('spriteWidth', spriteWidth, 'spriteHeight', spriteHeight, this.fontsize, r, this.text, margin); } /* let diff = 2//针对英文大部分在baseLine之上所以降低一点(metrics.fontBoundingBoxAscent - metrics.fontBoundingBoxDescent) / 2 context.textBaseline = "middle" */ var expand = Math.max(1, Math.pow(this.fontsize / 16, 1.3)) * r; // 针对英文大部分在baseLine之上所以降低一点,或者可以识别当不包含jgqp时才加这个值 //canvas原点在左上角 context.textBaseline = 'alphabetic'; // "middle" //设置文字基线。当起点y设置为0时,只有该线以下的部分被绘制出来。middle时文字显示一半(但是对该字体所有字的一半,有的字是不一定显示一半的,尤其汉字),alphabetic时是英文字母的那条基线。 // border color context.strokeStyle = 'rgba(' + this.borderColor.r + ',' + this.borderColor.g + ',' + this.borderColor.b + ',' + this.borderColor.a + ')'; var rectBorderThick = this.rectBorderThick * r; context.lineWidth = rectBorderThick; // background color context.fillStyle = 'rgba(' + this.backgroundColor.r + ',' + this.backgroundColor.g + ',' + this.backgroundColor.b + ',' + this.backgroundColor.a + ')'; this.roundRect(context, rectBorderThick / 2, rectBorderThick / 2, spriteWidth - rectBorderThick, spriteHeight - rectBorderThick, this.borderRadius * r); context.fillStyle = 'rgba(' + this.textColor.r + ',' + this.textColor.g + ',' + this.textColor.b + ',' + this.textColor.a + ')'; var y = margin.y + expand; for (var i = 0; i < this.text.length; i++) { //let actualHeight = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent // 当前文本字符串在这个字体下用的实际高度 //文字y向距离从textBaseline向上算 var actualBoundingBoxAscent = infos[i].actualBoundingBoxAscent == void 0 ? this.fontsize * r * 0.8 : infos[i].actualBoundingBoxAscent; //有的流览器没有。只能大概给一个 y += actualBoundingBoxAscent + this.textBorderThick; //console.log(actualBoundingBoxAscent) //console.log(this.text, 'y' , y, 'actualBoundingBoxAscent', metrics.actualBoundingBoxAscent,'expand',expand ) var textLeftSpace = (textMaxWidth - infos[i].width) / 2; var x = this.rectBorderThick + margin.x + textLeftSpace; // text color if (this.textBorderThick) { context.strokeStyle = 'rgba(' + this.textBorderColor.r + ',' + this.textBorderColor.g + ',' + this.textBorderColor.b + ',' + this.textBorderColor.a + ')'; context.lineWidth = this.textBorderThick * r; context.strokeText(this.text[i], x, y); } if (this.textshadowColor) { context.shadowOffsetX = 0; context.shadowOffsetY = 0; context.shadowColor = this.textshadowColor; context.shadowBlur = 12 * r; } context.fillText(this.text[i], x, y); y += lineSpace; } var texture = new Texture(canvas); texture.minFilter = LinearFilter; texture.magFilter = LinearFilter; texture.needsUpdate = true; //this.material.needsUpdate = true; if (this.sprite.material.map) { this.sprite.material.map.dispose(); } this.sprite.material.map = texture; this.sprite.scale.set(spriteWidth * 0.01 / r, spriteHeight * 0.01 / r, 1.0); } roundRect(ctx, x, y, w, h, r) { ctx.beginPath(); ctx.moveTo(x + r, y); ctx.lineTo(x + w - r, y); ctx.arcTo(x + w, y, x + w, y + r, r); //圆弧。前四个参数同quadraticCurveTo //ctx.quadraticCurveTo(x + w, y, x + w, y + r); //二次贝塞尔曲线需要两个点。第一个点是用于二次贝塞尔计算中的控制点,第二个点是曲线的结束点。 ctx.lineTo(x + w, y + h - r); ctx.arcTo(x + w, y + h, x + w - r, y + h, r); ctx.lineTo(x + r, y + h); ctx.arcTo(x, y + h, x, y + h - r, r); ctx.lineTo(x, y + r); ctx.arcTo(x, y, x + r, y, r); ctx.closePath(); ctx.fill(); ctx.stroke(); } dispose() { this.sprite.material.uniforms.map.value.dispose(); this.parent && this.parent.remove(this); this.sprite.dispose(); this.removeAllListeners(); this.dispatchEvent('dispose'); } } /* z | | | | x <-------| 中心为点云position加boudingbox中心 / / y */ var lineLen$1 = 2, stemLen = 4, arrowLen = 2, lineDisToStem = 5; var opacity = 0.5; class Axis extends Object3D { // 坐标轴 constructor() { super(); this.getArrow(); this.createArrows(); //this.position.copy(position) 点云的中心点就是在(0,0,0) //this.scale.set(2,2,2) /* viewer.addEventListener('camera_changed', e => { if(e.viewport.name != 'MainView')return //只调整mainView,否则需要每次渲染前调整。缺点:地图上的大小变来变去 let s = Potree.math.getScaleForConstantSize( {//规定下最小最大像素 width2d:50, camera:e.camera , position:this.position, resolution: e.viewport.resolution//2 }) this.scale.set(s,s,s) }) */ } getArrow() { var arrowGroup = new Object3D(); var line = LineDraw.createLine([new Vector3(), new Vector3(0, 0, lineLen$1)]); var stem = new Mesh(new BoxGeometry(0.3, 0.3, stemLen)); stem.position.set(0, 0, lineLen$1 + lineDisToStem + stemLen / 2); var arrow = new Mesh(new CylinderBufferGeometry(0, 0.6, arrowLen, 12, 1, false)); //radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 arrow.position.set(0, 0, lineLen$1 + lineDisToStem + stemLen + arrowLen / 2); arrow.rotation.set(Math.PI / 2, 0, 0); arrowGroup.add(stem); arrowGroup.add(line); arrowGroup.add(arrow); this.arrowGroup = arrowGroup; } createArrows() { var material = new MeshBasicMaterial({ color: "#00d7df", side: 2, transparent: true, opacity: 0.8, depthWrite: false }); ['x', 'y', 'z'].forEach(axisText => { var color = new Color().set(Potree.config.axis[axisText].color); var group = this.arrowGroup.clone(); group.children.forEach(e => { e.material = e.material.clone(); /* e.material.opacity = opacity e.material.transparent = true */ e.material.color.copy(color); }); var label = this.createLabel(axisText, color); label.position.set(0, 0, lineLen$1 + stemLen + arrowLen + lineDisToStem + 3); group.add(label); if (axisText == 'y') { group.rotation.x = -Math.PI / 2; } else if (axisText == 'x') { group.rotation.y = Math.PI / 2; } this.add(group); }); } createLabel(text, color) { var label = new TextSprite$2({ //无法解决 因其祖先有设定quaternion, 无法对着镜头 backgroundColor: { r: 0, g: 0, b: 0, a: 0 }, textColor: { r: color.r * 255, g: color.g * 255, b: color.b * 255, a: 1 }, fontsize: 120, //useDepth : true , renderOrder: 5, // pickOrder:5, text, name: 'axis' }); label.scale.set(3, 3, 3); return label; } /* createLabel(text,color){ var canvas = document.createElement("canvas") var context = canvas.getContext("2d"); canvas.width = 256, canvas.height = 256; var fontSize = 120 context.fillStyle = color //"#00ffee"; context.font = "normal " + fontSize + "px 微软雅黑" var textWidth = context.measureText(text).width; context.clearRect(0,0,canvas.width,canvas.height); context.fillText(text, (canvas.width - textWidth) / 2 , (canvas.height + fontSize) / 2); var tex = new THREE.Texture(canvas); tex.needsUpdate = true tex.minFilter = THREE.NearestFilter//防止边缘发黑 tex.magFilter = THREE.NearestFilter//防止边缘发黑 var sprite = new THREE.Sprite(new THREE.SpriteMaterial({ map: tex , // depthWrite:false, })) sprite.renderOrder = 1//防止在透明后还是出现白矩形挡住其他mesh sprite.scale.set(3,3,3) return sprite } */ } class Action extends EventDispatcher$1 { constructor() { var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(); this.icon = args.icon || ''; this.tooltip = args.tooltip; if (args.onclick !== undefined) { this.onclick = args.onclick; } } onclick(event) {} pairWith(object) {} setIcon(newIcon) { var oldIcon = this.icon; if (newIcon === oldIcon) { return; } this.icon = newIcon; this.dispatchEvent({ type: 'icon_changed', action: this, icon: newIcon, oldIcon: oldIcon }); } } ; //Potree.Actions = {}; // //Potree.Actions.ToggleAnnotationVisibility = class ToggleAnnotationVisibility extends Potree.Action { // constructor (args = {}) { // super(args); // // this.icon = Potree.resourcePath + '/icons/eye.svg'; // this.showIn = 'sidebar'; // this.tooltip = 'toggle visibility'; // } // // pairWith (annotation) { // if (annotation.visible) { // this.setIcon(Potree.resourcePath + '/icons/eye.svg'); // } else { // this.setIcon(Potree.resourcePath + '/icons/eye_crossed.svg'); // } // // annotation.addEventListener('visibility_changed', e => { // let annotation = e.annotation; // // if (annotation.visible) { // this.setIcon(Potree.resourcePath + '/icons/eye.svg'); // } else { // this.setIcon(Potree.resourcePath + '/icons/eye_crossed.svg'); // } // }); // } // // onclick (event) { // let annotation = event.annotation; // // annotation.visible = !annotation.visible; // // if (annotation.visible) { // this.setIcon(Potree.resourcePath + '/icons/eye.svg'); // } else { // this.setIcon(Potree.resourcePath + '/icons/eye_crossed.svg'); // } // } //}; class Annotation extends EventDispatcher$1 { constructor() { var _this; var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(); _this = this; this.scene = null; this._title = args.title || 'No Title'; this._description = args.description || ''; this.offset = new Vector3(); this.uuid = MathUtils.generateUUID(); if (!args.position) { this.position = null; } else if (args.position.x != null) { this.position = args.position; } else { this.position = new Vector3(...args.position); } this.cameraPosition = args.cameraPosition instanceof Array ? new Vector3().fromArray(args.cameraPosition) : args.cameraPosition; this.cameraTarget = args.cameraTarget instanceof Array ? new Vector3().fromArray(args.cameraTarget) : args.cameraTarget; this.radius = args.radius; this.view = args.view || null; this.keepOpen = false; this.descriptionVisible = false; this.showDescription = true; this.actions = args.actions || []; this.isHighlighted = false; this._visible = true; this.__visible = true; this._display = true; this._expand = false; this.collapseThreshold = [args.collapseThreshold, 100].find(e => e !== undefined); this.children = []; this.parent = null; this.boundingBox = new Box3(); var iconClose = exports.resourcePath + '/icons/close.svg'; this.domElement = $("\n\t\t\t
\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t").concat(this._description, "\n\t\t\t\t
\n\t\t\t
\n\t\t")); this.elTitlebar = this.domElement.find('.annotation-titlebar'); this.elTitle = this.elTitlebar.find('.annotation-label'); this.elTitle.append(this._title); this.elDescription = this.domElement.find('.annotation-description'); this.elDescriptionClose = this.elDescription.find('.annotation-description-close'); // this.elDescriptionContent = this.elDescription.find(".annotation-description-content"); this.clickTitle = () => { if (this.hasView()) { this.moveHere(this.scene.getActiveCamera()); } this.dispatchEvent({ type: 'click', target: this }); }; this.elTitle.click(this.clickTitle); this.actions = this.actions.map(a => { if (a instanceof Action) { return a; } else { return new Action(a); } }); for (var action of this.actions) { action.pairWith(this); } var actions = this.actions.filter(a => a.showIn === undefined || a.showIn.includes('scene')); var _loop = function _loop(_action) { var elButton = $("")); _this.elTitlebar.append(elButton); elButton.click(() => _action.onclick({ annotation: _this })); }; for (var _action of actions) { _loop(_action); } this.elDescriptionClose.hover(e => this.elDescriptionClose.css('opacity', '1'), e => this.elDescriptionClose.css('opacity', '0.5')); this.elDescriptionClose.click(e => this.setHighlighted(false)); // this.elDescriptionContent.html(this._description); this.domElement.mouseenter(e => this.setHighlighted(true)); this.domElement.mouseleave(e => this.setHighlighted(false)); this.domElement.on('touchstart', e => { this.setHighlighted(!this.isHighlighted); }); this.display = false; //this.display = true; } installHandles(viewer) { if (this.handles !== undefined) { return; } var domElement = $("\n\t\t\t
\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t
\n\t\t"); var svg = domElement.find("svg")[0]; var elLine = domElement.find("line")[0]; var elStart = domElement.find("circle")[0]; var elEnd = domElement.find("circle")[1]; var setCoordinates = (start, end) => { elStart.setAttribute("cx", "".concat(start.x)); elStart.setAttribute("cy", "".concat(start.y)); elEnd.setAttribute("cx", "".concat(end.x)); elEnd.setAttribute("cy", "".concat(end.y)); elLine.setAttribute("x1", start.x); elLine.setAttribute("y1", start.y); elLine.setAttribute("x2", end.x); elLine.setAttribute("y2", end.y); var box = svg.getBBox(); svg.setAttribute("width", "".concat(box.width)); svg.setAttribute("height", "".concat(box.height)); svg.setAttribute("viewBox", "".concat(box.x, " ").concat(box.y, " ").concat(box.width, " ").concat(box.height)); var ya = start.y - end.y; var xa = start.x - end.x; if (ya > 0) { start.y = start.y - ya; } if (xa > 0) { start.x = start.x - xa; } domElement.css("left", "".concat(start.x, "px")); domElement.css("top", "".concat(start.y, "px")); }; $(viewer.renderArea).append(domElement); var annotationStartPos = this.position.clone(); var annotationStartOffset = this.offset.clone(); $(this.domElement).draggable({ start: (event, ui) => { annotationStartPos = this.position.clone(); annotationStartOffset = this.offset.clone(); $(this.domElement).find(".annotation-titlebar").css("pointer-events", "none"); console.log($(this.domElement).find(".annotation-titlebar")); }, stop: () => { $(this.domElement).find(".annotation-titlebar").css("pointer-events", ""); }, drag: (event, ui) => { var renderAreaWidth = viewer.renderer.getSize(new Vector2()).width; //let renderAreaHeight = viewer.renderer.getSize().height; var diff = { x: ui.originalPosition.left - ui.position.left, y: ui.originalPosition.top - ui.position.top }; var nDiff = { x: -(diff.x / renderAreaWidth) * 2, y: diff.y / renderAreaWidth * 2 }; var camera = viewer.scene.getActiveCamera(); var oldScreenPos = new Vector3().addVectors(annotationStartPos, annotationStartOffset).project(camera); var newScreenPos = oldScreenPos.clone(); newScreenPos.x += nDiff.x; newScreenPos.y += nDiff.y; var newPos = newScreenPos.clone(); newPos.unproject(camera); var newOffset = new Vector3().subVectors(newPos, this.position); this.offset.copy(newOffset); } }); var updateCallback = () => { var position = this.position; var scene = viewer.scene; var renderAreaSize = viewer.renderer.getSize(new Vector2()); var renderAreaWidth = renderAreaSize.width; var renderAreaHeight = renderAreaSize.height; var start = this.position.clone(); var end = new Vector3().addVectors(this.position, this.offset); var toScreen = position => { var camera = scene.getActiveCamera(); var screenPos = new Vector3(); var worldView = new Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); var ndc = new Vector4(position.x, position.y, position.z, 1.0).applyMatrix4(worldView); // limit w to small positive value, in case position is behind the camera ndc.w = Math.max(ndc.w, 0.1); ndc.divideScalar(ndc.w); screenPos.copy(ndc); screenPos.x = renderAreaWidth * (screenPos.x + 1) / 2; screenPos.y = renderAreaHeight * (1 - (screenPos.y + 1) / 2); return screenPos; }; start = toScreen(start); end = toScreen(end); setCoordinates(start, end); }; viewer.addEventListener("update", updateCallback); this.handles = { domElement: domElement, setCoordinates: setCoordinates, updateCallback: updateCallback }; } removeHandles(viewer) { if (this.handles === undefined) { return; } //$(viewer.renderArea).remove(this.handles.domElement); this.handles.domElement.remove(); viewer.removeEventListener("update", this.handles.updateCallback); delete this.handles; } get visible() { return this._visible; } set visible(value) { if (this._visible === value) { return; } this._visible = value; //this.traverse(node => { // node.display = value; //}); this.dispatchEvent({ type: 'visibility_changed', annotation: this }); } get display() { return this._display; } set display(display) { if (this._display === display) { return; } this._display = display; if (display) { // this.domElement.fadeIn(200); this.domElement.show(); } else { // this.domElement.fadeOut(200); this.domElement.hide(); } } get expand() { return this._expand; } set expand(expand) { if (this._expand === expand) { return; } if (expand) { this.display = false; } else { this.display = true; this.traverseDescendants(node => { node.display = false; }); } this._expand = expand; } get title() { return this._title; } set title(title) { if (this._title === title) { return; } this._title = title; this.elTitle.empty(); this.elTitle.append(this._title); this.dispatchEvent({ type: "annotation_changed", annotation: this }); } get description() { return this._description; } set description(description) { if (this._description === description) { return; } this._description = description; var elDescriptionContent = this.elDescription.find(".annotation-description-content"); elDescriptionContent.empty(); elDescriptionContent.append(this._description); this.dispatchEvent({ type: "annotation_changed", annotation: this }); } add(annotation) { if (!this.children.includes(annotation)) { this.children.push(annotation); annotation.parent = this; var descendants = []; annotation.traverse(a => { descendants.push(a); }); for (var descendant of descendants) { var c = this; while (c !== null) { c.dispatchEvent({ 'type': 'annotation_added', 'annotation': descendant }); c = c.parent; } } } } level() { if (this.parent === null) { return 0; } else { return this.parent.level() + 1; } } hasChild(annotation) { return this.children.includes(annotation); } remove(annotation) { if (this.hasChild(annotation)) { annotation.removeAllChildren(); annotation.dispose(); this.children = this.children.filter(e => e !== annotation); annotation.parent = null; } } removeAllChildren() { this.children.forEach(child => { if (child.children.length > 0) { child.removeAllChildren(); } this.remove(child); }); } updateBounds() { var box = new Box3(); if (this.position) { box.expandByPoint(this.position); } for (var child of this.children) { child.updateBounds(); box.union(child.boundingBox); } this.boundingBox.copy(box); } traverse(handler) { var expand = handler(this); if (expand === undefined || expand === true) { for (var child of this.children) { child.traverse(handler); } } } traverseDescendants(handler) { for (var child of this.children) { child.traverse(handler); } } flatten() { var annotations = []; this.traverse(annotation => { annotations.push(annotation); }); return annotations; } descendants() { var annotations = []; this.traverse(annotation => { if (annotation !== this) { annotations.push(annotation); } }); return annotations; } setHighlighted(highlighted) { if (highlighted) { this.domElement.css('opacity', '0.8'); this.elTitlebar.css('box-shadow', '0 0 5px #fff'); this.domElement.css('z-index', '1000'); if (this._description) { this.descriptionVisible = true; this.elDescription.fadeIn(200); this.elDescription.css('position', 'relative'); } } else { this.domElement.css('opacity', '0.5'); this.elTitlebar.css('box-shadow', ''); this.domElement.css('z-index', '100'); this.descriptionVisible = false; this.elDescription.css('display', 'none'); } this.isHighlighted = highlighted; } hasView() { var hasPosTargetView = this.cameraTarget.x != null; hasPosTargetView = hasPosTargetView && this.cameraPosition.x != null; var hasRadiusView = this.radius !== undefined; var hasView = hasPosTargetView || hasRadiusView; return hasView; } moveHere(camera) { if (!this.hasView()) { return; } var view = this.scene.view; var animationDuration = 500; var easing = TWEEN.Easing.Quartic.Out; var endTarget; if (this.cameraTarget) { endTarget = this.cameraTarget; } else if (this.position) { endTarget = this.position; } else { endTarget = this.boundingBox.getCenter(new Vector3()); } if (this.cameraPosition) { var endPosition = this.cameraPosition; Utils.moveTo(this.scene, endPosition, endTarget); } else if (this.radius) { var direction = view.direction; var _endPosition = endTarget.clone().add(direction.multiplyScalar(-this.radius)); var startRadius = view.radius; var endRadius = this.radius; { // animate camera position var tween = new TWEEN.Tween(view.position).to(_endPosition, animationDuration); tween.easing(easing); tween.start(); } { // animate radius var t = { x: 0 }; var _tween = new TWEEN.Tween(t).to({ x: 1 }, animationDuration).onUpdate(function () { view.radius = this.x * endRadius + (1 - this.x) * startRadius; }); _tween.easing(easing); _tween.start(); } } } dispose() { if (this.domElement.parentElement) { this.domElement.parentElement.removeChild(this.domElement); } } toString() { return 'Annotation: ' + this._title; } } ; class Scene$1 extends EventDispatcher$1 { //base constructor() { super(); this.annotations = new Annotation(); this.scene = new Scene(); this.sceneBG = new Scene(); this.scenePointCloud = new Scene(); this.cameraP = new PerspectiveCamera(this.fov, 1, 0.1, 1000 * 1000); this.cameraO = new OrthographicCamera(-1, 1, 1, -1, 0.1, 1000 * 1000); this.cameraVR = new PerspectiveCamera(); this.cameraBG = new Camera(); this.cameraScreenSpace = new OrthographicCamera(-1, 1, 1, -1, 0.1, 10); this.cameraMode = CameraMode.PERSPECTIVE; this.overrideCamera = null; this.pointclouds = []; this.measurements = []; this.profiles = []; this.volumes = []; this.polygonClipVolumes = []; this.cameraAnimations = []; this.orientedImages = []; this.images360 = []; this.geopackages = []; this.fpControls = null; this.orbitControls = null; this.earthControls = null; this.geoControls = null; this.deviceControls = null; this.inputHandler = null; this.view = new ExtendView(); this.directionalLight = null; this.initialize(); } estimateHeightAt(position) { var height = null; var fromSpacing = Infinity; for (var pointcloud of this.pointclouds) { if (pointcloud.root.geometryNode === undefined) { continue; } var pHeight = null; var pFromSpacing = Infinity; var lpos = position.clone().sub(pointcloud.position); lpos.z = 0; var ray = new Ray(lpos, new Vector3(0, 0, 1)); var stack = [pointcloud.root]; while (stack.length > 0) { var node = stack.pop(); var box = node.getBoundingBox(); var inside = ray.intersectBox(box); if (!inside) { continue; } var h = node.geometryNode.mean.z + pointcloud.position.z + node.geometryNode.boundingBox.min.z; if (node.geometryNode.spacing <= pFromSpacing) { pHeight = h; pFromSpacing = node.geometryNode.spacing; } for (var index of Object.keys(node.children)) { var child = node.children[index]; if (child.geometryNode) { stack.push(node.children[index]); } } } if (height === null || pFromSpacing < fromSpacing) { height = pHeight; fromSpacing = pFromSpacing; } } return height; } getBoundingBox() { var pointclouds = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.pointclouds; var box = new Box3(); this.scenePointCloud.updateMatrixWorld(true); this.referenceFrame.updateMatrixWorld(true); for (var pointcloud of pointclouds) { pointcloud.updateMatrixWorld(true); var pointcloudBox = pointcloud.pcoGeometry.tightBoundingBox ? pointcloud.pcoGeometry.tightBoundingBox : pointcloud.boundingBox; var boxWorld = Utils.computeTransformedBoundingBox(pointcloudBox, pointcloud.matrixWorld); box.union(boxWorld); } return box; } addPointCloud(pointcloud) { this.pointclouds.push(pointcloud); this.scenePointCloud.add(pointcloud); this.dispatchEvent({ type: 'pointcloud_added', pointcloud: pointcloud }); } addVolume(volume) { this.volumes.push(volume); this.dispatchEvent({ 'type': 'volume_added', 'scene': this, 'volume': volume }); viewer.dispatchEvent('content_changed'); } addOrientedImages(images) { this.orientedImages.push(images); this.scene.add(images.node); this.dispatchEvent({ 'type': 'oriented_images_added', 'scene': this, 'images': images }); } removeOrientedImages(images) { var index = this.orientedImages.indexOf(images); if (index > -1) { this.orientedImages.splice(index, 1); this.dispatchEvent({ 'type': 'oriented_images_removed', 'scene': this, 'images': images }); } } add360Images(images) { this.images360.push(images); this.scene.add(images.node); this.dispatchEvent({ 'type': '360_images_added', 'scene': this, 'images': images }); } remove360Images(images) { var index = this.images360.indexOf(images); if (index > -1) { this.images360.splice(index, 1); this.dispatchEvent({ 'type': '360_images_removed', 'scene': this, 'images': images }); } } addGeopackage(geopackage) { this.geopackages.push(geopackage); this.scene.add(geopackage.node); this.dispatchEvent({ 'type': 'geopackage_added', 'scene': this, 'geopackage': geopackage }); } removeGeopackage(geopackage) { var index = this.geopackages.indexOf(geopackage); if (index > -1) { this.geopackages.splice(index, 1); this.dispatchEvent({ 'type': 'geopackage_removed', 'scene': this, 'geopackage': geopackage }); } } removeVolume(volume) { var index = this.volumes.indexOf(volume); if (index > -1) { this.volumes.splice(index, 1); this.dispatchEvent({ 'type': 'volume_removed', 'scene': this, 'volume': volume }); } viewer.dispatchEvent('content_changed'); } addCameraAnimation(animation) { this.cameraAnimations.push(animation); this.dispatchEvent({ 'type': 'camera_animation_added', 'scene': this, 'animation': animation }); } removeCameraAnimation(animation) { var index = this.cameraAnimations.indexOf(volume); if (index > -1) { this.cameraAnimations.splice(index, 1); this.dispatchEvent({ 'type': 'camera_animation_removed', 'scene': this, 'animation': animation }); } } addPolygonClipVolume(volume) { this.polygonClipVolumes.push(volume); this.dispatchEvent({ "type": "polygon_clip_volume_added", "scene": this, "volume": volume }); } removePolygonClipVolume(volume) { var index = this.polygonClipVolumes.indexOf(volume); if (index > -1) { this.polygonClipVolumes.splice(index, 1); this.dispatchEvent({ "type": "polygon_clip_volume_removed", "scene": this, "volume": volume }); } } addMeasurement(measurement) { measurement.lengthUnit = this.lengthUnit; measurement.lengthUnitDisplay = this.lengthUnitDisplay; this.measurements.push(measurement); this.dispatchEvent({ 'type': 'measurement_added', 'scene': this, 'measurement': measurement }); viewer.dispatchEvent('content_changed'); } removeMeasurement(measurement) { var index = this.measurements.indexOf(measurement); if (index > -1) { this.measurements.splice(index, 1); this.dispatchEvent({ 'type': 'measurement_removed', 'scene': this, 'measurement': measurement }); viewer.dispatchEvent('content_changed'); } } addProfile(profile) { this.profiles.push(profile); this.dispatchEvent({ 'type': 'profile_added', 'scene': this, 'profile': profile }); } removeProfile(profile) { var index = this.profiles.indexOf(profile); if (index > -1) { this.profiles.splice(index, 1); this.dispatchEvent({ 'type': 'profile_removed', 'scene': this, 'profile': profile }); } } removeAllMeasurements() { while (this.measurements.length > 0) { this.removeMeasurement(this.measurements[0]); } while (this.profiles.length > 0) { this.removeProfile(this.profiles[0]); } while (this.volumes.length > 0) { this.removeVolume(this.volumes[0]); } } removeAllClipVolumes() { var clipVolumes = this.volumes.filter(volume => volume.clip === true); for (var clipVolume of clipVolumes) { this.removeVolume(clipVolume); } while (this.polygonClipVolumes.length > 0) { this.removePolygonClipVolume(this.polygonClipVolumes[0]); } } getActiveCamera() { if (this.overrideCamera) { return this.overrideCamera; } if (this.cameraMode === CameraMode.PERSPECTIVE) { return this.cameraP; } else if (this.cameraMode === CameraMode.ORTHOGRAPHIC) { return this.cameraO; } else if (this.cameraMode === CameraMode.VR) { return this.cameraVR; } return null; } initialize() { this.referenceFrame = new Object3D(); this.referenceFrame.matrixAutoUpdate = false; this.scenePointCloud.add(this.referenceFrame); this.cameraP.up.set(0, 0, 1); this.cameraP.position.set(1000, 1000, 1000); this.cameraO.up.set(0, 0, 1); this.cameraO.position.set(1000, 1000, 1000); //this.camera.rotation.y = -Math.PI / 4; //this.camera.rotation.x = -Math.PI / 6; this.cameraScreenSpace.lookAt(new Vector3(0, 0, 0), new Vector3(0, 0, -1), new Vector3(0, 1, 0)); this.directionalLight = new DirectionalLight(0xffffff, 0.5); this.directionalLight.position.set(10, 10, 10); this.directionalLight.lookAt(new Vector3(0, 0, 0)); this.scenePointCloud.add(this.directionalLight); var light = new AmbientLight(0x555555); // soft white light this.scenePointCloud.add(light); { // background var texture = Utils.createBackgroundTexture(512, 512); texture.minFilter = texture.magFilter = NearestFilter; texture.minFilter = texture.magFilter = LinearFilter; var bg = new Mesh(new PlaneBufferGeometry(2, 2, 1), new MeshBasicMaterial({ map: texture })); bg.material.depthTest = false; bg.material.depthWrite = false; this.sceneBG.add(bg); } // { // lights // { // let light = new THREE.DirectionalLight(0xffffff); // light.position.set(10, 10, 1); // light.target.position.set(0, 0, 0); // this.scene.add(light); // } // { // let light = new THREE.DirectionalLight(0xffffff); // light.position.set(-10, 10, 1); // light.target.position.set(0, 0, 0); // this.scene.add(light); // } // { // let light = new THREE.DirectionalLight(0xffffff); // light.position.set(0, -10, 20); // light.target.position.set(0, 0, 0); // this.scene.add(light); // } // } } addAnnotation(position) { var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (position instanceof Array) { args.position = new Vector3().fromArray(position); } else if (position.x != null) { args.position = position; } var annotation = new Annotation(args); this.annotations.add(annotation); return annotation; } getAnnotations() { return this.annotations; } removeAnnotation(annotationToRemove) { this.annotations.remove(annotationToRemove); } } ; class ExtendScene extends Scene$1 { constructor() { super(); delete this.sceneBG; this.cameraP = new PerspectiveCamera(this.fov, 1, Potree.config.view.near, Potree.config.view.near); this.cameraO = new OrthographicCamera(-1, 1, 1, -1, Potree.config.view.near, Potree.settings.cameraFar); this.cameraP.limitFar = true; //add this.initializeExtend(); //------------- this.axisArrow = new Axis(); this.scene.add(this.axisArrow); if (!Potree.settings.isDebug && !Potree.settings.showAxis) this.axisArrow.visible = false; Potree.Utils.setObjectLayers(this.axisArrow, 'bothMapAndScene'); this.tags = new Object3D(); this.scene.add(this.tags); } estimateHeightAt(position) { var height = null; var fromSpacing = Infinity; for (var pointcloud of this.pointclouds) { if (pointcloud.root.geometryNode === undefined) { continue; } var pHeight = null; var pFromSpacing = Infinity; var lpos = position.clone().sub(pointcloud.position); lpos.z = 0; var ray = new Ray(lpos, new Vector3(0, 0, 1)); var stack = [pointcloud.root]; while (stack.length > 0) { var node = stack.pop(); var box = node.getBoundingBox(); var inside = ray.intersectBox(box); if (!inside) { continue; } var h = node.geometryNode.mean.z + pointcloud.position.z + node.geometryNode.boundingBox.min.z; if (node.geometryNode.spacing <= pFromSpacing) { pHeight = h; pFromSpacing = node.geometryNode.spacing; } for (var index of Object.keys(node.children)) { var child = node.children[index]; if (child.geometryNode) { stack.push(node.children[index]); } } } if (height === null || pFromSpacing < fromSpacing) { height = pHeight; fromSpacing = pFromSpacing; } } return height; } //add: removePointCloud(pointcloud) { var index = this.pointclouds.indexOf(pointcloud); if (index == -1) return; this.pointclouds.splice(index, 1); this.scenePointCloud.remove(pointcloud); pointcloud.panos.forEach(pano => { pano.dispose(); }); } removeCameraAnimation(animation) { var index = this.cameraAnimations.indexOf(animation); if (index > -1) { this.cameraAnimations.splice(index, 1); this.dispatchEvent({ 'type': 'camera_animation_removed', 'scene': this, 'animation': animation }); } } getActiveCamera() { return viewer.mainViewport.camera; } initialize() {//不用旧的 因为还没创建完变量 } initializeExtend() { //add 新的initialize this.referenceFrame = new Object3D(); this.referenceFrame.matrixAutoUpdate = false; this.scenePointCloud.add(this.referenceFrame); if (window.axisYup) {} else { this.cameraP.up.set(0, 0, 1); this.cameraO.up.set(0, 0, 1); } this.cameraP.position.set(1000, 1000, 1000); this.cameraO.position.set(1000, 1000, 1000); //this.camera.rotation.y = -Math.PI / 4; //this.camera.rotation.x = -Math.PI / 6; this.cameraScreenSpace.lookAt(new Vector3(0, 0, 0), new Vector3(0, 0, -1), new Vector3(0, 1, 0)); this.directionalLight = new DirectionalLight(0xffffff, 0.5); this.directionalLight.position.set(10, 10, 10); this.directionalLight.lookAt(new Vector3(0, 0, 0)); this.scenePointCloud.add(this.directionalLight); var light = new AmbientLight(0x555555); // soft white light this.scenePointCloud.add(light); //add:------给空间模型的box 或其他obj------ var light2 = new AmbientLight(16777215, 0.5); Potree.Utils.setObjectLayers(light2, 'light' /* 'bothMapAndScene' */); this.scene.add(light2); var light3 = new DirectionalLight(16777215, 0.7); light3.position.set(10, 10, 10); light3.lookAt(new Vector3(0, 0, 0)); Potree.Utils.setObjectLayers(light3, 'light'); this.scene.add(light3); var light4 = new DirectionalLight(16777215, 0.3); //补光 light4.position.set(-10, -5, -7); light4.lookAt(new Vector3(0, 0, 0)); Potree.Utils.setObjectLayers(light4, 'light'); this.scene.add(light4); //-------------------------------------------- { // background var texture = Utils.createBackgroundTexture(512, 512); texture.minFilter = texture.magFilter = NearestFilter; texture.minFilter = texture.magFilter = LinearFilter; var bg = new Mesh(new PlaneBufferGeometry(2, 2, 1), new MeshBasicMaterial({ map: texture })); bg.material.depthTest = false; bg.material.depthWrite = false; bg.name = 'bg'; //this.sceneBG.add(bg); this.scene.add(bg); bg.layers.set(Potree.config.renderLayers.bg); } { // background color var bg2 = new Mesh(new PlaneBufferGeometry(2, 2, 1), new MeshBasicMaterial({ transparent: true })); bg2.material.depthTest = false; bg2.material.depthWrite = false; bg2.name = 'bg2'; this.scene.add(bg2); bg2.layers.set(Potree.config.renderLayers.bg2); this.bg2 = bg2; } // { // lights // { // let light = new THREE.DirectionalLight(0xffffff); // light.position.set(10, 10, 1); // light.target.position.set(0, 0, 0); // this.scene.add(light); // } // { // let light = new THREE.DirectionalLight(0xffffff); // light.position.set(-10, 10, 1); // light.target.position.set(0, 0, 0); // this.scene.add(light); // } // { // let light = new THREE.DirectionalLight(0xffffff); // light.position.set(0, -10, 20); // light.target.position.set(0, 0, 0); // this.scene.add(light); // } // } } } ; KeyCodes.BACKSPACE = 8; //注意,这时候Potree.js中export的内容还不在Potree变量中 var texLoader$1 = new TextureLoader(); texLoader$1.crossOrigin = "anonymous"; { //defines: Potree.defines = {}; Potree.defines.Buttons = { // MouseEvent.buttons //buttons,设置按下了鼠标哪些键,是一个3个比特位的二进制值,默认为0。1表示按下主键(通常是左键),2表示按下次要键(通常是右键),4表示按下辅助键(通常是中间的键)。 NONE: 0, //add LEFT: 0b0001, RIGHT: 0b0010, MIDDLE: 0b0100 }; /* 如果访问的是button, 用THREE.MOUSE来判断: button,设置按下了哪一个鼠标按键,默认为0。-1表示没有按键,0表示按下主键(通常是左键),1表示按下辅助键(通常是中间的键),2表示按下次要键(通常是右键) */ Potree.browser = browser; /////////// add ////////////////////////////////// Potree.defines.GLCubeFaces = { GL_TEXTURE_CUBE_MAP_POSITIVE_X: 0, GL_TEXTURE_CUBE_MAP_NEGATIVE_X: 1, GL_TEXTURE_CUBE_MAP_POSITIVE_Y: 2, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: 3, GL_TEXTURE_CUBE_MAP_POSITIVE_Z: 4, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: 5 }; Potree.defines.PanoSizeClass = { BASE: 1, STANDARD: 2, HIGH: 3, ULTRAHIGH: 4 }; Potree.defines.PanoRendererEvents = { PanoRenderComplete: "panorama.render.complete", TileRenderFailure: "panorama.tile.render.failed", TileRenderSuccess: "panorama.tile.render.success", TileUploadAttempted: "panorama.tile.upload.attempted", UploadAttemptedForAllTiles: "panorama.upload.attempted.all.tiles", ZoomLevelRenderStarted: "panorama.zoom.render.started" }; Potree.defines.SceneRendererEvents = { ContextCreated: "scene-renderer-context-created", AfterRender: "after-render", MemoryUsageUpdated: "scene-renderer-memory-usage-updated" }; Potree.defines.TileDownloaderEvents = { TileDownloadSuccess: "tiledownloader.download.success", TileDownloadFailure: "tiledownloader.download.failure", PanoDownloadComplete: "tiledownloader.pano.download.complete" }; Potree.defines.Vectors = { UP: new Vector3(0, 1, 0), DOWN: new Vector3(0, -1, 0), LEFT: new Vector3(-1, 0, 0), RIGHT: new Vector3(1, 0, 0), FORWARD: new Vector3(0, 0, -1), BACK: new Vector3(0, 0, 1) }; /* var Vectors2 = {} for(var i in Vectors){ Vectors2[i] = math.convertVector.YupToZup(Vectors[i]) } */ Potree.defines.DownloadStatus = Object.freeze({ None: 0, Queued: 1, ForceQueued: 2, Downloading: 3, Downloaded: 4, DownloadFailed: 5 }); Potree.defines.ModelManagerEvents = { ModelAdded: "model-added", ActiveModelChanged: "active-model-changed" }; Potree.defines.PanoramaEvents = { Enter: 'panorama.enter', Exit: 'panorama.exit', LoadComplete: "panorama.load.complete", LoadFailed: "panorama.load.failed", TileLoaded: "panorama.tile.loaded", VideoRendered: "panorama.video.rendered" }; ClipTask.SHOW_INSIDE_Big = 4; } { //Features var gl_; Features.EXT_DEPTH = { isSupported: function isSupported(gl) { gl = gl || gl_; gl_ = gl; if (browser.detectIOS()) { var { major, minor, patch } = browser.iosVersion(); //console.warn('iosVersion',major,minor,patch) if (major == 15 && minor == 4 && patch == 1) { console.warn('检测到是ios15.4.1, 关闭EXT_frag_depth'); //该版本ext_depth有问题,导致clear错乱。没有解决办法先关闭。 return false; } } return typeof WebGL2RenderingContext != 'undefined' && gl instanceof WebGL2RenderingContext || gl.getExtension('EXT_frag_depth'); //shader中的GL_EXT_frag_depth需要判断一下detectIOS吗。。 } }; } Utils.loadSkybox = function (path, oldSky, callback) { var camera, scene, parent, cameraOrtho; if (!oldSky) { parent = new Object3D("skybox_root"); camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 100000); cameraOrtho = new OrthographicCamera(-1, 1, 1, -1, Potree.config.view.near, Potree.settings.cameraFar); if (!window.axisYup) camera.up.set(0, 0, 1); //add scene = new Scene(); var skyboxBgWidth = Potree.config.skyboxBgWidth; var skyGeometry = new BoxBufferGeometry(skyboxBgWidth, skyboxBgWidth, skyboxBgWidth); var skybox = new Mesh(skyGeometry, new ShaderMaterial({ vertexShader: Shaders['skybox.vs'], fragmentShader: Shaders['skybox.fs'], side: BackSide, uniforms: { tDiffuse: { type: "t", value: null }, matrix: { type: "m4", value: new Matrix4() } }, depthTest: false, depthWrite: false })); scene.add(skybox); scene.traverse(n => n.frustumCulled = false); // z up //scene.rotation.x = Math.PI / 2; parent.children.push(camera); camera.parent = parent; } else { camera = oldSky.camera, scene = oldSky.scene; parent = oldSky.parent; cameraOrtho = oldSky.cameraOrtho; } var texture = texLoader$1.load(path, () => { console.log('loadSkybox成功', path); texture.wrapS = RepeatWrapping; texture.flipY = false; texture.magFilter = LinearFilter; texture.minFilter = LinearFilter; scene.children[0].material.uniforms.tDiffuse.value = texture; callback && callback(); viewer.dispatchEvent('content_changed'); }, null, e => { //error console.error('loadSkybox失败', path); }); return { camera, scene, parent, cameraOrtho }; }; Utils.getMousePointCloudIntersection = function (viewport, mouse, pointer, camera, viewer, pointclouds) { var pickParams = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : {}; //getIntersectByDepthTex /* let result = viewer.edlRenderer.depthTexSampler.sample(viewport, mouse)//add if(result != 'unsupport')return result */ if (!pointclouds || pointclouds.filter(e => Potree.Utils.getObjVisiByReason(e, 'datasetSelection')).length == 0) return; //console.log('getMousePointCloudIntersection') var renderer = viewer.renderer; if (viewport) { //转换到类似整个画面时 /*let mouseInViewport = Utils.convertNDCToScreenPosition(pointer, null, viewport.resolution.x, viewport.resolution.y) pickParams.x = mouseInViewport.x //mouse.x / viewport.width; pickParams.y = mouseInViewport.y //renderer.domElement.clientHeight - mouse.y / viewport.height; */ pickParams.x = mouse.x; pickParams.y = viewport.resolution.y - mouse.y; } else { pickParams.x = mouse.x; pickParams.y = renderer.domElement.clientHeight - mouse.y; } //console.log('getMousePointCloudIntersection') /* if(!raycaster){ raycaster = new THREE.Raycaster(); raycaster.setFromCamera(pointer, camera); } */ var raycaster = new Raycaster(); raycaster.setFromCamera(pointer, camera); var ray = raycaster.ray; var selectedPointcloud = null; var closestDistance = Infinity; var closestIntersection = null; var closestPoint = null; //-----------add-------------------- var old_clipBoxes_in = new Map(); var old_clipBoxes_out = new Map(); var old_bigClipInBox = new Map(); var old_highlightBoxes = new Map(); var old_visibleNodes = new Map(); //bigClipInBox 最好也写下 var density; var sizeType; var size = new Map(); var visiMap = new Map(); var needsUpdate = false; if (pickParams.measuring || Potree.settings.displayMode == 'showPanos') { //测量或无深度图时的全景模式提高精准度. (全景模式有深度图时不会执行到这) density = Potree.settings.pointDensity; Potree.settings.pointDensity = 'magnifier'; //加载最高level pointclouds.forEach(e => { //因为全景模式的pointSizeType是fixed所以要还原下 visiMap.set(e, e.visible); e.visible = Potree.Utils.getObjVisiByReason(e, 'datasetSelection'); //先将隐藏的点云显示 if (!e.visible) return; size.set(e, e.temp.pointSize); sizeType = e.material.pointSizeType; e.material.pointSizeType = Potree.config.material.pointSizeType; //e.changePointSize(Potree.config.material.realPointSize*2, true)//更改点云大小到能铺满为止,否则容易识别不到 }); needsUpdate = true; } else { if (viewer.viewports.filter(e => !e.noPointcloud && e.active).length > 1 || pickParams.cameraChanged) { //在pick时相机和渲染时不一样的话 viewport.beforeRender && viewport.beforeRender(); needsUpdate = true; //不updatePointClouds的话hover久了会不准 因node是错的 //但依旧需要camera真的移动到那个位置才能加载出点云 } } if (!pickParams.pickClipped) { // 无视clipBoxes for (var pointcloud of pointclouds) { old_clipBoxes_in.set(pointcloud, pointcloud.clipBoxes_in); old_clipBoxes_out.set(pointcloud, pointcloud.clipBoxes_out); old_bigClipInBox.set(pointcloud, pointcloud.bigClipInBox); old_highlightBoxes.set(pointcloud, pointcloud.highlightBoxes); pointcloud.material.setClipBoxes(null, [], [], []); } needsUpdate = true; } if (needsUpdate) { for (var _pointcloud of pointclouds) { old_visibleNodes.set(_pointcloud, _pointcloud.visibleNodes); } if (window.notViewOffset) { Potree.updatePointClouds(pointclouds, camera, viewport.resolution); } else { //尽量减少点云加载的范围,集中在pick的空间(这部分以外还是会加载一些散点的) var viewWidth = 80; //viewer.magnifier ? viewer.magnifier.viewport.resolution.x : 200 var camera_ = camera.clone(); camera_.setViewOffset(viewport.resolution.x, viewport.resolution.y, pickParams.x - viewWidth / 2, viewport.resolution.y - pickParams.y - viewWidth / 2, viewWidth, viewWidth); //注意offsetY是从上到下,和一般的不同 Potree.updatePointClouds(pointclouds, camera_, viewport.resolution); } } //------------------------------------------------ var allPointclouds = []; for (var _pointcloud2 of pointclouds) { var point = _pointcloud2.pick(viewer, viewport, camera, ray, pickParams); if (!point) { continue; } allPointclouds.push(_pointcloud2); var distance = camera.position.distanceTo(point.position); if (distance < closestDistance) { closestDistance = distance; selectedPointcloud = _pointcloud2; closestIntersection = point.position; closestPoint = point; } } //恢复 if (pickParams.measuring || Potree.settings.displayMode == 'showPanos') { Potree.settings.pointDensity = density; pointclouds.forEach(e => { if (e.visible) { e.material.pointSizeType = sizeType; //e.changePointSize(size.get(e)) } e.visible = visiMap.get(e); }); } else { /* if(viewer.viewports.filter(e=>!e.noPointcloud).length>1){ viewport.afterRender && viewport.afterRender() } */ } if (!pickParams.pickClipped) { //add for (var _pointcloud3 of pointclouds) { _pointcloud3.material.setClipBoxes(old_bigClipInBox.get(_pointcloud3), old_clipBoxes_in.get(_pointcloud3), old_clipBoxes_out.get(_pointcloud3), old_highlightBoxes.get(_pointcloud3)); } } if (needsUpdate) { for (var _pointcloud4 of pointclouds) { //不恢复的话(尤其cameraChanged时),在下次render前,再次pick可能是错的。表现为多数据集刚开始reticule消失了,直到ifPointBlockedByIntersect停止 _pointcloud4.visibleNodes = old_visibleNodes.get(_pointcloud4); } } if (selectedPointcloud) { return { location: closestIntersection, distance: closestDistance, pointcloud: selectedPointcloud, point: closestPoint, pointclouds: allPointclouds, //add normal: closestPoint.normal && new Vector3().fromArray(closestPoint.normal).applyMatrix4(selectedPointcloud.rotateMatrix) //add }; } else { return null; } }; Utils.pixelsArrayToDataUrl = function (pixels, width, height) { var compressRatio = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0.7; var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; var context = canvas.getContext('2d'); pixels = new pixels.constructor(pixels); /* for (let i = 0; i < pixels.length; i++) { pixels[i * 4 + 3] = 255; } */ // flip vertically var bytesPerLine = width * 4; for (var i = 0; i < parseInt(height / 2); i++) { var j = height - i - 1; var lineI = pixels.slice(i * bytesPerLine, i * bytesPerLine + bytesPerLine); var lineJ = pixels.slice(j * bytesPerLine, j * bytesPerLine + bytesPerLine); pixels.set(lineJ, i * bytesPerLine); pixels.set(lineI, j * bytesPerLine); } var imageData = context.createImageData(width, height); imageData.data.set(pixels); context.putImageData(imageData, 0, 0); var dataURL = canvas.toDataURL(compressRatio); return dataURL; }; Utils.renderTargetToDataUrl = function (renderTarget, width, height, renderer) { var compressRatio = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0.7; var pixelCount = width * height; var buffer = new Uint8Array(4 * pixelCount); renderer.readRenderTargetPixels(renderTarget, 0, 0, width, height, buffer); var dataUrl = Utils.pixelsArrayToDataUrl(buffer, width, height, compressRatio); return dataUrl; }; Utils.mouseToRay = function (pointer, camera) { var vector = new Vector3(pointer.x, pointer.y, 1); var origin = new Vector3(pointer.x, pointer.y, -1); //不能用camera.position,在orbitCamera时不准 vector.unproject(camera); origin.unproject(camera); var direction = new Vector3().subVectors(vector, origin).normalize(); var ray = new Ray(origin, direction); return ray; }; Utils.getPos2d = function (point, viewport, dom, renderer) { //获取一个三维坐标对应屏幕中的二维坐标 var pos; if (math.closeTo(viewport.camera.position, point, 1e-5)) { //和相机位置重合时显示会四处飘,看是要改成一直显示中间还是隐藏? pos = new Vector3(0, 0, 1.5); //1.5是为了不可见 } else { pos = point.clone().project(viewport.camera); //比之前hotspot的计算方式写得简单 project用于3转2(求法同shader); unproject用于2转3 :new r.Vector3(e.x, e.y, -1).unproject(this.camera); } var size = renderer && renderer.getSize(new Vector2()); //如果是渲染到renderTarget上,resolution和dom的大小不一致。如果输出的结果给前端2d用,就使用clinetWidth,如果自己场景用,用renderer.size var w = renderer ? size.x : dom.clientWidth; var h = renderer ? size.y : dom.clientHeight; var x, y, left, top; x = (pos.x + 1) / 2 * w * viewport.width; y = (1 - (pos.y + 1) / 2) * h * viewport.height; left = viewport.left * w; top = (1 - viewport.bottom - viewport.height) * h; var inSight = pos.x <= 1 && pos.x >= -1 //是否在屏幕中 && pos.x <= 1 && pos.y >= -1; return { pos: new Vector2(left + x, top + y), // 屏幕像素坐标 vector: pos, //(范围 -1 ~ 1) trueSide: pos.z < 1, //trueSide为false时,即使在屏幕范围内可见,也是反方向的另一个不可以被渲染的点 参见Tag.update inSight: inSight, //在屏幕范围内可见, posInViewport: new Vector2(x, y) }; }; Utils.screenPass = new function () { this.screenScene = new Scene(); this.screenQuad = new Mesh(new PlaneBufferGeometry(2, 2, 1)); this.screenQuad.material.depthTest = true; this.screenQuad.material.depthWrite = true; this.screenQuad.material.transparent = true; this.screenScene.add(this.screenQuad); this.camera = new Camera(); this.render = function (renderer, material, target, composer) { this.screenQuad.material = material; if (typeof target === 'undefined') { (composer || renderer).render(this.screenScene, this.camera); } else { var oldTarget = renderer.getRenderTarget(); renderer.setRenderTarget(target); //renderer.clear(); //有时候不能clear,如renderBG后再 (composer || renderer).render(this.screenScene, this.camera); renderer.setRenderTarget(oldTarget); } }; }(); //add Utils.computePointcloudsBound = function (pointclouds) { var boundingBox = new Box3(); pointclouds.forEach(pointcloud => { pointcloud.updateBound(); boundingBox.union(pointcloud.bound2); }); var boundSize = boundingBox.getSize(new Vector3()); var center = boundingBox.getCenter(new Vector3()); return { boundSize, center, boundingBox }; }; Utils.convertScreenPositionToNDC = function (pointer, mouse, width, height) { return pointer = pointer || new Vector2(), pointer.x = mouse.x / width * 2 - 1, pointer.y = 2 * -(mouse.y / height) + 1, pointer; }; Utils.convertNDCToScreenPosition = function (pointer, mouse, width, height) { return mouse = mouse || new Vector2(), mouse.x = Math.round((pointer.x + 1) / 2 * width), mouse.y = Math.round(-(pointer.y - 1) / 2 * height), mouse; }; Utils.getOrthoCameraMoveVec = function (pointerDelta, camera) { //获取当camera为Ortho型时 屏幕点1 到 屏幕点2 的三维距离 var cameraViewWidth = camera.right / camera.zoom; var cameraViewHeight = camera.top / camera.zoom; var moveVec = new Vector3(); moveVec.set(pointerDelta.x * cameraViewWidth, pointerDelta.y * cameraViewHeight, 0).applyQuaternion(camera.quaternion); return moveVec; }; Utils.VectorFactory = { fromArray: function fromArray(t) { if (t) { if (t.length < 2 || t.length > 3) console.error("Wrong number of ordinates for a point!"); return 3 === t.length ? new Vector3().fromArray(t) : new Vector2().fromArray(t); } }, fromArray3: function fromArray3(t) { if (t) { if (3 !== t.length) console.error("Wrong number of ordinates for a point!"); return new Vector3().fromArray(t); } }, fromArray2: function fromArray2(t) { if (t) { if (2 !== t.length) console.error("Wrong number of ordinates for a point!"); return new Vector2().fromArray(t); } }, toString: function toString(t) { return t.x.toFixed(8) + "," + t.y.toFixed(8) + "," + t.z.toFixed(3); } }; Utils.QuaternionFactory = { rot90: new Quaternion().setFromAxisAngle(new Vector3(0, 0, 1), MathUtils.degToRad(-90)), fromArray: function fromArray(t) { if (t) { if (4 !== t.length) console.error("Wrong number of ordinates for a quaternion!"); return new Quaternion(t[1], t[2], t[3], t[0]).multiply(this.rot90); } }, toArray: function toArray(t) { if (t) { var e = t.clone().multiply(a).toArray(); return [e[3], e[0], e[1], e[2]]; } }, fromLonLat: function fromLonLat(t) { if (t) return new Quaternion().setFromEuler(new Euler(t.lon, t.lat, 0)); }, toLonLat: function toLonLat(t) { if (t) { var e = new Euler().setFromQuaternion(t); return { lon: e.x, lat: e.y }; } } }; Utils.datasetPosTransform = function () { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var pointcloud = o.pointcloud || viewer.scene.pointclouds.find(e => e.dataset_id == o.datasetId); var tranMatrix; if (pointcloud) { if (Potree.settings.editType == 'merge') { tranMatrix = o.fromDataset ? pointcloud.matrixWorld : new Matrix4().copy(pointcloud.matrixWorld).invert(); } else { tranMatrix = o.fromDataset ? pointcloud.transformMatrix : pointcloud.transformInvMatrix; } } else { if (Potree.settings.intersectOnObjs) { var object = o.object || viewer.objs.children.find(e => e.dataset_id == o.datasetId); if (object) { tranMatrix = o.fromDataset ? object.matrixWorld : new Matrix4().copy(object.matrixWorld).invert(); } } } if (tranMatrix) { return new Vector3().copy(o.position).applyMatrix4(tranMatrix); } else { if (o.datasetId != void 0) { console.error("datasetPosTransform\u627E\u4E0D\u5230datasetId\u4E3A".concat(o.datasetId, "\u7684\u6570\u636E\u96C6\u6216\u6A21\u578B\uFF0C\u8BF7\u68C0\u67E5\u6570\u636E\uFF0C \u6A21\u578B\u672A\u521B\u5EFA\u6216\u5220\u9664")); //很可能是旧的热点,需要删除 } } }; Utils.datasetRotTransform = function () { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var pointcloud = o.pointcloud || viewer.scene.pointclouds.find(e => e.dataset_id == o.datasetId); if (pointcloud) { var matrix, newMatrix, result; if (o.rotation) { matrix = new Matrix4().makeRotationFromEuler(o.rotation); } else if (o.quaternion) { matrix = new Matrix4().makeRotationFromQuaternion(o.quaternion); } else if (o.matrix) { matrix = o.matrix.clone(); } else { return; } var rotateMatrix = o.fromDataset ? pointcloud.rotateMatrix : pointcloud.rotateInvMatrix; newMatrix = new Matrix4().multiplyMatrices(rotateMatrix, matrix); if (o.getRotation) { result = new Euler().setFromRotationMatrix(newMatrix); } else if (o.getQuaternion) { result = new Quaternion().setFromRotationMatrix(newMatrix); } else if (o.getMatrix) { result = newMatrix; } return result; } }; Utils.isInsideFrustum = function (bounding, camera) { // bounding是否在视野范围内有可见部分(视野就是一个锥状box) var frustumMatrix = new Matrix4(); frustumMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); var frustum = new Frustum(); frustum.setFromProjectionMatrix(frustumMatrix); if (bounding instanceof Sphere) { return frustum.intersectsSphere(bounding); } else { return frustum.intersectsBox(bounding); } }; Utils.isIntersectBox = function (object, boxMatrix) { //object是否有在box中的部分。 object可以是点或者bounding, box原为1*1*1,但可能形变 //let frustum = new THREE.Frustum(); //frustum.setFromProjectionMatrix(boxMatrixInverse) --错 var px = new Vector3(+0.5, 0, 0).applyMatrix4(boxMatrix); var nx = new Vector3(-0.5, 0, 0).applyMatrix4(boxMatrix); var py = new Vector3(0, +0.5, 0).applyMatrix4(boxMatrix); var ny = new Vector3(0, -0.5, 0).applyMatrix4(boxMatrix); var pz = new Vector3(0, 0, +0.5).applyMatrix4(boxMatrix); var nz = new Vector3(0, 0, -0.5).applyMatrix4(boxMatrix); var pxN = new Vector3().subVectors(nx, px).normalize(); var nxN = pxN.clone().multiplyScalar(-1); var pyN = new Vector3().subVectors(ny, py).normalize(); var nyN = pyN.clone().multiplyScalar(-1); var pzN = new Vector3().subVectors(nz, pz).normalize(); var nzN = pzN.clone().multiplyScalar(-1); var pxPlane = new Plane().setFromNormalAndCoplanarPoint(pxN, px); var nxPlane = new Plane().setFromNormalAndCoplanarPoint(nxN, nx); var pyPlane = new Plane().setFromNormalAndCoplanarPoint(pyN, py); var nyPlane = new Plane().setFromNormalAndCoplanarPoint(nyN, ny); var pzPlane = new Plane().setFromNormalAndCoplanarPoint(pzN, pz); var nzPlane = new Plane().setFromNormalAndCoplanarPoint(nzN, nz); var frustum = new Frustum(pxPlane, nxPlane, pyPlane, nyPlane, pzPlane, nzPlane); if (object instanceof Box3) { var boxBound = new Box3(new Vector3(-0.5, -0.5, -0.5), new Vector3(0.5, 0.5, 0.5)).applyMatrix4(boxMatrix); //large boundingbox if (!object.intersectsBox(boxBound)) return; return frustum.intersectsBox(object); //根据该函数, 若存在某个plane在box上的对应点都在plane背面,则不相交. 可得知在box构成的frustum倾斜时不准确,不相交也判断为相交,甚至不如bound相交准确。所以前面加步骤排除下,但仍不完全准确。(可在裁剪中将box放置到数据集上方旋转下校验) } else if (object instanceof Array) { //点合集, 只能粗略计算下 var sphere = new Sphere(); sphere.setFromPoints(object); return this.isIntersectBox(sphere, boxMatrix); } else if (object instanceof Sphere) { return frustum.intersectsSphere(object); } else if (object instanceof Vector3) { return frustum.containsPoint(object); } else if (object instanceof Matrix4) {//第一个参数如果和第二个参数一样都是box的worldMatrix } /* containsPoint: ƒ containsPoint( point ) intersectsBox: ƒ intersectsBox( box ) intersectsObject: ƒ intersectsObject( object )//geo intersectsSphere: ƒ intersectsSphere( sphere ) intersectsSprite: ƒ intersectsSprite( sprite ) */ }; Utils.getIntersect = function (camera, meshes, pointer, raycaster) { //获取鼠标和meshes交点 if (!raycaster) { //getMouseIntersect camera.updateMatrixWorld(); raycaster = new Raycaster(); var origin = new Vector3(pointer.x, pointer.y, -1).unproject(camera), end = new Vector3(pointer.x, pointer.y, 1).unproject(camera); var dir = end.sub(origin).normalize(); raycaster.set(origin, dir); } meshes.forEach(e => { raycaster.layers.enable(math.getBaseLog(2, e.layers.mask)); }); var n = raycaster.intersectObjects(meshes); if (0 === n.length) return null; return n[0]; }; Utils.addOrRemoveDefine = function (material, defineName, type) { var value = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ''; var defines = material.defines; if (type == 'add') { if (defines[defineName] != void 0 && defines[defineName] == value) return; defines[defineName] = value; } else { if (defines[defineName] != void 0) return; delete defines[defineName]; } material.needsUpdate = true; }; Utils.makeTexDontResize = function (map) { //避免贴图因非2的次方而缩小。小心使用 if (!map || !map.image) { return console.log('!map || !map.image', map, map && map.image); } if (MathUtils.isPowerOfTwo(map.image.width) && MathUtils.isPowerOfTwo(map.image.height)) return; map.wrapS = map.wrapT = ClampToEdgeWrapping; //原默认 RepeatWrapping map.minFilter = LinearFilter; // or THREE.NearestFilter 原默认 LinearMipmapLinearFilter map.generateMipmaps = false; map.needsUpdate = true; }; Utils.updateVisible = function (object, reason, ifShow) { var level = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; var type = arguments.length > 4 ? arguments[4] : undefined; //当所有加入的条件都不为false时才显示. reason='force'一般是强制、临时的 if (!object.unvisibleReasons) object.unvisibleReasons = []; //如果length>0代表不可见 if (!object.visibleReasons) object.visibleReasons = []; //在同级时,优先可见 var update = function update() { //先按从高到低的level排列 object.unvisibleReasons = object.unvisibleReasons.sort((a, b) => b.level - a.level); object.visibleReasons = object.visibleReasons.sort((a, b) => b.level - a.level); var maxVisiLevel = object.visibleReasons[0] ? object.visibleReasons[0].level : -1; var maxunVisiLevel = object.unvisibleReasons[0] ? object.unvisibleReasons[0].level : -1; var shouldVisi = maxVisiLevel >= maxunVisiLevel; var visiBefore = object.visible; if (visiBefore != shouldVisi) { object.visible = shouldVisi; object.dispatchEvent({ type: 'isVisible', visible: shouldVisi, reason }); } }; if (ifShow) { var index = object.unvisibleReasons.findIndex(e => e.reason == reason); if (index > -1) { type = 'cancel'; object.unvisibleReasons.splice(index, 1); } if (type == 'add') { if (!object.visibleReasons.some(e => e.reason == reason)) { object.visibleReasons.push({ reason, level }); } } } else { var index = object.visibleReasons.findIndex(e => e.reason == reason); if (index > -1) { type = 'cancel'; object.visibleReasons.splice(index, 1); } if (type != 'cancel') { if (!object.unvisibleReasons.some(e => e.reason == reason)) { object.unvisibleReasons.push({ reason, level }); } } } update(); }; /* 复杂案例: 如果物体默认隐藏, 当符合任何一个其他条件时可见,则可: Potree.Utils.updateVisible(this, "default", false, 0 ) //默认隐藏 Potree.Utils.updateVisible(this, 条件名, ifShow, 1, ifShow?'add':'cancel' ) //其他的条件 */ Utils.getObjVisiByReason = function (object, reason) { //获取在某条件下是否可见. 注: 用户在数据集选择可不可见为"datasetSelection" if (object.visible) return true;else { return !object.unvisibleReasons || !object.unvisibleReasons.some(e => e.reason == reason); } }; Utils.setCameraLayers = function (camera, enableLayers) { var extraEnableLayers = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; //add camera.layers.disableAll(); enableLayers.concat(extraEnableLayers).forEach(e => { var layer = Potree.config.renderLayers[e]; if (layer == void 0) { console.error('setCameraLayer没找到layer!'); return; } camera.layers.enable(layer); }); }; Utils.setObjectLayers = function (object, layerName) { //add var layer = Potree.config.renderLayers[layerName]; if (layer == void 0) { console.error('setObjectLayers没找到layer!', layerName); return; } object.traverse(e => { e.layers.set(layer); }); }; Utils.imgAddText = async (img, text, labelInfo) => { var label = new Potree.TextSprite(Object.assign({ //如果直接在canvas里写字,要另外写很多和canvas.drawText有关的,所以还是借助textSprite吧 backgroundColor: { r: 0, g: 0, b: 0, a: 0 }, textColor: { r: 255, g: 255, b: 255, a: 1 }, margin: { x: 3, y: 3 }, renderOrder: 50, fontsize: 20, text }, labelInfo)); var labelImg = new Image(); labelImg.src = label.sprite.material.map.image.toDataURL('image/png'); return new Promise((resolve, reject) => { labelImg.onload = () => { if (labelInfo.horizonCenter) { //水平居中(对img来说) labelInfo.leftRatioToImg = 0.5 - labelImg.width / img.width / 2; } var result = Common.imgAddLabel(img, labelImg, labelInfo); label.dispose(); resolve(result); }; }); }; Utils.combineImgs = async (imgs, compressRatio, width, height) => { //拼合图片,顺序从上到下从左到右, 每张图大小不一定一致,但同列的宽一致,同行宽一致 return new Promise((resolve, reject) => { var item = imgs[0][0]; var wc = imgs.length, hc = imgs[0].length, loadCount = 0, amount = wc * hc; width = width || imgs.reduce((w, c) => w + c[0].width, 0), //相加得到的可能比想要得到的大几个像素,之后会重叠 height = height || imgs[0].reduce((w, c) => w + c.height, 0); var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; var context = canvas.getContext('2d'); for (var i = 0; i < wc; i++) { var _loop = function _loop() { var img = new Image(); img.src = imgs[i][j].dataUrl; img.index = { i, j }; img.onload = () => { loadCount++; context.drawImage(img, img.index.i * img.width, img.index.j * img.height, img.width, img.height); if (loadCount == amount) { var dataUrl = canvas.toDataURL('image/png', compressRatio); context.clearRect(0, 0, width, height); resolve(dataUrl); } }; }; for (var j = 0; j < hc; j++) { _loop(); } } }); }; BinaryLoader.prototype.load = function (node, callback) { //解析点云 if (node.loaded) { return; } var url = node.getURL(); if (this.version.equalOrHigher('1.4')) { url += '.bin'; } url += '?m=' + node.pcoGeometry.timeStamp; //add var xhr = XHRFactory.createXMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'arraybuffer'; xhr.overrideMimeType('text/plain; charset=x-user-defined'); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if ((xhr.status === 200 || xhr.status === 0) && xhr.response !== null) { var buffer = xhr.response; this.parse(node, buffer, callback); } else { node.loadFailed = 'status:' + xhr.status + ",url:" + url; Potree.numNodesLoading--; //console.error(`Failed to load file! HTTP status: ${xhr.status}, file: ${url}`); throw new Error("Failed to load file! HTTP status: ".concat(xhr.status, ", file: ").concat(url)); } } }; try { xhr.send(null); } catch (e) { node.loadFailed = 'catchError'; Potree.numNodesLoading--; console.error('加载点云node出错 ', url, e); } }; PointAttribute.RGBA_PACKED = new PointAttribute("rgba", PointAttributeTypes.DATA_TYPE_INT8, 4); PointAttribute.COLOR_PACKED = PointAttribute.RGBA_PACKED; PointAttribute.INTENSITY = new PointAttribute("intensity", PointAttributeTypes.DATA_TYPE_UINT16, 1); PointAttribute.CLASSIFICATION = new PointAttribute("classification", PointAttributeTypes.DATA_TYPE_UINT8, 1); PointAttribute.GPS_TIME = new PointAttribute("gps-time", PointAttributeTypes.DATA_TYPE_DOUBLE, 1); ProfileWindow.prototype.initTHREE = function () { this.renderer = new WebGLRenderer({ alpha: true, premultipliedAlpha: false }); this.renderer.setClearColor(0x000000, 0); this.renderer.setSize(10, 10); this.renderer.autoClear = false; this.renderArea.append($(this.renderer.domElement)); this.renderer.domElement.tabIndex = '2222'; $(this.renderer.domElement).css('width', '100%'); $(this.renderer.domElement).css('height', '100%'); { var gl = this.renderer.getContext(); if (gl.createVertexArray == null) { var extVAO = gl.getExtension('OES_vertex_array_object'); if (!extVAO) { throw new Error("OES_vertex_array_object extension not supported"); } gl.createVertexArray = extVAO.createVertexArrayOES.bind(extVAO); gl.bindVertexArray = extVAO.bindVertexArrayOES.bind(extVAO); } } this.camera = new OrthographicCamera(-1000, 1000, 1000, -1000, -1000, 1000); this.camera.up.set(0, 0, 1); this.camera.rotation.order = "ZXY"; this.camera.rotation.x = Math.PI / 2.0; this.scene = new Scene(); this.profileScene = new Scene(); var sg = new SphereGeometry(1, 16, 16); var sm = new MeshNormalMaterial(); this.pickSphere = new Mesh(sg, sm); this.scene.add(this.pickSphere); this.viewerPickSphere = new Mesh(sg, sm); }; //Potree_update_visibility Potree.updatePointClouds = function (pointclouds, camera, areaSize) { viewer.addTimeMark('updateClouds', 'start'); for (var pointcloud of pointclouds) { var start = performance.now(); for (var profileRequest of pointcloud.profileRequests) { profileRequest.update(); var _duration = performance.now() - start; if (_duration > 5) { break; } } var duration = performance.now() - start; } var result = Potree.updateVisibility(pointclouds, camera, areaSize); for (var _pointcloud5 of pointclouds) { //pointcloud.updateMaterial(pointcloud.material, pointcloud.visibleNodes, camera, renderer);//转移到渲染时 _pointcloud5.updateVisibleBounds(); } Potree.lru.freeMemory(); //即Potree.lru 能看到所有在加载的node viewer.addTimeMark('updateClouds', 'end'); return result; }; Potree.updateVisibilityStructures = function (pointclouds, camera, areaSize) { var frustums = {}; var camObjPositions = {}; var camObjDirs = {}; //add var priorityQueue = new BinaryHeap(function (x) { return -x.weight; /* 1 / x.weight; */ }); //二叉堆。 改,之前的weight不支持负数 viewer.addTimeMark('visiStructure', 'start'); //camera.updateMatrixWorld(); var viewI = camera.matrixWorldInverse; var proj = camera.projectionMatrix; var view = camera.matrixWorld; var projViewI = new Matrix4().multiply(proj).multiply(viewI); /* let list = pointclouds // stopWhenAllUsed = !viewer.lastFrameChanged let min = 5, max = Math.max(20 , Math.round(list.length / 10 )) let result = Common.batchHandling.getSlice('pcGetFrustum', list, { min,max, durBound1: 3, durBound2: 10} ) //iphonex稳定后大概在7-10。 */ for (var i = 0; i < pointclouds.length; i++) { var pointcloud = pointclouds[i]; if (!pointcloud.initialized()) { continue; } /* let info = history.get(pointcloud) if() */ pointcloud.numVisibleNodes = 0; pointcloud.numVisiblePoints = 0; pointcloud.deepestVisibleLevel = 0; pointcloud.visibleNodes = []; pointcloud.visibleGeometry = []; // 因漫游模式而隐藏的话 依旧需要加入visibleNodes,因为pick需要 /* if (pointcloud.visible && pointcloud.root !== null) { priorityQueue.push({pointcloud: i, node: pointcloud.root, weight: Number.MAX_VALUE}); } */ if (pointcloud.visible || !pointcloud.hasDepthTex && pointcloud.unvisibleReasons && pointcloud.unvisibleReasons.length == 1 && pointcloud.unvisibleReasons[0].reason == 'displayMode' && pointcloud.root !== null) { //改 visible -> priorityQueue.push({ pointcloud: i, node: pointcloud.root, weight: Number.MAX_VALUE }); } else { continue; } // frustum in object space var frustum = new Frustum(); var world = pointcloud.matrixWorld; // use close near plane for frustum intersection /* let frustumCam = camera.clone(); frustumCam.zoom = camera.zoom //add frustumCam.near = Math.min(camera.near, 0.1); frustumCam.updateProjectionMatrix(); */ //----没用到frustumCam,删了 var fm = new Matrix4().multiply(projViewI).multiply(world); frustum.setFromProjectionMatrix(fm); frustums[i] = frustum; //frustums.push(frustum); // camera position in object space var worldI = pointcloud.matrixWorldInverse; var camMatrixObject = new Matrix4().multiply(worldI).multiply(view); //假设点云无变换的话,相机相对于点云的变换矩阵 var camObjPos = new Vector3().setFromMatrixPosition(camMatrixObject); camObjPositions[i] = camObjPos; //camObjPositions.push(camObjPos); var quaternion = new Quaternion().setFromRotationMatrix(camMatrixObject); var camDir = new Vector3(0, 0, -1).applyQuaternion(quaternion); camObjDirs[i] = camDir; // hide all previously visible nodes // if(pointcloud.root instanceof PointCloudOctreeNode){ // pointcloud.hideDescendants(pointcloud.root.sceneNode); // } if (pointcloud.root.isTreeNode()) { pointcloud.hideDescendants(pointcloud.root.sceneNode); } for (var j = 0; j < pointcloud.boundingBoxNodes.length; j++) { pointcloud.boundingBoxNodes[j].visible = false; } } viewer.addTimeMark('visiStructure', 'end'); return { 'frustums': frustums, 'camObjPositions': camObjPositions, 'priorityQueue': priorityQueue, camObjDirs }; }; Potree.updateVisibility = function (pointclouds, camera, areaSize) { var numVisibleNodes = 0; var numVisiblePoints = 0; var numVisiblePointsInPointclouds = new Map(pointclouds.map(pc => [pc, 0])); var visibleNodes = []; var visibleGeometry = []; var unloadedGeometry = []; var lowestSpacing = Infinity; // calculate object space frustum and cam pos and setup priority queue var s = Potree.updateVisibilityStructures(pointclouds, camera, areaSize); //得到相机可见范围 var frustums = s.frustums; var camObjPositions = s.camObjPositions; var priorityQueue = s.priorityQueue; var camObjDirs = s.camObjDirs; var loadedToGPUThisFrame = 0; var domWidth = areaSize.x; //renderer.domElement.clientWidth; var domHeight = areaSize.y; //renderer.domElement.clientHeight; var fov = camera.fov * Math.PI / 180; var slope = Math.tan(fov / 2); var projFactor0 = 0.5 * domHeight / slope; // check if pointcloud has been transformed // some code will only be executed if changes have been detected if (!Potree._pointcloudTransformVersion) { Potree._pointcloudTransformVersion = new Map(); } var pointcloudTransformVersion = Potree._pointcloudTransformVersion; for (var pointcloud of pointclouds) { if (pointcloud.hasDepthTex ? !pointcloud.visible : !Potree.Utils.getObjVisiByReason(pointcloud, 'datasetSelection')) { //改 visible -> continue; } //if(!pointcloud.visible) continue pointcloud.updateMatrixWorld(); if (!pointcloudTransformVersion.has(pointcloud)) { pointcloudTransformVersion.set(pointcloud, { number: 0, transform: pointcloud.matrixWorld.clone() }); } else { var version = pointcloudTransformVersion.get(pointcloud); if (!version.transform.equals(pointcloud.matrixWorld)) { version.number++; version.transform.copy(pointcloud.matrixWorld); pointcloud.dispatchEvent({ type: "transformation_changed", target: pointcloud }); } } } var _loop2 = function _loop2() { var element = priorityQueue.pop(); //取出权重最大的一个 var node = element.node; var parent = element.parent; var pointcloud = pointclouds[element.pointcloud]; // { // restrict to certain nodes for debugging // let allowedNodes = ["r", "r0", "r4"]; // if(!allowedNodes.includes(node.name)){ // continue; // } // } var box = node.getBoundingBox(); var frustum = frustums[element.pointcloud]; var camObjPos = camObjPositions[element.pointcloud]; if (!frustum) return 0; // continue //add var camObjDir = camObjDirs[element.pointcloud]; var insideFrustum = frustum.intersectsBox(box); var maxLevel = pointcloud.maxLevel == void 0 ? Infinity : pointcloud.maxLevel; var minLevel = pointcloud.minLevel == void 0 ? 0 : pointcloud.minLevel; //add var level = node.getLevel(); var visible = insideFrustum; visible = visible && !(numVisiblePoints + node.getNumPoints() > Potree.pointBudget); visible = visible && !(numVisiblePointsInPointclouds.get(pointcloud) + node.getNumPoints() > pointcloud.pointBudget); // pointcloud.pointBudget一直是Infinity visible = visible && level <= maxLevel /* && level >= minLevel */; //< 改为 <= //visible = visible || node.getLevel() <= 2; var pcWorldInverse = pointcloud.matrixWorld.clone().invert(); /* let m = pcWorldInverse.elements let pcWorldInvM3 = new THREE.Matrix3().set(m[0],m[4],m[12],m[1],m[5],m[13],m[3],m[7],m[15]) //去掉z的 */ //pointcloud.pcMatrix3 = new THREE.Matrix3().set(m[0],m[4],m[12],m[1],m[5],m[13],m[3],m[7],m[15]) //去掉z的 var intersectBox = clipBox => { var toPCObject = pcWorldInverse.clone().multiply(clipBox.box.matrixWorld); //box乘上点云逆矩阵 return Potree.Utils.isIntersectBox(box, toPCObject); }; //改 总共两种box : 可见和不可见(都是并集) var clipBoxes_in = pointcloud.material.clipBoxes_in; var clipBoxes_out = pointcloud.material.clipBoxes_out; var bigClipInBox = pointcloud.material.bigClipInBox; if (visible && bigClipInBox) { //不在剪裁下载的框内 if (!intersectBox(bigClipInBox)) { visible = false; } } if (visible && clipBoxes_in.length > 0) { //当有可见box时,需要在任一可见box内才可见 var visi = false; for (var _i = 0, length = clipBoxes_in.length; _i < length; _i++) { if (intersectBox(clipBoxes_in[_i])) { visi = true; break; } } if (!visi) { visible = false; } } //outside不做处理。因为node必须完全在clipBox内才能完全隐藏,而这里的intersect只能识别出部分在clipBox内。因而只能说明不在任意一个box内绝对可见,没有意义,这里需要找出不可见的。 if (visible) { var prism = pointcloud.material.activeAttributeName == 'prismHeight' && pointcloud.material.prisms && pointcloud.material.prisms.find(e => e.computing); if (prism) { var bound = box.clone().applyMatrix4(pointcloud.matrixWorld); if (bound.intersectsBox(prism.prismBound)) { /* //node box是否包含points中的一个点 let box2 = new THREE.Box2().copy(box) let points2d = prisms.points.map(e=>new THREE.Vector2().copy(e).applyMatrix3(pcWorldInvM3)) let intersect = points2d.some(e=>{ return box2.containsPoint(e) }) if(!intersect){ //或者多边形中是否包含node box中的一个点 intersect = [ new THREE.Vector2(box.min.x, box.min.y), new THREE.Vector2(box.max.x, box.max.y), new THREE.Vector2(box.min.x, box.max.y), new THREE.Vector2(box.max.x, box.min.y), ].some(e=>{ if(math.isPointInArea(points2d, null, e) ){ return true } }) //z是不是在外层已经判断好了? if(!intersect){ visible = false } } */ //会有两个互不包含点但是交叉了的情况,所以就不仔细判断了(如横竖两个矩形构成十字架) } else visible = false; } } if (node.spacing) { lowestSpacing = Math.min(lowestSpacing, node.spacing); } else if (node.geometryNode && node.geometryNode.spacing) { lowestSpacing = Math.min(lowestSpacing, node.geometryNode.spacing); } if (numVisiblePoints + node.getNumPoints() > Potree.pointBudget) { viewer.dispatchEvent({ type: 'overPointBudget', restQueueSize: priorityQueue.size(), numVisiblePoints }); return 1; // break } if (!visible) { return 0; // continue } // TODO: not used, same as the declaration? // numVisibleNodes++; numVisiblePoints += node.getNumPoints(); var numVisiblePointsInPointcloud = numVisiblePointsInPointclouds.get(pointcloud); numVisiblePointsInPointclouds.set(pointcloud, numVisiblePointsInPointcloud + node.getNumPoints()); pointcloud.numVisibleNodes++; pointcloud.numVisiblePoints += node.getNumPoints(); if (node.isGeometryNode() && (!parent || parent.isTreeNode())) { if (node.isLoaded() && loadedToGPUThisFrame < 2) { node = pointcloud.toTreeNode(node, parent); loadedToGPUThisFrame++; } else { //console.log('unloadedGeometry',node) unloadedGeometry.push({ pointcloud, node }); //加载点云。虽然还没加载,但也计入了visibleNodes,只是无children,numPoints=0 visibleGeometry.push(node); } } if (node.isTreeNode()) { Potree.lru.touch(node.geometryNode); //在缓存中计入点云 node.sceneNode.visible = true; node.sceneNode.material = pointcloud.material; /* level >= minLevel && */ visibleNodes.push(node); /* level >= minLevel && */ pointcloud.visibleNodes.push(node); if (node._transformVersion === undefined) { node._transformVersion = -1; } var transformVersion = pointcloudTransformVersion.get(pointcloud); if (node._transformVersion !== transformVersion.number) { node.sceneNode.updateMatrix(); //node.sceneNode.matrixWorld.multiplyMatrices(pointcloud.matrixWorld, node.sceneNode.matrix); node.sceneNode.matrixWorld.multiplyMatrices(pointcloud.matrixWorld, node.sceneNode.matrix); node._transformVersion = transformVersion.number; } if (pointcloud.showBoundingBox && !node.boundingBoxNode && node.getBoundingBox) { var colorHue = level / (maxLevel + 1); var _s = 0.1 + level / (maxLevel + 1); var color = new Color().setHSL(colorHue, _s, _s); var boxHelper = new Box3Helper$1(node.getBoundingBox(), color); boxHelper.matrixAutoUpdate = false; pointcloud.boundingBoxNodes.push(boxHelper); node.boundingBoxNode = boxHelper; node.boundingBoxNode.matrix.copy(pointcloud.matrixWorld); } else if (pointcloud.showBoundingBox) { node.boundingBoxNode.visible = true; node.boundingBoxNode.matrix.copy(pointcloud.matrixWorld); } else if (!pointcloud.showBoundingBox && node.boundingBoxNode) { node.boundingBoxNode.visible = false; } // if(node.boundingBoxNode !== undefined && exports.debug.allowedNodes !== undefined){ // if(!exports.debug.allowedNodes.includes(node.name)){ // node.boundingBoxNode.visible = false; // } // } } // add child nodes to priorityQueue 由近及远、由大及小逐渐加载 var children = node.getChildren(); for (var _i2 = 0; _i2 < children.length; _i2++) { var child = children[_i2]; var weight = 0; if (camera.isPerspectiveCamera) { var sphere = child.getBoundingSphere(); var center = sphere.center; var dd = sphere.center.distanceToSquared(camObjPos); var addPow = 0.2; //viewer.mainViewport.view.isFlying() ? 0 : 0.5 //0-0.5,正常原本是0. 数字越大近处加载越快。但会造成远处加载慢甚至因pointBudge限制不加载。 isFlying:漫游时需要尽量加载一下远处的点云 //addPow *= window.devicePixelRatio //devicePixelRatio高的手机需要优先加载最近的高级点云,减少远处的中高级点云。 var distance = Math.pow(dd, 0.5 + addPow); //Math.sqrt(dd); //提高距离权重,为了提高近处加载速度。 某些场景近处加载慢优化明显,如SS-t-cqCAL6rJ5i //let attenuateDis = 10;//add var radius = sphere.radius; var projFactor = projFactor0 / distance; var screenPixelRadius = radius * projFactor; /* if(distance > attenuateDis){ screenPixelRadius -= (distance - attenuateDis) * Math.sqrt(radius) * projFactor0 * 0.002 } */ //screenPixelRadius 和 domHeight 成正比,所以手机横屏后screenPixelRadius会变小。这是正常的,因为vhov不变,相同物体高度在横屏后高度变小,所需要的密度不需要那么高了。但hfov横屏后扩大,所以可见的node范围变大,又增加了一些可见node;只是总体的可见node还是减少了。 //使用hfov和domWidth计算结果相同。 if (screenPixelRadius < pointcloud.minimumNodePixelSize / Math.pow(dd, addPow)) { //理论上因手机像素小,更不容易堆叠铺满,minimumNodePixelSize应该除以window.deviceRatio 但会造成加载过多,而内存小 continue; } weight = screenPixelRadius; if (!sphere.containsPoint(camObjPos)) { //add 优先加载屏幕中央的点云(手机端缩小离远效果明显,不会那么稀疏) var dir = new Vector3().subVectors(center, camObjPos).normalize(); var cos = 1 + dir.dot(camObjDir); //0-2 weight *= cos / 2; //Math.pow(cos,0.5) //幂越高,旁边的容易加载不到,出现缺块 如SS-t-7DUfWAUZ3V } if (distance - radius < 0) { weight = Number.MAX_VALUE; } //如果能得到每个方向上的密度,也就是node数量,密度大的远处少加载,因为被遮挡了显示也没有意义,就好了。 } else { // TODO ortho visibility //let bb = child.getBoundingBox(); var _sphere = child.getBoundingSphere(); //let diagonal = bb.max.clone().sub(bb.min).length(); var reduce = 0; //0-0.5,正常原本是0. if (_sphere.radius * /* Math.pow( */camera.zoom /* ,1-reduce) */ < pointcloud.minimumNodePixelSize) { continue; } var _distance = _sphere.center.distanceToSquared(camObjPos); //先加载中间然后四周 weight = _sphere.radius / _distance; /* let vec = new THREE.Vector3().subVectors(sphere.center, camObjPos) let disOnCamDir = vec.dot(camObjDir) let vecOnCamDir = camObjDir.clone().multiplyScalar(disOnCamDir) let vecSide = new THREE.Vector3().subVectors(vec, vecOnCamDir) //在屏幕上从中心到该node的向量 let disSide = vecSide.length() //weight = sphere.radius / disSide * camera.zoom - disOnCamDir * 2; //如果用除的,ortho的camera离远了的话dis的影响就小了 weight = sphere.radius / ( disSide * 0.1 + disOnCamDir * 14 ) */ //weight = diagonal; } priorityQueue.push({ pointcloud: element.pointcloud, node: child, parent: node, weight: weight }); //貌似好像二叉堆中子节点和父节点没什么关系,就只是为了方便排序层层遍历 } //手机上像素点更小,所以远处感觉会更稀疏 }, _ret; while (priorityQueue.size() > 0) { _ret = _loop2(); if (_ret === 0) continue; if (_ret === 1) break; } // end priority queue loop { // update DEM 这是什么 var maxDEMLevel = 4; var candidates = pointclouds.filter(p => p.generateDEM && p.dem instanceof Potree.DEM); for (var _pointcloud6 of candidates) { var updatingNodes = _pointcloud6.visibleNodes.filter(n => n.getLevel() <= maxDEMLevel); _pointcloud6.dem.update(updatingNodes); } } unloadedGeometry = unloadedGeometry.filter(e => !e.loadFailed); //过滤加载失败的,否则有失败的就无法发送加载完成 if (unloadedGeometry.length) { //加载点云 var maxNodesLoading = Common.getBestCount('unloadedGeometry', viewer.lastFrameChanged ? 1 : 3, 6, 4, 15 /* , true */); //dur在iphoneX中静止有7,pc是2 //!lastFrameChanged静止时加速下载 //THREE.Math.clamp(Math.round(9 - dur), 1, 6 ) //console.log('unloadedGeometry', unloadedGeometry.length) //主要在手机端有效果。不改之前在展示的点云较多时前进会卡。 for (var i = 0; i < Math.min(maxNodesLoading, unloadedGeometry.length); i++) { unloadedGeometry[i].node.load(unloadedGeometry[i].pointcloud.pcoGeometry); } if (!Potree.pointsLoading) { Potree.pointsLoading = true; //console.log('startLoad') viewer.dispatchEvent('startLoadPoints'); } } else { if (Potree.pointsLoading) { Potree.pointsLoading = false; //console.log('load done!') setTimeout(() => { Potree.pointsLoading || viewer.dispatchEvent('pointsLoaded'); }, document.hidden ? 3000 : 50); //hidden时可能好几秒才更新一次,所以这个并不准 } } Potree.unloadedGeometry = unloadedGeometry; //add: Potree.numVisiblePoints = numVisiblePoints; return { visibleNodes: visibleNodes, numVisiblePoints: numVisiblePoints, lowestSpacing: lowestSpacing }; }; Potree.numVisiblePoints = 0; /* note: 缓存中的点数 Potree.lru.numPoints 一般会 大于 每个点云显示点总数的numVisiblePoints 当超出缓冲区最大点云数时,加载的点云节点会被dispose彻底消除;否则,隐藏的节点就会等待再次被使用显示 由于加载按照由近及远、由大及小的顺序,要降低卡顿,就只需要降低Potree.pointBudget即可。但目前只设置了三个层次;另外提供maxLevel细节调节,能显示更均匀. 最好多一个调节pointBudge的滑动条 Potree.lru.numPoints Potree.numVisiblePoints viewer.scene.pointclouds[0].visibleNodes.length */ { //HQSplatRenderer var oldInit = HQSplatRenderer.prototype.init; HQSplatRenderer.prototype.init = function () { oldInit(); viewer.addEventListener('resize', this.resize.bind(this)); }; HQSplatRenderer.prototype.resize = function (e) { this.rtDepth.setSize(e.canvasWidth, e.canvasHeight); this.rtAttribute.setSize(e.canvasWidth, e.canvasHeight); }; HQSplatRenderer.prototype.clear = function () { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; this.init(); var { renderer, background } = this.viewer; if (background === "skybox") { renderer.setClearColor(0x000000, 0); } else if (background === 'gradient') { renderer.setClearColor(0x000000, 0); } else if (background === 'black') { renderer.setClearColor(0x000000, 1); } else if (background === 'white') { renderer.setClearColor(0xFFFFFF, 1); } else { renderer.setClearColor(0x000000, 0); } params.target || renderer.clear(); this.clearTargets(params); }; HQSplatRenderer.prototype.render = function () { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; this.init(); var viewer = this.viewer; var camera = params.camera ? params.camera : viewer.scene.getActiveCamera(); var { width, height } = params.width ? params : this.viewer.renderer.getSize(new Vector2()); viewer.renderer.setRenderTarget(params.target || null); viewer.dispatchEvent({ type: "render.pass.begin", viewer: viewer }); //params.target || this.resize(width, height); var visiblePointClouds = viewer.scene.pointclouds.filter(pc => pc.visible); var originalMaterials = new Map(); for (var pointcloud of visiblePointClouds) { originalMaterials.set(pointcloud, pointcloud.material); if (!this.attributeMaterials.has(pointcloud)) { var attributeMaterial = new ExtendPointCloudMaterial(); this.attributeMaterials.set(pointcloud, attributeMaterial); } if (!this.depthMaterials.has(pointcloud)) { var depthMaterial = new ExtendPointCloudMaterial(); depthMaterial.setDefine("depth_pass", "#define hq_depth_pass"); depthMaterial.setDefine("use_edl", "#define use_edl"); this.depthMaterials.set(pointcloud, depthMaterial); } } { // DEPTH PASS for (var _pointcloud7 of visiblePointClouds) { var octreeSize = _pointcloud7.pcoGeometry.boundingBox.getSize(new Vector3()).x; var material = originalMaterials.get(_pointcloud7); var _depthMaterial = this.depthMaterials.get(_pointcloud7); _depthMaterial.size = material.size; _depthMaterial.minSize = material.minSize; _depthMaterial.maxSize = material.maxSize; _depthMaterial.pointSizeType = material.pointSizeType; _depthMaterial.visibleNodesTexture = material.visibleNodesTexture; _depthMaterial.weighted = false; _depthMaterial.screenWidth = width; _depthMaterial.shape = PointShape.CIRCLE; _depthMaterial.screenHeight = height; _depthMaterial.uniforms.visibleNodes.value = material.visibleNodesTexture; _depthMaterial.uniforms.octreeSize.value = octreeSize; _depthMaterial.spacing = _pointcloud7.pcoGeometry.spacing; // * Math.max(...pointcloud.scale.toArray()); _depthMaterial.classification = material.classification; _depthMaterial.uniforms.classificationLUT.value.image.data = material.uniforms.classificationLUT.value.image.data; _depthMaterial.classificationTexture.needsUpdate = true; _depthMaterial.uniforms.uFilterReturnNumberRange.value = material.uniforms.uFilterReturnNumberRange.value; _depthMaterial.uniforms.uFilterNumberOfReturnsRange.value = material.uniforms.uFilterNumberOfReturnsRange.value; _depthMaterial.uniforms.uFilterGPSTimeClipRange.value = material.uniforms.uFilterGPSTimeClipRange.value; _depthMaterial.uniforms.uFilterPointSourceIDClipRange.value = material.uniforms.uFilterPointSourceIDClipRange.value; _depthMaterial.clipTask = material.clipTask; _depthMaterial.clipMethod = material.clipMethod; _depthMaterial.setClipBoxes(material.clipBoxes); _depthMaterial.setClipPolygons(material.clipPolygons); _pointcloud7.material = _depthMaterial; } viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, params.rtEDL || this.rtDepth, { clipSpheres: viewer.scene.volumes.filter(v => v instanceof SphereVolume) }); } { // ATTRIBUTE PASS for (var _pointcloud8 of visiblePointClouds) { var _octreeSize = _pointcloud8.pcoGeometry.boundingBox.getSize(new Vector3()).x; var _material = originalMaterials.get(_pointcloud8); var _attributeMaterial = this.attributeMaterials.get(_pointcloud8); _attributeMaterial.size = _material.size; _attributeMaterial.minSize = _material.minSize; _attributeMaterial.maxSize = _material.maxSize; _attributeMaterial.pointSizeType = _material.pointSizeType; _attributeMaterial.activeAttributeName = _material.activeAttributeName; _attributeMaterial.visibleNodesTexture = _material.visibleNodesTexture; _attributeMaterial.weighted = true; _attributeMaterial.screenWidth = width; _attributeMaterial.screenHeight = height; _attributeMaterial.shape = PointShape.CIRCLE; _attributeMaterial.uniforms.visibleNodes.value = _material.visibleNodesTexture; _attributeMaterial.uniforms.octreeSize.value = _octreeSize; _attributeMaterial.spacing = _pointcloud8.pcoGeometry.spacing; // * Math.max(...pointcloud.scale.toArray()); _attributeMaterial.classification = _material.classification; _attributeMaterial.uniforms.classificationLUT.value.image.data = _material.uniforms.classificationLUT.value.image.data; _attributeMaterial.classificationTexture.needsUpdate = true; _attributeMaterial.uniforms.uFilterReturnNumberRange.value = _material.uniforms.uFilterReturnNumberRange.value; _attributeMaterial.uniforms.uFilterNumberOfReturnsRange.value = _material.uniforms.uFilterNumberOfReturnsRange.value; _attributeMaterial.uniforms.uFilterGPSTimeClipRange.value = _material.uniforms.uFilterGPSTimeClipRange.value; _attributeMaterial.uniforms.uFilterPointSourceIDClipRange.value = _material.uniforms.uFilterPointSourceIDClipRange.value; _attributeMaterial.elevationGradientRepeat = _material.elevationGradientRepeat; _attributeMaterial.elevationRange = _material.elevationRange; _attributeMaterial.gradient = _material.gradient; _attributeMaterial.matcap = _material.matcap; _attributeMaterial.intensityRange = _material.intensityRange; _attributeMaterial.intensityGamma = _material.intensityGamma; _attributeMaterial.intensityContrast = _material.intensityContrast; _attributeMaterial.intensityBrightness = _material.intensityBrightness; _attributeMaterial.rgbGamma = _material.rgbGamma; _attributeMaterial.rgbContrast = _material.rgbContrast; _attributeMaterial.rgbBrightness = _material.rgbBrightness; _attributeMaterial.weightRGB = _material.weightRGB; _attributeMaterial.weightIntensity = _material.weightIntensity; _attributeMaterial.weightElevation = _material.weightElevation; _attributeMaterial.weightRGB = _material.weightRGB; _attributeMaterial.weightClassification = _material.weightClassification; _attributeMaterial.weightReturnNumber = _material.weightReturnNumber; _attributeMaterial.weightSourceID = _material.weightSourceID; _attributeMaterial.color = _material.color; _attributeMaterial.clipTask = _material.clipTask; _attributeMaterial.clipMethod = _material.clipMethod; _attributeMaterial.setClipBoxes(_material.clipBoxes); _attributeMaterial.setClipPolygons(_material.clipPolygons); _pointcloud8.material = _attributeMaterial; } var gl = this.gl; //viewer.renderer.setRenderTarget(null); viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, this.rtAttribute, { clipSpheres: viewer.scene.volumes.filter(v => v instanceof SphereVolume), //material: this.attributeMaterial, blendFunc: [gl.SRC_ALPHA, gl.ONE], //depthTest: false, depthWrite: false }); } for (var [_pointcloud9, _material2] of originalMaterials) { _pointcloud9.material = _material2; } if (viewer.background === "skybox") { viewer.renderer.setClearColor(0x000000, 0); viewer.renderer.clear(); viewer.skybox.camera.rotation.copy(viewer.scene.cameraP.rotation); viewer.skybox.camera.fov = viewer.scene.cameraP.fov; viewer.skybox.camera.aspect = viewer.scene.cameraP.aspect; viewer.skybox.parent.rotation.x = 0; viewer.skybox.parent.updateMatrixWorld(); viewer.skybox.camera.updateProjectionMatrix(); viewer.renderer.render(viewer.skybox.scene, viewer.skybox.camera); } else if (viewer.background === 'gradient') { viewer.renderer.setClearColor(0x000000, 0); viewer.renderer.clear(); viewer.renderer.render(viewer.scene.sceneBG, viewer.scene.cameraBG); } else if (viewer.background === 'black') { viewer.renderer.setClearColor(0x000000, 1); viewer.renderer.clear(); } else if (viewer.background === 'white') { viewer.renderer.setClearColor(0xFFFFFF, 1); viewer.renderer.clear(); } else { viewer.renderer.setClearColor(0x000000, 0); viewer.renderer.clear(); } { // NORMALIZATION PASS var normalizationMaterial = this.useEDL ? this.normalizationEDLMaterial : this.normalizationMaterial; if (this.useEDL) { normalizationMaterial.uniforms.edlStrength.value = viewer.edlStrength; normalizationMaterial.uniforms.radius.value = viewer.edlRadius; normalizationMaterial.uniforms.screenWidth.value = width; normalizationMaterial.uniforms.screenHeight.value = height; normalizationMaterial.uniforms.uEDLMap.value = (params.rtEDL || this.rtDepth).texture; } normalizationMaterial.uniforms.uWeightMap.value = this.rtAttribute.texture; normalizationMaterial.uniforms.uDepthMap.value = this.rtAttribute.depthTexture; Utils.screenPass.render(viewer.renderer, normalizationMaterial); } viewer.renderer.render(viewer.scene.scene, camera); viewer.dispatchEvent({ type: "render.pass.scene", viewer: viewer }); viewer.renderer.render(viewer.scene.sceneOverlay, camera); // add 透明贴图层 viewer.renderer.clearDepth(); viewer.transformationTool.update(); if (!params.target) { //测量线 viewer.dispatchEvent({ type: "render.pass.perspective_overlay", viewer: viewer, camera }); viewer.renderer.render(viewer.overlay, camera); //从 viewer.renderDefault搬过来,为了reticule不遮住测量线 } viewer.renderer.render(viewer.controls.sceneControls, camera); viewer.renderer.render(viewer.clippingTool.sceneVolume, camera); viewer.renderer.render(viewer.transformationTool.scene, camera); viewer.renderer.setViewport(width - viewer.navigationCube.width, height - viewer.navigationCube.width, viewer.navigationCube.width, viewer.navigationCube.width); viewer.renderer.render(viewer.navigationCube, viewer.navigationCube.camera); viewer.renderer.setViewport(0, 0, width, height); viewer.dispatchEvent({ type: "render.pass.end", viewer: viewer }); viewer.renderer.setRenderTarget(null); }; } //PointCloudOctreeGeometry.js PointCloudOctreeGeometryNode.prototype.loadHierachyThenPoints = function (pointcloud) { var node = this; // load hierarchy var callback = function callback(node, hbuffer) { var tStart = performance.now(); var view = new DataView(hbuffer); var stack = []; var children = view.getUint8(0); var numPoints = view.getUint32(1, true); node.numPoints = numPoints; stack.push({ children: children, numPoints: numPoints, name: node.name }); var decoded = []; var offset = 5; while (stack.length > 0) { var snode = stack.shift(); var mask = 1; for (var i = 0; i < 8; i++) { if ((snode.children & mask) !== 0) { var childName = snode.name + i; var childChildren = view.getUint8(offset); var childNumPoints = view.getUint32(offset + 1, true); stack.push({ children: childChildren, numPoints: childNumPoints, name: childName }); decoded.push({ children: childChildren, numPoints: childNumPoints, name: childName }); offset += 5; } mask = mask * 2; } if (offset === hbuffer.byteLength) { break; } } // console.log(decoded); var nodes = {}; nodes[node.name] = node; var pco = node.pcoGeometry; var maxLevel_ = 0; for (var _i3 = 0; _i3 < decoded.length; _i3++) { var name = decoded[_i3].name; var decodedNumPoints = decoded[_i3].numPoints; var index = parseInt(name.charAt(name.length - 1)); var parentName = name.substring(0, name.length - 1); var parentNode = nodes[parentName]; var level = name.length - 1; maxLevel_ = Math.max(maxLevel_, level); //add var boundingBox = Utils.createChildAABB(parentNode.boundingBox, index); var currentNode = new PointCloudOctreeGeometryNode(name, pco, boundingBox); currentNode.level = level; currentNode.numPoints = decodedNumPoints; currentNode.hasChildren = decoded[_i3].children > 0; currentNode.spacing = pco.spacing / Math.pow(2, level); parentNode.addChild(currentNode); nodes[name] = currentNode; } pco.dispatchEvent({ type: 'updateNodeMaxLevel', level: maxLevel_ }); //add var duration = performance.now() - tStart; if (duration > 5) { /* let msg = `duration: ${duration}ms, numNodes: ${decoded.length}`; console.log(msg); */ } node.loadPoints(); }; if (node.level % node.pcoGeometry.hierarchyStepSize === 0) { // let hurl = node.pcoGeometry.octreeDir + "/../hierarchy/" + node.name + ".hrc"; var hurl = node.pcoGeometry.octreeDir + '/' + node.getHierarchyPath() + '/' + node.name + '.hrc'; hurl += '?m=' + node.pcoGeometry.timeStamp; //add var xhr = XHRFactory.createXMLHttpRequest(); xhr.open('GET', hurl, true); xhr.responseType = 'arraybuffer'; xhr.overrideMimeType('text/plain; charset=x-user-defined'); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status === 200 || xhr.status === 0) { var hbuffer = xhr.response; callback(node, hbuffer); } else { console.log('Failed to load file! HTTP status: ' + xhr.status + ', file: ' + hurl); Potree.numNodesLoading--; } } }; try { xhr.send(null); } catch (e) { console.log('fehler beim laden der punktwolke: ' + e); } } }; PointCloudOctreeGeometryNode.prototype.loadPoints = function () { var name = this.name; this.pcoGeometry.loader.load(this, () => { //callback viewer.dispatchEvent('pointcloud_changed'); //console.log('loadPoints success ', name) }); }; //加载点云成功->准备渲染画面->更新点云可见性updateVisibility->请求加载新的点云 PointCloudOctreeGeometryNode.prototype.traverse = function (t, e) { //add from navvis 25.js void 0 === e && (e = !0); for (var n, i = e ? [this] : []; void 0 !== (n = i.pop());) { t(n); for (var o = 0, r = n.children; o < r.length; o++) { var a = r[o]; null !== a && i.push(a); } } }; Object.assign(PointCloudOctreeGeometry.prototype, EventDispatcher.prototype); LRU.prototype.freeMemory = function () { if (this.elements <= 1) { return; } var memoryRatio = browser.isMobile() ? 2 : 5; //改成navvis的,使用pointBudget,否则四屏点云闪烁。 (似乎要比updateVisiblede的node时限制要宽些,作为缓存继续存着。否则会闪烁) var max = MathUtils.clamp(viewer.viewports.length * memoryRatio * Potree.pointBudget, 0, 40e6); for (; this.numPoints > max;) { var node = this.getLRUItem(); node && this.disposeDescendants(node); } }; VolumeTool.prototype.update = function () {}; VolumeTool.prototype.startInsertion = function () { var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var volume; if (args.type) { volume = new args.type(); } else { volume = new Potree.BoxVolume(Object.assign(args, { clip: true })); } volume.highlight = true; volume.name = args.name || 'Volume-' + args.clipTask; volume.isNew = true; viewer.transformObject(null); //先清空 //console.log('startInsertion',volume.uuid) var oldVisiBoxes; if (args.clipTask == Potree.ClipTask.SHOW_INSIDE) { //如果是显示类型,需要将所有同类型的解除效果,否则看不到效果。 (或者可以在添加非第一个时去除highlight效果,会更自然,但看不清全貌) oldVisiBoxes = viewer.scene.volumes.filter(v => v.clipTask == Potree.ClipTask.SHOW_INSIDE && !v.highlight); oldVisiBoxes.forEach(box => box.highlight = true); } var updatePose = () => { //保证在视野中的大小一致: var camera = this.viewer.scene.getActiveCamera(); var w = math.getScaleForConstantSize({ width2d: 300, camera, position: volume.getWorldPosition(new Vector3()), resolution: viewer.mainViewport.resolution //2 }); /* let wp = volume.getWorldPosition(new THREE.Vector3()).applyMatrix4(camera.matrixWorldInverse); // let pp = new THREE.Vector4(wp.x, wp.y, wp.z).applyMatrix4(camera.projectionMatrix); let w = Math.abs((wp.z / 3));*/ if (!isNaN(w)) volume.scale.set(w, w, w); { //使水平朝向与camera一致 var direction = viewer.mainViewport.view.direction.setZ(0); volume.quaternion.copy(math.getQuaByAim(direction)); } }; this.dispatchEvent({ type: 'start_inserting_volume', volume: volume }); updatePose(); this.viewer.scene.addVolume(volume); this.scene.add(volume); var drag = e => { if (e.hoverViewport.name == 'mapViewport') return; var I = Utils.getMousePointCloudIntersection(viewer.mainViewport, viewer.inputHandler.mouse, viewer.inputHandler.pointer, this.viewer.scene.getActiveCamera(), this.viewer, this.viewer.scene.pointclouds, { pickClipped: args.clipTask == Potree.ClipTask.SHOW_OUTSIDE } //无视clip状态 ); var worldPos = I && I.location; if (!worldPos) { return; } volume.position.copy(worldPos); updatePose(); }; var cancel = () => { end('remove'); }; var end = e => { if (e.button == MOUSE.RIGHT && e.pressDistance <= Potree.config.clickMaxDragDis) { //remove e = 'remove'; } //console.log('end',volume.uuid, e) if (e != 'remove' && (!e.isAtDomElement || e.pressDistance > Potree.config.clickMaxDragDis)) return continueDrag(); volume.removeEventListener('drag', drag); volume.removeEventListener('drop', end); this.viewer.removeEventListener('cancel_insertions', cancel); volume.isNew = false; viewer.removeEventListener('camera_changed', updatePose); if (e == 'remove') { viewer.scene.removeVolume(volume); //删除没完成的 } else { viewer.transformObject(volume); volume.highlight = false; } volume.dispatchEvent({ type: 'createFinish', success: e != 'remove' }); oldVisiBoxes && oldVisiBoxes.forEach(box => box.highlight = false); }; var continueDrag = () => { //console.log('continueDrag',volume.uuid ) var timer = setTimeout(() => { //等 drag=null之后 //右键拖拽结束后需要重新得到drag if (volume.parent && volume.isNew) { viewer.inputHandler.startDragging(volume, { notPressMouse: true } /* {endDragFun: e.drag.endDragFun, notPressMouse:e.drag.notPressMouse, dragViewport:e.drag.dragViewport} */); } }, 1); return timer; }; volume.addEventListener('drag', drag); volume.addEventListener('drop', end); this.viewer.addEventListener('cancel_insertions', cancel); viewer.addEventListener('camera_changed', updatePose); this.viewer.inputHandler.startDragging(volume, { notPressMouse: true }); return volume; }; LineGeometry.prototype.setPositions = function (array) { //xzw改成类似LineSegments的多段线 (第二个点和第三个点之间是没有线段的, 所以不用在意线段顺序) var points = new Float32Array(array); LineSegmentsGeometry.prototype.setPositions.call(this, points); return this; }; Object.assign(ExtendView.prototype, EventDispatcher.prototype); Object.assign(ExtendScene.prototype, EventDispatcher.prototype); function start(dom, mapDom, number) { //t-Zvd3w0m /* { let obj = JSON.parse(localStorage.getItem('setting')) for(let i in obj){ console.log(i + ': ' + obj[i]) } } */ Potree.settings.number = number || 't-o5YMR13'; // 't-iksBApb'// 写在viewer前 if (!Potree.settings.isOfficial) { if ( /* Potree.settings.isTest && */browser.isMobile()) { changeLog(); } } if (browser.urlHasValue('google')) Potree.settings.mapCompany = 'google'; if (browser.urlHasValue('timing')) Potree.measureTimings = 1; var viewer = new Potree.Viewer(dom, mapDom); /* viewer.addEventListener('allLoaded',()=>{ const baseGeometry = new THREE.BufferGeometry(); baseGeometry.setIndex([0, 1, 2, 0, 2, 3]); const positionsArray = new Float32Array(4 * 3); const positions = new THREE.BufferAttribute(positionsArray, 3); baseGeometry.setAttribute('position', positions); positions.setXYZ(0, -1.0, -1.0, 0.0); positions.setXYZ(1, -1.0, 1.0, 0.0); positions.setXYZ(2, 1.0, 1.0, 0.0); positions.setXYZ(3, 1.0, -1.0, 0.0); positions.needsUpdate = true; const geometry = new THREE.InstancedBufferGeometry().copy(baseGeometry); let maxSplatCount = 8 // Splat index buffer const splatIndexArray = new Uint32Array(maxSplatCount); const splatIndexes = new THREE.InstancedBufferAttribute(splatIndexArray, 1, false); splatIndexes.setUsage(THREE.DynamicDrawUsage); geometry.setAttribute('splatIndex', splatIndexes); const splatPosArray = new Float32Array(maxSplatCount*3); const splatPoses = new THREE.InstancedBufferAttribute(splatPosArray, 3, false); splatPoses.setUsage(THREE.DynamicDrawUsage); geometry.setAttribute('splatCenter', splatPoses); splatPosArray.set([0,0,0, 1,1,1, 2,2,2, 3,3,3, 4,4,4, 5,5,5, 6,6,6, 7,7,7]) let vertexShaderSource = ` precision highp float; #include attribute vec3 splatCenter; attribute float splatIndex; varying vec2 vPosition; const float sqrt8 = sqrt(8.0); const float minAlpha = 1.0 / 255.0; void main () { mat4 transformModelViewMatrix = modelViewMatrix; vec4 viewCenter = transformModelViewMatrix * vec4(splatCenter, 1.0); vec4 clipCenter = projectionMatrix * viewCenter; float clip = 1.2 * clipCenter.w; if (clipCenter.z < -clip || clipCenter.x < -clip || clipCenter.x > clip || clipCenter.y < -clip || clipCenter.y > clip) { gl_Position = vec4(0.0, 0.0, 2.0, 1.0); return; } vPosition = position.xy; vec3 ndcCenter = clipCenter.xyz / clipCenter.w; float eigenValue1 = 0.2; float eigenValue2 = 0.2; //vec2 eigenVector1 = normalize(vec2(b, eigenValue1 - a)); vec2 eigenVector1 = normalize(vec2(0.5, 0.5)); vec2 eigenVector2 = vec2(eigenVector1.y, -eigenVector1.x); vec2 basisVector1 = eigenVector1 * min(sqrt8 * sqrt(eigenValue1), 2048.0); vec2 basisVector2 = eigenVector2 * min(sqrt8 * sqrt(eigenValue2), 2048.0); vec2 ndcOffset = vec2(vPosition.x * basisVector1 + vPosition.y * basisVector2) / viewport * 2.0 ; gl_Position = vec4(ndcCenter.xy + ndcOffset, ndcCenter.z , 1.0); vPosition *= sqrt8; }`; //面片模拟椭球,总是有厚度 const fragmentShaderSource = ` precision highp float; #include uniform vec3 color; varying vec2 vPosition; void main () { float A = dot(vPosition, vPosition); if (A > 8.0) discard; //position的范围半径为1。指一个rectangle面中的范围。椭圆外的完全透明 float opacity = exp(-0.5 * A) * vColor.a; //周围的透明度降低 gl_FragColor = vec4(color.rgb, opacity); }`; const uniforms = { 'viewport': { 'type': 'v2', 'value': new THREE.Vector2() } , color:{ 'type': 'v3', 'value': new THREE.Color() } }; const material = new THREE.ShaderMaterial({ uniforms: uniforms, vertexShader: vertexShaderSource, fragmentShader: fragmentShaderSource, transparent: true, alphaTest: 1.0, blending: THREE.NormalBlending, depthTest: true, depthWrite: false, side: THREE.DoubleSide }); window.splatMesh = new THREE.Mesh(geometry, material) viewer.scene.scene.add(window.splatMesh) viewer.addEventListener('resize',(e)=>{ if(e.viewport.name == 'mainViewport'){ uniforms.viewport.copy(e.viewport.resolution) } }) window.setSplatIndexes = (globalIndexes)=>{ geometry.attributes.splatIndex.set(globalIndexes); geometry.attributes.splatIndex.needsUpdate = true; geometry.instanceCount = globalIndexes.length } }) */ var Alignment = viewer.modules.Alignment; viewer.setEDLEnabled(false); viewer.setFOV(Potree.config.view.fov); //viewer.loadSettingsFromURL(); Potree.settings.cameraFar = Potree.config.view.far; if (!Potree.settings.isOfficial) { viewer.loadGUI(() => { viewer.setLanguage('en'); //$("#menu_appearance").next().show(); $("#menu_tools").next().show(); $("#menu_scene").next().show(); $("#siteModel").show(); //$("#alignment").show(); viewer.toggleSidebar(); }); Potree.settings.sizeFitToLevel = true; //当type为衰减模式时自动根据level调节大小。每长一级,大小就除以2 Potree.settings.rotAroundPoint = false; } Potree.loadDatasetsCallback = function (data, ifReload) { if (!data || data.length == 0) return console.error('getDataSet加载的数据为空'); Potree.datasetData = data; viewer.transform = null; var datasetLength = data.length; var pointcloudLoaded = 0; var panosLoaded = 0; var pointcloudLoadDone = function pointcloudLoadDone() {//点云cloud.js加载完毕后 }; var panosLoadDone = function panosLoadDone() { viewer.images360.loadDone(); viewer.scene.add360Images(viewer.images360); viewer.mapViewer.addListener(viewer.images360); viewer.updateModelBound(); //需等pano加载完 var { boundSize, center } = viewer.bound; if (!Potree.settings.isOfficial) { Potree.loadMapEntity('all'); //加载floorplan } if (!ifReload) { viewer.dispatchEvent({ type: 'loadPointCloudDone' }); if (!Potree.settings.UserPointDensity) { Potree.settings.UserPointDensity = 'high'; //'middle' } Potree.Log('loadPointCloudDone 点云加载完毕'); } { //初始位置 var panoId = browser.urlHasValue('pano', true); if (panoId !== '') { var pos; var pano = viewer.images360.panos.find(e => e.id == panoId); if (pano) { viewer.images360.focusPano({ pano, duration: 0, callback: () => {/* Potree.settings.displayMode = 'showPanos' */} }); } } else { //考虑到多数据集距离很远,或者像隧道那种场景,要使视野范围内一定能看到点云,最好初始点设置在漫游点上 var { boundSize: _boundSize, center: _center } = viewer.bound; var _pano = viewer.images360.findNearestPano(_center); if (_pano) { viewer.images360.flyToPano({ pano: _pano, duration: 0, target: viewer.images360.bound.center.setZ(_pano.position.z) //平视中心区域(但也不能保证这个方向一定能看到点云密集区,如果在边缘的话) }); } else { // 无漫游点 避免加载时看不到点云 SG-t-DXmdymgZ2sX SG-t-rVB03a5GXr8 //SG-t-XPf1k9pv3Zg 总有极端的场景,如这是倾斜的桥 - -, 只能调整为看到全局了 viewer.mainViewport.view.pitch = -0.7; //相对俯视 var bound = viewer.bound.boundingBox.clone(); viewer.focusOnObject({ boundingBox: bound }, 'boundingBox', 0, { dontChangeCamDir: true }); if (viewer.bound.boundSize.length() > 20) { //否则有可能超出far范围 viewer.mainViewport.camera.far = 10000; viewer.mainViewport.camera.updateProjectionMatrix(); viewer.fixCamFar = true; //不允许修改camera.far //等有点云加载出来后,再去focus其中一个,使camera.far不超过最大值 var count_ = 0; var done = () => { viewer.fixCamFar = false; viewer.mainViewport.camera.far = Potree.settings.cameraFar; viewer.mainViewport.camera.updateProjectionMatrix(); viewer.removeEventListener('pageVisible', focusPoint); clearTimeout(timer); }; var timer; var focusPoint = e => { //拉近到某个点 if (e && e.v === false) return; viewer.removeEventListener('pageVisible', focusPoint); var pointcloud = viewer.scene.pointclouds.find(e => e.root.geometryNode); console.log('初始加载focus点云', e, pointcloud); if (!pointcloud) { if (count_ < 10) { //可能没加载到,可能被隐藏 if (document.hidden) { //等回到页面再focus console.log('focus hidden'); return viewer.addEventListener('pageVisible', focusPoint); } count_++; //如果在别的 timer = setTimeout(focusPoint, 200); } else { //放弃 console.log('初始加载focus点云 放弃'); done(); } return console.warn('no!!!!!!!!!!!!!!'); } viewer.flyToDataset({ focusOnPoint: true, pointcloud, duration: 0 }); console.warn('ok!!!!!!!!!!!!!!!!'); done(); }; var focus = () => { timer = setTimeout(focusPoint, 300); }; viewer.addEventListener('setPose', () => { //设置了初始画面 viewer.removeEventListener('pointcloud_changed', focus); done(); }); viewer.addEventListener('pointcloud_changed', focus, { once: true }); //加载了点之后 } } } } viewer.addVideo(); //addFire() viewer.scene.pointclouds.some(e => !e.hasDepthTex) && (Potree.config.shelterMargin *= 3); //没有深度图的话在全景模式测量有偏差 console.log('allLoaded'); viewer.addTube({ 't-8KbK1JjubE': [{ //地上管子 黄色 path: [{ "x": -109.83, "y": -68.33, "z": -7.52 }, { "x": -95.17, "y": -59.3, "z": -7.38 }, { "x": -38.75, "y": -24.01, "z": -6.01 }, { "x": 0.5, "y": 0.19, "z": -3.89 }, { "x": 39.29, "y": 24.41, "z": -1.31 }, { "x": 43.58, "y": 27.7, "z": -0.97 }, { "x": 40.22, "y": 35.37, "z": -0.67 } // 拐弯向右 , { "x": 39.18, "y": 36.71, "z": 0.35 }, { "x": 38.69, "y": 36.04, "z": 18.04 } // 拐弯向上 } ], color: '#b86', radius: 0.08, height: 0.13 }, { //地下管子 藍色 path: [{ "x": -108.24, "y": -70.61, "z": -7.52 }, { "x": -57.8, "y": -39.31, "z": -6.72 }, { "x": -18.8, "y": -15.35, "z": -5.01 }, { "x": 55.87, "y": 31.67, "z": -0.04 }, { "x": 110.53, "y": 66.48, "z": 5.14 }], color: '#48a', radius: 0.08, height: -0.5 }] /* 'SG-t-h0I7LnfGFwj':[ //港华M层 { path:[[20.295,-10.269,-1.152],[19.996,-10.252,-1.153],[19.98,-10.253,-1.156],[19.967,-10.252,-1.165],[19.957,-10.251,-1.179],[19.953,-10.251,-1.225],[19.961,-10.242,-1.267],[19.968,-10.223,-1.296],[19.967,-10.193,-1.304],[20.007,-10.092,-1.321],[19.997,-10.063,-1.309],[19.979,-10.039,-1.284],[19.989,-10.028,-1.256],[19.993,-10.024,-1.23],[19.972,-10.026,-1.181],[20.009,-10.045,-1.026],[20.025,-10.048,-1.013],[20.045,-10.05,-1.006],[20.056,-10.052,-1.001],[20.413,-10.073,-1.016],[20.461,-10.075,-1.02],[20.498,-10.053,-1.018],[20.525,-10.022,-1.025],[20.538,-9.983,-1.029],[20.554,-9.536,-1.111],[20.554,-9.487,-1.118],[20.545,-9.445,-1.129],[20.521,-9.418,-1.14],[20.478,-9.396,-1.156],[20.427,-9.379,-1.182],[20.367,-9.369,-1.198],[19.971,-9.304,-1.221],[19.749,-9.197,-1.345]] ,color:'#8c99aa', radius:0.025, height:-0, fromDataset:true, tension:0.01, spaceDis:0.02,visiEntity:'厨房' }, { path:[[19.708,-2.921,-1.145],[19.721,-2.924,-1.119],[20.704,-2.881,-1.134],[20.736,-2.87,-1.138],[20.76,-2.852,-1.147],[20.773,-2.828,-1.148],[20.777,-2.809,-1.148],[20.794,-2.493,-1.167],[20.793,-2.461,-1.169],[20.776,-2.436,-1.174],[20.742,-2.425,-1.198],[20.14,-2.459,-1.309],[20.123,-2.457,-1.309],[20.108,-2.451,-1.31],[20.101,-2.439,-1.311],[20.095,-2.42,-1.313],[20.094,-2.399,-1.311],[20.092,-1.966,-1.295],[20.093,-1.945,-1.286],[20.094,-1.931,-1.269],[20.093,-1.929,-1.251],[20.09,-1.921,-1.197],[20.096,-1.914,-1.181],[20.107,-1.909,-1.174],[20.176,-1.893,-1.141],[20.699,-1.848,-1.076],[20.759,-1.824,-1.068],[20.81,-1.754,-1.076],[20.837,-1.71,-1.086],[20.85,-1.634,-1.1],[20.815,-1.01,-1.104],[20.824,-0.979,-1.115],[20.83,-0.957,-1.124],[20.843,-0.936,-1.132],[20.871,-0.925,-1.139],[21.065,-0.936,-1.166],[21.096,-0.935,-1.167],[21.115,-0.919,-1.167],[21.129,-0.887,-1.165],[21.136,-0.783,-1.167],[21.136,0.555,-1.201],[21.128,0.599,-1.201],[21.1,0.627,-1.199],[21.058,0.639,-1.198],[20.832,0.616,-1.179],[20.782,0.62,-1.186],[20.748,0.637,-1.19],[20.728,0.698,-1.21],[20.731,1.311,-1.233],[20.68,2.081,-1.292],[20.654,2.157,-1.307],[20.576,2.215,-1.314],[20.484,2.274,-1.321],[20.035,2.354,-1.353],[20.013,2.367,-1.363],[20.008,2.39,-1.371],[19.989,3.124,-1.384],[19.993,3.175,-1.39],[19.995,3.208,-1.393],[19.995,3.233,-1.374],[20.002,3.246,-1.324],[20.006,3.248,-1.266],[20.027,3.243,-1.245],[20.063,3.241,-1.239],[20.62,3.229,-1.226],[20.645,3.235,-1.204],[20.658,3.251,-1.191],[20.667,3.278,-1.184],[20.675,3.312,-1.193],[20.716,3.71,-1.24],[20.722,3.767,-1.251],[20.704,3.823,-1.268],[20.652,3.864,-1.279],[20.026,3.901,-1.368],[19.999,3.919,-1.37],[19.982,3.95,-1.361],[19.933,4.69,-1.285],[19.972,4.812,-1.332],[19.978,4.817,-1.233],[19.992,4.814,-1.203],[20.047,4.81,-1.196],[20.738,4.794,-1.196]] ,color:'#8c99aa', radius:0.025, height:-0, fromDataset:true, tension:0.01, spaceDis:0.02,visiEntity:'厨房' }, { path:[[19.685,-2.896,-1.115],[19.699,-2.93,-1.274],[19.701,-2.936,-1.295],[19.707,-2.94,-1.316],[19.712,-2.951,-1.34],[19.714,-2.965,-1.353],[19.716,-2.986,-1.359],[19.7,-3.595,-1.309],[19.703,-3.619,-1.303],[19.704,-3.628,-1.274],[19.719,-3.632,-1.256],[20.063,-3.633,-1.275],[20.089,-3.637,-1.254],[20.103,-3.64,-1.227],[20.11,-3.642,-1.191],[20.083,-3.669,-1.027],[20.075,-3.68,-0.999],[20.053,-3.694,-0.978],[20.053,-3.805,-0.957],[20.063,-3.827,-0.963],[20.045,-3.836,-0.962],[20.01,-3.841,-0.957],[19.737,-3.818,-0.964],[19.712,-3.814,-0.985],[19.699,-3.819,-1.059],[19.724,-3.817,-1.247],[19.725,-3.827,-1.28],[19.719,-3.842,-1.309],[19.719,-3.858,-1.33],[19.714,-3.881,-1.341],[19.699,-4.56,-1.339],[19.7,-4.62,-1.336],[19.7,-4.643,-1.334],[19.699,-4.66,-1.326],[19.698,-4.675,-1.31],[19.697,-4.678,-1.279],[19.697,-4.678,-1.21],[19.704,-4.682,-1.187],[19.716,-4.682,-1.173],[19.736,-4.683,-1.164],[20.481,-4.817,-1.026],[20.529,-4.847,-0.984],[20.562,-4.89,-0.935],[20.585,-4.932,-0.909],[20.59,-4.992,-0.887],[20.565,-5.98,-0.847],[20.547,-6.08,-0.846],[20.541,-6.17,-0.86],[20.476,-6.21,-0.858],[19.847,-6.207,-0.808],[19.803,-6.22,-0.827],[19.775,-6.217,-0.885],[19.75,-6.188,-1.289],[19.743,-6.193,-1.341],[19.742,-6.207,-1.375],[19.75,-6.232,-1.401],[19.722,-6.905,-1.359],[19.723,-6.958,-1.352],[19.722,-6.987,-1.342],[19.721,-7.001,-1.31],[19.721,-7.004,-1.231],[19.734,-7.03,-0.976],[19.742,-7.041,-0.947],[19.747,-7.059,-0.922],[19.755,-7.284,-0.764],[19.761,-7.312,-0.731],[19.776,-7.337,-0.711],[19.795,-7.355,-0.702],[20.502,-7.453,-0.715],[20.578,-7.496,-0.715],[20.631,-7.557,-0.719],[20.66,-7.653,-0.718],[20.658,-8.639,-0.766],[20.654,-8.789,-0.763],[20.639,-8.856,-0.763],[20.605,-8.89,-0.76],[20.57,-8.916,-0.761],[20.539,-8.945,-0.773],[19.879,-9.028,-0.814],[19.853,-9.032,-0.828],[19.834,-9.033,-0.842],[19.83,-9.033,-0.876],[19.857,-9.033,-1.292],[19.837,-9.037,-1.333],[19.819,-9.051,-1.354],[19.812,-9.082,-1.381],[19.79,-9.184,-1.386]] ,color:'#8c99aa', radius:0.02, height:-0, fromDataset:true, tension:0.01, spaceDis:0.02,visiEntity:'厨房' } ], 'SG-t-RGUFiJAoxvL':[ //济南工地覆土后 {//--旧的 整条 path: [[23.522,-19.432,-1.744],[25.344,20.312,-1.855],[25.344,21.302,-1.861],[25.253,21.904,-1.861],[25.088,22.381,-1.859],[24.748,22.772,-1.861],[24.222,22.893,-1.873],[-24.547,16.774,-1.319]] ,color:'#445', radius:0.08, height:-1.16, fromDataset:true, tension:0.01,// spaceDis:0.1 }, { path:[[22.726,22.678,-1.938],[-24.541,16.782,-1.319]] ,color:'#445', radius:0.08, height:-1.16, fromDataset:true, tension:0,// spaceDis:0.1 }, { path:[[23.519,-19.473,-1.744],[25.117,15.447,-1.783]] ,color:'#445', radius:0.08, height:-1.16, fromDataset:true, tension:0,// spaceDis:0.1 } ], 'SG-t-TK0S5EqWBxd':[ //济南工地 { path:[[-25.768,-12.695,-1.305],[-26.334,-21.834,-1.511],[-26.355,-22.153,-1.514],[-26.366,-22.418,-1.513],[-26.31,-22.66,-1.515],[-26.126,-22.841,-1.519],[-25.871,-22.968,-1.525],[-25.443,-22.969,-1.532],[-24.953,-22.956,-1.585],[-23.697,-22.854,-1.637]] ,color:'#445', radius:0.08, height:-1.16, fromDataset:true, spaceDis:0.2// tension:0.01, }, ],*/ }); viewer.dispatchEvent('allLoaded'); }; var transformPointcloud = (pointcloud, dataset) => { var locationLonLat = dataset.location.slice(0, 3); // [lon,lat,高程海拔] //当只有一个dataset时,无论如何transform 点云和漫游点都能对应上。 var location = viewer.transform.lonlatToLocal.forward(locationLonLat); //transform.inverse() //初始化位置 viewer.sidebar && viewer.sidebar.addAlignmentButton(pointcloud); //dataset.orientation = 0 Alignment.rotate(pointcloud, null, dataset.orientation); Alignment.translate(pointcloud, new Vector3(location[0], location[1], dataset.location[2] - originDataset.location[2])); //要使初始数据集的z为0,所以要减去初始数据集的z pointcloud.updateMatrixWorld(); Potree.Log("\u70B9\u4E91".concat(pointcloud.dataset_id, "(").concat(pointcloud.name, ")\u65CB\u8F6C\u503C:").concat(pointcloud.orientationUser, ", \u4F4D\u7F6E").concat(math.toPrecision(pointcloud.translateUser.toArray(), 3), ", \u7ECF\u7EAC\u5EA6 ").concat(dataset.location, ", spacing ").concat(pointcloud.material.spacing), { font: { color: "#f49", fontSize: 13 } }); }; if (!Potree.settings.originDatasetId) Potree.settings.originDatasetId = data[0].id; var originDataset = data.find(e => e.id == Potree.settings.originDatasetId); /* originDataset.location[0] = 113.60608878174709 originDataset.location[1] = 22.381189423935155 let ano = data.find(e=>e.name == 'SG-t-Jw0xyhL6oSY') ano.location[0] = 113.6060509967498 ano.location[1] = 22.381061273279244 */ { //拿初始数据集作为基准。它的位置要放到000 var locationLonLat = originDataset.location.slice(0, 2); Potree.setLonlat(locationLonLat[0], locationLonLat[1]); /* if(window.AMapWith84){//需要转换为高德的,但该函数不准确,转入后再转出,和原来的有偏差. navvis的我看data中存的globalLocation直接输入到高德地图后的定位和其要展示的定位一致,而我们要转为高德后才一致,猜测是navvis后台转为了高德可用的经纬度。 若不转的话,其他看起来没问题,仅高德地图定位不准确,因其为被加密后的火星坐标系。 locationLonLat = AMapWith84.wgs84ToAMap({x:locationLonLat[0], y:locationLonLat[1]}) locationLonLat = [locationLonLat.x,locationLonLat.y] } proj4.defs("LOCAL", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat[0].toPrecision(15) + " +lat_0=" + locationLonLat[1].toPrecision(15)); //高德坐标系 proj4.defs("LOCAL_MAP", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat[0].toPrecision(15) + " +lat_0=" + locationLonLat[1].toPrecision(15)); //地图和本地一样 proj4.defs("WGS84", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"); let transform1 = proj4("WGS84", "LOCAL"); //这个ok 是展开的平面投影 LOCAL即NAVVIS:TMERC let transform2 = proj4("+proj=tmerc +lat_0=0 +lon_0=123 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs;"); //注:转入后再转出,和原来的有偏差。如果输入是local坐标,数字越大偏差越大,当百万时就明显了。如果是lonlat,很奇怪经度小于50时就乱了。 viewer.transform = { lonlatToLocal : transform1, lonlatTo4550 : transform2 // 转大地坐标EPSG:4550 } if(window.AMapWith84 && Potree.settings.mapCompany != 'google'){//需要转换, 因本地高德用的lonlat和数据里的84不一样. (google地图在国内也用的高德,国外84) let change = (transform)=>{ let forward = transform.forward let inverse = transform.inverse; transform.forward = function(e, not84){ let needTran = e.x == void 0 if(needTran)var a1 = {x:e[0],y:e[1]} else var a1 = e var a = not84 ? a1 : AMapWith84.wgs84ToAMap(a1) if(needTran){ a = [a.x, a.y]; e[2] != void 0 && (a[2] = e[2]) }else{ e.z != void 0 && (a.z = e.z) } return forward(a) } transform.inverse = function(e, not84){ let needTran = e.x == void 0 var a = inverse(e) needTran && (a = {x:a[0],y:a[1]}) a = not84 ? a : AMapWith84.aMapToWgs84(a) if(needTran){ a = [a.x,a.y]; e[2] != void 0 && (a[2] = e[2]) }else{ e.z != void 0 && (a.z = e.z) } return a } } for(let f in viewer.transform){ change(viewer.transform[f]) } } */ viewer.mapViewer && viewer.mapViewer.mapLayer.maps[0].updateProjection(); } data.forEach((dataset, index) => { if (!ifReload) { var datasetCode = dataset.sceneCode || dataset.name; //对应4dkk的场景码 if (Potree.settings.isLocal && dataset.mapping) { var cloudPath = "".concat(Potree.settings.urls.prefix1, "/").concat(dataset.mapping, "/").concat(dataset.webBin); //webBin添加原因:每次裁剪之类的操作会换路径,因为oss文件缓存太严重,更新慢 } else { var cloudPath = "".concat(Potree.settings.urls.prefix1, "/").concat(dataset.webBin); //webBin添加原因:每次裁剪之类的操作会换路径,因为oss文件缓存太严重,更新慢 } //var cloudPath = `${Potree.scriptPath}/data/test/${dataset.name}/cloud.js` var timeStamp = dataset.updateTime ? dataset.updateTime.replace(/[^0-9]/ig, '') : ''; //每重算一次后缀随updateTime更新一次 //console.warn(dataset.name, 'timeStamp', timeStamp) Potree.loadPointCloud(cloudPath, dataset.name, datasetCode, timeStamp, e => { var scene = viewer.scene; var pointcloud = e.pointcloud; var config = Potree.config.material; var material = pointcloud.material; pointcloud.datasetData = dataset; pointcloud.dataset_id = dataset.id; //供漫游点找到属于的dataset点云 pointcloud.hasDepthTex = Potree.settings.useDepthTex && (!!dataset.has_depth || Potree.settings.isLocalhost && Potree.settings.number == 'SS-t-7DUfWAUZ3V'); //test material.minSize = config.minSize; material.maxSize = config.maxSize; material.pointSizeType = /* Potree.settings.isOfficial ? */config.pointSizeType; /* : 'ADAPTIVE' */ //Potree.PointSizeType[config.pointSizeType]//Potree.PointSizeType.ADAPTIVE;//FIXED pointcloud.changePointSize(config.realPointSize); //material.size = config.pointSize; pointcloud.changePointOpacity(1); material.shape = Potree.PointShape.SQUARE; pointcloud.color = pointcloud.material.color = dataset.color; pointcloud.timeStamp = timeStamp; transformPointcloud(pointcloud, dataset); scene.addPointCloud(pointcloud); if (!Potree.settings.isOfficial) { Potree.settings.floorplanEnables[dataset.id] = true; Potree.settings.floorplanType[dataset.id] = 'default'; } pointcloudLoaded++; if (pointcloudLoaded == datasetLength) pointcloudLoadDone(); Potree.loadPanos(dataset.id, data => { //console.log('loadPanos',dataset.sceneCode, dataset.id, data) viewer.images360.addPanoData(data, pointcloud); panosLoaded++; if (panosLoaded == datasetLength) { Potree.loadImgVersion(function () { var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; Potree.settings.panoVersion = e.imgVersion; //全景图被替换后 panosLoadDone(); }); } }); }); } else { var pointcloud = viewer.scene.pointclouds.find(p => p.dataset_id == dataset.id); if (!pointcloud) { Potree.Log('数据集id变了,自动使用第一个', { font: { color: '#500' } }); pointcloud = viewer.scene.pointclouds[0]; } //先归零 Alignment.translate(pointcloud, pointcloud.translateUser.clone().negate()); Alignment.rotate(pointcloud, null, -pointcloud.orientationUser); transformPointcloud(pointcloud, dataset); } }); if (ifReload) { //loadDone() } }; number && Potree.loadDatasets(Potree.loadDatasetsCallback); /* //调试用,加载多个本地 Potree.loadDatasetsCallback([ {name:'webcloud_0',id:0, orientation:0, location:[0,0,0]}, {name:'webcloud_1',id:1, orientation:0.047234761795199476, location:[-0.07925513345058573,-0.0010590072536559839,-2.403613132687564]}, {name:'webcloud_2',id:2, orientation:-1.5299545647758208, location:[1.5603736310030292, -0.0009340812579088904, -2.4464530770974139]}, ]) */ window.testTransform = function (locationLonLat, location1, location2) { proj4.defs("NAVVIS:test", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat[0].toPrecision(15) + " +lat_0=" + locationLonLat[1].toPrecision(15)); var transform = proj4("WGS84", "NAVVIS:test"); //这个ok navvis里也是这两种转换 见proj4Factory if (location1) { //经纬度 return transform.forward(location1); } else { return transform.inverse(location2); } }; window.THREE = THREE$1; window.buttonFunction = function () { viewer.scene.pointclouds.forEach(e => e.predictNodeMaxLevel()); /* viewer.startScreenshot({type:'measure', measurement:viewer.scene.measurements[0]}) viewer.modules.RouteGuider.routeStart = new THREE.Vector3(0,0,-1.3) viewer.modules.RouteGuider.routeEnd = new THREE.Vector3(-10,0,-1.3) */ }; if (Potree.settings.isLocalhost) { var before = {}; viewer.inputHandler.addEventListener('keydown', e => { //测试的代码 if (e.event.key == 't') { viewer.images360.cube.visible = true; viewer.images360.cube.material.wireframe = true; } else if (e.event.key == 'y') { viewer.images360.cube.material.wireframe = false; viewer.images360.cube.visible = Potree.settings.displayMode == 'showPanos'; } }); //-------------------------------- /* if(!number){ Potree.settings.boundAddObjs = true Potree.settings.intersectOnObjs = true // Load untextured bunny from ply viewer.loadModel({ fileType:'ply', url:Potree.resourcePath + "/models/indoor.ply", name:'test', }, (object)=>{ object.isModel = true viewer.updateModelBound() } ) } */ } } //======================================================================= /* 漫游点编辑 */ //======================================================================= function panoEditStart(dom, number, fileServer) { Potree.settings.editType = 'pano'; Potree.settings.number = number; Potree.settings.unableNavigate = true; Potree.settings.sizeFitToLevel = true; //当type为衰减模式时自动根据level调节大小。每长一级,大小就除以2 var viewer = new Potree.Viewer(dom); var Alignment = viewer.modules.Alignment; viewer.setEDLEnabled(false); viewer.setFOV(Potree.config.view.fov); //viewer.loadSettingsFromURL(); var datasetLoaded = 0; if (!Potree.settings.isOfficial) { viewer.loadGUI(() => { viewer.setLanguage('en'); $("#menu_tools").next().show(); $("#panos").show(); $("#alignment").show(); viewer.toggleSidebar(); }); Potree.settings.sizeFitToLevel = true; } var pointcloudLoadDone = function pointcloudLoadDone() { //所有点云cloud.js加载完毕后 viewer.scene.pointclouds.forEach(c => { transformPointcloud(c); }); viewer.images360.loadDone(); viewer.scene.add360Images(viewer.images360); viewer.updateModelBound(); var { boundSize, center } = viewer.bound; Potree.Log("\u4E2D\u5FC3\u70B9: ".concat(math.toPrecision(center.toArray(), 2), ", boundSize: ").concat(math.toPrecision(boundSize.toArray(), 2), " ")); viewer.scene.view.setView({ position: center.clone().add(new Vector3(10, 5, 10)), target: center }); viewer.dispatchEvent({ type: 'loadPointCloudDone' }); if (!Potree.settings.UserPointDensity) { Potree.settings.UserPointDensity = 'panoEdit'; //'middle' } Potree.Log('loadPointCloudDone 点云加载完毕', { font: [null, 10] }); viewer.dispatchEvent('allLoaded'); }; var transformPointcloud = pointcloud => { //初始化位置 viewer.sidebar && viewer.sidebar.addAlignmentButton(pointcloud); var orientation = pointcloud.panos[0].dataRotation.z + Math.PI; var location = pointcloud.panos[0].dataPosition.clone(); //.negate() Alignment.rotate(pointcloud, null, orientation); Alignment.translate(pointcloud, location); pointcloud.updateMatrixWorld(); }; var loadPanosDone = Potree.loadPanosDone = (datasetId, panoData) => { //一个数据集获取到它的panos后 Potree.settings.datasetsPanos[datasetId] = { panoData, panos: [] }; console.log('panoData', datasetId, panoData); var panoCount = panoData.length; var pointcloudLoaded = 0; var datasetsCount = Object.keys(Potree.settings.datasetsPanos).length; panoData.forEach((pano, index) => { //let cloudPath = `${Potree.scriptPath}/data/panoEdit/uuidcloud/${pano.uuid}/cloud.js` var cloudPath = "".concat(Potree.settings.urls.prefix1, "/").concat(Potree.settings.webSite, "/").concat(Potree.settings.number, "/data/bundle_").concat(Potree.settings.number, "/building/uuidcloud/").concat(pano.uuid, "/cloud.js"); /* if(Potree.settings.isLocal && dataset.mapping){ var cloudPath = `${Potree.settings.urls.prefix1}/${dataset.mapping}/${dataset.webBin}` //webBin添加原因:每次裁剪之类的操作会换路径,因为oss文件缓存太严重,更新慢 }else{ var cloudPath = `${Potree.settings.urls.prefix1}/${dataset.webBin}` //webBin添加原因:每次裁剪之类的操作会换路径,因为oss文件缓存太严重,更新慢 } */ var name = datasetId + '-' + pano.uuid; var timeStamp = 0; pano.index = index; //注意:index不等于uuid,因为有的uuid缺失。但是visibles中存的是下标! Potree.loadPointCloud(cloudPath, name, name, timeStamp, e => { //开始加载点云 var scene = viewer.scene; var pointcloud = e.pointcloud; var config = Potree.config.material; var material = pointcloud.material; material.minSize = config.minSize; material.maxSize = config.maxSize; material.pointSizeType = /* 'ADAPTIVE'// */config.pointSizeType; //Potree.PointSizeType[config.pointSizeType]//Potree.PointSizeType.ADAPTIVE;//FIXED pointcloud.changePointSize(0.1 /* config.realPointSize */); //material.size = config.pointSize; pointcloud.changePointOpacity(1); material.shape = Potree.PointShape.SQUARE; pointcloud.color = config.pointColor; pointcloud.dataset_id = datasetId; //多个点云指向一个datasetId pointcloud.panoUuid = pano.uuid; pointcloud.timeStamp = timeStamp; //transformPointcloud(pointcloud, pano) scene.addPointCloud(pointcloud); pointcloudLoaded++; if (pointcloudLoaded == panoCount) { datasetLoaded++; viewer.images360.addPanoData(panoData, pointcloud); if (datasetLoaded == datasetsCount) { pointcloudLoadDone(); } } }); }); }; if (!Potree.settings.isOfficial) { Potree.settings.datasetsPano = { 'testDataset': null }; Potree.loadPanosInfo(data => { loadPanosDone('testDataset', data.sweepLocations); }); } } function mergeEditStart(dom, mapDom) { Potree.settings.editType = 'merge'; Potree.settings.intersectOnObjs = true; Potree.settings.boundAddObjs = true; Potree.settings.unableNavigate = true; var viewer = new Potree.Viewer(dom, mapDom); var Alignment = viewer.modules.Alignment; viewer.setEDLEnabled(false); viewer.setFOV(Potree.config.view.fov); //viewer.loadSettingsFromURL(); { viewer.mainViewport.view.position.set(30, 30, 30); viewer.mainViewport.view.lookAt(0, 0, 0); viewer.updateModelBound(); //init //this.bound = new THREE.Box3(new THREE.Vector3(-1,-1,-1),new THREE.Vector3(1,1,1)) viewer.transformationTool.setModeEnable(['translation', 'rotation']); //viewer.ssaaRenderPass.sampleLevel = 1 // sampleLevel为1 的话,ground就不会变黑 viewer.inputHandler.fixSelection = true; //不通过点击屏幕而切换transfrom选中状态 } Potree.settings.sizeFitToLevel = true; //当type为衰减模式时自动根据level调节大小。每长一级,大小就除以2 Potree.loadPointCloudScene = function (url, type, id, title, done, onError, prefix) { //对应4dkk的场景码 var dataset; var loadCloud = _ref => { var { cloudPath, sceneName, sceneCode, timeStamp, color } = _ref; Potree.loadPointCloud(cloudPath, sceneName, sceneCode, timeStamp, e => { var scene = viewer.scene; var pointcloud = e.pointcloud; var config = Potree.config.material; var material = pointcloud.material; pointcloud.datasetData = dataset; pointcloud.hasDepthTex = dataset && Potree.settings.useDepthTex && !!dataset.has_depth; material.minSize = config.minSize; material.maxSize = config.maxSize; material.pointSizeType = config.pointSizeType; //Potree.PointSizeType[config.pointSizeType]//Potree.PointSizeType.ADAPTIVE;//FIXED pointcloud.changePointSize(config.realPointSize); //material.size = config.pointSize; pointcloud.changePointOpacity(1); material.shape = Potree.PointShape.SQUARE; color && (pointcloud.color = pointcloud.material.color = color); pointcloud.timeStamp = timeStamp; //transformPointcloud(pointcloud, originDataset) scene.addPointCloud(pointcloud); { viewer.updateModelBound(); var { boundSize, center } = viewer.bound; viewer.dispatchEvent({ type: 'loadPointCloudDone' }); if (!Potree.settings.UserPointDensity) { Potree.settings.UserPointDensity = 'high'; //'middle' } Potree.Log(' 点云加载完毕', sceneName, sceneCode); } viewer.dispatchEvent('allLoaded'); done(pointcloud); }, onError); }; if (type == 'laser') { var sceneCode = url; Potree.loadDatasets(data => { var originDataset = data.find(e => e.sceneCode == sceneCode); //只加载初始数据集 var timeStamp = originDataset.updateTime ? originDataset.updateTime.replace(/[^0-9]/ig, '') : ''; //每重算一次后缀随updateTime更新一次 //let cloudPath = `${Potree.settings.urls.prefix1}/${Potree.settings.webSite}/${sceneCode}/data/${sceneCode}/webcloud/cloud.js` var cloudPath = "".concat(Potree.settings.urls.prefix1, "/").concat(originDataset.webBin); //webBin添加原因:每次裁剪之类的操作会换路径,因为oss文件缓存太严重,更新慢 dataset = originDataset; loadCloud({ cloudPath, sceneName: originDataset.sceneName, sceneCode, timeStamp, color: originDataset.color }); }, sceneCode, onError, prefix); } else { //las or ply 直接用url var name = type + '|' + id + '|' + title; //有漫游点吗 if (url instanceof Array) { if (url.length == 1) { url = url[0]; } else { console.error('有多个点云?暂时还不支持', url, name); //多个点云要一起移动没想好怎么写 } } var cloudPath = url + '/cloud.js'; loadCloud({ cloudPath, sceneName: name, sceneCode: name, timeStamp: '' }); } }; var setMatrix = pointcloud => { //为了漫游点变换,要算一下 类似setMatrix /* pointcloud.transformMatrix = new THREE.Matrix4().multiplyMatrices(pointcloud.matrix, pointcloud.pos1MatrixInvert)//还原一点位移 pointcloud.transformInvMatrix.copy(pointcloud.transformMatrix).invert() pointcloud.rotateMatrix = new THREE.Matrix4().makeRotationFromEuler(pointcloud.rotation); pointcloud.rotateInvMatrix.copy(pointcloud.rotateMatrix).invert() pointcloud.panos.forEach(e=>e.transformByPointcloud()) */ //pointcloud.updateBound() //pointcloud.getPanosBound() viewer.updateModelBound(); }; var moveModel = e => { //根据鼠标移动的位置改变位置 var camera = viewer.mainViewport.camera; var origin = new Vector3(e.pointer.x, e.pointer.y, -1).unproject(camera), end = new Vector3(e.pointer.x, e.pointer.y, 1).unproject(camera); var dir = end.sub(origin); var planeZ = 0; var r = (planeZ - origin.z) / dir.z; var x = r * dir.x + origin.x; var y = r * dir.y + origin.y; //过后改为根据intersect的点来设置底部高度;这样的话,需要发送高度 /*let pos = new THREE.Vector3(x,y, planeZ ) modelEditing.updateMatrixWorld() let boundCenter = modelEditing.boundingBox.getCenter(new THREE.Vector3).applyMatrix4(modelEditing.matrixWorld); */ MergeEditor.moveBoundCenterTo(modelEditing, new Vector3(x, y, modelEditing.boundCenter.z)); //使模型中心的xy在鼠标所在位置 modelEditing.dispatchEvent("position_changed"); }; var cancelMove = () => { modelEditing = null; viewer.removeEventListener('global_mousemove', moveModel); viewer.removeEventListener('global_click', confirmPos); }; var confirmPos = () => { MergeEditor.focusOn(modelEditing); cancelMove(); return { stopContinue: true }; }; var modelType, modelEditing, MergeEditor = viewer.modules.MergeEditor; Potree.addModel = function (prop, done, onProgress, onError) { //加载模型 var loadDone = model => { model.dataset_id = prop.id; //唯一标识 if (prop.position) { model.position.copy(prop.position); } if (prop.rotation) { //model.rotation.setFromVector3(prop.rotation) model.rotation.copy(prop.rotation); } if (prop.scale) { model.scale.set(prop.scale, prop.scale, prop.scale); } if (model.isPointcloud) { model.renderOrder = Potree.config.renderOrders.model; //same as glb } if (Potree.settings.maintainBtmZ) { //transform --------维持离地高度和中心点的版本(local ver) var updateBound = () => { model.updateMatrixWorld(); viewer.updateModelBound(); }; var maintainBtmZAndCenter = () => { MergeEditor.maintainBoundXY(model); MergeEditor.setModelBtmHeight(model); updateBound(); model.dispatchEvent('transformChanged'); }; model.addEventListener('position_changed', () => { updateBound(); MergeEditor.getBoundCenter(model); //更新boundcenter MergeEditor.computeBtmHeight(model); if (prop.bottomRange && (model.btmHeight > prop.bottomRange.max || model.btmHeight < prop.bottomRange.min)) { model.btmHeight = MathUtils.clamp(model.btmHeight, prop.bottomRange.min, prop.bottomRange.max); MergeEditor.setModelBtmHeight(model); updateBound(); } model.dispatchEvent('transformChanged'); }); model.addEventListener("rotation_changed", maintainBtmZAndCenter); model.addEventListener("scale_changed", maintainBtmZAndCenter); model.addEventListener('transformChanged', () => { MergeEditor.modelTransformCallback(model); }); //离地高度只是boundingbox在transform后的最低点的高度,而非模型transform后的最低点的高度,所以旋转过后看起来不太准确 } else { //transform --------维持中心点的版本 var _updateBound = () => { model.updateMatrixWorld(); viewer.updateModelBound(); }; var maintainCenter = () => { //MergeEditor.maintainBoundXY(model) MergeEditor.maintainBoundCenter(model); _updateBound(); model.dispatchEvent('transformChanged'); }; model.addEventListener('position_changed', () => { _updateBound(); MergeEditor.getBoundCenter(model); //更新boundcenter model.dispatchEvent('transformChanged'); }); model.addEventListener("rotation_changed", maintainCenter); model.addEventListener("scale_changed", maintainCenter); model.addEventListener('transformChanged', () => { MergeEditor.modelTransformCallback(model); }); } model.updateMatrixWorld(); viewer.updateModelBound(); MergeEditor.getBoundCenter(model); //初始化 //model.lastMatrixWorld = model.matrixWorld.clone() model.lastMatrixWorld = new Matrix4(); MergeEditor.modelTransformCallback(model); done(model); // 先发送成功,因为2d界面会随机执行changePosition等初始化,然后这边再将模型移到中心地面上 if (prop.isFirstLoad) { MergeEditor.moveBoundCenterTo(model, new Vector3(0, 0, 0)); MergeEditor.setModelBtmHeight(model, 0); //初始加载设置离地高度为0 if (prop.mode != 'single') { //如果不是模型展示页,模型会随着鼠标位置移动 modelEditing = model; /* if(model.fileType == '3dTiles'){ setTimeout(()=>{ moveModel({pointer:{x:0,y:0}}) //3dTiles的移动会错乱,先默认放在当前视图中间吧 confirmPos() },1) }else{ */ viewer.addEventListener('global_mousemove', moveModel); viewer.addEventListener('global_click', confirmPos, { importance: 3 }); //} } model.dispatchEvent("position_changed"); } else { //MergeEditor.setModelBtmHeight(model, prop.bottom || 0) //默认离地高度为0 modelEditing = null; } MergeEditor.modelAdded(model); }; if (prop.type == 'glb') { var callback = object => { //focusOnSelect(object, 1000) object.isModel = true; //object.dataset_id = Date.now() //暂时 object.traverse(e => e.material && (e.material.transparent = true)); /* object.addEventListener('click',(e)=>{ //只是为了能得到hoverElement识别才加这个侦听 }) */ loadDone(object); }; var info = { fileType: prop.type, id: prop.id, unlit: prop.unlit, url: prop.url, name: prop.title /* transform : { position : prop.position, rotation : new THREE.Euler().setFromVector3(prop.rotation), scale: new THREE.Vector3(prop.scale,prop.scale,prop.scale), } */ }; viewer.loadModel(info, callback, onProgress, onError); } else if (prop.type == 'osgb' || prop.type == 'b3dm') { //3d tiles var _callback = object => { object.isModel = true; //透明度怎么办 //object.traverse(e=>e.material && (e.material.transparent = true)) loadDone(object); }; viewer.loadModel({ fileType: '3dTiles', id: prop.id, name: prop.title, maximumScreenSpaceError: prop.maximumScreenSpaceError, /* tilesUrl: 'https://4dkk.4dage.com/scene_view_data/SS-Ds19qsmuFA/images/3dtiles/tileset.json', transform : { rotation : [Math.PI/2, 0, 0], position : [0,0,0] } tilesUrl: 'https://testgis.4dage.com/LVBADUI_qp/tileset.json', transform : { rotation : [0, 0, 0], position : [0,0,0] } */ url: prop.url }, _callback, onprogress); } else if (prop.type == 'shp') { var _callback2 = object => { object.isModel = true; loadDone(object); }; viewer.loadModel({ fileType: 'shp', id: prop.id, name: prop.title, url: prop.url }, _callback2, onprogress); //shpModel.position.set(-330000, 900000,10)//尽量移动到原点。原位置在江门那 } else if (prop.type == '3dgs') { var _callback3 = object => { object.isModel = true; loadDone(object); }; viewer.loadModel({ fileType: '3dgs', id: prop.id, name: prop.title, url: prop.url }, _callback3, onprogress); } else { //else if(prop.type == 'las' || prop.type == 'ply' || prop.type == 'laz' ) Potree.loadPointCloudScene(prop.url, prop.type, prop.modelId, prop.title, pointcloud => { pointcloud.matrixAutoUpdate = true; pointcloud.initialPosition = pointcloud.position.clone(); pointcloud.pos1MatrixInvert = new Matrix4().setPosition(pointcloud.initialPosition).invert(); if (Potree.settings.mergeType2 && pointcloud.datasetData) { Potree.loadPanos(pointcloud.datasetData.id, data => { viewer.images360.addPanoData(data, pointcloud); viewer.images360.loadDone(); viewer.scene.add360Images(viewer.images360); loadDone(pointcloud); }, prop.url); } else { loadDone(pointcloud); } }, onError, prop.prefix); } }; return { THREE: THREE$1 }; } var changeLog = () => { var textarea = document.createElement('textarea'); textarea.id = "consoleLog"; textarea.style.width = '160px'; textarea.style.height = '200px'; textarea.style.position = 'fixed'; textarea.style.left = 0; textarea.style.bottom = '50px'; textarea.style['z-index'] = 9999; textarea.style.color = 'black'; textarea.style.opacity = 0.9; textarea.style['font-size'] = '12px'; textarea.style['backgroundColor'] = '#ffffff'; document.getElementsByTagName("body")[0].appendChild(textarea); var list = ["log", "error", "warn", "debug", "info", "time", "timeEnd"]; var exchange = function exchange(o) { console["old" + o] = console[o]; console[o] = function () { var args = Array.from(arguments); console["old" + o].apply(this, arguments); var t = document.getElementById("consoleLog").innerHTML; var str = ''; args.forEach(a => { str += a + ' '; }); document.getElementById("consoleLog").innerHTML = str + "\n\n" + t; }; }; for (var i = 0; i < list.length; i++) { exchange(list[i]); } }; /* 坐标转换问题: 由于控制点可以随便输入,所以本地和地理位置的转换也是可拉伸的。而navvis的转换是等比由中心展开, 所以对比两种转化方式时误差较大。 另外地理注册控制点是有参考数据集的,若参考数据集和我放置在0,0,0的数据集一致,就可直接使用,否则要转换。 --------- lonlat和空间坐标其实并非线性关系,因为lonlat其实是角度。当两个数据集在地球两端时,它们之间的夹角都相差180度了。 所以若要准确展示的话,需要将点云内所有物体,如漫游点,都先获取lonlat再去算local。或者直接将点云整体的transformMatrix考虑上在地球上相对于初始数据集的偏转。 支持ctrl+z、ctrl+Y 撤销回退的页面有: 测量、土方量、空间模型 这三个页面的点线拖拽;点云裁剪、点云下载中的裁剪 的框; 点云编辑的变换; 数据集校准; (所有数据一旦删除则无效 ) 其他快捷键: 按alt鼠标滚轮或WS键放慢。 测量or土方量: 按Alt键可以平行拖拽点。&dragPolyBeyondPoint 后缀则可平行拖拽到无点云区域 。 按M键拖拽点可以复制出当前点 点云按空格键+左键拖拽场景,可以不改相机位置的旋转视角 */ //xzw add var config$1 = { //配置参数 不可修改 displayMode: { showPointCloud: { atPano: { showPoint: true, showSkybox: false, pointUsePanoTex: false }, transition: { showPoint: true, showSkybox: false, pointUsePanoTex: false }, canLeavePano: true //是否能离开pano位置 }, showPanos: { atPano: { showPoint: false, showSkybox: true, pointUsePanoTex: false }, transition: { //showPoint: true, showSkybox: true //pointUsePanoTex: true //是否使用全景贴图 }, canLeavePano: false }, showBoth: { atPano: { showPoint: true, showSkybox: true, pointUsePanoTex: false //? }, transition: { showPoint: true, showSkybox: true, pointUsePanoTex: true }, canLeavePano: true //是否能离开pano位置 离开后自动变为showPointCloud }, //test: pointUsePanoTex: { //---静止时调点云 atPano: { showPoint: true, showSkybox: false, pointUsePanoTex: true }, transition: { showPoint: true, showSkybox: true, pointUsePanoTex: true //是否使用全景贴图 }, canLeavePano: false } }, urls: { //localTextures:'../resources/textures/', prefix1: 'https://laser-oss.4dkankan.com', //oss prefix2: 'https://testlaser.4dkankan.com', prefix3: 'https://4dkk.4dage.com', prefix4: 'https://uat-laser.4dkankan.com', //test.4dkankan prefix5: 'https://laser.4dkankan.com/backend', prefix6: 'https://mix3d.4dkankan.com/backend', //融合 prefix7: 'https://xfhd.4dkankan.com/backend' //融合 }, transitionsTime: { flyMinTime: 650, // 毫秒/米 flytimeDistanceMultiplier: 120 }, view: { fov: 70, //navvis:50 near: 0.1, far: 10000 }, map: { //mapViewer mapHeight: -1000, //要比点云低。最低 cameraHeight: 1000 //最高 ,注意(如sitemodel)其他的物体不能超过这个高度 }, minNodeSize: 30, // perspectiveCamera允许加载的node的最小可见像素宽度。越大越省性能 tiles3DMaxMemory: 300, //M. 最大支持3dTiles的内存大小 超出会崩溃。 改太小太大都会卡,太大崩溃 pointDensity: { magnifier: { maxLevelPercent: 1, pointBudget: 1 * 1000 * 1000, //至少显示这么多 minNodeSize: 5 //pick时调高精度 }, panorama: { //显示全景时的漫游。因为点只能显示1个像素的大小,所以必须很密集,但又要限制点的数量 maxLevelPercent: 0.6, pointBudget: /* 4*1000*1000// */browser.isMobile() ? 0.2 * 1000 * 1000 : 0.4 * 1000 * 1000, //点云总最大数 minNodeSize: 100 }, fourViewports: { //分四屏时防止卡顿 maxLevelPercent: 0.9, pointBudget: 3 * 1000 * 1000, // 只要限制这个就足够 (为什么分屏focus区域不同会闪烁,navvis不会)(navvis:maxLevel:5,pointBudget:1*1000*1000) minNodeSize: 70 }, fourViewportsMain: { //分四屏时防止卡顿 maxLevelPercent: 0.9, pointBudget: 3 * 1000 * 1000, // 只要限制这个就足够 (为什么分屏focus区域不同会闪烁,navvis不会)(navvis:maxLevel:5,pointBudget:1*1000*1000) minNodeSize: 70 }, panoEdit: { maxLevelPercent: 1, //在远处时由于pointBudget限制而展示稀疏,凑近时就变为最高质量了 pointBudget: 4 * 1000 * 1000, //要使点云达到200个以上时还不卡 percentByUser: true, minNodeSize: 80 //点云多的话远处的尽量就不可见吧 }, low: { //highPerformance maxLevelPercent: 0.4, //最小为0 percentByUser: true, //如果用户定义了percent,使用用户的 pointBudget: browser.isMobile() ? 1 * 1000 * 1000 : 2 * 1000 * 1000, minNodeSize: 40 / window.devicePixelRatio }, middle: { //balanced //不同场景相同级别所产生的numVisibleNodes和numVisiblePoints不同,如果分层比较细,可能要到level8才能看清,那么level5看到的点就很大且很少,如隧道t-e2Kb2iU maxLevelPercent: 0.7, percentByUser: true, pointBudget: browser.isMobile() ? 1.5 * 1000 * 1000 : 3.5 * 1000 * 1000, minNodeSize: 30 / window.devicePixelRatio }, high: { //highQuality maxLevelPercent: 1, percentByUser: true, pointBudget: browser.isMobile() ? 3 * 1000 * 1000 : 6 * 1000 * 1000, //原本最高是8,但是大部分电脑都太卡了,降 minNodeSize: 20 / window.devicePixelRatio //手机上因为像素点小,远一点的时候更需要加载密集的点云。(没事,有pointBudget限制着,会先从近处加载高级node,再远就不加载了) }, screenshot: { maxLevelPercent: 1, pointBudget: browser.isMobile() ? 4 * 1000 * 1000 : 10 * 1000 * 1000, //一般只有电脑需要截图,手机的加载多会崩 minNodeSize: 40 / window.devicePixelRatio }, screenshot2: { maxLevelPercent: 1, pointBudget: browser.isMobile() ? 8 * 1000 * 1000 : 15 * 1000 * 1000, minNodeSize: 20 / window.devicePixelRatio }, ultraHigh: { maxLevelPercent: 1, pointBudget: 20 * 1000 * 1000, minNodeSize: 10 / window.devicePixelRatio } //数值由testLevelSteps得来,其中nodeMaxLevel为2时,low和middle的都是1,如果真有这么低的点云就单独处理下。 //多个viewport尽量保证pointBudget一样,或者pointBudget不能太低于所需,否则会反复加载了又清除 }, clip: { color: '#FFC266' //map }, measure: { color: '#00C8AF', default: { color: "#64C8BB", //"#00c7b2", opacity: 0.7 }, highlight: { color: '#00C8AF', //"#00c7b2", opacity: 1, labelOpacity: 0.7 //1会挡住线和端点 }, guide: { color: '#FFFFFF', opacity: 0.8 }, backColor: '#333333', lineWidth: 3, textColor: "#000000", //"#FFFFFF" mulLabelHideFaraway: false, // 多折线根据远近显示label adsorptMinDis: 30 //最小吸附距离(像素) }, material: { //初始化 pointSize: 0.1, realPointSize: 0.1, //实际上的ui滑动条默认大小(兼容旧的版本) minSize: 0.1, maxSize: 10000, pointSizeType: 'ATTENUATED', //'ADAPTIVE'//'ADAPTIVE' \ FIXED //ADAPTIVE的在小房间里大小会不太匹配,但在远景似乎更好 /* ATTENUATED : 衰减 真实大小,靠近时感觉是点云一点点变多,缝隙变小 ADAPTIVE: 自适应 大小根据level变化,越高越小。靠近时感觉点云由大慢慢细分成小份。这个感觉更佳但是navvis为何不用这个 */ absolutePanoramaSize: 1.3, //全景漫游时的size 是fixed的模式 //sizeAtPanoRtEDL : 2000, pointColor: '#ffffff' //sizeAddAtPanoRtEDL : 0.5, //全景模式静止时的size //ADAPTIVE : 字会失真扭曲 //'ATTENUATED' 往旁边看有缝隙、点在浮动 }, skyboxBgWidth: 100, renderLayers: { //渲染层,方便分批渲染管理,替代scene的创建。数字不代表顺序。(数字不能太大) bg: 20, bg2: 21, skybox: 1, pointcloud: 11, sceneObjects: 0, //default model: 2, light: 15, measure: 4, magnifier: 5, magnifierContent: 16, volume: 6, transformationTool: 7, map: 8, mapObjects: 9, //default bothMapAndScene: 3, siteModeOnlyMapVisi: 12, //只能mapViewer可见 siteModelMapUnvisi: 13, //只有mapViewer不可见 siteModeSideVisi: 14, //只有侧面可见 layer1: 18, // 备用1 layer2: 17 // 备用2 }, renderOrders: { //会影响到绘制、pick时的顺序。 model: 10, reticule: 5, measureMarker: 6, measureLabelSub: 7, measureLabel: 8, sorptionSign: 10, model: 10, magnifier: 50 }, siteModel: { names: { 'building': '建筑', 'floor': '楼层', 'room': '房间' }, floorHeightDefault: 5 //一层楼的高度 }, panosEdit: {}, tiling: { panoPreRenderRepeatDelay: 2500, panoPreRenderDelay: 500, preRenderTourPanos: browser.valueFromHash("tileprerender", 0), tilingFlagNames: ["usetiles", "tiles"], maxNavPanoQuality: browser.valueFromHash("maxtileq", null), maxZoomPanoQuality: browser.valueFromHash("maxztileq", null), overlayStyle: browser.valueFromHash("tileoverlay", 0), uploadIntervalDelay: browser.valueFromHash("tileupdelay", 10), initialIntervalDelay: browser.valueFromHash("itiledelay", 0), maxNonBaseUploadsPerFrame: browser.valueFromHash("maxnbtpf", 1), maxBaseUploadsPerFrame: browser.valueFromHash("maxbtpf", 6), customCompression: browser.valueFromHash("tilecustcomp", 0), mobileHighQualityOverride: !1, allowUltraHighResolution: !0 }, navigation: { panoScores: !1, mouseDirection: !0, filterStrictness: .75, angleFactor: -30, directionFactor: 10, distanceFactor: -1, optionalityFactor: 3 }, axis: { 'x': { color: '#ea3f3f' /* '#d0021b' */ /* 'red' */ }, 'y': { color: '#86c215' /* '#86c542' */ /* 'green' */ }, 'z': { color: '#3396f8' /* '#3399c8' */ /* 'blue' */ }, 'xyz': { color: '#ccc' } }, shelterMargin: 0.15, //多少米内不算遮挡 (有的场景深度图不准,和点云差别蛮大如SG-t-24F0iT3pKAO) highQualityMaxZoom: 2, ultraHighQualityMaxZoom: 3, panoFieldRadius: 10, //当前位置多远范围内可以切全景模式 clickMaxDragDis: 3, clickMaxPressTime: 200, //ms doubleClickTime: 300, //双击间隔时间 testNodeCount1: browser.isMobile() ? 6 : 4, //testMaxNode次数达到这个数字时,changePointSize才使用nodeMaxLevel。 (调试时比较卡,在线上实际只需要3) background: '#232323', mapBG: /* '#232323', */'#F5F5F5', //地图的clearColor pickFrontPointRatio: 50, colors: { //from navvis red: [213, 0, 0], pink: [197, 17, 98], purple: [170, 0, 255], "deep purple": [98, 0, 234], blue: [41, 98, 255], "light blue": [0, 145, 234], cyan: [0, 184, 212], teal: [0, 191, 165], green: [0, 200, 83], "light green": [100, 221, 23], lime: [174, 234, 0], yellow: [255, 214, 0], amber: [255, 171, 0], orange: [255, 109, 0], "deep orange": [255, 61, 0] }, depthTexUVyLimit: 0.141 // 在这个范围内是没有深度的,从图片算的0.14003, 设置为稍大于这个数值 }; config$1.OrthoCameraLimit = { standard: { zoom: { min: 0.0004, max: 500 }, //如果camera缩太小,地图会因为数字边界问题而扭曲 latPad: 20, xBound: [-4e6, 4e6] }, expand: { zoom: { min: 0.0004, max: 500 }, //如果camera缩太小,地图会因为数字边界问题而扭曲 latPad: 20, xBound: [-6e6, 6e6] } }; /* 显示模式: 1只显示点云: 滚轮为前进后退,方向键可以行走。进入漫游点时自动变为混合(这样全景可以弥补缝隙),过渡时只显示点云。 2只显示全景: 不能任意行走。 过渡时显示贴图材质非edl的点云(否则有折痕不贴合)。 3混合:都显示。 不能任意行走。过渡时显示贴图材质非edl的点云(因为只显示点云的话不太美,点云很碎,不细腻) */ window.testLevelSteps = function (steps) { //[0.4,0.7,1] if (!steps) { var s = Potree.config.pointDensity; steps = [s.low.maxLevelPercent, s.middle.maxLevelPercent, s.high.maxLevelPercent]; } var max = 1; while (++max <= 12) { var r1 = steps.map(e => e * max); var r2 = steps.map(e => Math.round(e * max)); console.log("\u5F53nodeMaxLevel\u4E3A".concat(max, "\u65F6\uFF0C\u6BCF\u4E00\u7EA7\u7684level\u5206\u522B\u4E3A").concat(r2, ", (\u5C0F\u6570\uFF1A").concat(r1, ")")); } console.log('请检查每一层的三个level是否有重复'); }; function getPrefix() { var u = window.location.href.split('//'); var v = u[1].split('/'); return v[0]; } var isTest = browser.urlHasValue('test'); var settings = { //设置 可修改 editType: '', number: '', //场景序号 originDatasetId: '', //场景原本的数据集id,应该就是数据集第一个吧 isOfficial: false, webSite: 'testdata', //正式:'datav1', //不同环境对应的静态文件的地址不同 // language : "zh" isLocal: false, //是否本地 局域网版本 libsUrl: '../libs/', displayMode: '', isTest, prefix: getPrefix(), pointDensity: '', UserPointDensity: '', //pointDensity会随着进入不同的模块而自动改变,UserPointDensity记录了用户的设置 UserDensityPercent: null, //点云密度百分比 ifShowMarker: true, //显示漫游点 floorplanType: {}, //平面图类型 'default' | 'diy' 不同数据集不同{datasetId:...} floorplanEnable: false, floorplanEnables: {}, floorplanRequests: {}, //开始加载了的 mapEnable: true, //地图区域是否加载地图 cameraFar: config$1.view.far, //相机最远范围 1-300 //limitFar: true, //是否使用setting的cameraFar来限制(如在点云裁剪时为false) showPanoMesh: false, //显示小球, dblToFocusPoint: false, //调试时如果需要双击飞向某个点云的点,就打开。此时不在漫游点的话单击将无法漫游。//因和单击漫游冲突 unableNavigate: false, //进入如裁剪界面时 禁止漫游 sizeFitToLevel: false, //当type为衰减模式时自动根据level调节大小。每长一级,大小就除以2 zoom: { enabled: true, min: 1, max: config$1.highQualityMaxZoom }, navConstantly: true, navTileClass: /* browser.isMobile() ? '1k' : */'2k', //默认加载到 tileClass: '4k', //最高可达 /* loadTilesWhenUnfocus:false, //页面unfocus时也仍在加载tiles loadPointsWhenUnfocus:true, //页面unfocus时也仍在加载点云 */ //initialShowPano:true drawEntityData: false, //包括marker、线 zoomFromPointert: { //定点缩放(包括点云模式、全景模式、地图) whenPanos: true, whenPointCloud: true, map: true }, rotAroundPoint: true, //点云模式是否能绕intersectPoint旋转 tourTestCameraMove: false, //测试镜头时,不移动真实的镜头, 只移动frustum cameraAniSmoothRatio: 20, //镜头动画平滑系数,越高越平滑 urls: $.extend({}, config$1.urls, { prefix: config$1.urls.prefix4 //主要使用的 是测试环境,根据不同工程更改 }), useDepthTex: true, //使用深度贴图,但不代表一定有(得到的intersect更快速准确和稳定) SS-t-7DUfWAUZ3V //matUseDepth:false, //panoEdit: datasetsPanos: {}, //mergeModel: boundAddObjs: false, intersectOnObjs: false, intersectWhenHover: true, depTexLocBindDataset: true, //是否在pano模式下,使用深度图得到intersect的话,改intersect能属于该pano所在的点云。也就相当于在全景模式下intersect的点属于该全景图 notAdditiveBlending: false, //点云是否使用普通的blend, 否则会曝光过渡 precision: 2, // 两位小数 unit: 'm', useV4url: true, //v4的全景图等路径不一样 scene_view_data useRTskybox: true, //直接使用rtEDL绘制到屏幕,当是全景模式时. 在降4倍时能给render节省1毫秒,gpu时间未测 useRTPoint: true, //直接使用rtEDL绘制到屏幕,当是点云模式时。可以大大节省gpu时间。但有锯齿 pointEnableRT: false, //点云模式时是否绘制到rtEDL。如果不需要遮挡效果就不需绘制 cloudSameMat: true, //因为点云个数较多,就使用相同的材质,可见降低绘制速度(要保证所有点云的maxNodelevel一样,且要算出 material.spacing的平均值) showCompass: false, showAxis: isTest, //testCube : true, // moveToCenter:true, //针对数据集间隔很远的场景 dis>5000 容易抖动 tiles3DMaxMemory: config$1.tiles3DMaxMemory, adsorption: false, //测量时吸附点 pickFrontPointRatio: config$1.pickFrontPointRatio, //默认pick点云时选中靠近镜头的点的偏向 dragPolyBeyondPoint: browser.urlHasValue('dragPolyBeyondPoint'), //ctrlPolygon是否可以拖拽到没点云的地方 panoZoomByPointer: false, //全景图是否定点缩放 areaAtNotPlane: false //fastTran: isTest }; Potree.config = config$1; Potree.settings = settings; settings.isLocalhost = settings.prefix.includes('localhost:') || settings.prefix.includes('localhost:'); settings.isFormal = browser.urlHasValue('formal'); //正式环境 本地测试 if (settings.isFormal) { settings.urls.prefix = settings.urls.prefix5; settings.webSite = 'datav1'; } /* let sid = 0 let getName = ()=>{ return sid ++ } */ class BasicMaterial extends ShaderMaterial { constructor() { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(Object.assign({}, { uniforms: { color: { type: 'v3', value: o.color || new Color("#FFF") }, map: { type: 't', value: o.map }, opacity: { type: 'f', value: o.opacity == void 0 ? 1 : o.opacity } }, vertexShader: Shaders['basicTextured.vs'], fragmentShader: Shaders['basicTextured.fs'], defines: { HasColor: '' } }, o)); //this.name111 = getName() } copy(source) { super.copy(source); //console.log('copy', source.name111, this.name111, !!source.map ) this.map = source.map; return this; } set opacity(o) { this.uniforms && (this.uniforms.opacity.value = o); } get opacity() { return this.uniforms.opacity.value; } set map(o) { this.uniforms.map.value = o; if (o) { this.defines.HasMap = ''; } else { delete this.defines.HasMap; } //可能需要needsUpdate //console.log('hasMap', !!o, this.name111 ) } get map() { return this.uniforms.map.value; } } var texLoader$2 = new TextureLoader(); texLoader$2.crossOrigin = "anonymous"; var createErrorMaterial = function createErrorMaterial() { var t = new MeshBasicMaterial({ transparent: !0, depthWrite: !1, depthTest: !0, opacity: 1, side: DoubleSide }); return t.color = new Color(3355443), t; }; var tempVector = new Vector3(), //sharedata face1 = new Face3(0, 1, 2), face2 = new Face3(2, 3, 0), errorMaterial = createErrorMaterial(), uv00 = new Vector2(0, 0), uv01 = new Vector2(0, 1), uv10 = new Vector2(1, 0), uv11 = new Vector2(1, 1), face1UV = [uv00, uv10, uv11], face2UV = [uv11, uv01, uv00]; var HALF_WORLD_SIZE = 21e6; //略大于半个周长(mapSizeM/2) var MAX_VERTICAL_DIST = 2; var MAX_VERTICAL_DIST_TO_BEST = 1; function defineLocalProj(locationLonLat) { proj4.defs("LOCAL_MAP", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat[0].toPrecision(15) + " +lat_0=" + locationLonLat[1].toPrecision(15)); } var getSid = function () { var sid = 0; return function () { return sid++; }; }(); //高德坐标拾取工具 : https://lbs.amap.com/tools/picker class MapLayer extends EventDispatcher { // 包括了 MapLayerBase SceneLayer constructor(viewer_, viewport) { super(); this.sceneGroup = new Object3D(); this.sceneGroup.name = "MapLayer"; this.waitQueue = []; //等待加载的 this.loadingInProgress = 0; this.maps = []; this.frustum = new Frustum(); this.frustumMatrix = new Matrix4(); this.tileColor = new Color(16777215); this.viewport = viewport; this.changeViewer(viewer_); //添加地图 var map = new TiledMapOpenStreetMap(this, this.tileColor); this.addMap(map); //map.setEnable(false) this.sceneGroup.addEventListener('isVisible', () => { this.viewer.mapChanged = true; }); } addMapEntity(data, datasetId) { if (!data || !data[0]) { Potree.Log('平面图无数据', { font: 'red' }); return; } data[0].datasetId = datasetId; var floorplan = new TiledMapFromEntity(this, this.tileColor, data[0]); //[0]? if (floorplan) { floorplan.name += "_" + datasetId; this.addMap(floorplan); floorplan.updateProjection(); floorplan.updateObjectGroup(); var visible = false; if (datasetId in Potree.settings.floorplanEnables) { visible = Potree.settings.floorplanEnables[datasetId]; } else { visible = Potree.settings.floorplanEnable; } if (visible) { this.needUpdate = true; } else { floorplan.setEnable(false); } this.dispatchEvent({ type: 'floorplanLoaded', floorplan }); } return floorplan; } getFloorplan(datasetId) { return this.maps.find(e => e.name == 'floorplan' + "_" + datasetId); } addMap(t) { this.maps.push(t); //this.view.invalidateScene() this.needUpdate = true; this.viewer.mapChanged = true; } removeMap(t) { var e = this.maps.indexOf(t); if (e >= 0) { t.removeFromSceneGroup(this.sceneGroup); this.maps.splice(e, 1); } /* this.view.invalidateScene() */ this.needUpdate = true; this.viewer.mapChanged = true; } changeViewer(viewer_) { //add this.viewer = viewer_; } initProjection() { this.maps.forEach(map => { map.updateProjection(); map.updateObjectGroup(); }); } visibilityChanged() { if (!this.visible) for (var t = 0, e = this.maps; t < e.length; t++) { e[t].removeFromSceneGroup(this.sceneGroup); } } update() { this.needUpdate = false; if (this.disabled || !this.maps.find(e => !e.disabled) || !this.maps.find(e => e.objectGroup.visible)) return; //add this.viewer.mapChanged = true; var e, n, i, r, o; this.updateTimer = void 0, e = this.viewport.camera, n = e.projectionMatrix.clone(); var expandRatio = 1.3; n.elements[0] /= expandRatio; n.elements[5] /= expandRatio; // 为了缓存吗,使边界处也提前加载,扩大显示区域 this.frustumMatrix.multiplyMatrices(n, e.matrixWorldInverse), this.frustum.setFromProjectionMatrix(this.frustumMatrix), this.frustum.planes[4].setComponents(0, 0, 0, 0), this.frustum.planes[5].setComponents(0, 0, 0, 0), i = !0; //console.log('-------------update-----------') for (r = 0; r < this.maps.length; r++) { var map = this.maps[r]; i = map.update(this.frustum, this.sceneGroup) && i; } return [2, i]; } updateProjection() { for (var t = 0, e = this.maps; t < e.length; t++) { var n = e[t]; n.clearProjection(), n.updateObjectGroup(); } } } class TiledMapBase extends EventDispatcher { constructor(name, mapLayer, tileColor, projection) { super(); this.name = name; this.mapLayer = mapLayer, this.tileColor = tileColor, this.bias = 0; this.zIndex = -1; this.objectGroup = new Object3D(); this.objectGroup.name = name; this.objectGroupAdded = !1, this.baseTile = new MapTile(this, this.objectGroup, this.tileColor, null, '0'), this.isTileVisibleBox = new Box3(), this.isTileVisibleVec = new Vector3(); this.projection = projection; this._zoomLevel = 0; //1-20 this.objectGroup.addEventListener('isVisible', () => { this.mapLayer.viewer.mapChanged = true; }); this.computeCount = 0; this.maxLoading = 3; this.loadFailCount = 0; this.loadingInProgress = 0; } get zoomLevel() { return this._zoomLevel; } set zoomLevel(zoomLevel) { if (this._zoomLevel != zoomLevel) { this._zoomLevel = zoomLevel; this.dispatchEvent({ type: 'zoomLevelChange', zoomLevel }); //if(this.name == 'map')console.log(zoomLevel,viewer.mapViewer.camera.zoom) } } updateObjectGroup() { this.position && this.objectGroup.position.copy(this.position).setZ(0), this.quaternion && this.objectGroup.quaternion.copy(this.quaternion), this.objectGroup.updateMatrixWorld(!0); } updateProjection() { if (!this.transformMapToLocal) { this.transformMapToLocal = proj4(this.projection, "LOCAL_MAP"); } } clearProjection() { this.transformMapToLocal = void 0; this.projection !== 'LOCAL_MAP' && this.baseTile.remove(); } setEnable(enable) { //add if (!this.disabled == enable) return; if (enable) { //console.log('setEnable',true) } this.disabled = !enable; Potree.Utils.updateVisible(this.objectGroup, 'setEnable', enable); if (!enable) { this.baseTile.remove(); } else { this.mapLayer.needUpdate = true; } } update(e, n) { this.computeCount = 0; var unavailable = this.disabled || !this.objectGroup.visible; //地图即使不显示也要获得zoomlevel if (this.name != 'map' && unavailable) return; this.updateProjection(); if (!this.transformMapToLocal) return; if (!this.isTileVisible(new Vector3(0, 0, 0), this.mapSizeM, e)) return this.removeFromSceneGroup(n), !0; var viewport = this.mapLayer.viewport; var i = new Vector3(-.5 * this.mapSizeM, 0, 0); i.applyMatrix4(this.objectGroup.matrixWorld), i.project(viewport.camera); var o = new Vector3(.5 * this.mapSizeM, 0, 0); o.applyMatrix4(this.objectGroup.matrixWorld), o.project(viewport.camera); var a = viewport.resolution.x, s = viewport.resolution.y; if (a <= 0 || s <= 0 || isNaN(i.x) || isNaN(o.x)) return !1; i.sub(o), i.x *= a / 2, i.y *= s / 2; var scale; if (this.name == 'map') { //add 高纬度的因倾斜而造成tile较小,所以放大些,否则会造成显示的tile过多而卡 var lonlat = viewer.transform.lonlatToLocal.inverse(viewport.camera.position.clone()); var cos = Math.cos(MathUtils.degToRad(lonlat.y)); //越小就在纬度上越高,tile表现越小 //为什么lonlat.y会超出90? /* if(lonlat.y>90){ console.log('lonlat.y>90',lonlat.y) } */ cos = MathUtils.clamp(cos, 0, 1); var lonShift = Math.abs(viewer.mapViewer.camera.position.x / this.mapSizeM * 16); //越大就在经度离中心越远,tile表现越大 。 lonShift = MathUtils.clamp(lonShift, 0, Math.PI); lonShift = (1 - Math.sin(1 / 2 * lonShift + Math.PI / 2)) * Math.PI; // 0-Math.PI sin增速向上 scale = 0.5 * cos * (1 + lonShift) + 0.5 * Math.pow(cos, lonShift); } else { scale = 1; } var c = this.tileSizePx / i.length() / scale //多除以一个scale缩放因子,scale越大level越小 , level = Math.ceil(-Math.log(c) / Math.log(2) - this.bias); if (this.style == 'dark-standard') { //该模式贴图比较小放大点 level -= 1; } level = Math.max(level, 0); level = Math.min(level, void 0 === this.maxDepth ? 1 / 0 : this.maxDepth); this.zoomLevel = level; //add /* if(isNaN(this.zoomLevel )){ console.log(level, cos , scale , lonlat ) } */ if (!unavailable) { this.addToSceneGroup(n); return this.baseTile.update(this, e, level, this.mapSizeM, 0, 0, ""); } } isTileVisible(e, n, i) { if (n > HALF_WORLD_SIZE) return !0; var r = .5 * n; //简单版: this.transformMapToLocal.forward(e); //e转化为local this.isTileVisibleBox.makeEmpty(); this.isTileVisibleVec.set(e.x - r, e.y - r, e.z).applyMatrix4(this.objectGroup.matrixWorld); this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec); this.isTileVisibleVec.set(e.x - r, e.y + r, e.z).applyMatrix4(this.objectGroup.matrixWorld); this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec); this.isTileVisibleVec.set(e.x + r, e.y - r, e.z).applyMatrix4(this.objectGroup.matrixWorld); this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec); this.isTileVisibleVec.set(e.x + r, e.y + r, e.z).applyMatrix4(this.objectGroup.matrixWorld); this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec); //仿造createMesh写的准确版,但会因为大的tile非矩形,而视口是矩形,若视口刚好在tile的曲线边缘外却识别为可见,就会创建冗余tile。 但上面那个简单版在zoomlevel低的时候地球边缘容易有识别不到的tile,造成黑色三角形。 //容易出现奇怪的mesh /* this.isTileVisibleBox.makeEmpty() this.isTileVisibleVec.set(e.x - r, e.y - r, e.z) this.transformMapToLocal.forward(this.isTileVisibleVec) this.isTileVisibleVec.applyMatrix4(this.objectGroup.matrixWorld) this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec) this.isTileVisibleVec.set(e.x - r, e.y + r, e.z) this.transformMapToLocal.forward(this.isTileVisibleVec) this.isTileVisibleVec.applyMatrix4(this.objectGroup.matrixWorld) this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec) this.isTileVisibleVec.set(e.x + r, e.y - r, e.z) this.transformMapToLocal.forward(this.isTileVisibleVec) this.isTileVisibleVec.applyMatrix4(this.objectGroup.matrixWorld) this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec) this.isTileVisibleVec.set(e.x + r, e.y + r, e.z) this.transformMapToLocal.forward(this.isTileVisibleVec) this.isTileVisibleVec.applyMatrix4(this.objectGroup.matrixWorld) this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec) */ return i.intersectsBox(this.isTileVisibleBox); } addToSceneGroup(t) { this.objectGroupAdded || (t.add(this.objectGroup), this.objectGroupAdded = !0); } removeFromSceneGroup(t) { this.baseTile.remove(), this.objectGroupAdded && (t.remove(this.objectGroup), this.objectGroupAdded = !1); } } var loadDone = (tile, success) => { tile.map.mapLayer.loadingInProgress--; tile.map.loadingInProgress--; //console.log('loaddone', tile.name, 'loadingInProgress',tile.map.mapLayer.loadingInProgress, Date.now()) tile.loading = false; var next = tile.map.mapLayer.waitQueue[0]; if (next) { addLoadTile(next); } else { if (tile.map.mapLayer.loadingInProgress == 0) { //注意这时候不一定就加载完了,300ms后可能还会有新的tile加载 //console.log('loadDone All ?', Date.now()) tile.map.mapLayer.dispatchEvent('loadDone'); } } tile.mesh && (tile.mesh.material.needsUpdate = true); }; function addLoadTile(tile) { /* if(tile.texURL && tile.texURL.includes('testdata') ){ console.error('addLoadTile', tile.texURL.split('map_tiles/')[1] ) } */ if (tile.map.loadingInProgress < tile.map.maxLoading) { if (!tile.mesh) return; //有时候会遇到这种情况, 为什么没有被cancelLoad呢? tile.map.mapLayer.loadingInProgress++; tile.map.loadingInProgress++; tile.map.mapLayer.dispatchEvent('startLoad'); //console.log('addLoad', 'loadingInProgress',tile.map.mapLayer.loadingInProgress, Date.now()) //tile.texURL && tile.texURL.includes('testdata') && console.log('startloadTile ', tile.texURL.split('map_tiles/')[1] ) tile.loading = true; var index = tile.map.mapLayer.waitQueue.indexOf(tile); index > -1 && tile.map.mapLayer.waitQueue.splice(index, 1); var tex = tile.mesh.material.map = texLoader$2.load(tile.texURL, tex => { //如果一直加载不了会影响其他的加载,如google地图没有vpn会使全景图一直加载不了 if (tile.mesh) { //如果还要显示的话 tile.textureLoaded = true; tile.mesh.material.opacity = 1; tile.map.mapLayer.viewer.mapChanged = true; tile.map.mapLayer.needUpdate = true; //表示还要继续update(以removeChildren) if (tile.map instanceof TiledMapOpenStreetMap) { tile.map.maxLoading = browser.isMobile() ? 5 : 10; } } else { //tile.texURL && tile.texURL.includes('testdata') && console.log('loadDone and dispose', tile.texURL.split('map_tiles/')[1] ) tex.dispose(); } loadDone(tile, true); }, void 0, () => { //error tile.textureLoaded = !0; if (tile.mesh) { tile.mesh.material.dispose(); tile.mesh.material = errorMaterial; tile.map.mapLayer.viewer.mapChanged = true; } loadDone(tile, false); tile.map.loadFailCount++; if (tile.map instanceof TiledMapOpenStreetMap && Potree.settings.mapCompany == 'google' && tile.map.loadFailCount > 3) { //极有可能没有vpn为了防止影响到其他资源加载,减少加载的个数 tile.map.maxLoading = 2; } }); tex.anisotropy = 0; tex.generateMipmaps = !1; tex.minFilter = LinearFilter; tex.magFilter = LinearFilter; } else { tile.map.mapLayer.waitQueue.includes(tile) || tile.map.mapLayer.waitQueue.push(tile); } } function cancelLoad(tile, log) { //如果等待加载,但还没开始加载,取消加载 if (!tile.loading) { var index = tile.map.mapLayer.waitQueue.indexOf(tile); index > -1 && tile.map.mapLayer.waitQueue.splice(index, 1); //index > -1 && tile.texURL && tile.texURL.includes('testdata') && console.log('cancelLoad', tile.texURL.split('map_tiles/')[1]/* , (log && waitQueue.indexOf(tile)>-1) ? log:'' , tile.loading */ ) } } class MapTile { constructor(map, e, n, parent, name) { this.map = map; this.name = name; this.parent = parent; this.objectGroup = e, this.tileColor = n, this.meshAdded = !1, this.textureLoaded = !1, this.children = []; this.id = getSid(); } update(e, n, i, r, o, a, s) { return !!this.doesNotContainTilesToBeDisplayed(e) || (0 === i ? this.updateTile(e, r, o, a) : this.updateSubTiles(e, n, i, r, o, a, s)); } doesNotContainTilesToBeDisplayed(t) { return t.tilePresenceMap && t.tilePresenceMap.empty; } updateTile(t, e, n, i) { //真正显示mesh的是这一层,最高level //if(this.map.name.includes('floorplan'))console.log('updateTile',this.name) if (!this.mesh) { this.createTileObject(t, e, n, i); } if (!this.meshAdded) { this.objectGroup.add(this.mesh); this.meshAdded = !0; } if (this.textureLoaded) { //贴图加载完就不需要子集了 this.removeChildren(); } else { this.cancelChildren(); //add 停止加载子集 } return this.textureLoaded; } updateSubTiles(entity, n, level, o, a, s, c) { //if(entity.name.includes('floorplan'))console.log('updateSubTiles',this.name) //名字越长代表level越高 for (var childrenLoaded = !0, u = [-.25 * o, .25 * o, -.25 * o, .25 * o], d = [.25 * o, .25 * o, -.25 * o, -.25 * o], p = 0; p < 4; ++p) { var h = c + p.toString(10); //一级(512):0 1 2 3分别为左上、右上、左下、右下。二级(1024)就是把一级的每一块分裂,如00 01 02 03分别是0的左上、右上、左下、右下…… if (!entity.tilePresenceMap || entity.tilePresenceMap[h]) { //去掉判断,直接显示 var f = a + u[p], m = s + d[p]; tempVector.set(f, m, 0); this.map.computeCount++; //console.log(this.map.computeCount, this.name, 'level:',level) if (entity.isTileVisible(tempVector, .5 * o, n)) { this.children[p] || (this.children[p] = new MapTile(this.map, this.objectGroup, this.tileColor, this, this.name + p)); //childrenLoaded = childrenLoaded && this.children[p].update(entity, n, level - 1, .5 * o, f, m, h) //这句会使若有一个tile还在加载,就阻断了。原版是这么写的。但是为了加快加载速度,改成下面两行。感觉直接全部updateTile也没太卡,不知道很大的场景会不会卡,单帧updateTile次数超过100次的话(应该不会吧,地图大小会限制住个数) -- 2023.12 var childLoaded = this.children[p].update(entity, n, level - 1, .5 * o, f, m, h); childrenLoaded = childrenLoaded && childLoaded; } else { if (this.children[p]) { this.children[p].remove(); delete this.children[p]; } } } } return childrenLoaded && this.removeObject3D(), childrenLoaded; //子项加载完,母项mesh可以去除。(最后母项的母项以及前面的都会被删除,只留最后的叶子结点) } /* 一层层往后加载。加入第一次加载到第4层(因为level精细度是第4层),给第4层可见tile加上mesh。 然后下一次加载到第5层,那么第4层的mesh就要被清空(当它所属的第5层子集都加载完后) */ createTileObject(t, e, n, a) { var s = this; this.mesh = this.createMesh(t.transformMapToLocal, e, n, a), this.textureLoaded = !1; var c = t.mapSizeM / e, l = Math.log(c) / Math.log(2), u = n / e + .5 * (c - 1), d = -a / e + .5 * (c - 1), p = t.getTileUrl(Math.round(l), Math.round(u), Math.round(d)); Potree.Utils.setObjectLayers(this.mesh, 'map'); this.mesh.renderOrder = -(1e6 - l - 100 * (t.zIndex || 0)); this.mesh.name = this.name; //add this.texURL = p; /* let area = math.getArea(this.mesh.geometry.vertices.slice(0,3)); if(area >0){ this.mesh.visible = false console.log('area>0',this.mesh.name) } */ addLoadTile(this); } createMesh(t, e, n, o) { var a = new Geometry(); return tempVector.set(n - e / 2, o - e / 2, 0), a.vertices.push(new Vector3().copy(t.forward(tempVector))), tempVector.set(n + e / 2, o - e / 2, 0), a.vertices.push(new Vector3().copy(t.forward(tempVector))), tempVector.set(n + e / 2, o + e / 2, 0), a.vertices.push(new Vector3().copy(t.forward(tempVector))), tempVector.set(n - e / 2, o + e / 2, 0), a.vertices.push(new Vector3().copy(t.forward(tempVector))), a.faces.push(face1), a.faces.push(face2), a.faceVertexUvs[0].push(face1UV), a.faceVertexUvs[0].push(face2UV), new Mesh(a, this.createMaterial()); } createMaterial() { var t = new MeshBasicMaterial({ transparent: !0, depthWrite: !1, depthTest: !0, opacity: 0, side: DoubleSide }); /* var t = new BasicMaterial({ transparent: !0, depthWrite: !1, depthTest: !0, opacity: 0, side: THREE.DoubleSide }) t.defines.InverseColor = '' */ if (Potree.settings.isTest) { var colorHue = Math.random(); t.color = new Color().setHSL(colorHue, 0.6, 0.92); } else { t.color = this.tileColor ? this.tileColor : new Color(16777215); } return t; } traverse(f) { //add return Mesh.prototype.traverse.call(this, f); } remove() { this.removeObject3D(), this.removeChildren(); } removeObject3D() { var hasMesh = !!this.mesh; if (this.mesh) { this.objectGroup.remove(this.mesh); if (this.textureLoaded) { var t = this.mesh.material.map; t && t.dispose(); } else { cancelLoad(this); } this.mesh.material.dispose(); //o.disposeMeshMaterial(this.mesh), this.mesh.geometry.dispose(); this.mesh = void 0; } this.meshAdded = !1, this.textureLoaded = !1; //this.texURL && this.texURL.includes('testdata') && console.log('removeObject3D', this.id, 'hasMesh',hasMesh, this.texURL.split('map_tiles/')[1] ) } removeChildren() { for (var t = 0, e = this.children; t < e.length; t++) { var n = e[t]; n && (n.removeObject3D(), n.removeChildren()); } this.children.length = 0; } cancelChildren() { //子集全部停止加载 for (var t = 0, e = this.children; t < e.length; t++) { var n = e[t]; n && (cancelLoad(n, '提前'), n.cancelChildren()); } } } proj4.defs("EPSG:3857", "+title=WGS 84 / Pseudo-Mercator +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs"); //这里地图世界的中心是不是lon:0,lat:0 class TiledMapOpenStreetMap extends TiledMapBase { constructor(mapLayer, tileColor) { //Potree.settings.mapCompany = 'google' super('map', mapLayer, tileColor /* , projection */); //EPSG projection //this.baseUrl = "https://wprd03.is.autonavi.com/appmaptile?style=7&x=${x}&y=${y}&z=${z}", //this.baseUrl = "https://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x=${x}&y=${y}&z=${z}" //最高只到18 level this.switchStyle(); this.tileSizePx = 256; this.mapSizeM = 40075017; //总占据多少米(地球赤道周长) 和三维空间的不一样 - -, 空间上的是直径,地图上的是半个圆周 this.bias = 0.5; if (Potree.settings.mapCompany == 'google') { this.attribution = "© PopSmart, © 谷歌地图"; this.projection = "EPSG:900913"; //"EPSG:4326"//4550 } else { this.attribution = "© PopSmart, © 高德地图"; this.projection = "EPSG:3857"; } } getTileUrl(t, e, n) { return this.baseUrl.replace(/\${z}/, t.toString(10)).replace(/\${x}/, e.toString(10)).replace(/\${y}/, n.toString(10)); } switchStyle() { var style = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'standard'; //if(Potree.settings.mapCompany == 'google')return if (style == this.style) return; if (Potree.settings.mapCompany == 'google') { var [lang, glPos] = { 'zh': ["zh-CN", "cn"], 'en': ["en-US"], //范围大所以不指定地理位置 。 'ja': ["ja-JP", "JP"], 'ko': ["ko-KR", "KR"] }[Potree.settings.language] || []; this.baseUrl = "https://mt2.google.com/vt/lyrs=" + (style == 'satellite' ? "y" : "m") + "@159000000" + (lang ? "&hl=" + lang : '') + (glPos ? "&gl=" + glPos : '') + "&x=${x}&y=${y}&z=${z}&s=mt1"; this.maxDepth = 22; /* 1)lyrs= 表示的是图层类型,即瓦片类型,具体含义如下: m:路线图 t:地形图 p:带标签的地形图 s:卫星图 y:带标签的卫星图 h:标签层(路名、地名等) 2)& gl=CN 指定地理区域 谷歌地图针对中国有两套坐标,一套做了偏移,一套没有。经测试在url加入gl=cn地图会有偏移。 Tips:如果谷歌地图和RTK测量的WGS84坐标有偏差,可以尝试在url里去掉& gl=cn。(摘自网上) 通义千问:如果不指定gl参数,Google将使用默认值或基于其他因素(如IP地址)来推断用户的地理区域。这通常不会导致地图数据的不准确性,但可能会影响本地化信息的显示。地图上的标签(如街道名称、城市名称等)可能不会以最合适的语言显示。地址格式和拼写可能不符合当地标准 5)&hl= 设置地图注记文字语言类型,缺省默认为中文。 hl=nl 中英双语 hl=zh-CN 中文 */ } else { //baseUrl = "https://webst01.is.autonavi.com/appmaptile?lang=zh_cn&style=6&yrs=m&x=${x}&y=${y}&z=${z}" //卫星 maxDepth = 18 //搜索高德地图瓦片url if (Potree.settings.isJiangMen) { if (style == 'satellite') { //卫星 this.maxDepth = 18; this.baseUrl = "http://a.map.jms.gd/tile/weixing/${z}/${x}/${y}.png"; } else { this.maxDepth = 19; this.baseUrl = "http://a.map.jms.gd/tile/gd_xiangtu/${z}/${x}/${y}.png"; } } else { if (style == 'satellite') { //卫星 this.maxDepth = 18; this.baseUrl = "https://webst01.is.autonavi.com/appmaptile?lang=zh_cn&style=6&yrs=m&x=${x}&y=${y}&z=${z}"; } else if (style == 'dark-standard') { this.maxDepth = 18; this.baseUrl = "https://wprd01.is.autonavi.com/appmaptile?lang=zh_cn&style=8&yrs=m&x=${x}&y=${y}&z=${z}"; //路网 加上scl=2后去掉名字 } else { this.maxDepth = 19; this.baseUrl = "https://wprd04.is.autonavi.com/appmaptile?lang=zh_cn&style=7&yrs=m&x=${x}&y=${y}&z=${z}"; // } } //详解 https://www.cnblogs.com/lucio110/p/17310054.html } this.style = style; this.setEnable(false); this.setEnable(true); viewer.dispatchEvent('content_changed'); } } class TiledMapFromEntity extends TiledMapBase { constructor(mapLayer, tileColor, data) { super('floorplan', mapLayer, tileColor, "LOCAL" /* "EPSG:3857" */ /* "WGS84" */); //直接就是本地坐标,没有projec var entity = this.tiledMapEntity = this.fillFromData(data); var time = entity.updateTime || entity.createTime; this.tileSizePx = entity.tileSizePx, this.mapSizeM = entity.mapSizeM, this.maxDepth = entity.maxDepth; this.postStamp = time ? time.replace(/[^0-9]/ig, '') : new Date().getTime(); //this.projection = n.crsLocal, this.zIndex = 0, this.tilePresenceMap = this.decodeBitStream(this.tiledMapEntity.quadtree); //包含tile分裂信息,如果写错了会造成tile显示不全 this.maxLoading = 5; this.bias = 0.5; //越大加载层级越低,越模糊 if (window.devicePixelRatio >= 2 && window.innerHeight * window.innerWidth < 768 * 1024) { //手机还是加载高清点(反正也不需要截图等待),但平板太大了,要铺满屏幕可能慢,所以稍微模糊点?(反正可以继续放大去看) this.bias = 0; //level更高些 } } fillFromData(e) { var data = {}; data.id = e.id; data.globalLocation = Potree.Utils.VectorFactory.fromArray3(e.location); data.orientation = Potree.Utils.QuaternionFactory.fromArray(e.orientation); var pointcloud = viewer.scene.pointclouds.find(p => p.dataset_id == e.datasetId); if (pointcloud.datasetData.mapping) { data.filePath = "".concat(Potree.settings.urls.prefix1, "/").concat(pointcloud.datasetData.mapping).concat(e.file_path); } else { data.filePath = "".concat(Potree.settings.urls.prefix1).concat(e.file_path); } data.fileName = '$DEPTH/$X/$Y.png'; data.type = e.type, data.mapSizeM = e.map_size_m, data.tileSizePx = e.tile_size_px, data.maxDepth = e.max_depth, data.quadtree = e.quadtree, data.floorId = e.floor_id, data.bundleId = e.bundle_id; //this.computeLocalCoordinates() return data; } computeLocalCoordinates() { if (proj4.defs("LOCAL_MAP")) { var lonlat = this.tiledMapEntity.globalLocation; /* if(window.AMapWith84){//需要转换 lonlat = AMapWith84.wgs84ToAMap(lonlat) } */ lonlat = viewer.transform.lonlatToLocal.forward(lonlat); this.tiledMapEntity.location = new Vector3().copy(lonlat); } } updateProjection() { super.updateProjection(); if (!this.position) { this.computeLocalCoordinates(); } /* this.projection = this.TransformService.crsLocal, t.prototype.updateProjection.call(this) */ } get position() { return this.tiledMapEntity.location; /* enumerable: !0, configurable: !0 */ } get quaternion() { return this.tiledMapEntity.orientation; /* enumerable: !0, configurable: !0 */ } getTileUrl(t, e, n) { var i = (this.tiledMapEntity.filePath + "/" + this.tiledMapEntity.fileName).replace(/\$DEPTH/g, t.toString(10)).replace(/\$X/g, e.toString(10)).replace(/\$Y/g, n.toString(10)); return i += "?t=" + this.postStamp; //this.RestService.addAuthorizationQueryParameter(i) //???? } decodeBitStream(t) { if (!t) return { empty: !0 }; for (var e = {}, n = [e], i = 0; i < t.length; i++) { var r = n.shift(), o = parseInt(t.substr(i, 1), 16); if (1 & o) { var a = {}; r[0] = a, n.push(a); } 2 & o && (a = {}, r[1] = a, n.push(a)), 4 & o && (a = {}, r[2] = a, n.push(a)), 8 & o && (a = {}, r[3] = a, n.push(a)); } var s = { empty: !0 }; return this.computeHashes(s, e, ""), s; } computeHashes(t, e, n) { for (var i = 0; i < 4; i++) e[i] && (t[n + i.toString(10)] = !0, t.empty = !1, this.computeHashes(t, e[i], n + i.toString(10))); } } /* note: 目前缩小了能看出形态是一个地球。相机在高空朝下观测,地球平放着。 所以越靠近赤道和地球朝上的那面所在的中央经度(也就是local 0,0,0所对应的初始经度),tile越接近正方形。 所以在两极地区要怎么显示? 注册地理坐标时需要滚动地球吗?(修改初始经度、重定义NAVVIS:TMERC, 就需要更新所有三维世界中的物体位置) 切换中心点: var locationLonLat = viewer.transform.lonlatToLocal.inverse(viewer.mapViewer.camera.position.clone()) proj4.defs("LOCAL_MAP", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat.x.toPrecision(15) + " +lat_0=" + locationLonLat.y.toPrecision(15)); viewer.mapViewer.mapLayer.maps[0].transformMapToLocal = null 地理注册部分地图上的1和2标记有两层意思。当地图全屏展示时,标记的是当前右侧经纬度的位置;当地图为小窗时,标记的是对应场景里三维位置。(所以感觉最好换一个ui?)且在2023.2.1之前才改好,之前都是后者。 为什么边缘总是有奇怪的mesh,是因为有顶点到背面了吗 https://lbs.amap.com/tools/picker 高德坐标拾取器(手机登录),但和这里展示的不一样, 要用AMapWith84.aMapToWgs84({x: ,y: })转成84。 (qq or 手机登录) 所以potree本地和有AMapWith84函数的laser地图展现不一样 https://www.google.com/maps/@77.7730021,-34.4952712,4z google取点 打印所有mapTile的名字,字符串最长的代表有显示的mesh。 viewer.mapViewer.mapLayer.maps[0].baseTile.traverse(function(e){console.log(e.name)}) 能查看有几个显示的mesh viewer.mapViewer.mapLayer.maps[0].objectGroup.children 图片地址中 tiles/4/3/9.png 第一个数字越高代表level越高,放得越大 . (tile.name.length也能反映出 viewer.mapViewer.mapLayer.maps[1].objectGroup.children.map(e=>e.name.length-1) 目前看的几个场景floorplan原图是1米=33.03个像素 图宽度= 512*2^(max_depth-1) , map_size_m 代表整个地图是多少米 经纬度精度小数点后5位为米级别,6位为分米,7位是厘米 */ /** * @author mschuetz / http://mschuetz.at * * adapted from THREE.OrbitControls by * * @author qiao / https://github.com/qiao * @author mrdoob / http://mrdoob.com * @author alteredq / http://alteredqualia.com/ * @author WestLangley / http://github.com/WestLangley * @author erich666 / http://erichaines.com * * * */ var Buttons = Potree.defines.Buttons; class FirstPersonControls extends EventDispatcher { constructor(viewer, viewport) { var _this; super(); _this = this; this.viewer = viewer; this.renderer = viewer.renderer; this.scene = viewer.scene; this.rotationSpeed = 200; this.moveSpeed = 10; this.setCurrentViewport({ hoverViewport: viewport, force: true }); //this.currentViewport = viewport this.keys = { FORWARD: ['W'.charCodeAt(0), 38], BACKWARD: ['S'.charCodeAt(0), 40], LEFT: ['A'.charCodeAt(0), 37], RIGHT: ['D'.charCodeAt(0), 39], UP: ['Q'.charCodeAt(0)], DOWN: ['E'.charCodeAt(0)], //SHIFT : [16], ALT: [18], SPACE: [32], Rotate_LEFT: ['L'.charCodeAt(0)], Rotate_RIGHT: ['J'.charCodeAt(0)], Rotate_UP: ['K'.charCodeAt(0)], Rotate_DOWN: ['I'.charCodeAt(0)] }; this.fadeFactor = 20; this.yawDelta = 0; this.pitchDelta = 0; this.translationDelta = new Vector3(0, 0, 0); this.translationWorldDelta = new Vector3(0, 0, 0); this.tweens = []; this.dollyStart = new Vector2(); this.dollyEnd = new Vector2(); //this.enableChangePos = true this.viewer.addEventListener('camera_changed', e => { if (this.viewer.name == 'mapViewer' || e.changeInfo && e.changeInfo.positionChanged && !viewer.mainViewport.view.isFlying()) { this.setFPCMoveSpeed(e.viewport); } }); var drag = e => { if (!this.enabled) return; var viewport = e.dragViewport; if (!viewport) return; var camera = viewport.camera; var mode; if (e.isTouch) { if (e.touches.length == 1) { mode = !e.dragViewport || e.dragViewport.name == 'MainView' ? 'rotate' : 'pan'; } else if (e.touches.length == 2) { mode = Potree.settings.displayMode == 'showPanos' ? 'scale' : 'pan-scale'; } else { mode = !e.dragViewport || e.dragViewport.name == 'MainView' ? 'pan' : 'scale'; } } else { //mode = e.buttons === Buttons.LEFT && (!e.dragViewport || e.dragViewport.name == 'MainView') ? 'rotate' : 'pan' mode = e.buttons === Buttons.LEFT && camera.type != 'OrthographicCamera' ? 'rotate' : 'pan'; } //console.log('mode ', mode ) var moveSpeed = this.currentViewport.getMoveSpeed(); if (e.drag.startHandled === undefined) { ///??????? e.drag.startHandled = true; this.dispatchEvent({ type: 'start' }); } if (mode.includes('rotate')) { //旋转 //来自panoramaControl updateRotation if (!this.pointerDragStart) { return this.pointerDragStart = e.pointer.clone(); } var view = this.scene.view; if (this.rotateStartInfo.rotAroundPoint) { //定点旋转: 以当前intersect的点为target旋转,不改点在屏幕中的位置 var distance = camera.position.distanceTo(this.rotateStartInfo.rotCenter /* this.intersectStart.location */); //不按下ctrl的话 var posDir = new Vector3().subVectors(this.rotateStartInfo.rotCenter, view.position); if (posDir.dot(view.direction) < 0) distance *= -1; //在背面 //按照orbitControl的方式旋转: var rotationSpeed = 2; this.yawDelta -= e.drag.pointerDelta.x * rotationSpeed; this.pitchDelta += e.drag.pointerDelta.y * rotationSpeed; /* //旋转方向和偏移量尽量和在漫游点处旋转方式的一样 this.yawDelta += e.drag.pointerDelta.x / 500 * viewport.resolution.x this.pitchDelta -= e.drag.pointerDelta.y / 500 * viewport.resolution.y */ //先更新一下相机: this.update(); view.applyToCamera(camera); //然后得到新的相机角度下,原先点在屏幕中的位置所对应的3d点现在的坐标。只需要平移一下新旧坐标差值即可。//感觉貌似也可以用project和unproject后的差值的方式,还不用判断z背面 var newPointerDir = viewer.inputHandler.getMouseDirection(this.rotateStartInfo.rotCenter2d).direction.clone().multiplyScalar(distance); var pivot = new Vector3().addVectors(camera.position, newPointerDir); //新的3d点 var moveVec = new Vector3().subVectors(pivot, this.rotateStartInfo.rotCenter); this.translationWorldDelta.copy(moveVec.negate()); //立即更新下,防止因update和此drag频率不同而打滑。 this.update(); view.applyToCamera(camera); } else { var _matrixWorld = camera.matrixWorld; camera.matrixWorld = new Matrix4(); //unproject 前先把相机置于原点 var e1 = new Vector3(this.pointerDragStart.x, this.pointerDragStart.y, -1).unproject(camera), t = new Vector3(e.pointer.x, e.pointer.y, -1).unproject(camera), i = Math.sqrt(e1.x * e1.x + e1.z * e1.z), n = Math.sqrt(t.x * t.x + t.z * t.z), o = Math.atan2(e1.y, i), a = Math.atan2(t.y, n); this.pitchDelta += o - a; //上下旋转 e1.y = 0, t.y = 0; var s = Math.acos(e1.dot(t) / e1.length() / t.length()); if (!isNaN(s)) { var yawDelta = s; //左右旋转 this.pointerDragStart.x > e.pointer.x && (yawDelta *= -1); this.yawDelta += yawDelta; } //console.log('rotate:', this.pitchDelta, e.pointer.toArray(), this.pointerDragStart.toArray()) this.pointerDragStart.copy(e.pointer); camera.matrixWorld = _matrixWorld; } } if (mode.includes('pan')) { //平移 if (!this.canMovePos(viewport)) { return; } if (camera.type == "OrthographicCamera") { //console.log(e.drag.pointerDelta, e.pointer, e.drag.end) var _moveVec = Utils.getOrthoCameraMoveVec(e.drag.pointerDelta, camera); //最近一次移动向量 var pointclouds; var Alignment = window.viewer.modules.Alignment; var MergeEditor = window.viewer.modules.MergeEditor; var handleState = Alignment.handleState; //右键平移视图、左键操作点云 var _a = e.buttons === Buttons.LEFT && viewport.alignment && handleState && viewport.alignment[handleState]; if (Potree.settings.editType == 'pano') { var PanoEditor = window.viewer.modules.PanoEditor; if (_a && PanoEditor.selectedPano) { if ( /* !PanoEditor.selectedGroup || */!PanoEditor.checkIfAllLinked({ group: PanoEditor.selectedGroup })) { if (handleState == 'translate' && (e.drag.intersectStart.pointclouds && Common.getMixedSet(PanoEditor.selectedClouds, e.drag.intersectStart.pointclouds).length || PanoEditor.selectedPano.hovered) //平移时 拖拽到点云上 或 circle。(其中点云只需要intersect的点云中包含选择的点云中之一即可) || handleState == 'rotate') //旋转模式不需要intersect { pointclouds = PanoEditor.selectedClouds; } } else { PanoEditor.dispatchEvent('needToDisConnect'); console.warn('选中的漫游点连通了整个数据集,不允许移动'); } } if (!pointclouds && e.buttons === Buttons.LEFT && viewport.rotateSide) { //侧视图 (有时候会卡顿,是mousemove执行延迟了,一般发生在突然加载很多点云时) //console.log('rotateSide', -e.drag.pointerDelta.x ) return PanoEditor.rotateSideCamera(-e.drag.pointerDelta.x); } } else if (Potree.settings.editType == 'merge') { if (e.buttons === Buttons.LEFT && viewport.rotateSide) { return MergeEditor.rotateSideCamera(-e.drag.pointerDelta.x); } } else { /* if(Alignment.selectedClouds && Alignment.selectedClouds.length){//多个点云 pointclouds = a && e.drag.intersectStart.pointclouds && Common.getMixedSet(Alignment.selectedClouds, e.drag.intersectStart.pointclouds).length && Alignment.selectedClouds }else{ */ //pointclouds = a && e.drag.intersectStart.pointcloud && [e.drag.intersectStart.pointcloud] //} if (_a && e.drag.intersectStart.pointcloud) { pointclouds = [e.drag.intersectStart.pointcloud]; if (e.drag.intersectStart.pointcloud.dataset_id == Potree.settings.originDatasetId) { var p = e.drag.intersectStart.pointclouds.find(p => p.dataset_id != Potree.settings.originDatasetId); if (p) pointclouds = [p]; } } } if (pointclouds) { if (handleState == 'translate' && viewport.alignment.translateVec) { //只能沿某个方向移动 _moveVec.projectOnVector(viewport.alignment.translateVec); } this.dispatchEvent({ type: "transformPointcloud", intersect: e.intersect.orthoIntersect, intersectStart: e.drag.intersectStart.orthoIntersect, moveVec: _moveVec, pointclouds, camera }); } else { this.translationWorldDelta.add(_moveVec.negate()); } } else { //perspectiveCamera: if (e.drag.intersectStart) { //如果拖拽着点云 var ifInit = e.drag.z == void 0; var pointerStartPos2d = e.drag.intersectStart.location.clone().project(camera); //识别到的点云点的位置 e.drag.z = pointerStartPos2d.z; //记录z,保持拖拽物体到屏幕距离不变,所以z深度不变(如果拖拽过程中没有缩放,这个z其实不变) if (ifInit) { //拖拽开始 e.drag.projectionMatrixInverse = camera.projectionMatrixInverse.clone(); //防止吸附到最近点上(因为鼠标所在位置并非识别到的点云点的位置,需要得到鼠标所在位置的3d坐标。) var pointerStartPos2dReal = new Vector3(this.pointerDragStart.x, this.pointerDragStart.y, e.drag.z); e.drag.translateStartPos = pointerStartPos2dReal.clone().unproject(camera); //console.log('开始拖拽', e.pointer.clone()) } //拖拽的过程中将projectionMatrixInverse替换成开始拖拽时的,因为near、far一直在变,会导致unproject计算出的3d坐标改变很大而闪烁。 var _projectionMatrixInverse = camera.projectionMatrixInverse; camera.projectionMatrixInverse = e.drag.projectionMatrixInverse; var newPos2d = new Vector3(e.pointer.x, e.pointer.y, e.drag.z); var newPos3d = newPos2d.clone().unproject(camera); var _moveVec2 = newPos3d.clone().sub(e.drag.translateStartPos /* e.drag.intersectStart.location */); //移动相机,保持鼠标下的位置永远不变,所以用鼠标下的新位置减去鼠标下的原始位置 camera.projectionMatrixInverse = _projectionMatrixInverse; this.translationWorldDelta.copy(_moveVec2.negate()); //这里没法用add,原因未知,打开console时会跳动 //console.log('pan 1', this.translationWorldDelta.clone()) //四指松开剩三指时会偏移一下,暂不知道哪里的问题,或许跟开头防止点云吸附有关? } else { //如果鼠标没有找到和点云的交点,就假设移动整个模型(也可以去扩大范围寻找最近点云) /* let center = viewer.scene.pointclouds[0].position; let radius = camera.position.distanceTo(center); let ratio = radius * Math.tan(THREE.Math.degToRad(camera.fov)/2) / 1000 */ /* let speed = this.currentViewport.getMoveSpeed() if(FirstPersonControls.boundPlane){ speed = FirstPersonControls.boundPlane.distanceToPoint(this.currentViewport.position) speed = Math.max(1 , speed) } */ var lastIntersect = this.target || viewport.lastIntersect && (viewport.lastIntersect.location || viewport.lastIntersect); //该viewport的最近一次鼠标和点云的交点 if (!lastIntersect || !(lastIntersect instanceof Vector3)) lastIntersect = viewer.bound.center; var speed = camera.position.distanceTo(lastIntersect); var fov = cameraLight.getHFOVForCamera(camera, true); var ratio = speed * Math.tan(fov / 2); this.translationDelta.x -= e.drag.pointerDelta.x * ratio; this.translationDelta.z -= e.drag.pointerDelta.y * ratio; //console.log('pan2', e.drag.pointerDelta) } } this.useAttenuation = false; } if (mode.includes('scale')) { //触屏缩放 this.dollyEnd.subVectors(e.touches[0].pointer, e.touches[1].pointer); //if(!this.dollyStart)return var scale = this.dollyEnd.length() / this.dollyStart.length(); var pointer = new Vector2().addVectors(e.touches[0].pointer, e.touches[1].pointer).multiplyScalar(0.5); //两个指头的中心点 dolly({ pointer, scale, camera, drag: e.drag }); this.dollyStart.copy(this.dollyEnd); } //最好按ctrl可以变为dollhouse的那种旋转 }; var drop = e => { if (!this.enabled) return; this.dispatchEvent({ type: 'end' }); }; var dolly = function dolly() { var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (Potree.settings.displayMode == 'showPanos' && _this.currentViewport == viewer.mainViewport /* this.currentViewport.unableChangePos */) { //全景时 _this.dispatchEvent({ type: 'dollyStopCauseUnable', delta: e.delta, scale: e.scale }); return; } var camera = e.camera; if (camera.type == "OrthographicCamera") { var ratio; if (e.delta != void 0) { //滚轮缩放 if (e.delta == 0) { //mac return; } else if (e.delta < 0) { ratio = 0.9; } else if (e.delta > 0) { ratio = 1.12; //增加的需要比减少的多一些,否则缩放相同次数下,r0 * ([1+s)(1-s)]^n = r0 * (1-s^2)^n < r0 } } else { ratio = e.scale; //触屏缩放 } var zoom = camera.zoom * ratio; var limit = camera.zoomLimit; if (limit) zoom = MathUtils.clamp(zoom, limit.min, limit.max); var pointerPos = new Vector3(e.pointer.x, e.pointer.y, 0.5); var oldPos = pointerPos.clone().unproject(camera); if (camera.zoom != zoom) { camera.zoom = zoom; camera.updateProjectionMatrix(); } var newPos = pointerPos.clone().unproject(camera); //定点缩放, 恢复一下鼠标所在位置的位置改变量 var moveVec = new Vector3().subVectors(newPos, oldPos); _this.translationWorldDelta.add(moveVec.negate()); _this.useAttenuation = false; } else { var speed = _this.currentViewport.getMoveSpeed() * 7, direction; if (e.delta != void 0) { //滚轮缩放 if (e.delta == 0) return; //mac /*if(this.target && !e.intersect){//如果没有intersect点云且有target的话,就朝target的方向. 但无限靠近时有问题,且到背面时前进却是后退 direction = new THREE.Vector3().subVectors(this.target, camera.position).normalize() }else{ */ direction = _this.viewer.inputHandler.getMouseDirection().direction; //定点缩放 if (e.intersect && e.intersect.location) { //和intersect的墙越接近,速度越慢,便于focus细节 var dis = camera.position.distanceTo(e.intersect.location); speed = MathUtils.clamp(dis * 0.1, 0.3, speed); } if (e.delta < 0) { speed *= -1; } var slightly = _this.keys.ALT.some(e => _this.viewer.inputHandler.pressedKeys[e]); slightly && (speed *= 0.2); _this.useAttenuation = true; } else { //触屏缩放 direction = _this.viewer.inputHandler.getMouseDirection(e.pointer).direction; //定点缩放 if (e.drag.intersectStart) { //和intersect的墙越接近,速度越慢,便于focus细节 var _dis = camera.position.distanceTo(e.drag.intersectStart.location); var r = 1 - 1 / e.scale; var closeMin = 0.1, standardMin = 0.001, disBound1 = 2, disBound2 = 5; if (math.closeTo(e.scale, 1, 0.03)) { //如果偏差小于0.01,就不限制最小值,因为平移容易正负抖动,近距离有最小值的话抖动明显 closeMin = 0; //所以若缩放不明显(双指滑动慢),就不设置最低值。(这时候穿越障碍物会比较困难。) } //console.log('closeMin',closeMin) var min = math.linearClamp(_dis, [disBound1, disBound2], [closeMin, standardMin]); //触屏和滚轮不一样,触发较为连续,所以最小值设低一点。若要保持双指相对点云位置不变,理想最小值是0,但那样就无法穿越点云(最小值太小的话穿越密集点云如树丛很困难;太大会打滑)所以当离点云近时增大最小值 speed = Math.sign(r) * MathUtils.clamp(_dis * Math.abs(r), min, speed); //console.log(speed, dis, e.scale) } else { _this.useAttenuation = true; var accelerate = 40; if (math.closeTo(e.scale, 1, 0.02)) { //缩放小的时候很可能是双指平移时,容易抖动,所以降低移动速度 accelerate *= Math.min(40 * Math.abs(e.scale - 1), 0.8); } // console.log('accelerate',accelerate) var constantDis = _this.currentViewport.getMoveSpeed() * accelerate; //constantDis = 10;//常量系数,当放大一倍时前进的距离。可以调整 speed = (e.scale - 1) * constantDis; } } var vec = direction.multiplyScalar(speed); //this.translationWorldDelta.copy(vec) _this.translationWorldDelta.add(vec); //console.log(direction.toArray(), speed, e.scale) } return true; }; var scroll = e => { if (!this.enabled || !e.hoverViewport) return; this.setCurrentViewport(e); e.camera = e.hoverViewport.camera; dolly(e); }; var dblclick = e => { if (!this.enabled) return; if (!Potree.settings.dblToFocusPoint) return; //调试时才可双击 if (Potree.settings.displayMode == 'showPointCloud' /* !viewer.images360.isAtPano() */) this.zoomToLocation(e.mouse); }; this.viewer.addEventListener('global_drag', drag); /* this.viewer.addEventListener('global_touchmove', (e)=>{ if(!this.enabled)return if(e.touches.length>1){//单指的就触发上一句 //console.log('global_touchmove' ) drag(e) } }); */ this.viewer.addEventListener('global_drop', drop); this.viewer.addEventListener('global_mousewheel', scroll); this.viewer.addEventListener('global_dblclick', dblclick); var prepareScale = e => { //触屏的scale this.dollyStart.subVectors(e.touches[0].pointer, e.touches[1].pointer); e.drag.camDisToPointStart = null; }; var prepareRotate = e => { this.pointerDragStart = e.pointer.clone(); if (e.viewer.name != 'mainViewer') return; var intersect = e.intersect || e.dragViewport.lastIntersect; //在数据集外部时绕中心点旋转,在数据集内部时绕intersect点旋转(其他数据集的点也可以) 或者 原地旋转镜头 var rotAroundPoint = Potree.settings.rotAroundPoint && e.dragViewport.camera.type != 'OrthographicCamera' && (viewer.atDatasets.length == 0 || intersect) && this.canMovePos(viewport) && !viewer.images360.isAtPano() && !this.viewer.inputHandler.pressedKeys[32]; var rotCenter2d, rotCenter; if (rotAroundPoint) { var pivotType = this.target ? 'target' : viewer.atDatasets.length > 0 ? 'intersect' : viewer.inputHandler.selection.length ? 'selection' : this.target2 ? 'target2' : 'boundCenter'; rotCenter = pivotType == 'target' ? this.target : pivotType == 'intersect' ? intersect.location : pivotType == 'selection' ? viewer.inputHandler.selection[0].position : pivotType == 'target2' ? this.target2 : viewer.bound && viewer.bound.center; if (rotCenter) { rotCenter2d = rotCenter.clone().project(e.dragViewport.camera); //点在屏幕中的位置。 若z>1 则在背面 或 超出far范围 } else { rotAroundPoint = false; } } this.rotateStartInfo = { rotAroundPoint, //定点旋转 rotCenter, rotCenter2d }; //缺点:多数据集绕中心点转很难操作,感觉可以也改为绕lastIntersect //console.log('prepareRotate' ) }; var preparePan = e => { //触屏的pan点云 还是会偏移 this.pointerDragStart = e.pointer.clone(); e.drag.z = void 0; //清空 drag(e); //触屏点击时更新的pointer直接用一次drag //console.log('preparePan ' ) }; this.viewer.addEventListener('global_mousedown' /* 'startDragging' */, e => { if (!this.enabled) return; this.setCurrentViewport(e); prepareRotate(e); }); //注意,每次增减指头都会修改pointer,需要更新下状态 this.viewer.addEventListener('global_touchstart', e => { if (!this.enabled) return; if (e.touches.length == 2) { //只监听开头两个指头 prepareScale(e); preparePan(e); } else if (e.touches.length >= 3) { preparePan(e); } }); this.viewer.addEventListener('global_touchend', e => { //e.touches是剩余的指头 if (!this.enabled) return; if (e.touches.length == 2) { //停止平移,开始scale prepareScale(e); preparePan(e); } else if (e.touches.length == 1) { //停止scale,开始rotate prepareRotate(e); } else if (e.touches.length >= 3) { //重新准备下平移(因为抬起的指头可能包含平移使用的数据),否则抬起时漂移 preparePan(e); } }); /* this.viewer.addEventListener('enableChangePos', (e)=>{ if(!this.enabled)return this.enableChangePos = e.canLeavePano }) */ } canMovePos(viewport) { if (viewport == viewer.mainViewport && (Potree.settings.displayMode == 'showPanos' || viewer.images360.bumping || viewer.images360.latestToPano)) return false;else return true; } setEnable(enabled) { this.enabled = enabled; if (!enabled) { this.yawDelta = this.pitchDelta = 0; this.translationDelta.set(0, 0, 0); this.translationWorldDelta.set(0, 0, 0); } } setTarget(target, index) { //绕该点旋转,类似orbitControl if (index == 2) this.target2 = target;else this.target = target; } setFPCMoveSpeed(viewport) { if (viewport.camera.type == 'OrthographicCamera') { var s = 1 / viewport.camera.zoom; viewport.setMoveSpeed(s); } else { //根据和漫游点的最短距离算moveSpeed。缺点:对于导入的无漫游点的数据集没有意义。 if (viewport == viewer.mainViewport && viewer.images360) { var position = viewer.mainViewport.view.position; var speed; var pano = viewer.images360.findNearestPano(); if (!pano) { if (!viewer.bound || viewer.bound.boundSize.x == 0) return; var boundFloor = viewer.bound.boundingBox.clone(); boundFloor.max.z = boundFloor.min.z; speed = boundFloor.distanceToPoint(viewer.mainViewport.view.position); speed = Math.sqrt(speed) / 50; } else { var dis = pano.position.distanceTo(position); var minSpeed = 0.05, minDis = 3, multiplier = 0.005; speed = dis <= minDis ? minSpeed : minSpeed + (dis - minDis) * multiplier; //console.log('dis', dis, 'speed', speed, pano.id ) } viewer.setMoveSpeed(speed * 2); } //调试场景t-FhDWmV5xur 两个数据集,大的数据集没有漫游点。 } } setCurrentViewport() { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; //add if (!this.enabled && !o.force) return; if (o.hoverViewport && this.currentViewport != o.hoverViewport) { this.currentViewport = o.hoverViewport; //this.viewer.setMoveSpeed(this.currentViewport.radius/100); this.setFPCMoveSpeed(this.currentViewport); } if (this.currentViewport.camera.type == 'OrthographicCamera') { this.lockElevationOri = true; this.lockRotation = true; } else { this.lockElevationOri = false; this.lockRotation = false; } } setScene(scene) { this.scene = scene; } stop() { this.yawDelta = 0; this.pitchDelta = 0; this.translationDelta.set(0, 0, 0); } zoomToLocation(mouse) { if (!this.enabled) return; var camera = this.scene.getActiveCamera(); /* let I = Utils.getMousePointCloudIntersection( mouse, camera, this.viewer, this.scene.pointclouds); */ var I = this.viewer.inputHandler.intersect; if (!I) { return; } var targetRadius = 0; { var minimumJumpDistance = 0.2; var domElement = this.renderer.domElement; var ray = Utils.mouseToRay(this.viewer.inputHandler.pointer, camera); var { origin, direction } = this.viewer.inputHandler.getMouseDirection(); var raycaster = new Raycaster(); raycaster.ray.set(origin, direction); var nodes = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, ray); var nodes2 = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, raycaster.ray); var lastNode = nodes[nodes.length - 1]; var radius = lastNode.getBoundingSphere(new Sphere()).radius; targetRadius = Math.min(this.scene.view.radius, radius); targetRadius = Math.max(minimumJumpDistance, targetRadius); } var d = this.scene.view.direction.multiplyScalar(-1); var cameraTargetPosition = new Vector3().addVectors(I.location, d.multiplyScalar(targetRadius)); // TODO Unused: let controlsTargetPosition = I.location; var animationDuration = 600; var easing = TWEEN.Easing.Quartic.Out; { // animate var value = { x: 0 }; var tween = new TWEEN.Tween(value).to({ x: 1 }, animationDuration); tween.easing(easing); this.tweens.push(tween); var startPos = this.scene.view.position.clone(); var targetPos = cameraTargetPosition.clone(); var startRadius = this.scene.view.radius; var _targetRadius = cameraTargetPosition.distanceTo(I.location); tween.onUpdate(() => { var t = value.x; this.scene.view.position.x = (1 - t) * startPos.x + t * targetPos.x; this.scene.view.position.y = (1 - t) * startPos.y + t * targetPos.y; this.scene.view.position.z = (1 - t) * startPos.z + t * targetPos.z; this.scene.view.radius = (1 - t) * startRadius + t * _targetRadius; this.viewer.setMoveSpeed(this.scene.view.radius / 2.5); }); tween.onComplete(() => { this.tweens = this.tweens.filter(e => e !== tween); }); tween.start(); } } update() { var delta = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; if (!this.enabled) return; //console.log('update') var view = this.currentViewport.view; { // cancel move animations on user input var changes = [this.yawDelta, this.pitchDelta, this.translationDelta.length(), this.translationWorldDelta.length()]; var changeHappens = changes.some(e => Math.abs(e) > 0.001); if (changeHappens && this.tweens.length > 0) { this.tweens.forEach(e => e.stop()); this.tweens = []; } } { // accelerate while input is given var ih = this.viewer.inputHandler; var moveForward = this.keys.FORWARD.some(e => ih.pressedKeys[e]); var moveBackward = this.keys.BACKWARD.some(e => ih.pressedKeys[e]); var moveLeft = this.keys.LEFT.some(e => ih.pressedKeys[e]); var moveRight = this.keys.RIGHT.some(e => ih.pressedKeys[e]); var moveUp = this.keys.UP.some(e => ih.pressedKeys[e]); var moveDown = this.keys.DOWN.some(e => ih.pressedKeys[e]); var rotateLeft = this.keys.Rotate_LEFT.some(e => ih.pressedKeys[e]); var rotateRight = this.keys.Rotate_RIGHT.some(e => ih.pressedKeys[e]); var rotateUp = this.keys.Rotate_UP.some(e => ih.pressedKeys[e]); var rotateDown = this.keys.Rotate_DOWN.some(e => ih.pressedKeys[e]); this.lockElevation = this.lockElevationOri || this.keys.SPACE.some(e => ih.pressedKeys[e]); var slightly = this.keys.ALT.some(e => ih.pressedKeys[e]); if (!this.lockRotation) { if (rotateLeft) { this.yawDelta -= 0.01; } else if (rotateRight) { this.yawDelta += 0.01; } if (rotateUp) { this.pitchDelta -= 0.01; } else if (rotateDown) { this.pitchDelta += 0.01; } } if (this.canMovePos(this.currentViewport) && !this.lockKey) { if (this.lockElevation) { var dir = view.direction; dir.z = 0; dir.normalize(); if (moveForward && moveBackward) { this.translationWorldDelta.set(0, 0, 0); } else if (moveForward) { this.translationWorldDelta.copy(dir.multiplyScalar(this.currentViewport.getMoveSpeed())); } else if (moveBackward) { this.translationWorldDelta.copy(dir.multiplyScalar(-this.currentViewport.getMoveSpeed())); } } else { if (moveForward && moveBackward) { this.translationDelta.y = 0; } else if (moveForward) { this.translationDelta.y = this.currentViewport.getMoveSpeed() * (slightly ? 0.2 : 1); } else if (moveBackward) { this.translationDelta.y = -this.currentViewport.getMoveSpeed() * (slightly ? 0.2 : 1); } } if (moveLeft && moveRight) { this.translationDelta.x = 0; } else if (moveLeft) { this.translationDelta.x = -this.currentViewport.getMoveSpeed(); } else if (moveRight) { this.translationDelta.x = this.currentViewport.getMoveSpeed(); } if (moveUp && moveDown) { this.translationWorldDelta.z = 0; } else if (moveUp) { this.translationWorldDelta.z = this.currentViewport.getMoveSpeed(); } else if (moveDown) { this.translationWorldDelta.z = -this.currentViewport.getMoveSpeed(); } if (moveUp || moveDown || moveForward || moveBackward) { this.useAttenuation = false; } } } { // apply rotation var yaw = view.yaw; var pitch = view.pitch; yaw += this.yawDelta; /* * delta; */ pitch += this.pitchDelta; /* * delta; */ view.yaw = yaw; view.pitch = pitch; if (this.yawDelta || this.pitchDelta) { view.cancelFlying('rotate'); } this.yawDelta = 0; this.pitchDelta = 0; } /* if(this.translationWorldDelta.length()>0) { // console.log('translationDelta') } */ { // apply translation view.translate(this.translationDelta.x, /* * delta, */ this.translationDelta.y, /* * delta, */ this.translationDelta.z /* * delta */); this.translationDelta.set(0, 0, 0); //if(this.translationWorldDelta.length())console.log(translationWorldDelta) view.translateWorld(this.translationWorldDelta.x /* * delta */, this.translationWorldDelta.y /* * delta */, this.translationWorldDelta.z /* * delta */); //this.translationWorldDelta.set(0,0,0) } {// set view target according to speed //view.radius = 1 * this.currentViewport.getMoveSpeed(); /* if(viewer.bound) view.radius = view.position.distanceTo(viewer.bound.center) let speed = view.radius/100; this.viewer.setMoveSpeed(speed); */ //this.setMoveSpeed() } if (this.useAttenuation) { //只有滚轮缩放时开启 var attenuation = Math.max(0, 1 - this.fadeFactor * delta); /*this.yawDelta *= attenuation; this.pitchDelta *= attenuation; this.translationDelta.multiplyScalar(attenuation);*/ this.translationWorldDelta.multiplyScalar(attenuation); } else { this.translationWorldDelta.set(0, 0, 0); } } } ; /** * @author mschuetz / http://mschuetz.at * * */ var { Buttons: Buttons$1 } = Potree.defines; class InputHandler extends EventDispatcher { constructor(viewer, scene) { super(); this.viewer = viewer; this.renderer = viewer.renderer; this.domElement = this.renderer.domElement; this.enabled = true; this.scene = scene; this.interactiveScenes = []; this.interactiveObjects = new Set(); this.inputListeners = []; this.blacklist = new Set(); this.drag = null; this.mouse = new Vector2(0, 0); //add: this.pointer = new Vector2(0, 0); //交互点的屏幕坐标,有别于DOM坐标,在此存放NDC坐标。(NDC,三维常用坐标系,二维坐标,整个屏幕映射范围(-1,1),屏幕中心为原点,+Y朝上,+X朝右) this.mouseDownMouse = new Vector2(0, 0); this.selection = []; this.hoveredElements = []; this.pressedKeys = {}; this.wheelDelta = 0; this.speed = 1; this.logMessages = false; if (this.domElement.tabIndex === -1) { this.domElement.tabIndex = 2222; } this.lastPointerUpTime = 0; this.touches = []; this.interactHistory = { move: 0 }; //add this.hoverViewport = viewer.viewports[0]; this.domElement.addEventListener('contextmenu', event => { event.preventDefault(); }, false); this.domElement.addEventListener('click', this.onMouseClick.bind(this), false); this.domElement.addEventListener('mousedown', this.onMouseDown.bind(this), false); window.addEventListener('mouseup', this.onMouseUp.bind(this), false); if (Potree.isIframeChild) { //子页面的话在父页面也要加侦听(应该不会有多层吧?否则要一直加到最外层) //window.parent.addEventListener('mouseup', this.onMouseUp.bind(this), false); //可能跨域 //window.parent.postMessage('listenMouseup', '*'); window.addEventListener('mouseout', this.onMouseUp.bind(this), false); //cancel drag } this.domElement.addEventListener('mouseout', () => { this.containsMouse = false; }, false); this.domElement.addEventListener('mousemove', this.onMouseMove.bind(this), false); //add /* this.domElement.addEventListener("pointerout", this.onMouseUp.bind(this)), this.domElement.addEventListener("pointercancel", this.onMouseUp.bind(this)), */ this.domElement.addEventListener('mousewheel', this.onMouseWheel.bind(this), false); this.domElement.addEventListener('DOMMouseScroll', this.onMouseWheel.bind(this), false); // Firefox //this.domElement.addEventListener('dblclick', this.onDoubleClick.bind(this)); //因为双击时间间隔是跟随系统的所以不好判断 window.addEventListener('keydown', this.onKeyDown.bind(this)); //原先是this.domElement,这样的话一开始要点击屏幕后才能监听到 window.addEventListener('keyup', this.onKeyUp.bind(this)); window.addEventListener('blur', this.onKeyUp.bind(this)); //add this.domElement.addEventListener('touchstart', this.onTouchStart.bind(this)); this.domElement.addEventListener('touchend', this.onTouchEnd.bind(this)); this.domElement.addEventListener('touchmove', this.onTouchMove.bind(this)); { this.measuring = []; //正在编辑的measure //let mesureInfo = new THREE.EventDispatcher() this.addEventListener('measuring', e => { //true优先级高于false, 正在添加时dropMarker也不会停止 //Potree.Utils.updateVisible(mesureInfo, e.situation, e.v, 0, e.v?'add':'cancel' )//借用该函数,使true优先级高于false,防止正在添加时dropMarker而停止 if (e.v) { this.measuring.includes(e.object) || this.measuring.push(e.object); } else { var index = this.measuring.indexOf(e.object); index > -1 && this.measuring.splice(index, 1); } if (this.measuring.length == 0 && this.measuring.length > 0) { this.viewer.viewports.forEach(viewport => { this.collectClosePoints(viewport, true); //forceUpdate }); } //console.log('measuring',e.v, e.cause, e.situation, this.measuring.length ) }); } window.viewer.addEventListener('loopStart', () => { this.interactHistory = {}; //清空 }); } /* addInputListener (listener) { this.inputListeners.push(listener); } removeInputListener (listener) { this.inputListeners = this.inputListeners.filter(e => e !== listener); } getSortedListeners(){ return this.inputListeners.sort( (a, b) => { let ia = (a.importance !== undefined) ? a.importance : 0; let ib = (b.importance !== undefined) ? b.importance : 0; return ib - ia; }); } */ //统一跟第一个触碰的viewport相同 updateTouchesInfo(e) { var viewport, pointer, camera; var oldTouches = this.touches; var changedTouches = Array.from(e.changedTouches); var touches = Array.from(e.touches); this.touches = touches.map(touch => { var touch_ = oldTouches.find(a => a.touch.identifier == touch.identifier); var pointer = touch_ && touch_.pointer; //复制原先的值 return { touch, pointer }; }); if (e.touches.length > 0) { var newTouches = touches.filter(e => !oldTouches.some(a => a.touch.identifier == e.identifier) && !changedTouches.some(a => a.identifier == e.identifier)); //从按钮处划过时e.touches中会出现this.touches和changedTouches中都没有的identifier if (newTouches.length > 0) { console.warn('has new', newTouches.map(e => e.identifier)); } newTouches.concat(changedTouches).forEach(touch => { //修改changedTouches的 var touch_ = this.touches.find(a => a.touch.identifier == touch.identifier); if (touch_) { var a = this.getPointerInViewport(touch.pageX, touch.pageY, this.dragViewport || viewport, new Vector2()); touch_.pointer = a.pointer.clone(); viewport = a.viewport; camera = a.camera; } }); //使用当前touches的平均 if (e.touches.length > 1) { var pageX = Common.average(e.touches, "pageX"); var pageY = Common.average(e.touches, "pageY"); var a = this.getPointerInViewport(pageX, pageY, viewport, new Vector2()); this.pointer.copy(a.pointer); //console.log('updateTouchesInfo', this.pointer.clone()) } else { this.pointer = this.touches[0].pointer.clone(); //更新,使用当前touches中的第一个 } /* if(this.touches.find(e=>!e.pointer)){ console.error(' touches has no pointer', oldTouches.map(e=>e.touch.identifier), Array.from(e.touches).map(e=>e.identifier), Array.from(e.changedTouches).map(e=>e.identifier) ) } */ //console.log(this.touches) //console.log('更新pointer1',this.pointer.toArray()) return { viewport, camera /* , pointer:this.pointer */ }; } } onTouchStart(e) { if (this.logMessages) console.log(this.constructor.name + ': onTouchStart'); e.preventDefault(); /* if (e.touches.length === 1 || !this.drag) { //!this.drag代表一次性下了两个指头 let rect = this.domElement.getBoundingClientRect(); let x = e.touches[0].pageX let y = e.touches[0].pageY this.dealPointerDown(x,y,e,true) }else{ this.updateTouchesInfo(e) this.drag.end.copy(this.pointer) } */ this.dealPointerDown(e, true); this.viewer.dispatchEvent($.extend(this.getEventDesc(e, true), { type: 'global_' + e.type, changedTouches: e.changedTouches })); /* console.log('targetTouches :', Array.from(e.targetTouches).map(e=>'| identifier: '+ e.identifier), 'changedTouches :', Array.from(e.changedTouches).map(e=>'| identifier: '+ e.identifier) ) */ //console.log('') } onTouchMove(e) { if (this.logMessages) console.log(this.constructor.name + ': onTouchMove'); e.preventDefault(); /* if (e.touches.length === 1) { let rect = this.domElement.getBoundingClientRect(); let x = e.touches[0].pageX; let y = e.touches[0].pageY; }else{ this.updateTouchesInfo(e) this.drag.pointerDelta.subVectors(this.pointer, this.drag.end) this.drag.end.copy(this.pointer) } */ this.dealPointerMove(e, true); this.viewer.dispatchEvent($.extend(this.getEventDesc(e, true), { type: 'global_' + e.type, changedTouches: e.changedTouches })); /* console.log('targetTouches :', Array.from(e.targetTouches).map(e=>'| identifier: '+ e.identifier), 'changedTouches :', Array.from(e.changedTouches).map(e=>'| identifier: '+ e.identifier) ) */ } onTouchEnd(e) { if (this.logMessages) console.log(this.constructor.name + ': onTouchEnd'); e.preventDefault(); //console.log('onTouchEnd') this.updateTouchesInfo(e); /* if (e.touches.length === 0) { let rect = this.domElement.getBoundingClientRect(); let x = e.changedTouches[0].pageX //万一一次松开两个指头的怎么办 let y = e.changedTouches[0].pageY this.dealPointerUp(x,y,e,true) }else { this.drag.end.copy(this.pointer) } */ this.dealPointerUp(e, true); this.viewer.dispatchEvent($.extend(this.getEventDesc(e, true), { type: 'global_' + e.type })); //console.log('touchend length '+e.touches.length, this.touches.length) } onKeyDown(e) { if (this.logMessages) console.log(this.constructor.name + ': onKeyDown'); if (e.target.nodeName == 'INPUT' || e.target.nodeName == 'TEXTAREA') return; //正在输入文字 或e.srcElement if (!this.containsMouse) return; //在别的ui上无效 // DELETE /* if (e.keyCode === KeyCodes.DELETE && this.selection.length > 0) { this.dispatchEvent({ type: 'delete', selection: this.selection }); this.deselectAll(); } */ this.dispatchEvent({ type: 'keydown', keyCode: e.keyCode, event: e }); // for(let l of this.getSortedListeners()){ // l.dispatchEvent({ // type: "keydown", // keyCode: e.keyCode, // event: e // }); // } this.pressedKeys[e.keyCode] = true; // e.preventDefault(); } onKeyUp(e) { if (this.logMessages) console.log(this.constructor.name + ': onKeyUp'); if (e.keyCode != void 0) { delete this.pressedKeys[e.keyCode]; } else { this.pressedKeys = {}; } e.preventDefault(); } onDoubleClick(e) { if (this.logMessages) console.log(this.constructor.name + ': onDoubleClick'); var consumed = false; for (var hovered of this.hoveredElements) { if (hovered._listeners && hovered._listeners['dblclick']) { hovered.object.dispatchEvent({ type: 'dblclick', mouse: this.mouse, object: hovered.object }); consumed = true; break; } } if (!consumed) { /* for (let inputListener of this.getSortedListeners()) { inputListener. */ this.viewer.dispatchEvent({ type: 'global_dblclick', mouse: this.mouse, object: null }); //} } this.needSingleClick = false; //add e.preventDefault(); } onMouseClick(e) { if (this.logMessages) console.log(this.constructor.name + ': onMouseClick'); e.preventDefault(); } dealPointerDown(e, isTouch) { e.preventDefault(); //重新获取一下pointer, 因点击了浏览器的按钮展开列表时 move回来不会触发onmousemove,所以pointer是旧的 if (isTouch) { var { camera, viewport } = this.updateTouchesInfo(e); if (this.drag) { //因为触屏在按下前缺少pointermove所以要更新下 this.drag.end = this.pointer.clone(); } } else { var { camera, viewport } = this.getPointerInViewport(e.clientX, e.clientY); } this.dragViewport = this.hoverViewport = viewport; //if(isTouch || !Potree.settings.intersectWhenHover ){ if (isTouch || !this.dragViewport.view.isFlying() && Potree.settings.intersectWhenHover && Potree.settings.editType != 'pano') { //漫游点编辑如果拖拽前getIntersect旋转会延迟 //isTouch必须更新 否则是旧的 this.hoveredElements = this.getHoveredElements(); var dontIntersect = false; this.intersect = this.getIntersect({ viewport, dontIntersect, clientX: e.clientX, clientY: e.clientY }); //更新intersect,避免在没有mousemove但flyToPano后intersect未更新。 //this.intersect = this.getWholeIntersect() } if (!viewport) return; //why add this? if (!this.drag) { var target = (isTouch || e.button == MOUSE.LEFT) && this.hoveredElements.find(el => //只有左键能拖拽 el.object._listeners && el.object._listeners['drag'] && el.object._listeners['drag'].length > 0); if (target) { this.startDragging(target.object, { location: target.point }); } else { this.startDragging(null); } } this.drag.intersectStart = this.intersect; if (!isTouch || e.touches.length == 1) { var consumed = false; var consume = () => { return consumed = true; }; //if (this.hoveredElements.length === 0) { this.viewer.dispatchEvent($.extend(this.getEventDesc(e, isTouch), { type: 'global_mousedown' })); for (var hovered of this.hoveredElements) { var object = hovered.object; object.dispatchEvent({ type: 'mousedown', viewer: this.viewer, consume: consume }); if (consumed) { break; } } } this.mouseDownMouse = this.mouse.clone(); this.pointerDownTime = Date.now(); } onMouseDown(e) { if (this.logMessages) console.log(this.constructor.name + ': onMouseDown'); this.dealPointerDown(e); } /* getWholeIntersect(hoveredElements, intersectPoint){//add hoveredElements = hoveredElements || this.hoveredElements intersectPoint = intersectPoint || this.intersectPoint if(Potree.settings.intersectOnObjs && hoveredElements[0] && hoveredElements[0].object.isModel){ return {//模拟点云的intersectPoint的结构写法 hoveredElement : hoveredElements[0] , location: hoveredElements[0].point, point: {normal: hoveredElements[0].face.normal }, distance: hoveredElements[0].distance, object: hoveredElements[0].object } }else return intersectPoint } */ getEventDesc(e, isTouch) { //搜集dispatchEvent要给的一般数据 var o = { viewer: this.viewer, mouse: this.mouse, pointer: this.pointer, drag: this.drag, isTouch, dragViewport: this.dragViewport, hoverViewport: this.hoverViewport, // button: isTouch ? 0 : e.button, //intersectPoint:this.intersectPoint, hoveredElement: this.hoveredElements[0], intersect: this.intersect //this.getWholeIntersect() , //可能包含mesh上的,针对融合页面 }; if (e) { o.isAtDomElement = e.target == this.domElement; } if (isTouch) { o.touches = this.touches; } else if (e) { o.button = e.button; o.buttons = e.buttons; } return o; } dealPointerUp(e, isTouch) { if (!this.drag) { // 在canvas外mousedown return; } this.drag.end.copy(this.pointer); if (isTouch && e.touches.length >= 1) { return; } var now = Date.now(); if (this.logMessages) console.log(this.constructor.name + ': onMouseUp'); e.preventDefault(); var pressDistance = this.mouseDownMouse.distanceTo(this.mouse); var pressTime = now - this.pointerDownTime; var noMovement = this.drag.pointerDelta.length() == 0; //this.getNormalizedDrag().length() === 0; var consumed = false; var consume = () => { return consumed = true; }; //if (this.hoveredElements.length === 0) { /* for (let inputListener of this.getSortedListeners()) { inputListener */ this.viewer.dispatchEvent($.extend(this.getEventDesc(e, isTouch), { type: 'global_mouseup', pressDistance, consume })); /* if(consumed){//?? break; } */ //} //} if (this.hoveredElements.length > 0) { var hovered = this.hoveredElements.map(e => e.object).find(e => e._listeners && e._listeners['mouseup']); if (hovered) { hovered.dispatchEvent({ type: 'mouseup', viewer: this.viewer, consume: consume }); } } if (this.drag) { //拖拽结束 if (this.drag.object /* && e.button == THREE.MOUSE.LEFT */) { //add LEFT if (this.logMessages) console.log("".concat(this.constructor.name, ": drop ").concat(this.drag.object.name)); this.drag.object.dispatchEvent($.extend(this.getEventDesc(e, isTouch), { type: 'drop', pressDistance })); } else { this.viewer.dispatchEvent($.extend(this.getEventDesc(e, isTouch), { type: 'global_drop', pressDistance })); } // check for a click if (pressDistance < Potree.config.clickMaxDragDis && pressTime < Potree.config.clickMaxPressTime && !e.unableClick) { var clickElement, _consumed = false; if (this.hoveredElements) { clickElement = this.hoveredElements.find(e => e.object._listeners['click']); if (clickElement) { var canceled; var cancel = () => { return canceled = true; }; //console.log('clickElement',clickElement) if (this.logMessages) console.log("".concat(this.constructor.name, ": click ").concat(clickElement.name)); clickElement.object.dispatchEvent($.extend(this.getEventDesc(e, isTouch), { type: 'click', pressDistance, cancel })); if (canceled) { //比如只需要右键的话,可以忽视左键的点击 clickElement = null; } } } var selectable; if ( /* !consumed && */!this.fixSelection) { if (e.button === MOUSE.LEFT) { //if (noMovement) { selectable = this.hoveredElements.find(el => el.object._listeners && el.object._listeners['select']); if (selectable) { selectable = selectable.object; if (this.isSelected(selectable)) { this.deselectAll(); } else { this.deselectAll(); this.toggleSelection(selectable); } _consumed = true; //add } else { if (this.selection.length > 0) _consumed = true; //add 取消选择后,阻断后续 this.deselectAll(); } //} } else if (e.button === MOUSE.RIGHT /* && noMovement */) { this.deselectAll(); } } var _consume = () => { return _consumed = true; }; var desc = this.getEventDesc(e, isTouch); if (!_consumed) { this.viewer.dispatchEvent($.extend(desc, { type: 'global_click', pressDistance, clickElement: clickElement /* || selectable */, consume: _consume })); } //增加 单击: this.needSingleClick = true; _consumed || setTimeout(() => { if (this.needSingleClick) { this.viewer.dispatchEvent($.extend(desc, { type: 'global_single_click', pressDistance, clickElement })); } }, Potree.config.doubleClickTime + 1); //自行执行双击: if (now - this.lastClickTime < Potree.config.doubleClickTime) { this.onDoubleClick(e); } this.lastClickTime = now; } this.drag = null; } this.dragViewport = null; } onMouseUp(e) { this.dealPointerUp(e); } getPointerInViewport(clientX, clientY, viewForceAt, pointer) { var rect = this.domElement.getBoundingClientRect(); var x = clientX - rect.left; var y = clientY - rect.top; var camera; var viewport; pointer = pointer || this.pointer; //if(this.viewer.viewports || viewForceAt){ var getDimension = view => { var left = Math.ceil(this.domElement.clientWidth * view.left), bottom = Math.ceil(this.domElement.clientHeight * view.bottom), width = Math.ceil(this.domElement.clientWidth * view.width), height = Math.ceil(this.domElement.clientHeight * view.height), top = this.domElement.clientHeight - bottom - height; return { left, bottom, width, height, top }; }; var getView = (view, left, bottom, width, height, top) => { this.mouse.set(x - left, y - top); Utils.convertScreenPositionToNDC(pointer, this.mouse, width, height); //console.log('更新pointer2',this.pointer.toArray()) camera = view.camera; viewport = view; }; if (viewForceAt) { var { left: _left, bottom: _bottom, width: _width, height: _height, top: _top } = getDimension(viewForceAt); getView(viewForceAt, _left, _bottom, _width, _height, _top); } else { var length = this.viewer.viewports.length; //var getif = false for (var i = 0; i < length; i++) { var view = this.viewer.viewports[i]; if (!view.active) continue; var { left, bottom, width, height, top } = getDimension(view); if (x >= left && x <= left + width && y >= top && y <= top + height) { getView(view, left, bottom, width, height, top); //getif = true break; } } } return { camera, viewport, pointer }; } ifBlockedByIntersect() { var { point, margin = 0, cameraPos, pickWindowSize, pano, useDepthTex, viewport } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; //某点是否被遮挡(不允许camera修改位置, 因为depthTex不好置换) viewport = viewport || this.hoverViewport || viewer.mainViewport; var intersect = this.getIntersect({ viewport, onlyGetIntersect: true, pickWindowSize, useDepthTex, point, cameraPos, pano }); var cameraPos_ = !cameraPos && pano ? pano.position : cameraPos || viewport.view.position; if (intersect && intersect.distance + margin <= point.distanceTo(cameraPos_)) { return intersect; //被遮挡 } //点云模式,对没加载出的点云不准确。 尤其是需要修改相机位置时,因临时修改并不能使点云加载。 } collectClosePoints(viewport, forceUpdate) { //获取吸附点 if (!Potree.settings.adsorption) return; var point2ds = []; //吸附测量线端点 viewer.scene.measurements.forEach(e => { if (this.measuring.includes(e)) return; //不吸附到正在拖拽的自身 point2ds.push(...e.getPointsPos2d(viewport, forceUpdate)); }); return point2ds; } getIntersect() { var { viewport, onlyGetIntersect, pickWindowSize, dontIntersect, usePointcloud, useDepthTex, cameraPos, point, pano, clientX, clientY } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; // usePointcloud:必须使用点云 var intersect, intersectPoint, intersectOnModel, allElements; var camera = viewport.camera; var raycaster; viewer.addTimeMark('getIntersect', 'start'); var getByDepthTex = () => { var intersect; if (point) { var _cameraPos = pano ? pano.position : camera.position; var _dir = new Vector3().subVectors(point, _cameraPos).normalize(); intersect = { dir: _dir }; } else { intersect = Utils.getIntersect(camera, [viewer.images360.cube], this.pointer, raycaster); } intersectPoint = viewer.images360.depthSampler.sample(intersect, pano, !!point); //可能不准确, 因pano可能未加载depthTex if (intersectPoint && Potree.settings.depTexLocBindDataset) { intersectPoint.pointcloud = (pano || viewer.images360.currentPano).pointcloud; //在全景模式下,虽然深度图上的点可能对应别的pointcloud,但因为是在当前全景图处得到的,所以即使将原本对应的点云移走,该点也不移动是有道理的。它可以永远跟着该全景图。 } }; var getByCloud = () => { var pointer, mouse; if (point) { //指定了目标点,而非只是用pointer所在位置 cameraPos && camera.position.copy(cameraPos); camera.lookAt(point); camera.updateMatrixWorld(); pointer = this.pointer.clone(); mouse = this.mouse.clone(); this.pointer.set(0, 0); //画布中心 this.mouse.set(Math.round(viewport.resolution.x / 2), Math.round(viewport.resolution.y / 2)); } intersectPoint = viewport.noPointcloud || dontIntersect ? null : Utils.getMousePointCloudIntersection(viewport, this.mouse, this.pointer, camera, this.viewer, this.viewer.scene.pointclouds, { pickClipped: true, measuring: this.measuring.length > 0, pickWindowSize, cameraChanged: !!point }); //恢复 if (point) { viewport.view.applyToCamera(camera); this.pointer.copy(pointer); this.mouse.copy(mouse); } }; if (this.measuring.length && Potree.settings.adsorption) { //吸附 var points = this.collectClosePoints(viewport); var points2 = points.filter(e => e.trueSide && e.inSight && math.closeTo(this.mouse, e.posInViewport, Potree.config.measure.adsorptMinDis)); var disArr = points2.map(e => e.pos.distanceToSquared(this.mouse)); var min = points2.slice().sort((a, b) => disArr[points.indexOf(a)] - disArr[points.indexOf(b)]); if (min[0]) { intersect = { //hoveredElement location: min[0].pos3d, //point: {normal: allElements[0].face.normal }, //normal //distance object: min[0].object, adsorption: true }; console.log('找到吸附点', min[0].pos3d, min[0].object.uuid); } } if (!intersect) { var canUseDepthTex = (Potree.settings.displayMode == 'showPanos' || useDepthTex) && viewer.images360.currentPano.pointcloud.hasDepthTex && viewport == viewer.mainViewport && !usePointcloud; if (canUseDepthTex) getByDepthTex();else if (Potree.settings.mergeType2 && Potree.settings.displayMode == 'showPanos' && !viewer.images360.currentPano.pointcloud.isPointcloud) {} //融合页面进入非点云的场景的全景模式不用pick else getByCloud(); /* if(canUseDepthTex && this.measuring.length){ getByDepthTex() }else{ getByCloud() if(!intersectPoint && canUseDepthTex ){ //若在测量,先尝试点云,再用全景 //后来发现有深度图的点云全景visibleNode为空,pick不到的 getByDepthTex() } } */ //console.log(viewport.name , intersectPoint && intersectPoint.location ) if (Potree.settings.intersectOnObjs && !dontIntersect) { if (point) { raycaster = new Raycaster(); var dir = new Vector3().subVectors(point, camera.position).normalize(); raycaster.set(camera.position, dir); //var origin = new THREE.Vector3(pointer.x, pointer.y, -1).unproject(camera), } allElements = this.getHoveredElements(viewer.objs.children, true, raycaster); if (allElements[0]) { var normal; if (allElements[0].object.fileType == '3dgs') { normal = allElements[0].normal; } else { var nor = allElements[0].face && allElements[0].face.normal; if (nor) { var quaternion = new Quaternion(); allElements[0].oriObject.matrixWorld.decompose(new Vector3(), quaternion, new Vector3()); normal = nor.applyQuaternion(quaternion); } } intersectOnModel = { //模拟点云的intersectPoint的结构写法 hoveredElement: allElements[0], location: allElements[0].point, //point: {normal: allElements[0].face.normal }, normal, distance: allElements[0].distance, object: allElements[0].object }; } } if (intersectPoint && intersectOnModel) { if (intersectPoint.distance < intersectOnModel.distance) { intersect = intersectPoint; } else { intersect = intersectOnModel; } } else { intersect = intersectOnModel || intersectPoint; } } if (viewport.camera.type == 'OrthographicCamera' /* == 'mapViewport' */) { var pos3d = new Vector3(this.pointer.x, this.pointer.y, -1).unproject(viewport.camera); //z:-1朝外 if (!intersect) { intersect = {}; } intersect.orthoIntersect = pos3d.clone(); } //记录全部hover到的: if (intersect) { intersect.allElements = allElements; intersect.pointclouds = intersectPoint ? intersectPoint.pointclouds : []; } viewer.addTimeMark('getIntersect', 'end'); //点云费时:2-15ms //深度图费时: 0.1-0.2ms /* intersect && intersect.location && intersect.location.applyMatrix4(viewer.scene.scene.matrix)//add */ if (onlyGetIntersect) { return intersect; } if (intersect) { if (viewer.showCoordType) { //显示坐标位置时 var pos = intersect.point.position.toArray(); if (viewer.showCoordType == "local") {} else if (viewer.showCoordType == "lonlat") { pos = viewer.transform.lonlatToLocal.inverse(pos); } else { pos = viewer.transform.lonlatToLocal.inverse(pos); pos = viewer.transform.lonlatTo4550.forward(pos); } viewer.dispatchEvent({ type: "coordinateChange", pos }); } } //console.log('getIntersect', !!intersectPoint) this.intersect = intersect; intersect && (this.hoverViewport.lastIntersect = intersect); return intersect; } onMouseMove(e) { return this.dealPointerMove(e); } dealPointerMove(e, isTouch) { if (this.interactHistory.move) return; //一帧只触发一次 this.interactHistory.move = 1; if (isTouch) { var { camera, viewport } = this.updateTouchesInfo(e); } else { var { camera, viewport } = this.getPointerInViewport(e.clientX, e.clientY, this.dragViewport); } this.hoverViewport = viewport; if (!viewport) return; //刚变化viewport时会找不到 var isFlying = this.viewer.viewports.some(e => e.view.isFlying()) || viewer.scene.cameraAnimations.some(c => c.onUpdate); var intersect; if (e.onlyGetIntersect || !this.drag || this.drag.object || viewport.alignment) { //没有拖拽物体,但按下鼠标了的话,不intersect。触屏的就能直接避免intersect var dontIntersect = this.drag && viewport.alignment || isFlying || !Potree.settings.intersectWhenHover; // flying 时可能卡顿 //console.log('dontIntersectPointcloud',dontIntersectPointcloud) intersect = this.getIntersect(Object.assign({}, e, { viewport, dontIntersect, clientX: e.clientX, clientY: e.clientY })); //数据集多的时候卡顿 } if (e.onlyGetIntersect) { return intersect; } e.preventDefault(); if (this.drag) { //有拖拽(不一定拖拽了物体, 也不一定按下了鼠标) this.drag.mouse = isTouch ? 1 : e.buttons; //add: //this.drag.pointer = this.pointer.clone(); //this.drag.hoverViewport = this.hoverViewport this.drag.pointerDelta.subVectors(this.pointer, this.drag.end); this.drag.end.copy(this.pointer); var dragConsumed = false; if (this.drag.object && (e.buttons == Buttons$1.NONE || !this.drag.notPressMouse)) { //如果是本不需要按鼠标的拖拽,但按下了鼠标,就不执行这段(改为拖拽场景,如添加测量时突然拖拽画面) if (this.logMessages) console.log(this.constructor.name + ': drag: ' + this.drag.object.name); var refused; this.drag.object.dispatchEvent($.extend(this.getEventDesc(e, isTouch), { type: 'drag', //拖拽物体 refuse: () => { refused = true; } })); if (!refused) dragConsumed = true; viewer.dispatchEvent('content_changed'); } if (!dragConsumed) { if (this.logMessages) console.log(this.constructor.name + ': drag: '); this.viewer.dispatchEvent($.extend(this.getEventDesc(e, isTouch), { type: 'global_drag' //拖拽画面 //consume: () => {dragConsumed = true;} })); } } if (!isTouch || e.touches.length == 1) { if ((!this.drag || this.drag.notPressMouse || Potree.settings.intersectOnObjs && this.drag.object) && !isFlying) { /* let blacklist = this.drag && this.drag */ var hoveredElements = this.getHoveredElements(); if (hoveredElements.length > 0) { var names = hoveredElements.map(h => h.object.name).join(", "); if (this.logMessages) console.log("".concat(this.constructor.name, ": onMouseMove; hovered: '").concat(names, "'")); } var cur = hoveredElements.find(a => a.object); var curr = cur && cur.object; //hoveredElements.map(a => a.object).find(a => true);//只取第一个 var prev = this.lastMouseoverElement; //this.hoveredElements.map(a => a.object).find(a => true); if (curr !== prev) { if (curr) { if (this.logMessages) console.log("".concat(this.constructor.name, ": mouseover: ").concat(curr.name)); curr.dispatchEvent({ type: 'mouseover', object: curr, hoveredElement: cur }); } if (prev) { if (this.logMessages) console.log("".concat(this.constructor.name, ": mouseleave: ").concat(prev.name)); prev.dispatchEvent({ type: 'mouseleave', object: prev }); } this.lastMouseoverElement = curr; viewer.dispatchEvent('content_changed'); } if (hoveredElements.length > 0) { var object = hoveredElements.map(e => e.object).find(e => e._listeners && e._listeners['mousemove']); if (object) { object.dispatchEvent({ type: 'mousemove', object: object }); } } this.hoveredElements = hoveredElements; } //this.intersect = this.getWholeIntersect() this.viewer.dispatchEvent($.extend(this.getEventDesc(e, isTouch), { type: 'global_mousemove' })); this.containsMouse = true; } } onMouseWheel(e) { if (!this.enabled) return; if (this.logMessages) console.log(this.constructor.name + ": onMouseWheel"); e.preventDefault(); var delta = 0; if (e.wheelDelta !== undefined) { // WebKit / Opera / Explorer 9 delta = e.wheelDelta; } else if (e.detail !== undefined) { // Firefox delta = -e.detail; } var ndelta = Math.sign(delta); // this.wheelDelta += Math.sign(delta); if (!this.hoverViewport) { //调试手机版时会无 var { viewport } = this.getPointerInViewport(e.clientX, e.clientY); this.hoverViewport = viewport; } if (this.hoveredElement) { this.hoveredElement.object.dispatchEvent($.extend(this.getEventDesc(e, isTouch), { type: 'mousewheel', delta: ndelta, object: this.hoveredElement.object })); } else { this.viewer.dispatchEvent($.extend(this.getEventDesc(e), { type: 'global_mousewheel', delta: ndelta })); } setTimeout(() => { this.dealPointerMove(e); //add 在更新完view后重新获取intersect 和 drag }, 1); //只延迟1会崩溃吗 } startDragging(object) { var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var name = object ? object.name : "no name"; if (this.logMessages) console.log("".concat(this.constructor.name, ": startDragging: '").concat(name, "'")); this.drag = { start: this.pointer.clone(), end: this.pointer.clone(), pointerDelta: new Vector2(0, 0), object: object, hoverViewport: this.hoverViewport, //会变化 dragViewport: this.hoverViewport //不变 }; if (args) { for (var key of Object.keys(args)) { this.drag[key] = args[key]; } } if (object) { object.dispatchEvent($.extend(this.getEventDesc(), { type: 'startDragging' })); } } /* getMousePointCloudIntersection (mouse) { return Utils.getMousePointCloudIntersection( this.mouse, this.scene.getActiveCamera(), this.viewer, this.scene.pointclouds); } */ toggleSelection(object) { var oldSelection = this.selection; var index = this.selection.indexOf(object); if (index === -1) { this.selection.push(object); object.dispatchEvent({ type: 'select' }); } else { this.selection.splice(index, 1); object.dispatchEvent({ type: 'deselect' }); } this.dispatchEvent({ type: 'selection_changed', oldSelection: oldSelection, selection: this.selection }); viewer.dispatchEvent('content_changed'); } deselect(object) { var oldSelection = this.selection; var index = this.selection.indexOf(object); if (index >= 0) { this.selection.splice(index, 1); object.dispatchEvent({ type: 'deselect' }); this.dispatchEvent({ type: 'selection_changed', oldSelection: oldSelection, selection: this.selection }); } viewer.dispatchEvent('content_changed'); } deselectAll() { for (var object of this.selection) { object.dispatchEvent({ type: 'deselect' }); } var oldSelection = this.selection; if (this.selection.length > 0) { this.selection = []; this.dispatchEvent({ type: 'selection_changed', oldSelection: oldSelection, selection: this.selection }); } viewer.dispatchEvent('content_changed'); } isSelected(object) { var index = this.selection.indexOf(object); return index !== -1; } registerInteractiveObject(object) { this.interactiveObjects.add(object); } removeInteractiveObject(object) { this.interactiveObjects.delete(object); } registerInteractiveScene(scene) { var index = this.interactiveScenes.indexOf(scene); if (index === -1) { this.interactiveScenes.push(scene); } } unregisterInteractiveScene(scene) { var index = this.interactiveScenes.indexOf(scene); if (index > -1) { this.interactiveScenes.splice(index, 1); } } getHoveredElement() { var hoveredElements = this.getHoveredElements(); if (hoveredElements.length > 0) { return hoveredElements[0]; } else { return null; } } getHoveredElements(interactables, dontCheckDis, raycaster) { if (!interactables) { var scenes = this.hoverViewport.interactiveScenes || this.interactiveScenes.concat(this.scene); var interactableListeners = ['mouseup', 'mousemove', 'mouseover', 'mouseleave', 'drag', 'drop', 'click', 'select', 'deselect']; interactables = []; for (var scene of scenes) { scene.traverseVisible(node => { //检测加了侦听的object if (node._listeners && node.visible && !this.blacklist.has(node)) { var hasInteractableListener = interactableListeners.filter(e => { return node._listeners[e] !== undefined; }).length > 0; if (hasInteractableListener) { interactables.push(node); } } }); } } else interactables = interactables.filter(e => e.visible); var camera = this.hoverViewport.camera; if (!raycaster) { var ray = Utils.mouseToRay(this.pointer, camera); raycaster = new Raycaster(); raycaster.ray.set(ray.origin, ray.direction); raycaster.camera = camera; //add } if (camera.type == "OrthographicCamera") { //使无论多远,threshold区域都是一样宽的 raycaster.params.Line.threshold = 20 / camera.zoom; } else { raycaster.params.Line.threshold = 0.04; //相对长度 } raycaster.params.Line2 = { threshold: browser.isMobile() ? 100 : 20 }; //拓宽的lineWidth //raycaster.layers.enableAll()//add var layers = ['sceneObjects', 'mapObjects', 'measure', 'transformationTool', 'model', 'bothMapAndScene']; //设置能识别到的layers(如空间模型里只有mapViewer能识别到marker) if (Potree.settings.mergeType2 && Potree.settings.modelSkybox && Potree.settings.displayMode == 'showPanos' && !viewer.images360.currentPano.pointcloud.hasDepthTex) layers.push('skybox'); //model变成skybox了 Potree.Utils.setCameraLayers(raycaster, layers, this.hoverViewport && this.hoverViewport.extraEnableLayers); //this.hoverViewport.beforeRender && this.hoverViewport.beforeRender() viewer.dispatchEvent({ type: 'raycaster', viewport: this.hoverViewport, raycaster, viewer: this.viewer, interactables }); //add var intersections = raycaster.intersectObjects(interactables, true, null, true); //原本是false 检测不到children var intersectionsCopy = intersections.slice(); if (this.intersect && this.intersect.distance != void 0 && !dontCheckDis) { //add intersections = intersections.filter(e => { if (this.intersect.hoveredElement && this.intersect.hoveredElement.oriObject == e.object) return true; var material = e.object.material; return e.object.pickDontCheckDis || (material.depthTest == false || material.depthWrite == false) && !material.realUseDepth //!material.depthTestWhenPick || (material.useDepth ? e.distance <= this.intersect.distance + material.uniforms.clipDistance.value : e.distance <= this.intersect.distance); //maxClipFactor是否需要考虑? }); } intersections = intersections.map(e => { //add 转化为interactables var object = e.object; do { if (interactables.includes(object)) { e.oriObject = e.object; e.object = object; break; } object = object.parent; } while (object); return e; }); //add for测量线,在检测到sphere时优先选中sphere而非线 //intersections = intersections.sort(function(a,b){return b.object.renderOrder-a.object.renderOrder}) // 降序 intersections = intersections.sort(function (a, b) { var order2 = b.object.pickOrder || 0; var order1 = a.object.pickOrder || 0; return order2 - order1; }); // 降序 //console.log('getHoveredElement ', intersections) return intersections; } /* setScene (scene) { this.deselectAll(); this.scene = scene; } */ update(delta) {} /*getNormalizedDrag () { if (!this.drag) { return new THREE.Vector2(0, 0); } let diff = new THREE.Vector2().subVectors(this.drag.end, this.drag.start); diff.x = diff.x / this.domElement.clientWidth; diff.y = diff.y / this.domElement.clientHeight; return diff; } getNormalizedLastDrag () { if (!this.drag) { return new THREE.Vector2(0, 0); } let mouseDelta = this.drag.mouseDelta.clone(); mouseDelta.x = mouseDelta.x / this.domElement.clientWidth; mouseDelta.y = mouseDelta.y / this.domElement.clientHeight; return mouseDelta; } */ getMouseDirection(pointer) { //add pointer = pointer || this.pointer; var camera = this.hoverViewport.camera; var t = new Vector3(pointer.x, pointer.y, -1).unproject(camera), i = new Vector3(pointer.x, pointer.y, 1).unproject(camera); return { origin: t, direction: i.clone().sub(t).normalize() }; } } class ViewerBase extends EventDispatcher { constructor(domElement) { var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; super(); this.name = args.name; this.renderArea = domElement; this.oldResolution = new Vector2(); this.oldResolution2 = new Vector2(); this.screenSizeInfo = { W: 0, H: 0, pixelRatio: 1, windowWidth: 0, windowHeight: 0 }; this.initContext(args); this.addEventListener('content_changed', () => { //画面改变,需要渲染 this.needRender = true; //console.log('needRender') }); } initContext(args) { //console.log(`initializing three.js ${THREE.REVISION}`); var width = this.renderArea.clientWidth; var height = this.renderArea.clientHeight; var contextAttributes = { alpha: true, //支持透明 depth: true, stencil: false, antialias: !!args.antialias, preserveDrawingBuffer: args.preserveDrawingBuffer || false, powerPreference: "high-performance" }; var canvas = document.createElement("canvas"); var webglVer = Potree.browser.urlHasValue('webgl1') || !window.WebGL2RenderingContext ? 'webgl' : 'webgl2'; //遇到有设备(iphone8 plus ios14.1 型号MQ8F2CH/A)直接获取webgl2后会点云和全景图闪烁,WebGL2RenderingContext和得到的context是undefined。但是为何4dkk不会闪烁 var context = canvas.getContext(webglVer, contextAttributes); if (context && webglVer == 'webgl2') { Potree.settings.isWebgl2 = true; } this.renderer = new WebGLRenderer({ premultipliedAlpha: false, canvas: canvas, context: context }); this.renderer.sortObjects = true; //原先false 打开了renderOrder才奏效 //this.renderer.setSize(width, height); this.renderer.autoClear = args.autoClear || false; //args.clearColor = args.clearColor || '#aa0033' args.clearColor && this.renderer.setClearColor(args.clearColor); this.renderArea.appendChild(this.renderer.domElement); this.renderer.domElement.tabIndex = '2222'; this.renderer.domElement.style.position = 'absolute'; this.renderer.domElement.addEventListener('mousedown', () => { this.renderer.domElement.focus(); }); //this.renderer.domElement.focus(); // NOTE: If extension errors occur, pass the string into this.renderer.extensions.get(x) before enabling // enable frag_depth extension for the interpolation shader, if available var gl = this.renderer.getContext(); gl.getExtension('EXT_frag_depth'); gl.getExtension('WEBGL_depth_texture'); gl.getExtension('WEBGL_color_buffer_float'); // Enable explicitly for more portability, EXT_color_buffer_float is the proper name in WebGL 2 if (gl.createVertexArray == null) { var extVAO = gl.getExtension('OES_vertex_array_object'); if (!extVAO) { throw new Error("OES_vertex_array_object extension not supported"); } gl.createVertexArray = extVAO.createVertexArrayOES.bind(extVAO); gl.bindVertexArray = extVAO.bindVertexArrayOES.bind(extVAO); } /* let oldClear = gl.clear; gl.clear = (bits)=>{ console.error('clear') } */ } updateScreenSize() { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; //有可能需要让viewport来判断,当窗口大小不变但viewport大小变时 if (this.screenshoting && !o.forceUpdateSize) return; //截图时不允许因窗口改变大小而updateScreenSize var render = false, ratio, w, h; //记录应当render的大小 if (o.width != void 0 && o.height != void 0) { w = o.width; h = o.height; render = true; ratio = 1; } else { w = this.renderArea.clientWidth; h = this.renderArea.clientHeight; if (w !== this.screenSizeInfo.W || h !== this.screenSizeInfo.H || o.forceUpdateSize || this.screenSizeInfo.pixelRatio != window.devicePixelRatio) { this.screenSizeInfo.W = w; this.screenSizeInfo.H = h; render = true; this.screenSizeInfo.pixelRatio = window.devicePixelRatio; //如果player放在小窗口了,也要监测devicePixelRatio,因为缩放时client宽高不会改变 //config.isMobile ? (ratio = Math.min(window.devicePixelRatio, 2)) : (ratio = window.devicePixelRatio) ratio = window.devicePixelRatio; } } if (render) { this.setSize(w, h, ratio, o.forTarget); } } setSize(width, height, devicePixelRatio, onlyForTarget) { //console.log('setSize', width) if (!onlyForTarget) { //onlyForTarget表示不更改当前renderer,只是为了rendertarget才要改变viewport this.renderer.setPixelRatio(devicePixelRatio); this.renderer.setSize(width, height); // resize之后会自动clear(似乎因为setScissor ),所以一定要立刻绘制,所以setSize要在cameraChanged、update之前 } //this.composer && this.composer.setSize(width, height); if (this.viewports) { this.viewports.forEach((view, i) => { //if(!view.active)return var width_ = width * view.width; var height_ = height * view.height; view.setResolution(Math.ceil(width_), Math.ceil(height_), width, height); if (height_ == 0) return; //avoid NAN var aspect = width_ / height_; //camera的参数精确些,不用视口的归整的resolution像素值,否则hasChange无法为true, 导致canvasResize了但map没update从而闪烁 view.camera.aspect = aspect; if (view.camera.type == "OrthographicCamera") { /* //不改宽度 同4dkk var heightHalf = view.camera.right / aspect view.camera.top = heightHalf view.camera.bottom = -heightHalf */ //高宽都改 使大小不随视口大小改变 navvis (直接和视口大小一致即可,通过zoom来定大小) view.camera.left = -width_ / 2; view.camera.right = width_ / 2; view.camera.bottom = -height_ / 2; view.camera.top = height_ / 2; } else {} view.camera.updateProjectionMatrix(); }); } if (!onlyForTarget) { //因为onlyForTarget不传递devicePixelRatio所以不发送了 this.dispatchEvent('viewerResize'); this.viewports.forEach(e => { this.ifEmitResize({ viewport: e, deviceRatio: devicePixelRatio }); }); } } ifEmitResize(e) { //切换viewport渲染时, 若这些viewport大小不同就发送一次, 通知一些材质更新resolution。 //console.log('ifEmitResize',e.viewport.name,e.viewport.resolution2 ) if (!e.viewport.resolution.equals(this.oldResolution) || !e.viewport.resolution2.equals(this.oldResolution2)) { this.dispatchEvent($.extend(e, { type: 'resize' })); this.oldResolution.copy(e.viewport.resolution); this.oldResolution2.copy(e.viewport.resolution2); } } cameraChanged() { //判断相机是否改变 var changed = false; /* if(this.needRender){ this.needRender = false return true } */ for (var i = 0, j = this.viewports.length; i < j; i++) { var viewport = this.viewports[i]; var changeInfo = viewport.cameraChanged(); if (changeInfo.changed) { changed = true; //if(!this.changeTime ||this.changeTime<100){ this.dispatchEvent({ type: "camera_changed", camera: viewport.camera, viewport, changeInfo }); //this.changeTime = (this.changeTime || 0) +1 //} viewport.needRender = true; //直接写这咯 if (changeInfo.resolutionChanged) { this.ifEmitResize({ viewport }); //for map } } } return changed; } makeScreenshot(size, viewports, compressRatio) { //暂时不要指定viewports渲染,但也可以 var { width, height } = size; /* let oldBudget = Potree.pointBudget; Potree.pointBudget = Math.max(10 * 1000 * 1000, 2 * oldBudget); let result = Potree.updatePointClouds(this.scene.pointclouds, camera, size ); Potree.pointBudget = oldBudget; this.dispatchEvent({ //resize everything such as lines targets type: 'resize', resolution: new THREE.Vector2(width,height), });*/ var target = new WebGLRenderTarget(width, height, { format: RGBAFormat }); this.setSize(width, height, 1, true); this.render({ target, //camera , viewports: viewports || this.viewports, screenshot: true, width, height, resize: true //需要resize }); var dataUrl = Potree.Utils.renderTargetToDataUrl(target, width, height, this.renderer, compressRatio); /* let pixelCount = width * height; let buffer = new Uint8Array(4 * pixelCount); this.renderer.readRenderTargetPixels(target, 0, 0, width, height, buffer); let dataUrl = Potree.Utils.pixelsArrayToDataUrl(buffer, width, height, compressRatio) */ target.dispose(); //resize back //this.updateScreenSize({forceUpdateSize:true}) return { width, height, dataUrl }; } dispose() { var scene = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.scene; scene.clear(); this.renderer.dispose(); this.renderer.forceContextLoss(); var gl = this.renderer.getContext(); gl.getExtension("WEBGL_lose_context") && gl.getExtension("WEBGL_lose_context").loseContext(); this.renderArea.removeChild(this.renderer.domElement); this.dispatchEvent('dispose'); } } class Viewport extends EventDispatcher { constructor(view, camera) { var prop = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; //目前不支持换camera super(); this.left = prop.left; this.bottom = prop.bottom; this.width = prop.width; this.height = prop.height; this.name = prop.name; this.view = view; this.camera = camera; this.active = true; this.unableChangePos = false; this.noPointcloud; //this.keys = [...] firstPersonCtl.... this.resolution = new Vector2(); this.resolution2 = new Vector2(); this.offset = new Vector2(); //viewportOffset 范围从0-整个画布的像素 this.extraEnableLayers = prop.extraEnableLayers || []; //额外可展示的层 this.cameraLayers = prop.cameraLayers; this.pixelRatio = prop.pixelRatio; //如果规定pixelRatio的话要传,这样就覆盖devicePicelRatio, 如magnifier } clone() { return Common.CloneClassObject(this); } getMoveSpeed() { return this.moveSpeed; } setMoveSpeed(e) { this.moveSpeed = e; } layersAdd(name) { this.extraEnableLayers.includes(name) || this.extraEnableLayers.push(name); } layersRemove(name) { var index = this.extraEnableLayers.indexOf(name); if (index > -1) { this.extraEnableLayers.splice(index, 1); } } cameraChanged() { var copy = () => { this.previousState = { projectionMatrix: this.camera.projectionMatrix.clone(), //worldMatrix在this.control时归零了所以不用了吧,用position和qua也一样 position: this.camera.position.clone(), quaternion: this.camera.quaternion.clone(), active: this.active, resolution: this.resolution.clone(), resolution2: this.resolution2.clone() //有时clientWidth没变但是ratio缩放了 }; }; var projectionChanged = true, positionChanged = true, quaternionChanged = true, activeChanged = true, resolutionChanged = true; var getChanged = () => { return { projectionChanged, positionChanged, quaternionChanged, activeChanged, resolutionChanged, changed: projectionChanged || positionChanged || quaternionChanged || activeChanged || resolutionChanged }; }; if (this.previousState) { projectionChanged = !this.camera.projectionMatrix.equals(this.previousState.projectionMatrix); positionChanged = !this.camera.position.equals(this.previousState.position); quaternionChanged = !this.camera.quaternion.equals(this.previousState.quaternion); activeChanged = this.active != this.previousState.active; resolutionChanged = !this.resolution.equals(this.previousState.resolution) || !this.resolution2.equals(this.previousState.resolution2); } copy(); return getChanged(); } setResolution(w, h) { var wholeW = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var wholeH = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; this.resolution.set(w, h); //是client的width height this.resolution2.copy(this.resolution).multiplyScalar(this.pixelRatio || window.devicePixelRatio); this.offset.set(wholeW, wholeH).multiply(new Vector2(this.left, this.bottom)); //.multiplyScalar(window.devicePixelRatio) this.dispatchEvent({ type: 'resize' }); } } var prefixVertex = "precision highp float;\nprecision highp int;\n\nuniform mat4 modelMatrix;\nuniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nuniform mat4 viewMatrix;\nuniform mat3 normalMatrix;\nuniform vec3 cameraPosition;\n attribute vec3 position;\n attribute vec3 normal;\n attribute vec2 uv;\n"; var prefixFragment = "precision highp float;\nprecision highp int;\n\nuniform mat4 viewMatrix;\nuniform vec3 cameraPosition;\n"; var shader = { uniforms: { opacity: { type: "f" // value: 1 }, progress: { type: "f", value: 0 }, pano0Map: { type: "t", value: null }, pano1Map: { type: "t", value: null }, depthMap0: { type: "t", value: null }, depthMap1: { type: "t", value: null }, pano0Position: { type: "v3", value: new Vector3() }, pano0Matrix: { type: "m4", value: new Matrix4() }, pano1Position: { type: "v3", value: new Vector3() }, pano1Matrix: { type: "m4", value: new Matrix4() }, /* pano1Matrix2: { type: "m4", value: new THREE.Matrix4 }, */ inverseProjectionMatrix: { value: new Matrix4() }, /* projectionMatrix:{//需要再写一遍吗 value: new THREE.Matrix4 }, */ viewport: { value: new Vector4() }, //如 {x: 0, y: 0, z: 428, w: 969} xy应该是offset, zw是宽高 cameraHeight0: { type: "f", value: 1 }, cameraHeight1: { type: "f", value: 1 }, ceilHeight0: { type: "f", value: 2 }, ceilHeight1: { type: "f", value: 2 } }, vertexShader: prefixVertex + "\n\n uniform vec3 pano0Position;\n uniform mat4 pano0Matrix;\n \n uniform vec3 pano1Position;\n uniform mat4 pano1Matrix; \n\n \n varying vec2 vUv; \n varying vec3 vWorldPosition0;\n varying vec3 vWorldPosition1;\n varying vec3 vWorldPosition12;\n \n vec3 transformAxis( vec3 direction ) //navvis->4dkk\n {\n float y = direction.y;\n direction.y = direction.z;\n direction.z = -y;\n return direction;\n }\n \n \n void main() {\n \n vUv = uv;\n vec4 worldPosition = modelMatrix * vec4(position, 1.0);\n \n \n \n vec3 positionLocalToPanoCenter0 = worldPosition.xyz - pano0Position;\n vWorldPosition0 = (vec4(positionLocalToPanoCenter0, 1.0) * pano0Matrix).xyz;\n vWorldPosition0.x *= -1.0;\n vWorldPosition0 = transformAxis(vWorldPosition0);\n \n vec3 positionLocalToPanoCenter1 = worldPosition.xyz - pano1Position;\n vWorldPosition1 = (vec4(positionLocalToPanoCenter1, 1.0) * pano1Matrix).xyz;\n vWorldPosition1.x *= -1.0;\n vWorldPosition1 = transformAxis(vWorldPosition1);\n \n /* \n vec3 positionLocalToPanoCenter12 = worldPosition.xyz - pano1Position;\n vWorldPosition12 = (vec4(positionLocalToPanoCenter12, 1.0) * pano1Matrix2).xyz;\n vWorldPosition12.x *= -1.0;\n vWorldPosition12 = transformAxis(vWorldPosition12);\n */\n \n \n \n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n \n }\n\n ", fragmentShader: prefixFragment + "\n #extension GL_EXT_frag_depth : enable // otherwise error: 'GL_EXT_frag_depth' : extension is disabled\n \n #define PI 3.141592653 \n \n \n uniform float modelAlpha;\n uniform float opacity;\n uniform float progress;\n uniform int tranType;\n uniform vec3 pano0Position;\n uniform vec3 pano1Position;\n uniform float maxDistance;\n uniform float minDistance;\n uniform float minOpa;\n \n \n \n uniform samplerCube pano0Map;\n uniform samplerCube pano1Map;\n \n \n varying vec2 vUv; \n varying vec3 vWorldPosition0;\n varying vec3 vWorldPosition1; \n \n \n /* vec2 getSamplerCoord( vec3 direction ) \n {\n direction = normalize(direction);\n float tx=atan(direction.x,-direction.y)/(PI*2.0)+0.5;\n float ty=acos(direction.z)/PI;\n\n return vec2(tx,ty);\n } */\n\n vec2 getSamplerCoord2( vec3 direction ) \n { \n direction = normalize(direction);\n float tx=atan(direction.x,direction.z)/(PI*2.0)+0.5;\n float ty=acos(direction.y)/PI;\n\n return vec2(tx,ty); \n }\n \n \n #if defined(GL_EXT_frag_depth) && defined(hasDepthTex) \n uniform sampler2D depthMap0;\n uniform sampler2D depthMap1;\n uniform mat4 inverseProjectionMatrix;\n uniform mat4 projectionMatrix;\n uniform vec4 viewport; \n uniform float cameraHeight0;\n uniform float cameraHeight1;\n uniform float ceilHeight0;\n uniform float ceilHeight1;\n \n \n vec2 getDepth(vec3 dir, sampler2D depthMap, float heightDown, float heightUp, vec4 eyePos){\n vec2 depthValue = vec2(0.0, 0.0);\n vec2 uv2 = getSamplerCoord2( dir.xyz); //\u6682\u65F6\u53EA\u7528\u57FA\u4E8E\u76EE\u6807\u6F2B\u6E38\u70B9\u7684\u65B9\u5411\n uv2.x -= 0.25; //\u5168\u666F\u56FE\u548CCube\u7684\u6C34\u5E73\u91C7\u6837\u8D77\u59CB\u5750\u6807\u76F8\u5DEE90\u5EA6\uFF0C\u8FD9\u91CC\u77EB\u6B63 0.25 \u4E2A\u91C7\u6837\u504F\u79FB\n vec4 depth = texture2D(depthMap, uv2);\n //float distance = depth.r + 256. * (depth.g + 256. * depth.b);\n //distance *= 255. * .001; // distance is now in meters\n \n //\u66F4\u6539\n float distance = (depth.g + depth.r / 256.) * 255.; \n \n if(distance == 0.0){//\u6F2B\u6E38\u70B9\u5E95\u90E8\u8BC6\u522B\u4E0D\u5230\u7684\u533A\u57DF\uFF0C\u7ED9\u4E00\u4E2A\u5730\u677F\u9AD8\u5EA6 \n if(uv2.y < depthTexUVyLimit) distance = heightUp / dir.y; \n else if(uv2.y > 1.0 - depthTexUVyLimit) distance = heightDown / -dir.y; \n else distance = 100000.0;//\u7ED9\u4E2A\u8D85\u7EA7\u8FDC\u7684\u503C\n } \n \n if(distance == 0.0)distance = 100000.0;//\u7ED9\u4E2A\u8D85\u7EA7\u8FDC\u7684\u503C\n \n depthValue.x = distance;\n \n distance += .1; // add a safety margin\n\n vec4 eyePos2 = vec4(normalize(eyePos.xyz) * distance, 1.);\n vec4 clipPos2 = projectionMatrix * eyePos2;\n vec4 ndcPos2 = clipPos2 * 1. / clipPos2.w;\n\n \n depthValue.y = 0.5 * ((gl_DepthRange.far - gl_DepthRange.near) * ndcPos2.z\n + gl_DepthRange.near + gl_DepthRange.far); \n \n #if defined(depth_background) \n //\u540E\u6392\u7684 skybox \u4E0D\u80FD\u6321\u4F4Fchunk \n depthValue.y += 0.3;\n #endif\n \n \n \n return depthValue; \n }\n //\u6CE8\uFF1A\u672A\u52A0\u8F7D\u597D\u7684\u8BDD\uFF0Cdepth\u4E3A0\uFF0C\u5BFC\u81F4\u7B2C\u4E00\u6B21\u6F2B\u6E38\u8FC7\u53BB\u7684\u65F6\u5019\u8BB8\u591Amesh\u4F1A\u7ACB\u523B\u88AB\u906E\u6321\uFF0C\u6240\u4EE5\u8981\u786E\u4FDD\u52A0\u8F7D\u5B8C\n #endif\n \n void main()\n {\n vec3 vWorldPosition0N = normalize(vWorldPosition0);\n vec3 vWorldPosition1N = normalize(vWorldPosition1);\n float progress_ = progress;\n \n vec4 colorFromPano0 = vec4(0.0,0.0,0.0,0.0);\n #if defined(usePanoMap0)\n //\u5373progress < 1.0 \u901A\u5E38\u662F1\n colorFromPano0=textureCube(pano0Map,vWorldPosition0N.xyz);\n #else \n progress_ = 1.0;\n #endif\n vec4 colorFromPano1=textureCube(pano1Map,vWorldPosition1N.xyz);\n \n gl_FragColor = mix(colorFromPano0,colorFromPano1,progress_);\n \n \n \n \n //\u6DF1\u5EA6\u56FE\u4FEE\u6539\u6DF1\u5EA6\n \n #if defined(GL_EXT_frag_depth) && defined(hasDepthTex) \n vec4 ndcPos;\n ndcPos.xy = ((2.0 * gl_FragCoord.xy) - (2.0 * viewport.xy)) / (viewport.zw) - 1.;\n ndcPos.z = (2.0 * gl_FragCoord.z - gl_DepthRange.near - gl_DepthRange.far) /\n (gl_DepthRange.far - gl_DepthRange.near);\n ndcPos.w = 1.0;\n\n vec4 clipPos = ndcPos / gl_FragCoord.w;\n vec4 eyePos = inverseProjectionMatrix * clipPos;\n vec2 depth0 = vec2(0.0,0.0); \n #if defined(usePanoMap0)\n depth0 = getDepth(vWorldPosition0N, depthMap0, cameraHeight0, ceilHeight0, eyePos);\n #endif\n vec2 depth1 = getDepth(vWorldPosition1N, depthMap1, cameraHeight1, ceilHeight1, eyePos);\n \n \n gl_FragDepthEXT = mix(depth0.y,depth1.y,progress_); \n gl_FragDepthEXT = clamp(gl_FragDepthEXT, 0.0, 1.0); //\u9632\u6B62\u90E8\u5206\u624B\u673A\u51FA\u73B0\u9ED1\u5757\u3002ios 16 \u3002 \u56E0\u4E3A\u6211\u7ED9\u7684\u8D85\u8FDC\u503C\u8D85\u51FA\u8303\u56F4\n \n\n #endif\n\n \n }\n " }; //注:gl_FragDepthEXT 修改了确实能像真实mesh那样遮挡住在后面的物体。但是为过渡时不能直接像有模型那样,和角度有关。 class ModelTextureMaterial extends RawShaderMaterial { constructor() { var defines = { depthTexUVyLimit: Potree.config.depthTexUVyLimit }; var { vs, fs } = Common.changeShaderToWebgl2(shader.vertexShader, shader.fragmentShader, 'RawShaderMaterial'); super({ fragmentShader: fs, vertexShader: vs, uniforms: UniformsUtils.clone(shader.uniforms), side: DoubleSide, name: "ModelTextureMaterial", defines }); this.glslVersion = Potree.settings.isWebgl2 && '300 es'; var setSize = e => { var viewport = e.viewport; //let viewportOffset = viewport.offset || new Vector2() var resolution = viewport.resolution2; //this.uniforms.viewport.value.set(viewportOffset.x, viewportOffset.y, resolution.x, resolution.y) this.uniforms.viewport.value.set(0, 0, resolution.x, resolution.y); // xy是在viewport中的left和bottom,和整个窗口没有关系,所以不是viewportOffset。几乎都是0,0 }; var viewport = viewer.mainViewport; setSize({ viewport }); viewer.addEventListener('resize', e => { if (e.viewport.name != "MainView") return; setSize(e); }); //var supportExtDepth = !!Features.EXT_DEPTH.isSupported() { //add viewer.addEventListener('camera_changed', e => { if (e.viewport.name != "MainView") return; //this.uniforms.projectionMatrix.value.copy(e.camera.projectionMatrix) e.camera && this.uniforms.inverseProjectionMatrix.value.copy(e.camera.projectionMatrixInverse); }); } var progress = 0; Object.defineProperty(this.uniforms.progress, 'value', { get: function get() { return progress; }, set: e => { if (e < 1 && !Potree.settings.fastTran) { if (!('usePanoMap0' in this.defines)) { this.defines.usePanoMap0 = ''; this.needsUpdate = true; } } else { if ('usePanoMap0' in this.defines) { delete this.defines.usePanoMap0; this.needsUpdate = true; } } progress = e; } }); //------------------------------------- } /** * * @param {Panorama} pano0 * @param {Panorama} pano1 * @param {boolean} flag 更新全景图的材质uniforms */ setProjectedPanos(pano0, pano1, progressValue) { progressValue != void 0 && (this.uniforms.progress.value = progressValue); //pano0.ensureSkyboxReadyForRender(); if (pano0) { this.uniforms.pano0Map.value = pano0.getSkyboxTexture(); //pano0.texture this.uniforms.pano0Position.value.copy(pano0.position); this.uniforms.pano0Matrix.value.copy(pano0.panoMatrix /* pano0.mesh.matrixWorld */); //pano1.ensureSkyboxReadyForRender(); } this.uniforms.pano1Map.value = pano1.getSkyboxTexture(); //pano1.texture; this.uniforms.pano1Position.value.copy(pano1.position); this.uniforms.pano1Matrix.value.copy(pano1.panoMatrix /* pano1.mesh.matrixWorld */); this.pano0 = pano0; this.pano1 = pano1; this.updateDepthTex(pano0); this.updateDepthTex(pano1); //console.log('setProjectedPanos', pano0&&pano0.id, pano1&&pano1.id) this.needsUpdate = true; } updateDepthTex(pano, extra) { if (!Potree.settings.useDepthTex || !pano || !pano.depthTex || pano != this.pano0 && pano != this.pano1) return; //console.log('updateDepthTex', pano.id, this.pano0 && this.pano0.id, this.pano1 && this.pano1.id) if (this.pano0) { this.uniforms.depthMap0.value = this.pano0.entered ? this.pano0.depthTex : null; //dispose了就不要赋值否则dispose会失败 this.uniforms.cameraHeight0.value = this.pano0.floorPosition.distanceTo(this.pano0.position); this.uniforms.ceilHeight0.value = this.pano0.getCeilHeight() - this.pano0.position.z; } if (this.pano1) { this.uniforms.depthMap1.value = this.pano1.depthTex; //pano1还没entered时也需要,可能在飞入 this.uniforms.cameraHeight1.value = this.pano1.floorPosition.distanceTo(this.pano1.position); this.uniforms.ceilHeight1.value = this.pano1.getCeilHeight() - this.pano1.position.z; } this.updateDepthTexEnable(); } updateDepthTexEnable() { if (this.dontChangeDepth) return; var hasDepthTex = this.pano0 && this.pano1 && this.pano0.pointcloud.hasDepthTex && this.pano1.pointcloud.hasDepthTex; //暂时不知道一个有图一个没图怎么写所以 Potree.Utils.addOrRemoveDefine(this, 'hasDepthTex', hasDepthTex ? 'add' : 'remove'); } /* EnableDepthTex(){//开启DepthTex if(this.defines['hasDepthTex']){ return } this.defines['hasDepthTex'] = '' this.needsUpdate = true; } */ } class FastTranPass { constructor(renderer) { this.renderer = renderer; this.coverRenderTarget = new WebGLRenderTarget(100, 100, { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat }); this.coverTex = this.coverRenderTarget.texture; this.enabled = false; /* this.oldClearColor = new THREE.Color(); this.oldClearAlpha = 1; this.camera = new THREE.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); this.scene = new THREE.Scene(); */ this.material = this.getMaskMaterial(); /* var copyShader = THREE.CopyShader; this.materialCopy = new THREE.ShaderMaterial( { uniforms: this.copyUniforms, vertexShader: copyShader.vertexShader, fragmentShader: copyShader.fragmentShader, blending: THREE.NoBlending, depthTest: false, depthWrite: false, transparent: true } ); this.quad = new THREE.Mesh( new THREE.PlaneBufferGeometry( 2, 2 ), this.material); this.quad.frustumCulled = false; // Avoid getting clipped this.scene.add( this.quad ); this.renderToScreen = true*/ } setSize(width, height) { this.coverRenderTarget.setSize(width, height); } start() { this.enabled = true; var { x, y } = viewer.mainViewport.resolution2; this.setSize(x, y); //draw coverTex var oldTarget = this.renderer.getRenderTarget(); //let oldClearColor = this.renderer.getClearColor() this.renderer.setRenderTarget(this.coverRenderTarget); //this.renderer.setClearColor( 0x000000, 0) var oldLayer = viewer.mainViewport.camera.layers.mask; Potree.Utils.setCameraLayers(viewer.mainViewport.camera, ['skybox']); this.renderer.render(viewer.scene.scene, viewer.mainViewport.camera); //this.renderer.setClearColor( 0x000000, 0) this.renderer.setRenderTarget(oldTarget); viewer.mainViewport.camera.layers.mask = oldLayer; this.material.uniforms.progress.value = 1; console.log('start111'); } render(scene, camera, viewports, renderer, writeBuffer, readBuffer) { /* var oldAutoClear = renderer.autoClear; renderer.autoClear = false; */ var { x, y } = viewer.mainViewport.resolution2; var uniforms = this.material.uniforms; //uniforms.bgTex.value = readBuffer.texture; //更新 uniforms.coverTex.value = this.coverTex; uniforms.progress.value = viewer.images360.cube.material.uniforms.progress.value; uniforms.screenRatio.value = x / y; // 使波纹为圆形 uniforms.screenRatio.value *= uniforms.screenRatio.value; Potree.Utils.screenPass.render(viewer.renderer, viewer.images360.fastTranMaskPass.material); //renderer.autoClear = oldAutoClear; } stop() { this.enabled = false; //console.log('stop111') } getMaskMaterial() { return new ShaderMaterial({ uniforms: { coverTex: { type: "t", value: null }, progress: { type: "f", value: 0 }, screenRatio: { type: "f", value: 1 } }, vertexShader: " \n varying vec2 vUv;\n \n void main() \n {\n vUv = uv;\n \n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n } \n \n ", fragmentShader: " \n uniform sampler2D coverTex; \n uniform float progress; \n uniform float screenRatio;\n varying vec2 vUv;\n \n void main() {\n \n const float maxRadius = 0.708; // sqrt(0.5^2+0.5^2)\n const float minRadius = 0.0 ;\n \n float radius = screenRatio>1.0 ? sqrt((vUv.x - 0.5)*(vUv.x - 0.5) + (vUv.y - 0.5)*(vUv.y - 0.5)/screenRatio) : sqrt((vUv.x - 0.5)*(vUv.x - 0.5)*screenRatio+ (vUv.y - 0.5)*(vUv.y - 0.5));\n float diff = 0.292; //1.0-maxRadius;\n float radiusIn = maxRadius * progress + minRadius * (1.0-progress);\n float radiusOut = radiusIn + diff;\n if(radius < radiusIn) {\n \n discard;\n \n }else if(radius>radiusOut){\n gl_FragColor = texture2D(coverTex, vUv) ;\n //gl_FragColor = vec4(1.0,1.0,0.0,1.0);//\n \n }else{\n \n /* vec4 color1 = texture2D(bgTex, vUv);\n vec4 color2 = texture2D(coverTex, vUv);\n float rotio = smoothstep(radiusIn ,radiusOut,radius);\n \n gl_FragColor = mix(color1, color2, rotio); */\n \n float rotio = smoothstep(radiusIn ,radiusOut, radius);\n \n vec4 color2 = texture2D(coverTex, vUv);\n color2.a = rotio;\n \n \n }\n }\n " }); } /* getMaskMaterial(){ return new THREE.ShaderMaterial( { uniforms: { coverTex: { type: "t", value: null }, bgTex: { type: "t", value: null }, progress:{ type: "f", value: 0 }, screenRatio:{ type: "f", value: 1 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform sampler2D coverTex; uniform sampler2D bgTex; uniform float progress; uniform float screenRatio; varying vec2 vUv; void main() { const float maxRadius = 0.708; // sqrt(0.5^2+0.5^2) const float minRadius = 0.0 ; float radius = screenRatio>1.0 ? sqrt((vUv.x - 0.5)*(vUv.x - 0.5) + (vUv.y - 0.5)*(vUv.y - 0.5)/screenRatio) : sqrt((vUv.x - 0.5)*(vUv.x - 0.5)*screenRatio+ (vUv.y - 0.5)*(vUv.y - 0.5)); float diff = 0.292; //1.0-maxRadius; float radiusIn = maxRadius * progress + minRadius * (1.0-progress); float radiusOut = radiusIn + diff; if(radius < radiusIn) { gl_FragColor = texture2D(bgTex, vUv); //gl_FragColor = vec4(0.0,0.0,1.0,1.0);// }else if(radius>radiusOut){ gl_FragColor = texture2D(coverTex, vUv) ; //gl_FragColor = vec4(1.0,1.0,0.0,1.0);// }else{ vec4 color1 = texture2D(bgTex, vUv); vec4 color2 = texture2D(coverTex, vUv); float rotio = smoothstep(radiusIn ,radiusOut,radius); gl_FragColor = mix(color1, color2, rotio); } } ` } ); } */ } var GLCubeFaces$1 = Potree.defines.GLCubeFaces; var TileUtils = {}; TileUtils.TILE_SIZE = 512, TileUtils.FACES_PER_PANO = 6, TileUtils.LocationOnTile = { Center: 0, UpperLeft: 1, UpperRight: 2, LowerRight: 3, LowerLeft: 4 }, /* * 获取某tile在cube中的方向 direction (向量起点在cube中心,终点在tile图的指定位置)。spherical通过先求uv,再直接得到dir * @param {*} size 面分辨率 * @param {*} cubeFace 所在面 * @param {*} Center 在tile上的目标位置,默认为中心,其他位置就是四个顶点 * @param {*} c 似乎是在tile的缩进百分比,根据所在面的不同,分别向不同方向缩进,但都是向tile的中心 * @param {*} dir 所求方向 */ TileUtils.getTileVector = function () { //获取某tile在cube中的方向 direction (向量起点在cube中心,终点在tile图的中心) return function (size, tileSize, cubeFace, tileX, tileY, Center, c, dir) { //c似乎是缩进百分比 Center = Center || TileUtils.LocationOnTile.Center; //假设该cube边长为2: var u = size / tileSize, d = tileX / u; tileY = -tileY + (u - 1); var p = tileY / u, f = tileSize / size, g = 2 * f //一个tile的宽度 (乘以2是因为cube边长是2) , m = g / 2, v = 2 * d - 1 + m, A = 2 * p - 1 + m; switch (Center) { //计算在tile中指定位置带来的偏移 case TileUtils.LocationOnTile.UpperLeft: //1 v -= m, A += m, v += c * g; //似乎是向内缩进 break; case TileUtils.LocationOnTile.UpperRight: v += m, A += m, A -= c * g; break; case TileUtils.LocationOnTile.LowerRight: v += m, A -= m, v -= c * g; break; case TileUtils.LocationOnTile.LowerLeft: v -= m, A -= m, A += c * g; break; case TileUtils.LocationOnTile.Center: //0 } switch (cubeFace) { case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_X: MathLight.setVector(dir, -1, A, -v); break; case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_X: MathLight.setVector(dir, 1, A, v); break; case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Y: //顶面 MathLight.setVector(dir, -v, 1, -A); break; case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: MathLight.setVector(dir, -v, -1, A); break; case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Z: MathLight.setVector(dir, -v, A, 1); break; case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: MathLight.setVector(dir, v, A, -1); } MathLight.normalize(dir); }; }(), /* * 获取该tile在第几个面(简易装载法) */ TileUtils.getFaceForTile = function (size, index) { //获取该tile在第几个面 var tileSize = TileUtils.TILE_SIZE; size < TileUtils.TILE_SIZE && (tileSize = size); var n = Math.floor(size / tileSize), sum = n * n; //得每个面tile总数 return Math.floor(index / sum); }, TileUtils.getTileLocation = function (size, t, result) { var tileSize = TileUtils.TILE_SIZE; size < TileUtils.TILE_SIZE && (tileSize = size); var r = TileUtils.getFaceForTile(size, t), a = Math.floor(size / tileSize), s = a * a, l = t - r * s; result.tileX = l % a; result.tileY = Math.floor(l / a); result.face = r; result.faceTileIndex = l; return result; }, /* * 求size分辨率需要多少张tile */ TileUtils.getTileCountForSize = function (e) { if (e <= TileUtils.TILE_SIZE) return TileUtils.FACES_PER_PANO; var t = Math.floor(e / TileUtils.TILE_SIZE), i = t * t, n = i * TileUtils.FACES_PER_PANO; return n; }, TileUtils.getRelativeDirection = function () { var e = new MathLight.Matrix4(), t = new MathLight.Quaternion(); return function (i, n) { //i是pano.quaternion, n是camera的direction t.copy(i), t.inverse(), e.makeRotationFromQuaternion(t), e.applyToVector3(n), MathLight.normalize(n); }; }(), /* * 根据方向寻找合适的tile加载 */ TileUtils.matchingTilesInDirection = function () { var e = new MathLight.Vector3(), t = new MathLight.Vector3(0, 0, -1), i = new MathLight.Quaternion(), n = function n(e, t) { e.push({ face: t.face, faceTileIndex: t.faceTileIndex, tileX: t.tileX, tileY: t.tileY }); }, a = function () { var e = { face: -1, faceTileIndex: -1, tileX: -1, tileY: -1 }; return function (size, i, r) { for (var a = TileUtils.getTileCountForSize(size), s = 0, l = 0; l < a; l++) TileUtils.getTileLocation(size, l, e), i && !i(e) || (s++, r && n(r, e)); return s; }; }(); return function (pano, size, dir, hFov, vFov, result) { var d = size < TileUtils.TILE_SIZE ? size : TileUtils.TILE_SIZE; //TileUtils.getTileCountForSize(size); if (!hFov && !vFov) return a(size, null, result); var p = !!vFov; vFov = vFov || hFov, vFov = Math.max(0, Math.min(vFov, 360)), hFov = Math.max(0, Math.min(hFov, 360)), MathLight.copyVector(dir, e), TileUtils.getRelativeDirection(pano.quaternion4dkk, e); if (p) { //如果有vFov hFov i.setFromUnitVectors(e, t); var f = function f(e) { return TileUtils.isTileWithinFrustum(size, d, e.face, e.tileX, e.tileY, i, hFov, vFov); //在视野中的 }; return a(size, f, result); } var g = function g(t) { //如果仅有hFov return TileUtils.isTileWithinFOV(size, d, t.face, t.tileX, t.tileY, e, hFov); }; return a(size, g, result); }; }(), /* * 是否在屏幕范围内 */ TileUtils.isTileWithinFrustum = function () { var e = new MathLight.Vector3(), t = 1e-5; return function (i, n, a, s, l, c, h, u) { for (var d = Math.tan(.5 * u * MathLight.RADIANS_PER_DEGREE), p = -d, f = Math.tan(.5 * h * MathLight.RADIANS_PER_DEGREE), g = -f, m = TileUtils.mapFaceToCubemapFace(a), v = 0, A = 0, y = 0, C = 0, I = 0, E = 0, b = TileUtils.LocationOnTile.Center; b <= TileUtils.LocationOnTile.LowerLeft; b++) { TileUtils.getTileVector(i, n, m, s, l, b, 0, e), //get e // size, tileSize, cubeFace, tileX, tileY, Center, c, dir MathLight.applyQuaternionToVector(c, e); if (e.z >= -t) //似乎是在相机背面 I++;else { var w = -1 / e.z, _ = e.x * w, T = e.y * w; T > d ? v++ : T < p && A++, //这四种似乎代表在这个画框之外,如在左、在上、在下、在右 _ > f ? y++ : _ < g && C++, E++; } } return A !== E && v !== E && y !== E && C !== E; //如果有一项和E相等代表要么是在相机背面要么是tile的四个顶点都画在画布的同一边,所以肯定不在画布上 }; }(), /* * 是否在FOV范围内 */ TileUtils.isTileWithinFOV = function () { var e = new MathLight.Vector3(), t = new MathLight.Vector3(0, 1, 0), i = new MathLight.Vector3(1, 0, 0); return function (panoSize, tileSize, face, tileX, tileY, direction, fov) { //direction是作用了pano.quaternion的camera.direction var d = TileUtils.mapFaceToCubemapFace(face); MathLight.cross(direction, t, i); //get i 好像没用到 TileUtils.getTileVector(panoSize, tileSize, d, tileX, tileY, TileUtils.LocationOnTile.Center, 0, e); if (TileUtils.isWithinFOV(e, direction, fov, null)) //先判断tile中心在不在FOV内 return !0; for (var p = fov / 360, f = Math.floor(1 / p), g = 0, m = 0; m < f; m++) { for (var v = TileUtils.LocationOnTile.UpperLeft; v <= TileUtils.LocationOnTile.LowerLeft; v++) if (TileUtils.getTileVector(panoSize, tileSize, d, tileX, tileY, v, g, e), TileUtils.isWithinFOV(e, direction, fov, null)) return !0; g += p; //可能是考虑到有可能tile比fov覆盖了fov(虽然一般不可能,除非fov特别小),所以将tile分成若干段,取tile中的点再检测下 } return !1; }; }(), TileUtils.isWithinFOV = function () { var e = new MathLight.Vector3(), t = new MathLight.Vector3(); return function (dir, cameraDir, fov, a) { if (MathLight.copyVector(dir, t), a) { MathLight.copyVector(a, e), MathLight.normalize(e); var s = MathLight.dot(e, dir); e.x *= s, e.y *= s, e.z *= s, MathLight.subVector(t, e); } var l = fov / 2 * MathLight.RADIANS_PER_DEGREE, c = Math.cos(l), h = MathLight.dot(t, cameraDir); return h >= c; }; }(), TileUtils.mapFaceToCubemapFace = function () { var e = { 0: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 1: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 2: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_X, 3: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 4: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 5: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y }; return function (t) { return e[t]; }; }(); var { PanoRendererEvents, PanoramaEvents, PanoSizeClass } = Potree.defines; var texLoader$3 = new TextureLoader(); var markerOpacitys = { default: 0.4, hovered: 1 }; var labelProp = { sizeInfo: { minSize: 200, maxSize: 250, nearBound: 0.8, farBound: 10 }, backgroundColor: { r: 255, g: 255, b: 255, a: 0.4 }, textColor: { r: 0, g: 0, b: 0, a: 1 }, borderRadius: 15, renderOrder: 10, useDepth: true, clipDistance: 30, maxClipFactor: 0.3, occlusionDistance: 3 }; var labelProp2 = { //sizeInfo: {minSize : 200 , maxSize : 250, nearBound : 0.8, farBound : 10}, backgroundColor: { r: 255, g: 255, b: 255, a: 0 }, textColor: { r: 255, g: 255, b: 255, a: 1 }, textBorderColor: { r: 30, g: 30, b: 30, a: 1 }, textBorderThick: 3, dontFixOrient: true, renderOrder: 10, fontsize: 30 }; var markerTex; //显示全景图时marker没有被遮挡,如果需要,要换成depthBasicMaterial 或者直接把skybox的深度修改(拿到深度贴图后更如此) var planeGeo = new PlaneBufferGeometry(0.2, 0.2); var sg = new SphereGeometry(0.1, 8, 8); var smHovered = new MeshBasicMaterial({ /* side: THREE.BackSide, */color: 0xff0000 }); var sm = new MeshBasicMaterial({/* side: THREE.BackSide */}); var rot90 = new Quaternion().setFromAxisAngle(new Vector3(0, 0, 1), Math.PI / 2); //使用的是刚好适合全景图的,给cube贴图需要转90° //var rot90 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1,0,0), -Math.PI/2 ); //4dkk->navvis //var rot901 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,1,0), -Math.PI/2 ); //整张球幕图要旋转下 //rot90 = new THREE.Quaternion().multiplyQuaternions( rot901, rot90) var old = null; /* 转成四维看看的axis: var a = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,0,1), THREE.Math.degToRad(-90)) 因为四维的要绕y转90 这里的quaternion.multiply(a); 先乘再换顺序 w : q.w, x:q.x , y:-q.z, z:q.y */ //暂时直接用4dkkconsole输出的数据 class Panorama extends EventDispatcher { constructor(o, images360) { //file, time, longitude, latitude, altitude, course, pitch, roll super(); this.id = o.id; //唯一标识 this.images360 = images360; this.visible = true; //for updateVisible this.enabled = true; //是否可以走 this.addEventListener('isVisible', e => { //是否显示该点的mesh(不显示也能走) //console.log('pano isVisible', this.id, e.visible) Potree.Utils.updateVisible(this.marker, 'panoVisi', e.visible); Potree.settings.showPanoMesh && (this.mesh.visible = e.visible); if (e.reason == 'screenshot' || e.visible) { this.label && (this.label.visible = e.visible); //截图时隐藏下 } this.label2 && Potree.Utils.updateVisible(this.label2, 'panoVisi', e.visible); }); /* 漫游点可见性:旧 level reason 类型 2(最高)buildingChange(不在此楼层) unvisible 1 modeIsShowPanos(漫游模式) visible //不记得为什么加这个了,所以重写 0 pointcloudVisi(隐藏了数据集) unvisible */ /* 漫游点可见性:新 level reason 类型 2(最高)buildingChange(不在此楼层) unvisible 1 ifShowMarker(marker显示开关) unvisible 0 pointcloudVisi(隐藏了数据集) unvisible */ if (Potree.settings.editType == 'pano') { //漫游点拼合编辑 this.uuid = o.uuid; //因为有多个数据集 所以会重复 this.index = this.originID = o.index; //下标, 用于visibles this.pointcloud = viewer.scene.pointclouds.find(e => e.panoUuid == o.uuid); this.pointcloud.panos.push(this); this.sid = this.pointcloud.dataset_id + '|' + this.uuid; //不会更改的标记 用于entity.panos里的标记 delete o.pointcloud; this.panosData = o; //数据中原本的位置朝向 this.dataPosition = new Vector3().copy(o.pose.translation); this.dataQuaternion = new Quaternion().copy(o.pose.rotation); this.dataRotation = new Euler().setFromQuaternion(this.dataQuaternion); //因为位置朝向随着点云位置改变,所以直接运用到点云上,这里清零 this.originPosition = new Vector3(); //{x: 0, y: 0, z: 0} this.quaternion = new Quaternion(); //{w: 0, x: 0, y: 0, z: 1} //this.quaternion4dkk = math.convertVisionQuaternion(this.quaternion)//4dkk内使用的quaternion this.visibles = o.visibles; this.rtkState = o.has_rtk ? o.use_rtk : null; var height = 1.4; //相机高度 this.originFloorPosition = this.originPosition.clone(); this.originFloorPosition.z -= height; /* this.originPosition = new THREE.Vector3().copy(o.pose.translation) //{x: 0, y: 0, z: 0} this.quaternion = new THREE.Quaternion().copy(o.pose.rotation) //{w: 0, x: 0, y: 0, z: 1} //this.quaternion4dkk = math.convertVisionQuaternion(this.quaternion)//4dkk内使用的quaternion this.visibles = o.visibles this.pointcloud = viewer.scene.pointclouds.find(e=>e.dataset_id == o.uuid) this.pointcloud.panos.push(this) const height = 1.5; //相机高度 this.originFloorPosition = this.originPosition.clone() this.originFloorPosition.z -= height */ } else { this.originPosition = new Vector3().fromArray(o.dataset_location); //完全对应vision.txt的translation this.originFloorPosition = new Vector3().fromArray(o.dataset_floor_location); this.originID = parseInt(o.file_id); //"file_id":"00022"对应是原本的4dkk的id --来自vision.txt this.pointcloud = o.pointcloud; //viewer.scene.pointclouds.find(e=>e.dataset_id == o.dataset_id) || viewer.scene.pointclouds[0] this.pointcloud.panos.push(this); //this.sid = this.pointcloud.sceneCode + '|' + this.originID //不会更改的标记 this.sid = this.pointcloud.dataset_id + '|' + this.originID; //不会更改的标记 //全景图和Cube的水平采样起始坐标相差90度 /* if(from4dkk){ var qua = o.dataset_orientation var quaternion = new THREE.Quaternion().fromArray(qua) quaternion = new THREE.Quaternion().multiplyQuaternions(quaternion, rot901);//整张球幕图要旋转下 因为在4dkk里转过,还原。如果是tiles的不用 this.quaternion = new THREE.Quaternion(quaternion.x, -quaternion.z, quaternion.y, quaternion.w) //转化坐标 }else{ */ var qua = o.dataset_orientation; //完全对应vision.txt的rotation qua = [qua[1], qua[2], qua[3], qua[0]]; this.quaternion = new Quaternion().fromArray(qua); this.quaternion4dkk = math.convertVisionQuaternion(this.quaternion); //4dkk内使用的quaternion this.quaternion2 = this.quaternion.clone(); this.quaternion = new Quaternion().multiplyQuaternions(this.quaternion, rot90); //全景图和Cube的水平采样起始坐标相差90度,cubeTex转90度 this.rotation4dkk = new Euler().setFromQuaternion(this.quaternion4dkk); //} //this.quaternion1 = Potree.Utils.QuaternionFactory.fromArray(o.dataset_orientation) //同quaternion //let xy = this.transform.forward([this.longitude, this.latitude]); //this.file = `https://4dkk.4dage.com/images/images${Potree.settings.number}/pan/high/${this.id}.jpg` this.neighbours = []; } this.rotation = new Euler().setFromQuaternion(this.quaternion); this.build(); this.transformByPointcloud(); //初始化位移 { //tile this.minimumTiledPanoLoaded = !1; this.highestPartialTileRenderOpCompleted = 0; this.highestFullTileRenderOpCompleted = 0; this.shouldRedrawOnBaseLoaded = !1; this.resolutionPromise = {}; this.tiledPanoRenderTarget = null; this.zoomed = !1; images360.panoRenderer.addEventListener(PanoRendererEvents.TileRenderSuccess, this.onTileRendered.bind(this)); images360.panoRenderer.addEventListener(PanoRendererEvents.PanoRenderComplete, this.onPanoRendered.bind(this)); images360.panoRenderer.addEventListener(PanoRendererEvents.TileRenderFailure, this.onTileRenderFail.bind(this)); images360.panoRenderer.addEventListener(PanoRendererEvents.UploadAttemptedForAllTiles, this.onUploadAttemptedForAllTiles.bind(this)); } this.addEventListener('hoverOn', e => { //from Map if (!e.byMainView) { this.hoverOn(e); } }); this.addEventListener('hoverOff', e => { if (!e.byMainView) { this.hoverOff(e); } }); } get noNeighbour() { //是否绝对到不到的孤立点 for (var i = 0, j = this.images360.panos.length; i < j; i++) { if (this.images360.neighbourMap[this.id][i] !== false) { return false; } } return true; //return this.neighbours.length == 0 } setEnable(enable) { //是否可以走 Potree.Utils.updateVisible(this, 'isEnabled', enable); //令所有marker不可见 this.enabled = enable; //如果当前在全景模式且在这个点,需要切换显示吗? 目前用不到 } loadDepthImg() { if (!this.pointcloud.hasDepthTex || this.depthTex || this.depthTexLoading) return; this.depthTexLoading = true; var mapping = Potree.settings.isLocal2 ? '' : this.pointcloud.datasetData.mapping; //非离线包的话加mapping var src = "".concat(Potree.settings.urls.prefix1, "/").concat(mapping ? mapping + '/' : '').concat(Potree.settings.webSite, "/").concat(this.pointcloud.sceneCode, "/data/").concat(this.pointcloud.sceneCode, "/depthmap/").concat(this.originID, ".png"); // `${Potree.settings.urls.prefix1}/${Potree.settings.webSite}/${this.pointcloud.sceneCode}/data/${this.pointcloud.sceneCode}/depthmap/${this.originID}.png` //console.log('开始下载depthImg', this.id) var texture = texLoader$3.load(src, () => { this.depthTex = texture; this.dispatchEvent({ type: 'loadedDepthImg', loaded: true }); this.images360.dispatchEvent({ type: 'loadedDepthImg', pano: this }); this.depthTexLoading = false; this.images360.updateDepthTex(this); }, null, e => { //error console.error('loadDepthImg失败, 数据集sceneCode' + this.pointcloud.sceneCode, this.id); this.pointcloud.hasDepthTex = false; this.dispatchEvent({ type: 'loadedDepthImg' }); }); texture.wrapS = RepeatWrapping; texture.flipY = false; texture.magFilter = LinearFilter; texture.minFilter = LinearFilter; texture.generateMipmaps = false; } build() { { // orientation //add //var quaternion = new THREE.Quaternion().multiplyQuaternions(this.quaternion, rot901);//改 为球目全 //quaternion.premultiply(rot90) this.panoMatrix = new Matrix4().makeRotationFromQuaternion(this.quaternion); this.oriPanoMatrix = this.panoMatrix.clone(); if (this.quaternion2) this.oriPanoMatrix2 = new Matrix4().makeRotationFromQuaternion(this.quaternion2); //console.log(this.quaternion) //this.quaternion = quaternion } /* let marker = new THREE.Mesh(planeGeo, this.getMarkerMat() ) //marker.lookAt(marker.up) marker.scale.set(2,2,2) */ var marker = new Mesh(planeGeo, this.getMarkerMat()); //new Sprite({mat:this.getMarkerMat(), dontFixOrient:true }) marker.scale.set(2, 2, 2); //marker.scale.set(0.4,0.4,0.4) marker.name = 'marker_' + this.id; marker.up.set(0, 0, 1); this.addEventListener('changeMarkerTex', e => { marker.material.map = markerTex[e.name]; }); this.marker = marker; marker.pano = this; this.images360.node.add(marker); Potree.settings.isTest && this.addLabel(); //this.addLabel2() marker.addEventListener('mouseover', this.hoverOn.bind(this)); marker.addEventListener('mouseleave', this.hoverOff.bind(this)); } transformByPointcloud() { var position = this.originPosition.clone().applyMatrix4(this.pointcloud.transformMatrix); //也可以用datasetPosTransform算 var floorPosition = this.originFloorPosition.clone().applyMatrix4(this.pointcloud.transformMatrix); this.setPosition(position, floorPosition); this.panoMatrix = new Matrix4().multiplyMatrices(this.pointcloud.rotateMatrix, this.oriPanoMatrix); //this.panoMatrix2 = Potree.Utils.datasetRotTransform({fromDataset:true, pointcloud:this.pointcloud, matrix:this.oriPanoMatrix, getMatrix:true}) //和上一行结果一样 //quaternion也变下 if (this.oriPanoMatrix2) { this.panoMatrix2 = new Matrix4().multiplyMatrices(this.pointcloud.rotateMatrix, this.oriPanoMatrix2); //供DepthImageSampler使用 this.panoMatrix2Inverse = this.panoMatrix2.clone().invert(); } this.dispatchEvent('rePos'); } setPosition(position, floorPosition) { this.position = position; this.floorPosition = floorPosition; //this.mesh.position.copy(this.position) this.marker.position.copy(this.floorPosition); this.marker.position.z += 0.04; //会被点云遮住 if (this.label) { if (Potree.settings.editType == 'pano') { this.label.position.copy(this.position); } else { this.label.position.copy(this.floorPosition); } this.label.position.z += 0.14; this.label.update(); } /* if(this.label2){ if(Potree.settings.editType == 'pano'){ this.label2.position.copy(this.position) }else{ this.label2.position.copy(this.floorPosition) } this.label2.position.copy(this.marker.position) this.label2.update() } */ } /* getRealPos(){//当整体移动以后 return this.position.clone().applyMatrix4(viewer.scene.scene.matrix) } */ getMarkerMat() { if (!markerTex) { markerTex = { default: texLoader$3.load(Potree.resourcePath + '/textures/marker.png'), ring: texLoader$3.load(Potree.resourcePath + '/textures/marker2.png') }; markerTex.default.anisotropy = 4; // 各向异性过滤 .防止倾斜模糊 markerTex.ring.anisotropy = 4; //有可能被点云遮住吗。 } var mat = new DepthBasicMaterial({ opacity: markerOpacitys.default, side: DoubleSide, map: markerTex.default, transparent: true, clipDistance: 2, occlusionDistance: 1, //不能设置太短,因为过渡时深度不准确 useDepth: !!(Potree.settings.useDepthTex && this.pointcloud.hasDepthTex || Potree.settings.modelSkybox && this.pointcloud.is4dkkModel), autoDepthTest: true //改为DepthBasicMaterial是因为原Basic的材质在有深度图时过渡会先隐藏后出现。 注:没有深度图时全景模式的marker无法遮挡 }); mat.mapTransparent = true; return mat; } hoverOn() { var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; //console.log("hoverOn " + this.id ) transitions$1.start(lerp.property(this.marker.material, "opacity", markerOpacitys.hovered, () => { viewer.dispatchEvent('content_changed'); }), this.marker.visible ? 250 : 0); if (!e.byMap) this.dispatchEvent({ type: 'hoverOn', byMainView: true }); if (!e.byImages360) this.images360.dispatchEvent({ type: 'markerHover', hovered: true, pano: this }); } hoverOff() { var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; //console.log("hoverOff " + this.id ) transitions$1.start(lerp.property(this.marker.material, "opacity", markerOpacitys.default, () => { viewer.dispatchEvent('content_changed'); }), this.marker.visible ? 250 : 0); if (!e.byMap) this.dispatchEvent({ type: 'hoverOff', byMainView: true }); if (!e.byImages360) this.images360.dispatchEvent({ type: 'markerHover', hovered: false, pano: this }); } setZoomed(zoomed) { this.zoomed = zoomed; Potree.settings.displayMode == 'showPanos' && this.updateSkyboxForZoomLevel(); //放大后换成zoomTarget贴图 viewer.dispatchEvent({ type: 'panoSetZoom', zoomed }); } enter() { this.entered = true; this.setZoomed(!1); viewer.dispatchEvent({ type: PanoramaEvents.Enter, oldPano: old, newPano: this }); old = this; //console.log("enter pano "+ this.id) } exit() { this.clearWaitDeferreds(); this.minimumTiledPanoLoaded = !1; this.tiledPanoRenderTarget = null; this.setZoomed(!1); this.images360.panoRenderer.deactivateTiledPano(this); this.highestPartialTileRenderOpCompleted = 0; this.highestFullTileRenderOpCompleted = 0; this.depthTex && this.depthTex.dispose(); //贴图不使用后先dispose,下次到该点时会自动还原 this.entered = false; //add //console.log("exit pano "+ this.id) viewer.dispatchEvent({ type: PanoramaEvents.Exit, pano: this }); } updateSkyboxForZoomLevel() { if (this.minimumTiledPanoLoaded) { this.images360.updateProjectedPanos(); } } getSkyboxTexture() { if (this.minimumTiledPanoLoaded) { if (this.zoomed && this.images360.qualityManager.maxRenderTargetSize > this.images360.qualityManager.maxNavPanoSize) //change 如果放大后和不放大都是2k就不用这个 { return this.images360.panoRenderer.zoomRenderTarget.texture; } else { this.tiledPanoRenderTarget.texture.mapping = UVMapping; //add return this.tiledPanoRenderTarget.texture; } } else { return null; } } isLoaded(e) { if (e && "string" == typeof e) console.error("Wrong panoSize given to Panorama.isLoaded(); a tiled pano uses PanoSizeClass"); return !!this.minimumTiledPanoLoaded && (!e || this.highestFullTileRenderOpCompleted >= e); //改:原本是:this.highestPartialTileRenderOpCompleted >= e, 希望这代表全部加载完 } getWaitDeferred(size) { //获取不同size的tile贴图的promiss var t = this.resolutionPromise[this.id]; t || (t = {}, this.resolutionPromise[this.id] = t); var i = t[size]; return i || (i = { deferred: $.Deferred(), active: !1 }, t[size] = i), i; } clearWaitDeferreds() { var e = this.resolutionPromise[this.id]; e || (e = {}, this.resolutionPromise[this.id] = e); for (var t in e) if (e.hasOwnProperty(t)) { var i = e[t]; i.active = !1, i.deferred = $.Deferred(); } } resetWaitDeferred(e) { var t = this.getWaitDeferred(e); t.active = !1; t.deferred = $.Deferred(); } onTileRendered(ev) { ev.id === this.id && this.dispatchEvent({ type: PanoramaEvents.TileLoaded, size: ev.panoSize, index: ev.tileIndex, count: ev.totalTiles }); } onPanoRendered(ev) { if (ev.id === this.id) { this.minimumTiledPanoLoaded = !0; this.updateSkyboxForZoomLevel(); //更新贴图 setProjected ev.panoSize > this.highestPartialTileRenderOpCompleted && (this.highestPartialTileRenderOpCompleted = ev.panoSize); //应该是更新最高获取到的Partial size ev.updateFullComplete && ev.panoSize > this.highestFullTileRenderOpCompleted && (this.highestFullTileRenderOpCompleted = ev.panoSize); //应该是更新最高获取到的Full size //this.dispatchEvent("load", ev.panoSize); viewer.ifAllLoaded(this); this.dispatchEvent({ type: PanoramaEvents.LoadComplete, size: ev.panoSize, count: ev.totalTiles }); } } onTileRenderFail(ev) { ev.id === this.id && this.dispatchEvent({ type: PanoramaEvents.LoadFailed }); } onUploadAttemptedForAllTiles(ev) { if (ev.id === this.id) { var n = this.images360.qualityManager.getPanoSize(PanoSizeClass.BASE); if (ev.panoSize === n && this.shouldRedrawOnBaseLoaded) //shouldRedrawOnBaseLoaded一直是false。在4dkk里只有初始点在quickstart后变为true。 { this.shouldRedrawOnBaseLoaded = !1; this.panoRenderer.resetRenderStatus(this.id, !0, !1); this.panoRenderer.renderPanoTiles(this.id, null, !0, !0); } } } addLabel() { this.removeTextLabel(); this.label = new TextSprite$2(Object.assign({}, labelProp, { text: this.id + "(" + this.originID + ")" }) //{text: `id:${this.id}, dataset:${this.pointcloud.name}, 4dkkId:${this.originID}`} ); this.images360.node.add(this.label); this.floorPosition && this.label.position.copy(this.floorPosition); } addLabel2() { if (this.label2) return; this.label2 = new TextSprite$2(Object.assign({}, labelProp2, { text: /* this.originID */parseInt(this.id) + 1 }) //{text: `id:${this.id}, dataset:${this.pointcloud.name}, 4dkkId:${this.originID}`} ); //this.images360.node.add(this.label2); this.marker.add(this.label2); //this.floorPosition && this.label2.position.copy(this.floorPosition) var s = 0.2; this.label2.scale.set(s, s, s); Potree.Utils.updateVisible(this.label2, 'notDisplay', false); Potree.Utils.updateVisible(this.label2, 'panoVisi', this.visible); //Potree.Utils.setObjectLayers(this.label2, 'bothMapAndScene') } removeTextLabel() { if (this.label) { this.label.parent.remove(this.label); } } dispose() { var i = viewer.images360.panos.indexOf(this); if (i == -1) return; this.marker.parent.remove(this.marker); this.removeTextLabel(); if (this.depthTex) this.depthTex.dispose(); viewer.images360.panos.splice(i, 1); this.dispatchEvent('dispose'); //删除tile贴图、depthTex等以后再写 } getCeilHeight() { //天花板高度值 (假设不存在depth为0的点,所有为0的要么是在盲区,要么是无穷远。) if (this.ceilZ == void 0) { //const depthTiming = Potree.timeCollect.depthSampler.median //pc firefox达到4. chrome为0.01 //用三个间隔120度散开,和中心垂直线成一定夹角的三个向量去求 最高高度 (不求平均的原因:万一是0不好算) var rotMat = new Matrix4().makeRotationX((Potree.config.depthTexUVyLimit + 0.01) * Math.PI); // 角度不能小于天花板中空的半径 var dir0 = new Vector3(0, 0, 1).applyMatrix4(rotMat); var dirs = [dir0, dir0.clone().applyMatrix4(new Matrix4().makeRotationZ(Math.PI * 2 / 3)), dir0.clone().applyMatrix4(new Matrix4().makeRotationZ(-Math.PI * 2 / 3))]; /* if(depthTiming < 1){ let rotMat1 = new THREE.Matrix4().makeRotationZ(Math.PI*2 / 3); dirs.push(dirs[0].clone().applyMatrix4(rotMat1)) } if(depthTiming < 0.3){ let rotMat2 = new THREE.Matrix4().makeRotationZ(-Math.PI*2 / 3); dirs.push(dirs[0].clone().applyMatrix4(rotMat2)); } */ var zs = dirs.map(dir_ => { var dir = dir_.clone().applyMatrix4(this.panoMatrix2); //pano不一定是垂直的, 需要把之前的dirInPano先转成真实的dir,防止超出角度限制 var intersect = viewer.images360.getIntersect(this, dir); var z = intersect ? intersect.location.z : Infinity; /* this.position.z+skyHeight */ //没有intersect代表可能是天空 return z; }); zs.sort((a, b) => { return b - a; }); //得最大值 (不用中位数的原因:在屋檐处,如果仅有一个intersect是天空,因到了室外所以也用天空高度) this.ceilZ = zs[0]; var min = this.position.z + 1; // 防止意外太低 this.ceilZ = Math.max(min, this.ceilZ); //console.log(this.id, 'ceilZ:', this.ceilZ ) } return this.ceilZ; } } ; Panorama.prototype.loadTiledPano = function () { //var downloads = [] , t = []; var downloaded = {}, eventAdded = {}, latestPartialRequest = {}; //每个pano对应一组这些 return function (size, dirs, fov, o, a, download) { var dir = dirs.datasetsLocal.find(e => e.datasetId == this.pointcloud.dataset_id).direction; //var dir = dirs null !== o && void 0 !== o || (o = !0), null !== a && void 0 !== a || (a = !0); var l = this.getWaitDeferred(size), c = l.deferred, h = null, u = null; fov && ("number" == typeof fov ? h = fov : (h = fov.hFov, u = fov.vFov)); if (!this.isLoaded(size)) { //console.log('loadTiledPano', this.id, size, fov) if (!l.active) { l.active = !0; var name = this.id + ":" + size; downloaded[name] = downloaded[name] || []; /* this.downloaded = downloaded this.latestPartialRequest = latestPartialRequest */ latestPartialRequest[name] = null; if (fov) { var tileArr = []; //add var d = TileUtils.matchingTilesInDirection(this, size, dir, h, u, tileArr); latestPartialRequest[name] = tileArr; downloaded[name].forEach(e => { var item = latestPartialRequest[name].find(a => e.faceTileIndex == a.faceTileIndex && e.face == a.face); if (item) { item.loaded = true; } }); if (!latestPartialRequest[name].some(e => !e.loaded)) { //所需要的全部加载成功 //let total = TileUtils.getTileCountForSize(size) //this.onPanoRendered(this.id, size, total, !0); c.resolve(size /* , total */); this.resetWaitDeferred(size); //console.log('该部分早已经加载好了'+size, this.id) latestPartialRequest[name] = null; } //console.log("Loading partial pano: " + this.id + " with " + d + " tiles") } if (!eventAdded[this.id]) { eventAdded[this.id] = !0; this.addEventListener(PanoramaEvents.LoadComplete, function (ev /* e, t */) { //本次任务全部加载完毕 //console.warn('点位(可能部分)下载完成 ', 'id:'+this.id, 'size:'+ev.size ) var i = this.getWaitDeferred(ev.size).deferred; //"pending"为还未完成 i && "pending" === i.state() && this.highestPartialTileRenderOpCompleted >= ev.size && (i.resolve(ev.size, ev.count), this.resetWaitDeferred(ev.size)); //恢复active为false }.bind(this)); this.addEventListener(PanoramaEvents.LoadFailed, function (ev) { var t = this.getWaitDeferred(e).deferred; t && "pending" === t.state() && this.highestPartialTileRenderOpCompleted >= ev.t && (t.reject(ev.t), this.resetWaitDeferred(ev.t)); //恢复active为false }.bind(this)); this.addEventListener(PanoramaEvents.TileLoaded, function (ev /* t, i, n */) { //每张加载完时 //console.log('tileLoaded', 'id:'+this.id, 'size:'+ev.size, 'tileIndex:'+ev.index ) var tileIndex = ev.index; var total = ev.count; var size = ev.size; var name = this.id + ":" + size; downloaded[name] = downloaded[name] || []; //不是所有的加载都是从loadTiledPano获取的所以会有未定义的情况 var { faceTileIndex, face } = TileUtils.getTileLocation(size, tileIndex, {}); downloaded[name].push({ faceTileIndex, face }); var r = this.getWaitDeferred(size).deferred; if (r && "pending" === r.state()) { r.notify(size, tileIndex, total); if (latestPartialRequest[name]) { var item = latestPartialRequest[name].find(e => e.faceTileIndex == faceTileIndex && e.face == face); item && (item.loaded = true); if (!latestPartialRequest[name].some(e => !e.loaded)) { //所需要的局部tiles全部加载成功 this.onPanoRendered(this.id, size, total, !0); //onPanoRendered还会触发 PanoramaEvents.LoadComplete r.resolve(size, total); this.resetWaitDeferred(size); //console.log('该部分加载好了'+size, this.id) latestPartialRequest[name] = null; } } } viewer.dispatchEvent('content_changed'); /* var r = this.getWaitDeferred(ev.size).deferred; if (r && "pending" === r.state()) { r.notify(ev.size, ev.index, ev.count); var o = downloads[this.id + ":" + ev.size]; if(o){//如果有规定下载哪些tile,只需要下载这些tile则LoadComplete o.tileCount++ if(o.tileCount === o.targetTileCount){//达到下载目标数 this.onPanoRendered(this.id, ev.size, ev.count, !0); r.resolve(ev.size, ev.count); this.resetWaitDeferred(ev.size) } } } */ }.bind(this)); } } this.images360.tileDownloader.clearForceQueue(); this.images360.tileDownloader.forceQueueTilesForPano(this, size, dir, h, u, download); this.tiledPanoRenderTarget = this.images360.panoRenderer.activateTiledPano(this, this.images360.qualityManager.getMaxNavPanoSize(), o); this.images360.panoRenderer.renderPanoTiles(this.id, dirs, a); } else { //console.log('早已经全加载好了' +size, this.id) c.resolve(size); } return c.promise(); }; }(); var { ModelManagerEvents, PanoSizeClass: PanoSizeClass$1 } = Potree.defines; class QualityManager { constructor(e, t, i) { this.maxNavPanoSize = -1; this.maxZoomPanoSize = -1; this.devicePixelDensity = e; this.deviceScreenSize = t; this.clientBandwidth = i; this.panoSizeClassMap = {}; this.useHighResolutionPanos = !0; //是否能够使用2k及以上图 this.useUltraHighResolutionPanos = !1; this.modelHasUltraHighPanos = !1; this.qualityManager = this; this.maxRenderTargetSize = browser.isMobile() ? 2048 : 4096; //add this.init(); } init(e) { //var metadata = store.getters['scene/metadata'] ;//有时候请求不到 //if(metadata.sceneSource == 11 || metadata.sceneScheme == 12){ /* if(config.tileClass == '1k'){ this.useHighResolutionPanos = false //xzw add 只加载1k } */ this.buildPanoSizeClassMap(this.devicePixelDensity, this.deviceScreenSize, this.clientBandwidth); this.ultraHighSize = this.getPanoSize(PanoSizeClass$1.ULTRAHIGH); this.highSize = this.getPanoSize(PanoSizeClass$1.HIGH); this.standardSize = this.getPanoSize(PanoSizeClass$1.STANDARD); this.baseSize = this.getPanoSize(PanoSizeClass$1.BASE); config$1.tiling.maxZoomPanoQuality && this.ultraHighSize <= config$1.tiling.maxZoomPanoQuality && (config$1.tiling.allowUltraHighResolution = !0); this.highQualityThreshold = browser.valueFromHash("threshold2k", config$1.windowHeightHighQualityThreshold); this.updateMaximums(); //e.on(ModelManagerEvents.ActiveModelChanged, this.onModelChanged.bind(this)); } updateFromModel(e) { //this.updateHighResolutionSettings(e) this.updateUltraHighResolutionSettings(e); } /* updateHighResolutionSettings(e) { this.useHighResolutionPanos = !0 this.updateMaximums() } */ updateUltraHighResolutionSettings(e) { if (config$1.tiling.allowUltraHighResolution && this.modelHasUltraHighPanos) { this.useUltraHighResolutionPanos = !0; } else { this.useUltraHighResolutionPanos = !1; } this.updateMaximums(); } enableUltraHighQualityMode() { this.modelHasUltraHighPanos = !0; this.updateUltraHighResolutionSettings(null); } ultraHighQualityModeEnabled() { return this.modelHasUltraHighPanos; } onModelChanged(e) { this.updateFromModel(e.model), this.updateMaximums(); } updateMaximums() { this.maxNavPanoSize = config$1.tiling.maxNavPanoQuality || this.detectMaxNavPanoSize(), this.maxZoomPanoSize = config$1.tiling.maxZoomPanoQuality || this.detectMaxZoomPanoSize(), this.maxZoomPanoSize < this.maxNavPanoSize && (this.maxNavPanoSize = this.maxZoomPanoSize); } buildPanoSizeClassMap() { this.panoSizeClassMap[PanoSizeClass$1.BASE] = 512, this.panoSizeClassMap[PanoSizeClass$1.STANDARD] = 1024, this.panoSizeClassMap[PanoSizeClass$1.HIGH] = 2048, this.panoSizeClassMap[PanoSizeClass$1.ULTRAHIGH] = 4096; } getPanoSize(e) { return this.panoSizeClassMap[e]; } getMaxPossiblePanoSize() { return this.getPanoSize(PanoSizeClass$1.ULTRAHIGH); } getMaxPanoSize() { return this.maxZoomPanoSize; } getMaxNavPanoSize() { return this.maxNavPanoSize; } getMaxZoomPanoSize() { return this.maxZoomPanoSize; } detectMaxNavPanoSizeClass() { //return this.useHighResolutionPanos ? browser.isMobile() ? PanoSizeClass.STANDARD : window.innerHeight < this.highQualityThreshold ? PanoSizeClass.STANDARD : PanoSizeClass.HIGH : PanoSizeClass.STANDARD /* if(config.name == 'decor'){ return PanoSizeClass.STANDARD } return PanoSizeClass.HIGH */ switch (Potree.settings.navTileClass) { case '1k': return PanoSizeClass$1.STANDARD; break; case '2k': default: return PanoSizeClass$1.HIGH; } } detectMaxNavPanoSize() { var e = this.detectMaxNavPanoSizeClass(); return this.getPanoSize(e); } detectMaxZoomPanoSize() { //获取当前zoomRenderTarget应下载的最高级别 //若是有三个级别,每次只需要加载到当前的zoomLevel;而两级时因为有zoomed来判断是使用基本贴图还是zoomRenderTarget,所以只需要返回最大的即可 if (this.zoomLevelResolution) { //有三个级别 if (this.zoomLevelResolution == '4k' && this.useUltraHighResolutionPanos) { return this.getPanoSize(PanoSizeClass$1.ULTRAHIGH); } else if (this.zoomLevelResolution == '1k' || !this.useHighResolutionPanos) { return this.getPanoSize(PanoSizeClass$1.STANDARD); } else { return this.getPanoSize(PanoSizeClass$1.HIGH); } } else { if (this.useHighResolutionPanos) { /* if (browser.isMobile()) {//手机版如果要2k的将这里去掉 if (settings.tiling.mobileHighQualityOverride) { return this.getPanoSize(PanoSizeClass.HIGH); } else { return this.getPanoSize(PanoSizeClass.STANDARD); } } else */ if (this.useUltraHighResolutionPanos) { return this.getPanoSize(PanoSizeClass$1.ULTRAHIGH); } else { return this.getPanoSize(PanoSizeClass$1.HIGH); } } else { return this.getPanoSize(PanoSizeClass$1.STANDARD); } } } } var { DownloadStatus } = Potree.defines; var h = Object.freeze({ None: 0, DirectionalFOV: 1 }); var u = function () { var e = function e(t, i) { var n = e._panoSpaceDir, r = e._fovThreshold, o = e._fovThresholdNarrow, a = Math.max(Math.min(n.dot(t.direction), 1), -1), s = Math.max(Math.min(n.dot(i.direction), 1), -1); return t._dot = a, i._dot = s, a >= r && s < r ? -1 : a < r && s >= r ? 1 : a >= o && s < o ? -1 : a < o && s >= o ? 1 : t.panoSize > i.panoSize ? 1 : i.panoSize > t.panoSize ? -1 : -(a - s); }; return e._panoSpaceDir = new Vector3(), e._fovThreshold = -1, e._fovThresholdNarrow = -1, e; }(); class TilePrioritizer { //优先级处理序列 constructor(e, t, i, o, a) { this.qualityManager = e; this.maxNavQuality = this.qualityManager.getMaxNavPanoSize(); this.maxZoomQuality = this.qualityManager.getMaxZoomPanoSize(); this.baseSize = t; this.standardSize = i; this.highSize = o; this.ultraHighSize = a; this.priorityCriteria = new TilePrioritizer.PriorityCriteria(null, new Vector3(0, 0, 0), new Vector3(0, 0, -1), new Vector3(0, 0, -1)); } updateCriteria(e, t, i, n) { //由player更新 this.priorityCriteria.pano = e, this.priorityCriteria.cameraPosition.copy(t), //this.priorityCriteria.cameraDir.copy(i), this.priorityCriteria.cameraDirs = i; this.priorityCriteria.upcomingPanos = n, this.maxNavQuality = this.qualityManager.getMaxNavPanoSize(), this.maxZoomQuality = this.qualityManager.getMaxZoomPanoSize(); } canDownloadSize(e) { return this.maxNavQuality >= e || this.maxZoomQuality >= e && this.zoomingActive; } /* populateNeighborPanos(e, t, i) { i = i || [], i.length = 0; var n = t.getNeighbours(e); for (var r in n) if (n.hasOwnProperty(r)) { var o = t.get(r); if(!o){ console.log(1) } i.push(o) } return i } */ populateScoredPanos(e, t, i, dirs, a, dontFilterDir) { i = i || [], i.length = 0; var s = [Images360.filters.not(e)], l = [Images360.scoreFunctions.distanceSquared(e), Images360.scoreFunctions.direction(e.position, dirs)], c = Common.sortByScore(t, s, l); if (!dontFilterDir) { s.push(Images360.filters.inPanoDirection(e.position, dirs, TilePrioritizer.DIRECTION_SCORE_STRICTNESS)); } if (c) for (var h = 0; h < c.length && h < a; h++) { var u = c[h].item; i.push(u); } return i; } queueTilesForPanos(e, t, i, n, r) { for (var o = 0, a = 0; a < t.length; a++) { var s = t[a], l = this.queueTilesForPano(e, i, s, n); if (o += l > 0 ? 1 : 0, r && o >= r) break; } return o; } /* queueTilesInDirectionForPanos(e, t, i, n, r, o, a, s) {//没用到 for (var l = 0, c = 0; c < i.length; c++) { var h = i[c], u = this.queueTilesInDirectionForPano(e, t, h, n, o, a); if (l += u > 0 ? 1 : 0, s && l >= s) break } return l } */ canIncludeDescriptor(e) { return e.status !== DownloadStatus.Downloading && e.status !== DownloadStatus.Downloaded; } canIncludePano(e, t) { return !e.isLoaded(t); } getFOVDotThreshold(e) { return Math.cos(MathUtils.degToRad(e / 2)); } setZoomingActive(e) { e !== this.zoomingActive && (this.zoomingActive = e); } } TilePrioritizer.PriorityCriteria = function (e, t, i, n, o) { this.pano = e, this.cameraPosition = new Vector3().copy(t), //this.cameraDir = (new THREE.Vector3).copy(i), this.cameraDirs = [], // this.panoSpaceDir = new Vector3().copy(n), this.upcomingPanos = o, this.copy = function (e) { this.pano = e.pano, this.cameraPosition.copy(e.cameraPosition), //this.cameraDir.copy(e.cameraDir), this.cameraDirs = e.cameraDirs; this.panoSpaceDir.copy(e.panoSpaceDir), this.upcomingPanos = o; }, this.zoomingActive = !1; }; TilePrioritizer.DIRECTIONAL_FOV = 180; TilePrioritizer.DIRECTIONAL_FOV_NARROW = 120; TilePrioritizer.MAX_SCORED_PANOS_TOCONSIDER = 6; TilePrioritizer.MAX_SCORED_PANOS_TOADD = 2; TilePrioritizer.MAX_UPCOMING_PANOS_TOADD = 3; TilePrioritizer.DIRECTION_SCORE_STRICTNESS = .75; TilePrioritizer.appendQueue = function (e, t) { if (e && t) for (var i = 0; i < t.length; i++) { e.push(t[i]); //console.log(t[i]) } }; TilePrioritizer.sortPanoTiles = function (descriptors, pano, dir) { if (dir.datasetsLocal) dir = dir.datasetsLocal.find(e => e.datasetId == pano.pointcloud.dataset_id).direction; //add u._panoSpaceDir.copy(dir); TileUtils.getRelativeDirection(pano.quaternion4dkk, u._panoSpaceDir); //应该是将dir根据quaternion转化下 u._fovThresholdNarrow = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV_NARROW); u._fovThreshold = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV); descriptors.sort(u); }; TilePrioritizer.insertSortedPanoTile = function (e, t, pano, dir) { if (dir.datasetsLocal) dir = dir.datasetsLocal.find(e => e.datasetId == pano.pointcloud.dataset_id).direction; //add u._panoSpaceDir.copy(dir), TileUtils.getRelativeDirection(pano.quaternion4dkk, u._panoSpaceDir), u._fovThresholdNarrow = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV_NARROW), u._fovThreshold = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV); for (var o = -1, a = 0; a < e.length; a++) { var s = u(t, e[a]); if (s <= 0) { o = a; break; } } if (o === -1) e[e.length] = t;else { for (var h = e.length; h > o; h--) e[h] = e[h - 1]; e[o] = t; } }; TilePrioritizer.prototype.filterDepthTex = function (panos) { // 下载depthTex if (!Potree.settings.useDepthTex || !this.priorityCriteria.pano || viewer.mainViewport.view.isFlying()) return; var cameraDirLocals = this.priorityCriteria.cameraDirs.vectorForward; var nearPanos = []; //用于获得邻近点位序列 this.populateScoredPanos(this.priorityCriteria.pano, panos, nearPanos, cameraDirLocals, Infinity, true); var dlCount = browser.isMobile() ? 1 : 2; var loadingCount = panos.filter(p => p.depthTexLoading).length; if (viewer.mapViewer) { var mapLayer = viewer.mapViewer.mapLayer; loadingCount += mapLayer.loadingInProgress * 1.5 + mapLayer.waitQueue.length; } if (loadingCount < dlCount) { nearPanos.filter(p => !p.depthTex).slice(0, dlCount - loadingCount).forEach(p => p.loadDepthImg()); } this.nearPanos = nearPanos; }; TilePrioritizer.prototype.filterAndPrioritize = function () { //挑选出优先加载的 pano和tile (有点复杂,没看很懂) var e = [], t = [], i = []; return function (queue, panos, tileDownloader) { //this.populateNeighborPanos(this.priorityCriteria.pano, panos, e); /* let cameraDirLocals = this.priorityCriteria.cameraDirs.map(e=>{ //add var dataset = viewer.scene.pointclouds.find(u=>u.dataset_id == e.datasetId) var matrix = new THREE.Matrix4().copy(dataset.rotateMatrix) var direction = math.convertVector.YupToZup(e.direction) return { datasetId:e.datasetId, direction: direction.clone().applyMatrix4(matrix) } }) */ var cameraDirLocals = this.priorityCriteria.cameraDirs.vectorForward; //获得视野范围内的邻近点位序列t this.populateScoredPanos(this.priorityCriteria.pano, panos, t, cameraDirLocals, TilePrioritizer.MAX_SCORED_PANOS_TOCONSIDER); //t.filter(p=>!p.depthTex).slice(0, Potree.config.depTexDlCount).forEach(p=>p.loadDepthImg()) //add var s = this.baseSize //512 , l = this.standardSize //1024 , c = this.highSize //2048 , h = this.ultraHighSize; //4096 this.queueTilesForPano(queue, tileDownloader, this.priorityCriteria.pano, s); //把当前pano的512下载了 if (this.priorityCriteria.upcomingPanos) { // 添加即将走到的点(之前用于导览路线)512 tiles this.queueTilesForPanos(queue, this.priorityCriteria.upcomingPanos, tileDownloader, s, TilePrioritizer.MAX_UPCOMING_PANOS_TOADD); } i.length = 0; //把当前pano角度范围内的tile按照分辨率从低到高加入队列 if (this.canDownloadSize(l)) { //1024如果在限制范围内的话 this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, l, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV_NARROW); } TilePrioritizer.sortPanoTiles(i, this.priorityCriteria.pano, this.priorityCriteria.cameraDirs); //排序 TilePrioritizer.appendQueue(queue, i); //添加邻近点t 512的tiles this.queueTilesForPanos(queue, t, tileDownloader, s, TilePrioritizer.MAX_SCORED_PANOS_TOADD); i.length = 0; //NARROW : if (this.canDownloadSize(c)) { //2048 this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, c, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV_NARROW); } if (this.canDownloadSize(h)) { //4096 this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, h, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV_NARROW); } TilePrioritizer.sortPanoTiles(i, this.priorityCriteria.pano, this.priorityCriteria.cameraDirs); //排序 TilePrioritizer.appendQueue(queue, i); i.length = 0; if (this.canDownloadSize(l)) { //1024 this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, l, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV); } if (this.canDownloadSize(c)) { //2048 this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, c, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV); } if (this.canDownloadSize(h)) { //4096 this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, h, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV); } TilePrioritizer.sortPanoTiles(i, this.priorityCriteria.pano, this.priorityCriteria.cameraDirs); //排序 TilePrioritizer.appendQueue(queue, i); this.queueTilesForPanos(queue, e, tileDownloader, s); // 如果前面有populateNeighborPanos的话,这步就是加neibour }; }(); TilePrioritizer.prototype.queueTilesInDirectionForPano = function () { var e = { filter: h.DirectionalFOV, direction: new Vector3(), fov: 60 }, t = new Vector3(); return function (i, n, pano, o, a, dirs, c) { var dir = dirs.datasetsLocal.find(e => e.datasetId == pano.pointcloud.dataset_id).direction; //add //var dir = dirs t.copy(dir); TileUtils.getRelativeDirection(pano.quaternion4dkk, t); e.direction.copy(t); e.fov = c; return this.filterAndQueueTileDownloadDescriptors(i, n, pano, o, e); }; }(); TilePrioritizer.prototype.filterAndQueueTileDownloadDescriptors = function () { var e = []; return function (t, i, n, r, o) { var a = i.getTileDownloadDescriptors(n, r); e.length = 0, this.filterTileDownloadDescriptors(n, a, e, o); for (var s = 0, l = 0; l < e.length; l++) { var c = e[l]; if (c) { t.push(c); s++; } } return s; }; }(); TilePrioritizer.prototype.filterTileDownloadDescriptors = function () { new Vector3(); return function (e, t, i, n) { var r, o; switch (n.filter) { case h.DirectionalFOV: for (r = 0; r < t.length; r++) o = t[r], TileUtils.isTileWithinFOV(o.panoSize, o.tileSize, o.face, o.tileX, o.tileY, n.direction, n.fov) && i.push(o); break; default: for (r = 0; r < t.length; r++) o = t[r], i.push(o); } for (r = 0; r < i.length; r++) o = i[r], this.canIncludeDescriptor(o) || (i[r] = null); }; }(); TilePrioritizer.prototype.queueTilesForPano = function () { var e = { filter: h.None }; return function (t, i, n, r) { return this.filterAndQueueTileDownloadDescriptors(t, i, n, r, e); }; }(); /* TilePrioritizer.prototype.queueTilesForPanosInDirection = function () { //没用到 var e = new THREE.Vector3; return function (t, i, n, r, o, a, s, l) { for (var h = 0, u = 0; u < n.length; u++) { var d = n[u]; e.copy(d.position), e.sub(o), e.normalize(); var p = Math.max(Math.min(a.dot(e), 1), -1), f = c.getFOVDotThreshold(s); if (p >= f) { var g = this.queueTilesInDirectionForPano(t, i, d, r, o, a, s); if (h += g > 0 ? 1 : 0, l && h >= l) break } } return h } }() */ //import { i18n } from "@/lang/index" // 媒体名称 /* export const mediaTypes = { image: i18n.t("common.photo"), video: i18n.t("common.video"), audio: i18n.t("common.voice"), } */ // 媒体扩展类型 var mediaMimes = { image: ["jpg", "png", "jpeg", "bmp", "gif"], audio: ["mp3", "aac", "ogg", "wav" /* , "m4a" */], video: ["mp4", "mov", "quicktime", "webm" /* "rmvb", "wmv" */] //ios:mov }; // 媒体大小显示(MB) var mediaMaxSize = { image: 10, video: 20, audio: 5 }; /** * 获取媒体扩展类型 * @param {Stirng} filename 文件名称 */ var getMime = filename => { if (!filename || filename.indexOf(".") === -1) { return ""; } return filename.split(".").pop().toLowerCase(); }; /** * 在路径中获取文件名 * @param {*} path */ var getFilename = path => { var segment = (path || "").split("/"); return segment[segment.length - 1]; }; /** * 检测媒体文件是否超过预设限制 * @param {String} type 媒体类型 * @param {Number} size 文件大小 */ var checkSizeLimit = (type, size) => { size = size / 1024 / 1024; return size <= mediaMaxSize[type]; }; var checkSizeLimitFree = (size, limit) => { size = size / 1024 / 1024; return size <= limit; }; /** * 检测媒体类型 * @param {String} type 媒体类型 * @param {String} filename 文件名称 */ var checkMediaMime = (type, filename) => { var mime = getMime(filename); var find = mediaMimes[type]; if (!find) { return false; } return find.indexOf(mime) !== -1; }; var checkMediaMimeByAccept = (accept, filename) => { var mime = getMime(filename); var type = accept; if (type && type.indexOf("jpg") == -1 && type.indexOf("jpeg") != -1) { type += ",image/jpg"; } return (type || "").indexOf(mime) != -1; }; var base64ToBlob = base64 => { var arr = base64.split(","), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); }; var base64ToDataURL = base64 => { return window.URL.createObjectURL(base64ToBlob(base64)); }; var blobToBase64 = function blobToBase64(blob) { return new Promise(resolve => { var reader = new FileReader(); reader.onload = function () { resolve(reader.result); }; reader.readAsDataURL(blob); }); }; /* * @Author: Rindy * @Date: 2019-08-06 16:25:08 * @LastEditors: Rindy * @LastEditTime: 2021-08-27 12:33:49 * @Description: Request */ //import { $alert, $confirm, $loginTips } from "@/components/shared/message" //import { $waiting } from "@/components/shared/loading" //import { checkLogin } from "@/api" //import { LoginDetector } from "@/core/starter" //import { i18n } from "@/lang" //import { password } from "@/utils/string" //import store from "../Store" // 空函数 var noop = function noop() {}; // 请求回调队列 var postQueue = []; /** * @property {number} NEXT - 继续执行 * @property {number} SUCCESS - 成功 * @property {number} EXCEPTION - 异常错误 * @property {number} FAILURE_CODE_3001 - 缺少必要参数 * @property {number} FAILURE_CODE_3002 - 访问异常 * @property {number} FAILURE_CODE_3003 - 非法访问 * @property {number} FAILURE_CODE_3004 - 用户未登录 * @property {number} FAILURE_CODE_3005 - 验证码已过期 * @property {number} FAILURE_CODE_3006 - 验证码错误 * @property {number} FAILURE_CODE_3007 - 昵称已存在 * @property {number} FAILURE_CODE_3008 - 该手机已被注册 * @property {number} FAILURE_CODE_3009 - 两次输入的密码不一致 * @property {number} FAILURE_CODE_3010 - 昵称长度错误 * @property {number} FAILURE_CODE_3011 - 密码长度错误 * @property {number} FAILURE_CODE_3012 - 昵称包含敏感词 * @property {number} FAILURE_CODE_3013 - 手机号码格式错误 * @property {number} FAILURE_CODE_3014 - 账号或密码不正确 * @property {number} FAILURE_CODE_3015 - 用户不存在 * @property {number} FAILURE_CODE_3016 - 您没有权限,请联系管理员 * @property {number} FAILURE_CODE_3017 - 空文件 * @property {number} FAILURE_CODE_3018 - 需要上传或使用的文件不存在 * @property {number} FAILURE_CODE_5010 - 找不到该场景对应的相机 * @property {number} FAILURE_CODE_5012 - 数据不正常 * @property {number} FAILURE_CODE_5014 - 无权操作该场景 * @property {number} FAILURE_CODE_5005 - 场景不存在 */ var statusCode = { NEXT: -999, SUCCESS: 0, EXCEPTION: -1, FAILURE_CODE_3001: 3001, FAILURE_CODE_3002: 3002, FAILURE_CODE_3003: 3003, FAILURE_CODE_3004: 3004, FAILURE_CODE_3005: 3005, FAILURE_CODE_3006: 3006, FAILURE_CODE_3007: 3007, FAILURE_CODE_3008: 3008, FAILURE_CODE_3009: 3009, FAILURE_CODE_3010: 3010, FAILURE_CODE_3011: 3011, FAILURE_CODE_3012: 3012, FAILURE_CODE_3013: 3013, FAILURE_CODE_3014: 3014, FAILURE_CODE_3015: 3015, FAILURE_CODE_3016: 3016, FAILURE_CODE_3017: 3017, FAILURE_CODE_3018: 3018, FAILURE_CODE_5010: 5010, FAILURE_CODE_5012: 5012, FAILURE_CODE_5014: 5014, FAILURE_CODE_5005: 5005 }; /** * 获取Token * @function */ function getToken() { var urlToken = browser.urlHasValue("token", true); if (urlToken) { // 设置token共享给用户中心 localStorage.setItem("token", urlToken); } return urlToken || localStorage.getItem("token") || ""; } /** * 根据状态码的结果处理后续操作 * @function * @param {number} code - 状态码 * @param {function} callback - 回调 */ function statusCodesHandler(code, callback) { if (code == statusCode.EXCEPTION) { return $alert({ content: i18n.t("tips.exception") }); } if (code == statusCode.FAILURE_CODE_3002 || code == statusCode.FAILURE_CODE_3003 || code == statusCode.FAILURE_CODE_3004) { callback(code); return showLoginTips(); } if (code == statusCode.FAILURE_CODE_3001) { callback(code); return $alert({ content: i18n.t("tips.params_notfound") }); } if (code == statusCode.FAILURE_CODE_3017) { callback(code); return $alert({ content: i18n.t("tips.file_notfound") }); } if (code == statusCode.FAILURE_CODE_5005) { /* if (!config.isEdit) { return (location.href = config.pages.NotFound) } */ callback(code); return $alert({ content: i18n.t("tips.scene_notfound") }); } if (code == statusCode.FAILURE_CODE_5010) { callback(code); return $alert({ content: i18n.t("tips.camera_notfound") }); } if (code == statusCode.FAILURE_CODE_5012) { callback(code); return $alert({ content: i18n.t("tips.data_error") }); } if (code == statusCode.FAILURE_CODE_5014) { callback(code); return $alert({ content: i18n.t("tips.auth_deny") }); } return statusCode.NEXT; } $.ajaxSetup({ headers: {}, beforeSend: function beforeSend(xhr) { var token = getToken(); if (token) { xhr.setRequestHeader("token", token); } else if (!token && this.url.indexOf("isLogin") != -1) { showLoginTips(); } /* if (config.oem == "localshow") { // 本地版本兼容当前目录 if (this.url.indexOf("http") == -1 && this.url.indexOf("/") == 0) { this.url = this.url.substr(1) } } */ // if(this.url.indexOf('http')==-1 && this.url.indexOf('/') !=0){ // this.url = '/'+this.url // } }, error: function error(xhr, status, _error) { // 出错时默认的处理函数 if (this.url.indexOf("/scene.json") != -1 && xhr.status == 404) { return $alert({ content: i18n.t("tips.scene_notfound") }); } else if (this.type === "POST") { return $alert({ content: i18n.t("tips.network_error") }); } }, success: function success(result) {}, complete: function complete() { // Post类型请求无论成功或失败都关闭等待提示 if (this.type === "POST") { http.__loading && $waiting.hide(); } http.__loading = true; } }); /** * @namespace http * @type {Object} */ var http = { statusCode, __loading: true, __request(xhr, method, url, data, done, fail) { if (typeof done != "function") { done = noop; } if (typeof fail != "function") { fail = noop; } xhr.done(result => { if (typeof result.code !== "undefined") { var flag = statusCodesHandler(result.code, function (code) { // 需要登录的状态 if (code == statusCode.FAILURE_CODE_3001 || code == statusCode.FAILURE_CODE_3002 || code == statusCode.FAILURE_CODE_3003 || code == statusCode.FAILURE_CODE_3004) { if (url.indexOf("isLogin") == -1 && url.indexOf("openSceneBykey") == -1) { postQueue.push(function () { http[method](url, data, done, fail); }); } } fail(); }); if (flag === statusCode.NEXT) { done(result, result.code == 0); } } else { done(result); } }); xhr.fail(fail); xhr.always(() => xhr = null); return xhr; }, /** * Get请求 * @param {String} url 请求地址 * @param {Object?} data 请求参数 * @param {Function?} done 成功回调 * @param {Function?} fail 失败回调 */ get(url) { var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var done = arguments.length > 2 ? arguments[2] : undefined; var fail = arguments.length > 3 ? arguments[3] : undefined; if (/\.json/.test(url)) { // json文件格式自动调用getJson方法 return this.getJson(url, data, done, fail); } return this.__request($.get(url, data), "get", url, data, done, fail); }, /** * Get Blob请求 * @param {String} url 请求地址 * @param {Object?} data 请求参数 * @param {Function?} done 成功回调 * @param {Function?} fail 失败回调 */ getText(url) { var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var done = arguments.length > 2 ? arguments[2] : undefined; var fail = arguments.length > 3 ? arguments[3] : undefined; return this.__request($.ajax({ url: url, dataType: "text" }), "getText", url, data, done, fail); }, /** * GetJson请求 读取json文件数据 * @param {String} url 请求地址 * @param {Object?} data 请求参数 * @param {Function?} done 成功回调 * @param {Function?} fail 失败回调 */ getJson(url) { var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var done = arguments.length > 2 ? arguments[2] : undefined; var fail = arguments.length > 3 ? arguments[3] : undefined; return this.__request($.getJSON(url, data), "get", url, data, done, fail); }, /** * Get Blob请求 * @param {String} url 请求地址 * @param {Object?} data 请求参数 * @param {Function?} done 成功回调 * @param {Function?} fail 失败回调 */ getBlob(url) { var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var done = arguments.length > 2 ? arguments[2] : undefined; var fail = arguments.length > 3 ? arguments[3] : undefined; return this.__request($.ajax({ url: url, dataType: "blob" }), "getBlob", url, data, done, fail); }, /** * Get Arraybuffer请求 * @param {String} url 请求地址 * @param {Object?} data 请求参数 * @param {Function?} done 成功回调 * @param {Function?} fail 失败回调 */ getArraybuffer(url) { var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var done = arguments.length > 2 ? arguments[2] : undefined; var fail = arguments.length > 3 ? arguments[3] : undefined; return this.__request($.ajax({ url: url, dataType: "arraybuffer" }), "getArraybuffer", url, data, done, fail); }, /** * Post 请求 * @param {String} url 请求地址 * @param {Object?} data 请求参数 * @param {Function?} done 成功回调 * @param {Function?} fail 失败回调 */ post(url) { var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var done = arguments.length > 2 ? arguments[2] : undefined; var fail = arguments.length > 3 ? arguments[3] : undefined; if (url.indexOf("isLogin") == -1) { http.__loading && $waiting.show(); } return this.__request($.post(url, data), "post", url, data, done, fail); }, /** * PostJson 请求 * @param {String} url 请求地址 * @param {Object?} data 请求参数 * @param {Function?} done 成功回调 * @param {Function?} fail 失败回调 */ postJson(url) { var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var done = arguments.length > 2 ? arguments[2] : undefined; var fail = arguments.length > 3 ? arguments[3] : undefined; http.__loading && $waiting.show(); return this.__request($.ajax({ type: "POST", url: url, contentType: "application/json", data: JSON.stringify(data) }), "postJson", url, data, done, fail); }, /** * Post 表单 支持文件上传 * @param {String} url 请求地址 * @param {FormData?} formData 请求参数 * @param {Function?} done 成功回调 * @param {Function?} fail 失败回调 */ postForm(url, formData, done, fail, onProgress) { if (typeof onProgress === "function") { return this.__request($.ajax({ type: "POST", url: url, processData: false, contentType: false, data: formData, xhr: function xhr() { var xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", function (e) { onProgress(e.loaded / e.total * 100 + "%"); }); return xhr; } }), "postForm", url, formData, done, fail); } else { http.__loading && $waiting.show(); return this.__request($.ajax({ type: "POST", url: url, processData: false, contentType: false, data: formData }), "postForm", url, formData, done, fail); } }, /** * 加载图片 * @param {String} url 请求地址 * @param {Number?} retry 重试次数,默认为3 */ loadImage(url) { var retry = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3; var def = $.Deferred(); var img = new Image(); /* if (process.env.VUE_APP_REGION == "AWS" && url.indexOf("x-oss-process=image") != -1) { var arr = url.split("?") url = arr[0] + encodeURIComponent("?" + arr[1].replace(/\//g, "@")) } */ var load = () => { console.warn("Retrying load image: " + url); this.loadImage(url, retry - 1).done(def.resolve.bind(def)).progress(def.notify.bind(def)).fail(def.reject.bind(def)); }; img.onerror = function () { retry > 0 ? setTimeout(() => load(), 1e3) : def.reject("[".concat(url, "]\u52A0\u8F7D\u5931\u8D25")); }; img.onload = function () { def.resolve(img); }; img.crossOrigin = "anonymous"; img.src = url; return def; }, /** * 上传文件 * @param {String} url 请求地址 * @param {Object?} data 请求参数 * @param {Function?} done 成功回调 * @param {Function?} fail 失败回调 */ uploadFile(url) { var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var done = arguments.length > 2 ? arguments[2] : undefined; var fail = arguments.length > 3 ? arguments[3] : undefined; var onProgress = arguments.length > 4 ? arguments[4] : undefined; var form = new FormData(); // if (file.needTransfer) { //ie和苹果都不支持dataURLtoFile得传送,所以只能用blob // form.append("file", common.dataURLtoBlob(file.file), file.name || file.file.name); // } else { // form.append("file", file.file, file.name || file.file.name); // } for (var key in data) { if (key == "file") { form.append("file", data[key], data.filename || data[key].name); } else if (key != "filename") { form.append(key, data[key]); } } return this.postForm(url, form, done, fail, onProgress); }, /** * 上传文件 * @param {String} url 请求地址 * @param {Object?} data 请求参数 {file:'base64 string',filename:'image.jpg',...} * @param {Function?} done 成功回调 * @param {Function?} fail 失败回调 */ uploadBlobFile(url) { var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var done = arguments.length > 2 ? arguments[2] : undefined; var fail = arguments.length > 3 ? arguments[3] : undefined; var form = new FormData(); for (var key in data) { if (key === "file") { form.append("file", base64ToBlob(data.file), data.filename); } else if (key != "filename") { form.append(key, data[key]); } } return this.postForm(url, form, done, fail); } }; var { TileDownloaderEvents, DownloadStatus: DownloadStatus$1 } = Potree.defines; window.downloaded = {}; window.startdownloads = []; class TileDownloader extends EventDispatcher { constructor() { super(); this.panos = null; this.retryMinimumTime = 1e4; this.panoLoadCallbacks = {}; this.downloadDescriptors = {}; this.priorityQueue = []; this.forceQueue = []; this.activeDownloads = []; this.tilePrioritizer = null; this.refreshInterval = null; this.processPriorityQueue = !1; this.concurrentDownloads = 6; //e.concurrentDownloads || 1; this.downloadTestResults = {}; this.freeze = Object.freeze({ Testing: 1, Success: 2, Fail: 3 }); /* viewer.addEventListener('pageVisible', (e)=>{//不可见时不refreshUpdateInterval //console.log('visibilitychange:', state) Potree.Utils.updateVisible(this, 'pageVisible', e.v) this.judgeStart() }) this.visible = true //add 借用Potree.Utils.updateVisible来判断是否start if(Potree.settings.useDepthTex){ this.judgeStart() //开始下载depthTex }else{ Potree.Utils.updateVisible(this,'showPanos', false ) //默认visible = false } */ } setPanoData(e, t /* , i */) { this.panos = e, this.imagePanos = t; // this.panoGroupId = i } start() { this.downloadCubeTex = true; /* if(!Potree.settings.useDepthTex){ Potree.Utils.updateVisible(this,'showPanos', true ) this.judgeStart() }else{ //this.refreshInterval || this.judgeStart() } */ } stop() { this.downloadCubeTex = false; /* if(!Potree.settings.useDepthTex){ Potree.Utils.updateVisible(this,'showPanos', false ) this.judgeStart() } */ } /* judgeStart(){//add if(this.visible){ //console.log('judgeStart true') this.started = true //this.refreshUpdateInterval(0) }else{ //console.log('judgeStart false') this.started = false //window.clearTimeout(this.refreshInterval) } } */ /* refreshUpdateInterval(e) { e || (e = 0), this.refreshInterval = window.setTimeout(function() { var e = this.update(); e ? this.refreshUpdateInterval(TileDownloader.ACTIVE_REFRESH_DELAY) : this.refreshUpdateInterval(TileDownloader.IDLE_REFRESH_DELAY) } .bind(this), e) } */ update() { if (this.downloadCubeTex) { //可以下载贴图 var e = this.forceQueue.length > 0; this.processQueueForDownloading(this.forceQueue); if (this.processPriorityQueue) { Potree.Common.intervalTool.isWaiting('processPriorityQueue', () => { //延时update,防止崩溃 , 未到时间就拦截(第一次直接执行) this.queuePrioritizedTilesForPanos(this.panos); //这句比较耗时 降四倍时大概1-2毫秒 }, 66); this.priorityQueue.length > 0 && (e = !0); this.processQueueForDownloading(this.priorityQueue); } //return e } Potree.Common.intervalTool.isWaiting('filterDepthTex', () => { this.tilePrioritizer.filterDepthTex(this.panos); //下载深度图 }, 77); } queuePrioritizedTilesForPanos(e) { this.tilePrioritizer && (this.clearQueue(this.priorityQueue), this.tilePrioritizer.filterAndPrioritize(this.priorityQueue, e, this), this.clearFromQueue(this.priorityQueue, DownloadStatus$1.None, !0), //去除state为DownloadStatus.None的(可能是去除已经在下载的) this.setStatusOrRemoveForAllDescriptors(this.priorityQueue, DownloadStatus$1.Queued)); } clearQueue(e) { //停止下载并清空 this.setStatusForAllDescriptors(e, DownloadStatus$1.None), e.length = 0; } clearForceQueue() { this.clearQueue(this.forceQueue); } clearFromQueue(e, t, i) { for (var n = 0; n < e.length; n++) { var r = e[n]; r && (t === r.status && !i || t !== r.status && i) && (e[n] = null); } } setStatusForAllDescriptors(e, t) { for (var i = 0; i < e.length; i++) { var n = e[i]; n && (n.status = t); } } setStatusOrRemoveForAllDescriptors(e, t) { for (var i = 0; i < e.length; i++) { var n = e[i]; n && (n.status !== t ? n.status = t : e[i] = null); } } getTileDownloadDescriptors(pano, size) { //获取该pano的该size的全部的tile的descriptor var i = this.getAllTileDownloadDescriptorsForPano(pano), n = i[size]; return n || (n = this.buildDownloadDescriptorArray(size), //创建的全部是空的 i[size] = n, this.initTileDownloadDescriptors(n, pano, size)), //绑定到该pano size n; } getAllTileDownloadDescriptorsForPano(pano) { //新建空Descriptors var t = this.downloadDescriptors[pano.id]; return t || (t = {}, this.downloadDescriptors[pano.id] = t), t; } processQueueForDownloading(e, t) { //执行下载任务 this.cleanupActiveDownloads(); if (e.length) { var concurrentDownloads = Potree.Common.getBestCount('concurrentDownloads', 1, 6, 1.8, 14 /* ,true */); //flying ? (isMobile ? 2 : 3) : 6 if (this.activeDownloads.length < concurrentDownloads || t) { var i = t ? e.length : concurrentDownloads - this.activeDownloads.length; for (var n = 0, r = 0; n < i && e.length > 0; r++) { var o = e.shift(); if (o) { //add 为了防止1024的在512前下载完,这里强行等待512下载完毕再开始下载 if (o.panoSize > 512 && !this.isPanoDownloaded(o.pano, 512)) { //console.log('512的还没下载好呢!') e.push(o); break; //一般512的都是连续下载的,所以后面就都不是512了直接中断 } this.startDownload(o); n++; } } } } } testDownload(panoSize, tileSize, callback) { var n = this.downloadTestResults[panoSize]; if (n) return void (n === this.freeze.Success ? callback(!0) : n === this.freeze.Fail && callback(!1)); this.downloadTestResults[panoSize] = this.freeze.Testing; var r = this.panos[0], o = this.getTileUrl({ pano: r, panoSize, tileSize, tileIndex: 0 } /* r.id, panoSize, tileSize, 0 */), a = function (t) { this.downloadTestResults[panoSize] = this.freeze.Success, callback(!0); }.bind(this), s = function () { this.downloadTestResults[panoSize] = this.freeze.Fail, callback(!1); }.bind(this); this.loadImage(o, 0, a, s); } startDownload(e) { //开始下载啦 //console.log('startDownload') startdownloads.push(e); e.local2SrcFailed = this.local2SrcFailed; e.status = DownloadStatus$1.Downloading; var t = this.getTileUrl(e /* e.pano.id, e.panoSize, e.tileSize, e.tileIndex, e.pano.alignmentType */); //xzw add alignmentType if (!t) return; this.activeDownloads.push(e); this.loadImage(t, TileDownloader.DOWNLOAD_RETRIES, this.downloadComplete.bind(this, e), this.downloadFailed.bind(this, e)); } downloadFailed(e, t) { //add if (Potree.settings.isLocal2 && !e.local2SrcFailed) { //为了兼容旧的数据src,如果新src没加载成功,就加载旧的 e.local2SrcFailed = this.local2SrcFailed = true; //this.startDownload(e)//重新下载 var t = this.getTileUrl(e); this.loadImage(t, TileDownloader.DOWNLOAD_RETRIES, this.downloadComplete.bind(this, e), this.downloadFailed.bind(this, e)); } } downloadComplete(e, t) { //下载成功时 //if (e.panoGroupId === this.panoGroupId) { var i = this.getPanoLoadCallbacks(e.pano, e.panoSize); e.status = DownloadStatus$1.Downloaded, i && i.onProgress && i.onProgress(e.pano, e.panoSize); var n = { panoId: e.pano.id, image: t, tileSize: e.tileSize, panoSize: e.panoSize, tileIndex: e.tileIndex, faceTileIndex: e.faceTileIndex, totalTiles: e.totalTiles, face: e.face, tileX: e.tileX, tileY: e.tileY, direction: e.direction }; downloaded[e.pano.id] || (downloaded[e.pano.id] = { 512: [], 1024: [], 2048: [] }); downloaded[e.pano.id][e.panoSize] || (downloaded[e.pano.id][e.panoSize] = []); downloaded[e.pano.id][e.panoSize].push(e); if (e.panoSize != 512 && downloaded[e.pano.id][512].length < 6) { console.warn('没下完'); } e.image = t, this.dispatchEvent({ type: TileDownloaderEvents.TileDownloadSuccess, desc: n }); this.isPanoDownloaded(e.pano, e.panoSize) && (n = { panoId: e.pano.id, tileSize: e.tileSize, panoSize: e.panoSize }, this.dispatchEvent({ type: TileDownloaderEvents.PanoDownloadComplete, desc: n }), i && i.onLoad && i.onLoad(e.pano, e.panoSize)); //} } isPanoDownloaded(e, t) { var i = this.getTileDownloadDescriptors(e, t); if (i.length <= 0) return !1; for (var n = 0; n < i.length; n++) { var r = i[n]; if (r.status !== DownloadStatus$1.Downloaded) return !1; } return !0; } setPanoLoadCallbacks(e, t, i, n, r) { var o = e.id + ":" + this.qualityManager.getPanoSize(t); this.panoLoadCallbacks[o] = { onLoad: i, onFail: n, onProgress: r }; } getPanoLoadCallbacks(e, t) { var i = e.id + ":" + t; return this.panoLoadCallbacks[i]; } buildDownloadDescriptorArray(e) { for (var t = TileUtils.getTileCountForSize(e), i = [], n = 0; n < t; n++) { var r = this.buildDownloadDescriptor(); i.push(r); } return i; } buildDownloadDescriptor() { //Descriptor! var e = { panoGroupId: null, pano: null, panoSize: -1, tileSize: -1, tileIndex: -1, totalTiles: -1, faceTileIndex: -1, status: DownloadStatus$1.None, url: null, image: null, direction: new Vector3(), //该tile在cube中的方向 face: -1, cubeFace: -1, tileX: -1, tileY: -1 }; return e; } initTileDownloadDescriptors(e, t, i) { for (var n = 0; n < e.length; n++) { var r = e[n]; this.initTileDownloadDescriptor(r, t, i, n); } } initTileDownloadDescriptor(desc, pano, size, index) { var r = size >= TileUtils.TILE_SIZE ? TileUtils.TILE_SIZE : size; desc.face = TileUtils.getFaceForTile(size, index); //根据顺序得到的face的index desc.cubeFace = TileUtils.mapFaceToCubemapFace(desc.face); //为了贴图而转化的face index //desc.panoGroupId = this.panoGroupId;//就是场景号 desc.pano = pano; desc.panoSize = size; desc.tileSize = r; //瓦片图size 512 desc.tileIndex = index; desc.totalTiles = TileUtils.getTileCountForSize(size); desc.status = DownloadStatus$1.None; desc.image = null; TileUtils.getTileLocation(desc.panoSize, desc.tileIndex, desc); //得到该tile在这个face中的具体位置(tileX等) TileUtils.getTileVector(desc.panoSize, desc.tileSize, desc.cubeFace, desc.tileX, desc.tileY, TileUtils.LocationOnTile.Center, 0, desc.direction); } getTiles(d, sceneNum, useV4url, pointcloud) { var v3OrV4Str = useV4url ? "/scene_view_data/".concat(sceneNum, "/images/") : "/images/images".concat(sceneNum, "/"); if (Potree.settings.isLocal && !this.local2SrcFailed && pointcloud.datasetData.mapping && !Potree.settings.isLocal2) { //非离线包的话加mapping return "".concat(Potree.settings.urls.prefix3, "/").concat(pointcloud.datasetData.mapping).concat(v3OrV4Str).concat(d); } return "".concat(Potree.settings.urls.prefix3).concat(v3OrV4Str).concat(d); /* if(Potree.settings.isLocal && !this.local2SrcFailed || useV4url){//新的地址 scene_view_data/场景码/images/tiles if(pointcloud.datasetData.mapping && !Potree.settings.isLocal2){//非离线包的话加mapping return `${Potree.settings.urls.prefix3}/${pointcloud.datasetData.mapping}/scene_view_data/${sceneNum}/images/${d}` }else{ return `${Potree.settings.urls.prefix3}/scene_view_data/${sceneNum}/images/${d}` } } return `${Potree.settings.urls.prefix3}/images/images${sceneNum}/${d}` */ } loadImage(e, t, i, n) { //自己修改了ajax,把getImage改成了loadImg http.loadImage(e, t).then(function (e) { i(e); }).fail(n); } } TileDownloader.prototype.forceQueueTilesForPano = function () { //根据条件开始加载tile var e = [], t = []; return function (pano, size, dir, hFov, vFov, download) { e.length = 0; for (var u = this.getTileDownloadDescriptors(pano, size), d = 0; d < u.length; d++) { var p = u[d]; p.status !== DownloadStatus$1.None && p.status !== DownloadStatus$1.Queued || e.push(p); } if (dir && e.length > 0) { TilePrioritizer.sortPanoTiles(e, pano, dir); //按最佳方向排序e t.length = 0; TileUtils.matchingTilesInDirection(pano, size, dir, hFov, vFov, t); //得到在符合视野标准的集合t for (var f = 0, g = function g(e) { return e.face === m.face && e.faceTileIndex === m.faceTileIndex; }; f < e.length;) { //过滤掉不符合角度要求的 var m = e[f], v = t.findIndex(g); v < 0 ? e.splice(f, 1) : f++; } } for (var A = 0; A < e.length; A++) { this.forceQueue.push(e[A]); //装载 } /* if(e.length){ console.log(e) } */ this.setStatusForAllDescriptors(this.forceQueue, DownloadStatus$1.ForceQueued); this.clearFromQueue(this.priorityQueue, DownloadStatus$1.ForceQueued, !1); download && this.processQueueForDownloading(this.forceQueue, !0); }; }(); TileDownloader.prototype.cleanupActiveDownloads = function () { var e = []; return function () { e.length = 0; for (var t = 0; t < this.activeDownloads.length; t++) { var i = this.activeDownloads[t]; i.status !== DownloadStatus$1.Downloaded && i.status !== DownloadStatus$1.Failed && e.push(i); } this.activeDownloads.length = 0, this.activeDownloads.push.apply(this.activeDownloads, e); }; }(); TileDownloader.prototype.getTileUrl = function () { var e = { 256: "256", 512: "512", 1024: "1k", 2048: "2k", 4096: "4k" }, t = { face: -1, faceTileIndex: -1, tileX: -1, tileY: -1 }; return function () { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var id = o.pano.originID, //////// panoSize = o.panoSize, tileSize = o.tileSize, tileIndex = o.tileIndex, sceneCode = o.pano.pointcloud.sceneCode, useV4url = Potree.settings.useV4url && o.pano.pointcloud.datasetData.sceneVersion == 'V4'; //v4的全景图等路径不一样 var metadata = { sceneScheme: 10 }; TileUtils.getTileLocation(panoSize, tileIndex, t); var s = Math.floor(panoSize / tileSize), l = s * s, h = Math.floor(tileIndex / l), u = "", d = '', g = ''; if (Potree.settings.tileOriginUrl) { //原始规则 //1 === config.tiling.customCompression && (u = "_" + config.tiling["q" + e[panoSize]]); //1 === o.tiling.customCompression && (u = "_" + o.tiling["q" + e[n]]); d = "tiles/" + id + "/" + e[panoSize] + u + "_face" + h + "_" + t.tileX + "_" + t.tileY + ".jpg"; d = this.getTiles(d, sceneCode, useV4url, o.pano.pointcloud); g = "?"; } else { //阿里云oss的规则 if (metadata.sceneScheme == 10) d = 'tiles/4k/' + id + '_skybox' + h + '.jpg?x-oss-process='; if (e[panoSize] == '512') { d += 'image/resize,h_512'; } else { //4k的图,移动端是1k,pc端是2k,放大才是4k if (e[panoSize] == '1k' || e[panoSize] == '2k') { //https://4dkk.4dage.com/images/imagesx4iqYDG3/tiles/4k/122_skybox0.jpg?x-oss-process=image/resize,m_lfit,w_1024/crop,w_512,h_512,x_511,y_0 d += 'image/resize,m_lfit,w_' + panoSize + '/crop,w_512,h_512,'; } else { d = 'tiles/4k/' + id + '_skybox' + h + '.jpg?x-oss-process=image/crop,w_512,h_512,'; } //起始位置 if (t.tileX == 0) { d += 'x_0,'; } else { d += 'x_' + 512 * t.tileX /* - 1 */ + ','; } if (t.tileY == 0) { d += 'y_0'; } else { d += 'y_' + 512 * t.tileY /* - 1 */; } } d = this.getTiles(d, sceneCode, useV4url, o.pano.pointcloud); g = "&"; } //Potree.settings.panoVersion = 4 d += g + (Potree.settings.panoVersion ? 'version=' + Potree.settings.panoVersion : 'time=' + o.pano.pointcloud.timeStamp); //加后缀 return d; /* 4dkk getViewImagesURL(url) { if (url.indexOf('&_=') !== -1) { return url } let version = url.indexOf('/panorama/') !== -1 ? this.linkVersion : this.imageVersion if (url.indexOf('?') !== -1) { return this.$app.config.resource + `scene_view_data/${this.num}/images/${url}&_=${version}` } return this.$app.config.resource + `scene_view_data/${this.num}/images/${url}?_=${version}` } /** */ }; }(); TileDownloader.tilegen = true; TileDownloader.IDLE_REFRESH_DELAY = 500; TileDownloader.ACTIVE_REFRESH_DELAY = 16; TileDownloader.DOWNLOAD_RETRIES = 4; function Node$1(e, t) { this.tree = e, //所属树(TileTree) this.parent = t, this.children = [], this.id = ++u$1; } function o(e, t, i, r, a, s, l, h) { if (e) { l = l || TileTree.TraversalType.PreOrder; var u = r * c + i; if (l === TileTree.TraversalType.PreOrder && (a && a(e, t, u, i, r), s && s.push(e)), e.children && 0 !== e.children.length) { for (var d = r * c, p = i * c, f = 0; f < c; f++) for (var g = 0; g < c; g++) o(e.children[g * c + f], t + 1, p + f, d + g, a, s, l, h); l === TileTree.TraversalType.PostOrder && (a && a(e, t, u, i, r), s && s.push(e)); } } } function Plant(seed) { seed.root = Branch(seed, null, 0); } function Branch(seed, parent, level) { if (level > seed.levels) return null; var node = new Node$1(seed, parent); seed.allNodes.push(node); for (var o = 0; o < h$1; o++) node.children[o] = Branch(seed, node, level + 1); return node; } function l(parent, t, level, n, r) { if (!parent) return null; if (0 === level) return parent; if (!parent.children || 0 === parent.children.length) return null; var o = Math.pow(c, level), a = o / c, s = n % a, h = r % a, u = Math.floor(r / a), d = Math.floor(n / a), p = u * c + d, f = parent.children[p]; return l(f, t + 1, level - 1, s, h); } /* cube每个面都有一个分层树 用于代表瓦片图的细分? 树4096的分为三层,每层有4个子节点。(最后一层的四个子节点都是null) */ var c = 2, h$1 = c * c; //4个子节点 var u$1 = 0; class TileTree { constructor(e, t) { this.levels = t, this.tileSize = e, this.root = null, this.allNodes = [], Plant(this); } getSubNode(e, t, i) { (!t || e < this.tileSize) && (t = 0), (!i || e < this.tileSize) && (i = 0), e < this.tileSize && (e = this.tileSize); var level = TileTree.getLevelCountForSize(this.tileSize, e), o = l(this.root, 0, level, t, i); return o; } breadthFirst(e) { //广度优先搜索 e = e || {}; var t = !!e.nullLevelEnd, i = e.maxLevel, n = e.minLevel, r = e.callback, o = e.saveVisited, a = [], s = {}, l = 0, c = 0; for (a.push(this.root), a.push(s); a.length > 0 && !(i && l > i);) { var h = a.shift(); if (h === s) (!n || l >= n) && (r && t && r(null), o && t && o.push(null)), a.length > 0 && a.push(s), l++, c = 0;else { if (h.children) for (var u = 0; u < h.children.length; u++) { var d = h.children[u]; d && a.push(h.children[u]); } var p = this.getFaceIndexFromNode(h); (!n || l >= n) && (r && r(h, l, p), o && o.push(h)), c++; } } } getFaceIndexFromNode(e) { if (!e) return -1; for (var t = 1, i = e, n = 0, r = 0;;) { var o = i.parent; if (!o) break; for (var a = -1, s = 0; s < o.children.length; s++) o.children[s] === i && (a = s); var l = a % c, h = Math.floor(a / c); n = l * t + n, r = h * t + r, t *= c, i = o; } return r * t + n; } depthFirst(e, t, i) { o(this.root, 0, 0, 0, e, t, i, this.tileSize); } } TileTree.TraversalType = Object.freeze({ PreOrder: 0, PostOrder: 1 }); TileTree.getLevelCountForSize = function (tileSize, size) { //512->0 2024->1 var i = 0; for (size < tileSize && (size = tileSize);;) { if (size /= c, size < tileSize) break; i++; } return i; }; TileTree.getSizeForLevel = function (e, t) { return Math.pow(c, t) * e; }; var { PanoSizeClass: PanoSizeClass$2, PanoRendererEvents: PanoRendererEvents$1, Vectors, SceneRendererEvents, TileDownloaderEvents: TileDownloaderEvents$1, GLCubeFaces: GLCubeFaces$2 } = Potree.defines; function createDescriptor() { var e = { renderTarget: null, inUse: !1, size: -1, pano: null }; return e; } /* function upload() { if (!this.uploadIntervalCancelled) { if (this.overlayTilesLoaded || !this.usingTileOverlay) { b = !0 let maxNonBaseUploadsPerFrame = viewer.mainViewport.view.isFlying() ? 1 : this.maxNonBaseUploadsPerFrame //原先2。这是每帧uploadTile非512的瓦片tex的数量。之前的2太卡了,降为1。(检测卡顿方法:在一个pano点旋转至所有2048的tile都加载完,然后之后到这个点看看卡不卡。因为该点tiles都下载完了所以会在飞过来时陆续都加载,所以容易卡) this.updateUploadQueue(maxNonBaseUploadsPerFrame, this.maxBaseUploadsPerFrame) let time = viewer.mainViewport.view.isFlying() ? 60 : w //add 飞行有时候会卡,增长间隔 this.peekNextFromUploadQueue() ? this.refreshUploadInterval(time) : this.uploadInterval = null //定时下一次更新 } else { this.refreshUploadInterval(this.uploadIntervalDelay) } } } */ var b = !1, w = config$1.tiling.uploadIntervalDelay, _ = config$1.tiling.initialIntervalDelay, T = config$1.tiling.maxNonBaseUploadsPerFrame, //2 size>512的每次只upload这么多个 x$1 = config$1.tiling.maxBaseUploadsPerFrame, //6 S = { Base: 0, Remaining: 1 }; /* , M = []; */ class PanoRenderer extends EventDispatcher { constructor(viewer, tileDownloader, qualityManager) { super(); this.tileDirectory = {}; this.activeRenderTargetDescriptors = {}; this.activePanos = []; this.panoLODDescriptors = {}; this.panoDescriptors = {}; this.tileTrees = {}; this.forceQueue = []; this.uploadQueues = {}; this.uploadInterval = null; this.uploadIntervalCancelled = true; //!1; this.usingTileOverlay = !1; this.overlayTilesLoaded = !1; this.overlayTileBase = null; this.overlayTilesBasic = {}; this.overlayTilesEnhanced = {}; this.zoomRenderTarget = null; //用于缩放的rendertarget this.zoomPano = null; this.zoomingActive = !1; this.zoomPanoId = null; this.zoomPanoRenderingDisabled = !1; this.direction = []; //new THREE.Vector3; this.maxBaseUploadsPerFrame = x$1; this.maxNonBaseUploadsPerFrame = T; this.M = []; //move M to here 似乎列表里会有两个 this.viewer = viewer; this.tileDownloader = tileDownloader; this.qualityManager = qualityManager; this.initTime = performance.now(); this.bindEvents(); } getActivePanoTextures(e) { e = e || []; for (var t = 0; t < M.length; t++) { var i = M[t]; i.renderTarget && i.renderTarget.texture && e.push(i.renderTarget.texture); } } hasQueuedTiles() { var e = this.peekNextFromUploadQueue(); return null !== e && void 0 !== e; } getActiveRenderTargetDescriptor(e) { return this.activeRenderTargetDescriptors[e]; } setActiveRenderTargetDescriptor(e, t) { this.activeRenderTargetDescriptors[e] = t; } bindEvents() { this.tileDownloader.addEventListener(TileDownloaderEvents$1.TileDownloadSuccess, this.onTileDownloaded.bind(this)); } enableUltraHighQualityMode(e) { if (config$1.tileClass == "2k" || config$1.tileClass == "1k") return this.enableHighQuality(e); //xzw add 濡傛灉鏈€澶氬彧瑕?k鐨勮瘽 if (!this.qualityManager.ultraHighQualityModeEnabled()) { var t = this.qualityManager.getPanoSize(PanoSizeClass$2.ULTRAHIGH); this.tileDownloader.testDownload(t, TileUtils.TILE_SIZE, function (t) { t && (this.qualityManager.enableUltraHighQualityMode(), this.setupZoomRenderTarget(), e()); }.bind(this)); } } activateTiledPano(pano, size, i) { i && this.clearAllQueuedUploads(); for (var n = 0; n < TileUtils.FACES_PER_PANO; n++) this.initTileTree(pano.id, n, this.qualityManager.getMaxPossiblePanoSize()); //得到this.tileTrees[pano.id],arr[6] this.linkAllTilesAndNodes(pano); var r = this.getActiveRenderTargetDescriptor(pano.id), l = size; l > this.qualityManager.getMaxNavPanoSize() && (l = this.qualityManager.getMaxNavPanoSize()); if (!r || l !== r.size) { r && this.deactiveDescripor(r.renderTarget); r = this.activeDescripor(l); if (!r) { var ren = this.initTiledPano(l, Potree.settings.disableAATarget ? false : !browser.isMobile()); //有的老设备如果抗锯齿打开场景时要多花五秒 r = this.initDescriptor(ren.width); r.renderTarget = ren; } r.pano = pano; this.resetPanoDescriptor(pano.id); this.resetPanoLODDescriptors(pano.id); this.resetRenderStatus(pano.id, !0, !0); } this.setActiveRenderTargetDescriptor(pano.id, r); var h = i ? 0 : 1; this.updateActivePanos(pano, h); //console.log(`index:${this.viewer.index} ${r.renderTarget.texture.id} ${pano.id}`) return r.renderTarget; } deactivateTiledPano(pano) { var t = this.getActiveRenderTargetDescriptor(pano.id); if (this.isRenderTargetDescriptorValid(t)) { this.deactiveDescripor(t.renderTarget); this.setActiveRenderTargetDescriptor(pano.id, null); } var i = this.getUploadQueueForPano(pano.id); this.clearUploadQueue(i); this.updateActivePanos(); viewer.cancelLoad(pano); //add } getActivePanoCount() { return this.activePanos.length; } resetRenderStatus(e, t, i, n) { var r = null; n && (r = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, n) + 1); for (var o = function o(e, n, r, _o) { i && (n.tile.zoomUploaded = !1), t && (n.tile.uploaded = !1); }, a = 0; a < TileUtils.FACES_PER_PANO; a++) { var s = this.getTileTree(e, a); s.breadthFirst({ callback: o.bind(this, a), minLevel: r }); } } copyBaseRenderStatusToZoomed(e) { for (var t = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, this.qualityManager.getMaxNavPanoSize()), i = function i(e, t, _i, n) { t.tile.zoomUploaded = t.tile.uploaded, t.zoomCovered = t.covered; }, n = 0; n < TileUtils.FACES_PER_PANO; n++) { var r = this.getTileTree(e, n); r.breadthFirst({ callback: i.bind(this, n), maxLevel: t }); } } isRenderTargetDescriptorValid(e) { return e && e.renderTarget; } isPanoActive(e) { var t = this.getActiveRenderTargetDescriptor(e); return this.isRenderTargetDescriptorValid(t); } isPanoZoomed(e) { return this.zoomingActive && this.zoomPanoId === e; } initTileTree(e, t, i) { var n = this.tileTrees[e]; n || (n = [], this.tileTrees[e] = n); var r = n[t]; if (!r) { var o = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, i); r = new TileTree(TileUtils.TILE_SIZE, o), n[t] = r; } } getTileTree(e, t) { var i = this.tileTrees[e]; if (!i) console.error("PanoRenderer.getTileTree() -> Tree array not yet initialized!"); var n = i[t]; if (!n) console.error("PanoRenderer.getTileTree() -> Tree not yet initialized!"); return n; } /* * 创建tile的renderTarget, 包括pano.tiledPanoRenderTarget和zoomRenderTarget * @param {number} size 当前的panoSize,每个面的分辨率 */ initTiledPano(size, ifNormalFilter) { //创建 RenderTargetCube var renderer = this.viewer.renderer; var renderTarget, texture; renderTarget = new WebGLCubeRenderTarget(size, { //THREE.WebGLRenderTargetCube(size, size, { stencilBuffer: !1 }); texture = new CubeTexture([]); texture.image = [null, null, null, null, null, null]; texture.flipY = !0, texture.format = RGBAFormat; ifNormalFilter ? (texture.generateMipmaps = !0, texture.magFilter = LinearFilter, texture.minFilter = LinearMipMapLinearFilter) : (texture.generateMipmaps = !1, texture.magFilter = LinearFilter, //LinearFilter更清晰,但锯齿噪点严重,相当于锐化,其实失真了。对于条纹状的画面移动镜头时锯齿明显 眩晕 texture.minFilter = LinearFilter); //平时还是直接用LinearMipMapLinearFilter,其实并非不清晰,只是没有加锐化,像加了层柔光和抗锯齿,观感更好。放大后使用LinearFilter // 如果抗锯齿的话,采用mipmap,会增加一倍的存储消耗。原版本都是不抗锯齿的。但是抗锯齿效果更柔和 renderTarget.texture = texture; //居然漏了一句,2022.10.9补 renderer.setRenderTarget(renderTarget); renderer.setRenderTarget(null); var o = renderer.properties.get(texture); o.__image__webglTextureCube = o.__webglTexture; //window.tex[r.id] = {texture:r, index:this.viewer.index } return renderTarget; } getUploadQueueForPano(e) { var t = this.uploadQueues[e]; return t || (t = [], this.uploadQueues[e] = t), t; } isTileUploaded(e) { return this.isPanoZoomed(e.panoId) ? e.zoomUploaded : e.uploaded; } setUploaded(e, t) { this.isPanoZoomed(e.panoId) ? e.zoomUploaded = t : e.uploaded = t; } queueTileUpload(e, t, i) { var n = this.getActiveRenderTargetDescriptor(e.panoId); if (this.isRenderTargetDescriptorValid(n) && e.downloaded && !this.isTileUploaded(e) && (!e.uploadQueued || i) && (!(e.panoSize > this.qualityManager.getMaxNavPanoSize()) || this.zoomingActive)) { var r = this.getUploadQueueForPano(e.panoId); //console.log(window.sceneName, 'queueTileUpload: ', e.panoId, e.tileIndex, i) if (i) { //console.log('512下载好了直接uploadTile') this.uploadTile(e, !1); //提交后该tile直接loaded了,无需等待 } else { if (this.shoulPushToFrontOfQueue(e)) { //如果是512的优先 this.forceQueue.push(e); } else { if (t && this.direction) { TilePrioritizer.insertSortedPanoTile(r, e, n.pano, this.direction); } else r.push(e); } e.uploadQueued = !0; this.uploadInterval || this.uploadIntervalCancelled || this.refreshUploadInterval(0); } } } shoulPushToFrontOfQueue(e) { return 0 === TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, e.panoSize); } getTopUploadQueue() { for (var e = null, t = null, i = S.Base; i <= S.Remaining; i++) for (var n = 0; n < this.activePanos.length; n++) if (e = this.activePanos[n], t = this.getUploadQueueForPano(e.id), t.length > 0) switch (i) { case S.Base: if (0 === t[0].level) return t; break; case S.Remaining: return t; } return null; } peekNextFromUploadQueue() { if (this.forceQueue.length > 0) return this.forceQueue[0]; var e = this.getTopUploadQueue(); return e && e.length > 0 ? e[0] : null; } clearAllQueuedUploads() { this.clearAllUploadQueues(null, 0); } clearAllQueuedUploadsForPano(e) { this.clearAllUploadQueues(e, 0); } clearAllUploadQueues(e, t) { if (e) this.clearUploadQueue(this.getUploadQueueForPano(e), t), this.clearUploadQueue(this.forceQueue, t, e);else { for (var i = 0; i < this.activePanos.length; i++) { var n = this.activePanos[i]; this.clearUploadQueue(this.getUploadQueueForPano(n.id), t); } this.clearUploadQueue(this.forceQueue, t); } } clearUploadQueue(e, t, i) { void 0 !== t && null !== t || (t = 0); for (var n = 0; n < e.length;) { var r = e[n]; (!i || i && i === r.tile.panoId) && r.level >= t ? (r.uploadQueued = !1, e.splice(n, 1)) : n++; } //若报错, r.tile.panoId改为 r.panoId } updateUploadQueue(maxNPF, maxPF /* e, t */) { //参数是 maxNonBaseUploadsPerFrame and maxBaseUploadsPerFrame, 优先上传512 //maxNPF || (maxNPF = 1); for (var i = 0, n = 0;;) { //let old = this.forceQueue.slice(0) if (n >= maxPF || i >= maxNPF) break; var r = this.getNextFromUploadQueue(); if (!r) break; //r.panoSize <2048 && console.log('panoId', r.panoId, 'panoSize', r.panoSize , old) 0 !== r.level ? i++ : n++; if (!(r.panoSize > this.qualityManager.getMaxNavPanoSize()) || this.zoomingActive) { var o = this.getActiveRenderTargetDescriptor(r.panoId); this.isRenderTargetDescriptorValid(o) && this.uploadTile(r, r.forceUpload); } } } updateDirection(e) { if (e = e || this.direction) { this.direction = e; for (var t = 0; t < this.activePanos.length; t++) { var i = this.activePanos[t], n = this.getUploadQueueForPano(i.id); TilePrioritizer.sortPanoTiles(n, i, this.direction); } } } anyUploaded(e) { if (!e) return !1; if (e.tile && this.isTileUploaded(e.tile)) return !0; if (e.children) for (var t = 0; t < e.children.length; t++) { var i = e.children[t]; if (this.anyUploaded(i)) return !0; } return !1; } setNodeCovered(e, t) { this.isPanoZoomed(e.tile.panoId) ? e.zoomCovered = t : e.covered = t; } isNodeCovered(e) { return !!e && (this.isPanoZoomed(e.tile.panoId) ? e.zoomCovered : e.covered); } addCoverageForNode(e) { if (this.setNodeCovered(e, !0), e.parent && e.covered) { var t = e.parent; this.nodeSubcovered(t) && this.addCoverageForNode(t, !0); } } calcFullCoverage(e) { var t = !1; if (e.children) for (var i = 0; i < e.children.length; i++) { var n = e.children[i]; t = t || this.calcFullCoverage(n); } e.covered = e.tile.uploaded || t; } nodeSubcovered(e) { if (!e.children) return !1; for (var t = 0; t < e.children.length; t++) if (!e.children[t] || !this.isNodeCovered(e.children[t])) return !1; return !0; } resetPanoDescriptor(e) { this.getPanoDescriptor(e); } getPanoDescriptor(e) { var t = this.panoDescriptors[e]; return t || (t = {}, this.panoDescriptors[e] = t), t; } resetPanoLODDescriptors(e) { var t = this.getPanoLODDescriptors(e); for (var i in t) if (t.hasOwnProperty(i)) { var n = t[i]; n.uploadCount = 0, n.uploadAttempts = 0; n.uploaded = []; } } getPanoLODDescriptor(e, t) { var i = this.getPanoLODDescriptors(e), n = i[t]; return n || (n = { uploadCount: 0, uploadAttempts: 0, uploaded: [] //add }, i[t] = n), n; } getPanoLODDescriptors(e) { var t = this.panoLODDescriptors[e]; return t || (t = {}, this.panoLODDescriptors[e] = t), t; } onTileDownloaded(o) { var e = o.desc; var t = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, e.panoSize), i = this.getTileDirectoryEntry(e.panoId, e.face, t, e.faceTileIndex); i.downloaded = !0; i.image = e.image; i.panoSize = e.panoSize; i.tileX = e.tileX; i.tileY = e.tileY; i.totalTiles = e.totalTiles; i.tileIndex = e.tileIndex; i.faceTileIndex = e.faceTileIndex; i.face = e.face; i.cubeFace = TileUtils.mapFaceToCubemapFace(e.face); i.panoId = e.panoId; i.tileSize = e.tileSize; i.direction = new Vector3().copy(e.direction); i.node = null; i.level = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, i.panoSize); if (this.isPanoActive(i.panoId)) { var n = this.getTileTree(i.panoId, i.face); var r = n.getSubNode(i.panoSize, i.tileX, i.tileY); this.linkTileAndNode(i, r); this.queueTileUpload(i, !0); } } getTileDirectoryEntry(panoId, t, i, n) { var r = this.tileDirectory[panoId]; r || (r = {}, this.tileDirectory[panoId] = r); var o = 16384 * t + 1024 * i + n, //t:4096级别 a = r[o]; return a || (a = { downloaded: !1, uploaded: !1, zoomUploaded: !1 }, r[o] = a), a._key = panoId + ":" + t + ":" + i + ":" + n, //panoId : face : level : faceTileIndex a._tileKey = o, a; } setZoomingActive(active, pano, i) { //设置当前正在zoom的pano this.zoomPanoRenderingDisabled || active === this.zoomingActive && this.zoomPanoId === pano.id || (this.zoomingActive = active, this.zoomPanoId = pano.id, this.zoomingActive && (this.zoomPanoId !== pano.id || i) && this.updateZoomedPanoFromBase(pano)); } updateZoomedPanoFromBase(pano) { //因更换pano所以将pano的rendertarget渲染到panoRenderer的zoomRenderTarget上 if (!this.zoomPanoRenderingDisabled) { var t = this.getActiveRenderTargetDescriptor(pano.id); if (t && t.renderTarget) { if (this.zoomRenderTarget) { var i = Math.min(this.qualityManager.maxRenderTargetSize, this.qualityManager.getMaxZoomPanoSize()), //change n = t.renderTarget, r = t.size; this.copyCubeMap(n.texture, this.zoomRenderTarget, r, r, i, i); } this.copyBaseRenderStatusToZoomed(pano.id); } } } add(e) { this.M.push(e); } initDescriptor(size) { var t = createDescriptor(); t.inUse = !0; t.size = size; this.add(t); return t; } activeDescripor(e) { for (var t = 0; t < this.M.length; t++) { var i = this.M[t]; if (!i.inUse && i.size === e) { i.inUse = !0; return i; } } return null; } deactiveDescripor(e) { for (var t = 0; t < this.M.length; t++) { var i = this.M[t]; if (i.renderTarget === e) { i.inUse = !1; return !0; } } return !1; } enableHighQuality(e) { //xzw add 如果最多只要2k图的话enableUltraHighQualityMode替换成这个 if (!this.qualityManager.highQualityModeStarted) { this.setupZoomRenderTarget(); e(); //this.qualityManager.updateHighResolutionSettings(e)////////? this.qualityManager.highQualityModeStarted = true; } } linkTileAndNode(e, t) { t.tile = e, e.node = t; } linkAllTilesAndNodes(e) { var t = function t(_t, i, n, r, o) { var a = this.getTileDirectoryEntry(e.id, i, r, o); this.linkTileAndNode(a, n); }; for (var i = 0; i < TileUtils.FACES_PER_PANO; i++) { var n = this.getTileTree(e.id, i); n.breadthFirst({ callback: t.bind(this, n, i) }); } } //--------------sceneRenderer initSizedTexture2D(e, t, i) { var renderer = this.viewer.renderer, o = renderer.getContext(), a = renderer.state, s = new Texture(null); s.flipY = !1, i !== !0 && (i = !1), s.generateMipmaps = i; var l = renderer.paramThreeToGL(s.format), c = renderer.paramThreeToGL(s.type), h = renderer.properties.get(s), u = o.createTexture(); a.bindTexture(o.TEXTURE_2D, u), o.pixelStorei(o.UNPACK_FLIP_Y_WEBGL, s.flipY), o.texImage2D(o.TEXTURE_2D, 0, l, e, e, 0, l, c, null), s.wrapS = t, s.wrapT = t; var d = renderer.paramThreeToGL(t); return o.texParameteri(o.TEXTURE_2D, o.TEXTURE_WRAP_S, d), o.texParameteri(o.TEXTURE_2D, o.TEXTURE_WRAP_T, d), i ? (s.magFilter = LinearFilter, s.minFilter = LinearMipMapLinearFilter, o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MAG_FILTER, o.LINEAR), o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MIN_FILTER, o.LINEAR_MIPMAP_NEAREST), o.generateMipmap(o.TEXTURE_2D)) : (s.magFilter = LinearFilter, s.minFilter = LinearFilter, o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MAG_FILTER, o.LINEAR), o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MIN_FILTER, o.LINEAR)), a.bindTexture(o.TEXTURE_2D, null), h.__webglTexture = u, s; } deallocateCubeTexture(e) { var t = this.viewer.renderer, i = t.getContext(), renderer = t.properties.get(e); i.deleteTexture(renderer.__image__webglTextureCube); } uploadTexture2D(img, tex, startX, startY, width, height) { var renderer = this.viewer.renderer, gl = renderer.getContext(), webglState = renderer.state, c = renderer.properties.get(tex); webglState.bindTexture(gl.TEXTURE_2D, c.__webglTexture), gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, tex.flipY), gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, tex.premultiplyAlpha), gl.pixelStorei(gl.UNPACK_ALIGNMENT, tex.unpackAlignment), gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, renderer.paramThreeToGL(tex.wrapS)), gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, renderer.paramThreeToGL(tex.wrapT)), gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, renderer.paramThreeToGL(tex.magFilter)), gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, renderer.paramThreeToGL(tex.minFilter)), gl.texSubImage2D(gl.TEXTURE_2D, 0, startX, startY, gl.RGBA, gl.UNSIGNED_BYTE, img), tex.generateMipmaps && gl.generateMipmap(gl.TEXTURE_2D), webglState.bindTexture(gl.TEXTURE_2D, null); } getCubeOrientationForCubeFace(e, t) { switch (e) { case GLCubeFaces$2.GL_TEXTURE_CUBE_MAP_POSITIVE_X: t.set(0, -Math.PI / 2, 0); break; case GLCubeFaces$2.GL_TEXTURE_CUBE_MAP_NEGATIVE_X: t.set(0, Math.PI / 2, 0); break; case GLCubeFaces$2.GL_TEXTURE_CUBE_MAP_POSITIVE_Y: t.set(Math.PI / 2, Math.PI, 0); break; case GLCubeFaces$2.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: t.set(-Math.PI / 2, Math.PI, 0); break; case GLCubeFaces$2.GL_TEXTURE_CUBE_MAP_POSITIVE_Z: t.set(0, -Math.PI, 0); break; case GLCubeFaces$2.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: t.set(0, 0, 0); } } //dispose所有cubeRenderTarget disposeIdelTargets() { var disposeCount = 0; for (var t = 0; t < this.M.length; t++) { var i = this.M[t]; if (!i.inUse) { disposeCount++; i.renderTarget.dispose(); } } //console.log('disposeIdelTargets ', disposeCount, 'of', this.M.length) } } PanoRenderer.prototype.setupZoomRenderTarget = function () { var targets = {}; return function () { if (this.qualityManager.maxRenderTargetSize == 2048 && this.qualityManager.getMaxNavPanoSize() == 2048) return; //不使用zoomTarget 直接用pano的tiledPanoRenderTarget,防崩溃 if (this.qualityManager.getMaxZoomPanoSize() >= this.qualityManager.getMaxNavPanoSize()) { //部分手机2k时copyCubeMap会重载 , 所以如果没有超出当前分辨率,就不使用zoomRenderTarget。但在微信依旧会重载,只是优化了些,safari几乎不会。 if (this.zoomRenderTarget && this.zoomRenderTarget.width === this.qualityManager.getMaxZoomPanoSize()) return; var e = this.zoomRenderTarget; var size = this.qualityManager.getMaxZoomPanoSize(); if (size > this.qualityManager.maxRenderTargetSize) { return; } if (targets[size]) { this.zoomRenderTarget = targets[size]; } else { this.zoomRenderTarget = this.initTiledPano(size, false); //放大后不使用抗锯齿,否则消 targets[size] = this.zoomRenderTarget; } if (e) { //将旧的zoomRenderTarget渲染到新zoomRenderTarget上 var t = e.width, i = this.zoomRenderTarget.width; this.copyCubeMap(e.texture, this.zoomRenderTarget, t, t, i, i), e.texture.dispose(), e.texture.loaded = !1, e.texture.version = 0, this.deallocateCubeTexture(e.texture), e.texture = null; } this.zoomPanoRenderingDisabled = !1; } else this.zoomPanoRenderingDisabled = !0; }; }(); PanoRenderer.prototype.updateActivePanos = function () { var e = []; return function (t, i) { e.length = 0; for (var n = 0; n < this.activePanos.length; n++) { t && e.length === i && e.push(t); var r = this.activePanos[n], o = this.getActiveRenderTargetDescriptor(r.id); t && r.id === t.id || !this.isRenderTargetDescriptorValid(o) || e.push(r); } t && i >= e.length && e.push(t), this.activePanos.length = 0, this.activePanos.push.apply(this.activePanos, e); }; }(); PanoRenderer.prototype.renderPanoTiles = function () { var e = []; return function (panoId, i, n, r) { this.zoomRenderTarget && this.zoomRenderTarget.width === this.qualityManager.getMaxZoomPanoSize() || this.zoomPanoRenderingDisabled || this.setupZoomRenderTarget(), //如果ZoomRenderTarget大小需要变动就重新创建 i = i || this.direction || Vectors.FORWARD; // [{1:Vectors.FORWARD}]? var o = this.getActiveRenderTargetDescriptor(panoId); if (!this.isRenderTargetDescriptorValid(o)) console.error("PanoRenderer.renderPanoTiles() -> Cannot render to a pano that is not activated."); for (var a = 0; a < TileUtils.FACES_PER_PANO; a++) { var s = this.getTileTree(panoId, a); e.length = 0; s.breadthFirst({ //获取该面所有node 85个 = 1+4+16+64 saveVisited: e }); for (var l = 0; l < e.length; l++) { var c = e[l]; this.queueTileUpload(c.tile, !1, r || 0 === l && n); // 第0个是512的,会直接uploadTile } } this.updateDirection(i); }; }(); PanoRenderer.prototype.getNextFromUploadQueue = function () { var e = function e(_e) { var t = _e.shift(); return t.uploadQueued = !1, t; }; return function () { if (this.forceQueue.length > 0) return e(this.forceQueue); var t = this.getTopUploadQueue(); return t && t.length > 0 ? e(t) : null; }; }(); /* PanoRenderer.prototype.refreshUploadInterval = function () { var e = null; return function (t) { this.uploadIntervalCancelled || (e || (e = upload.bind(this)), null !== t && void 0 !== t || (t = w), b || (t = _), this.uploadInterval = window.setTimeout(e, t), this.uploadIntervalDelay = t) } }() PanoRenderer.prototype.update = function () { var e = performance.now(), t = 0; return function () { this.uploadIntervalCancelled = !0; window.clearTimeout(this.uploadInterval); this.uploadInterval = null; var i = performance.now() - e; //!(i > w || 0 === t) || !this.overlayTilesLoaded && this.usingTileOverlay || (this.updateUploadQueue(this.maxNonBaseUploadsPerFrame, this.maxBaseUploadsPerFrame), //e = performance.now()), if (!(i > w || 0 === t) || !this.overlayTilesLoaded && this.usingTileOverlay) {} else { this.updateUploadQueue(this.maxNonBaseUploadsPerFrame, this.maxBaseUploadsPerFrame); e = performance.now(); } t++; } }() */ PanoRenderer.prototype.update = function () { //this.uploadIntervalCancelled = true ; //不使用setTimeout,而是在sceneRenderer每帧都update if (viewer.images360.latestRequestMode == 'showPanos') { var maxNonBaseUploadsPerFrame = viewer.lastFrameChanged ? Common.getBestCount('maxStandard', 0, 2, 1, 10 /* ,true */) : 2; // 这是每帧uploadTile非512的瓦片tex的数量。 手机在前进时可能会总是0,直到到漫游点后为2 var maxBaseUploadsPerFrame = viewer.lastFrameChanged ? Common.getBestCount('maxBase', 1, 6, 1, 14 /* ,true */) : 6; //this.maxBaseUploadsPerFrame //原先6. 但持续前进过程中会请求加载下一个漫游图,一次加6张会卡的。 this.updateUploadQueue(maxNonBaseUploadsPerFrame, maxBaseUploadsPerFrame); //注:静止时看不出卡顿所以全速加载 } }; /* function upload() { if (!this.uploadIntervalCancelled) { if (this.overlayTilesLoaded || !this.usingTileOverlay) { b = !0 let maxNonBaseUploadsPerFrame = viewer.mainViewport.view.isFlying() ? 1 : this.maxNonBaseUploadsPerFrame //原先2。这是每帧uploadTile非512的瓦片tex的数量。之前的2太卡了,降为1。(检测卡顿方法:在一个pano点旋转至所有2048的tile都加载完,然后之后到这个点看看卡不卡。因为该点tiles都下载完了所以会在飞过来时陆续都加载,所以容易卡) this.updateUploadQueue(maxNonBaseUploadsPerFrame, this.maxBaseUploadsPerFrame) let time = viewer.mainViewport.view.isFlying() ? 60 : w //add 飞行有时候会卡,增长间隔 this.peekNextFromUploadQueue() ? this.refreshUploadInterval(time) : this.uploadInterval = null //定时下一次更新 } else { this.refreshUploadInterval(this.uploadIntervalDelay) } } } */ PanoRenderer.prototype.uploadTile = function () { //重写 var collection = {}, overlayStyle = config$1.tiling.overlayStyle; var failHistory = {}; return function (info, n) { var id = info.panoId, img = info.image, tileSize = info.tileSize, panoSize = info.panoSize, tileIndex = info.tileIndex, totalTiles = info.totalTiles, tileX = info.tileX, tileY = info.tileY, p = !0, g = !1, ignore = false, //add LodDescripor = (this.getPanoDescriptor(id), this.getPanoLODDescriptor(id, panoSize)), activeDescripor = this.getActiveRenderTargetDescriptor(id), renderTarget = activeDescripor.renderTarget, size = activeDescripor.size; //当前要渲染的面的分辨率,也就是MaxNavPanoSize if (this.isPanoZoomed(id) && this.zoomRenderTarget) { renderTarget = this.zoomRenderTarget; size = this.zoomRenderTarget.width; //this.qualityManager.getMaxZoomPanoSize(); //放大后可能2048或4096 } //console.log(window.sceneName, 'uploadTile ', id, tileIndex) var done = () => { if (!LodDescripor.uploaded.includes(tileIndex)) { //已经upload过(本来这时候直接返回,但发现缩放后这不会归零,导致清晰度不更新,所以还是redraw且emit吧) //console.log('try to reupload and return',tileIndex) LodDescripor.uploaded.push(tileIndex); LodDescripor.uploadCount++; } this.dispatchEvent({ type: PanoRendererEvents$1.TileRenderSuccess, id, panoSize, tileIndex, totalTiles }); LodDescripor.uploadCount === totalTiles && this.dispatchEvent({ type: PanoRendererEvents$1.PanoRenderComplete, id, panoSize, totalTiles, updateFullComplete: true }); this.setUploaded(info, !0); this.addCoverageForNode(info.node); }; { //已经uploadTile过了不再uploadTile if (!this.isRenderTargetDescriptorValid(activeDescripor)) { p = !1; g = !1; } if (!n) { this.anyUploaded(info.node) && (p = !1, g = !0, ignore = true); //包括子集也uploadTile了 this.isTileUploaded(info) && (p = !1, g = !1, ignore = true); //当前tile uploadTile了 } } if (p) { /*if(failHistory[id+':'+ panoSize+ ':' +tileIndex]){ console.log('uploadTile retry',id, panoSize, tileIndex) } console.log('uploadTile 成功', id, panoSize, tileIndex) */ var C = tileX * tileSize, I = tileY * tileSize, E = tileSize / panoSize * size, // tile在renderTarget上渲染出的宽度 b = C / panoSize * size, // tile在renderTarget上渲染的startX w = I / panoSize * size; // tile在renderTarget上渲染的startY if (panoSize > this.qualityManager.maxRenderTargetSize) { //4096 改 /* var tex = this.initSizedTexture2D(tileSize, THREE.ClampToEdgeWrapping); var loaded = this.viewer.images360.isHighMapLoaded(info.cubeFace, tileX,tileY) */ this.viewer.images360.getHighImage(img, info.cubeFace, tileX, tileY); } else { collection[tileSize] || (collection[tileSize] = this.initSizedTexture2D(tileSize, ClampToEdgeWrapping)); var tex = collection[tileSize]; this.uploadTexture2D(img, tex, 0, 0, tileSize, tileSize); //只替换tex对应的img,不新建 if (panoSize > this.qualityManager.maxRenderTargetSize) { loaded || this.viewer.images360.updateHighMap(tex, info.cubeFace, tileX, tileY); } else { if (1 === overlayStyle || 2 === overlayStyle) { var T = 1 === overlayStyle ? this.overlayTilesBasic : this.overlayTilesEnhanced; this.renderToCubeMap(tex, renderTarget, tileSize, tileSize, 0, 0, tileSize, tileSize, b, w, E, E, info.cubeFace); this.renderToCubeMap(T[panoSize], renderTarget, tileSize, tileSize, 0, 0, tileSize, tileSize, b, w, E, E, info.cubeFace, NormalBlending, !0, .5); } else { this.renderToCubeMap(tex, renderTarget, tileSize, tileSize, 0, 0, tileSize, tileSize, b, w, E, E, info.cubeFace); } } } done(); } else if (ignore) { //console.log('finish because anyUploaded',id,panoSize,tileIndex) done(); //改: 如果因为这部分更高清的贴图已加载所以才不绘制的话,直接完成 } else { //console.log('uploadTile 失败', id, panoSize, tileIndex) if (panoSize == 512) { //console.log("!!!!!!!!!!!!!") } failHistory[id + ':' + panoSize + ':' + tileIndex] = true; this.setUploaded(info, !1); } info.uploadAttempted || (LodDescripor.uploadAttempts++, this.dispatchEvent({ type: PanoRendererEvents$1.TileUploadAttempted, id, panoSize, tileIndex, totalTiles })), info.uploadAttempted = !0; LodDescripor.uploadAttempts === totalTiles && this.dispatchEvent({ type: PanoRendererEvents$1.UploadAttemptedForAllTiles, id, panoSize, totalTiles }); return g; }; }(); /* 注:tileY的方向同UV,从下到上 renderToCubeMap里的画布or镜头的xy范围是-0.5到0.5 */ PanoRenderer.prototype.renderToCubeMap = function () { var inited = !1, scene = null, camera = null, material = null, geo = null, plane = null, l = 1; return function (texture, renderTarget, tileWidth, tileHeight, startXinTile, startYinTile, widthinTile, heightinTile, startX, startY, width, height, cubeFace, E, b, w) { var renderer = this.viewer.renderer; inited || (camera = new OrthographicCamera(l / -2, l / 2, l / 2, l / -2, -200, 200), camera.position.z = 150, scene = new Scene(), scene.add(camera), material = new BasicMaterial({ depthWrite: !1, depthTest: !1, side: 0 }), geo = new PlaneBufferGeometry(l, l), plane = new Mesh(geo, material), plane.position.z = 0, scene.add(plane), inited = !0); var uv = geo.getAttribute("uv"); uv.setDynamic(!0), //setUsage uv.needsUpdate = !0; var uvArr = uv.array, S = startXinTile / tileWidth, //uv这几个值基本是固定的startXinTile:0,startYinTile:0,widthinTile:512,widthinTile:512,tileWidth:512,tileHeight:512 也就是说uv不会变、每张tile的有效范围是100% M = startYinTile / tileHeight, R = widthinTile / tileWidth, P = heightinTile / tileHeight; uvArr[0] = S, uvArr[1] = M + P, uvArr[2] = S + R, uvArr[3] = M + P, uvArr[4] = S, uvArr[5] = M, uvArr[6] = S + R, uvArr[7] = M; //修改posistion,使该plane只占据需要绘制的部分。类似拼图。 //startX startY width height 都是在画布上的大小,比如画布大小为2048*2048,此tile为16分之一,tileX是1,tileY是1,则startX=2048/4,startY=2048/4 var pos = geo.getAttribute("position"); pos.setDynamic(!0), pos.needsUpdate = !0; var posArr = pos.array, D = startX / renderTarget.width - l / 2 // 起始x , N = startY / renderTarget.height - l / 2 // 起始y , B = width / renderTarget.width // 宽 , F = height / renderTarget.height; // 高 posArr[0] = D, posArr[1] = N + F, posArr[3] = D + B, posArr[4] = N + F, posArr[6] = D, posArr[7] = N, posArr[9] = D + B, posArr[10] = N; //renderer.properties.get(scene); material.map = texture; //material.uniforms.map.value = texture; material.blending = E || NoBlending, material.transparent = !!b; void 0 !== w && null !== w || (w = 1), material.uniforms.opacity.value = w, // material.needUpdate = !0 //renderTarget.activeCubeFace = cubeFace, //0-5 应该是指定渲染h中的面 失效 /* renderer.setScissorTest(!0) //指定绘制区域,类似遮罩(相对于屏幕) renderer.setScissor(startX,startY,width,height) //加上这个会不会快一些,尤其是spherical //指定绘制视口位置和大小(相对于屏幕) */ renderTarget.viewport.set(0, 0, renderTarget.width, renderTarget.height); var V = renderer.autoClear; var oldTarget = renderer.getRenderTarget(); renderer.autoClear = !1; renderer.setRenderTarget(renderTarget, cubeFace); renderer.render(scene, camera /* , renderTarget, !1 */); renderer.setRenderTarget(oldTarget); renderer.autoClear = V; //renderer.setScissorTest(!1) /* this.renderer.render(scene, camera, this.planeTargets[cubeFace], !1),//针对有的场景app第一个点图加载不成功的问题 console.log(`图index ${cubeFace} , ${startX}, ${startY}, ${width}, ${height}`) this.targetList[cubeFace] || (this.targetList[cubeFace] = []) this.targetList[cubeFace].push([startX,startY,width,height])*/ }; }(); /* * 将texture渲染到zoomRenderTarget上(目的是复制贴图到zoomRenderTarget) */ PanoRenderer.prototype.copyCubeMap = function () { //将texture渲染到zoomRenderTarget上 var inited = !1, scene = null, camera = null, material = null, geo = null, mesh = null, testCube = null, //add c = new Euler(); return function (texture, renderTarget, tWidth, tHeight, rWidth, rHeight, m, v, A) { if (rWidth > this.qualityManager.maxRenderTargetSize) return; //add if (!inited) { var w = 2; camera = new OrthographicCamera(w / -2, w / 2, w / 2, w / -2, 0, 200), camera.position.set(0, 0, 0), scene = new Scene(), scene.add(camera); material = new ShaderMaterial({ uniforms: { tDiffuse: { type: "t", value: null }, alpha: { type: "f", value: 1 } }, vertexShader: Shaders['copyCubeMap.vs'], fragmentShader: Shaders['copyCubeMap.fs'], depthWrite: !1, depthTest: !1, side: DoubleSide }); geo = new BoxGeometry(w, w, w), mesh = new Mesh(geo, material), scene.add(mesh); inited = !0; /* testCube = mesh.clone(); viewer.scene.scene.add(testCube); Potree.Utils.setObjectLayers(testCube, 'sceneObjects') */ } var autoClear = this.viewer.renderer.autoClear; var oldTarget = this.viewer.renderer.getRenderTarget(); this.viewer.renderer.autoClear = false; material.uniforms.tDiffuse.value = texture; material.blending = m || NoBlending; material.transparent = !!v; void 0 !== A && null !== A || (A = 1); material.uniforms.alpha.value = A; material.needUpdate = !0; for (var C = 0; C < 6; C++) { this.getCubeOrientationForCubeFace(C, c); mesh.rotation.copy(c); mesh.matrixWorldNeedsUpdate = !0; mesh.updateMatrixWorld(); renderTarget.viewport.set(0, 0, rWidth, rHeight); this.viewer.renderer.setRenderTarget(renderTarget, C); //renderTarget.activeCubeFace = C//失效 this.viewer.renderer.render(scene, camera); } //console.warn('copyCubeMap' + rWidth) this.viewer.renderer.autoClear = autoClear; this.viewer.renderer.setRenderTarget(oldTarget); }; }(); class DepthImageSampler extends EventDispatcher { constructor() { super(); var canvas = document.createElement("canvas"); this.canvas = canvas; this.context = canvas.getContext("2d", { willReadFrequently: true }); this.imgDatas = []; /* document.getElementsByTagName('body')[0].appendChild(canvas); canvas.style.position = 'fixed'; canvas.style.width = '1024px'; canvas.style.top = canvas.style.left = 0 canvas.style['z-index'] = 100 */ this.maxDataCount = browser.isMobile() ? 6 : 20; //手机会崩溃. 平均每张图为8M数据量(以200个点的园区为例,加载时间久一些后,总内存=700 + 每张图的8M * maxDataCount) this.maxNeighCount = browser.isMobile() ? 3 : 14; //包含在maxDataCount内的nearPanos最大个数.至少比maxDataCount少3个,留出空位给最近更新的pano this.nearPanos = []; } updateNearPanos(panos) { this.nearPanos = panos.slice(0, this.maxNeighCount); } changeImg(img, pano) { this.pano = pano; var item = this.imgDatas.find(p => p.pano == pano); if ( /* this.img == img || */item) { //最新的在末尾,所以换到末尾 var index = this.imgDatas.indexOf(item); this.imgDatas.splice(index, 1); this.imgDatas.push(item); //console.log('重复使用',item.pano.id) return; } Potree.timeCollect.depthSamChangeImg.start = true; //不过在刚启动时得到的用时较大 try { viewer.addTimeMark('depthSamChangeImg', 'start'); this.canvas.width = img.width; this.canvas.height = img.height; this.context.drawImage(img, 0, 0); var o = this.context.getImageData(0, 0, img.width, img.height); var data = o && o.data; //getImageData 1px时 : pc chrome 耗时0.01毫秒左右(排除第一次的50) , 但firefox: 4。但换贴图之后就多达5甚至几十 //console.log('changeImg', pano.id, !!data ) //this.img = img if (!data) { console.error('getImageData 得不到?!why!'); return false; } if (this.imgDatas.length >= this.maxDataCount) { var old = this.imgDatas.find(e => !this.nearPanos.includes(e.pano)); //console.log('推出',old.pano.id) this.imgDatas.splice(this.imgDatas.indexOf(old), 1); //推出使用时间最早的一个非nearPano } this.imgDatas.push({ pano, data }); this.dispatchEvent({ type: 'changeImg', pano }); viewer.addTimeMark('depthSamChangeImg', 'end'); //耗时chrome 25ms,firefox: 38ms, iphoneX:33ms } catch (e) { console.error(e); //内存不足 Failed to execute 'getImageData' on 'CanvasRenderingContext2D': Out of memory at ImageData creation return false; } /* pano.depthData = {} for(let h=0; h0) pano.depthData[h+'|'+w] = depth } } */ } clearTexData() { this.imgDatas.length = 0; } getDepth(UVx, UVy, useNeighIfZero) { //根据图片像素获取深度值 var x = Math.round(UVx * (this.canvas.width - 1)), y = Math.round(UVy * (this.canvas.height - 1)); var imgData = this.imgDatas.find(p => p.pano == this.pano); var get = (x, y) => { if (!(x < 0 || y < 0 || x >= this.canvas.width || y >= this.canvas.height)) { var blockIndex = this.canvas.width * y + x; var color = imgData.data.slice(blockIndex * 4, (blockIndex + 1) * 4); return color[1] + color[0] / 256; //为什么不是除以255见聊天记录.(验证过比点云的远一点点) } }; /* viewer.addTimeMark('depthSampler','start') var r = this.context.getImageData(x, y, 1, 1).data; //pc chrome 耗时0.01毫秒左右(排除第一次的50) , 但firefox: 4。但换贴图之后就多达5甚至几十 viewer.addTimeMark('depthSampler','end') */ var depth = get(x, y); if (!depth && useNeighIfZero) { //遇到过有的相隔很远且有阻挡的两个漫游点间居然depth为0,没有阻挡?但是周围点有四个非零。所以为了修正会飞到很远的点加个识别周围像素的depth 。 2024.3.19 var results = []; var d = 0, sum = 0, count = 0, maxResDis = 1; while (d++ < maxResDis) { for (var i = -d; i <= d; i++) { for (var j = -d; j <= d; j++) { if (i == -d || i == d || j == -d || j == d) { //外围 var depth1 = get(x + i, y + j); if (depth1 != 0) { results.push(depth1); } } } } } if (results.length) { depth = results.reduce((w, c) => { return w + c; }, 0) / results.length; //console.error('useNeighIfZero', results, depth) } //console.log('useNeighIfZero', results, depth) } return depth; } sample(intersect, currentPano, onlyPos, useNeighIfZero) { //通过和skybox的intersect得到真实的intersect的位置 if (!intersect) return; var location = new Vector3(); var normal; currentPano = currentPano || viewer.images360.currentPano; if (currentPano != this.currentPano || !this.imgDatas.find(p => p.pano == currentPano)) { if (!currentPano.depthTex /* || !currentPano.depthTex.image */) return; //未加载 if (this.changeImg(currentPano.depthTex.image, currentPano) === false) { console.log('失败', currentPano.id); return false; //失败 } this.currentPano = currentPano; } var origin = currentPano.position; var dir = intersect.dir || new Vector3().subVectors(intersect.point, origin).normalize(); //var uv = intersect.uv //let dirInPano = math.getNormalDir(dir, currentPano)//转化为考虑漫游点旋转的方向 var dirInPano = dir.clone().applyMatrix4(currentPano.panoMatrix2Inverse).normalize(); //转化为考虑漫游点旋转的方向 var uv = math.getUVfromDir(dirInPano); //转化为uv var distance = this.getDepth(uv.x, uv.y, useNeighIfZero); //viewer.addTimeMark(markName,'end') if (!distance) { var margin = 0.1; if (uv.y > 1 - Potree.config.depthTexUVyLimit) { //漫游点底部识别不到的区域,给一个地板高度 distance = (currentPano.floorPosition.z - origin.z - margin) / dir.z; location.copy(dir).multiplyScalar(distance).add(origin); var _normal = new Vector3(0, 0, 1); return { location, normal: _normal, distance }; } else if (uv.y < Potree.config.depthTexUVyLimit) { var ceilZ = currentPano.getCeilHeight(); if (ceilZ == Infinity) return !1;else { distance = (ceilZ - origin.z - margin) / dir.z; location.copy(dir).multiplyScalar(distance).add(origin); var _normal2 = new Vector3(0, 0, -1); return { location, normal: _normal2, distance }; } } //console.log('无穷远') return !1; //应该是天空或模型外 , 因为很少有漫游点的地方还拍不到地板 } //console.log('distance', distance, dirInPano.clone().multiplyScalar(distance)) location.copy(dir).multiplyScalar(distance).add(origin); if (!onlyPos) { var pL = this.getNearbyPoint(origin, uv, -1, 0), pR = this.getNearbyPoint(origin, uv, 1, 0), pB = this.getNearbyPoint(origin, uv, 0, -1), pT = this.getNearbyPoint(origin, uv, 0, 1); normal = this.planeFit(dir, location, pL, pR, pB, pT); } /* if(normal.x != normal.x ){ console.log('NAN', normal) var pL = this.getNearbyPoint(origin, uv, -1, 0) , pR = this.getNearbyPoint(origin, uv, 1, 0) , pB = this.getNearbyPoint(origin, uv, 0, -1) , pT = this.getNearbyPoint(origin, uv, 0, 1); } */ //console.log(location, normal, distance) return { location, normal, distance }; } getNearbyPoint(origin, uv, x, y) { //获取附近的若干像素距离的点 var uv2 = uv.clone(); uv2.x += x / (this.canvas.width - 1); uv2.x = this.clampUV(uv2.x); uv2.y += y / (this.canvas.height - 1); uv2.y = this.clampUV(uv2.y); /* if(uv2.x < 0 || uv2.y < 0 || uv2.x > 1 || uv2.y > 1){ console.log('will nan') } */ var dir = math.getDirFromUV(uv2); //从uv获取到方向 dir.applyMatrix4(viewer.images360.currentPano.panoMatrix2); var depth = this.getDepth(uv2.x, uv2.y); /* if(Math.abs(depth - this.mainDepth) > 0.3){ console.log('Math.abs(depth - this.mainDepth) > 0.3') } */ //let dir = new THREE.Vector3().subVectors(intersect.point, origin).normalize() var position = new Vector3().copy(dir).multiplyScalar(depth).add(origin); //console.log('getNearbyPoint', uv2, depth, dir, position ) return position; } clampUV(v) { return (v + 1) % 1; // 使输出在 0-1 } planeFit(dir, position, pL, pR, pB, pT) { //求平均法线 var normal = new Vector3(); var plane = new Plane(); function addNormal(p1, p2) { //根据临接的四个点,分别求法线,然后法线相加能得到平均法线 if (!p1 || !p2) return; plane.setFromCoplanarPoints(position, p1, p2); //console.log('normalSub', plane.normal) normal.addScaledVector(plane.normal, dir.dot(plane.normal) < 0 ? 1 : -1); //根据面的朝向判断加还是减 } addNormal(pL, pB); addNormal(pL, pT); addNormal(pR, pB); addNormal(pR, pT); if (0 !== normal.x || 0 !== normal.y || 0 !== normal.z) { normal.normalize(); //console.log(normal) return normal; } /* 四个面拼成一个菱形 */ } } var { PanoSizeClass: PanoSizeClass$3, Vectors: Vectors$1, GLCubeFaces: GLCubeFaces$3, PanoramaEvents: PanoramaEvents$1 } = Potree.defines; var rot90$1 = new Quaternion().setFromAxisAngle(new Vector3(0, 0, 1), Math.PI / 2); //使用的是刚好适合全景图的,给cube贴图需要转90° var raycaster = new Raycaster(); //let currentlyHovered = null; var texLoader$4 = new TextureLoader(); var addLine = function addLine(origin, dir, len) { var color = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '#fff'; var line1 = LineDraw.createLine([origin, origin.clone().add(dir.clone().multiplyScalar(len || 1))], { color }); //console.log(origin.toArray(), dir.toArray()) viewer.scene.scene.add(line1); return line1; }; var tileArr = []; var previousView = { controls: null, position: null, target: null }; var HighMapCubeWidth = 1; var directionFactor = 400; //原先10,几乎只往距离近的走了;设置太大容易略过近处漫游点走向下坡,因为鼠标一般在地面,下坡的漫游点更有利 class Images360 extends EventDispatcher { constructor(viewer) { super(); this.viewer = viewer; this.panos = []; this.neighbourMap = {}; this.node = new Object3D(); this.node.name = 'ImagesNode'; this.cubePanos = []; this.fastTranMaskPass = new FastTranPass(viewer.renderer); { this.cube = new Mesh(new BoxBufferGeometry(1, 1, 1, 1), new ModelTextureMaterial()); Potree.Utils.updateVisible(this.cube, 'showSkybox', false); this.cube.layers.set(Potree.config.renderLayers.skybox); this.cube.name = 'skyboxCube'; viewer.scene.scene.add(this.cube); if (Potree.settings.mergeType2 && Potree.settings.modelSkybox) { this.materialInside = new ModelTextureMaterial(); this.materialInside.dontChangeDepth = true; //chunk本身深度是对的,不用深度图,否则过渡会有很多裂痕 this.cube.material.defines.depth_background = ''; //skybox的深度改得向后一些, 避免盖住chunk,造成坑坑洼洼 this.addEventListener('endChangeMode', e => { var _this$currentPano; /* if( this.currentPano?.pointcloud?.is4dkkModel){ let model = this.currentPano.pointcloud if(model.fileType == '3dTiles'){ viewer.setAllTilesets(model, (child)=>{ child.runtime.limit2lowestDepth(e.mode == 'showPanos') child.runtime.getTileset().tiles.forEach(e=>{ this.judgeModelMat(e.tileContent) }) }) }else{ this.judgeModelMat(model) } } */ if ((_this$currentPano = this.currentPano) !== null && _this$currentPano !== void 0 && (_this$currentPano = _this$currentPano.pointcloud) !== null && _this$currentPano !== void 0 && _this$currentPano.is4dkkModel) { this.changeModelMat(this.currentPano.pointcloud); } }); if (Potree.settings.canWalkThroughModel) { var lastModel; this.addEventListener('flyToPano', e => { //漫游到另一个模型就要选中这个模型 var model = e.toPano.pano.pointcloud; if (model != lastModel) { this.changeModelMat(model, true); //目标模型 } }); this.addEventListener('flyToPanoDone', e => { //漫游到另一个模型就要选中这个模型 if (!e.makeIt) return; var model = this.currentPano.pointcloud; if (model != lastModel) { this.changeModelMat(lastModel); } lastModel = model; }); } } } if (Potree.settings.testCube) { this.cubeTest = this.cube.clone(); this.cubeTest.material = new MeshBasicMaterial({ wireframe: true, color: '#FF3377', transparent: true, opacity: 0.7, depthWrite: false, depthTest: false }); viewer.scene.scene.add(this.cubeTest); this.cubeTest.visible = true; } this.flying_ = false; this.currentPano = null; this.mouseLastMoveTime = Date.now(); this.scrollZoomSpeed = 0.06; this.zoomLevel = 1; this.tileDownloader = new TileDownloader(); this.qualityManager = new QualityManager(); this.panoRenderer = new PanoRenderer(viewer, this.tileDownloader, this.qualityManager); this.basePanoSize = this.qualityManager.getPanoSize(PanoSizeClass$3.BASE); this.standardPanoSize = this.qualityManager.getPanoSize(PanoSizeClass$3.STANDARD); this.highPanoSize = this.qualityManager.getPanoSize(PanoSizeClass$3.HIGH); this.ultraHighPanoSize = this.qualityManager.getPanoSize(PanoSizeClass$3.ULTRAHIGH); this.tileDownloader.processPriorityQueue = !1; this.tileDownloader.tilePrioritizer = new TilePrioritizer(this.qualityManager, this.basePanoSize, this.standardPanoSize, this.highPanoSize, this.ultraHighPanoSize); { //高分辨率cube 放大 this.addHighMapCube(); viewer.addEventListener(PanoramaEvents$1.Enter, e => { this.setHighMap(e.newPano); }); viewer.addEventListener('panoSetZoom', e => { if (Potree.settings.displayMode == 'showPanos') { e.zoomed ? this.showHighMap() : this.hideHighMap(); //add } }); } this.depthSampler = new DepthImageSampler(); viewer.fpControls.addEventListener('dollyStopCauseUnable', e => { if ( /* e.hoverViewport != viewer.mainViewport || */!Potree.settings.zoom.enabled) return; if (e.scale != void 0) { //触屏 this.zoomBy(e.scale, e.pointer); } else { //滚轮 var zoom; if (e.delta > 0) { zoom = 1 + this.scrollZoomSpeed; } else { zoom = 1 - this.scrollZoomSpeed; } e.delta != 0 && this.zoomBy(zoom); } }); var click = e => { //不用"mouseup" 是因为 mouseup有drag object时也会触发 if (e.clickElement || Potree.settings.unableNavigate || this.flying || !e.isTouch && e.button != MOUSE.LEFT || e.drag && e.drag.object //拖拽结束时不算 || Potree.settings.editType == 'pano' && viewer.modules.PanoEditor.activeViewName != 'mainView' //|| Potree.settings.editType == 'merge' && !e.intersectPoint || viewer.inputHandler.hoveredElements[0] && viewer.inputHandler.hoveredElements[0].isModel && e.intersectPoint.distance > viewer.inputHandler.hoveredElements[0].distance || Potree.settings.editType == 'merge' && !Potree.settings.mergeType2 || Potree.settings.mergeType2 && Potree.settings.displayMode == 'showPointCloud') return; if (Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge') { if (e.hoverViewport == viewer.mapViewer.viewports[0]) { return viewer.mapViewer.dispatchEvent(e /* {type:'global_click',e } */); } else if (e.hoverViewport != viewer.mainViewport) { //如数据集校准其他viewport return; } } if (!Potree.settings.dblToFocusPoint /* && this.currentPano */) { //双击不会focus点云 或者 已经focusPano了 this.flyToPanoClosestToMouse(); } }; viewer.addEventListener('global_click', click); viewer.addEventListener("global_mousemove", e => { if (!Potree.settings.unableNavigate && Potree.settings.ifShowMarker && e.hoverViewport == viewer.mainViewport) { //如果不显示marker,就在点击时再更新 this.updateClosestPano(e.intersect); } }); this.addEventListener('markerHover', e => { this.updateClosestPano(e.pano, e.hovered); }); if (!Potree.settings.isOfficial) { this.domRoot = viewer.renderer.domElement.parentElement; var elUnfocus = $(""); elUnfocus.css({ position: "absolute", right: '25%', bottom: '20px', zIndex: "10000", fontSize: '1em', color: "black", display: 'none', background: 'rgba(255,255,255,0.8)' }); elUnfocus.on("click", () => this.unfocus()); this.elUnfocus = elUnfocus; this.domRoot.appendChild(elUnfocus[0]); if (Potree.settings.editType != 'merge') { var elHide = $(""); elHide.css({ position: "absolute", right: '40%', bottom: '20px', zIndex: "10000", fontSize: '1em', color: "black", width: '100px', background: 'rgba(255,255,255,0.8)' }); this.domRoot.appendChild(elHide[0]); elHide.on("click", e => { var visi = Potree.Utils.getObjVisiByReason(viewer.scene.pointclouds[0], 'force'); viewer.scene.pointclouds.forEach(e => { Potree.Utils.updateVisible(e, 'force', !visi); }); elHide.val(!visi ? "隐藏点云" : "显示点云"); }); } var elDisplayModel = $(""); elDisplayModel.css({ position: "absolute", right: '65%', bottom: '20px', zIndex: "10000", fontSize: '1em', color: "black", width: '100px', background: 'rgba(255,255,255,0.8)' }); this.domRoot.appendChild(elDisplayModel[0]); elDisplayModel.on("click", e => { if (Potree.settings.displayMode == 'showPointCloud' && this.panos.length == 0) return; Potree.settings.displayMode = Potree.settings.displayMode == 'showPointCloud' ? 'showPanos' : 'showPointCloud'; }); this.elDisplayModel = elDisplayModel; if (viewer.mapViewer) { var mapStyleBtn = $(""); mapStyleBtn.css({ position: "absolute", right: '50%', bottom: '20px', zIndex: "10000", fontSize: '1em', color: "black", width: '100px', background: 'rgba(255,255,255,0.8)' }); this.domRoot.appendChild(mapStyleBtn[0]); var map = viewer.mapViewer.mapLayer.maps.find(e => e.name == 'map'); mapStyleBtn.on("click", e => { map.switchStyle(map.style == 'satellite' ? 'standard' : 'satellite'); mapStyleBtn.val(map.style == 'satellite' ? '卫星' : '普通'); }); } } { //切换模式 var displayMode = ''; this.latestRequestMode = ''; //因为可能延迟,所以记录下每次的请求模式,延迟后判断这个 Object.defineProperty(Potree.settings, "displayMode", { get: function get() { return displayMode; }, set: mode => { this.latestRequestMode = mode; console.warn('Request setMode: ' + mode); this.dispatchEvent({ type: 'requestMode', mode }); var config2; var config = Potree.config.displayMode[mode]; if (this.isAtPano() && !this.latestToPano) { config2 = config.atPano; } else { config2 = config.transition; } var changeTileDownload = () => { if (config2.showSkybox || config2.showPoint && config2.pointUsePanoTex) { this.tileDownloader.start(); this.currentPano && this.currentPano.enter(); } else { this.tileDownloader.stop(); this.currentPano && this.currentPano.exit(); this.nextPano && viewer.cancelLoad(this.nextPano); } }; if (mode != displayMode) { var camera = viewer.scene.getActiveCamera(); if (mode == 'showPanos' && viewer.mainViewport.view.isFlying()) { //飞完才能切换全景 var f = () => { if (this.latestRequestMode == mode) { //如果ui还是停在这个模式的话 Potree.settings.displayMode = mode; } viewer.mainViewport.view.removeEventListener('flyingDone', f); viewer.mainViewport.view.removeEventListener('flyCancel', f); }; viewer.mainViewport.view.addEventListener('flyingDone', f); //once viewer.mainViewport.view.addEventListener('flyCancel', f); return; } if (this.isAtPano() && !this.latestToPano) { config2 = config.atPano; } else { config2 = config.transition; if (mode == 'showPanos') { //自动飞入一个pano //要改成飞进最近的。。。 if (this.panos.length == 0) return; //this.modeChanging = true //主要是因为到全景图不会立刻成功 var wait = e => { console.log('flyToPanoDone'); this.removeEventListener('flyToPanoDone', wait); setTimeout(() => { if (this.latestRequestMode == mode) { Potree.settings.displayMode = mode; //被打断,重新执行 } }, e.makeIt ? 1 : 50); }; this.addEventListener('flyToPanoDone', wait); //等待飞行完毕。flyToPano的callback可能不执行所以换这个。但也可能被cancel this.flyToPano({ pano: this.findNearestPano() //dealDoneWhenCancel:true, /* callback: ()=>{ setTimeout(()=>{ //防止循环,所以延迟 if(this.latestRequestMode == mode ){ Potree.settings.displayMode = mode } },1) } */ }); return; } else {} } changeTileDownload(); if (config2.showSkybox || config2.pointUsePanoTex) { var _wait = () => { //console.log('waitdone') //if(e.pano && e.pano != this.currentPano)return //loadedDepthImg setTimeout(() => { if (this.latestRequestMode == mode) { Potree.settings.displayMode = mode; } }, 1); }; //this.updateDepthTex() if (this.checkAndWaitForPanoLoad(this.currentPano, this.basePanoSize, _wait)) { //console.log('等待贴图加载2', this.currentPano.id) return; } } viewer.scene.pointclouds.forEach(e => { Potree.Utils.updateVisible(e, 'displayMode', config2.showPoint, 2); }); if (config2.pointUsePanoTex) { viewer.scene.pointclouds.forEach(e => { e.material.setProjectedPanos(this.currentPano, this.currentPano, 1); }); } else { viewer.scene.pointclouds.forEach(e => { e.material.stopProjectedPanos(); }); } Potree.Utils.updateVisible(this.cube, 'showSkybox', config2.showSkybox); // this.cube.visible = config2.showSkybox //this.cube.visible = config.atPano.showSkybox if (this.cube.visible) { //this.cube.material.setProjectedPanos(this.currentPano, this.currentPano, 1) this.setProjectedPanos({ progress: 1, ifSkybox: true, ifPointcloud: false, easeInOutRatio: 0, pano0: this.currentPano, pano1: this.currentPano }); } else { this.smoothZoomTo(1); this.resetHighMap(); this.hideHighMap(); } /* viewer.dispatchEvent({ type: "enableChangePos", canLeavePano : config.canLeavePano , viewport: }) */ //viewer.mainViewport.unableChangePos = !config.canLeavePano displayMode = mode; if (mode == 'showPanos') { camera.far = viewer.farWhenShowPano; //修改far Potree.settings.pointDensity = 'panorama'; if (Potree.config.displayMode.showPanos.transition.pointUsePanoTex) { viewer.scene.pointclouds.forEach(e => { e.material.pointSizeType = 'FIXED'; }); } this.updateCube(this.currentPano); //viewer.setControls(viewer.fpControls) } else { if (camera.limitFar) camera.far = Potree.settings.cameraFar; //修改far Potree.settings.pointDensity = Potree.settings.UserPointDensity; //Potree.sdk && Potree.sdk.scene.changePointOpacity() if (Potree.config.displayMode.showPanos.transition.pointUsePanoTex) { viewer.scene.pointclouds.forEach(e => { e.material.pointSizeType = Potree.config.material.pointSizeType; }); } //Potree.settings.editType == 'merge' && viewer.setControls(viewer.orbitControls) } camera.updateProjectionMatrix(); if (this.elDisplayModel) { this.elDisplayModel.val(mode == 'showPointCloud' ? ">>全景" : '>>点云'); } /* this.panos.forEach(e=>{ Potree.Utils.updateVisible(e, 'modeIsShowPanos', mode == 'showPanos', 1, mode == 'showPanos' ? 'add':'cancel') // }) */ this.dispatchEvent({ type: 'endChangeMode', mode }); console.log('setModeSuccess: ' + mode); } else { changeTileDownload(); //this.dispatchEvent({type:'endChangeMode',mode}) } } }); Potree.settings.displayMode = 'showPointCloud'; } // 切换模式 end { // var currentPano = null; Object.defineProperty(this, "currentPano", { get: function get() { return currentPano; }, set: function set(e) { if (e != currentPano) { //console.log('set currentPano ', e.id) currentPano && currentPano.exit(); e && e.enter(); currentPano = e; } } }); } { //是否显示marker var ifShowMarker = true; Object.defineProperty(Potree.settings, "ifShowMarker", { get: function get() { return ifShowMarker; }, set: show => { show = !!show; if (show != ifShowMarker) { this.panos.forEach(pano => { Potree.Utils.updateVisible(pano, 'ifShowMarker', show, 1); }); //this.emit('markersDisplayChange', show) ifShowMarker = show; viewer.dispatchEvent('showMarkerChanged'); viewer.dispatchEvent('content_changed'); } } }); } viewer.addEventListener("update", () => { this.update(viewer); }); //viewer.inputHandler.addInputListener(this); var keys = { FORWARD: ['W'.charCodeAt(0), 38], BACKWARD: ['S'.charCodeAt(0), 40], LEFT: ['A'.charCodeAt(0), 37], RIGHT: ['D'.charCodeAt(0), 39] }; viewer.inputHandler.addEventListener('keydown', e => { if (Potree.settings.displayMode == 'showPanos') { for (var i in keys) { if (keys[i].some(a => a == e.keyCode)) { switch (i) { case 'FORWARD': this.flyLocalDirection(Vectors$1.FORWARD.clone()); break; case 'BACKWARD': this.flyLocalDirection(Vectors$1.BACK.clone()); break; case 'LEFT': this.flyLocalDirection(Vectors$1.LEFT.clone()); break; case 'RIGHT': this.flyLocalDirection(Vectors$1.RIGHT.clone()); break; } break; } } } }); } changeModelMat(model, isCurModel) { if (model !== null && model !== void 0 && model.is4dkkModel) { if (model.fileType == '3dTiles') { viewer.setAllTilesets(model, child => { child.runtime.limit2lowestDepth(Potree.settings.displayMode == 'showPanos'); child.runtime.getTileset().tiles.forEach(e => { this.judgeModelMat(e.tileContent, isCurModel); }); }); } else { this.judgeModelMat(model, isCurModel); } } } judgeModelMat(object, isCurModel) { if (!(Potree.settings.mergeType2 && Potree.settings.modelSkybox)) return; object.traverse(mesh => { if (mesh.material) { if (!mesh.materialOutside) { mesh.materialOutside = mesh.material; } mesh.material = Potree.settings.displayMode == 'showPanos' && (this.currentPano.pointcloud == object || isCurModel) ? this.materialInside : mesh.materialOutside; Potree.Utils.setObjectLayers(mesh, Potree.settings.displayMode == 'showPanos' ? 'skybox' : 'model'); //为了渲染到rtEDL } }); } updateDepthTex(pano) { if (this.currentPano != pano || !pano.depthTex) return; //this.depthSampler.changeImg(pano.depthTex.image); //pick sampler要飞到了才能切换图,而skybox贴图是随着全景图切换而切换的 this.cube.material.updateDepthTex(pano); //确保一下 } findNearestPano(pos) { var panos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.panos; pos = pos ? new Vector3().copy(pos) : this.position; var result = Common.sortByScore(panos, [Images360.filters.isEnabled()], [e => -e.position.distanceTo(pos)]); var pano = result[0] && result[0].item; return pano; } /* set flying(v){//正在飞向pano this.flying_ = !!v //console.log('this.flying_ ', !!v ) //this.emit('flying', this.flying_) let config = Potree.config.displayMode[Potree.settings.displayMode] viewer.mainViewport.unableChangePos = !config.canLeavePano || !!v } get flying(){ return this.flying_ } */ flyLocalDirection(dir) { var direction = this.getDirection(dir), option1 = 1 === dir.y ? .4 : .75, option2 = 1 === Math.abs(dir.x); return this.flyDirection(direction, option1, option2, true); } getDirection(e) { if (!e) { return viewer.scene.view.direction; } else { return e = e ? e : new Vector3().copy(Vectors$1.FORWARD), e.applyQuaternion(viewer.mainViewport.camera.quaternion); } } get position() { return this.viewer.scene.view.position.clone(); } isAtPano() { var precision = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1e-6; //是否在某个漫游点上 if (precision) { return this.currentPano && math.closeTo(viewer.scene.view.position, this.currentPano.position, precision); } return this.currentPano && viewer.scene.view.position.equals(this.currentPano.position); } updateProjectedPanos() { //更新材质贴图 //console.warn('updateProjectedPanos') this.projectedPano0 && this.projectedPano1 && this.setProjectedPanos({ pano0: this.projectedPano0, pano1: this.projectedPano1 }); } setProjectedPanos() { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; //设置cube和点云的材质贴图 this.cube.material.setProjectedPanos(o.pano0, o.pano1, o.progress); this.materialInside && this.materialInside.setProjectedPanos(o.pano0, o.pano1, o.progress); if (o.ifPointcloud) { viewer.scene.pointclouds.forEach(e => { e.material.setProjectedPanos(o.pano0, o.pano1, o.progress, o.easeInOutRatio); }); } //console.warn('setProjectedPanos ', o.pano0.id , o.pano1.id) this.projectedPano0 = o.pano0; this.projectedPano1 = o.pano1; } cancelFlyToPano(toPano) { //取消当前已有的飞行准备,前提是相机还未移动 if (viewer.mainViewport.view.isFlying() || toPano && this.latestToPano != toPano) return; //Potree.Log('cancelFlyToPano', this.latestToPano && this.latestToPano.pano.id) this.nextPano = null; this.latestToPano = null; } flyToPano(toPano) { //飞向漫游点 if (!toPano) return; if (typeof toPano == 'number') toPano = this.panos[toPano]; if (toPano instanceof Panorama) { toPano = { pano: toPano }; } var done = (makeIt, disturb) => { //console.log('flyToPano done ', toPano.pano.id, makeIt, disturb ) if (makeIt || disturb) { // disturb已经开始飞行但中途取消 toPano.callback && toPano.callback(makeIt); //this.flying = false this.cancelFlyToPano(toPano); this.updateClosestPano(this.closestPano, false); //飞行结束后取消点击漫游点时得到的closestPano } else {} this.dispatchEvent({ type: 'flyToPanoDone', makeIt, disturb }); this.fastTranMaskPass.stop(); toPano.deferred && toPano.deferred.resolve(makeIt); //测量线截图时发现,resolve需要写在flying=false 后才行。 }; if (!toPano.pano.enabled) return done(false, true); //Potree.Log('hope flyToPano: '+toPano.pano.id, toPano.pano.position.toArray() ) if (!toPano.canCancelLast && this.latestToPano && this.latestToPano != toPano && ( //还在飞 this.latestToPano.pano != this.currentPano || !this.isAtPano())) { //如果旧的toPano只在pano旋转镜头,就直接取消旧的,继续执行 return done(false); } if (this.currentPano == toPano.pano && this.isAtPano() && !toPano.target && !toPano.quaternion) { //已在该pano this.dispatchEvent({ type: 'flyToPano', toPano }); return done(true); } //Potree.Log('flyToPano: '+toPano.pano.id, toPano.pano.position.toArray() /* this.latestToPano && this.latestToPano.pano.id */ ) var target = toPano.target; var config = Potree.config.displayMode[Potree.settings.displayMode]; var pano = toPano.pano; var dis = pano.position.distanceTo(this.position); this.nextPano = pano; this.latestToPano = toPano; //this.flying = true //防止新的请求 //Potree.Log('flyToPano:'+pano.id + ' , duration:'+toPano.duration, null, 12) { //不飞的话是否不要执行这段? var wait = e => { //console.log('wait done', pano.id) if ( /* e.pano && */this.latestToPano && pano != this.latestToPano.pano) return; //loadedDepthImg if (this.latestToPano != toPano) return Potree.Log('已经取消', pano.id); //如果取消了 setTimeout(() => { if (this.latestToPano != toPano) return; this.flyToPano(toPano); }, 1); }; if (!pano.depthTex && pano.pointcloud.hasDepthTex) { //点云模式也要加载depthTex,因获取neighbour需要用到 console.log('等待加载depthtex', pano.id); pano.addEventListener('loadedDepthImg', wait, { once: true }); return pano.loadDepthImg(); } if (config.atPano.showSkybox || config.atPano.pointUsePanoTex) { var a = this.updateCube(this.currentPano, toPano.pano); if (a == 'useBound') { toPano.useBound = true; } if (this.checkAndWaitForPanoLoad(pano, toPano.basePanoSize || this.basePanoSize, wait)) { //console.log('等待贴图加载',pano.id) return; } } } config = Potree.config.displayMode[Potree.settings.displayMode]; //可能换了 var pointcloudVisi = config.atPano.showPoint; //viewer.scene.pointclouds[0].visible Potree.Utils.updateVisible(this.cube, 'showSkybox', config.atPano.showSkybox); // this.cube.visible = config.atPano.showSkybox //console.log('开始飞1') if (config.transition.showPoint) { viewer.scene.pointclouds.forEach(e => { Potree.Utils.updateVisible(e, 'displayMode', true); }); } var endPosition = pano.position.clone(); var T = Potree.config.transitionsTime; /* let maxTime = this.isAtPano() ? T.panoToPanoMax : T.flyIn let duration = toPano.duration == void 0 ? (T.flyMinTime+Math.min(T.flytimeDistanceMultiplier * dis, maxTime)) : toPano.duration */ /* let maxDis = this.isAtPano() ? T.maxDistanceThreshold : T.maxDistanceThresholdFlyIn let duration = toPano.duration == void 0 ? Math.min(dis, T.maxDistanceThreshold) * T.flytimeDistanceMultiplier + T.flyMinTime : toPano.duration */ var maxDis = 7; var duration = toPano.duration == void 0 ? Math.min(dis, maxDis) * T.flytimeDistanceMultiplier + T.flyMinTime : toPano.duration; if (config.transition.showSkybox || config.transition.pointUsePanoTex) { if (Potree.settings.fastTran) { this.fastTranMaskPass.start(); //截图当前画面 viewer.scene.view.position.copy(endPosition); } this.setProjectedPanos({ progress: 0, ifSkybox: this.cube.visible, ifPointcloud: config.transition.pointUsePanoTex, easeInOutRatio: pointcloudVisi ? 0.3 : 0, pano0: this.currentPano, pano1: pano }); } if (toPano.useBound) { duration = Math.min(1500, duration); toPano.easeName = 'easeInOutQuad'; } else { if (endPosition.equals(this.position)) toPano.easeName = 'easeOutSine'; } { toPano.easeName = toPano.easeName || 'linearTween'; toPano.duration = duration; this.beforeFlyToPano(toPano); } /* let fly = ()=>{ this.dispatchEvent({type:'flyToPano', toPano}) viewer.scene.view.setView({position:endPosition, target, quaternion:toPano.quaternion , duration, callback:()=>{ if(!config.atPano.pointUsePanoTex){ viewer.scene.pointclouds.forEach(e=>{ e.material.stopProjectedPanos() }) } this.currentPano = pano; this.nextPano = null; if(Potree.settings.displayMode == 'showPanos'){ viewer.scene.pointclouds.forEach(e=>{ Potree.Utils.updateVisible(e, 'displayMode',pointcloudVisi) }) } done(true); this.updateDepthTex(this.currentPano) }, onUpdate:(progress)=>{ //console.log('uniforms progress',progress) this.cube.material.uniforms.progress.value = progress viewer.scene.pointclouds.forEach(e=>{ e.material.uniforms.progress.value = progress }) }, cancelFun:()=>{ done(false, true) }, Easing:easeName }) //duration > 0 && (this.flying = true) //再写一遍 防止cancel其他项目导致flying为false } */ var _onUpdate = progress => { this.cube.material.uniforms.progress.value = progress; this.materialInside && (this.materialInside.uniforms.progress.value = progress); viewer.scene.pointclouds.forEach(e => { e.material.uniforms.progress.value = progress; }); }; var fly = () => { var startProgress = toPano.progress = toPano.progress || 0; var loadNextProgress = MathUtils.clamp(1 - 2.5 / dis, 0.3, 0.8); //console.log(loadNextProgress, (1-loadNextProgress) * dis ) this.dispatchEvent({ type: 'flyToPano', toPano }); viewer.scene.view.setView({ position: endPosition, target, quaternion: toPano.quaternion, duration: toPano.duration, onUpdate: (progress_, delta) => { var progress = startProgress + progress_ * (1 - startProgress); var currentSpeed; if (progress_ != 1 && progress_ != 0) { // 1的时候不准,往往偏小, 0的时候速度为0,也不记录 currentSpeed = (progress - toPano.progress) * dis / delta; //记录下当前速度,当变为匀速时可以过渡到flySpeed } else { currentSpeed = toPano.currentSpeed || 0; } toPano.currentSpeed = currentSpeed; toPano.progress = progress; //console.log('progress_', progress_, 'delta',delta , 'progress', progress/*, 'currentSpeed', currentSpeed, */ ) if (progress > loadNextProgress && toPano.easeName == 'linearTween' && currentSpeed) { // 减速. 如果仅旋转就不停止 //console.log('减速', /* currentSpeed , */progress_ ) toPano.easeName = 'easeOutSine'; var restDis = (1 - progress) * dis; toPano.duration = Math.PI / 2 * restDis / currentSpeed; // 这样能保证初始速度为currentSpeed viewer.scene.view.cancelFlying('all', false); //为了防止执行cancelFun先主动cancel toPano.flyCount = 2; fly(toPano); } _onUpdate(progress); }, callback: () => { if (!config.atPano.pointUsePanoTex) { viewer.scene.pointclouds.forEach(e => { e.material.stopProjectedPanos(); }); } this.lastPano = this.currentPano; //记录,调试 this.currentPano = pano; this.nextPano = null; if (Potree.settings.displayMode == 'showPanos') { viewer.scene.pointclouds.forEach(e => { Potree.Utils.updateVisible(e, 'displayMode', pointcloudVisi); }); } done(true); this.updateDepthTex(this.currentPano); //删除dispose的depthTex }, cancelFun: () => { done(false, true); }, Easing: toPano.easeName, ignoreFirstFrame: toPano.flyCount != 2 //变换transition时不停一帧 }); }; if (Potree.settings.displayMode == 'showPanos') { setTimeout(fly, 40); //更新geo后缓冲 } else { fly(); } //console.log('flyToPano:', toPano.pano.id) } beforeFlyToPano(toPano) { if (this.currentPano != toPano.pano) { if (Potree.settings.displayMode == 'showPanos') { this.resetHighMap(); } this.smoothZoomTo(toPano.zoomLevel || 1, toPano.duration / 2); } } /* updateCube(pano0, pano1){ if(Potree.settings.displayMode != 'showPanos')return if(!viewer.scene.pointclouds.some(e=>!e.hasDepthTex)) return this.updateCube2(pano0, pano1) //都hasDepthTex的话 let useBound = (bound, size)=>{ size = size || bound.getSize(new THREE.Vector3) let center = bound.getCenter(new THREE.Vector3) size.max(new THREE.Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth)) this.cube.scale.copy(size) this.cube.position.copy(center) } let getPanoBound = (pano)=>{//因漫游点可能在点云外部,如室外平地,所以需要union进漫游点 let panoBound = new THREE.Box3 panoBound.expandByPoint(pano.position) panoBound.expandByVector(new THREE.Vector3(10,10,10));//give pano a margin return pano.pointcloud.bound.clone().union(panoBound) } let getDis = (bound1, bound2)=>{ //获取bound1边界到bound2边界距离 if(bound1.intersectsBox(bound2))return 0 let center1 = bound1.getCenter(new THREE.Vector3) let center2 = bound2.getCenter(new THREE.Vector3) let dis = center1.distanceTo(center2) let dis1 = bound1.distanceToPoint(center2) let dis2 = bound2.distanceToPoint(center1) return dis1 + dis2 - dis } if(pano1){//过渡 if(pano0.pointcloud == pano1.pointcloud){//同一个数据集内的过渡 useBound(getPanoBound(pano0)) }else{//非同一个数据集内的过渡 let bound = getPanoBound(pano0).union(getPanoBound(pano1)) if(getDis(pano0.pointcloud.bound, pano1.pointcloud.bound) < 100){ useBound(bound) }else{//如果两个数据集boundingbox距离大于这个距离,扩大一下,防止精度问题导致失真//对很远的数据集似乎没有什么用 let size = bound.getSize(new THREE.Vector3) let max = Math.max(size.x, size.y, size.z) size.set(max,max,max) useBound(pano0.pointcloud.bound.clone().union(pano1.pointcloud.bound), size) } } }else{ useBound(getPanoBound(pano0)) //假定一个数据集不会太大,否则会造成失真,且bump时移动距离看起来很小。或者可以考虑用固定大小 } } */ getIntersect(pano, dir, origin) { if (pano && pano.pointcloud.hasDepthTex) { return this.depthSampler.sample({ dir }, pano, true); } else { origin = origin || pano.position; return viewer.inputHandler.getIntersect({ viewport: viewer.inputHandler.hoverViewport, onlyGetIntersect: true, usePointcloud: true, point: origin.clone().add(dir), cameraPos: origin }); } } /* updateCube(pano0, pano1){//增加细分的版本,且垂直方向上也分多个 if(Potree.settings.displayMode != 'showPanos')return console.log('updateCube',pano0.id, pano1&&pano1.id) let f = (bound, size)=>{ size = size || bound.getSize(new THREE.Vector3) let center = bound.getCenter(new THREE.Vector3) size.max(new THREE.Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth)) this.cube.scale.copy(size) this.cube.position.copy(center) } this.cube.geometry.dispose(); if(pano1){//过渡 let count1, count2; let panoIndex = 0 let add = (pano, dir )=>{ let getPI = function(index, panoIndex_){ if(panoIndex_ == void 0) panoIndex_ = panoIndex return (count1 * count2 + 2 ) * panoIndex_ + index + 2 } let minZ, maxZ minZ = pano.floorPosition.z {//天花板高度值 //用三个间隔120度散开,和中心垂直线成一定夹角的三个向量去求 最高高度 (不求平均的原因:万一是0不好算) let rotMat = new THREE.Matrix4().makeRotationX(THREE.Math.degToRad(40))// 角度不能小于天花板中空的半径,大概就是0.2*Math.PI=36度 let dir1 = new THREE.Vector3(0,0,1).applyMatrix4(rotMat) let rotMat1 = new THREE.Matrix4().makeRotationZ(Math.PI*2 / 3); let rotMat2 = new THREE.Matrix4().makeRotationZ(-Math.PI*2 / 3); let dir2 = dir1.clone().applyMatrix4(rotMat1) let dir3 = dir1.clone().applyMatrix4(rotMat2) let zs = [dir1,dir2,dir3].map(dir_=>{ let intersect = this.depthSampler.sample( {dir: dir_}, pano, true ) let z = intersect ? intersect.location.z : pano.position.z return z }) zs.sort((a,b)=>{return b-a});//得最大值 maxZ = zs[0] let min = pano.position.z + 1 if(maxZ < pano.position.z + 0.04){//户外 maxZ = pano.position.z + 50 } maxZ = Math.max(min,maxZ) console.log(pano.id, 'maxZ:',maxZ ) console.log(pano.id, 'minZ:',minZ ) } [maxZ, minZ ].forEach(z=>{ posArr.push(pano.position.clone().setZ(z)) }) const angle = Math.PI/8 let getDir = (angle_)=>{ let rotMat = new THREE.Matrix4().makeRotationZ(angle_) return dir.clone().applyMatrix4(rotMat) } let dirs = [ getDir(angle*4), getDir(angle*3), getDir(angle*2), getDir(angle), dir.clone(), getDir(-angle) , getDir(-angle*2), getDir(-angle*3), getDir(-angle*4) ]; // 夹角总和180度 count1 = dirs.length dirs.forEach((dir, index)=>{//获取在这个方向上和墙体intersect的最远距离,使用中、上、下三个方向 let dirs_ = [ dir.clone().setZ(Math.tan(THREE.Math.degToRad(30))).normalize(), dir.clone().setZ(Math.tan(THREE.Math.degToRad(15))).normalize(), dir.clone(), // 水平方向 dir.clone().setZ(-Math.tan(THREE.Math.degToRad(15))).normalize(), dir.clone().setZ(-Math.tan(THREE.Math.degToRad(30))).normalize(), ]; count2 = dirs_.length dirs_.forEach((dir_, i) =>{ let intersect = this.depthSampler.sample( {dir: dir_}, pano, true ) let location if(!intersect){ //超级远 let distance = 100 location = dir_.clone().multiplyScalar(distance).add(pano.position) intersect = {distance,location} } //intersect.distance location = intersect.location.clone() let shouldZ// = THREE.Math.clamp(intersect.location.z, minZ, maxZ); let needShrink = false if(i == 0){//最上方的点高度直接等于天花板 shouldZ = maxZ if(location.zminZ)location.z = minZ else needShrink = true } if(needShrink ){//需要在保持dir_不变的情况下修改z let len = (shouldZ - pano.position.z) / (intersect.location.z - pano.position.z) * intersect.distance location = dir_.clone().multiplyScalar(len).add(pano.position) } posArr.push(location) if(index!=0 && i!=0){//加入一块四方面 let curIndex = getPI(count2 * index + i); faceArr.push([curIndex-1, curIndex-count2-1, curIndex-count2], [curIndex-1, curIndex, curIndex-count2]) } }) if(index!=0){ let top = -2; let btm = -1 faceArr.push([getPI(count2*(index-1) ), getPI(count2*index ), getPI(top) ])//天花板扇形 faceArr.push([getPI(count2*index-1), getPI(count2*(index+1)-1), getPI(btm) ] )//地板扇形 }else{ //加入和另一个pano连接的其中一个侧边 let panoIndex2 = (panoIndex + 1) % 2; for(let i=1;i 2 && arguments[2] !== undefined ? arguments[2] : {}; //是否之间没有遮挡(在加载visibles之前,自己算) 最好pano0是currentPano if (!pano0 || !pano1) return; var margin = 0.1; var map0 = this.neighbourMap[pano0.id]; //主 var map1 = this.neighbourMap[pano1.id]; //副 /* if(map0[pano1.id] != void 0){ ifNeighbour = map0[pano1.id] } if(!ifNeighbour && map1[pano0.id] != void 0){ ifNeighbour = map1[pano0.id] } */ var ifNeighbour = map1[pano0.id] == void 0 ? map0[pano1.id] : map0[pano1.id] && map1[pano0.id]; //如果map1没计算就只要返回map0 var dis = pano0.position.distanceTo(pano1.position); if (math.closeTo(dis, 0)) { //两个点相同 ifNeighbour = map1[pano0.id] = map0[pano1.id] = true; return true; } if (dontCompute) return ifNeighbour; var logSids = [/* '1739923562316697600|3','1739923562316697600|2' */]; var ifLog = pano0.sid == logSids[0] && pano1.sid == logSids[1] || pano0.sid == logSids[1] && pano1.sid == logSids[0]; if (ifLog) { console.log(2); } var ifSheltered = (mainPano, subPano) => { //该点前方近处是否都被遮挡 。 为了防止杂点干扰,多个方向探测 var vec = new Vector3().subVectors(subPano.position, mainPano.position).normalize(); var getDir = (angle_, upDown) => { //基于vec的方向 向左向右旋转 //if(upDown) vec.clone().applyAxisAngle(new THREE.Vector3(1, 0, 0), upDown); return vec.clone().applyAxisAngle(new Vector3(0, 0, 1), angle_); }; var minScore = 0.25; var angles = [20, 16, 12.5, 10, 8, 6, 4.5, 3, 1, -1, -3, -4.5, -6, -8, -10, -12.5, -16, -20]; //水平方向角度 3之间有较大概率杂点, 3以外一部分有较大概率有空隙所以紧凑点 var wellCount = 0; var seccess = []; for (var i = 0; i < angles.length; i++) { var rad = MathUtils.degToRad(angles[i]); var dir = getDir(rad); var color = void 0; var intersectPoint = viewer.images360.depthSampler.sample({ dir }, mainPano, true); if (!intersectPoint || intersectPoint.distance * Math.cos(Math.abs(rad)) /* + margin */ > dis) { //投影在vec方向的长度不超过漫游点间距 wellCount++; seccess.push(angles[i]); color = new Color('#0f8'); } ifLog && addLine(mainPano.position, dir, dis, color); } //console.log('ifSheltered') if (ifLog) { console.log('ifSheltered seccess', seccess, 'id:', mainPano.originID, subPano.originID); } var score = wellCount / angles.length; if (score >= minScore) { //合格个数 return score; } }; /* 识别一定角度范围内是否有遮挡时 几种奇葩的情况: 1 在墙的两边的但是墙是倾斜的漫游点: A / / / B 从B出发和BA成20度的射线和墙面的交点会远于A,导致识别为无遮挡。 所以还是改为识别范围内多个深度图像素, 合格像素个数占比 至少要大于50%,因为半边墙壁是50% 如SG-9UsbysDufBw&formal&test 的 6、9点。 而SS-GTmFBp1JN8k&formal&test的 2、3两点是人物遮挡 2 可以通行,但是右边是墙,右边的都检测失败,左侧的又有一些杂点,导致成功dir个数很低。 所以minRatio 要降低于0.5 */ //三个方向 : position0到position1, position0到floorPosition1, position1到floorPosition0。 只要有一个满足ifNeighbour就为true。 不过为了不使sampler总换图,先只考虑从主pano到副pano的方向 var getNeighbour = (mainPano, subPano) => { var dirPoints = [[subPano.position, mainPano.position]]; //注: 点A能到B不代表点B能到A,因为拍摄时物体会移动,或点位相对位置不对,无论是否是意外遮挡都且记下来,反正最后只要有一方可行就算相邻。 if (dis < 20) { //在远处去掉对floorPosition的判断 dirPoints.push([subPano.floorPosition.clone().add(new Vector3(0, 0, 0.1)), mainPano.position]); } if (dis < 12) { //为了防止楼梯拐角、杂点遮挡。 尽量只在穿墙时不可通行 dirPoints.push([subPano.position.clone().add(new Vector3(0, 0, 0.8)), mainPano.position]); var normal = math.getNormal2d({ p1: subPano.position, p2: mainPano.position }).multiplyScalar(0.3); //左右方向 dirPoints.push([subPano.position.clone().add(new Vector3(normal.x, normal.y, 0.1)), mainPano.position]); dirPoints.push([subPano.position.clone().add(new Vector3(-normal.x, -normal.y, 0.1)), mainPano.position]); } //console.warn('getNeighbour', mainPano.id,subPano.id) for (var i = 0; i < dirPoints.length; i++) { var dir = new Vector3().subVectors(dirPoints[i][0], dirPoints[i][1]).normalize(); var intersectPoint = viewer.images360.depthSampler.sample({ dir }, mainPano, true, true); if (!intersectPoint || intersectPoint.distance + margin > dirPoints[i][0].distanceTo(dirPoints[i][1])) { //if(i>2)console.log('haha',i,'id:',mainPano.id,subPano.id) return true; } } }; //if(!ifNeighbour && (map0[pano1.id] == void 0 || computeTwoDir && !map0[pano1.id] && map1[pano0.id] == void 0 )) {//主方向为空且不为邻居 if (pano0.pointcloud.hasDepthTex || pano1.pointcloud.hasDepthTex) { if (computeTwoDir ? map0[pano1.id] == void 0 || map1[pano0.id] == void 0 : map0[pano1.id] == void 0 && map1[pano0.id] !== false) { //2024.3.20改为必须两个方向都为true才行。 因为如果两个点分别在两个数据集相距很远,A确定有墙无法到B,B朝A看 没有B所在的数据集点云遮挡,因深度图不会包含别的数据集的点,故深度图探测到A处为无遮挡,就会导致会飞到遥远的A。 即使在同一个数据集,因为点云可以编辑位置,导致AB相对位置错误,也要避免这种情况可以互相乱走。 缺点是更容易被杂点阻挡,所以需要ifShelter降低阈值。 if (map0[pano1.id] == void 0 && pano0.depthTex) { var is = getNeighbour(pano0, pano1); map0[pano1.id] = !!is; } if (computeTwoDir && map0[pano1.id] && pano1.depthTex && map1[pano0.id] == void 0) { //computeTwoDir : 允许反向计算,即可以读取另一张的深度图 。 如果map0为false,map1就不用计算,只需要等待计算ifShelter var _is = getNeighbour(pano1, pano0); map1[pano0.id] = !!_is; } if (map0[pano1.id] === false || map1[pano0.id] === false) { if (dis < 20) { //再检查下 只要两方都没有被完全遮挡就算可通行 针对杂点较多的情况 if (pano0.depthTex && pano1.depthTex) { ifNeighbour = false; var a = ifSheltered(pano0, pano1); if (a) { var b = ifSheltered(pano1, pano0); if (b && a + b >= 0.6) { ifNeighbour = true; } } map0[pano1.id] = map1[pano0.id] = ifNeighbour; } } else { //标记为无需再计算, 因已经失败。 当map0和map1都不为void 0后就无法再计算了。 if (map0[pano1.id] === void 0) map0[pano1.id] = 0; if (map1[pano0.id] === void 0) map1[pano0.id] = 0; } } ifNeighbour = map1[pano0.id] == void 0 ? map0[pano1.id] : map0[pano1.id] && map1[pano0.id]; //如果map1没计算就只要返回map0 if (ifLog) { console.log('isNeighbour', pano0.id + "(" + pano0.originID + ")", pano1.id + "(" + pano1.originID + ")", map0[pano1.id], map1[pano0.id]); } } } else if (!onlyUseTex && !ifNeighbour) { //使用点云判断(有深度贴图时不会执行到这) /* let inDirection = ()=>{ let dir = new THREE.Vector3().subVectors(pano1.position,pano0.position).normalize() let dis = pano1.position.distanceTo(pano0.position) let fov = THREE.Math.degToRad(viewer.mainViewport.camera.fov) let hfov = cameraLight.getHFOVForCamera(viewer.mainViewport.camera , true ); let hov = Math.min(fov, hfov) let max = Math.cos(THREE.Math.degToRad(10)) let min = Math.cos(THREE.Math.degToRad(40)) if(this.getDirection().dot(dir) > THREE.Math.clamp(Math.cos(hov/2 ) * dis / 10, min, max )){//距离越远要求和视线角度越接近 return true } } if(computeDirFirst){//先计算方向,防止重复计算ifBlockedByIntersect if(inDirection()){ ifNeighbour = !viewer.inputHandler.ifBlockedByIntersect({point:pano1.position, margin, cameraPos:pano0.position}) } }else{ ifNeighbour = !viewer.inputHandler.ifBlockedByIntersect({point:pano1.position, margin, cameraPos:pano0.position}) if(ifNeighbour && !inDirection()){ ifNeighbour = undefined //不确定 } } map0[pano1.id] = map1[pano0.id] = ifNeighbour ? 'byCloud' : ifNeighbour//写简单点 */ map0[pano1.id] = map1[pano0.id] = true; //全部可通行 } if (map0[pano1.id] && map1[pano0.id]) { pano0.neighbours.includes(pano1) || pano0.neighbours.push(pano1); pano1.neighbours.includes(pano0) || pano1.neighbours.push(pano0); } return ifNeighbour; } bump(direction) { //撞墙弹回效果 if (!this.bumping && !this.latestToPano) { var distance = Potree.settings.displayMode == 'showPanos' ? 0.15 : 0.12; //感觉点云模式比全景模式更明显,所以降低 var currentPos = this.position.clone(); var endPosition = new Vector3().addVectors(this.position, direction.clone().multiplyScalar(distance)); var duration = 150; viewer.scene.view.setView({ position: endPosition, duration, callback: () => { viewer.scene.view.setView({ position: currentPos, duration: duration * 5, callback: () => { this.bumping = false; //this.dispatchEvent('cameraMoveDone') }, Easing: 'easeInOutSine', cancelFun: () => { this.bumping = false; } }); this.bumping = true; }, cancelFun: () => { this.bumping = false; }, Easing: 'easeInOutSine' }); this.bumping = true; } //备注:将4dkk中的‘前后方向变化fov、左右方向移动镜头’ 都改为移动镜头。 因为这里无法判断左右离壁距离。 } flyToPanoClosestToMouse() { /* if (Date.now() - this.mouseLastMoveTime > 50) { //this.intersect = this.getMouseIntersect(); this.intersect && this.updateClosestPano(this.intersect); } */ if (!Potree.settings.ifShowMarker) { //不显示marker的时候mousemove没更新鼠标最近点所以更新 this.updateClosestPano(viewer.inputHandler.intersect); } //console.log('flyToPanoClosestToMouse',this.closestPano) if (this.closestPano) { var pano = this.closestPano; return this.flyToPano({ pano, easeName: this.isAtPano() ? 'linearTween' : 'easeInOutQuad' }); } var direction = this.viewer.inputHandler.getMouseDirection().direction; this.flyDirection(direction); } flyDirection(direction, option1, option2, byKey) { if (viewer.mainViewport.view.isFlying()) { // closestPanoInDirection函数耗时长,飞行时运行会卡顿(如果以后加无缝过渡再说) return; } var deferred = $.Deferred(); //this.history.invalidate(); var panoSet = this.closestPanoInDirection(direction, option1, option2, byKey); if (panoSet) { this.flyToPano({ pano: panoSet, callback: deferred.resolve.bind(deferred, !0) }); } else { //如果离数据集较远,转动也很难找到点云,就飞到就近点: if (Potree.settings.displayMode == 'showPointcloud') { var po = viewer.scene.pointclouds.find(e => e.visibleNodes.some(a => a.getLevel() > Math.ceil(e.maxLevel * 0.15))); //虽然当点云在前方很远的地方也可能符合 if (!po) { //无可见点云 //console.log('no visi cloud') if (!this.panos.length) { //如果场景中没有漫游点,如SG-t-XPf1k9pv3Zg 点击后回到可见区域 if (viewer.scene.pointclouds.length == 0) return; var map = new Map(); var clouds = viewer.scene.pointclouds.filter(e => e.root.geometryNode); clouds.forEach(e => map.set(e, e.bound.distanceToPoint(this.position))); clouds.sort((a, b) => map.get(a) - map.get(b)); viewer.flyToDataset({ focusOnPoint: true, pointcloud: clouds[0], duration: 500 }); //飞最近的一个点云 return deferred.promise(); } this.flyToPano({ pano: this.findNearestPano(), duration: 500, callback: deferred.resolve.bind(deferred, !0) }); return deferred.promise(); } } this.bump(direction); deferred.resolve(!1); } return deferred.promise(); } closestPanoInDirection(direction, option1, option2, byKey) { return this.rankedPanoInDirection(0, direction, option1, option2, byKey); } rankedPanoInDirection(t, direction, option1, option2, byKey) { //此direction为mouseDirection,是否需要加上相机角度的权重 var startTime = Date.now(); var panoSet = { pano: null, candidates: [] //缓存顺序--如果需要打印的话 }; t || (t = 0); option1 = void 0 !== option1 ? option1 : 0.6; //.75; 2024.3.22改小,也就是可以走的角度范围增加,主要针对像山野那种很大的场景,不知道可以走哪,容易因角度范围内无近点而飞到远处的情况。但不能太小,总是横着走路 var o = option2 ? "angle" : "direction"; var floor = viewer.modules.SiteModel.currentFloor; var entity = viewer.modules.SiteModel.inEntity; var getHeightDis = pano => { if (floor && !floor.panos.includes(pano) && pano.position.z < this.position.z) { //若是上方的漫游点,就正常走。因为一般不会点击天花板。 return this.position.z - pano.position.z; } else { return 0; } }; var disSquareMap = new Map(); this.panos.forEach(pano => { var dis2 = pano.position.distanceToSquared(this.position); //距离目标点 disSquareMap.set(pano, dis2); }); var changeTexCount = 0, maxWaitDur = 300; //maxSamplerChangeTex = THREE.Math.clamp( maxWaitDur / Potree.timeCollect.depthSampler.median, 2, 10) //计算换贴图最大数目 var request = [ //必要条件 Images360.filters.not(this.currentPano), Images360.filters.isEnabled(), //Images360.filters.inFloorDirection( this.position, direction, option1 ), //原先用inPanoDirection,但容易穿楼层,当mouse较低或较高 //因不束缚纵向所以可能往相反反向 pano => { /* let isNeighbour = this.isNeighbour(this.currentPano, pano, true, true); //不计算的 if(isNeighbour == void 0){ let willChangeTex = pano.depthTex && !this.depthSampler.imgDatas.some(e=>e.pano == pano) if(changeTexCount < maxSamplerChangeTex || !willChangeTex ){ isNeighbour = this.isNeighbour(this.currentPano, pano, false, true);//计算 if(willChangeTex && isNeighbour != void 0) changeTexCount++ }else{ if(disSquareMap.get(pano) < 500)return true //因为费时,超过一定个数就不计算了,距离近的话先可通行。 } } */ // 不会再changeTex了 var isNeighbour = this.isNeighbour(this.currentPano, pano, { onlyUseTex: true }); if (isNeighbour || pano.noNeighbour && disSquareMap.get(pano) < 200) { //在靠近孤立点时可以通行。但是不好把握这个距离,太远的话很多地方都会不小心到孤立点,太近的话可能永远到不了。 return true; } } /* (pano)=>{ //防止不小心穿越地板到下一层, 尽量走楼梯,实在没有楼梯或楼梯漫游点稀疏的话就通过楼层按钮。 let dis = getHeightDis(pano) //console.log('getHeightDis',pano.id,dis) if(dis < 3){//不能超过最大高度差( 最大高度差暂定为接近一层楼的高度。)(最好的解决方案是设置漫游可行) return true }else{ return this.isNeighbour(this.currentPano, pano) } } */]; if (!byKey) { request.push(Images360.filters.inPanoDirection(this.position, this.getDirection(), option1 /* , true */)); //垂直方向上再稍微限制一下, 要接近视线方向,避免点击前方时因无路而到下一楼。但不能太高,否则楼梯上稍微朝下点击都到不了上方。之所以使用视线方向是因为镜头方向比鼠标方向目的性更强。 } var list = [ //决胜项目 pano => { return -disSquareMap.get(pano); }, Images360.scoreFunctions[o](this.position, direction, true), pano => { var neighbour = this.isNeighbour(this.currentPano, pano, { dontCompute: true, isNeighbour: true }); //不计算的 return neighbour ? directionFactor : 0; } /* (pano)=>{//尽量不穿越地板到下一层 let dis = getHeightDis(pano) return -dis * directionFactor * 0.1; }, */ /* (pano)=>{ //尽量在一个建筑内行走,这样不易穿墙 let score = 0 if(entity ){ if(!entity.panos.includes(pano) ) score -= directionFactor * 0.01; //不能设置太高,否则会走不进大房间的小房间中,因为容易穿过小房间的一个门到另一个门外 if(!floor.panos.includes(pano)) {//避免穿楼层 let heightDiff = Math.abs(pano.position.z - this.position.z); if(heightDiff > 2){ score -= directionFactor * 0.1 * heightDiff; } } } return score } */]; if (!byKey && viewer.inputHandler.intersect && this.currentPano) { //方便上下楼, 考虑panos之间的角度差 var pos1 = this.currentPano.floorPosition; var vec1 = new Vector3().subVectors(viewer.inputHandler.intersect.location, pos1).normalize(); //应该只有atPano时才会执行到这吧? list.push(function (pano) { var pos2 = pano.floorPosition; var vec2 = pos2.clone().sub(pos1).normalize(); return vec2.dot(vec1) * directionFactor * 4; }); } this.findRankedByScore(t, request, list, panoSet); //console.log( 'costTime:',Date.now() - startTime) return panoSet.pano; } findRankedByScore(e, t, i, n) { n && (n.candidates = null, //candidates 缓存顺序--如果需要打印的话 n.pano = null), e || (e = 0); var r = Common.sortByScore(this.panos, t, i); //console.log('findRankedByScore', r && r.map(u=>u.item.id + '| ' + math.toPrecision(u.score,4) + " | " + math.toPrecision(u.scores,4))) return !r || 0 === r.length || e >= r.length ? null : (n && (n.candidates = r, n.pano = r[e].item), r[e].item); } updateClosestPano(intersect, state) { //hover到的pano 大多数时候是null var pano; if (intersect instanceof Panorama) { //漫游模式 pano = state ? intersect : null; } else { if (this.isAtPano() || this.bumping) { return; } else { var filterFuncs = []; intersect = intersect && intersect.location; if (!intersect) return; var sortFuncs = Potree.settings.editType != 'pano' ? [Images360.sortFunctions.floorDisSquaredToPoint(intersect)] : [Images360.sortFunctions.disSquaredToPoint(intersect)]; pano = Common.find(this.panos, filterFuncs, sortFuncs); } } if (pano != this.closestPano) { pano && (this.isPanoHover = !0); this.closestPanoChanging(this.closestPano, pano); // 高亮marker //console.log('closestPano '+ (pano ? pano.id : 'null' )) this.closestPano = pano; } else { this.isPanoHover = !1; } } closestPanoChanging(oldPano, newPano) { if (!Potree.settings.ifShowMarker) return; oldPano && oldPano.hoverOff({ byImages360: true }); newPano && newPano.hoverOn({ byImages360: true }); } getTileDirection() { //根据不同dataset的来存储 var vectorForward = viewer.scene.view.direction.clone(); var vectorForwards = viewer.scene.pointclouds.concat(viewer.objs.children.filter(e => e.panos)).map(e => { var inv = new Matrix4().copy(e.rotateMatrix).invert(); //乘上dataset的旋转的反转 var direction = vectorForward.clone().applyMatrix4(inv); return { datasetId: e.dataset_id, direction: math.convertVector.ZupToYup(direction) }; }); //return vectorForwards[0].direction return { datasetsLocal: vectorForwards, vectorForward }; } update() { //if(this.tileDownloader.started){ var vectorForwards = this.getTileDirection(); //vectorForwards = vectorForwards[0].direction this.updateTileDownloader(tileArr, vectorForwards); this.updatePanoRenderer(vectorForwards); //} this.updateZoomPano(); } updateTileDownloader(t, vectorForward) { var i = this.nextPano || this.currentPano; if (i) { this.tileDownloader.tilePrioritizer.updateCriteria(i, viewer.scene.view.position.clone(), vectorForward, t.length > 0 ? t : null), this.tileDownloader.processPriorityQueue = !0; } } updatePanoRenderer(vectorForward) { var i = this.nextPano || this.currentPano; if (i) { if (this.panoRenderer.hasQueuedTiles() && i) { this.panoRenderer.updateDirection(vectorForward); } } } //等待部分加载完 checkAndWaitForTiledPanoLoad(pano, basePanoSize, callback1, callback2, progressCallback, iswait, isclear, l) { //console.log('checkAndWaitForTiledPanoLoad',pano.id) if (!pano) { console.error("Player.checkAndWaitForTiledPanoLoad() -> Cannot load texture for null pano."); } var vectorForward = this.getTileDirection(); if (!pano.isLoaded(basePanoSize)) { iswait && viewer.waitForLoad(pano, function () { //发送loading return pano.isLoaded(basePanoSize); }); /* var fov = {//test for direction 预加载的边缘有一丢丢不准确,尤其在相机倾斜时(4dkk也是)。 hFov: cameraLight.getHFOVForCamera(viewer.scene.getActiveCamera() ), vFov: viewer.scene.getActiveCamera().fov }//原先是null,不要求方向 */ var fov = null; //若不为null的话,因为可能可见范围的tile下载过了从而无法触发下载,然后得不到下载成功的消息,怎么办 pano.loadTiledPano( /* 1024 */basePanoSize, vectorForward, fov, isclear, l, null).done(function (e, t) { callback1 && callback1(e, t); }.bind(this)).fail(function (msg) { callback2 && callback2(msg); }.bind(this)).progress(function (e, t, i) { progressCallback && progressCallback(e, t, i); }.bind(this)); return !0; } } fitPanoTowardPoint(o) { //寻找最适合的点位 var point = o.point, //相机最佳位置 target = o.target || o.point, //实际要看的位置 require = o.require || [], rank = o.rank || [], force = o.force, getAll = o.getAll, bestDistance = o.bestDistance || 0, sameFloor = o.sameFloor, maxDis = o.maxDis, dir = o.dir; var camera = viewer.scene.getActiveCamera(); if (target && !dir) { dir = new Vector3().subVectors(target, point).normalize(); } var atFloor = sameFloor && viewer.modules.SiteModel.pointInWhichEntity(point, 'floor'); //if(o.floor)require.push(Panorama.filters.atFloor(o.floor)) var checkIntersect = o.checkIntersect; var base = Math.max(300, viewer.bound.boundSize.length() * 3); if (o.boundSphere) { //只接受boundSphere var aspect = 1; //size.x / size.y var dis; if (camera.aspect > aspect) { //视野更宽则用bound的纵向来决定 dis = /* size.y */o.boundSphere.radius /* / 2 */ / MathUtils.degToRad(camera.fov / 2); } else { var hfov = cameraLight.getHFOVForCamera(camera, true); dis = /* size.x */o.boundSphere.radius /* / 2 */ / (hfov / 2); } bestDistance = dis; //*0.8 } var disSquareMap = new Map(); var bestDisSquared = bestDistance * bestDistance; var maxDisSquared = maxDis && maxDis * maxDis; this.panos.forEach(pano => { var dis2 = pano.position.distanceToSquared(target); //距离目标点 disSquareMap.set(pano, dis2); }); var panos = this.panos.sort((p1, p2) => { return disSquareMap.get(p1) - disSquareMap.get(p2); }); if (maxDisSquared) { //热点超过最大距离不可见的 var panos2 = [], _pano, i = 0; while (_pano = panos[i], disSquareMap.get(_pano) < maxDisSquared) { panos2.push(_pano); i++; } if (panos2.length == 0) return { pano: _pano, msg: 'tooFar' }; //全部都大于maxDis, 就返回最近的 panos = panos2; } rank.push(pano => { var dis1 = Math.abs(pano.position.distanceToSquared(point) - bestDisSquared); //距离最佳位置 disSquareMap.set(pano, dis1); if (!target) { return -dis1; } else { var dis2 = disSquareMap.get(pano); if (o.gotoBestView) { //忽略和当前视线的角度 return -(dis1 + dis2 * 0.3); } var vec2 = new Vector3().subVectors(target, pano.position).normalize(); var cos = dir.dot(vec2); //let result = (- dis1 - Math.pow(dis2 , 1.5)) / (cos + 2) // cos+2是为了调整到1-3, var result = (dis1 + dis2 * 0.3) * (-1 + cos * 0.9); //尽量贴近最佳位置的角度, 或贴近相机原来的角度 。尽量靠近最佳观测点,并且优先选择靠近目标点的位置.(注意cos的乘数不能太接近1,否则容易只考虑角度) //Potree.Log(pano.id, dis1, dis2, cos, result,{font:{toFixed:2,fontSize:10}}) return result; } //注:热点最好加上法线信息,这样可以多加一个限制,尽量顺着热点像展示的方向。 }, pano => { var score = 0; if (pano.depthTex && checkIntersect) { var intersect = !!viewer.ifPointBlockedByIntersect(target, pano.id, true); //viewer.inputHandler.ifBlockedByIntersect({point:target, margin:0.1, cameraPos:pano}) if (intersect) { score = 0; } else { score = base * 2; } } else { score = base * 1.5; //没加载好的话,不管了 , 几乎当做无遮挡,否则容易到不了最近点 } return score; }); var g = Common.sortByScore(panos, require, rank); // console.log(g) /* let result1 = g && g.slice(0, 10) if(result1){ g = Common.sortByScore(result1, [], [(e)=>{//避免遮挡 let pano = e.item; let score = 0, log = '' if(atFloor && atFloor.panos.includes(pano)){//如果不在任何一楼呢? score += 600, log+='atFloor' } return {score, log} }]); if(g){ g.forEach(e=>{e.item = e.item.item}) } console.log(g) } */ var pano = g && g.length > 0 && g[0].item; if (pano && checkIntersect) { var intersect = !!viewer.ifPointBlockedByIntersect(target, pano.id, true); if (intersect) { return { pano, msg: 'sheltered' }; } } //if(getAll)return g; return pano; //注:深度图有的位置会不准确,以至于会算出错误的遮挡、选择错误的pano,解决办法只能是移动下热点到更好的位置 } //---------------scroll zoom ------------------------------------------ /* zoomIn = function() { //放大 this.zoomBy(1 + this.zoomSpeed); } zoomOut = function() {//缩小 this.zoomBy(1 - this.zoomSpeed); } */ zoomBy(e, pointer) { //以倍数 this.zoomTo(this.zoomLevel * e, pointer); } zoomTo(zoomLevel, pointer) { //缩放到某绝对zoomLevel var zoom = Potree.settings.zoom; if (zoom.enabled) { zoomLevel = MathUtils.clamp(zoomLevel, zoom.min, zoom.max); //console.log(zoomLevel) if (zoomLevel == this.zoomLevel) return; this.zoomLevel = zoomLevel; if (Potree.settings.panoZoomByPointer) { //定点缩放:使当前鼠标所在的位置缩放后不变 var view = viewer.scene.view; var originDir = viewer.scene.view.direction; var oldPointerDir = viewer.inputHandler.getMouseDirection(pointer).direction; viewer.setFOV(Potree.config.view.fov * (1 / this.zoomLevel)); var newPointerDir = viewer.inputHandler.getMouseDirection(pointer).direction; view.direction = oldPointerDir; //获取一下鼠标所在位置的yaw 和 pitch var oldPitch = view.pitch, oldYaw = view.yaw; view.direction = newPointerDir; var newPitch = view.pitch, newYaw = view.yaw; view.direction = originDir; //还原 viewer.scene.view.pitch -= newPitch - oldPitch; viewer.scene.view.yaw -= newYaw - oldYaw; } else { viewer.setFOV(Potree.config.view.fov * (1 / this.zoomLevel)); } } } zoomFovTo(fov) { //通过fov来算zoomLevel var zoomLevel = Potree.config.view.fov /* this.baseFov */ / fov; this.zoomTo(zoomLevel); } smoothZoomTo(aimLevel) { var dur = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var currentLevel = this.zoomLevel; if (currentLevel == aimLevel) return; var fun = progress => { //progress > 1 && (progress = 1) var level = currentLevel * (1 - progress) + aimLevel * progress; this.zoomTo(level, !0); }; transitions$1.start(fun, dur, null, null, 0, easing['easeInOutQuad']); } updateZoomPano() { if (!this.panoRenderer.zoomPanoRenderingDisabled && Potree.settings.displayMode == 'showPanos') { var currentPano = this.currentPano; if (currentPano) { var levelThreshold1 = Potree.settings.navTileClass == '1k' ? 1.3 : 1.7, levelThreshold2 = 2; var t = this.zoomLevel > levelThreshold1, n = !(this.flying && this.nextPano && this.nextPano !== this.currentPano), r = t && n; this.tileDownloader.tilePrioritizer.setZoomingActive(r); this.panoRenderer.setZoomingActive(r, currentPano, !0); var o = (pano, ifZoom) => { this.panoRenderer.resetRenderStatus(pano.id, !1, !0, this.qualityManager.getMaxNavPanoSize()); this.panoRenderer.clearAllQueuedUploadsForPano(pano.id); this.panoRenderer.renderPanoTiles(pano.id, null, !1, !1); pano.setZoomed(ifZoom); }; if (r && (!currentPano.zoomed || this.qualityManager.zoomLevelResolution && this.qualityManager.zoomLevelResolution != '4k')) { //needZoom currentPano.zoomed || o(currentPano, !0); if (Potree.settings.navTileClass == '1k' && Potree.settings.tileClass != '1k' && this.zoomLevel < levelThreshold2) { this.panoRenderer.enableHighQuality(function () { //开启2k if (Potree.settings.tileClass != '4k') o(currentPano, !0); }.bind(this)); } else { this.panoRenderer.enableUltraHighQualityMode(function () { //开启4k getMaxZoomPanoSize this.qualityManager.useUltraHighResolutionPanos && (Potree.settings.zoom.max = Potree.config.ultraHighQualityMaxZoom); o(currentPano, !0); }.bind(this)); } } else { !t && currentPano.zoomed && o(currentPano, !1); } if (r && Potree.settings.navTileClass == '1k' && Potree.settings.tileClass == '4k') { //目前只有手机端navTileClass == '1k' (分三个梯度) var change = zoomedFlag => { this.qualityManager.updateMaximums(); //更新maxZoomPanoSize this.panoRenderer.setupZoomRenderTarget(); //更新renderTarget //currentPano.setZoomed(t);//更新uniforms贴图 }; this.qualityManager.zoomLevelResolution = this.zoomLevel >= levelThreshold2 ? '4k' : this.zoomLevel > levelThreshold1 ? '2k' : '1k'; if (this.oldZoomLevel < levelThreshold2 && this.zoomLevel >= levelThreshold2) { //1k/2k-4k change(); o(currentPano, t); } else if (this.oldZoomLevel <= levelThreshold1 && this.zoomLevel > levelThreshold1) { //1k-2k change(); } else if (this.oldZoomLevel > levelThreshold2 && this.zoomLevel <= levelThreshold2) { //4k-2k/1k change(); o(currentPano, t); } else if (this.oldZoomLevel > levelThreshold1 && this.zoomLevel <= levelThreshold1) { //2k-1k change(); } this.oldZoomLevel = this.zoomLevel; } } } } //-------------------- addHighMapCube() { //创建8*8的tile cube 主要因手机版崩溃 要在电脑端测试得设置maxRenderTargetSize if (Potree.settings.tileClass == '4k' && this.qualityManager.maxRenderTargetSize == 2048) { var geo = new PlaneGeometry(1, 1, 1, 1); var cube = new Object3D(); cube.tiles = []; for (var cubeIndex = 0; cubeIndex < 6; cubeIndex++) { var face = new Object3D(); for (var i = 0; i < 8; i++) { for (var j = 0; j < 8; j++) { var tile = new Mesh(geo, new MeshBasicMaterial({ //side:THREE.DoubleSide transparent: true, opacity: 0.4, depthTest: false })); tile.position.set(i - 3.5, j - 3.5, -4); if (Potree.settings.isTest) { var colorHue = Math.random(); tile.material.color = new Color().setHSL(colorHue, 0.6, 0.7); /* tile.scoreLabel = new TextSprite( { backgroundColor: { r: 0, g: 0, b: 0, a: 0 }, textColor: { r: 0, g: 0, b: 0, a: 1 }, borderRadius: 15, renderOrder: 50, fontsize : 13, text: '' , dontFixOrient:true }) tile.scoreLabel.sprite.material.side = 2; tile.scoreLabel.rotation.x = Math.PI tile.add(tile.scoreLabel) */ } tile.visible = false; tile.tileX = i; tile.tileY = j; tile.cubeFace = cubeIndex; //tile.renderOrder = RenderOrder.highTileCube cube.tiles.push(tile); face.add(tile); } } switch (cubeIndex) { case GLCubeFaces$3.GL_TEXTURE_CUBE_MAP_POSITIVE_X: face.rotation.set(0, Math.PI / 2, 0); break; case GLCubeFaces$3.GL_TEXTURE_CUBE_MAP_NEGATIVE_X: face.rotation.set(0, -Math.PI / 2, 0); break; case GLCubeFaces$3.GL_TEXTURE_CUBE_MAP_POSITIVE_Y: var rot1 = new Quaternion().setFromAxisAngle(new Vector3(0, 1, 0), Math.PI); var rot2 = new Quaternion().setFromAxisAngle(new Vector3(1, 0, 0), Math.PI / 2); face.quaternion.copy(rot1).multiply(rot2); //face.rotation.set(Math.PI/2,0,0); break; case GLCubeFaces$3.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: //face.rotation.set(-Math.PI/2,0,0); var rot1 = new Quaternion().setFromAxisAngle(new Vector3(0, 1, 0), Math.PI); var rot2 = new Quaternion().setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2); face.quaternion.copy(rot1).multiply(rot2); break; case GLCubeFaces$3.GL_TEXTURE_CUBE_MAP_POSITIVE_Z: face.rotation.set(0, Math.PI, 0); break; case GLCubeFaces$3.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: face.rotation.set(0, 0, 0); } face.scale.set(1, -1, 1); face.cubeFace = cubeIndex; cube.add(face); } cube.name = 'highMapCube'; this.highMapCube = cube; viewer.scene.scene.add(cube); { var s = 0.1; cube.scale.set(s, s, s); } //注:由于原本的mesh上加了深度贴图,可能距离镜头比这里的近。凡是在cube以内的部分都会挡住cube导致模糊。但是应该不常见吧(另外到天空的边缘也是很近)。姑且depthTest=false this.highMapCube.visible = false; Potree.Utils.setObjectLayers(this.highMapCube, 'sceneObjects' /* 'skybox' */); //因它的深度是错误的,故不在skybox层渲染,影响edlRT, 而在renderOverlay时渲染覆盖。 //console.warn('addHighMapCube') viewer.addEventListener('update', () => { if (this.highMapCube.visibleTiles) { this.updateTiles(); //逐步将visibleTiles加载完 } }); viewer.addEventListener('camera_changed', e => { if (e.viewport == viewer.mainViewport) { //重新获取visibleTiles Common.intervalTool.isWaiting('update4kTiles', () => { var vectorForward = this.getDirection(); this.updateTiles(vectorForward); }, 500); } }); } } isHighMapLoaded(cubeFace, tileX, tileY) { var tile = this.highMapCube.children[cubeFace].children[tileX * 8 + tileY]; return !!tile.material.map; } updateTiles(direction) { if (!this.highMapCube || !this.highMapCube.visible) return; if (this.highMapCube.tiles.filter(e => e.image).length <= 10) return; //加载的太少了 //performance.mark('updateTiles-start') if (direction) { var camera = viewer.mainViewport.camera; var hfov = cameraLight.getHFOVForCamera(camera, true) / 2; var vfov = MathUtils.degToRad(camera.fov) / 2; /* let hcos = Math.cos(hfov / 2) let vcos = Math.cos(vfov / 2) */ var list = this.highMapCube.tiles; list.forEach(e => { //屏幕外的不显示 var pos = e.getWorldPosition(new Vector3()); var dir = new Vector3().subVectors(pos, this.highMapCube.position).normalize(); var hcos_ = dir.clone().setZ(direction.z).normalize().dot(direction); //在direction的斜面上水平角度差 var hRad = Math.acos(hcos_); var vRad = -200; if ( /* hRad > hfov + 0.08 */hRad / hfov > 1.5) { e.score = -100; } else { vRad = Math.abs(Math.acos(dir.z) - Math.acos(direction.z)); if ( /* vRad > vfov + 0.08 */vRad / vfov > 1.5) { e.score = -100; } else { e.score = -(hRad / hfov + vRad / vfov); } } e.scores = hRad.toFixed(3) + ', ' + vRad.toFixed(3); if (e.score == -100) { this.resetTile(e); } }); this.highMapCube.visibleTiles = list.filter(e => e.score > -100); //list.forEach(e=>e.scoreLabel.setText(e.scores)) } var needRecover = this.highMapCube.visibleTiles.filter(e => !e.material.map); if (needRecover.length) { var maxCount = Common.getBestCount('4kmaxTileRecover', 0, 2, 1.5, 6, false, 2); var count = 0; console.log(maxCount); needRecover.forEach((e, i) => { //只更新若干个,因为太耗时了, 其余的等下帧更新 if (count >= maxCount) return; var r = this.recoverTile(e); if (r) count++; }); } } getHighImage(image, cubeFace, tileX, tileY) { var tile = this.highMapCube.children[cubeFace].children[tileX * 8 + tileY]; tile.image = image; //先记录下来 } updateHighMap(image, cubeFace, tileX, tileY) { //console.warn('updateHighMap') var tile = this.highMapCube.children[cubeFace].children[tileX * 8 + tileY]; if (image) tile.image = image; //先记录下来 if (tile.material.map) return; if (this.highMapCube.visibleTiles && !this.highMapCube.visibleTiles.includes(tile) /* this.highMapCube.texLoadedCount >= this.getMaxTileCount() */) { return; } //简易创建贴图 /* var tex = this.$app.core.get('SceneRenderer').initSizedTexture2D(512, THREE.ClampToEdgeWrapping) //var loaded = this.$app.core.get('Player').model.isHighMapLoaded(tile.cubeFace, tile.tileX, tile.tileY) this.$app.core.get('SceneRenderer').uploadTexture2D(image, tex, 0, 0, 512, 512) //只替换tex对应的img,不新建 */ var tex = new Texture(); tex.image = image; tex.flipY = false; tex.wrapS = tex.wrapT = ClampToEdgeWrapping; tex.generateMipmaps = false; tex.minFilter = LinearFilter; tex.needsUpdate = true; tile.material.map = tex; tile.material.opacity = 1; tile.material.transparent = false; tile.visible = true; tile.material.needsUpdate = true; //发现每次开始放大但还未放大到4k时也会把之前加载过的4k加载 } recoverTile(tile) { if (tile.material.map) return; if (tile.image) { this.updateHighMap(tile.image, tile.cubeFace, tile.tileX, tile.tileY); return true; } else { //console.log('no image') } } resetTile(tile, kill) { if (kill) { //完全消灭 tile.image = null; } var map = tile.material.map; if (map) { map.dispose(); //这句执行了以后,h.__webglTexture一直就是undefined map.loaded = !1; map.version = 0; //保底再执行一下这个,类似app.sceneRenderer.deallocateCubeTexture(tile.material.map) var h = viewer.renderer.properties.get(map); //console.log('__webglTexture',!!h.__webglTexture) viewer.renderer.getContext().deleteTexture(h.__webglTexture); tile.material.map = null; tile.material.needsUpdate = true; tile.visible = false; //this.highMapCube.texLoadedCount -- //console.log('resetTile'/* , tile.cubeFace, tile.tileX, tile.tileY */) } } resetHighMap() { if (!this.highMapCube) return; this.highMapCube.children.forEach(e => e.children.forEach(tile => { this.resetTile(tile, true); })); //this.highMapCube.texLoadedCount = 0 this.highMapCube.visibleTiles = null; this.hideHighMap(); //console.log('resetHighMap') } setHighMap(pano) { if (!this.highMapCube) return; this.highMapCube.position.copy(pano.position); //可以利用第0个pano查看,其 rotation4dkk是(_x: 0, _y: -1.5707963267948966, _z: 0 )而手动旋转至(_x:1.5707963, _y: -1.57079, _z: 0)时才正确,说明要在4dkk的旋转基础上,绕x轴转90度,(也就是转成navvis坐标系), 然后得到YupToZup的函数写法的 this.highMapCube.quaternion.copy(math.convertQuaternion.YupToZup(pano.quaternion4dkk)); //乘上数据集整体的旋转: var modelRotQua = new Quaternion().setFromRotationMatrix(pano.pointcloud.rotateMatrix); this.highMapCube.quaternion.premultiply(modelRotQua); } showHighMap() { if (!this.highMapCube) return; //console.warn('showHighMap') this.highMapCube.visible = true; } hideHighMap() { if (!this.highMapCube) return; //console.warn('hideHighMap') this.highMapCube.visible = false; } //缩小后继续显示cube呢还是不显示? 不显示的话,就要把cube上的复制到renderTarget上……会不会又崩溃,or没加载的显示??? addPanoData(data, pointcloud) { //加载漫游点 //data[0].file_id = '00019' if (data.data) data = data.data; //if(data.length == 0)console.error(pointcloud.dataset_id + ' 没有漫游点') //data = data.sort(function(a,b){return a.id-b.id}) data.forEach(info => { //if(Potree.fileServer){ info.id = this.panos.length; //把info的id的一长串数字改简单点 info.pointcloud = pointcloud; //} var pano = new Panorama(info, this); pano.addEventListener('dispose', e => { if (this.closestPano == pano) this.closestPano = null; }); this.panos.push(pano); this.neighbourMap[info.id] = {}; pano.label && Potree.Utils.setObjectLayers(pano.label, 'bothMapAndScene'); pano.label2 && Potree.Utils.setObjectLayers(pano.label2, 'bothMapAndScene'); if (Potree.settings.editType == 'pano') { Potree.settings.datasetsPanos[pointcloud.dataset_id].panos.push(pano); } }); } loadDone() { Potree.Utils.setObjectLayers(this.node, 'sceneObjects'); this.tileDownloader.setPanoData(this.panos, []); { var minSize = new Vector3(1, 1, 1); this.bound = math.getBoundByPoints(this.panos.map(e => e.position), minSize); viewer.scene.pointclouds.forEach(pointcloud => pointcloud.getPanosBound()); } if (viewer.scene.pointclouds.some(e => e.panos.length == 0)) { //console.warn('存在数据集没有pano'); viewer.hasNoPanoDataset = true; } } getPano(value) { var typeName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'id'; //默认找的是id,也可以是sid、uuid return this.panos.find(p => p[typeName] == value); } } ; //判断当前点是否加载了全景图 Images360.prototype.checkAndWaitForPanoLoad = function () { var isLoadedPanos = {}, LoadedTimePanos = {}, loadedCallback = {}, //add maxTime = 5e3; var withinTime = function withinTime() { for (var panoId in isLoadedPanos) if (isLoadedPanos.hasOwnProperty(panoId) && isLoadedPanos[panoId]) { var differTime = performance.now() - LoadedTimePanos[panoId]; if (differTime < maxTime) return !0; } return !1; }; return function (pano, basePanoSize, doneFun1, doneFun2, progressCallback, iswait, isclear, p) { loadedCallback[pano.id] = doneFun1; //add 因为有可能之前请求的没加doneFun1, 如果加载好就执行最新的doneFun1 if (withinTime()) { //距离上次请求时间很近 //console.log(11) return !0; //这里感觉应该是!1 } var changeMode = e => { if (e.mode == 'showPointCloud') { console.warn('切到点云模式了,就删除loadedCallback记录', pano.id); //否则再次转为showPanos会被withinTime阻拦 delete isLoadedPanos[pano.id]; viewer.cancelLoad(pano); loadedCallback[pano.id] && loadedCallback[pano.id](); //可以飞行了 doneFun2 && doneFun2(); this.removeEventListener('requestMode', changeMode); } }; this.addEventListener('requestMode', changeMode); var callback1 = (param1, param2) => { setTimeout(() => { isLoadedPanos[pano.id] = !1; loadedCallback[pano.id] && loadedCallback[pano.id](param1, param2); this.removeEventListener('requestMode', changeMode); }, 1); }; var callback2 = param => { //没有看到有传doneFun2的 setTimeout(() => { isLoadedPanos[pano.id] = !1; doneFun2 && doneFun2(param); }, 1); }; try { null !== iswait && void 0 !== iswait || (iswait = !0); isLoadedPanos[pano.id] = this.checkAndWaitForTiledPanoLoad(pano, basePanoSize, callback1, callback2, progressCallback, iswait, isclear, p); //true代表没加载好 isLoadedPanos[pano.id] && (LoadedTimePanos[pano.id] = performance.now()); return isLoadedPanos[pano.id]; } catch (msg) { isLoadedPanos[pano.id] = !1; LoadedTimePanos[pano.id] = performance.now() - maxTime; throw msg; } }; }(); //加载全景图的流程:请求下载当前点的最低分辨率图(不过有可能已经下载了),并且请求uploadTile渲染当前漫游点,若tile都upload完(先6个)会发送消息,LoadComplete 从而回调成功。 Images360.prototype.getNeighbours = function () { //逐渐自动获取neighbours。 200个点差不多在半分钟内算完 var lastIndex, inited; //标记上次查询到哪,防止重新sortByScore return function (interacted) { if (!this.currentPano || viewer.mainViewport.view.isFlying() || viewer.lastFrameChanged || viewer.inputHandler.drag /* interacted */) { //拖拽时不更新,否则移动端卡 return lastIndex = 0; } var nearPanos = this.tileDownloader.tilePrioritizer.nearPanos; if (!nearPanos) return; //let startTime = Date.now() var panos = [this.currentPano, ...nearPanos]; this.depthSampler.updateNearPanos(panos); var maxWaitDur = browser.isMobile() ? 40 : 60; var changeCount = 0, maxChangeTex = browser.isMobile() ? 1 : 3, getCount = 0; var changeTexCount = () => { changeCount++; }; var median = Potree.timeCollect.depthSamChangeImg.median; var ifOverTime = () => { var is = changeCount >= maxChangeTex || changeCount * median + getCount * 0.01 > maxWaitDur; //不换贴图也要一丢丢计算时间 /* if(is){ console.log('OverTime, changeCount', changeCount) } */ return is; }; this.depthSampler.addEventListener('changeImg', changeTexCount); outer: for (var i = lastIndex, j = panos.length; i < j; i++) { var pano = panos[i]; var others = panos.slice(i + 1, j); lastIndex = i; if (!pano.pointcloud.hasDepthTex && i > 0) break; //点云的情况下最好不改相机位置,因为其他位置点云还没加载完,所以不判断当前点以外的漫游点 var g = Common.sortByScore(others, [], [Images360.scoreFunctions.distanceSquared(pano.position)]); for (var a = 0, b = g.length; a < b; a++) { var item = g[a]; if (item.item == pano) continue; if (this.neighbourMap[pano.id][item.item.id] != void 0 && this.neighbourMap[item.item.id][pano.id] != void 0 /* this.isNeighbour(pano,item.item,{dontCompute:true}) != void 0 */) continue; //确定结果了就不需要算 //console.log('check isNeighbour', pano.id, item.item.id) var byCloud = !pano.pointcloud.hasDepthTex; var result = this.isNeighbour(pano, item.item, { onlyUseTex: !byCloud, computeDirFirst: true, computeTwoDir: true }); //计算 if (result != void 0) { //计算了 (byTex时其实并不一定) //console.log('提前计算neighbor', pano.id, item.item.id) this.dispatchEvent({ type: 'getNeighbourAuto', panos: [pano, item.item] }); if (byCloud) { //只计算一次 //console.log('提前计算neighbor byCloud', result, pano.id, item.item.id) break outer; } getCount++; if (ifOverTime()) { break outer; } } } lastIndex = i + 1; //这轮结束 } /* if(changeCount){ console.log( 'changeCount', changeCount) } */ this.depthSampler.removeEventListener('changeImg', changeTexCount); if (!inited) { inited = true; this.addEventListener('loadedDepthImg', e => { //console.log('loadedDepthImg',e.pano) lastIndex = 0; //主要针对刚打开场景第一个点有杂点时单向不成功,要立即进一步双向计算ifShelter }); } /* let costTime = Date.now() - startTime costTime > maxWaitDur && console.log( 'costTime:',costTime) */ }; }(); Images360.filters = { inPanoDirection: function inPanoDirection(pos, dir, i, log) { //pano在mouse的方向上 return function (pano) { var r = pano.floorPosition.clone().sub(pos).normalize(); var o = pano.position.clone().sub(pos).normalize(); log && console.log('dire', pano.id, r.dot(dir), o.dot(dir)); return r.dot(dir) > i || o.dot(dir) > i; }; }, inFloorDirection: function inFloorDirection(pos, dir, min, log) { //pano在mouse的水平方向上 return function (pano) { var vec = new Vector2().subVectors(pano.floorPosition, pos).normalize(); var dir_ = new Vector2().copy(dir).normalize(); log && console.log('dire', pano.id, vec.dot(dir_)); return vec.dot(dir_) > min; /* var i = pano.floorPosition.clone().sub(pos).setZ(0).normalize();//改成在xz方向上,否则点击墙面不会移动 return i.dot(dir.clone().setZ(0)) > min */ }; }, isNotBehindNormal: function isNotBehindNormal(e, t) { var i = new Vector3(); return t = t.clone(), function (n) { var r = i.copy(n.position).sub(e).normalize(); return r.dot(t) > 0; }; }, isCloseEnoughTo: function isCloseEnoughTo(e, t) { return function (i) { //因为marker可能比地面高,所以识别范围要比marker看起来更近一些。(因为投影到地板的位置比marker更近) return e.distanceTo(i.floorPosition) < t; //许钟文 }; }, not: function not(e) { return function (t) { return t !== e; }; }, isEnabled: function isEnabled() { return function (t) { return t.enabled; }; }, isVisible: function isVisible() { return function (t) { return t.visible; }; } }; Images360.scoreFunctions = { direction: function direction(curPos, dir, ifLog) { return function (pano) { var pos1 = /* pano.floorPosition */pano.position; //旧:改为权重放在marker上,这样对有斜坡的更准确,如上楼, 但这样近距离的pano角度就会向下了,以致于走不到 var n = pos1.clone().sub(curPos).normalize(); //ifLog && console.log('direction', pano.id, n.dot(dir) * directionFactor ) return n.dot(dir) * directionFactor; }; }, distance: function distance(pos1) { var r = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var ifLog = arguments.length > 2 ? arguments[2] : undefined; if (pos1.position) pos1 = pos1.position; return function (pano) { //许钟文 改 var pos2 = pano.position.clone(); //ifLog && console.log('distance', pano.id, pos1.distance(pos2) * -1 ) return pos1.distanceTo(pos2) * -1 * r; }; }, distanceSquared: function distanceSquared(pos1) { var r = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; if (pos1.position) pos1 = pos1.position; return function (pano) { //许钟文 改 var pos2 = pano.position.clone(); return pos1.distanceToSquared(pos2) * -1 * r; }; }, angle: function angle(e, t) { return function (i) { var n = i.position.clone().sub(e).normalize(); return n.angleTo(t) * Potree.config.navigation.angleFactor; }; } }; Images360.sortFunctions = { //排序函数,涉及到两个item相减 floorDisSquaredToPoint: function floorDisSquaredToPoint(e) { return function (t, i) { return t.floorPosition.distanceToSquared(e) - i.floorPosition.distanceToSquared(e); }; }, disSquaredToPoint: function disSquaredToPoint(e) { return function (t, i) { return t.position.distanceToSquared(e) - i.position.distanceToSquared(e); }; } }; Images360.prototype.updateCube = function () { //增加细分的版本,且垂直方向上取中位数 侧边多条 var minDis = 0.2; //pano和墙距离不能小于相机的near var height = 1; //准确计算的话要分别计算两个pano的地面、天花板之间的俯仰角,和pano之间的还不一样。这里统一假设一个比较小的高度,因高度越大 maxSinAlpha 越大 var minTanBeta = minDis / height; /* (pano0.position.z - pano0.floorPosition.z) */ var minBeta = Math.atan(minTanBeta); var maxSinAlpha = Math.cos(minBeta); // 注:beta = Math/2 - alpha var skyHeight = 50; return function (pano0, pano1) { if (Potree.settings.displayMode != 'showPanos' || pano0 == pano1 || this.cubePanos.some(e => e.pano == pano0 && e.matrix.equals(pano0.pointcloud.matrix)) && (!pano1 || this.cubePanos.some(e => e.pano == pano1 && e.matrix.equals(pano1.pointcloud.matrix)))) return; this.cubePanos = [{ pano: pano0, matrix: pano0.pointcloud.matrix.clone() }, { pano: pano1, matrix: pano1 && pano1.pointcloud.matrix.clone() }]; viewer.addTimeMark('updateCube', 'start'); //console.log('updateCube',pano0.id, pano1&&pano1.id) var useBound = (bound, size) => { size = size || bound.getSize(new Vector3()); var center = bound.getCenter(new Vector3()); size.max(new Vector3(HighMapCubeWidth, HighMapCubeWidth, HighMapCubeWidth)); this.cube.geometry = new BoxBufferGeometry(1, 1, 1, 1); this.cube.scale.copy(size); this.cube.position.copy(center); if (Potree.settings.testCube) { this.cubeTest.geometry = this.cube.geometry; this.cubeTest.scale.copy(size); this.cubeTest.position.copy(center); } return 'useBound'; }; var getPanoBound = (pano, dis) => { //因漫游点可能在点云外部,如室外平地,所以需要union进漫游点 var panoBound = new Box3(); panoBound.expandByPoint(pano.position); var margin = dis ? Math.max(dis * 0.1, 10) : 10; panoBound.expandByVector(new Vector3(margin, margin, margin)); //give pano a margin 。 随着bound扩大,margin要相应扩大,否则当距离很远时看起来就像没有 return pano.pointcloud.bound.clone().union(panoBound); }; this.cube.geometry.dispose(); if (pano1) { //过渡 var dontAddSides; var dis = pano0.position.distanceTo(pano1.position); if (dis == 0) return; var sinAlpha = Math.abs(pano0.position.z - pano1.position.z) / dis; //俯仰角的sin,随角度增大而增大 0-1 var score = (1 + sinAlpha * 20) * dis; //score越大创建的mesh越不适合 var isNeighbour = this.isNeighbour(pano0, pano1); //console.log(pano0.id, pano1.id, maxSinAlpha.toFixed(2), sinAlpha.toFixed(2), score.toFixed(2), isNeighbour) if (sinAlpha > maxSinAlpha || !pano0.pointcloud.hasDepthTex || !pano1.pointcloud.hasDepthTex || (isNeighbour ? score > 100 : score > 50)) { var bound = getPanoBound(pano0, dis).union(getPanoBound(pano1, dis)); var size = bound.getSize(new Vector3()); var max = Math.max(size.x, size.y, size.z); size.set(max, max, max); //距离太远的数据集,过渡会畸变。所以扩大skybox,且为立方体 return useBound(bound, size); } else if (isNeighbour ? score > 70 : score > 15) { dontAddSides = true; //pano间有阻挡时得到的side点可能使通道变窄,所以去掉。 } //俯仰角增大时可能不在同一楼层,算出来的mesh不太好,所以更倾向直接使用cube,或去除side。 var half = browser.isMobile() ? 4 : 8; //自行输入 (点云计算的慢,还不准) var count1 = 2 * half; //偶数个 每个pano向 外dir 个数 //奇数个的好处:在窄空间内能探测到最远距离,坏处是前方有尖角。偶数个的坏处就是可能检测距离太近。 var getDir = (angle_, vec) => { //旋转获得水平向量 var rotMat = new Matrix4().makeRotationZ(angle_); return vec.clone().applyMatrix4(rotMat); }; var getFar = (dir, pano, origin, height) => { //获取在这个方向上和墙体intersect的距离 //在垂直方向上分出多个方向,取一个最可能的接近真实的距离 var maxH = 40, minH = 2, minR = 0.5, maxR = 2; height = height == void 0 ? Math.min(skyHeight, pano.ceilZ - pano.floorPosition.z) : height; //let r = height (maxH - minH)* 0.14 // 高度越小,角度越小 //let r = minR + ( maxR - minR) * THREE.Math.clamp((height - minH) / (maxH - minH),0,1) //THREE.Math.smoothstep(currentDis, op.nearBound, op.farBound); var r = math.linearClamp(height, [minH, maxH], [minR, maxR]); var getZ = deg => { deg *= r; deg = MathUtils.clamp(deg, 1, 80); return Math.tan(MathUtils.degToRad(deg)); }; var dirs_; //注意:角度太大会碰到天花板或地板,越远越容易碰到, 在地下停车场就会伸展不开。 更多取接近0度的,否则围墙矮一点就会取到远处。 dirs_ = [15, 8, 3, -1, -5]; dirs_ = dirs_.map(deg => dir.clone().setZ(getZ(deg)).normalize()); var max = 50; var count2 = dirs_.length; var disArr = dirs_.map((dir_, i) => { var intersect = this.getIntersect(pano, dir_, origin); var projectLen = intersect && intersect.distance ? dir_.dot(dir) * intersect.distance : max; //得到project在dir的长度 return projectLen; //得水平距离 }); //console.log(pano ? pano.id : 'side','disArr', disArr.slice(0)) disArr.sort((a, b) => { return b - a; }); //从大到小 //console.log(pano ? pano.id : 'side','disArr', disArr) var dis = disArr[Math.floor(count2 / 2 - 0.5)]; //对半、取前(中位数) return dis; }; var sideCount = [0, 0]; var addPos = (pano, vec) => { //添加这个pano这一侧向外半圆的顶点 //添加pano位置对应的最高点最低点: var minZ, maxZ; minZ = pano.floorPosition.z; maxZ = pano.getCeilHeight(); if (maxZ == Infinity) maxZ = skyHeight + pano.position.z; //maxZ = Math.max(skyHeight, maxZ) [maxZ, minZ].forEach(z => { posArr.push(pano.position.clone().setZ(z)); }); //在画面上线条从左往右数 var angle = Math.PI / (count1 - 1); var dirs = []; //平分这半边180度 for (var i = 0; i < count1; i++) { dirs.push(getDir(Math.PI / 2 - i * angle, vec)); //正的在左边 } var dirs2 = dirs.map(dir => { return { dir, dis: getFar(dir, pano) }; }); //剔除那些突然间离相机很近的dir。有可能是拍摄的人、或者杆子、树 /* dirs2.forEach((e,i)=>{ console.log(i, e.dis) let smallThanBefore = ()=>{ return dirs2[i-1].dis / e.dis > maxRatio } let smallThanAfter = ()=>{ return dirs2[i+1].dis / e.dis > maxRatio } if(i>0 && i { start += 1; //不包含start和end var count = end - start; var dis = 0; for (var m = start; m < end; m++) { //得平均数 dis += dirs2[m].dis; } dis /= count; var angle = Math.PI / (count1 - 1) * count / 2; var width = dis * Math.tan(angle); //得到block的半宽度 return width; }; var changeDis = (start, end) => { //不包含start start += 1; //不包含start和end for (var m = start; m < end; m++) { dirs2[m].disB = dirs2[end].dis * 0.8; //console.log('changeDis', m, dirs2[m].disB) } }; var start = -1; for (var _i = 0; _i < count1; _i++) { //遍历时将左边dis比之小很多且宽度较小的改大 //console.log(i, dirs2[i].dis) var j = _i - 1; var ratios = 0; while (j > start && dirs2[_i].dis / dirs2[j].dis > maxRatio1) { ratios += dirs2[_i].dis / dirs2[j].dis; j--; } var count = _i - j - 1; ratios /= count; if (count > 0 && computeWidth(j, _i) < minWidth * ratios / maxRatio2) { //怎么感觉好像改成了视觉宽度小于某个值即可,那直接用count好了? changeDis(j, _i); start = _i; //在此之前的修改过,之后不用再判断 } /* if(count > 0 && (count == 1 || computeWidth(j,i) { var dir = e.dir.clone().multiplyScalar(e.disB || e.dis); [maxZ, minZ].forEach(z => { posArr.push(pano.position.clone().setZ(z).add(dir)); //获取到外墙点 }); }); }; var addSide = () => { //两个漫游点间两边各加一些侧线 //中点处的 var top0 = pano0.ceilZ == Infinity ? pano0.position.z + skyHeight : pano0.ceilZ; var top1 = pano1.ceilZ == Infinity ? pano1.position.z + skyHeight : pano1.ceilZ; var midMaxZ = (top0 + top1) / 2; var midMinZ = (pano0.floorPosition.z + pano1.floorPosition.z) / 2; var mid = new Vector3().addVectors(pano0.position, pano1.position).multiplyScalar(0.5); if (!dontAddSides) { if (pano0.pointcloud.hasDepthTex && pano0.pointcloud.hasDepthTex) { var panos = [pano0, pano1]; var vecs = [vec.clone().negate(), vec]; var axis = [[-1, 1], [1, -1]]; var dis2d = new Vector2().subVectors(pano0.position, pano1.position).length(); //水平上的距离 var maxDis = 50, _minDis = 0.5, minR = 0.2, maxR = 1.2; //let r = maxR - ( maxR - minR) * THREE.Math.clamp((dis2d - minDis) / (maxDis - minDis),0,1) //dis2d越大,角度要越小 //THREE.Math.smoothstep(currentDis, op.nearBound, op.farBound); var r = math.linearClamp(dis2d, [_minDis, maxDis], [maxR, minR]); //console.log('dis2d',dis2d,'r',r) var angles = (browser.isMobile() /* || dis2d<4 */ ? [60] : [50, 70] /* [35,65] */).map(deg => { //正的在左边 尽量能够平分中间这段墙体。 (角度为从中心向外) var angle = MathUtils.clamp(deg * r, 5, 80); //console.log('angle',angle) return MathUtils.degToRad(angle); }); axis.forEach((axis_, index0) => { var disToSides = []; var accordingPano = index0 == 0 ? pano0 : pano1; //根据离该点在vec方向上的距离顺序来存顶点 panos.forEach((pano, index) => { var dirs = angles.map(angle => getDir(axis_[index] * angle, vecs[index])); //一侧的若干角度 dirs.forEach((dir_, i) => { var dis1 = getFar(dir_, pano); var disToPano2d = dis1 * Math.cos(angles[i]); if (disToPano2d < dis2d) { //超过的话都到另一半pano的半圆了,不计入。(角度越小越容易超过) var disToSide = dis1 * Math.sin(angles[i]); if (pano != accordingPano) { disToPano2d = dis2d - disToPano2d; //反一下 } dir_.multiplyScalar(dis1); disToSides.push({ disToSide, disToPano2d, pano, dir_ }); } else { //console.log('超过',index0,index,i) } }); }); if (disToSides.length) { //disToSides.sort((a,b)=>{return b-a});//从大到小 //由距离accordingPano的近到远: disToSides.sort((a, b) => { return a.disToPano2d - b.disToPano2d; }); //console.log('disToSides', index0, disToSides) if (disToSides.length == 1 && disToSides[0].disToSide < 0.5) { disToSides = []; //如果太近直接去除 } disToSides.forEach(e => { //求z var ratio = e.disToPano2d / dis2d; var r = accordingPano == pano0 ? 1 - ratio : ratio; var sideMaxZ_ = top0 * r + top1 * (1 - r); var sideMinZ_ = pano0.floorPosition.z * r + pano1.floorPosition.z * (1 - r); [sideMaxZ_, sideMinZ_].forEach(z => { posArr.push(e.pano.position.clone().setZ(z).add(e.dir_)); //是直接使用最长dis的那个intersect点好还是mid }); }); } sideCount[index0] = disToSides.length; //记录侧边个数 }); } else { //这段针对点云时,仅测试才会执行到 sideCount = [1, 1]; var sideDirs = [getDir(Math.PI / 2, vec), getDir(-Math.PI / 2, vec)]; sideDirs.forEach((dir_, index) => { var dis = getFar(dir_, null, mid, midMaxZ - midMinZ); //直接从中点求两侧的距离 dir_.multiplyScalar( /* Math.max( */dis /* , sideDis[index]) */); [midMaxZ, midMinZ].forEach(z => { posArr.push(mid.clone().setZ(z).add(dir_)); }); }); } } //中心: [midMaxZ, midMinZ].forEach(z => { posArr.push(mid.clone().setZ(z)); }); }; //positions存放顺序:pano的每边的 zMax和zMin 、count1个dir的点 ;侧边的点 ;连接处顶底的中点 var addFaces = () => { var getPI = function getPI(index, posType, panoIndex) { //获取顶点序号 return 2 + (count1 * 2 + 2) * panoIndex + index * 2 + (posType == 'top' ? 0 : 1); }; var getSidePI = function getSidePI(index, posType, panoIndex) { //获取侧边顶点序号 if (panoIndex == 1) index += sideCount[0]; return getPI(index, posType, 2) - 2; }; var getPanoPI = function getPanoPI(posType, panoIndex) { //获取pano处对应的点序号 return getPI(-1, posType, panoIndex); }; var topCenter = posArr.length - 2; //最后添加的两个中心点 var btmCenter = posArr.length - 1; for (var i = 0; i < 2; i++) { for (var index = 1; index < count1; index++) { //pano外侧半圆围墙 faceArr.push([getPI(index, 'top', i), getPI(index - 1, 'btm', i), getPI(index - 1, 'top', i)], //加入一块四方面 [getPI(index, 'top', i), getPI(index, 'btm', i), getPI(index - 1, 'btm', i)]); faceArr.push([getPI(index, 'top', i), getPI(index - 1, 'top', i), getPanoPI('top', i)]); //天花板扇形 faceArr.push([getPI(index, 'btm', i), getPI(index - 1, 'btm', i), getPanoPI('btm', i)]); //地板扇形 } var j = (i + 1) % 2; //另一个pano //侧边 for (var u = 0; u <= sideCount[i]; u++) { //侧边每个四方的左上右上左下右下四个点 var pLT = u == 0 ? getPI(0, 'top', i) : getSidePI(u - 1, 'top', i); var pRT = u == sideCount[i] ? getPI(count1 - 1, 'top', j) : getSidePI(u, 'top', i); var pLB = u == 0 ? getPI(0, 'btm', i) : getSidePI(u - 1, 'btm', i); var pRB = u == sideCount[i] ? getPI(count1 - 1, 'btm', j) : getSidePI(u, 'btm', i); faceArr.push([pLT, pLB, pRB], [pLT, pRB, pRT]); //外侧四方面 faceArr.push([pLT, topCenter, pRT], [pLB, btmCenter, pRB]); //顶部和底部到整体中心的扇形(由于点的顺序是根据和两个pano的距离,因此到中心的夹角并没按顺序排列,所以可能会重叠) if (i == 0) { //只需要算一次 //顶部和底部中心与两个pano边构成的三角形 if (u == 0) { faceArr.push([pLT, getPI(count1 - 1, 'top', i), topCenter], [pLB, getPI(count1 - 1, 'btm', i), btmCenter]); } //不能用else 因为当length==0时u==0也==sideCount[i],此时就是要两个面 if (u == sideCount[i]) { faceArr.push([pRT, getPI(0, 'top', j), topCenter], [pRB, getPI(0, 'btm', j), btmCenter]); } } } } }; var posArr = []; var faceArr = []; //两点连线的水平向量 var vec = new Vector3().subVectors(pano0.position, pano1.position).setZ(0).normalize(); /* let sideDis0 = */ addPos(pano0, vec); /* let sideDis1 = */ addPos(pano1, vec.clone().negate()); addSide(); addFaces(); //MeshDraw.updateGeometry(this.cube.geometry, posArr, faceArr) var geo = MeshDraw.createGeometry(posArr, faceArr); this.cube.geometry = geo; this.cube.scale.set(1, 1, 1); this.cube.position.set(0, 0, 0); if (Potree.settings.testCube) { this.cubeTest.geometry = geo; this.cubeTest.scale.set(1, 1, 1); this.cubeTest.position.set(0, 0, 0); } } else { useBound(getPanoBound(pano0)); } viewer.addTimeMark('updateCube', 'end'); return true; /* 关于卡顿: 即使使用cube,若scale设置为只容纳两个pano,也会卡顿。但也是有的卡有的不卡。 若按照原先的复杂geo,一般在平直的街道上行走流畅,经过拐弯或者复杂区域较卡。减小geo复杂度没有什么作用。 注: 修改skybox,若不准的话,会遮住其他mesh,比如marker。尤其在没有深度贴图时。 耗时: chrome: 20+ ,但是firefox:500+ 咋回事 ? iphonex safari: 40+ */ }; }(); /* viewer.images360.flyToPano(viewer.images360.getPano('1765955963253690368|70','sid')) viewer.images360.flyToPano(viewer.images360.lastPano) */ /** * @author alteredq / http://alteredqualia.com/ * * Full-screen textured quad shader */ var CopyShader = { uniforms: { "tDiffuse": { value: null }, "opacity": { value: 1.0 } }, vertexShader: ["varying vec2 vUv;", "void main() {", "vUv = uv;", "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", "}"].join("\n"), fragmentShader: ["uniform float opacity;", "uniform sampler2D tDiffuse;", "varying vec2 vUv;", "void main() {", "vec4 texel = texture2D( tDiffuse, vUv );", //如果开启premultipliedAlpha用这个,否则用注释的 "gl_FragColor = opacity * texel;", //"gl_FragColor = texture2D( tDiffuse, vUv );", //"gl_FragColor.a *= opacity;", "}"].join("\n") }; /** * @author alteredq / http://alteredqualia.com/ */ var Pass = function Pass() { // if set to true, the pass is processed by the composer this.enabled = true; // if set to true, the pass indicates to swap read and write buffer after rendering this.needsSwap = true; // if set to true, the pass clears its buffer before rendering this.clear = false; // if set to true, the result of the pass is rendered to screen this.renderToScreen = false; }; Object.assign(Pass.prototype, { setSize: function setSize(width, height) {}, render: function render(renderer, writeBuffer, readBuffer, delta, maskActive) { console.error('THREE.Pass: .render() must be implemented in derived pass.'); } }); var ShaderPass = function ShaderPass(shader, textureID) { Pass.call(this); this.textureID = textureID !== undefined ? textureID : "tDiffuse"; if (shader instanceof ShaderMaterial) { this.uniforms = shader.uniforms; this.material = shader; } else if (shader) { this.uniforms = UniformsUtils.clone(shader.uniforms); this.material = new ShaderMaterial({ defines: Object.assign({}, shader.defines), uniforms: this.uniforms, vertexShader: shader.vertexShader, fragmentShader: shader.fragmentShader, transparent: true //add }); } this.camera = new OrthographicCamera(-1, 1, 1, -1, 0, 1); this.scene = new Scene(); this.quad = new Mesh(new PlaneBufferGeometry(2, 2), null); this.quad.frustumCulled = false; // Avoid getting clipped this.scene.add(this.quad); }; ShaderPass.prototype = Object.assign(Object.create(Pass.prototype), { constructor: ShaderPass, render: function render(scene, camera, viewports, renderer, writeBuffer, readBuffer, delta, maskActive) { var oldTarget = renderer.getRenderTarget(); /* if(this.readTarget){ //add readBuffer = oldTarget } */ if (this.uniforms[this.textureID]) { this.uniforms[this.textureID].value = readBuffer.texture; } this.quad.material = this.material; if (this.renderToScreen) { renderer.render(this.scene, this.camera); } else { renderer.setRenderTarget(writeBuffer); if (this.clear) renderer.clear(); renderer.render(this.scene, this.camera); renderer.setRenderTarget(oldTarget); } } }); // Copied from three.js: WebGLRenderer.js function paramThreeToGL$1(_gl, 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$1) 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$1) 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; } ; var attributeLocations$1 = { "position": { name: "position", location: 0 }, "color": { name: "color", location: 1 }, "rgba": { name: "color", location: 1 }, "intensity": { name: "intensity", location: 2 }, "classification": { name: "classification", location: 3 }, "returnNumber": { name: "returnNumber", location: 4 }, "return number": { name: "returnNumber", location: 4 }, "returns": { name: "returnNumber", location: 4 }, "numberOfReturns": { name: "numberOfReturns", location: 5 }, "number of returns": { name: "numberOfReturns", location: 5 }, "pointSourceID": { name: "pointSourceID", location: 6 }, "source id": { name: "pointSourceID", location: 6 }, "point source id": { name: "pointSourceID", location: 6 }, "indices": { name: "indices", location: 7 }, "normal": { name: "normal", location: 8 }, "spacing": { name: "spacing", location: 9 }, "gps-time": { name: "gpsTime", location: 10 }, "aExtra": { name: "aExtra", location: 11 } }; class Shader$1 { constructor(gl, name, vsSource, fsSource) { this.gl = gl; this.name = name; this.vsSource = vsSource; this.fsSource = fsSource; this.cache = new Map(); this.vs = null; this.fs = null; this.program = null; this.uniformLocations = {}; this.attributeLocations = {}; this.uniformBlockIndices = {}; this.uniformBlocks = {}; this.uniforms = {}; this.update(vsSource, fsSource); } update(vsSource, fsSource) { this.vsSource = vsSource; this.fsSource = fsSource; this.linkProgram(); } compileShader(shader, source) { var gl = this.gl; gl.shaderSource(shader, source); gl.compileShader(shader); var success = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (!success) { var info = gl.getShaderInfoLog(shader); var numberedSource = source.split("\n").map((a, i) => "".concat(i + 1).padEnd(5) + a).join("\n"); throw "could not compile shader ".concat(this.name, ": ").concat(info, ", \n").concat(numberedSource); } } linkProgram() { var tStart = performance.now(); var gl = this.gl; this.uniformLocations = {}; this.attributeLocations = {}; this.uniforms = {}; gl.useProgram(null); var cached = this.cache.get("".concat(this.vsSource, ", ").concat(this.fsSource)); if (cached) { this.program = cached.program; this.vs = cached.vs; this.fs = cached.fs; this.attributeLocations = cached.attributeLocations; this.uniformLocations = cached.uniformLocations; this.uniformBlocks = cached.uniformBlocks; this.uniforms = cached.uniforms; return; } else { this.vs = gl.createShader(gl.VERTEX_SHADER); this.fs = gl.createShader(gl.FRAGMENT_SHADER); this.program = gl.createProgram(); if (!gl.isProgram(this.program)) { //创建失败 开启多个页面可能会,原因是webglcontextlost //console.error('创建program失败'); viewer.dispatchEvent('webglError', { msg: 'potreeRenderer创建program失败' }); console.log(this.vs); console.log(this.fs); return; } for (var name of Object.keys(attributeLocations$1)) { var location = attributeLocations$1[name].location; var glslName = attributeLocations$1[name].name; gl.bindAttribLocation(this.program, location, glslName); } this.compileShader(this.vs, this.vsSource); this.compileShader(this.fs, this.fsSource); var program = this.program; gl.attachShader(program, this.vs); gl.attachShader(program, this.fs); gl.linkProgram(program); gl.detachShader(program, this.vs); gl.detachShader(program, this.fs); // 检测当前程序链接状态 var success = gl.getProgramParameter(program, gl.LINK_STATUS); if (!success) { var info = gl.getProgramInfoLog(program); throw "could not link program ".concat(this.name, ": ").concat(info); } { // attribute locations var numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); for (var i = 0; i < numAttributes; i++) { var attribute = gl.getActiveAttrib(program, i); var _location = gl.getAttribLocation(program, attribute.name); this.attributeLocations[attribute.name] = _location; } } { // uniform locations var numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); for (var _i = 0; _i < numUniforms; _i++) { var uniform = gl.getActiveUniform(program, _i); var _location2 = gl.getUniformLocation(program, uniform.name); this.uniformLocations[uniform.name] = _location2; this.uniforms[uniform.name] = { location: _location2, value: null }; } } // uniform blocks if (typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext) { //WebGL2RenderingContext在mac的safari14以下是没有定义的 var numBlocks = gl.getProgramParameter(program, gl.ACTIVE_UNIFORM_BLOCKS); for (var _i2 = 0; _i2 < numBlocks; _i2++) { var blockName = gl.getActiveUniformBlockName(program, _i2); var blockIndex = gl.getUniformBlockIndex(program, blockName); this.uniformBlockIndices[blockName] = blockIndex; gl.uniformBlockBinding(program, blockIndex, blockIndex); var dataSize = gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_DATA_SIZE); var uBuffer = gl.createBuffer(); gl.bindBuffer(gl.UNIFORM_BUFFER, uBuffer); gl.bufferData(gl.UNIFORM_BUFFER, dataSize, gl.DYNAMIC_READ); gl.bindBufferBase(gl.UNIFORM_BUFFER, blockIndex, uBuffer); gl.bindBuffer(gl.UNIFORM_BUFFER, null); this.uniformBlocks[blockName] = { name: blockName, index: blockIndex, dataSize: dataSize, buffer: uBuffer }; } } var _cached = { program: this.program, vs: this.vs, fs: this.fs, attributeLocations: this.attributeLocations, uniformLocations: this.uniformLocations, uniforms: this.uniforms, uniformBlocks: this.uniformBlocks }; this.cache.set("".concat(this.vsSource, ", ").concat(this.fsSource), _cached); } var tEnd = performance.now(); var duration = tEnd - tStart; //console.log(`shader compile duration: ${duration.toFixed(3)}`); } setUniformMatrix4(name, value) { var gl = this.gl; var location = this.uniformLocations[name]; if (location == null) { return; } var tmp = new Float32Array(value.elements); gl.uniformMatrix4fv(location, false, tmp); } setUniform1f(name, value) { var gl = this.gl; var uniform = this.uniforms[name]; if (uniform === undefined) { return; } if (uniform.value === value) { return; } uniform.value = value; gl.uniform1f(uniform.location, value); } setUniformBoolean(name, value) { var gl = this.gl; var uniform = this.uniforms[name]; if (uniform === undefined) { return; } if (uniform.value === value) { return; } uniform.value = value; gl.uniform1i(uniform.location, value); } setUniformTexture(name, value) { var gl = this.gl; var location = this.uniformLocations[name]; if (location == null) { return; } gl.uniform1i(location, value); } setUniform2f(name, value) { var gl = this.gl; var location = this.uniformLocations[name]; if (location == null) { return; } gl.uniform2f(location, value[0], value[1]); } setUniform3f(name, value) { var gl = this.gl; var location = this.uniformLocations[name]; if (location == null) { return; } gl.uniform3f(location, value[0], value[1], value[2]); } setUniform(name, value) { if (value.constructor === Matrix4) { this.setUniformMatrix4(name, value); } else if (typeof value === "number") { this.setUniform1f(name, value); } else if (typeof value === "boolean") { this.setUniformBoolean(name, value); } else if (value instanceof WebGLTexture$1) { this.setUniformTexture(name, value); } else if (value instanceof Array) { if (value.length === 2) { this.setUniform2f(name, value); } else if (value.length === 3) { this.setUniform3f(name, value); } } else { console.error("unhandled uniform type: ", name, value); } } setUniform1i(name, value) { var gl = this.gl; var location = this.uniformLocations[name]; if (location == null) { return; } gl.uniform1i(location, value); } } ; class WebGLTexture$1 { constructor(gl, texture, threeRenderer) { this.gl = gl; this.texture = texture; if (texture.image && !(texture.image instanceof Image) && !texture.isCanvasTexture && !texture.isDataTexture) { //renderTarget的texture在创建renderTarget时已经初始化过 见setupRenderTarget this.id = threeRenderer.properties.get(texture).__webglTexture || gl.createTexture(); this.isFromRenderTarget = true; } else { this.id = gl.createTexture(); } this.target = gl.TEXTURE_2D; this.version = -1; this.update(texture); } update() { if (!this.texture.image) { this.version = this.texture.version; return; } //if(this.isFromRenderTarget)return //没找到怎么update。 在three.js里的uploadTexture没找到。 这里会报错,可能是 state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ),类似depthTex的写法 var gl = this.gl; var texture = this.texture; if (this.version === texture.version) { return; } this.target = gl.TEXTURE_2D; gl.bindTexture(this.target, this.id); var level = 0; var internalFormat = paramThreeToGL$1(gl, texture.format); var width = texture.image.width; var height = texture.image.height; var border = 0; var srcFormat = internalFormat; var srcType = paramThreeToGL$1(gl, texture.type); var data; 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); if (texture instanceof DataTexture) { data = texture.image.data; gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL$1(gl, texture.magFilter)); gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL$1(gl, texture.minFilter)); gl.texImage2D(this.target, level, internalFormat, width, height, border, srcFormat, srcType, data); } else if (texture instanceof CanvasTexture || texture instanceof Texture) { data = texture.image; gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, paramThreeToGL$1(gl, texture.wrapS)); gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, paramThreeToGL$1(gl, texture.wrapT)); gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL$1(gl, texture.magFilter)); gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL$1(gl, texture.minFilter)); if (this.isFromRenderTarget) { //咋写? //gl.texImage2D( 3553, 0, internalFormat, width, height, 0, srcFormat, srcType, null ) //console.log('isFromRenderTarget') } else { gl.texImage2D(this.target, level, internalFormat, internalFormat, srcType, data); //这个参数怎么跟我查的不一样呢 } if (texture instanceof Texture) { gl.generateMipmap(gl.TEXTURE_2D); } } gl.bindTexture(this.target, null); this.version = texture.version; } } ; class WebGLBuffer$1 { constructor() { this.numElements = 0; this.vao = null; this.vbos = new Map(); } } ; class Renderer$1 { constructor(threeRenderer) { this.threeRenderer = threeRenderer; this.gl = this.threeRenderer.getContext(); this.buffers = new Map(); this.shaders = new Map(); this.textures = new Map(); this.glTypeMapping = new Map(); this.glTypeMapping.set(Float32Array, this.gl.FLOAT); this.glTypeMapping.set(Uint8Array, this.gl.UNSIGNED_BYTE); this.glTypeMapping.set(Uint16Array, this.gl.UNSIGNED_SHORT); this.toggle = 0; } deleteBuffer(geometry) { var gl = this.gl; var webglBuffer = this.buffers.get(geometry); if (webglBuffer != null) { for (var attributeName in geometry.attributes) { gl.deleteBuffer(webglBuffer.vbos.get(attributeName).handle); } this.buffers.delete(geometry); } } createBuffer(geometry) { var gl = this.gl; var webglBuffer = new WebGLBuffer$1(); webglBuffer.vao = gl.createVertexArray(); webglBuffer.numElements = geometry.attributes.position.count; gl.bindVertexArray(webglBuffer.vao); for (var attributeName in geometry.attributes) { var bufferAttribute = geometry.attributes[attributeName]; var vbo = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vbo); gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW); var normalized = bufferAttribute.normalized; var type = this.glTypeMapping.get(bufferAttribute.array.constructor); if (attributeLocations$1[attributeName] === undefined) { //attributeLocation = attributeLocations["aExtra"]; } else { var attributeLocation = attributeLocations$1[attributeName].location; gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0); gl.enableVertexAttribArray(attributeLocation); } webglBuffer.vbos.set(attributeName, { handle: vbo, name: attributeName, count: bufferAttribute.count, itemSize: bufferAttribute.itemSize, type: geometry.attributes.position.array.constructor, version: 0 }); } gl.bindBuffer(gl.ARRAY_BUFFER, null); gl.bindVertexArray(null); var disposeHandler = event => { this.deleteBuffer(geometry); geometry.removeEventListener("dispose", disposeHandler); }; geometry.addEventListener("dispose", disposeHandler); return webglBuffer; } updateBuffer(geometry) { var gl = this.gl; var webglBuffer = this.buffers.get(geometry); gl.bindVertexArray(webglBuffer.vao); for (var attributeName in geometry.attributes) { var bufferAttribute = geometry.attributes[attributeName]; var normalized = bufferAttribute.normalized; var type = this.glTypeMapping.get(bufferAttribute.array.constructor); var vbo = null; if (!webglBuffer.vbos.has(attributeName)) { vbo = gl.createBuffer(); webglBuffer.vbos.set(attributeName, { handle: vbo, name: attributeName, count: bufferAttribute.count, itemSize: bufferAttribute.itemSize, type: geometry.attributes.position.array.constructor, version: bufferAttribute.version }); } else { vbo = webglBuffer.vbos.get(attributeName).handle; webglBuffer.vbos.get(attributeName).version = bufferAttribute.version; } gl.bindBuffer(gl.ARRAY_BUFFER, vbo); gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW); if (attributeLocations$1[attributeName] === undefined) { //attributeLocation = attributeLocations["aExtra"]; } else { var attributeLocation = attributeLocations$1[attributeName].location; gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0); gl.enableVertexAttribArray(attributeLocation); } } gl.bindBuffer(gl.ARRAY_BUFFER, null); gl.bindVertexArray(null); } traverse(scene) { var octrees = []; var stack = [scene]; while (stack.length > 0) { var node = stack.pop(); if (node instanceof PointCloudTree) { octrees.push(node); continue; } var visibleChildren = node.children.filter(c => c.visible); stack.push(...visibleChildren); } var result = { octrees: octrees }; return result; } renderNodes(octree, nodes, visibilityTextureData, camera, target, shader, params) { var _this = this; viewer.addTimeMark('renderNodes', 'start'); var gl = this.gl; var material = params.material ? params.material : octree.material; var shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps; var view = camera.matrixWorldInverse; if (params.viewOverride) { view = params.viewOverride; } var worldView = new Matrix4(); var mat4holder = new Float32Array(16); var i = 0; //---------从renderOctree搬到这---- shader.setUniform1f("size", material.usePanoMap ? Potree.config.material.absolutePanoramaSize * Math.min(window.devicePixelRatio, 2) : material.size); //usePanoMap时控制在不大不小的范围内感觉较好,考虑到有的点云稀疏,用大一点的点 shader.setUniform1f("uOpacity", material.usePanoMap ? 1 : material.opacity); shader.setUniform3f("uColor", material.color.toArray()); var currentTextureBindingPoint = params.currentTextureBindingPoint; if (material.pointSizeType >= 0 /* && window.needvisibilityTexture */) { if (material.pointSizeType === PointSizeType.ADAPTIVE || material.activeAttributeName === "level of detail") { var vnNodes = params.vnTextureNodes != null ? params.vnTextureNodes : nodes; visibilityTextureData = octree.computeVisibilityTextureData(vnNodes, camera); var vnt = material.visibleNodesTexture; var data = vnt.image.data; data.set(visibilityTextureData.data); vnt.needsUpdate = true; var webGLTexture = this.textures.get(vnt); webGLTexture.update(); //不加这个会闪烁 var vnWebGLTexture = this.textures.get(material.visibleNodesTexture); //不知道为什么这段从renderOctree中移过来,会崩溃。暂时不移动了 if (vnWebGLTexture) { shader.setUniform1i("visibleNodes", currentTextureBindingPoint); gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint); gl.bindTexture(vnWebGLTexture.target, vnWebGLTexture.id); currentTextureBindingPoint++; } } } /* if (material.pointSizeType >= 0) { if (material.pointSizeType === PointSizeType.ADAPTIVE || material.activeAttributeName === "level of detail") { let vnNodes = (params.vnTextureNodes != null) ? params.vnTextureNodes : nodes; visibilityTextureData = octree.computeVisibilityTextureData(vnNodes, camera); const vnt = material.visibleNodesTexture; const data = vnt.image.data; data.set(visibilityTextureData.data); vnt.needsUpdate = true; } } */ var transparent = false; if (params.transparent !== undefined) { transparent = params.transparent && material.opacity < 1; } else { transparent = material.usePanoMap ? false : material.useFilterByNormal || material.opacity < 1; //add useFilterByNormal } if (transparent) { gl.enable(gl.BLEND); if (params.notAdditiveBlending) { gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); //NormalBlending /* gl.enable(gl.DEPTH_TEST); gl.depthMask(true); //如果不开启depthWrite, 深度会错乱。 */ //无解 gl.disable(gl.DEPTH_TEST); gl.depthMask(true); } else { gl.blendFunc(gl.SRC_ALPHA, gl.ONE); //AdditiveBlending 原本 gl.disable(gl.DEPTH_TEST); gl.depthMask(false); } } else { gl.disable(gl.BLEND); gl.depthMask(true); gl.enable(gl.DEPTH_TEST); } if (params.blendFunc !== undefined) { gl.enable(gl.BLEND); gl.blendFunc(...params.blendFunc); } if (params.depthTest !== undefined) { if (params.depthTest === true) { gl.enable(gl.DEPTH_TEST); } else { gl.disable(gl.DEPTH_TEST); } } if (params.depthWrite !== undefined) { if (params.depthWrite === true) { gl.depthMask(true); } else { gl.depthMask(false); } } //--------------------------------- var _loop = function _loop() { if (exports.debug.allowedNodes !== undefined) { if (!exports.debug.allowedNodes.includes(node.name)) { return 1; // continue } } var world = node.sceneNode.matrixWorld; worldView.multiplyMatrices(view, world); if (visibilityTextureData) { var vnStart = visibilityTextureData.offsets.get(node); //console.log('vnStart',vnStart) shader.setUniform1f("uVNStart", vnStart); } var level = node.getLevel(); if (node.debug) { shader.setUniform("uDebug", true); } else { shader.setUniform("uDebug", false); } // let isLeaf = false; // if(node instanceof PointCloudOctreeNode){ // isLeaf = Object.keys(node.children).length === 0; // }else if(node instanceof PointCloudArena4DNode){ // isLeaf = node.geometryNode.isLeaf; // } // shader.setUniform("uIsLeafNode", isLeaf); // let isLeaf = node.children.filter(n => n != null).length === 0; // if(!isLeaf){ // continue; // } // TODO consider passing matrices in an array to avoid uniformMatrix4fv overhead var lModel = shader.uniformLocations["modelMatrix"]; if (lModel) { mat4holder.set(world.elements); gl.uniformMatrix4fv(lModel, false, mat4holder); } var lModelView = shader.uniformLocations["modelViewMatrix"]; //mat4holder.set(worldView.elements); // faster then set in chrome 63 for (var j = 0; j < 16; j++) { mat4holder[j] = worldView.elements[j]; } gl.uniformMatrix4fv(lModelView, false, mat4holder); { // Clip Polygons if (material.clipPolygons && material.clipPolygons.length > 0) { var clipPolygonVCount = []; var worldViewProjMatrices = []; for (var clipPolygon of material.clipPolygons) { var _view = clipPolygon.viewMatrix; var proj = clipPolygon.projMatrix; var worldViewProj = proj.clone().multiply(_view).multiply(world); clipPolygonVCount.push(clipPolygon.markers.length); worldViewProjMatrices.push(worldViewProj); } var flattenedMatrices = [].concat(...worldViewProjMatrices.map(m => m.elements)); var flattenedVertices = new Array(8 * 3 * material.clipPolygons.length); for (var _i3 = 0; _i3 < material.clipPolygons.length; _i3++) { var _clipPolygon = material.clipPolygons[_i3]; for (var _j = 0; _j < _clipPolygon.markers.length; _j++) { flattenedVertices[_i3 * 24 + (_j * 3 + 0)] = _clipPolygon.markers[_j].position.x; flattenedVertices[_i3 * 24 + (_j * 3 + 1)] = _clipPolygon.markers[_j].position.y; flattenedVertices[_i3 * 24 + (_j * 3 + 2)] = _clipPolygon.markers[_j].position.z; } } var lClipPolygonVCount = shader.uniformLocations["uClipPolygonVCount[0]"]; gl.uniform1iv(lClipPolygonVCount, clipPolygonVCount); var lClipPolygonVP = shader.uniformLocations["uClipPolygonWVP[0]"]; gl.uniformMatrix4fv(lClipPolygonVP, false, flattenedMatrices); var lClipPolygons = shader.uniformLocations["uClipPolygonVertices[0]"]; gl.uniform3fv(lClipPolygons, flattenedVertices); } } //shader.setUniformMatrix4("modelMatrix", world); //shader.setUniformMatrix4("modelViewMatrix", worldView); shader.setUniform1f("uLevel", level); shader.setUniform1f("levelPercent", octree.nodeMaxLevel ? level / octree.nodeMaxLevel : 0.5); //xzw add shader.setUniform1f("uNodeSpacing", node.geometryNode.estimatedSpacing); shader.setUniform1f("uPCIndex", i); // uBBSize if (shadowMaps.length > 0) { var lShadowMap = shader.uniformLocations["uShadowMap[0]"]; shader.setUniform3f("uShadowColor", material.uniforms.uShadowColor.value); var bindingStart = 5; var bindingPoints = new Array(shadowMaps.length).fill(bindingStart).map((a, i) => a + i); gl.uniform1iv(lShadowMap, bindingPoints); for (var _i4 = 0; _i4 < shadowMaps.length; _i4++) { var shadowMap = shadowMaps[_i4]; var bindingPoint = bindingPoints[_i4]; var glTexture = _this.threeRenderer.properties.get(shadowMap.target.texture).__webglTexture; gl.activeTexture(gl["TEXTURE".concat(bindingPoint)]); gl.bindTexture(gl.TEXTURE_2D, glTexture); } { var worldViewMatrices = shadowMaps.map(sm => sm.camera.matrixWorldInverse).map(view => new Matrix4().multiplyMatrices(view, world)); var _flattenedMatrices = [].concat(...worldViewMatrices.map(c => c.elements)); var lWorldView = shader.uniformLocations["uShadowWorldView[0]"]; gl.uniformMatrix4fv(lWorldView, false, _flattenedMatrices); } { var _flattenedMatrices2 = [].concat(...shadowMaps.map(sm => sm.camera.projectionMatrix.elements)); var lProj = shader.uniformLocations["uShadowProj[0]"]; gl.uniformMatrix4fv(lProj, false, _flattenedMatrices2); } } var geometry = node.geometryNode.geometry; if (geometry.attributes["gps-time"]) { var bufferAttribute = geometry.attributes["gps-time"]; var attGPS = octree.getAttribute("gps-time"); var initialRange = attGPS.initialRange; var initialRangeSize = initialRange[1] - initialRange[0]; var globalRange = attGPS.range; var globalRangeSize = globalRange[1] - globalRange[0]; var scale = initialRangeSize / globalRangeSize; var offset = -(globalRange[0] - initialRange[0]) / initialRangeSize; scale = Number.isNaN(scale) ? 1 : scale; offset = Number.isNaN(offset) ? 0 : offset; shader.setUniform1f("uGpsScale", scale); shader.setUniform1f("uGpsOffset", offset); //shader.setUniform2f("uFilterGPSTimeClipRange", [-Infinity, Infinity]); var uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value; // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0] // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1] // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]); var normalizedClipRange = [(uFilterGPSTimeClipRange[0] - globalRange[0]) / globalRangeSize, (uFilterGPSTimeClipRange[1] - globalRange[0]) / globalRangeSize]; shader.setUniform2f("uFilterGPSTimeClipRange", normalizedClipRange); // // ranges in full gps coordinate system // const globalRange = attGPS.range; // const bufferRange = bufferAttribute.potree.range; // // ranges in [0, 1] // // normalizedGlobalRange = [0, 1] // // normalizedBufferRange: norm buffer within norm global range e.g. [0.2, 0.8] // const globalWidth = globalRange[1] - globalRange[0]; // const normalizedBufferRange = [ // (bufferRange[0] - globalRange[0]) / globalWidth, // (bufferRange[1] - globalRange[0]) / globalWidth, // ]; // shader.setUniform2f("uNormalizedGpsBufferRange", normalizedBufferRange); // let uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value; // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0] // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1] // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]); // shader.setUniform1f("uGpsScale", bufferAttribute.potree.scale); // shader.setUniform1f("uGpsOffset", bufferAttribute.potree.offset); } { var uFilterReturnNumberRange = material.uniforms.uFilterReturnNumberRange.value; var uFilterNumberOfReturnsRange = material.uniforms.uFilterNumberOfReturnsRange.value; var uFilterPointSourceIDClipRange = material.uniforms.uFilterPointSourceIDClipRange.value; shader.setUniform2f("uFilterReturnNumberRange", uFilterReturnNumberRange); shader.setUniform2f("uFilterNumberOfReturnsRange", uFilterNumberOfReturnsRange); shader.setUniform2f("uFilterPointSourceIDClipRange", uFilterPointSourceIDClipRange); } var webglBuffer = null; if (!_this.buffers.has(geometry)) { webglBuffer = _this.createBuffer(geometry); _this.buffers.set(geometry, webglBuffer); } else { webglBuffer = _this.buffers.get(geometry); for (var attributeName in geometry.attributes) { var attribute = geometry.attributes[attributeName]; if (attribute.version > webglBuffer.vbos.get(attributeName).version) { _this.updateBuffer(geometry); } } } gl.bindVertexArray(webglBuffer.vao); var isExtraAttribute = attributeLocations$1[material.activeAttributeName] === undefined && Object.keys(geometry.attributes).includes(material.activeAttributeName); if (isExtraAttribute) { var attributeLocation = attributeLocations$1["aExtra"].location; for (var _attributeName in geometry.attributes) { var _bufferAttribute = geometry.attributes[_attributeName]; var _vbo = webglBuffer.vbos.get(_attributeName); gl.bindBuffer(gl.ARRAY_BUFFER, _vbo.handle); gl.disableVertexAttribArray(attributeLocation); } var attName = material.activeAttributeName; var _bufferAttribute2 = geometry.attributes[attName]; var vbo = webglBuffer.vbos.get(attName); if (_bufferAttribute2 !== undefined && vbo !== undefined) { var type = _this.glTypeMapping.get(_bufferAttribute2.array.constructor); var normalized = _bufferAttribute2.normalized; gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle); gl.vertexAttribPointer(attributeLocation, _bufferAttribute2.itemSize, type, normalized, 0, 0); gl.enableVertexAttribArray(attributeLocation); } { var attExtra = octree.pcoGeometry.pointAttributes.attributes.find(a => a.name === attName); var range = material.getRange(attName); if (!range) { range = attExtra.range; } if (!range) { range = [0, 1]; } var _initialRange = attExtra.initialRange; var _initialRangeSize = _initialRange[1] - _initialRange[0]; var _globalRange = range; var _globalRangeSize = _globalRange[1] - _globalRange[0]; var _scale = _initialRangeSize / _globalRangeSize; var _offset = -(_globalRange[0] - _initialRange[0]) / _initialRangeSize; _scale = Number.isNaN(_scale) ? 1 : _scale; _offset = Number.isNaN(_offset) ? 0 : _offset; shader.setUniform1f("uExtraScale", _scale); shader.setUniform1f("uExtraOffset", _offset); } } else { for (var _attributeName2 in geometry.attributes) { var _bufferAttribute3 = geometry.attributes[_attributeName2]; var _vbo2 = webglBuffer.vbos.get(_attributeName2); if (attributeLocations$1[_attributeName2] !== undefined) { var _attributeLocation = attributeLocations$1[_attributeName2].location; var _type = _this.glTypeMapping.get(_bufferAttribute3.array.constructor); var _normalized = _bufferAttribute3.normalized; gl.bindBuffer(gl.ARRAY_BUFFER, _vbo2.handle); gl.vertexAttribPointer(_attributeLocation, _bufferAttribute3.itemSize, _type, _normalized, 0, 0); gl.enableVertexAttribArray(_attributeLocation); } } } var numPoints = webglBuffer.numElements; gl.drawArrays(gl.POINTS, 0, numPoints); //gl.drawArrays(gl.TRIANGLES, 0, numPoints); i++; }; for (var node of nodes) { if (_loop()) continue; } gl.bindVertexArray(null); viewer.addTimeMark('renderNodes', 'end'); } renderOctree(octrees, nodes, camera, target) { var params = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; viewer.addTimeMark('renderOctree', 'start'); var octree; if (octrees instanceof Array) { octree = octrees[0]; } else { octree = octrees; octrees = [octree]; } var gl = this.gl; var material = params.material ? params.material : octree.material; var shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps; var view = camera.matrixWorldInverse; var viewInv = camera.matrixWorld; if (params.viewOverride) { view = params.viewOverride; viewInv = view.clone().invert(); } var proj = camera.projectionMatrix; var projInv = proj.clone().invert(); //let worldView = new THREE.Matrix4(); var shader = null; var visibilityTextureData = null; var currentTextureBindingPoint = 0; /* if (material.pointSizeType >= 0) {//最好搬到renderNodes if (material.pointSizeType === PointSizeType.ADAPTIVE || material.activeAttributeName === "level of detail") { let vnNodes = (params.vnTextureNodes != null) ? params.vnTextureNodes : nodes; visibilityTextureData = octree.computeVisibilityTextureData(vnNodes, camera); const vnt = material.visibleNodesTexture; const data = vnt.image.data; data.set(visibilityTextureData.data); vnt.needsUpdate = true; } } */ { // UPDATE SHADER AND TEXTURES if (!this.shaders.has(material)) { var [vs, fs] = [material.vertexShader, material.fragmentShader]; var _shader = new Shader$1(gl, "pointcloud", vs, fs); this.shaders.set(material, _shader); } shader = this.shaders.get(material); if (material.shaderNeedsUpdate) { var [_vs, _fs] = [material.vertexShader, material.fragmentShader]; var numSnapshots = material.snapEnabled ? material.numSnapshots : 0; var num_in_clipboxes = material.clipBoxes_in && material.clipBoxes_in.length ? material.clipBoxes_in.length : 0; var num_out_clipboxes = material.clipBoxes_out && material.clipBoxes_out.length ? material.clipBoxes_out.length : 0; var num_highlightBox = material.highlightBoxes && material.highlightBoxes.length ? material.highlightBoxes.length : 0; var numClipSpheres = params.clipSpheres && params.clipSpheres.length ? params.clipSpheres.length : 0; var numClipPolygons = material.clipPolygons && material.clipPolygons.length ? material.clipPolygons.length : 0; var defines = ["#define num_shadowmaps ".concat(shadowMaps.length), "#define num_snapshots ".concat(numSnapshots), "#define num_in_clipboxes ".concat(num_in_clipboxes), //改 "#define num_out_clipboxes ".concat(num_out_clipboxes), //改 "#define num_highlightBox ".concat(num_highlightBox), //改 "#define num_clipspheres ".concat(numClipSpheres), "#define num_prism ".concat(material.prisms.pointsCount ? material.prisms.length : 0), //土方量数 如果num_prism>0,prismPointCountSum为0 会报错 :array size must be greater than zero "#define prismPointCountSum ".concat(material.prisms.pointsCount), //点总个数 "#define prism_maxPointsCount ".concat(material.prisms.maxPointsCount) //单个prism最大点个数 (如果define也能传递个数数组,就不用再uniform里传了,呜 ) ]; //add:----------- if (material.bigClipInBox) { //裁剪下载 defines.push('#define bigClipInBox'); } if (material.usePanoMap) { defines.push("#define usePanoMap"); } if (material.useFilterByNormal) { defines.push("#define use_filter_by_normal"); //Potree.settings.editType == 'pano' ? defines.push("#define attenuated_opacity2") : defines.push("#define attenuated_opacity"); } if (material.uniforms.baseHeightAreaMap.value) { //根据模型高亮土方 defines.push('#define showBaseHeight'); } //--------------- if (octree.pcoGeometry.root.isLoaded()) { var attributes = octree.pcoGeometry.root.geometry.attributes; if (attributes["gps-time"]) { defines.push("#define clip_gps_enabled"); } if (attributes["return number"]) { defines.push("#define clip_return_number_enabled"); } if (attributes["number of returns"]) { defines.push("#define clip_number_of_returns_enabled"); } if (attributes["source id"] || attributes["point source id"]) { defines.push("#define clip_point_source_id_enabled"); } } var definesString = defines.join("\n"); var vsVersionIndex = _vs.indexOf("#version "); var fsVersionIndex = _fs.indexOf("#version "); if (vsVersionIndex >= 0) { _vs = _vs.replace(/(#version .*)/, "$1\n".concat(definesString)); } else { _vs = "".concat(definesString, "\n").concat(_vs); } if (fsVersionIndex >= 0) { _fs = _fs.replace(/(#version .*)/, "$1\n".concat(definesString)); } else { _fs = "".concat(definesString, "\n").concat(_fs); } shader.update(_vs, _fs); material.shaderNeedsUpdate = false; } for (var uniformName of Object.keys(material.uniforms)) { var uniform = material.uniforms[uniformName]; if (uniform.type == "t") { var texture = uniform.value; if (!texture) { continue; } //add if (uniformName == 'pano0Map' || uniformName == 'pano1Map') { //属于cubeTex,另外设置 continue; } /* if(texture.image && !(texture.image instanceof Image) && !(texture instanceof THREE.CanvasTexture)){ //renderTarget的texture在创建renderTarget时已经初始化过 见setupRenderTarget continue } */ if (!this.textures.has(texture) || texture.needsRebuild) { var webglTexture = new WebGLTexture$1(gl, texture, this.threeRenderer); this.textures.set(texture, webglTexture); delete texture.needsRebuild; //renderTarget在resize后会触发dispose, 然后 _gl.deleteTexture( textureProperties.__webglTexture )所以需要重新建立 } var webGLTexture = this.textures.get(texture); webGLTexture.update(); } } } gl.useProgram(shader.program); /* let transparent = false; if(params.transparent !== undefined){ transparent = params.transparent && material.opacity < 1; }else{ transparent = material.usePanoMap ? false : (material.useFilterByNormal || material.opacity < 1); //add useFilterByNormal } if (transparent){ gl.enable(gl.BLEND); if(params.notAdditiveBlending){ gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); //NormalBlending gl.enable(gl.DEPTH_TEST); gl.depthMask(true); //如果不开启depthWrite,深度会错乱。 }else{ gl.blendFunc(gl.SRC_ALPHA, gl.ONE); //AdditiveBlending 原本 gl.disable(gl.DEPTH_TEST); gl.depthMask(false); } } else { gl.disable(gl.BLEND); gl.depthMask(true); gl.enable(gl.DEPTH_TEST); } if(params.blendFunc !== undefined){ gl.enable(gl.BLEND); gl.blendFunc(...params.blendFunc); } if(params.depthTest !== undefined){ if(params.depthTest === true){ gl.enable(gl.DEPTH_TEST); }else{ gl.disable(gl.DEPTH_TEST); } } if(params.depthWrite !== undefined){ if(params.depthWrite === true){ gl.depthMask(true); }else{ gl.depthMask(false); } } */ { // UPDATE UNIFORMS shader.setUniformMatrix4("projectionMatrix", proj); shader.setUniformMatrix4("viewMatrix", view); shader.setUniformMatrix4("uViewInv", viewInv); shader.setUniformMatrix4("uProjInv", projInv); /* let screenWidth = target ? target.width : material.screenWidth; let screenHeight = target ? target.height : material.screenHeight; shader.setUniform1f("uScreenWidth", screenWidth); shader.setUniform1f("uScreenHeight", screenHeight); */ shader.setUniform2f('resolution', material.resolution.toArray()); shader.setUniform1f("fov", Math.PI * camera.fov / 180); shader.setUniform1f("near", camera.near); shader.setUniform1f("far", camera.far); if (camera instanceof OrthographicCamera) { shader.setUniform("uUseOrthographicCamera", true); shader.setUniform("uOrthoWidth", (camera.right - camera.left) / camera.zoom); //改 shader.setUniform("uOrthoHeight", camera.top - camera.bottom); } else { shader.setUniform("uUseOrthographicCamera", false); } /* if(material.clipBoxes.length + material.clipPolygons.length === 0){//改 shader.setUniform1i("clipTask", ClipTask.NONE); }else{ shader.setUniform1i("clipTask", material.clipTask); } shader.setUniform1i("clipMethod", material.clipMethod);*/ //改 if (material.clipBoxes_in && material.clipBoxes_in.length > 0) { //let flattenedMatrices = [].concat(...material.clipBoxes.map(c => c.inverse.elements)); var lClipBoxes = shader.uniformLocations["clipBoxes_in[0]"]; gl.uniformMatrix4fv(lClipBoxes, false, material.uniforms.clipBoxes_in.value); } if (material.clipBoxes_out && material.clipBoxes_out.length > 0) { //add var lClipBoxes2 = shader.uniformLocations["clipBoxes_out[0]"]; gl.uniformMatrix4fv(lClipBoxes2, false, material.uniforms.clipBoxes_out.value); } if (material.highlightBoxes && material.highlightBoxes.length > 0) { //add var boxes_highlight = shader.uniformLocations["boxes_highlight[0]"]; gl.uniformMatrix4fv(boxes_highlight, false, material.uniforms.boxes_highlight.value); } if (material.bigClipInBox) { //add shader.setUniformMatrix4("clipBoxBig_in", material.uniforms.clipBoxBig_in.value); } if (material.uniforms.baseHeightAreaMap.value) { //根据模型高亮土方 var baseHeightBoundZ = shader.uniformLocations["baseHeightBoundZ"]; gl.uniform2f(baseHeightBoundZ, ...material.uniforms.baseHeightBoundZ.value.toArray()); var baseHeightBoundXY = shader.uniformLocations["baseHeightBoundXY"]; gl.uniform4f(baseHeightBoundXY, ...material.uniforms.baseHeightBoundXY.value.toArray()); } if (material.prisms.length) { var prismList = shader.uniformLocations["prismList[0]"]; gl.uniformMatrix3fv(prismList, false, material.uniforms.prismList.value); var prismPoints = shader.uniformLocations["prismPoints[0]"]; gl.uniform2fv(prismPoints, material.uniforms.prismPoints.value); } // TODO CLIPSPHERES if (params.clipSpheres && params.clipSpheres.length > 0) { var clipSpheres = params.clipSpheres; var matrices = []; for (var clipSphere of clipSpheres) { //let mScale = new THREE.Matrix4().makeScale(...clipSphere.scale.toArray()); //let mTranslate = new THREE.Matrix4().makeTranslation(...clipSphere.position.toArray()); //let clipToWorld = new THREE.Matrix4().multiplyMatrices(mTranslate, mScale); var clipToWorld = clipSphere.matrixWorld; var viewToWorld = camera.matrixWorld; var worldToClip = clipToWorld.clone().invert(); var viewToClip = new Matrix4().multiplyMatrices(worldToClip, viewToWorld); matrices.push(viewToClip); } var flattenedMatrices = [].concat(...matrices.map(matrix => matrix.elements)); var lClipSpheres = shader.uniformLocations["uClipSpheres[0]"]; gl.uniformMatrix4fv(lClipSpheres, false, flattenedMatrices); //const lClipSpheres = shader.uniformLocations["uClipSpheres[0]"]; //gl.uniformMatrix4fv(lClipSpheres, false, material.uniforms.clipSpheres.value); } shader.setUniform1f("orthoMaxSize", material.uniforms.orthoMaxSize.value); shader.setUniform1f("maxSize", material.uniforms.maxSize.value); shader.setUniform1f("minSize", material.uniforms.minSize.value); // uniform float uPCIndex shader.setUniform1f("uOctreeSpacing", material.spacing); shader.setUniform("uOctreeSize", material.uniforms.octreeSize.value); shader.setUniform2f("elevationRange", material.elevationRange); shader.setUniform2f("intensityRange", material.intensityRange); shader.setUniform3f("uIntensity_gbc", [material.intensityGamma, material.intensityBrightness, material.intensityContrast]); shader.setUniform3f("uRGB_gbc", [material.rgbGamma, material.rgbBrightness, material.rgbContrast]); shader.setUniform1f("uTransition", material.transition); shader.setUniform1f("wRGB", material.weightRGB); shader.setUniform1f("wIntensity", material.weightIntensity); shader.setUniform1f("wElevation", material.weightElevation); shader.setUniform1f("wClassification", material.weightClassification); shader.setUniform1f("wReturnNumber", material.weightReturnNumber); shader.setUniform1f("wSourceID", material.weightSourceID); shader.setUniform("backfaceCulling", material.uniforms.backfaceCulling.value); //========================== //gl.TEXTURE_CUBE_MAP: 34067 //gl.TEXTURE0=33984 , vnWebGLTexture.target=gl.TEXTURE_2D = 3353 /* let vnWebGLTexture = this.textures.get(material.visibleNodesTexture);//最好搬到renderNodes if(vnWebGLTexture){ shader.setUniform1i("visibleNodes", currentTextureBindingPoint); //为何之前写的是"visibleNodesTexture",但和"visibleNodes"效果相同?可shader里只有"visibleNodes" gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint); gl.bindTexture(vnWebGLTexture.target, vnWebGLTexture.id); currentTextureBindingPoint++; } */ var gradientTexture = this.textures.get(material.gradientTexture); shader.setUniform1i("gradient", currentTextureBindingPoint); gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint); gl.bindTexture(gradientTexture.target, gradientTexture.id); currentTextureBindingPoint++; var repeat = material.elevationGradientRepeat; if (repeat === ElevationGradientRepeat.REPEAT) { gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.REPEAT); gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.REPEAT); } else if (repeat === ElevationGradientRepeat.MIRRORED_REPEAT) { gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); } else { gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); } currentTextureBindingPoint++; var classificationTexture = this.textures.get(material.classificationTexture); shader.setUniform1i("classificationLUT", currentTextureBindingPoint); gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint); gl.bindTexture(classificationTexture.target, classificationTexture.id); currentTextureBindingPoint++; /* let matcapTexture = this.textures.get(material.matcapTexture); shader.setUniform1i("matcapTextureUniform", currentTextureBindingPoint); gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint); gl.bindTexture(matcapTexture.target, matcapTexture.id); currentTextureBindingPoint++; */ var baseHeightAreaMap = material.uniforms.baseHeightAreaMap.value; if (baseHeightAreaMap) { //根据模型高亮土方 var map = this.textures.get(baseHeightAreaMap); shader.setUniform1i("baseHeightAreaMap", currentTextureBindingPoint); gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint); gl.bindTexture(map.target, map.id); currentTextureBindingPoint++; } if (material.snapEnabled === true) { { var lSnapshot = shader.uniformLocations["uSnapshot[0]"]; var lSnapshotDepth = shader.uniformLocations["uSnapshotDepth[0]"]; var bindingStart = currentTextureBindingPoint; var lSnapshotBindingPoints = new Array(5).fill(bindingStart).map((a, i) => a + i); var lSnapshotDepthBindingPoints = new Array(5).fill(1 + Math.max(...lSnapshotBindingPoints)).map((a, i) => a + i); currentTextureBindingPoint = 1 + Math.max(...lSnapshotDepthBindingPoints); gl.uniform1iv(lSnapshot, lSnapshotBindingPoints); gl.uniform1iv(lSnapshotDepth, lSnapshotDepthBindingPoints); for (var i = 0; i < 5; i++) { var _texture = material.uniforms["uSnapshot"].value[i]; var textureDepth = material.uniforms["uSnapshotDepth"].value[i]; if (!_texture) { break; } var snapTexture = this.threeRenderer.properties.get(_texture).__webglTexture; var snapTextureDepth = this.threeRenderer.properties.get(textureDepth).__webglTexture; var bindingPoint = lSnapshotBindingPoints[i]; var depthBindingPoint = lSnapshotDepthBindingPoints[i]; gl.activeTexture(gl["TEXTURE".concat(bindingPoint)]); gl.bindTexture(gl.TEXTURE_2D, snapTexture); gl.activeTexture(gl["TEXTURE".concat(depthBindingPoint)]); gl.bindTexture(gl.TEXTURE_2D, snapTextureDepth); } } { var _flattenedMatrices3 = [].concat(...material.uniforms.uSnapView.value.map(c => c.elements)); var lSnapView = shader.uniformLocations["uSnapView[0]"]; gl.uniformMatrix4fv(lSnapView, false, _flattenedMatrices3); } { var _flattenedMatrices4 = [].concat(...material.uniforms.uSnapProj.value.map(c => c.elements)); var lSnapProj = shader.uniformLocations["uSnapProj[0]"]; gl.uniformMatrix4fv(lSnapProj, false, _flattenedMatrices4); } { var _flattenedMatrices5 = [].concat(...material.uniforms.uSnapProjInv.value.map(c => c.elements)); var lSnapProjInv = shader.uniformLocations["uSnapProjInv[0]"]; gl.uniformMatrix4fv(lSnapProjInv, false, _flattenedMatrices5); } { var _flattenedMatrices6 = [].concat(...material.uniforms.uSnapViewInv.value.map(c => c.elements)); var lSnapViewInv = shader.uniformLocations["uSnapViewInv[0]"]; gl.uniformMatrix4fv(lSnapViewInv, false, _flattenedMatrices6); } } //=============add=========== if (material.usePanoMap) { //为什么pointsize失效 shader.setUniform1f("progress", material.uniforms.progress.value); shader.setUniform1f("easeInOutRatio", material.uniforms.easeInOutRatio.value); shader.setUniform3f("pano0Position", material.uniforms.pano0Position.value.toArray()); shader.setUniform3f("pano1Position", material.uniforms.pano1Position.value.toArray()); shader.setUniform('pano0Matrix', material.uniforms.pano0Matrix.value); shader.setUniform('pano1Matrix', material.uniforms.pano1Matrix.value); var pano0Map = material.uniforms.pano0Map.value; if (pano0Map) { this.threeRenderer._textures.safeSetTextureCube(pano0Map, ++currentTextureBindingPoint); shader.setUniform1i('pano0Map', currentTextureBindingPoint); } var pano1Map = material.uniforms.pano1Map.value; if (pano1Map) { this.threeRenderer._textures.safeSetTextureCube(pano1Map, ++currentTextureBindingPoint); shader.setUniform1i('pano1Map', currentTextureBindingPoint); } //注: three.js我添加了个 _textures, safeSetTextureCube里主要就是activeTexture和bindTexture } } viewer.addTimeMark('renderOctree', 'end'); params.currentTextureBindingPoint = ++currentTextureBindingPoint; octrees.forEach(octree => { this.renderNodes(octree, nodes || octree.visibleNodes, visibilityTextureData, camera, target, shader, params); }); gl.activeTexture(gl.TEXTURE2); gl.bindTexture(gl.TEXTURE_2D, null); gl.activeTexture(gl.TEXTURE0); //gl.bindTexture(gl.TEXTURE_2D, null); //add //add 恢复为不透明(否则renderToCubeMap时的贴图会被渲染成高亮的颜色) gl.disable(gl.BLEND); gl.depthMask(true); gl.enable(gl.DEPTH_TEST); //DEPTH_TEST等需要恢复吗 } render(scene, camera) { var target = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var params = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var gl = this.gl; // PREPARE if (target != null) { this.threeRenderer.setRenderTarget(target); } //camera.updateProjectionMatrix(); // camera.matrixWorldInverse.invert(camera.matrixWorld); var traversalResult = this.traverse(scene); //排序 if (params.notAdditiveBlending) { //add traversalResult.octrees.forEach(tree => { if (tree.material.opacity == 1) { tree._z = Infinity; //不透明的先渲染 } else { var center = tree.boundCenter ? tree.boundCenter.clone() : tree.boundingBox.getCenter(tree.boundCenter).applyMatrix4(tree.matrixWorld); center.project(camera); tree._z = center.z; } }); traversalResult.octrees.sort((tree1, tree2) => { return tree2._z - tree1._z; //降序 (-1 朝外)。 离屏幕近的后渲染 }); } // RENDER var mat = params.material || traversalResult.octrees[0].material; if (Potree.settings.cloudSameMat && viewer.scene.volumes.length == 0 && mat.pointSizeType != PointSizeType.ADAPTIVE && mat.activeAttributeName != "level of detail") { this.renderOctree(traversalResult.octrees, null, camera, target, params); //所有点云除了个别属性需要在shader中更新,其他都使用第一个点云的材质 } else for (var octree of traversalResult.octrees) { for (var _octree of traversalResult.octrees) { this.renderOctree(_octree, _octree.visibleNodes, camera, target, params); } } //if (octree material.pointSizeType === PointSizeType.ADAPTIVE || material.activeAttributeName === "level of detail") { // CLEANUP gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, null); gl.bindBuffer(gl.ARRAY_BUFFER, null); gl.bindVertexArray(null); this.threeRenderer.resetState(); } } ; /* 中东的链接http://indoor.popsmart.cn:8094/zdoblh-yz/?vlon=5.14&vlat=-0.13&fov=100.0&pc=true&lon=121.61136592&lat=29.87855579&z=16.577 geometry: 有的attributes: 属性是: classification: color: indices: normal: position: 最好有个spacing */ /* const mapHeight = -1000;//要比点云低。最低 const cameraHeight = 1000; //最高 */ var panosHeight = config$1.map.mapHeight + 100; //要比点云低 (marker) var cursorHeight = 0; //比地图高就行 var routeLayerHeight = config$1.map.mapHeight + 105; var texLoader$5 = new TextureLoader(); var planeGeo$1 = new PlaneBufferGeometry(1, 1); var markerSize = 1; var initCameraFeildWidth = 50; var panoMarkerMats; class MapViewer extends ViewerBase { constructor(dom) { super(dom, { clearColor: Potree.config.mapBG, name: 'mapViewer', antialias: true }); this.visible = true; this.initScene(); this.needRender_ = false; this.mapLayer = new MapLayer(this, this.viewports[0]); this.scene.add(this.mapLayer.sceneGroup); this.mapLayer.sceneGroup.position.setZ(Potree.config.map.mapHeight); this.mapRatio = 0.5; this.splitDir = 'leftRight'; this.renderMeasure = false; //因context的preserveDrawingBuffer为false之后,canvas渲染多个viewport时会自动clear,所以若不渲染就会是空的。所以没有变化时就直接拷贝buffer好了。 this.copyPass = new ShaderPass(CopyShader); this.copyBuffer = new WebGLRenderTarget(100, 100, { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat, stencilBuffer: false }); viewer.addEventListener("camera_changed", e => { var needUpdateCursor; if (e.viewport == viewer.mainViewport) { needUpdateCursor = true; } else if (e.viewport == this.viewports[0]) { //attachedToViewer needUpdateCursor = true; this.mapChanged = true; this.updateWhenAtViewer(); e.changeInfo.projectionChanged && this.setViewLimit(); } needUpdateCursor && this.updateCursor(); }); this.addEventListener("camera_changed", e => { e.changeInfo.projectionChanged && this.setViewLimit(); }); //viewer.addEventListener("global_mousemove", this.updateWhenAtViewer.bind(this)) //鼠标移动时reticule也动,所以直接就needRender /* viewer.reticule.addEventListener('update',(e)=>{ if(this.attachedToViewer)this.needRender = true }) */ viewer.scene.addEventListener("360_images_added", this.addPanos.bind(this)); viewer.addEventListener("loadPointCloudDone", this.initProjection.bind(this)); this.addEventListener('global_click', e => { if (!e.isTouch && e.button != MOUSE.LEFT) return; this.updateClosestPano(e.intersect); }); this.addEventListener('add', e => { //添加其他mesh this.scene.add(e.object); if (e.name == 'route') { e.object.position.z = routeLayerHeight; } Potree.Utils.setObjectLayers(e.object, 'mapObjects'); }); viewer.addEventListener('allLoaded', () => { this.setViewLimit('standard'); }); if (!Potree.settings.isOfficial) { var domRoot = viewer.renderer.domElement.parentElement; var elAttach = $(""); elAttach.css({ position: "absolute", right: '80%', bottom: '20px', zIndex: "10000", fontSize: '1em', color: "black", background: 'rgba(255,255,255,0.8)' }); var state = false; elAttach.on("click", () => { state = !state; this.attachToMainViewer(state, 'measure'); elAttach.val(state ? 'map分离' : 'map绑定'); }); domRoot.appendChild(elAttach[0]); } } get needRender() { return this.needRender_; } set needRender(n) { this.needRender_ = n; n && (this.viewports[0].needRender = true); //使attachedToViewer时在renderDefault中可渲染 } get mapChanged() { return this.mapChanged_; } set mapChanged(c) { //镜头移动、地图内容改变都会为true this.mapChanged_ = c; c && (this.needRender = true); } waitLoadDone(callback) { //确保加载完后执行 var timer; //等待一段时间看有没有新加载的tile,如果超过这个时间没有就不等了,算加载结束 var pauseCountDown = () => { //重新等待加载结束,中断倒计时 clearTimeout(timer); //console.log('pauseCountDown') }; var freshCountDown = () => { //刷新倒计时 //console.log('freshCountDown') clearTimeout(timer); timer = setTimeout(() => { this.mapLayer.removeEventListener('loadDone', freshCountDown); this.mapLayer.removeEventListener('startLoad', pauseCountDown); callback(); }, document.hidden ? 5000 : 500); }; this.mapLayer.addEventListener('loadDone', freshCountDown); this.mapLayer.addEventListener('startLoad', pauseCountDown); if (this.mapLayer.loadingInProgress == 0) { freshCountDown(); } } addListener(images360) { images360.addEventListener('flyToPano', e => { var toPano = e.toPano; if (toPano.dontMoveMap) return; /* transitions.start(lerp.vector(this.view.position, toPano.pano.position.clone().setZ(cameraHeight), (pos, progress)=>{ }), toPano.duration, null, 0, easing[toPano.easeName] ); */ var boundSize; // = new THREE.Vector2(10,10) this.moveTo(toPano.pano.position.clone().setZ(Potree.config.map.cameraHeight), boundSize, toPano.duration, null, toPano.easeName); }); } initProjection() { this.started = true; this.mapLayer.initProjection(); } initScene() { var w = initCameraFeildWidth; var width = this.renderArea.clientWidth; var height = this.renderArea.clientHeight; //let aspect = width / height this.camera = new OrthographicCamera(-width / 2, width / 2, height / 2, -height / 2 /* -w/2, w/2, w/2/aspect, -w/2/aspect */, 0.01, 10000); this.camera.zoom = width / w; //zoom越大视野越小 //this.camera.position.set(0,0,10); this.camera.up.set(0, 0, 1); //this.camera.lookAt(new THREE.Vector3()) //this.camera.updateMatrixWorld() this.view = new ExtendView(); this.view.position.set(0, 0, Potree.config.map.cameraHeight); this.view.lookAt(0, 0, 0); var viewport = new Viewport(this.view, this.camera, { left: 0, bottom: 0, width: 1, height: 1, name: 'mapViewport' }); viewport.axis = ["x", "y"]; viewport.axisSign = [1, 1]; viewport.noPointcloud = true; //不要渲染点云 viewport.render = this.render.bind(this); //标志给mainView渲染 //viewport.unableDepth = true //depthBasicMaterial等在此viewport中不开启depth viewport.addEventListener('resize', () => { this.copyBuffer.setSize(viewport.resolution2.x, viewport.resolution2.y); //this.cloudBuffer && this.cloudBuffer.setSize(viewport.resolution2.x, viewport.resolution2.y) }); this.viewports = [viewport]; this.controls = new FirstPersonControls(this, this.viewports[0]); this.controls.setEnable(true); this.scene = new Scene(); this.inputHandler = new InputHandler(this, this.scene); this.inputHandler.name = 'mapInputHandler'; //this.inputHandler.addInputListener(this.controls); this.inputHandler.registerInteractiveScene(this.scene); //interactiveScenes this.viewports[0].interactiveScenes = this.inputHandler.interactiveScenes; //供viewer的inputHandler使用 var cursor = new Mesh(planeGeo$1, new MeshBasicMaterial({ transparent: true, opacity: 0.9, depthTest: false, //防止透明冲突 map: texLoader$5.load(Potree.resourcePath + '/textures/pic_location128.png') })); cursor.position.set(0, 0, cursorHeight); this.cursor = cursor; this.scene.add(cursor); Potree.Utils.setObjectLayers(this.scene, 'mapObjects'); } setViewLimit(state) { //设置边界,当编辑空间模型等时要解禁 if (!state) state = this.limitBoundState; if (!state) return; this.limitBoundState = state; var setting = Potree.config.OrthoCameraLimit[state]; if (setting) { this.camera.zoomLimit = $.extend({}, setting.zoom); var lonlatCenter = viewer.transform.lonlatToLocal.inverse([0, 0]); var minY = viewer.transform.lonlatToLocal.forward([lonlatCenter[0], -90 + setting.latPad])[1]; //屏幕边界的bound var maxY = viewer.transform.lonlatToLocal.forward([lonlatCenter[0], 90 - setting.latPad])[1]; /*this.view.limitBound = new THREE.Box3( new THREE.Vector3(setting.xBound[0], minY, Potree.config.map.cameraHeight), new THREE.Vector3(setting.xBound[1], maxY, 1 / 0) ) */ var halfHeight = this.viewports[0].resolution.y / 2 / this.camera.zoom; //屏幕所占高度的一半 var halfWidth = this.viewports[0].resolution.x / 2 / this.camera.zoom; this.view.limitBound = new Box3(new Vector3(setting.xBound[0] + halfWidth, minY + halfHeight, Potree.config.map.cameraHeight), new Vector3(setting.xBound[1] - halfWidth, maxY - halfHeight, 1 / 0)); } else { this.view.limitBound = null; this.camera.zoomLimit = null; } } updateCursor() { //console.log('pos', viewer.mainViewport.camera.position.toArray() ) var scale = math.getScaleForConstantSize({ //规定下最小最大像素 minSize: 80, maxSize: 200, nearBound: initCameraFeildWidth * 0.1, farBound: initCameraFeildWidth * 2, camera: this.camera, position: this.cursor.getWorldPosition(new Vector3()), resolution: this.viewports[0].resolution //2 }); this.cursor.scale.set(scale, scale, scale); //当地图缩放时 this.cursor.position.copy(viewer.mainViewport.camera.position).setZ(cursorHeight); //当场景镜头旋转移动时 this.cursor.rotation.z = viewer.mainViewport.view.yaw; this.needRender = true; } addPanos(e) { var panosGroup = new Object3D(); panosGroup.name = 'markers'; panoMarkerMats = { default: new MeshBasicMaterial({ transparent: true, opacity: 0.5, map: texLoader$5.load(Potree.resourcePath + '/textures/map_marker.png') }), selected: new MeshBasicMaterial({ transparent: true, opacity: 1, map: texLoader$5.load(Potree.resourcePath + '/textures/map_marker.png') }) }; e.images.panos.forEach(pano => { pano.mapMarker = new Mesh(planeGeo$1, panoMarkerMats.default); pano.mapMarker.position.copy(pano.position).setZ(0); pano.mapMarker.scale.set(markerSize, markerSize, markerSize); pano.mapMarker.name = 'mapMarker'; panosGroup.add(pano.mapMarker); var mouseover = e => { if (!e.byMap) { pano.mapMarker.material = panoMarkerMats.selected; if (!e.byMainView) pano.dispatchEvent({ type: "hoverOn", byMap: true }); this.needRender = true; } }; var mouseleave = e => { if (!e.byMap) { pano.mapMarker.material = panoMarkerMats.default; if (!e.byMainView) pano.dispatchEvent({ type: "hoverOff", byMap: true }); this.needRender = true; } }; pano.mapMarker.addEventListener('mouseover', mouseover); pano.mapMarker.addEventListener('mouseleave', mouseleave); pano.addEventListener('hoverOn', mouseover); pano.addEventListener('hoverOff', mouseleave); var onclick = e => { viewer.images360.flyToPano(pano); }; pano.mapMarker.addEventListener('click', onclick); pano.addEventListener('isVisible', e => { //是否显示该点的mesh(不显示也能走) //console.log('panoMarker isVisible', pano.id, e.visible) Potree.Utils.updateVisible(pano.mapMarker, 'panoVisible', e.visible); this.needRender = true; }); pano.addEventListener('rePos', e => { pano.mapMarker.position.copy(pano.position).setZ(0); }); }); this.scene.add(panosGroup); panosGroup.position.z = panosHeight; this.panosGroup = panosGroup; Potree.Utils.setObjectLayers(panosGroup, 'mapObjects'); /* e.images.on('markersDisplayChange', (show)=>{ panosGroup.visible = show this.needRender = true }) */ //------- //this.fitPanosToViewport() this.initFitView(); } updateClosestPano(intersect) { if (viewer.images360.flying) return; intersect = intersect && intersect.orthoIntersect; if (!intersect) return; intersect = intersect.clone().setZ(0); var minDis = 20; //距离鼠标不能太远 var filterFuncs = [Images360.filters.isEnabled(), Images360.filters.isVisible(), //只走显示的点,否则会走到别的层 pano => { return pano.position.clone().setZ(0).distanceTo(intersect) < minDis; }]; var pano = Common.find(viewer.images360.panos, filterFuncs, [Images360.sortFunctions.floorDisSquaredToPoint(intersect)]); if (pano && pano != viewer.images360.currentPano) { viewer.images360.flyToPano(pano); } } fitPanosToViewport() { //使所有漫游点占满viewport //var w = viewer.bound.boundSize.x; var boundSize = viewer.images360.bound.size.clone().multiplyScalar(1.1); boundSize.max(new Vector3(4, 4, 4)); var endPosition = viewer.images360.bound.center.clone(); this.moveTo(endPosition, boundSize, 0); } fitToPointcloud(pointcloud) { var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 400; var boundSize = pointcloud.bound.getSize(new Vector3()); /* .multiplyScalar(1.1); */ boundSize.max(new Vector3(4, 4, 4)); var endPosition = pointcloud.bound.getCenter(new Vector3()); this.moveTo(endPosition, boundSize, duration); //给点duration去变化 否则地图放大后所占的还是很小 } initFitView() { var dis = 5, px = 70; //地图上px像素长度代表的距离为dis //px是手动缩放到5m后发现是这个长度 var zoom = px / dis; this.camera.zoom = zoom; this.moveTo(viewer.images360.position /* viewer.images360.bound.center */); this.camera.updateProjectionMatrix(); } fitToDatasets(datasets) { var bound = new Box3(); datasets.forEach(e => bound.union(e.bound)); var center = bound.getCenter(new Vector3()); var size = bound.getSize(new Vector3()); this.moveTo(center, size, 200); //给duration是为了顺应视口大小改变,缓冲 } moveTo(endPosition, boundSize) { var duration = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var margin = arguments.length > 3 ? arguments[3] : undefined; var easeName = arguments.length > 4 ? arguments[4] : undefined; var callback = arguments.length > 5 ? arguments[5] : undefined; //前两个参数有xy即可 var z = Math.max(Potree.config.map.cameraHeight, endPosition.z + (boundSize !== null && boundSize !== void 0 && boundSize.z ? boundSize.z / 2 : 0)); endPosition = new Vector3(endPosition.x, endPosition.y, z); this.view.moveOrthoCamera(this.viewports[0], { endPosition, boundSize, margin, callback }, duration, easeName); /* let endZoom, startZoom = this.camera.zoom //修改相机为bound中心,这样能看到全部(宽度范围内) this.view.setView({ position:endPosition, duration, callback:()=>{//done }, onUpdate:(progress)=>{ if(boundSize){ let aspect = boundSize.x / boundSize.y let w, h; if(this.camera.aspect > aspect){//视野更宽则用bound的纵向来决定 h = boundSize.y //w = h * this.camera.aspect endZoom = this.viewports[0].resolution.y / h }else{ w = boundSize.x; //h = w / this.camera.aspect endZoom = this.viewports[0].resolution.x / w } //onUpdate时更新endzoom是因为画布大小可能更改 this.camera.zoom = endZoom * progress + startZoom * (1 - progress) this.camera.updateProjectionMatrix() } }, Easing:easeName }) */ } updateWhenAtViewer(e) { //两个触发来源: 1 camera_changed时 2 mapLayer.needUpdate时。 render在viewer中执行 if (this.attachedToViewer) { if (this.started) this.mapLayer.update(); this.needRender = true; } } update(delta, areaSize) { if (!this.visible && !this.attachedToViewer) return; if (this.attachedToViewer) { if (this.mapLayer.needUpdate) { this.updateWhenAtViewer(); } return; } this.updateScreenSize(); this.controls.update(delta); this.view.applyToCamera(this.camera); var changed = this.cameraChanged(); if (this.started && (changed || this.mapLayer.needUpdate)) this.mapLayer.update(); if (changed /*|| || this.needRender */) { /* this.dispatchEvent({ type: "camera_changed", camera: this.camera, viewport : this.viewports[0] }) */ this.mapChanged = true; this.needRender = true; this.updateCursor(); //更改大小 } this.render(); } attachToMainViewer(state, desc) { var mapRatio = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0.5; var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; //转移到viewer中。测量时展示or截图需要 if (!Potree.settings.isOfficial) this.renderArea.style.display = state ? 'none' : 'block'; if (state) { this.enabledOld = this.enabled; this.enabled = true; if (mapRatio != 'dontSet') { this.changeSplitScreenDir(options.dir, mapRatio); if (this.attachedToViewer) { //this.fitPanosToViewport() viewer.updateScreenSize({ forceUpdateSize: true }); return; } viewer.viewports = [viewer.mainViewport, viewer.mapViewer.viewports[0]]; //因为mainViewer的相机变化会触发map的变化,所以先渲染mainViewer } if (desc == 'measure') this.inputHandler.registerInteractiveScene(viewer.measuringTool.scene); //虽然用的是viewer的inputHandler,但借用了this.inputHandler的interactiveScenes else if (desc == 'split4Screens') { this.inputHandler.registerInteractiveScene(viewer.scene.scene); } } else { if (!this.attachedToViewer) return; viewer.mainViewport.left = 0; viewer.mainViewport.bottom = 0; viewer.mainViewport.width = 1; viewer.mainViewport.height = 1; this.viewports[0].width = 1; this.viewports[0].bottom = 0; this.viewports[0].height = 1; this.viewports[0].left = 0; this.renderMeasure || this.inputHandler.unregisterInteractiveScene(viewer.measuringTool.scene); this.inputHandler.unregisterInteractiveScene(viewer.scene.scene); viewer.viewports = [viewer.mainViewport]; this.updateScreenSize({ forceUpdateSize: true }); //更新相机projectionMatrix } //if(desc == 'measure')this.renderMeasure = state this.attachedToViewer = state; viewer.updateScreenSize({ forceUpdateSize: true }); //mapRatio != 'dontSet' && !options.dontFit && this.moveTo(...)//要写在updateScreenSize后面,因为要根据视图大小来fit if (options.moveToCurrentPos) { var boundSize = new Vector2(10, 10); var duration = 1000; this.moveTo(viewer.images360.position.clone(), boundSize, duration); } this.needRender = true; } setDrawMeasure(draw) { this.renderMeasure = !!draw; if (draw) { this.inputHandler.registerInteractiveScene(viewer.measuringTool.scene); } else { this.inputHandler.unregisterInteractiveScene(viewer.measuringTool.scene); } } changeSplitScreenDir(dir, mapRatio) { //左右 | 上下 //if(!dir || dir == this.dir)return if (dir) this.splitDir = dir; this.updateSplitSize(mapRatio); /* if(this.attachedToViewer){ //如果已经分屏了,中途修改方向的话…… this.updateSplitSize() } */ } updateSplitSize(mapRatio) { if (mapRatio != void 0) this.mapRatio = mapRatio; //console.log(this.mapRatio) if (this.splitDir == 'leftRight') { //地图在左方 viewer.mainViewport.left = this.mapRatio; viewer.mainViewport.width = 1 - this.mapRatio; this.viewports[0].width = this.mapRatio; viewer.mainViewport.bottom = this.viewports[0].bottom = 0; viewer.mainViewport.height = this.viewports[0].height = 1; } else if (this.splitDir == 'upDown') { //地图在下方 viewer.mainViewport.bottom = this.mapRatio; viewer.mainViewport.height = 1 - this.mapRatio; this.viewports[0].height = this.mapRatio; viewer.mainViewport.left = this.viewports[0].left = 0; viewer.mainViewport.width = this.viewports[0].width = 1; } if (this.attachedToViewer) { viewer.updateScreenSize({ forceUpdateSize: true }); } } render1() { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; //viewer的preserveDrawingBuffer为false时的版本 var needCopy, waitCopy; if (!this.visible && !this.attachedToViewer || !this.needRender && !params.force) { if (this.attachedToViewer) { needCopy = true; } else { return; } } waitCopy = this.attachedToViewer && this.needRender && !params.force; //是否写入到copyBuffer。双屏时,若needRender就拷贝到copyBuffer中,双屏时就直接使用copyBuffer。 四屏时因渲染点云会每帧都渲染,所以不需要缓存。 var renderer = params.renderer || this.renderer; if (waitCopy) { this.copyBuffer.setSize(params.viewport.resolution2.x, params.viewport.resolution2.y); renderer.setRenderTarget(this.copyBuffer); } else if (params.target) { renderer.setRenderTarget(params.target); } /* if(params.resize){ this.emitResizeMsg(new THREE.Vector2(params.width,params.height, viewport:params.viewport)) } */ params.clear ? params.clear() : renderer.clear(); if (!needCopy || waitCopy) { //重绘 viewer.dispatchEvent({ type: "render.begin", viewer: this, viewport: this.viewports[0], params }); Potree.Utils.setCameraLayers(this.camera, ['map', 'mapObjects', 'bothMapAndScene']); if (this.mapGradientBG) { //渲染背景 viewer.scene.cameraBG.layers.set(Potree.config.renderLayers.bg); renderer.render(viewer.scene.scene, viewer.scene.cameraBG); } renderer.render(this.scene, this.camera); renderer.render(viewer.scene.scene, this.camera); //测量线等 //params.renderOverlay && params.renderOverlay( $.extend({}, params, { isMap:true })) renderer.setRenderTarget(params.target || null); } if (needCopy || waitCopy) { //使用缓存 ----当viewer的preserveDrawingBuffer为false的话,使用buffer this.copyPass.render(null, null, null, renderer, params.target || null, this.copyBuffer); } this.needRender = false; return true; } clear(params) { if (this.transparentBG) { this.renderer.setClearColor(0x000000, 0); } else { this.renderer.setClearColor(Potree.config.mapBG, 1); } (params.renderer || this.renderer).clear(); } //拆成两次渲染,一个地图一个其他物体,且地图渲染后保存在buffer中,只有当地图变化后才重渲染。 render() { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (!this.visible && !this.attachedToViewer || !this.needRender && !params.force) { //注意:mapViewer.needRender的权重高于它的viewport的needRender,也就是说,当attachedToViewer时,viewer即使needRender, mapViewer也不一定会渲染。 return; } viewer.addTimeMark('mapRender', 'start'); var renderer = params.renderer || this.renderer; if (this.mapChanged) { //渲染地图背景 renderer.setRenderTarget(this.copyBuffer); params.clear ? params.clear(params) : this.clear(params); if (this.mapGradientBG) { //渲染背景 viewer.scene.cameraBG.layers.set(Potree.config.renderLayers.bg); renderer.render(viewer.scene.scene, viewer.scene.cameraBG); } Potree.Utils.setCameraLayers(this.camera, ['map']); renderer.render(this.scene, this.camera); params.renderBG && params.renderBG(this.viewports[0]); this.mapChanged = false; renderer.setRenderTarget(params.target || null); } params.clear ? params.clear(params) : this.clear(params); this.copyPass.render(null, null, null, renderer, params.target || null, this.copyBuffer); //拷贝地图背景 renderer.clearDepth(); //防止地图遮挡其他物体 //绘制其他物体 Potree.Utils.setCameraLayers(this.camera, ['mapObjects', 'bothMapAndScene', 'light']); viewer.dispatchEvent({ type: "render.begin", viewer: this, viewport: this.viewports[0], params }); this.attachedToViewer || this.renderCloud || renderer.render(viewer.scene.scene, this.camera); //类同renderOverlay renderer.render(this.scene, this.camera); if (!this.attachedToViewer && this.renderMeasure) { //在未attach到主页面时也要渲染测量线 viewer.dispatchEvent({ type: "render.pass.perspective_overlay", camera: this.camera, viewport: this.viewports[0], renderer }); } renderer.setRenderTarget(null); this.needRender = false; viewer.addTimeMark('mapRender', 'end'); return true; } renderOverlay() { //偶尔需要绘制测量线 viewer.renderOverlay({ camera: this.camera, viewport: this.viewports[0], renderer: this.renderer }); } setRenderCloud() { var _this = this; var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; //使利用viewer的渲染来渲染点云 (如果点云不旋转其实也可以贴floorplan……) this.renderPointcloud = true; this.viewports[0].noPointcloud = false; this.viewports[0].background = 'none'; //防止renderBG绘制skybox var oldMapRender = this.render, oldMapClear = this.clear; var pRenderer = new Renderer$1(this.renderer); //必须重新创建一个点云渲染器,否则和旧的webgl冲突 this.render = function () { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (!_this.visible && !_this.attachedToViewer || !_this.needRender && !params.force) { //注意:mapViewer.needRender的权重高于它的viewport的needRender,也就是说,当attachedToViewer时,viewer即使needRender, mapViewer也不一定会渲染。 return; } if (!options.renderMeasure) { viewer.scene.measurements.forEach(e => Potree.Utils.updateVisible(e, 'renderCloudAtMap', false)); } viewer.renderDefault({ viewports: _this.viewports, camera: _this.camera, renderer: _this.renderer, render: oldMapRender, clear: oldMapClear, pRenderer }); viewer.scene.measurements.forEach(e => Potree.Utils.updateVisible(e, 'renderCloudAtMap', true)); }; } //本来想用mainViewer渲染点云在target上再贴过来的,但是失败了,可能因为不同的renderer不能互通。 /* setRenderCloud(){ this.renderCloud = true this.cloudBuffer = new THREE.WebGLRenderTarget( 300, 200 , { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat, //stencilBuffer: false, }); } */ } /* 渲染顺序: 地图 背景Overlay 地图scene的物体,如cursor、 marker 点云(如果有) overlay,两层:第一层:viewer的scene中bothMapAndScene的如reticule. 第二层:如测量线(attachToMainViewer时才渲染) */ //本地调试地图白屏是因为代码自动更新了 但没刷新 class U { static toVector3(v, offset) { return new Vector3().fromArray(v, offset || 0); } static toBox3(b) { return new Box3(U.toVector3(b), U.toVector3(b, 3)); } static findDim(schema, name) { var dim = schema.find(dim => dim.name == name); if (!dim) throw new Error('Failed to find ' + name + ' in schema'); return dim; } static sphereFrom(b) { return b.getBoundingSphere(new Sphere()); } } ; class PointCloudEptGeometry { constructor(url, info) { var version = info.version; var schema = info.schema; var bounds = info.bounds; var boundsConforming = info.boundsConforming; var xyz = [U.findDim(schema, 'X'), U.findDim(schema, 'Y'), U.findDim(schema, 'Z')]; var scale = xyz.map(d => d.scale || 1); var offset = xyz.map(d => d.offset || 0); this.eptScale = U.toVector3(scale); this.eptOffset = U.toVector3(offset); this.url = url; this.info = info; this.type = 'ept'; this.schema = schema; this.span = info.span || info.ticks; this.boundingBox = U.toBox3(bounds); this.tightBoundingBox = U.toBox3(boundsConforming); this.offset = U.toVector3([0, 0, 0]); this.boundingSphere = U.sphereFrom(this.boundingBox); this.tightBoundingSphere = U.sphereFrom(this.tightBoundingBox); this.version = new Potree.Version('1.7'); this.projection = null; this.fallbackProjection = null; if (info.srs && info.srs.horizontal) { this.projection = info.srs.authority + ':' + info.srs.horizontal; } if (info.srs.wkt) { if (!this.projection) this.projection = info.srs.wkt;else this.fallbackProjection = info.srs.wkt; } { // TODO [mschuetz]: named projections that proj4 can't handle seem to cause problems. // remove them for now try { proj4(this.projection); } catch (e) { this.projection = null; } } { var attributes = new PointAttributes(); attributes.add(PointAttribute.POSITION_CARTESIAN); attributes.add(new PointAttribute("rgba", PointAttributeTypes.DATA_TYPE_UINT8, 4)); attributes.add(new PointAttribute("intensity", PointAttributeTypes.DATA_TYPE_UINT16, 1)); attributes.add(new PointAttribute("classification", PointAttributeTypes.DATA_TYPE_UINT8, 1)); attributes.add(new PointAttribute("gps-time", PointAttributeTypes.DATA_TYPE_DOUBLE, 1)); attributes.add(new PointAttribute("returnNumber", PointAttributeTypes.DATA_TYPE_UINT8, 1)); attributes.add(new PointAttribute("number of returns", PointAttributeTypes.DATA_TYPE_UINT8, 1)); attributes.add(new PointAttribute("return number", PointAttributeTypes.DATA_TYPE_UINT8, 1)); attributes.add(new PointAttribute("source id", PointAttributeTypes.DATA_TYPE_UINT16, 1)); this.pointAttributes = attributes; } this.spacing = (this.boundingBox.max.x - this.boundingBox.min.x) / this.span; var hierarchyType = info.hierarchyType || 'json'; var dataType = info.dataType; if (dataType == 'laszip') { this.loader = new Potree.EptLaszipLoader(); } else if (dataType == 'binary') { this.loader = new Potree.EptBinaryLoader(); } else if (dataType == 'zstandard') { this.loader = new Potree.EptZstandardLoader(); } else { throw new Error('Could not read data type: ' + dataType); } } } ; class EptKey { constructor(ept, b, d, x, y, z) { this.ept = ept; this.b = b; this.d = d; this.x = x || 0; this.y = y || 0; this.z = z || 0; } name() { return this.d + '-' + this.x + '-' + this.y + '-' + this.z; } step(a, b, c) { var min = this.b.min.clone(); var max = this.b.max.clone(); var dst = new Vector3().subVectors(max, min); if (a) min.x += dst.x / 2;else max.x -= dst.x / 2; if (b) min.y += dst.y / 2;else max.y -= dst.y / 2; if (c) min.z += dst.z / 2;else max.z -= dst.z / 2; return new Potree.EptKey(this.ept, new Box3(min, max), this.d + 1, this.x * 2 + a, this.y * 2 + b, this.z * 2 + c); } children() { var result = []; for (var a = 0; a < 2; ++a) { for (var b = 0; b < 2; ++b) { for (var c = 0; c < 2; ++c) { var add = this.step(a, b, c).name(); if (!result.includes(add)) result = result.concat(add); } } } return result; } } class PointCloudEptGeometryNode extends PointCloudTreeNode { constructor(ept, b, d, x, y, z) { super(); this.ept = ept; this.key = new Potree.EptKey(this.ept, b || this.ept.boundingBox, d || 0, x, y, z); this.id = PointCloudEptGeometryNode.IDCount++; this.geometry = null; this.boundingBox = this.key.b; this.tightBoundingBox = this.boundingBox; this.spacing = this.ept.spacing / Math.pow(2, this.key.d); this.boundingSphere = U.sphereFrom(this.boundingBox); // These are set during hierarchy loading. this.hasChildren = false; this.children = {}; this.numPoints = -1; this.level = this.key.d; this.loaded = false; this.loading = false; this.oneTimeDisposeHandlers = []; var k = this.key; this.name = this.toPotreeName(k.d, k.x, k.y, k.z); this.index = parseInt(this.name.charAt(this.name.length - 1)); } isGeometryNode() { return true; } getLevel() { return this.level; } isTreeNode() { return false; } isLoaded() { return this.loaded; } getBoundingSphere() { return this.boundingSphere; } getBoundingBox() { return this.boundingBox; } url() { return this.ept.url + 'ept-data/' + this.filename(); } getNumPoints() { return this.numPoints; } filename() { return this.key.name(); } getChildren() { var children = []; for (var i = 0; i < 8; i++) { if (this.children[i]) { children.push(this.children[i]); } } return children; } addChild(child) { this.children[child.index] = child; child.parent = this; } load() { if (this.loaded || this.loading) return; if (Potree.numNodesLoading >= Potree.maxNodesLoading) return; this.loading = true; ++Potree.numNodesLoading; if (this.numPoints == -1) this.loadHierarchy(); this.loadPoints(); } loadPoints() { this.ept.loader.load(this); } async loadHierarchy() { var nodes = {}; nodes[this.filename()] = this; this.hasChildren = false; var eptHierarchyFile = "".concat(this.ept.url, "ept-hierarchy/").concat(this.filename(), ".json"); var response = await fetch(eptHierarchyFile); var hier = await response.json(); // Since we want to traverse top-down, and 10 comes // lexicographically before 9 (for example), do a deep sort. var keys = Object.keys(hier).sort((a, b) => { var [da, xa, ya, za] = a.split('-').map(n => parseInt(n, 10)); var [db, xb, yb, zb] = b.split('-').map(n => parseInt(n, 10)); if (da < db) return -1; if (da > db) return 1; if (xa < xb) return -1; if (xa > xb) return 1; if (ya < yb) return -1; if (ya > yb) return 1; if (za < zb) return -1; if (za > zb) return 1; return 0; }); keys.forEach(v => { var [d, x, y, z] = v.split('-').map(n => parseInt(n, 10)); var a = x & 1, b = y & 1, c = z & 1; var parentName = d - 1 + '-' + (x >> 1) + '-' + (y >> 1) + '-' + (z >> 1); var parentNode = nodes[parentName]; if (!parentNode) return; parentNode.hasChildren = true; var key = parentNode.key.step(a, b, c); var node = new Potree.PointCloudEptGeometryNode(this.ept, key.b, key.d, key.x, key.y, key.z); node.level = d; node.numPoints = hier[v]; parentNode.addChild(node); nodes[key.name()] = node; }); } doneLoading(bufferGeometry, tightBoundingBox, np, mean) { bufferGeometry.boundingBox = this.boundingBox; this.geometry = bufferGeometry; this.tightBoundingBox = tightBoundingBox; this.numPoints = np; this.mean = mean; this.loaded = true; this.loading = false; --Potree.numNodesLoading; } toPotreeName(d, x, y, z) { var name = 'r'; for (var i = 0; i < d; ++i) { var shift = d - i - 1; var mask = 1 << shift; var step = 0; if (x & mask) step += 4; if (y & mask) step += 2; if (z & mask) step += 1; name += step; } return name; } dispose() { if (this.geometry && this.parent != null) { this.geometry.dispose(); this.geometry = null; this.loaded = false; // this.dispatchEvent( { type: 'dispose' } ); for (var i = 0; i < this.oneTimeDisposeHandlers.length; i++) { var handler = this.oneTimeDisposeHandlers[i]; handler(); } this.oneTimeDisposeHandlers = []; } } } PointCloudEptGeometryNode.IDCount = 0; class ExtendPointCloudOctree extends PointCloudOctree { constructor(geometry, material) { material = material || new ExtendPointCloudMaterial(); super(geometry, material); //xzw move from material 。 adaptive_point_size才使用 /* this.visibleNodesTexture = Utils.generateDataTexture(2048, 1, new THREE.Color(0xffffff)); this.visibleNodesTexture.minFilter = THREE.NearestFilter; this.visibleNodesTexture.magFilter = THREE.NearestFilter; */ this.boundingBox = this.pcoGeometry.tightBoundingBox; //this.pcoGeometry.boundingBox; //boundingBox是正方体,所以换掉 this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere()); this.nodeMaxLevel = 0; //add if (!this.pcoGeometry.loader.version.equalOrHigher('1.5')) { //las 一级一级增长的,但是testNodeMaxLevel时需要大于0 this.nodeMaxLevel = 1; //add } this.maxLevel = Infinity; this.temp = { sizeFitToLevel: {}, opacity: {} }; //add //add this.panos = []; this.matrixAutoUpdate = false; //最好禁止updateMatrix 直接使用matrixWorld this.orientationUser = 0; this.translateUser = new Vector3(); this.rotateMatrix = new Matrix4(); this.transformMatrix = new Matrix4(); // 数据集的变化矩阵 this.transformInvMatrix = new Matrix4(); /* this.transformMatrix2 = new THREE.Matrix4;// 数据集的变化矩阵 this.transformInvMatrix2 = new THREE.Matrix4; */ this.rotateInvMatrix = new Matrix4(); this.material.spacing = this.pcoGeometry.spacing; //初始化一下 以便于设置pointsize this.nodeMaxLevelPredict = this.predictNodeMaxLevel(); //预测maxNodeLevel this.testMaxNodeCount = this.testMaxNodeCount2 = 0; this._visible = true; this.pcoGeometry.addEventListener('updateNodeMaxLevel', this.updateNodeMaxLevel.bind(this)); this.isPointcloud = true; //add } /* 注释:node的level从最大的box 0开始。 且加载任意一个node必定也会加载它的所有祖先。(如visibleNodes中有一个level为4,则一定有3,2,1,0) visibleNodes就是所有可见的node,比如: 如果相机在0这个位置朝下,这时候的visibleNodes中只有一个level为0的node; 而如果朝上看,上方的几个node如果在视野中占据足够大的位置的话,就会加载。 如果相机在2这个位置朝上,这时候的visibleNodes中所包含的level为: 0,1,2 ________________ | | | | |__2| | | | 1 | 1 | |_______|_______| | | | | | 0 | |_______________| 查看box可在potree中开启 */ updateNodeMaxLevel(e) { //目前点云包含node的最高level var level = Math.max(e.level, this.nodeMaxLevel); if (level != this.nodeMaxLevel) { this.nodeMaxLevel = level; //viewer.dispatchEvent({type:'updateNodeMaxLevel', pointcloud: this, nodeMaxLevel:level}) Potree.settings.isOfficial || console.log('updateNodeMaxLevel ' + this.dataset_id + " : " + this.nodeMaxLevel); setTimeout(() => { this.setPointLevel(); //重新计算 延迟是因为testNodeMax会变回旧的 }, 1); if (!Potree.settings.sizeFitToLevel) { this.changePointSize(); } } } //注:在没有加载到真实的 nodeMaxLevel之前,点云会显示得偏大 //panoEdit时比预测值小很多? testMaxNodeLevel(camera) { //手动使maxLevel达到最高,从而迫使updateNodeMaxLevel。 因为Potree.settings.pointDensity 不为 'high'时,maxLevel不是所加载的最高,就很容易加载不出下一个层级,导致无法知道nodeMaxLevel if (this.testMaxNodeLevelDone) return; //if(this.nodeMaxLevel > this.nodeMaxLevelPredict.min )return if (this.nodeMaxLevel == 0) return true; if (camera.type == "OrthographicCamera" || this.testMaxNodeCount < 50) { if (!Potree.Utils.isInsideFrustum(this.bound, camera)) { return true; } } else if (!viewer.atDatasets.includes(this)) return true; //否则老远就count++ var levels = this.visibleNodes.map(e => e.getLevel()); var actMaxLevel = Math.max.apply(null, levels); //实际加载到的最高的node level if (actMaxLevel < this.maxLevel) return true; // 还没加载到能加载到的最高。 但在细节设置较低时,排除作用微弱。 //尝试加载出更高级的level var old = this.maxLevel; this.maxLevel = 12; //var visibleNodes1 = this.visibleNodes.map(e=>e.getLevel()) //console.log('visibleNodes1',visibleNodes1) Potree.updatePointClouds([this], viewer.scene.getActiveCamera(), viewer.mainViewport.resolution); //不在camera可视范围内还是加载不出来。即使临时修改位置 var visibleNodes2 = this.visibleNodes.map(e => e.getLevel()); //console.log('visibleNodes2',visibleNodes2) this.maxLevel = old; this.testMaxNodeCount++; viewer.testMaxNodeCount++; //console.log('testMaxNodeCount', this.dataset_id, this.testMaxNodeCount, 'nodeMaxLevel', this.nodeMaxLevel ) if (this.testMaxNodeCount == Potree.config.testNodeCount1) { //差不多等当前所在数据集nodeMaxLevel加载出来 this.changePointSize(); //重新更新一下大小。因之前用的是nodeMaxLevelPredict (防止刚开始因nodeMaxLevel没涨完,导致过大的点云突然出现 } if (this.testMaxNodeCount > 100) { console.log('testMaxNodeLevel次数超出,强制结束:', this.dataset_id, this.nodeMaxLevel, this.nodeMaxLevelPredict.min); this.testMaxNodeLevelDone = 'moreThanMaxCount'; return; //在可以看见点云的情况下,超时,有可能是预测的max是错的 } if (this.nodeMaxLevel < this.nodeMaxLevelPredict.min) return true; //仍需要继续testMaxNodeLevel this.testMaxNodeCount2++; // 已经> this.nodeMaxLevelPredict.min 后,开始计数。因为min可能低于真实nodeMaxLevel所以要再试几次 if (this.testMaxNodeCount2 < 50) return true; //再试几次 ( 主要是细节调得低时需要多测几次才加载到 this.testMaxNodeLevelDone = true; } updateMatrixWorld(force) { //add super.updateMatrixWorld(force); this.matrixWorldInverse = this.matrixWorld.clone().invert(); } setPointLevel() { var pointDensity = Potree.settings.pointDensity; var config = Potree.config.pointDensity[pointDensity]; if (!config) return; /* if(this.testingMaxLevel){ this.maxLevel = 12;//先加载到最大的直到测试完毕。由于5个level为一组来加载,所以如果写4最高能加载到5,如果写5最高能加载到下一个级别的最高也就是10 //console.log('maxLevel: '+e.maxLevel + ' testingMaxLevel中 ' ) }else{ */ var percent = config.percentByUser && Potree.settings.UserDensityPercent != void 0 ? Potree.settings.UserDensityPercent : config.maxLevelPercent; this.maxLevel = Math.round(percent * this.nodeMaxLevel); //console.log('maxLevel: '+e.maxLevel + ', density : '+Potree.settings.pointDensity, ", percent :"+percent); if (Potree.settings.sizeFitToLevel) { this.changePointSize(); } this.changePointOpacity(); //} viewer.dealBeforeRender || viewer.dispatchEvent('content_changed'); } //预测可能的nodeMaxLevel: predictNodeMaxLevel() { //预测maxNodeLevel。 可能只适用于我们相机拍的点云 var spacing = { min: 0.005, max: 0.014 }; //最小节的两点间的距离 ,获得方法:spacing / Math.pow(2, nodeMaxLevel)。 目前观测的我们自己拍的这个数值的范围大概是这样 var min = Math.log2(this.material.spacing / spacing.max); //有见过最大是0.01368 var max = Math.log2(this.material.spacing / spacing.min); //大部分是 0.006 //console.log('predictNodeMaxLevel:', this.name , min, max ) //只对深时相机,其他相机不准 return { min, max }; } getHighestNodeSpacing() { return this.material.spacing / Math.pow(2, this.nodeMaxLevel); //前提是这个nodeMaxLevel是准确的 } updateMaterial(material, visibleNodes, camera, renderer, resolution) { //改 material.fov = camera.fov * (Math.PI / 180); /* material.screenWidth = renderer.domElement.clientWidth; material.screenHeight = renderer.domElement.clientHeight; */ material.resolution = resolution; material.spacing = this.pcoGeometry.spacing; // * Math.max(this.scale.x, this.scale.y, this.scale.z); material.near = camera.near; material.far = camera.far; material.uniforms.octreeSize.value = this.pcoGeometry.boundingBox.getSize(new Vector3()).x; } pick(viewer, viewport, camera, ray) { var params = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; //改 var renderer = viewer.renderer; var pRenderer = viewer.pRenderer; viewer.addTimeMark('pick', 'start'); var getVal = (a, b) => a != void 0 ? a : b; var pickWindowSize = params.pickWindowSize; //拾取像素边长,越小越精准,但点云稀疏的话可能容易出现识别不到的情况。 另外左下侧会有缝隙无法识别到,缝隙大小和这个值有关//突然发现pickWindowSize在一百以内的变化对pick费时影响甚微,1和100差1毫秒不到,但400时会多4毫秒 if (pickWindowSize == void 0) { if (Potree.settings.displayMode == 'showPanos') { pickWindowSize = 50; } else { var r0 = this.nodeMaxLevel > 0 ? this.maxLevel / this.nodeMaxLevel : 0.5; pickWindowSize = MathUtils.clamp(Math.round((1.1 - r0) * 80), 15, 100); } } if (camera.type == 'OrthographicCamera') { var cameraDir = new Vector3(0, 0, -1).applyQuaternion(camera.quaternion); pickWindowSize *= 4; //pointsize比较大时截取太小会没多少点可以选 } var pickOutsideClipRegion = getVal(params.pickOutsideClipRegion, false); var size = viewport ? viewport.resolution : renderer.getSize(new Vector2()); var width = Math.ceil(getVal(params.width, size.width)); //renderTarget大小。影响识别精度 var height = Math.ceil(getVal(params.height, size.height)); var screenshot = () => { if (window.testScreen) { var dataUrl = Potree.Utils.renderTargetToDataUrl(pickState.renderTarget, width, height, renderer); Potree.Common.downloadFile(dataUrl, 'screenshot.png'); window.testScreen = 0; } }; var pointSizeType = getVal(params.pointSizeType, this.material.pointSizeType); var pointSize = getVal(params.pointSize, this.material.size); var nodes = this.nodesOnRay(this.visibleNodes, ray); if (nodes.length === 0) { return null; } //console.log('nodes.length != 0', this.name) if (!this.pickState) { var scene = new Scene(); var material = new ExtendPointCloudMaterial(); material.activeAttributeName = "indices"; //indices var renderTarget = new WebGLRenderTarget(1, 1, { minFilter: LinearFilter, magFilter: NearestFilter, format: RGBAFormat }); this.pickState = { renderTarget: renderTarget, material: material, scene: scene }; } ; var pickState = this.pickState; var pickMaterial = pickState.material; { // update pick material pickMaterial.pointSizeType = pointSizeType; //pickMaterial.shape = this.material.shape; pickMaterial.shape = Potree.PointShape.PARABOLOID; pickMaterial.uniforms.uFilterReturnNumberRange.value = this.material.uniforms.uFilterReturnNumberRange.value; pickMaterial.uniforms.uFilterNumberOfReturnsRange.value = this.material.uniforms.uFilterNumberOfReturnsRange.value; pickMaterial.uniforms.uFilterGPSTimeClipRange.value = this.material.uniforms.uFilterGPSTimeClipRange.value; pickMaterial.uniforms.uFilterPointSourceIDClipRange.value = this.material.uniforms.uFilterPointSourceIDClipRange.value; pickMaterial.size = pointSize; pickMaterial.uniforms.minSize.value = this.material.uniforms.minSize.value; pickMaterial.uniforms.maxSize.value = this.material.uniforms.maxSize.value; pickMaterial.classification = this.material.classification; pickMaterial.recomputeClassification(); //pickClipped判断转移到上一层函数 var { bigClipInBox, clipBoxes_in, clipBoxes_out } = this.material; pickMaterial.setClipBoxes(bigClipInBox, clipBoxes_in, clipBoxes_out, []); this.updateMaterial(pickMaterial, nodes, camera, renderer, new Vector2(width, height)); } pickState.renderTarget.setSize(width, height); //仅绘制屏幕大小的,而不乘以devicePixelRatio var pixelPos = new Vector2(params.x, params.y); var gl = renderer.getContext(); //规定渲染范围,只渲染一小块 /* renderer.setScissorTest(true); gl.enable(gl.SCISSOR_TEST); gl.scissor( parseInt(pixelPos.x - (pickWindowSize - 1) / 2), parseInt(pixelPos.y - (pickWindowSize - 1) / 2), parseInt(pickWindowSize), parseInt(pickWindowSize)); */ //---这段没用 pickState.renderTarget.scissor.set(parseInt(pixelPos.x - (pickWindowSize - 1) / 2), parseInt(pixelPos.y - (pickWindowSize - 1) / 2), parseInt(pickWindowSize), parseInt(pickWindowSize)); pickState.renderTarget.scissorTest = true; renderer.state.buffers.depth.setTest(pickMaterial.depthTest); renderer.state.buffers.depth.setMask(pickMaterial.depthWrite); renderer.state.setBlending(NoBlending); { // RENDER renderer.setRenderTarget(pickState.renderTarget); gl.clearColor(0, 0, 0, 0); //renderer.clear(true, true, true); var tmp = this.material; this.material = pickMaterial; pRenderer.renderOctree(this, nodes, camera, pickState.renderTarget); //只绘制ray pick到的部分nodes screenshot(); this.material = tmp; } var clamp = (number, min, max) => Math.min(Math.max(min, number), max); var x = parseInt(clamp(pixelPos.x - (pickWindowSize - 1) / 2, 0, width)); var y = parseInt(clamp(pixelPos.y - (pickWindowSize - 1) / 2, 0, height)); /* let w = parseInt(Math.min(x + pickWindowSize, width) - x); let h = parseInt(Math.min(y + pickWindowSize, height) - y); */ var pixelCount = pickWindowSize * pickWindowSize; //w * h; var buffer = new Uint8Array(4 * pixelCount); //w 0) { //最后选取的是最靠近鼠标的那个pick if (distance < hits[0].distanceToCenter) { hits[0] = hit; } } else { hits.push(hit); } if (distance < rSquare) hits2.push(hit); //add } } } } if (!params.all && Potree.settings.pickFrontPointRatio) { if (hits2.length) { //add hits = hits2; } } // { // DEBUG: show panel with pick image // let img = Utils.pixelsArrayToImage(buffer, w, h); // let screenshot = img.src; // if(!this.debugDIV){ // this.debugDIV = $(` //
`); // $(document.body).append(this.debugDIV); // } // this.debugDIV.empty(); // this.debugDIV.append($(``)); // //$(this.debugWindow.document).append($(``)); // //this.debugWindow.document.write(''); // } for (var _hit of hits) { var point = {}; if (!nodes[_hit.pcIndex]) { return null; } var node = nodes[_hit.pcIndex]; var pc = node.sceneNode; var geometry = node.geometryNode.geometry; var _loop = function _loop() { var attribute = geometry.attributes[attributeName]; if (attributeName === 'position') { var _x = attribute.array[3 * _hit.pIndex + 0]; var _y = attribute.array[3 * _hit.pIndex + 1]; var z = attribute.array[3 * _hit.pIndex + 2]; var position = new Vector3(_x, _y, z); position.applyMatrix4(pc.matrixWorld); point[attributeName] = position; //add if (!params.all && Potree.settings.pickFrontPointRatio) { if (camera.type == 'OrthographicCamera') { var vec = new Vector3().subVectors(position, camera.position); _hit.disSquare = vec.projectOnVector(cameraDir).length(); //只考虑到相机的垂直距离 } else { _hit.disSquare = camera.position.distanceTo(position); } } } else if (attributeName === 'indices') {} else { var values = attribute.array.slice(attribute.itemSize * _hit.pIndex, attribute.itemSize * (_hit.pIndex + 1)); if (attribute.potree) { var { scale, offset: _offset } = attribute.potree; values = values.map(v => v / scale + _offset); } point[attributeName] = values; //debugger; //if (values.itemSize === 1) { // point[attribute.name] = values.array[hit.pIndex]; //} else { // let value = []; // for (let j = 0; j < values.itemSize; j++) { // value.push(values.array[values.itemSize * hit.pIndex + j]); // } // point[attribute.name] = value; //} } }; for (var attributeName in geometry.attributes) { _loop(); } _hit.point = point; } viewer.addTimeMark('pick', 'end'); if (params.all) { return hits.map(hit => hit.point); } else { if (hits.length === 0) { return null; } else { if (Potree.settings.pickFrontPointRatio == 0) { //如果不需要选偏离镜头近的,就要离中心近的即可 //console.log(hits[0], hits2, pixelPos) return hits[0].point; } //为了防止透过点云缝隙,选到后排的点云,将选取的位置离相机的距离考虑进去。倾向选择离相机近、且离鼠标位置近的点。(否则按照原方案只选离鼠标位置最近的,可能从高楼不小心走到下层,导航选点也是) var sorted1 = hits.sort((a, b) => a.disSquare - b.disSquare).slice(); var nearest = sorted1[0]; //return nearest.point; //直接用最近点 在点云稀疏时不太跟手,如地面上,最近点往往在鼠标下方 hits.forEach(hit => { var disDiff = hit.disSquare - nearest.disSquare; //和最近点的偏差 hit.disDiff = disDiff; hit.score = -hit.distanceToCenter - disDiff * Potree.settings.pickFrontPointRatio; }); var sorted2 = hits.sort((a, b) => b.score - a.score); //console.log(sorted2[0].point.position.z ) return sorted2[0].point; } } } // 设置点大小 changePointSize(num, sizeFitToLevel) { var size, nodeMaxLevel; var dontRender = viewer.dealBeforeRender; if (this.material.pointSizeType != PointSizeType.ATTENUATED) { num && (size = num / Potree.config.material.realPointSize / 1.3); } else { var num_ = num; if (num_ == void 0) { num_ = this.temp.pointSize; } else { this.temp.pointSize = num_; } num_ = num_ / (Potree.config.material.realPointSize / Potree.config.material.pointSize); //兼容 //num_ = Math.pow(num_, 1.05) * 5 nodeMaxLevel = this.testMaxNodeCount >= Potree.config.testNodeCount1 ? this.nodeMaxLevel : Math.max(this.nodeMaxLevel, this.nodeMaxLevelPredict.max); //防止刚开始因nodeMaxLevel没涨完,导致过大的点云突然出现 if (sizeFitToLevel || Potree.settings.sizeFitToLevel) { //按照点云质量来调整的版本: 近似将pointSizeType换成ADAPTIVE var str = this.temp.pointSize + ':' + this.maxLevel + ':' + nodeMaxLevel; var value = this.temp.sizeFitToLevel[str]; //储存。防止每次渲染(反复切换density)都要算。 if (value) { size = value; } else { if (this.maxLevel == Infinity) return; var base = this.material.spacing / Math.pow(2, this.maxLevel); //点云大小在level为0时设置为spacing,每长一级,大小就除以2. (不同场景还是会有偏差) var r = nodeMaxLevel > 0 ? this.maxLevel / nodeMaxLevel : 0.5; //越大,越精细,需要越缩小 base *= nodeMaxLevel > 0 ? Math.max(0.1, Math.pow(r, 3 * r + 0.3)) : 0.1; //低质量的缩小点,因为视觉上看太大了。navvis是不铺满的,我们也留一点缝隙(但是ortho是不用缩小的,如果能分开判断就好了) //base *= nodeMaxLevel > 0 ? Math.max(0.1, Math.pow(this.maxLevel / nodeMaxLevel, 1.1)) : 0.1 //低质量的缩小点,因为视觉上看太大了。navvis是不铺满的,我们也留一点缝隙(但是ortho是不用缩小的,如果能分开判断就好了) size = base * 20 * num_; /* * window.devicePixelRatio */ //在t-8BCqxQAr93 会议室 和 t-e2Kb2iU 隧道 两个场景里调节,因为它们的spacing相差较大,观察会议室墙壁的龟裂程度 this.temp.sizeFitToLevel[str] = size; } } else { var _base = 0.015; //2024.8.21 又要求需要不同场景点云大小相同,所以只能固定值了 (正式环境这两个场景 SG-5yxFuWhEMlg SG-XZNyvCDk0jz) //let base = this.material.spacing / Math.pow(2, nodeMaxLevel) //在保证最高级别大小刚好的情况下,不改变level降低后的大小 //base的数值理论上应该是右侧算出来的,但发现有的场景nodeMaxLevel和nodeMaxLevelPredict差别较大的点云显示也过大,而直接换成固定值反而可以适应所有场景。该固定值来源于 getHighestNodeSpacing 最小值,修改了下。(会不会是我们的相机其实该值是固定的,根据该值算出的spacing才是有误差的? 如果换了相机是否要改值?) //2022-12-21又换回非固定值。因为有的场景如SS-t-t01myDqnfE的两个数据集密集程度差别很大,应该将稀疏点云的大小设置的大些。 但是这样的缺点是两个数据集因相接处有大有小无法融合。 size = _base * 20 * num_; } //不同数据集点云最高级别时的间距不同,但不知道如何计算, 级别越高点云越密,spacing越大初始级别越密。 但实际并非2的level次方,底数可能1-2之间 } //console.log('changePointSize:' + this.dataset_id + ' , num: ' + (num && num.toPrecision(3)) + ' , size: ' + size.toPrecision(3), 'nodeMaxLevel', nodeMaxLevel.toPrecision(3), 'testMaxNodeCount',this.testMaxNodeCount /* this.material.spacing */) if (size) { if (Potree.settings.sortCloudMat) { //被废弃,不给material分组了 this.size = size; this.material.size = size; } else { this.material.size = size; } } dontRender || viewer.dispatchEvent('content_changed'); } // 设置点透明度 changePointOpacity(num, canMoreThanOne) { //num:0-1 navvis用的是亮度 if (num == void 0) { num = this.temp.pointOpacity; } else { this.temp.pointOpacity = num; } var dontRender = viewer.dealBeforeRender; //在执行beforeRender时更改的话不要发送content_changed 尤其分屏 if (Potree.settings.notAdditiveBlending) { return this.material.opacity = num; } var opacity; if (num == 1) { opacity = 1; } else { var str = (Potree.settings.sizeFitToLevel ? 'sizeFit:' : '') + (canMoreThanOne ? 'canMoreThanOne:' : '') + this.temp.pointOpacity + ':' + this.maxLevel + ':' + this.nodeMaxLevel; var value = this.temp.opacity[str]; //储存。防止每次渲染(反复切换density)都要算。 if (value) { opacity = value; } else { if (Potree.settings.sizeFitToLevel) { //按照点云质量来调整的版本: var base = this.material.spacing / Math.pow(1.7, this.maxLevel); //随着level提高,点云重叠几率增多 var minBase = this.material.spacing / Math.pow(1.7, this.nodeMaxLevel); var ratio = Math.min(1 / base, 1 / minBase / 3); //ratio为一个能使opacity不大于1 的 乘量,minBase要除以一个数,该数调越大减弱效果越强。level越低opacity和面板越接,level越高效果越弱,以减免过度重叠后的亮度。 opacity = base * ratio * num; if (!canMoreThanOne) { opacity = MathUtils.clamp(opacity, 0, 0.999); //到1就不透明了(可能出现一段一样) } } else { var _base2 = this.material.spacing / Math.pow(2, this.maxLevel); var _minBase = this.material.spacing / Math.pow(2, this.nodeMaxLevel); //console.log(1 / base, 1 / minBase / 6) var _ratio = Math.min(1 / _base2, 1 / _minBase / 3); //ratio为一个能使opacity不大于1 的 乘量,minBase要除以一个数,该数调越大减弱效果越强。level越低opacity和面板越接,level越高效果越弱,以减免过度重叠后的亮度。 opacity = _base2 * _ratio * num; if (!canMoreThanOne) { opacity = MathUtils.clamp(opacity, 0, 0.999); //到1就不透明了(可能出现一段一样) } } this.temp.opacity[str] = opacity; } //缺点:防止颜色过亮主要是相机离远时,当在漫游点处由于离点云太近,可能会导致高质量点云看起来很暗。 } //console.log('changePointOpacity ' + this.dataset_id + ', num : ' + num + ' , opacity : ' + this.material.opacity) //检查是否做到了低质量时num==opacity,中质量opacity稍小于num,高质量更小 if (Potree.settings.sortCloudMat) { this.opacity = opacity; this.material.opacity = opacity; } else { this.material.opacity = opacity; } dontRender || viewer.dispatchEvent('content_changed'); } updateBound() { var boundingBox_ = this.pcoGeometry.tightBoundingBox.clone().applyMatrix4(this.matrixWorld); //tightBoundingBox是点云原始的bound,但经过(绕z)旋转后bound有所改变,比之前体积更大。 this.bound = boundingBox_; this.bound2 = this.getBoundWithPanos(); } getBoundWithPanos() { //确保panoBound在内的bound var bound = this.bound.clone(); this.panos.forEach(pano => { var panoBound = new Box3(); panoBound.expandByPoint(pano.position); panoBound.expandByVector(new Vector3(1, 1, 1)); //give pano a margin bound.union(panoBound); }); return bound; } getPanosBound() { //仅由所有pano构成的bound if (this.panos.length > 0) { var minSize = new Vector3(1, 1, 1); this.panosBound = math.getBoundByPoints(this.panos.map(e => e.position), minSize); } else { this.panosBound = null; } } getUnrotBoundPoint(type) { //获取没有旋转的tightBounding的水平四个点 //如果alighment支持任意轴旋转,水平面上看到的可能就是六边形了,失去意义,到时候不能用这个。也可以若只绕z旋转, 使用tightBoundingBox,否则bound var bound = this.pcoGeometry.tightBoundingBox; if (type == 'all') { return [new Vector3(bound.min.x, bound.min.y, bound.min.z), new Vector3(bound.max.x, bound.min.y, bound.min.z), new Vector3(bound.max.x, bound.max.y, bound.min.z), new Vector3(bound.min.x, bound.max.y, bound.min.z), new Vector3(bound.min.x, bound.min.y, bound.max.z), new Vector3(bound.max.x, bound.min.y, bound.max.z), new Vector3(bound.max.x, bound.max.y, bound.max.z), new Vector3(bound.min.x, bound.max.y, bound.max.z)].map(e => e.applyMatrix4(this.matrixWorld)); } else return [new Vector3(bound.min.x, bound.min.y, 0), new Vector3(bound.max.x, bound.min.y, 0), new Vector3(bound.max.x, bound.max.y, 0), new Vector3(bound.min.x, bound.max.y, 0)].map(e => e.applyMatrix4(this.matrixWorld)); } getVolume() { /* var points = this.getUnrotBoundPoint() -----在只绕z轴旋转时这么写也行 var area = Math.abs(math.getArea(points)) return area * (this.bound.max.z - this.bound.min.z) */ var bound = this.pcoGeometry.tightBoundingBox.clone(); var size = bound.getSize(new Vector3()); return size.x * size.y * size.z; } ifContainsPoint(pos) { //pos是否坐落于tightBound内 /* if(!this.bound || !this.bound.containsPoint(pos))return ---这样写也行 var points = this.getUnrotBoundPoint() return math.isPointInArea(points, null, pos) */ //要把tightBoundingBox想象成一个volumeBox var box = this.pcoGeometry.tightBoundingBox; var center = box.getCenter(new Vector3()); var size = box.getSize(new Vector3()); var boxMatrix = new Matrix4().setPosition(center.x, center.y, center.z); boxMatrix.scale(size); boxMatrix.premultiply(this.matrixWorld); return Potree.Utils.isIntersectBox(pos, boxMatrix); } intersectBox(boxWorldMatrix) { var boxM = boxWorldMatrix.clone().premultiply(this.matrixWorld.clone().invert()); //box乘上点云逆矩阵 (因为点云的忽略掉其matrixWorld, 为了保持相对位置不变,box要左乘matrixWorld的逆)(因第一个参数bound不好变形,第二个参数box可以) return Potree.Utils.isIntersectBox(this.pcoGeometry.tightBoundingBox, boxM); } } class ProfileData { constructor(profile) { this.profile = profile; this.segments = []; this.boundingBox = new Box3(); for (var i = 0; i < profile.points.length - 1; i++) { var start = profile.points[i]; var end = profile.points[i + 1]; var startGround = new Vector3(start.x, start.y, 0); var endGround = new Vector3(end.x, end.y, 0); var center = new Vector3().addVectors(endGround, startGround).multiplyScalar(0.5); var length = startGround.distanceTo(endGround); var side = new Vector3().subVectors(endGround, startGround).normalize(); var up = new Vector3(0, 0, 1); var forward = new Vector3().crossVectors(side, up).normalize(); var N = forward; var cutPlane = new Plane().setFromNormalAndCoplanarPoint(N, startGround); var halfPlane = new Plane().setFromNormalAndCoplanarPoint(side, center); var segment = { start: start, end: end, cutPlane: cutPlane, halfPlane: halfPlane, length: length, points: new Points$1() }; this.segments.push(segment); } } size() { var size = 0; for (var segment of this.segments) { size += segment.points.numPoints; } return size; } } ; class ProfileRequest { constructor(pointcloud, profile, maxDepth, callback) { this.pointcloud = pointcloud; this.profile = profile; this.maxDepth = maxDepth || Number.MAX_VALUE; this.callback = callback; this.temporaryResult = new ProfileData(this.profile); this.pointsServed = 0; this.highestLevelServed = 0; this.priorityQueue = new BinaryHeap(function (x) { return 1 / x.weight; }); this.initialize(); } initialize() { this.priorityQueue.push({ node: this.pointcloud.pcoGeometry.root, weight: Infinity }); } // traverse the node and add intersecting descendants to queue traverse(node) { var stack = []; for (var i = 0; i < 8; i++) { var child = node.children[i]; if (child && this.pointcloud.nodeIntersectsProfile(child, this.profile)) { stack.push(child); } } while (stack.length > 0) { var _node = stack.pop(); var weight = _node.boundingSphere.radius; this.priorityQueue.push({ node: _node, weight: weight }); // add children that intersect the cutting plane if (_node.level < this.maxDepth) { for (var _i = 0; _i < 8; _i++) { var _child = _node.children[_i]; if (_child && this.pointcloud.nodeIntersectsProfile(_child, this.profile)) { stack.push(_child); } } } } } update() { if (!this.updateGeneratorInstance) { this.updateGeneratorInstance = this.updateGenerator(); } var result = this.updateGeneratorInstance.next(); if (result.done) { this.updateGeneratorInstance = null; } } *updateGenerator() { // load nodes in queue // if hierarchy expands, also load nodes from expanded hierarchy // once loaded, add data to this.points and remove node from queue // only evaluate 1-50 nodes per frame to maintain responsiveness var start = performance.now(); var maxNodesPerUpdate = 1; var intersectedNodes = []; for (var i = 0; i < Math.min(maxNodesPerUpdate, this.priorityQueue.size()); i++) { var element = this.priorityQueue.pop(); var node = element.node; if (node.level > this.maxDepth) { continue; } if (node.loaded) { // add points to result intersectedNodes.push(node); exports.lru.touch(node); this.highestLevelServed = Math.max(node.getLevel(), this.highestLevelServed); var geom = node.pcoGeometry; var hierarchyStepSize = geom ? geom.hierarchyStepSize : 1; var doTraverse = node.getLevel() === 0 || node.level % hierarchyStepSize === 0 && node.hasChildren; if (doTraverse) { this.traverse(node); } } else { node.load(); this.priorityQueue.push(element); } } if (intersectedNodes.length > 0) { for (var done of this.getPointsInsideProfile(intersectedNodes, this.temporaryResult)) { if (!done) { //console.log("updateGenerator yields"); yield false; } } if (this.temporaryResult.size() > 100) { this.pointsServed += this.temporaryResult.size(); this.callback.onProgress({ request: this, points: this.temporaryResult }); this.temporaryResult = new ProfileData(this.profile); } } if (this.priorityQueue.size() === 0) { // we're done! inform callback and remove from pending requests if (this.temporaryResult.size() > 0) { this.pointsServed += this.temporaryResult.size(); this.callback.onProgress({ request: this, points: this.temporaryResult }); this.temporaryResult = new ProfileData(this.profile); } this.callback.onFinish({ request: this }); var index = this.pointcloud.profileRequests.indexOf(this); if (index >= 0) { this.pointcloud.profileRequests.splice(index, 1); } } yield true; } *getAccepted(numPoints, node, matrix, segment, segmentDir, points, totalMileage) { var checkpoint = performance.now(); var accepted = new Uint32Array(numPoints); var mileage = new Float64Array(numPoints); var acceptedPositions = new Float32Array(numPoints * 3); var numAccepted = 0; var pos = new Vector3(); var svp = new Vector3(); var view = new Float32Array(node.geometry.attributes.position.array); for (var i = 0; i < numPoints; i++) { pos.set(view[i * 3 + 0], view[i * 3 + 1], view[i * 3 + 2]); pos.applyMatrix4(matrix); var distance = Math.abs(segment.cutPlane.distanceToPoint(pos)); var centerDistance = Math.abs(segment.halfPlane.distanceToPoint(pos)); if (distance < this.profile.width / 2 && centerDistance < segment.length / 2) { svp.subVectors(pos, segment.start); var localMileage = segmentDir.dot(svp); accepted[numAccepted] = i; mileage[numAccepted] = localMileage + totalMileage; points.boundingBox.expandByPoint(pos); pos.sub(this.pointcloud.position); acceptedPositions[3 * numAccepted + 0] = pos.x; acceptedPositions[3 * numAccepted + 1] = pos.y; acceptedPositions[3 * numAccepted + 2] = pos.z; numAccepted++; } if (i % 1000 === 0) { var duration = performance.now() - checkpoint; if (duration > 4) { //console.log(`getAccepted yield after ${duration}ms`); yield false; checkpoint = performance.now(); } } } accepted = accepted.subarray(0, numAccepted); mileage = mileage.subarray(0, numAccepted); acceptedPositions = acceptedPositions.subarray(0, numAccepted * 3); //let end = performance.now(); //let duration = end - start; //console.log("accepted duration ", duration) //console.log(`getAccepted finished`); yield [accepted, mileage, acceptedPositions]; } *getPointsInsideProfile(nodes, target) { var checkpoint = performance.now(); var totalMileage = 0; var pointsProcessed = 0; for (var segment of target.segments) { for (var node of nodes) { var numPoints = node.numPoints; var geometry = node.geometry; if (!numPoints) { continue; } { // skip if current node doesn't intersect current segment var bbWorld = node.boundingBox.clone().applyMatrix4(this.pointcloud.matrixWorld); var bsWorld = bbWorld.getBoundingSphere(new Sphere()); var start = new Vector3(segment.start.x, segment.start.y, bsWorld.center.z); var end = new Vector3(segment.end.x, segment.end.y, bsWorld.center.z); var closest = new Line3(start, end).closestPointToPoint(bsWorld.center, true, new Vector3()); var distance = closest.distanceTo(bsWorld.center); var intersects = distance < bsWorld.radius + target.profile.width; if (!intersects) { continue; } } //{// DEBUG // console.log(node.name); // let boxHelper = new Potree.Box3Helper(node.getBoundingBox()); // boxHelper.matrixAutoUpdate = false; // boxHelper.matrix.copy(viewer.scene.pointclouds[0].matrixWorld); // viewer.scene.scene.add(boxHelper); //} var sv = new Vector3().subVectors(segment.end, segment.start).setZ(0); var segmentDir = sv.clone().normalize(); var points = new Points$1(); var nodeMatrix = new Matrix4().makeTranslation(...node.boundingBox.min.toArray()); var matrix = new Matrix4().multiplyMatrices(this.pointcloud.matrixWorld, nodeMatrix); pointsProcessed = pointsProcessed + numPoints; var accepted = null; var mileage = null; var acceptedPositions = null; for (var result of this.getAccepted(numPoints, node, matrix, segment, segmentDir, points, totalMileage)) { if (!result) { var _duration = performance.now() - checkpoint; //console.log(`getPointsInsideProfile yield after ${duration}ms`); yield false; checkpoint = performance.now(); } else { [accepted, mileage, acceptedPositions] = result; } } var duration = performance.now() - checkpoint; if (duration > 4) { //console.log(`getPointsInsideProfile yield after ${duration}ms`); yield false; checkpoint = performance.now(); } points.data.position = acceptedPositions; var relevantAttributes = Object.keys(geometry.attributes).filter(a => !["position", "indices"].includes(a)); for (var attributeName of relevantAttributes) { var attribute = geometry.attributes[attributeName]; var numElements = attribute.array.length / numPoints; if (numElements !== parseInt(numElements)) { debugger; } var Type = attribute.array.constructor; var filteredBuffer = new Type(numElements * accepted.length); var source = attribute.array; var _target = filteredBuffer; for (var i = 0; i < accepted.length; i++) { var index = accepted[i]; var _start = index * numElements; var _end = _start + numElements; var sub = source.subarray(_start, _end); _target.set(sub, i * numElements); } points.data[attributeName] = filteredBuffer; } points.data['mileage'] = mileage; points.numPoints = accepted.length; segment.points.add(points); } totalMileage += segment.length; } for (var _segment of target.segments) { target.boundingBox.union(_segment.points.boundingBox); } //console.log(`getPointsInsideProfile finished`); yield true; } finishLevelThenCancel() { if (this.cancelRequested) { return; } this.maxDepth = this.highestLevelServed; this.cancelRequested = true; //console.log(`maxDepth: ${this.maxDepth}`); } cancel() { this.callback.onCancel(); this.priorityQueue = new BinaryHeap(function (x) { return 1 / x.weight; }); var index = this.pointcloud.profileRequests.indexOf(this); if (index >= 0) { this.pointcloud.profileRequests.splice(index, 1); } } } class WorkerPool { constructor() { this.workers = {}; } getWorker(url) { if (!this.workers[url]) { this.workers[url] = []; } if (this.workers[url].length === 0) { var _worker = new Worker(url); this.workers[url].push(_worker); } var worker = this.workers[url].pop(); return worker; } returnWorker(url, worker) { this.workers[url].push(worker); } } ; function createPointcloudData(pointcloud) { var material = pointcloud.material; var ranges = []; for (var [name, value] of material.ranges) { ranges.push({ name: name, value: value }); } if (typeof material.elevationRange[0] === "number") { ranges.push({ name: "elevationRange", value: material.elevationRange }); } if (typeof material.intensityRange[0] === "number") { ranges.push({ name: "intensityRange", value: material.intensityRange }); } var pointSizeTypeName = Object.entries(Potree.PointSizeType).find(e => e[1] === material.pointSizeType)[0]; var jsonMaterial = { activeAttributeName: material.activeAttributeName, ranges: ranges, size: material.size, minSize: material.minSize, pointSizeType: pointSizeTypeName, matcap: material.matcap }; var pcdata = { name: pointcloud.name, url: pointcloud.pcoGeometry.url, position: pointcloud.position.toArray(), rotation: pointcloud.rotation.toArray(), scale: pointcloud.scale.toArray(), material: jsonMaterial }; return pcdata; } function createProfileData(profile) { var data = { uuid: profile.uuid, name: profile.name, points: profile.points.map(p => p.toArray()), height: profile.height, width: profile.width }; return data; } function createVolumeData(volume) { var data = { uuid: volume.uuid, type: volume.constructor.name, name: volume.name, position: volume.position.toArray(), rotation: volume.rotation.toArray(), scale: volume.scale.toArray(), visible: volume.visible, clip: volume.clip }; return data; } function createCameraAnimationData(animation) { var controlPoints = animation.controlPoints.map(cp => { var cpdata = { position: cp.position.toArray(), target: cp.target.toArray() }; return cpdata; }); var data = { uuid: animation.uuid, name: animation.name, duration: animation.duration, t: animation.t, curveType: animation.curveType, visible: animation.visible, controlPoints: controlPoints }; return data; } function createMeasurementData(measurement) { var data = { uuid: measurement.uuid, name: measurement.name, points: measurement.points.map(p => p.position.toArray()), showDistances: measurement.showDistances, showCoordinates: measurement.showCoordinates, showArea: measurement.showArea, closed: measurement.closed, showAngles: measurement.showAngles, showHeight: measurement.showHeight, showCircle: measurement.showCircle, showAzimuth: measurement.showAzimuth, showEdges: measurement.showEdges, color: measurement.color.toArray() }; return data; } function createOrientedImagesData(images) { var data = { cameraParamsPath: images.cameraParamsPath, imageParamsPath: images.imageParamsPath }; return data; } function createGeopackageData(geopackage) { var data = { path: geopackage.path }; return data; } function createAnnotationData(annotation) { var data = { uuid: annotation.uuid, title: annotation.title.toString(), description: annotation.description, position: annotation.position.toArray(), offset: annotation.offset.toArray(), children: [] }; if (annotation.cameraPosition) { data.cameraPosition = annotation.cameraPosition.toArray(); } if (annotation.cameraTarget) { data.cameraTarget = annotation.cameraTarget.toArray(); } if (typeof annotation.radius !== "undefined") { data.radius = annotation.radius; } return data; } function createAnnotationsData(viewer) { var map = new Map(); viewer.scene.annotations.traverseDescendants(a => { var aData = createAnnotationData(a); map.set(a, aData); }); for (var [annotation, data] of map) { for (var child of annotation.children) { var childData = map.get(child); data.children.push(childData); } } var annotations = viewer.scene.annotations.children.map(a => map.get(a)); return annotations; } function createSettingsData(viewer) { return { pointBudget: viewer.getPointBudget(), fov: viewer.getFOV(), edlEnabled: viewer.getEDLEnabled(), edlRadius: viewer.getEDLRadius(), edlStrength: viewer.getEDLStrength(), background: viewer.getBackground(), minNodeSize: viewer.getMinNodeSize(), showBoundingBoxes: viewer.getShowBoundingBox() }; } function createSceneContentData(viewer) { var data = []; var potreeObjects = []; viewer.scene.scene.traverse(node => { if (node.potree) { potreeObjects.push(node); } }); for (var object of potreeObjects) { if (object.potree.file) { var saveObject = { file: object.potree.file }; data.push(saveObject); } } return data; } function createViewData(viewer) { var view = viewer.scene.view; var data = { position: view.position.toArray(), target: view.getPivot().toArray() }; return data; } function createClassificationData(viewer) { var classifications = viewer.classifications; var data = classifications; return data; } function saveProject(viewer) { var scene = viewer.scene; var data = { type: "Potree", version: 1.7, settings: createSettingsData(viewer), view: createViewData(viewer), classification: createClassificationData(viewer), pointclouds: scene.pointclouds.map(createPointcloudData), measurements: scene.measurements.map(createMeasurementData), volumes: scene.volumes.map(createVolumeData), cameraAnimations: scene.cameraAnimations.map(createCameraAnimationData), profiles: scene.profiles.map(createProfileData), annotations: createAnnotationsData(viewer), orientedImages: scene.orientedImages.map(createOrientedImagesData), geopackages: scene.geopackages.map(createGeopackageData) // objects: createSceneContentData(viewer), }; return data; } class ControlPoint { constructor() { this.position = new Vector3(0, 0, 0); this.target = new Vector3(0, 0, 0); this.positionHandle = null; this.targetHandle = null; } } ; class CameraAnimation extends EventDispatcher$1 { constructor(viewer) { super(); this.viewer = viewer; this.selectedElement = null; this.controlPoints = []; this.uuid = MathUtils.generateUUID(); this.node = new Object3D(); this.node.name = "camera animation"; this.viewer.scene.scene.add(this.node); this.frustum = this.createFrustum(); this.node.add(this.frustum); this.name = "Camera Animation"; this.duration = 5; this.t = 0; // "centripetal", "chordal", "catmullrom" this.curveType = "centripetal"; this.visible = true; this.createUpdateHook(); this.createPath(); } static defaultFromView(viewer) { var animation = new CameraAnimation(viewer); var camera = viewer.scene.getActiveCamera(); var target = viewer.scene.view.getPivot(); var cpCenter = new Vector3(0.3 * camera.position.x + 0.7 * target.x, 0.3 * camera.position.y + 0.7 * target.y, 0.3 * camera.position.z + 0.7 * target.z); var targetCenter = new Vector3(0.05 * camera.position.x + 0.95 * target.x, 0.05 * camera.position.y + 0.95 * target.y, 0.05 * camera.position.z + 0.95 * target.z); var r = camera.position.distanceTo(target) * 0.3; //const dir = target.clone().sub(camera.position).normalize(); var angle = Utils.computeAzimuth(camera.position, target); var n = 5; for (var i = 0; i < n; i++) { var u = 1.5 * Math.PI * (i / n) + angle; var dx = r * Math.cos(u); var dy = r * Math.sin(u); var cpPos = [cpCenter.x + dx, cpCenter.y + dy, cpCenter.z]; var targetPos = [targetCenter.x + dx * 0.1, targetCenter.y + dy * 0.1, targetCenter.z]; var cp = animation.createControlPoint(); cp.position.set(...cpPos); cp.target.set(...targetPos); } return animation; } createUpdateHook() { var viewer = this.viewer; viewer.addEventListener("update", () => { var camera = viewer.scene.getActiveCamera(); var { width, height } = viewer.renderer.getSize(new Vector2()); this.node.visible = this.visible; for (var cp of this.controlPoints) { { // position var projected = cp.position.clone().project(camera); var visible = this.visible && projected.z < 1 && projected.z > -1; if (visible) { var x = width * (projected.x * 0.5 + 0.5); var y = height - height * (projected.y * 0.5 + 0.5); cp.positionHandle.svg.style.left = x - cp.positionHandle.svg.clientWidth / 2; cp.positionHandle.svg.style.top = y - cp.positionHandle.svg.clientHeight / 2; cp.positionHandle.svg.style.display = ""; } else { cp.positionHandle.svg.style.display = "none"; } } { // target var _projected = cp.target.clone().project(camera); var _visible = this.visible && _projected.z < 1 && _projected.z > -1; if (_visible) { var _x = width * (_projected.x * 0.5 + 0.5); var _y = height - height * (_projected.y * 0.5 + 0.5); cp.targetHandle.svg.style.left = _x - cp.targetHandle.svg.clientWidth / 2; cp.targetHandle.svg.style.top = _y - cp.targetHandle.svg.clientHeight / 2; cp.targetHandle.svg.style.display = ""; } else { cp.targetHandle.svg.style.display = "none"; } } } this.line.material.resolution.set(width, height); this.updatePath(); { // frustum var frame = this.at(this.t); var frustum = this.frustum; frustum.position.copy(frame.position); frustum.lookAt(...frame.target.toArray()); frustum.scale.set(20, 20, 20); frustum.material.resolution.set(width, height); } }); } createControlPoint(index) { if (index === undefined) { index = this.controlPoints.length; } var cp = new ControlPoint(); if (this.controlPoints.length >= 2 && index === 0) { var cp1 = this.controlPoints[0]; var cp2 = this.controlPoints[1]; var dir = cp1.position.clone().sub(cp2.position).multiplyScalar(0.5); cp.position.copy(cp1.position).add(dir); var tDir = cp1.target.clone().sub(cp2.target).multiplyScalar(0.5); cp.target.copy(cp1.target).add(tDir); } else if (this.controlPoints.length >= 2 && index === this.controlPoints.length) { var _cp2 = this.controlPoints[this.controlPoints.length - 2]; var _cp3 = this.controlPoints[this.controlPoints.length - 1]; var _dir = _cp3.position.clone().sub(_cp2.position).multiplyScalar(0.5); cp.position.copy(_cp2.position).add(_dir); var _tDir = _cp3.target.clone().sub(_cp2.target).multiplyScalar(0.5); cp.target.copy(_cp3.target).add(_tDir); } else if (this.controlPoints.length >= 2) { var _cp4 = this.controlPoints[index - 1]; var _cp5 = this.controlPoints[index]; cp.position.copy(_cp4.position.clone().add(_cp5.position).multiplyScalar(0.5)); cp.target.copy(_cp4.target.clone().add(_cp5.target).multiplyScalar(0.5)); } // cp.position.copy(viewer.scene.view.position); // cp.target.copy(viewer.scene.view.getPivot()); cp.positionHandle = this.createHandle(cp.position); cp.targetHandle = this.createHandle(cp.target); this.controlPoints.splice(index, 0, cp); this.dispatchEvent({ type: "controlpoint_added", controlpoint: cp }); return cp; } removeControlPoint(cp) { this.controlPoints = this.controlPoints.filter(_cp => _cp !== cp); this.dispatchEvent({ type: "controlpoint_removed", controlpoint: cp }); cp.positionHandle.svg.remove(); cp.targetHandle.svg.remove(); // TODO destroy cp } createPath() { { // position var geometry = new LineGeometry(); var material = new LineMaterial({ color: 0x00ff00, dashSize: 5, gapSize: 2, linewidth: 2, resolution: new Vector2(1000, 1000) }); var line = new Line2(geometry, material); this.line = line; this.node.add(line); } { // target var _geometry = new LineGeometry(); var _material = new LineMaterial({ color: 0x0000ff, dashSize: 5, gapSize: 2, linewidth: 2, resolution: new Vector2(1000, 1000) }); var _line = new Line2(_geometry, _material); this.targetLine = _line; this.node.add(_line); } } createFrustum() { var f = 0.3; var positions = [0, 0, 0, -f, -f, +1, 0, 0, 0, f, -f, +1, 0, 0, 0, f, f, +1, 0, 0, 0, -f, f, +1, -f, -f, +1, f, -f, +1, f, -f, +1, f, f, +1, f, f, +1, -f, f, +1, -f, f, +1, -f, -f, +1]; var geometry = new LineGeometry(); geometry.setPositions(positions); geometry.verticesNeedUpdate = true; geometry.computeBoundingSphere(); var material = new LineMaterial({ color: 0xff0000, linewidth: 2, resolution: new Vector2(1000, 1000) }); var line = new Line2(geometry, material); line.computeLineDistances(); return line; } updatePath() { { // positions var positions = this.controlPoints.map(cp => cp.position); var first = positions[0]; var curve = new CatmullRomCurve3(positions); curve.curveType = this.curveType; var n = 100; var curvePositions = []; for (var k = 0; k <= n; k++) { var t = k / n; var position = curve.getPoint(t).sub(first); curvePositions.push(position.x, position.y, position.z); } this.line.geometry.setPositions(curvePositions); this.line.geometry.verticesNeedUpdate = true; this.line.geometry.computeBoundingSphere(); this.line.position.copy(first); this.line.computeLineDistances(); this.cameraCurve = curve; } { // targets var _positions = this.controlPoints.map(cp => cp.target); var _first = _positions[0]; var _curve = new CatmullRomCurve3(_positions); _curve.curveType = this.curveType; var _n = 100; var _curvePositions = []; for (var _k = 0; _k <= _n; _k++) { var _t = _k / _n; var _position = _curve.getPoint(_t).sub(_first); _curvePositions.push(_position.x, _position.y, _position.z); } this.targetLine.geometry.setPositions(_curvePositions); this.targetLine.geometry.verticesNeedUpdate = true; this.targetLine.geometry.computeBoundingSphere(); this.targetLine.position.copy(_first); this.targetLine.computeLineDistances(); this.targetCurve = _curve; } } at(t) { if (t > 1) { t = 1; } else if (t < 0) { t = 0; } var camPos = this.cameraCurve.getPointAt(t); var target = this.targetCurve.getPointAt(t); var frame = { position: camPos, target: target }; return frame; } set(t) { this.t = t; } createHandle(vector) { var svgns = "http://www.w3.org/2000/svg"; var svg = document.createElementNS(svgns, "svg"); svg.setAttribute("width", "2em"); svg.setAttribute("height", "2em"); svg.setAttribute("position", "absolute"); svg.style.left = "50px"; svg.style.top = "50px"; svg.style.position = "absolute"; svg.style.zIndex = "10000"; var circle = document.createElementNS(svgns, 'circle'); circle.setAttributeNS(null, 'cx', "1em"); circle.setAttributeNS(null, 'cy', "1em"); circle.setAttributeNS(null, 'r', "0.5em"); circle.setAttributeNS(null, 'style', 'fill: red; stroke: black; stroke-width: 0.2em;'); svg.appendChild(circle); var element = this.viewer.renderer.domElement.parentElement; element.appendChild(svg); var startDrag = evt => { this.selectedElement = svg; document.addEventListener("mousemove", drag); }; var endDrag = evt => { this.selectedElement = null; document.removeEventListener("mousemove", drag); }; var drag = evt => { if (this.selectedElement) { evt.preventDefault(); var rect = viewer.renderer.domElement.getBoundingClientRect(); var x = evt.clientX - rect.x; var y = evt.clientY - rect.y; var { width, height } = this.viewer.renderer.getSize(new Vector2()); var camera = this.viewer.scene.getActiveCamera(); //const cp = this.controlPoints.find(cp => cp.handle.svg === svg); var projected = vector.clone().project(camera); projected.x = (x / width - 0.5) / 0.5; projected.y = (-(y - height) / height - 0.5) / 0.5; var unprojected = projected.clone().unproject(camera); vector.set(unprojected.x, unprojected.y, unprojected.z); } }; svg.addEventListener('mousedown', startDrag); svg.addEventListener('mouseup', endDrag); var handle = { svg: svg }; return handle; } setVisible(visible) { this.node.visible = visible; var display = visible ? "" : "none"; for (var cp of this.controlPoints) { cp.positionHandle.svg.style.display = display; cp.targetHandle.svg.style.display = display; } this.visible = visible; } setDuration(duration) { this.duration = duration; } getDuration(duration) { return this.duration; } play() { var tStart = performance.now(); var duration = this.duration; var originalyVisible = this.visible; this.setVisible(false); var onUpdate = delta => { var tNow = performance.now(); var elapsed = (tNow - tStart) / 1000; var t = elapsed / duration; this.set(t); var frame = this.at(t); viewer.scene.view.position.copy(frame.position); viewer.scene.view.lookAt(frame.target); if (t > 1) { this.setVisible(originalyVisible); this.viewer.removeEventListener("update", onUpdate); } }; this.viewer.addEventListener("update", onUpdate); } } function loadPointCloud(viewer, data) { var loadMaterial = target => { if (data.material) { if (data.material.activeAttributeName != null) { target.activeAttributeName = data.material.activeAttributeName; } if (data.material.ranges != null) { for (var range of data.material.ranges) { if (range.name === "elevationRange") { target.elevationRange = range.value; } else if (range.name === "intensityRange") { target.intensityRange = range.value; } else { target.setRange(range.name, range.value); } } } if (data.material.size != null) { target.size = data.material.size; } if (data.material.minSize != null) { target.minSize = data.material.minSize; } if (data.material.pointSizeType != null) { target.pointSizeType = PointSizeType[data.material.pointSizeType]; } if (data.material.matcap != null) { target.matcap = data.material.matcap; } } else if (data.activeAttributeName != null) { target.activeAttributeName = data.activeAttributeName; } else { // no material data } }; var promise = new Promise(resolve => { var names = viewer.scene.pointclouds.map(p => p.name); var alreadyExists = names.includes(data.name); if (alreadyExists) { resolve(); return; } Potree.loadPointCloud(data.url, data.name, e => { var { pointcloud } = e; pointcloud.position.set(...data.position); pointcloud.rotation.set(...data.rotation); pointcloud.scale.set(...data.scale); loadMaterial(pointcloud.material); viewer.scene.addPointCloud(pointcloud); resolve(pointcloud); }); }); return promise; } function loadMeasurement(viewer, data) { var duplicate = viewer.scene.measurements.find(measure => measure.uuid === data.uuid); if (duplicate) { return; } var measure = new Measure(); measure.uuid = data.uuid; measure.name = data.name; measure.showDistances = data.showDistances; measure.showCoordinates = data.showCoordinates; measure.showArea = data.showArea; measure.closed = data.closed; measure.showAngles = data.showAngles; measure.showHeight = data.showHeight; measure.showCircle = data.showCircle; measure.showAzimuth = data.showAzimuth; measure.showEdges = data.showEdges; // color for (var point of data.points) { var pos = new Vector3(...point); measure.addMarker(pos); } viewer.scene.addMeasurement(measure); } function loadVolume(viewer, data) { var duplicate = viewer.scene.volumes.find(volume => volume.uuid === data.uuid); if (duplicate) { return; } var volume = new Potree[data.type](); volume.uuid = data.uuid; volume.name = data.name; volume.position.set(...data.position); volume.rotation.set(...data.rotation); volume.scale.set(...data.scale); volume.visible = data.visible; volume.clip = data.clip; viewer.scene.addVolume(volume); } function loadCameraAnimation(viewer, data) { var duplicate = viewer.scene.cameraAnimations.find(a => a.uuid === data.uuid); if (duplicate) { return; } var animation = new CameraAnimation(viewer); animation.uuid = data.uuid; animation.name = data.name; animation.duration = data.duration; animation.t = data.t; animation.curveType = data.curveType; animation.visible = data.visible; animation.controlPoints = []; for (var cpdata of data.controlPoints) { var cp = animation.createControlPoint(); cp.position.set(...cpdata.position); cp.target.set(...cpdata.target); } viewer.scene.addCameraAnimation(animation); } function loadOrientedImages(viewer, images) { var { cameraParamsPath, imageParamsPath } = images; var duplicate = viewer.scene.orientedImages.find(i => i.imageParamsPath === imageParamsPath); if (duplicate) { return; } Potree.OrientedImageLoader.load(cameraParamsPath, imageParamsPath, viewer).then(images => { viewer.scene.addOrientedImages(images); }); } function loadGeopackage(viewer, geopackage) { var path = geopackage.path; var duplicate = viewer.scene.geopackages.find(i => i.path === path); if (duplicate) { return; } var projection = viewer.getProjection(); proj4.defs("WGS84", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"); proj4.defs("pointcloud", projection); var transform = proj4("WGS84", "pointcloud"); var params = { transform: transform }; Potree.GeoPackageLoader.loadUrl(path, params).then(data => { viewer.scene.addGeopackage(data); }); } function loadSettings(viewer, data) { if (!data) { return; } viewer.setPointBudget(data.pointBudget); viewer.setFOV(data.fov); viewer.setEDLEnabled(data.edlEnabled); viewer.setEDLRadius(data.edlRadius); viewer.setEDLStrength(data.edlStrength); viewer.setBackground(data.background); viewer.setMinNodeSize(data.minNodeSize); viewer.setShowBoundingBox(data.showBoundingBoxes); } function loadView(viewer, view) { viewer.scene.view.position.set(...view.position); viewer.scene.view.lookAt(...view.target); } function loadAnnotationItem(item) { var annotation = new Annotation({ position: item.position, title: item.title, cameraPosition: item.cameraPosition, cameraTarget: item.cameraTarget }); annotation.description = item.description; annotation.uuid = item.uuid; if (item.offset) { annotation.offset.set(...item.offset); } return annotation; } function loadAnnotations(viewer, data) { if (!data) { return; } var findDuplicate = item => { var duplicate = null; viewer.scene.annotations.traverse(a => { if (a.uuid === item.uuid) { duplicate = a; } }); return duplicate; }; var traverse = (item, parent) => { var duplicate = findDuplicate(item); if (duplicate) { return; } var annotation = loadAnnotationItem(item); for (var childItem of item.children) { traverse(childItem, annotation); } parent.add(annotation); }; for (var item of data) { traverse(item, viewer.scene.annotations); } } function loadProfile(viewer, data) { var { name, points } = data; var duplicate = viewer.scene.profiles.find(profile => profile.uuid === data.uuid); if (duplicate) { return; } var profile = new Potree.Profile(); profile.name = name; profile.uuid = data.uuid; profile.setWidth(data.width); for (var point of points) { profile.addMarker(new Vector3(...point)); } viewer.scene.addProfile(profile); } function loadClassification(viewer, data) { if (!data) { return; } var classifications = data; viewer.setClassifications(classifications); } async function loadProject(viewer, data) { if (data.type !== "Potree") { console.error("not a valid Potree project"); return; } loadSettings(viewer, data.settings); loadView(viewer, data.view); var pointcloudPromises = []; for (var pointcloud of data.pointclouds) { var promise = loadPointCloud(viewer, pointcloud); pointcloudPromises.push(promise); } for (var measure of data.measurements) { loadMeasurement(viewer, measure); } for (var volume of data.volumes) { loadVolume(viewer, volume); } for (var animation of data.cameraAnimations) { loadCameraAnimation(viewer, animation); } for (var profile of data.profiles) { loadProfile(viewer, profile); } if (data.orientedImages) { for (var images of data.orientedImages) { loadOrientedImages(viewer, images); } } loadAnnotations(viewer, data.annotations); loadClassification(viewer, data.classification); // need to load at least one point cloud that defines the scene projection, // before we can load stuff in other projections such as geopackages //await Promise.any(pointcloudPromises); // (not yet supported) Utils.waitAny(pointcloudPromises).then(() => { if (data.geopackages) { for (var geopackage of data.geopackages) { loadGeopackage(viewer, geopackage); } } }); await Promise.all(pointcloudPromises); } // // Algorithm by Christian Boucheny // shader code taken and adapted from CloudCompare // // see // https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL // http://www.kitware.com/source/home/post/9 // https://tel.archives-ouvertes.fr/tel-00438464/document p. 115+ (french) class EyeDomeLightingMaterial extends RawShaderMaterial { //base constructor() { var parameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(); var uniforms = { screenWidth: { type: 'f', value: 0 }, screenHeight: { type: 'f', value: 0 }, edlStrength: { type: 'f', value: 1.0 }, uNear: { type: 'f', value: 1.0 }, uFar: { type: 'f', value: 1.0 }, radius: { type: 'f', value: 1.0 }, neighbours: { type: '2fv', value: [] }, depthMap: { type: 't', value: null }, uEDLColor: { type: 't', value: null }, uEDLDepth: { type: 't', value: null }, opacity: { type: 'f', value: 1.0 }, uProj: { type: "Matrix4fv", value: [] } }; this.setValues({ uniforms: uniforms, vertexShader: this.getDefines() + Shaders['edl.vs'], fragmentShader: this.getDefines() + Shaders['edl.fs'], lights: false }); this.neighbourCount = 8; } getDefines() { var defines = ''; defines += '#define NEIGHBOUR_COUNT ' + this.neighbourCount + '\n'; return defines; } updateShaderSource() { var vs = this.getDefines() + Shaders['edl.vs']; var fs = this.getDefines() + Shaders['edl.fs']; this.setValues({ vertexShader: vs, fragmentShader: fs }); this.uniforms.neighbours.value = this.neighbours; this.needsUpdate = true; } get neighbourCount() { return this._neighbourCount; } set neighbourCount(value) { if (this._neighbourCount !== value) { //周围八个格子 this._neighbourCount = value; this.neighbours = new Float32Array(this._neighbourCount * 2); for (var c = 0; c < this._neighbourCount; c++) { this.neighbours[2 * c + 0] = Math.cos(2 * c * Math.PI / this._neighbourCount); this.neighbours[2 * c + 1] = Math.sin(2 * c * Math.PI / this._neighbourCount); } this.updateShaderSource(); } } } /** * laslaz code taken and adapted from plas.io js-laslaz * http://plas.io/ * https://github.com/verma/plasio * * Thanks to Uday Verma and Howard Butler * */ class LasLazLoader { constructor(version, extension) { if (typeof version === 'string') { this.version = new Version(version); } else { this.version = version; } this.extension = extension; } static progressCB() {} load(node, callback) { if (node.loaded) { return; } var url = node.getURL(); if (this.version.equalOrHigher('1.4')) { url += ".".concat(this.extension); } var xhr = XHRFactory.createXMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'arraybuffer'; xhr.overrideMimeType('text/plain; charset=x-user-defined'); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status === 200 || xhr.status === 0) { var buffer = xhr.response; this.parse(node, buffer, callback); } else { console.log('Failed to load file! HTTP status: ' + xhr.status + ', file: ' + url); } } }; xhr.send(null); } async parse(node, buffer, callback) { //add callback var lf = new LASFile(buffer); var handler = new LasLazBatcher(node); try { await lf.open(); lf.isOpen = true; } catch (e) { console.log("failed to open file. :("); return; } var header = await lf.getHeader(); var skip = 1; var totalRead = 0; var totalToRead = skip <= 1 ? header.pointsCount : header.pointsCount / skip; var hasMoreData = true; while (hasMoreData) { var data = await lf.readData(1000 * 1000, 0, skip); handler.push(new LASDecoder(data.buffer, header.pointsFormatId, header.pointsStructSize, data.count, header.scale, header.offset, header.mins, header.maxs)); totalRead += data.count; LasLazLoader.progressCB(totalRead / totalToRead); hasMoreData = data.hasMoreData; } header.totalRead = totalRead; header.versionAsString = lf.versionAsString; header.isCompressed = lf.isCompressed; LasLazLoader.progressCB(1); try { await lf.close(); lf.isOpen = false; } catch (e) { console.error("failed to close las/laz file!!!"); throw e; } callback(); //add } handle(node, url) {} } ; class LasLazBatcher { constructor(node) { this.node = node; } push(lasBuffer) { var workerPath = Potree.scriptPath + '/workers/LASDecoderWorker.js'; var worker = Potree.workerPool.getWorker(workerPath); var node = this.node; var pointAttributes = node.pcoGeometry.pointAttributes; worker.onmessage = e => { var geometry = new BufferGeometry(); var numPoints = lasBuffer.pointsCount; var positions = new Float32Array(e.data.position); var colors = new Uint8Array(e.data.color); var intensities = new Float32Array(e.data.intensity); var classifications = new Uint8Array(e.data.classification); var returnNumbers = new Uint8Array(e.data.returnNumber); var numberOfReturns = new Uint8Array(e.data.numberOfReturns); var pointSourceIDs = new Uint16Array(e.data.pointSourceID); var indices = new Uint8Array(e.data.indices); geometry.setAttribute('position', new BufferAttribute(positions, 3)); geometry.setAttribute('color', new BufferAttribute(colors, 4, true)); geometry.setAttribute('intensity', new BufferAttribute(intensities, 1)); geometry.setAttribute('classification', new BufferAttribute(classifications, 1)); geometry.setAttribute('return number', new BufferAttribute(returnNumbers, 1)); geometry.setAttribute('number of returns', new BufferAttribute(numberOfReturns, 1)); geometry.setAttribute('source id', new BufferAttribute(pointSourceIDs, 1)); geometry.setAttribute('indices', new BufferAttribute(indices, 4)); geometry.attributes.indices.normalized = true; var _loop = function _loop(key) { var range = e.data.ranges[key]; var attribute = pointAttributes.attributes.find(a => a.name === key); attribute.range[0] = Math.min(attribute.range[0], range[0]); attribute.range[1] = Math.max(attribute.range[1], range[1]); }; for (var key in e.data.ranges) { _loop(key); } var tightBoundingBox = new Box3(new Vector3().fromArray(e.data.tightBoundingBox.min), new Vector3().fromArray(e.data.tightBoundingBox.max)); geometry.boundingBox = this.node.boundingBox; this.node.tightBoundingBox = tightBoundingBox; this.node.geometry = geometry; this.node.numPoints = numPoints; this.node.loaded = true; this.node.loading = false; Potree.numNodesLoading--; this.node.mean = new Vector3(...e.data.mean); Potree.workerPool.returnWorker(workerPath, worker); }; var message = { buffer: lasBuffer.arrayb, numPoints: lasBuffer.pointsCount, pointSize: lasBuffer.pointSize, pointFormatID: 2, scale: lasBuffer.scale, offset: lasBuffer.offset, mins: lasBuffer.mins, maxs: lasBuffer.maxs }; worker.postMessage(message, [message.buffer]); } } function parseAttributes(cloudjs) { var version = new Version(cloudjs.version); var replacements = { "COLOR_PACKED": "rgba", "RGBA": "rgba", "INTENSITY": "intensity", "CLASSIFICATION": "classification", "GPS_TIME": "gps-time" }; var replaceOldNames = old => { if (replacements[old]) { return replacements[old]; } else { return old; } }; var pointAttributes = []; if (version.upTo('1.7')) { for (var attributeName of cloudjs.pointAttributes) { var oldAttribute = PointAttribute[attributeName]; var attribute = { name: oldAttribute.name, size: oldAttribute.byteSize, elements: oldAttribute.numElements, elementSize: oldAttribute.byteSize / oldAttribute.numElements, type: oldAttribute.type.name, description: "" }; pointAttributes.push(attribute); } } else { pointAttributes.push(...cloudjs.pointAttributes); } { var attributes = new PointAttributes(); var typeConversion = { int8: PointAttributeTypes.DATA_TYPE_INT8, int16: PointAttributeTypes.DATA_TYPE_INT16, int32: PointAttributeTypes.DATA_TYPE_INT32, int64: PointAttributeTypes.DATA_TYPE_INT64, uint8: PointAttributeTypes.DATA_TYPE_UINT8, uint16: PointAttributeTypes.DATA_TYPE_UINT16, uint32: PointAttributeTypes.DATA_TYPE_UINT32, uint64: PointAttributeTypes.DATA_TYPE_UINT64, double: PointAttributeTypes.DATA_TYPE_DOUBLE, float: PointAttributeTypes.DATA_TYPE_FLOAT }; for (var jsAttribute of pointAttributes) { if (jsAttribute.name == void 0) { //add 有的是这个,也有的不是(点云编辑页的) var attribute_ = PointAttribute[jsAttribute]; attributes.add(attribute_); continue; } var name = replaceOldNames(jsAttribute.name); var type = typeConversion[jsAttribute.type]; var numElements = jsAttribute.elements; var description = jsAttribute.description; var _attribute = new PointAttribute(name, type, numElements); attributes.add(_attribute); } { // check if it has normals var hasNormals = pointAttributes.find(a => a.name === "NormalX") !== undefined && pointAttributes.find(a => a.name === "NormalY") !== undefined && pointAttributes.find(a => a.name === "NormalZ") !== undefined; if (hasNormals) { var vector = { name: "NORMAL", attributes: ["NormalX", "NormalY", "NormalZ"] }; attributes.addVector(vector); } } return attributes; } } function lasLazAttributes(fMno) { var attributes = new PointAttributes(); attributes.add(PointAttribute.POSITION_CARTESIAN); attributes.add(new PointAttribute("rgba", PointAttributeTypes.DATA_TYPE_UINT8, 4)); attributes.add(new PointAttribute("intensity", PointAttributeTypes.DATA_TYPE_UINT16, 1)); attributes.add(new PointAttribute("classification", PointAttributeTypes.DATA_TYPE_UINT8, 1)); attributes.add(new PointAttribute("gps-time", PointAttributeTypes.DATA_TYPE_DOUBLE, 1)); attributes.add(new PointAttribute("number of returns", PointAttributeTypes.DATA_TYPE_UINT8, 1)); attributes.add(new PointAttribute("return number", PointAttributeTypes.DATA_TYPE_UINT8, 1)); attributes.add(new PointAttribute("source id", PointAttributeTypes.DATA_TYPE_UINT16, 1)); //attributes.add(new PointAttribute("pointSourceID", PointAttributeTypes.DATA_TYPE_INT8, 4)); return attributes; } class POCLoader { static load(url, timeStamp, callback) { //add timeStamp try { var pco = new PointCloudOctreeGeometry(); pco.timeStamp = timeStamp; pco.url = url; var xhr = XHRFactory.createXMLHttpRequest(); xhr.open('GET', url + '?m=' + timeStamp, true); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 0)) { var fMno = JSON.parse(xhr.responseText); var version = new Version(fMno.version); // assume octreeDir is absolute if it starts with http if (fMno.octreeDir.indexOf('http') === 0) { pco.octreeDir = fMno.octreeDir; } else { pco.octreeDir = url + '/../' + fMno.octreeDir; } pco.spacing = fMno.spacing; pco.hierarchyStepSize = fMno.hierarchyStepSize; pco.pointAttributes = fMno.pointAttributes; var min = new Vector3(fMno.boundingBox.lx, fMno.boundingBox.ly, fMno.boundingBox.lz); var max = new Vector3(fMno.boundingBox.ux, fMno.boundingBox.uy, fMno.boundingBox.uz); var boundingBox = new Box3(min, max); var tightBoundingBox = boundingBox.clone(); if (fMno.tightBoundingBox) { //这个才是真实的bounding,前面那个bounding的size是个正方体,似乎取了最长边作为边长 tightBoundingBox.min.copy(new Vector3(fMno.tightBoundingBox.lx, fMno.tightBoundingBox.ly, fMno.tightBoundingBox.lz)); tightBoundingBox.max.copy(new Vector3(fMno.tightBoundingBox.ux, fMno.tightBoundingBox.uy, fMno.tightBoundingBox.uz)); } var offset = min.clone(); //将成为点云的position,被我用作旋转中心(但在点云中不那么居中,navvis也是这样, 这样可能是为了让模型在这数据的bounding上) boundingBox.min.sub(offset); //点云的真实坐标的min都是0,0,0吗(我看案例是,因绕角落旋转,也就是原点) boundingBox.max.sub(offset); tightBoundingBox.min.sub(offset); tightBoundingBox.max.sub(offset); //改 //pco.projection = fMno.projection || "+proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs ", //"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs" //给地图 pco.boundingBox = boundingBox; pco.tightBoundingBox = tightBoundingBox; pco.boundingSphere = boundingBox.getBoundingSphere(new Sphere()); pco.tightBoundingSphere = tightBoundingBox.getBoundingSphere(new Sphere()); pco.offset = offset; if (fMno.pointAttributes === 'LAS') { pco.loader = new LasLazLoader(fMno.version, "las"); pco.pointAttributes = lasLazAttributes(fMno); } else if (fMno.pointAttributes === 'LAZ') { pco.loader = new LasLazLoader(fMno.version, "laz"); pco.pointAttributes = lasLazAttributes(fMno); } else { pco.loader = new BinaryLoader(fMno.version, boundingBox, fMno.scale); pco.pointAttributes = parseAttributes(fMno); } var nodes = {}; { // load root var name = 'r'; var root = new PointCloudOctreeGeometryNode(name, pco, boundingBox); root.level = 0; root.hasChildren = true; root.spacing = pco.spacing; if (version.upTo('1.5')) { root.numPoints = fMno.hierarchy[0][1]; } else { root.numPoints = 0; } pco.root = root; pco.root.load(); nodes[name] = root; } // load remaining hierarchy if (version.upTo('1.4')) { for (var i = 1; i < fMno.hierarchy.length; i++) { var _name = fMno.hierarchy[i][0]; var numPoints = fMno.hierarchy[i][1]; var index = parseInt(_name.charAt(_name.length - 1)); var parentName = _name.substring(0, _name.length - 1); var parentNode = nodes[parentName]; var level = _name.length - 1; //let boundingBox = POCLoader.createChildAABB(parentNode.boundingBox, index); var _boundingBox = Utils.createChildAABB(parentNode.boundingBox, index); var node = new PointCloudOctreeGeometryNode(_name, pco, _boundingBox); node.level = level; node.numPoints = numPoints; node.spacing = pco.spacing / Math.pow(2, level); parentNode.addChild(node); nodes[_name] = node; } } pco.nodes = nodes; callback(pco); } }; xhr.send(null); } catch (e) { console.log("loading failed: '" + url + "'"); console.log(e); callback(); } } loadPointAttributes(mno) { var fpa = mno.pointAttributes; var pa = new PointAttributes(); for (var i = 0; i < fpa.length; i++) { var pointAttribute = PointAttribute[fpa[i]]; pa.add(pointAttribute); } return pa; } createChildAABB(aabb, index) { var min = aabb.min.clone(); var max = aabb.max.clone(); var size = new Vector3().subVectors(max, min); if ((index & 0b0001) > 0) { min.z += size.z / 2; } else { max.z -= size.z / 2; } if ((index & 0b0010) > 0) { min.y += size.y / 2; } else { max.y -= size.y / 2; } if ((index & 0b0100) > 0) { min.x += size.x / 2; } else { max.x -= size.x / 2; } return new Box3(min, max); } } class OctreeGeometry { constructor() { this.url = null; this.spacing = 0; this.boundingBox = null; this.root = null; this.pointAttributes = null; this.loader = null; } } ; class OctreeGeometryNode { constructor(name, octreeGeometry, boundingBox) { this.id = OctreeGeometryNode.IDCount++; this.name = name; this.index = parseInt(name.charAt(name.length - 1)); this.octreeGeometry = octreeGeometry; this.boundingBox = boundingBox; this.boundingSphere = boundingBox.getBoundingSphere(new Sphere()); this.children = {}; this.numPoints = 0; this.level = null; this.oneTimeDisposeHandlers = []; } isGeometryNode() { return true; } getLevel() { return this.level; } isTreeNode() { return false; } isLoaded() { return this.loaded; } getBoundingSphere() { return this.boundingSphere; } getBoundingBox() { return this.boundingBox; } getChildren() { var children = []; for (var i = 0; i < 8; i++) { if (this.children[i]) { children.push(this.children[i]); } } return children; } getBoundingBox() { return this.boundingBox; } load() { if (Potree.numNodesLoading >= Potree.maxNodesLoading) { return; } this.octreeGeometry.loader.load(this); } getNumPoints() { return this.numPoints; } dispose() { if (this.geometry && this.parent != null) { this.geometry.dispose(); this.geometry = null; this.loaded = false; // this.dispatchEvent( { type: 'dispose' } ); for (var i = 0; i < this.oneTimeDisposeHandlers.length; i++) { var handler = this.oneTimeDisposeHandlers[i]; handler(); } this.oneTimeDisposeHandlers = []; } } } ; OctreeGeometryNode.IDCount = 0; // let loadedNodes = new Set(); class NodeLoader { constructor(url) { this.url = url; } async load(node) { if (node.loaded || node.loading) { return; } node.loading = true; Potree.numNodesLoading++; // console.log(node.name, node.numPoints); // if(loadedNodes.has(node.name)){ // // debugger; // } // loadedNodes.add(node.name); try { if (node.nodeType === 2) { await this.loadHierarchy(node); } var { byteOffset, byteSize } = node; var urlOctree = "".concat(this.url, "/../octree.bin"); var first = byteOffset; var last = byteOffset + byteSize - 1n; var buffer; if (byteSize === 0n) { buffer = new ArrayBuffer(0); console.warn("loaded node with 0 bytes: ".concat(node.name)); } else { var response = await fetch(urlOctree, { headers: { 'content-type': 'multipart/byteranges', 'Range': "bytes=".concat(first, "-").concat(last) } }); buffer = await response.arrayBuffer(); } var workerPath; if (this.metadata.encoding === "BROTLI") { workerPath = Potree.scriptPath + '/workers/2.0/DecoderWorker_brotli.js'; } else { workerPath = Potree.scriptPath + '/workers/2.0/DecoderWorker.js'; } var worker = Potree.workerPool.getWorker(workerPath); worker.onmessage = function (e) { var data = e.data; var buffers = data.attributeBuffers; Potree.workerPool.returnWorker(workerPath, worker); var geometry = new BufferGeometry(); for (var property in buffers) { var _buffer = buffers[property].buffer; if (property === "position") { geometry.setAttribute('position', new BufferAttribute(new Float32Array(_buffer), 3)); } else if (property === "rgba") { geometry.setAttribute('rgba', new BufferAttribute(new Uint8Array(_buffer), 4, true)); } else if (property === "NORMAL") { //geometry.setAttribute('rgba', new THREE.BufferAttribute(new Uint8Array(buffer), 4, true)); geometry.setAttribute('normal', new BufferAttribute(new Float32Array(_buffer), 3)); } else if (property === "INDICES") { var bufferAttribute = new BufferAttribute(new Uint8Array(_buffer), 4); bufferAttribute.normalized = true; geometry.setAttribute('indices', bufferAttribute); } else { var _bufferAttribute = new BufferAttribute(new Float32Array(_buffer), 1); var batchAttribute = buffers[property].attribute; _bufferAttribute.potree = { offset: buffers[property].offset, scale: buffers[property].scale, preciseBuffer: buffers[property].preciseBuffer, range: batchAttribute.range }; geometry.setAttribute(property, _bufferAttribute); } } // indices ?? node.density = data.density; node.geometry = geometry; node.loaded = true; node.loading = false; Potree.numNodesLoading--; }; var pointAttributes = node.octreeGeometry.pointAttributes; var scale = node.octreeGeometry.scale; var box = node.boundingBox; var min = node.octreeGeometry.offset.clone().add(box.min); var size = box.max.clone().sub(box.min); var max = min.clone().add(size); var numPoints = node.numPoints; var offset = node.octreeGeometry.loader.offset; var message = { name: node.name, buffer: buffer, pointAttributes: pointAttributes, scale: scale, min: min, max: max, size: size, offset: offset, numPoints: numPoints }; worker.postMessage(message, [message.buffer]); } catch (e) { node.loaded = false; node.loading = false; Potree.numNodesLoading--; console.log("failed to load ".concat(node.name)); console.log(e); console.log("trying again!"); } } parseHierarchy(node, buffer) { var view = new DataView(buffer); var tStart = performance.now(); var bytesPerNode = 22; var numNodes = buffer.byteLength / bytesPerNode; var octree = node.octreeGeometry; // let nodes = [node]; var nodes = new Array(numNodes); nodes[0] = node; var nodePos = 1; for (var i = 0; i < numNodes; i++) { var current = nodes[i]; var type = view.getUint8(i * bytesPerNode + 0); var childMask = view.getUint8(i * bytesPerNode + 1); var numPoints = view.getUint32(i * bytesPerNode + 2, true); var byteOffset = view.getBigInt64(i * bytesPerNode + 6, true); var byteSize = view.getBigInt64(i * bytesPerNode + 14, true); // if(byteSize === 0n){ // // debugger; // } if (current.nodeType === 2) { // replace proxy with real node current.byteOffset = byteOffset; current.byteSize = byteSize; current.numPoints = numPoints; } else if (type === 2) { // load proxy current.hierarchyByteOffset = byteOffset; current.hierarchyByteSize = byteSize; current.numPoints = numPoints; } else { // load real node current.byteOffset = byteOffset; current.byteSize = byteSize; current.numPoints = numPoints; } if (current.byteSize === 0n) { // workaround for issue #1125 // some inner nodes erroneously report >0 points even though have 0 points // however, they still report a byteSize of 0, so based on that we now set node.numPoints to 0 current.numPoints = 0; } current.nodeType = type; if (current.nodeType === 2) { continue; } for (var childIndex = 0; childIndex < 8; childIndex++) { var childExists = (1 << childIndex & childMask) !== 0; if (!childExists) { continue; } var childName = current.name + childIndex; var childAABB = createChildAABB(current.boundingBox, childIndex); var child = new OctreeGeometryNode(childName, octree, childAABB); child.name = childName; child.spacing = current.spacing / 2; child.level = current.level + 1; current.children[childIndex] = child; child.parent = current; // nodes.push(child); nodes[nodePos] = child; nodePos++; } // if((i % 500) === 0){ // yield; // } } var duration = performance.now() - tStart; // if(duration > 20){ // let msg = `duration: ${duration}ms, numNodes: ${numNodes}`; // console.log(msg); // } } async loadHierarchy(node) { var { hierarchyByteOffset, hierarchyByteSize } = node; var hierarchyPath = "".concat(this.url, "/../hierarchy.bin"); var first = hierarchyByteOffset; var last = first + hierarchyByteSize - 1n; var response = await fetch(hierarchyPath, { headers: { 'content-type': 'multipart/byteranges', 'Range': "bytes=".concat(first, "-").concat(last) } }); var buffer = await response.arrayBuffer(); this.parseHierarchy(node, buffer); // let promise = new Promise((resolve) => { // let generator = this.parseHierarchy(node, buffer); // let repeatUntilDone = () => { // let result = generator.next(); // if(result.done){ // resolve(); // }else{ // requestAnimationFrame(repeatUntilDone); // } // }; // repeatUntilDone(); // }); // await promise; } } var tmpVec3 = new Vector3(); function createChildAABB(aabb, index) { var min = aabb.min.clone(); var max = aabb.max.clone(); var size = tmpVec3.subVectors(max, min); if ((index & 0b0001) > 0) { min.z += size.z / 2; } else { max.z -= size.z / 2; } if ((index & 0b0010) > 0) { min.y += size.y / 2; } else { max.y -= size.y / 2; } if ((index & 0b0100) > 0) { min.x += size.x / 2; } else { max.x -= size.x / 2; } return new Box3(min, max); } var typenameTypeattributeMap = { "double": PointAttributeTypes.DATA_TYPE_DOUBLE, "float": PointAttributeTypes.DATA_TYPE_FLOAT, "int8": PointAttributeTypes.DATA_TYPE_INT8, "uint8": PointAttributeTypes.DATA_TYPE_UINT8, "int16": PointAttributeTypes.DATA_TYPE_INT16, "uint16": PointAttributeTypes.DATA_TYPE_UINT16, "int32": PointAttributeTypes.DATA_TYPE_INT32, "uint32": PointAttributeTypes.DATA_TYPE_UINT32, "int64": PointAttributeTypes.DATA_TYPE_INT64, "uint64": PointAttributeTypes.DATA_TYPE_UINT64 }; class OctreeLoader { static parseAttributes(jsonAttributes) { var attributes = new PointAttributes(); var replacements = { "rgb": "rgba" }; for (var jsonAttribute of jsonAttributes) { var { name, description, size, numElements, elementSize, min, max } = jsonAttribute; var type = typenameTypeattributeMap[jsonAttribute.type]; var potreeAttributeName = replacements[name] ? replacements[name] : name; var attribute = new PointAttribute(potreeAttributeName, type, numElements); if (numElements === 1) { attribute.range = [min[0], max[0]]; } else { attribute.range = [min, max]; } if (name === "gps-time") { // HACK: Guard against bad gpsTime range in metadata, see potree/potree#909 if (attribute.range[0] === attribute.range[1]) { attribute.range[1] += 1; } } attribute.initialRange = attribute.range; attributes.add(attribute); } { // check if it has normals var hasNormals = attributes.attributes.find(a => a.name === "NormalX") !== undefined && attributes.attributes.find(a => a.name === "NormalY") !== undefined && attributes.attributes.find(a => a.name === "NormalZ") !== undefined; if (hasNormals) { var vector = { name: "NORMAL", attributes: ["NormalX", "NormalY", "NormalZ"] }; attributes.addVector(vector); } } return attributes; } static async load(url) { var response = await fetch(url); var metadata = await response.json(); var attributes = OctreeLoader.parseAttributes(metadata.attributes); var loader = new NodeLoader(url); loader.metadata = metadata; loader.attributes = attributes; loader.scale = metadata.scale; loader.offset = metadata.offset; var octree = new OctreeGeometry(); octree.url = url; octree.spacing = metadata.spacing; octree.scale = metadata.scale; // let aPosition = metadata.attributes.find(a => a.name === "position"); // octree var min = new Vector3(...metadata.boundingBox.min); var max = new Vector3(...metadata.boundingBox.max); var boundingBox = new Box3(min, max); var offset = min.clone(); boundingBox.min.sub(offset); boundingBox.max.sub(offset); octree.projection = metadata.projection; octree.boundingBox = boundingBox; octree.tightBoundingBox = boundingBox.clone(); octree.boundingSphere = boundingBox.getBoundingSphere(new Sphere()); octree.tightBoundingSphere = boundingBox.getBoundingSphere(new Sphere()); octree.offset = offset; octree.pointAttributes = OctreeLoader.parseAttributes(metadata.attributes); octree.loader = loader; var root = new OctreeGeometryNode("r", octree, boundingBox); root.level = 0; root.nodeType = 2; root.hierarchyByteOffset = 0n; root.hierarchyByteSize = BigInt(metadata.hierarchy.firstChunkSize); root.hasChildren = false; root.spacing = octree.spacing; root.byteOffset = 0; octree.root = root; loader.load(root); var result = { geometry: octree }; return result; } } ; /** * @author Connor Manning */ class EptLoader { static async load(file, callback) { var response = await fetch(file); var json = await response.json(); var url = file.substr(0, file.lastIndexOf('ept.json')); var geometry = new Potree.PointCloudEptGeometry(url, json); var root = new Potree.PointCloudEptGeometryNode(geometry); geometry.root = root; geometry.root.load(); callback(geometry); } } ; class EptBinaryLoader { extension() { return '.bin'; } workerPath() { return Potree.scriptPath + '/workers/EptBinaryDecoderWorker.js'; } load(node) { if (node.loaded) return; var url = node.url() + this.extension(); var xhr = XHRFactory.createXMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'arraybuffer'; xhr.overrideMimeType('text/plain; charset=x-user-defined'); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status === 200) { var buffer = xhr.response; this.parse(node, buffer); } else { console.log('Failed ' + url + ': ' + xhr.status); } } }; try { xhr.send(null); } catch (e) { console.log('Failed request: ' + e); } } parse(node, buffer) { var workerPath = this.workerPath(); var worker = Potree.workerPool.getWorker(workerPath); worker.onmessage = function (e) { var g = new BufferGeometry(); var numPoints = e.data.numPoints; var position = new Float32Array(e.data.position); g.setAttribute('position', new BufferAttribute(position, 3)); var indices = new Uint8Array(e.data.indices); g.setAttribute('indices', new BufferAttribute(indices, 4)); if (e.data.color) { var color = new Uint8Array(e.data.color); g.setAttribute('color', new BufferAttribute(color, 4, true)); } if (e.data.intensity) { var intensity = new Float32Array(e.data.intensity); g.setAttribute('intensity', new BufferAttribute(intensity, 1)); } if (e.data.classification) { var classification = new Uint8Array(e.data.classification); g.setAttribute('classification', new BufferAttribute(classification, 1)); } if (e.data.returnNumber) { var returnNumber = new Uint8Array(e.data.returnNumber); g.setAttribute('return number', new BufferAttribute(returnNumber, 1)); } if (e.data.numberOfReturns) { var numberOfReturns = new Uint8Array(e.data.numberOfReturns); g.setAttribute('number of returns', new BufferAttribute(numberOfReturns, 1)); } if (e.data.pointSourceId) { var pointSourceId = new Uint16Array(e.data.pointSourceId); g.setAttribute('source id', new BufferAttribute(pointSourceId, 1)); } g.attributes.indices.normalized = true; var tightBoundingBox = new Box3(new Vector3().fromArray(e.data.tightBoundingBox.min), new Vector3().fromArray(e.data.tightBoundingBox.max)); node.doneLoading(g, tightBoundingBox, numPoints, new Vector3(...e.data.mean)); Potree.workerPool.returnWorker(workerPath, worker); }; var toArray = v => [v.x, v.y, v.z]; var message = { buffer: buffer, schema: node.ept.schema, scale: node.ept.eptScale, offset: node.ept.eptOffset, mins: toArray(node.key.b.min) }; worker.postMessage(message, [message.buffer]); } } ; /** * laslaz code taken and adapted from plas.io js-laslaz * http://plas.io/ * https://github.com/verma/plasio * * Thanks to Uday Verma and Howard Butler * */ class EptLaszipLoader { load(node) { if (node.loaded) return; var url = node.url() + '.laz'; var xhr = XHRFactory.createXMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'arraybuffer'; xhr.overrideMimeType('text/plain; charset=x-user-defined'); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status === 200) { var buffer = xhr.response; this.parse(node, buffer); } else { console.log('Failed ' + url + ': ' + xhr.status); } } }; xhr.send(null); } async parse(node, buffer) { var lf = new LASFile(buffer); var handler = new EptLazBatcher(node); try { await lf.open(); lf.isOpen = true; var header = await lf.getHeader(); { var i = 0; var toArray = v => [v.x, v.y, v.z]; var mins = toArray(node.key.b.min); var maxs = toArray(node.key.b.max); var hasMoreData = true; while (hasMoreData) { var data = await lf.readData(1000000, 0, 1); var d = new LASDecoder(data.buffer, header.pointsFormatId, header.pointsStructSize, data.count, header.scale, header.offset, mins, maxs); d.extraBytes = header.extraBytes; d.pointsFormatId = header.pointsFormatId; handler.push(d); i += data.count; hasMoreData = data.hasMoreData; } header.totalRead = i; header.versionAsString = lf.versionAsString; header.isCompressed = lf.isCompressed; await lf.close(); lf.isOpen = false; } } catch (err) { console.error('Error reading LAZ:', err); if (lf.isOpen) { await lf.close(); lf.isOpen = false; } throw err; } } } ; class EptLazBatcher { constructor(node) { this.node = node; } push(las) { var workerPath = Potree.scriptPath + '/workers/EptLaszipDecoderWorker.js'; var worker = Potree.workerPool.getWorker(workerPath); worker.onmessage = e => { var g = new BufferGeometry(); var numPoints = las.pointsCount; var positions = new Float32Array(e.data.position); var colors = new Uint8Array(e.data.color); var intensities = new Float32Array(e.data.intensity); var classifications = new Uint8Array(e.data.classification); var returnNumbers = new Uint8Array(e.data.returnNumber); var numberOfReturns = new Uint8Array(e.data.numberOfReturns); var pointSourceIDs = new Uint16Array(e.data.pointSourceID); var indices = new Uint8Array(e.data.indices); var gpsTime = new Float32Array(e.data.gpsTime); g.setAttribute('position', new BufferAttribute(positions, 3)); g.setAttribute('rgba', new BufferAttribute(colors, 4, true)); g.setAttribute('intensity', new BufferAttribute(intensities, 1)); g.setAttribute('classification', new BufferAttribute(classifications, 1)); g.setAttribute('return number', new BufferAttribute(returnNumbers, 1)); g.setAttribute('number of returns', new BufferAttribute(numberOfReturns, 1)); g.setAttribute('source id', new BufferAttribute(pointSourceIDs, 1)); g.setAttribute('indices', new BufferAttribute(indices, 4)); g.setAttribute('gpsTime', new BufferAttribute(gpsTime, 1)); this.node.gpsTime = e.data.gpsMeta; g.attributes.indices.normalized = true; var tightBoundingBox = new Box3(new Vector3().fromArray(e.data.tightBoundingBox.min), new Vector3().fromArray(e.data.tightBoundingBox.max)); this.node.doneLoading(g, tightBoundingBox, numPoints, new Vector3(...e.data.mean)); Potree.workerPool.returnWorker(workerPath, worker); }; var message = { buffer: las.arrayb, numPoints: las.pointsCount, pointSize: las.pointSize, pointFormatID: las.pointsFormatId, scale: las.scale, offset: las.offset, mins: las.mins, maxs: las.maxs }; worker.postMessage(message, [message.buffer]); } } ; class EptZstandardLoader extends EptBinaryLoader { extension() { return '.zst'; } workerPath() { return Potree.scriptPath + '/workers/EptZstandardDecoderWorker.js'; } } ; class ShapefileLoader { constructor() { this.transform = null; } async load(path, color) { var matLine = new LineMaterial({ color: color || 0xff0000, lineWidth: 3, // in pixels resolution: new Vector2(1000, 1000), dashed: false }); var features = await this.loadShapefileFeatures(path); var node = new Object3D(); var jump = 0; for (var feature of features) { //5是碎的 //if(feature.geometry.type!= 'MultiLineString' || ++jump != 5) continue var fnode = this.featureToSceneNode(feature, matLine); fnode && node.add(fnode); } var setResolution = (x, y) => { matLine.resolution.set(x, y); }; var result = { features: features, node: node, setResolution: setResolution }; return result; } featureToSceneNode(feature, matLine) { //console.log(feature) var geometry = feature.geometry; var color = new Color(1, 1, 1); var transform = this.transform; if (transform === null) { transform = { forward: v => v }; } if (geometry.type === "Point") { var sg = new SphereGeometry(1, 18, 18); var sm = new MeshNormalMaterial(); var s = new Mesh(sg, sm); var [long, lat] = geometry.coordinates; var pos = transform.forward([long, lat]); s.position.set(...pos, 20); s.scale.set(10, 10, 10); return s; } else if (geometry.type === "LineString") { var coordinates = []; var min = new Vector3(Infinity, Infinity, Infinity); for (var i = 0; i < geometry.coordinates.length; i++) { var [_long, _lat] = geometry.coordinates[i]; var _pos = transform.forward([_long, _lat]); min.x = Math.min(min.x, _pos[0]); min.y = Math.min(min.y, _pos[1]); min.z = Math.min(min.z, 20); coordinates.push(..._pos, 20); if (i > 0 && i < geometry.coordinates.length - 1) { coordinates.push(..._pos, 20); } } for (var _i = 0; _i < coordinates.length; _i += 3) { coordinates[_i + 0] -= min.x; coordinates[_i + 1] -= min.y; coordinates[_i + 2] -= min.z; } var lineGeometry = new LineGeometry(); lineGeometry.setPositions(coordinates); var line = new Line2(lineGeometry, matLine); line.computeLineDistances(); line.scale.set(1, 1, 1); line.position.copy(min); return line; } else if (geometry.type === "MultiLineString") { //xzw add 江门的那个文件 var _coordinates = []; //console.warn('MultiLineString') //多组连续线段,组之间不连续 var _min = new Vector3(Infinity, Infinity, Infinity); var _loop = function _loop() { var points = geometry.coordinates[_i2]; //有时候是两个点有时候多个 var coordinateSlice = []; points.forEach(point => { var [long, lat] = point; var pos = transform.forward([long, lat]); _min.x = Math.min(_min.x, pos[0]); _min.y = Math.min(_min.y, pos[1]); _min.z = Math.min(_min.z, 20); coordinateSlice.push(new Vector3(pos[0], pos[1], 20)); }); _coordinates.push(coordinateSlice); }; for (var _i2 = 0; _i2 < geometry.coordinates.length; _i2++) { _loop(); } _coordinates.forEach(coordinateSlice => coordinateSlice.forEach(point => point.sub(_min))); var _line = LineDraw.createFatLine(_coordinates, { uncontinuous: true, mat: matLine /* color: 0xff0000, dashSize: 0.5, gapSize: 0.2, lineWidth: config$1.measure.lineWidth, */ }); _line.position.copy(_min); return _line; } else if (geometry.type === "Polygon") { for (var pc of geometry.coordinates) { var _coordinates2 = []; var _min2 = new Vector3(Infinity, Infinity, Infinity); for (var _i3 = 0; _i3 < pc.length; _i3++) { var [_long2, _lat2] = pc[_i3]; var _pos2 = transform.forward([_long2, _lat2]); _min2.x = Math.min(_min2.x, _pos2[0]); _min2.y = Math.min(_min2.y, _pos2[1]); _min2.z = Math.min(_min2.z, 20); _coordinates2.push(..._pos2, 20); if (_i3 > 0 && _i3 < pc.length - 1) { _coordinates2.push(..._pos2, 20); } } for (var _i4 = 0; _i4 < _coordinates2.length; _i4 += 3) { _coordinates2[_i4 + 0] -= _min2.x; _coordinates2[_i4 + 1] -= _min2.y; _coordinates2[_i4 + 2] -= _min2.z; } var _lineGeometry = new LineGeometry(); _lineGeometry.setPositions(_coordinates2); var _line2 = new Line2(_lineGeometry, matLine); _line2.computeLineDistances(); _line2.scale.set(1, 1, 1); _line2.position.copy(_min2); return _line2; } } else { console.log("unhandled feature: ", geometry.type); } function getLine(coordinates) {} } async loadShapefileFeatures(file) { var features = []; if (file.split('.').pop() == 'shp') { var source = await shapefile.open(file); while (true) { var result = await source.read(); if (result.done) { break; } if (result.value && result.value.type === 'Feature' && result.value.geometry !== undefined) { features.push(result.value); } } return features; } else if (file.split('.').pop() == 'json') { return new Promise((resolve, reject) => { Potree.loadFile(file, {/* returnText:true */}, data => { console.log(data); resolve(data.features); }); }); } } } ; var defaultColors = { "landuse": [0.5, 0.5, 0.5], "natural": [0.0, 1.0, 0.0], "places": [1.0, 0.0, 1.0], "points": [0.0, 1.0, 1.0], "roads": [1.0, 1.0, 0.0], "waterways": [0.0, 0.0, 1.0], "default": [0.9, 0.6, 0.1] }; function getColor(feature) { var color = defaultColors[feature]; if (!color) { color = defaultColors["default"]; } return color; } class Geopackage$1 { constructor() { this.path = null; this.node = null; } } ; class GeoPackageLoader { constructor() {} static async loadUrl(url, params) { await Promise.all([Utils.loadScript("".concat(Potree.scriptPath, "/lazylibs/geopackage/geopackage.js")), Utils.loadScript("".concat(Potree.scriptPath, "/lazylibs/sql.js/sql-wasm.js"))]); var result = await fetch(url); var buffer = await result.arrayBuffer(); params = params || {}; params.source = url; return GeoPackageLoader.loadBuffer(buffer, params); } static async loadBuffer(buffer, params) { await Promise.all([Utils.loadScript("".concat(Potree.scriptPath, "/lazylibs/geopackage/geopackage.js")), Utils.loadScript("".concat(Potree.scriptPath, "/lazylibs/sql.js/sql-wasm.js"))]); params = params || {}; var resolver = async resolve => { var transform = params.transform; if (!transform) { transform = { forward: arg => arg }; } var wasmPath = "".concat(Potree.scriptPath, "/lazylibs/sql.js/sql-wasm.wasm"); var SQL = await initSqlJs({ locateFile: filename => wasmPath }); var u8 = new Uint8Array(buffer); var data = await geopackage.open(u8); window.data = data; var geopackageNode = new Object3D(); geopackageNode.name = params.source; geopackageNode.potree = { source: params.source }; var geo = new Geopackage$1(); geo.path = params.source; geo.node = geopackageNode; var tables = data.getTables(); for (var table of tables.features) { var dao = data.getFeatureDao(table); var boundingBox = dao.getBoundingBox(); boundingBox = boundingBox.projectBoundingBox(dao.projection, 'EPSG:4326'); var geoJson = data.queryForGeoJSONFeaturesInTable(table, boundingBox); var matLine = new LineMaterial({ color: new Color().setRGB(...getColor(table)), linewidth: 2, resolution: new Vector2(1000, 1000), dashed: false }); var node = new Object3D(); node.name = table; geo.node.add(node); for (var [index, feature] of Object.entries(geoJson)) { //const featureNode = GeoPackageLoader.featureToSceneNode(feature, matLine, transform); var featureNode = GeoPackageLoader.featureToSceneNode(feature, matLine, dao.projection, transform); node.add(featureNode); } } resolve(geo); }; return new Promise(resolver); } static featureToSceneNode(feature, matLine, geopackageProjection, transform) { var geometry = feature.geometry; var color = new Color(1, 1, 1); if (feature.geometry.type === "Point") { var sg = new SphereGeometry(1, 18, 18); var sm = new MeshNormalMaterial(); var s = new Mesh(sg, sm); var [long, lat] = geometry.coordinates; var pos = transform.forward(geopackageProjection.forward([long, lat])); s.position.set(...pos, 20); s.scale.set(10, 10, 10); return s; } else if (geometry.type === "LineString") { var coordinates = []; var min = new Vector3(Infinity, Infinity, Infinity); for (var i = 0; i < geometry.coordinates.length; i++) { var [_long, _lat] = geometry.coordinates[i]; var _pos = transform.forward(geopackageProjection.forward([_long, _lat])); min.x = Math.min(min.x, _pos[0]); min.y = Math.min(min.y, _pos[1]); min.z = Math.min(min.z, 20); coordinates.push(..._pos, 20); if (i > 0 && i < geometry.coordinates.length - 1) { coordinates.push(..._pos, 20); } } for (var _i = 0; _i < coordinates.length; _i += 3) { coordinates[_i + 0] -= min.x; coordinates[_i + 1] -= min.y; coordinates[_i + 2] -= min.z; } var lineGeometry = new LineGeometry(); lineGeometry.setPositions(coordinates); var line = new Line2(lineGeometry, matLine); line.computeLineDistances(); line.scale.set(1, 1, 1); line.position.copy(min); return line; } else if (geometry.type === "Polygon") { for (var pc of geometry.coordinates) { var _coordinates = []; var _min = new Vector3(Infinity, Infinity, Infinity); for (var _i2 = 0; _i2 < pc.length; _i2++) { var [_long2, _lat2] = pc[_i2]; var _pos2 = transform.forward(geopackageProjection.forward([_long2, _lat2])); _min.x = Math.min(_min.x, _pos2[0]); _min.y = Math.min(_min.y, _pos2[1]); _min.z = Math.min(_min.z, 20); _coordinates.push(..._pos2, 20); if (_i2 > 0 && _i2 < pc.length - 1) { _coordinates.push(..._pos2, 20); } } for (var _i3 = 0; _i3 < _coordinates.length; _i3 += 3) { _coordinates[_i3 + 0] -= _min.x; _coordinates[_i3 + 1] -= _min.y; _coordinates[_i3 + 2] -= _min.z; } var _lineGeometry = new LineGeometry(); _lineGeometry.setPositions(_coordinates); var _line = new Line2(_lineGeometry, matLine); _line.computeLineDistances(); _line.scale.set(1, 1, 1); _line.position.copy(_min); return _line; } } else { console.log("unhandled feature: ", feature); } } } ; class ClipVolume extends Object3D { constructor(args) { super(); this.constructor.counter = this.constructor.counter === undefined ? 0 : this.constructor.counter + 1; this.name = "clip_volume_" + this.constructor.counter; var alpha = args.alpha || 0; var beta = args.beta || 0; var gamma = args.gamma || 0; this.rotation.x = alpha; this.rotation.y = beta; this.rotation.z = gamma; this.clipOffset = 0.001; this.clipRotOffset = 1; var boxGeometry = new BoxGeometry(1, 1, 1); boxGeometry.computeBoundingBox(); var boxFrameGeometry = new Geometry(); { // bottom boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5)); // top boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5)); // sides boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5)); boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5)); boxFrameGeometry.colors.push(new Vector3(1, 1, 1)); } var planeFrameGeometry = new Geometry(); { // middle line planeFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.0)); planeFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.0)); planeFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.0)); planeFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.0)); planeFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.0)); planeFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.0)); planeFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.0)); planeFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.0)); } this.dimension = new Vector3(1, 1, 1); this.material = new MeshBasicMaterial({ color: 0x00ff00, transparent: true, opacity: 0.3, depthTest: true, depthWrite: false }); this.box = new Mesh(boxGeometry, this.material); this.box.geometry.computeBoundingBox(); this.boundingBox = this.box.geometry.boundingBox; this.add(this.box); this.frame = new LineSegments(boxFrameGeometry, new LineBasicMaterial({ color: 0x000000 })); this.add(this.frame); this.planeFrame = new LineSegments(planeFrameGeometry, new LineBasicMaterial({ color: 0xff0000 })); this.add(this.planeFrame); // set default thickness this.setScaleZ(0.1); // create local coordinate system var createArrow = (name, direction, color) => { var material = new MeshBasicMaterial({ color: color, depthTest: false, depthWrite: false }); var shaftGeometry = new Geometry(); shaftGeometry.vertices.push(new Vector3(0, 0, 0)); shaftGeometry.vertices.push(new Vector3(0, 1, 0)); var shaftMaterial = new LineBasicMaterial({ color: color, depthTest: false, depthWrite: false, transparent: true }); var shaft = new Line(shaftGeometry, shaftMaterial); shaft.name = name + "_shaft"; var headGeometry = new CylinderGeometry(0, 0.04, 0.1, 10, 1, false); var headMaterial = material; var head = new Mesh(headGeometry, headMaterial); head.name = name + "_head"; head.position.y = 1; var arrow = new Object3D(); arrow.name = name; arrow.add(shaft); arrow.add(head); return arrow; }; this.arrowX = createArrow("arrow_x", new Vector3(1, 0, 0), 0xFF0000); this.arrowY = createArrow("arrow_y", new Vector3(0, 1, 0), 0x00FF00); this.arrowZ = createArrow("arrow_z", new Vector3(0, 0, 1), 0x0000FF); this.arrowX.rotation.z = -Math.PI / 2; this.arrowZ.rotation.x = Math.PI / 2; this.arrowX.visible = false; this.arrowY.visible = false; this.arrowZ.visible = false; this.add(this.arrowX); this.add(this.arrowY); this.add(this.arrowZ); { // event listeners this.addEventListener("ui_select", e => { this.arrowX.visible = true; this.arrowY.visible = true; this.arrowZ.visible = true; }); this.addEventListener("ui_deselect", e => { this.arrowX.visible = false; this.arrowY.visible = false; this.arrowZ.visible = false; }); this.addEventListener("select", e => { var scene_header = $("#" + this.name + " .scene_header"); if (!scene_header.next().is(":visible")) { scene_header.click(); } }); this.addEventListener("deselect", e => { var scene_header = $("#" + this.name + " .scene_header"); if (scene_header.next().is(":visible")) { scene_header.click(); } }); } this.update(); } setClipOffset(offset) { this.clipOffset = offset; } setClipRotOffset(offset) { this.clipRotOffset = offset; } setScaleX(x) { this.box.scale.x = x; this.frame.scale.x = x; this.planeFrame.scale.x = x; } setScaleY(y) { this.box.scale.y = y; this.frame.scale.y = y; this.planeFrame.scale.y = y; } setScaleZ(z) { this.box.scale.z = z; this.frame.scale.z = z; this.planeFrame.scale.z = z; } offset(args) { var cs = args.cs || null; var axis = args.axis || null; var dir = args.dir || null; if (!cs || !axis || !dir) return; if (axis === "x") { if (cs === "local") { this.position.add(this.localX.clone().multiplyScalar(dir * this.clipOffset)); } else if (cs === "global") { this.position.x = this.position.x + dir * this.clipOffset; } } else if (axis === "y") { if (cs === "local") { this.position.add(this.localY.clone().multiplyScalar(dir * this.clipOffset)); } else if (cs === "global") { this.position.y = this.position.y + dir * this.clipOffset; } } else if (axis === "z") { if (cs === "local") { this.position.add(this.localZ.clone().multiplyScalar(dir * this.clipOffset)); } else if (cs === "global") { this.position.z = this.position.z + dir * this.clipOffset; } } this.dispatchEvent({ "type": "clip_volume_changed", "viewer": viewer, "volume": this }); } rotate(args) { var cs = args.cs || null; var axis = args.axis || null; var dir = args.dir || null; if (!cs || !axis || !dir) return; if (cs === "local") { if (axis === "x") { this.rotateOnAxis(new Vector3(1, 0, 0), dir * this.clipRotOffset * Math.PI / 180); } else if (axis === "y") { this.rotateOnAxis(new Vector3(0, 1, 0), dir * this.clipRotOffset * Math.PI / 180); } else if (axis === "z") { this.rotateOnAxis(new Vector3(0, 0, 1), dir * this.clipRotOffset * Math.PI / 180); } } else if (cs === "global") { var rotaxis = new Vector4(1, 0, 0, 0); if (axis === "y") { rotaxis = new Vector4(0, 1, 0, 0); } else if (axis === "z") { rotaxis = new Vector4(0, 0, 1, 0); } this.updateMatrixWorld(); var invM = newthis.matrixWorld.clone().invert(); rotaxis = rotaxis.applyMatrix4(invM).normalize(); rotaxis = new Vector3(rotaxis.x, rotaxis.y, rotaxis.z); this.rotateOnAxis(rotaxis, dir * this.clipRotOffset * Math.PI / 180); } this.updateLocalSystem(); this.dispatchEvent({ "type": "clip_volume_changed", "viewer": viewer, "volume": this }); } update() { this.boundingBox = this.box.geometry.boundingBox; this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere()); this.box.visible = false; this.updateLocalSystem(); } updateLocalSystem() { // extract local coordinate axes var rotQuat = this.getWorldQuaternion(); this.localX = new Vector3(1, 0, 0).applyQuaternion(rotQuat).normalize(); this.localY = new Vector3(0, 1, 0).applyQuaternion(rotQuat).normalize(); this.localZ = new Vector3(0, 0, 1).applyQuaternion(rotQuat).normalize(); } raycast(raycaster, intersects) { var is = []; this.box.raycast(raycaster, is); if (is.length > 0) { var I = is[0]; intersects.push({ distance: I.distance, object: this, point: I.point.clone() }); } } } ; //这个文件只是clipping polygon的,没用到 class ClippingTool extends EventDispatcher$1 { constructor(viewer) { super(); this.viewer = viewer; this.maxPolygonVertices = 8; this.addEventListener("start_inserting_clipping_volume", e => { this.viewer.dispatchEvent({ type: "cancel_insertions" }); }); this.sceneMarker = new Scene(); this.sceneVolume = new Scene(); this.sceneVolume.name = "scene_clip_volume"; this.viewer.inputHandler.registerInteractiveScene(this.sceneVolume); this.onRemove = e => { this.sceneVolume.remove(e.volume); }; this.onAdd = e => { this.sceneVolume.add(e.volume); }; this.viewer.inputHandler.addEventListener("delete", e => { var volumes = e.selection.filter(e => e instanceof ClipVolume); volumes.forEach(e => this.viewer.scene.removeClipVolume(e)); var polyVolumes = e.selection.filter(e => e instanceof PolygonClipVolume); polyVolumes.forEach(e => this.viewer.scene.removePolygonClipVolume(e)); }); } setScene(scene) { if (this.scene === scene) { return; } if (this.scene) { this.scene.removeEventListeners("clip_volume_added", this.onAdd); this.scene.removeEventListeners("clip_volume_removed", this.onRemove); this.scene.removeEventListeners("polygon_clip_volume_added", this.onAdd); this.scene.removeEventListeners("polygon_clip_volume_removed", this.onRemove); } this.scene = scene; this.scene.addEventListener("clip_volume_added", this.onAdd); this.scene.addEventListener("clip_volume_removed", this.onRemove); this.scene.addEventListener("polygon_clip_volume_added", this.onAdd); this.scene.addEventListener("polygon_clip_volume_removed", this.onRemove); } startInsertion() { var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var type = args.type || null; if (!type) return null; var domElement = this.viewer.renderer.domElement; var canvasSize = this.viewer.renderer.getSize(new Vector2()); var svg = $("\n\t\t\n\n\t\t\t\n\t\t\t\t \n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\n\n\t\t\t\n\n\t\t\t\n\t\t")); $(domElement.parentElement).append(svg); var polyClipVol = new PolygonClipVolume(this.viewer.scene.getActiveCamera().clone()); this.dispatchEvent({ "type": "start_inserting_clipping_volume" }); this.viewer.scene.addPolygonClipVolume(polyClipVol); this.sceneMarker.add(polyClipVol); var cancel = { callback: null }; var insertionCallback = e => { if (e.button === MOUSE.LEFT) { polyClipVol.addMarker(); // SVC Screen Line svg.find("polyline").each((index, target) => { var newPoint = svg[0].createSVGPoint(); newPoint.x = e.offsetX; newPoint.y = e.offsetY; var polyline = target.points.appendItem(newPoint); }); if (polyClipVol.markers.length > this.maxPolygonVertices) { cancel.callback(); } this.viewer.inputHandler.startDragging(polyClipVol.markers[polyClipVol.markers.length - 1]); } else if (e.button === MOUSE.RIGHT) { cancel.callback(e); } }; cancel.callback = e => { //let first = svg.find("polyline")[0].points[0]; //svg.find("polyline").each((index, target) => { // let newPoint = svg[0].createSVGPoint(); // newPoint.x = first.x; // newPoint.y = first.y; // let polyline = target.points.appendItem(newPoint); //}); svg.remove(); if (polyClipVol.markers.length > 3) { polyClipVol.removeLastMarker(); polyClipVol.initialized = true; } else { this.viewer.scene.removePolygonClipVolume(polyClipVol); } this.viewer.renderer.domElement.removeEventListener("mouseup", insertionCallback, true); this.viewer.removeEventListener("cancel_insertions", cancel.callback); this.viewer.inputHandler.enabled = true; }; this.viewer.addEventListener("cancel_insertions", cancel.callback); this.viewer.renderer.domElement.addEventListener("mouseup", insertionCallback, true); this.viewer.inputHandler.enabled = false; polyClipVol.addMarker(); this.viewer.inputHandler.startDragging(polyClipVol.markers[polyClipVol.markers.length - 1]); return polyClipVol; } update() {} } ; var GeoTIFF = function (exports) { 'use strict'; var Endianness = new Enum({ LITTLE: "II", BIG: "MM" }); var Type = new Enum({ BYTE: { value: 1, bytes: 1 }, ASCII: { value: 2, bytes: 1 }, SHORT: { value: 3, bytes: 2 }, LONG: { value: 4, bytes: 4 }, RATIONAL: { value: 5, bytes: 8 }, SBYTE: { value: 6, bytes: 1 }, UNDEFINED: { value: 7, bytes: 1 }, SSHORT: { value: 8, bytes: 2 }, SLONG: { value: 9, bytes: 4 }, SRATIONAL: { value: 10, bytes: 8 }, FLOAT: { value: 11, bytes: 4 }, DOUBLE: { value: 12, bytes: 8 } }); var Tag = new Enum({ IMAGE_WIDTH: 256, IMAGE_HEIGHT: 257, BITS_PER_SAMPLE: 258, COMPRESSION: 259, PHOTOMETRIC_INTERPRETATION: 262, STRIP_OFFSETS: 273, ORIENTATION: 274, SAMPLES_PER_PIXEL: 277, ROWS_PER_STRIP: 278, STRIP_BYTE_COUNTS: 279, X_RESOLUTION: 282, Y_RESOLUTION: 283, PLANAR_CONFIGURATION: 284, RESOLUTION_UNIT: 296, SOFTWARE: 305, COLOR_MAP: 320, SAMPLE_FORMAT: 339, MODEL_PIXEL_SCALE: 33550, // [GeoTIFF] TYPE: double N: 3 MODEL_TIEPOINT: 33922, // [GeoTIFF] TYPE: double N: 6 * NUM_TIEPOINTS GEO_KEY_DIRECTORY: 34735, // [GeoTIFF] TYPE: short N: >= 4 GEO_DOUBLE_PARAMS: 34736, // [GeoTIFF] TYPE: short N: variable GEO_ASCII_PARAMS: 34737 // [GeoTIFF] TYPE: ascii N: variable }); var typeMapping = new Map([[Type.BYTE, Uint8Array], [Type.ASCII, Uint8Array], [Type.SHORT, Uint16Array], [Type.LONG, Uint32Array], [Type.RATIONAL, Uint32Array], [Type.SBYTE, Int8Array], [Type.UNDEFINED, Uint8Array], [Type.SSHORT, Int16Array], [Type.SLONG, Int32Array], [Type.SRATIONAL, Int32Array], [Type.FLOAT, Float32Array], [Type.DOUBLE, Float64Array]]); class IFDEntry { constructor(tag, type, count, offset, value) { this.tag = tag; this.type = type; this.count = count; this.offset = offset; this.value = value; } } class Image { constructor() { this.width = 0; this.height = 0; this.buffer = null; this.metadata = []; } } class Reader { constructor() {} static read(data) { var endiannessTag = String.fromCharCode(...Array.from(data.slice(0, 2))); var endianness = Endianness.fromValue(endiannessTag); var tiffCheckTag = data.readUInt8(2); if (tiffCheckTag !== 42) { throw new Error("not a valid tiff file"); } var offsetToFirstIFD = data.readUInt32LE(4); console.log("offsetToFirstIFD", offsetToFirstIFD); var ifds = []; var IFDsRead = false; var currentIFDOffset = offsetToFirstIFD; var i = 0; while (IFDsRead || i < 100) { console.log("currentIFDOffset", currentIFDOffset); var numEntries = data.readUInt16LE(currentIFDOffset); var nextIFDOffset = data.readUInt32LE(currentIFDOffset + 2 + numEntries * 12); console.log("next offset: ", currentIFDOffset + 2 + numEntries * 12); var entryBuffer = data.slice(currentIFDOffset + 2, currentIFDOffset + 2 + 12 * numEntries); for (var _i = 0; _i < numEntries; _i++) { var tag = Tag.fromValue(entryBuffer.readUInt16LE(_i * 12)); var type = Type.fromValue(entryBuffer.readUInt16LE(_i * 12 + 2)); var count = entryBuffer.readUInt32LE(_i * 12 + 4); var offsetOrValue = entryBuffer.readUInt32LE(_i * 12 + 8); var valueBytes = type.bytes * count; var value = void 0; if (valueBytes <= 4) { value = offsetOrValue; } else { var valueBuffer = new Uint8Array(valueBytes); valueBuffer.set(data.slice(offsetOrValue, offsetOrValue + valueBytes)); var ArrayType = typeMapping.get(type); value = new ArrayType(valueBuffer.buffer); if (type === Type.ASCII) { value = String.fromCharCode(...value); } } var ifd = new IFDEntry(tag, type, count, offsetOrValue, value); ifds.push(ifd); } console.log("nextIFDOffset", nextIFDOffset); if (nextIFDOffset === 0) { break; } currentIFDOffset = nextIFDOffset; i++; } var ifdForTag = tag => { for (var entry of ifds) { if (entry.tag === tag) { return entry; } } return null; }; var width = ifdForTag(Tag.IMAGE_WIDTH, ifds).value; var height = ifdForTag(Tag.IMAGE_HEIGHT, ifds).value; var compression = ifdForTag(Tag.COMPRESSION, ifds).value; var rowsPerStrip = ifdForTag(Tag.ROWS_PER_STRIP, ifds).value; var ifdStripOffsets = ifdForTag(Tag.STRIP_OFFSETS, ifds); var ifdStripByteCounts = ifdForTag(Tag.STRIP_BYTE_COUNTS, ifds); var numStrips = Math.ceil(height / rowsPerStrip); var stripByteCounts = []; for (var _i2 = 0; _i2 < ifdStripByteCounts.count; _i2++) { var _type = ifdStripByteCounts.type; var offset = ifdStripByteCounts.offset + _i2 * _type.bytes; var _value = void 0; if (_type === Type.SHORT) { _value = data.readUInt16LE(offset); } else if (_type === Type.LONG) { _value = data.readUInt32LE(offset); } stripByteCounts.push(_value); } var stripOffsets = []; for (var _i3 = 0; _i3 < ifdStripOffsets.count; _i3++) { var _type2 = ifdStripOffsets.type; var _offset = ifdStripOffsets.offset + _i3 * _type2.bytes; var _value2 = void 0; if (_type2 === Type.SHORT) { _value2 = data.readUInt16LE(_offset); } else if (_type2 === Type.LONG) { _value2 = data.readUInt32LE(_offset); } stripOffsets.push(_value2); } var imageBuffer = new Uint8Array(width * height * 3); var linesProcessed = 0; for (var _i4 = 0; _i4 < numStrips; _i4++) { var stripOffset = stripOffsets[_i4]; var stripBytes = stripByteCounts[_i4]; var stripData = data.slice(stripOffset, stripOffset + stripBytes); var lineBytes = width * 3; for (var y = 0; y < rowsPerStrip; y++) { var line = stripData.slice(y * lineBytes, y * lineBytes + lineBytes); imageBuffer.set(line, linesProcessed * lineBytes); if (line.length === lineBytes) { linesProcessed++; } else { break; } } } console.log("width: ".concat(width)); console.log("height: ".concat(height)); console.log("numStrips: ".concat(numStrips)); console.log("stripByteCounts", stripByteCounts.join(", ")); console.log("stripOffsets", stripOffsets.join(", ")); var image = new Image(); image.width = width; image.height = height; image.buffer = imageBuffer; image.metadata = ifds; return image; } } class Exporter { constructor() {} static toTiffBuffer(image) { var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var offsetToFirstIFD = 8; var headerBuffer = new Uint8Array([0x49, 0x49, 42, 0, offsetToFirstIFD, 0, 0, 0]); var [width, height] = [image.width, image.height]; var ifds = [new IFDEntry(Tag.IMAGE_WIDTH, Type.SHORT, 1, null, width), new IFDEntry(Tag.IMAGE_HEIGHT, Type.SHORT, 1, null, height), new IFDEntry(Tag.BITS_PER_SAMPLE, Type.SHORT, 4, null, new Uint16Array([8, 8, 8, 8])), new IFDEntry(Tag.COMPRESSION, Type.SHORT, 1, null, 1), new IFDEntry(Tag.PHOTOMETRIC_INTERPRETATION, Type.SHORT, 1, null, 2), new IFDEntry(Tag.ORIENTATION, Type.SHORT, 1, null, 1), new IFDEntry(Tag.SAMPLES_PER_PIXEL, Type.SHORT, 1, null, 4), new IFDEntry(Tag.ROWS_PER_STRIP, Type.LONG, 1, null, height), new IFDEntry(Tag.STRIP_BYTE_COUNTS, Type.LONG, 1, null, width * height * 3), new IFDEntry(Tag.PLANAR_CONFIGURATION, Type.SHORT, 1, null, 1), new IFDEntry(Tag.RESOLUTION_UNIT, Type.SHORT, 1, null, 1), new IFDEntry(Tag.SOFTWARE, Type.ASCII, 6, null, "......"), new IFDEntry(Tag.STRIP_OFFSETS, Type.LONG, 1, null, null), new IFDEntry(Tag.X_RESOLUTION, Type.RATIONAL, 1, null, new Uint32Array([1, 1])), new IFDEntry(Tag.Y_RESOLUTION, Type.RATIONAL, 1, null, new Uint32Array([1, 1]))]; if (params.ifdEntries) { ifds.push(...params.ifdEntries); } var valueOffset = offsetToFirstIFD + 2 + ifds.length * 12 + 4; // create 12 byte buffer for each ifd and variable length buffers for ifd values var ifdEntryBuffers = new Map(); var ifdValueBuffers = new Map(); for (var ifd of ifds) { var entryBuffer = new ArrayBuffer(12); var entryView = new DataView(entryBuffer); var valueBytes = ifd.type.bytes * ifd.count; entryView.setUint16(0, ifd.tag.value, true); entryView.setUint16(2, ifd.type.value, true); entryView.setUint32(4, ifd.count, true); if (ifd.count === 1 && ifd.type.bytes <= 4) { entryView.setUint32(8, ifd.value, true); } else { entryView.setUint32(8, valueOffset, true); var valueBuffer = new Uint8Array(ifd.count * ifd.type.bytes); if (ifd.type === Type.ASCII) { valueBuffer.set(new Uint8Array(ifd.value.split("").map(c => c.charCodeAt(0)))); } else { valueBuffer.set(new Uint8Array(ifd.value.buffer)); } ifdValueBuffers.set(ifd.tag, valueBuffer); valueOffset = valueOffset + valueBuffer.byteLength; } ifdEntryBuffers.set(ifd.tag, entryBuffer); } var imageBufferOffset = valueOffset; new DataView(ifdEntryBuffers.get(Tag.STRIP_OFFSETS)).setUint32(8, imageBufferOffset, true); var concatBuffers = buffers => { var totalLength = buffers.reduce((sum, buffer) => sum + buffer.byteLength, 0); var merged = new Uint8Array(totalLength); var offset = 0; for (var buffer of buffers) { merged.set(new Uint8Array(buffer), offset); offset += buffer.byteLength; } return merged; }; var ifdBuffer = concatBuffers([new Uint16Array([ifds.length]), ...ifdEntryBuffers.values(), new Uint32Array([0])]); var ifdValueBuffer = concatBuffers([...ifdValueBuffers.values()]); var tiffBuffer = concatBuffers([headerBuffer, ifdBuffer, ifdValueBuffer, image.buffer]); return { width: width, height: height, buffer: tiffBuffer }; } } exports.Tag = Tag; exports.Type = Type; exports.IFDEntry = IFDEntry; exports.Image = Image; exports.Reader = Reader; exports.Exporter = Exporter; return exports; }({}); class Message { constructor(content) { this.content = content; var closeIcon = "".concat(exports.resourcePath, "/icons/close.svg"); this.element = $("\n\t\t\t
\n\t\t\t\t\n\t\t\t\t\n\t\t\t
")); this.elClose = this.element.find("img[name=close]"); this.elContainer = this.element.find("span[name=content_container]"); if (typeof content === "string") { this.elContainer.append($("".concat(content, ""))); } else { this.elContainer.append(content); } } setMessage(content) { this.elContainer.empty(); if (typeof content === "string") { this.elContainer.append($("".concat(content, ""))); } else { this.elContainer.append(content); } } } class PointCloudSM { constructor(potreeRenderer) { this.potreeRenderer = potreeRenderer; this.threeRenderer = this.potreeRenderer.threeRenderer; this.target = new WebGLRenderTarget(2 * 1024, 2 * 1024, { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat, type: FloatType }); this.target.depthTexture = new DepthTexture(); this.target.depthTexture.type = UnsignedIntType; //this.threeRenderer.setClearColor(0x000000, 1); this.threeRenderer.setClearColor(0xff0000, 1); //HACK? removed while moving to three.js 109 //this.threeRenderer.clearTarget(this.target, true, true, true); { var oldTarget = this.threeRenderer.getRenderTarget(); this.threeRenderer.setRenderTarget(this.target); this.threeRenderer.clear(true, true, true); this.threeRenderer.setRenderTarget(oldTarget); } } setLight(light) { this.light = light; var fov = 180 * light.angle / Math.PI; var aspect = light.shadow.mapSize.width / light.shadow.mapSize.height; var near = 0.1; var far = light.distance === 0 ? 10000 : light.distance; this.camera = new PerspectiveCamera(fov, aspect, near, far); this.camera.up.set(0, 0, 1); this.camera.position.copy(light.position); var target = new Vector3().subVectors(light.position, light.getWorldDirection(new Vector3())); this.camera.lookAt(target); this.camera.updateProjectionMatrix(); this.camera.updateMatrix(); this.camera.updateMatrixWorld(); this.camera.matrixWorldInverse.copy(this.camera.matrixWorld).invert(); } setSize(width, height) { if (this.target.width !== width || this.target.height !== height) { this.target.dispose(); } this.target.setSize(width, height); } render(scene, camera) { this.threeRenderer.setClearColor(0x000000, 1); var oldTarget = this.threeRenderer.getRenderTarget(); this.threeRenderer.setRenderTarget(this.target); this.threeRenderer.clear(true, true, true); this.potreeRenderer.render(scene, this.camera, this.target, {}); this.threeRenderer.setRenderTarget(oldTarget); } } class Label extends EventDispatcher { constructor() { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(); this.position = o.pos; this.text = o.text || ''; this.elem = $('
'); o.className && this.elem.addClass(o.className); this.elem.find('a').html(this.text); $("#potree_labels").append(this.elem); this.pos2d = new Vector3(); this.dom = o.dom || viewer.renderArea; this.camera = o.camera || viewer.scene.getActiveCamera(); var update = e => { this.update(e); }; viewer.addEventListener('camera_changed', update); this.addEventListener('dispose', () => { viewer.removeEventListener('camera_changed', update); this.dispose(); }); } update() { if (!this.position || this.elem.hasClass('unvisible')) return; var p = Utils.getPos2d(this.position, viewer.mainViewport, this.dom); if (!p.trueSide) { this.elem.addClass("hide"); return; } this.elem.css({ left: p.pos.x + 'px', top: p.pos.y + 'px' }); this.elem.removeClass("hide"); this.pos2d = p.vector; } setVisible(visi) { if (!visi) { this.elem.addClass("unvisible"); } else { this.elem.removeClass("unvisible"); this.update(); } } setText(text) { this.text = text || ''; this.elem.find('a').html(this.text); } setPos(pos) { this.position = pos; } dispose() { this.elem.remove(); this.removeAllListeners(); } } //THREE.Vector2.name1 = 'ctrlPolygon' var verticalLine = new Line3(); //控制点和边的合集。具有可以拖拽修改的功能,拖拽时能防止线相交。 class ctrlPolygon extends Object3D { constructor(type, prop) { super(); this.type = type; this.maxMarkers = Number.MAX_SAFE_INTEGER; this.transformData(prop); for (var i in prop) { this[i] = prop[i]; } if ((this.atPlane || this.showArea) && this.closed && this.dimension == '2d') { this.areaPlane = this.createAreaPlane(); this.add(this.areaPlane); } //数据--刚开始一定是空的 this.points = []; //mesh 不一定有 this.markers = []; this.edges = []; this.center; } initData(prop) { //开始加数据 prop.dataset_points && (this.dataset_points = prop.dataset_points); prop.datasetId && (this.datasetId = prop.datasetId); prop.points_datasets && (this.points_datasets = prop.points_datasets); if (Potree.settings.editType == 'merge' || this.measureType == 'MulDistance Ring') { //融合页面没有地图,measure的不需要指定datasetId,每个点都有各自的datasetId,跟着各自的模型走 if (this.dataset_points) { this.dataset_points = this.dataset_points.map(e => { return e && new Vector3().copy(e); }); prop.points = this.dataset_points.map((p, i) => { return Potree.Utils.datasetPosTransform({ fromDataset: true, datasetId: this.points_datasets[i], position: p }); }); if (prop.points.some(e => e == void 0)) { return false; } } else { this.dataset_points = []; } } if (prop.points) { for (var p of prop.points) { var pos = new Vector3().copy(p); this.addMarker({ point: pos }); } if (Potree.settings.editType != 'merge' && this.measureType != 'MulDistance Ring') { if (this.datasetId != void 0) { //初始化位置 if (this.dataset_points) { this.dataset_points = this.dataset_points.map(e => { return e && new Vector3().copy(e); }); this.transformByPointcloud(); //根据dataset_points和this.datasetId生成points } } else { if (prop.dataset_points && prop.dataset_points.some(e => e != void 0)) { console.error('存在测量线的datasetId为空而dataset_points有值,请检查并删除:' + this.sid); //存在过的bug,原因未知,可能是后台处理dataset时替换的错误:http://192.168.0.21/index.php?m=bug&f=view&bugID=23601 console.log(this); } } } this.facePlane = this.getFacePlane(); this.getPoint2dInfo(this.points); this.update({ ifUpdateMarkers: true }); //this.dragChange(new THREE.Vector3().copy(prop.points[prop.points.length-1]), prop.points.length-1); this.setSelected(false); this.markers.forEach(marker => { marker.dispatchEvent('addHoverEvent'); }); return true; } } addMarker() { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var index = o.index == void 0 ? this.points.length : o.index; //要当第几个 this.points = [...this.points.slice(0, index), o.point.clone(), ...this.points.slice(index, this.points.length)]; //this.points.push(o.point); if ('dataset_point' in o) { //需要增加,可能是null this.dataset_points = this.dataset_points ? [...this.dataset_points.slice(0, index), o.dataset_point && o.dataset_point.clone(), ...this.dataset_points.slice(index, this.dataset_points.length)] : null; //如果原本是null,新加的应该也是 } if ('points_dataset' in o) { this.points_datasets = [...this.points_datasets.slice(0, index), o.points_dataset, ...this.points_datasets.slice(index, this.points_datasets.length)]; } if (o.marker) { this.add(o.marker); this.markers = [...this.markers.slice(0, index), o.marker, ...this.markers.slice(index, this.markers.length)]; this.updateMarker(o.marker, o.point); o.marker.addEventListener('drag', this.dragMarker.bind(this), { importance: 2 }); o.marker.addEventListener('drop', this.dropMarker.bind(this), { importance: 2 }); o.marker.createTime = Date.now(); var addHoverEvent = e => { var mouseover = e => { this.setMarkerSelected(e.object, 'hover', 'single'); viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "markerMove" }); }; var mouseleave = e => { this.setMarkerSelected(e.object, 'unhover', 'single'); viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "markerMove" }); }; o.marker.addEventListener('mouseover', mouseover); o.marker.addEventListener('mouseleave', mouseleave); o.marker.addEventListener('startDragging', e => { //for mobile this.setMarkerSelected(o.marker, 'hover', 'single'); this.dispatchEvent('startDragging'); }); o.marker.addEventListener('drop', e => { //for mobile this.setMarkerSelected(o.marker, 'unhover', 'single'); }); o.marker.removeEventListener('addHoverEvent', addHoverEvent); }; o.marker.addEventListener('addHoverEvent', addHoverEvent); //当非isNew时才添加事件 if (!this.isNew) { o.marker.dispatchEvent('addHoverEvent'); } } if (o.edge) { this.add(o.edge); this.edges = [...this.edges.slice(0, index), o.edge, ...this.edges.slice(index, this.edges.length)]; } } dragMarker(e) { var I, atMap; if (e.hoverViewport != e.drag.dragViewport) { //不能使用e.dragViewport,要使用drag中的,因为drag中存储的要一直继承下来,不因mouseup了而改变。 viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "polygon_AtWrongPlace" }); return; } if (e.drag.pointerDelta.length() == 0 && !this.isNew) { //部分设备(华为matePad11)在touchstart后立即执行了touchmove,导致marker立即移动,需要屏蔽..(刚创建时也会是0) return; } viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "polygon_AtWrongPlace" }); atMap = e.drag.dragViewport.name == 'mapViewport'; if (atMap && this.unableDragAtMap) { e.drag.object = null; //取消拖拽 return; } e.drag.object.isDragging = true; I = e.intersect && (e.intersect.adsorption ? e.intersect.location : e.intersect.orthoIntersect || e.intersect.location); if (viewer.inputHandler.pressedKeys[18] || Potree.settings.dragPolyBeyondPoint && !I) { //alt dragPolyBeyondPoint可以平移拖拽到无点的地方---测试用 var i = this.markers.indexOf(e.drag.object); I = this.points[i].clone(); var projected = I.clone().project(e.drag.dragViewport.camera); projected.x = e.pointer.x; projected.y = e.pointer.y; var unprojected = projected.clone().unproject(e.drag.dragViewport.camera); I.copy(unprojected); } if (I) { var _i = this.markers.indexOf(e.drag.object); if (_i !== -1) { this.dragChange(I.clone(), _i, atMap); if (this.points_datasets) { if (e.intersect) { if (e.intersect.pointcloud) this.points_datasets[_i] = e.intersect.pointcloud.dataset_id;else if (e.intersect.object) this.points_datasets[_i] = e.intersect.object.dataset_id;else { //地图 if (this.measureType == 'MulDistance Ring') { //因为它的每个point跟着各自的dataset走,而不是整体的dataset var pointcloud = viewer.findClosestDatasetOnMap(I) || viewer.scene.pointclouds[0]; this.points_datasets[_i] = pointcloud.dataset_id; } else this.points_datasets[_i] = null; } } } } this.editStateChange(true); return true; } } dragChange(intersectPos, i, atMap) { var len = this.markers.length; var oldPoint = this.points[i]; if (atMap) { intersectPos.setZ(oldPoint.z); //在地图上拖拽,不改变其高度。 } var location = intersectPos.clone(); if (this.faceDirection && this.maxMarkers == 2 && len == 2) { //add 固定方向的点不直接拖拽 var p1 = this.markers[0].position; if (this.faceDirection == 'horizontal') { var projectPos = location.clone().setZ(p1.z); } else { var projectPos = p1.clone().setZ(location.z); } //var p2 = p1.clone().add(this.direction) //var projectPos = math.getFootPoint(location, p1, p2) LineDraw.updateLine(this.guideLine, [location, projectPos]); location = projectPos; this.guideLine.visible = true; } else if (len > 1) { var points = this.points.map(e => e.clone()); points[i].copy(location); //算normal需要提前确认point //若为定义了面朝向的矩形 if (this.faceDirection == 'horizontal') { if (len == 2) { location.setZ(points[0].z); } if (!this.facePlane) { //一个点就能确定面 this.facePlane = new Plane().setFromNormalAndCoplanarPoint(new Vector3(0, 0, 1), this.points[0]); } } else if (this.faceDirection == 'vertical') { //当有两个点时, 有两个方向的可能 if (len == 2) { if (this.isRect) { var _vec = points[0].clone().sub(location); if (Math.sqrt(_vec.x * _vec.x + _vec.y * _vec.y) > Math.abs(_vec.z)) { //水平(高度差小于水平距离时) location.setZ(points[0].z); //this.cannotConfirmNormal = false;//能确定面为水平方向 } else { //垂直 (当两点一样时也属于这种) location.setX(points[0].x); location.setY(points[0].y); //this.cannotConfirmNormal = true; //不能确定面,因第三点可绕着纵轴线自由移动 } } } else { { //判断cannotConfirmNormal. 如果前几段都在竖直线上,就不能固定出面方向。 this.cannotConfirmNormal = true; var max = this.isRect ? 1 : len - 2; for (var _i2 = 0; _i2 < max; _i2++) { var _p = points[_i2].clone(); var _p2 = points[_i2 + 1].clone(); var _vec2 = _p.sub(_p2); if (_vec2.x != 0 || _vec2.y != 0) { this.cannotConfirmNormal = false; break; } } } if (!this.facePlane || this.cannotConfirmNormal) { //三个点且为水平方向时,计算面 var points_ = points.map(e => new Vector2(e.x, e.y)); var points2 = getDifferentPoint(points_, 2); if (points2) { var normal = math.getNormal2d({ p1: points2[0], p2: points2[1] }); normal = new Vector3(normal.x, normal.y, 0); this.facePlane = new Plane().setFromNormalAndCoplanarPoint(normal, this.points[0]); } } } } if (len > 2) { if (!this.faceDirection && this.showArea) { if (len == 3 || this.isRect) this.cannotConfirmNormal = true; //当第三个点固定后(有四个点时)才能固定面 if (!this.facePlane || this.cannotConfirmNormal) { var points3 = getDifferentPoint(points, 3); //只有找到三个不同的点算拥有面和area if (points3) { this.facePlane = new Plane().setFromCoplanarPoints(...points3); } } } if (this.atPlane && this.facePlane && !this.cannotConfirmNormal) { //之后加的点一定要在面上 if (atMap) { //地图上用垂直线,得到和面的交点。 verticalLine.set(location.clone().setZ(100000), location.clone().setZ(-100000)); //确保长度范围覆盖所有测量面 location = this.facePlane.intersectLine(verticalLine, new Vector3()); if (!location) return; } else { location = this.facePlane.projectPoint(intersectPos, new Vector3()); } } points[i].copy(location); //再copy确认一次 if (len == 3 && this.faceDirection == 'horizontal' && this.closed) { //normal方向还不确定 会影响label在里侧还是外侧 var facePlane = new Plane().setFromCoplanarPoints(...points); if (facePlane.normal.z && facePlane.normal.z * this.facePlane.normal.z < 0) { this.facePlane.normal.z *= -1, this.facePlane.constant *= -1; //console.log(this.facePlane.normal, this.facePlane.constant) } } if (this.isRect) { //是矩形 (即使没有faceDirection也能执行) //根据前两个点计算当前和下一个点 var p1 = points[(i - 2 + len) % len]; var p2 = points[(i - 1 + len) % len]; if (p1.equals(p2)) { //意外情况:重复点两次 ( bug点,改了好多遍) if (this.faceDirection == 'vertical') { p2.add(new Vector3(0, 0, 0.0001)); } else { p2.add(new Vector3(0, 0.0001, 0)); } } //p3 : location var foot = math.getFootPoint(location, p1, p2); //p2 修改p2到垂足的位置 var vec = foot.clone().sub(location); var p4 = p1.clone().sub(vec); points[(i - 1 + len) % len].copy(foot); points[(i + 1) % len].copy(p4); this.setPosition((i - 1 + len) % len, foot); //p2 this.setPosition((i + 1) % len, p4); } this.getPoint2dInfo(points); var isIntersectSelf = this.atPlane && this.closed && !this.isRect && this.point2dInfo && this.intersectSelf(this.point2dInfo.points2d); //检测相交 this.isIntersectSelf = isIntersectSelf; if (isIntersectSelf) { //not-allowed if (!this.isNew && isIntersectSelf == 'lastLine') this.isIntersectSelf = 'all'; //已经画好了就不用特别对待最后一条线 if (this.isIntersectSelf == 'lastLine') { Potree.Utils.updateVisible(this.areaPlane, 'intersectLastLine', false); Potree.Utils.updateVisible(this.areaLabel, 'intersectLastLine', false); } else { viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "polygon_isIntersectSelf" }); return; } } if (!this.isIntersectSelf) { this.areaPlane && Potree.Utils.updateVisible(this.areaPlane, 'intersectLastLine', true); this.areaLabel && Potree.Utils.updateVisible(this.areaLabel, 'intersectLastLine', true); } if (!this.isIntersectSelf || this.isIntersectSelf == 'lastLine') { viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "polygon_isIntersectSelf" }); } } var showGuideLine = len > 1 && (this.faceDirection || len > 3); if (showGuideLine && this.guideLine) { LineDraw.updateLine(this.guideLine, [intersectPos, location]); this.guideLine.visible = true; } //console.log(this.points.map(e=>e.toArray())) } if (this.restrictArea) { var holes = this.restrictArea.holes.concat(this.restrictArea.parentHoles); var holesPoints = holes.filter(e => e != this && e.points.length > 2).map(e => e.points); if (!math.isPointInArea(this.restrictArea.points, holesPoints, location)) { viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "polygon_AtWrongPlace" }); this.isAtWrongPlace = true; return; } //就不处理相交线了。 有个缺点:floor上的hole可以限制room,但hole不受room限制,会导致room的marker被框在hole里而动不了。只能去调整hole了 } viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "polygon_AtWrongPlace" }); this.isAtWrongPlace = false; this.setPosition(i, location); this.update({ index: this.isRect ? null : i }); this.dispatchEvent({ type: 'dragChange', index: i }); } dropMarker(e) { //console.log('dropMarker') if (this.isNew && e.pressDistance > Potree.config.clickMaxDragDis) { //拖拽的话返回 return this.continueDrag(null, e); } if (e.hoverViewport != e.drag.dragViewport) { //copy from dragMarker, for sitemodel, only mapViewport can be dropped return this.continueDrag(null, e); } if (e.isTouch) { if (e.hoverViewport != viewer.mainViewport && this.unableDragAtMap) { viewer.dispatchEvent({ type: 'reticule_forbit', v: true }); //console.log('reticule_forbit',true) return this.continueDrag(null, e); } else { viewer.dispatchEvent({ type: 'reticule_forbit', v: false }); //console.log('reticule_forbit',false) } this.isNew && this.dragMarker(e); //isNew触屏点击时必须先更新下点,因为指尖不在屏幕上时没更新。但对已经创建的marker点击时不应该更新 } if (e.button != MOUSE.RIGHT && ( //右键click的话继续执行,因为会停止 this.isIntersectSelf == 'all' && this.isNew //有线相交了 || this.isAtWrongPlace && this.isNew || !e.isAtDomElement && this.isNew //如果是刚添加时在其他dom点击, 不要响应 || e.hoverViewport != viewer.mainViewport && this.unableDragAtMap //垂直的测量线不允许在地图上放点 || this.isNew && !getDifferentPoint(this.points, this.points.length) //不允许和之前的点相同, 但这句在点云稀疏时会导致难结束 )) { return this.continueDrag(null, e); } //console.log('drop marker' ) var i = this.markers.indexOf(e.drag.object); if (i !== -1) { this.dispatchEvent({ 'type': 'marker_dropped', 'index': i }); if (this.markers.length > 2 && this.facePlane) this.cannotConfirmNormal = false; this.guideLine && (this.guideLine.visible = false); } this.setMarkerSelected(e.drag.object, 'unhover', 'single'); this.editStateChange(false); e.drag.endDragFun && e.drag.endDragFun(e); // addmarker //if(this.changeCallBack)this.changeCallBack() return true; } getFacePlane() { //最普通一种get方法,根据顶点。且假设所有点已经共面,且不重合 if ( /* !this.atPlane || */this.points.length < 3) return; /* this.facePlane = new THREE.Plane().setFromCoplanarPoints(...this.points.slice(0,3) ) */ var facePlane = this.facePlane; if (!this.atPlane || !facePlane) { //多折线 没有实时更新facePlane所以重新算 var normal = new Vector3(), len = this.points.length - 2; for (var i = 0; i < len; i++) { //获取normal的顺序方法必须和setFromCoplanarPoints一致 var vec0 = new Vector3().subVectors(this.points[i + 2], this.points[i + 1]); var vec1 = new Vector3().subVectors(this.points[i], this.points[i + 1]); var nor = vec0.cross(vec1).normalize(); normal.add(nor); } normal.normalize(); facePlane = new Plane().setFromNormalAndCoplanarPoint(normal, this.points[0]); } return facePlane; } getPoint2dInfo(points) { //在更新areaplane之前必须更新过point2dInfo (针对所有点在同一平面上的) if (this.facePlane && (this.atPlane || Potree.settings.areaAtNotPlane)) { var facePlane = this.getFacePlane(); var originPoint0 = points[0].clone(); var qua = math.getQuaBetween2Vector(facePlane.normal, new Vector3(0, 0, 1), new Vector3(0, 0, 1)); var points2d = points.map(e => e.clone().applyQuaternion(qua)); this.point2dInfo = { originPoint0, points2d, quaInverse: qua.clone().invert() }; } } setPosition(index, position) { //拖拽后设置位置 var point = this.points[index]; point.copy(position); /* if(this.datasetId){ this.dataset_points[index] = Potree.Utils.datasetPosTransform({toDataset:true, datasetId:this.datasetId, position:point.clone()}) } */ /* if(Potree.settings.editType == 'merge'){ this.dataset_points[index] = Potree.Utils.datasetPosTransform({toDataset:true,this.points_datasets[i], position:point.clone()}) } */ var marker = this.markers[index]; this.updateMarker(marker, point); } updateMarker(marker, pos) { marker.position.copy(pos); marker.waitUpdate(); } intersectSelf(points2d) { //add var len = points2d.length; for (var i = 0; i < len; i++) { for (var j = i + 2; j < len; j++) { if (Math.abs(j - len - i) < 2) continue; //不和邻边比 var p1 = points2d[i]; var p2 = points2d[i + 1]; var p3 = points2d[j]; var p4 = points2d[(j + 1) % len]; if (p1.equals(p2) || p3.equals(p4) || p1.equals(p3) || p2.equals(p3) || p1.equals(p4) || p2.equals(p4)) continue; var line1 = [p1, p2]; var line2 = [p3, p4]; var intersect = math.isLineIntersect(line1, line2, false, 0.001); if (intersect) { if (i == len - 1 || j == len - 1) { //最后一条线。如果还没绘制完,最后的线还没定下,可被允许继续绘制,但无法显示面积。 return 'lastLine'; } else { return 'all'; } break; } } } } removeMarker(index) { this.points.splice(index, 1); var marker = this.markers[index]; //this.remove(marker); this.markers.splice(index, 1); marker.dispose(); var edgeIndex = index; //(index === 0) ? 0 : (index - 1); var edge = this.edges[edgeIndex]; if (edge) { this.remove(edge); this.edges.splice(edgeIndex, 1); edge.geometry.dispose(); } this.point2dInfo && this.point2dInfo.points2d.splice(index, 1); //add this.dispatchEvent({ type: 'removeMarker', index, marker }); } createAreaPlane(mat) { var geometry = new Geometry(); var mesh = new Mesh(geometry, mat); return mesh; } updateAreaPlane() { this.areaPlane.geometry.dispose(); if (this.points.length > 2) { if (this.isPrism) { var z = this.horizonZ || 0; var points2d = this.points.map(e => e.clone().setZ(z)); this.areaPlane.geometry = MeshDraw.getShapeGeo(points2d); //z=0 var center = math.getCenterOfGravityPoint(points2d); //重心 this.areaPlaneCenter = new Vector3(center.x, center.y, z); this.areaPlane.position.z = z; } else if (this.point2dInfo) { if (Potree.settings.areaAtNotPlane) { //测点不在同一平面的面积. (缺点:容易出现三角缺块, 以及搭错线导致超出理想边界外。在平面上n个点能构成n-2个三角形,但空间中更多个,所以若要指定出类似平面那样n-2个三角形是有多种可能的。故暂不开放。 用d3.Delaunay结果更差) //测试桥面 SG-arqnGgAR7om&formal //参考 http://indoor.popsmart.cn:8084/sxswsw-sx/ 找到场景中面积测量线的方法:window.scene.children[18].children[0].material.color.r = 1 var geometry = new Geometry(); var faceArray = [], triangles = ShapeUtils.triangulateShape(this.point2dInfo.points2d, []); //因为它只关注xy平面,垂直画就容易错,所以用转到平面的points2d来识别三角。 if (triangles.length == 0) return; this._area = 0; for (var i = 0; i < triangles.length; i++) { faceArray[i] = new Face3(triangles[i][0], triangles[i][1], triangles[i][2]); var nor = new Vector3().crossVectors(new Vector3().subVectors(this.points[triangles[i][0]], this.points[triangles[i][2]]), new Vector3().subVectors(this.points[triangles[i][1]], this.points[triangles[i][2]])); this._area += nor.length() / 2; nor.normalize(); faceArray[i].normal.copy(nor); } geometry.vertices = this.points; geometry.faces = faceArray; this.areaPlane.geometry = new BufferGeometry().fromGeometry(geometry); //不知道为何不转为bufferGeometry显示不出 //this.center //参考getFacePlane 在这里建立_normal? } else { //if(this.point2dInfo){//旧的。 之前的规定点要在同一平面 this.areaPlane.geometry = MeshDraw.getShapeGeo(this.point2dInfo.points2d); var _center = math.getCenterOfGravityPoint(this.point2dInfo.points2d); //重心 var firstPos = this.point2dInfo.points2d[0].clone(); firstPos.z = 0; //因为shape只读取了xy,所以位移下, 再算出最终位置,得到差距 firstPos.applyQuaternion(this.point2dInfo.quaInverse); var vec = this.point2dInfo.originPoint0.clone().sub(firstPos); _center = new Vector3(_center.x, _center.y, 0); _center.applyQuaternion(this.point2dInfo.quaInverse); this.areaPlane.quaternion.copy(this.point2dInfo.quaInverse); this.areaPlane.position.copy(vec); _center.add(vec); this.center = _center; //} } } } else { this.areaPlane.geometry = new Geometry(); } } getIndex(index, add) { var lastIndex = this.points.length - 1; if (add == -1) return index === 0 ? lastIndex : index - 1;else if (add == 1) return index + 1 > lastIndex ? 0 : index + 1; } update() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (this.points.length === 0) { return; } //performance.mark('measureUpdate-start') var lastIndex = this.points.length - 1; if (options.index != void 0) { //更新第几个点 this.updateMarker(this.markers[options.index], this.points[options.index]); var previousIndex = this.getIndex(options.index, -1); var nextIndex = this.getIndex(options.index, +1); if (this.closed || nextIndex != 0) LineDraw.updateLine(this.edges[options.index], [this.points[options.index], this.points[nextIndex]]); if (this.closed || previousIndex != lastIndex) LineDraw.updateLine(this.edges[previousIndex], [this.points[options.index], this.points[previousIndex]]); } else { for (var index = 0; index <= lastIndex; index++) { var _nextIndex = this.getIndex(index, +1); var _previousIndex = this.getIndex(index, -1); var point = this.points[index]; var nextPoint = this.points[_nextIndex]; var previousPoint = this.points[_previousIndex]; if (options.ifUpdateMarkers) { this.updateMarker(this.markers[index], point); } if (!this.closed && _nextIndex == 0) break; //add { var edge = this.edges[index]; if (edge) { LineDraw.updateLine(edge, [point, nextPoint]); } } } } if (this.areaPlane) { this.updateAreaPlane(); } //this.dispatchEvent({type:'update'}) viewer.dispatchEvent('content_changed'); viewer.mapViewer && viewer.mapViewer.dispatchEvent('content_changed'); //暂时先这么都通知 //performance.mark('measureUpdate-end') //let measure = performance.measure('measure-','measureUpdate-start', 'measureUpdate-end' ); //console.log('update-time', measure.duration) } createPrismLines(color) { this.lineMesh = LineDraw.createLine([], { color }); this.lineMesh.name = 'PrismLines'; this.add(this.lineMesh); } updatePrismLines() { if (!this.lineMesh) return; var positions = []; var length = this.points.length; this.points.forEach((point, index) => { //竖线: positions.push(point.clone().setZ(this.zMin), point.clone().setZ(this.zMax)); //横线 var nextPoint = this.points[(index + 1) % length]; if (!nextPoint) return; //when length==1 positions.push(point.clone().setZ(this.zMax), nextPoint.clone().setZ(this.zMax)); //上横线 positions.push(point.clone().setZ(this.zMin), nextPoint.clone().setZ(this.zMin)); //下横线 }); LineDraw.moveLine(this.lineMesh, positions); viewer.dispatchEvent('content_changed'); } dispose() { //add this.parent.remove(this); this.markers.forEach(e => e.dispose()); this.edges.forEach(e => e.geometry.dispose()); } reDraw() { var restMarkerCount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; //重新开始画 var pointCount = this.points.length - restMarkerCount; // restMarkerCount为需要留下的marker数量 while (pointCount > 0) { this.removeMarker(--pointCount); } this.point2dInfo = null; this.facePlane = null; } setMarkerSelected() {} editStateChange(state) { if (!state) { viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "polygon_isIntersectSelf" }); viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "polygon_AtWrongPlace" }); viewer.dispatchEvent({ type: 'reticule_forbit', v: false }); this.markers.forEach(e => e.isDragging = false); } } transformData(prop) { var pick = (defaul, alternative) => { if (defaul != null) { return defaul; } else { return alternative; } }; prop.showDistances = prop.showDistances === null ? true : prop.showDistances; prop.showArea = pick(prop.showArea, false); prop.showAngles = pick(prop.showAngles, false); prop.showCoordinates = pick(prop.showCoordinates, false); prop.showHeight = pick(prop.showHeight, false); prop.showCircle = pick(prop.showCircle, false); prop.showAzimuth = pick(prop.showAzimuth, false); prop.showEdges = pick(prop.showEdges, true); prop.closed = pick(prop.closed, false); prop.maxMarkers = pick(prop.maxMarkers, Infinity); prop.direction = prop.direction; //add prop.type = prop.type; prop.showGuideLine = pick(prop.showGuideLine, false); prop.isRect = pick(prop.isRect, false); } setSelected() {} continueDrag(marker, e) { var object = marker || e.drag.object; object.isDragging = true; this.editStateChange(true); var timer = setTimeout(() => { //等 drag=null之后 //右键拖拽结束后需要重新得到drag if (this.parent && object.parent && object.isDragging) { //console.log('continueDrag') viewer.inputHandler.startDragging(object, { endDragFun: e.drag.endDragFun, notPressMouse: e.drag.notPressMouse, dragViewport: e.drag.dragViewport }); } }, 1); return timer; } } function getDifferentPoint(points, count) { //for facePlane var result = []; for (var i = 0; i < points.length; i++) { var p = points[i]; if (result.find(e => e.equals(p))) continue;else result.push(p); if (result.length == count) break; } if (result.length == count) return result; } var texLoader$6 = new TextureLoader(); var defaultColor$1 = new Color(config$1.measure.default.color); var highlightColor = new Color(config$1.measure.highlight.color); var color = new Color(config$1.measure.color); var textColor = new Color(config$1.measure.textColor); var markerMats; var lineMats; var planeMats; var textSizeRatio = math.linearClamp(window.outerWidth * window.outerHeight, [360 * 720, 1920 * 1080], [0.7, 1]); //pc字显示大一些 用 var lineDepthInfo = { clipDistance: 15, //4,//消失距离 occlusionDistance: 3 //1,//变为backColor距离 }; var markerMapShrink = browser.isMobile() ? 0.4 : 0.8; //触屏需要更大的热区 var markerSizeInfo = { width2d: 18 / markerMapShrink // nearBound : 1.5, farBound : 15, }; /* const markerSizeInfo = { minSize : 10 , maxSize : 15 , nearBound : 1.5, farBound : 15, } */ var labelSizeInfo = { width2d: 200 }; var mainLabelProp = { //backgroundColor: {r: defaultColor.r*255, g: defaultColor.g*255, b: defaultColor.b*255, a:config.measure.default.opacity}, backgroundColor: { r: 0, g: 0, b: 0, a: 0 }, textColor: { r: textColor.r * 255, g: textColor.g * 255, b: textColor.b * 255, a: 1.0 }, textBorderColor: { r: 255, g: 255, b: 255, a: 1.0 }, textBorderThick: 3, fontsize: 15 * textSizeRatio, borderRadius: 12, margin: { x: 20, y: 4 }, renderOrder: Potree.config.renderOrders.measureLabel, pickOrder: Potree.config.renderOrders.measureLabel, disToLine: -0.15, useDepth: true, // 2023.10 尽量不让数字被挡住 clipDistance: 10, //消失距离 occlusionDistance: 10, //变为backColor距离 maxOcclusionFactor: 0.3, maxClipFactor: 0.8 }; var subLabelProp = { backgroundColor: { r: 255, g: 255, b: 255, a: 0 }, textColor: { r: textColor.r * 255, g: textColor.g * 255, b: textColor.b * 255, a: 1.0 }, textBorderColor: { r: 255, g: 255, b: 255, a: 1.0 }, textBorderThick: 3, fontsize: 14 * textSizeRatio, renderOrder: Potree.config.renderOrders.measureLabelSub, pickOrder: Potree.config.renderOrders.measureLabelSub, disToLine: -0.13 }; var angle = MathUtils.degToRad(5); //显示水平垂直辅助线的最小角度 var guideShowMinAngle = { min: angle, max: Math.PI / 2 - angle }; class Measure$1 extends ctrlPolygon { constructor(prop) { prop.dimension = '2d'; super('measure', prop); this.constructor.counter = this.constructor.counter === undefined ? 0 : this.constructor.counter + 1; this.name = this.measureType + this.constructor.counter; //'Measure_' + this.constructor.counter; this.markerLabels = []; this.edgeLabels = []; this.angleLabels = []; this.coordinateLabels = []; this.area = { value: 0, string: '' }; if (this.showArea) { this.areaLabel = this.createAreaLabel(); this.add(this.areaLabel); } //add: if (this.atPlane || this.faceDirection) { //是一个平面上的话 this.createGuideLine(); } if (this.measureType == 'Distance' /* || this.measureType.includes('MulDistance') */) { this.createHorVerGuideLine(); } this.selectStates = {}; this.setUnitSystem(prop.unit || viewer.unitConvert.UnitService.defaultSystem); Potree.Utils.setObjectLayers(this, 'measure'); if (this.measureType == 'MulDistance' || this.measureType == 'Hor MulDistance' || this.measureType == 'Ver MulDistance') { //this.showTotalDis = true this.totalDisLabel = this.createTotalDisLabel(); this.add(this.totalDisLabel); } //addMarkers: this.initData(prop); this.pointsPos2d = new Map(); //屏幕上的二维坐标 this.points_datasets || (this.points_datasets = []); //存每个点是哪个数据集 this.addEventListener('marker_dropped', e => { this.updateDatasetBelong(e.index); }); this.addEventListener('isVisible', () => { viewer.mapViewer && viewer.mapViewer.dispatchEvent({ type: 'content_changed' }); }); this.lastDropTime = 0; } initData(prop) { var makeIt = super.initData(prop); if (makeIt) { this.edges.forEach(edge => { edge.dispatchEvent('addHoverEvent'); }); } else { this.failBuilded = true; } } updateDatasetBelong(changeIndex) { //更新所属数据集 if (Potree.settings.editType == "merge" || this.measureType == 'MulDistance Ring') { //点直接跟着数据集走,不用找整体的datasetId this.dataset_points[changeIndex] = Potree.Utils.datasetPosTransform({ toDataset: true, datasetId: this.points_datasets[changeIndex], position: this.points[changeIndex].clone() }); return; } var old = this.datasetId; var maxCount = { id: null, count: 0 }; var datasets = {}; this.points_datasets.forEach(e => { if (e == void 0) return; if (datasets[e]) { datasets[e]++; } else { datasets[e] = 1; } }); for (var i in datasets) { if (datasets[i] > maxCount.count) { maxCount = { id: i, count: datasets[i] }; } } this.datasetId = maxCount.count > 0 ? maxCount.id : null; //if(this.datasetId != old){ //this.dispatchEvent({type:'changeDatasetId'}) if (this.datasetId == void 0) { this.dataset_points = null; //可能为空或[null,null...] } else { this.dataset_points = this.points.map(e => { return Potree.Utils.datasetPosTransform({ toDataset: true, datasetId: this.datasetId, position: e.clone() }); }); } //} } transformByPointcloud() { //每次移动点云 or 加载测量线时要获取一下当前position //有地图时 if (this.datasetId == void 0) return; this.points = this.dataset_points.map(e => { return Potree.Utils.datasetPosTransform({ fromDataset: true, datasetId: this.datasetId, position: e.clone() }); }); this.getPoint2dInfo(this.points); this.update({ ifUpdateMarkers: true }); this.setSelected(false); //隐藏edgelabel } update() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (options.index == -1) return; super.update(options); if (this.showCoordinates && this.points.length > 0) { var position = this.points[0]; this.markers[0].position.copy(position); { // coordinate labels var coordinateLabel = this.coordinateLabels[0]; var pos = [position.toArray()]; if (viewer.transform) { var lonlat = viewer.transform.lonlatToLocal.inverse(position.toArray()); var EPSG4550 = viewer.transform.lonlatTo4550.forward(lonlat); pos.push(lonlat, EPSG4550); } //let msg = position.toArray().map(p => Utils.addCommas(p.toFixed(2))).join(" / "); var msg = pos.map(a => a.map(p => Utils.addCommas(p.toFixed(10))).join(", ")).join("
"); coordinateLabel.setText(msg); coordinateLabel.setPos(position); coordinateLabel.setVisible(true); //this.showCoordinates; } return; } var setEdgeLabel = (label, p1, p2, distance) => { //设置label位置和字 this.setEdgeLabelPos(label, p1, p2); distance = distance == void 0 ? p1.distanceTo(p2) : distance; //var text = viewer.unitConvert.convert(distance, 'distance', Potree.settings.precision, this.unitSystem, 1 , true)//distance要传0.1 这个factor var text = this.getConvertString(distance, 'distance'); label.setText(text); return distance; }; /* let setEdgeLabel = (label,p1,p2,distance)=>{//设置label位置和字 this.setEdgeLabelPos(label,p1,p2) distance = distance == void 0 ? p1.distanceTo(p2) : distance; var text = this.labelText || viewer.unitConvert.convert(distance, 'distance', Potree.settings.precision , this.unitSystem, 0.001 , true, true)//distance要传0.1 这个factor label.setText(text) } */ var lastIndex = this.points.length - 1; var setLabel = index => { var previousIndex = this.getIndex(index, -1); var nextIndex = this.getIndex(index, +1); var previousPoint = this.points[previousIndex]; var point = this.points[index]; var nextPoint = this.points[nextIndex]; if (this.showDistances) { // edge labels var edgeLabel = this.edgeLabels[index]; var distance = point.distanceTo(nextPoint); this.edges[index].distance_ = distance; edgeLabel.shouldVisi = (index < lastIndex || this.isRect || this.closed && !this.isNew) && distance > 0; //this.closed || edgeLabel.setVisible(edgeLabel.shouldVisi) //closed的在setEdgesDisplay中设置 Utils.updateVisible(edgeLabel, 'shouldVisi', edgeLabel.shouldVisi, 2); if (edgeLabel.shouldVisi) { edgeLabel.lineDir = new Vector3().subVectors(point, nextPoint).normalize(); //[point,nextPoint] setEdgeLabel(edgeLabel, point, nextPoint, distance); } } }; if (options.index != void 0) { //更新第几个点 setLabel(options.index); var previousIndex = this.getIndex(options.index, -1); setLabel(previousIndex); } else { for (var index = 0; index <= lastIndex; index++) { setLabel(index); } } if (Potree.config.measure.mulLabelHideFaraway) { this.measureType == 'MulDistance' && this.clearEdgeLabelVisi(); } if (this.measureType == 'Distance' && this.points.length > 1) { //设置水平垂直辅助线 var pTop, pBtm; if (this.points[0].z > this.points[1].z) { pTop = this.points[0]; pBtm = this.points[1]; } else { pTop = this.points[1]; pBtm = this.points[0]; } var projectPos = new Vector3(pTop.x, pTop.y, pBtm.z); //两条guideline的交点 { //倾斜角度太小的时候不显示 var tan = pTop.distanceTo(projectPos) / pBtm.distanceTo(projectPos); var _angle = Math.atan(tan); this.shouldShowHorVerGuide = _angle > guideShowMinAngle.min && _angle < guideShowMinAngle.max; } LineDraw.updateLine(this.verGuideEdge, [pTop, projectPos]); LineDraw.updateLine(this.horGuideEdge, [pBtm, projectPos]); setEdgeLabel(this.verEdgeLabel, pTop, projectPos); setEdgeLabel(this.horEdgeLabel, pBtm, projectPos); this.verGuideEdge.visible = this.horGuideEdge.visible = this.shouldShowHorVerGuide; this.verEdgeLabel.visible = this.horEdgeLabel.visible = this.shouldShowHorVerGuide; } if (this.showArea && this.points.length > 2) { // update area var _msg = this.getArea().string; this.areaLabel.setPos(this.getCenter('areaPlaneCenter')); this.areaLabel.setText(_msg); Utils.updateVisible(this.areaLabel, 'setVisible', true); //this.areaLabel.setVisible(true) } if (this.totalDisLabel) { this.ifShowTotalDis(); Utils.updateVisible(this.totalDisLabel, 'setVisible', this.showTotalDis); this.edgeLabels.forEach(e => Utils.updateVisible(e, 'showTotalDis', !this.showTotalDis)); if (this.showTotalDis) { var dis = this.getTotalDistance(); var _msg2 = this.getConvertString(dis, 'distance'); this.center = null; this.center = this.getCenter(); this.totalDisLabel.setPos(this.center); this.totalDisLabel.setText(_msg2); } } } getArea() { var area; if (this._area != void 0) { area = this._area; } else if (this.point2dInfo) { area = Math.abs(math.getArea(this.point2dInfo.points2d)); //this.getArea(); } else { //mulDistance Ring 2d面 area = Math.abs(math.getArea(this.points)); } var msg = this.getConvertString(area, 'area'); //let msg = viewer.unitConvert.convert(area, 'area', Potree.settings.precision, this.unitSystem/* , 0.1 */ ) this.area = { value: area, string: msg }; return this.area; } getConvertString(num, type) { return viewer.unitConvert.convert(num, type, Potree.settings.precision, this.unitSystem, true, { 'imperial': { minFactor: 0.01 }, 'metric': { minFactor: 0.01 } }); } ifShowTotalDis() { var show = this.points.length > 2; if (show) { var maxDis = 0.15; var lastIndex = this.points.length - 1; for (var i = 0; i < lastIndex; i++) { var len = this.edges[i].distance_; if (len > maxDis) { show = false; break; } } } this.showTotalDis = show; /* 连续测量: 1. ≥2次测量,单个距离<15cm时,居中显示总长, hover、选中时显示每段长度 2. 若连续测量的线段中,大于等于1段超出15cm,所有线段均显示长度 ------------------- */ } clearEdgeLabelVisi() { //修改点位置后清空,下次render时会自动getEdgeLabelVisi var lastIndex = this.points.length - 1; for (var index = 0; index <= lastIndex; index++) { if (!this.closed && index == lastIndex) continue; var edgeLabel = this.edgeLabels[index]; edgeLabel.visiMap.clear(); } } getEdgeLabelVisi(viewport) { //获取多折线的edgelabel在不同视图里的可见性。要保证任何时候label能出现的线最小二维长度一致 var camera = viewport.camera; var lastIndex = this.points.length - 1; /* let pos2ds = this.points.map(point=> point.clone().project(camera) ) //即使只是旋转也会变动,尤其是转到屏幕外后变为显示。所以不用这种 let minDis = 0.01; */ var minDis = 0.02, minAngleRatio = 0.07, minAngle; var vecs; var forceShow; if (camera.type == 'OrthographicCamera') { minDis *= Math.pow(camera.top / camera.zoom, 2); //console.log(minDis) } else { if (Potree.settings.displayMode == 'showPanos' && viewer.images360.zoomLevel == Potree.settings.zoom.max) { forceShow = true; //当zoom到最大时强制显示,避免有的线太短永远显示不出长度 } else { vecs = this.points.map(point => new Vector3().subVectors(point, camera.position).normalize()); minAngleRatio /= viewport.resolution.y / 1000 / textSizeRatio; //角度占fov最小比率 minAngle = minAngleRatio * MathUtils.degToRad(camera.fov); } } for (var index = 0; index <= lastIndex; index++) { if (!this.closed && index == lastIndex) continue; var edgeLabel = this.edgeLabels[index]; var nextIndex = index + 1 > lastIndex ? 0 : index + 1; var previousIndex = index === 0 ? lastIndex : index - 1; var point = this.points[index]; var nextPoint = this.points[nextIndex]; /* let point2d = pos2ds[index]; let nextPoint2d = pos2ds[nextIndex]; let dis2d = point2d.distanceToSquared(nextPoint2d) let v = dis2d > minDis //可见长度太小,为避免拥挤,不显示 edgeLabel.visiMap.set(camera, v) */ var v = void 0; if (forceShow) { v = true; } else if (camera.type == 'OrthographicCamera') { var vec = new Vector3().subVectors(point, nextPoint); var projVec = vec.projectOnPlane(viewport.view.direction); v = projVec.lengthSq() > minDis; } else { var vec0 = vecs[index]; var vec1 = vecs[nextIndex]; v = Math.acos(vec0.dot(vec1)) > minAngle; //角度过小代表可见长度太小,为避免拥挤,不显示 } edgeLabel.visiMap.set(camera, v); } } setEdgeLabelPos(label, p1, p2) { //调整label的位置,使倾斜后看起来在线的中心,而不要挡住端点 var center = new Vector3().addVectors(p1, p2).multiplyScalar(0.5); return label.setPos(center); if (label.lineDir && label.lineDir.length() > 0) { if (viewer.mainViewport.camera.type == 'OrthographicCamera') { label.setPos(center); } else { //根据视线和线的夹角(后又加入相机和两个端点距离差)来决定标签偏移位置。+ var eyePos = viewer.mainViewport.camera.position; var dir = viewer.mainViewport.view.direction; //new THREE.Vector3().subVectors(center,eyePos).normalize() /*let centerDir = new THREE.Vector3().subVectors(center,eyePos).normalize() if(centerDir.dot(dir)<0){//中点在相机后方,就不设置 label.setPos(center) return } */ var cos = dir.dot(label.lineDir); var nearPoint = cos > 0 ? p2 : p1; //近端点。 var far = cos > 0 ? p1 : p2; //远端点。 var nearPointDir = new Vector3().subVectors(nearPoint, eyePos); //.normalize() //使label在中点和近端点中变化, 近端点可能到了相机后方,需要投影到相机所在平面上 if (nearPointDir.dot(dir) < 0) { //近端点到了相机后方,前移。 //let hfov = cameraLight.getHFOVForCamera(viewer.mainViewport.camera , true ); //暂且只看水平fov //if(nearPointDir.dot(dir) 0 ? label.lineDir : label.lineDir.clone().negate()); var camDirPlane = new Plane().setFromNormalAndCoplanarPoint(dir, eyePos); nearPoint = ray.ray.intersectPlane(camDirPlane, new Vector3()); if (!nearPoint) { //线是垂直的,视线是水平的时候 return label.setPos(center); } } //防止离远了之后也偏移很多,但远了之后相机到端点vec和到中点的vec的夹角接近,不需要怎么偏移的。 var dis1 = nearPoint.distanceToSquared(eyePos); var dis2 = far.distanceToSquared(eyePos); var diff = Math.abs(dis1 / dis2); diff < 1 && (diff = 1 / diff); diff = math.linearClamp(diff, [0, 30], [0, 1]); var efficiency = 0.7; // 0-1 数值越高,r越容易接近1或-1,label越容易在倾斜后靠近近端点。 //let r = 0.5*efficiency*cos + 0.5 var r = 0.5 * efficiency * diff * cos + 0.5; r = MathUtils.clamp(r, 0.1, 0.9); //视线越接近线的方向,标签应该越往近端点偏移,防止看起来几乎在远端。 if (cos > 0) { center = p1.clone().multiplyScalar(1 - r).add(nearPoint.clone().multiplyScalar(r)); //label在线上滑动,使尽量保持在视觉中心 } else { center = nearPoint.clone().multiplyScalar(1 - r).add(p2.clone().multiplyScalar(r)); //label在线上滑动,使尽量保持在视觉中心 } label.setPos(center); } //归零 //this.orient2dInfo = null //this.markers.forEach(e=>e.needsUpdate=true) } else { label.setPos(center); } } cloneMarker(cloneIndex, index) { return this.addMarker({ index, point: this.points[cloneIndex], dataset_point: this.dataset_points && this.dataset_points[cloneIndex], points_dataset: this.points_datasets[cloneIndex] }); } addMarker() { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var index = o.index == void 0 ? this.points.length : o.index; //要当第几个 var marker = new Sprite$2({ mat: this.getMarkerMaterial('default'), sizeInfo: markerSizeInfo, name: "measure_point" }); Potree.Utils.setObjectLayers(marker, 'measure'); marker.pickOrder = marker.renderOrder = Potree.config.renderOrders.measureMarker; marker.markerSelectStates = {}; marker.addEventListener('startDragging', e => { /* if(e.drag.dragViewport.name == 'MainView') */viewer.inputHandler.dispatchEvent({ type: 'measuring', v: true, cause: 'startDragging', situation: 'dragging', object: this }); //add for 调试,方便后期增加点 if (!this.isNew && viewer.inputHandler.pressedKeys['M'.charCodeAt(0)] && this.points.length < this.maxMarkers) { viewer.measuringTool.history.beforeChange(this); var curIndex = this.markers.indexOf(marker); this.cloneMarker(curIndex, curIndex + 1); } this.isNew || viewer.measuringTool.history.beforeChange(this); }); marker.addEventListener('drop', e => { if (e.button != MOUSE.LEFT) return; viewer.inputHandler.dispatchEvent({ type: 'measuring', v: false, cause: 'stopDragging', situation: 'dragging', object: this }); this.lastDropTime = Date.now(); if (Potree.settings.adsorption) { this.isNew || viewer.viewports.forEach(viewport => { this.getPointsPos2d(viewport, true); //forceUpdate }); } this.isNew || viewer.measuringTool.history.afterChange(this); }); marker.addEventListener('click', () => { if (viewer.measuringTool.editMode == 'delPoint') { /* if(this.points.length == this.minMarkers){//--前端去重绘 viewer.scene.removeMeasurement(this) }else{ */ viewer.measuringTool.history.beforeChange(this); var _index = this.markers.indexOf(marker); this.removeMarker(_index); viewer.measuringTool.history.afterChange(this); this.dispatchEvent('changed'); //} } }); //marker.measure = this var edge; { // edges edge = LineDraw.createFatLine([], { mat: this.getLineMat('edgeDefault') }); edge.pickOrder = 0; Potree.Utils.setObjectLayers(edge, 'measure'); var addHoverEvent = () => { //当非isNew时才添加事件 var mouseover = e => { /* if(this.measureType == 'MulDistance'){ } */ this.setSelected(true, 'edge'); }; var mouseleave = e => { this.setSelected(false, 'edge'); }; edge.addEventListener('mouseover', mouseover); edge.addEventListener('mouseleave', mouseleave); edge.removeEventListener('addHoverEvent', addHoverEvent); edge.addEventListener('click', e => { var now = Date.now(); if (now - this.lastDropTime < 100) return; //防止拖拽marker时误触导致focus, 以及点到marker不focus if (viewer.measuringTool.editMode == 'addPoint' && this.points.length < this.maxMarkers) { viewer.measuringTool.history.beforeChange(this); var _index2 = this.edges.indexOf(edge) + 1; var nextIndex = _index2 % this.edges.length; var point = math.getFootPoint(e.hoveredElement.point, this.points[_index2 - 1], this.points[nextIndex]); this.addMarker({ index: _index2, point, dataset_point: this.dataset_points && new Vector3(), //初始化 points_dataset: this.points_datasets[_index2 - 1] //使用前一个的 }); this.updateDatasetBelong(_index2); //获取dataset_point viewer.measuringTool.history.afterChange(this); this.dispatchEvent('changed'); //this.update({}) } else { this.isNew || viewer.measuringTool.isAdding || viewer.focusOnObject(this, 'measure'); //正在添加测量线时不要focus其他线(容易误触) } }); }; edge.addEventListener('addHoverEvent', addHoverEvent); if (!this.isNew) { edge.dispatchEvent('addHoverEvent'); } } super.addMarker(Object.assign(o, { index, marker, edge })); if (this.showEdges) { // edge labels var edgeLabel = this.createEdgeLabel('edgeLabel', !this.closed); this.edgeLabels = [...this.edgeLabels.slice(0, index), edgeLabel, ...this.edgeLabels.slice(index, this.edgeLabels.length)]; } if (this.showCoordinates) { // coordinate labels var coordinateLabel = new Label({ className: 'measure_pointPos', camera: viewer.scene.getActiveCamera() }); coordinateLabel.setVisible(false); this.coordinateLabels.push(coordinateLabel); } var event = { type: 'marker_added', measurement: this, marker: marker }; this.dispatchEvent(event); //this.setMarker(this.points.length - 1, point); this.update({ index }); //更新一下倒数第二条线 return marker; //add } editStateChange(state) { //主要针对edgeLabels显示切换,编辑时显示 super.editStateChange(state); if (!state) { this.editStateTimer = setTimeout(() => { if (!this.isEditing) { this.dispatchEvent({ type: 'editStateChange', state: false }); this.setEdgesDisplay(false); this.areaPlane && Potree.Utils.updateVisible(this.areaPlane, 'intersectLastLine', true); this.areaLabel && Potree.Utils.updateVisible(this.areaLabel, 'intersectLastLine', true); } }, 100); } else { if (!this.isEditing) { this.dispatchEvent({ type: 'editStateChange', state: true }); this.setEdgesDisplay(true); clearTimeout(this.editStateTimer); } } this.isEditing = state; } setMarkerSelected(marker, state, hoverObject) { //console.warn(marker.id , state, hoverObject) marker.markerSelectStates[hoverObject] = state; var absoluteState = false; for (var i in marker.markerSelectStates) { if (marker.markerSelectStates[i] == 'hover') { absoluteState = true; break; } } if (absoluteState) { marker.material = this.getMarkerMaterial('select'); marker.renderOrder = marker.pickOrder = Potree.config.renderOrders.measureMarker + 1; } else { marker.material = this.getMarkerMaterial('default'); marker.renderOrder = marker.pickOrder = Potree.config.renderOrders.measureMarker; } marker.selected = absoluteState; viewer.mapViewer && viewer.mapViewer.dispatchEvent('content_changed'); viewer.dispatchEvent('content_changed'); } setEdgesDisplay(state, ignoreGuideLine) { this.closed && this.edgeLabels.forEach(e => Utils.updateVisible(e, 'hover', state)); if (this.totalDisLabel && !viewer.screenshoting) { this.edgeLabels.forEach(e => Utils.updateVisible(e, 'hover', state, 1, state ? 'add' : 'cancel')); Utils.updateVisible(this.totalDisLabel, 'hover', !state); } if (!ignoreGuideLine && this.measureType == 'Distance') { this.horEdgeLabel.visible = this.verEdgeLabel.visible = this.horGuideEdge.visible = this.verGuideEdge.visible = !!(state && this.shouldShowHorVerGuide); } } setSelected(state, hoverObject) { //add //console.log('setSelected',state, hoverObject) var absoluteState = !!state; if (hoverObject) { //如果没有hoverObject且state为false 就强制取消选中态 this.selectStates[hoverObject] = state; for (var i in this.selectStates) { if (this.selectStates[i]) { absoluteState = true; break; } } } if (absoluteState) { this.markers.forEach(e => this.setMarkerSelected(e, 'hover', 'selectAll')); this.edges.forEach(e => { e.renderOrder = Potree.config.renderOrders.lines + 1; e.material = this.getLineMat('edgeSelect'); }); this.areaPlane && (this.areaPlane.material = planeMats.selected); //this.areaLabel && this.areaLabel.elem.addClass('highLight') //this.closed || this.edgeLabels.forEach(e=>e.elem.addClass('highLight') ) this.setEdgesDisplay(true, hoverObject == "screenshot"); this.areaLabel && setLabelHightState(this.areaLabel, true); this.closed || this.edgeLabels.forEach(e => setLabelHightState(e, true)); } else { this.markers.forEach(e => this.setMarkerSelected(e, 'unhover', 'selectAll')); this.edges.forEach(e => e.material = this.getLineMat('edgeDefault')); this.areaPlane && (this.areaPlane.material = planeMats.default); this.setEdgesDisplay(false, hoverObject == "screenshot"); //this.areaLabel && this.areaLabel.elem.removeClass('highLight') //this.closed || this.edgeLabels.forEach(e=>e.elem.removeClass('highLight') ) this.areaLabel && setLabelHightState(this.areaLabel, false); this.closed || this.edgeLabels.forEach(e => setLabelHightState(e, false)); } this.selected = absoluteState; if (hoverObject != 'byList') { //this.bus && this.bus.emit('highlight', this.selected) this.dispatchEvent({ type: 'highlight', state: this.selected }); //列表高亮 } viewer.dispatchEvent('content_changed'); viewer.mapViewer && viewer.mapViewer.dispatchEvent('content_changed'); } removeMarker(index) { super.removeMarker(index); this.points_datasets.splice(index, 1); this.dataset_points && this.dataset_points.splice(index, 1); this.coordinateLabels.splice(index, 1); var edgeIndex = index; //(index === 0) ? 0 : (index - 1); if (this.edgeLabels[edgeIndex]) { this.edgeLabels[edgeIndex].dispose(); this.edgeLabels.splice(edgeIndex, 1); } this.update({ index: this.getIndex(index, -1) }); this.dispatchEvent({ type: 'marker_removed', measurement: this }); } setPosition(index, position) { super.setPosition(index, position); var event = { type: 'marker_moved', measure: this, index: index, position: position.clone() }; this.dispatchEvent(event); } dispose() { //add var labels = this.edgeLabels.concat(this.coordinateLabels); this.areaLabel && labels.push(this.areaLabel); labels.forEach(e => e.dispose()); super.dispose(); this.dispatchEvent('disposed'); } getTotalDistance() { if (this.points.length === 0) { return 0; } var distance = 0; for (var i = 1; i < this.points.length; i++) { var prev = this.points[i - 1]; var curr = this.points[i]; var d = prev.distanceTo(curr); distance += d; } if (this.closed && this.points.length > 1) { var first = this.points[0]; var last = this.points[this.points.length - 1]; var _d = last.distanceTo(first); distance += _d; } return distance; } getAngleBetweenLines(cornerPoint, point1, point2) { var v1 = new Vector3().subVectors(point1, cornerPoint); var v2 = new Vector3().subVectors(point2, cornerPoint); // avoid the error printed by threejs if denominator is 0 var denominator = Math.sqrt(v1.lengthSq() * v2.lengthSq()); if (denominator === 0) { return 0; } else { return v1.angleTo(v2); } } getAngle(index) { if (this.points.length < 3 || index >= this.points.length) { return 0; } var previous = index === 0 ? this.points[this.points.length - 1] : this.points[index - 1]; var point = this.points[index]; var next = this.points[(index + 1) % this.points.length]; return this.getAngleBetweenLines(point, previous, next); } getCenter(type) { if (this.center) { return this.center.clone(); } else { var center = this.points.reduce(function (total, currentValue) { return total.add(currentValue); }, new Vector3()); this.points.length && center.multiplyScalar(1 / this.points.length); return center; //求不出重心呜呜 } } // updateAzimuth(){ // // if(this.points.length !== 2){ // // return; // // } // // const azimuth = this.azimuth; // // const [p0, p1] = this.points; // // const r = p0.distanceTo(p1); // } createGuideLine() { //add 辅助线 var guideLine = LineDraw.createFatLine([], { mat: this.getLineMat('guide') }); guideLine.visible = false; this.guideLine = guideLine; this.add(guideLine); } createHorVerGuideLine() { //创建水平与垂直辅助线,仅距离测量有。 var verGuideEdge = LineDraw.createFatLine([], { mat: this.getLineMat('guide') }); verGuideEdge.visible = false; this.verGuideEdge = verGuideEdge; verGuideEdge.name = 'verGuideEdge'; var horGuideEdge = LineDraw.createFatLine([], { mat: this.getLineMat('guide') }); horGuideEdge.visible = false; horGuideEdge.name = 'horGuideEdge'; this.horGuideEdge = horGuideEdge; this.add(this.verGuideEdge); this.add(this.horGuideEdge); //label: this.verEdgeLabel = this.createEdgeLabel('verGuideEdge'); this.horEdgeLabel = this.createEdgeLabel('horGuideEdge'); } createEdgeLabel(name, hasHoverEvent) { var inf = { sizeInfo: labelSizeInfo, name: name || 'edgeLabel' }; if (name && name.includes('Guide')) { inf.fontsize = 12; } var edgeLabel = new TextSprite$2($.extend({}, hasHoverEvent ? mainLabelProp : subLabelProp, inf)); if (hasHoverEvent) { edgeLabel.addEventListener('mouseover', () => { this.setSelected(true, 'edgeLabel'); }); edgeLabel.addEventListener('mouseleave', () => { this.setSelected(false, 'edgeLabel'); }); edgeLabel.addEventListener('click', () => { this.isNew || viewer.measuringTool.isAdding || viewer.focusOnObject(this, 'measure'); }); } edgeLabel.visible = false; edgeLabel.measure = this; edgeLabel.sprite.material.depthTestWhenPick = true; Potree.Utils.setObjectLayers(edgeLabel, 'measure'); this.add(edgeLabel); if (this.measureType == 'MulDistance') { edgeLabel.visiMap = new Map(); } return edgeLabel; } createAreaLabel() { var areaLabel = this.createCenterLabel('areaLabel'); return areaLabel; } createTotalDisLabel() { var totalDisLabel = this.createCenterLabel('totalDisLabel'); return totalDisLabel; } createCenterLabel(name) { var centerLabel = new TextSprite$2($.extend({}, mainLabelProp, { sizeInfo: labelSizeInfo, name, disToLine: 0, fontsize: 16 * textSizeRatio })); centerLabel.addEventListener('mouseover', () => { this.isNew || this.setSelected(true, 'centerLabel'); }); centerLabel.addEventListener('mouseleave', () => { this.isNew || this.setSelected(false, 'centerLabel'); }); centerLabel.addEventListener('click', () => { this.isNew || viewer.measuringTool.isAdding || viewer.focusOnObject(this, 'measure'); }); Potree.Utils.setObjectLayers(centerLabel, 'measure'); Utils.updateVisible(centerLabel, 'setVisible', false); return centerLabel; } getMarkerMaterial(type) { if (!markerMats) { markerMats = { default: new DepthBasicMaterial($.extend({}, lineDepthInfo, { transparent: !0, opacity: 1, map: texLoader$6.load(Potree.resourcePath + '/textures/pic_point_s32.png'), useDepth: true, mapScale: markerMapShrink })), select: new MeshBasicMaterial({ transparent: !0, opacity: 1, depthTest: false, map: texLoader$6.load(Potree.resourcePath + '/textures/pic_point32.png' /* , null, null, { antialias: false } */) }) }; Measure$1.markerMats = markerMats; markerMats.select.map.repeat.set(1 / markerMapShrink, 1 / markerMapShrink); markerMats.select.map.offset.set((markerMapShrink - 1) / 2 / markerMapShrink, (markerMapShrink - 1) / 2 / markerMapShrink); //markerMats.select.map.offset.set( -1.1 , -1.1 ) } return markerMats[type]; } getLineMat(type) { if (!Measure$1.lineMats) { Measure$1.lineMats = { edgeDefault: LineDraw.createFatLineMat($.extend({}, lineDepthInfo, { color: config$1.measure.default.color, lineWidth: config$1.measure.lineWidth, useDepth: true, dashWithDepth: true, // 只在被遮住的部分显示虚线,因为实线容易挡住label dashed: true, dashSize: 0.04, gapSize: 0.04, transparent: true, opacity: config$1.measure.default.opacity, depthTestWhenPick: true })), edgeSelect: LineDraw.createFatLineMat($.extend({}, lineDepthInfo, { color: config$1.measure.highlight.color, //'#f0ff00', dashSize: 0.5, gapSize: 0.2, lineWidth: config$1.measure.lineWidth, transparent: true, opacity: config$1.measure.highlight.opacity })), guide: LineDraw.createFatLineMat($.extend({}, lineDepthInfo, { color: config$1.measure.guide.color, dashSize: 0.1, gapSize: 0.02, dashed: true, lineWidth: config$1.measure.lineWidth / 2 })) }; } return Measure$1.lineMats[type]; } createAreaPlane() { planeMats || (planeMats = { default: new DepthBasicMaterial($.extend({}, lineDepthInfo, { color: color, side: DoubleSide, opacity: 0.2, transparent: true, useDepth: true })), selected: new MeshBasicMaterial({ color: color, side: DoubleSide, opacity: 0.3, transparent: true //wireframe:true }) }, Measure$1.planeMats = planeMats); return super.createAreaPlane(planeMats.default); } raycast(raycaster, intersects) { for (var i = 0; i < this.points.length; i++) { var marker = this.markers[i]; marker.raycast(raycaster, intersects); } // recalculate distances because they are not necessarely correct // for scaled objects. // see https://github.com/mrdoob/three.js/issues/5827 // TODO: remove this once the bug has been fixed for (var _i = 0; _i < intersects.length; _i++) { var I = intersects[_i]; I.distance = raycaster.ray.origin.distanceTo(I.point); } intersects.sort(function (a, b) { return a.distance - b.distance; }); } getPointsPos2d(viewport, update) { //获取屏幕上的二维坐标 var ps = this.pointsPos2d.get(viewport); if (update || !ps) { var points = this.points.map(e => { var p = Potree.Utils.getPos2d(e, viewport, viewer.renderArea); p.pos3d = e.clone(), p.object = this; return p; }); this.pointsPos2d.set(viewport, points); console.log('updatePointsPos2d', this.uuid, viewport.name); } return this.pointsPos2d.get(viewport); } transformData(prop) { if (prop.measureType == 'Point') { prop.showCoordinates = true, prop.closed = true, prop.maxMarkers = 1, prop.minMarkers = 1; } else if (prop.measureType == 'Distance') { prop.showDistances = true, prop.showEdges = true, prop.maxMarkers = 2, prop.minMarkers = 2; } else if (prop.measureType == 'MulDistance') { prop.showDistances = true, prop.showEdges = true, prop.minMarkers = 2; } else if (prop.measureType == 'MulDistance Ring') { prop.showDistances = true, prop.showEdges = true, prop.showArea = true, prop.closed = true, prop.minMarkers = 3; } else if (prop.measureType == 'Ver MulDistance') { prop.showDistances = true, prop.atPlane = true, prop.showEdges = true, prop.minMarkers = 2; prop.faceDirection = "vertical"; prop.unableDragAtMap = true; } else if (prop.measureType == 'Hor MulDistance') { prop.showDistances = true, prop.atPlane = true, prop.showEdges = true, prop.minMarkers = 2; prop.faceDirection = "horizontal"; } else if (prop.measureType == 'Ver Distance') { prop.showDistances = true, prop.showEdges = true, prop.maxMarkers = 2, prop.minMarkers = 2, prop.faceDirection = "vertical"; prop.unableDragAtMap = true; } else if (prop.measureType == 'Hor Distance') { prop.showDistances = true, prop.showEdges = true, prop.maxMarkers = 2, prop.minMarkers = 2, prop.faceDirection = "horizontal"; } else if (prop.measureType == 'Area') { prop.showDistances = true, Potree.settings.areaAtNotPlane || (prop.atPlane = true); prop.showEdges = true, prop.closed = true, prop.minMarkers = 3; } else if (prop.measureType == 'Hor Area') { prop.showDistances = true, prop.atPlane = true, prop.showEdges = true, prop.closed = true, prop.minMarkers = 3; prop.faceDirection = "horizontal"; } else if (prop.measureType == 'Ver Area') { prop.showDistances = true, prop.atPlane = true, prop.showEdges = true, prop.closed = true, prop.minMarkers = 3; prop.faceDirection = "vertical"; prop.unableDragAtMap = true; } else if (prop.measureType == 'Rect Area') { prop.showDistances = true, prop.atPlane = true, prop.showEdges = true, prop.closed = true, prop.minMarkers = 4; prop.maxMarkers = 4; } else if (prop.measureType == 'Hor Rect Area') { prop.showDistances = true, prop.atPlane = true, prop.showEdges = true, prop.closed = true, prop.minMarkers = 4; prop.maxMarkers = 4; prop.isRect = true; prop.faceDirection = "horizontal"; } else if (prop.measureType == 'Ver Rect Area') { prop.showDistances = true, prop.atPlane = true, prop.showEdges = true, prop.closed = true, prop.minMarkers = 4; prop.maxMarkers = 4; prop.isRect = true; prop.faceDirection = "vertical"; prop.unableDragAtMap = true; } if (prop.atPlane && prop.closed) { //atPlane在同一平面上 prop.showArea = true; } super.transformData(prop); } setUnitSystem(unitSystem) { //console.log(this.name +':' +this.unitSystem) if (unitSystem != this.unitSystem) { if (unitSystem == "metric") {} else if (unitSystem == 'imperial') {} this.unitSystem = unitSystem; this.update(); } } reDraw() { var restMarkerCount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; //重新开始画 super.reDraw(restMarkerCount); if (this.measureType == 'Distance') { this.shouldShowHorVerGuide = false; this.setEdgesDisplay(false); } if (this.showArea) { this.area = { value: 0 }; this.areaLabel && Utils.updateVisible(this.areaLabel, 'setVisible', false); } if (this.totalDisLabel && this.showTotalDis) { Utils.updateVisible(this.totalDisLabel, 'setVisible', false); } viewer.inputHandler.dispatchEvent({ type: 'measuring', v: true, cause: 'reDraw', object: this, situation: 'dragging' }); } } function setLabelHightState(label, state) { if (state) { var _color = new Color(Potree.config.measure.highlight.color); //label.sprite.material.opacity = config.measure.highlight.opacity //label.setBackgroundColor({r:255*color.r, g:255*color.g, b:255*color.b, a:config.measure.highlight.opacity}) label.sprite.material.useDepth = false; //label.textColor = {r: this.color.r*255, g: this.color.g*255, b: this.color.b*255, a: 1} } else { //label.setBackgroundColor({r: this.color.r*255, g: this.color.g*255, b: this.color.b*255, a:config.measure.default.opacity}) label.sprite.material.useDepth = true; //label.sprite.material.opacity = 0.98 //label.textColor = {r: 255, g: 255, b: 255, a: 1} } label.updateTexture(); } /* function setLabelHightState(label, state){ if(state){ label.setBackgroundColor({r: highlightColor.r*255, g: highlightColor.g*255, b: highlightColor.b*255, a:config.measure.highlight.labelOpacity}) label.sprite.material.useDepth = false; }else{ label.setBackgroundColor(mainLabelProp.backgroundColor) label.sprite.material.useDepth = true } label.updateTexture() //label.sprite.material.needsUpdate = true } */ function createCircleRadiusLabel$1() { var circleRadiusLabel = new TextSprite$2(""); circleRadiusLabel.setTextColor({ r: 140, g: 250, b: 140, a: 1.0 }); circleRadiusLabel.setBorderColor({ r: 0, g: 0, b: 0, a: 1.0 }); circleRadiusLabel.setBackgroundColor({ r: 0, g: 0, b: 0, a: 1.0 }); circleRadiusLabel.fontsize = 16; circleRadiusLabel.material.depthTest = false; circleRadiusLabel.material.opacity = 1; circleRadiusLabel.visible = false; return circleRadiusLabel; } function createCircleRadiusLine$1() { /* const lineGeometry = new LineGeometry(); lineGeometry.setPositions([ 0, 0, 0, 0, 0, 0, ]); const lineMaterial = new LineMaterial({ color: 0xff0000, lineWidth: 2, resolution: new THREE.Vector2(1000, 1000), gapSize: 1, dashed: true, }); lineMaterial.depthTest = false; const circleRadiusLine = new Line2(lineGeometry, lineMaterial);*/ var circleRadiusLine = LineDraw.createFatLine([], { color: 0xff0000, dashSize: 0.5, gapSize: 0.2, lineWidth: config$1.measure.lineWidth }); circleRadiusLine.visible = false; return circleRadiusLine; } function createCircleLine$1() { var coordinates = []; var n = 128; for (var i = 0; i <= n; i++) { var u0 = 2 * Math.PI * (i / n); var u1 = 2 * Math.PI * (i + 1) / n; var p0 = new Vector3(Math.cos(u0), Math.sin(u0), 0); var p1 = new Vector3(Math.cos(u1), Math.sin(u1), 0); coordinates.push(p0, p1); } /* const geometry = new LineGeometry(); geometry.setPositions(coordinates); const material = new LineMaterial({ color: 0xff0000, dashSize: 5, gapSize: 2, lineWidth: 2, resolution: new THREE.Vector2(1000, 1000), }); material.depthTest = false; const circleLine = new Line2(geometry, material); circleLine.visible = false; circleLine.computeLineDistances();*/ var circleLine = LineDraw.createFatLine(coordinates, { color: 0xff0000, dashSize: 0.5, gapSize: 0.2, lineWidth: config$1.measure.lineWidth }); return circleLine; } /* function createCircleCenter(){ const sg = new THREE.markerGeometry(1, 32, 32); const sm = new THREE.MeshNormalMaterial(); const circleCenter = new THREE.Mesh(sg, sm); circleCenter.visible = false; return circleCenter; } */ function createLine$1() { var line = LineDraw.createFatLine([], { color: 0xff0000, dashSize: 0.5, gapSize: 0.2, lineWidth: config$1.measure.lineWidth }); return line; } function createCircle$1() { var coordinates = []; var n = 128; for (var i = 0; i <= n; i++) { var u0 = 2 * Math.PI * (i / n); var u1 = 2 * Math.PI * (i + 1) / n; var p0 = new Vector3(Math.cos(u0), Math.sin(u0), 0); var p1 = new Vector3(Math.cos(u1), Math.sin(u1), 0); coordinates.push(p0, p1); } var line = LineDraw.createFatLine(coordinates, { color: 0xff0000, dashSize: 0.5, gapSize: 0.2, lineWidth: config$1.measure.lineWidth }); return line; } /* function createAzimuth(){ const azimuth = { label: null, center: null, target: null, north: null, centerToNorth: null, centerToTarget: null, centerToTargetground: null, targetgroundToTarget: null, circle: null, node: null, }; const sg = new THREE.markerGeometry(1, 32, 32); const sm = new THREE.MeshNormalMaterial(); { const label = new TextSprite(""); label.setTextColor({r: 140, g: 250, b: 140, a: 1.0}); label.setBorderColor({r: 0, g: 0, b: 0, a: 1.0}); label.setBackgroundColor({r: 0, g: 0, b: 0, a: 1.0}); label.fontsize = 16; label.material.depthTest = false; label.material.opacity = 1; azimuth.label = label; } azimuth.center = new THREE.Mesh(sg, sm); azimuth.target = new THREE.Mesh(sg, sm); azimuth.north = new THREE.Mesh(sg, sm); azimuth.centerToNorth = createLine(); azimuth.centerToTarget = createLine(); azimuth.centerToTargetground = createLine(); azimuth.targetgroundToTarget = createLine(); azimuth.circle = createCircle(); azimuth.node = new THREE.Object3D(); azimuth.node.add( azimuth.centerToNorth, azimuth.centerToTarget, azimuth.centerToTargetground, azimuth.targetgroundToTarget, azimuth.circle, azimuth.label, azimuth.center, azimuth.target, azimuth.north, ); return azimuth; } */ /* 按alt鼠标滚轮或WS键放慢。 按Alt键可以平行屏幕拖拽点。&dragPolyBeyondPoint 后缀在拖拽到无点云区域也是此效果。 按M键拖拽点可以复制出当前点 */ class History extends EventDispatcher { constructor(o) { super(); this.undoList = []; this.redoList = []; this.applyData = o.applyData; //应用数据的方法 this.getData = o.getData; //获取数据的方法 this.dataBefore; (o.viewer || viewer).inputHandler.addEventListener('keydown', e => { if (e.keyCode == 90 && e.event.ctrlKey) { //Z this.undo(); } else if (e.keyCode == 89 && e.event.ctrlKey) { //Y this.redo(); } }); } undo() { //回退 var length = this.undoList.length; if (length > 0) { var unExist; var last = this.undoList.pop(); this.applyData && (unExist = !this.applyData(last.before)); unExist || this.redoList.push(last); unExist && this.undo(); //找不到就回退下一个。 this.dispatchEvent('undo'); //console.log('undo',last) } } redo() { //撤销回退 var length = this.undoList.length; var last = this.redoList.pop(); if (last) { //注意:每行的顺序不能乱 this.undoList.push(last); this.applyData && this.applyData(last.after); this.dispatchEvent('redo'); //console.log('redo',last) } } beforeChange(o) { //在变化之前(可能执行好几次直到变化完,但只有第一次有效)。 o的内容完全根据getData怎么定义 if (!this.dataBefore) { var data = this.getData(o); data && (this.dataBefore = data); } } afterChange(o) { //变化结束,从beforeChange到此算一次操作。 if (this.dataBefore) { this.writeIn({ before: this.dataBefore, after: this.getData(o) }); //写入某物体变化前和变化后的状态 this.dataBefore = null; } } writeIn(data) { this.redoList.length = 0; //一旦录入新的操作,就不允许undo了 this.undoList.push(data); //console.log('新增undo', data) } clear() { this.redoList.length = 0; this.undoList.length = 0; this.dataBefore = null; } } var areaPlaneMats = {}; class Prism extends Measure$1 { constructor(args) { args.isPrism = true; super(args); this.volumeInfo = {}; this.needsCompute = true; /*this.createPrismLines(new THREE.Color('#FFF') ) this.lineMesh.material.transparent = true this.lineMesh.material.opacity = 0.5 Potree.Utils.setObjectLayers(this.lineMesh, 'measure' ) */ this.setClipBox(); this.setTopOrBtm('zMin'); this.setTopOrBtm('zMax'); this.setHorizonHeight('btm'); var update = () => { this.setHorizonHeight(this.horizonType, true); //更新 this.needsCompute = true; this.getBound(); this.dispatchEvent('updated'); }; this.addEventListener('marker_dropped' /* 'marker_moved' */, update); this.addEventListener('changeByHistory', update); this.addEventListener('changed', update); /* this.addEventListener('createDone',()=>{ this.setHorizonHeight()//更新 this.updateAreaPlane() }) */ this.updateAreaPlane(); this.getBound(); this.addEventListener('needsCompute', () => { this.needsCompute = true; }, 10); //Potree.Utils.setObjectLayers(this.lineMesh, 'bothMapAndScene' ) } set needsCompute(state) { if (state == 'byVolume') { this.needsCompute_ = this.volumeInfo.Vupper == void 0; } else { this.needsCompute_ = !!state; //console.error('needsCompute', state) } } get needsCompute() { return this.needsCompute_; } setHorizonHeight(v) { var old = this.horizonZ; if (typeof v == 'number') { this.horizonType = 'number'; this.horizonZ = v; } else { if (v) { this.horizonType = v; } if (!this.horizonType) this.horizonType = 'btm'; if (this.horizonType == 'number') return; var zs = this.points.map(p => p.z).sort((a, b) => a - b); this.horizonZ = this.horizonType == 'btm' ? zs[0] : zs[this.points.length - 1]; } //this.horizonZ = THREE.Math.clamp(this.horizonZ, this.zMin, this.zMax ) if (this.horizonZ != old) { this.needsCompute = true; this.update(); //update areaPlane and areaLabel pos this.dispatchEvent('horizonZChanged'); } //console.log(this.horizonZ) } setBaseModel(model, modelHaventLoad) { //三种状态:使用model、使用基准高度、 什么都没有(不允许计算、不高亮、等待模型上传) this.baseModel = model; this.modelHaventLoad = modelHaventLoad; Potree.Utils.updateVisible(this.areaPlane, 'unuseHorizonH', !model && !modelHaventLoad); } setClipBox(boxes) { //clipBoxes_out this.clipBoxes = boxes || []; } setTopOrBtm(name, v) { if (v != void 0) { this[name] = v; this.updatePrismLines(); } else { this[name] = viewer.bound.boundingBox[name == 'zMin' ? 'min' : 'max'].z; } this.getBound(); this.needsCompute = true; } getBound() { var bound = Potree.math.getBound(this.points); bound.min.z = this.zMin; bound.max.z = this.zMax; this.prismBound = bound; } setVolumeInfo(volumeInfo) { this.volumeInfo = volumeInfo; this.getVolumeString(); this.needsCompute = false; //但得到的不一定是对的可能 检查下 } getVolumeString() { if (!this.volumeInfo || this.volumeInfo.Vupper == void 0) return; this.VupperString = this.getConvertString(this.volumeInfo.Vupper, 'volume', true); this.VlowerString = this.getConvertString(this.volumeInfo.Vlower, 'volume', true); this.highestString = this.getConvertString(this.volumeInfo.highest, 'distance', true); this.lowestString = this.getConvertString(this.volumeInfo.lowest, 'distance', true); } getConvertString(num, type, restrictUnit) { if (!restrictUnit) return super.getConvertString(num, type); return viewer.unitConvert.convert(num, type, Potree.settings.precision, this.unitSystem, null, { //在pdf里的高度要统一单位 'imperial': { restrictUnit: 'Foot' }, //ft 'metric': { restrictUnit: 'Meter' } }); } setUnitSystem(unitSystem) { var old = this.unitSystem; super.setUnitSystem(unitSystem); if (unitSystem != old) { this.getVolumeString(); } } getCenter(type) { if (type == 'areaPlaneCenter') { //areaPlane中心 return this.areaPlaneCenter; } return super.getCenter(); //点的中心 } update() { super.update.apply(this, arguments); this.updatePrismLines(); } getTransformationMatrix(pointcloud) { //剪裁矩阵 var invMatrix = new Matrix4(); //把当前z移动到-0.5 ~ 0.5所需要的变换 var minZ = this.zMin; //viewer.bound.boundingBox.min.z var maxZ = this.zMax; //viewer.bound.boundingBox.max.z var s = 1 / (maxZ - minZ); var pos = new Vector3(0, 0, -0.5 - minZ * s), scale = new Vector3(1, 1, s); invMatrix.compose(pos, new Quaternion(), scale); //先缩放后位移 return new Matrix4().multiplyMatrices(invMatrix, pointcloud.transformMatrix).transpose(); } changeStyleForScreenshot(state) { var { hideLabel, showName } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; //截图前变一下外观。根据高度变化颜色 var config = Potree.settings.prismHeightColor; var color; //, lineWidth = this.edges[0].material.lineWidth if (this.volumeInfo.Vupper > 0.01 && this.volumeInfo.Vlower > 0.01) { color = config.every.color; } else if (this.volumeInfo.Vupper > this.volumeInfo.Vlower) { for (var i = config.dig.length - 1; i >= 0; i--) { if (this.volumeInfo.Vupper >= config.dig[i].min) { color = config.dig[i].color; break; } } } else { for (var _i = config.fill.length - 1; _i >= 0; _i--) { if (this.volumeInfo.Vlower >= config.fill[_i].min) { color = config.fill[_i].color; break; } } } color = new Color(color[0] / 255, color[1] / 255, color[2] / 255); var name = color.getHexString(); if (state) { Potree.Utils.updateVisible(this.areaPlane, 'screenshot', true, 2, 'add'); //强制显示 var mat = areaPlaneMats[name]; if (!mat) { mat = new MeshBasicMaterial({ color, transparent: true, opacity: 0.6, side: DoubleSide }); areaPlaneMats[name] = mat; } this.oldAreaPlaneMat = this.areaPlane.material; this.areaPlane.material = mat; if (hideLabel) { Potree.Utils.updateVisible(this.areaLabel, 'screenshot-single', false); } if (showName) { this.areaLabel.setText([this.name, this.area.string]); /* let btm = this.areaPlaneCenter.clone().setY(this.prismBound.min.y) //置于土方2d块底部 this.areaLabel.setPos(btm) this.areaLabel.sprite.position.y = -0.25 */ } this.markers.forEach(marker => Potree.Utils.updateVisible(marker, 'screenshot-Prism', false)); this.edges.forEach(edge => Potree.Utils.updateVisible(edge, 'screenshot-Prism', false)); //Potree.Utils.updateVisible(this.lineMesh,'screenshot-Prism',false) this.styleRecover = () => { this.areaPlane.material = this.oldAreaPlaneMat; if (hideLabel) { Potree.Utils.updateVisible(this.areaLabel, 'screenshot-single', true); } if (showName) { this.areaLabel.setText(this.area.string); /* this.areaLabel.setPos(this.areaPlaneCenter) this.areaLabel.sprite.position.y = 0 */ } this.markers.forEach(marker => Potree.Utils.updateVisible(marker, 'screenshot-Prism', true)); this.edges.forEach(edge => Potree.Utils.updateVisible(edge, 'screenshot-Prism', true)); //Potree.Utils.updateVisible(this.lineMesh,'screenshot-Prism',true) this.styleRecover = null; }; } else { this.styleRecover && this.styleRecover(); Potree.Utils.updateVisible(this.areaPlane, 'screenshot', false, 2, 'cancel'); } } dispose() { super.dispose(); this.clipBoxes.forEach(e => viewer.scene.removeVolume(e)); } setEditState(state) { //编辑页面or截图 state = !!state; this.editing = state; this.dontHighlight = !state; this.clipBoxes.forEach(box => { Potree.Utils.updateVisible(box, 'hidden', state), box.clip = state; }); } /* { fill: [ {color: [236, 213, 143, 1], min: 0, max: 5}, {color: [223, 118, 21, 1], min: 5, max: 10}, // 没有min表示大于 {color: [186, 57, 57, 1], min: 10} ], dig: [ {color: [144, 193, 190, 1], min: 0, max: 5}, {color: [76, 155, 211, 1], min: 5, max: 10}, // 没有min表示大于 {color: [79, 76, 211, 1], min: 10} ], // 填挖并存 every: { color: [49, 200, 181, 1] } } */ } class MeasuringTool extends EventDispatcher { constructor(viewer) { super(); this.viewer = viewer; this.renderer = viewer.renderer; this.viewer.addEventListener('start_inserting_measurement', e => { this.viewer.dispatchEvent({ type: 'cancel_insertions' }); }); this.showLabels = true; this.scene = new Scene(); this.scene.name = 'scene_measurement'; //this.light = new THREE.PointLight(0xffffff, 1.0); //this.scene.add(this.light); this.viewer.inputHandler.registerInteractiveScene(this.scene); this.history = new History({ applyData: data => { if (data.measure.parent && data.measure.visible) { data = Potree.Common.CloneObject(data); //避免使用后更改数据又被使用 data.measure.reDraw(); data.measure.initData(data); data.measure.isNew = data.isNew; data.measure.dispatchEvent('changeByHistory'); /* if(data.measure.isPrism){ data.measure.needsCompute = data.needsCompute } */ data.measure.facePlane = data.facePlane && data.facePlane.clone(); data.measure.cannotConfirmNormal = data.cannotConfirmNormal; return true; } }, getData: measure => { var data = { measure, points: measure.points.map(e => e.clone()), dataset_points: measure.dataset_points ? measure.dataset_points.map(e => e && e.clone()) : null, points_datasets: measure.points_datasets.slice(), datasetId: measure.datasetId, isNew: measure.isNew, facePlane: measure.facePlane && measure.facePlane.clone(), cannotConfirmNormal: measure.cannotConfirmNormal }; /* if(measure.isPrism){ //没用 data.volumeInfo = measure.volumeInfo data.needsCompute = measure.needsCompute //但不记录其他信息 } */ return data; } }), //this.scene = viewer.overlay// this.onRemove = e => { e.measurement.dispose(); /* this.scene.remove(e.measurement); */ }; this.onAdd = e => { this.scene.add(e.measurement); }; for (var measurement of viewer.scene.measurements) { this.onAdd({ measurement: measurement }); } viewer.addEventListener('camera_changed', this.update.bind(this), { importance: 10 }); //优先级高于sprite if (Potree.config.measure.mulLabelHideFaraway) { viewer.addEventListener("raycaster", this.beforeDraw.bind(this), { importance: 10 }); //before render viewer.addEventListener("render.begin", this.beforeDraw.bind(this), { importance: 10 }); //before render viewer.addEventListener("render.begin2", this.beforeDraw.bind(this), { importance: 10 }); } //viewer.addEventListener("update", this.update.bind(this)); viewer.addEventListener("render.pass.perspective_overlay", this.render.bind(this)); viewer.addEventListener("scene_changed", this.onSceneChange.bind(this)); viewer.scene.addEventListener('measurement_added', this.onAdd); viewer.scene.addEventListener('measurement_removed', this.onRemove); viewer.addEventListener('resize', this.setSize.bind(this)); } onSceneChange(e) { if (e.oldScene) { e.oldScene.removeEventListener('measurement_added', this.onAdd); e.oldScene.removeEventListener('measurement_removed', this.onRemove); } e.scene.addEventListener('measurement_added', this.onAdd); e.scene.addEventListener('measurement_removed', this.onRemove); } createMeasureFromData(data) { //add var measure = data.measureType == 'MulDistance Ring' ? new Prism(data) : new Measure$1(data); if (measure.failBuilded) { return; } viewer.scene.addMeasurement(measure); if (measure.guideLine) measure.guideLine.visible = false; return measure; } beforeDraw(e) { if (e.viewport.name == 'mapViewport' && !viewer.mapViewer.attachedToViewer) return; //no measures viewer.scene.measurements.forEach(measure => { if (measure.measureType != 'MulDistance' || (measure.isNew ? measure.points.length < 4 : measure.points.length < 3)) return; var lastIndex = measure.points.length - 1; for (var index = 0; index <= lastIndex; index++) { if (!measure.closed && index == lastIndex) continue; var edgeLabel = measure.edgeLabels[index]; var v = edgeLabel.visiMap.get(e.viewport.camera); if (v == void 0) { return measure.getEdgeLabelVisi(e.viewport); } Potree.Utils.updateVisible(edgeLabel, 'tooFar', v === false ? false : true); } }); } update(e) { /* viewer.scene.measurements.forEach(measure=>{ if(measure.measureType != 'MulDistance' || (measure.isNew ? measure.points.length<4 : measure.points.length<3)) return }) */ if (viewer.inputHandler.measuring && Potree.settings.adsorption) { viewer.scene.measurements.forEach(measure => { measure.getPointsPos2d(e.viewport, true); }); } if (Potree.config.measure.mulLabelHideFaraway) { if (e.changeInfo.projectionChanged || e.viewport.camera.type == 'PerspectiveCamera' && e.changeInfo.positionChanged) { //for MulDistance viewer.scene.measurements.forEach(measure => { if (measure.measureType != 'MulDistance' || (measure.isNew ? measure.points.length < 4 : measure.points.length < 3)) return; measure.getEdgeLabelVisi(e.viewport); return; var lastIndex = measure.points.length - 1; for (var index = 0; index <= lastIndex; index++) { if (!measure.closed && index == lastIndex) continue; var nextIndex = index + 1 > lastIndex ? 0 : index + 1; var previousIndex = index === 0 ? lastIndex : index - 1; var point = measure.points[index]; var nextPoint = measure.points[nextIndex]; var previousPoint = measure.points[previousIndex]; var point2d = new Vector2().copy(pos2ds[index]); var nextPoint2d = new Vector2().copy(pos2ds[nextIndex]); if (measure.showDistances || measure.labelText) { // edge labels var edgeLabel = measure.edgeLabels[index]; if (edgeLabel.visible) { measure.setEdgeLabelPos(edgeLabel, point, nextPoint); } } } }); } } return; var camera = this.viewer.scene.getActiveCamera(); var domElement = this.renderer.domElement; var measurements = this.viewer.scene.measurements; // make size independant of distance var mainLabels = [], subLabels = []; for (var measure of measurements) { measure.lengthUnit = this.viewer.lengthUnit; measure.lengthUnitDisplay = this.viewer.lengthUnitDisplay; //measure.update(); updateAzimuth(this.viewer, measure); /* [...measure.markers, ...measure.edgeLabels, measure.areaLabel].forEach(e=>{ e && e.update() }); */ // labels /* let labels = measure.edgeLabels.concat(measure.angleLabels); for(let label of labels){ label.update() if(label.elem.hasClass('sub')){ subLabels.push(label) }else{ mainLabels.push(label) } } // coordinate labels for (let j = 0; j < measure.coordinateLabels.length; j++) { let label = measure.coordinateLabels[j]; label.update() mainLabels.push(label) } if(measure.showArea){ // area label let label = measure.areaLabel; label.update() mainLabels.push(label) } */ /* if(measure.showCircle){ // radius label let label = measure.circleRadiusLabel; let distance = label.position.distanceTo(camera.position); let pr = Utils.projectedRadius(1, camera, distance, clientWidth, clientHeight); let scale = (70 / pr); label.scale.set(scale, scale, scale); } */ if (!this.showLabels) { var labels = [...measure.sphereLabels, ...measure.angleLabels, measure.circleRadiusLabel]; for (var label of labels) { label.visible = false; } } } //this.updateLabelZIndex([{labels:subLabels},{labels:mainLabels}]) } setSize(e) {//e.resolution /* if(Measure.lineMats){ for(var m in Measure.lineMats){ Measure.lineMats[m].resolution.set(e.canvasWidth, e.canvasHeight); } } if(Measure.sphereMats){ for(var s in Measure.sphereMats){ Measure.sphereMats[s].uniforms.resolution.value.set(e.canvasWidth, e.canvasHeight); } } for (let measure of this.viewer.scene.measurements) { measure.edgeLabels.concat(measure.areaLabel).forEach(label=>{ label.sprite.material.uniforms.resolution.value.set(e.canvasWidth, e.canvasHeight); }) } */ } updateLabelZIndex(group) { //[{labels:[]},{}] 顺序按照z-index低到高 group.forEach((e, i) => { e.base = group[i - 1] ? group[i - 1].base + group[i - 1].labels.length : 0; var labels = e.labels.sort((a, b) => { return b.pos2d.z - a.pos2d.z; }); labels.forEach((label, index) => { $(label.elem).css('z-index', e.base + index); }); }); } changeEditMode(mode) { viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "addPoint" }); viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "delPoint" }); if (mode) { if (mode == 'addPoint') { viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "addPoint" }); } else { viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "delPoint" }); } } this.editMode = mode; } editStateChange(e) { //console.log("editStateChange" , e.state) var state = e.state; if (!state) { state = viewer.scene.measurements.some(e => e.isEditing); } if (state) { viewer.dispatchEvent({ type: "measureMovePoint" }); //重新激活reticule状态 } else { viewer.dispatchEvent({ type: "endMeasureMove" }); } //this.editing = } startInsertion() { var _this = this; var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var callback = arguments.length > 1 ? arguments[1] : undefined; var cancelFun = arguments.length > 2 ? arguments[2] : undefined; var domElement = this.viewer.renderer.domElement; var measure = args.measureType == 'MulDistance Ring' ? new Prism(args) : new Measure$1(args); this.scene.add(measure); measure.isNew = true; this.viewer.dispatchEvent({ type: 'start_inserting_measurement', measure: measure }); measure.addEventListener('editStateChange', this.editStateChange.bind(this)); measure.editStateChange(true); var timer; this.isAdding = true; var endDragFun = e => { var length = measure.points.length; if (e.button == MOUSE.LEFT || e.isTouch) { if (length >= measure.maxMarkers) { _end({ finish: true }); } else { this.history.beforeChange(measure); var marker = measure.cloneMarker(length - 1, length); if (args.isRect && measure.markers.length == 3) { //marker全可见 measure.cloneMarker(0, 3); } else { measure.markers[length].visible = false; measure.edges[length].visible = false; } measure.edges[length - 1].visible = true; measure.markers[length - 1].visible = true; marker.isDragging = true; this.history.afterChange(measure); measure.continueDrag(marker, e); } } else if (e.button === MOUSE.RIGHT) { //触屏怎么取消? if (e.pressDistance < Potree.config.clickMaxDragDis) { //非拖拽的话 var isIntersectSelf = measure.atPlane && measure.closed && !measure.isRect && measure.point2dInfo && measure.intersectSelf(measure.point2dInfo.points2d.slice(0, measure.point2dInfo.points2d.length - 1)); //检测除了最后一个点的相交情况 if (!isIntersectSelf) _end(e);else measure.continueDrag(null, e); } else measure.continueDrag(null, e); } }; var _end = function end() { var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; //确定、结束 if (!measure.isNew) return; if (args.minMarkers != void 0) { if (!e.finish && measure.markers.length <= args.minMarkers) { //右键 当个数不够时取消 //this.viewer.scene.removeMeasurement(measure) //重新开始画 if (measure.markers.length > 0) { measure.markers[0].removeEventListener('mousedown', _end); measure.reDraw(); _this.viewer.addEventListener('global_click', click, { importance: 10 }); measure.editStateChange(true); } return; /* if(!Potree.settings.isOfficial) this.viewer.scene.removeMeasurement(measure) else if(e.drag){ //正式版本不允许右键退出, 继续 continueDrag(e.drag.object) measure.editStateChange(true) return } */ } } var lastMarker = measure.markers[measure.markers.length - 1]; if ( /* !e.finish&& */measure.markers.length > args.minMarkers) { measure.removeMarker(measure.points.length - 1); measure.markers[0].removeEventListener('mouseover', mouseover); measure.markers[0].removeEventListener('mouseleave', mouseleave); measure.markers[0].removeEventListener('click' /* 'mousedown' */, Exit); if (e.byClickMarker && measure.markers.length > args.minMarkers) { //通过点击第一个marker而结束的话,会多一个marker。但点击marker后可能会因为和它坐标一致而没有添加成功,就不删,根据添加的时间来判断。 var delta = Date.now() - lastMarker.createTime; //console.log('delta',delta) if (delta < 10) { //刚生成的,说明点击后新增了一个marker measure.removeMarker(measure.points.length - 1); } } } measure.isNew = false; var length = measure.points.length; if (length) { measure.markers[length - 1].visible = true; measure.edges[length - 1].visible = !!measure.closed; measure.markers.forEach(marker => { marker.dispatchEvent('addHoverEvent'); }); measure.edges.forEach(edge => { edge.dispatchEvent('addHoverEvent'); }); measure.update(); //update last edgeLabel } clearTimeout(timer); _this.viewer.removeEventListener('cancel_insertions', Exit); //pressExit && this.viewer.inputHandler.removeEventListener('keydown', pressExit); _this.viewer.removeEventListener('global_click', click); _this.viewer.removeEventListener('global_mousemove', ifAtWrongPlace); viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "polygon_AtWrongPlace" }); viewer.inputHandler.dispatchEvent({ type: 'measuring', v: false, cause: 'stopInsertion', situation: 'adding', object: measure }); //var isIntersectSelf = measure.atPlane && measure.closed && !measure.isRect && measure.point2dInfo && measure.intersectSelf(measure.point2dInfo.points2d.slice(0,measure.point2dInfo.points2d.length-1))//检测除了最后一个点的相交情况 var isIntersectSelf = measure.atPlane && measure.closed && !measure.isRect && measure.point2dInfo && measure.intersectSelf(measure.point2dInfo.points2d); if (isIntersectSelf) return cancelFun && cancelFun(); //请求删除,不重建 e.remove || callback && callback(); /* this.viewer.dispatchEvent({ type: 'finish_inserting_measurement', measure: measure }); */ _this.isAdding = false; measure.dispatchEvent('createDone'); }; measure.addEventListener('finish', _end); //完成 var Exit = e => { //强制退出 if (e.measure && e.measure != measure || !viewer.scene.measurements.includes(measure) || !measure.isNew) { return; //若指定了退出的measure但和该measure不一致,就返回 } if (e.remove || e.type == 'cancel_insertions') { viewer.scene.removeMeasurement(measure); } measure.editStateChange(false); measure.cannotConfirmNormal = false; //一些dropMarker中的句子 measure.guideLine && (measure.guideLine.visible = false); /* if(this.viewer.inputHandler.drag && !e.remove ){//还未触发drop的话 this.viewer.inputHandler.drag.object.dispatchEvent({ //这句会导致又增一个marker type: 'drop', drag: this.viewer.inputHandler.drag, viewer: this.viewer, pressDistance:0, button : THREE.MOUSE.RIGHT }); } else {*/ //未结束时添加新的measure时会触发 _end({ finish: true, remove: e.remove, byClickMarker: e.type == 'click' }); //} this.viewer.inputHandler.drag && (this.viewer.inputHandler.drag.object = null); }; this.viewer.addEventListener('cancel_insertions', Exit); /*let pressExit if(!Potree.settings.isOfficial){ pressExit = (e)=>{ if(e.keyCode == 27){//Esc //Exit() //怎么模拟右键???//现由前端发出 } } this.viewer.inputHandler.addEventListener('keydown', pressExit) } */ var mouseover = e => { measure.setMarkerSelected(e.object, 'hover', 'single'); }; var mouseleave = e => { measure.setMarkerSelected(e.object, 'unhover', 'single'); }; var click = e => { //一旦点击就立刻增加两marker if (ifAtWrongPlace(e)) return; if (e.clickElement) return; //如点击label时focusOnObject if (e.button === MOUSE.RIGHT) return; //console.log('measure clicked33', !!e.intersectPoint) //var I = e.intersectPoint && (e.intersectPoint.orthoIntersect || e.intersectPoint.location) var I = e.intersect && (e.intersect.orthoIntersect || e.intersect.location); if (!I) { return measure.dispatchEvent('intersectNoPointcloud'); } var atMap = e.drag.dragViewport.name == 'mapViewport'; //在地图上测量的首个点按楼层高度(暂时先只按mainViewport相机高度吧,但navvis是按楼层,画在楼层的地面上,可能因为平面图显示的是楼层近地面), if (atMap) { I = I.clone().setZ(viewer.mainViewport.camera.position.z); } var marker = measure.addMarker({ point: I }); marker.isDragging = true; this.viewer.inputHandler.startDragging(marker, { endDragFun, notPressMouse: true }); //notPressMouse代表不是通过按下鼠标来拖拽 e.drag = this.viewer.inputHandler.drag; /* e.drag.endDragFun = endDragFun e.drag.notPressMouse = true */ //if(!measure.dragMarker(e) || !measure.dropMarker(e))return measure.dragMarker(e); measure.dropMarker(e); if (measure.maxMarkers > 1) { measure.markers[1].visible = false; measure.edges[1].visible = false; } if (measure.closed && !measure.isRect) { measure.markers[0].addEventListener('mouseover', mouseover); measure.markers[0].addEventListener('mouseleave', mouseleave); measure.markers[0].addEventListener('click' /* 'mousedown' */, Exit); //点击到第一个marker就结束 } this.viewer.removeEventListener('global_click', click); ///* global_drop */ //console.log('measure clicked') e.consume && e.consume(); return { stopContinue: true }; //防止继续执行别的侦听,如flytopano }; //点击第n下拥有n+1个marker, n>0 viewer.inputHandler.dispatchEvent({ type: 'measuring', v: true, cause: 'startInsertion', situation: 'adding', object: measure }); this.viewer.addEventListener('global_click', click, { importance: 10 }); //add importance var ifAtWrongPlace = e => { if (measure.unableDragAtMap && e.hoverViewport.name == 'mapViewport') { if (e.isTouch) { viewer.dispatchEvent({ type: 'reticule_forbit', v: true }); } else { viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "polygon_AtWrongPlace" }); } return true; } else { if (e.isTouch) { viewer.dispatchEvent({ type: 'reticule_forbit', v: false }); } else { viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "polygon_AtWrongPlace" }); } } }; if (measure.unableDragAtMap) { this.viewer.addEventListener('global_mousemove', ifAtWrongPlace); } var changeByHistory = e => { if (!measure.isNew) return; var marker = measure.markers[measure.points.length - 1]; this.viewer.inputHandler.startDragging(marker, { endDragFun, notPressMouse: true }); var I = viewer.inputHandler.intersect && (viewer.inputHandler.intersect.orthoIntersect || viewer.inputHandler.intersect.location); if (I) { measure.dragChange(I.clone(), measure.points.length - 1); //使最后一个点在鼠标处 } /* if(measure.markers.length == 1){ Common.updateVisible(marker, ,false) } */ args.isRect || (measure.edges[measure.points.length - 1].visible = false); //measure.continueDrag(measure.markers[measure.points.length-1], o ) }; measure.addEventListener('changeByHistory', changeByHistory); this.viewer.scene.addMeasurement(measure); return measure; } render() { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (this.scene.children.filter(e => e.visible).length == 0) return; var renderer = o.renderer || this.viewer.renderer; Potree.Utils.setCameraLayers(o.camera, ['measure']); /* if(o.screenshot && this.viewer.fxaaPass.enabled){ //抗锯齿 this.viewer.ssaaRenderPass.sampleLevel = 4 this.viewer.composer.render(this.scene, o.camera ); }else{ */ viewer.dispatchEvent({ type: "render.begin2", name: 'measure', viewport: o.viewport, renderer: o.renderer }); renderer.render(this.scene, o.camera); //} } } ; function updateAzimuth(viewer, measure) { if (!measure.showAzimuth) return; var azimuth = measure.azimuth; var isOkay = measure.points.length === 2; azimuth.node.visible = isOkay; if (!azimuth.node.visible) { return; } var camera = viewer.scene.getActiveCamera(); var renderAreaSize = viewer.renderer.getSize(new Vector2()); var width = renderAreaSize.width; var height = renderAreaSize.height; var [p0, p1] = measure.points; var r = p0.position.distanceTo(p1.position); var northVec = Utils.getNorthVec(p0.position, r, viewer.getProjection()); var northPos = p0.position.clone().add(northVec); azimuth.center.position.copy(p0.position); azimuth.center.scale.set(2, 2, 2); azimuth.center.visible = false; // azimuth.target.visible = false; { // north azimuth.north.position.copy(northPos); azimuth.north.scale.set(2, 2, 2); var _distance = azimuth.north.position.distanceTo(camera.position); var _pr = Utils.projectedRadius(1, camera, _distance, width, height); var _scale = 5 / _pr; azimuth.north.scale.set(_scale, _scale, _scale); } { // target azimuth.target.position.copy(p1.position); azimuth.target.position.z = azimuth.north.position.z; var _distance2 = azimuth.target.position.distanceTo(camera.position); var _pr2 = Utils.projectedRadius(1, camera, _distance2, width, height); var _scale2 = 5 / _pr2; azimuth.target.scale.set(_scale2, _scale2, _scale2); } azimuth.circle.position.copy(p0.position); azimuth.circle.scale.set(r, r, r); azimuth.circle.material.resolution.set(width, height); // to target azimuth.centerToTarget.geometry.setPositions([0, 0, 0, ...p1.position.clone().sub(p0.position).toArray()]); azimuth.centerToTarget.position.copy(p0.position); azimuth.centerToTarget.geometry.verticesNeedUpdate = true; azimuth.centerToTarget.geometry.computeBoundingSphere(); azimuth.centerToTarget.computeLineDistances(); azimuth.centerToTarget.material.resolution.set(width, height); // to target ground azimuth.centerToTargetground.geometry.setPositions([0, 0, 0, p1.position.x - p0.position.x, p1.position.y - p0.position.y, 0]); azimuth.centerToTargetground.position.copy(p0.position); azimuth.centerToTargetground.geometry.verticesNeedUpdate = true; azimuth.centerToTargetground.geometry.computeBoundingSphere(); azimuth.centerToTargetground.computeLineDistances(); azimuth.centerToTargetground.material.resolution.set(width, height); // to north azimuth.centerToNorth.geometry.setPositions([0, 0, 0, northPos.x - p0.position.x, northPos.y - p0.position.y, 0]); azimuth.centerToNorth.position.copy(p0.position); azimuth.centerToNorth.geometry.verticesNeedUpdate = true; azimuth.centerToNorth.geometry.computeBoundingSphere(); azimuth.centerToNorth.computeLineDistances(); azimuth.centerToNorth.material.resolution.set(width, height); // label var radians = Utils.computeAzimuth(p0.position, p1.position, viewer.getProjection()); var degrees = MathUtils.radToDeg(radians); if (degrees < 0) { degrees = 360 + degrees; } var txtDegrees = "".concat(degrees.toFixed(2), "\xB0"); var labelDir = northPos.clone().add(p1.position).multiplyScalar(0.5).sub(p0.position); if (labelDir.length() > 0) { labelDir.z = 0; labelDir.normalize(); var labelVec = labelDir.clone().multiplyScalar(r); var labelPos = p0.position.clone().add(labelVec); azimuth.label.position.copy(labelPos); } azimuth.label.setText(txtDegrees); var distance = azimuth.label.position.distanceTo(camera.position); var pr = Utils.projectedRadius(1, camera, distance, width, height); var scale = 70 / pr; azimuth.label.scale.set(scale, scale, scale); } class ProfileTool extends EventDispatcher$1 { constructor(viewer) { super(); this.viewer = viewer; this.renderer = viewer.renderer; this.addEventListener('start_inserting_profile', e => { this.viewer.dispatchEvent({ type: 'cancel_insertions' }); }); this.scene = new Scene(); this.scene.name = 'scene_profile'; this.light = new PointLight(0xffffff, 1.0); this.scene.add(this.light); this.viewer.inputHandler.registerInteractiveScene(this.scene); this.onRemove = e => this.scene.remove(e.profile); this.onAdd = e => this.scene.add(e.profile); for (var profile of viewer.scene.profiles) { this.onAdd({ profile: profile }); } viewer.addEventListener("update", this.update.bind(this)); viewer.addEventListener("render.pass.perspective_overlay", this.render.bind(this)); viewer.addEventListener("scene_changed", this.onSceneChange.bind(this)); viewer.scene.addEventListener('profile_added', this.onAdd); viewer.scene.addEventListener('profile_removed', this.onRemove); } onSceneChange(e) { if (e.oldScene) { e.oldScene.removeEventListeners('profile_added', this.onAdd); e.oldScene.removeEventListeners('profile_removed', this.onRemove); } e.scene.addEventListener('profile_added', this.onAdd); e.scene.addEventListener('profile_removed', this.onRemove); } startInsertion() { var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var domElement = this.viewer.renderer.domElement; var profile = new Profile(); profile.name = args.name || 'Profile'; this.dispatchEvent({ type: 'start_inserting_profile', profile: profile }); this.scene.add(profile); var cancel = { callback: null }; var insertionCallback = e => { if (e.button === MOUSE.LEFT) { if (profile.points.length <= 1) { var camera = this.viewer.scene.getActiveCamera(); var distance = camera.position.distanceTo(profile.points[0]); var clientSize = this.viewer.renderer.getSize(new Vector2()); var pr = Utils.projectedRadius(1, camera, distance, clientSize.width, clientSize.height); var width = 10 / pr; profile.setWidth(width); } profile.addMarker(profile.points[profile.points.length - 1].clone()); this.viewer.inputHandler.startDragging(profile.spheres[profile.spheres.length - 1]); } else if (e.button === MOUSE.RIGHT) { cancel.callback(); } }; cancel.callback = e => { profile.removeMarker(profile.points.length - 1); domElement.removeEventListener('mouseup', insertionCallback, false); this.viewer.removeEventListener('cancel_insertions', cancel.callback); }; this.viewer.addEventListener('cancel_insertions', cancel.callback); domElement.addEventListener('mouseup', insertionCallback, false); profile.addMarker(new Vector3(0, 0, 0)); this.viewer.inputHandler.startDragging(profile.spheres[profile.spheres.length - 1]); this.viewer.scene.addProfile(profile); return profile; } update() { var camera = this.viewer.scene.getActiveCamera(); var profiles = this.viewer.scene.profiles; var renderAreaSize = this.viewer.renderer.getSize(new Vector2()); var clientWidth = renderAreaSize.width; var clientHeight = renderAreaSize.height; this.light.position.copy(camera.position); // make size independant of distance for (var profile of profiles) { for (var sphere of profile.spheres) { var distance = camera.position.distanceTo(sphere.getWorldPosition(new Vector3())); var pr = Utils.projectedRadius(1, camera, distance, clientWidth, clientHeight); var scale = 15 / pr; sphere.scale.set(scale, scale, scale); } } } render() { this.viewer.renderer.render(this.scene, this.viewer.scene.getActiveCamera()); } } class ScreenBoxSelectTool extends EventDispatcher$1 { constructor(viewer) { super(); this.viewer = viewer; this.scene = new Scene(); viewer.addEventListener("update", this.update.bind(this)); viewer.addEventListener("render.pass.perspective_overlay", this.render.bind(this)); viewer.addEventListener("scene_changed", this.onSceneChange.bind(this)); } onSceneChange(scene) { console.log("scene changed"); } startInsertion() { var domElement = this.viewer.renderer.domElement; var volume = new BoxVolume(); volume.position.set(12345, 12345, 12345); volume.showVolumeLabel = false; volume.visible = false; volume.update(); this.viewer.scene.addVolume(volume); this.importance = 10; var selectionBox = $("
"); $(domElement.parentElement).append(selectionBox); selectionBox.css("right", "10px"); selectionBox.css("bottom", "10px"); var drag = e => { volume.visible = true; var mStart = e.drag.start; var mEnd = e.drag.end; var box2D = new Box2(); box2D.expandByPoint(mStart); box2D.expandByPoint(mEnd); selectionBox.css("left", "".concat(box2D.min.x, "px")); selectionBox.css("top", "".concat(box2D.min.y, "px")); selectionBox.css("width", "".concat(box2D.max.x - box2D.min.x, "px")); selectionBox.css("height", "".concat(box2D.max.y - box2D.min.y, "px")); var camera = e.viewer.scene.getActiveCamera(); var size = e.viewer.renderer.getSize(new Vector2()); var frustumSize = new Vector2(camera.right - camera.left, camera.top - camera.bottom); var screenCentroid = new Vector2().addVectors(e.drag.end, e.drag.start).multiplyScalar(0.5); var ray = Utils.mouseToRay(screenCentroid, camera, size.width, size.height); var diff = new Vector2().subVectors(e.drag.end, e.drag.start); diff.divide(size).multiply(frustumSize); volume.position.copy(ray.origin); volume.up.copy(camera.up); volume.rotation.copy(camera.rotation); volume.scale.set(diff.x, diff.y, 1000 * 100); e.consume(); }; var drop = e => { this.importance = 0; $(selectionBox).remove(); this.viewer.inputHandler.deselectAll(); this.viewer.inputHandler.toggleSelection(volume); var camera = e.viewer.scene.getActiveCamera(); var size = e.viewer.renderer.getSize(new Vector2()); var screenCentroid = new Vector2().addVectors(e.drag.end, e.drag.start).multiplyScalar(0.5); var ray = Utils.mouseToRay(screenCentroid, camera, size.width, size.height); var line = new Line3(ray.origin, new Vector3().addVectors(ray.origin, ray.direction)); this.removeEventListener("drag", drag); this.removeEventListener("drop", drop); var allPointsNear = []; var allPointsFar = []; // TODO support more than one point cloud for (var pointcloud of this.viewer.scene.pointclouds) { if (!pointcloud.visible) { continue; } var volCam = camera.clone(); volCam.left = -volume.scale.x / 2; volCam.right = +volume.scale.x / 2; volCam.top = +volume.scale.y / 2; volCam.bottom = -volume.scale.y / 2; volCam.near = -volume.scale.z / 2; volCam.far = +volume.scale.z / 2; volCam.rotation.copy(volume.rotation); volCam.position.copy(volume.position); volCam.updateMatrix(); volCam.updateMatrixWorld(); volCam.updateProjectionMatrix(); volCam.matrixWorldInverse.copy(volCam.matrixWorld).invert(); var _ray = new Ray(volCam.getWorldPosition(new Vector3()), volCam.getWorldDirection(new Vector3())); var rayInverse = new Ray(_ray.origin.clone().add(_ray.direction.clone().multiplyScalar(volume.scale.z)), _ray.direction.clone().multiplyScalar(-1)); var pickerSettings = { width: 8, height: 8, pickWindowSize: 8, all: true, pickClipped: true, pointSizeType: PointSizeType.FIXED, pointSize: 1 }; var pointsNear = pointcloud.pick(viewer, volCam, _ray, pickerSettings); volCam.rotateX(Math.PI); volCam.updateMatrix(); volCam.updateMatrixWorld(); volCam.updateProjectionMatrix(); volCam.matrixWorldInverse.copy(volCam.matrixWorld).invert(); var pointsFar = pointcloud.pick(viewer, volCam, rayInverse, pickerSettings); allPointsNear.push(...pointsNear); allPointsFar.push(...pointsFar); } if (allPointsNear.length > 0 && allPointsFar.length > 0) { var viewLine = new Line3(ray.origin, new Vector3().addVectors(ray.origin, ray.direction)); var closestOnLine = allPointsNear.map(p => viewLine.closestPointToPoint(p.position, false, new Vector3())); var closest = closestOnLine.sort((a, b) => ray.origin.distanceTo(a) - ray.origin.distanceTo(b))[0]; var farthestOnLine = allPointsFar.map(p => viewLine.closestPointToPoint(p.position, false, new Vector3())); var farthest = farthestOnLine.sort((a, b) => ray.origin.distanceTo(b) - ray.origin.distanceTo(a))[0]; var distance = closest.distanceTo(farthest); var centroid = new Vector3().addVectors(closest, farthest).multiplyScalar(0.5); volume.scale.z = distance * 1.1; volume.position.copy(centroid); } volume.clip = true; }; this.addEventListener("drag", drag); this.addEventListener("drop", drop); viewer.inputHandler.addInputListener(this); return volume; } update(e) { //console.log(e.delta) } render() { this.viewer.renderer.render(this.scene, this.viewer.scene.getActiveCamera()); } } class SpotLightHelper$1 extends Object3D { constructor(light, color) { super(); this.light = light; this.color = color; //this.up.set(0, 0, 1); this.updateMatrix(); this.updateMatrixWorld(); { // SPHERE var sg = new SphereGeometry(1, 32, 32); var sm = new MeshNormalMaterial(); this.sphere = new Mesh(sg, sm); this.sphere.scale.set(0.5, 0.5, 0.5); this.add(this.sphere); } { // LINES var positions = new Float32Array([+0, +0, +0, +0, +0, -1, +0, +0, +0, -1, -1, -1, +0, +0, +0, +1, -1, -1, +0, +0, +0, +1, +1, -1, +0, +0, +0, -1, +1, -1, -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.setAttribute("position", new BufferAttribute(positions, 3)); var material = new LineBasicMaterial(); this.frustum = new LineSegments(geometry, material); this.add(this.frustum); } this.update(); } update() { this.light.updateMatrix(); this.light.updateMatrixWorld(); var position = this.light.position; var target = new Vector3().addVectors(this.light.position, this.light.getWorldDirection(new Vector3()).multiplyScalar(-1)); var quat = new Quaternion().setFromRotationMatrix(new Matrix4().lookAt(position, target, new Vector3(0, 0, 1))); this.setRotationFromQuaternion(quat); this.position.copy(position); var coneLength = this.light.distance > 0 ? this.light.distance : 1000; var coneWidth = coneLength * Math.tan(this.light.angle * 0.5); this.frustum.scale.set(coneWidth, coneWidth, coneLength); } } //问题:如何转换到世界坐标?(缩放方向有bug。) //add------------------------------------- var OpaWhenNotSelect = 0.6; var ScaleRatio = 3; var OutlineColor = 0x666666; //---------------------------------------- var hideFocusHandles = true; //add class TransformationTool extends EventDispatcher { constructor(viewer) { super(); this.viewer = viewer; this.modesEnabled = {}; //add this.style = 'singleMode'; //建mesh时按照singleModes建的 this.scene = new Scene(); this.selection = []; this.pivot = new Vector3(); this.dragging = false; this.showPickVolumes = false; this.viewer.inputHandler.registerInteractiveScene(this.scene); this.viewer.inputHandler.addEventListener('selection_changed', e => { /* for(let selected of this.selection){ //若不删除,应该会穿过选中的物体选到别的而不是取消选择 this.viewer.inputHandler.blacklist.delete(selected); } */ this.selection = e.selection; /* for(let selected of this.selection){ this.viewer.inputHandler.blacklist.add(selected); } */ }); this.viewer.addEventListener('global_touchstart', e => { //add this.update(); }); this.viewer.addEventListener('global_mousemove', e => { //add this.onPointerMove(); }); var red = Potree.config.axis.x.color; var green = Potree.config.axis.y.color; var blue = Potree.config.axis.z.color; var white = Potree.config.axis.xyz.color; this.activeHandle = null; this.scaleHandles = { "scale.x+": { name: "scale.x+", node: new Object3D(), color: red, alignment: [+1, +0, +0] }, "scale.x-": { name: "scale.x-", node: new Object3D(), color: red, alignment: [-1, +0, +0] }, "scale.y+": { name: "scale.y+", node: new Object3D(), color: green, alignment: [+0, +1, +0] }, "scale.y-": { name: "scale.y-", node: new Object3D(), color: green, alignment: [+0, -1, +0] }, "scale.z+": { name: "scale.z+", node: new Object3D(), color: blue, alignment: [+0, +0, +1] }, "scale.z-": { name: "scale.z-", node: new Object3D(), color: blue, alignment: [+0, +0, -1] }, "lines": { name: 'lines', node: new Object3D(), dontScale: true } //add }; this.focusHandles = { "focus.x+": { name: "focus.x+", node: new Object3D(), color: red, alignment: [+1, +0, +0] }, "focus.x-": { name: "focus.x-", node: new Object3D(), color: red, alignment: [-1, +0, +0] }, "focus.y+": { name: "focus.y+", node: new Object3D(), color: green, alignment: [+0, +1, +0] }, "focus.y-": { name: "focus.y-", node: new Object3D(), color: green, alignment: [+0, -1, +0] }, "focus.z+": { name: "focus.z+", node: new Object3D(), color: blue, alignment: [+0, +0, +1] }, "focus.z-": { name: "focus.z-", node: new Object3D(), color: blue, alignment: [+0, +0, -1] } }; this.translationHandles = { "translation.x": { name: "translation.x", node: new Object3D(), color: red, alignment: [1, 0, 0] }, "translation.y": { name: "translation.y", node: new Object3D(), color: green, alignment: [0, 1, 0] }, "translation.z": { name: "translation.z", node: new Object3D(), color: blue, alignment: [0, 0, 1] }, //add 'translation.xyz': { name: "translation.xyz", node: new Object3D(), color: white, alignment: [0, 0, 0], alignment2: [1, 1, 1] }, 'translation.plane.xy': { name: "translation.plane.xy", node: new Object3D(), color: blue, alignment: [0, 0, 1], alignment2: [1, 1, 0] }, 'translation.plane.yz': { name: "translation.plane.yz", node: new Object3D(), color: red, alignment: [1, 0, 0], alignment2: [0, 1, 1] }, 'translation.plane.xz': { name: "translation.plane.xz", node: new Object3D(), color: green, alignment: [0, 1, 0], alignment2: [1, 0, 1] } }; this.rotationHandles = { "rotation.x": { name: "rotation.x", node: new Object3D(), color: red, alignment: [1, 0, 0] }, "rotation.y": { name: "rotation.y", node: new Object3D(), color: green, alignment: [0, 1, 0] }, "rotation.z": { name: "rotation.z", node: new Object3D(), color: blue, alignment: [0, 0, 1] } }; this.handles = Object.assign({}, this.scaleHandles, hideFocusHandles ? {} : this.focusHandles, this.translationHandles, this.rotationHandles); this.pickVolumes = []; this.initializeScaleHandles(); this.initializeFocusHandles(); this.initializeTranslationHandles(); this.initializeRotationHandles(); var boxFrameGeometry = new Geometry(); { // bottom boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5)); // top boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5)); // sides boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5)); boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5)); boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5)); } this.frame = new LineSegments(boxFrameGeometry, new LineBasicMaterial({ color: 0xffff00 })); this.scene.add(this.frame); //------------------add----------------------- this.setModeEnable(['scale', 'translation', 'rotation']); Potree.Utils.setObjectLayers(this.scene, 'transformationTool'); this.scene.traverse(e => { e.pickDontCheckDis = true; //pick时不需要识别是否在点云之上 }); { var exist = object => { //是否没被删除(暂时不考虑换了parent) while (object.parent) { object = object.parent; } if (object instanceof Scene) { return true; } }; this.history = new History({ //也可以写到全局,但需要加个判断物品是否存在的函数 applyData: data => { if (exist(data.object)) { //viewer.scene.volumes.includes(data.box) //或许还要识别是否matrixAuto data.matrix.decompose(data.object.position, data.object.quaternion, data.object.scale); this.dispatchEvent('changeByHistory'); viewer.dispatchEvent('content_changed'); return true; } }, getData: data => { return data; } }); this.addEventListener('transformed', e => { var object = viewer.transformationTool.selection[0]; this.history.beforeChange({ object, matrix: e.matrixBefore.clone() }); this.viewer.dispatchEvent('content_changed'); }); this.addEventListener('stopDrag', e => { var object = viewer.transformationTool.selection[0]; object && this.history.afterChange({ object, matrix: object.matrix.clone() }); }); /* viewer.inputHandler.addEventListener('keydown', (e)=>{ if(e.keyCode == 90 && e.event.ctrlKey){//Z this.history.undo() }else if(e.keyCode == 89 && e.event.ctrlKey){//Y this.history.redo() } }) */ } } setModeEnable() { var enableModes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; //xzw add var length = 0; ['translation', 'scale', 'rotation'].forEach(mode => { var handels = this[mode + 'Handles']; var enable = enableModes.includes(mode); for (var o in handels) { Potree.Utils.updateVisible(handels[o].node, 'modeForce', !!enable); } this.modesEnabled[mode] = !!enable; enable && length++; }); if (this.style == 'singleMode' && length > 1) { this.changeStyle('mixedModes'); } else if (this.style == 'mixedModes' && length == 1) { this.changeStyle('singleMode'); } } changeStyle(style) { // 切换单个mode & 多个mode混合 风格(因多个混合比较拥挤,需要做调整) var s1 = style == 'singleMode' ? 30 : 25; var s2 = style == 'singleMode' ? 15 : 10; ['x', 'y', 'z'].forEach(axis => { this.translationHandles['translation.' + axis].node.children.forEach(mesh => { if (mesh.name.includes('arrow')) { Potree.Utils.updateVisible(mesh, 'modeStyle', style == 'singleMode'); } else if (mesh.name.includes('handle')) { mesh.material.lineWidth = style == 'singleMode' ? 5 : 7; } }); this.rotationHandles['rotation.' + axis].translateNode.scale.set(s1, s1, s1); }); ['xy', 'yz', 'xz'].forEach(axis => { var handle = this.translationHandles['translation.plane.' + axis]; handle.node.children[0].scale.set(s2, s2, s2); handle.node.children[0].position.fromArray(handle.alignment2).multiplyScalar(s2 * 1.5); }); Potree.Utils.updateVisible(this.scaleHandles['lines'].node, 'modeStyle', style == 'singleMode'); this.style = style; } initializeTranslationHandles() { var _this = this; //大改 var boxGeometry = new BoxGeometry(1, 1, 1); var length = 100, arrowRadius = 4, arrowHeight = 10; var arrowGeometry = new CylinderBufferGeometry(0, arrowRadius, arrowHeight, 12, 1, false); //add 箭头朝(0,1,0) var arrowInitialQua = new Quaternion().setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2); //先将qua旋转到朝向0,0,-1, 因为一般quaternion不设置时默认表示朝向0,0,-1, var octahedronGeometry = new OctahedronBufferGeometry(5, 0); var planeGeometry = new PlaneBufferGeometry(1, 1); var _loop = function _loop(handleName) { var handle = _this.handles[handleName]; var node = handle.node; _this.scene.add(node); node.name = handleName; //add var alignment = new Vector3(...handle.alignment); var geometry, mesh, pickVolume, meshScale, pickScale, rotation, position, lookAtPoint, hasPick = true, meshPickable = false, renderOrder; var matProp = { color: handle.color, opacity: OpaWhenNotSelect, transparent: true, side: handleName.includes('plane') ? DoubleSide : FrontSide }; var material = new MeshBasicMaterial(matProp); var pickMaterial = new MeshNormalMaterial({ opacity: 0.2, transparent: true, visible: _this.showPickVolumes }); if (handleName.includes('xyz')) { geometry = octahedronGeometry; meshPickable = true; renderOrder = 12; } else if (handleName.includes('plane')) { geometry = planeGeometry; meshPickable = true; position = new Vector3(...handle.alignment2); lookAtPoint = alignment; if (handleName.includes('xy')) {} else if (handleName.includes('yz')) {} else if (handleName.includes('xz')) {} } else { geometry = boxGeometry; var point = new Vector3(0, 0, length / 2); //new THREE.Vector3().copy(alignment).multiplyScalar(length/2) mesh = LineDraw.createFatLine([point, point.clone().negate()], { lineWidth: 6, mat: new LineDraw.createFatLineMat(matProp) }); lookAtPoint = alignment; renderOrder = 10; pickScale = new Vector3(4, 4, length + arrowHeight * 2); //pickScale = new THREE.Vector3(4, 4, 1.2) { var arrow = new Mesh(arrowGeometry, material); arrow.name = "".concat(handleName, ".arrow"); arrow.renderOrder = 11; arrow.position.set(...handle.alignment).multiplyScalar(length / 2 + arrowHeight / 2); arrow.lookAt(0, 0, 0); node.add(arrow); var arrow2 = arrow.clone(); arrow2.position.negate(); arrow2.lookAt(0, 0, 0); node.add(arrow2); arrow.quaternion.multiply(arrowInitialQua); //乘上初始旋转 arrow2.quaternion.multiply(arrowInitialQua); } } mesh || (mesh = new Mesh(geometry, material)); mesh.name = "".concat(handleName, ".handle"); node.add(mesh); renderOrder && (mesh.renderOrder = renderOrder); meshScale && mesh.scale.copy(meshScale); rotation && mesh.rotation.copy(rotation); lookAtPoint && mesh.lookAt(lookAtPoint); position && mesh.position.copy(position); if (!meshPickable && hasPick) { pickVolume = new Mesh(geometry, pickMaterial); pickScale && pickVolume.scale.copy(pickScale); } else if (hasPick && meshPickable) { pickVolume = mesh; } if (pickVolume) { if (mesh != pickVolume) { mesh.add(pickVolume); pickVolume.name = "".concat(handleName, ".pick_volume"); } else { pickVolume.name += ' & pick_volume'; } pickVolume.handle = handleName; _this.pickVolumes.push(pickVolume); } node.setOpacity = target => { if (handleName.includes('plane')) { var more = 1.5; //减掉更多,使min更低,max还是1 target = 1 - (1 - target) * more; } var opacity = { x: material.opacity }; var t = new TWEEN.Tween(opacity).to({ x: target }, 0); t.onUpdate(() => { mesh.visible = opacity.x > 0; pickVolume && (pickVolume.visible = opacity.x > 0); material.opacity = opacity.x; mesh.material.opacity = opacity.x; //outlineMaterial.opacity = opacity.x; pickMaterial.opacity = opacity.x * 0.5; }); t.start(); }; pickVolume.addEventListener("drag", e => { _this.dragTranslationHandle(e); }); pickVolume.addEventListener("drop", e => { _this.dropTranslationHandle(e); }); }; for (var handleName of Object.keys(this.translationHandles)) { _loop(handleName); } } initializeScaleHandles() { var _this2 = this; var sgSphere = new SphereGeometry(1, 32, 32); var sgLowPolySphere = new SphereGeometry(1, 16, 16); var _loop2 = function _loop2() { var handle = _this2.scaleHandles[handleName]; var node = handle.node; node.name = handleName; //add _this2.scene.add(node); if (handleName == 'lines') { //add ['x', 'y', 'z'].forEach(axis => { var handle1_ = _this2.scaleHandles['scale.' + axis + '+']; var handle2_ = _this2.scaleHandles['scale.' + axis + '-']; var line = LineDraw.createFatLine([new Vector3().fromArray(handle1_.alignment).multiplyScalar(0.5), new Vector3().fromArray(handle2_.alignment).multiplyScalar(0.5)], { color: handle1_.color, lineWidth: 4 } // , dontAlwaysSeen:true ); node.add(line); }); node.setOpacity = opacity => { opacity *= 0.6; node.children.forEach(e => e.material.opacity = opacity); }; return 1; // continue } node.position.set(...handle.alignment).multiplyScalar(0.5); var material = new MeshBasicMaterial({ color: handle.color, side: DoubleSide, //xzw add opacity: OpaWhenNotSelect, transparent: true }); var outlineMaterial = new MeshBasicMaterial({ color: OutlineColor, side: BackSide, opacity: OpaWhenNotSelect, transparent: true }); var pickMaterial = new MeshNormalMaterial({ opacity: 0.2, transparent: true, side: DoubleSide, //xzw add for orthoCam, 缩小画面时因球体放大导致到相机背面去了而看不到球体正面 visible: _this2.showPickVolumes }); var sphere = new Mesh(sgSphere, material); sphere.scale.set(5, 5, 5); sphere.name = "".concat(handleName, ".handle"); node.add(sphere); sphere.renderOrder = 10; /* let outline = new THREE.Mesh(sgSphere, outlineMaterial); outline.scale.set(1.1, 1.1, 1.1); outline.name = `${handleName}.outline`; sphere.add(outline); */ var pickSphere = new Mesh(sgLowPolySphere, pickMaterial); pickSphere.name = "".concat(handleName, ".pick_volume"); pickSphere.scale.set(1.5, 1.5, 1.5); sphere.add(pickSphere); pickSphere.handle = handleName; _this2.pickVolumes.push(pickSphere); node.setOpacity = target => { var opacity = { x: material.opacity }; var t = new TWEEN.Tween(opacity).to({ x: target }, 0); //xzw改 原100毫秒,因为太慢容易选错 t.onUpdate(() => { sphere.visible = opacity.x > 0; pickSphere.visible = opacity.x > 0; material.opacity = opacity.x; outlineMaterial.opacity = opacity.x; pickSphere.material.opacity = opacity.x * 0.5; }); t.start(); }; pickSphere.addEventListener("drag", e => _this2.dragScaleHandle(e)); pickSphere.addEventListener("drop", e => _this2.dropScaleHandle(e)); pickSphere.addEventListener("mouseover", e => { //node.setOpacity(1); }); pickSphere.addEventListener("click", e => { //e.consume(); }); pickSphere.addEventListener("mouseleave", e => { //node.setOpacity(OpaWhenNotSelect); }); }; for (var handleName of Object.keys(this.scaleHandles)) { if (_loop2()) continue; } } initializeRotationHandles() { var _this3 = this; var boldAdjust = 2.3; var torusGeometry = new TorusGeometry(1.3, boldAdjust * 0.015, 8, 64, Math.PI / 2); //let outlineGeometry = new THREE.TorusGeometry(1, boldAdjust * 0.018, 8, 64, Math.PI / 2); var pickGeometry = new TorusGeometry(1.3, boldAdjust * 0.06, 6, 4, Math.PI / 2); var _loop3 = function _loop3() { var handle = _this3.handles[handleName]; var node = handle.node; _this3.scene.add(node); node.name = handleName; //add var material = new MeshBasicMaterial({ color: handle.color, opacity: OpaWhenNotSelect, transparent: true }); /* let outlineMaterial = new THREE.MeshBasicMaterial({ color: OutlineColor, side: THREE.BackSide, opacity: OpaWhenNotSelect, transparent: true }); */ var pickMaterial = new MeshNormalMaterial({ opacity: 0.2, transparent: true, visible: _this3.showPickVolumes }); var box = new Mesh(torusGeometry, material); box.name = "".concat(handleName, ".handle"); box.scale.set(30, 30, 30); box.lookAt(new Vector3(...handle.alignment)); node.add(box); handle.translateNode = box; /* let outline = new THREE.Mesh(outlineGeometry, outlineMaterial); outline.name = `${handleName}.outline`; outline.scale.set(1, 1, 1); outline.renderOrder = 0; box.add(outline); */ var pickVolume = new Mesh(pickGeometry, pickMaterial); pickVolume.name = "".concat(handleName, ".pick_volume"); pickVolume.scale.set(1, 1, 1); pickVolume.handle = handleName; box.add(pickVolume); _this3.pickVolumes.push(pickVolume); node.setOpacity = target => { var opacity = { x: material.opacity }; var t = new TWEEN.Tween(opacity).to({ x: target }, 0); t.onUpdate(() => { box.visible = opacity.x > 0; pickVolume.visible = opacity.x > 0; material.opacity = opacity.x; //outlineMaterial.opacity = opacity.x; pickMaterial.opacity = opacity.x * 0.5; }); t.start(); }; //pickVolume.addEventListener("mouseover", (e) => { // //let a = this.viewer.scene.getActiveCamera().getWorldDirection(new THREE.Vector3()).dot(pickVolume.getWorldDirection(new THREE.Vector3())); // console.log(pickVolume.getWorldDirection(new THREE.Vector3())); //}); pickVolume.addEventListener("drag", e => { _this3.dragRotationHandle(e); }); pickVolume.addEventListener("drop", e => { _this3.dropRotationHandle(e); }); }; for (var handleName of Object.keys(this.rotationHandles)) { _loop3(); } } initializeFocusHandles() { var _this4 = this; if (hideFocusHandles) return; //add //let sgBox = new THREE.BoxGeometry(1, 1, 1); var sgPlane = new PlaneGeometry(4, 4, 1, 1); var sgLowPolySphere = new SphereGeometry(1, 16, 16); var texture = new TextureLoader().load("".concat(exports.resourcePath, "/icons/eye_2.png")); var _loop4 = function _loop4() { var handle = _this4.focusHandles[handleName]; var node = handle.node; _this4.scene.add(node); var align = handle.alignment; node.name = handleName; //add //node.lookAt(new THREE.Vector3().addVectors(node.position, new THREE.Vector3(...align))); node.lookAt(new Vector3(...align)); var off = 0.8; if (align[0] === 1) { node.position.set(1, off, -off).multiplyScalar(0.5); node.rotation.z = Math.PI / 2; } else if (align[0] === -1) { node.position.set(-1, -off, -off).multiplyScalar(0.5); node.rotation.z = Math.PI / 2; } else if (align[1] === 1) { node.position.set(-off, 1, -off).multiplyScalar(0.5); node.rotation.set(Math.PI / 2, Math.PI, 0.0); } else if (align[1] === -1) { node.position.set(off, -1, -off).multiplyScalar(0.5); node.rotation.set(Math.PI / 2, 0.0, 0.0); } else if (align[2] === 1) { node.position.set(off, off, 1).multiplyScalar(0.5); } else if (align[2] === -1) { node.position.set(-off, off, -1).multiplyScalar(0.5); } var material = new MeshBasicMaterial({ color: handle.color, opacity: 0, transparent: true, map: texture }); //let outlineMaterial = new THREE.MeshBasicMaterial({ // color: 0x000000, // side: THREE.BackSide, // opacity: 0, // transparent: true}); var pickMaterial = new MeshNormalMaterial({ //opacity: 0, transparent: true, visible: _this4.showPickVolumes }); var box = new Mesh(sgPlane, material); box.name = "".concat(handleName, ".handle"); box.scale.set(1.5, 1.5, 1.5); box.position.set(0, 0, 0); box.visible = false; node.add(box); //handle.focusNode = box; //let outline = new THREE.Mesh(sgPlane, outlineMaterial); //outline.scale.set(1.4, 1.4, 1.4); //outline.name = `${handleName}.outline`; //box.add(outline); var pickSphere = new Mesh(sgLowPolySphere, pickMaterial); pickSphere.name = "".concat(handleName, ".pick_volume"); pickSphere.scale.set(2, 2, 2); box.add(pickSphere); pickSphere.handle = handleName; _this4.pickVolumes.push(pickSphere); node.setOpacity = target => { var opacity = { x: material.opacity }; var t = new TWEEN.Tween(opacity).to({ x: target }, 0); t.onUpdate(() => { pickSphere.visible = opacity.x > 0; box.visible = opacity.x > 0; material.opacity = opacity.x; //outlineMaterial.opacity = opacity.x; pickSphere.material.opacity = opacity.x * 0.5; }); t.start(); }; //pickSphere.addEventListener("drag", e => {}); pickSphere.addEventListener("mouseup", e => { //e.consume(); }); pickSphere.addEventListener("mousedown", e => { //e.consume(); }); pickSphere.addEventListener("click", e => { //e.consume(); var selected = _this4.selection[0]; var maxScale = Math.max(...selected.scale.toArray()); var minScale = Math.min(...selected.scale.toArray()); var handleLength = Math.abs(selected.scale.dot(new Vector3(...handle.alignment))); var alignment = new Vector3(...handle.alignment).multiplyScalar(2 * maxScale / handleLength); alignment.applyMatrix4(selected.matrixWorld); var newCamPos = alignment; var newCamTarget = selected.getWorldPosition(new Vector3()); Utils.moveTo(_this4.viewer.scene, newCamPos, newCamTarget); }); pickSphere.addEventListener("mouseover", e => { //box.setOpacity(1); }); pickSphere.addEventListener("mouseleave", e => { //box.setOpacity(OpaWhenNotSelect); }); }; for (var handleName of Object.keys(this.focusHandles)) { _loop4(); } } dragRotationHandle(e) { var drag = e.drag; var handle = this.activeHandle; var camera = this.viewer.mainViewport.camera; //this.viewer.scene.getActiveCamera(); if (!handle || !handle.name.includes('rotation')) { return; } ; var localNormal = new Vector3(...handle.alignment); var n = new Vector3(); n.copy(new Vector4(...localNormal.toArray(), 0).applyMatrix4(handle.node.matrixWorld)); n.normalize(); if (!drag.intersectionStart) { //this.viewer.scene.scene.remove(this.debug); //this.debug = new THREE.Object3D(); //this.viewer.scene.scene.add(this.debug); //Utils.debugSphere(this.debug, drag.location, 3, 0xaaaaaa); //let debugEnd = drag.location.clone().add(n.clone().multiplyScalar(20)); //Utils.debugLine(this.debug, drag.location, debugEnd, 0xff0000); drag.intersectionStart = drag.location; drag.objectStart = drag.object.getWorldPosition(new Vector3()); drag.handle = handle; var plane = new Plane().setFromNormalAndCoplanarPoint(n, drag.intersectionStart); drag.dragPlane = plane; drag.pivot = drag.intersectionStart; } else { handle = drag.handle; } if (!drag.dragPlane) return; //xzw add 因有时候没有 this.dragging = true; var pointer = this.viewer.inputHandler.pointer; var domElement = this.viewer.renderer.domElement; var ray = Utils.mouseToRay(pointer, camera, domElement.clientWidth, domElement.clientHeight); var I = ray.intersectPlane(drag.dragPlane, new Vector3()); if (I) { var center = this.scene.getWorldPosition(new Vector3()); //bounding中心 var from = drag.pivot; var to = I; var v1 = from.clone().sub(center).normalize(); var v2 = to.clone().sub(center).normalize(); var angle = Math.acos(v1.dot(v2)); var sign = Math.sign(v1.cross(v2).dot(n)); angle = angle * sign; if (Number.isNaN(angle)) { return; } var matrixBefore = this.selection[0].matrix.clone(); var normal = new Vector3(...handle.alignment); for (var selection of this.selection) { //直接修改matrix,使整体绕boundingBox中心旋转。 xzw var quaternion = selection.quaternion.clone(); var diffQua = new Quaternion().setFromAxisAngle(normal, angle); //变化量,参考 selection.rotateOnAxis(normal, angle); var moveToZero = new Matrix4().setPosition(center.clone().negate()); //先将boundingBox中心(整体)移动到原点 var rotM = new Matrix4().makeRotationFromQuaternion(quaternion.clone().inverse().premultiply(diffQua).premultiply(quaternion)); //再旋转。根据selection.rotateOnAxis,应该是旧的qua 右乘 diffQua,所以先用invert消掉旧的qua var moveBack = new Matrix4().setPosition(center.clone()); //移动回去,使boundingBox中心位置还原 selection.matrix.premultiply(moveToZero).premultiply(rotM).premultiply(moveBack); selection.matrix.decompose(selection.position, selection.quaternion, selection.scale); //记录 (scale基本不变) selection.updateMatrixWorld(); //xzw add 保险起见立即update selection.dispatchEvent({ type: "orientation_changed", object: selection }); selection.dispatchEvent({ //当boundingBox中心不在原点时 type: "position_changed", object: selection }); } this.dispatchEvent({ type: 'transformed', changeType: ['orientation'], matrixBefore }); //add drag.pivot = I; } } dropRotationHandle(e) { this.dragging = false; this.setActiveHandle(null); this.dispatchEvent({ type: 'stopDrag', handle: 'rotation' }); //add } dragTranslationHandle(e) { //---大改,参考transformControls,为了加上xyz xy yz xz 这四个方向的变换。 (但感觉好像plane上有丢丢延迟?是因为drag延迟还是worldmatrix没更新) var drag = e.drag; var handle = this.activeHandle; var camera = this.viewer.mainViewport.camera; //this.viewer.scene.getActiveCamera(); if (handle && handle.name.includes('translation') && this.selection[0]) { var posWorld = this.scene.getWorldPosition(new Vector3()); //bounding中心 if (!drag.intersectionStart) { drag.intersectionStart = drag.location; drag.worldPositionStart = this.selection[0].getWorldPosition(new Vector3()); drag.objectQua = this.selection[0].quaternion.clone(); //不考虑父级 drag.objectQuaInv = drag.objectQua.clone().invert(); this.dragging = true; } if (drag.intersectionStart) { var pointer = this.viewer.inputHandler.pointer; var ray = Utils.mouseToRay(pointer, camera); //方向滑动所在面 var normal; var axisName = handle.name.split('.').pop(); if (axisName == 'xyz') { // 平行于屏幕滑动 normal = viewer.mainViewport.view.direction; } else { var alignVector = new Vector3(); normal = new Vector3(); var unitX = new Vector3(1, 0, 0).applyQuaternion(drag.objectQua); var unitY = new Vector3(0, 1, 0).applyQuaternion(drag.objectQua); var unitZ = new Vector3(0, 0, 1).applyQuaternion(drag.objectQua); switch (axisName) { case 'x': alignVector.copy(viewer.mainViewport.view.direction).cross(unitX); normal.copy(unitX).cross(alignVector); break; case 'y': alignVector.copy(viewer.mainViewport.view.direction).cross(unitY); normal.copy(unitY).cross(alignVector); break; case 'z': alignVector.copy(viewer.mainViewport.view.direction).cross(unitZ); normal.copy(unitZ).cross(alignVector); break; case 'xy': normal.copy(unitZ); break; case 'yz': normal.copy(unitX); break; case 'xz': normal.copy(unitY); break; } //参考transformControls.使跟手 } drag.dragPlane = new Plane().setFromNormalAndCoplanarPoint(normal, posWorld /* drag.worldPositionStart */); //过center的与视线垂直的平面 var I = ray.intersectPlane(drag.dragPlane, new Vector3()); if (I) { var offset = new Vector3().subVectors(I, drag.worldPositionStart); //let offset = new THREE.Vector3().subVectors(iOnLine, drag.worldPositionStart); if (!drag.pointStart) { drag.pointStart = offset; } else { drag.pointEnd = offset; var diff = new Vector3().subVectors(drag.pointEnd, drag.pointStart); diff.applyQuaternion(drag.objectQuaInv); // 得到在该物体local空间上的offset if (!handle.name.includes('x')) diff.x = 0; if (!handle.name.includes('y')) diff.y = 0; if (!handle.name.includes('z')) diff.z = 0; //恢复为world offset diff.applyQuaternion(drag.objectQua); //------------- var matrixBefore = this.selection[0].matrix.clone(); this.selection[0].position.copy(diff).add(drag.worldPositionStart); for (var selection of this.selection) { selection.updateMatrixWorld(); //xzw add 保险起见立即update selection.dispatchEvent({ type: "position_changed", object: selection }); } this.dispatchEvent({ type: 'transformed', changeType: ['position'], matrixBefore }); //add } } } } } dropTranslationHandle(e) { this.dragging = false; this.setActiveHandle(null); this.dispatchEvent({ type: 'stopDrag', handle: 'translation' }); //add } dropScaleHandle(e) { this.dragging = false; this.setActiveHandle(null); this.dispatchEvent({ type: 'stopDrag', handle: 'scale' }); //add } dragScaleHandle(e) { var drag = e.drag; var handle = this.activeHandle; if (!handle || !handle.name.includes('scale')) return; var camera = this.viewer.mainViewport.camera; //this.viewer.scene.getActiveCamera(); if (!drag.intersectionStart) { drag.intersectionStart = drag.location; drag.objectStart = drag.object.getWorldPosition(new Vector3()); drag.handle = handle; var start = drag.intersectionStart; var dir = new Vector4(...handle.alignment, 0).applyMatrix4(this.scene.matrixWorld); var end = new Vector3().addVectors(start, dir); var line = new Line3(start.clone(), end.clone()); drag.line = line; var normal; if (camera.type == 'OrthographicCamera') { //xzw add normal = new Vector3(0, 0, -1).applyQuaternion(camera.quaternion); } else { var camOnLine = line.closestPointToPoint(camera.position, false, new Vector3()); normal = new Vector3().subVectors(camera.position, camOnLine); } var plane = new Plane().setFromNormalAndCoplanarPoint(normal, drag.intersectionStart); //过轴线的一个能铺满屏幕的平面 drag.dragPlane = plane; drag.pivot = drag.intersectionStart; //Utils.debugSphere(viewer.scene.scene, drag.pivot, 0.05); } else { handle = drag.handle; } this.dragging = true; if (drag.dragPlane) { //xzw add 因有时候没有 var pointer = this.viewer.inputHandler.pointer; var domElement = this.viewer.renderer.domElement; var ray = Utils.mouseToRay(pointer, camera, domElement.clientWidth, domElement.clientHeight); var I = ray.intersectPlane(drag.dragPlane, new Vector3()); if (I) { var iOnLine = drag.line.closestPointToPoint(I, false, new Vector3()); var direction = handle.alignment.reduce((a, v) => a + v, 0); var toObjectSpace = this.selection[0].matrixWorld.clone().invert(); var iOnLineOS = iOnLine.clone().applyMatrix4(toObjectSpace); var pivotOS = drag.pivot.clone().applyMatrix4(toObjectSpace); var diffOS = new Vector3().subVectors(iOnLineOS, pivotOS); var dragDirectionOS = diffOS.clone().normalize(); if (iOnLine.distanceTo(drag.pivot) === 0) { dragDirectionOS.set(0, 0, 0); } var dragDirection = dragDirectionOS.dot(new Vector3(...handle.alignment)); var alignment = new Vector3(...handle.alignment); var diff = new Vector3().subVectors(iOnLine, drag.pivot); var diffScale = alignment.clone().multiplyScalar(diff.length() * direction * dragDirection); //let diffPosition = diff.clone().multiplyScalar(0.5); //这个仅当bound包含原点才准确。 var matrixBefore = this.selection[0].matrix.clone(); for (var selection of this.selection) { //xzw 改:否则不跟手 var { min, max } = selection.boundingBox; var fixPoint = alignment.x != 0 ? (alignment.x > 0 ? min : max).clone().setY(0).setZ(0) : //要保证另一边不能移动 alignment.y != 0 ? (alignment.y > 0 ? min : max).clone().setX(0).setZ(0) : (alignment.z > 0 ? min : max).clone().setX(0).setY(0); var fixPointBefore = fixPoint.clone().applyMatrix4(selection.matrixWorld); var size = selection.boundingBox.getSize(new Vector3()); var diffScale_ = diffScale.clone().divide(size); size.x == 0 && (diffScale_.x = 0); //add 若为0,不改此轴大小 size.y == 0 && (diffScale_.y = 0); size.z == 0 && (diffScale_.z = 0); selection.scale.add(diffScale_); selection.scale.max(new Vector3(0.1, 0.1, 0.1)); //selection.position.add(diffPosition); selection.updateMatrixWorld(); var fixPointAfter = fixPoint.clone().applyMatrix4(this.selection[0].matrixWorld); selection.position.sub(new Vector3().subVectors(fixPointAfter, fixPointBefore)); //保证另一边不能移动所需要的位移 selection.updateMatrixWorld(); //xzw add 保险起见立即update selection.dispatchEvent({ type: "position_changed", object: selection }); selection.dispatchEvent({ type: "scale_changed", object: selection }); } this.dispatchEvent({ type: 'transformed', changeType: ['position', 'scale'], matrixBefore }); //add drag.pivot.copy(iOnLine); //Utils.debugSphere(viewer.scene.scene, drag.pivot, 0.05); } } } setActiveHandle(handle) { if (this.dragging) { return; } if (this.activeHandle === handle) { return; } this.activeHandle = handle; if (handle === null) { for (var handleName of Object.keys(this.handles)) { var _handle = this.handles[handleName]; _handle.node.setOpacity(0); } } viewer.dispatchEvent({ type: 'CursorChange', action: this.activeHandle ? 'add' : 'remove', name: 'hoverTranHandle' }); if (!hideFocusHandles) { for (var _handleName of Object.keys(this.focusHandles)) { var _handle2 = this.focusHandles[_handleName]; if (this.activeHandle === _handle2) { _handle2.node.setOpacity(1.0); } else { _handle2.node.setOpacity(OpaWhenNotSelect); } } } for (var _handleName2 of Object.keys(this.translationHandles)) { var _handle3 = this.translationHandles[_handleName2]; if (this.activeHandle === _handle3) { _handle3.node.setOpacity(1.0); } else { _handle3.node.setOpacity(OpaWhenNotSelect); } } for (var _handleName3 of Object.keys(this.rotationHandles)) { var _handle4 = this.rotationHandles[_handleName3]; //if(this.activeHandle === handle){ // handle.node.setOpacity(1.0); //}else{ // handle.node.setOpacity(OpaWhenNotSelect) //} _handle4.node.setOpacity(OpaWhenNotSelect); } for (var _handleName4 of Object.keys(this.scaleHandles)) { var _handle5 = this.scaleHandles[_handleName4]; if (this.activeHandle === _handle5) { _handle5.node.setOpacity(1.0); if (!hideFocusHandles) { var relatedFocusHandle = this.focusHandles[_handle5.name.replace("scale", "focus")]; var relatedFocusNode = relatedFocusHandle.node; relatedFocusNode.setOpacity(OpaWhenNotSelect); } for (var translationHandleName of Object.keys(this.translationHandles)) { var translationHandle = this.translationHandles[translationHandleName]; translationHandle.node.setOpacity(OpaWhenNotSelect); } //let relatedTranslationHandle = this.translationHandles[ // handle.name.replace("scale", "translation").replace(/[+-]/g, "")]; //let relatedTranslationNode = relatedTranslationHandle.node; //relatedTranslationNode.setOpacity(OpaWhenNotSelect); } else { _handle5.node.setOpacity(OpaWhenNotSelect); } } if (handle) { handle.node.setOpacity(1.0); } viewer.dispatchEvent('content_changed'); } update() { if (this.selection.length === 1) { this.scene.visible = true; this.scene.updateMatrix(); this.scene.updateMatrixWorld(); var selected = this.selection[0]; //selected.updateMatrixWorld();//add 否则scale的sphere抖动 var world = selected.matrixWorld; var camera = this.viewer.mainViewport.camera; //this.viewer.scene.getActiveCamera(); var domElement = this.viewer.renderer.domElement; var center = selected.boundingBox.getCenter(new Vector3()).clone().applyMatrix4(selected.matrixWorld); var scale = selected.boundingBox.getSize(new Vector3()).multiply(selected.scale); scale.max(new Vector3(.1, .1, .1)); //xzw add 如果是plane,没有厚度,会导致该tool消失 this.scene.scale.copy(scale); this.scene.position.copy(center); this.scene.rotation.copy(selected.rotation); //这里只考虑当前子级的scale rotation //如果是世界坐标 (缩放方向有bug。) /* let boundingBox = selected.boundingBox.clone().applyMatrix4(selected.matrixWorld); let center = boundingBox.getCenter(new THREE.Vector3()) this.scene.position.copy(center); this.scene.scale.copy(boundingBox.getSize(new THREE.Vector3())); */ this.scene.updateMatrixWorld(); { // adjust rotation handles if (!this.dragging) { if (this.modesEnabled.rotation || this.modesEnabled.translation) { var tWorld = this.scene.matrixWorld; var tObject = tWorld.clone().invert(); var camObjectPos = camera.getWorldPosition(new Vector3()).applyMatrix4(tObject); if (this.modesEnabled.translation) { //add ['xy', 'yz', 'xz'].forEach(axis => { var handle = this.translationHandles["translation.plane." + axis]; var pos = handle.node.children[0].position; camObjectPos.x && (pos.x = Math.sign(camObjectPos.x) * Math.abs(pos.x)); camObjectPos.y && (pos.y = Math.sign(camObjectPos.y) * Math.abs(pos.y)); camObjectPos.z && (pos.z = Math.sign(camObjectPos.z) * Math.abs(pos.z)); }); } if (this.modesEnabled.rotation) { var above = camObjectPos.z > 0; var below = !above; var PI_HALF = Math.PI / 2; var x = this.rotationHandles["rotation.x"].node.rotation; var y = this.rotationHandles["rotation.y"].node.rotation; var z = this.rotationHandles["rotation.z"].node.rotation; x.order = "ZYX"; y.order = "ZYX"; if (above) { if (camObjectPos.x > 0 && camObjectPos.y > 0) { x.x = 1 * PI_HALF; y.y = 3 * PI_HALF; z.z = 0 * PI_HALF; } else if (camObjectPos.x < 0 && camObjectPos.y > 0) { x.x = 1 * PI_HALF; y.y = 2 * PI_HALF; z.z = 1 * PI_HALF; } else if (camObjectPos.x < 0 && camObjectPos.y < 0) { x.x = 2 * PI_HALF; y.y = 2 * PI_HALF; z.z = 2 * PI_HALF; } else if (camObjectPos.x > 0 && camObjectPos.y < 0) { x.x = 2 * PI_HALF; y.y = 3 * PI_HALF; z.z = 3 * PI_HALF; } } else if (below) { if (camObjectPos.x > 0 && camObjectPos.y > 0) { x.x = 0 * PI_HALF; y.y = 0 * PI_HALF; z.z = 0 * PI_HALF; } else if (camObjectPos.x < 0 && camObjectPos.y > 0) { x.x = 0 * PI_HALF; y.y = 1 * PI_HALF; z.z = 1 * PI_HALF; } else if (camObjectPos.x < 0 && camObjectPos.y < 0) { x.x = 3 * PI_HALF; y.y = 1 * PI_HALF; z.z = 2 * PI_HALF; } else if (camObjectPos.x > 0 && camObjectPos.y < 0) { x.x = 3 * PI_HALF; y.y = 0 * PI_HALF; z.z = 3 * PI_HALF; } } } } } // adjust scale of components for (var handleName of Object.keys(this.handles)) { var handle = this.handles[handleName]; var node = handle.node; //xzw add:---- -当该轴正对相机时隐藏。(主要针对ortho类型camera。 if (!Potree.Utils.getObjVisiByReason(node, 'modeForce')) continue; var alignment = handle.alignment; if (alignment && (!handleName.includes('rotation') || camera.type == 'OrthographicCamera')) { //旋转的话正常都应该显示 var normal = void 0; var dir = new Vector3(...alignment).applyQuaternion(this.scene.quaternion); if (camera.type == 'OrthographicCamera') { normal = new Vector3(0, 0, -1).applyQuaternion(camera.quaternion); } else { normal = new Vector3().subVectors(center, camera.position).normalize(); } var ifOnLine = void 0; if (handleName.includes('rotation') || handleName.includes('plane')) { // 旋转轴和视线垂直时隐藏 ifOnLine = Math.abs(dir.dot(normal)) < 0.1; } else { ifOnLine = Math.abs(dir.dot(normal)) > 0.995; } Potree.Utils.updateVisible(node, 'faceToCamHide', !ifOnLine); } else { Potree.Utils.updateVisible(node, 'faceToCamHide', true); } if (!node.visible) continue; //------------------------------------------------------------------------ if (handle.dontScale) continue; //add var handlePos = node.getWorldPosition(new Vector3()); var distance = handlePos.distanceTo(camera.position); var pr = Utils.projectedRadius(1, camera, distance, domElement.clientWidth, domElement.clientHeight); var ws = node.parent.getWorldScale(new Vector3()); var s = ScaleRatio / pr; var _scale = new Vector3(s, s, s).divide(ws); var rot = new Matrix4().makeRotationFromEuler(node.rotation); //需要使用到旋转,所以我把设置scale的移到旋转后了,否则在视图上下旋转的分界线处rotateHandel会被拉长从而闪烁。 var rotInv = rot.clone().invert(); _scale.applyMatrix4(rotInv); _scale.x = Math.abs(_scale.x); _scale.y = Math.abs(_scale.y); _scale.z = Math.abs(_scale.z); node.scale.copy(_scale); } } } else { this.scene.visible = false; } } onPointerMove() { var pointer = this.viewer.inputHandler.pointer; var camera = this.viewer.mainViewport.camera; if (this.selection.length === 1 && !this.dragging) { //xzw 添加dragging条件 var ray = Utils.mouseToRay(pointer, camera); var raycaster = new Raycaster(ray.origin, ray.direction); raycaster.layers.enableAll(); //add var pickVolumes = this.pickVolumes.filter(v => { var mode = v.handle.split('.')[0]; if (!this.modesEnabled[mode]) return; return v.parent.parent.visible; //可能被隐藏该轴 }); var intersects = raycaster.intersectObjects(pickVolumes, true); intersects = intersects.sort(function (a, b) { var order2 = b.object.renderOrder || 0; var order1 = a.object.renderOrder || 0; return order2 - order1; }); // 降序 if (intersects.length > 0) { var I = intersects[0]; var handleName = I.object.handle; //console.log(handleName) this.setActiveHandle(this.handles[handleName]); } else { this.setActiveHandle(null); } } } } ; /* note: transformationTool.scene会跟随选中物体,其scale就是boundingbox的大小。因此transformationTool.frame这个框也会跟着缩放 */ var boxOpacity = { hovered: 0.1, selected: 0.2 }; var LineOpacity = { default: 0.6, selected: 1 }; var colors = { 2: 0x2ee4ce, //0x00ff80, //可见 3: 0xffc23b, //0xff3158, //不可见 4: 0xffffff // }; class Volume$1 extends Object3D { constructor() { var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(); if (this.constructor.name === "Volume") { console.warn("Can't create object of class Volume directly. Use classes BoxVolume or SphereVolume instead."); } this._clip = args.clip || false; this._visible = true; //this.showVolumeLabel = true; this._modifiable = args.modifiable || true; { // event listeners this.addEventListener('select', e => { //console.log('select') this.setSelected(true); }); this.addEventListener('deselect', e => { //console.log('deselect') this.setSelected(false); }); this.addEventListener('mouseover', e => { this.hovered = true; this.update(); }); this.addEventListener('mouseleave', e => { this.hovered = false; this.update(); }); } } setSelected(state) { //add this.selected = !!state; this.update(); } get visible() { return this._visible; } set visible(value) { if (this._visible !== value) { this._visible = value; this.dispatchEvent({ type: "visibility_changed", object: this }); } } getVolume() { console.warn("override this in subclass"); } update() {} raycast(raycaster, intersects) {} get clip() { return this._clip; } set clip(value) { if (this._clip !== value) { this._clip = value; this.update(); this.dispatchEvent({ type: "clip_changed", object: this }); } } get modifieable() { return this._modifiable; } set modifieable(value) { this._modifiable = value; this.update(); } } ; class BoxVolume$1 extends Volume$1 { constructor() { var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(args); this.constructor.counter = this.constructor.counter === undefined ? 0 : this.constructor.counter + 1; this.name = 'box_' + this.constructor.counter; this.clipTask = args.clipTask || Potree.ClipTask.SHOW_INSIDE; //add this.showBox = true; var boxGeometry = new BoxGeometry(1, 1, 1); boxGeometry.computeBoundingBox(); var boxFrameGeometry = new Geometry(); var Vector3$1 = Vector3; { boxFrameGeometry.vertices.push( // bottom new Vector3$1(-0.5, -0.5, 0.5), new Vector3$1(0.5, -0.5, 0.5), new Vector3$1(0.5, -0.5, 0.5), new Vector3$1(0.5, -0.5, -0.5), new Vector3$1(0.5, -0.5, -0.5), new Vector3$1(-0.5, -0.5, -0.5), new Vector3$1(-0.5, -0.5, -0.5), new Vector3$1(-0.5, -0.5, 0.5), // top new Vector3$1(-0.5, 0.5, 0.5), new Vector3$1(0.5, 0.5, 0.5), new Vector3$1(0.5, 0.5, 0.5), new Vector3$1(0.5, 0.5, -0.5), new Vector3$1(0.5, 0.5, -0.5), new Vector3$1(-0.5, 0.5, -0.5), new Vector3$1(-0.5, 0.5, -0.5), new Vector3$1(-0.5, 0.5, 0.5), // sides new Vector3$1(-0.5, -0.5, 0.5), new Vector3$1(-0.5, 0.5, 0.5), new Vector3$1(0.5, -0.5, 0.5), new Vector3$1(0.5, 0.5, 0.5), new Vector3$1(0.5, -0.5, -0.5), new Vector3$1(0.5, 0.5, -0.5), new Vector3$1(-0.5, -0.5, -0.5), new Vector3$1(-0.5, 0.5, -0.5)); } this.material = new DepthBasicMaterial({ color: colors[this.clipTask], side: DoubleSide, transparent: true, opacity: boxOpacity.hovered, depthTest: true, depthWrite: false, useDepth: true, clipDistance: 2, //消失距离 occlusionDistance: 0.1, //变为backColor距离 maxClipFactor: 0.9 }); this.box = new Mesh(boxGeometry, this.material); this.box.geometry.computeBoundingBox(); this.boundingBox = this.box.geometry.boundingBox; this.add(this.box); //this.frame = new THREE.LineSegments(boxFrameGeometry, new THREE.LineBasicMaterial({color: colors[this.clipTask], opacity:LineOpacity.default/* 0xff2050 */})); this.frame = LineDraw.createFatLine(boxFrameGeometry.vertices, { color: colors[this.clipTask], opacity: LineOpacity.default, lineWidth: 1, dontAlwaysSeen: true }); // this.frame.mode = THREE.Lines; this.add(this.frame); this.update(); } update() { this.boundingBox = this.box.geometry.boundingBox; this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere()); Potree.Utils.updateVisible(this.box, 'selected', (this.selected || this.hovered) && this.showBox); this.box.material.opacity = this.selected ? boxOpacity.selected : boxOpacity.hovered; this.box.material.color.set(colors[this.clipTask]); this.frame.material.color.set(colors[this.clipTask]); this.frame.material.opacity = this.selected ? LineOpacity.selected : LineOpacity.default; this.frame.material.lineWidth = this.selected ? 2 : 1; } raycast(raycaster, intersects) { var is = []; this.box.raycast(raycaster, is); if (is.length > 0) { var I = is[0]; intersects.push({ distance: I.distance, object: this, point: I.point.clone() }); } } getVolume() { return Math.abs(this.scale.x * this.scale.y * this.scale.z); } } ; class SphereVolume$2 extends Volume$1 { constructor() { var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(args); this.constructor.counter = this.constructor.counter === undefined ? 0 : this.constructor.counter + 1; this.name = 'sphere_' + this.constructor.counter; var sphereGeometry = new SphereGeometry(1, 32, 32); sphereGeometry.computeBoundingBox(); this.material = new MeshBasicMaterial({ color: 0x00ff00, transparent: true, opacity: 0.3, depthTest: true, depthWrite: false }); this.sphere = new Mesh(sphereGeometry, this.material); this.sphere.visible = false; this.sphere.geometry.computeBoundingBox(); this.boundingBox = this.sphere.geometry.boundingBox; this.add(this.sphere); this.label.visible = false; var frameGeometry = new Geometry(); { var steps = 64; var uSegments = 8; var vSegments = 5; var r = 1; for (var uSegment = 0; uSegment < uSegments; uSegment++) { var alpha = uSegment / uSegments * Math.PI * 2; var dirx = Math.cos(alpha); var diry = Math.sin(alpha); for (var i = 0; i <= steps; i++) { var v = i / steps * Math.PI * 2; var vNext = v + 2 * Math.PI / steps; var height = Math.sin(v); var xyAmount = Math.cos(v); var heightNext = Math.sin(vNext); var xyAmountNext = Math.cos(vNext); var vertex = new Vector3(dirx * xyAmount, diry * xyAmount, height); frameGeometry.vertices.push(vertex); var vertexNext = new Vector3(dirx * xyAmountNext, diry * xyAmountNext, heightNext); frameGeometry.vertices.push(vertexNext); } } // creates rings at poles, just because it's easier to implement for (var vSegment = 0; vSegment <= vSegments + 1; vSegment++) { //let height = (vSegment / (vSegments + 1)) * 2 - 1; // -1 to 1 var uh = vSegment / (vSegments + 1); // -1 to 1 uh = (1 - uh) * (-Math.PI / 2) + uh * (Math.PI / 2); var _height = Math.sin(uh); console.log(uh, _height); for (var _i = 0; _i <= steps; _i++) { var u = _i / steps * Math.PI * 2; var uNext = u + 2 * Math.PI / steps; var _dirx = Math.cos(u); var _diry = Math.sin(u); var dirxNext = Math.cos(uNext); var diryNext = Math.sin(uNext); var _xyAmount = Math.sqrt(1 - _height * _height); var _vertex = new Vector3(_dirx * _xyAmount, _diry * _xyAmount, _height); frameGeometry.vertices.push(_vertex); var _vertexNext = new Vector3(dirxNext * _xyAmount, diryNext * _xyAmount, _height); frameGeometry.vertices.push(_vertexNext); } } } this.frame = new LineSegments(frameGeometry, new LineBasicMaterial({ color: 0x000000 })); this.add(this.frame); var frameMaterial = new MeshBasicMaterial({ wireframe: true, color: 0x000000 }); this.frame = new Mesh(sphereGeometry, frameMaterial); //this.add(this.frame); //this.frame = new THREE.LineSegments(boxFrameGeometry, new THREE.LineBasicMaterial({color: 0x000000})); // this.frame.mode = THREE.Lines; //this.add(this.frame); this.update(); } update() { this.boundingBox = this.sphere.geometry.boundingBox; this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere()); //if (this._clip) { // this.sphere.visible = false; // this.label.visible = false; //} else { // this.sphere.visible = true; // this.label.visible = this.showVolumeLabel; //} } raycast(raycaster, intersects) { var is = []; this.sphere.raycast(raycaster, is); if (is.length > 0) { var I = is[0]; intersects.push({ distance: I.distance, object: this, point: I.point.clone() }); } } // see https://en.wikipedia.org/wiki/Ellipsoid#Volume getVolume() { return 4 / 3 * Math.PI * this.scale.x * this.scale.y * this.scale.z; } } ; function _OverloadYield(e, d) { this.v = e, this.k = d; } function _applyDecoratedDescriptor(i, e, r, n, l) { var a = {}; return Object.keys(n).forEach(function (i) { a[i] = n[i]; }), a.enumerable = !!a.enumerable, a.configurable = !!a.configurable, ("value" in a || a.initializer) && (a.writable = !0), a = r.slice().reverse().reduce(function (r, n) { return n(i, e, r) || r; }, a), l && void 0 !== a.initializer && (a.value = a.initializer ? a.initializer.call(l) : void 0, a.initializer = void 0), void 0 === a.initializer ? (Object.defineProperty(i, e, a), null) : a; } function _applyDecs2311(e, t, n, r, o, i) { var a, c, u, s, f, l, p, d = Symbol.metadata || Symbol.for("Symbol.metadata"), m = Object.defineProperty, h = Object.create, y = [h(null), h(null)], v = t.length; function g(t, n, r) { return function (o, i) { n && (i = o, o = e); for (var a = 0; a < t.length; a++) i = t[a].apply(o, r ? [i] : []); return r ? i : o; }; } function b(e, t, n, r) { if ("function" != typeof e && (r || void 0 !== e)) throw new TypeError(t + " must " + (n || "be") + " a function" + (r ? "" : " or undefined")); return e; } function applyDec(e, t, n, r, o, i, u, s, f, l, p) { function d(e) { if (!p(e)) throw new TypeError("Attempted to access private element on non-instance"); } var h = [].concat(t[0]), v = t[3], w = !u, D = 1 === o, S = 3 === o, j = 4 === o, E = 2 === o; function I(t, n, r) { return function (o, i) { return n && (i = o, o = e), r && r(o), P[t].call(o, i); }; } if (!w) { var P = {}, k = [], F = S ? "get" : j || D ? "set" : "value"; if (f ? (l || D ? P = { get: _setFunctionName(function () { return v(this); }, r, "get"), set: function (e) { t[4](this, e); } } : P[F] = v, l || _setFunctionName(P[F], r, E ? "" : F)) : l || (P = Object.getOwnPropertyDescriptor(e, r)), !l && !f) { if ((c = y[+s][r]) && 7 != (c ^ o)) throw Error("Decorating two elements with the same name (" + P[F].name + ") is not supported yet"); y[+s][r] = o < 3 ? 1 : o; } } for (var N = e, O = h.length - 1; O >= 0; O -= n ? 2 : 1) { var T = b(h[O], "A decorator", "be", !0), z = n ? h[O - 1] : void 0, A = {}, H = { kind: ["field", "accessor", "method", "getter", "setter", "class"][o], name: r, metadata: a, addInitializer: function (e, t) { if (e.v) throw new TypeError("attempted to call addInitializer after decoration was finished"); b(t, "An initializer", "be", !0), i.push(t); }.bind(null, A) }; if (w) c = T.call(z, N, H), A.v = 1, b(c, "class decorators", "return") && (N = c);else if (H.static = s, H.private = f, c = H.access = { has: f ? p.bind() : function (e) { return r in e; } }, j || (c.get = f ? E ? function (e) { return d(e), P.value; } : I("get", 0, d) : function (e) { return e[r]; }), E || S || (c.set = f ? I("set", 0, d) : function (e, t) { e[r] = t; }), N = T.call(z, D ? { get: P.get, set: P.set } : P[F], H), A.v = 1, D) { if ("object" == typeof N && N) (c = b(N.get, "accessor.get")) && (P.get = c), (c = b(N.set, "accessor.set")) && (P.set = c), (c = b(N.init, "accessor.init")) && k.unshift(c);else if (void 0 !== N) throw new TypeError("accessor decorators must return an object with get, set, or init properties or undefined"); } else b(N, (l ? "field" : "method") + " decorators", "return") && (l ? k.unshift(N) : P[F] = N); } return o < 2 && u.push(g(k, s, 1), g(i, s, 0)), l || w || (f ? D ? u.splice(-1, 0, I("get", s), I("set", s)) : u.push(E ? P[F] : b.call.bind(P[F])) : m(e, r, P)), N; } function w(e) { return m(e, d, { configurable: !0, enumerable: !0, value: a }); } return void 0 !== i && (a = i[d]), a = h(null == a ? null : a), f = [], l = function (e) { e && f.push(g(e)); }, p = function (t, r) { for (var i = 0; i < n.length; i++) { var a = n[i], c = a[1], l = 7 & c; if ((8 & c) == t && !l == r) { var p = a[2], d = !!a[3], m = 16 & c; applyDec(t ? e : e.prototype, a, m, d ? "#" + p : _toPropertyKey(p), l, l < 2 ? [] : t ? s = s || [] : u = u || [], f, !!t, d, r, t && d ? function (t) { return _checkInRHS(t) === e; } : o); } } }, p(8, 0), p(0, 0), p(8, 1), p(0, 1), l(u), l(s), c = f, v || w(e), { e: c, get c() { var n = []; return v && [w(e = applyDec(e, [t], r, e.name, 5, n)), g(n, 1)]; } }; } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); } function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } function _asyncGeneratorDelegate(t) { var e = {}, n = !1; function pump(e, r) { return n = !0, r = new Promise(function (n) { n(t[e](r)); }), { done: !1, value: new _OverloadYield(r, 1) }; } return e["undefined" != typeof Symbol && Symbol.iterator || "@@iterator"] = function () { return this; }, e.next = function (t) { return n ? (n = !1, t) : pump("next", t); }, "function" == typeof t.throw && (e.throw = function (t) { if (n) throw n = !1, t; return pump("throw", t); }), "function" == typeof t.return && (e.return = function (t) { return n ? (n = !1, t) : pump("return", t); }), e; } function _asyncIterator(r) { var n, t, o, e = 2; for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) { if (t && null != (n = r[t])) return n.call(r); if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r)); t = "@@asyncIterator", o = "@@iterator"; } throw new TypeError("Object is not async iterable"); } function AsyncFromSyncIterator(r) { function AsyncFromSyncIteratorContinuation(r) { if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object.")); var n = r.done; return Promise.resolve(r.value).then(function (r) { return { value: r, done: n }; }); } return AsyncFromSyncIterator = function (r) { this.s = r, this.n = r.next; }, AsyncFromSyncIterator.prototype = { s: null, n: null, next: function () { return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); }, return: function (r) { var n = this.s.return; return void 0 === n ? Promise.resolve({ value: r, done: !0 }) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments)); }, throw: function (r) { var n = this.s.return; return void 0 === n ? Promise.reject(r) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments)); } }, new AsyncFromSyncIterator(r); } function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } function _awaitAsyncGenerator(e) { return new _OverloadYield(e, 0); } function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } function _checkInRHS(e) { if (Object(e) !== e) throw TypeError("right-hand side of 'in' should be an object, got " + (null !== e ? typeof e : "null")); return e; } function _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _classNameTDZError(e) { throw new ReferenceError('Class "' + e + '" cannot be referenced in computed property keys.'); } function _classPrivateFieldGet2(s, a) { return s.get(_assertClassBrand(s, a)); } function _classPrivateFieldInitSpec(e, t, a) { _checkPrivateRedeclaration(e, t), t.set(e, a); } function _classPrivateFieldLooseBase(e, t) { if (!{}.hasOwnProperty.call(e, t)) throw new TypeError("attempted to use private field on non-instance"); return e; } var id = 0; function _classPrivateFieldLooseKey(e) { return "__private_" + id++ + "_" + e; } function _classPrivateFieldSet2(s, a, r) { return s.set(_assertClassBrand(s, a), r), r; } function _classPrivateGetter(s, r, a) { return a(_assertClassBrand(s, r)); } function _classPrivateMethodInitSpec(e, a) { _checkPrivateRedeclaration(e, a), a.add(e); } function _classPrivateSetter(s, r, a, t) { return r(_assertClassBrand(s, a), t), t; } function _classStaticPrivateMethodGet(s, a, t) { return _assertClassBrand(a, s), t; } function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var n = 0, F = function () {}; return { s: F, n: function () { return n >= r.length ? { done: !0 } : { done: !1, value: r[n++] }; }, e: function (r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function () { t = t.call(r); }, n: function () { var r = t.next(); return a = r.done, r; }, e: function (r) { u = !0, o = r; }, f: function () { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; } function _createForOfIteratorHelperLoose(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (t) return (t = t.call(r)).next.bind(t); if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var o = 0; return function () { return o >= r.length ? { done: !0 } : { done: !1, value: r[o++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _createSuper(t) { var r = _isNativeReflectConstruct(); return function () { var e, o = _getPrototypeOf(t); if (r) { var s = _getPrototypeOf(this).constructor; e = Reflect.construct(o, arguments, s); } else e = o.apply(this, arguments); return _possibleConstructorReturn(this, e); }; } function _decorate(e, r, t, i) { var o = _getDecoratorsApi(); if (i) for (var n = 0; n < i.length; n++) o = i[n](o); var s = r(function (e) { o.initializeInstanceElements(e, a.elements); }, t), a = o.decorateClass(_coalesceClassElements(s.d.map(_createElementDescriptor)), e); return o.initializeClassElements(s.F, a.elements), o.runClassFinishers(s.F, a.finishers); } function _getDecoratorsApi() { _getDecoratorsApi = function () { return e; }; var e = { elementsDefinitionOrder: [["method"], ["field"]], initializeInstanceElements: function (e, r) { ["method", "field"].forEach(function (t) { r.forEach(function (r) { r.kind === t && "own" === r.placement && this.defineClassElement(e, r); }, this); }, this); }, initializeClassElements: function (e, r) { var t = e.prototype; ["method", "field"].forEach(function (i) { r.forEach(function (r) { var o = r.placement; if (r.kind === i && ("static" === o || "prototype" === o)) { var n = "static" === o ? e : t; this.defineClassElement(n, r); } }, this); }, this); }, defineClassElement: function (e, r) { var t = r.descriptor; if ("field" === r.kind) { var i = r.initializer; t = { enumerable: t.enumerable, writable: t.writable, configurable: t.configurable, value: void 0 === i ? void 0 : i.call(e) }; } Object.defineProperty(e, r.key, t); }, decorateClass: function (e, r) { var t = [], i = [], o = { static: [], prototype: [], own: [] }; if (e.forEach(function (e) { this.addElementPlacement(e, o); }, this), e.forEach(function (e) { if (!_hasDecorators(e)) return t.push(e); var r = this.decorateElement(e, o); t.push(r.element), t.push.apply(t, r.extras), i.push.apply(i, r.finishers); }, this), !r) return { elements: t, finishers: i }; var n = this.decorateConstructor(t, r); return i.push.apply(i, n.finishers), n.finishers = i, n; }, addElementPlacement: function (e, r, t) { var i = r[e.placement]; if (!t && -1 !== i.indexOf(e.key)) throw new TypeError("Duplicated element (" + e.key + ")"); i.push(e.key); }, decorateElement: function (e, r) { for (var t = [], i = [], o = e.decorators, n = o.length - 1; n >= 0; n--) { var s = r[e.placement]; s.splice(s.indexOf(e.key), 1); var a = this.fromElementDescriptor(e), l = this.toElementFinisherExtras((0, o[n])(a) || a); e = l.element, this.addElementPlacement(e, r), l.finisher && i.push(l.finisher); var c = l.extras; if (c) { for (var p = 0; p < c.length; p++) this.addElementPlacement(c[p], r); t.push.apply(t, c); } } return { element: e, finishers: i, extras: t }; }, decorateConstructor: function (e, r) { for (var t = [], i = r.length - 1; i >= 0; i--) { var o = this.fromClassDescriptor(e), n = this.toClassDescriptor((0, r[i])(o) || o); if (void 0 !== n.finisher && t.push(n.finisher), void 0 !== n.elements) { e = n.elements; for (var s = 0; s < e.length - 1; s++) for (var a = s + 1; a < e.length; a++) if (e[s].key === e[a].key && e[s].placement === e[a].placement) throw new TypeError("Duplicated element (" + e[s].key + ")"); } } return { elements: e, finishers: t }; }, fromElementDescriptor: function (e) { var r = { kind: e.kind, key: e.key, placement: e.placement, descriptor: e.descriptor }; return Object.defineProperty(r, Symbol.toStringTag, { value: "Descriptor", configurable: !0 }), "field" === e.kind && (r.initializer = e.initializer), r; }, toElementDescriptors: function (e) { if (void 0 !== e) return _toArray(e).map(function (e) { var r = this.toElementDescriptor(e); return this.disallowProperty(e, "finisher", "An element descriptor"), this.disallowProperty(e, "extras", "An element descriptor"), r; }, this); }, toElementDescriptor: function (e) { var r = e.kind + ""; if ("method" !== r && "field" !== r) throw new TypeError('An element descriptor\'s .kind property must be either "method" or "field", but a decorator created an element descriptor with .kind "' + r + '"'); var t = _toPropertyKey(e.key), i = e.placement + ""; if ("static" !== i && "prototype" !== i && "own" !== i) throw new TypeError('An element descriptor\'s .placement property must be one of "static", "prototype" or "own", but a decorator created an element descriptor with .placement "' + i + '"'); var o = e.descriptor; this.disallowProperty(e, "elements", "An element descriptor"); var n = { kind: r, key: t, placement: i, descriptor: Object.assign({}, o) }; return "field" !== r ? this.disallowProperty(e, "initializer", "A method descriptor") : (this.disallowProperty(o, "get", "The property descriptor of a field descriptor"), this.disallowProperty(o, "set", "The property descriptor of a field descriptor"), this.disallowProperty(o, "value", "The property descriptor of a field descriptor"), n.initializer = e.initializer), n; }, toElementFinisherExtras: function (e) { return { element: this.toElementDescriptor(e), finisher: _optionalCallableProperty(e, "finisher"), extras: this.toElementDescriptors(e.extras) }; }, fromClassDescriptor: function (e) { var r = { kind: "class", elements: e.map(this.fromElementDescriptor, this) }; return Object.defineProperty(r, Symbol.toStringTag, { value: "Descriptor", configurable: !0 }), r; }, toClassDescriptor: function (e) { var r = e.kind + ""; if ("class" !== r) throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator created a class descriptor with .kind "' + r + '"'); this.disallowProperty(e, "key", "A class descriptor"), this.disallowProperty(e, "placement", "A class descriptor"), this.disallowProperty(e, "descriptor", "A class descriptor"), this.disallowProperty(e, "initializer", "A class descriptor"), this.disallowProperty(e, "extras", "A class descriptor"); var t = _optionalCallableProperty(e, "finisher"); return { elements: this.toElementDescriptors(e.elements), finisher: t }; }, runClassFinishers: function (e, r) { for (var t = 0; t < r.length; t++) { var i = (0, r[t])(e); if (void 0 !== i) { if ("function" != typeof i) throw new TypeError("Finishers must return a constructor."); e = i; } } return e; }, disallowProperty: function (e, r, t) { if (void 0 !== e[r]) throw new TypeError(t + " can't have a ." + r + " property."); } }; return e; } function _createElementDescriptor(e) { var r, t = _toPropertyKey(e.key); "method" === e.kind ? r = { value: e.value, writable: !0, configurable: !0, enumerable: !1 } : "get" === e.kind ? r = { get: e.value, configurable: !0, enumerable: !1 } : "set" === e.kind ? r = { set: e.value, configurable: !0, enumerable: !1 } : "field" === e.kind && (r = { configurable: !0, writable: !0, enumerable: !0 }); var i = { kind: "field" === e.kind ? "field" : "method", key: t, placement: e.static ? "static" : "field" === e.kind ? "own" : "prototype", descriptor: r }; return e.decorators && (i.decorators = e.decorators), "field" === e.kind && (i.initializer = e.value), i; } function _coalesceGetterSetter(e, r) { void 0 !== e.descriptor.get ? r.descriptor.get = e.descriptor.get : r.descriptor.set = e.descriptor.set; } function _coalesceClassElements(e) { for (var r = [], isSameElement = function (e) { return "method" === e.kind && e.key === o.key && e.placement === o.placement; }, t = 0; t < e.length; t++) { var i, o = e[t]; if ("method" === o.kind && (i = r.find(isSameElement))) { if (_isDataDescriptor(o.descriptor) || _isDataDescriptor(i.descriptor)) { if (_hasDecorators(o) || _hasDecorators(i)) throw new ReferenceError("Duplicated methods (" + o.key + ") can't be decorated."); i.descriptor = o.descriptor; } else { if (_hasDecorators(o)) { if (_hasDecorators(i)) throw new ReferenceError("Decorators can't be placed on different accessors with for the same property (" + o.key + ")."); i.decorators = o.decorators; } _coalesceGetterSetter(o, i); } } else r.push(o); } return r; } function _hasDecorators(e) { return e.decorators && e.decorators.length; } function _isDataDescriptor(e) { return void 0 !== e && !(void 0 === e.value && void 0 === e.writable); } function _optionalCallableProperty(e, r) { var t = e[r]; if (void 0 !== t && "function" != typeof t) throw new TypeError("Expected '" + r + "' to be a function"); return t; } function _defaults(e, r) { for (var t = Object.getOwnPropertyNames(r), o = 0; o < t.length; o++) { var n = t[o], a = Object.getOwnPropertyDescriptor(r, n); a && a.configurable && void 0 === e[n] && Object.defineProperty(e, n, a); } return e; } function _defineAccessor(e, r, n, t) { var c = { configurable: !0, enumerable: !0 }; return c[e] = t, Object.defineProperty(r, n, c); } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); } function _get() { return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) { var p = _superPropBase(e, t); if (p) { var n = Object.getOwnPropertyDescriptor(p, t); return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value; } }, _get.apply(null, arguments); } function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } function _identity(t) { return t; } function _importDeferProxy(e) { var t = null, constValue = function (e) { return function () { return e; }; }, proxy = function (r) { return function (n, o, f) { return null === t && (t = e()), r(t, o, f); }; }; return new Proxy({}, { defineProperty: constValue(!1), deleteProperty: constValue(!1), get: proxy(Reflect.get), getOwnPropertyDescriptor: proxy(Reflect.getOwnPropertyDescriptor), getPrototypeOf: constValue(null), isExtensible: constValue(!1), has: proxy(Reflect.has), ownKeys: proxy(Reflect.ownKeys), preventExtensions: constValue(!0), set: constValue(!1), setPrototypeOf: constValue(!1) }); } function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); } function _initializerDefineProperty(e, i, r, l) { r && Object.defineProperty(e, i, { enumerable: r.enumerable, configurable: r.configurable, writable: r.writable, value: r.initializer ? r.initializer.call(l) : void 0 }); } function _initializerWarningHelper(r, e) { throw Error("Decorating class property failed. Please ensure that transform-class-properties is enabled and runs after the decorators transform."); } function _instanceof(n, e) { return null != e && "undefined" != typeof Symbol && e[Symbol.hasInstance] ? !!e[Symbol.hasInstance](n) : n instanceof e; } function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function () { return !!t; })(); } function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } var REACT_ELEMENT_TYPE; function _jsx(e, r, E, l) { REACT_ELEMENT_TYPE || (REACT_ELEMENT_TYPE = "function" == typeof Symbol && Symbol.for && Symbol.for("react.element") || 60103); var o = e && e.defaultProps, n = arguments.length - 3; if (r || 0 === n || (r = { children: void 0 }), 1 === n) r.children = l;else if (n > 1) { for (var t = Array(n), f = 0; f < n; f++) t[f] = arguments[f + 3]; r.children = t; } if (r && o) for (var i in o) void 0 === r[i] && (r[i] = o[i]);else r || (r = o || {}); return { $$typeof: REACT_ELEMENT_TYPE, type: e, key: void 0 === E ? null : "" + E, ref: null, props: r, _owner: null }; } function _maybeArrayLike(r, a, e) { if (a && !Array.isArray(a) && "number" == typeof a.length) { var y = a.length; return _arrayLikeToArray(a, void 0 !== e && e < y ? e : y); } return r(a, e); } function _newArrowCheck(n, r) { if (n !== r) throw new TypeError("Cannot instantiate an arrow function"); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _nullishReceiverError(r) { throw new TypeError("Cannot set property of null or undefined."); } function _objectDestructuringEmpty(t) { if (null == t) throw new TypeError("Cannot destructure " + t); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; } function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; } function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } function _readOnlyError(r) { throw new TypeError('"' + r + '" is read-only'); } function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function () { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function (t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function (t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(typeof e + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function (e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function () { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function (e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function (t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function (t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function (t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function (t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function (e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } function set(e, r, t, o) { return set = "undefined" != typeof Reflect && Reflect.set ? Reflect.set : function (e, r, t, o) { var f, i = _superPropBase(e, r); if (i) { if ((f = Object.getOwnPropertyDescriptor(i, r)).set) return f.set.call(o, t), !0; if (!f.writable) return !1; } if (f = Object.getOwnPropertyDescriptor(o, r)) { if (!f.writable) return !1; f.value = t, Object.defineProperty(o, r, f); } else _defineProperty(o, r, t); return !0; }, set(e, r, t, o); } function _set(e, r, t, o, f) { if (!set(e, r, t, o || e) && f) throw new TypeError("failed to set property"); return t; } function _setFunctionName(e, t, n) { "symbol" == typeof t && (t = (t = t.description) ? "[" + t + "]" : ""); try { Object.defineProperty(e, "name", { configurable: !0, value: n ? n + " " + t : t }); } catch (e) {} return e; } function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } function _skipFirstGeneratorNext(t) { return function () { var r = t.apply(this, arguments); return r.next(), r; }; } function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } function _superPropBase(t, o) { for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t));); return t; } function _superPropGet(t, e, r, o) { var p = _get(_getPrototypeOf(1 & o ? t.prototype : t), e, r); return 2 & o ? function (t) { return p.apply(r, t); } : p; } function _superPropSet(t, e, o, r, p, f) { return _set(_getPrototypeOf(f ? t.prototype : t), e, o, r, p); } function _taggedTemplateLiteral(e, t) { return t || (t = e.slice(0)), Object.freeze(Object.defineProperties(e, { raw: { value: Object.freeze(t) } })); } function _taggedTemplateLiteralLoose(e, t) { return t || (t = e.slice(0)), e.raw = t, e; } function _tdz(e) { throw new ReferenceError(e + " is not defined - temporal dead zone"); } function _temporalRef(r, e) { return r === _temporalUndefined ? _tdz(e) : r; } function _temporalUndefined() {} function _toArray(r) { return _arrayWithHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableRest(); } function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } function _toSetter(t, e, n) { e || (e = []); var r = e.length++; return Object.defineProperty({}, "_", { set: function (o) { e[r] = o, t.apply(n, e); } }); } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _usingCtx() { var r = "function" == typeof SuppressedError ? SuppressedError : function (r, e) { var n = Error(); return n.name = "SuppressedError", n.error = r, n.suppressed = e, n; }, e = {}, n = []; function using(r, e) { if (null != e) { if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined."); if (r) var o = e[Symbol.asyncDispose || Symbol.for("Symbol.asyncDispose")]; if (void 0 === o && (o = e[Symbol.dispose || Symbol.for("Symbol.dispose")], r)) var t = o; if ("function" != typeof o) throw new TypeError("Object is not disposable."); t && (o = function () { try { t.call(e); } catch (r) { return Promise.reject(r); } }), n.push({ v: e, d: o, a: r }); } else r && n.push({ d: e, a: r }); return e; } return { e: e, u: using.bind(null, !1), a: using.bind(null, !0), d: function () { var o, t = this.e, s = 0; function next() { for (; o = n.pop();) try { if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next); if (o.d) { var r = o.d.call(o.v); if (o.a) return s |= 2, Promise.resolve(r).then(next, err); } else s |= 1; } catch (r) { return err(r); } if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve(); if (t !== e) throw t; } function err(n) { return t = t !== e ? new r(n, t) : n, next(); } return next(); } }; } function _wrapAsyncGenerator(e) { return function () { return new AsyncGenerator(e.apply(this, arguments)); }; } function AsyncGenerator(e) { var r, t; function resume(r, t) { try { var n = e[r](t), o = n.value, u = o instanceof _OverloadYield; Promise.resolve(u ? o.v : o).then(function (t) { if (u) { var i = "return" === r ? "return" : "next"; if (!o.k || t.done) return resume(i, t); t = e[i](t).value; } settle(n.done ? "return" : "normal", t); }, function (e) { resume("throw", e); }); } catch (e) { settle("throw", e); } } function settle(e, n) { switch (e) { case "return": r.resolve({ value: n, done: !0 }); break; case "throw": r.reject(n); break; default: r.resolve({ value: n, done: !1 }); } (r = r.next) ? resume(r.key, r.arg) : t = null; } this._invoke = function (e, n) { return new Promise(function (o, u) { var i = { key: e, arg: n, resolve: o, reject: u, next: null }; t ? t = t.next = i : (r = t = i, resume(e, n)); }); }, "function" != typeof e.return && (this.return = void 0); } AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function () { return this; }, AsyncGenerator.prototype.next = function (e) { return this._invoke("next", e); }, AsyncGenerator.prototype.throw = function (e) { return this._invoke("throw", e); }, AsyncGenerator.prototype.return = function (e) { return this._invoke("return", e); }; function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function (t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } function _wrapRegExp() { _wrapRegExp = function (e, r) { return new BabelRegExp(e, void 0, r); }; var e = RegExp.prototype, r = new WeakMap(); function BabelRegExp(e, t, p) { var o = RegExp(e, t); return r.set(o, p || r.get(e)), _setPrototypeOf(o, BabelRegExp.prototype); } function buildGroups(e, t) { var p = r.get(t); return Object.keys(p).reduce(function (r, t) { var o = p[t]; if ("number" == typeof o) r[t] = e[o];else { for (var i = 0; void 0 === e[o[i]] && i + 1 < o.length;) i++; r[t] = e[o[i]]; } return r; }, Object.create(null)); } return _inherits(BabelRegExp, RegExp), BabelRegExp.prototype.exec = function (r) { var t = e.exec.call(this, r); if (t) { t.groups = buildGroups(t, this); var p = t.indices; p && (p.groups = buildGroups(p, this)); } return t; }, BabelRegExp.prototype[Symbol.replace] = function (t, p) { if ("string" == typeof p) { var o = r.get(this); return e[Symbol.replace].call(this, t, p.replace(/\$<([^>]+)>/g, function (e, r) { var t = o[r]; return "$" + (Array.isArray(t) ? t.join("$") : t); })); } if ("function" == typeof p) { var i = this; return e[Symbol.replace].call(this, t, function () { var e = arguments; return "object" != typeof e[e.length - 1] && (e = [].slice.call(e)).push(buildGroups(e, i)), p.apply(this, e); }); } return e[Symbol.replace].call(this, t, p); }, _wrapRegExp.apply(this, arguments); } function _writeOnlyError(r) { throw new TypeError('"' + r + '" is write-only'); } function _AwaitValue(t) { this.wrapped = t; } function old_createMetadataMethodsForProperty(e, t, a, r) { return { getMetadata: function (o) { old_assertNotFinished(r, "getMetadata"), old_assertMetadataKey(o); var i = e[o]; if (void 0 !== i) if (1 === t) { var n = i.public; if (void 0 !== n) return n[a]; } else if (2 === t) { var l = i.private; if (void 0 !== l) return l.get(a); } else if (Object.hasOwnProperty.call(i, "constructor")) return i.constructor; }, setMetadata: function (o, i) { old_assertNotFinished(r, "setMetadata"), old_assertMetadataKey(o); var n = e[o]; if (void 0 === n && (n = e[o] = {}), 1 === t) { var l = n.public; void 0 === l && (l = n.public = {}), l[a] = i; } else if (2 === t) { var s = n.priv; void 0 === s && (s = n.private = new Map()), s.set(a, i); } else n.constructor = i; } }; } function old_convertMetadataMapToFinal(e, t) { var a = e[Symbol.metadata || Symbol.for("Symbol.metadata")], r = Object.getOwnPropertySymbols(t); if (0 !== r.length) { for (var o = 0; o < r.length; o++) { var i = r[o], n = t[i], l = a ? a[i] : null, s = n.public, c = l ? l.public : null; s && c && Object.setPrototypeOf(s, c); var d = n.private; if (d) { var u = Array.from(d.values()), f = l ? l.private : null; f && (u = u.concat(f)), n.private = u; } l && Object.setPrototypeOf(n, l); } a && Object.setPrototypeOf(t, a), e[Symbol.metadata || Symbol.for("Symbol.metadata")] = t; } } function old_createAddInitializerMethod(e, t) { return function (a) { old_assertNotFinished(t, "addInitializer"), old_assertCallable(a, "An initializer"), e.push(a); }; } function old_memberDec(e, t, a, r, o, i, n, l, s) { var c; switch (i) { case 1: c = "accessor"; break; case 2: c = "method"; break; case 3: c = "getter"; break; case 4: c = "setter"; break; default: c = "field"; } var d, u, f = { kind: c, name: l ? "#" + t : _toPropertyKey(t), isStatic: n, isPrivate: l }, p = { v: !1 }; if (0 !== i && (f.addInitializer = old_createAddInitializerMethod(o, p)), l) { d = 2, u = Symbol(t); var v = {}; 0 === i ? (v.get = a.get, v.set = a.set) : 2 === i ? v.get = function () { return a.value; } : (1 !== i && 3 !== i || (v.get = function () { return a.get.call(this); }), 1 !== i && 4 !== i || (v.set = function (e) { a.set.call(this, e); })), f.access = v; } else d = 1, u = t; try { return e(s, Object.assign(f, old_createMetadataMethodsForProperty(r, d, u, p))); } finally { p.v = !0; } } function old_assertNotFinished(e, t) { if (e.v) throw Error("attempted to call " + t + " after decoration was finished"); } function old_assertMetadataKey(e) { if ("symbol" != typeof e) throw new TypeError("Metadata keys must be symbols, received: " + e); } function old_assertCallable(e, t) { if ("function" != typeof e) throw new TypeError(t + " must be a function"); } function old_assertValidReturnValue(e, t) { var a = typeof t; if (1 === e) { if ("object" !== a || null === t) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); void 0 !== t.get && old_assertCallable(t.get, "accessor.get"), void 0 !== t.set && old_assertCallable(t.set, "accessor.set"), void 0 !== t.init && old_assertCallable(t.init, "accessor.init"), void 0 !== t.initializer && old_assertCallable(t.initializer, "accessor.initializer"); } else if ("function" !== a) throw new TypeError((0 === e ? "field" : 10 === e ? "class" : "method") + " decorators must return a function or void 0"); } function old_getInit(e) { var t; return null == (t = e.init) && (t = e.initializer) && void 0 !== console && console.warn(".initializer has been renamed to .init as of March 2022"), t; } function old_applyMemberDec(e, t, a, r, o, i, n, l, s) { var c, d, u, f, p, v, y, h = a[0]; if (n ? (0 === o || 1 === o ? (c = { get: a[3], set: a[4] }, u = "get") : 3 === o ? (c = { get: a[3] }, u = "get") : 4 === o ? (c = { set: a[3] }, u = "set") : c = { value: a[3] }, 0 !== o && (1 === o && _setFunctionName(a[4], "#" + r, "set"), _setFunctionName(a[3], "#" + r, u))) : 0 !== o && (c = Object.getOwnPropertyDescriptor(t, r)), 1 === o ? f = { get: c.get, set: c.set } : 2 === o ? f = c.value : 3 === o ? f = c.get : 4 === o && (f = c.set), "function" == typeof h) void 0 !== (p = old_memberDec(h, r, c, l, s, o, i, n, f)) && (old_assertValidReturnValue(o, p), 0 === o ? d = p : 1 === o ? (d = old_getInit(p), v = p.get || f.get, y = p.set || f.set, f = { get: v, set: y }) : f = p);else for (var m = h.length - 1; m >= 0; m--) { var b; void 0 !== (p = old_memberDec(h[m], r, c, l, s, o, i, n, f)) && (old_assertValidReturnValue(o, p), 0 === o ? b = p : 1 === o ? (b = old_getInit(p), v = p.get || f.get, y = p.set || f.set, f = { get: v, set: y }) : f = p, void 0 !== b && (void 0 === d ? d = b : "function" == typeof d ? d = [d, b] : d.push(b))); } if (0 === o || 1 === o) { if (void 0 === d) d = function (e, t) { return t; };else if ("function" != typeof d) { var g = d; d = function (e, t) { for (var a = t, r = 0; r < g.length; r++) a = g[r].call(e, a); return a; }; } else { var _ = d; d = function (e, t) { return _.call(e, t); }; } e.push(d); } 0 !== o && (1 === o ? (c.get = f.get, c.set = f.set) : 2 === o ? c.value = f : 3 === o ? c.get = f : 4 === o && (c.set = f), n ? 1 === o ? (e.push(function (e, t) { return f.get.call(e, t); }), e.push(function (e, t) { return f.set.call(e, t); })) : 2 === o ? e.push(f) : e.push(function (e, t) { return f.call(e, t); }) : Object.defineProperty(t, r, c)); } function old_applyMemberDecs(e, t, a, r, o) { for (var i, n, l = new Map(), s = new Map(), c = 0; c < o.length; c++) { var d = o[c]; if (Array.isArray(d)) { var u, f, p, v = d[1], y = d[2], h = d.length > 3, m = v >= 5; if (m ? (u = t, f = r, 0 != (v -= 5) && (p = n = n || [])) : (u = t.prototype, f = a, 0 !== v && (p = i = i || [])), 0 !== v && !h) { var b = m ? s : l, g = b.get(y) || 0; if (!0 === g || 3 === g && 4 !== v || 4 === g && 3 !== v) throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + y); !g && v > 2 ? b.set(y, v) : b.set(y, !0); } old_applyMemberDec(e, u, d, y, v, m, h, f, p); } } old_pushInitializers(e, i), old_pushInitializers(e, n); } function old_pushInitializers(e, t) { t && e.push(function (e) { for (var a = 0; a < t.length; a++) t[a].call(e); return e; }); } function old_applyClassDecs(e, t, a, r) { if (r.length > 0) { for (var o = [], i = t, n = t.name, l = r.length - 1; l >= 0; l--) { var s = { v: !1 }; try { var c = Object.assign({ kind: "class", name: n, addInitializer: old_createAddInitializerMethod(o, s) }, old_createMetadataMethodsForProperty(a, 0, n, s)), d = r[l](i, c); } finally { s.v = !0; } void 0 !== d && (old_assertValidReturnValue(10, d), i = d); } e.push(i, function () { for (var e = 0; e < o.length; e++) o[e].call(i); }); } } function _applyDecs(e, t, a) { var r = [], o = {}, i = {}; return old_applyMemberDecs(r, e, i, o, t), old_convertMetadataMapToFinal(e.prototype, i), old_applyClassDecs(r, e, o, a), old_convertMetadataMapToFinal(e, o), r; } function applyDecs2203Factory() { function createAddInitializerMethod(e, t) { return function (r) { !function (e, t) { if (e.v) throw Error("attempted to call addInitializer after decoration was finished"); }(t), assertCallable(r, "An initializer"), e.push(r); }; } function memberDec(e, t, r, a, n, i, s, o) { var c; switch (n) { case 1: c = "accessor"; break; case 2: c = "method"; break; case 3: c = "getter"; break; case 4: c = "setter"; break; default: c = "field"; } var l, u, f = { kind: c, name: s ? "#" + t : t, static: i, private: s }, p = { v: !1 }; 0 !== n && (f.addInitializer = createAddInitializerMethod(a, p)), 0 === n ? s ? (l = r.get, u = r.set) : (l = function () { return this[t]; }, u = function (e) { this[t] = e; }) : 2 === n ? l = function () { return r.value; } : (1 !== n && 3 !== n || (l = function () { return r.get.call(this); }), 1 !== n && 4 !== n || (u = function (e) { r.set.call(this, e); })), f.access = l && u ? { get: l, set: u } : l ? { get: l } : { set: u }; try { return e(o, f); } finally { p.v = !0; } } function assertCallable(e, t) { if ("function" != typeof e) throw new TypeError(t + " must be a function"); } function assertValidReturnValue(e, t) { var r = typeof t; if (1 === e) { if ("object" !== r || null === t) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); void 0 !== t.get && assertCallable(t.get, "accessor.get"), void 0 !== t.set && assertCallable(t.set, "accessor.set"), void 0 !== t.init && assertCallable(t.init, "accessor.init"); } else if ("function" !== r) throw new TypeError((0 === e ? "field" : 10 === e ? "class" : "method") + " decorators must return a function or void 0"); } function applyMemberDec(e, t, r, a, n, i, s, o) { var c, l, u, f, p, d, h = r[0]; if (s ? c = 0 === n || 1 === n ? { get: r[3], set: r[4] } : 3 === n ? { get: r[3] } : 4 === n ? { set: r[3] } : { value: r[3] } : 0 !== n && (c = Object.getOwnPropertyDescriptor(t, a)), 1 === n ? u = { get: c.get, set: c.set } : 2 === n ? u = c.value : 3 === n ? u = c.get : 4 === n && (u = c.set), "function" == typeof h) void 0 !== (f = memberDec(h, a, c, o, n, i, s, u)) && (assertValidReturnValue(n, f), 0 === n ? l = f : 1 === n ? (l = f.init, p = f.get || u.get, d = f.set || u.set, u = { get: p, set: d }) : u = f);else for (var v = h.length - 1; v >= 0; v--) { var g; void 0 !== (f = memberDec(h[v], a, c, o, n, i, s, u)) && (assertValidReturnValue(n, f), 0 === n ? g = f : 1 === n ? (g = f.init, p = f.get || u.get, d = f.set || u.set, u = { get: p, set: d }) : u = f, void 0 !== g && (void 0 === l ? l = g : "function" == typeof l ? l = [l, g] : l.push(g))); } if (0 === n || 1 === n) { if (void 0 === l) l = function (e, t) { return t; };else if ("function" != typeof l) { var y = l; l = function (e, t) { for (var r = t, a = 0; a < y.length; a++) r = y[a].call(e, r); return r; }; } else { var m = l; l = function (e, t) { return m.call(e, t); }; } e.push(l); } 0 !== n && (1 === n ? (c.get = u.get, c.set = u.set) : 2 === n ? c.value = u : 3 === n ? c.get = u : 4 === n && (c.set = u), s ? 1 === n ? (e.push(function (e, t) { return u.get.call(e, t); }), e.push(function (e, t) { return u.set.call(e, t); })) : 2 === n ? e.push(u) : e.push(function (e, t) { return u.call(e, t); }) : Object.defineProperty(t, a, c)); } function pushInitializers(e, t) { t && e.push(function (e) { for (var r = 0; r < t.length; r++) t[r].call(e); return e; }); } return function (e, t, r) { var a = []; return function (e, t, r) { for (var a, n, i = new Map(), s = new Map(), o = 0; o < r.length; o++) { var c = r[o]; if (Array.isArray(c)) { var l, u, f = c[1], p = c[2], d = c.length > 3, h = f >= 5; if (h ? (l = t, 0 != (f -= 5) && (u = n = n || [])) : (l = t.prototype, 0 !== f && (u = a = a || [])), 0 !== f && !d) { var v = h ? s : i, g = v.get(p) || 0; if (!0 === g || 3 === g && 4 !== f || 4 === g && 3 !== f) throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + p); !g && f > 2 ? v.set(p, f) : v.set(p, !0); } applyMemberDec(e, l, c, p, f, h, d, u); } } pushInitializers(e, a), pushInitializers(e, n); }(a, e, t), function (e, t, r) { if (r.length > 0) { for (var a = [], n = t, i = t.name, s = r.length - 1; s >= 0; s--) { var o = { v: !1 }; try { var c = r[s](n, { kind: "class", name: i, addInitializer: createAddInitializerMethod(a, o) }); } finally { o.v = !0; } void 0 !== c && (assertValidReturnValue(10, c), n = c); } e.push(n, function () { for (var e = 0; e < a.length; e++) a[e].call(n); }); } }(a, e, r), a; }; } var applyDecs2203Impl; function _applyDecs2203(e, t, r) { return (applyDecs2203Impl = applyDecs2203Impl || applyDecs2203Factory())(e, t, r); } function applyDecs2203RFactory() { function createAddInitializerMethod(e, t) { return function (r) { !function (e, t) { if (e.v) throw Error("attempted to call addInitializer after decoration was finished"); }(t), assertCallable(r, "An initializer"), e.push(r); }; } function memberDec(e, t, r, n, a, i, o, s) { var c; switch (a) { case 1: c = "accessor"; break; case 2: c = "method"; break; case 3: c = "getter"; break; case 4: c = "setter"; break; default: c = "field"; } var l, u, f = { kind: c, name: o ? "#" + t : _toPropertyKey(t), static: i, private: o }, p = { v: !1 }; 0 !== a && (f.addInitializer = createAddInitializerMethod(n, p)), 0 === a ? o ? (l = r.get, u = r.set) : (l = function () { return this[t]; }, u = function (e) { this[t] = e; }) : 2 === a ? l = function () { return r.value; } : (1 !== a && 3 !== a || (l = function () { return r.get.call(this); }), 1 !== a && 4 !== a || (u = function (e) { r.set.call(this, e); })), f.access = l && u ? { get: l, set: u } : l ? { get: l } : { set: u }; try { return e(s, f); } finally { p.v = !0; } } function assertCallable(e, t) { if ("function" != typeof e) throw new TypeError(t + " must be a function"); } function assertValidReturnValue(e, t) { var r = typeof t; if (1 === e) { if ("object" !== r || null === t) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); void 0 !== t.get && assertCallable(t.get, "accessor.get"), void 0 !== t.set && assertCallable(t.set, "accessor.set"), void 0 !== t.init && assertCallable(t.init, "accessor.init"); } else if ("function" !== r) throw new TypeError((0 === e ? "field" : 10 === e ? "class" : "method") + " decorators must return a function or void 0"); } function applyMemberDec(e, t, r, n, a, i, o, s) { var c, l, u, f, p, d, h, v = r[0]; if (o ? (0 === a || 1 === a ? (c = { get: r[3], set: r[4] }, u = "get") : 3 === a ? (c = { get: r[3] }, u = "get") : 4 === a ? (c = { set: r[3] }, u = "set") : c = { value: r[3] }, 0 !== a && (1 === a && _setFunctionName(r[4], "#" + n, "set"), _setFunctionName(r[3], "#" + n, u))) : 0 !== a && (c = Object.getOwnPropertyDescriptor(t, n)), 1 === a ? f = { get: c.get, set: c.set } : 2 === a ? f = c.value : 3 === a ? f = c.get : 4 === a && (f = c.set), "function" == typeof v) void 0 !== (p = memberDec(v, n, c, s, a, i, o, f)) && (assertValidReturnValue(a, p), 0 === a ? l = p : 1 === a ? (l = p.init, d = p.get || f.get, h = p.set || f.set, f = { get: d, set: h }) : f = p);else for (var g = v.length - 1; g >= 0; g--) { var y; void 0 !== (p = memberDec(v[g], n, c, s, a, i, o, f)) && (assertValidReturnValue(a, p), 0 === a ? y = p : 1 === a ? (y = p.init, d = p.get || f.get, h = p.set || f.set, f = { get: d, set: h }) : f = p, void 0 !== y && (void 0 === l ? l = y : "function" == typeof l ? l = [l, y] : l.push(y))); } if (0 === a || 1 === a) { if (void 0 === l) l = function (e, t) { return t; };else if ("function" != typeof l) { var m = l; l = function (e, t) { for (var r = t, n = 0; n < m.length; n++) r = m[n].call(e, r); return r; }; } else { var b = l; l = function (e, t) { return b.call(e, t); }; } e.push(l); } 0 !== a && (1 === a ? (c.get = f.get, c.set = f.set) : 2 === a ? c.value = f : 3 === a ? c.get = f : 4 === a && (c.set = f), o ? 1 === a ? (e.push(function (e, t) { return f.get.call(e, t); }), e.push(function (e, t) { return f.set.call(e, t); })) : 2 === a ? e.push(f) : e.push(function (e, t) { return f.call(e, t); }) : Object.defineProperty(t, n, c)); } function applyMemberDecs(e, t) { for (var r, n, a = [], i = new Map(), o = new Map(), s = 0; s < t.length; s++) { var c = t[s]; if (Array.isArray(c)) { var l, u, f = c[1], p = c[2], d = c.length > 3, h = f >= 5; if (h ? (l = e, 0 != (f -= 5) && (u = n = n || [])) : (l = e.prototype, 0 !== f && (u = r = r || [])), 0 !== f && !d) { var v = h ? o : i, g = v.get(p) || 0; if (!0 === g || 3 === g && 4 !== f || 4 === g && 3 !== f) throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + p); !g && f > 2 ? v.set(p, f) : v.set(p, !0); } applyMemberDec(a, l, c, p, f, h, d, u); } } return pushInitializers(a, r), pushInitializers(a, n), a; } function pushInitializers(e, t) { t && e.push(function (e) { for (var r = 0; r < t.length; r++) t[r].call(e); return e; }); } return function (e, t, r) { return { e: applyMemberDecs(e, t), get c() { return function (e, t) { if (t.length > 0) { for (var r = [], n = e, a = e.name, i = t.length - 1; i >= 0; i--) { var o = { v: !1 }; try { var s = t[i](n, { kind: "class", name: a, addInitializer: createAddInitializerMethod(r, o) }); } finally { o.v = !0; } void 0 !== s && (assertValidReturnValue(10, s), n = s); } return [n, function () { for (var e = 0; e < r.length; e++) r[e].call(n); }]; } }(e, r); } }; }; } function _applyDecs2203R(e, t, r) { return (_applyDecs2203R = applyDecs2203RFactory())(e, t, r); } function applyDecs2301Factory() { function createAddInitializerMethod(e, t) { return function (r) { !function (e, t) { if (e.v) throw Error("attempted to call addInitializer after decoration was finished"); }(t), assertCallable(r, "An initializer"), e.push(r); }; } function assertInstanceIfPrivate(e, t) { if (!e(t)) throw new TypeError("Attempted to access private element on non-instance"); } function memberDec(e, t, r, n, a, i, s, o, c) { var u; switch (a) { case 1: u = "accessor"; break; case 2: u = "method"; break; case 3: u = "getter"; break; case 4: u = "setter"; break; default: u = "field"; } var l, f, p = { kind: u, name: s ? "#" + t : _toPropertyKey(t), static: i, private: s }, d = { v: !1 }; if (0 !== a && (p.addInitializer = createAddInitializerMethod(n, d)), s || 0 !== a && 2 !== a) { if (2 === a) l = function (e) { return assertInstanceIfPrivate(c, e), r.value; };else { var h = 0 === a || 1 === a; (h || 3 === a) && (l = s ? function (e) { return assertInstanceIfPrivate(c, e), r.get.call(e); } : function (e) { return r.get.call(e); }), (h || 4 === a) && (f = s ? function (e, t) { assertInstanceIfPrivate(c, e), r.set.call(e, t); } : function (e, t) { r.set.call(e, t); }); } } else l = function (e) { return e[t]; }, 0 === a && (f = function (e, r) { e[t] = r; }); var v = s ? c.bind() : function (e) { return t in e; }; p.access = l && f ? { get: l, set: f, has: v } : l ? { get: l, has: v } : { set: f, has: v }; try { return e(o, p); } finally { d.v = !0; } } function assertCallable(e, t) { if ("function" != typeof e) throw new TypeError(t + " must be a function"); } function assertValidReturnValue(e, t) { var r = typeof t; if (1 === e) { if ("object" !== r || null === t) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); void 0 !== t.get && assertCallable(t.get, "accessor.get"), void 0 !== t.set && assertCallable(t.set, "accessor.set"), void 0 !== t.init && assertCallable(t.init, "accessor.init"); } else if ("function" !== r) throw new TypeError((0 === e ? "field" : 10 === e ? "class" : "method") + " decorators must return a function or void 0"); } function curryThis2(e) { return function (t) { e(this, t); }; } function applyMemberDec(e, t, r, n, a, i, s, o, c) { var u, l, f, p, d, h, v, y, g = r[0]; if (s ? (0 === a || 1 === a ? (u = { get: (d = r[3], function () { return d(this); }), set: curryThis2(r[4]) }, f = "get") : 3 === a ? (u = { get: r[3] }, f = "get") : 4 === a ? (u = { set: r[3] }, f = "set") : u = { value: r[3] }, 0 !== a && (1 === a && _setFunctionName(u.set, "#" + n, "set"), _setFunctionName(u[f || "value"], "#" + n, f))) : 0 !== a && (u = Object.getOwnPropertyDescriptor(t, n)), 1 === a ? p = { get: u.get, set: u.set } : 2 === a ? p = u.value : 3 === a ? p = u.get : 4 === a && (p = u.set), "function" == typeof g) void 0 !== (h = memberDec(g, n, u, o, a, i, s, p, c)) && (assertValidReturnValue(a, h), 0 === a ? l = h : 1 === a ? (l = h.init, v = h.get || p.get, y = h.set || p.set, p = { get: v, set: y }) : p = h);else for (var m = g.length - 1; m >= 0; m--) { var b; void 0 !== (h = memberDec(g[m], n, u, o, a, i, s, p, c)) && (assertValidReturnValue(a, h), 0 === a ? b = h : 1 === a ? (b = h.init, v = h.get || p.get, y = h.set || p.set, p = { get: v, set: y }) : p = h, void 0 !== b && (void 0 === l ? l = b : "function" == typeof l ? l = [l, b] : l.push(b))); } if (0 === a || 1 === a) { if (void 0 === l) l = function (e, t) { return t; };else if ("function" != typeof l) { var I = l; l = function (e, t) { for (var r = t, n = 0; n < I.length; n++) r = I[n].call(e, r); return r; }; } else { var w = l; l = function (e, t) { return w.call(e, t); }; } e.push(l); } 0 !== a && (1 === a ? (u.get = p.get, u.set = p.set) : 2 === a ? u.value = p : 3 === a ? u.get = p : 4 === a && (u.set = p), s ? 1 === a ? (e.push(function (e, t) { return p.get.call(e, t); }), e.push(function (e, t) { return p.set.call(e, t); })) : 2 === a ? e.push(p) : e.push(function (e, t) { return p.call(e, t); }) : Object.defineProperty(t, n, u)); } function applyMemberDecs(e, t, r) { for (var n, a, i, s = [], o = new Map(), c = new Map(), u = 0; u < t.length; u++) { var l = t[u]; if (Array.isArray(l)) { var f, p, d = l[1], h = l[2], v = l.length > 3, y = d >= 5, g = r; if (y ? (f = e, 0 != (d -= 5) && (p = a = a || []), v && !i && (i = function (t) { return _checkInRHS(t) === e; }), g = i) : (f = e.prototype, 0 !== d && (p = n = n || [])), 0 !== d && !v) { var m = y ? c : o, b = m.get(h) || 0; if (!0 === b || 3 === b && 4 !== d || 4 === b && 3 !== d) throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + h); !b && d > 2 ? m.set(h, d) : m.set(h, !0); } applyMemberDec(s, f, l, h, d, y, v, p, g); } } return pushInitializers(s, n), pushInitializers(s, a), s; } function pushInitializers(e, t) { t && e.push(function (e) { for (var r = 0; r < t.length; r++) t[r].call(e); return e; }); } return function (e, t, r, n) { return { e: applyMemberDecs(e, t, n), get c() { return function (e, t) { if (t.length > 0) { for (var r = [], n = e, a = e.name, i = t.length - 1; i >= 0; i--) { var s = { v: !1 }; try { var o = t[i](n, { kind: "class", name: a, addInitializer: createAddInitializerMethod(r, s) }); } finally { s.v = !0; } void 0 !== o && (assertValidReturnValue(10, o), n = o); } return [n, function () { for (var e = 0; e < r.length; e++) r[e].call(n); }]; } }(e, r); } }; }; } function _applyDecs2301(e, t, r, n) { return (_applyDecs2301 = applyDecs2301Factory())(e, t, r, n); } function _applyDecs2305(e, t, r, n, o, a) { function i(e, t, r) { return function (n, o) { return r && r(n), e[t].call(n, o); }; } function c(e, t) { for (var r = 0; r < e.length; r++) e[r].call(t); return t; } function s(e, t, r, n) { if ("function" != typeof e && (n || void 0 !== e)) throw new TypeError(t + " must " + (r || "be") + " a function" + (n ? "" : " or undefined")); return e; } function applyDec(e, t, r, n, o, a, c, u, l, f, p, d, h) { function m(e) { if (!h(e)) throw new TypeError("Attempted to access private element on non-instance"); } var y, v = t[0], g = t[3], b = !u; if (!b) { r || Array.isArray(v) || (v = [v]); var w = {}, S = [], A = 3 === o ? "get" : 4 === o || d ? "set" : "value"; f ? (p || d ? w = { get: _setFunctionName(function () { return g(this); }, n, "get"), set: function (e) { t[4](this, e); } } : w[A] = g, p || _setFunctionName(w[A], n, 2 === o ? "" : A)) : p || (w = Object.getOwnPropertyDescriptor(e, n)); } for (var P = e, j = v.length - 1; j >= 0; j -= r ? 2 : 1) { var D = v[j], E = r ? v[j - 1] : void 0, I = {}, O = { kind: ["field", "accessor", "method", "getter", "setter", "class"][o], name: n, metadata: a, addInitializer: function (e, t) { if (e.v) throw Error("attempted to call addInitializer after decoration was finished"); s(t, "An initializer", "be", !0), c.push(t); }.bind(null, I) }; try { if (b) (y = s(D.call(E, P, O), "class decorators", "return")) && (P = y);else { var k, F; O.static = l, O.private = f, f ? 2 === o ? k = function (e) { return m(e), w.value; } : (o < 4 && (k = i(w, "get", m)), 3 !== o && (F = i(w, "set", m))) : (k = function (e) { return e[n]; }, (o < 2 || 4 === o) && (F = function (e, t) { e[n] = t; })); var N = O.access = { has: f ? h.bind() : function (e) { return n in e; } }; if (k && (N.get = k), F && (N.set = F), P = D.call(E, d ? { get: w.get, set: w.set } : w[A], O), d) { if ("object" == typeof P && P) (y = s(P.get, "accessor.get")) && (w.get = y), (y = s(P.set, "accessor.set")) && (w.set = y), (y = s(P.init, "accessor.init")) && S.push(y);else if (void 0 !== P) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); } else s(P, (p ? "field" : "method") + " decorators", "return") && (p ? S.push(P) : w[A] = P); } } finally { I.v = !0; } } return (p || d) && u.push(function (e, t) { for (var r = S.length - 1; r >= 0; r--) t = S[r].call(e, t); return t; }), p || b || (f ? d ? u.push(i(w, "get"), i(w, "set")) : u.push(2 === o ? w[A] : i.call.bind(w[A])) : Object.defineProperty(e, n, w)), P; } function u(e, t) { return Object.defineProperty(e, Symbol.metadata || Symbol.for("Symbol.metadata"), { configurable: !0, enumerable: !0, value: t }); } if (arguments.length >= 6) var l = a[Symbol.metadata || Symbol.for("Symbol.metadata")]; var f = Object.create(null == l ? null : l), p = function (e, t, r, n) { var o, a, i = [], s = function (t) { return _checkInRHS(t) === e; }, u = new Map(); function l(e) { e && i.push(c.bind(null, e)); } for (var f = 0; f < t.length; f++) { var p = t[f]; if (Array.isArray(p)) { var d = p[1], h = p[2], m = p.length > 3, y = 16 & d, v = !!(8 & d), g = 0 == (d &= 7), b = h + "/" + v; if (!g && !m) { var w = u.get(b); if (!0 === w || 3 === w && 4 !== d || 4 === w && 3 !== d) throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + h); u.set(b, !(d > 2) || d); } applyDec(v ? e : e.prototype, p, y, m ? "#" + h : _toPropertyKey(h), d, n, v ? a = a || [] : o = o || [], i, v, m, g, 1 === d, v && m ? s : r); } } return l(o), l(a), i; }(e, t, o, f); return r.length || u(e, f), { e: p, get c() { var t = []; return r.length && [u(applyDec(e, [r], n, e.name, 5, f, t), f), c.bind(null, t, e)]; } }; } function _classApplyDescriptorDestructureSet(e, t) { if (t.set) return "__destrObj" in t || (t.__destrObj = { set value(r) { t.set.call(e, r); } }), t.__destrObj; if (!t.writable) throw new TypeError("attempted to set read only private field"); return t; } function _classApplyDescriptorGet(e, t) { return t.get ? t.get.call(e) : t.value; } function _classApplyDescriptorSet(e, t, l) { if (t.set) t.set.call(e, l);else { if (!t.writable) throw new TypeError("attempted to set read only private field"); t.value = l; } } function _classCheckPrivateStaticAccess(s, a, r) { return _assertClassBrand(a, s, r); } function _classCheckPrivateStaticFieldDescriptor(t, e) { if (void 0 === t) throw new TypeError("attempted to " + e + " private static field before its declaration"); } function _classExtractFieldDescriptor(e, t) { return _classPrivateFieldGet2(t, e); } function _classPrivateFieldDestructureSet(e, t) { var r = _classPrivateFieldGet2(t, e); return _classApplyDescriptorDestructureSet(e, r); } function _classPrivateFieldGet(e, t) { var r = _classPrivateFieldGet2(t, e); return _classApplyDescriptorGet(e, r); } function _classPrivateFieldSet(e, t, r) { var s = _classPrivateFieldGet2(t, e); return _classApplyDescriptorSet(e, s, r), r; } function _classPrivateMethodGet(s, a, r) { return _assertClassBrand(a, s), r; } function _classPrivateMethodSet() { throw new TypeError("attempted to reassign private method"); } function _classStaticPrivateFieldDestructureSet(t, r, s) { return _assertClassBrand(r, t), _classCheckPrivateStaticFieldDescriptor(s, "set"), _classApplyDescriptorDestructureSet(t, s); } function _classStaticPrivateFieldSpecGet(t, s, r) { return _assertClassBrand(s, t), _classCheckPrivateStaticFieldDescriptor(r, "get"), _classApplyDescriptorGet(t, r); } function _classStaticPrivateFieldSpecSet(s, t, r, e) { return _assertClassBrand(t, s), _classCheckPrivateStaticFieldDescriptor(r, "set"), _classApplyDescriptorSet(s, r, e), e; } function _classStaticPrivateMethodSet() { throw new TypeError("attempted to set read only static private field"); } function _defineEnumerableProperties(e, r) { for (var t in r) { var n = r[t]; n.configurable = n.enumerable = !0, "value" in n && (n.writable = !0), Object.defineProperty(e, t, n); } if (Object.getOwnPropertySymbols) for (var a = Object.getOwnPropertySymbols(r), b = 0; b < a.length; b++) { var i = a[b]; (n = r[i]).configurable = n.enumerable = !0, "value" in n && (n.writable = !0), Object.defineProperty(e, i, n); } return e; } function dispose_SuppressedError(r, e) { return "undefined" != typeof SuppressedError ? dispose_SuppressedError = SuppressedError : (dispose_SuppressedError = function (r, e) { this.suppressed = e, this.error = r, this.stack = Error().stack; }, dispose_SuppressedError.prototype = Object.create(Error.prototype, { constructor: { value: dispose_SuppressedError, writable: !0, configurable: !0 } })), new dispose_SuppressedError(r, e); } function _dispose(r, e, s) { function next() { for (; r.length > 0;) try { var o = r.pop(), p = o.d.call(o.v); if (o.a) return Promise.resolve(p).then(next, err); } catch (r) { return err(r); } if (s) throw e; } function err(r) { return e = s ? new dispose_SuppressedError(e, r) : r, s = !0, next(); } return next(); } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? Object(arguments[r]) : {}, o = Object.keys(t); "function" == typeof Object.getOwnPropertySymbols && o.push.apply(o, Object.getOwnPropertySymbols(t).filter(function (e) { return Object.getOwnPropertyDescriptor(t, e).enumerable; })), o.forEach(function (r) { _defineProperty(e, r, t[r]); }); } return e; } function _using(o, n, e) { if (null == n) return n; if (Object(n) !== n) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined."); if (e) var r = n[Symbol.asyncDispose || Symbol.for("Symbol.asyncDispose")]; if (null == r && (r = n[Symbol.dispose || Symbol.for("Symbol.dispose")]), "function" != typeof r) throw new TypeError("Property [Symbol.dispose] is not a function."); return o.push({ v: n, d: r, a: e }), n; } var _SplatBuffer, _PlyParser; /* let Ray$1 = THREE.Ray, Plane = THREE.Plane, MathUtils = THREE.MathUtils, EventDispatcher = THREE.EventDispatcher, Vector3 = THREE.Vector3, MOUSE = THREE.MOUSE, TOUCH = THREE.TOUCH, Quaternion = THREE.Quaternion, Spherical = THREE.Spherical, Vector2 = THREE.Vector2 */ //加 { var _tables = /*@__PURE__*/_generateTables(); function _generateTables() { // float32 to float16 helpers var buffer = new ArrayBuffer(4); var floatView = new Float32Array(buffer); var uint32View = new Uint32Array(buffer); var baseTable = new Uint32Array(512); var shiftTable = new Uint32Array(512); for (var i = 0; i < 256; ++i) { var e = i - 127; // very small number (0, -0) if (e < -27) { baseTable[i] = 0x0000; baseTable[i | 0x100] = 0x8000; shiftTable[i] = 24; shiftTable[i | 0x100] = 24; // small number (denorm) } else if (e < -14) { baseTable[i] = 0x0400 >> -e - 14; baseTable[i | 0x100] = 0x0400 >> -e - 14 | 0x8000; shiftTable[i] = -e - 1; shiftTable[i | 0x100] = -e - 1; // normal number } else if (e <= 15) { baseTable[i] = e + 15 << 10; baseTable[i | 0x100] = e + 15 << 10 | 0x8000; shiftTable[i] = 13; shiftTable[i | 0x100] = 13; // large number (Infinity, -Infinity) } else if (e < 128) { baseTable[i] = 0x7c00; baseTable[i | 0x100] = 0xfc00; shiftTable[i] = 24; shiftTable[i | 0x100] = 24; // stay (NaN, Infinity, -Infinity) } else { baseTable[i] = 0x7c00; baseTable[i | 0x100] = 0xfc00; shiftTable[i] = 13; shiftTable[i | 0x100] = 13; } } // float16 to float32 helpers var mantissaTable = new Uint32Array(2048); var exponentTable = new Uint32Array(64); var offsetTable = new Uint32Array(64); for (var _i = 1; _i < 1024; ++_i) { var m = _i << 13; // zero pad mantissa bits var _e = 0; // zero exponent // normalized while ((m & 0x00800000) === 0) { m <<= 1; _e -= 0x00800000; // decrement exponent } m &= ~0x00800000; // clear leading 1 bit _e += 0x38800000; // adjust bias mantissaTable[_i] = m | _e; } for (var _i2 = 1024; _i2 < 2048; ++_i2) { mantissaTable[_i2] = 0x38000000 + (_i2 - 1024 << 13); } for (var _i3 = 1; _i3 < 31; ++_i3) { exponentTable[_i3] = _i3 << 23; } exponentTable[31] = 0x47800000; exponentTable[32] = 0x80000000; for (var _i4 = 33; _i4 < 63; ++_i4) { exponentTable[_i4] = 0x80000000 + (_i4 - 32 << 23); } exponentTable[63] = 0xc7800000; for (var _i5 = 1; _i5 < 64; ++_i5) { if (_i5 !== 32) { offsetTable[_i5] = 1024; } } return { floatView: floatView, uint32View: uint32View, baseTable: baseTable, shiftTable: shiftTable, mantissaTable: mantissaTable, exponentTable: exponentTable, offsetTable: offsetTable }; } // float32 to float16 /* function toHalfFloat( val ) { if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' ); val = clamp( val, - 65504, 65504 ); _tables.floatView[ 0 ] = val; const f = _tables.uint32View[ 0 ]; const e = ( f >> 23 ) & 0x1ff; return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] ); } */ // float16 to float32 function _fromHalfFloat(val) { var m = val >> 10; _tables.uint32View[0] = _tables.mantissaTable[_tables.offsetTable[m] + (val & 0x3ff)] + _tables.exponentTable[m]; return _tables.floatView[0]; } /* THREE.DataUtils = { toHalfFloat: toHalfFloat, fromHalfFloat: fromHalfFloat, }; */ DataUtils.fromHalfFloat = _fromHalfFloat; } //--------------------------------------------------- /** * AbortablePromise: A quick & dirty wrapper for JavaScript's Promise class that allows the underlying * asynchronous operation to be cancelled. It is only meant for simple situations where no complex promise * chaining or merging occurs. It needs a significant amount of work to truly replicate the full * functionality of JavaScript's Promise class. Look at Util.fetchWithProgress() for example usage. * * This class was primarily added to allow splat scene downloads to be cancelled. It has not been tested * very thoroughly and the implementation is kinda janky. If you can at all help it, please avoid using it :) */ class AbortablePromise { constructor(promiseFunc, abortHandler) { var promiseResolve; var promiseReject; this.promise = new Promise((resolve, reject) => { promiseResolve = resolve.bind(this); promiseReject = reject.bind(this); }); var resolve = function resolve() { promiseResolve(...arguments); }; var reject = error => { promiseReject(error); }; promiseFunc(resolve.bind(this), reject.bind(this)); this.abortHandler = abortHandler; this.id = AbortablePromise.idGen++; } then(onResolve) { return new AbortablePromise((resolve, reject) => { this.promise = this.promise.then(function () { var onResolveResult = onResolve(...arguments); if (onResolveResult instanceof Promise || onResolveResult instanceof AbortablePromise) { onResolveResult.then(function () { resolve(...arguments); }); } else { resolve(onResolveResult); } }).catch(error => { reject(error); }); }, this.abortHandler); } catch(onFail) { return new AbortablePromise(resolve => { this.promise = this.promise.then(function () { resolve(...arguments); }).catch(onFail); }, this.abortHandler); } abort() { if (this.abortHandler) this.abortHandler(); } } _defineProperty(AbortablePromise, "idGen", 0); class AbortedPromiseError extends Error { constructor(msg) { super(msg); } } var floatToHalf = function () { var floatView = new Float32Array(1); var int32View = new Int32Array(floatView.buffer); return function (val) { floatView[0] = val; var x = int32View[0]; var bits = x >> 16 & 0x8000; var m = x >> 12 & 0x07ff; var e = x >> 23 & 0xff; if (e < 103) return bits; if (e > 142) { bits |= 0x7c00; bits |= (e == 255 ? 0 : 1) && x & 0x007fffff; return bits; } if (e < 113) { m |= 0x0800; bits |= (m >> 114 - e) + (m >> 113 - e & 1); return bits; } bits |= e - 112 << 10 | m >> 1; bits += m & 1; return bits; }; }(); var uintEncodedFloat = function () { var floatView = new Float32Array(1); var int32View = new Int32Array(floatView.buffer); return function (f) { floatView[0] = f; return int32View[0]; }; }(); var rgbaToInteger = function rgbaToInteger(r, g, b, a) { return r + (g << 8) + (b << 16) + (a << 24); }; var rgbaArrayToInteger = function rgbaArrayToInteger(arr, offset) { return arr[offset] + (arr[offset + 1] << 8) + (arr[offset + 2] << 16) + (arr[offset + 3] << 24); }; var fetchWithProgress = function fetchWithProgress(path, onProgress) { var saveChunks = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var abortController = new AbortController(); var signal = abortController.signal; var aborted = false; var rejectFunc = null; var abortHandler = () => { abortController.abort(); rejectFunc(new AbortedPromiseError('Fetch aborted.')); aborted = true; }; return new AbortablePromise((resolve, reject) => { rejectFunc = reject; fetch(path, { signal }).then(async data => { var reader = data.body.getReader(); var bytesDownloaded = 0; var _fileSize = data.headers.get('Content-Length'); var fileSize = _fileSize ? parseInt(_fileSize) : undefined; var chunks = []; while (!aborted) { try { var { value: chunk, done } = await reader.read(); if (done) { if (onProgress) { onProgress(100, '100%', chunk, fileSize); } if (saveChunks) { var buffer = new Blob(chunks).arrayBuffer(); resolve(buffer); } else { resolve(); } break; } bytesDownloaded += chunk.length; var percent = void 0; var percentLabel = void 0; if (fileSize !== undefined) { percent = bytesDownloaded / fileSize * 100; percentLabel = "".concat(percent.toFixed(2), "%"); } if (saveChunks) chunks.push(chunk); if (onProgress) { var cancelSaveChucnks = onProgress(percent, percentLabel, chunk, fileSize); if (cancelSaveChucnks) saveChunks = false; } } catch (error) { reject(error); break; } } }); }, abortHandler); }; var clamp = function clamp(val, min, max) { return Math.max(Math.min(val, max), min); }; var getCurrentTime = function getCurrentTime() { return performance.now() / 1000; }; var disposeAllMeshes = object3D => { if (object3D.geometry) { object3D.geometry.dispose(); object3D.geometry = null; } if (object3D.material) { object3D.material.dispose(); object3D.material = null; } if (object3D.children) { for (var child of object3D.children) { disposeAllMeshes(child); } } }; var delayedExecute = (func, fast) => { return new Promise(resolve => { window.setTimeout(() => { resolve(func()); }, fast ? 1 : 50); }); }; var getSphericalHarmonicsComponentCountForDegree = function getSphericalHarmonicsComponentCountForDegree() { var sphericalHarmonicsDegree = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; switch (sphericalHarmonicsDegree) { case 1: return 9; case 2: return 24; } return 0; }; var BASE_COMPONENT_COUNT = 14; class UncompressedSplatArray { constructor() { var sphericalHarmonicsDegree = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; this.sphericalHarmonicsDegree = sphericalHarmonicsDegree; this.sphericalHarmonicsCount = getSphericalHarmonicsComponentCountForDegree(this.sphericalHarmonicsDegree); this.componentCount = this.sphericalHarmonicsCount + BASE_COMPONENT_COUNT; this.defaultSphericalHarmonics = new Array(this.sphericalHarmonicsCount).fill(0); this.splats = []; this.splatCount = 0; } static createSplat() { var sphericalHarmonicsDegree = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var baseSplat = [0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]; var shEntries = getSphericalHarmonicsComponentCountForDegree(sphericalHarmonicsDegree); for (var i = 0; i < shEntries; i++) baseSplat.push(0); return baseSplat; } addSplat(splat) { this.splats.push(splat); this.splatCount++; } getSplat(index) { return this.splats[index]; } addDefaultSplat() { var newSplat = UncompressedSplatArray.createSplat(this.sphericalHarmonicsDegree); this.addSplat(newSplat); return newSplat; } addSplatFromComonents(x, y, z, scale0, scale1, scale2, rot0, rot1, rot2, rot3, r, g, b, opacity) { var newSplat = [x, y, z, scale0, scale1, scale2, rot0, rot1, rot2, rot3, r, g, b, opacity, ...this.defaultSphericalHarmonics]; for (var i = 0; i < (arguments.length <= 14 ? 0 : arguments.length - 14) && i < this.sphericalHarmonicsCount; i++) { newSplat[i] = i + 14 < 14 || arguments.length <= i + 14 ? undefined : arguments[i + 14]; } this.addSplat(newSplat); return newSplat; } addSplatFromArray(src, srcIndex) { var srcSplat = src.splats[srcIndex]; var newSplat = UncompressedSplatArray.createSplat(this.sphericalHarmonicsDegree); for (var i = 0; i < this.componentCount && i < srcSplat.length; i++) { newSplat[i] = srcSplat[i]; } this.addSplat(newSplat); } } _defineProperty(UncompressedSplatArray, "OFFSET", { X: 0, Y: 1, Z: 2, SCALE0: 3, SCALE1: 4, SCALE2: 5, ROTATION0: 6, ROTATION1: 7, ROTATION2: 8, ROTATION3: 9, FDC0: 10, FDC1: 11, FDC2: 12, OPACITY: 13, FRC0: 14, FRC1: 15, FRC2: 16, FRC3: 17, FRC4: 18, FRC5: 19, FRC6: 20, FRC7: 21, FRC8: 22, FRC9: 23, FRC10: 24, FRC11: 25, FRC12: 26, FRC13: 27, FRC14: 28, FRC15: 29, FRC16: 30, FRC17: 31, FRC18: 32, FRC19: 33, FRC20: 34, FRC21: 35, FRC22: 36, FRC23: 37 }); var toHalfFloat = DataUtils.toHalfFloat.bind(DataUtils); var toUint8 = v => { return Math.floor(v * 128) + 128; }; var fromUint8 = v => { return v / 255 * 2.0 - 1.0; }; //xzw 改 暂时没用到 需要更新版本 var fromHalfFloat = DataUtils.fromHalfFloat.bind(DataUtils); var fromHalfFloatToUint8 = v => { return Math.floor(fromHalfFloat(v) * 128) + 128; }; var toUncompressedFloat = function toUncompressedFloat(f, compressionLevel) { var isSH = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (compressionLevel === 0) { return f; } else if (compressionLevel === 1 || compressionLevel === 2 && !isSH) { return DataUtils.fromHalfFloat(f); } else if (compressionLevel === 2) { return fromUint8(f); } }; var dataViewFloatForCompressionLevel = function dataViewFloatForCompressionLevel(dataView, floatIndex, compressionLevel) { var isSH = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; if (compressionLevel === 0) { return dataView.getFloat32(floatIndex * 4, true); } else if (compressionLevel === 1 || compressionLevel === 2 && !isSH) { return dataView.getUint16(floatIndex * 2, true); } else { return dataView.getUint8(floatIndex, true); } }; /** * SplatBuffer: Container for splat data from a single scene/file and capable of (mediocre) compression. */ class SplatBuffer { constructor(bufferData) { var secLoadedCountsToMax = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; _defineProperty(this, "getSplatScaleAndRotation", function () { var scaleMatrix = new Matrix4(); var rotationMatrix = new Matrix4(); var tempMatrix = new Matrix4(); var tempPosition = new Vector3(); var scale = new Vector3(); var rotation = new Quaternion(); return function (index, outScale, outRotation, transform) { var sectionIndex = this.globalSplatIndexToSectionMap[index]; var section = this.sections[sectionIndex]; var localSplatIndex = index - section.splatCountOffset; var srcSplatScalesBase = section.bytesPerSplat * localSplatIndex + SplatBuffer.CompressionLevels[this.compressionLevel].ScaleOffsetBytes; var dataView = new DataView(this.bufferData, section.dataBase + srcSplatScalesBase); scale.set(toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 0, this.compressionLevel), this.compressionLevel), toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 1, this.compressionLevel), this.compressionLevel), toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 2, this.compressionLevel), this.compressionLevel)); rotation.set(toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 4, this.compressionLevel), this.compressionLevel), toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 5, this.compressionLevel), this.compressionLevel), toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 6, this.compressionLevel), this.compressionLevel), toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 3, this.compressionLevel), this.compressionLevel)); if (transform) { scaleMatrix.makeScale(scale.x, scale.y, scale.z); rotationMatrix.makeRotationFromQuaternion(rotation); tempMatrix.copy(scaleMatrix).multiply(rotationMatrix).multiply(transform); tempMatrix.decompose(tempPosition, outRotation, outScale); } else { outScale.copy(scale); outRotation.copy(rotation); } }; }()); _defineProperty(this, "fillSphericalHarmonicsArray", function () { var sphericalHarmonicVectors = []; for (var i = 0; i < 15; i++) { sphericalHarmonicVectors[i] = new Vector3(); } var tempMatrix3 = new Matrix3(); var sh11 = []; var sh12 = []; var sh13 = []; var sh21 = []; var sh22 = []; var sh23 = []; var sh24 = []; var sh25 = []; var shIn1 = []; var shIn2 = []; var shIn3 = []; var shIn4 = []; var shIn5 = []; var shOut1 = []; var shOut2 = []; var shOut3 = []; var shOut4 = []; var shOut5 = []; var noop = v => v; var set3 = (array, val1, val2, val3) => { array[0] = val1; array[1] = val2; array[2] = val3; }; var set3FromArray = (array, srcDestView, stride, srcBase, compressionLevel) => { array[0] = dataViewFloatForCompressionLevel(srcDestView, srcBase, compressionLevel, true); array[1] = dataViewFloatForCompressionLevel(srcDestView, srcBase + stride, compressionLevel, true); array[2] = dataViewFloatForCompressionLevel(srcDestView, srcBase + stride + stride, compressionLevel, true); }; var copy3 = (srcArray, destArray) => { destArray[0] = srcArray[0]; destArray[1] = srcArray[1]; destArray[2] = srcArray[2]; }; var setOutput3 = (srcArray, destArray, destBase, conversionFunc) => { destArray[destBase] = conversionFunc(srcArray[0]); destArray[destBase + 1] = conversionFunc(srcArray[1]); destArray[destBase + 2] = conversionFunc(srcArray[2]); }; var toUncompressedFloatArray3 = (src, dest, compressionLevel) => { dest[0] = toUncompressedFloat(src[0], compressionLevel, true); dest[1] = toUncompressedFloat(src[1], compressionLevel, true); dest[2] = toUncompressedFloat(src[2], compressionLevel, true); return dest; }; return function (outSphericalHarmonicsArray, outSphericalHarmonicsDegree, transform, srcFrom, srcTo, destFrom, desiredOutputCompressionLevel) { var splatCount = this.splatCount; srcFrom = srcFrom || 0; srcTo = srcTo || splatCount - 1; if (destFrom === undefined) destFrom = srcFrom; if (transform && outSphericalHarmonicsDegree >= 1) { tempMatrix3.setFromMatrix4(transform); set3(sh11, tempMatrix3.elements[4], -tempMatrix3.elements[7], tempMatrix3.elements[1]); set3(sh12, -tempMatrix3.elements[5], tempMatrix3.elements[8], -tempMatrix3.elements[2]); set3(sh13, tempMatrix3.elements[3], -tempMatrix3.elements[6], tempMatrix3.elements[0]); } for (var _i6 = srcFrom; _i6 <= srcTo; _i6++) { var sectionIndex = this.globalSplatIndexToSectionMap[_i6]; var section = this.sections[sectionIndex]; outSphericalHarmonicsDegree = Math.min(outSphericalHarmonicsDegree, section.sphericalHarmonicsDegree); var outSphericalHarmonicsComponentsCount = getSphericalHarmonicsComponentCountForDegree(outSphericalHarmonicsDegree); var localSplatIndex = _i6 - section.splatCountOffset; var srcSplatSHBase = section.bytesPerSplat * localSplatIndex + SplatBuffer.CompressionLevels[this.compressionLevel].SphericalHarmonicsOffsetBytes; var dataView = new DataView(this.bufferData, section.dataBase + srcSplatSHBase); var shDestBase = (_i6 - srcFrom + destFrom) * outSphericalHarmonicsComponentsCount; var compressionLevelForOutputConversion = transform ? 0 : this.compressionLevel; var outputConversionFunc = noop; if (compressionLevelForOutputConversion !== desiredOutputCompressionLevel) { if (compressionLevelForOutputConversion === 1) { if (desiredOutputCompressionLevel === 0) outputConversionFunc = fromHalfFloat;else if (desiredOutputCompressionLevel == 2) outputConversionFunc = fromHalfFloatToUint8; } else if (compressionLevelForOutputConversion === 0) { if (desiredOutputCompressionLevel === 1) outputConversionFunc = toHalfFloat;else if (desiredOutputCompressionLevel == 2) outputConversionFunc = toUint8; } } if (outSphericalHarmonicsDegree >= 1) { set3FromArray(shIn1, dataView, 3, 0, this.compressionLevel); set3FromArray(shIn2, dataView, 3, 1, this.compressionLevel); set3FromArray(shIn3, dataView, 3, 2, this.compressionLevel); if (transform) { toUncompressedFloatArray3(shIn1, shIn1, this.compressionLevel); toUncompressedFloatArray3(shIn2, shIn2, this.compressionLevel); toUncompressedFloatArray3(shIn3, shIn3, this.compressionLevel); SplatBuffer.rotateSphericalHarmonics3(shIn1, shIn2, shIn3, sh11, sh12, sh13, shOut1, shOut2, shOut3); } else { copy3(shIn1, shOut1); copy3(shIn2, shOut2); copy3(shIn3, shOut3); } setOutput3(shOut1, outSphericalHarmonicsArray, shDestBase, outputConversionFunc); setOutput3(shOut2, outSphericalHarmonicsArray, shDestBase + 3, outputConversionFunc); setOutput3(shOut3, outSphericalHarmonicsArray, shDestBase + 6, outputConversionFunc); if (outSphericalHarmonicsDegree >= 2) { set3FromArray(shIn1, dataView, 5, 9, this.compressionLevel); set3FromArray(shIn2, dataView, 5, 10, this.compressionLevel); set3FromArray(shIn3, dataView, 5, 11, this.compressionLevel); set3FromArray(shIn4, dataView, 5, 12, this.compressionLevel); set3FromArray(shIn5, dataView, 5, 13, this.compressionLevel); if (transform) { toUncompressedFloatArray3(shIn1, shIn1, this.compressionLevel); toUncompressedFloatArray3(shIn2, shIn2, this.compressionLevel); toUncompressedFloatArray3(shIn3, shIn3, this.compressionLevel); toUncompressedFloatArray3(shIn4, shIn4, this.compressionLevel); toUncompressedFloatArray3(shIn5, shIn5, this.compressionLevel); SplatBuffer.rotateSphericalHarmonics5(shIn1, shIn2, shIn3, shIn4, shIn5, sh11, sh12, sh13, sh21, sh22, sh23, sh24, sh25, shOut1, shOut2, shOut3, shOut4, shOut5); } else { copy3(shIn1, shOut1); copy3(shIn2, shOut2); copy3(shIn3, shOut3); copy3(shIn4, shOut4); copy3(shIn5, shOut5); } setOutput3(shOut1, outSphericalHarmonicsArray, shDestBase + 9, outputConversionFunc); setOutput3(shOut2, outSphericalHarmonicsArray, shDestBase + 12, outputConversionFunc); setOutput3(shOut3, outSphericalHarmonicsArray, shDestBase + 15, outputConversionFunc); setOutput3(shOut4, outSphericalHarmonicsArray, shDestBase + 18, outputConversionFunc); setOutput3(shOut5, outSphericalHarmonicsArray, shDestBase + 21, outputConversionFunc); } } } }; }()); this.constructFromBuffer(bufferData, secLoadedCountsToMax); } getSplatCount() { return this.splatCount; } getMaxSplatCount() { return this.maxSplatCount; } getMinSphericalHarmonicsDegree() { var minSphericalHarmonicsDegree = 0; for (var i = 0; i < this.sections.length; i++) { var section = this.sections[i]; if (i === 0 || section.sphericalHarmonicsDegree < minSphericalHarmonicsDegree) { minSphericalHarmonicsDegree = section.sphericalHarmonicsDegree; } } return minSphericalHarmonicsDegree; } getBucketIndex(section, localSplatIndex) { var bucketIndex; var maxSplatIndexInFullBuckets = section.fullBucketCount * section.bucketSize; if (localSplatIndex < maxSplatIndexInFullBuckets) { bucketIndex = Math.floor(localSplatIndex / section.bucketSize); } else { var bucketSplatIndex = maxSplatIndexInFullBuckets; bucketIndex = section.fullBucketCount; var partiallyFullBucketIndex = 0; while (bucketSplatIndex < section.splatCount) { var currentPartiallyFilledBucketSize = section.partiallyFilledBucketLengths[partiallyFullBucketIndex]; if (localSplatIndex >= bucketSplatIndex && localSplatIndex < bucketSplatIndex + currentPartiallyFilledBucketSize) { break; } bucketSplatIndex += currentPartiallyFilledBucketSize; bucketIndex++; partiallyFullBucketIndex++; } } return bucketIndex; } getSplatCenter(globalSplatIndex, outCenter, transform) { var sectionIndex = this.globalSplatIndexToSectionMap[globalSplatIndex]; var section = this.sections[sectionIndex]; var localSplatIndex = globalSplatIndex - section.splatCountOffset; var srcSplatCentersBase = section.bytesPerSplat * localSplatIndex; var dataView = new DataView(this.bufferData, section.dataBase + srcSplatCentersBase); var x = dataViewFloatForCompressionLevel(dataView, 0, this.compressionLevel); var y = dataViewFloatForCompressionLevel(dataView, 1, this.compressionLevel); var z = dataViewFloatForCompressionLevel(dataView, 2, this.compressionLevel); if (this.compressionLevel >= 1) { var bucketIndex = this.getBucketIndex(section, localSplatIndex); var bucketBase = bucketIndex * SplatBuffer.BucketStorageSizeFloats; var sf = section.compressionScaleFactor; var sr = section.compressionScaleRange; outCenter.x = (x - sr) * sf + section.bucketArray[bucketBase]; outCenter.y = (y - sr) * sf + section.bucketArray[bucketBase + 1]; outCenter.z = (z - sr) * sf + section.bucketArray[bucketBase + 2]; } else { outCenter.x = x; outCenter.y = y; outCenter.z = z; } if (transform) outCenter.applyMatrix4(transform); } getSplatColor(globalSplatIndex, outColor) { var sectionIndex = this.globalSplatIndexToSectionMap[globalSplatIndex]; var section = this.sections[sectionIndex]; var localSplatIndex = globalSplatIndex - section.splatCountOffset; var srcSplatColorsBase = section.bytesPerSplat * localSplatIndex + SplatBuffer.CompressionLevels[this.compressionLevel].ColorOffsetBytes; var splatColorsArray = new Uint8Array(this.bufferData, section.dataBase + srcSplatColorsBase, 4); outColor.set(splatColorsArray[0], splatColorsArray[1], splatColorsArray[2], splatColorsArray[3]); } fillSplatCenterArray(outCenterArray, transform, srcFrom, srcTo, destFrom) { var splatCount = this.splatCount; srcFrom = srcFrom || 0; srcTo = srcTo || splatCount - 1; if (destFrom === undefined) destFrom = srcFrom; var center = new Vector3(); for (var i = srcFrom; i <= srcTo; i++) { var sectionIndex = this.globalSplatIndexToSectionMap[i]; var section = this.sections[sectionIndex]; var localSplatIndex = i - section.splatCountOffset; var centerDestBase = (i - srcFrom + destFrom) * SplatBuffer.CenterComponentCount; var srcSplatCentersBase = section.bytesPerSplat * localSplatIndex; var dataView = new DataView(this.bufferData, section.dataBase + srcSplatCentersBase); var x = dataViewFloatForCompressionLevel(dataView, 0, this.compressionLevel); var y = dataViewFloatForCompressionLevel(dataView, 1, this.compressionLevel); var z = dataViewFloatForCompressionLevel(dataView, 2, this.compressionLevel); if (this.compressionLevel >= 1) { var bucketIndex = this.getBucketIndex(section, localSplatIndex); var bucketBase = bucketIndex * SplatBuffer.BucketStorageSizeFloats; var sf = section.compressionScaleFactor; var sr = section.compressionScaleRange; center.x = (x - sr) * sf + section.bucketArray[bucketBase]; center.y = (y - sr) * sf + section.bucketArray[bucketBase + 1]; center.z = (z - sr) * sf + section.bucketArray[bucketBase + 2]; } else { center.x = x; center.y = y; center.z = z; } if (transform) { center.applyMatrix4(transform); } outCenterArray[centerDestBase] = center.x; outCenterArray[centerDestBase + 1] = center.y; outCenterArray[centerDestBase + 2] = center.z; } } fillSplatCovarianceArray(covarianceArray, transform, srcFrom, srcTo, destFrom, desiredOutputCompressionLevel) { var splatCount = this.splatCount; var scale = new Vector3(); var rotation = new Quaternion(); srcFrom = srcFrom || 0; srcTo = srcTo || splatCount - 1; if (destFrom === undefined) destFrom = srcFrom; for (var i = srcFrom; i <= srcTo; i++) { var sectionIndex = this.globalSplatIndexToSectionMap[i]; var section = this.sections[sectionIndex]; var localSplatIndex = i - section.splatCountOffset; var covarianceDestBase = (i - srcFrom + destFrom) * SplatBuffer.CovarianceComponentCount; var srcSplatScalesBase = section.bytesPerSplat * localSplatIndex + SplatBuffer.CompressionLevels[this.compressionLevel].ScaleOffsetBytes; var dataView = new DataView(this.bufferData, section.dataBase + srcSplatScalesBase); scale.set(toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 0, this.compressionLevel), this.compressionLevel), toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 1, this.compressionLevel), this.compressionLevel), toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 2, this.compressionLevel), this.compressionLevel)); rotation.set(toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 4, this.compressionLevel), this.compressionLevel), toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 5, this.compressionLevel), this.compressionLevel), toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 6, this.compressionLevel), this.compressionLevel), toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 3, this.compressionLevel), this.compressionLevel)); SplatBuffer.computeCovariance(scale, rotation, transform, covarianceArray, covarianceDestBase, desiredOutputCompressionLevel); } } fillSplatColorArray(outColorArray, minimumAlpha, srcFrom, srcTo, destFrom) { var splatCount = this.splatCount; srcFrom = srcFrom || 0; srcTo = srcTo || splatCount - 1; if (destFrom === undefined) destFrom = srcFrom; for (var i = srcFrom; i <= srcTo; i++) { var sectionIndex = this.globalSplatIndexToSectionMap[i]; var section = this.sections[sectionIndex]; var localSplatIndex = i - section.splatCountOffset; var colorDestBase = (i - srcFrom + destFrom) * SplatBuffer.ColorComponentCount; var srcSplatColorsBase = section.bytesPerSplat * localSplatIndex + SplatBuffer.CompressionLevels[this.compressionLevel].ColorOffsetBytes; var dataView = new Uint8Array(this.bufferData, section.dataBase + srcSplatColorsBase); var alpha = dataView[3]; alpha = alpha >= minimumAlpha ? alpha : 0; outColorArray[colorDestBase] = dataView[0]; outColorArray[colorDestBase + 1] = dataView[1]; outColorArray[colorDestBase + 2] = dataView[2]; outColorArray[colorDestBase + 3] = alpha; } } static parseHeader(buffer) { var headerArrayUint8 = new Uint8Array(buffer, 0, SplatBuffer.HeaderSizeBytes); var headerArrayUint16 = new Uint16Array(buffer, 0, SplatBuffer.HeaderSizeBytes / 2); var headerArrayUint32 = new Uint32Array(buffer, 0, SplatBuffer.HeaderSizeBytes / 4); var headerArrayFloat32 = new Float32Array(buffer, 0, SplatBuffer.HeaderSizeBytes / 4); var versionMajor = headerArrayUint8[0]; var versionMinor = headerArrayUint8[1]; var maxSectionCount = headerArrayUint32[1]; var sectionCount = headerArrayUint32[2]; var maxSplatCount = headerArrayUint32[3]; var splatCount = headerArrayUint32[4]; var compressionLevel = headerArrayUint16[10]; var sceneCenter = new Vector3(headerArrayFloat32[6], headerArrayFloat32[7], headerArrayFloat32[8]); return { versionMajor, versionMinor, maxSectionCount, sectionCount, maxSplatCount, splatCount, compressionLevel, sceneCenter }; } static writeHeaderCountsToBuffer(sectionCount, splatCount, buffer) { var headerArrayUint32 = new Uint32Array(buffer, 0, SplatBuffer.HeaderSizeBytes / 4); headerArrayUint32[2] = sectionCount; headerArrayUint32[4] = splatCount; } static writeHeaderToBuffer(header, buffer) { var headerArrayUint8 = new Uint8Array(buffer, 0, SplatBuffer.HeaderSizeBytes); var headerArrayUint16 = new Uint16Array(buffer, 0, SplatBuffer.HeaderSizeBytes / 2); var headerArrayUint32 = new Uint32Array(buffer, 0, SplatBuffer.HeaderSizeBytes / 4); var headerArrayFloat32 = new Float32Array(buffer, 0, SplatBuffer.HeaderSizeBytes / 4); headerArrayUint8[0] = header.versionMajor; headerArrayUint8[1] = header.versionMinor; headerArrayUint8[2] = 0; // unused for now headerArrayUint8[3] = 0; // unused for now headerArrayUint32[1] = header.maxSectionCount; headerArrayUint32[2] = header.sectionCount; headerArrayUint32[3] = header.maxSplatCount; headerArrayUint32[4] = header.splatCount; headerArrayUint16[10] = header.compressionLevel; headerArrayFloat32[6] = header.sceneCenter.x; headerArrayFloat32[7] = header.sceneCenter.y; headerArrayFloat32[8] = header.sceneCenter.z; } static parseSectionHeaders(header, buffer) { var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var secLoadedCountsToMax = arguments.length > 3 ? arguments[3] : undefined; var compressionLevel = header.compressionLevel; var maxSectionCount = header.maxSectionCount; var sectionHeaderArrayUint16 = new Uint16Array(buffer, offset, maxSectionCount * SplatBuffer.SectionHeaderSizeBytes / 2); var sectionHeaderArrayUint32 = new Uint32Array(buffer, offset, maxSectionCount * SplatBuffer.SectionHeaderSizeBytes / 4); var sectionHeaderArrayFloat32 = new Float32Array(buffer, offset, maxSectionCount * SplatBuffer.SectionHeaderSizeBytes / 4); var sectionHeaders = []; var sectionHeaderBase = 0; var sectionHeaderBaseUint16 = sectionHeaderBase / 2; var sectionHeaderBaseUint32 = sectionHeaderBase / 4; var sectionBase = SplatBuffer.HeaderSizeBytes + header.maxSectionCount * SplatBuffer.SectionHeaderSizeBytes; var splatCountOffset = 0; for (var i = 0; i < maxSectionCount; i++) { var maxSplatCount = sectionHeaderArrayUint32[sectionHeaderBaseUint32 + 1]; var bucketSize = sectionHeaderArrayUint32[sectionHeaderBaseUint32 + 2]; var bucketCount = sectionHeaderArrayUint32[sectionHeaderBaseUint32 + 3]; var bucketBlockSize = sectionHeaderArrayFloat32[sectionHeaderBaseUint32 + 4]; var halfBucketBlockSize = bucketBlockSize / 2.0; var bucketStorageSizeBytes = sectionHeaderArrayUint16[sectionHeaderBaseUint16 + 10]; var compressionScaleRange = sectionHeaderArrayUint32[sectionHeaderBaseUint32 + 6] || SplatBuffer.CompressionLevels[compressionLevel].ScaleRange; var fullBucketCount = sectionHeaderArrayUint32[sectionHeaderBaseUint32 + 8]; var partiallyFilledBucketCount = sectionHeaderArrayUint32[sectionHeaderBaseUint32 + 9]; var bucketsMetaDataSizeBytes = partiallyFilledBucketCount * 4; var bucketsStorageSizeBytes = bucketStorageSizeBytes * bucketCount + bucketsMetaDataSizeBytes; var sphericalHarmonicsDegree = sectionHeaderArrayUint16[sectionHeaderBaseUint16 + 20]; var { bytesPerSplat } = SplatBuffer.calculateComponentStorage(compressionLevel, sphericalHarmonicsDegree); var splatDataStorageSizeBytes = bytesPerSplat * maxSplatCount; var storageSizeBytes = splatDataStorageSizeBytes + bucketsStorageSizeBytes; var sectionHeader = { bytesPerSplat: bytesPerSplat, splatCountOffset: splatCountOffset, splatCount: secLoadedCountsToMax ? maxSplatCount : 0, maxSplatCount: maxSplatCount, bucketSize: bucketSize, bucketCount: bucketCount, bucketBlockSize: bucketBlockSize, halfBucketBlockSize: halfBucketBlockSize, bucketStorageSizeBytes: bucketStorageSizeBytes, bucketsStorageSizeBytes: bucketsStorageSizeBytes, splatDataStorageSizeBytes: splatDataStorageSizeBytes, storageSizeBytes: storageSizeBytes, compressionScaleRange: compressionScaleRange, compressionScaleFactor: halfBucketBlockSize / compressionScaleRange, base: sectionBase, bucketsBase: sectionBase + bucketsMetaDataSizeBytes, dataBase: sectionBase + bucketsStorageSizeBytes, fullBucketCount: fullBucketCount, partiallyFilledBucketCount: partiallyFilledBucketCount, sphericalHarmonicsDegree: sphericalHarmonicsDegree }; sectionHeaders[i] = sectionHeader; sectionBase += storageSizeBytes; sectionHeaderBase += SplatBuffer.SectionHeaderSizeBytes; sectionHeaderBaseUint16 = sectionHeaderBase / 2; sectionHeaderBaseUint32 = sectionHeaderBase / 4; splatCountOffset += maxSplatCount; } return sectionHeaders; } static writeSectionHeaderToBuffer(sectionHeader, compressionLevel, buffer) { var offset = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; var sectionHeadeArrayUint16 = new Uint16Array(buffer, offset, SplatBuffer.SectionHeaderSizeBytes / 2); var sectionHeadeArrayUint32 = new Uint32Array(buffer, offset, SplatBuffer.SectionHeaderSizeBytes / 4); var sectionHeadeArrayFloat32 = new Float32Array(buffer, offset, SplatBuffer.SectionHeaderSizeBytes / 4); sectionHeadeArrayUint32[0] = sectionHeader.splatCount; sectionHeadeArrayUint32[1] = sectionHeader.maxSplatCount; sectionHeadeArrayUint32[2] = compressionLevel >= 1 ? sectionHeader.bucketSize : 0; sectionHeadeArrayUint32[3] = compressionLevel >= 1 ? sectionHeader.bucketCount : 0; sectionHeadeArrayFloat32[4] = compressionLevel >= 1 ? sectionHeader.bucketBlockSize : 0.0; sectionHeadeArrayUint16[10] = compressionLevel >= 1 ? SplatBuffer.BucketStorageSizeBytes : 0; sectionHeadeArrayUint32[6] = compressionLevel >= 1 ? sectionHeader.compressionScaleRange : 0; sectionHeadeArrayUint32[7] = sectionHeader.storageSizeBytes; sectionHeadeArrayUint32[8] = compressionLevel >= 1 ? sectionHeader.fullBucketCount : 0; sectionHeadeArrayUint32[9] = compressionLevel >= 1 ? sectionHeader.partiallyFilledBucketCount : 0; sectionHeadeArrayUint16[20] = sectionHeader.sphericalHarmonicsDegree; } static writeSectionHeaderSplatCountToBuffer(splatCount, buffer) { var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var sectionHeadeArrayUint32 = new Uint32Array(buffer, offset, SplatBuffer.SectionHeaderSizeBytes / 4); sectionHeadeArrayUint32[0] = splatCount; } constructFromBuffer(bufferData, secLoadedCountsToMax) { this.bufferData = bufferData; this.globalSplatIndexToLocalSplatIndexMap = []; this.globalSplatIndexToSectionMap = []; var header = SplatBuffer.parseHeader(this.bufferData); this.versionMajor = header.versionMajor; this.versionMinor = header.versionMinor; this.maxSectionCount = header.maxSectionCount; this.sectionCount = secLoadedCountsToMax ? header.maxSectionCount : 0; this.maxSplatCount = header.maxSplatCount; this.splatCount = secLoadedCountsToMax ? header.maxSplatCount : 0; this.compressionLevel = header.compressionLevel; this.sceneCenter = new Vector3().copy(header.sceneCenter); this.sections = SplatBuffer.parseSectionHeaders(header, this.bufferData, SplatBuffer.HeaderSizeBytes, secLoadedCountsToMax); this.linkBufferArrays(); this.buildMaps(); } static calculateComponentStorage(compressionLevel, sphericalHarmonicsDegree) { var bytesPerCenter = SplatBuffer.CompressionLevels[compressionLevel].BytesPerCenter; var bytesPerScale = SplatBuffer.CompressionLevels[compressionLevel].BytesPerScale; var bytesPerRotation = SplatBuffer.CompressionLevels[compressionLevel].BytesPerRotation; var bytesPerColor = SplatBuffer.CompressionLevels[compressionLevel].BytesPerColor; var sphericalHarmonicsComponentsPerSplat = getSphericalHarmonicsComponentCountForDegree(sphericalHarmonicsDegree); var sphericalHarmonicsBytesPerSplat = SplatBuffer.CompressionLevels[compressionLevel].BytesPerSphericalHarmonicsComponent * sphericalHarmonicsComponentsPerSplat; var bytesPerSplat = bytesPerCenter + bytesPerScale + bytesPerRotation + bytesPerColor + sphericalHarmonicsBytesPerSplat; return { bytesPerCenter, bytesPerScale, bytesPerRotation, bytesPerColor, sphericalHarmonicsComponentsPerSplat, sphericalHarmonicsBytesPerSplat, bytesPerSplat }; } linkBufferArrays() { for (var i = 0; i < this.maxSectionCount; i++) { var section = this.sections[i]; section.bucketArray = new Float32Array(this.bufferData, section.bucketsBase, section.bucketCount * SplatBuffer.BucketStorageSizeFloats); if (section.partiallyFilledBucketCount > 0) { section.partiallyFilledBucketLengths = new Uint32Array(this.bufferData, section.base, section.partiallyFilledBucketCount); } } } buildMaps() { var cumulativeSplatCount = 0; for (var i = 0; i < this.maxSectionCount; i++) { var section = this.sections[i]; for (var j = 0; j < section.maxSplatCount; j++) { var globalSplatIndex = cumulativeSplatCount + j; this.globalSplatIndexToLocalSplatIndexMap[globalSplatIndex] = j; this.globalSplatIndexToSectionMap[globalSplatIndex] = i; } cumulativeSplatCount += section.maxSplatCount; } } updateLoadedCounts(newSectionCount, newSplatCount) { SplatBuffer.writeHeaderCountsToBuffer(newSectionCount, newSplatCount, this.bufferData); this.sectionCount = newSectionCount; this.splatCount = newSplatCount; } updateSectionLoadedCounts(sectionIndex, newSplatCount) { var sectionHeaderOffset = SplatBuffer.HeaderSizeBytes + SplatBuffer.SectionHeaderSizeBytes * sectionIndex; SplatBuffer.writeSectionHeaderSplatCountToBuffer(newSplatCount, this.bufferData, sectionHeaderOffset); this.sections[sectionIndex].splatCount = newSplatCount; } static generateFromUncompressedSplatArrays(splatArrays, minimumAlpha, compressionLevel, sceneCenter, blockSize, bucketSize) { var options = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : []; var copyBetweenBuffers = function copyBetweenBuffers(srcBuffer, srcOffset, destBuffer, destOffset) { var byteCount = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; var src = new Uint8Array(srcBuffer, srcOffset); var dest = new Uint8Array(destBuffer, destOffset); for (var i = 0; i < byteCount; i++) { dest[i] = src[i]; } }; var sphericalHarmonicsDegree = 0; for (var sa = 0; sa < splatArrays.length; sa++) { var splatArray = splatArrays[sa]; if (sa === 0 || splatArray.sphericalHarmonicsDegree < sphericalHarmonicsDegree) { if (sa > 0 && splatArray.sphericalHarmonicsDegree !== sphericalHarmonicsDegree) { var msg = 'SplatBuffer::generateFromUncompressedSplatArrays() -> ' + 'all splat arrays must have the same spherical harmonics degree.'; throw new Error(msg); } sphericalHarmonicsDegree = splatArray.sphericalHarmonicsDegree; } } var { bytesPerCenter, bytesPerScale, bytesPerRotation, bytesPerColor, sphericalHarmonicsComponentsPerSplat, sphericalHarmonicsBytesPerSplat, bytesPerSplat } = SplatBuffer.calculateComponentStorage(compressionLevel, sphericalHarmonicsDegree); var compressionScaleRange = SplatBuffer.CompressionLevels[compressionLevel].ScaleRange; var sectionBuffers = []; var sectionHeaderBuffers = []; var totalSplatCount = 0; var tempRotation = new Quaternion(); for (var _sa = 0; _sa < splatArrays.length; _sa++) { var _splatArray = splatArrays[_sa]; var sectionOptions = options[_sa] || {}; var sectionBlockSize = (sectionOptions.blockSizeFactor || 1) * (blockSize || SplatBuffer.BucketBlockSize); var sectionBucketSize = Math.ceil((sectionOptions.bucketSizeFactor || 1) * (bucketSize || SplatBuffer.BucketSize)); var validSplats = new UncompressedSplatArray(sphericalHarmonicsDegree); for (var i = 0; i < _splatArray.splatCount; i++) { var targetSplat = _splatArray.splats[i]; var alpha = void 0; if (targetSplat[UncompressedSplatArray.OFFSET.OPACITY]) { alpha = targetSplat[UncompressedSplatArray.OFFSET.OPACITY]; } else { alpha = 255; } if (alpha >= minimumAlpha) { validSplats.addSplat(targetSplat); } } var bucketInfo = SplatBuffer.computeBucketsForUncompressedSplatArray(validSplats, sectionBlockSize, sectionBucketSize); var fullBucketCount = bucketInfo.fullBuckets.length; var partiallyFullBucketLengths = bucketInfo.partiallyFullBuckets.map(bucket => bucket.splats.length); var partiallyFilledBucketCount = partiallyFullBucketLengths.length; var buckets = [...bucketInfo.fullBuckets, ...bucketInfo.partiallyFullBuckets]; var sectionDataSizeBytes = validSplats.splats.length * bytesPerSplat; var bucketMetaDataSizeBytes = partiallyFilledBucketCount * 4; var bucketDataBytes = compressionLevel >= 1 ? buckets.length * SplatBuffer.BucketStorageSizeBytes + bucketMetaDataSizeBytes : 0; var sectionSizeBytes = sectionDataSizeBytes + bucketDataBytes; var sectionBuffer = new ArrayBuffer(sectionSizeBytes); var blockHalfSize = sectionBlockSize / 2.0; var compressionScaleFactor = compressionScaleRange / blockHalfSize; var doubleCompressionScaleRange = compressionScaleRange * 2 + 1; var tempCenterBuffer = new ArrayBuffer(bytesPerCenter); var tempScaleBuffer = new ArrayBuffer(bytesPerScale); var tempRotationBuffer = new ArrayBuffer(bytesPerRotation); var tempColorBuffer = new ArrayBuffer(bytesPerColor); var tempSHBuffer = new ArrayBuffer(sphericalHarmonicsBytesPerSplat); var bucketCenter = new Vector3(); var bucketCenterDelta = new Vector3(); var outSplatCount = 0; for (var b = 0; b < buckets.length; b++) { var bucket = buckets[b]; bucketCenter.fromArray(bucket.center); for (var _i7 = 0; _i7 < bucket.splats.length; _i7++) { var row = bucket.splats[_i7]; var _targetSplat = validSplats.splats[row]; var centerBase = bucketDataBytes + outSplatCount * bytesPerSplat; var scaleBase = centerBase + bytesPerCenter; var rotationBase = scaleBase + bytesPerScale; var colorBase = rotationBase + bytesPerRotation; var sphericalHarmonicsBase = colorBase + bytesPerColor; if (compressionLevel === 0) { var center = new Float32Array(sectionBuffer, centerBase, SplatBuffer.CenterComponentCount); var rot = new Float32Array(sectionBuffer, rotationBase, SplatBuffer.RotationComponentCount); var scale = new Float32Array(sectionBuffer, scaleBase, SplatBuffer.ScaleComponentCount); if (_targetSplat[UncompressedSplatArray.OFFSET.SCALE0] !== undefined) { tempRotation.set(_targetSplat[UncompressedSplatArray.OFFSET.ROTATION0], _targetSplat[UncompressedSplatArray.OFFSET.ROTATION1], _targetSplat[UncompressedSplatArray.OFFSET.ROTATION2], _targetSplat[UncompressedSplatArray.OFFSET.ROTATION3]); tempRotation.normalize(); rot.set([tempRotation.x, tempRotation.y, tempRotation.z, tempRotation.w]); scale.set([_targetSplat[UncompressedSplatArray.OFFSET.SCALE0], _targetSplat[UncompressedSplatArray.OFFSET.SCALE1], _targetSplat[UncompressedSplatArray.OFFSET.SCALE2]]); } else { rot.set([1.0, 0.0, 0.0, 0.0]); scale.set([0.01, 0.01, 0.01]); } center.set([_targetSplat[UncompressedSplatArray.OFFSET.X], _targetSplat[UncompressedSplatArray.OFFSET.Y], _targetSplat[UncompressedSplatArray.OFFSET.Z]]); if (sphericalHarmonicsDegree > 0) { var shOut = new Float32Array(sectionBuffer, sphericalHarmonicsBase, sphericalHarmonicsComponentsPerSplat); if (sphericalHarmonicsDegree >= 1) { for (var s = 0; s < 9; s++) shOut[s] = _targetSplat[UncompressedSplatArray.OFFSET.FRC0 + s]; if (sphericalHarmonicsDegree >= 2) { for (var _s = 0; _s < 15; _s++) shOut[_s + 9] = _targetSplat[UncompressedSplatArray.OFFSET.FRC9 + _s]; } } } } else { var _center = new Uint16Array(tempCenterBuffer, 0, SplatBuffer.CenterComponentCount); var _rot = new Uint16Array(tempRotationBuffer, 0, SplatBuffer.RotationComponentCount); var _scale = new Uint16Array(tempScaleBuffer, 0, SplatBuffer.ScaleComponentCount); if (_targetSplat[UncompressedSplatArray.OFFSET.SCALE0] !== undefined) { tempRotation.set(_targetSplat[UncompressedSplatArray.OFFSET.ROTATION0], _targetSplat[UncompressedSplatArray.OFFSET.ROTATION1], _targetSplat[UncompressedSplatArray.OFFSET.ROTATION2], _targetSplat[UncompressedSplatArray.OFFSET.ROTATION3]); tempRotation.normalize(); _rot.set([toHalfFloat(tempRotation.x), toHalfFloat(tempRotation.y), toHalfFloat(tempRotation.z), toHalfFloat(tempRotation.w)]); _scale.set([toHalfFloat(_targetSplat[UncompressedSplatArray.OFFSET.SCALE0]), toHalfFloat(_targetSplat[UncompressedSplatArray.OFFSET.SCALE1]), toHalfFloat(_targetSplat[UncompressedSplatArray.OFFSET.SCALE2])]); } else { _rot.set([toHalfFloat(1.), 0, 0, 0]); _scale.set([toHalfFloat(0.01), toHalfFloat(0.01), toHalfFloat(0.01)]); } bucketCenterDelta.set(_targetSplat[UncompressedSplatArray.OFFSET.X], _targetSplat[UncompressedSplatArray.OFFSET.Y], _targetSplat[UncompressedSplatArray.OFFSET.Z]).sub(bucketCenter); bucketCenterDelta.x = Math.round(bucketCenterDelta.x * compressionScaleFactor) + compressionScaleRange; bucketCenterDelta.x = clamp(bucketCenterDelta.x, 0, doubleCompressionScaleRange); bucketCenterDelta.y = Math.round(bucketCenterDelta.y * compressionScaleFactor) + compressionScaleRange; bucketCenterDelta.y = clamp(bucketCenterDelta.y, 0, doubleCompressionScaleRange); bucketCenterDelta.z = Math.round(bucketCenterDelta.z * compressionScaleFactor) + compressionScaleRange; bucketCenterDelta.z = clamp(bucketCenterDelta.z, 0, doubleCompressionScaleRange); _center.set([bucketCenterDelta.x, bucketCenterDelta.y, bucketCenterDelta.z]); if (sphericalHarmonicsDegree > 0) { var SHArrayType = compressionLevel === 1 ? Uint16Array : Uint8Array; var bytesPerSHComponent = compressionLevel === 1 ? 2 : 1; var _shOut = new SHArrayType(tempSHBuffer, 0, sphericalHarmonicsComponentsPerSplat); if (sphericalHarmonicsDegree >= 1) { for (var _s2 = 0; _s2 < 9; _s2++) { var srcVal = _targetSplat[UncompressedSplatArray.OFFSET.FRC0 + _s2]; _shOut[_s2] = compressionLevel === 1 ? toHalfFloat(srcVal) : toUint8(srcVal); } var degree1ByteCount = 9 * bytesPerSHComponent; copyBetweenBuffers(_shOut.buffer, 0, sectionBuffer, sphericalHarmonicsBase, degree1ByteCount); if (sphericalHarmonicsDegree >= 2) { for (var _s3 = 0; _s3 < 15; _s3++) { var _srcVal = _targetSplat[UncompressedSplatArray.OFFSET.FRC9 + _s3]; _shOut[_s3 + 9] = compressionLevel === 1 ? toHalfFloat(_srcVal) : toUint8(_srcVal); } var degree2ByteCount = 15 * bytesPerSHComponent; copyBetweenBuffers(_shOut.buffer, degree1ByteCount, sectionBuffer, sphericalHarmonicsBase + degree1ByteCount, degree2ByteCount); } } } copyBetweenBuffers(_center.buffer, 0, sectionBuffer, centerBase, 6); copyBetweenBuffers(_scale.buffer, 0, sectionBuffer, scaleBase, 6); copyBetweenBuffers(_rot.buffer, 0, sectionBuffer, rotationBase, 8); } var rgba = new Uint8ClampedArray(tempColorBuffer, 0, 4); if (_targetSplat[UncompressedSplatArray.OFFSET.FDC0] !== undefined) { rgba.set([_targetSplat[UncompressedSplatArray.OFFSET.FDC0], _targetSplat[UncompressedSplatArray.OFFSET.FDC1], _targetSplat[UncompressedSplatArray.OFFSET.FDC2]]); } else { rgba.set([255, 0, 0]); } if (_targetSplat[UncompressedSplatArray.OFFSET.OPACITY] !== undefined) { rgba[3] = _targetSplat[UncompressedSplatArray.OFFSET.OPACITY]; } else { rgba[3] = 255; } copyBetweenBuffers(rgba.buffer, 0, sectionBuffer, colorBase, 4); outSplatCount++; } } totalSplatCount += outSplatCount; if (compressionLevel >= 1) { var bucketMetaDataArray = new Uint32Array(sectionBuffer, 0, partiallyFullBucketLengths.length * 4); for (var pfb = 0; pfb < partiallyFullBucketLengths.length; pfb++) { bucketMetaDataArray[pfb] = partiallyFullBucketLengths[pfb]; } var bucketArray = new Float32Array(sectionBuffer, bucketMetaDataSizeBytes, buckets.length * SplatBuffer.BucketStorageSizeFloats); for (var _b = 0; _b < buckets.length; _b++) { var _bucket = buckets[_b]; var base = _b * 3; bucketArray[base] = _bucket.center[0]; bucketArray[base + 1] = _bucket.center[1]; bucketArray[base + 2] = _bucket.center[2]; } } sectionBuffers.push(sectionBuffer); var sectionHeaderBuffer = new ArrayBuffer(SplatBuffer.SectionHeaderSizeBytes); SplatBuffer.writeSectionHeaderToBuffer({ maxSplatCount: outSplatCount, splatCount: outSplatCount, bucketSize: sectionBucketSize, bucketCount: buckets.length, bucketBlockSize: sectionBlockSize, compressionScaleRange: compressionScaleRange, storageSizeBytes: sectionSizeBytes, fullBucketCount: fullBucketCount, partiallyFilledBucketCount: partiallyFilledBucketCount, sphericalHarmonicsDegree: sphericalHarmonicsDegree }, compressionLevel, sectionHeaderBuffer, 0); sectionHeaderBuffers.push(sectionHeaderBuffer); } var sectionsCumulativeSizeBytes = 0; for (var _sectionBuffer of sectionBuffers) sectionsCumulativeSizeBytes += _sectionBuffer.byteLength; var unifiedBufferSize = SplatBuffer.HeaderSizeBytes + SplatBuffer.SectionHeaderSizeBytes * sectionBuffers.length + sectionsCumulativeSizeBytes; var unifiedBuffer = new ArrayBuffer(unifiedBufferSize); SplatBuffer.writeHeaderToBuffer({ versionMajor: 0, versionMinor: 1, maxSectionCount: sectionBuffers.length, sectionCount: sectionBuffers.length, maxSplatCount: totalSplatCount, splatCount: totalSplatCount, compressionLevel: compressionLevel, sceneCenter: sceneCenter }, unifiedBuffer); var currentUnifiedBase = SplatBuffer.HeaderSizeBytes; for (var _sectionHeaderBuffer of sectionHeaderBuffers) { new Uint8Array(unifiedBuffer, currentUnifiedBase, SplatBuffer.SectionHeaderSizeBytes).set(new Uint8Array(_sectionHeaderBuffer)); currentUnifiedBase += SplatBuffer.SectionHeaderSizeBytes; } for (var _sectionBuffer2 of sectionBuffers) { new Uint8Array(unifiedBuffer, currentUnifiedBase, _sectionBuffer2.byteLength).set(new Uint8Array(_sectionBuffer2)); currentUnifiedBase += _sectionBuffer2.byteLength; } var splatBuffer = new SplatBuffer(unifiedBuffer); return splatBuffer; } static computeBucketsForUncompressedSplatArray(splatArray, blockSize, bucketSize) { var splatCount = splatArray.splatCount; var halfBlockSize = blockSize / 2.0; var min = new Vector3(); var max = new Vector3(); for (var i = 0; i < splatCount; i++) { var targetSplat = splatArray.splats[i]; var center = [targetSplat[UncompressedSplatArray.OFFSET.X], targetSplat[UncompressedSplatArray.OFFSET.Y], targetSplat[UncompressedSplatArray.OFFSET.Z]]; if (i === 0 || center[0] < min.x) min.x = center[0]; if (i === 0 || center[0] > max.x) max.x = center[0]; if (i === 0 || center[1] < min.y) min.y = center[1]; if (i === 0 || center[1] > max.y) max.y = center[1]; if (i === 0 || center[2] < min.z) min.z = center[2]; if (i === 0 || center[2] > max.z) max.z = center[2]; } var dimensions = new Vector3().copy(max).sub(min); var yBlocks = Math.ceil(dimensions.y / blockSize); var zBlocks = Math.ceil(dimensions.z / blockSize); var blockCenter = new Vector3(); var fullBuckets = []; var partiallyFullBuckets = {}; for (var _i8 = 0; _i8 < splatCount; _i8++) { var _targetSplat2 = splatArray.splats[_i8]; var _center2 = [_targetSplat2[UncompressedSplatArray.OFFSET.X], _targetSplat2[UncompressedSplatArray.OFFSET.Y], _targetSplat2[UncompressedSplatArray.OFFSET.Z]]; var xBlock = Math.floor((_center2[0] - min.x) / blockSize); var yBlock = Math.floor((_center2[1] - min.y) / blockSize); var zBlock = Math.floor((_center2[2] - min.z) / blockSize); blockCenter.x = xBlock * blockSize + min.x + halfBlockSize; blockCenter.y = yBlock * blockSize + min.y + halfBlockSize; blockCenter.z = zBlock * blockSize + min.z + halfBlockSize; var bucketId = xBlock * (yBlocks * zBlocks) + yBlock * zBlocks + zBlock; var bucket = partiallyFullBuckets[bucketId]; if (!bucket) { partiallyFullBuckets[bucketId] = bucket = { 'splats': [], 'center': blockCenter.toArray() }; } bucket.splats.push(_i8); if (bucket.splats.length >= bucketSize) { fullBuckets.push(bucket); partiallyFullBuckets[bucketId] = null; } } var partiallyFullBucketArray = []; for (var _bucketId in partiallyFullBuckets) { if (partiallyFullBuckets.hasOwnProperty(_bucketId)) { var _bucket2 = partiallyFullBuckets[_bucketId]; if (_bucket2) { partiallyFullBucketArray.push(_bucket2); } } } return { 'fullBuckets': fullBuckets, 'partiallyFullBuckets': partiallyFullBucketArray }; } } _SplatBuffer = SplatBuffer; _defineProperty(SplatBuffer, "CurrentMajorVersion", 0); _defineProperty(SplatBuffer, "CurrentMinorVersion", 1); _defineProperty(SplatBuffer, "CenterComponentCount", 3); _defineProperty(SplatBuffer, "ScaleComponentCount", 3); _defineProperty(SplatBuffer, "RotationComponentCount", 4); _defineProperty(SplatBuffer, "ColorComponentCount", 4); _defineProperty(SplatBuffer, "CovarianceComponentCount", 6); _defineProperty(SplatBuffer, "SplatScaleOffsetFloat", 3); _defineProperty(SplatBuffer, "SplatRotationOffsetFloat", 6); _defineProperty(SplatBuffer, "CompressionLevels", { 0: { BytesPerCenter: 12, BytesPerScale: 12, BytesPerRotation: 16, BytesPerColor: 4, ScaleOffsetBytes: 12, RotationffsetBytes: 24, ColorOffsetBytes: 40, SphericalHarmonicsOffsetBytes: 44, ScaleRange: 1, BytesPerSphericalHarmonicsComponent: 4, SphericalHarmonicsOffsetFloat: 11, SphericalHarmonicsDegrees: { 0: { BytesPerSplat: 44 }, 1: { BytesPerSplat: 80 }, 2: { BytesPerSplat: 140 } } }, 1: { BytesPerCenter: 6, BytesPerScale: 6, BytesPerRotation: 8, BytesPerColor: 4, ScaleOffsetBytes: 6, RotationffsetBytes: 12, ColorOffsetBytes: 20, SphericalHarmonicsOffsetBytes: 24, ScaleRange: 32767, BytesPerSphericalHarmonicsComponent: 2, SphericalHarmonicsOffsetFloat: 12, SphericalHarmonicsDegrees: { 0: { BytesPerSplat: 24 }, 1: { BytesPerSplat: 42 }, 2: { BytesPerSplat: 72 } } }, 2: { BytesPerCenter: 6, BytesPerScale: 6, BytesPerRotation: 8, BytesPerColor: 4, ScaleOffsetBytes: 6, RotationffsetBytes: 12, ColorOffsetBytes: 20, SphericalHarmonicsOffsetBytes: 24, ScaleRange: 32767, BytesPerSphericalHarmonicsComponent: 1, SphericalHarmonicsOffsetFloat: 12, SphericalHarmonicsDegrees: { 0: { BytesPerSplat: 24 }, 1: { BytesPerSplat: 33 }, 2: { BytesPerSplat: 48 } } } }); _defineProperty(SplatBuffer, "CovarianceSizeFloats", 6); _defineProperty(SplatBuffer, "HeaderSizeBytes", 4096); _defineProperty(SplatBuffer, "SectionHeaderSizeBytes", 1024); _defineProperty(SplatBuffer, "BucketStorageSizeBytes", 12); _defineProperty(SplatBuffer, "BucketStorageSizeFloats", 3); _defineProperty(SplatBuffer, "BucketBlockSize", 5.0); _defineProperty(SplatBuffer, "BucketSize", 256); _defineProperty(SplatBuffer, "computeCovariance", function () { //通过旋转和缩放计算协方差(决定姿态)得到6个数 var tempMatrix4 = new Matrix4(); var scaleMatrix = new Matrix3(); var rotationMatrix = new Matrix3(); var covarianceMatrix = new Matrix3(); var transformedCovariance = new Matrix3(); var transform3x3 = new Matrix3(); var transform3x3Transpose = new Matrix3(); return function (scale, rotation, transform, outCovariance) { var outOffset = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; var desiredOutputCompressionLevel = arguments.length > 5 ? arguments[5] : undefined; tempMatrix4.makeScale(scale.x, scale.y, scale.z); scaleMatrix.setFromMatrix4(tempMatrix4); tempMatrix4.makeRotationFromQuaternion(rotation); rotationMatrix.setFromMatrix4(tempMatrix4); covarianceMatrix.copy(rotationMatrix).multiply(scaleMatrix); transformedCovariance.copy(covarianceMatrix).transpose().premultiply(covarianceMatrix); //为什么要乘以自己的转置呀? if (transform) { //场景的整体transform transform3x3.setFromMatrix4(transform); transform3x3Transpose.copy(transform3x3).transpose(); transformedCovariance.multiply(transform3x3Transpose); transformedCovariance.premultiply(transform3x3); } if (desiredOutputCompressionLevel >= 1) { //压缩 outCovariance[outOffset] = toHalfFloat(transformedCovariance.elements[0]); outCovariance[outOffset + 1] = toHalfFloat(transformedCovariance.elements[3]); outCovariance[outOffset + 2] = toHalfFloat(transformedCovariance.elements[6]); outCovariance[outOffset + 3] = toHalfFloat(transformedCovariance.elements[4]); outCovariance[outOffset + 4] = toHalfFloat(transformedCovariance.elements[7]); outCovariance[outOffset + 5] = toHalfFloat(transformedCovariance.elements[8]); } else { outCovariance[outOffset] = transformedCovariance.elements[0]; outCovariance[outOffset + 1] = transformedCovariance.elements[3]; outCovariance[outOffset + 2] = transformedCovariance.elements[6]; outCovariance[outOffset + 3] = transformedCovariance.elements[4]; outCovariance[outOffset + 4] = transformedCovariance.elements[7]; outCovariance[outOffset + 5] = transformedCovariance.elements[8]; } }; }()); _defineProperty(SplatBuffer, "dot3", (v1, v2, v3, transformRow, outArray) => { outArray[0] = outArray[1] = outArray[2] = 0; var t0 = transformRow[0]; var t1 = transformRow[1]; var t2 = transformRow[2]; _SplatBuffer.addInto3(v1[0] * t0, v1[1] * t0, v1[2] * t0, outArray); _SplatBuffer.addInto3(v2[0] * t1, v2[1] * t1, v2[2] * t1, outArray); _SplatBuffer.addInto3(v3[0] * t2, v3[1] * t2, v3[2] * t2, outArray); }); _defineProperty(SplatBuffer, "addInto3", (val1, val2, val3, destArray) => { destArray[0] = destArray[0] + val1; destArray[1] = destArray[1] + val2; destArray[2] = destArray[2] + val3; }); _defineProperty(SplatBuffer, "dot5", (v1, v2, v3, v4, v5, transformRow, outArray) => { outArray[0] = outArray[1] = outArray[2] = 0; var t0 = transformRow[0]; var t1 = transformRow[1]; var t2 = transformRow[2]; var t3 = transformRow[3]; var t4 = transformRow[4]; _SplatBuffer.addInto3(v1[0] * t0, v1[1] * t0, v1[2] * t0, outArray); _SplatBuffer.addInto3(v2[0] * t1, v2[1] * t1, v2[2] * t1, outArray); _SplatBuffer.addInto3(v3[0] * t2, v3[1] * t2, v3[2] * t2, outArray); _SplatBuffer.addInto3(v4[0] * t3, v4[1] * t3, v4[2] * t3, outArray); _SplatBuffer.addInto3(v5[0] * t4, v5[1] * t4, v5[2] * t4, outArray); }); _defineProperty(SplatBuffer, "rotateSphericalHarmonics3", (in1, in2, in3, tsh11, tsh12, tsh13, out1, out2, out3) => { _SplatBuffer.dot3(in1, in2, in3, tsh11, out1); _SplatBuffer.dot3(in1, in2, in3, tsh12, out2); _SplatBuffer.dot3(in1, in2, in3, tsh13, out3); }); _defineProperty(SplatBuffer, "rotateSphericalHarmonics5", (in1, in2, in3, in4, in5, tsh11, tsh12, tsh13, tsh21, tsh22, tsh23, tsh24, tsh25, out1, out2, out3, out4, out5) => { var kSqrt0104 = Math.sqrt(1.0 / 4.0); var kSqrt0304 = Math.sqrt(3.0 / 4.0); var kSqrt0103 = Math.sqrt(1.0 / 3.0); var kSqrt0403 = Math.sqrt(4.0 / 3.0); var kSqrt0112 = Math.sqrt(1.0 / 12.0); tsh21[0] = kSqrt0104 * (tsh13[2] * tsh11[0] + tsh13[0] * tsh11[2] + (tsh11[2] * tsh13[0] + tsh11[0] * tsh13[2])); tsh21[1] = tsh13[1] * tsh11[0] + tsh11[1] * tsh13[0]; tsh21[2] = kSqrt0304 * (tsh13[1] * tsh11[1] + tsh11[1] * tsh13[1]); tsh21[3] = tsh13[1] * tsh11[2] + tsh11[1] * tsh13[2]; tsh21[4] = kSqrt0104 * (tsh13[2] * tsh11[2] - tsh13[0] * tsh11[0] + (tsh11[2] * tsh13[2] - tsh11[0] * tsh13[0])); _SplatBuffer.dot5(in1, in2, in3, in4, in5, tsh21, out1); tsh22[0] = kSqrt0104 * (tsh12[2] * tsh11[0] + tsh12[0] * tsh11[2] + (tsh11[2] * tsh12[0] + tsh11[0] * tsh12[2])); tsh22[1] = tsh12[1] * tsh11[0] + tsh11[1] * tsh12[0]; tsh22[2] = kSqrt0304 * (tsh12[1] * tsh11[1] + tsh11[1] * tsh12[1]); tsh22[3] = tsh12[1] * tsh11[2] + tsh11[1] * tsh12[2]; tsh22[4] = kSqrt0104 * (tsh12[2] * tsh11[2] - tsh12[0] * tsh11[0] + (tsh11[2] * tsh12[2] - tsh11[0] * tsh12[0])); _SplatBuffer.dot5(in1, in2, in3, in4, in5, tsh22, out2); tsh23[0] = kSqrt0103 * (tsh12[2] * tsh12[0] + tsh12[0] * tsh12[2]) + -kSqrt0112 * (tsh13[2] * tsh13[0] + tsh13[0] * tsh13[2] + (tsh11[2] * tsh11[0] + tsh11[0] * tsh11[2])); tsh23[1] = kSqrt0403 * tsh12[1] * tsh12[0] + -kSqrt0103 * (tsh13[1] * tsh13[0] + tsh11[1] * tsh11[0]); tsh23[2] = tsh12[1] * tsh12[1] + -kSqrt0104 * (tsh13[1] * tsh13[1] + tsh11[1] * tsh11[1]); tsh23[3] = kSqrt0403 * tsh12[1] * tsh12[2] + -kSqrt0103 * (tsh13[1] * tsh13[2] + tsh11[1] * tsh11[2]); tsh23[4] = kSqrt0103 * (tsh12[2] * tsh12[2] - tsh12[0] * tsh12[0]) + -kSqrt0112 * (tsh13[2] * tsh13[2] - tsh13[0] * tsh13[0] + (tsh11[2] * tsh11[2] - tsh11[0] * tsh11[0])); _SplatBuffer.dot5(in1, in2, in3, in4, in5, tsh23, out3); tsh24[0] = kSqrt0104 * (tsh12[2] * tsh13[0] + tsh12[0] * tsh13[2] + (tsh13[2] * tsh12[0] + tsh13[0] * tsh12[2])); tsh24[1] = tsh12[1] * tsh13[0] + tsh13[1] * tsh12[0]; tsh24[2] = kSqrt0304 * (tsh12[1] * tsh13[1] + tsh13[1] * tsh12[1]); tsh24[3] = tsh12[1] * tsh13[2] + tsh13[1] * tsh12[2]; tsh24[4] = kSqrt0104 * (tsh12[2] * tsh13[2] - tsh12[0] * tsh13[0] + (tsh13[2] * tsh12[2] - tsh13[0] * tsh12[0])); _SplatBuffer.dot5(in1, in2, in3, in4, in5, tsh24, out4); tsh25[0] = kSqrt0104 * (tsh13[2] * tsh13[0] + tsh13[0] * tsh13[2] - (tsh11[2] * tsh11[0] + tsh11[0] * tsh11[2])); tsh25[1] = tsh13[1] * tsh13[0] - tsh11[1] * tsh11[0]; tsh25[2] = kSqrt0304 * (tsh13[1] * tsh13[1] - tsh11[1] * tsh11[1]); tsh25[3] = tsh13[1] * tsh13[2] - tsh11[1] * tsh11[2]; tsh25[4] = kSqrt0104 * (tsh13[2] * tsh13[2] - tsh13[0] * tsh13[0] - (tsh11[2] * tsh11[2] - tsh11[0] * tsh11[0])); _SplatBuffer.dot5(in1, in2, in3, in4, in5, tsh25, out5); }); var HeaderMagicBytes = new Uint8Array([112, 108, 121, 10]); var HeaderEndTokenBytes = new Uint8Array([10, 101, 110, 100, 95, 104, 101, 97, 100, 101, 114, 10]); var HeaderEndToken = 'end_header'; var DataTypeMap = new Map([['char', Int8Array], ['uchar', Uint8Array], ['short', Int16Array], ['ushort', Uint16Array], ['int', Int32Array], ['uint', Uint32Array], ['float', Float32Array], ['double', Float64Array]]); var unpackUnorm = (value, bits) => { var t = (1 << bits) - 1; return (value & t) / t; }; var unpack111011 = (result, value) => { result.x = unpackUnorm(value >>> 21, 11); result.y = unpackUnorm(value >>> 11, 10); result.z = unpackUnorm(value, 11); }; var unpack8888 = (result, value) => { result.x = unpackUnorm(value >>> 24, 8); result.y = unpackUnorm(value >>> 16, 8); result.z = unpackUnorm(value >>> 8, 8); result.w = unpackUnorm(value, 8); }; // unpack quaternion with 2,10,10,10 format (largest element, 3x10bit element) var unpackRot = (result, value) => { var norm = 1.0 / (Math.sqrt(2) * 0.5); var a = (unpackUnorm(value >>> 20, 10) - 0.5) * norm; var b = (unpackUnorm(value >>> 10, 10) - 0.5) * norm; var c = (unpackUnorm(value, 10) - 0.5) * norm; var m = Math.sqrt(1.0 - (a * a + b * b + c * c)); switch (value >>> 30) { case 0: result.set(m, a, b, c); break; case 1: result.set(a, m, b, c); break; case 2: result.set(a, b, m, c); break; case 3: result.set(a, b, c, m); break; } }; var lerp$1 = (a, b, t) => { return a * (1 - t) + b * t; }; var getElementPropStorage = (element, name) => { var _element$properties$f; return (_element$properties$f = element.properties.find(p => p.name === name && p.storage)) === null || _element$properties$f === void 0 ? void 0 : _element$properties$f.storage; }; class CompressedPlyParser { static decodeHeaderText(headerText) { var element; var chunkElement; var vertexElement; var headerLines = headerText.split('\n').filter(line => !line.startsWith('comment ')); var bytesPerSplat = 0; var done = false; for (var i = 1; i < headerLines.length; ++i) { var words = headerLines[i].split(' '); switch (words[0]) { case 'format': if (words[1] !== 'binary_little_endian') { throw new Error('Unsupported ply format'); } break; case 'element': element = { name: words[1], count: parseInt(words[2], 10), properties: [], storageSizeBytes: 0 }; if (element.name === 'chunk') chunkElement = element;else if (element.name === 'vertex') vertexElement = element; break; case 'property': { if (!DataTypeMap.has(words[1])) { throw new Error("Unrecognized property data type '".concat(words[1], "' in ply header")); } var StorageType = DataTypeMap.get(words[1]); var storageSizeByes = StorageType.BYTES_PER_ELEMENT * element.count; if (element.name === 'vertex') bytesPerSplat += StorageType.BYTES_PER_ELEMENT; element.properties.push({ type: words[1], name: words[2], storage: null, byteSize: StorageType.BYTES_PER_ELEMENT, storageSizeByes: storageSizeByes }); element.storageSizeBytes += storageSizeByes; break; } case HeaderEndToken: done = true; break; default: throw new Error("Unrecognized header value '".concat(words[0], "' in ply header")); } if (done) break; } return { 'chunkElement': chunkElement, 'vertexElement': vertexElement, 'bytesPerSplat': bytesPerSplat, 'headerSizeBytes': headerText.indexOf(HeaderEndToken) + HeaderEndToken.length + 1 }; } static decodeHeader(plyBuffer) { /** * Searches for the first occurrence of a sequence within a buffer. * @example * find(new Uint8Array([1, 2, 3, 4]), new Uint8Array([3, 4])); // 2 * @param {Uint8Array} buf - The buffer in which to search. * @param {Uint8Array} search - The sequence to search for. * @return {number} The index of the first occurrence of the search sequence in the buffer, or -1 if not found. */ var find = (buf, search) => { var endIndex = buf.length - search.length; var i; var j; for (i = 0; i <= endIndex; ++i) { for (j = 0; j < search.length; ++j) { if (buf[i + j] !== search[j]) { break; } } if (j === search.length) { return i; } } return -1; }; /** * Checks if array 'a' starts with the same elements as array 'b'. * @example * startsWith(new Uint8Array([1, 2, 3, 4]), new Uint8Array([1, 2])); // true * @param {Uint8Array} a - The array to check against. * @param {Uint8Array} b - The array of elements to look for at the start of 'a'. * @return {boolean} - True if 'a' starts with all elements of 'b', otherwise false. */ var startsWith = (a, b) => { if (a.length < b.length) { return false; } for (var i = 0; i < b.length; ++i) { if (a[i] !== b[i]) { return false; } } return true; }; var buf = new Uint8Array(plyBuffer); var endHeaderTokenOffset; if (buf.length >= HeaderMagicBytes.length && !startsWith(buf, HeaderMagicBytes)) { throw new Error('Invalid PLY header'); } endHeaderTokenOffset = find(buf, HeaderEndTokenBytes); if (endHeaderTokenOffset === -1) { throw new Error('End of PLY header not found'); } var headerText = new TextDecoder('ascii').decode(buf.slice(0, endHeaderTokenOffset)); var { chunkElement, vertexElement, bytesPerSplat } = CompressedPlyParser.decodeHeaderText(headerText); return { 'headerSizeBytes': endHeaderTokenOffset + HeaderEndTokenBytes.length, 'bytesPerSplat': bytesPerSplat, 'chunkElement': chunkElement, 'vertexElement': vertexElement }; } static readElementData(element, readBuffer, readOffset, fromIndex, toIndex) { var propertyFilter = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; var dataView = readBuffer instanceof DataView ? readBuffer : new DataView(readBuffer); fromIndex = fromIndex || 0; toIndex = toIndex || element.count - 1; for (var e = fromIndex; e <= toIndex; ++e) { for (var j = 0; j < element.properties.length; ++j) { var property = element.properties[j]; var StorageType = DataTypeMap.get(property.type); var requiredStorageSizeBytes = StorageType.BYTES_PER_ELEMENT * element.count; if ((!property.storage || property.storage.byteLength < requiredStorageSizeBytes) && (!propertyFilter || propertyFilter(property.name))) { property.storage = new StorageType(element.count); } if (property.storage) { switch (property.type) { case 'char': property.storage[e] = dataView.getInt8(readOffset); break; case 'uchar': property.storage[e] = dataView.getUint8(readOffset); break; case 'short': property.storage[e] = dataView.getInt16(readOffset, true); break; case 'ushort': property.storage[e] = dataView.getUint16(readOffset, true); break; case 'int': property.storage[e] = dataView.getInt32(readOffset, true); break; case 'uint': property.storage[e] = dataView.getUint32(readOffset, true); break; case 'float': property.storage[e] = dataView.getFloat32(readOffset, true); break; case 'double': property.storage[e] = dataView.getFloat64(readOffset, true); break; } } readOffset += property.byteSize; } } return readOffset; } static readPly(plyBuffer) { var propertyFilter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var header = CompressedPlyParser.decodeHeader(plyBuffer); var readIndex = CompressedPlyParser.readElementData(header.chunkElement, plyBuffer, header.headerSizeBytes, null, null, propertyFilter); CompressedPlyParser.readElementData(header.vertexElement, plyBuffer, readIndex, null, null, propertyFilter); return { 'chunkElement': header.chunkElement, 'vertexElement': header.vertexElement }; } static getElementStorageArrays(chunkElement, vertexElement) { var minX = getElementPropStorage(chunkElement, 'min_x'); var minY = getElementPropStorage(chunkElement, 'min_y'); var minZ = getElementPropStorage(chunkElement, 'min_z'); var maxX = getElementPropStorage(chunkElement, 'max_x'); var maxY = getElementPropStorage(chunkElement, 'max_y'); var maxZ = getElementPropStorage(chunkElement, 'max_z'); var minScaleX = getElementPropStorage(chunkElement, 'min_scale_x'); var minScaleY = getElementPropStorage(chunkElement, 'min_scale_y'); var minScaleZ = getElementPropStorage(chunkElement, 'min_scale_z'); var maxScaleX = getElementPropStorage(chunkElement, 'max_scale_x'); var maxScaleY = getElementPropStorage(chunkElement, 'max_scale_y'); var maxScaleZ = getElementPropStorage(chunkElement, 'max_scale_z'); var position = getElementPropStorage(vertexElement, 'packed_position'); var rotation = getElementPropStorage(vertexElement, 'packed_rotation'); var scale = getElementPropStorage(vertexElement, 'packed_scale'); var color = getElementPropStorage(vertexElement, 'packed_color'); return { positionExtremes: { minX, maxX, minY, maxY, minZ, maxZ }, scaleExtremes: { minScaleX, maxScaleX, minScaleY, maxScaleY, minScaleZ, maxScaleZ }, position, rotation, scale, color }; } static parseToUncompressedSplatBufferSection(chunkElement, vertexElement, fromIndex, toIndex, chunkSplatIndexOffset, vertexDataBuffer, veretxReadOffset, outBuffer, outOffset) { var propertyFilter = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : null; CompressedPlyParser.readElementData(vertexElement, vertexDataBuffer, veretxReadOffset, fromIndex, toIndex, propertyFilter); var outBytesPerCenter = SplatBuffer.CompressionLevels[0].BytesPerCenter; var outBytesPerScale = SplatBuffer.CompressionLevels[0].BytesPerScale; var outBytesPerRotation = SplatBuffer.CompressionLevels[0].BytesPerRotation; var outBytesPerSplat = SplatBuffer.CompressionLevels[0].SphericalHarmonicsDegrees[0].BytesPerSplat; var { positionExtremes, scaleExtremes, position, rotation, scale, color } = CompressedPlyParser.getElementStorageArrays(chunkElement, vertexElement); var OFFSET = UncompressedSplatArray.OFFSET; var tempSplat = UncompressedSplatArray.createSplat(); for (var i = fromIndex; i <= toIndex; ++i) { CompressedPlyParser.decompressSplat(i, chunkSplatIndexOffset, position, positionExtremes, scale, scaleExtremes, rotation, color, tempSplat); var outBase = i * outBytesPerSplat + outOffset; var outCenter = new Float32Array(outBuffer, outBase, 3); var outScale = new Float32Array(outBuffer, outBase + outBytesPerCenter, 3); var outRotation = new Float32Array(outBuffer, outBase + outBytesPerCenter + outBytesPerScale, 4); var outColor = new Uint8Array(outBuffer, outBase + outBytesPerCenter + outBytesPerScale + outBytesPerRotation, 4); outCenter[0] = tempSplat[OFFSET.X]; outCenter[1] = tempSplat[OFFSET.Y]; outCenter[2] = tempSplat[OFFSET.Z]; outScale[0] = tempSplat[OFFSET.SCALE0]; outScale[1] = tempSplat[OFFSET.SCALE1]; outScale[2] = tempSplat[OFFSET.SCALE2]; outRotation[0] = tempSplat[OFFSET.ROTATION0]; outRotation[1] = tempSplat[OFFSET.ROTATION1]; outRotation[2] = tempSplat[OFFSET.ROTATION2]; outRotation[3] = tempSplat[OFFSET.ROTATION3]; outColor[0] = tempSplat[OFFSET.FDC0]; outColor[1] = tempSplat[OFFSET.FDC1]; outColor[2] = tempSplat[OFFSET.FDC2]; outColor[3] = tempSplat[OFFSET.OPACITY]; } } static parseToUncompressedSplatArray(plyBuffer) { var { chunkElement, vertexElement } = CompressedPlyParser.readPly(plyBuffer); var splatArray = new UncompressedSplatArray(); var { positionExtremes, scaleExtremes, position, rotation, scale, color } = CompressedPlyParser.getElementStorageArrays(chunkElement, vertexElement); for (var i = 0; i < vertexElement.count; ++i) { splatArray.addDefaultSplat(); var newSplat = splatArray.getSplat(splatArray.splatCount - 1); CompressedPlyParser.decompressSplat(i, 0, position, positionExtremes, scale, scaleExtremes, rotation, color, newSplat); } var mat = new Matrix4(); mat.identity(); return splatArray; } } _defineProperty(CompressedPlyParser, "decompressSplat", function () { var p = new Vector3(); var r = new Quaternion(); var s = new Vector3(); var c = new Vector4(); var OFFSET = UncompressedSplatArray.OFFSET; return function (index, chunkSplatIndexOffset, positionArray, positionExtremes, scaleArray, scaleExtremes, rotationArray, colorArray, outSplat) { outSplat = outSplat || UncompressedSplatArray.createSplat(); var chunkIndex = Math.floor((chunkSplatIndexOffset + index) / 256); unpack111011(p, positionArray[index]); unpackRot(r, rotationArray[index]); unpack111011(s, scaleArray[index]); unpack8888(c, colorArray[index]); outSplat[OFFSET.X] = lerp$1(positionExtremes.minX[chunkIndex], positionExtremes.maxX[chunkIndex], p.x); outSplat[OFFSET.Y] = lerp$1(positionExtremes.minY[chunkIndex], positionExtremes.maxY[chunkIndex], p.y); outSplat[OFFSET.Z] = lerp$1(positionExtremes.minZ[chunkIndex], positionExtremes.maxZ[chunkIndex], p.z); outSplat[OFFSET.ROTATION0] = r.x; outSplat[OFFSET.ROTATION1] = r.y; outSplat[OFFSET.ROTATION2] = r.z; outSplat[OFFSET.ROTATION3] = r.w; outSplat[OFFSET.SCALE0] = Math.exp(lerp$1(scaleExtremes.minScaleX[chunkIndex], scaleExtremes.maxScaleX[chunkIndex], s.x)); outSplat[OFFSET.SCALE1] = Math.exp(lerp$1(scaleExtremes.minScaleY[chunkIndex], scaleExtremes.maxScaleY[chunkIndex], s.y)); outSplat[OFFSET.SCALE2] = Math.exp(lerp$1(scaleExtremes.minScaleZ[chunkIndex], scaleExtremes.maxScaleZ[chunkIndex], s.z)); outSplat[OFFSET.FDC0] = clamp(Math.floor(c.x * 255), 0, 255); outSplat[OFFSET.FDC1] = clamp(Math.floor(c.y * 255), 0, 255); outSplat[OFFSET.FDC2] = clamp(Math.floor(c.z * 255), 0, 255); outSplat[OFFSET.OPACITY] = clamp(Math.floor(c.w * 255), 0, 255); return outSplat; }; }()); class PlyParser { static checkTextForEndHeader(endHeaderTestText) { if (endHeaderTestText.includes(PlyParser.HeaderEndToken)) { return true; } return false; } static checkBufferForEndHeader(buffer, searchOfset, chunkSize, decoder) { var endHeaderTestChunk = new Uint8Array(buffer, Math.max(0, searchOfset - chunkSize), chunkSize); var endHeaderTestText = decoder.decode(endHeaderTestChunk); return PlyParser.checkTextForEndHeader(endHeaderTestText); } static decodeHeaderText(headerText) { var headerLines = headerText.split('\n'); var prunedLines = []; var splatCount = 0; var propertyTypes = {}; var compressed = false; for (var i = 0; i < headerLines.length; i++) { var line = headerLines[i].trim(); prunedLines.push(line); if (line.startsWith('element chunk') || line.match(/[A-Za-z]*packed_[A-Za-z]*/)) { compressed = true; } else if (line.startsWith('element vertex')) { var splatCountMatch = line.match(/\d+/); if (splatCountMatch) { splatCount = parseInt(splatCountMatch[0]); } } else if (line.startsWith('property')) { var propertyMatch = line.match(/(\w+)\s+(\w+)\s+(\w+)/); if (propertyMatch) { var propertyType = propertyMatch[2]; var propertyName = propertyMatch[3]; propertyTypes[propertyName] = propertyType; } } else if (line === PlyParser.HeaderEndToken) { break; } } var bytesPerSplat = 0; var fieldOffsets = {}; var fieldSize = { 'double': 8, 'int': 4, 'uint': 4, 'float': 4, 'short': 2, 'ushort': 2, 'uchar': 1 }; var fieldNames = []; for (var fieldName in propertyTypes) { if (propertyTypes.hasOwnProperty(fieldName)) { fieldNames.push(fieldName); var type = propertyTypes[fieldName]; fieldOffsets[fieldName] = bytesPerSplat; bytesPerSplat += fieldSize[type]; } } var sphericalHarmonicsFieldCount = 0; var sphericalHarmonicsCoefficientsPerChannel = 0; for (var _fieldName of fieldNames) { if (_fieldName.startsWith('f_rest')) sphericalHarmonicsFieldCount++; } sphericalHarmonicsCoefficientsPerChannel = sphericalHarmonicsFieldCount / 3; var sphericalHarmonicsDegree = 0; if (sphericalHarmonicsCoefficientsPerChannel >= 3) sphericalHarmonicsDegree = 1; if (sphericalHarmonicsCoefficientsPerChannel >= 8) sphericalHarmonicsDegree = 2; var sphericalHarmonicsDegree1Fields = []; if (sphericalHarmonicsDegree >= 1) { for (var rgb = 0; rgb < 3; rgb++) { for (var _i9 = 0; _i9 < 3; _i9++) { sphericalHarmonicsDegree1Fields.push('f_rest_' + (_i9 + sphericalHarmonicsCoefficientsPerChannel * rgb)); } } } var sphericalHarmonicsDegree2Fields = []; if (sphericalHarmonicsDegree >= 2) { for (var _rgb = 0; _rgb < 3; _rgb++) { for (var _i10 = 0; _i10 < 5; _i10++) { sphericalHarmonicsDegree2Fields.push('f_rest_' + (_i10 + sphericalHarmonicsCoefficientsPerChannel * _rgb + 3)); } } } return { 'splatCount': splatCount, 'propertyTypes': propertyTypes, 'compressed': compressed, 'headerText': headerText, 'headerLines': prunedLines, 'headerSizeBytes': headerText.indexOf(PlyParser.HeaderEndToken) + PlyParser.HeaderEndToken.length + 1, 'bytesPerSplat': bytesPerSplat, 'fieldOffsets': fieldOffsets, 'sphericalHarmonicsDegree': sphericalHarmonicsDegree, 'sphericalHarmonicsCoefficientsPerChannel': sphericalHarmonicsCoefficientsPerChannel, 'sphericalHarmonicsDegree1Fields': sphericalHarmonicsDegree1Fields, 'sphericalHarmonicsDegree2Fields': sphericalHarmonicsDegree2Fields }; } static decodeHeadeFromBuffer(plyBuffer) { var decoder = new TextDecoder(); var headerOffset = 0; var headerText = ''; var readChunkSize = 100; while (true) { if (headerOffset + readChunkSize >= plyBuffer.byteLength) { throw new Error('End of file reached while searching for end of header'); } var headerChunk = new Uint8Array(plyBuffer, headerOffset, readChunkSize); headerText += decoder.decode(headerChunk); headerOffset += readChunkSize; if (PlyParser.checkBufferForEndHeader(plyBuffer, headerOffset, readChunkSize * 2, decoder)) { break; } } return PlyParser.decodeHeaderText(headerText); } static findVertexData(plyBuffer, header) { return new DataView(plyBuffer, header.headerSizeBytes); } static readRawVertexFast(vertexData, offset, fieldOffsets, propertiesToRead, propertyTypes, outVertex) { var rawVertex = outVertex || {}; for (var property of propertiesToRead) { var propertyType = propertyTypes[property]; if (propertyType === 'float') { rawVertex[property] = vertexData.getFloat32(offset + fieldOffsets[property], true); } else if (propertyType === 'double') { //xzw add! 因为我试过一个ply的坐标是double rawVertex[property] = vertexData.getFloat64(offset + fieldOffsets[property], true); } else if (propertyType === 'uchar') { rawVertex[property] = vertexData.getUint8(offset + fieldOffsets[property]) / 255.0; } } } static parseToUncompressedSplatBufferSection(header, fromSplat, toSplat, vertexData, vertexDataOffset, toBuffer, toOffset) { var outSphericalHarmonicsDegree = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0; outSphericalHarmonicsDegree = Math.min(outSphericalHarmonicsDegree, header.sphericalHarmonicsDegree); var outBytesPerCenter = SplatBuffer.CompressionLevels[0].BytesPerCenter; var outBytesPerScale = SplatBuffer.CompressionLevels[0].BytesPerScale; var outBytesPerRotation = SplatBuffer.CompressionLevels[0].BytesPerRotation; var outBytesPerColor = SplatBuffer.CompressionLevels[0].BytesPerColor; var outBytesPerSplat = SplatBuffer.CompressionLevels[0].SphericalHarmonicsDegrees[outSphericalHarmonicsDegree].BytesPerSplat; for (var i = fromSplat; i <= toSplat; i++) { var parsedSplat = PlyParser.parseToUncompressedSplat(vertexData, i, header, vertexDataOffset, outSphericalHarmonicsDegree); var outBase = i * outBytesPerSplat + toOffset; var outCenter = new Float32Array(toBuffer, outBase, 3); var outScale = new Float32Array(toBuffer, outBase + outBytesPerCenter, 3); var outRotation = new Float32Array(toBuffer, outBase + outBytesPerCenter + outBytesPerScale, 4); var outColor = new Uint8Array(toBuffer, outBase + outBytesPerCenter + outBytesPerScale + outBytesPerRotation, 4); outCenter[0] = parsedSplat[UncompressedSplatArray.OFFSET.X]; outCenter[1] = parsedSplat[UncompressedSplatArray.OFFSET.Y]; outCenter[2] = parsedSplat[UncompressedSplatArray.OFFSET.Z]; outScale[0] = parsedSplat[UncompressedSplatArray.OFFSET.SCALE0]; outScale[1] = parsedSplat[UncompressedSplatArray.OFFSET.SCALE1]; outScale[2] = parsedSplat[UncompressedSplatArray.OFFSET.SCALE2]; outRotation[0] = parsedSplat[UncompressedSplatArray.OFFSET.ROTATION0]; outRotation[1] = parsedSplat[UncompressedSplatArray.OFFSET.ROTATION1]; outRotation[2] = parsedSplat[UncompressedSplatArray.OFFSET.ROTATION2]; outRotation[3] = parsedSplat[UncompressedSplatArray.OFFSET.ROTATION3]; outColor[0] = parsedSplat[UncompressedSplatArray.OFFSET.FDC0]; outColor[1] = parsedSplat[UncompressedSplatArray.OFFSET.FDC1]; outColor[2] = parsedSplat[UncompressedSplatArray.OFFSET.FDC2]; outColor[3] = parsedSplat[UncompressedSplatArray.OFFSET.OPACITY]; if (outSphericalHarmonicsDegree >= 1) { var outSphericalHarmonics = new Float32Array(toBuffer, outBase + outBytesPerCenter + outBytesPerScale + outBytesPerRotation + outBytesPerColor, parsedSplat.sphericalHarmonicsCount); for (var _i11 = 0; _i11 <= 8; _i11++) { outSphericalHarmonics[_i11] = parsedSplat[UncompressedSplatArray.OFFSET.FRC0 + _i11]; } if (outSphericalHarmonicsDegree >= 2) { for (var _i12 = 9; _i12 <= 23; _i12++) { outSphericalHarmonics[_i12] = parsedSplat[UncompressedSplatArray.OFFSET.FRC0 + _i12]; } } } } } static parseToUncompressedSplatArray(plyBuffer) { var outSphericalHarmonicsDegree = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var header = PlyParser.decodeHeadeFromBuffer(plyBuffer); if (header.compressed) { return CompressedPlyParser.parseToUncompressedSplatArray(plyBuffer); } else { var splatCount = header.splatCount; var vertexData = PlyParser.findVertexData(plyBuffer, header); // TODO: Eventually properly support multiple degree spherical harmonics // figure out the SH degree from the number of coefficients /* let nRestCoeffs = 0; for (const propertyName in header.propertyTypes) { if (propertyName.startsWith('f_rest_')) { nRestCoeffs += 1; } } const nCoeffsPerColor = nRestCoeffs / 3;*/ // const sphericalHarmonicsDegree = Math.sqrt(nCoeffsPerColor + 1) - 1; // const sphericalHarmonicsDegree = 0; // console.log('Detected degree', sphericalHarmonicsDegree, 'with ', nCoeffsPerColor, 'coefficients per color'); // figure out the order in which spherical harmonics should be read /* const shFeatureOrder = []; for (let rgb = 0; rgb < 3; ++rgb) { shFeatureOrder.push(`f_dc_${rgb}`); } for (let i = 0; i < nCoeffsPerColor; ++i) { for (let rgb = 0; rgb < 3; ++rgb) { shFeatureOrder.push(`f_rest_${rgb * nCoeffsPerColor + i}`); } }*/ var splatArray = new UncompressedSplatArray(outSphericalHarmonicsDegree); for (var row = 0; row < splatCount; row++) { var newSplat = PlyParser.parseToUncompressedSplat(vertexData, row, header, 0, outSphericalHarmonicsDegree); splatArray.addSplat(newSplat); } return splatArray; } } } _PlyParser = PlyParser; _defineProperty(PlyParser, "HeaderEndToken", 'end_header'); _defineProperty(PlyParser, "BaseFields", ['scale_0', 'scale_1', 'scale_2', 'rot_0', 'rot_1', 'rot_2', 'rot_3', 'x', 'y', 'z', 'f_dc_0', 'f_dc_1', 'f_dc_2', 'red', 'green', 'blue', 'opacity']); _defineProperty(PlyParser, "SphericalHarmonicsFields", Array.from(Array(45)).map((e, i) => "f_rest_".concat(i))); _defineProperty(PlyParser, "Fields", [[..._PlyParser.BaseFields], [..._PlyParser.BaseFields, ..._PlyParser.SphericalHarmonicsFields]]); _defineProperty(PlyParser, "parseToUncompressedSplat", function () { var rawVertex = {}; var tempRotation = new Quaternion(); return function (vertexData, row, header) { var vertexDataOffset = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; var outSphericalHarmonicsDegree = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; outSphericalHarmonicsDegree = Math.min(outSphericalHarmonicsDegree, header.sphericalHarmonicsDegree); _PlyParser.readRawVertexFast(vertexData, row * header.bytesPerSplat + vertexDataOffset, header.fieldOffsets, _PlyParser.Fields[outSphericalHarmonicsDegree > 0 ? 1 : 0], header.propertyTypes, rawVertex); var newSplat = UncompressedSplatArray.createSplat(outSphericalHarmonicsDegree); if (rawVertex['scale_0'] !== undefined) { newSplat[UncompressedSplatArray.OFFSET.SCALE0] = Math.exp(rawVertex['scale_0']); newSplat[UncompressedSplatArray.OFFSET.SCALE1] = Math.exp(rawVertex['scale_1']); newSplat[UncompressedSplatArray.OFFSET.SCALE2] = Math.exp(rawVertex['scale_2']); } else { newSplat[UncompressedSplatArray.OFFSET.SCALE0] = 0.01; newSplat[UncompressedSplatArray.OFFSET.SCALE1] = 0.01; newSplat[UncompressedSplatArray.OFFSET.SCALE2] = 0.01; } if (rawVertex['f_dc_0'] !== undefined) { var SH_C0 = 0.28209479177387814; newSplat[UncompressedSplatArray.OFFSET.FDC0] = (0.5 + SH_C0 * rawVertex['f_dc_0']) * 255; newSplat[UncompressedSplatArray.OFFSET.FDC1] = (0.5 + SH_C0 * rawVertex['f_dc_1']) * 255; newSplat[UncompressedSplatArray.OFFSET.FDC2] = (0.5 + SH_C0 * rawVertex['f_dc_2']) * 255; } else if (rawVertex['red'] !== undefined) { newSplat[UncompressedSplatArray.OFFSET.FDC0] = rawVertex['red'] * 255; newSplat[UncompressedSplatArray.OFFSET.FDC1] = rawVertex['green'] * 255; newSplat[UncompressedSplatArray.OFFSET.FDC2] = rawVertex['blue'] * 255; } else { newSplat[UncompressedSplatArray.OFFSET.FDC0] = 0; newSplat[UncompressedSplatArray.OFFSET.FDC1] = 0; newSplat[UncompressedSplatArray.OFFSET.FDC2] = 0; } if (rawVertex['opacity'] !== undefined) { newSplat[UncompressedSplatArray.OFFSET.OPACITY] = 1 / (1 + Math.exp(-rawVertex['opacity'])) * 255; } else { //xzw add newSplat[UncompressedSplatArray.OFFSET.OPACITY] = 1; } newSplat[UncompressedSplatArray.OFFSET.FDC0] = clamp(Math.floor(newSplat[UncompressedSplatArray.OFFSET.FDC0]), 0, 255); newSplat[UncompressedSplatArray.OFFSET.FDC1] = clamp(Math.floor(newSplat[UncompressedSplatArray.OFFSET.FDC1]), 0, 255); newSplat[UncompressedSplatArray.OFFSET.FDC2] = clamp(Math.floor(newSplat[UncompressedSplatArray.OFFSET.FDC2]), 0, 255); newSplat[UncompressedSplatArray.OFFSET.OPACITY] = clamp(Math.floor(newSplat[UncompressedSplatArray.OFFSET.OPACITY]), 0, 255); if (outSphericalHarmonicsDegree >= 1) { if (rawVertex['f_rest_0'] !== undefined) { for (var i = 0; i < 9; i++) { newSplat[UncompressedSplatArray.OFFSET.FRC0 + i] = rawVertex[header.sphericalHarmonicsDegree1Fields[i]]; } if (outSphericalHarmonicsDegree >= 2) { for (var _i23 = 0; _i23 < 15; _i23++) { newSplat[UncompressedSplatArray.OFFSET.FRC9 + _i23] = rawVertex[header.sphericalHarmonicsDegree2Fields[_i23]]; } } } else { newSplat[UncompressedSplatArray.OFFSET.FRC0] = 0; newSplat[UncompressedSplatArray.OFFSET.FRC1] = 0; newSplat[UncompressedSplatArray.OFFSET.FRC2] = 0; } } if (rawVertex['rot_0'] == void 0) { //xzw add 表现为任何方向都是圆形 sprite tempRotation.set(0, 0, 0, 1); } else { tempRotation.set(rawVertex['rot_0'], rawVertex['rot_1'], rawVertex['rot_2'], rawVertex['rot_3']); tempRotation.normalize(); } newSplat[UncompressedSplatArray.OFFSET.ROTATION0] = tempRotation.x; newSplat[UncompressedSplatArray.OFFSET.ROTATION1] = tempRotation.y; newSplat[UncompressedSplatArray.OFFSET.ROTATION2] = tempRotation.z; newSplat[UncompressedSplatArray.OFFSET.ROTATION3] = tempRotation.w; newSplat[UncompressedSplatArray.OFFSET.X] = rawVertex['x']; newSplat[UncompressedSplatArray.OFFSET.Y] = rawVertex['y']; newSplat[UncompressedSplatArray.OFFSET.Z] = rawVertex['z']; return newSplat; }; }()); class SplatPartitioner { constructor(sectionCount, sectionFilters, groupingParameters, partitionGenerator) { this.sectionCount = sectionCount; this.sectionFilters = sectionFilters; this.groupingParameters = groupingParameters; this.partitionGenerator = partitionGenerator; } partitionUncompressedSplatArray(splatArray) { var groupingParameters; var sectionCount; var sectionFilters; if (this.partitionGenerator) { var results = this.partitionGenerator(splatArray); groupingParameters = results.groupingParameters; sectionCount = results.sectionCount; sectionFilters = results.sectionFilters; } else { groupingParameters = this.groupingParameters; sectionCount = this.sectionCount; sectionFilters = this.sectionFilters; } var newArrays = []; for (var s = 0; s < sectionCount; s++) { var sectionSplats = new UncompressedSplatArray(splatArray.sphericalHarmonicsDegree); var sectionFilter = sectionFilters[s]; for (var i = 0; i < splatArray.splatCount; i++) { if (sectionFilter(i)) { sectionSplats.addSplatFromArray(splatArray, i); } } newArrays.push(sectionSplats); } return { splatArrays: newArrays, parameters: groupingParameters }; } static getStandardPartitioner() { var partitionSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var sceneCenter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Vector3(); var blockSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : SplatBuffer.BucketBlockSize; var bucketSize = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : SplatBuffer.BucketSize; var partitionGenerator = splatArray => { if (partitionSize <= 0) partitionSize = splatArray.splatCount; var centerA = new Vector3(); var centerB = new Vector3(); var clampDistance = 0.5; var clampPoint = point => { point.x = Math.floor(point.x / clampDistance) * clampDistance; point.y = Math.floor(point.y / clampDistance) * clampDistance; point.z = Math.floor(point.z / clampDistance) * clampDistance; }; splatArray.splats.sort((a, b) => { centerA.set(a[UncompressedSplatArray.OFFSET.X], a[UncompressedSplatArray.OFFSET.Y], a[UncompressedSplatArray.OFFSET.Z]).sub(sceneCenter); clampPoint(centerA); var centerADist = centerA.lengthSq(); centerB.set(b[UncompressedSplatArray.OFFSET.X], b[UncompressedSplatArray.OFFSET.Y], b[UncompressedSplatArray.OFFSET.Z]).sub(sceneCenter); clampPoint(centerB); var centerBDist = centerB.lengthSq(); if (centerADist > centerBDist) return 1;else return -1; }); var sectionFilters = []; var groupingParameters = []; partitionSize = Math.min(splatArray.splatCount, partitionSize); var patitionCount = Math.ceil(splatArray.splatCount / partitionSize); var currentStartSplat = 0; var _loop = function _loop() { var startSplat = currentStartSplat; sectionFilters.push(splatIndex => { return splatIndex >= startSplat && splatIndex < startSplat + partitionSize; }); groupingParameters.push({ 'blocksSize': blockSize, 'bucketSize': bucketSize }); currentStartSplat += partitionSize; }; for (var i = 0; i < patitionCount; i++) { _loop(); } return { 'sectionCount': sectionFilters.length, sectionFilters, groupingParameters }; }; return new SplatPartitioner(undefined, undefined, undefined, partitionGenerator); } } class SplatBufferGenerator { constructor(splatPartitioner, alphaRemovalThreshold, compressionLevel, sectionSize, sceneCenter, blockSize, bucketSize) { this.splatPartitioner = splatPartitioner; this.alphaRemovalThreshold = alphaRemovalThreshold; this.compressionLevel = compressionLevel; this.sectionSize = sectionSize; this.sceneCenter = sceneCenter ? new Vector3().copy(sceneCenter) : undefined; this.blockSize = blockSize; this.bucketSize = bucketSize; } generateFromUncompressedSplatArray(splatArray) { var partitionResults = this.splatPartitioner.partitionUncompressedSplatArray(splatArray); return SplatBuffer.generateFromUncompressedSplatArrays(partitionResults.splatArrays, this.alphaRemovalThreshold, this.compressionLevel, this.sceneCenter, this.blockSize, this.bucketSize, partitionResults.parameters); } static getStandardGenerator() { var alphaRemovalThreshold = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; var compressionLevel = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var sectionSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var sceneCenter = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new Vector3(); var blockSize = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : SplatBuffer.BucketBlockSize; var bucketSize = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : SplatBuffer.BucketSize; var splatPartitioner = SplatPartitioner.getStandardPartitioner(sectionSize, sceneCenter, blockSize, bucketSize); return new SplatBufferGenerator(splatPartitioner, alphaRemovalThreshold, compressionLevel, sectionSize, sceneCenter, blockSize, bucketSize); } } var LoaderStatus = { 'Downloading': 0, 'Processing': 1, 'Done': 2 }; class Constants {} _defineProperty(Constants, "DepthMapRange", 1 << 16); _defineProperty(Constants, "MemoryPageSize", 65536); _defineProperty(Constants, "BytesPerFloat", 4); _defineProperty(Constants, "BytesPerInt", 4); _defineProperty(Constants, "MaxScenes", 32); _defineProperty(Constants, "StreamingSectionSize", 524288); function storeChunksInBuffer(chunks, buffer) { var inBytes = 0; for (var chunk of chunks) inBytes += chunk.sizeBytes; if (!buffer || buffer.byteLength < inBytes) { buffer = new ArrayBuffer(inBytes); } var offset = 0; for (var _chunk of chunks) { new Uint8Array(buffer, offset, _chunk.sizeBytes).set(_chunk.data); offset += _chunk.sizeBytes; } return buffer; } class PlyLoader { static loadFromURL(fileName, onProgress, streamLoadData, onStreamedSectionProgress, minimumAlpha, compressionLevel) { var outSphericalHarmonicsDegree = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; var sectionSize = arguments.length > 7 ? arguments[7] : undefined; var sceneCenter = arguments.length > 8 ? arguments[8] : undefined; var blockSize = arguments.length > 9 ? arguments[9] : undefined; var bucketSize = arguments.length > 10 ? arguments[10] : undefined; var streamedSectionSizeBytes = Constants.StreamingSectionSize; var splatDataOffsetBytes = SplatBuffer.HeaderSizeBytes + SplatBuffer.SectionHeaderSizeBytes; var sectionCount = 1; var streamBufferIn; var streamBufferOut; var streamedSplatBuffer; var compressedPlyHeaderChunksBuffer; var maxSplatCount = 0; var splatCount = 0; var headerLoaded = false; var readyToLoadSplatData = false; var compressed = false; var streamLoadCompleteResolver; var streamLoadPromise = new Promise(resolve => { streamLoadCompleteResolver = resolve; }); var numBytesStreamed = 0; var numBytesParsed = 0; var numBytesDownloaded = 0; var headerText = ''; var header = null; var chunks = []; var textDecoder = new TextDecoder(); var localOnProgress = (percent, percentLabel, chunkData) => { var loadComplete = percent >= 100; if (streamLoadData) { if (chunkData) { chunks.push({ 'data': chunkData, 'sizeBytes': chunkData.byteLength, 'startBytes': numBytesDownloaded, 'endBytes': numBytesDownloaded + chunkData.byteLength }); numBytesDownloaded += chunkData.byteLength; } if (!headerLoaded) { headerText += textDecoder.decode(chunkData); if (PlyParser.checkTextForEndHeader(headerText)) { header = PlyParser.decodeHeaderText(headerText); outSphericalHarmonicsDegree = Math.min(outSphericalHarmonicsDegree, header.sphericalHarmonicsDegree); compressed = header.compressed; if (compressed) { header = CompressedPlyParser.decodeHeaderText(headerText); maxSplatCount = header.vertexElement.count; } else { maxSplatCount = header.splatCount; readyToLoadSplatData = true; } var shDescriptor = SplatBuffer.CompressionLevels[0].SphericalHarmonicsDegrees[outSphericalHarmonicsDegree]; var splatBufferSizeBytes = splatDataOffsetBytes + shDescriptor.BytesPerSplat * maxSplatCount; streamBufferOut = new ArrayBuffer(splatBufferSizeBytes); SplatBuffer.writeHeaderToBuffer({ versionMajor: SplatBuffer.CurrentMajorVersion, versionMinor: SplatBuffer.CurrentMinorVersion, maxSectionCount: sectionCount, sectionCount: sectionCount, maxSplatCount: maxSplatCount, splatCount: splatCount, compressionLevel: 0, sceneCenter: new Vector3() }, streamBufferOut); numBytesStreamed = header.headerSizeBytes; numBytesParsed = header.headerSizeBytes; headerLoaded = true; } } else if (compressed && !readyToLoadSplatData) { var sizeRequiredForHeaderAndChunks = header.headerSizeBytes + header.chunkElement.storageSizeBytes; compressedPlyHeaderChunksBuffer = storeChunksInBuffer(chunks, compressedPlyHeaderChunksBuffer); if (compressedPlyHeaderChunksBuffer.byteLength >= sizeRequiredForHeaderAndChunks) { CompressedPlyParser.readElementData(header.chunkElement, compressedPlyHeaderChunksBuffer, header.headerSizeBytes); numBytesStreamed = sizeRequiredForHeaderAndChunks; numBytesParsed = sizeRequiredForHeaderAndChunks; readyToLoadSplatData = true; } } if (headerLoaded && readyToLoadSplatData) { if (chunks.length > 0) { streamBufferIn = storeChunksInBuffer(chunks, streamBufferIn); var bytesLoadedSinceLastStreamedSection = numBytesDownloaded - numBytesStreamed; if (bytesLoadedSinceLastStreamedSection > streamedSectionSizeBytes || loadComplete) { var numBytesToProcess = numBytesDownloaded - numBytesParsed; var addedSplatCount = Math.floor(numBytesToProcess / header.bytesPerSplat); var numBytesToParse = addedSplatCount * header.bytesPerSplat; var numBytesLeftOver = numBytesToProcess - numBytesToParse; var newSplatCount = splatCount + addedSplatCount; var parsedDataViewOffset = numBytesParsed - chunks[0].startBytes; var dataToParse = new DataView(streamBufferIn, parsedDataViewOffset, numBytesToParse); var _shDescriptor = SplatBuffer.CompressionLevels[0].SphericalHarmonicsDegrees[outSphericalHarmonicsDegree]; var outOffset = splatCount * _shDescriptor.BytesPerSplat + splatDataOffsetBytes; if (compressed) { CompressedPlyParser.parseToUncompressedSplatBufferSection(header.chunkElement, header.vertexElement, 0, addedSplatCount - 1, splatCount, dataToParse, 0, streamBufferOut, outOffset); } else { PlyParser.parseToUncompressedSplatBufferSection(header, 0, addedSplatCount - 1, dataToParse, 0, streamBufferOut, outOffset, outSphericalHarmonicsDegree); } splatCount = newSplatCount; if (!streamedSplatBuffer) { SplatBuffer.writeSectionHeaderToBuffer({ maxSplatCount: maxSplatCount, splatCount: splatCount, bucketSize: 0, bucketCount: 0, bucketBlockSize: 0, compressionScaleRange: 0, storageSizeBytes: 0, fullBucketCount: 0, partiallyFilledBucketCount: 0, sphericalHarmonicsDegree: outSphericalHarmonicsDegree }, 0, streamBufferOut, SplatBuffer.HeaderSizeBytes); streamedSplatBuffer = new SplatBuffer(streamBufferOut, false); } streamedSplatBuffer.updateLoadedCounts(1, splatCount); onStreamedSectionProgress(streamedSplatBuffer, loadComplete); numBytesStreamed += streamedSectionSizeBytes; numBytesParsed += numBytesToParse; if (numBytesLeftOver === 0) { chunks = []; } else { var keepChunks = []; var keepSize = 0; for (var i = chunks.length - 1; i >= 0; i--) { var chunk = chunks[i]; keepSize += chunk.sizeBytes; keepChunks.unshift(chunk); if (keepSize >= numBytesLeftOver) break; } chunks = keepChunks; } } } if (loadComplete) { streamLoadCompleteResolver(streamedSplatBuffer); } } } if (onProgress) onProgress(percent, percentLabel, LoaderStatus.Downloading); }; return fetchWithProgress(fileName, localOnProgress, !streamLoadData).then(plyFileData => { if (onProgress) onProgress(0, '0%', LoaderStatus.Processing); var loadPromise = streamLoadData ? streamLoadPromise : PlyLoader.loadFromFileData(plyFileData, minimumAlpha, compressionLevel, outSphericalHarmonicsDegree, sectionSize, sceneCenter, blockSize, bucketSize); return loadPromise.then(splatBuffer => { if (onProgress) onProgress(100, '100%', LoaderStatus.Done); return splatBuffer; }); }); } static loadFromFileData(plyFileData, minimumAlpha, compressionLevel) { var outSphericalHarmonicsDegree = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; var sectionSize = arguments.length > 4 ? arguments[4] : undefined; var sceneCenter = arguments.length > 5 ? arguments[5] : undefined; var blockSize = arguments.length > 6 ? arguments[6] : undefined; var bucketSize = arguments.length > 7 ? arguments[7] : undefined; return delayedExecute(() => { return PlyParser.parseToUncompressedSplatArray(plyFileData, outSphericalHarmonicsDegree); }).then(splatArray => { var splatBufferGenerator = SplatBufferGenerator.getStandardGenerator(minimumAlpha, compressionLevel, sectionSize, sceneCenter, blockSize, bucketSize); return splatBufferGenerator.generateFromUncompressedSplatArray(splatArray); }); } } class SplatParser { static parseToUncompressedSplatBufferSection(fromSplat, toSplat, fromBuffer, fromOffset, toBuffer, toOffset) { var outBytesPerCenter = SplatBuffer.CompressionLevels[0].BytesPerCenter; var outBytesPerScale = SplatBuffer.CompressionLevels[0].BytesPerScale; var outBytesPerRotation = SplatBuffer.CompressionLevels[0].BytesPerRotation; var outBytesPerSplat = SplatBuffer.CompressionLevels[0].SphericalHarmonicsDegrees[0].BytesPerSplat; for (var i = fromSplat; i <= toSplat; i++) { var inBase = i * SplatParser.RowSizeBytes + fromOffset; var inCenter = new Float32Array(fromBuffer, inBase, 3); var inScale = new Float32Array(fromBuffer, inBase + SplatParser.CenterSizeBytes, 3); var inColor = new Uint8Array(fromBuffer, inBase + SplatParser.CenterSizeBytes + SplatParser.ScaleSizeBytes, 4); var inRotation = new Uint8Array(fromBuffer, inBase + SplatParser.CenterSizeBytes + SplatParser.ScaleSizeBytes + SplatParser.RotationSizeBytes, 4); var quat = new Quaternion((inRotation[1] - 128) / 128, (inRotation[2] - 128) / 128, (inRotation[3] - 128) / 128, (inRotation[0] - 128) / 128); quat.normalize(); var outBase = i * outBytesPerSplat + toOffset; var outCenter = new Float32Array(toBuffer, outBase, 3); var outScale = new Float32Array(toBuffer, outBase + outBytesPerCenter, 3); var outRotation = new Float32Array(toBuffer, outBase + outBytesPerCenter + outBytesPerScale, 4); var outColor = new Uint8Array(toBuffer, outBase + outBytesPerCenter + outBytesPerScale + outBytesPerRotation, 4); outCenter[0] = inCenter[0]; outCenter[1] = inCenter[1]; outCenter[2] = inCenter[2]; outScale[0] = inScale[0]; outScale[1] = inScale[1]; outScale[2] = inScale[2]; outRotation[0] = quat.w; outRotation[1] = quat.x; outRotation[2] = quat.y; outRotation[3] = quat.z; outColor[0] = inColor[0]; outColor[1] = inColor[1]; outColor[2] = inColor[2]; outColor[3] = inColor[3]; } } static parseStandardSplatToUncompressedSplatArray(inBuffer) { // Standard .splat row layout: // XYZ - Position (Float32) // XYZ - Scale (Float32) // RGBA - colors (uint8) // IJKL - quaternion/rot (uint8) var splatCount = inBuffer.byteLength / SplatParser.RowSizeBytes; var splatArray = new UncompressedSplatArray(); for (var i = 0; i < splatCount; i++) { var inBase = i * SplatParser.RowSizeBytes; var inCenter = new Float32Array(inBuffer, inBase, 3); var inScale = new Float32Array(inBuffer, inBase + SplatParser.CenterSizeBytes, 3); var inColor = new Uint8Array(inBuffer, inBase + SplatParser.CenterSizeBytes + SplatParser.ScaleSizeBytes, 4); var inRotation = new Uint8Array(inBuffer, inBase + SplatParser.CenterSizeBytes + SplatParser.ScaleSizeBytes + SplatParser.ColorSizeBytes, 4); var quat = new Quaternion((inRotation[1] - 128) / 128, (inRotation[2] - 128) / 128, (inRotation[3] - 128) / 128, (inRotation[0] - 128) / 128); quat.normalize(); splatArray.addSplatFromComonents(inCenter[0], inCenter[1], inCenter[2], inScale[0], inScale[1], inScale[2], quat.w, quat.x, quat.y, quat.z, inColor[0], inColor[1], inColor[2], inColor[3]); } return splatArray; } } _defineProperty(SplatParser, "RowSizeBytes", 32); _defineProperty(SplatParser, "CenterSizeBytes", 12); _defineProperty(SplatParser, "ScaleSizeBytes", 12); _defineProperty(SplatParser, "RotationSizeBytes", 4); _defineProperty(SplatParser, "ColorSizeBytes", 4); class SplatLoader { static loadFromURL(fileName, onProgress, streamLoadData, onStreamedSectionProgress, minimumAlpha, compressionLevel, optimizeSplatData, sectionSize, sceneCenter, blockSize, bucketSize) { var splatDataOffsetBytes = SplatBuffer.HeaderSizeBytes + SplatBuffer.SectionHeaderSizeBytes; var streamSectionSizeBytes = Constants.StreamingSectionSize; var sectionCount = 1; var streamBufferIn; var streamBufferOut; var streamSplatBuffer; var maxSplatCount = 0; var splatCount = 0; var streamLoadCompleteResolver; var streamLoadPromise = new Promise(resolve => { streamLoadCompleteResolver = resolve; }); var numBytesStreamed = 0; var numBytesLoaded = 0; var chunks = []; var localOnProgress = (percent, percentStr, chunk, fileSize) => { var loadComplete = percent >= 100; if (!fileSize) streamLoadData = false; if (streamLoadData) { if (!streamBufferIn) { maxSplatCount = fileSize / SplatParser.RowSizeBytes; streamBufferIn = new ArrayBuffer(fileSize); var bytesPerSplat = SplatBuffer.CompressionLevels[0].SphericalHarmonicsDegrees[0].BytesPerSplat; var splatBufferSizeBytes = splatDataOffsetBytes + bytesPerSplat * maxSplatCount; streamBufferOut = new ArrayBuffer(splatBufferSizeBytes); SplatBuffer.writeHeaderToBuffer({ versionMajor: SplatBuffer.CurrentMajorVersion, versionMinor: SplatBuffer.CurrentMinorVersion, maxSectionCount: sectionCount, sectionCount: sectionCount, maxSplatCount: maxSplatCount, splatCount: splatCount, compressionLevel: 0, sceneCenter: new Vector3() }, streamBufferOut); } if (chunk) { chunks.push(chunk); new Uint8Array(streamBufferIn, numBytesLoaded, chunk.byteLength).set(new Uint8Array(chunk)); numBytesLoaded += chunk.byteLength; var bytesLoadedSinceLastSection = numBytesLoaded - numBytesStreamed; if (bytesLoadedSinceLastSection > streamSectionSizeBytes || loadComplete) { var bytesToUpdate = loadComplete ? bytesLoadedSinceLastSection : streamSectionSizeBytes; var addedSplatCount = bytesToUpdate / SplatParser.RowSizeBytes; var newSplatCount = splatCount + addedSplatCount; SplatParser.parseToUncompressedSplatBufferSection(splatCount, newSplatCount - 1, streamBufferIn, 0, streamBufferOut, splatDataOffsetBytes); splatCount = newSplatCount; if (!streamSplatBuffer) { SplatBuffer.writeSectionHeaderToBuffer({ maxSplatCount: maxSplatCount, splatCount: splatCount, bucketSize: 0, bucketCount: 0, bucketBlockSize: 0, compressionScaleRange: 0, storageSizeBytes: 0, fullBucketCount: 0, partiallyFilledBucketCount: 0 }, 0, streamBufferOut, SplatBuffer.HeaderSizeBytes); streamSplatBuffer = new SplatBuffer(streamBufferOut, false); } streamSplatBuffer.updateLoadedCounts(1, splatCount); onStreamedSectionProgress(streamSplatBuffer, loadComplete); numBytesStreamed += streamSectionSizeBytes; } } if (loadComplete) { streamLoadCompleteResolver(streamSplatBuffer); } } if (onProgress) onProgress(percent, percentStr, LoaderStatus.Downloading); return streamLoadData; }; return fetchWithProgress(fileName, localOnProgress, true).then(fullBuffer => { if (onProgress) onProgress(0, '0%', LoaderStatus.Processing); var loadPromise = streamLoadData ? streamLoadPromise : SplatLoader.loadFromFileData(fullBuffer, minimumAlpha, compressionLevel, optimizeSplatData, sectionSize, sceneCenter, blockSize, bucketSize); return loadPromise.then(splatBuffer => { if (onProgress) onProgress(100, '100%', LoaderStatus.Done); return splatBuffer; }); }); } static loadFromFileData(splatFileData, minimumAlpha, compressionLevel, optimizeSplatData, sectionSize, sceneCenter, blockSize, bucketSize) { return delayedExecute(() => { var splatArray = SplatParser.parseStandardSplatToUncompressedSplatArray(splatFileData); if (optimizeSplatData) { var splatBufferGenerator = SplatBufferGenerator.getStandardGenerator(minimumAlpha, compressionLevel, sectionSize, sceneCenter, blockSize, bucketSize); return splatBufferGenerator.generateFromUncompressedSplatArray(splatArray); } else { return SplatBuffer.generateFromUncompressedSplatArrays([splatArray], minimumAlpha, 0, new Vector3()); } }); } } class KSplatLoader { static checkVersion(buffer) { var minVersionMajor = SplatBuffer.CurrentMajorVersion; var minVersionMinor = SplatBuffer.CurrentMinorVersion; var header = SplatBuffer.parseHeader(buffer); if (header.versionMajor === minVersionMajor && header.versionMinor >= minVersionMinor || header.versionMajor > minVersionMajor) { return true; } else { throw new Error("KSplat version not supported: v".concat(header.versionMajor, ".").concat(header.versionMinor, ". ") + "Minimum required: v".concat(minVersionMajor, ".").concat(minVersionMinor)); } } static loadFromURL(fileName, onProgress, streamLoadData, onSectionBuilt) { var streamBuffer; var streamSplatBuffer; var headerBuffer; var header; var headerLoaded = false; var headerLoading = false; var sectionHeadersBuffer; var sectionHeaders = []; var sectionHeadersLoaded = false; var sectionHeadersLoading = false; var numBytesLoaded = 0; var numBytesStreamed = 0; var streamSectionSizeBytes = Constants.StreamingSectionSize; var totalBytesToDownload = 0; var loadComplete = false; var chunks = []; var streamLoadCompleteResolver; var streamLoadPromise = new Promise(resolve => { streamLoadCompleteResolver = resolve; }); var checkAndLoadHeader = () => { if (!headerLoaded && !headerLoading && numBytesLoaded >= SplatBuffer.HeaderSizeBytes) { headerLoading = true; var headerAssemblyPromise = new Blob(chunks).arrayBuffer(); headerAssemblyPromise.then(bufferData => { headerBuffer = new ArrayBuffer(SplatBuffer.HeaderSizeBytes); new Uint8Array(headerBuffer).set(new Uint8Array(bufferData, 0, SplatBuffer.HeaderSizeBytes)); KSplatLoader.checkVersion(headerBuffer); headerLoading = false; headerLoaded = true; header = SplatBuffer.parseHeader(headerBuffer); window.setTimeout(() => { checkAndLoadSectionHeaders(); }, 1); }); } }; var queuedCheckAndLoadSectionsCount = 0; var queueCheckAndLoadSections = () => { if (queuedCheckAndLoadSectionsCount === 0) { queuedCheckAndLoadSectionsCount++; window.setTimeout(() => { queuedCheckAndLoadSectionsCount--; checkAndLoadSections(true); }, 1); } }; var checkAndLoadSectionHeaders = () => { var performLoad = () => { sectionHeadersLoading = true; var sectionHeadersAssemblyPromise = new Blob(chunks).arrayBuffer(); sectionHeadersAssemblyPromise.then(bufferData => { sectionHeadersLoading = false; sectionHeadersLoaded = true; sectionHeadersBuffer = new ArrayBuffer(header.maxSectionCount * SplatBuffer.SectionHeaderSizeBytes); new Uint8Array(sectionHeadersBuffer).set(new Uint8Array(bufferData, SplatBuffer.HeaderSizeBytes, header.maxSectionCount * SplatBuffer.SectionHeaderSizeBytes)); sectionHeaders = SplatBuffer.parseSectionHeaders(header, sectionHeadersBuffer, 0, false); var totalSectionStorageStorageByes = 0; for (var i = 0; i < header.maxSectionCount; i++) { totalSectionStorageStorageByes += sectionHeaders[i].storageSizeBytes; } var totalStorageSizeBytes = SplatBuffer.HeaderSizeBytes + header.maxSectionCount * SplatBuffer.SectionHeaderSizeBytes + totalSectionStorageStorageByes; if (!streamBuffer) { streamBuffer = new ArrayBuffer(totalStorageSizeBytes); var offset = 0; for (var _i13 = 0; _i13 < chunks.length; _i13++) { var chunk = chunks[_i13]; new Uint8Array(streamBuffer, offset, chunk.byteLength).set(new Uint8Array(chunk)); offset += chunk.byteLength; } } totalBytesToDownload = SplatBuffer.HeaderSizeBytes + SplatBuffer.SectionHeaderSizeBytes * header.maxSectionCount; for (var _i14 = 0; _i14 <= sectionHeaders.length && _i14 < header.maxSectionCount; _i14++) { totalBytesToDownload += sectionHeaders[_i14].storageSizeBytes; } queueCheckAndLoadSections(); }); }; if (!sectionHeadersLoading && !sectionHeadersLoaded && headerLoaded && numBytesLoaded >= SplatBuffer.HeaderSizeBytes + SplatBuffer.SectionHeaderSizeBytes * header.maxSectionCount) { performLoad(); } }; var checkAndLoadSections = () => { if (sectionHeadersLoaded) { if (loadComplete) return; loadComplete = numBytesLoaded >= totalBytesToDownload; var bytesLoadedSinceLastSection = numBytesLoaded - numBytesStreamed; if (bytesLoadedSinceLastSection > streamSectionSizeBytes || loadComplete) { numBytesStreamed = numBytesLoaded; if (!streamSplatBuffer) streamSplatBuffer = new SplatBuffer(streamBuffer, false); var baseDataOffset = SplatBuffer.HeaderSizeBytes + SplatBuffer.SectionHeaderSizeBytes * header.maxSectionCount; var sectionBase = 0; var reachedSections = 0; var loadedSplatCount = 0; for (var i = 0; i < header.maxSectionCount; i++) { var sectionHeader = sectionHeaders[i]; var bucketsDataOffset = sectionBase + sectionHeader.partiallyFilledBucketCount * 4 + sectionHeader.bucketStorageSizeBytes * sectionHeader.bucketCount; var bytesRequiredToReachSectionSplatData = baseDataOffset + bucketsDataOffset; if (numBytesLoaded >= bytesRequiredToReachSectionSplatData) { reachedSections++; var bytesPastSSectionSplatDataStart = numBytesLoaded - bytesRequiredToReachSectionSplatData; var baseDescriptor = SplatBuffer.CompressionLevels[header.compressionLevel]; var shDesc = baseDescriptor.SphericalHarmonicsDegrees[sectionHeader.sphericalHarmonicsDegree]; var bytesPerSplat = shDesc.BytesPerSplat; var loadedSplatsForSection = Math.floor(bytesPastSSectionSplatDataStart / bytesPerSplat); loadedSplatsForSection = Math.min(loadedSplatsForSection, sectionHeader.maxSplatCount); loadedSplatCount += loadedSplatsForSection; streamSplatBuffer.updateLoadedCounts(reachedSections, loadedSplatCount); streamSplatBuffer.updateSectionLoadedCounts(i, loadedSplatsForSection); } else { break; } sectionBase += sectionHeader.storageSizeBytes; } onSectionBuilt(streamSplatBuffer, loadComplete); if (loadComplete) { streamLoadCompleteResolver(streamSplatBuffer); } } } }; var localOnProgress = (percent, percentStr, chunk) => { if (chunk) { chunks.push(chunk); if (streamBuffer) { new Uint8Array(streamBuffer, numBytesLoaded, chunk.byteLength).set(new Uint8Array(chunk)); } numBytesLoaded += chunk.byteLength; } if (streamLoadData) { checkAndLoadHeader(); checkAndLoadSectionHeaders(); checkAndLoadSections(); } if (onProgress) onProgress(percent, percentStr, LoaderStatus.Downloading); }; return fetchWithProgress(fileName, localOnProgress, !streamLoadData).then(fullBuffer => { if (onProgress) onProgress(0, '0%', LoaderStatus.Processing); var loadPromise = streamLoadData ? streamLoadPromise : KSplatLoader.loadFromFileData(fullBuffer); return loadPromise.then(splatBuffer => { if (onProgress) onProgress(100, '100%', LoaderStatus.Done); return splatBuffer; }); }); } static loadFromFileData(fileData) { return delayedExecute(() => { KSplatLoader.checkVersion(fileData); return new SplatBuffer(fileData); }); } } _defineProperty(KSplatLoader, "downloadFile", function () { var downLoadLink; return function (splatBuffer, fileName) { var blob = new Blob([splatBuffer.bufferData], { type: 'application/octet-stream' }); if (!downLoadLink) { downLoadLink = document.createElement('a'); document.body.appendChild(downLoadLink); } downLoadLink.download = fileName; downLoadLink.href = URL.createObjectURL(blob); downLoadLink.click(); }; }()); var SceneFormat = { 'Splat': 0, 'KSplat': 1, 'Ply': 2 }; var sceneFormatFromPath = path => { if (path.endsWith('.ply')) return SceneFormat.Ply;else if (path.endsWith('.splat')) return SceneFormat.Splat;else if (path.endsWith('.ksplat')) return SceneFormat.KSplat; return null; }; var Utils$1 = /*#__PURE__*/Object.freeze({ __proto__: null, sceneFormatFromPath: sceneFormatFromPath }); /* Copyright © 2010-2024 three.js authors & Mark Kellogg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ // OrbitControls performs orbiting, dollying (zooming), and panning. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default). // // Orbit - left mouse / touch: one-finger move // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move var _changeEvent = { type: 'change' }; var _startEvent = { type: 'start' }; var _endEvent = { type: 'end' }; var _ray$4 = new Ray(); var _plane = new Plane(); var TILT_LIMIT = Math.cos(70 * MathUtils.DEG2RAD); class OrbitControls extends EventDispatcher { constructor(object, domElement) { super(); this.object = object; this.domElement = domElement; this.domElement.style.touchAction = 'none'; // disable touch scroll // Set to false to disable this control this.enabled = true; // "target" sets the location of focus, where the object orbits around this.target = new Vector3(); // How far you can dolly in and out ( PerspectiveCamera only ) this.minDistance = 0; this.maxDistance = Infinity; // How far you can zoom in and out ( OrthographicCamera only ) this.minZoom = 0; this.maxZoom = Infinity; // How far you can orbit vertically, upper and lower limits. // Range is 0 to Math.PI radians. this.minPolarAngle = 0; // radians this.maxPolarAngle = Math.PI; // radians // How far you can orbit horizontally, upper and lower limits. // If set, the interval [min, max] must be a sub-interval of [- 2 PI, 2 PI], with ( max - min < 2 PI ) this.minAzimuthAngle = -Infinity; // radians this.maxAzimuthAngle = Infinity; // radians // Set to true to enable damping (inertia) // If damping is enabled, you must call controls.update() in your animation loop this.enableDamping = false; this.dampingFactor = 0.05; // This option actually enables dollying in and out; left as "zoom" for backwards compatibility. // Set to false to disable zooming this.enableZoom = true; this.zoomSpeed = 1.0; // Set to false to disable rotating this.enableRotate = true; this.rotateSpeed = 1.0; // Set to false to disable panning this.enablePan = true; this.panSpeed = 1.0; this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up this.keyPanSpeed = 7.0; // pixels moved per arrow key push this.zoomToCursor = false; // Set to true to automatically rotate around the target // If auto-rotate is enabled, you must call controls.update() in your animation loop this.autoRotate = false; this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60 // The four arrow keys this.keys = { LEFT: 'KeyA', UP: 'KeyW', RIGHT: 'KeyD', BOTTOM: 'KeyS' }; // Mouse buttons this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }; // Touch fingers this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }; // for reset this.target0 = this.target.clone(); this.position0 = this.object.position.clone(); this.zoom0 = this.object.zoom; // the target DOM element for key events this._domElementKeyEvents = null; // // public methods // this.getPolarAngle = function () { return spherical.phi; }; this.getAzimuthalAngle = function () { return spherical.theta; }; this.getDistance = function () { return this.object.position.distanceTo(this.target); }; this.listenToKeyEvents = function (domElement) { domElement.addEventListener('keydown', onKeyDown); this._domElementKeyEvents = domElement; }; this.stopListenToKeyEvents = function () { this._domElementKeyEvents.removeEventListener('keydown', onKeyDown); this._domElementKeyEvents = null; }; this.saveState = function () { scope.target0.copy(scope.target); scope.position0.copy(scope.object.position); scope.zoom0 = scope.object.zoom; }; this.reset = function () { scope.target.copy(scope.target0); scope.object.position.copy(scope.position0); scope.object.zoom = scope.zoom0; this.clearDampedRotation(); this.clearDampedPan(); scope.object.updateProjectionMatrix(); scope.dispatchEvent(_changeEvent); scope.update(); state = STATE.NONE; }; this.clearDampedRotation = function () { sphericalDelta.theta = 0.0; sphericalDelta.phi = 0.0; }; this.clearDampedPan = function () { panOffset.set(0, 0, 0); }; // this method is exposed, but perhaps it would be better if we can make it private... this.update = function () { var offset = new Vector3(); // so camera.up is the orbit axis var quat = new Quaternion().setFromUnitVectors(object.up, new Vector3(0, 1, 0)); var quatInverse = quat.clone().invert(); var lastPosition = new Vector3(); var lastQuaternion = new Quaternion(); var lastTargetPosition = new Vector3(); var twoPI = 2 * Math.PI; return function update() { quat.setFromUnitVectors(object.up, new Vector3(0, 1, 0)); quatInverse.copy(quat).invert(); var position = scope.object.position; offset.copy(position).sub(scope.target); // rotate offset to "y-axis-is-up" space offset.applyQuaternion(quat); // angle from z-axis around y-axis spherical.setFromVector3(offset); if (scope.autoRotate && state === STATE.NONE) { rotateLeft(getAutoRotationAngle()); } if (scope.enableDamping) { spherical.theta += sphericalDelta.theta * scope.dampingFactor; spherical.phi += sphericalDelta.phi * scope.dampingFactor; } else { spherical.theta += sphericalDelta.theta; spherical.phi += sphericalDelta.phi; } // restrict theta to be between desired limits var min = scope.minAzimuthAngle; var max = scope.maxAzimuthAngle; if (isFinite(min) && isFinite(max)) { if (min < -Math.PI) min += twoPI;else if (min > Math.PI) min -= twoPI; if (max < -Math.PI) max += twoPI;else if (max > Math.PI) max -= twoPI; if (min <= max) { spherical.theta = Math.max(min, Math.min(max, spherical.theta)); } else { spherical.theta = spherical.theta > (min + max) / 2 ? Math.max(min, spherical.theta) : Math.min(max, spherical.theta); } } // restrict phi to be between desired limits spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi)); spherical.makeSafe(); // move target to panned location if (scope.enableDamping === true) { scope.target.addScaledVector(panOffset, scope.dampingFactor); } else { scope.target.add(panOffset); } // adjust the camera position based on zoom only if we're not zooming to the cursor or if it's an ortho camera // we adjust zoom later in these cases if (scope.zoomToCursor && performCursorZoom || scope.object.isOrthographicCamera) { spherical.radius = clampDistance(spherical.radius); } else { spherical.radius = clampDistance(spherical.radius * scale); } offset.setFromSpherical(spherical); // rotate offset back to "camera-up-vector-is-up" space offset.applyQuaternion(quatInverse); position.copy(scope.target).add(offset); scope.object.lookAt(scope.target); if (scope.enableDamping === true) { sphericalDelta.theta *= 1 - scope.dampingFactor; sphericalDelta.phi *= 1 - scope.dampingFactor; panOffset.multiplyScalar(1 - scope.dampingFactor); } else { sphericalDelta.set(0, 0, 0); panOffset.set(0, 0, 0); } // adjust camera position var zoomChanged = false; if (scope.zoomToCursor && performCursorZoom) { var newRadius = null; if (scope.object.isPerspectiveCamera) { // move the camera down the pointer ray // this method avoids floating point error var prevRadius = offset.length(); newRadius = clampDistance(prevRadius * scale); var radiusDelta = prevRadius - newRadius; scope.object.position.addScaledVector(dollyDirection, radiusDelta); scope.object.updateMatrixWorld(); } else if (scope.object.isOrthographicCamera) { // adjust the ortho camera position based on zoom changes var mouseBefore = new Vector3(mouse.x, mouse.y, 0); mouseBefore.unproject(scope.object); scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / scale)); scope.object.updateProjectionMatrix(); zoomChanged = true; var mouseAfter = new Vector3(mouse.x, mouse.y, 0); mouseAfter.unproject(scope.object); scope.object.position.sub(mouseAfter).add(mouseBefore); scope.object.updateMatrixWorld(); newRadius = offset.length(); } else { console.warn('WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled.'); scope.zoomToCursor = false; } // handle the placement of the target if (newRadius !== null) { if (this.screenSpacePanning) { // position the orbit target in front of the new camera position scope.target.set(0, 0, -1).transformDirection(scope.object.matrix).multiplyScalar(newRadius).add(scope.object.position); } else { // get the ray and translation plane to compute target _ray$4.origin.copy(scope.object.position); _ray$4.direction.set(0, 0, -1).transformDirection(scope.object.matrix); // if the camera is 20 degrees above the horizon then don't adjust the focus target to avoid // extremely large values if (Math.abs(scope.object.up.dot(_ray$4.direction)) < TILT_LIMIT) { object.lookAt(scope.target); } else { _plane.setFromNormalAndCoplanarPoint(scope.object.up, scope.target); _ray$4.intersectPlane(_plane, scope.target); } } } } else if (scope.object.isOrthographicCamera) { scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / scale)); scope.object.updateProjectionMatrix(); zoomChanged = true; } scale = 1; performCursorZoom = false; // update condition is: // min(camera displacement, camera rotation in radians)^2 > EPS // using small-angle approximation cos(x/2) = 1 - x^2 / 8 if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS || lastTargetPosition.distanceToSquared(scope.target) > 0) { scope.dispatchEvent(_changeEvent); lastPosition.copy(scope.object.position); lastQuaternion.copy(scope.object.quaternion); lastTargetPosition.copy(scope.target); zoomChanged = false; return true; } return false; }; }(); this.dispose = function () { scope.domElement.removeEventListener('contextmenu', onContextMenu); scope.domElement.removeEventListener('pointerdown', onPointerDown); scope.domElement.removeEventListener('pointercancel', onPointerUp); scope.domElement.removeEventListener('wheel', onMouseWheel); scope.domElement.removeEventListener('pointermove', onPointerMove); scope.domElement.removeEventListener('pointerup', onPointerUp); if (scope._domElementKeyEvents !== null) { scope._domElementKeyEvents.removeEventListener('keydown', onKeyDown); scope._domElementKeyEvents = null; } }; // // internals // var scope = this; var STATE = { NONE: -1, ROTATE: 0, DOLLY: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_PAN: 4, TOUCH_DOLLY_PAN: 5, TOUCH_DOLLY_ROTATE: 6 }; var state = STATE.NONE; var EPS = 0.000001; // current position in spherical coordinates var spherical = new Spherical(); var sphericalDelta = new Spherical(); var scale = 1; var panOffset = new Vector3(); var rotateStart = new Vector2(); var rotateEnd = new Vector2(); var rotateDelta = new Vector2(); var panStart = new Vector2(); var panEnd = new Vector2(); var panDelta = new Vector2(); var dollyStart = new Vector2(); var dollyEnd = new Vector2(); var dollyDelta = new Vector2(); var dollyDirection = new Vector3(); var mouse = new Vector2(); var performCursorZoom = false; var pointers = []; var pointerPositions = {}; function getAutoRotationAngle() { return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; } function getZoomScale() { return Math.pow(0.95, scope.zoomSpeed); } function rotateLeft(angle) { sphericalDelta.theta -= angle; } function rotateUp(angle) { sphericalDelta.phi -= angle; } var panLeft = function () { var v = new Vector3(); return function panLeft(distance, objectMatrix) { v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix v.multiplyScalar(-distance); panOffset.add(v); }; }(); var panUp = function () { var v = new Vector3(); return function panUp(distance, objectMatrix) { if (scope.screenSpacePanning === true) { v.setFromMatrixColumn(objectMatrix, 1); } else { v.setFromMatrixColumn(objectMatrix, 0); v.crossVectors(scope.object.up, v); } v.multiplyScalar(distance); panOffset.add(v); }; }(); // deltaX and deltaY are in pixels; right and down are positive var pan = function () { var offset = new Vector3(); return function pan(deltaX, deltaY) { var element = scope.domElement; if (scope.object.isPerspectiveCamera) { // perspective var position = scope.object.position; offset.copy(position).sub(scope.target); var targetDistance = offset.length(); // half of the fov is center to top of screen targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180.0); // we use only clientHeight here so aspect ratio does not distort speed panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix); panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix); } else if (scope.object.isOrthographicCamera) { // orthographic panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix); panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix); } else { // camera neither orthographic nor perspective console.warn('WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.'); scope.enablePan = false; } }; }(); function dollyOut(dollyScale) { if (scope.object.isPerspectiveCamera || scope.object.isOrthographicCamera) { scale /= dollyScale; } else { console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.'); scope.enableZoom = false; } } function dollyIn(dollyScale) { if (scope.object.isPerspectiveCamera || scope.object.isOrthographicCamera) { scale *= dollyScale; } else { console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.'); scope.enableZoom = false; } } function updateMouseParameters(event) { if (!scope.zoomToCursor) { return; } performCursorZoom = true; var rect = scope.domElement.getBoundingClientRect(); var x = event.clientX - rect.left; var y = event.clientY - rect.top; var w = rect.width; var h = rect.height; mouse.x = x / w * 2 - 1; mouse.y = -(y / h) * 2 + 1; dollyDirection.set(mouse.x, mouse.y, 1).unproject(object).sub(object.position).normalize(); } function clampDistance(dist) { return Math.max(scope.minDistance, Math.min(scope.maxDistance, dist)); } // // event callbacks - update the object state // function handleMouseDownRotate(event) { rotateStart.set(event.clientX, event.clientY); } function handleMouseDownDolly(event) { updateMouseParameters(event); dollyStart.set(event.clientX, event.clientY); } function handleMouseDownPan(event) { panStart.set(event.clientX, event.clientY); } function handleMouseMoveRotate(event) { rotateEnd.set(event.clientX, event.clientY); rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed); var element = scope.domElement; rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight); rotateStart.copy(rotateEnd); scope.update(); } function handleMouseMoveDolly(event) { dollyEnd.set(event.clientX, event.clientY); dollyDelta.subVectors(dollyEnd, dollyStart); if (dollyDelta.y > 0) { dollyOut(getZoomScale()); } else if (dollyDelta.y < 0) { dollyIn(getZoomScale()); } dollyStart.copy(dollyEnd); scope.update(); } function handleMouseMovePan(event) { panEnd.set(event.clientX, event.clientY); panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed); pan(panDelta.x, panDelta.y); panStart.copy(panEnd); scope.update(); } function handleMouseWheel(event) { updateMouseParameters(event); if (event.deltaY < 0) { dollyIn(getZoomScale()); } else if (event.deltaY > 0) { dollyOut(getZoomScale()); } scope.update(); } function handleKeyDown(event) { var needsUpdate = false; switch (event.code) { case scope.keys.UP: if (event.ctrlKey || event.metaKey || event.shiftKey) { rotateUp(2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight); } else { pan(0, scope.keyPanSpeed); } needsUpdate = true; break; case scope.keys.BOTTOM: if (event.ctrlKey || event.metaKey || event.shiftKey) { rotateUp(-2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight); } else { pan(0, -scope.keyPanSpeed); } needsUpdate = true; break; case scope.keys.LEFT: if (event.ctrlKey || event.metaKey || event.shiftKey) { rotateLeft(2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight); } else { pan(scope.keyPanSpeed, 0); } needsUpdate = true; break; case scope.keys.RIGHT: if (event.ctrlKey || event.metaKey || event.shiftKey) { rotateLeft(-2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight); } else { pan(-scope.keyPanSpeed, 0); } needsUpdate = true; break; } if (needsUpdate) { // prevent the browser from scrolling on cursor keys event.preventDefault(); scope.update(); } } function handleTouchStartRotate() { if (pointers.length === 1) { rotateStart.set(pointers[0].pageX, pointers[0].pageY); } else { var x = 0.5 * (pointers[0].pageX + pointers[1].pageX); var y = 0.5 * (pointers[0].pageY + pointers[1].pageY); rotateStart.set(x, y); } } function handleTouchStartPan() { if (pointers.length === 1) { panStart.set(pointers[0].pageX, pointers[0].pageY); } else { var x = 0.5 * (pointers[0].pageX + pointers[1].pageX); var y = 0.5 * (pointers[0].pageY + pointers[1].pageY); panStart.set(x, y); } } function handleTouchStartDolly() { var dx = pointers[0].pageX - pointers[1].pageX; var dy = pointers[0].pageY - pointers[1].pageY; var distance = Math.sqrt(dx * dx + dy * dy); dollyStart.set(0, distance); } function handleTouchStartDollyPan() { if (scope.enableZoom) handleTouchStartDolly(); if (scope.enablePan) handleTouchStartPan(); } function handleTouchStartDollyRotate() { if (scope.enableZoom) handleTouchStartDolly(); if (scope.enableRotate) handleTouchStartRotate(); } function handleTouchMoveRotate(event) { if (pointers.length == 1) { rotateEnd.set(event.pageX, event.pageY); } else { var position = getSecondPointerPosition(event); var x = 0.5 * (event.pageX + position.x); var y = 0.5 * (event.pageY + position.y); rotateEnd.set(x, y); } rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed); var element = scope.domElement; rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight); rotateStart.copy(rotateEnd); } function handleTouchMovePan(event) { if (pointers.length === 1) { panEnd.set(event.pageX, event.pageY); } else { var position = getSecondPointerPosition(event); var x = 0.5 * (event.pageX + position.x); var y = 0.5 * (event.pageY + position.y); panEnd.set(x, y); } panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed); pan(panDelta.x, panDelta.y); panStart.copy(panEnd); } function handleTouchMoveDolly(event) { var position = getSecondPointerPosition(event); var dx = event.pageX - position.x; var dy = event.pageY - position.y; var distance = Math.sqrt(dx * dx + dy * dy); dollyEnd.set(0, distance); dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed)); dollyOut(dollyDelta.y); dollyStart.copy(dollyEnd); } function handleTouchMoveDollyPan(event) { if (scope.enableZoom) handleTouchMoveDolly(event); if (scope.enablePan) handleTouchMovePan(event); } function handleTouchMoveDollyRotate(event) { if (scope.enableZoom) handleTouchMoveDolly(event); if (scope.enableRotate) handleTouchMoveRotate(event); } // // event handlers - FSM: listen for events and reset state // function onPointerDown(event) { if (scope.enabled === false) return; if (pointers.length === 0) { scope.domElement.setPointerCapture(event.pointerId); scope.domElement.addEventListener('pointermove', onPointerMove); scope.domElement.addEventListener('pointerup', onPointerUp); } // addPointer(event); if (event.pointerType === 'touch') { onTouchStart(event); } else { onMouseDown(event); } } function onPointerMove(event) { if (scope.enabled === false) return; if (event.pointerType === 'touch') { onTouchMove(event); } else { onMouseMove(event); } } function onPointerUp(event) { removePointer(event); if (pointers.length === 0) { scope.domElement.releasePointerCapture(event.pointerId); scope.domElement.removeEventListener('pointermove', onPointerMove); scope.domElement.removeEventListener('pointerup', onPointerUp); } scope.dispatchEvent(_endEvent); state = STATE.NONE; } function onMouseDown(event) { var mouseAction; switch (event.button) { case 0: mouseAction = scope.mouseButtons.LEFT; break; case 1: mouseAction = scope.mouseButtons.MIDDLE; break; case 2: mouseAction = scope.mouseButtons.RIGHT; break; default: mouseAction = -1; } switch (mouseAction) { case MOUSE.DOLLY: if (scope.enableZoom === false) return; handleMouseDownDolly(event); state = STATE.DOLLY; break; case MOUSE.ROTATE: if (event.ctrlKey || event.metaKey || event.shiftKey) { if (scope.enablePan === false) return; handleMouseDownPan(event); state = STATE.PAN; } else { if (scope.enableRotate === false) return; handleMouseDownRotate(event); state = STATE.ROTATE; } break; case MOUSE.PAN: if (event.ctrlKey || event.metaKey || event.shiftKey) { if (scope.enableRotate === false) return; handleMouseDownRotate(event); state = STATE.ROTATE; } else { if (scope.enablePan === false) return; handleMouseDownPan(event); state = STATE.PAN; } break; default: state = STATE.NONE; } if (state !== STATE.NONE) { scope.dispatchEvent(_startEvent); } } function onMouseMove(event) { switch (state) { case STATE.ROTATE: if (scope.enableRotate === false) return; handleMouseMoveRotate(event); break; case STATE.DOLLY: if (scope.enableZoom === false) return; handleMouseMoveDolly(event); break; case STATE.PAN: if (scope.enablePan === false) return; handleMouseMovePan(event); break; } } function onMouseWheel(event) { if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE) return; event.preventDefault(); scope.dispatchEvent(_startEvent); handleMouseWheel(event); scope.dispatchEvent(_endEvent); } function onKeyDown(event) { if (scope.enabled === false || scope.enablePan === false) return; handleKeyDown(event); } function onTouchStart(event) { trackPointer(event); switch (pointers.length) { case 1: switch (scope.touches.ONE) { case TOUCH.ROTATE: if (scope.enableRotate === false) return; handleTouchStartRotate(); state = STATE.TOUCH_ROTATE; break; case TOUCH.PAN: if (scope.enablePan === false) return; handleTouchStartPan(); state = STATE.TOUCH_PAN; break; default: state = STATE.NONE; } break; case 2: switch (scope.touches.TWO) { case TOUCH.DOLLY_PAN: if (scope.enableZoom === false && scope.enablePan === false) return; handleTouchStartDollyPan(); state = STATE.TOUCH_DOLLY_PAN; break; case TOUCH.DOLLY_ROTATE: if (scope.enableZoom === false && scope.enableRotate === false) return; handleTouchStartDollyRotate(); state = STATE.TOUCH_DOLLY_ROTATE; break; default: state = STATE.NONE; } break; default: state = STATE.NONE; } if (state !== STATE.NONE) { scope.dispatchEvent(_startEvent); } } function onTouchMove(event) { trackPointer(event); switch (state) { case STATE.TOUCH_ROTATE: if (scope.enableRotate === false) return; handleTouchMoveRotate(event); scope.update(); break; case STATE.TOUCH_PAN: if (scope.enablePan === false) return; handleTouchMovePan(event); scope.update(); break; case STATE.TOUCH_DOLLY_PAN: if (scope.enableZoom === false && scope.enablePan === false) return; handleTouchMoveDollyPan(event); scope.update(); break; case STATE.TOUCH_DOLLY_ROTATE: if (scope.enableZoom === false && scope.enableRotate === false) return; handleTouchMoveDollyRotate(event); scope.update(); break; default: state = STATE.NONE; } } function onContextMenu(event) { if (scope.enabled === false) return; event.preventDefault(); } function addPointer(event) { pointers.push(event); } function removePointer(event) { delete pointerPositions[event.pointerId]; for (var i = 0; i < pointers.length; i++) { if (pointers[i].pointerId == event.pointerId) { pointers.splice(i, 1); return; } } } function trackPointer(event) { var position = pointerPositions[event.pointerId]; if (position === undefined) { position = new Vector2(); pointerPositions[event.pointerId] = position; } position.set(event.pageX, event.pageY); } function getSecondPointerPosition(event) { var pointer = event.pointerId === pointers[0].pointerId ? pointers[1] : pointers[0]; return pointerPositions[pointer.pointerId]; } // scope.domElement.addEventListener('contextmenu', onContextMenu); scope.domElement.addEventListener('pointerdown', onPointerDown); scope.domElement.addEventListener('pointercancel', onPointerUp); scope.domElement.addEventListener('wheel', onMouseWheel, { passive: false }); // force an update at start this.update(); } } var fadeElement = (element, out, displayStyle, duration, onComplete) => { var startTime = performance.now(); var startOpacity = element.style.display === 'none' ? 0 : parseFloat(element.style.opacity); if (isNaN(startOpacity)) startOpacity = 1; var interval = window.setInterval(() => { var currentTime = performance.now(); var elapsed = currentTime - startTime; var t = Math.min(elapsed / duration, 1.0); if (t > 0.999) t = 1; var opacity; if (out) { opacity = (1.0 - t) * startOpacity; if (opacity < 0.0001) opacity = 0; } else { opacity = (1.0 - startOpacity) * t + startOpacity; } if (opacity > 0) { element.style.display = displayStyle; element.style.opacity = opacity; } else { element.style.display = 'none'; } if (t >= 1) { if (onComplete) onComplete(); window.clearInterval(interval); } }, 16); return interval; }; var cancelFade = interval => { window.clearInterval(interval); }; var STANDARD_FADE_DURATION = 500; class LoadingSpinner { constructor(message, container) { this.taskIDGen = 0; this.elementID = LoadingSpinner.elementIDGen++; this.tasks = []; this.message = message || 'Loading...'; this.container = container || document.body; this.spinnerContainerOuter = document.createElement('div'); this.spinnerContainerOuter.className = "spinnerOuterContainer".concat(this.elementID); this.spinnerContainerOuter.style.display = 'none'; this.spinnerContainerPrimary = document.createElement('div'); this.spinnerContainerPrimary.className = "spinnerContainerPrimary".concat(this.elementID); this.spinnerPrimary = document.createElement('div'); this.spinnerPrimary.classList.add("spinner".concat(this.elementID), "spinnerPrimary".concat(this.elementID)); this.messageContainerPrimary = document.createElement('div'); this.messageContainerPrimary.classList.add("messageContainer".concat(this.elementID), "messageContainerPrimary".concat(this.elementID)); this.messageContainerPrimary.innerHTML = this.message; this.spinnerContainerMin = document.createElement('div'); this.spinnerContainerMin.className = "spinnerContainerMin".concat(this.elementID); this.spinnerMin = document.createElement('div'); this.spinnerMin.classList.add("spinner".concat(this.elementID), "spinnerMin".concat(this.elementID)); this.messageContainerMin = document.createElement('div'); this.messageContainerMin.classList.add("messageContainer".concat(this.elementID), "messageContainerMin".concat(this.elementID)); this.messageContainerMin.innerHTML = this.message; this.spinnerContainerPrimary.appendChild(this.spinnerPrimary); this.spinnerContainerPrimary.appendChild(this.messageContainerPrimary); this.spinnerContainerOuter.appendChild(this.spinnerContainerPrimary); this.spinnerContainerMin.appendChild(this.spinnerMin); this.spinnerContainerMin.appendChild(this.messageContainerMin); this.spinnerContainerOuter.appendChild(this.spinnerContainerMin); var style = document.createElement('style'); style.innerHTML = "\n\n .spinnerOuterContainer".concat(this.elementID, " {\n width: 100%;\n height: 100%;\n margin: 0;\n top: 0;\n left: 0;\n position: absolute;\n pointer-events: none;\n }\n\n .messageContainer").concat(this.elementID, " {\n height: 20px;\n font-family: arial;\n font-size: 12pt;\n color: #ffffff;\n text-align: center;\n vertical-align: middle;\n }\n\n .spinner").concat(this.elementID, " {\n padding: 15px;\n background: #07e8d6;\n z-index:99999;\n \n aspect-ratio: 1;\n border-radius: 50%;\n --_m: \n conic-gradient(#0000,#000),\n linear-gradient(#000 0 0) content-box;\n -webkit-mask: var(--_m);\n mask: var(--_m);\n -webkit-mask-composite: source-out;\n mask-composite: subtract;\n box-sizing: border-box;\n animation: load 1s linear infinite;\n }\n\n .spinnerContainerPrimary").concat(this.elementID, " {\n z-index:99999;\n background-color: rgba(128, 128, 128, 0.75);\n border: #666666 1px solid;\n border-radius: 5px;\n padding-top: 20px;\n padding-bottom: 10px;\n margin: 0;\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-80px, -80px);\n width: 180px;\n pointer-events: auto;\n }\n\n .spinnerPrimary").concat(this.elementID, " {\n width: 120px;\n margin-left: 30px;\n }\n\n .messageContainerPrimary").concat(this.elementID, " {\n padding-top: 15px;\n }\n\n .spinnerContainerMin").concat(this.elementID, " {\n z-index:99999;\n background-color: rgba(128, 128, 128, 0.75);\n border: #666666 1px solid;\n border-radius: 5px;\n padding-top: 20px;\n padding-bottom: 15px;\n margin: 0;\n position: absolute;\n bottom: 50px;\n left: 50%;\n transform: translate(-50%, 0);\n display: flex;\n flex-direction: left;\n pointer-events: auto;\n min-width: 250px;\n }\n\n .messageContainerMin").concat(this.elementID, " {\n margin-right: 15px;\n }\n\n .spinnerMin").concat(this.elementID, " {\n width: 50px;\n height: 50px;\n margin-left: 15px;\n margin-right: 25px;\n }\n\n .messageContainerMin").concat(this.elementID, " {\n padding-top: 15px;\n }\n \n @keyframes load {\n to{transform: rotate(1turn)}\n }\n\n "); this.spinnerContainerOuter.appendChild(style); this.container.appendChild(this.spinnerContainerOuter); this.setMinimized(false, true); this.fadeTransitions = []; } addTask(message) { var newTask = { 'message': message, 'id': this.taskIDGen++ }; this.tasks.push(newTask); this.update(); return newTask.id; } removeTask(id) { var index = 0; for (var task of this.tasks) { if (task.id === id) { this.tasks.splice(index, 1); break; } index++; } this.update(); } removeAllTasks() { this.tasks = []; this.update(); } setMessageForTask(id, message) { for (var task of this.tasks) { if (task.id === id) { task.message = message; break; } } this.update(); } update() { if (this.tasks.length > 0) { this.show(); this.setMessage(this.tasks[this.tasks.length - 1].message); } else { this.hide(); } } show() { this.spinnerContainerOuter.style.display = 'block'; this.visible = true; } hide() { this.spinnerContainerOuter.style.display = 'none'; this.visible = false; } setContainer(container) { if (this.container) { this.container.removeChild(this.spinnerContainerOuter); } if (container) { this.container = container; this.container.appendChild(this.spinnerContainerOuter); this.spinnerContainerOuter.style.zIndex = this.container.style.zIndex + 1; } } setMinimized(minimized, instant) { var showHideSpinner = (element, show, instant, displayStyle, fadeTransitionsIndex) => { if (instant) { element.style.display = show ? displayStyle : 'none'; } else { this.fadeTransitions[fadeTransitionsIndex] = fadeElement(element, !show, displayStyle, STANDARD_FADE_DURATION, () => { this.fadeTransitions[fadeTransitionsIndex] = null; }); } }; showHideSpinner(this.spinnerContainerPrimary, !minimized, instant, 'block', 0); showHideSpinner(this.spinnerContainerMin, minimized, instant, 'flex', 1); this.minimized = minimized; } setMessage(msg) { this.messageContainerPrimary.innerHTML = msg; this.messageContainerMin.innerHTML = msg; } } _defineProperty(LoadingSpinner, "elementIDGen", 0); class LoadingProgressBar { constructor(container) { this.idGen = 0; this.tasks = []; this.container = container || document.body; this.progressBarContainerOuter = document.createElement('div'); this.progressBarContainerOuter.className = 'progressBarOuterContainer'; this.progressBarContainerOuter.style.display = 'none'; this.progressBarBox = document.createElement('div'); this.progressBarBox.className = 'progressBarBox'; this.progressBarBackground = document.createElement('div'); this.progressBarBackground.className = 'progressBarBackground'; this.progressBar = document.createElement('div'); this.progressBar.className = 'progressBar'; this.progressBarBackground.appendChild(this.progressBar); this.progressBarBox.appendChild(this.progressBarBackground); this.progressBarContainerOuter.appendChild(this.progressBarBox); var style = document.createElement('style'); style.innerHTML = "\n\n .progressBarOuterContainer {\n width: 100%;\n height: 100%;\n margin: 0;\n top: 0;\n left: 0;\n position: absolute;\n pointer-events: none;\n }\n\n .progressBarBox {\n z-index:99999;\n padding: 7px 9px 5px 7px;\n background-color: rgba(190, 190, 190, 0.75);\n border: #555555 1px solid;\n border-radius: 15px;\n margin: 0;\n position: absolute;\n bottom: 50px;\n left: 50%;\n transform: translate(-50%, 0);\n width: 180px;\n height: 30px;\n pointer-events: auto;\n }\n\n .progressBarBackground {\n width: 100%;\n height: 25px;\n border-radius:10px;\n background-color: rgba(128, 128, 128, 0.75);\n border: #444444 1px solid;\n box-shadow: inset 0 0 10px #333333;\n }\n\n .progressBar {\n height: 25px;\n width: 0px;\n border-radius:10px;\n background-color: rgba(0, 200, 0, 0.75);\n box-shadow: inset 0 0 10px #003300;\n }\n\n "; this.progressBarContainerOuter.appendChild(style); this.container.appendChild(this.progressBarContainerOuter); } show() { this.progressBarContainerOuter.style.display = 'block'; } hide() { this.progressBarContainerOuter.style.display = 'none'; } setProgress(progress) { this.progressBar.style.width = progress + '%'; } setContainer(container) { if (this.container) { this.container.removeChild(this.progressBarContainerOuter); } if (container) { this.container = container; this.container.appendChild(this.progressBarContainerOuter); this.progressBarContainerOuter.style.zIndex = this.container.style.zIndex + 1; } } } class InfoPanel { constructor(container) { _defineProperty(this, "update", function (renderDimensions, cameraPosition, cameraLookAtPosition, cameraUp, orthographicCamera, meshCursorPosition, currentFPS, splatCount, splatRenderCount, splatRenderCountPct, lastSortTime, focalAdjustment, splatScale, pointCloudMode) { var cameraPosString = "".concat(cameraPosition.x.toFixed(5), ", ").concat(cameraPosition.y.toFixed(5), ", ").concat(cameraPosition.z.toFixed(5)); if (this.infoCells.cameraPosition.innerHTML !== cameraPosString) { this.infoCells.cameraPosition.innerHTML = cameraPosString; } if (cameraLookAtPosition) { var cla = cameraLookAtPosition; var cameraLookAtString = "".concat(cla.x.toFixed(5), ", ").concat(cla.y.toFixed(5), ", ").concat(cla.z.toFixed(5)); if (this.infoCells.cameraLookAt.innerHTML !== cameraLookAtString) { this.infoCells.cameraLookAt.innerHTML = cameraLookAtString; } } var cameraUpString = "".concat(cameraUp.x.toFixed(5), ", ").concat(cameraUp.y.toFixed(5), ", ").concat(cameraUp.z.toFixed(5)); if (this.infoCells.cameraUp.innerHTML !== cameraUpString) { this.infoCells.cameraUp.innerHTML = cameraUpString; } this.infoCells.orthographicCamera.innerHTML = orthographicCamera ? 'Orthographic' : 'Perspective'; if (meshCursorPosition) { var cursPos = meshCursorPosition; var cursorPosString = "".concat(cursPos.x.toFixed(5), ", ").concat(cursPos.y.toFixed(5), ", ").concat(cursPos.z.toFixed(5)); this.infoCells.cursorPosition.innerHTML = cursorPosString; } else { this.infoCells.cursorPosition.innerHTML = 'N/A'; } this.infoCells.fps.innerHTML = currentFPS; this.infoCells.renderWindow.innerHTML = "".concat(renderDimensions.x, " x ").concat(renderDimensions.y); this.infoCells.renderSplatCount.innerHTML = "".concat(splatRenderCount, " splats out of ").concat(splatCount, " (").concat(splatRenderCountPct.toFixed(2), "%)"); this.infoCells.sortTime.innerHTML = "".concat(lastSortTime.toFixed(3), " ms"); this.infoCells.focalAdjustment.innerHTML = "".concat(focalAdjustment.toFixed(3)); this.infoCells.splatScale.innerHTML = "".concat(splatScale.toFixed(3)); this.infoCells.pointCloudMode.innerHTML = "".concat(pointCloudMode); }); this.container = container || document.body; this.infoCells = {}; var layout = [['Camera position', 'cameraPosition'], ['Camera look-at', 'cameraLookAt'], ['Camera up', 'cameraUp'], ['Camera mode', 'orthographicCamera'], ['Cursor position', 'cursorPosition'], ['FPS', 'fps'], ['Rendering:', 'renderSplatCount'], ['Sort time', 'sortTime'], ['Render window', 'renderWindow'], ['Focal adjustment', 'focalAdjustment'], ['Splat scale', 'splatScale'], ['Point cloud mode', 'pointCloudMode']]; this.infoPanelContainer = document.createElement('div'); var style = document.createElement('style'); style.innerHTML = "\n\n .infoPanel {\n width: 430px;\n padding: 10px;\n background-color: rgba(50, 50, 50, 0.85);\n border: #555555 2px solid;\n color: #dddddd;\n border-radius: 10px;\n z-index: 9999;\n font-family: arial;\n font-size: 11pt;\n text-align: left;\n margin: 0;\n top: 10px;\n left:10px;\n position: absolute;\n pointer-events: auto;\n }\n\n .info-panel-cell {\n margin-bottom: 5px;\n padding-bottom: 2px;\n }\n\n .label-cell {\n font-weight: bold;\n font-size: 12pt;\n width: 140px;\n }\n\n "; this.infoPanelContainer.append(style); this.infoPanel = document.createElement('div'); this.infoPanel.className = 'infoPanel'; var infoTable = document.createElement('div'); infoTable.style.display = 'table'; for (var layoutEntry of layout) { var row = document.createElement('div'); row.style.display = 'table-row'; row.className = 'info-panel-row'; var labelCell = document.createElement('div'); labelCell.style.display = 'table-cell'; labelCell.innerHTML = "".concat(layoutEntry[0], ": "); labelCell.classList.add('info-panel-cell', 'label-cell'); var spacerCell = document.createElement('div'); spacerCell.style.display = 'table-cell'; spacerCell.style.width = '10px'; spacerCell.innerHTML = ' '; spacerCell.className = 'info-panel-cell'; var infoCell = document.createElement('div'); infoCell.style.display = 'table-cell'; infoCell.innerHTML = ''; infoCell.className = 'info-panel-cell'; this.infoCells[layoutEntry[1]] = infoCell; row.appendChild(labelCell); row.appendChild(spacerCell); row.appendChild(infoCell); infoTable.appendChild(row); } this.infoPanel.appendChild(infoTable); this.infoPanelContainer.append(this.infoPanel); this.infoPanelContainer.style.display = 'none'; this.container.appendChild(this.infoPanelContainer); this.visible = false; } setContainer(container) { if (this.container) { this.container.removeChild(this.infoPanelContainer); } if (container) { this.container = container; this.container.appendChild(this.infoPanelContainer); this.infoPanelContainer.style.zIndex = this.container.style.zIndex + 1; } } show() { this.infoPanelContainer.style.display = 'block'; this.visible = true; } hide() { this.infoPanelContainer.style.display = 'none'; this.visible = false; } } class ArrowHelper$1 extends Object3D { constructor() { var dir = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Vector3(0, 0, 1); var origin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Vector3(0, 0, 0); var length = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; var radius = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0.1; var color = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0xffff00; var headLength = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : length * 0.2; var headRadius = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : headLength * 0.2; super(); this.type = 'ArrowHelper'; var lineGeometry = new CylinderGeometry(radius, radius, length, 32); lineGeometry.translate(0, length / 2.0, 0); var coneGeometry = new CylinderGeometry(0, headRadius, headLength, 32); coneGeometry.translate(0, length, 0); this.position.copy(origin); this.line = new Mesh(lineGeometry, new MeshBasicMaterial({ color: color, toneMapped: false })); this.line.matrixAutoUpdate = false; this.add(this.line); this.cone = new Mesh(coneGeometry, new MeshBasicMaterial({ color: color, toneMapped: false })); this.cone.matrixAutoUpdate = false; this.add(this.cone); this.setDirection(dir); } setDirection(dir) { if (dir.y > 0.99999) { this.quaternion.set(0, 0, 0, 1); } else if (dir.y < -0.99999) { this.quaternion.set(1, 0, 0, 0); } else { _axis.set(dir.z, 0, -dir.x).normalize(); var radians = Math.acos(dir.y); this.quaternion.setFromAxisAngle(_axis, radians); } } setColor(color) { this.line.material.color.set(color); this.cone.material.color.set(color); } copy(source) { super.copy(source, false); this.line.copy(source.line); this.cone.copy(source.cone); return this; } dispose() { this.line.geometry.dispose(); this.line.material.dispose(); this.cone.geometry.dispose(); this.cone.material.dispose(); } } class SceneHelper { constructor(threeScene) { _defineProperty(this, "updateFocusMarker", function () { var tempPosition = new Vector3(); var tempMatrix = new Matrix4(); var toCamera = new Vector3(); return function (position, camera, viewport) { tempMatrix.copy(camera.matrixWorld).invert(); tempPosition.copy(position).applyMatrix4(tempMatrix); tempPosition.normalize().multiplyScalar(10); tempPosition.applyMatrix4(camera.matrixWorld); toCamera.copy(camera.position).sub(position); var toCameraDistance = toCamera.length(); this.focusMarker.position.copy(position); this.focusMarker.scale.set(toCameraDistance, toCameraDistance, toCameraDistance); this.focusMarker.material.uniforms.realFocusPosition.value.copy(position); this.focusMarker.material.uniforms.viewport.value.copy(viewport); this.focusMarker.material.uniformsNeedUpdate = true; }; }()); _defineProperty(this, "positionAndOrientControlPlane", function () { var tempQuaternion = new Quaternion(); var defaultUp = new Vector3(0, 1, 0); return function (position, up) { tempQuaternion.setFromUnitVectors(defaultUp, up); this.controlPlane.position.copy(position); this.controlPlane.quaternion.copy(tempQuaternion); }; }()); this.threeScene = threeScene; this.splatRenderTarget = null; this.renderTargetCopyQuad = null; this.renderTargetCopyCamera = null; this.meshCursor = null; this.focusMarker = null; this.controlPlane = null; this.debugRoot = null; this.secondaryDebugRoot = null; } updateSplatRenderTargetForRenderDimensions(width, height) { this.destroySplatRendertarget(); this.splatRenderTarget = new WebGLRenderTarget(width, height, { format: RGBAFormat, stencilBuffer: false, depthBuffer: true }); this.splatRenderTarget.depthTexture = new DepthTexture(width, height); this.splatRenderTarget.depthTexture.format = DepthFormat; this.splatRenderTarget.depthTexture.type = UnsignedIntType; } destroySplatRendertarget() { if (this.splatRenderTarget) { this.splatRenderTarget = null; } } setupRenderTargetCopyObjects() { var uniforms = { 'sourceColorTexture': { 'type': 't', 'value': null }, 'sourceDepthTexture': { 'type': 't', 'value': null } }; var renderTargetCopyMaterial = new ShaderMaterial({ vertexShader: "\n varying vec2 vUv;\n void main() {\n vUv = uv;\n gl_Position = vec4( position.xy, 0.0, 1.0 ); \n }\n ", fragmentShader: "\n #include \n #include \n varying vec2 vUv;\n uniform sampler2D sourceColorTexture;\n uniform sampler2D sourceDepthTexture;\n void main() {\n vec4 color = texture2D(sourceColorTexture, vUv);\n float fragDepth = texture2D(sourceDepthTexture, vUv).x;\n gl_FragDepth = fragDepth;\n gl_FragColor = vec4(color.rgb, color.a * 2.0);\n }\n ", uniforms: uniforms, depthWrite: false, depthTest: false, transparent: true, blending: CustomBlending, blendSrc: SrcAlphaFactor, blendSrcAlpha: SrcAlphaFactor, blendDst: OneMinusSrcAlphaFactor, blendDstAlpha: OneMinusSrcAlphaFactor }); renderTargetCopyMaterial.extensions.fragDepth = true; this.renderTargetCopyQuad = new Mesh(new PlaneGeometry(2, 2), renderTargetCopyMaterial); this.renderTargetCopyCamera = new OrthographicCamera(-1, 1, 1, -1, 0, 1); } destroyRenderTargetCopyObjects() { if (this.renderTargetCopyQuad) { disposeAllMeshes(this.renderTargetCopyQuad); this.renderTargetCopyQuad = null; } } setupMeshCursor() { if (!this.meshCursor) { var coneGeometry = new ConeGeometry(0.5, 1.5, 32); var coneMaterial = new MeshBasicMaterial({ color: 0xFFFFFF }); var downArrow = new Mesh(coneGeometry, coneMaterial); downArrow.rotation.set(0, 0, Math.PI); downArrow.position.set(0, 1, 0); var upArrow = new Mesh(coneGeometry, coneMaterial); upArrow.position.set(0, -1, 0); var leftArrow = new Mesh(coneGeometry, coneMaterial); leftArrow.rotation.set(0, 0, Math.PI / 2.0); leftArrow.position.set(1, 0, 0); var rightArrow = new Mesh(coneGeometry, coneMaterial); rightArrow.rotation.set(0, 0, -Math.PI / 2.0); rightArrow.position.set(-1, 0, 0); this.meshCursor = new Object3D(); this.meshCursor.add(downArrow); this.meshCursor.add(upArrow); this.meshCursor.add(leftArrow); this.meshCursor.add(rightArrow); this.meshCursor.scale.set(0.1, 0.1, 0.1); this.threeScene.add(this.meshCursor); this.meshCursor.visible = false; } } destroyMeshCursor() { if (this.meshCursor) { disposeAllMeshes(this.meshCursor); this.threeScene.remove(this.meshCursor); this.meshCursor = null; } } setMeshCursorVisibility(visible) { this.meshCursor.visible = visible; } getMeschCursorVisibility() { return this.meshCursor.visible; } setMeshCursorPosition(position) { this.meshCursor.position.copy(position); } positionAndOrientMeshCursor(position, camera) { this.meshCursor.position.copy(position); this.meshCursor.up.copy(camera.up); this.meshCursor.lookAt(camera.position); } setupFocusMarker() { if (!this.focusMarker) { var sphereGeometry = new SphereGeometry(.5, 32, 32); var focusMarkerMaterial = SceneHelper.buildFocusMarkerMaterial(); focusMarkerMaterial.depthTest = false; focusMarkerMaterial.depthWrite = false; focusMarkerMaterial.transparent = true; this.focusMarker = new Mesh(sphereGeometry, focusMarkerMaterial); } } destroyFocusMarker() { if (this.focusMarker) { disposeAllMeshes(this.focusMarker); this.focusMarker = null; } } setFocusMarkerVisibility(visible) { this.focusMarker.visible = visible; } setFocusMarkerOpacity(opacity) { this.focusMarker.material.uniforms.opacity.value = opacity; this.focusMarker.material.uniformsNeedUpdate = true; } getFocusMarkerOpacity() { return this.focusMarker.material.uniforms.opacity.value; } setupControlPlane() { if (!this.controlPlane) { var planeGeometry = new PlaneGeometry(1, 1); planeGeometry.rotateX(-Math.PI / 2); var planeMaterial = new MeshBasicMaterial({ color: 0xffffff }); planeMaterial.transparent = true; planeMaterial.opacity = 0.6; planeMaterial.depthTest = false; planeMaterial.depthWrite = false; planeMaterial.side = DoubleSide; var planeMesh = new Mesh(planeGeometry, planeMaterial); var arrowDir = new Vector3(0, 1, 0); arrowDir.normalize(); var arrowOrigin = new Vector3(0, 0, 0); var arrowLength = 0.5; var arrowRadius = 0.01; var arrowColor = 0x00dd00; var arrowHelper = new ArrowHelper$1(arrowDir, arrowOrigin, arrowLength, arrowRadius, arrowColor, 0.1, 0.03); this.controlPlane = new Object3D(); this.controlPlane.add(planeMesh); this.controlPlane.add(arrowHelper); } } destroyControlPlane() { if (this.controlPlane) { disposeAllMeshes(this.controlPlane); this.controlPlane = null; } } setControlPlaneVisibility(visible) { this.controlPlane.visible = visible; } addDebugMeshes() { this.debugRoot = this.createDebugMeshes(); this.secondaryDebugRoot = this.createSecondaryDebugMeshes(); this.threeScene.add(this.debugRoot); this.threeScene.add(this.secondaryDebugRoot); } destroyDebugMeshes() { for (var debugRoot of [this.debugRoot, this.secondaryDebugRoot]) { if (debugRoot) { disposeAllMeshes(debugRoot); this.threeScene.remove(debugRoot); } } this.debugRoot = null; this.secondaryDebugRoot = null; } createDebugMeshes(renderOrder) { var sphereGeometry = new SphereGeometry(1, 32, 32); var debugMeshRoot = new Object3D(); var createMesh = (color, position) => { var sphereMesh = new Mesh(sphereGeometry, SceneHelper.buildDebugMaterial(color)); sphereMesh.renderOrder = renderOrder; debugMeshRoot.add(sphereMesh); sphereMesh.position.fromArray(position); }; createMesh(0xff0000, [-50, 0, 0]); createMesh(0xff0000, [50, 0, 0]); createMesh(0x00ff00, [0, 0, -50]); createMesh(0x00ff00, [0, 0, 50]); createMesh(0xffaa00, [5, 0, 5]); return debugMeshRoot; } createSecondaryDebugMeshes(renderOrder) { var boxGeometry = new BoxGeometry(3, 3, 3); var debugMeshRoot = new Object3D(); var boxColor = 0xBBBBBB; var createMesh = position => { var boxMesh = new Mesh(boxGeometry, SceneHelper.buildDebugMaterial(boxColor)); boxMesh.renderOrder = renderOrder; debugMeshRoot.add(boxMesh); boxMesh.position.fromArray(position); }; var separation = 10; createMesh([-separation, 0, -separation]); createMesh([-separation, 0, separation]); createMesh([separation, 0, -separation]); createMesh([separation, 0, separation]); return debugMeshRoot; } static buildDebugMaterial(color) { var vertexShaderSource = "\n #include \n varying float ndcDepth;\n\n void main() {\n gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position.xyz, 1.0);\n ndcDepth = gl_Position.z / gl_Position.w;\n gl_Position.x = gl_Position.x / gl_Position.w;\n gl_Position.y = gl_Position.y / gl_Position.w;\n gl_Position.z = 0.0;\n gl_Position.w = 1.0;\n \n }\n "; var fragmentShaderSource = "\n #include \n uniform vec3 color;\n varying float ndcDepth;\n void main() {\n gl_FragDepth = (ndcDepth + 1.0) / 2.0;\n gl_FragColor = vec4(color.rgb, 0.0);\n }\n "; var uniforms = { 'color': { 'type': 'v3', 'value': new Color(color) } }; var material = new ShaderMaterial({ uniforms: uniforms, vertexShader: vertexShaderSource, fragmentShader: fragmentShaderSource, transparent: false, depthTest: true, depthWrite: true, side: FrontSide }); material.extensions.fragDepth = true; return material; } static buildFocusMarkerMaterial(color) { var vertexShaderSource = "\n #include \n\n uniform vec2 viewport;\n uniform vec3 realFocusPosition;\n\n varying vec4 ndcPosition;\n varying vec4 ndcCenter;\n varying vec4 ndcFocusPosition;\n\n void main() {\n float radius = 0.01;\n\n vec4 viewPosition = modelViewMatrix * vec4(position.xyz, 1.0);\n vec4 viewCenter = modelViewMatrix * vec4(0.0, 0.0, 0.0, 1.0);\n\n vec4 viewFocusPosition = modelViewMatrix * vec4(realFocusPosition, 1.0);\n\n ndcPosition = projectionMatrix * viewPosition;\n ndcPosition = ndcPosition * vec4(1.0 / ndcPosition.w);\n ndcCenter = projectionMatrix * viewCenter;\n ndcCenter = ndcCenter * vec4(1.0 / ndcCenter.w);\n\n ndcFocusPosition = projectionMatrix * viewFocusPosition;\n ndcFocusPosition = ndcFocusPosition * vec4(1.0 / ndcFocusPosition.w);\n\n gl_Position = projectionMatrix * viewPosition;\n\n }\n "; var fragmentShaderSource = "\n #include \n uniform vec3 color;\n uniform vec2 viewport;\n uniform float opacity;\n\n varying vec4 ndcPosition;\n varying vec4 ndcCenter;\n varying vec4 ndcFocusPosition;\n\n void main() {\n vec2 screenPosition = vec2(ndcPosition) * viewport;\n vec2 screenCenter = vec2(ndcCenter) * viewport;\n\n vec2 screenVec = screenPosition - screenCenter;\n\n float projectedRadius = length(screenVec);\n\n float lineWidth = 0.0005 * viewport.y;\n float aaRange = 0.0025 * viewport.y;\n float radius = 0.06 * viewport.y;\n float radDiff = abs(projectedRadius - radius) - lineWidth;\n float alpha = 1.0 - clamp(radDiff / 5.0, 0.0, 1.0); \n\n gl_FragColor = vec4(color.rgb, alpha * opacity);\n }\n "; var uniforms = { 'color': { 'type': 'v3', 'value': new Color(color) }, 'realFocusPosition': { 'type': 'v3', 'value': new Vector3() }, 'viewport': { 'type': 'v2', 'value': new Vector2() }, 'opacity': { 'value': 0.0 } }; var material = new ShaderMaterial({ uniforms: uniforms, vertexShader: vertexShaderSource, fragmentShader: fragmentShaderSource, transparent: true, depthTest: false, depthWrite: false, side: FrontSide }); return material; } dispose() { this.destroyMeshCursor(); this.destroyFocusMarker(); this.destroyDebugMeshes(); this.destroyControlPlane(); this.destroyRenderTargetCopyObjects(); this.destroySplatRendertarget(); } } var VectorRight = new Vector3(1, 0, 0); var VectorUp = new Vector3(0, 1, 0); var VectorBackward = new Vector3(0, 0, 1); class Ray$1 { constructor() { var origin = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Vector3(); var direction = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Vector3(); _defineProperty(this, "intersectBox", function () { var planeIntersectionPoint = new Vector3(); var planeIntersectionPointArray = []; var originArray = []; var directionArray = []; return function (box, outHit) { originArray[0] = this.origin.x; originArray[1] = this.origin.y; originArray[2] = this.origin.z; directionArray[0] = this.direction.x; directionArray[1] = this.direction.y; directionArray[2] = this.direction.z; if (this.boxContainsPoint(box, this.origin, 0.0001)) { if (outHit) { outHit.origin.copy(this.origin); outHit.normal.set(0, 0, 0); outHit.distance = -1; } return true; } for (var i = 0; i < 3; i++) { if (directionArray[i] == 0.0) continue; var hitNormal = i == 0 ? VectorRight : i == 1 ? VectorUp : VectorBackward; var extremeVec = directionArray[i] < 0 ? box.max : box.min; var multiplier = -Math.sign(directionArray[i]); planeIntersectionPointArray[0] = i == 0 ? extremeVec.x : i == 1 ? extremeVec.y : extremeVec.z; var toSide = planeIntersectionPointArray[0] - originArray[i]; if (toSide * multiplier < 0) { var idx1 = (i + 1) % 3; var idx2 = (i + 2) % 3; planeIntersectionPointArray[2] = directionArray[idx1] / directionArray[i] * toSide + originArray[idx1]; planeIntersectionPointArray[1] = directionArray[idx2] / directionArray[i] * toSide + originArray[idx2]; planeIntersectionPoint.set(planeIntersectionPointArray[i], planeIntersectionPointArray[idx2], planeIntersectionPointArray[idx1]); if (this.boxContainsPoint(box, planeIntersectionPoint, 0.0001)) { if (outHit) { outHit.origin.copy(planeIntersectionPoint); outHit.normal.copy(hitNormal).multiplyScalar(multiplier); outHit.distance = planeIntersectionPoint.sub(this.origin).length(); } return true; } } } return false; }; }()); _defineProperty(this, "intersectSphere", function () { var toSphereCenterVec = new Vector3(); return function (center, radius, outHit) { toSphereCenterVec.copy(center).sub(this.origin); var toClosestApproach = toSphereCenterVec.dot(this.direction); var toClosestApproachSq = toClosestApproach * toClosestApproach; var toSphereCenterSq = toSphereCenterVec.dot(toSphereCenterVec); var diffSq = toSphereCenterSq - toClosestApproachSq; var radiusSq = radius * radius; if (diffSq > radiusSq) return false; var thc = Math.sqrt(radiusSq - diffSq); var t0 = toClosestApproach - thc; var t1 = toClosestApproach + thc; if (t1 < 0) return false; var t = t0 < 0 ? t1 : t0; if (outHit) { outHit.origin.copy(this.origin).addScaledVector(this.direction, t); outHit.normal.copy(outHit.origin).sub(center).normalize(); outHit.distance = t; } return true; }; }()); this.origin = new Vector3(); this.direction = new Vector3(); this.setParameters(origin, direction); } setParameters(origin, direction) { this.origin.copy(origin); this.direction.copy(direction).normalize(); } boxContainsPoint(box, point, epsilon) { return point.x < box.min.x - epsilon || point.x > box.max.x + epsilon || point.y < box.min.y - epsilon || point.y > box.max.y + epsilon || point.z < box.min.z - epsilon || point.z > box.max.z + epsilon ? false : true; } } class Hit { constructor() { this.origin = new Vector3(); this.normal = new Vector3(); this.distance = 0; this.splatIndex = 0; } set(origin, normal, distance, splatIndex) { this.origin.copy(origin); this.normal.copy(normal); this.distance = distance; this.splatIndex = splatIndex; } clone() { var hitClone = new Hit(); hitClone.origin.copy(this.origin); hitClone.normal.copy(this.normal); hitClone.distance = this.distance; hitClone.splatIndex = this.splatIndex; return hitClone; } } class Raycaster$1 { constructor(_origin, direction) { var raycastAgainstTrueSplatEllipsoid = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; _defineProperty(this, "setFromCameraAndScreenPosition", function () { var ndcCoords = new Vector2(); return function (camera, screenPosition, screenDimensions) { ndcCoords.x = screenPosition.x / screenDimensions.x * 2.0 - 1.0; ndcCoords.y = (screenDimensions.y - screenPosition.y) / screenDimensions.y * 2.0 - 1.0; if (camera.isPerspectiveCamera) { this.ray.origin.setFromMatrixPosition(camera.matrixWorld); this.ray.direction.set(ndcCoords.x, ndcCoords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize(); this.camera = camera; } else if (camera.isOrthographicCamera) { this.ray.origin.set(ndcCoords.x, ndcCoords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld); this.camera = camera; } else { throw new Error('Raycaster::setFromCameraAndScreenPosition() -> Unsupported camera type'); } }; }()); _defineProperty(this, "intersectSplatMesh", function () { var toLocal = new Matrix4(); var fromLocal = new Matrix4(); var sceneTransform = new Matrix4(); var localRay = new Ray$1(); var tempPoint = new Vector3(); return function (splatMesh) { var outHits = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var splatTree = splatMesh.getSplatTree(); if (!splatTree) return; for (var s = 0; s < splatTree.subTrees.length; s++) { var subTree = splatTree.subTrees[s]; fromLocal.copy(splatMesh.matrixWorld); if (splatMesh.dynamicMode) { splatMesh.getSceneTransform(s, sceneTransform); fromLocal.multiply(sceneTransform); } toLocal.copy(fromLocal).invert(); //直接在ray上乘上模型变换 localRay.origin.copy(this.ray.origin).applyMatrix4(toLocal); localRay.direction.copy(this.ray.origin).add(this.ray.direction); localRay.direction.applyMatrix4(toLocal).sub(localRay.origin).normalize(); var outHitsForSubTree = []; if (subTree.rootNode) { this.castRayAtSplatTreeNode(localRay, splatTree, subTree.rootNode, outHitsForSubTree); } outHitsForSubTree.forEach(hit => { hit.origin.applyMatrix4(fromLocal); hit.normal.applyMatrix4(fromLocal).normalize(); hit.distance = tempPoint.copy(hit.origin).sub(this.ray.origin).length(); }); outHits.push(...outHitsForSubTree); } outHits.sort((a, b) => { if (a.distance > b.distance) return 1;else return -1; }); return outHits; }; }()); _defineProperty(this, "castRayAtSplatTreeNode", function () { var tempColor = new Vector4(); var tempCenter = new Vector3(); var tempScale = new Vector3(); var tempRotation = new Quaternion(); var tempHit = new Hit(); var scaleEpsilon = 0.0000001; var origin = new Vector3(0, 0, 0); var uniformScaleMatrix = new Matrix4(); var scaleMatrix = new Matrix4(); var rotationMatrix = new Matrix4(); var toSphereSpace = new Matrix4(); var fromSphereSpace = new Matrix4(); var tempRay = new Ray$1(); return function (ray, splatTree, node) { var outHits = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; if (!ray.intersectBox(node.boundingBox)) { return; } if (node.data && node.data.indexes && node.data.indexes.length > 0) { for (var i = 0; i < node.data.indexes.length; i++) { var splatGlobalIndex = node.data.indexes[i]; splatTree.splatMesh.getSplatColor(splatGlobalIndex, tempColor); splatTree.splatMesh.getSplatCenter(splatGlobalIndex, tempCenter); splatTree.splatMesh.getSplatScaleAndRotation(splatGlobalIndex, tempScale, tempRotation); if (tempScale.x <= scaleEpsilon || tempScale.y <= scaleEpsilon || tempScale.z <= scaleEpsilon) { continue; } if (!this.raycastAgainstTrueSplatEllipsoid) { //是只需得到近似值的意思吗 var radius = (tempScale.x + tempScale.y + tempScale.z) / 3; //椭球的平均半径 if (ray.intersectSphere(tempCenter, radius, tempHit)) { //没细看,是pick球上哪个点? var hitClone = tempHit.clone(); hitClone.splatIndex = splatGlobalIndex; outHits.push(hitClone); } } else { scaleMatrix.makeScale(tempScale.x, tempScale.y, tempScale.z); rotationMatrix.makeRotationFromQuaternion(tempRotation); var uniformScale = Math.log10(tempColor.w) * 2.0; uniformScaleMatrix.makeScale(uniformScale, uniformScale, uniformScale); fromSphereSpace.copy(uniformScaleMatrix).multiply(rotationMatrix).multiply(scaleMatrix); toSphereSpace.copy(fromSphereSpace).invert(); tempRay.origin.copy(ray.origin).sub(tempCenter).applyMatrix4(toSphereSpace); tempRay.direction.copy(ray.origin).add(ray.direction).sub(tempCenter); tempRay.direction.applyMatrix4(toSphereSpace).sub(tempRay.origin).normalize(); if (tempRay.intersectSphere(origin, 1.0, tempHit)) { var _hitClone = tempHit.clone(); _hitClone.splatIndex = splatGlobalIndex; _hitClone.origin.applyMatrix4(fromSphereSpace).add(tempCenter); outHits.push(_hitClone); } } } } if (node.children && node.children.length > 0) { for (var child of node.children) { this.castRayAtSplatTreeNode(ray, splatTree, child, outHits); } } return outHits; }; }()); this.ray = new Ray$1(_origin, direction); this.raycastAgainstTrueSplatEllipsoid = raycastAgainstTrueSplatEllipsoid; } } /** * SplatScene: Descriptor for a single splat scene managed by an instance of SplatMesh. */ class SplatScene { constructor(splatBuffer) { var position = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Vector3(); var quaternion = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Quaternion(); var scale = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new Vector3(1, 1, 1); var minimumAlpha = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 1; this.splatBuffer = splatBuffer; this.position = position.clone(); this.quaternion = quaternion.clone(); this.scale = scale.clone(); this.transform = new Matrix4(); this.minimumAlpha = minimumAlpha; this.updateTransform(); } copyTransformData(otherScene) { this.position.copy(otherScene.position); this.quaternion.copy(otherScene.quaternion); this.scale.copy(otherScene.scale); this.transform.copy(otherScene.transform); } updateTransform() { this.transform.compose(this.position, this.quaternion, this.scale); } } /* 将点云中的点按照八叉树的方式一层层等分存储。 每个子节点自动向下分割,直到层数到达最大,或者其点数量小于最大容纳点数为止。 */ class SplatTreeNode { constructor(min, max, depth, id) { this.min = new Vector3().copy(min); this.max = new Vector3().copy(max); this.boundingBox = new Box3(this.min, this.max); this.center = new Vector3().copy(this.max).sub(this.min).multiplyScalar(0.5).add(this.min); this.depth = depth; this.children = []; this.data = null; this.id = id || SplatTreeNode.idGen++; } } _defineProperty(SplatTreeNode, "idGen", 0); class SplatSubTree { constructor(maxDepth, maxCentersPerNode) { this.maxDepth = maxDepth; this.maxCentersPerNode = maxCentersPerNode; this.sceneDimensions = new Vector3(); this.sceneMin = new Vector3(); this.sceneMax = new Vector3(); this.rootNode = null; this.nodesWithIndexes = []; this.splatMesh = null; } static convertWorkerSubTreeNode(workerSubTreeNode) { var minVector = new Vector3().fromArray(workerSubTreeNode.min); var maxVector = new Vector3().fromArray(workerSubTreeNode.max); var convertedNode = new SplatTreeNode(minVector, maxVector, workerSubTreeNode.depth, workerSubTreeNode.id); if (workerSubTreeNode.data.indexes) { convertedNode.data = { 'indexes': [] }; for (var index of workerSubTreeNode.data.indexes) { convertedNode.data.indexes.push(index); } } if (workerSubTreeNode.children) { for (var child of workerSubTreeNode.children) { convertedNode.children.push(SplatSubTree.convertWorkerSubTreeNode(child)); } } return convertedNode; } static convertWorkerSubTree(workerSubTree, splatMesh) { var convertedSubTree = new SplatSubTree(workerSubTree.maxDepth, workerSubTree.maxCentersPerNode); convertedSubTree.sceneMin = new Vector3().fromArray(workerSubTree.sceneMin); convertedSubTree.sceneMax = new Vector3().fromArray(workerSubTree.sceneMax); convertedSubTree.splatMesh = splatMesh; convertedSubTree.rootNode = SplatSubTree.convertWorkerSubTreeNode(workerSubTree.rootNode); var visitLeavesFromNode = (node, visitFunc) => { if (node.children.length === 0) visitFunc(node); for (var child of node.children) { visitLeavesFromNode(child, visitFunc); } }; convertedSubTree.nodesWithIndexes = []; visitLeavesFromNode(convertedSubTree.rootNode, node => { if (node.data && node.data.indexes && node.data.indexes.length > 0) { convertedSubTree.nodesWithIndexes.push(node); } }); return convertedSubTree; } } function createSplatTreeWorker(self) { var WorkerSplatTreeNodeIDGen = 0; class WorkerBox3 { constructor(min, max) { this.min = [min[0], min[1], min[2]]; this.max = [max[0], max[1], max[2]]; } containsPoint(point) { return point[0] >= this.min[0] && point[0] <= this.max[0] && point[1] >= this.min[1] && point[1] <= this.max[1] && point[2] >= this.min[2] && point[2] <= this.max[2]; } } class WorkerSplatSubTree { constructor(maxDepth, maxCentersPerNode) { this.maxDepth = maxDepth; this.maxCentersPerNode = maxCentersPerNode; this.sceneDimensions = []; this.sceneMin = []; this.sceneMax = []; this.rootNode = null; this.addedIndexes = {}; this.nodesWithIndexes = []; this.splatMesh = null; this.disposed = false; } } class WorkerSplatTreeNode { constructor(min, max, depth, id) { this.min = [min[0], min[1], min[2]]; this.max = [max[0], max[1], max[2]]; this.center = [(max[0] - min[0]) * 0.5 + min[0], (max[1] - min[1]) * 0.5 + min[1], (max[2] - min[2]) * 0.5 + min[2]]; this.depth = depth; this.children = []; this.data = null; this.id = id || WorkerSplatTreeNodeIDGen++; } } processSplatTreeNode = function (_processSplatTreeNode) { function processSplatTreeNode(_x, _x2, _x3, _x4) { return _processSplatTreeNode.apply(this, arguments); } processSplatTreeNode.toString = function () { return _processSplatTreeNode.toString(); }; return processSplatTreeNode; }(function (tree, node, indexToCenter, sceneCenters) { var splatCount = node.data.indexes.length; if (splatCount < tree.maxCentersPerNode || node.depth > tree.maxDepth) { //该节点停止分割 var newIndexes = []; for (var i = 0; i < node.data.indexes.length; i++) { if (!tree.addedIndexes[node.data.indexes[i]]) { newIndexes.push(node.data.indexes[i]); tree.addedIndexes[node.data.indexes[i]] = true; } } node.data.indexes = newIndexes; node.data.indexes.sort((a, b) => { if (a > b) return 1;else return -1; }); tree.nodesWithIndexes.push(node); return; } var nodeDimensions = [node.max[0] - node.min[0], node.max[1] - node.min[1], node.max[2] - node.min[2]]; var halfDimensions = [nodeDimensions[0] * 0.5, nodeDimensions[1] * 0.5, nodeDimensions[2] * 0.5]; var nodeCenter = [node.min[0] + halfDimensions[0], node.min[1] + halfDimensions[1], node.min[2] + halfDimensions[2]]; var childrenBounds = [ //分割成八块 // top section, clockwise from upper-left (looking from above, +Y) new WorkerBox3([nodeCenter[0] - halfDimensions[0], nodeCenter[1], nodeCenter[2] - halfDimensions[2]], [nodeCenter[0], nodeCenter[1] + halfDimensions[1], nodeCenter[2]]), new WorkerBox3([nodeCenter[0], nodeCenter[1], nodeCenter[2] - halfDimensions[2]], [nodeCenter[0] + halfDimensions[0], nodeCenter[1] + halfDimensions[1], nodeCenter[2]]), new WorkerBox3([nodeCenter[0], nodeCenter[1], nodeCenter[2]], [nodeCenter[0] + halfDimensions[0], nodeCenter[1] + halfDimensions[1], nodeCenter[2] + halfDimensions[2]]), new WorkerBox3([nodeCenter[0] - halfDimensions[0], nodeCenter[1], nodeCenter[2]], [nodeCenter[0], nodeCenter[1] + halfDimensions[1], nodeCenter[2] + halfDimensions[2]]), // bottom section, clockwise from lower-left (looking from above, +Y) new WorkerBox3([nodeCenter[0] - halfDimensions[0], nodeCenter[1] - halfDimensions[1], nodeCenter[2] - halfDimensions[2]], [nodeCenter[0], nodeCenter[1], nodeCenter[2]]), new WorkerBox3([nodeCenter[0], nodeCenter[1] - halfDimensions[1], nodeCenter[2] - halfDimensions[2]], [nodeCenter[0] + halfDimensions[0], nodeCenter[1], nodeCenter[2]]), new WorkerBox3([nodeCenter[0], nodeCenter[1] - halfDimensions[1], nodeCenter[2]], [nodeCenter[0] + halfDimensions[0], nodeCenter[1], nodeCenter[2] + halfDimensions[2]]), new WorkerBox3([nodeCenter[0] - halfDimensions[0], nodeCenter[1] - halfDimensions[1], nodeCenter[2]], [nodeCenter[0], nodeCenter[1], nodeCenter[2] + halfDimensions[2]])]; var splatCounts = []; var baseIndexes = []; for (var _i15 = 0; _i15 < childrenBounds.length; _i15++) { splatCounts[_i15] = 0; baseIndexes[_i15] = []; } var center = [0, 0, 0]; for (var _i16 = 0; _i16 < splatCount; _i16++) { //查找每一块包含的index var splatGlobalIndex = node.data.indexes[_i16]; var centerBase = indexToCenter[splatGlobalIndex]; center[0] = sceneCenters[centerBase]; center[1] = sceneCenters[centerBase + 1]; center[2] = sceneCenters[centerBase + 2]; for (var j = 0; j < childrenBounds.length; j++) { if (childrenBounds[j].containsPoint(center)) { splatCounts[j]++; baseIndexes[j].push(splatGlobalIndex); break; //xzw!!!! add 防止ply转的如果都是000点,就会每块都有然后不停分割下去 } } } for (var _i17 = 0; _i17 < childrenBounds.length; _i17++) { var childNode = new WorkerSplatTreeNode(childrenBounds[_i17].min, childrenBounds[_i17].max, node.depth + 1); //创建子节点 childNode.data = { 'indexes': baseIndexes[_i17] }; node.children.push(childNode); } node.data = {}; //清空自身index for (var child of node.children) { processSplatTreeNode(tree, child, indexToCenter, sceneCenters); //继续分割 } return; }); var buildSubTree = (sceneCenters, maxDepth, maxCentersPerNode) => { var sceneMin = [0, 0, 0]; var sceneMax = [0, 0, 0]; var indexes = []; var centerCount = Math.floor(sceneCenters.length / 4); for (var i = 0; i < centerCount; i++) { var base = i * 4; var x = sceneCenters[base]; var y = sceneCenters[base + 1]; var z = sceneCenters[base + 2]; var index = Math.round(sceneCenters[base + 3]); if (i === 0 || x < sceneMin[0]) sceneMin[0] = x; if (i === 0 || x > sceneMax[0]) sceneMax[0] = x; if (i === 0 || y < sceneMin[1]) sceneMin[1] = y; if (i === 0 || y > sceneMax[1]) sceneMax[1] = y; if (i === 0 || z < sceneMin[2]) sceneMin[2] = z; if (i === 0 || z > sceneMax[2]) sceneMax[2] = z; indexes.push(index); } var subTree = new WorkerSplatSubTree(maxDepth, maxCentersPerNode); subTree.sceneMin = sceneMin; subTree.sceneMax = sceneMax; subTree.rootNode = new WorkerSplatTreeNode(subTree.sceneMin, subTree.sceneMax, 0); subTree.rootNode.data = { 'indexes': indexes }; return subTree; }; function createSplatTree(allCenters, maxDepth, maxCentersPerNode) { var indexToCenter = []; for (var sceneCenters of allCenters) { var centerCount = Math.floor(sceneCenters.length / 4); for (var i = 0; i < centerCount; i++) { var base = i * 4; var index = Math.round(sceneCenters[base + 3]); indexToCenter[index] = base; } } var subTrees = []; for (var _sceneCenters of allCenters) { var subTree = buildSubTree(_sceneCenters, maxDepth, maxCentersPerNode); //建立树 subTrees.push(subTree); processSplatTreeNode(subTree, subTree.rootNode, indexToCenter, _sceneCenters); //开始分割 } self.postMessage({ 'subTrees': subTrees }); } self.onmessage = e => { if (e.data.process) { createSplatTree(e.data.process.centers, e.data.process.maxDepth, e.data.process.maxCentersPerNode); } }; } function workerProcessCenters(splatTreeWorker, centers, transferBuffers, maxDepth, maxCentersPerNode) { splatTreeWorker.postMessage({ 'process': { 'centers': centers, 'maxDepth': maxDepth, 'maxCentersPerNode': maxCentersPerNode } }, transferBuffers); } function checkAndCreateWorker() { var splatTreeWorker = new Worker(URL.createObjectURL(new Blob(['(', createSplatTreeWorker.toString(), ')(self)'], { type: 'application/javascript' }))); return splatTreeWorker; } /** * SplatTree: Octree tailored to splat data from a SplatMesh instance */ class SplatTree { constructor(maxDepth, maxCentersPerNode) { /** * Construct this instance of SplatTree from an instance of SplatMesh. * * @param {SplatMesh} splatMesh The instance of SplatMesh from which to construct this splat tree. * @param {function} filterFunc Optional function to filter out unwanted splats. * @param {function} onIndexesUpload Function to be called when the upload of splat centers to the splat tree * builder worker starts and finishes. * @param {function} onSplatTreeConstruction Function to be called when the conversion of the local splat tree from * the format produced by the splat tree builder worker starts and ends. * @return {undefined} */ _defineProperty(this, "processSplatMesh", function (splatMesh) { var filterFunc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : () => true; var onIndexesUpload = arguments.length > 2 ? arguments[2] : undefined; var onSplatTreeConstruction = arguments.length > 3 ? arguments[3] : undefined; if (!this.splatTreeWorker) this.splatTreeWorker = checkAndCreateWorker(); this.splatMesh = splatMesh; this.subTrees = []; var center = new Vector3(); var addCentersForScene = (splatOffset, splatCount) => { var sceneCenters = new Float32Array(splatCount * 4); var addedCount = 0; for (var i = 0; i < splatCount; i++) { var globalSplatIndex = i + splatOffset; if (filterFunc(globalSplatIndex)) { splatMesh.getSplatCenter(globalSplatIndex, center); var addBase = addedCount * 4; sceneCenters[addBase] = center.x; sceneCenters[addBase + 1] = center.y; sceneCenters[addBase + 2] = center.z; sceneCenters[addBase + 3] = globalSplatIndex; addedCount++; } } return sceneCenters; }; return new Promise(resolve => { var checkForEarlyExit = () => { if (this.disposed) { this.diposeSplatTreeWorker(); resolve(); return true; } return false; }; if (onIndexesUpload) onIndexesUpload(false); delayedExecute(() => { if (checkForEarlyExit()) return; var allCenters = []; if (splatMesh.dynamicMode) { var splatOffset = 0; for (var s = 0; s < splatMesh.scenes.length; s++) { var scene = splatMesh.getScene(s); var splatCount = scene.splatBuffer.getSplatCount(); var sceneCenters = addCentersForScene(splatOffset, splatCount); allCenters.push(sceneCenters); splatOffset += splatCount; } } else { var _sceneCenters2 = addCentersForScene(0, splatMesh.getSplatCount()); allCenters.push(_sceneCenters2); } this.splatTreeWorker.onmessage = e => { if (checkForEarlyExit()) return; if (e.data.subTrees) { if (onSplatTreeConstruction) onSplatTreeConstruction(false); delayedExecute(() => { if (checkForEarlyExit()) return; for (var workerSubTree of e.data.subTrees) { var convertedSubTree = SplatSubTree.convertWorkerSubTree(workerSubTree, splatMesh); this.subTrees.push(convertedSubTree); } this.diposeSplatTreeWorker(); if (onSplatTreeConstruction) onSplatTreeConstruction(true); delayedExecute(() => { resolve(); }); }); } }; delayedExecute(() => { if (checkForEarlyExit()) return; if (onIndexesUpload) onIndexesUpload(true); var transferBuffers = allCenters.map(array => array.buffer); workerProcessCenters(this.splatTreeWorker, allCenters, transferBuffers, this.maxDepth, this.maxCentersPerNode); }); }); }); }); this.maxDepth = maxDepth; this.maxCentersPerNode = maxCentersPerNode; this.subTrees = []; this.splatMesh = null; } dispose() { this.diposeSplatTreeWorker(); this.disposed = true; } diposeSplatTreeWorker() { if (this.splatTreeWorker) this.splatTreeWorker.terminate(); this.splatTreeWorker = null; } countLeaves() { var leafCount = 0; this.visitLeaves(() => { leafCount++; }); return leafCount; } visitLeaves(visitFunc) { //traverse var visitLeavesFromNode = (node, visitFunc) => { if (node.children.length === 0) visitFunc(node); for (var child of node.children) { visitLeavesFromNode(child, visitFunc); } }; for (var subTree of this.subTrees) { visitLeavesFromNode(subTree.rootNode, visitFunc); } } } function WebGLExtensions$1(gl) { var extensions = {}; function getExtension(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; default: extension = gl.getExtension(name); } extensions[name] = extension; return extension; } return { has: function has(name) { return getExtension(name) !== null; }, init: function init(capabilities) { if (capabilities.isWebGL2) { getExtension('EXT_color_buffer_float'); getExtension('WEBGL_clip_cull_distance'); } else { getExtension('WEBGL_depth_texture'); getExtension('OES_texture_float'); getExtension('OES_texture_half_float'); getExtension('OES_texture_half_float_linear'); getExtension('OES_standard_derivatives'); getExtension('OES_element_index_uint'); getExtension('OES_vertex_array_object'); getExtension('ANGLE_instanced_arrays'); } getExtension('OES_texture_float_linear'); getExtension('EXT_color_buffer_half_float'); getExtension('WEBGL_multisampled_render_to_texture'); }, get: function get(name) { var extension = getExtension(name); if (extension === null) { console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.'); } return extension; } }; } function WebGLCapabilities$1(gl, extensions, parameters) { var maxAnisotropy; function getMaxAnisotropy() { if (maxAnisotropy !== undefined) return maxAnisotropy; if (extensions.has('EXT_texture_filter_anisotropic') === true) { var extension = extensions.get('EXT_texture_filter_anisotropic'); 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 isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl.constructor.name === 'WebGL2RenderingContext'; 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 drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers'); var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; 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 = isWebGL2 || extensions.has('OES_texture_float'); var floatVertexTextures = vertexTextures && floatFragmentTextures; var maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0; return { isWebGL2: isWebGL2, drawBuffers: drawBuffers, 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, maxSamples: maxSamples }; } var SceneRevealMode = { Default: 0, Gradual: 1, Instant: 2 }; var LogLevel = { None: 0, Error: 1, Warning: 2, Info: 3, Debug: 4 }; var dummyGeometry = new BufferGeometry(); var dummyMaterial = new MeshBasicMaterial(); var COVARIANCES_ELEMENTS_PER_SPLAT = 6; var CENTER_COLORS_ELEMENTS_PER_SPLAT = 4; var COVARIANCES_ELEMENTS_PER_TEXEL = 4; var CENTER_COLORS_ELEMENTS_PER_TEXEL = 4; var TRANSFORM_INDEXES_ELEMENTS_PER_TEXEL = 1; var SCENE_FADEIN_RATE_FAST = 0.012; var SCENE_FADEIN_RATE_GRADUAL = 0.003; var VISIBLE_REGION_EXPANSION_DELTA = 1; /** * SplatMesh: Container for one or more splat scenes, abstracting them into a single unified container for * splat data. Additionally contains data structures and code to make the splat data renderable as a Three.js mesh. */ class SplatMesh extends Mesh { constructor() { var dynamicMode = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; var halfPrecisionCovariancesOnGPU = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var devicePixelRatio = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; var enableDistancesComputationOnGPU = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; var integerBasedDistancesComputation = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; var antialiased = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; var maxScreenSpaceSplatSize = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 2048; var logLevel = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : LogLevel.None; var sphericalHarmonicsDegree = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : 0; super(dummyGeometry, dummyMaterial); // Reference to a Three.js renderer /** * Build an instance of SplatTree (a specialized octree) for the given splat mesh. * @param {Array} minAlphas Array of minimum splat slphas for each scene * @param {function} onSplatTreeIndexesUpload Function to be called when the upload of splat centers to the splat tree * builder worker starts and finishes. * @param {function} onSplatTreeConstruction Function to be called when the conversion of the local splat tree from * the format produced by the splat tree builder worker starts and ends. * @return {SplatTree} */ _defineProperty(this, "buildSplatTree", function () { var minAlphas = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var onSplatTreeIndexesUpload = arguments.length > 1 ? arguments[1] : undefined; var onSplatTreeConstruction = arguments.length > 2 ? arguments[2] : undefined; return new Promise(resolve => { this.disposeSplatTree(); // TODO: expose SplatTree constructor parameters (maximumDepth and maxCentersPerNode) so that they can // be configured on a per-scene basis this.baseSplatTree = new SplatTree(8, 1000); var buildStartTime = performance.now(); var splatColor = new Vector4(); this.baseSplatTree.processSplatMesh(this, splatIndex => { this.getSplatColor(splatIndex, splatColor); var sceneIndex = this.getSceneIndexForSplat(splatIndex); var minAlpha = minAlphas[sceneIndex] || 1; return splatColor.w >= minAlpha; }, onSplatTreeIndexesUpload, onSplatTreeConstruction).then(() => { var buildTime = performance.now() - buildStartTime; if (this.logLevel >= LogLevel.Info) console.log('SplatTree build: ' + buildTime + ' ms'); if (this.disposed) { resolve(); } else { this.splatTree = this.baseSplatTree; this.baseSplatTree = null; var leavesWithVertices = 0; var avgSplatCount = 0; var maxSplatCount = 0; var nodeCount = 0; this.splatTree.visitLeaves(node => { var nodeSplatCount = node.data.indexes.length; if (nodeSplatCount > 0) { avgSplatCount += nodeSplatCount; maxSplatCount = Math.max(maxSplatCount, nodeSplatCount); nodeCount++; leavesWithVertices++; } }); if (this.logLevel >= LogLevel.Info) { console.log("SplatTree leaves: ".concat(this.splatTree.countLeaves())); console.log("SplatTree leaves with splats:".concat(leavesWithVertices)); avgSplatCount = avgSplatCount / nodeCount; console.log("Avg splat count per node: ".concat(avgSplatCount)); console.log("Total splat count: ".concat(this.getSplatCount())); } resolve(); } }); }); }); _defineProperty(this, "updateUniforms", function () { var viewport = new Vector2(); return function (renderDimensions, cameraFocalLengthX, cameraFocalLengthY, orthographicMode, orthographicZoom, inverseFocalAdjustment) { var splatCount = this.getSplatCount(); if (splatCount > 0) { viewport.set(renderDimensions.x * this.devicePixelRatio, renderDimensions.y * this.devicePixelRatio); this.material.uniforms.viewport.value.copy(viewport); this.material.uniforms.basisViewport.value.set(1.0 / viewport.x, 1.0 / viewport.y); this.material.uniforms.focal.value.set(cameraFocalLengthX, cameraFocalLengthY); this.material.uniforms.orthographicMode.value = orthographicMode ? 1 : 0; this.material.uniforms.orthoZoom.value = orthographicZoom; this.material.uniforms.inverseFocalAdjustment.value = inverseFocalAdjustment; if (this.dynamicMode) { for (var i = 0; i < this.scenes.length; i++) { this.material.uniforms.transforms.value[i].copy(this.getScene(i).transform); } } this.material.uniformsNeedUpdate = true; } }; }()); _defineProperty(this, "setupDistancesComputationTransformFeedback", function () { var currentMaxSplatCount; return function () { var maxSplatCount = this.getMaxSplatCount(); if (!this.renderer) return; var rebuildGPUObjects = this.lastRenderer !== this.renderer; var rebuildBuffers = currentMaxSplatCount !== maxSplatCount; if (!rebuildGPUObjects && !rebuildBuffers) return; if (rebuildGPUObjects) { this.disposeDistancesComputationGPUResources(); } else if (rebuildBuffers) { this.disposeDistancesComputationGPUBufferResources(); } var gl = this.renderer.getContext(); var createShader = (gl, type, source) => { var shader = gl.createShader(type); if (!shader) { console.error('Fatal error: gl could not create a shader object.'); return null; } gl.shaderSource(shader, source); gl.compileShader(shader); var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (!compiled) { var typeName = 'unknown'; if (type === gl.VERTEX_SHADER) typeName = 'vertex shader';else if (type === gl.FRAGMENT_SHADER) typeName = 'fragement shader'; var errors = gl.getShaderInfoLog(shader); console.error('Failed to compile ' + typeName + ' with these errors:' + errors); gl.deleteShader(shader); return null; } return shader; }; var vsSource; if (this.integerBasedDistancesComputation) { vsSource = "#version 300 es\n in ivec4 center;\n flat out int distance;"; if (this.dynamicMode) { vsSource += "\n in uint transformIndex;\n uniform ivec4 transforms[".concat(Constants.MaxScenes, "];\n void main(void) {\n ivec4 transform = transforms[transformIndex];\n distance = center.x * transform.x + center.y * transform.y + center.z * transform.z + transform.w * center.w;\n }\n "); } else { vsSource += "\n uniform ivec3 modelViewProj;\n void main(void) {\n distance = center.x * modelViewProj.x + center.y * modelViewProj.y + center.z * modelViewProj.z;\n }\n "; } } else { vsSource = "#version 300 es\n in vec4 center;\n flat out float distance;"; if (this.dynamicMode) { vsSource += "\n in uint transformIndex;\n uniform mat4 transforms[".concat(Constants.MaxScenes, "];\n void main(void) {\n vec4 transformedCenter = transforms[transformIndex] * vec4(center.xyz, 1.0);\n distance = transformedCenter.z;\n }\n "); } else { vsSource += "\n uniform vec3 modelViewProj;\n void main(void) {\n distance = center.x * modelViewProj.x + center.y * modelViewProj.y + center.z * modelViewProj.z;\n }\n "; } } var fsSource = "#version 300 es\n precision lowp float;\n out vec4 fragColor;\n void main(){}\n "; var currentVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING); var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM); var currentProgramDeleted = currentProgram ? gl.getProgramParameter(currentProgram, gl.DELETE_STATUS) : false; if (rebuildGPUObjects) { this.distancesTransformFeedback.vao = gl.createVertexArray(); } gl.bindVertexArray(this.distancesTransformFeedback.vao); if (rebuildGPUObjects) { var program = gl.createProgram(); var vertexShader = createShader(gl, gl.VERTEX_SHADER, vsSource); var fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fsSource); if (!vertexShader || !fragmentShader) { throw new Error('Could not compile shaders for distances computation on GPU.'); } gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); gl.transformFeedbackVaryings(program, ['distance'], gl.SEPARATE_ATTRIBS); gl.linkProgram(program); var linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked) { var error = gl.getProgramInfoLog(program); console.error('Fatal error: Failed to link program: ' + error); gl.deleteProgram(program); gl.deleteShader(fragmentShader); gl.deleteShader(vertexShader); throw new Error('Could not link shaders for distances computation on GPU.'); } this.distancesTransformFeedback.program = program; this.distancesTransformFeedback.vertexShader = vertexShader; this.distancesTransformFeedback.vertexShader = fragmentShader; } gl.useProgram(this.distancesTransformFeedback.program); this.distancesTransformFeedback.centersLoc = gl.getAttribLocation(this.distancesTransformFeedback.program, 'center'); if (this.dynamicMode) { this.distancesTransformFeedback.transformIndexesLoc = gl.getAttribLocation(this.distancesTransformFeedback.program, 'transformIndex'); for (var i = 0; i < this.scenes.length; i++) { this.distancesTransformFeedback.transformsLocs[i] = gl.getUniformLocation(this.distancesTransformFeedback.program, "transforms[".concat(i, "]")); } } else { this.distancesTransformFeedback.modelViewProjLoc = gl.getUniformLocation(this.distancesTransformFeedback.program, 'modelViewProj'); } if (rebuildGPUObjects || rebuildBuffers) { this.distancesTransformFeedback.centersBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.centersBuffer); gl.enableVertexAttribArray(this.distancesTransformFeedback.centersLoc); if (this.integerBasedDistancesComputation) { gl.vertexAttribIPointer(this.distancesTransformFeedback.centersLoc, 4, gl.INT, 0, 0); } else { gl.vertexAttribPointer(this.distancesTransformFeedback.centersLoc, 4, gl.FLOAT, false, 0, 0); } if (this.dynamicMode) { this.distancesTransformFeedback.transformIndexesBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.transformIndexesBuffer); gl.enableVertexAttribArray(this.distancesTransformFeedback.transformIndexesLoc); gl.vertexAttribIPointer(this.distancesTransformFeedback.transformIndexesLoc, 1, gl.UNSIGNED_INT, 0, 0); } } if (rebuildGPUObjects || rebuildBuffers) { this.distancesTransformFeedback.outDistancesBuffer = gl.createBuffer(); } gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.outDistancesBuffer); gl.bufferData(gl.ARRAY_BUFFER, maxSplatCount * 4, gl.STATIC_READ); if (rebuildGPUObjects) { this.distancesTransformFeedback.id = gl.createTransformFeedback(); } gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, this.distancesTransformFeedback.id); gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, this.distancesTransformFeedback.outDistancesBuffer); if (currentProgram && currentProgramDeleted !== true) gl.useProgram(currentProgram); if (currentVao) gl.bindVertexArray(currentVao); this.lastRenderer = this.renderer; currentMaxSplatCount = maxSplatCount; }; }()); /** * Fill 'array' with the transforms for each scene in this splat mesh. * @param {Array} array Empty array to be filled with scene transforms. If not empty, contents will be overwritten. */ _defineProperty(this, "fillTransformsArray", function () { var tempArray = []; return function (array) { if (tempArray.length !== array.length) tempArray.length = array.length; for (var i = 0; i < this.scenes.length; i++) { var sceneTransform = this.getScene(i).transform; var sceneTransformElements = sceneTransform.elements; for (var j = 0; j < 16; j++) { tempArray[i * 16 + j] = sceneTransformElements[j]; } } array.set(tempArray); }; }()); _defineProperty(this, "computeDistancesOnGPU", function () { var tempMatrix = new Matrix4(); return function (modelViewProjMatrix, outComputedDistances) { if (!this.renderer) return; // console.time("gpu_compute_distances"); var gl = this.renderer.getContext(); var currentVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING); var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM); var currentProgramDeleted = currentProgram ? gl.getProgramParameter(currentProgram, gl.DELETE_STATUS) : false; gl.bindVertexArray(this.distancesTransformFeedback.vao); gl.useProgram(this.distancesTransformFeedback.program); gl.enable(gl.RASTERIZER_DISCARD); if (this.dynamicMode) { for (var i = 0; i < this.scenes.length; i++) { tempMatrix.copy(this.getScene(i).transform); tempMatrix.premultiply(modelViewProjMatrix); if (this.integerBasedDistancesComputation) { var iTempMatrix = SplatMesh.getIntegerMatrixArray(tempMatrix); var iTransform = [iTempMatrix[2], iTempMatrix[6], iTempMatrix[10], iTempMatrix[14]]; gl.uniform4i(this.distancesTransformFeedback.transformsLocs[i], iTransform[0], iTransform[1], iTransform[2], iTransform[3]); } else { gl.uniformMatrix4fv(this.distancesTransformFeedback.transformsLocs[i], false, tempMatrix.elements); } } } else { if (this.integerBasedDistancesComputation) { var iViewProjMatrix = SplatMesh.getIntegerMatrixArray(modelViewProjMatrix); var iViewProj = [iViewProjMatrix[2], iViewProjMatrix[6], iViewProjMatrix[10]]; gl.uniform3i(this.distancesTransformFeedback.modelViewProjLoc, iViewProj[0], iViewProj[1], iViewProj[2]); } else { var viewProj = [modelViewProjMatrix.elements[2], modelViewProjMatrix.elements[6], modelViewProjMatrix.elements[10]]; gl.uniform3f(this.distancesTransformFeedback.modelViewProjLoc, viewProj[0], viewProj[1], viewProj[2]); } } gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.centersBuffer); gl.enableVertexAttribArray(this.distancesTransformFeedback.centersLoc); if (this.integerBasedDistancesComputation) { gl.vertexAttribIPointer(this.distancesTransformFeedback.centersLoc, 4, gl.INT, 0, 0); } else { gl.vertexAttribPointer(this.distancesTransformFeedback.centersLoc, 4, gl.FLOAT, false, 0, 0); } if (this.dynamicMode) { gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.transformIndexesBuffer); gl.enableVertexAttribArray(this.distancesTransformFeedback.transformIndexesLoc); gl.vertexAttribIPointer(this.distancesTransformFeedback.transformIndexesLoc, 1, gl.UNSIGNED_INT, 0, 0); } gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, this.distancesTransformFeedback.id); gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, this.distancesTransformFeedback.outDistancesBuffer); gl.beginTransformFeedback(gl.POINTS); gl.drawArrays(gl.POINTS, 0, this.getSplatCount()); gl.endTransformFeedback(); gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, null); gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, null); gl.disable(gl.RASTERIZER_DISCARD); var sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0); gl.flush(); var promise = new Promise(resolve => { var checkSync = () => { if (this.disposed) { resolve(); } else { var timeout = 0; var bitflags = 0; var status = gl.clientWaitSync(sync, bitflags, timeout); switch (status) { case gl.TIMEOUT_EXPIRED: this.computeDistancesOnGPUSyncTimeout = setTimeout(checkSync); return this.computeDistancesOnGPUSyncTimeout; case gl.WAIT_FAILED: throw new Error('should never get here'); default: this.computeDistancesOnGPUSyncTimeout = null; gl.deleteSync(sync); var _currentVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING); gl.bindVertexArray(this.distancesTransformFeedback.vao); gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.outDistancesBuffer); gl.getBufferSubData(gl.ARRAY_BUFFER, 0, outComputedDistances); gl.bindBuffer(gl.ARRAY_BUFFER, null); if (_currentVao) gl.bindVertexArray(_currentVao); // console.timeEnd("gpu_compute_distances"); resolve(); } } }; this.computeDistancesOnGPUSyncTimeout = setTimeout(checkSync); }); if (currentProgram && currentProgramDeleted !== true) gl.useProgram(currentProgram); if (currentVao) gl.bindVertexArray(currentVao); return promise; }; }()); /** * Get the center for a splat, transformed as appropriate. * @param {number} globalIndex Global index of splat * @param {THREE.Vector3} outCenter THREE.Vector3 instance in which to store splat center * @param {boolean} applySceneTransform By default, if the splat mesh is static, the transform of the scene to which the splat at * 'globalIndex' belongs will be applied to the splat center. If 'applySceneTransform' is true, * the scene transform will always be applied and if 'applySceneTransform' is false, the * scene transform will never be applied. If undefined, the default behavior will apply. */ _defineProperty(this, "getSplatCenter", function () { var paramsObj = {}; return function (globalIndex, outCenter, applySceneTransform) { this.getLocalSplatParameters(globalIndex, paramsObj, applySceneTransform); paramsObj.splatBuffer.getSplatCenter(paramsObj.localIndex, outCenter, paramsObj.sceneTransform); }; }()); /** * Get the scale and rotation for a splat, transformed as appropriate. * @param {number} globalIndex Global index of splat * @param {THREE.Vector3} outScale THREE.Vector3 instance in which to store splat scale * @param {THREE.Quaternion} outRotation THREE.Quaternion instance in which to store splat rotation * @param {boolean} applySceneTransform By default, if the splat mesh is static, the transform of the scene to which the splat at * 'globalIndex' belongs will be applied to the splat scale and rotation. If * 'applySceneTransform' is true, the scene transform will always be applied and if * 'applySceneTransform' is false, the scene transform will never be applied. If undefined, * the default behavior will apply. */ _defineProperty(this, "getSplatScaleAndRotation", function () { var paramsObj = {}; return function (globalIndex, outScale, outRotation, applySceneTransform) { this.getLocalSplatParameters(globalIndex, paramsObj, applySceneTransform); paramsObj.splatBuffer.getSplatScaleAndRotation(paramsObj.localIndex, outScale, outRotation, paramsObj.sceneTransform); }; }()); /** * Get the color for a splat. * @param {number} globalIndex Global index of splat * @param {THREE.Vector4} outColor THREE.Vector4 instance in which to store splat color */ _defineProperty(this, "getSplatColor", function () { var paramsObj = {}; return function (globalIndex, outColor) { this.getLocalSplatParameters(globalIndex, paramsObj); paramsObj.splatBuffer.getSplatColor(paramsObj.localIndex, outColor); }; }()); this.renderer = undefined; // Use 16-bit floating point values when storing splat covariance data in textures, instead of 32-bit this.halfPrecisionCovariancesOnGPU = halfPrecisionCovariancesOnGPU; // When 'dynamicMode' is true, scenes are assumed to be non-static. Dynamic scenes are handled differently // and certain optimizations cannot be made for them. Additionally, by default, all splat data retrieved from // this splat mesh will not have their scene transform applied to them if the splat mesh is dynamic. That // can be overriden via parameters to the individual functions that are used to retrieve splat data. this.dynamicMode = dynamicMode; // Ratio of the resolution in physical pixels to the resolution in CSS pixels for the current display device this.devicePixelRatio = devicePixelRatio; // Use a transform feedback to calculate splat distances from the camera this.enableDistancesComputationOnGPU = enableDistancesComputationOnGPU; // Use a faster integer-based approach for calculating splat distances from the camera this.integerBasedDistancesComputation = integerBasedDistancesComputation; // When true, will perform additional steps during rendering to address artifacts caused by the rendering of gaussians at a // substantially different resolution than that at which they were rendered during training. This will only work correctly // for models that were trained using a process that utilizes this compensation calculation. For more details: // https://github.com/nerfstudio-project/gsplat/pull/117 // https://github.com/graphdeco-inria/gaussian-splatting/issues/294#issuecomment-1772688093 this.antialiased = antialiased; // Specify the maximum clip space splat size, can help deal with large splats that get too unwieldy this.maxScreenSpaceSplatSize = maxScreenSpaceSplatSize; // The verbosity of console logging this.logLevel = logLevel; // Degree 0 means no spherical harmonics this.sphericalHarmonicsDegree = sphericalHarmonicsDegree; this.minSphericalHarmonicsDegree = 0; // The individual splat scenes stored in this splat mesh, each containing their own transform this.scenes = []; // Special octree tailored to SplatMesh instances this.splatTree = null; this.baseSplatTree = null; // Textures in which splat data will be stored for rendering this.splatDataTextures = {}; this.distancesTransformFeedback = { 'id': null, 'vertexShader': null, 'fragmentShader': null, 'program': null, 'centersBuffer': null, 'transformIndexesBuffer': null, 'outDistancesBuffer': null, 'centersLoc': -1, 'modelViewProjLoc': -1, 'transformIndexesLoc': -1, 'transformsLocs': [] }; this.globalSplatIndexToLocalSplatIndexMap = []; this.globalSplatIndexToSceneIndexMap = []; this.lastBuildSplatCount = 0; this.lastBuildScenes = []; this.lastBuildMaxSplatCount = 0; this.lastBuildSceneCount = 0; this.firstRenderTime = -1; this.finalBuild = false; this.webGLUtils = null; this.boundingBox = new Box3(); this.calculatedSceneCenter = new Vector3(); this.maxSplatDistanceFromSceneCenter = 0; this.visibleRegionBufferRadius = 0; this.visibleRegionRadius = 0; this.visibleRegionFadeStartRadius = 0; this.visibleRegionChanging = false; this.splatScale = 1.0; this.pointCloudModeEnabled = false; this.disposed = false; this.lastRenderer = null; this.visible = false; } /** * Build the Three.js material that is used to render the splats. * @param {number} dynamicMode If true, it means the scene geometry represented by this splat mesh is not stationary or * that the splat count might change * @param {boolean} antialiased If true, calculate compensation factor to deal with gaussians being rendered at a significantly * different resolution than that of their training * @param {number} maxScreenSpaceSplatSize The maximum clip space splat size * @param {number} splatScale Value by which all splats are scaled in screen-space (default is 1.0) * @param {number} pointCloudModeEnabled Render all splats as screen-space circles * @param {number} maxSphericalHarmonicsDegree Degree of spherical harmonics to utilize in rendering splats * @return {THREE.ShaderMaterial} */ static buildMaterial() { var dynamicMode = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; var antialiased = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var maxScreenSpaceSplatSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2048; var splatScale = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1.0; var pointCloudModeEnabled = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; var maxSphericalHarmonicsDegree = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; // Contains the code to project 3D covariance to 2D and from there calculate the quad (using the eigen vectors of the // 2D covariance) that is ultimately rasterized var vertexShaderSource = "\n precision highp float;\n #include \n\n attribute uint splatIndex;\n\n uniform highp sampler2D covariancesTexture;\n uniform highp usampler2D centersColorsTexture;\n uniform highp sampler2D sphericalHarmonicsTexture;"; if (dynamicMode) { vertexShaderSource += "\n uniform highp usampler2D transformIndexesTexture;\n uniform highp mat4 transforms[".concat(Constants.MaxScenes, "];\n uniform vec2 transformIndexesTextureSize;\n "); } vertexShaderSource += "\n uniform vec2 focal;\n uniform float orthoZoom;\n uniform int orthographicMode;\n uniform int pointCloudModeEnabled;\n uniform float inverseFocalAdjustment;\n uniform vec2 viewport;\n uniform vec2 basisViewport;\n uniform vec2 covariancesTextureSize;\n uniform vec2 centersColorsTextureSize;\n uniform int sphericalHarmonicsDegree;\n uniform vec2 sphericalHarmonicsTextureSize;\n uniform int sphericalHarmonics8BitMode;\n uniform float visibleRegionRadius;\n uniform float visibleRegionFadeStartRadius;\n uniform float firstRenderTime;\n uniform float currentTime;\n uniform int fadeInComplete;\n uniform vec3 sceneCenter;\n uniform float splatScale;\n\n varying vec4 vColor;\n varying vec2 vUv;\n\n varying vec2 vPosition;\n\n const float sqrt8 = sqrt(8.0);\n const float minAlpha = 1.0 / 255.0;\n\n const vec4 encodeNorm4 = vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\n const uvec4 mask4 = uvec4(uint(0x000000FF), uint(0x0000FF00), uint(0x00FF0000), uint(0xFF000000));\n const uvec4 shift4 = uvec4(0, 8, 16, 24);\n vec4 uintToRGBAVec (uint u) {\n uvec4 urgba = mask4 & u;\n urgba = urgba >> shift4;\n vec4 rgba = vec4(urgba) * encodeNorm4;\n return rgba;\n }\n\n vec2 getDataUV(in int stride, in int offset, in vec2 dimensions) {\n vec2 samplerUV = vec2(0.0, 0.0);\n float d = float(splatIndex * uint(stride) + uint(offset)) / dimensions.x;\n samplerUV.y = float(floor(d)) / dimensions.y;\n samplerUV.x = fract(d);\n return samplerUV;\n }\n\n vec2 getDataUVF(in uint sIndex, in float stride, in uint offset, in vec2 dimensions) {\n vec2 samplerUV = vec2(0.0, 0.0);\n float d = float(uint(float(sIndex) * stride) + offset) / dimensions.x;\n samplerUV.y = float(floor(d)) / dimensions.y;\n samplerUV.x = fract(d);\n return samplerUV;\n }\n\n const float SH_C1 = 0.4886025119029199f;\n const float[5] SH_C2 = float[](1.0925484, -1.0925484, 0.3153916, -1.0925484, 0.5462742);\n const vec3 vecOnes3 = vec3(1.0, 1.0, 1.0);\n\n void main () {\n\n uint oddOffset = splatIndex & uint(0x00000001);\n uint doubleOddOffset = oddOffset * uint(2);\n bool isEven = oddOffset == uint(0);\n uint nearestEvenIndex = splatIndex - oddOffset;\n float fOddOffset = float(oddOffset);\n\n uvec4 sampledCenterColor = texture(centersColorsTexture, getDataUV(1, 0, centersColorsTextureSize));\n vec3 splatCenter = uintBitsToFloat(uvec3(sampledCenterColor.gba));"; if (dynamicMode) { vertexShaderSource += "\n uint transformIndex = texture(transformIndexesTexture, getDataUV(1, 0, transformIndexesTextureSize)).r;\n mat4 transform = transforms[transformIndex];\n mat4 transformModelViewMatrix = modelViewMatrix * transform;\n "; } else { vertexShaderSource += "mat4 transformModelViewMatrix = modelViewMatrix;"; } vertexShaderSource += "\n vec4 viewCenter = transformModelViewMatrix * vec4(splatCenter, 1.0);\n\n vec4 clipCenter = projectionMatrix * viewCenter;\n\n float clip = 1.2 * clipCenter.w;\n if (clipCenter.z < -clip || clipCenter.x < -clip || clipCenter.x > clip || clipCenter.y < -clip || clipCenter.y > clip) {\n gl_Position = vec4(0.0, 0.0, 2.0, 1.0);\n return;\n }\n\n vPosition = position.xy;\n vColor = uintToRGBAVec(sampledCenterColor.r);\n\n "; if (maxSphericalHarmonicsDegree >= 1) { vertexShaderSource += " \n if (sphericalHarmonicsDegree >= 1) {\n "; if (dynamicMode) { vertexShaderSource += "\n mat4 mTransform = modelMatrix * transform;\n vec3 worldViewDir = normalize(splatCenter - vec3(inverse(mTransform) * vec4(cameraPosition, 1.0)));\n "; } else { vertexShaderSource += "\n vec3 worldViewDir = normalize(splatCenter - cameraPosition);\n "; } if (maxSphericalHarmonicsDegree >= 2) { vertexShaderSource += "\n vec4 sampledSH0123 = texture(sphericalHarmonicsTexture, getDataUV(6, 0, sphericalHarmonicsTextureSize));\n vec4 sampledSH4567 = texture(sphericalHarmonicsTexture, getDataUV(6, 1, sphericalHarmonicsTextureSize));\n vec4 sampledSH891011 = texture(sphericalHarmonicsTexture, getDataUV(6, 2, sphericalHarmonicsTextureSize));\n vec3 sh1 = sampledSH0123.rgb;\n vec3 sh2 = vec3(sampledSH0123.a, sampledSH4567.rg);\n vec3 sh3 = vec3(sampledSH4567.ba, sampledSH891011.r);\n "; } else { vertexShaderSource += "\n vec2 shUV = getDataUVF(nearestEvenIndex, 2.5, doubleOddOffset, sphericalHarmonicsTextureSize);\n vec4 sampledSH0123 = texture(sphericalHarmonicsTexture, shUV);\n shUV = getDataUVF(nearestEvenIndex, 2.5, doubleOddOffset + uint(1), sphericalHarmonicsTextureSize);\n vec4 sampledSH4567 = texture(sphericalHarmonicsTexture, shUV);\n shUV = getDataUVF(nearestEvenIndex, 2.5, doubleOddOffset + uint(2), sphericalHarmonicsTextureSize);\n vec4 sampledSH891011 = texture(sphericalHarmonicsTexture, shUV);\n\n vec3 sh1 = vec3(sampledSH0123.rgb) * (1.0 - fOddOffset) + vec3(sampledSH0123.ba, sampledSH4567.r) * fOddOffset;\n vec3 sh2 = vec3(sampledSH0123.a, sampledSH4567.rg) * (1.0 - fOddOffset) + vec3(sampledSH4567.gba) * fOddOffset;\n vec3 sh3 = vec3(sampledSH4567.ba, sampledSH891011.r) * (1.0 - fOddOffset) + vec3(sampledSH891011.rgb) * fOddOffset;\n "; } vertexShaderSource += "\n if (sphericalHarmonics8BitMode == 1) {\n sh1 = sh1 * 2.0 - vecOnes3;\n sh2 = sh2 * 2.0 - vecOnes3;\n sh3 = sh3 * 2.0 - vecOnes3;\n }\n float x = worldViewDir.x;\n float y = worldViewDir.y;\n float z = worldViewDir.z;\n vColor.rgb += SH_C1 * (-sh1 * y + sh2 * z - sh3 * x);\n "; if (maxSphericalHarmonicsDegree >= 2) { vertexShaderSource += "\n if (sphericalHarmonicsDegree >= 2) {\n float xx = x * x;\n float yy = y * y;\n float zz = z * z;\n float xy = x * y;\n float yz = y * z;\n float xz = x * z;\n\n vec4 sampledSH12131415 = texture(sphericalHarmonicsTexture, getDataUV(6, 3, sphericalHarmonicsTextureSize));\n vec4 sampledSH16171819 = texture(sphericalHarmonicsTexture, getDataUV(6, 4, sphericalHarmonicsTextureSize));\n vec4 sampledSH20212223 = texture(sphericalHarmonicsTexture, getDataUV(6, 5, sphericalHarmonicsTextureSize));\n\n vec3 sh4 = sampledSH891011.gba;\n vec3 sh5 = sampledSH12131415.rgb;\n vec3 sh6 = vec3(sampledSH12131415.a, sampledSH16171819.rg);\n vec3 sh7 = vec3(sampledSH16171819.ba, sampledSH20212223.r);\n vec3 sh8 = sampledSH20212223.gba;\n\n if (sphericalHarmonics8BitMode == 1) {\n sh4 = sh4 * 2.0 - vecOnes3;\n sh5 = sh5 * 2.0 - vecOnes3;\n sh6 = sh6 * 2.0 - vecOnes3;\n sh7 = sh7 * 2.0 - vecOnes3;\n sh8 = sh8 * 2.0 - vecOnes3;\n }\n\n vColor.rgb +=\n (SH_C2[0] * xy) * sh4 +\n (SH_C2[1] * yz) * sh5 +\n (SH_C2[2] * (2.0 * zz - xx - yy)) * sh6 +\n (SH_C2[3] * xz) * sh7 +\n (SH_C2[4] * (xx - yy)) * sh8;\n }\n "; } vertexShaderSource += "\n }\n "; } vertexShaderSource += "\n\n vec4 sampledCovarianceA = texture(covariancesTexture,\n getDataUVF(nearestEvenIndex, 1.5, oddOffset, covariancesTextureSize));\n vec4 sampledCovarianceB = texture(covariancesTexture,\n getDataUVF(nearestEvenIndex, 1.5, oddOffset + uint(1), covariancesTextureSize));\n\n vec3 cov3D_M11_M12_M13 = vec3(sampledCovarianceA.rgb) * (1.0 - fOddOffset) +\n vec3(sampledCovarianceA.ba, sampledCovarianceB.r) * fOddOffset;\n vec3 cov3D_M22_M23_M33 = vec3(sampledCovarianceA.a, sampledCovarianceB.rg) * (1.0 - fOddOffset) +\n vec3(sampledCovarianceB.gba) * fOddOffset;\n\n // Construct the 3D covariance matrix\n mat3 Vrk = mat3(\n cov3D_M11_M12_M13.x, cov3D_M11_M12_M13.y, cov3D_M11_M12_M13.z,\n cov3D_M11_M12_M13.y, cov3D_M22_M23_M33.x, cov3D_M22_M23_M33.y,\n cov3D_M11_M12_M13.z, cov3D_M22_M23_M33.y, cov3D_M22_M23_M33.z\n );\n\n \n // Construct the Jacobian\u884C\u5217\u5F0F of the affine\u4EFF\u5C04 approximation\u903C\u8FD1 of the projection matrix. It will be used to transform the\n // 3D covariance matrix instead of using the actual projection matrix because that transformation would\n // require a non-linear component (perspective division) which would yield a non-gaussian result. (This assumes\u5047\u8BBE\n // the current projection is a perspective projection).\n //\u7FFB\u8BD1\u7ED3\u679C\uFF1A\u6784\u5EFA\u6295\u5F71\u77E9\u9635\u4EFF\u5C04\u8FD1\u4F3C\u7684\u96C5\u53EF\u6BD4\u77E9\u9635\u3002\u5B83\u5C06\u88AB\u7528\u6765\u53D8\u63623D\u534F\u65B9\u5DEE\u77E9\u9635\uFF0C\u800C\u4E0D\u662F\u76F4\u63A5\u4F7F\u7528\u5B9E\u9645\u7684\u6295\u5F71\u77E9\u9635\uFF0C\u56E0\u4E3A\u4F7F\u7528\u5B9E\u9645\u6295\u5F71\u77E9\u9635\u8FDB\u884C\u53D8\u6362\u9700\u8981\u5305\u542B\u975E\u7EBF\u6027\u6210\u5206\uFF08\u900F\u89C6\u9664\u6CD5\uFF09\uFF0C\u8FD9\u4F1A\u5BFC\u81F4\u975E\u9AD8\u65AF\u7684\u7ED3\u679C\u3002\u8FD9\u91CC\u5047\u8BBE\u5F53\u524D\u7684\u6295\u5F71\u4E3A\u900F\u89C6\u6295\u5F71\u3002\n //\u770B\u4E0D\u61C2 https://zhuanlan.zhihu.com/p/661569671\n\n \n mat3 J;\n if (orthographicMode == 1) {\n // Since the projection is linear, we don't need an approximation\n J = transpose(mat3(orthoZoom, 0.0, 0.0,\n 0.0, orthoZoom, 0.0,\n 0.0, 0.0, 0.0));\n } else {\n // Construct the Jacobian of the affine approximation of the projection matrix. It will be used to transform the\n // 3D covariance matrix instead of using the actual projection matrix because that transformation would\n // require a non-linear component (perspective division) which would yield a non-gaussian result.\n float s = 1.0 / (viewCenter.z * viewCenter.z);\n J = mat3(\n focal.x / viewCenter.z, 0., -(focal.x * viewCenter.x) * s,\n 0., focal.y / viewCenter.z, -(focal.y * viewCenter.y) * s,\n 0., 0., 0.\n );\n }\n\n // Concatenate the projection approximation with the model-view transformation\n mat3 W = transpose(mat3(transformModelViewMatrix));\n mat3 T = W * J;\n\n // Transform the 3D covariance matrix (Vrk) to compute the 2D covariance matrix\n mat3 cov2Dm = transpose(T) * Vrk * T;\n "; if (antialiased) { vertexShaderSource += "\n float detOrig = cov2Dm[0][0] * cov2Dm[1][1] - cov2Dm[0][1] * cov2Dm[0][1];\n cov2Dm[0][0] += 0.3;\n cov2Dm[1][1] += 0.3;\n float detBlur = cov2Dm[0][0] * cov2Dm[1][1] - cov2Dm[0][1] * cov2Dm[0][1];\n float compensation = sqrt(max(detOrig / detBlur, 0.0));\n "; } else { vertexShaderSource += "\n cov2Dm[0][0] += 0.3;\n cov2Dm[1][1] += 0.3;\n float compensation = 1.0;\n "; } vertexShaderSource += "\n\n vColor.a *= compensation;\n\n if (vColor.a < minAlpha) return;\n\n // We are interested in the upper-left 2x2 portion of the projected 3D covariance matrix because\n // we only care about the X and Y values. We want the X-diagonal, cov2Dm[0][0],\n // the Y-diagonal, cov2Dm[1][1], and the correlation between the two cov2Dm[0][1]. We don't\n // need cov2Dm[1][0] because it is a symetric matrix.\n vec3 cov2Dv = vec3(cov2Dm[0][0], cov2Dm[0][1], cov2Dm[1][1]);\n\n vec3 ndcCenter = clipCenter.xyz / clipCenter.w;\n\n // We now need to solve for the eigen-values and eigen vectors of the 2D covariance matrix\n // so that we can determine the 2D basis for the splat. This is done using the method described\n // here: https://people.math.harvard.edu/~knill/teaching/math21b2004/exhibits/2dmatrices/index.html \u516C\u5F0F\u51FA\u5904\n // After calculating the eigen-values and eigen-vectors, we calculate the basis for rendering the splat\n // by normalizing the eigen-vectors and then multiplying them by (sqrt(8) * eigen-value), which is\n // equal to scaling them by sqrt(8) standard deviations.\n //\n // This is a different approach than in the original work at INRIA. In that work they compute the\n // max extents of the projected splat in screen space to form a screen-space aligned bounding rectangle\n // which forms the geometry that is actually rasterized. The dimensions of that bounding box are 3.0\n // times the maximum eigen-value, or 3 standard deviations. They then use the inverse 2D covariance\n // matrix (called 'conic') in the CUDA rendering thread to determine fragment opacity by calculating the\n // full gaussian: exp(-0.5 * (X - mean) * conic * (X - mean)) * splat opacity\n float a = cov2Dv.x;\n float d = cov2Dv.z;\n float b = cov2Dv.y;\n float D = a * d - b * b;\n float trace = a + d; //\u8FFD\u8E2A\n float traceOver2 = 0.5 * trace;\n float term2 = sqrt(max(0.1f, traceOver2 * traceOver2 - D));\n float eigenValue1 = traceOver2 + term2; //\u7279\u5F81\u503CL1\n float eigenValue2 = traceOver2 - term2; //\u7279\u5F81\u503CL1\n\n if (pointCloudModeEnabled == 1) {// each splat is rendered as a filled circle\n eigenValue1 = eigenValue2 = 0.2;\n }\n\n if (eigenValue2 <= 0.0) return;\n\n vec2 eigenVector1 = normalize(vec2(b, eigenValue1 - a));\n // since the eigen vectors are orthogonal, we derive the second one from the first \u7531\u4E8E\u672C\u5F81\u5411\u91CF\u662F\u6B63\u4EA4\u7684\uFF0C\u56E0\u6B64\u6211\u4EEC\u4ECE\u7B2C\u4E00\u4E2A\u5BFC\u51FA\u7B2C\u4E8C\u4E2A\n vec2 eigenVector2 = vec2(eigenVector1.y, -eigenVector1.x);\n\n // We use sqrt(8) standard deviations\u504F\u5DEE instead of 3 to eliminate\u6D88\u9664 more of the splat with a very low opacity.\n vec2 basisVector1 = eigenVector1 * splatScale * min(sqrt8 * sqrt(eigenValue1), ".concat(parseInt(maxScreenSpaceSplatSize), ".0);\n vec2 basisVector2 = eigenVector2 * splatScale * min(sqrt8 * sqrt(eigenValue2), ").concat(parseInt(maxScreenSpaceSplatSize), ".0);\n\n if (fadeInComplete == 0) {\n float opacityAdjust = 1.0;\n float centerDist = length(splatCenter - sceneCenter);\n float renderTime = max(currentTime - firstRenderTime, 0.0);\n\n float fadeDistance = 0.75;\n float distanceLoadFadeInFactor = step(visibleRegionFadeStartRadius, centerDist);\n distanceLoadFadeInFactor = (1.0 - distanceLoadFadeInFactor) +\n (1.0 - clamp((centerDist - visibleRegionFadeStartRadius) / fadeDistance, 0.0, 1.0)) *\n distanceLoadFadeInFactor;\n opacityAdjust *= distanceLoadFadeInFactor;\n vColor.a *= opacityAdjust;\n }\n\n vec2 ndcOffset = vec2(vPosition.x * basisVector1 + vPosition.y * basisVector2) *\n basisViewport * 2.0 * inverseFocalAdjustment;\n\n vec4 quadPos = vec4(ndcCenter.xy + ndcOffset, ndcCenter.z , 1.0);\n gl_Position = quadPos; //\u5C06\u6574\u4E2A\u6B63\u65B9\u5F62\u505A\u4E00\u5B9A\u7684\u62C9\u4F38\u5F62\u53D8\uFF0C\u4E4B\u540E\u5728fs\u4E2D\u56E0\u4E3A\u53EA\u663E\u793A\u4E2D\u95F4\u7684\u5706\uFF0C\u6240\u4EE5\u4E5F\u5C31\u662F\u663E\u793A\u62C9\u4F38\u540E\u7684\u5706\u3002\uFF08vs\u53EA\u8BA1\u7B97\u56DB\u4E2A\u9876\u70B9\u7684\u5177\u4F53\u4F4D\u7F6E\uFF0C\u5176\u4ED6\u4F4D\u7F6E\u662F\u63D2\u503C\u5F97\u5230\u7684\uFF09\n\n // Scale the position data we send to the fragment shader\n vPosition *= sqrt8;\n }"); //面片模拟椭球,总是有厚度 var fragmentShaderSource = "\n precision highp float;\n #include \n \n uniform vec3 debugColor;\n\n varying vec4 vColor;\n varying vec2 vUv;\n\n varying vec2 vPosition;\n\n void main () {\n // Compute the positional squared distance from the center of the splat to the current fragment.\n float A = dot(vPosition, vPosition);\n // Since the positional data in vPosition has been scaled by sqrt(8), the squared result will be\n // scaled by a factor of 8. If the squared result is larger than 8, it means it is outside the ellipse\n // defined by the rectangle formed by vPosition. It also means it's farther\n // away than sqrt(8) standard deviations from the mean.\n if (A > 8.0) discard; //position\u7684\u8303\u56F4\u534A\u5F84\u4E3A1\u3002\u6307\u4E00\u4E2Arectangle\u9762\u4E2D\u7684\u8303\u56F4\u3002\u692D\u5706\u5916\u7684\u5B8C\u5168\u900F\u660E\n vec3 color = vColor.rgb;\n\n // Since the rendered splat is scaled by sqrt(8), the inverse covariance matrix that is part of\n // the gaussian formula becomes the identity matrix. We're then left with (X - mean) * (X - mean),\n // and since 'mean' is zero, we have X * X, which is the same as A:\n float opacity = exp(-0.5 * A) * vColor.a; //\u5468\u56F4\u7684\u900F\u660E\u5EA6\u964D\u4F4E\n\n gl_FragColor = vec4(color.rgb, opacity);\n //\u4E0D\u77E5\u9053\u4E3A\u4F55ply\u8F6C\u8FC7\u6765\u7684vColor.a\u662F0\uFF0C(\u4F46\u662F\u5728\u5916\u9762\u8BBF\u95EE\u7684opacity\u5E76\u4E0D\u662F0), \u5BFC\u81F4\u5168\u662F\u9ED1\u8272\n }"; var uniforms = { 'sceneCenter': { 'type': 'v3', 'value': new Vector3() }, 'fadeInComplete': { 'type': 'i', 'value': 0 }, 'orthographicMode': { 'type': 'i', 'value': 0 }, 'visibleRegionFadeStartRadius': { 'type': 'f', 'value': 0.0 }, 'visibleRegionRadius': { 'type': 'f', 'value': 0.0 }, 'currentTime': { 'type': 'f', 'value': 0.0 }, 'firstRenderTime': { 'type': 'f', 'value': 0.0 }, 'covariancesTexture': { //协方差 'type': 't', 'value': null }, 'centersColorsTexture': { 'type': 't', 'value': null }, 'sphericalHarmonicsTexture': { 'type': 't', 'value': null }, 'focal': { 'type': 'v2', 'value': new Vector2() }, 'orthoZoom': { 'type': 'f', 'value': 1.0 }, 'inverseFocalAdjustment': { 'type': 'f', 'value': 1.0 }, 'viewport': { 'type': 'v2', 'value': new Vector2() }, 'basisViewport': { 'type': 'v2', 'value': new Vector2() }, 'debugColor': { 'type': 'v3', 'value': new Color() }, 'covariancesTextureSize': { 'type': 'v2', 'value': new Vector2(1024, 1024) }, 'centersColorsTextureSize': { 'type': 'v2', 'value': new Vector2(1024, 1024) }, 'sphericalHarmonicsDegree': { 'type': 'i', 'value': maxSphericalHarmonicsDegree }, 'sphericalHarmonicsTextureSize': { 'type': 'v2', 'value': new Vector2(1024, 1024) }, 'sphericalHarmonics8BitMode': { 'type': 'i', 'value': 0 }, 'splatScale': { 'type': 'f', 'value': splatScale }, 'pointCloudModeEnabled': { 'type': 'i', 'value': pointCloudModeEnabled ? 1 : 0 } }; if (dynamicMode) { uniforms['transformIndexesTexture'] = { 'type': 't', 'value': null }; var transformMatrices = []; for (var i = 0; i < Constants.MaxScenes; i++) { transformMatrices.push(new Matrix4()); } uniforms['transforms'] = { 'type': 'mat4', 'value': transformMatrices }; uniforms['transformIndexesTextureSize'] = { 'type': 'v2', 'value': new Vector2(1024, 1024) }; } var material = new ShaderMaterial({ uniforms: uniforms, vertexShader: vertexShaderSource, fragmentShader: fragmentShaderSource, transparent: true, alphaTest: 1.0, blending: NormalBlending, depthTest: true, depthWrite: false, side: DoubleSide }); return material; } /** * Build the Three.js geometry that will be used to render the splats. The geometry is instanced and is made up of * vertices for a single quad as well as an attribute buffer for the splat indexes. * @param {number} maxSplatCount The maximum number of splats that the geometry will need to accomodate * @return {THREE.InstancedBufferGeometry} */ static buildGeomtery(maxSplatCount) { var baseGeometry = new BufferGeometry(); baseGeometry.setIndex([0, 1, 2, 0, 2, 3]); // Vertices for the instanced quad var positionsArray = new Float32Array(4 * 3); var positions = new BufferAttribute(positionsArray, 3); baseGeometry.setAttribute('position', positions); positions.setXYZ(0, -1.0, -1.0, 0.0); positions.setXYZ(1, -1.0, 1.0, 0.0); positions.setXYZ(2, 1.0, 1.0, 0.0); positions.setXYZ(3, 1.0, -1.0, 0.0); positions.needsUpdate = true; var geometry = new InstancedBufferGeometry().copy(baseGeometry); // Splat index buffer var splatIndexArray = new Uint32Array(maxSplatCount); var splatIndexes = new InstancedBufferAttribute(splatIndexArray, 1, false); splatIndexes.setUsage(DynamicDrawUsage); geometry.setAttribute('splatIndex', splatIndexes); geometry.instanceCount = 0; return geometry; } /** * Build a container for each scene managed by this splat mesh based on an instance of SplatBuffer, along with optional * transform data (position, scale, rotation) passed to the splat mesh during the build process. * @param {Array} splatBuffers SplatBuffer instances containing splats for each scene * @param {Array} sceneOptions Array of options objects: { * * position (Array): Position of the scene, acts as an offset from its default position, defaults to [0, 0, 0] * * rotation (Array): Rotation of the scene represented as a quaternion, defaults to [0, 0, 0, 1] * * scale (Array): Scene's scale, defaults to [1, 1, 1] * } * @return {Array} */ static buildScenes(splatBuffers, sceneOptions) { var scenes = []; scenes.length = splatBuffers.length; for (var i = 0; i < splatBuffers.length; i++) { var splatBuffer = splatBuffers[i]; var _options = sceneOptions[i] || {}; var positionArray = _options['position'] || [0, 0, 0]; var rotationArray = _options['rotation'] || [0, 0, 0, 1]; var scaleArray = _options['scale'] || [1, 1, 1]; var position = new Vector3().fromArray(positionArray); var rotation = new Quaternion().fromArray(rotationArray); var scale = new Vector3().fromArray(scaleArray); scenes[i] = SplatMesh.createScene(splatBuffer, position, rotation, scale, _options.splatAlphaRemovalThreshold || 1); } return scenes; } static createScene(splatBuffer, position, rotation, scale, minimumAlpha) { return new SplatScene(splatBuffer, position, rotation, scale, minimumAlpha); } /** * Build data structures that map global splat indexes (based on a unified index across all splat buffers) to * local data within a single scene. * @param {Array} splatBuffers Instances of SplatBuffer off which to build the maps * @return {object} */ static buildSplatIndexMaps(splatBuffers) { var localSplatIndexMap = []; var sceneIndexMap = []; var totalSplatCount = 0; for (var s = 0; s < splatBuffers.length; s++) { var splatBuffer = splatBuffers[s]; var maxSplatCount = splatBuffer.getMaxSplatCount(); for (var i = 0; i < maxSplatCount; i++) { localSplatIndexMap[totalSplatCount] = i; sceneIndexMap[totalSplatCount] = s; totalSplatCount++; } } return { localSplatIndexMap, sceneIndexMap }; } /** * Construct this instance of SplatMesh. * @param {Array} splatBuffers The base splat data, instances of SplatBuffer * @param {Array} sceneOptions Dynamic options for each scene { * * splatAlphaRemovalThreshold: Ignore any splats with an alpha less than the specified * value (valid range: 0 - 255), defaults to 1 * * position (Array): Position of the scene, acts as an offset from its default position, defaults to [0, 0, 0] * * rotation (Array): Rotation of the scene represented as a quaternion, defaults to [0, 0, 0, 1] * * scale (Array): Scene's scale, defaults to [1, 1, 1] * * } * @param {boolean} keepSceneTransforms For a scene that already exists and is being overwritten, this flag * says to keep the transform from the existing scene. * @param {boolean} finalBuild Will the splat mesh be in its final state after this build? * @param {function} onSplatTreeIndexesUpload Function to be called when the upload of splat centers to the splat tree * builder worker starts and finishes. * @param {function} onSplatTreeConstruction Function to be called when the conversion of the local splat tree from * the format produced by the splat tree builder worker starts and ends. * @return {object} Object containing info about the splats that are updated */ build(splatBuffers, sceneOptions) { var keepSceneTransforms = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var finalBuild = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; var onSplatTreeIndexesUpload = arguments.length > 4 ? arguments[4] : undefined; var onSplatTreeConstruction = arguments.length > 5 ? arguments[5] : undefined; this.sceneOptions = sceneOptions; this.finalBuild = finalBuild; var maxSplatCount = SplatMesh.getTotalMaxSplatCountForSplatBuffers(splatBuffers); var newScenes = SplatMesh.buildScenes(splatBuffers, sceneOptions); if (keepSceneTransforms) { for (var i = 0; i < this.scenes.length && i < newScenes.length; i++) { var newScene = newScenes[i]; var existingScene = this.getScene(i); newScene.copyTransformData(existingScene); } } this.scenes = newScenes; var minSphericalHarmonicsDegree = 3; for (var splatBuffer of splatBuffers) { var splatBufferSphericalHarmonicsDegree = splatBuffer.getMinSphericalHarmonicsDegree(); if (splatBufferSphericalHarmonicsDegree < minSphericalHarmonicsDegree) { minSphericalHarmonicsDegree = splatBufferSphericalHarmonicsDegree; } } this.minSphericalHarmonicsDegree = Math.min(minSphericalHarmonicsDegree, this.sphericalHarmonicsDegree); var splatBuffersChanged = false; if (splatBuffers.length !== this.lastBuildScenes.length) { splatBuffersChanged = true; } else { for (var _i18 = 0; _i18 < splatBuffers.length; _i18++) { var _splatBuffer = splatBuffers[_i18]; if (_splatBuffer !== this.lastBuildScenes[_i18].splatBuffer) { splatBuffersChanged = true; break; } } } var isUpdateBuild = true; if (this.scenes.length !== 1 || this.lastBuildSceneCount !== this.scenes.length || this.lastBuildMaxSplatCount !== maxSplatCount || splatBuffersChanged) { isUpdateBuild = false; } if (!isUpdateBuild) { this.boundingBox = new Box3(); this.maxSplatDistanceFromSceneCenter = 0; this.visibleRegionBufferRadius = 0; this.visibleRegionRadius = 0; this.visibleRegionFadeStartRadius = 0; this.firstRenderTime = -1; this.lastBuildScenes = []; this.lastBuildSplatCount = 0; this.lastBuildMaxSplatCount = 0; this.disposeMeshData(); this.geometry = SplatMesh.buildGeomtery(maxSplatCount); this.material = SplatMesh.buildMaterial(this.dynamicMode, this.antialiased, this.maxScreenSpaceSplatSize, this.splatScale, this.pointCloudModeEnabled, this.minSphericalHarmonicsDegree); var indexMaps = SplatMesh.buildSplatIndexMaps(splatBuffers); this.globalSplatIndexToLocalSplatIndexMap = indexMaps.localSplatIndexMap; this.globalSplatIndexToSceneIndexMap = indexMaps.sceneIndexMap; } var splatCount = this.getSplatCount(); if (this.enableDistancesComputationOnGPU) this.setupDistancesComputationTransformFeedback(); var dataUpdateResults = this.refreshGPUDataFromSplatBuffers(isUpdateBuild); for (var _i19 = 0; _i19 < this.scenes.length; _i19++) { this.lastBuildScenes[_i19] = this.scenes[_i19]; } this.lastBuildSplatCount = splatCount; this.lastBuildMaxSplatCount = this.getMaxSplatCount(); this.lastBuildSceneCount = this.scenes.length; if (finalBuild && this.scenes.length > 0) { this.buildSplatTree(sceneOptions.map(options => options.splatAlphaRemovalThreshold || 1), onSplatTreeIndexesUpload, onSplatTreeConstruction).then(() => { if (this.onSplatTreeReadyCallback) this.onSplatTreeReadyCallback(this.splatTree); }); } this.visible = this.scenes.length > 0; return dataUpdateResults; } /** * Dispose all resources held by the splat mesh */ dispose() { this.disposeMeshData(); this.disposeTextures(); this.disposeSplatTree(); if (this.enableDistancesComputationOnGPU) { if (this.computeDistancesOnGPUSyncTimeout) { clearTimeout(this.computeDistancesOnGPUSyncTimeout); this.computeDistancesOnGPUSyncTimeout = null; } this.disposeDistancesComputationGPUResources(); } this.scenes = []; this.distancesTransformFeedback = { 'id': null, 'vertexShader': null, 'fragmentShader': null, 'program': null, 'centersBuffer': null, 'transformIndexesBuffer': null, 'outDistancesBuffer': null, 'centersLoc': -1, 'modelViewProjLoc': -1, 'transformIndexesLoc': -1, 'transformsLocs': [] }; this.renderer = null; this.globalSplatIndexToLocalSplatIndexMap = []; this.globalSplatIndexToSceneIndexMap = []; this.lastBuildSplatCount = 0; this.lastBuildScenes = []; this.lastBuildMaxSplatCount = 0; this.lastBuildSceneCount = 0; this.firstRenderTime = -1; this.finalBuild = false; this.webGLUtils = null; this.boundingBox = new Box3(); this.calculatedSceneCenter = new Vector3(); this.maxSplatDistanceFromSceneCenter = 0; this.visibleRegionBufferRadius = 0; this.visibleRegionRadius = 0; this.visibleRegionFadeStartRadius = 0; this.visibleRegionChanging = false; this.splatScale = 1.0; this.pointCloudModeEnabled = false; this.disposed = true; this.lastRenderer = null; this.visible = false; } /** * Dispose of only the Three.js mesh resources (geometry, material, and texture) */ disposeMeshData() { if (this.geometry && this.geometry !== dummyGeometry) { this.geometry.dispose(); this.geometry = null; } if (this.material) { this.material.dispose(); this.material = null; } } disposeTextures() { for (var textureKey in this.splatDataTextures) { if (this.splatDataTextures.hasOwnProperty(textureKey)) { var textureContainer = this.splatDataTextures[textureKey]; if (textureContainer.texture) { textureContainer.texture.dispose(); textureContainer.texture = null; } } } this.splatDataTextures = null; } disposeSplatTree() { if (this.splatTree) { this.splatTree.dispose(); this.splatTree = null; } else if (this.baseSplatTree) { this.baseSplatTree.dispose(); this.baseSplatTree = null; } } getSplatTree() { return this.splatTree; } onSplatTreeReady(callback) { this.onSplatTreeReadyCallback = callback; } /** * Get copies of data that are necessary for splat distance computation: splat center positions and splat * scene indexes (necessary for applying dynamic scene transformations during distance computation) * @param {*} start The index at which to start copying data * @param {*} end The index at which to stop copying data * @return {object} */ getDataForDistancesComputation(start, end) { var centers = this.integerBasedDistancesComputation ? this.getIntegerCenters(start, end, true) : this.getFloatCenters(start, end, true); var sceneIndexes = this.getSceneIndexes(start, end); return { centers, sceneIndexes }; } /** * Refresh data textures and GPU buffers with splat data from the splat buffers belonging to this mesh. * @param {boolean} sinceLastBuildOnly Specify whether or not to only update for splats that have been added since the last build. * @return {object} */ refreshGPUDataFromSplatBuffers(sinceLastBuildOnly) { var splatCount = this.getSplatCount(); this.refreshDataTexturesFromSplatBuffers(sinceLastBuildOnly); var updateStart = sinceLastBuildOnly ? this.lastBuildSplatCount : 0; var { centers, sceneIndexes } = this.getDataForDistancesComputation(updateStart, splatCount - 1); if (this.enableDistancesComputationOnGPU) { this.refreshGPUBuffersForDistancesComputation(centers, sceneIndexes, sinceLastBuildOnly); } return { 'from': updateStart, 'to': splatCount - 1, 'count': splatCount - updateStart, 'centers': centers, 'sceneIndexes': sceneIndexes }; } /** * Update the GPU buffers that are used for computing splat distances on the GPU. * @param {Array} centers Splat center positions * @param {Array} sceneIndexes Indexes of the scene to which each splat belongs * @param {boolean} sinceLastBuildOnly Specify whether or not to only update for splats that have been added since the last build. */ refreshGPUBuffersForDistancesComputation(centers, sceneIndexes) { var sinceLastBuildOnly = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var offset = sinceLastBuildOnly ? this.lastBuildSplatCount : 0; this.updateGPUCentersBufferForDistancesComputation(sinceLastBuildOnly, centers, offset); this.updateGPUTransformIndexesBufferForDistancesComputation(sinceLastBuildOnly, sceneIndexes, offset); } /** * Refresh data textures with data from the splat buffers for this mesh. * @param {boolean} sinceLastBuildOnly Specify whether or not to only update for splats that have been added since the last build. */ refreshDataTexturesFromSplatBuffers(sinceLastBuildOnly) { if (!sinceLastBuildOnly) { this.setupDataTextures(); } else { this.updateDataTextures(); } this.updateVisibleRegion(sinceLastBuildOnly); } setupDataTextures() { var maxSplatCount = this.getMaxSplatCount(); var splatCount = this.getSplatCount(); this.disposeTextures(); var computeDataTextureSize = (elementsPerTexel, elementsPerSplatl) => { var texSize = new Vector2(4096, 1024); while (texSize.x * texSize.y * elementsPerTexel < maxSplatCount * elementsPerSplatl) texSize.y *= 2; return texSize; }; var covarianceCompressionLevel = this.getTargetCovarianceCompressionLevel(); var sphericalHarmonicsCompressionLevel = this.getTargetSphericalHarmonicsCompressionLevel(); var covariances = new Float32Array(maxSplatCount * COVARIANCES_ELEMENTS_PER_SPLAT); var centers = new Float32Array(maxSplatCount * 3); var colors = new Uint8Array(maxSplatCount * 4); var SphericalHarmonicsArrayType = Float32Array; if (sphericalHarmonicsCompressionLevel === 1) SphericalHarmonicsArrayType = Uint16Array;else if (sphericalHarmonicsCompressionLevel === 2) SphericalHarmonicsArrayType = Uint8Array; var sphericalHarmonicsComponentCount = getSphericalHarmonicsComponentCountForDegree(this.minSphericalHarmonicsDegree); var paddedSphericalHarmonicsComponentCount = sphericalHarmonicsComponentCount; if (paddedSphericalHarmonicsComponentCount % 2 !== 0) paddedSphericalHarmonicsComponentCount++; var sphericalHarmonics = this.minSphericalHarmonicsDegree ? new SphericalHarmonicsArrayType(maxSplatCount * sphericalHarmonicsComponentCount) : undefined; this.fillSplatDataArrays(covariances, centers, colors, sphericalHarmonics, undefined, covarianceCompressionLevel, sphericalHarmonicsCompressionLevel); // set up covariances data texture var covTexSize = computeDataTextureSize(COVARIANCES_ELEMENTS_PER_TEXEL, 6); var CovariancesDataType = covarianceCompressionLevel >= 1 ? Uint16Array : Float32Array; var covariancesTextureType = covarianceCompressionLevel >= 1 ? HalfFloatType : FloatType; var paddedCovariances = new CovariancesDataType(covTexSize.x * covTexSize.y * COVARIANCES_ELEMENTS_PER_TEXEL); paddedCovariances.set(covariances); var covTex = new DataTexture(paddedCovariances, covTexSize.x, covTexSize.y, RGBAFormat, covariancesTextureType); covTex.needsUpdate = true; this.material.uniforms.covariancesTexture.value = covTex; this.material.uniforms.covariancesTextureSize.value.copy(covTexSize); // set up centers/colors data texture var centersColsTexSize = computeDataTextureSize(CENTER_COLORS_ELEMENTS_PER_TEXEL, 4); var paddedCentersCols = new Uint32Array(centersColsTexSize.x * centersColsTexSize.y * CENTER_COLORS_ELEMENTS_PER_TEXEL); SplatMesh.updateCenterColorsPaddedData(0, splatCount, centers, colors, paddedCentersCols); var centersColsTex = new DataTexture(paddedCentersCols, centersColsTexSize.x, centersColsTexSize.y, RGBAIntegerFormat, UnsignedIntType); centersColsTex.internalFormat = 'RGBA32UI'; centersColsTex.needsUpdate = true; this.material.uniforms.centersColorsTexture.value = centersColsTex; this.material.uniforms.centersColorsTextureSize.value.copy(centersColsTexSize); this.material.uniformsNeedUpdate = true; this.splatDataTextures = { 'baseData': { 'covariances': covariances, 'centers': centers, 'colors': colors, 'sphericalHarmonics': sphericalHarmonics }, 'covariances': { 'data': paddedCovariances, 'texture': covTex, 'size': covTexSize, 'compressionLevel': covarianceCompressionLevel }, 'centerColors': { 'data': paddedCentersCols, 'texture': centersColsTex, 'size': centersColsTexSize } }; if (sphericalHarmonics) { var sphericalHarmonicsElementsPerTexel = 4; var sphericalHarmonicsTexSize = computeDataTextureSize(sphericalHarmonicsElementsPerTexel, paddedSphericalHarmonicsComponentCount); var paddedSHArraySize = sphericalHarmonicsTexSize.x * sphericalHarmonicsTexSize.y * sphericalHarmonicsElementsPerTexel; var paddedSHArray = new SphericalHarmonicsArrayType(paddedSHArraySize); for (var c = 0; c < splatCount; c++) { var srcBase = sphericalHarmonicsComponentCount * c; var destBase = paddedSphericalHarmonicsComponentCount * c; for (var i = 0; i < sphericalHarmonicsComponentCount; i++) { paddedSHArray[destBase + i] = sphericalHarmonics[srcBase + i]; } } var textureType = sphericalHarmonicsCompressionLevel === 2 ? UnsignedByteType : HalfFloatType; var sphericalHarmonicsTex = new DataTexture(paddedSHArray, sphericalHarmonicsTexSize.x, sphericalHarmonicsTexSize.y, RGBAFormat, textureType); sphericalHarmonicsTex.needsUpdate = true; this.material.uniforms.sphericalHarmonicsTexture.value = sphericalHarmonicsTex; this.material.uniforms.sphericalHarmonicsTextureSize.value.copy(sphericalHarmonicsTexSize); if (sphericalHarmonicsCompressionLevel === 2) { this.material.uniforms.sphericalHarmonics8BitMode.value = 1; } this.material.uniformsNeedUpdate = true; this.splatDataTextures['sphericalHarmonics'] = { 'componentCount': sphericalHarmonicsComponentCount, 'paddedComponentCount': paddedSphericalHarmonicsComponentCount, 'data': paddedSHArray, 'texture': sphericalHarmonicsTex, 'size': sphericalHarmonicsTexSize, 'compressionLevel': sphericalHarmonicsCompressionLevel }; } if (this.dynamicMode) { var transformIndexesTexSize = computeDataTextureSize(TRANSFORM_INDEXES_ELEMENTS_PER_TEXEL, 4); var paddedTransformIndexes = new Uint32Array(transformIndexesTexSize.x * transformIndexesTexSize.y * TRANSFORM_INDEXES_ELEMENTS_PER_TEXEL); for (var _c = 0; _c < splatCount; _c++) paddedTransformIndexes[_c] = this.globalSplatIndexToSceneIndexMap[_c]; var transformIndexesTexture = new DataTexture(paddedTransformIndexes, transformIndexesTexSize.x, transformIndexesTexSize.y, RedIntegerFormat, UnsignedIntType); transformIndexesTexture.internalFormat = 'R32UI'; transformIndexesTexture.needsUpdate = true; this.material.uniforms.transformIndexesTexture.value = transformIndexesTexture; this.material.uniforms.transformIndexesTextureSize.value.copy(transformIndexesTexSize); this.material.uniformsNeedUpdate = true; this.splatDataTextures['tansformIndexes'] = { 'data': paddedTransformIndexes, 'texture': transformIndexesTexture, 'size': transformIndexesTexSize }; } } updateDataTextures() { var splatCount = this.getSplatCount(); var covarianceCompressionLevel = this.splatDataTextures['covariances'].compressionLevel; var sphericalHarmonicsTextureDesc = this.splatDataTextures['sphericalHarmonics']; var sphericalHarmonicsCompressionLevel = sphericalHarmonicsTextureDesc ? sphericalHarmonicsTextureDesc.compressionLevel : 0; this.fillSplatDataArrays(this.splatDataTextures.baseData.covariances, this.splatDataTextures.baseData.centers, this.splatDataTextures.baseData.colors, this.splatDataTextures.baseData.sphericalHarmonics, undefined, covarianceCompressionLevel, sphericalHarmonicsCompressionLevel, this.lastBuildSplatCount, splatCount - 1, this.lastBuildSplatCount); var covariancesTextureDescriptor = this.splatDataTextures['covariances']; var paddedCovariances = covariancesTextureDescriptor.data; var covariancesTexture = covariancesTextureDescriptor.texture; var covarancesStartSplat = this.lastBuildSplatCount * COVARIANCES_ELEMENTS_PER_SPLAT; var covariancesEndSplat = splatCount * COVARIANCES_ELEMENTS_PER_SPLAT; for (var i = covarancesStartSplat; i < covariancesEndSplat; i++) { var covariance = this.splatDataTextures.baseData.covariances[i]; paddedCovariances[i] = covariance; } var covariancesTextureProps = this.renderer ? this.renderer.properties.get(covariancesTexture) : null; if (!covariancesTextureProps || !covariancesTextureProps.__webglTexture) { covariancesTexture.needsUpdate = true; } else { var covaranceBytesPerElement = covarianceCompressionLevel ? 2 : 4; this.updateDataTexture(paddedCovariances, covariancesTextureDescriptor, covariancesTextureProps, COVARIANCES_ELEMENTS_PER_TEXEL, COVARIANCES_ELEMENTS_PER_SPLAT, covaranceBytesPerElement, this.lastBuildSplatCount, splatCount - 1); } var centerColorsTextureDescriptor = this.splatDataTextures['centerColors']; var paddedCenterColors = centerColorsTextureDescriptor.data; var centerColorsTexture = centerColorsTextureDescriptor.texture; SplatMesh.updateCenterColorsPaddedData(this.lastBuildSplatCount, splatCount, this.splatDataTextures.baseData.centers, this.splatDataTextures.baseData.colors, paddedCenterColors); var centerColorsTextureProps = this.renderer ? this.renderer.properties.get(centerColorsTexture) : null; if (!centerColorsTextureProps || !centerColorsTextureProps.__webglTexture) { centerColorsTexture.needsUpdate = true; } else { this.updateDataTexture(paddedCenterColors, centerColorsTextureDescriptor, centerColorsTextureProps, CENTER_COLORS_ELEMENTS_PER_TEXEL, CENTER_COLORS_ELEMENTS_PER_SPLAT, 4, this.lastBuildSplatCount, splatCount - 1); } if (this.splatDataTextures.baseData.sphericalHarmonics) { var sphericalHarmonicsComponentCount = sphericalHarmonicsTextureDesc.componentCount; var paddedSphericalHarmonicsComponentCount = sphericalHarmonicsTextureDesc.paddedComponentCount; var paddedSHArray = sphericalHarmonicsTextureDesc.data; for (var c = this.lastBuildSplatCount; c < splatCount; c++) { var srcBase = sphericalHarmonicsComponentCount * c; var destBase = paddedSphericalHarmonicsComponentCount * c; for (var _i20 = 0; _i20 < sphericalHarmonicsComponentCount; _i20++) { paddedSHArray[destBase + _i20] = this.splatDataTextures.baseData.sphericalHarmonics[srcBase + _i20]; } } var sphericalHarmonicsTex = sphericalHarmonicsTextureDesc.texture; var sphericalHarmonicsTextureProps = this.renderer ? this.renderer.properties.get(sphericalHarmonicsTex) : null; if (!sphericalHarmonicsTextureProps || !sphericalHarmonicsTextureProps.__webglTexture) { sphericalHarmonicsTex.needsUpdate = true; } else { var sphericalHarmonicsElementsPerTexel = 4; var sphericalHarmonicsBytesPerElement = 4; if (sphericalHarmonicsCompressionLevel === 1) sphericalHarmonicsBytesPerElement = 2;else if (sphericalHarmonicsCompressionLevel === 2) sphericalHarmonicsBytesPerElement = 1; this.updateDataTexture(paddedSHArray, sphericalHarmonicsTextureDesc, sphericalHarmonicsTextureProps, sphericalHarmonicsElementsPerTexel, paddedSphericalHarmonicsComponentCount, sphericalHarmonicsBytesPerElement, this.lastBuildSplatCount, splatCount - 1); } } if (this.dynamicMode) { var transformIndexesTexDesc = this.splatDataTextures['tansformIndexes']; var paddedTransformIndexes = transformIndexesTexDesc.data; for (var _c2 = this.lastBuildSplatCount; _c2 < splatCount; _c2++) { paddedTransformIndexes[_c2] = this.globalSplatIndexToSceneIndexMap[_c2]; } var transformIndexesTexture = transformIndexesTexDesc.texture; var transformIndexesTextureProps = this.renderer ? this.renderer.properties.get(transformIndexesTexture) : null; if (!transformIndexesTextureProps || !transformIndexesTextureProps.__webglTexture) { transformIndexesTexture.needsUpdate = true; } else { this.updateDataTexture(paddedTransformIndexes, transformIndexesTexDesc, transformIndexesTextureProps, 1, 1, 1, this.lastBuildSplatCount, splatCount - 1); } } } getTargetCovarianceCompressionLevel() { return this.halfPrecisionCovariancesOnGPU ? 1 : 0; } getTargetSphericalHarmonicsCompressionLevel() { return Math.max(1, this.getMaximumSplatBufferCompressionLevel()); } getMaximumSplatBufferCompressionLevel() { var maxCompressionLevel; for (var i = 0; i < this.scenes.length; i++) { var scene = this.getScene(i); var splatBuffer = scene.splatBuffer; if (i === 0 || splatBuffer.compressionLevel > maxCompressionLevel) { maxCompressionLevel = splatBuffer.compressionLevel; } } return maxCompressionLevel; } getMinimumSplatBufferCompressionLevel() { var minCompressionLevel; for (var i = 0; i < this.scenes.length; i++) { var scene = this.getScene(i); var splatBuffer = scene.splatBuffer; if (i === 0 || splatBuffer.compressionLevel < minCompressionLevel) { minCompressionLevel = splatBuffer.compressionLevel; } } return minCompressionLevel; } static computeTextureUpdateRegion(startSplat, endSplat, textureWidth, elementsPerTexel, elementsPerSplat) { var texelsPerSplat = elementsPerSplat / elementsPerTexel; var startSplatTexels = startSplat * texelsPerSplat; var startRow = Math.floor(startSplatTexels / textureWidth); var startRowElement = startRow * textureWidth * elementsPerTexel; var endSplatTexels = endSplat * texelsPerSplat; var endRow = Math.floor(endSplatTexels / textureWidth); var endRowEndElement = endRow * textureWidth * elementsPerTexel + textureWidth * elementsPerTexel; return { 'dataStart': startRowElement, 'dataEnd': endRowEndElement, 'startRow': startRow, 'endRow': endRow }; } //局部纹理刷新 updateDataTexture(paddedData, textureDesc, textureProps, elementsPerTexel, elementsPerSplat, bytesPerElement, from, to) { var gl = this.renderer.getContext(); var updateRegion = SplatMesh.computeTextureUpdateRegion(from, to, textureDesc.size.x, elementsPerTexel, elementsPerSplat); var updateElementCount = updateRegion.dataEnd - updateRegion.dataStart; var updateDataView = new paddedData.constructor(paddedData.buffer, updateRegion.dataStart * bytesPerElement, updateElementCount); var updateHeight = updateRegion.endRow - updateRegion.startRow + 1; var dataTexture = textureDesc.texture; var glType = this.webGLUtils.convert(dataTexture.type); var glFormat = this.webGLUtils.convert(dataTexture.format, dataTexture.colorSpace); var currentTexture = gl.getParameter(gl.TEXTURE_BINDING_2D); gl.bindTexture(gl.TEXTURE_2D, textureProps.__webglTexture); gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, updateRegion.startRow, textureDesc.size.x, updateHeight, glFormat, glType, updateDataView); //(target, level, xoffset, yoffset, width, height, format, type, pixels); gl.bindTexture(gl.TEXTURE_2D, currentTexture); } static updateCenterColorsPaddedData(to, from, centers, colors, paddedCenterColors) { for (var c = to; c < from; c++) { var colorsBase = c * 4; var centersBase = c * 3; var centerColorsBase = c * 4; paddedCenterColors[centerColorsBase] = rgbaArrayToInteger(colors, colorsBase); paddedCenterColors[centerColorsBase + 1] = uintEncodedFloat(centers[centersBase]); paddedCenterColors[centerColorsBase + 2] = uintEncodedFloat(centers[centersBase + 1]); paddedCenterColors[centerColorsBase + 3] = uintEncodedFloat(centers[centersBase + 2]); } } updateVisibleRegion(sinceLastBuildOnly) { var splatCount = this.getSplatCount(); var tempCenter = new Vector3(); if (!sinceLastBuildOnly) { var avgCenter = new Vector3(); this.scenes.forEach(scene => { avgCenter.add(scene.splatBuffer.sceneCenter); }); avgCenter.multiplyScalar(1.0 / this.scenes.length); this.calculatedSceneCenter.copy(avgCenter); this.material.uniforms.sceneCenter.value.copy(this.calculatedSceneCenter); this.material.uniformsNeedUpdate = true; } var startSplatFormMaxDistanceCalc = sinceLastBuildOnly ? this.lastBuildSplatCount : 0; for (var i = startSplatFormMaxDistanceCalc; i < splatCount; i++) { this.getSplatCenter(i, tempCenter, false); var distFromCSceneCenter = tempCenter.sub(this.calculatedSceneCenter).length(); if (distFromCSceneCenter > this.maxSplatDistanceFromSceneCenter) this.maxSplatDistanceFromSceneCenter = distFromCSceneCenter; } if (this.maxSplatDistanceFromSceneCenter - this.visibleRegionBufferRadius > VISIBLE_REGION_EXPANSION_DELTA) { this.visibleRegionBufferRadius = this.maxSplatDistanceFromSceneCenter; this.visibleRegionRadius = Math.max(this.visibleRegionBufferRadius - VISIBLE_REGION_EXPANSION_DELTA, 0.0); } if (this.finalBuild) this.visibleRegionRadius = this.visibleRegionBufferRadius = this.maxSplatDistanceFromSceneCenter; this.updateVisibleRegionFadeDistance(); } updateVisibleRegionFadeDistance() { var sceneRevealMode = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : SceneRevealMode.Default; var fastFadeRate = SCENE_FADEIN_RATE_FAST; var gradualFadeRate = SCENE_FADEIN_RATE_GRADUAL; var defaultFadeInRate = this.finalBuild ? fastFadeRate : gradualFadeRate; var fadeInRate = sceneRevealMode === SceneRevealMode.Default ? defaultFadeInRate : gradualFadeRate; this.visibleRegionFadeStartRadius = (this.visibleRegionRadius - this.visibleRegionFadeStartRadius) * fadeInRate + this.visibleRegionFadeStartRadius; var fadeInPercentage = this.visibleRegionBufferRadius > 0 ? this.visibleRegionFadeStartRadius / this.visibleRegionBufferRadius : 0; var fadeInComplete = fadeInPercentage > 0.99; var shaderFadeInComplete = fadeInComplete || sceneRevealMode === SceneRevealMode.Instant ? 1 : 0; this.material.uniforms.visibleRegionFadeStartRadius.value = this.visibleRegionFadeStartRadius; this.material.uniforms.visibleRegionRadius.value = this.visibleRegionRadius; this.material.uniforms.firstRenderTime.value = this.firstRenderTime; this.material.uniforms.currentTime.value = performance.now(); this.material.uniforms.fadeInComplete.value = shaderFadeInComplete; this.material.uniformsNeedUpdate = true; this.visibleRegionChanging = !fadeInComplete; } /** * Set the indexes of splats that should be rendered; should be sorted in desired render order. * @param {Uint32Array} globalIndexes Sorted index list of splats to be rendered * @param {number} renderSplatCount Total number of splats to be rendered. Necessary because we may not want to render * every splat. */ updateRenderIndexes(globalIndexes, renderSplatCount) { //仅渲染前renderSplatCount个点,在前renderSplatCount的顺序是否可以打乱? var geometry = this.geometry; geometry.attributes.splatIndex.set(globalIndexes); geometry.attributes.splatIndex.needsUpdate = true; if (renderSplatCount > 0 && this.firstRenderTime === -1) this.firstRenderTime = performance.now(); geometry.instanceCount = renderSplatCount; } //注:假设全部点都渲染的话,是无所谓index的顺序的,可以直接第0个为0,第n个为n…… /** * Update the transforms for each scene in this splat mesh from their individual components (position, * quaternion, and scale) */ updateTransforms() { for (var i = 0; i < this.scenes.length; i++) { var scene = this.getScene(i); scene.updateTransform(); } } setSplatScale() { var splatScale = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; this.splatScale = splatScale; this.material.uniforms.splatScale.value = splatScale; this.material.uniformsNeedUpdate = true; } getSplatScale() { return this.splatScale; } setPointCloudModeEnabled(enabled) { this.pointCloudModeEnabled = enabled; this.material.uniforms.pointCloudModeEnabled.value = enabled ? 1 : 0; this.material.uniformsNeedUpdate = true; } getPointCloudModeEnabled() { return this.pointCloudModeEnabled; } getSplatDataTextures() { return this.splatDataTextures; } getSplatCount() { return SplatMesh.getTotalSplatCountForScenes(this.scenes); } static getTotalSplatCountForScenes(scenes) { var totalSplatCount = 0; for (var scene of scenes) { if (scene && scene.splatBuffer) totalSplatCount += scene.splatBuffer.getSplatCount(); } return totalSplatCount; } static getTotalSplatCountForSplatBuffers(splatBuffers) { var totalSplatCount = 0; for (var splatBuffer of splatBuffers) totalSplatCount += splatBuffer.getSplatCount(); return totalSplatCount; } getMaxSplatCount() { return SplatMesh.getTotalMaxSplatCountForScenes(this.scenes); } static getTotalMaxSplatCountForScenes(scenes) { var totalSplatCount = 0; for (var scene of scenes) { if (scene && scene.splatBuffer) totalSplatCount += scene.splatBuffer.getMaxSplatCount(); } return totalSplatCount; } static getTotalMaxSplatCountForSplatBuffers(splatBuffers) { var totalSplatCount = 0; for (var splatBuffer of splatBuffers) totalSplatCount += splatBuffer.getMaxSplatCount(); return totalSplatCount; } disposeDistancesComputationGPUResources() { if (!this.renderer) return; var gl = this.renderer.getContext(); if (this.distancesTransformFeedback.vao) { gl.deleteVertexArray(this.distancesTransformFeedback.vao); this.distancesTransformFeedback.vao = null; } if (this.distancesTransformFeedback.program) { gl.deleteProgram(this.distancesTransformFeedback.program); gl.deleteShader(this.distancesTransformFeedback.vertexShader); gl.deleteShader(this.distancesTransformFeedback.fragmentShader); this.distancesTransformFeedback.program = null; this.distancesTransformFeedback.vertexShader = null; this.distancesTransformFeedback.fragmentShader = null; } this.disposeDistancesComputationGPUBufferResources(); if (this.distancesTransformFeedback.id) { gl.deleteTransformFeedback(this.distancesTransformFeedback.id); this.distancesTransformFeedback.id = null; } } disposeDistancesComputationGPUBufferResources() { if (!this.renderer) return; var gl = this.renderer.getContext(); if (this.distancesTransformFeedback.centersBuffer) { this.distancesTransformFeedback.centersBuffer = null; gl.deleteBuffer(this.distancesTransformFeedback.centersBuffer); } if (this.distancesTransformFeedback.outDistancesBuffer) { gl.deleteBuffer(this.distancesTransformFeedback.outDistancesBuffer); this.distancesTransformFeedback.outDistancesBuffer = null; } } /** * Set the Three.js renderer used by this splat mesh * @param {THREE.WebGLRenderer} renderer Instance of THREE.WebGLRenderer */ setRenderer(renderer) { if (renderer !== this.renderer) { this.renderer = renderer; var gl = this.renderer.getContext(); var extensions = new WebGLExtensions$1(gl); var capabilities = new WebGLCapabilities$1(gl, extensions, {}); extensions.init(capabilities); this.webGLUtils = new WebGLUtils(gl, extensions, capabilities); if (this.enableDistancesComputationOnGPU && this.getSplatCount() > 0) { this.setupDistancesComputationTransformFeedback(); var { centers: _centers, sceneIndexes } = this.getDataForDistancesComputation(0, this.getSplatCount() - 1); this.refreshGPUBuffersForDistancesComputation(_centers, sceneIndexes); } } } /** * Refresh GPU buffers used for computing splat distances with centers data from the scenes for this mesh. * @param {boolean} isUpdate Specify whether or not to update the GPU buffer or to initialize & fill * @param {Array} centers The splat centers data * @param {number} offsetSplats Offset in the GPU buffer at which to start updating data, specified in splats */ updateGPUCentersBufferForDistancesComputation(isUpdate, centers, offsetSplats) { if (!this.renderer) return; var gl = this.renderer.getContext(); var currentVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING); gl.bindVertexArray(this.distancesTransformFeedback.vao); var ArrayType = this.integerBasedDistancesComputation ? Uint32Array : Float32Array; var attributeBytesPerCenter = 16; var subBufferOffset = offsetSplats * attributeBytesPerCenter; gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.centersBuffer); if (isUpdate) { gl.bufferSubData(gl.ARRAY_BUFFER, subBufferOffset, centers); } else { var maxArray = new ArrayType(this.getMaxSplatCount() * attributeBytesPerCenter); maxArray.set(centers); gl.bufferData(gl.ARRAY_BUFFER, maxArray, gl.STATIC_DRAW); } gl.bindBuffer(gl.ARRAY_BUFFER, null); if (currentVao) gl.bindVertexArray(currentVao); } /** * Refresh GPU buffers used for pre-computing splat distances with centers data from the scenes for this mesh. * @param {boolean} isUpdate Specify whether or not to update the GPU buffer or to initialize & fill * @param {Array} transformIndexes The splat transform indexes * @param {number} offsetSplats Offset in the GPU buffer at which to start updating data, specified in splats */ updateGPUTransformIndexesBufferForDistancesComputation(isUpdate, transformIndexes, offsetSplats) { if (!this.renderer || !this.dynamicMode) return; var gl = this.renderer.getContext(); var currentVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING); gl.bindVertexArray(this.distancesTransformFeedback.vao); var subBufferOffset = offsetSplats * 4; gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.transformIndexesBuffer); if (isUpdate) { gl.bufferSubData(gl.ARRAY_BUFFER, subBufferOffset, transformIndexes); } else { var maxArray = new Uint32Array(this.getMaxSplatCount() * 4); maxArray.set(transformIndexes); gl.bufferData(gl.ARRAY_BUFFER, maxArray, gl.STATIC_DRAW); } gl.bindBuffer(gl.ARRAY_BUFFER, null); if (currentVao) gl.bindVertexArray(currentVao); } /** * Get a typed array containing a mapping from global splat indexes to their scene index. * @param {number} start Starting splat index to store * @param {number} end Ending splat index to store * @return {Uint32Array} */ getSceneIndexes(start, end) { var sceneIndexes; var fillCount = end - start + 1; sceneIndexes = new Uint32Array(fillCount); for (var i = start; i <= end; i++) { sceneIndexes[i] = this.globalSplatIndexToSceneIndexMap[i]; } return sceneIndexes; } /** * Given a global splat index, return corresponding local data (splat buffer, index of splat in that splat * buffer, and the corresponding transform) * @param {number} globalIndex Global splat index * @param {object} paramsObj Object in which to store local data * @param {boolean} returnSceneTransform By default, the transform of the scene to which the splat at 'globalIndex' belongs will be * returned via the 'sceneTransform' property of 'paramsObj' only if the splat mesh is static. * If 'returnSceneTransform' is true, the 'sceneTransform' property will always contain the scene * transform, and if 'returnSceneTransform' is false, the 'sceneTransform' property will always * be null. */ getLocalSplatParameters(globalIndex, paramsObj, returnSceneTransform) { if (returnSceneTransform === undefined || returnSceneTransform === null) { returnSceneTransform = this.dynamicMode ? false : true; } paramsObj.splatBuffer = this.getSplatBufferForSplat(globalIndex); paramsObj.localIndex = this.getSplatLocalIndex(globalIndex); paramsObj.sceneTransform = returnSceneTransform ? this.getSceneTransformForSplat(globalIndex) : null; } /** * Fill arrays with splat data and apply transforms if appropriate. Each array is optional. * @param {Float32Array} covariances Target storage for splat covariances * @param {Float32Array} centers Target storage for splat centers * @param {Uint8Array} colors Target storage for splat colors * @param {Float32Array} sphericalHarmonics Target storage for spherical harmonics * @param {boolean} applySceneTransform By default, scene transforms are applied to relevant splat data only if the splat mesh is * static. If 'applySceneTransform' is true, scene transforms will always be applied and if * it is false, they will never be applied. If undefined, the default behavior will apply. * @param {number} covarianceCompressionLevel The compression level for covariances in the destination array * @param {number} sphericalHarmonicsCompressionLevel The compression level for spherical harmonics in the destination array * @param {number} srcStart The start location from which to pull source data * @param {number} srcEnd The end location from which to pull source data * @param {number} destStart The start location from which to write data */ fillSplatDataArrays(covariances, centers, colors, sphericalHarmonics, applySceneTransform) { var covarianceCompressionLevel = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; var sphericalHarmonicsCompressionLevel = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 1; var srcStart = arguments.length > 7 ? arguments[7] : undefined; var srcEnd = arguments.length > 8 ? arguments[8] : undefined; var destStart = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : 0; for (var i = 0; i < this.scenes.length; i++) { if (applySceneTransform === undefined || applySceneTransform === null) { applySceneTransform = this.dynamicMode ? false : true; } var scene = this.getScene(i); var splatBuffer = scene.splatBuffer; var sceneTransform = applySceneTransform ? scene.transform : null; if (covariances) { splatBuffer.fillSplatCovarianceArray(covariances, sceneTransform, srcStart, srcEnd, destStart, covarianceCompressionLevel); } if (centers) splatBuffer.fillSplatCenterArray(centers, sceneTransform, srcStart, srcEnd, destStart); if (colors) splatBuffer.fillSplatColorArray(colors, scene.minimumAlpha, srcStart, srcEnd, destStart); if (sphericalHarmonics) { splatBuffer.fillSphericalHarmonicsArray(sphericalHarmonics, this.minSphericalHarmonicsDegree, sceneTransform, srcStart, srcEnd, destStart, sphericalHarmonicsCompressionLevel); } destStart += splatBuffer.getSplatCount(); } } /** * Convert splat centers, which are floating point values, to an array of integers and multiply * each by 1000. Centers will get transformed as appropriate before conversion to integer. * @param {number} start The index at which to start retrieving data * @param {number} end The index at which to stop retrieving data * @param {boolean} padFour Enforce alignment of 4 by inserting a 1 after every 3 values * @return {Int32Array} */ getIntegerCenters(start, end) { var padFour = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var splatCount = end - start + 1; var floatCenters = new Float32Array(splatCount * 3); this.fillSplatDataArrays(null, floatCenters, null, null, undefined, undefined, undefined, start); var intCenters; var componentCount = padFour ? 4 : 3; intCenters = new Int32Array(splatCount * componentCount); for (var i = 0; i < splatCount; i++) { for (var t = 0; t < 3; t++) { intCenters[i * componentCount + t] = Math.round(floatCenters[i * 3 + t] * 1000.0); } if (padFour) intCenters[i * componentCount + 3] = 1000; } return intCenters; } /** * Returns an array of splat centers, transformed as appropriate, optionally padded. * @param {number} start The index at which to start retrieving data * @param {number} end The index at which to stop retrieving data * @param {boolean} padFour Enforce alignment of 4 by inserting a 1 after every 3 values * @return {Float32Array} */ getFloatCenters(start, end) { var padFour = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var splatCount = end - start + 1; var floatCenters = new Float32Array(splatCount * 3); this.fillSplatDataArrays(null, floatCenters, null, null, undefined, undefined, undefined, start); if (!padFour) return floatCenters; var paddedFloatCenters = new Float32Array(splatCount * 4); for (var i = 0; i < splatCount; i++) { for (var t = 0; t < 3; t++) { paddedFloatCenters[i * 4 + t] = floatCenters[i * 3 + t]; } paddedFloatCenters[i * 4 + 3] = 1.0; } return paddedFloatCenters; } /** * Store the transform of the scene at 'sceneIndex' in 'outTransform'. * @param {number} sceneIndex Index of the desired scene * @param {THREE.Matrix4} outTransform Instance of THREE.Matrix4 in which to store the scene's transform */ getSceneTransform(sceneIndex, outTransform) { var scene = this.getScene(sceneIndex); scene.updateTransform(); outTransform.copy(scene.transform); } /** * Get the scene at 'sceneIndex'. * @param {number} sceneIndex Index of the desired scene * @return {SplatScene} */ getScene(sceneIndex) { if (sceneIndex < 0 || sceneIndex >= this.scenes.length) { throw new Error('SplatMesh::getScene() -> Invalid scene index.'); } return this.scenes[sceneIndex]; } getSplatBufferForSplat(globalIndex) { return this.getScene(this.globalSplatIndexToSceneIndexMap[globalIndex]).splatBuffer; } getSceneIndexForSplat(globalIndex) { return this.globalSplatIndexToSceneIndexMap[globalIndex]; } getSceneTransformForSplat(globalIndex) { return this.getScene(this.globalSplatIndexToSceneIndexMap[globalIndex]).transform; } getSplatLocalIndex(globalIndex) { return this.globalSplatIndexToLocalSplatIndexMap[globalIndex]; } static getIntegerMatrixArray(matrix) { var matrixElements = matrix.elements; var intMatrixArray = []; for (var i = 0; i < 16; i++) { intMatrixArray[i] = Math.round(matrixElements[i] * 1000.0); } return intMatrixArray; } } var SorterWasm = "AGFzbQEAAAAADAZkeWxpbmsAAAAAAAEbA2AAAGAQf39/f39/f39/f39/f39/fwBgAAF/AhIBA2VudgZtZW1vcnkCAwCAgAQDBAMAAQIHOQMRX193YXNtX2NhbGxfY3RvcnMAAAtzb3J0SW5kZXhlcwABE2Vtc2NyaXB0ZW5fdGxzX2luaXQAAgrHEAMDAAELuxAFAXwDewJ/A30CfiALIAprIQwCQCAOBEAgDQRAQfj///8HIQ5BiICAgHghDSALIAxNDQIgDCEBA0AgAyABQQJ0IgVqIAIgACAFaigCAEECdGooAgAiBTYCACAFIA4gBSAOSBshDiAFIA0gBSANShshDSABQQFqIgEgC0cNAAsMAgsgDwRAQfj///8HIQ5BiICAgHghDSALIAxNDQJBfyEPIAwhAgNAIA8gByAAIAJBAnQiFGooAgAiFUECdGooAgAiCkcEQAJ+IAX9CQIIIAggCkEGdGoiD/0JAgAgDyoCEP0gASAPKgIg/SACIA8qAjD9IAP95gEgBf0JAhggD/0JAgQgDyoCFP0gASAPKgIk/SACIA8qAjT9IAP95gH95AEgBf0JAiggD/0JAgggDyoCGP0gASAPKgIo/SACIA8qAjj9IAP95gH95AEgBf0JAjggD/0JAgwgDyoCHP0gASAPKgIs/SACIA8qAjz9IAP95gH95AEiEf0fArv9FCAR/R8Du/0iAf0MAAAAAABAj0AAAAAAAECPQCIS/fIBIhP9IQEiEJlEAAAAAAAA4ENjBEAgELAMAQtCgICAgICAgICAfwshGQJ+IBP9IQAiEJlEAAAAAAAA4ENjBEAgELAMAQtCgICAgICAgICAfwv9EiETAn4gEf0fALv9FCAR/R8Bu/0iASAS/fIBIhH9IQEiEJlEAAAAAAAA4ENjBEAgELAMAQtCgICAgICAgICAfwshGiATIBn9HgEhEgJ+IBH9IQAiEJlEAAAAAAAA4ENjBEAgELAMAQtCgICAgICAgICAfwv9EiAa/R4BIBL9DQABAgMICQoLEBESExgZGhshEiAKIQ8LIAMgFGogASAVQQR0av0AAAAgEv21ASIR/RsAIBH9GwFqIBH9GwJqIBH9GwNqIgo2AgAgCiAOIAogDkgbIQ4gCiANIAogDUobIQ0gAkEBaiICIAtHDQALDAILAn8gBSoCGLtEAAAAAABAj0CiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEKAn8gBSoCCLtEAAAAAABAj0CiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyECAn8gBSoCKLtEAAAAAABAj0CiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEFQfj///8HIQ5BiICAgHghDSALIAxNDQEgAv0RIAr9HAEgBf0cAiESIAwhBQNAIAMgBUECdCICaiABIAAgAmooAgBBBHRq/QAAACAS/bUBIhH9GwAgEf0bAWogEf0bAmoiAjYCACACIA4gAiAOSBshDiACIA0gAiANShshDSAFQQFqIgUgC0cNAAsMAQsgDQRAQfj///8HIQ5BiICAgHghDSALIAxNDQEgDCEBA0AgAyABQQJ0IgVqAn8gAiAAIAVqKAIAQQJ0aioCALtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyIKNgIAIAogDiAKIA5IGyEOIAogDSAKIA1KGyENIAFBAWoiASALRw0ACwwBCwJAIA9FBEAgCyAMSw0BQYiAgIB4IQ1B+P///wchDgwCC0H4////ByEOQYiAgIB4IQ0gCyAMTQ0BQX8hDyAMIQIDQCAPIAcgACACQQJ0IhRqKAIAQQJ0IhVqKAIAIgpHBEAgBf0JAgggCCAKQQZ0aiIP/QkCACAPKgIQ/SABIA8qAiD9IAIgDyoCMP0gA/3mASAF/QkCGCAP/QkCBCAPKgIU/SABIA8qAiT9IAIgDyoCNP0gA/3mAf3kASAF/QkCKCAP/QkCCCAPKgIY/SABIA8qAij9IAIgDyoCOP0gA/3mAf3kASAF/QkCOCAP/QkCDCAPKgIc/SABIA8qAiz9IAIgDyoCPP0gA/3mAf3kASERIAohDwsgAyAUagJ/IBEgASAVQQJ0IgpqKQIA/RL95gEiEv0fACAS/R8BkiARIBH9DQgJCgsMDQ4PAAAAAAAAAAAgASAKQQhyaikCAP0S/eYBIhL9HwCSIBL9HwGSu0QAAAAAAACwQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIgo2AgAgCiAOIAogDkgbIQ4gCiANIAogDUobIQ0gAkEBaiICIAtHDQALDAELIAUqAighFiAFKgIYIRcgBSoCCCEYQfj///8HIQ5BiICAgHghDSAMIQUDQAJ/IBggASAAIAVBAnQiB2ooAgBBBHRqIgIqAgCUIBcgAioCBJSSIBYgAioCCJSSu0QAAAAAAACwQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIQogAyAHaiAKNgIAIAogDiAKIA5IGyEOIAogDSAKIA1KGyENIAVBAWoiBSALRw0ACwsgCyAMSwRAIAlBAWuzIA2yIA6yk5UhFiAMIQ0DQAJ/IBYgAyANQQJ0aiIBKAIAIA5rspQiF4tDAAAAT10EQCAXqAwBC0GAgICAeAshCiABIAo2AgAgBCAKQQJ0aiIBIAEoAgBBAWo2AgAgDUEBaiINIAtHDQALCyAJQQJPBEAgBCgCACENQQEhDgNAIAQgDkECdGoiASABKAIAIA1qIg02AgAgDkEBaiIOIAlHDQALCyAMQQBKBEAgDCEOA0AgBiAOQQFrIgFBAnQiAmogACACaigCADYCACAOQQFKIQIgASEOIAINAAsLIAsgDEoEQCALIQ4DQCAGIAsgBCADIA5BAWsiDkECdCIBaigCAEECdGoiAigCACIFa0ECdGogACABaigCADYCACACIAVBAWs2AgAgDCAOSA0ACwsLBABBAAs="; //sortIndexes 按照深度排序 function sortWorker(self) { var wasmInstance; var wasmMemory; var useSharedMemory; var integerBasedSort; var dynamicMode; var splatCount; var indexesToSortOffset; //存储首地址 var sortedIndexesOffset; var transformIndexesOffset; var transformsOffset; var precomputedDistancesOffset; var mappedDistancesOffset; var frequenciesOffset; var centersOffset; var modelViewProjOffset; var countsZero; var sortedIndexesOut; var Constants; function sort(splatSortCount, splatRenderCount, modelViewProj, usePrecomputedDistances, copyIndexesToSort, copyPrecomputedDistances, copyTransforms) { var sortStartTime = performance.now(); if (!useSharedMemory) { var indexesToSort = new Uint32Array(wasmMemory, indexesToSortOffset, copyIndexesToSort.byteLength / Constants.BytesPerInt); indexesToSort.set(copyIndexesToSort); var transforms = new Float32Array(wasmMemory, transformsOffset, copyTransforms.byteLength / Constants.BytesPerFloat); transforms.set(copyTransforms); if (usePrecomputedDistances) { var precomputedDistances; if (integerBasedSort) { precomputedDistances = new Int32Array(wasmMemory, precomputedDistancesOffset, copyPrecomputedDistances.byteLength / Constants.BytesPerInt); } else { precomputedDistances = new Float32Array(wasmMemory, precomputedDistancesOffset, copyPrecomputedDistances.byteLength / Constants.BytesPerFloat); } precomputedDistances.set(copyPrecomputedDistances); } } if (!countsZero) countsZero = new Uint32Array(Constants.DepthMapRange); new Float32Array(wasmMemory, modelViewProjOffset, 16).set(modelViewProj); //由于新数组已经与 WebAssembly 内存关联,实际上是将 modelViewProj 的数据复制到了 WebAssembly 内存的指定位置。 new Uint32Array(wasmMemory, frequenciesOffset, Constants.DepthMapRange).set(countsZero); wasmInstance.exports.sortIndexes(indexesToSortOffset, centersOffset, precomputedDistancesOffset, mappedDistancesOffset, frequenciesOffset, modelViewProjOffset, sortedIndexesOffset, transformIndexesOffset, transformsOffset, Constants.DepthMapRange, splatSortCount, splatRenderCount, splatCount, usePrecomputedDistances, integerBasedSort, dynamicMode); var sortMessage = { 'sortDone': true, 'splatSortCount': splatSortCount, 'splatRenderCount': splatRenderCount, 'sortTime': 0 }; if (!useSharedMemory) { var sortedIndexes = new Uint32Array(wasmMemory, sortedIndexesOffset, splatRenderCount); if (!sortedIndexesOut || sortedIndexesOut.length < splatRenderCount) { sortedIndexesOut = new Uint32Array(splatRenderCount); } sortedIndexesOut.set(sortedIndexes); sortMessage.sortedIndexes = sortedIndexesOut; } var sortEndTime = performance.now(); sortMessage.sortTime = sortEndTime - sortStartTime; self.postMessage(sortMessage); } self.onmessage = e => { if (e.data.centers) { //填入坐标数据 centers = e.data.centers; transformIndexes = e.data.transformIndexes; if (integerBasedSort) { new Int32Array(wasmMemory, centersOffset + e.data.range.from * Constants.BytesPerInt * 4, e.data.range.count * 4).set(new Int32Array(centers)); } else { new Float32Array(wasmMemory, centersOffset + e.data.range.from * Constants.BytesPerFloat * 4, e.data.range.count * 4).set(new Float32Array(centers)); } if (dynamicMode) { new Uint32Array(wasmMemory, transformIndexesOffset + e.data.range.from * 4, e.data.range.count).set(new Uint32Array(transformIndexes)); } self.postMessage({ 'centerDataSet': true }); } else if (e.data.sort) { //请求sort var renderCount = e.data.sort.splatRenderCount || 0; var sortCount = e.data.sort.splatSortCount || 0; var usePrecomputedDistances = e.data.sort.usePrecomputedDistances; var copyIndexesToSort; var copyPrecomputedDistances; var copyTransforms; if (!useSharedMemory) { copyIndexesToSort = e.data.sort.indexesToSort; copyTransforms = e.data.sort.transforms; if (usePrecomputedDistances) copyPrecomputedDistances = e.data.sort.precomputedDistances; } sort(sortCount, renderCount, e.data.sort.modelViewProj, usePrecomputedDistances, copyIndexesToSort, copyPrecomputedDistances, copyTransforms); } else if (e.data.init) { //初始化 分配空间 // Yep, this is super hacky and gross :( Constants = e.data.init.Constants; splatCount = e.data.init.splatCount; useSharedMemory = e.data.init.useSharedMemory; integerBasedSort = e.data.init.integerBasedSort; dynamicMode = e.data.init.dynamicMode; var CENTERS_BYTES_PER_ENTRY = integerBasedSort ? Constants.BytesPerInt * 4 : Constants.BytesPerFloat * 4; var sorterWasmBytes = new Uint8Array(e.data.init.sorterWasmBytes); var matrixSize = 16 * Constants.BytesPerFloat; var memoryRequiredForIndexesToSort = splatCount * Constants.BytesPerInt; var memoryRequiredForCenters = splatCount * CENTERS_BYTES_PER_ENTRY; var memoryRequiredForModelViewProjectionMatrix = matrixSize; var memoryRequiredForPrecomputedDistances = integerBasedSort ? splatCount * Constants.BytesPerInt : splatCount * Constants.BytesPerFloat; var memoryRequiredForMappedDistances = splatCount * Constants.BytesPerInt; var memoryRequiredForSortedIndexes = splatCount * Constants.BytesPerInt; var memoryRequiredForIntermediateSortBuffers = Constants.DepthMapRange * Constants.BytesPerInt * 2; var memoryRequiredforTransformIndexes = dynamicMode ? splatCount * Constants.BytesPerInt : 0; var memoryRequiredforTransforms = dynamicMode ? Constants.MaxScenes * matrixSize : 0; var extraMemory = Constants.MemoryPageSize * 32; var totalRequiredMemory = memoryRequiredForIndexesToSort + memoryRequiredForCenters + memoryRequiredForModelViewProjectionMatrix + memoryRequiredForPrecomputedDistances + memoryRequiredForMappedDistances + memoryRequiredForIntermediateSortBuffers + memoryRequiredForSortedIndexes + memoryRequiredforTransformIndexes + memoryRequiredforTransforms + extraMemory; var totalPagesRequired = Math.floor(totalRequiredMemory / Constants.MemoryPageSize) + 1; var sorterWasmImport = { module: {}, env: { memory: new WebAssembly.Memory({ initial: totalPagesRequired * 2, //创建一个初始大小为 .. 页(每页64KiB)的内存实例 maximum: totalPagesRequired * 4, shared: true }) } }; WebAssembly.compile(sorterWasmBytes).then(wasmModule => { return WebAssembly.instantiate(wasmModule, sorterWasmImport); }).then(instance => { wasmInstance = instance; indexesToSortOffset = 0; centersOffset = indexesToSortOffset + memoryRequiredForIndexesToSort; modelViewProjOffset = centersOffset + memoryRequiredForCenters; precomputedDistancesOffset = modelViewProjOffset + memoryRequiredForModelViewProjectionMatrix; mappedDistancesOffset = precomputedDistancesOffset + memoryRequiredForPrecomputedDistances; frequenciesOffset = mappedDistancesOffset + memoryRequiredForMappedDistances; sortedIndexesOffset = frequenciesOffset + memoryRequiredForIntermediateSortBuffers; transformIndexesOffset = sortedIndexesOffset + memoryRequiredForSortedIndexes; transformsOffset = transformIndexesOffset + memoryRequiredforTransformIndexes; wasmMemory = sorterWasmImport.env.memory.buffer; //SharedArrayBuffer if (useSharedMemory) { self.postMessage({ 'sortSetupPhase1Complete': true, 'indexesToSortBuffer': wasmMemory, 'indexesToSortOffset': indexesToSortOffset, 'sortedIndexesBuffer': wasmMemory, //整理好的indexes 'sortedIndexesOffset': sortedIndexesOffset, 'precomputedDistancesBuffer': wasmMemory, 'precomputedDistancesOffset': precomputedDistancesOffset, 'transformsBuffer': wasmMemory, 'transformsOffset': transformsOffset }); } else { self.postMessage({ 'sortSetupPhase1Complete': true }); } }); } }; } function createSortWorker(splatCount, useSharedMemory, integerBasedSort, dynamicMode) { var worker = new Worker(URL.createObjectURL(new Blob(['(', sortWorker.toString(), ')(self)'], { type: 'application/javascript' }))); var sorterWasmBinaryString = atob(SorterWasm); //二进制代码 var sorterWasmBytes = new Uint8Array(sorterWasmBinaryString.length); for (var i = 0; i < sorterWasmBinaryString.length; i++) { sorterWasmBytes[i] = sorterWasmBinaryString.charCodeAt(i); } worker.postMessage({ 'init': { 'sorterWasmBytes': sorterWasmBytes.buffer, 'splatCount': splatCount, 'useSharedMemory': useSharedMemory, 'integerBasedSort': integerBasedSort, 'dynamicMode': dynamicMode, // Super hacky 'Constants': { 'BytesPerFloat': Constants.BytesPerFloat, 'BytesPerInt': Constants.BytesPerInt, 'DepthMapRange': Constants.DepthMapRange, 'MemoryPageSize': Constants.MemoryPageSize, 'MaxScenes': Constants.MaxScenes } } }); return worker; } /* 相关函数见 setupSortWorker updateSplatSort updateRenderIndexes addSplatBuffers 为什么要手动排序?shader无法计算准确的深度吗 */ var WebXRMode = { None: 0, VR: 1, AR: 2 }; /* Copyright © 2010-2024 three.js authors & Mark Kellogg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ class VRButton { static createButton(renderer) { var button = document.createElement('button'); function showEnterVR( /* device */ ) { var currentSession = null; async function onSessionStarted(session) { session.addEventListener('end', onSessionEnded); await renderer.xr.setSession(session); button.textContent = 'EXIT VR'; currentSession = session; } function onSessionEnded( /* event */ ) { currentSession.removeEventListener('end', onSessionEnded); button.textContent = 'ENTER VR'; currentSession = null; } // button.style.display = ''; button.style.cursor = 'pointer'; button.style.left = 'calc(50% - 50px)'; button.style.width = '100px'; button.textContent = 'ENTER VR'; // WebXR's requestReferenceSpace only works if the corresponding feature // was requested at session creation time. For simplicity, just ask for // the interesting ones as optional features, but be aware that the // requestReferenceSpace call will fail if it turns out to be unavailable. // ('local' is always available for immersive sessions and doesn't need to // be requested separately.) var sessionInit = { optionalFeatures: ['local-floor', 'bounded-floor', 'hand-tracking', 'layers'] }; button.onmouseenter = function () { button.style.opacity = '1.0'; }; button.onmouseleave = function () { button.style.opacity = '0.5'; }; button.onclick = function () { if (currentSession === null) { navigator.xr.requestSession('immersive-vr', sessionInit).then(onSessionStarted); } else { currentSession.end(); if (navigator.xr.offerSession !== undefined) { navigator.xr.offerSession('immersive-vr', sessionInit).then(onSessionStarted).catch(err => { console.warn(err); }); } } }; if (navigator.xr.offerSession !== undefined) { navigator.xr.offerSession('immersive-vr', sessionInit).then(onSessionStarted).catch(err => { console.warn(err); }); } } function disableButton() { button.style.display = ''; button.style.cursor = 'auto'; button.style.left = 'calc(50% - 75px)'; button.style.width = '150px'; button.onmouseenter = null; button.onmouseleave = null; button.onclick = null; } function showWebXRNotFound() { disableButton(); button.textContent = 'VR NOT SUPPORTED'; } function showVRNotAllowed(exception) { disableButton(); console.warn('Exception when trying to call xr.isSessionSupported', exception); button.textContent = 'VR NOT ALLOWED'; } function stylizeElement(element) { element.style.position = 'absolute'; element.style.bottom = '20px'; element.style.padding = '12px 6px'; element.style.border = '1px solid #fff'; element.style.borderRadius = '4px'; element.style.background = 'rgba(0,0,0,0.1)'; element.style.color = '#fff'; element.style.font = 'normal 13px sans-serif'; element.style.textAlign = 'center'; element.style.opacity = '0.5'; element.style.outline = 'none'; element.style.zIndex = '999'; } if ('xr' in navigator) { button.id = 'VRButton'; button.style.display = 'none'; stylizeElement(button); navigator.xr.isSessionSupported('immersive-vr').then(function (supported) { supported ? showEnterVR() : showWebXRNotFound(); if (supported && VRButton.xrSessionIsGranted) { button.click(); } }).catch(showVRNotAllowed); return button; } else { var message = document.createElement('a'); if (window.isSecureContext === false) { message.href = document.location.href.replace(/^http:/, 'https:'); message.innerHTML = 'WEBXR NEEDS HTTPS'; // TODO Improve message } else { message.href = 'https://immersiveweb.dev/'; message.innerHTML = 'WEBXR NOT AVAILABLE'; } message.style.left = 'calc(50% - 90px)'; message.style.width = '180px'; message.style.textDecoration = 'none'; stylizeElement(message); return message; } } static registerSessionGrantedListener() { if (typeof navigator !== 'undefined' && 'xr' in navigator) { // WebXRViewer (based on Firefox) has a bug where addEventListener // throws a silent exception and aborts execution entirely. if (/WebXRViewer\//i.test(navigator.userAgent)) return; navigator.xr.addEventListener('sessiongranted', () => { VRButton.xrSessionIsGranted = true; }); } } } VRButton.xrSessionIsGranted = false; VRButton.registerSessionGrantedListener(); /* Copyright © 2010-2024 three.js authors & Mark Kellogg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ class ARButton { static createButton(renderer) { var sessionInit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var button = document.createElement('button'); function showStartAR( /* device */ ) { if (sessionInit.domOverlay === undefined) { var overlay = document.createElement('div'); overlay.style.display = 'none'; document.body.appendChild(overlay); var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.setAttribute('width', 38); svg.setAttribute('height', 38); svg.style.position = 'absolute'; svg.style.right = '20px'; svg.style.top = '20px'; svg.addEventListener('click', function () { currentSession.end(); }); overlay.appendChild(svg); var path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); path.setAttribute('d', 'M 12,12 L 28,28 M 28,12 12,28'); path.setAttribute('stroke', '#fff'); path.setAttribute('stroke-width', 2); svg.appendChild(path); if (sessionInit.optionalFeatures === undefined) { sessionInit.optionalFeatures = []; } sessionInit.optionalFeatures.push('dom-overlay'); sessionInit.domOverlay = { root: overlay }; } // var currentSession = null; async function onSessionStarted(session) { session.addEventListener('end', onSessionEnded); renderer.xr.setReferenceSpaceType('local'); await renderer.xr.setSession(session); button.textContent = 'STOP AR'; sessionInit.domOverlay.root.style.display = ''; currentSession = session; } function onSessionEnded( /* event */ ) { currentSession.removeEventListener('end', onSessionEnded); button.textContent = 'START AR'; sessionInit.domOverlay.root.style.display = 'none'; currentSession = null; } // button.style.display = ''; button.style.cursor = 'pointer'; button.style.left = 'calc(50% - 50px)'; button.style.width = '100px'; button.textContent = 'START AR'; button.onmouseenter = function () { button.style.opacity = '1.0'; }; button.onmouseleave = function () { button.style.opacity = '0.5'; }; button.onclick = function () { if (currentSession === null) { navigator.xr.requestSession('immersive-ar', sessionInit).then(onSessionStarted); } else { currentSession.end(); if (navigator.xr.offerSession !== undefined) { navigator.xr.offerSession('immersive-ar', sessionInit).then(onSessionStarted).catch(err => { console.warn(err); }); } } }; if (navigator.xr.offerSession !== undefined) { navigator.xr.offerSession('immersive-ar', sessionInit).then(onSessionStarted).catch(err => { console.warn(err); }); } } function disableButton() { button.style.display = ''; button.style.cursor = 'auto'; button.style.left = 'calc(50% - 75px)'; button.style.width = '150px'; button.onmouseenter = null; button.onmouseleave = null; button.onclick = null; } function showARNotSupported() { disableButton(); button.textContent = 'AR NOT SUPPORTED'; } function showARNotAllowed(exception) { disableButton(); console.warn('Exception when trying to call xr.isSessionSupported', exception); button.textContent = 'AR NOT ALLOWED'; } function stylizeElement(element) { element.style.position = 'absolute'; element.style.bottom = '20px'; element.style.padding = '12px 6px'; element.style.border = '1px solid #fff'; element.style.borderRadius = '4px'; element.style.background = 'rgba(0,0,0,0.1)'; element.style.color = '#fff'; element.style.font = 'normal 13px sans-serif'; element.style.textAlign = 'center'; element.style.opacity = '0.5'; element.style.outline = 'none'; element.style.zIndex = '999'; } if ('xr' in navigator) { button.id = 'ARButton'; button.style.display = 'none'; stylizeElement(button); navigator.xr.isSessionSupported('immersive-ar').then(function (supported) { supported ? showStartAR() : showARNotSupported(); }).catch(showARNotAllowed); return button; } else { var message = document.createElement('a'); if (window.isSecureContext === false) { message.href = document.location.href.replace(/^http:/, 'https:'); message.innerHTML = 'WEBXR NEEDS HTTPS'; // TODO Improve message } else { message.href = 'https://immersiveweb.dev/'; message.innerHTML = 'WEBXR NOT AVAILABLE'; } message.style.left = 'calc(50% - 90px)'; message.style.width = '180px'; message.style.textDecoration = 'none'; stylizeElement(message); return message; } } } var RenderMode = { Always: 0, OnChange: 1, Never: 2 }; var THREE_CAMERA_FOV = 50; var MINIMUM_DISTANCE_TO_NEW_FOCAL_POINT = .75; var MIN_SPLAT_COUNT_TO_SHOW_SPLAT_TREE_LOADING_SPINNER = 1500000; var FOCUS_MARKER_FADE_IN_SPEED = 10.0; var FOCUS_MARKER_FADE_OUT_SPEED = 2.5; var CONSECUTIVE_RENDERED_FRAMES_FOR_FPS_CALCULATION = 60; /** * Viewer: Manages the rendering of splat scenes. Manages an instance of SplatMesh as well as a web worker * that performs the sort for its splats. */ class Viewer { constructor() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _defineProperty(this, "onKeyDown", function () { var forward = new Vector3(); var tempMatrixLeft = new Matrix4(); var tempMatrixRight = new Matrix4(); return function (e) { forward.set(0, 0, -1); forward.transformDirection(this.camera.matrixWorld); tempMatrixLeft.makeRotationAxis(forward, Math.PI / 128); tempMatrixRight.makeRotationAxis(forward, -Math.PI / 128); switch (e.code) { case 'KeyG': this.focalAdjustment += 0.02; this.forceRenderNextFrame(); break; case 'KeyF': this.focalAdjustment -= 0.02; this.forceRenderNextFrame(); break; case 'ArrowLeft': this.camera.up.transformDirection(tempMatrixLeft); break; case 'ArrowRight': this.camera.up.transformDirection(tempMatrixRight); break; case 'KeyC': this.showMeshCursor = !this.showMeshCursor; break; case 'KeyU': this.showControlPlane = !this.showControlPlane; break; case 'KeyI': this.showInfo = !this.showInfo; if (this.showInfo) { this.infoPanel.show(); } else { this.infoPanel.hide(); } break; case 'KeyO': if (!this.usingExternalCamera) { this.setOrthographicMode(!this.camera.isOrthographicCamera); } break; case 'KeyP': if (!this.usingExternalCamera) { this.splatMesh.setPointCloudModeEnabled(!this.splatMesh.getPointCloudModeEnabled()); } break; case 'Equal': if (!this.usingExternalCamera) { this.splatMesh.setSplatScale(this.splatMesh.getSplatScale() + 0.05); } break; case 'Minus': if (!this.usingExternalCamera) { this.splatMesh.setSplatScale(Math.max(this.splatMesh.getSplatScale() - 0.05, 0.0)); } break; } }; }()); _defineProperty(this, "onMouseUp", function () { var clickOffset = new Vector2(); return function (mouse) { clickOffset.copy(this.mousePosition).sub(this.mouseDownPosition); var mouseUpTime = getCurrentTime(); var wasClick = mouseUpTime - this.mouseDownTime < 0.5 && clickOffset.length() < 2; if (wasClick) { this.onMouseClick(mouse); } }; }()); _defineProperty(this, "checkForFocalPointChange", function () { var renderDimensions = new Vector2(); var toNewFocalPoint = new Vector3(); var outHits = []; return function () { if (!this.transitioningCameraTarget) { this.getRenderDimensions(renderDimensions); outHits.length = 0; this.raycaster.setFromCameraAndScreenPosition(this.camera, this.mousePosition, renderDimensions); this.raycaster.intersectSplatMesh(this.splatMesh, outHits); if (outHits.length > 0) { var hit = outHits[0]; var intersectionPoint = hit.origin; toNewFocalPoint.copy(intersectionPoint).sub(this.camera.position); if (toNewFocalPoint.length() > MINIMUM_DISTANCE_TO_NEW_FOCAL_POINT) { this.previousCameraTarget.copy(this.controls.target); this.nextCameraTarget.copy(intersectionPoint); this.transitioningCameraTarget = true; this.transitioningCameraTargetStartTime = getCurrentTime(); } } } }; }()); _defineProperty(this, "updateSplatMesh", function () { var renderDimensions = new Vector2(); return function () { if (!this.splatMesh) return; var splatCount = this.splatMesh.getSplatCount(); if (splatCount > 0) { this.splatMesh.updateTransforms(); this.getRenderDimensions(renderDimensions); var focalLengthX = this.camera.projectionMatrix.elements[0] * 0.5 * this.devicePixelRatio * renderDimensions.x; var focalLengthY = this.camera.projectionMatrix.elements[5] * 0.5 * this.devicePixelRatio * renderDimensions.y; //this.camera.projectionMatrix.elements[0] 等效于 (2 * n) / (r - l),其中n是焦距(到近裁剪面的距离)。当它乘以0.5,然后再乘以renderDimensions.x(即视口宽度)时,你得到的是 (n * 宽度) / (r - l)。由于r - l等于宽度,最终就只剩下了n,即焦距。对于cameraFocalLengthY的计算应该得出相同的结果,所以实际上我只需要向updateUniforms()函数传递一个单独的焦距值即可。(see:https://github.com/mkkellogg/GaussianSplats3D/issues/108) var focalMultiplier = this.camera.isOrthographicCamera ? 1.0 / this.devicePixelRatio : 1.0; var focalAdjustment = this.focalAdjustment * focalMultiplier; var inverseFocalAdjustment = 1.0 / focalAdjustment; this.adjustForWebXRStereo(renderDimensions); this.splatMesh.updateUniforms(renderDimensions, focalLengthX * focalAdjustment, focalLengthY * focalAdjustment, this.camera.isOrthographicCamera, this.camera.zoom || 1.0, inverseFocalAdjustment); } }; }()); /** * Add one or more instances of SplatBuffer to the SplatMesh instance managed by the viewer and set up the sorting web worker. * This function will terminate the existing sort worker (if there is one). */ _defineProperty(this, "addSplatBuffers", function () { return function (splatBuffers) { var splatBufferOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var finalBuild = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var showLoadingUI = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; var showLoadingUIForSplatTreeBuild = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true; if (this.isDisposingOrDisposed()) return Promise.resolve(); this.splatRenderReady = false; var splatProcessingTaskId = null; var finish = buildResults => { if (this.isDisposingOrDisposed()) return; if (splatProcessingTaskId !== null) { this.loadingSpinner.removeTask(splatProcessingTaskId); splatProcessingTaskId = null; } // If we aren't calculating the splat distances from the center on the GPU, the sorting worker needs splat centers and // transform indexes so that it can calculate those distance values. if (!this.gpuAcceleratedSort && this.sortWorker) { this.sortWorker.postMessage({ 'centers': buildResults.centers.buffer, 'transformIndexes': buildResults.sceneIndexes.buffer, 'range': { 'from': buildResults.from, 'to': buildResults.to, 'count': buildResults.count } }); } this.splatRenderReady = true; this.sortNeededForSceneChange = true; }; return new Promise(resolve => { if (showLoadingUI) { splatProcessingTaskId = this.loadingSpinner.addTask('Processing splats...'); } delayedExecute(() => { if (this.isDisposingOrDisposed()) { resolve(); } else { var buildResults = this.addSplatBuffersToMesh(splatBuffers, splatBufferOptions, finalBuild, showLoadingUIForSplatTreeBuild); var maxSplatCount = this.splatMesh.getMaxSplatCount(); if (this.sortWorker && this.sortWorker.maxSplatCount !== maxSplatCount) this.disposeSortWorker(); var sortWorkerSetupPromise = !this.sortWorker && maxSplatCount > 0 ? this.setupSortWorker(this.splatMesh) : Promise.resolve(); sortWorkerSetupPromise.then(() => { finish(buildResults); resolve(); }); } }, true); }); }; }()); _defineProperty(this, "shouldRender", function () { var renderCount = 0; var lastCameraPosition = new Vector3(); var lastCameraOrientation = new Quaternion(); var changeEpsilon = 0.0001; return function () { var shouldRender = false; var cameraChanged = false; if (this.camera) { var cp = this.camera.position; var co = this.camera.quaternion; cameraChanged = Math.abs(cp.x - lastCameraPosition.x) > changeEpsilon || Math.abs(cp.y - lastCameraPosition.y) > changeEpsilon || Math.abs(cp.z - lastCameraPosition.z) > changeEpsilon || Math.abs(co.x - lastCameraOrientation.x) > changeEpsilon || Math.abs(co.y - lastCameraOrientation.y) > changeEpsilon || Math.abs(co.z - lastCameraOrientation.z) > changeEpsilon || Math.abs(co.w - lastCameraOrientation.w) > changeEpsilon; } shouldRender = this.renderMode !== RenderMode.Never && (renderCount === 0 || this.splatMesh.visibleRegionChanging || cameraChanged || this.renderMode === RenderMode.Always || this.dynamicMode === true || this.renderNextFrame); if (this.camera) { lastCameraPosition.copy(this.camera.position); lastCameraOrientation.copy(this.camera.quaternion); } renderCount++; return shouldRender; }; }()); _defineProperty(this, "render", function () { return function () { if (!this.initialized || !this.splatRenderReady) return; var hasRenderables = threeScene => { for (var child of threeScene.children) { if (child.visible) return true; } return false; }; var oldLayer = this.camera.layers.mask; this.camera.layers.set(0); //xzw add var savedAuoClear = this.renderer.autoClear; /* if (hasRenderables(this.threeScene)) {//xzw this.renderer.render(this.threeScene, this.camera); this.renderer.autoClear = false; } */ this.renderer.render(this.splatMesh, this.camera); this.renderer.autoClear = false; if (this.sceneHelper.getFocusMarkerOpacity() > 0.0) this.renderer.render(this.sceneHelper.focusMarker, this.camera); if (this.showControlPlane) this.renderer.render(this.sceneHelper.controlPlane, this.camera); this.renderer.autoClear = savedAuoClear; this.camera.layers.mask = oldLayer; }; }()); _defineProperty(this, "updateFPS", function () { var lastCalcTime = getCurrentTime(); var frameCount = 0; return function () { if (this.consecutiveRenderFrames > CONSECUTIVE_RENDERED_FRAMES_FOR_FPS_CALCULATION) { var currentTime = getCurrentTime(); var calcDelta = currentTime - lastCalcTime; if (calcDelta >= 1.0) { this.currentFPS = frameCount; frameCount = 0; lastCalcTime = currentTime; } else { frameCount++; } } else { this.currentFPS = null; } }; }()); _defineProperty(this, "updateForRendererSizeChanges", function () { var lastRendererSize = new Vector2(); var currentRendererSize = new Vector2(); var lastCameraOrthographic; return function () { if (!this.usingExternalCamera) { this.renderer.getSize(currentRendererSize); if (lastCameraOrthographic === undefined || lastCameraOrthographic !== this.camera.isOrthographicCamera || currentRendererSize.x !== lastRendererSize.x || currentRendererSize.y !== lastRendererSize.y) { if (this.camera.isOrthographicCamera) { this.camera.left = -currentRendererSize.x / 2.0; this.camera.right = currentRendererSize.x / 2.0; this.camera.top = currentRendererSize.y / 2.0; this.camera.bottom = -currentRendererSize.y / 2.0; } else { this.camera.aspect = currentRendererSize.x / currentRendererSize.y; } this.camera.updateProjectionMatrix(); lastRendererSize.copy(currentRendererSize); lastCameraOrthographic = this.camera.isOrthographicCamera; } } }; }()); _defineProperty(this, "timingSensitiveUpdates", function () { var lastUpdateTime; return function () { var currentTime = getCurrentTime(); if (!lastUpdateTime) lastUpdateTime = currentTime; var timeDelta = currentTime - lastUpdateTime; this.updateCameraTransition(currentTime); this.updateFocusMarker(timeDelta); lastUpdateTime = currentTime; }; }()); _defineProperty(this, "updateCameraTransition", function () { var tempCameraTarget = new Vector3(); var toPreviousTarget = new Vector3(); var toNextTarget = new Vector3(); return function (currentTime) { if (this.transitioningCameraTarget) { toPreviousTarget.copy(this.previousCameraTarget).sub(this.camera.position).normalize(); toNextTarget.copy(this.nextCameraTarget).sub(this.camera.position).normalize(); var rotationAngle = Math.acos(toPreviousTarget.dot(toNextTarget)); var rotationSpeed = rotationAngle / (Math.PI / 3) * .65 + .3; var t = rotationSpeed / rotationAngle * (currentTime - this.transitioningCameraTargetStartTime); tempCameraTarget.copy(this.previousCameraTarget).lerp(this.nextCameraTarget, t); this.camera.lookAt(tempCameraTarget); this.controls.target.copy(tempCameraTarget); if (t >= 1.0) { this.transitioningCameraTarget = false; } } }; }()); _defineProperty(this, "updateFocusMarker", function () { var renderDimensions = new Vector2(); var wasTransitioning = false; return function (timeDelta) { this.getRenderDimensions(renderDimensions); if (this.transitioningCameraTarget) { this.sceneHelper.setFocusMarkerVisibility(true); var currentFocusMarkerOpacity = Math.max(this.sceneHelper.getFocusMarkerOpacity(), 0.0); var newFocusMarkerOpacity = Math.min(currentFocusMarkerOpacity + FOCUS_MARKER_FADE_IN_SPEED * timeDelta, 1.0); this.sceneHelper.setFocusMarkerOpacity(newFocusMarkerOpacity); this.sceneHelper.updateFocusMarker(this.nextCameraTarget, this.camera, renderDimensions); wasTransitioning = true; this.forceRenderNextFrame(); } else { var _currentFocusMarkerOpacity; if (wasTransitioning) _currentFocusMarkerOpacity = 1.0;else _currentFocusMarkerOpacity = Math.min(this.sceneHelper.getFocusMarkerOpacity(), 1.0); if (_currentFocusMarkerOpacity > 0) { this.sceneHelper.updateFocusMarker(this.nextCameraTarget, this.camera, renderDimensions); var _newFocusMarkerOpacity = Math.max(_currentFocusMarkerOpacity - FOCUS_MARKER_FADE_OUT_SPEED * timeDelta, 0.0); this.sceneHelper.setFocusMarkerOpacity(_newFocusMarkerOpacity); if (_newFocusMarkerOpacity === 0.0) this.sceneHelper.setFocusMarkerVisibility(false); } if (_currentFocusMarkerOpacity > 0.0) this.forceRenderNextFrame(); wasTransitioning = false; } }; }()); _defineProperty(this, "updateMeshCursor", function () { var outHits = []; var renderDimensions = new Vector2(); return function () { if (this.showMeshCursor) { this.forceRenderNextFrame(); this.getRenderDimensions(renderDimensions); outHits.length = 0; this.raycaster.setFromCameraAndScreenPosition(this.camera, this.mousePosition, renderDimensions); this.raycaster.intersectSplatMesh(this.splatMesh, outHits); if (outHits.length > 0) { this.sceneHelper.setMeshCursorVisibility(true); this.sceneHelper.positionAndOrientMeshCursor(outHits[0].origin, this.camera); } else { this.sceneHelper.setMeshCursorVisibility(false); } } else { if (this.sceneHelper.getMeschCursorVisibility()) this.forceRenderNextFrame(); this.sceneHelper.setMeshCursorVisibility(false); } }; }()); _defineProperty(this, "updateInfoPanel", function () { var renderDimensions = new Vector2(); return function () { if (!this.showInfo) return; var splatCount = this.splatMesh.getSplatCount(); this.getRenderDimensions(renderDimensions); var cameraLookAtPosition = this.controls ? this.controls.target : null; var meshCursorPosition = this.showMeshCursor ? this.sceneHelper.meshCursor.position : null; var splatRenderCountPct = splatCount > 0 ? this.splatRenderCount / splatCount * 100 : 0; this.infoPanel.update(renderDimensions, this.camera.position, cameraLookAtPosition, this.camera.up, this.camera.isOrthographicCamera, meshCursorPosition, this.currentFPS || 'N/A', splatCount, this.splatRenderCount, splatRenderCountPct, this.lastSortTime, this.focalAdjustment, this.splatMesh.getSplatScale(), this.splatMesh.getPointCloudModeEnabled()); }; }()); _defineProperty(this, "updateSplatSort", function () { var mvpMatrix = new Matrix4(); var cameraPositionArray = []; var lastSortViewDir = new Vector3(0, 0, -1); var sortViewDir = new Vector3(0, 0, -1); var lastSortViewPos = new Vector3(); var sortViewOffset = new Vector3(); var queuedSorts = []; var partialSorts = [{ 'angleThreshold': 0.55, 'sortFractions': [0.125, 0.33333, 0.75] }, { 'angleThreshold': 0.65, 'sortFractions': [0.33333, 0.66667] }, { 'angleThreshold': 0.8, 'sortFractions': [0.5] }]; return async function () { var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; if (this.sortRunning) return; if (this.splatMesh.getSplatCount() <= 0) return; var angleDiff = 0; var positionDiff = 0; var needsRefreshForRotation = false; var needsRefreshForPosition = false; sortViewDir.set(0, 0, -1).applyQuaternion(this.camera.quaternion); angleDiff = sortViewDir.dot(lastSortViewDir); positionDiff = sortViewOffset.copy(this.camera.position).sub(lastSortViewPos).length(); if (!force) { if (!this.sortNeededForSceneChange && !this.splatMesh.dynamicMode && queuedSorts.length === 0) { if (angleDiff <= 0.99) needsRefreshForRotation = true; if (positionDiff >= 1.0) needsRefreshForPosition = true; if (!needsRefreshForRotation && !needsRefreshForPosition) return; } } this.sortRunning = true; var { splatRenderCount, shouldSortAll } = this.gatherSceneNodesForSort(); this.splatRenderCount = splatRenderCount; mvpMatrix.copy(this.camera.matrixWorld).invert(); var mvpCamera = this.perspectiveCamera || this.camera; mvpMatrix.premultiply(mvpCamera.projectionMatrix); mvpMatrix.multiply(this.splatMesh.matrixWorld); if (this.gpuAcceleratedSort && (queuedSorts.length <= 1 || queuedSorts.length % 2 === 0)) { await this.splatMesh.computeDistancesOnGPU(mvpMatrix, this.sortWorkerPrecomputedDistances); } if (this.splatMesh.dynamicMode || shouldSortAll) { queuedSorts.push(this.splatRenderCount); } else { if (queuedSorts.length === 0) { for (var partialSort of partialSorts) { if (angleDiff < partialSort.angleThreshold) { for (var sortFraction of partialSort.sortFractions) { queuedSorts.push(Math.floor(this.splatRenderCount * sortFraction)); } break; } } queuedSorts.push(this.splatRenderCount); } } var sortCount = Math.min(queuedSorts.shift(), this.splatRenderCount); cameraPositionArray[0] = this.camera.position.x; cameraPositionArray[1] = this.camera.position.y; cameraPositionArray[2] = this.camera.position.z; var sortMessage = { 'modelViewProj': mvpMatrix.elements, 'cameraPosition': cameraPositionArray, 'splatRenderCount': this.splatRenderCount, 'splatSortCount': sortCount, 'usePrecomputedDistances': this.gpuAcceleratedSort }; if (this.splatMesh.dynamicMode) { this.splatMesh.fillTransformsArray(this.sortWorkerTransforms); } if (!this.sharedMemoryForWorkers) { sortMessage.indexesToSort = this.sortWorkerIndexesToSort; sortMessage.transforms = this.sortWorkerTransforms; if (this.gpuAcceleratedSort) { sortMessage.precomputedDistances = this.sortWorkerPrecomputedDistances; } } this.sortPromise = new Promise(resolve => { this.sortPromiseResolver = resolve; }); this.sortWorker.postMessage({ 'sort': sortMessage }); if (queuedSorts.length === 0) { lastSortViewPos.copy(this.camera.position); lastSortViewDir.copy(sortViewDir); } this.sortNeededForSceneChange = false; }; }()); /** * Determine which splats to render by checking which are inside or close to the view frustum */ _defineProperty(this, "gatherSceneNodesForSort", function () { var nodeRenderList = []; var allSplatsSortBuffer = null; var tempVectorYZ = new Vector3(); var tempVectorXZ = new Vector3(); var tempVector = new Vector3(); var modelView = new Matrix4(); var baseModelView = new Matrix4(); var sceneTransform = new Matrix4(); var renderDimensions = new Vector3(); var forward = new Vector3(0, 0, -1); var tempMax = new Vector3(); var nodeSize = node => { return tempMax.copy(node.max).sub(node.min).length(); }; return function () { var gatherAllNodes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; this.getRenderDimensions(renderDimensions); var cameraFocalLength = renderDimensions.y / 2.0 / Math.tan(this.camera.fov / 2.0 * MathUtils.DEG2RAD); var fovXOver2 = Math.atan(renderDimensions.x / 2.0 / cameraFocalLength); var fovYOver2 = Math.atan(renderDimensions.y / 2.0 / cameraFocalLength); var cosFovXOver2 = Math.cos(fovXOver2); var cosFovYOver2 = Math.cos(fovYOver2); var splatTree = this.splatMesh.getSplatTree(); if (splatTree) { baseModelView.copy(this.camera.matrixWorld).invert(); baseModelView.multiply(this.splatMesh.matrixWorld); var nodeRenderCount = 0; var splatRenderCount = 0; for (var s = 0; s < splatTree.subTrees.length; s++) { var subTree = splatTree.subTrees[s]; modelView.copy(baseModelView); if (this.splatMesh.dynamicMode) { this.splatMesh.getSceneTransform(s, sceneTransform); modelView.multiply(sceneTransform); } var nodeCount = subTree.nodesWithIndexes.length; for (var i = 0; i < nodeCount; i++) { var node = subTree.nodesWithIndexes[i]; if (!node.data || !node.data.indexes || node.data.indexes.length === 0) continue; tempVector.copy(node.center).applyMatrix4(modelView); var distanceToNode = tempVector.length(); tempVector.normalize(); tempVectorYZ.copy(tempVector).setX(0).normalize(); tempVectorXZ.copy(tempVector).setY(0).normalize(); var cameraAngleXZDot = forward.dot(tempVectorXZ); var cameraAngleYZDot = forward.dot(tempVectorYZ); var ns = nodeSize(node); var outOfFovY = cameraAngleYZDot < cosFovYOver2 - .6; //角度超出 var outOfFovX = cameraAngleXZDot < cosFovXOver2 - .6; if (!gatherAllNodes && (outOfFovX || outOfFovY) && distanceToNode > ns) { continue; } splatRenderCount += node.data.indexes.length; nodeRenderList[nodeRenderCount] = node; node.data.distanceToNode = distanceToNode; nodeRenderCount++; } } nodeRenderList.length = nodeRenderCount; nodeRenderList.sort((a, b) => { //从近到远排序。去掉后也不影响,毕竟之后还要sort index if (a.data.distanceToNode < b.data.distanceToNode) return -1;else return 1; }); //将要渲染的点的index写入sortWorkerIndexesToSort的buffer var currentByteOffset = splatRenderCount * Constants.BytesPerInt; for (var _i21 = 0; _i21 < nodeRenderCount; _i21++) { var _node = nodeRenderList[_i21]; var windowSizeInts = _node.data.indexes.length; var windowSizeBytes = windowSizeInts * Constants.BytesPerInt; var destView = new Uint32Array(this.sortWorkerIndexesToSort.buffer, //写入sortWorkerIndexesToSort currentByteOffset - windowSizeBytes, windowSizeInts); destView.set(_node.data.indexes); currentByteOffset -= windowSizeBytes; } return { 'splatRenderCount': splatRenderCount, 'shouldSortAll': false }; } else { var totalSplatCount = this.splatMesh.getSplatCount(); if (!allSplatsSortBuffer || allSplatsSortBuffer.length !== totalSplatCount) { allSplatsSortBuffer = new Uint32Array(totalSplatCount); for (var _i22 = 0; _i22 < totalSplatCount; _i22++) { allSplatsSortBuffer[_i22] = _i22; } } this.sortWorkerIndexesToSort.set(allSplatsSortBuffer); return { 'splatRenderCount': totalSplatCount, 'shouldSortAll': true }; } }; }()); // The natural 'up' vector for viewing the scene (only has an effect when used with orbit controls and // when the viewer uses its own camera). if (!options.cameraUp) options.cameraUp = [0, 1, 0]; this.cameraUp = new Vector3().fromArray(options.cameraUp); // The camera's initial position (only used when the viewer uses its own camera). if (!options.initialCameraPosition) options.initialCameraPosition = [0, 10, 15]; this.initialCameraPosition = new Vector3().fromArray(options.initialCameraPosition); // The initial focal point of the camera and center of the camera's orbit (only used when the viewer uses its own camera). if (!options.initialCameraLookAt) options.initialCameraLookAt = [0, 0, 0]; this.initialCameraLookAt = new Vector3().fromArray(options.initialCameraLookAt); // 'dropInMode' is a flag that is used internally to support the usage of the viewer as a Three.js scene object this.dropInMode = options.dropInMode || false; // If 'selfDrivenMode' is true, the viewer manages its own update/animation loop via requestAnimationFrame() if (options.selfDrivenMode === undefined || options.selfDrivenMode === null) options.selfDrivenMode = true; this.selfDrivenMode = options.selfDrivenMode && !this.dropInMode; this.selfDrivenUpdateFunc = this.selfDrivenUpdate.bind(this); // If 'useBuiltInControls' is true, the viewer will create its own instance of OrbitControls and attach to the camera if (options.useBuiltInControls === undefined) options.useBuiltInControls = true; this.useBuiltInControls = options.useBuiltInControls; // parent element of the Three.js renderer canvas this.rootElement = options.rootElement; // Tells the viewer to pretend the device pixel ratio is 1, which can boost performance on devices where it is larger, // at a small cost to visual quality this.ignoreDevicePixelRatio = options.ignoreDevicePixelRatio || false; this.devicePixelRatio = this.ignoreDevicePixelRatio ? 1 : window.devicePixelRatio; // Tells the viewer to use 16-bit floating point values when storing splat covariance data in textures, instead of 32-bit this.halfPrecisionCovariancesOnGPU = options.halfPrecisionCovariancesOnGPU || false; // If 'threeScene' is valid, it will be rendered by the viewer along with the splat mesh this.threeScene = options.threeScene; // Allows for usage of an external Three.js renderer this.renderer = options.renderer; // Allows for usage of an external Three.js camera this.camera = options.camera; // If 'gpuAcceleratedSort' is true, a partially GPU-accelerated approach to sorting splats will be used. // Currently this means pre-computing splat distances from the camera on the GPU this.gpuAcceleratedSort = options.gpuAcceleratedSort || false; // if 'integerBasedSort' is true, the integer version of splat centers as well as other values used to calculate // splat distances are used instead of the float version. This speeds up computation, but introduces the possibility of // overflow in larger scenes. if (options.integerBasedSort === undefined || options.integerBasedSort === null) { options.integerBasedSort = true; } this.integerBasedSort = options.integerBasedSort; // If 'sharedMemoryForWorkers' is true, a SharedArrayBuffer will be used to communicate with web workers. This method // is faster than copying memory to or from web workers, but comes with security implications as outlined here: // https://web.dev/articles/cross-origin-isolation-guide // If enabled, it requires specific CORS headers to be present in the response from the server that is sent when // loading the application. More information is available in the README. if (options.sharedMemoryForWorkers === undefined || options.sharedMemoryForWorkers === null) options.sharedMemoryForWorkers = true; this.sharedMemoryForWorkers = options.sharedMemoryForWorkers; // if 'dynamicScene' is true, it tells the viewer to assume scene elements are not stationary or that the number of splats in the // scene may change. This prevents optimizations that depend on a static scene from being made. Additionally, if 'dynamicScene' is // true it tells the splat mesh to not apply scene tranforms to splat data that is returned by functions like // SplatMesh.getSplatCenter() by default. this.dynamicScene = !!options.dynamicScene; // When true, will perform additional steps during rendering to address artifacts caused by the rendering of gaussians at a // substantially different resolution than that at which they were rendered during training. This will only work correctly // for models that were trained using a process that utilizes this compensation calculation. For more details: // https://github.com/nerfstudio-project/gsplat/pull/117 // https://github.com/graphdeco-inria/gaussian-splatting/issues/294#issuecomment-1772688093 this.antialiased = options.antialiased || false; this.webXRMode = options.webXRMode || WebXRMode.None; if (this.webXRMode !== WebXRMode.None) { this.gpuAcceleratedSort = false; } this.webXRActive = false; // if 'renderMode' is RenderMode.Always, then the viewer will rrender the scene on every update. If it is RenderMode.OnChange, // it will only render when something in the scene has changed. this.renderMode = options.renderMode || RenderMode.Always; // SceneRevealMode.Default results in a nice, slow fade-in effect for progressively loaded scenes, // and a fast fade-in for non progressively loaded scenes. // SceneRevealMode.Gradual will force a slow fade-in for all scenes. // SceneRevealMode.Instant will force all loaded scene data to be immediately visible. this.sceneRevealMode = options.sceneRevealMode || SceneRevealMode.Default; // Hacky, experimental, non-scientific parameter for tweaking focal length related calculations. For scenes with very // small gaussians, small details, and small dimensions -- increasing this value can help improve visual quality. this.focalAdjustment = options.focalAdjustment || 1.0; // Specify the maximum screen-space splat size, can help deal with large splats that get too unwieldy this.maxScreenSpaceSplatSize = options.maxScreenSpaceSplatSize || 2048; // The verbosity of console logging this.logLevel = options.logLevel || LogLevel.None; // Degree of spherical harmonics to utilize in rendering splats (assuming the data is present in the splat scene). // Valid values are 0 - 3. Default value is 0. this.sphericalHarmonicsDegree = options.sphericalHarmonicsDegree || 0; this.createSplatMesh(); this.controls = null; this.perspectiveControls = null; this.orthographicControls = null; this.orthographicCamera = null; this.perspectiveCamera = null; this.showMeshCursor = false; this.showControlPlane = false; this.showInfo = false; this.sceneHelper = null; this.sortWorker = null; this.sortRunning = false; this.splatRenderCount = 0; this.sortWorkerIndexesToSort = null; this.sortWorkerSortedIndexes = null; this.sortWorkerPrecomputedDistances = null; this.sortWorkerTransforms = null; this.runAfterFirstSort = []; this.selfDrivenModeRunning = false; this.splatRenderReady = false; this.raycaster = new Raycaster$1(); this.infoPanel = null; this.startInOrthographicMode = false; this.currentFPS = 0; this.lastSortTime = 0; this.consecutiveRenderFrames = 0; this.previousCameraTarget = new Vector3(); this.nextCameraTarget = new Vector3(); this.mousePosition = new Vector2(); this.mouseDownPosition = new Vector2(); this.mouseDownTime = null; this.resizeObserver = null; this.mouseMoveListener = null; this.mouseDownListener = null; this.mouseUpListener = null; this.keyDownListener = null; this.sortPromise = null; this.sortPromiseResolver = null; this.splatSceneDownloadPromises = {}; this.splatSceneDownloadAndBuildPromise = null; this.splatSceneRemovalPromise = null; this.loadingSpinner = new LoadingSpinner(null, this.rootElement || document.body); this.loadingSpinner.hide(); this.loadingProgressBar = new LoadingProgressBar(this.rootElement || document.body); this.loadingProgressBar.hide(); this.infoPanel = new InfoPanel(this.rootElement || document.body); this.infoPanel.hide(); this.usingExternalCamera = this.dropInMode || this.camera ? true : false; this.usingExternalRenderer = this.dropInMode || this.renderer ? true : false; this.initialized = false; this.disposing = false; this.disposed = false; if (!this.dropInMode) this.init(); } createSplatMesh() { this.splatMesh = new SplatMesh(this.dynamicScene, this.halfPrecisionCovariancesOnGPU, this.devicePixelRatio, this.gpuAcceleratedSort, this.integerBasedSort, this.antialiased, this.maxScreenSpaceSplatSize, this.logLevel, this.sphericalHarmonicsDegree); this.splatMesh.frustumCulled = false; } init() { if (this.initialized) return; if (!this.rootElement) { if (!this.usingExternalRenderer) { this.rootElement = document.createElement('div'); this.rootElement.style.width = '100%'; this.rootElement.style.height = '100%'; this.rootElement.style.position = 'absolute'; document.body.appendChild(this.rootElement); } else { this.rootElement = this.renderer.domElement.parentElement || document.body; } } this.setupCamera(); this.setupRenderer(); this.setupWebXR(); this.setupControls(); this.setupEventHandlers(); this.threeScene = this.threeScene || new Scene(); this.sceneHelper = new SceneHelper(this.threeScene); this.sceneHelper.setupMeshCursor(); this.sceneHelper.setupFocusMarker(); this.sceneHelper.setupControlPlane(); this.loadingProgressBar.setContainer(this.rootElement); this.loadingSpinner.setContainer(this.rootElement); this.infoPanel.setContainer(this.rootElement); this.initialized = true; } setupCamera() { if (!this.usingExternalCamera) { var renderDimensions = new Vector2(); this.getRenderDimensions(renderDimensions); this.perspectiveCamera = new PerspectiveCamera(THREE_CAMERA_FOV, renderDimensions.x / renderDimensions.y, 0.1, 1000); this.orthographicCamera = new OrthographicCamera(renderDimensions.x / -2, renderDimensions.x / 2, renderDimensions.y / 2, renderDimensions.y / -2, 0.1, 1000); this.camera = this.startInOrthographicMode ? this.orthographicCamera : this.perspectiveCamera; this.camera.position.copy(this.initialCameraPosition); this.camera.up.copy(this.cameraUp).normalize(); this.camera.lookAt(this.initialCameraLookAt); } } setupRenderer() { if (!this.usingExternalRenderer) { var renderDimensions = new Vector2(); this.getRenderDimensions(renderDimensions); this.renderer = new WebGLRenderer({ antialias: false, precision: 'highp' }); this.renderer.setPixelRatio(this.devicePixelRatio); this.renderer.autoClear = true; this.renderer.setClearColor(new Color(0x000000), 0.0); this.renderer.setSize(renderDimensions.x, renderDimensions.y); this.resizeObserver = new ResizeObserver(() => { this.getRenderDimensions(renderDimensions); this.renderer.setSize(renderDimensions.x, renderDimensions.y); this.forceRenderNextFrame(); }); this.resizeObserver.observe(this.rootElement); this.rootElement.appendChild(this.renderer.domElement); } } setupWebXR() { if (this.webXRMode) { if (this.webXRMode === WebXRMode.VR) { this.rootElement.appendChild(VRButton.createButton(this.renderer)); } else if (this.webXRMode === WebXRMode.AR) { this.rootElement.appendChild(ARButton.createButton(this.renderer)); } this.renderer.xr.addEventListener('sessionstart', e => { this.webXRActive = true; }); this.renderer.xr.addEventListener('sessionend', e => { this.webXRActive = false; }); this.renderer.xr.enabled = true; this.camera.position.copy(this.initialCameraPosition); this.camera.up.copy(this.cameraUp).normalize(); this.camera.lookAt(this.initialCameraLookAt); } } setupControls() { if (this.useBuiltInControls && this.webXRMode === WebXRMode.None) { if (!this.usingExternalCamera) { this.perspectiveControls = new OrbitControls(this.perspectiveCamera, this.renderer.domElement); this.orthographicControls = new OrbitControls(this.orthographicCamera, this.renderer.domElement); } else { if (this.camera.isOrthographicCamera) { this.orthographicControls = new OrbitControls(this.camera, this.renderer.domElement); } else { this.perspectiveControls = new OrbitControls(this.camera, this.renderer.domElement); } } for (var controls of [this.perspectiveControls, this.orthographicControls]) { if (controls) { controls.listenToKeyEvents(window); controls.rotateSpeed = 0.5; controls.maxPolarAngle = Math.PI * .75; controls.minPolarAngle = 0.1; controls.enableDamping = true; controls.dampingFactor = 0.05; controls.target.copy(this.initialCameraLookAt); } } this.controls = this.camera.isOrthographicCamera ? this.orthographicControls : this.perspectiveControls; } } setupEventHandlers() { if (this.useBuiltInControls && this.webXRMode === WebXRMode.None) { this.mouseMoveListener = this.onMouseMove.bind(this); this.renderer.domElement.addEventListener('pointermove', this.mouseMoveListener, false); this.mouseDownListener = this.onMouseDown.bind(this); this.renderer.domElement.addEventListener('pointerdown', this.mouseDownListener, false); this.mouseUpListener = this.onMouseUp.bind(this); this.renderer.domElement.addEventListener('pointerup', this.mouseUpListener, false); this.keyDownListener = this.onKeyDown.bind(this); window.addEventListener('keydown', this.keyDownListener, false); } } removeEventHandlers() { if (this.useBuiltInControls) { this.renderer.domElement.removeEventListener('pointermove', this.mouseMoveListener); this.mouseMoveListener = null; this.renderer.domElement.removeEventListener('pointerdown', this.mouseDownListener); this.mouseDownListener = null; this.renderer.domElement.removeEventListener('pointerup', this.mouseUpListener); this.mouseUpListener = null; window.removeEventListener('keydown', this.keyDownListener); this.keyDownListener = null; } } setRenderMode(renderMode) { this.renderMode = renderMode; } onMouseMove(mouse) { this.mousePosition.set(mouse.offsetX, mouse.offsetY); } onMouseDown() { this.mouseDownPosition.copy(this.mousePosition); this.mouseDownTime = getCurrentTime(); } onMouseClick(mouse) { this.mousePosition.set(mouse.offsetX, mouse.offsetY); this.checkForFocalPointChange(); } getRenderDimensions(outDimensions) { if (this.rootElement) { outDimensions.x = this.rootElement.offsetWidth; outDimensions.y = this.rootElement.offsetHeight; } else { this.renderer.getSize(outDimensions); } } setOrthographicMode(orthographicMode) { if (orthographicMode === this.camera.isOrthographicCamera) return; var fromCamera = this.camera; var toCamera = orthographicMode ? this.orthographicCamera : this.perspectiveCamera; toCamera.position.copy(fromCamera.position); toCamera.up.copy(fromCamera.up); toCamera.rotation.copy(fromCamera.rotation); toCamera.quaternion.copy(fromCamera.quaternion); toCamera.matrix.copy(fromCamera.matrix); this.camera = toCamera; if (this.controls) { var resetControls = controls => { controls.saveState(); controls.reset(); }; var fromControls = this.controls; var toControls = orthographicMode ? this.orthographicControls : this.perspectiveControls; resetControls(toControls); resetControls(fromControls); toControls.target.copy(fromControls.target); if (orthographicMode) { Viewer.setCameraZoomFromPosition(toCamera, fromCamera, fromControls); } else { Viewer.setCameraPositionFromZoom(toCamera, fromCamera, toControls); } this.controls = toControls; this.camera.lookAt(this.controls.target); } } adjustForWebXRStereo(renderDimensions) { // TODO: Figure out a less hacky way to determine if stereo rendering is active if (this.camera && this.webXRActive) { var xrCamera = this.renderer.xr.getCamera(); var xrCameraProj00 = xrCamera.projectionMatrix.elements[0]; var cameraProj00 = this.camera.projectionMatrix.elements[0]; renderDimensions.x *= cameraProj00 / xrCameraProj00; } } isLoadingOrUnloading() { return Object.keys(this.splatSceneDownloadPromises).length > 0 || this.splatSceneDownloadAndBuildPromise !== null || this.splatSceneRemovalPromise !== null; } isDisposingOrDisposed() { return this.disposing || this.disposed; } addSplatSceneDownloadPromise(promise) { this.splatSceneDownloadPromises[promise.id] = promise; } removeSplatSceneDownloadPromise(promise) { delete this.splatSceneDownloadPromises[promise.id]; } setSplatSceneDownloadAndBuildPromise(promise) { this.splatSceneDownloadAndBuildPromise = promise; } clearSplatSceneDownloadAndBuildPromise() { this.splatSceneDownloadAndBuildPromise = null; } /** * Add a splat scene to the viewer and display any loading UI if appropriate. * @param {string} path Path to splat scene to be loaded * @param {object} options { * * splatAlphaRemovalThreshold: Ignore any splats with an alpha less than the specified * value (valid range: 0 - 255), defaults to 1 * * showLoadingUI: Display a loading spinner while the scene is loading, defaults to true * * position (Array): Position of the scene, acts as an offset from its default position, defaults to [0, 0, 0] * * rotation (Array): Rotation of the scene represented as a quaternion, defaults to [0, 0, 0, 1] * * scale (Array): Scene's scale, defaults to [1, 1, 1] * * onProgress: Function to be called as file data are received, or other processing occurs * * } * @return {AbortablePromise} */ addSplatScene(path) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (this.isLoadingOrUnloading()) { throw new Error('Cannot add splat scene while another load or unload is already in progress.'); } if (this.isDisposingOrDisposed()) { throw new Error('Cannot add splat scene after dispose() is called.'); } var format = options.format !== undefined && options.format !== null ? options.format : sceneFormatFromPath(path); var streamBuildSections = Viewer.isStreamable(format) && options.streamView; var showLoadingUI = options.showLoadingUI !== undefined && options.showLoadingUI !== null ? options.showLoadingUI : true; var loadingUITaskId = null; if (showLoadingUI) { this.loadingSpinner.removeAllTasks(); loadingUITaskId = this.loadingSpinner.addTask('Downloading...'); } var hideLoadingUI = () => { this.loadingProgressBar.hide(); this.loadingSpinner.removeAllTasks(); }; var onProgressUIUpdate = (percentComplete, percentCompleteLabel, loaderStatus) => { if (showLoadingUI) { if (loaderStatus === LoaderStatus.Downloading) { if (percentComplete == 100) { this.loadingSpinner.setMessageForTask(loadingUITaskId, 'Download complete!'); } else { if (streamBuildSections) { this.loadingSpinner.setMessageForTask(loadingUITaskId, 'Downloading splats...'); } else { var suffix = percentCompleteLabel ? ": ".concat(percentCompleteLabel) : "..."; this.loadingSpinner.setMessageForTask(loadingUITaskId, "Downloading".concat(suffix)); } } } else if (loaderStatus === LoaderStatus.Processing) { this.loadingSpinner.setMessageForTask(loadingUITaskId, 'Processing splats...'); } else { this.loadingSpinner.setMessageForTask(loadingUITaskId, 'Ready!'); } } }; var downloadDone = false; var downloadedPercentage = 0; var splatBuffersAddedUIUpdate = (firstBuild, finalBuild) => { if (showLoadingUI) { if (firstBuild && streamBuildSections || finalBuild && !streamBuildSections) { this.runAfterFirstSort.push(() => { this.loadingSpinner.removeTask(loadingUITaskId); if (!finalBuild && !downloadDone) this.loadingProgressBar.show(); }); } if (streamBuildSections) { if (finalBuild) { downloadDone = true; this.loadingProgressBar.hide(); } else { this.loadingProgressBar.setProgress(downloadedPercentage); } } } }; var onProgress = (percentComplete, percentCompleteLabel, loaderStatus) => { downloadedPercentage = percentComplete; onProgressUIUpdate(percentComplete, percentCompleteLabel, loaderStatus); if (options.onProgress) options.onProgress(percentComplete, percentCompleteLabel, loaderStatus); }; var buildSection = (splatBuffer, firstBuild, finalBuild) => { if (!streamBuildSections && options.onProgress) options.onProgress(0, '0%', LoaderStatus.Processing); var addSplatBufferOptions = { 'rotation': options.rotation || options.orientation, 'position': options.position, 'scale': options.scale, 'splatAlphaRemovalThreshold': options.splatAlphaRemovalThreshold }; return this.addSplatBuffers([splatBuffer], [addSplatBufferOptions], finalBuild, firstBuild && showLoadingUI, showLoadingUI).then(() => { if (!streamBuildSections && options.onProgress) options.onProgress(100, '100%', LoaderStatus.Processing); splatBuffersAddedUIUpdate(firstBuild, finalBuild); }); }; var loadFunc = streamBuildSections ? this.downloadAndBuildSingleSplatSceneStreaming.bind(this) : this.downloadAndBuildSingleSplatSceneNonStreaming.bind(this); return loadFunc(path, format, options.splatAlphaRemovalThreshold, buildSection.bind(this), onProgress, hideLoadingUI.bind(this)); } /** * Download a single non-streamed splat scene, convert to splat buffer and then rebuild the viewer's splat mesh * by calling 'buildFunc'. Also sets/clears relevant instance synchronization objects, and calls appropriate functions * on success or failure. * @param {string} path Path to splat scene to be loaded * @param {SceneFormat} format Format of the splat scene file * @param {number} splatAlphaRemovalThreshold Ignore any splats with an alpha less than the specified value (valid range: 0 - 255) * @param {function} buildFunc Function to build the viewer's splat mesh with the downloaded splat buffer * @param {function} onProgress Function to be called as file data are received, or other processing occurs * @param {function} onException Function to be called when exception occurs * @return {AbortablePromise} */ downloadAndBuildSingleSplatSceneNonStreaming(path, format, splatAlphaRemovalThreshold, buildFunc, onProgress, onException) { var downloadPromise = this.downloadSplatSceneToSplatBuffer(path, splatAlphaRemovalThreshold, onProgress, false, undefined, format).then(splatBuffer => { this.removeSplatSceneDownloadPromise(downloadPromise); return buildFunc(splatBuffer, true, true).then(() => { this.clearSplatSceneDownloadAndBuildPromise(); }); }).catch(e => { if (onException) onException(); this.clearSplatSceneDownloadAndBuildPromise(); this.removeSplatSceneDownloadPromise(downloadPromise); if (!(e instanceof AbortedPromiseError)) { throw new Error("Viewer::addSplatScene -> Could not load file ".concat(path)); } }); this.addSplatSceneDownloadPromise(downloadPromise); this.setSplatSceneDownloadAndBuildPromise(downloadPromise); return downloadPromise; } /** * Download a single splat scene and convert to splat buffer in a streamed manner, allowing rendering as the file downloads. * As each section is downloaded, the viewer's splat mesh is rebuilt by calling 'buildFunc' * Also sets/clears relevant instance synchronization objects, and calls appropriate functions on success or failure. * @param {string} path Path to splat scene to be loaded * @param {SceneFormat} format Format of the splat scene file * @param {number} splatAlphaRemovalThreshold Ignore any splats with an alpha less than the specified value (valid range: 0 - 255) * @param {function} buildFunc Function to rebuild the viewer's splat mesh after a new splat buffer section is downloaded * @param {function} onDownloadProgress Function to be called as file data are received * @param {function} onDownloadException Function to be called when exception occurs at any point during the full download * @return {AbortablePromise} */ downloadAndBuildSingleSplatSceneStreaming(path, format, splatAlphaRemovalThreshold, buildFunc, onDownloadProgress, onDownloadException) { var firstStreamedSectionDownloadAndBuildResolver; var firstStreamedSectionDownloadAndBuildRejecter; var splatSceneDownloadAndBuildResolver; var splatSceneDownloadAndBuildRejecter; var steamedSectionBuildCount = 0; var streamedSectionBuilding = false; var queuedStreamedSectionBuilds = []; var checkAndBuildStreamedSections = () => { if (queuedStreamedSectionBuilds.length > 0 && !streamedSectionBuilding && !this.isDisposingOrDisposed()) { streamedSectionBuilding = true; var queuedBuild = queuedStreamedSectionBuilds.shift(); buildFunc(queuedBuild.splatBuffer, queuedBuild.firstBuild, queuedBuild.finalBuild).then(() => { streamedSectionBuilding = false; if (queuedBuild.firstBuild) { firstStreamedSectionDownloadAndBuildRejecter = null; firstStreamedSectionDownloadAndBuildResolver(); } else if (queuedBuild.finalBuild) { splatSceneDownloadAndBuildResolver(); this.clearSplatSceneDownloadAndBuildPromise(); } if (queuedStreamedSectionBuilds.length > 0) delayedExecute(() => checkAndBuildStreamedSections()); }); } }; var onStreamedSectionProgress = (splatBuffer, finalBuild) => { if (!this.isDisposingOrDisposed()) { if (finalBuild || queuedStreamedSectionBuilds.length === 0 || splatBuffer.getSplatCount() > queuedStreamedSectionBuilds[0].splatBuffer.getSplatCount()) { queuedStreamedSectionBuilds.push({ splatBuffer, firstBuild: steamedSectionBuildCount === 0, finalBuild }); steamedSectionBuildCount++; checkAndBuildStreamedSections(); } } }; var splatSceneDownloadPromise = this.downloadSplatSceneToSplatBuffer(path, splatAlphaRemovalThreshold, onDownloadProgress, true, onStreamedSectionProgress, format); var firstStreamedSectionBuildPromise = new AbortablePromise((resolver, rejecter) => { firstStreamedSectionDownloadAndBuildResolver = resolver; firstStreamedSectionDownloadAndBuildRejecter = rejecter; }, splatSceneDownloadPromise.abortHandler); var splatSceneDownloadAndBuildPromise = new AbortablePromise((resolver, rejecter) => { splatSceneDownloadAndBuildResolver = resolver; splatSceneDownloadAndBuildRejecter = rejecter; }); this.addSplatSceneDownloadPromise(splatSceneDownloadPromise); this.setSplatSceneDownloadAndBuildPromise(splatSceneDownloadAndBuildPromise); splatSceneDownloadPromise.then(() => { this.removeSplatSceneDownloadPromise(splatSceneDownloadPromise); }).catch(e => { this.clearSplatSceneDownloadAndBuildPromise(); this.removeSplatSceneDownloadPromise(splatSceneDownloadPromise); if (!(e instanceof AbortedPromiseError)) { splatSceneDownloadAndBuildRejecter(e); if (firstStreamedSectionDownloadAndBuildRejecter) firstStreamedSectionDownloadAndBuildRejecter(e); if (onDownloadException) onDownloadException(e); } }); return firstStreamedSectionBuildPromise; } /** * Add multiple splat scenes to the viewer and display any loading UI if appropriate. * @param {Array} sceneOptions Array of per-scene options: { * * path: Path to splat scene to be loaded * * splatAlphaRemovalThreshold: Ignore any splats with an alpha less than the specified * value (valid range: 0 - 255), defaults to 1 * * position (Array): Position of the scene, acts as an offset from its default position, defaults to [0, 0, 0] * * rotation (Array): Rotation of the scene represented as a quaternion, defaults to [0, 0, 0, 1] * * scale (Array): Scene's scale, defaults to [1, 1, 1] * } * @param {boolean} showLoadingUI Display a loading spinner while the scene is loading, defaults to true * @param {function} onProgress Function to be called as file data are received * @return {AbortablePromise} */ addSplatScenes(sceneOptions) { var showLoadingUI = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var onProgress = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; if (this.isLoadingOrUnloading()) { throw new Error('Cannot add splat scene while another load or unload is already in progress.'); } if (this.isDisposingOrDisposed()) { throw new Error('Cannot add splat scene after dispose() is called.'); } var fileCount = sceneOptions.length; var percentComplete = []; if (showLoadingUI) { this.loadingSpinner.removeAllTasks(); this.loadingSpinner.show(); } var onLoadProgress = (fileIndex, percent, percentLabel) => { percentComplete[fileIndex] = percent; var totalPercent = 0; for (var i = 0; i < fileCount; i++) totalPercent += percentComplete[i] || 0; totalPercent = totalPercent / fileCount; percentLabel = "".concat(totalPercent.toFixed(2), "%"); if (showLoadingUI) { this.loadingSpinner.setMessage(totalPercent == 100 ? "Download complete!" : "Downloading: ".concat(percentLabel)); } if (onProgress) onProgress(totalPercent, percentLabel, LoaderStatus.Downloading); }; var downloadPromises = []; var nativeLoadPromises = []; var abortHandlers = []; for (var i = 0; i < sceneOptions.length; i++) { var _options2 = sceneOptions[i]; var format = _options2.format !== undefined && _options2.format !== null ? _options2.format : sceneFormatFromPath(_options2.path); var _downloadPromise = this.downloadSplatSceneToSplatBuffer(_options2.path, _options2.splatAlphaRemovalThreshold, onLoadProgress.bind(this, i), false, undefined, format); abortHandlers.push(_downloadPromise.abortHandler); downloadPromises.push(_downloadPromise); nativeLoadPromises.push(_downloadPromise.promise); this.addSplatSceneDownloadPromise(_downloadPromise); } var downloadPromise = new AbortablePromise((resolve, reject) => { Promise.all(nativeLoadPromises).then(splatBuffers => { if (showLoadingUI) this.loadingSpinner.hide(); if (onProgress) options.onProgress(0, '0%', LoaderStatus.Processing); this.addSplatBuffers(splatBuffers, sceneOptions, true, showLoadingUI, showLoadingUI).then(() => { if (onProgress) onProgress(100, '100%', LoaderStatus.Processing); this.clearSplatSceneDownloadAndBuildPromise(); resolve(); }); }).catch(e => { if (showLoadingUI) this.loadingSpinner.hide(); this.clearSplatSceneDownloadAndBuildPromise(); if (!(e instanceof AbortedPromiseError)) { reject(new Error("Viewer::addSplatScenes -> Could not load one or more splat scenes.")); } else { resolve(); } }).finally(() => { for (var _downloadPromise2 of downloadPromises) { this.removeSplatSceneDownloadPromise(_downloadPromise2); } }); }, () => { for (var abortHandler of abortHandlers) abortHandler(); }); this.setSplatSceneDownloadAndBuildPromise(downloadPromise); return downloadPromise; } /** * Download a splat scene and convert to SplatBuffer instance. * @param {string} path Path to splat scene to be loaded * @param {number} splatAlphaRemovalThreshold Ignore any splats with an alpha less than the specified * value (valid range: 0 - 255), defaults to 1 * * @param {function} onProgress Function to be called as file data are received * @param {boolean} streamBuiltSections Construct file sections into splat buffers as they are downloaded * @param {function} onSectionBuilt Function to be called when new section is added to the file * @param {string} format File format of the scene * @return {AbortablePromise} */ downloadSplatSceneToSplatBuffer(path) { var splatAlphaRemovalThreshold = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var onProgress = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; var streamBuiltSections = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; var onSectionBuilt = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : undefined; var format = arguments.length > 5 ? arguments[5] : undefined; if (format === SceneFormat.Splat) { return SplatLoader.loadFromURL(path, onProgress, streamBuiltSections, onSectionBuilt, splatAlphaRemovalThreshold, 0, false); } else if (format === SceneFormat.KSplat) { return KSplatLoader.loadFromURL(path, onProgress, streamBuiltSections, onSectionBuilt); } else if (format === SceneFormat.Ply) { return PlyLoader.loadFromURL(path, onProgress, streamBuiltSections, onSectionBuilt, splatAlphaRemovalThreshold, 0, this.sphericalHarmonicsDegree); } return AbortablePromise.reject(new Error("Viewer::downloadSplatSceneToSplatBuffer -> File format not supported: ".concat(path))); } static isStreamable(format) { return format === SceneFormat.Splat || format === SceneFormat.KSplat || format === SceneFormat.Ply; } /** * Add one or more instances of SplatBuffer to the SplatMesh instance managed by the viewer. This function is additive; all splat * buffers contained by the viewer's splat mesh before calling this function will be preserved. * @param {Array} splatBuffers SplatBuffer instances * @param {Array} splatBufferOptions Array of options objects: { * * splatAlphaRemovalThreshold: Ignore any splats with an alpha less than the specified * value (valid range: 0 - 255), defaults to 1 * * position (Array): Position of the scene, acts as an offset from its default position, defaults to [0, 0, 0] * * rotation (Array): Rotation of the scene represented as a quaternion, defaults to [0, 0, 0, 1] * * scale (Array): Scene's scale, defaults to [1, 1, 1] * } * @param {boolean} finalBuild Will the splat mesh be in its final state after this build? * @param {boolean} showLoadingUIForSplatTreeBuild Whether or not to show the loading spinner during construction of the splat tree. * @return {object} Object containing info about the splats that are updated */ addSplatBuffersToMesh(splatBuffers, splatBufferOptions) { var finalBuild = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var showLoadingUIForSplatTreeBuild = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; if (this.isDisposingOrDisposed()) return; var allSplatBuffers = this.splatMesh.splatBuffers || []; var allSplatBufferOptions = this.splatMesh.splatBufferOptions || []; allSplatBuffers.push(...splatBuffers); allSplatBufferOptions.push(...splatBufferOptions); if (this.renderer) this.splatMesh.setRenderer(this.renderer); var splatOptimizingTaskId; var onSplatTreeIndexesUpload = finished => { if (this.isDisposingOrDisposed()) return; var splatCount = this.splatMesh.getSplatCount(); if (showLoadingUIForSplatTreeBuild && splatCount >= MIN_SPLAT_COUNT_TO_SHOW_SPLAT_TREE_LOADING_SPINNER) { if (!finished && !splatOptimizingTaskId) { this.loadingSpinner.setMinimized(true, true); splatOptimizingTaskId = this.loadingSpinner.addTask('Optimizing splats...'); } } }; var onSplatTreeReady = finished => { if (this.isDisposingOrDisposed()) return; if (finished && splatOptimizingTaskId) { this.loadingSpinner.removeTask(splatOptimizingTaskId); } }; return this.splatMesh.build(allSplatBuffers, allSplatBufferOptions, true, finalBuild, onSplatTreeIndexesUpload, onSplatTreeReady); } /** * Set up the splat sorting web worker. * @param {SplatMesh} splatMesh SplatMesh instance that contains the splats to be sorted * @return {Promise} */ setupSortWorker(splatMesh) { if (this.isDisposingOrDisposed()) return; return new Promise(resolve => { var DistancesArrayType = this.integerBasedSort ? Int32Array : Float32Array; var splatCount = splatMesh.getSplatCount(); var maxSplatCount = splatMesh.getMaxSplatCount(); this.sortWorker = createSortWorker(maxSplatCount, this.sharedMemoryForWorkers, this.integerBasedSort, this.splatMesh.dynamicMode); var sortCount = 0; this.sortWorker.onmessage = e => { if (e.data.sortDone) { this.sortRunning = false; if (this.sharedMemoryForWorkers) { this.splatMesh.updateRenderIndexes(this.sortWorkerSortedIndexes, e.data.splatRenderCount); } else { var sortedIndexes = new Uint32Array(e.data.sortedIndexes.buffer, 0, e.data.splatRenderCount); this.splatMesh.updateRenderIndexes(sortedIndexes, e.data.splatRenderCount); } this.lastSortTime = e.data.sortTime; this.sortPromiseResolver(); this.sortPromiseResolver = null; this.forceRenderNextFrame(); if (sortCount === 0) { this.runAfterFirstSort.forEach(func => { func(); }); this.runAfterFirstSort.length = 0; } sortCount++; } else if (e.data.sortCanceled) { this.sortRunning = false; } else if (e.data.sortSetupPhase1Complete) { //划分好共享数据 if (this.logLevel >= LogLevel.Info) console.log('Sorting web worker WASM setup complete.'); if (this.sharedMemoryForWorkers) { this.sortWorkerSortedIndexes = new Uint32Array(e.data.sortedIndexesBuffer, //这是以后就是每次要渲染的indexes e.data.sortedIndexesOffset, maxSplatCount); this.sortWorkerIndexesToSort = new Uint32Array(e.data.indexesToSortBuffer, //准备sort的点,每次镜头改变时先选出要渲染的点,再排序 e.data.indexesToSortOffset, maxSplatCount); this.sortWorkerPrecomputedDistances = new DistancesArrayType(e.data.precomputedDistancesBuffer, e.data.precomputedDistancesOffset, maxSplatCount); this.sortWorkerTransforms = new Float32Array(e.data.transformsBuffer, e.data.transformsOffset, Constants.MaxScenes * 16); } else { this.sortWorkerIndexesToSort = new Uint32Array(maxSplatCount); this.sortWorkerPrecomputedDistances = new DistancesArrayType(maxSplatCount); this.sortWorkerTransforms = new Float32Array(Constants.MaxScenes * 16); } for (var i = 0; i < splatCount; i++) this.sortWorkerIndexesToSort[i] = i; //初始化待sort的所有index,按顺序赋值就行 this.sortWorker.maxSplatCount = maxSplatCount; //总点数 if (this.logLevel >= LogLevel.Info) { console.log('Sorting web worker ready.'); var splatDataTextures = this.splatMesh.getSplatDataTextures(); var covariancesTextureSize = splatDataTextures.covariances.size; var centersColorsTextureSize = splatDataTextures.centerColors.size; console.log('Covariances texture size: ' + covariancesTextureSize.x + ' x ' + covariancesTextureSize.y); console.log('Centers/colors texture size: ' + centersColorsTextureSize.x + ' x ' + centersColorsTextureSize.y); } resolve(); } }; }); } disposeSortWorker() { if (this.sortWorker) this.sortWorker.terminate(); this.sortWorker = null; this.sortPromise = null; if (this.sortPromiseResolver) { this.sortPromiseResolver(); this.sortPromiseResolver = null; } this.sortRunning = false; } removeSplatScene(index) { var showLoadingUI = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; if (this.isLoadingOrUnloading()) { throw new Error('Cannot remove splat scene while another load or unload is already in progress.'); } if (this.isDisposingOrDisposed()) { throw new Error('Cannot remove splat scene after dispose() is called.'); } var sortPromise; this.splatSceneRemovalPromise = new Promise((resolve, reject) => { var revmovalTaskId; if (showLoadingUI) { this.loadingSpinner.removeAllTasks(); this.loadingSpinner.show(); revmovalTaskId = this.loadingSpinner.addTask('Removing splat scene...'); } var checkAndHideLoadingUI = () => { if (showLoadingUI) { this.loadingSpinner.hide(); this.loadingSpinner.removeTask(revmovalTaskId); } }; var onDone = error => { checkAndHideLoadingUI(); this.splatSceneRemovalPromise = null; if (!error) resolve();else reject(error); }; var checkForEarlyExit = () => { if (this.isDisposingOrDisposed()) { onDone(); return true; } return false; }; sortPromise = this.sortPromise || Promise.resolve(); sortPromise.then(() => { if (checkForEarlyExit()) return; var savedSplatBuffers = []; var savedSceneOptions = []; var savedSceneTransformComponents = []; var savedVisibleRegionFadeStartRadius = this.splatMesh.visibleRegionFadeStartRadius; for (var i = 0; i < this.splatMesh.scenes.length; i++) { if (i !== index) { var scene = this.splatMesh.scenes[i]; savedSplatBuffers.push(scene.splatBuffer); savedSceneOptions.push(this.splatMesh.sceneOptions[i]); savedSceneTransformComponents.push({ 'position': scene.position.clone(), 'quaternion': scene.quaternion.clone(), 'scale': scene.scale.clone() }); } } this.disposeSortWorker(); this.splatMesh.dispose(); this.createSplatMesh(); this.addSplatBuffers(savedSplatBuffers, savedSceneOptions, true, false, true).then(() => { if (checkForEarlyExit()) return; checkAndHideLoadingUI(); this.splatMesh.visibleRegionFadeStartRadius = savedVisibleRegionFadeStartRadius; this.splatMesh.scenes.forEach((scene, index) => { scene.position.copy(savedSceneTransformComponents[index].position); scene.quaternion.copy(savedSceneTransformComponents[index].quaternion); scene.scale.copy(savedSceneTransformComponents[index].scale); }); this.splatMesh.updateTransforms(); this.splatRenderReady = false; this.updateSplatSort(true).then(() => { if (checkForEarlyExit()) { this.splatRenderReady = true; return; } sortPromise = this.sortPromise || Promise.resolve(); sortPromise.then(() => { this.splatRenderReady = true; onDone(); }); }); }).catch(e => { onDone(e); }); }); }); return this.splatSceneRemovalPromise; } /** * Start self-driven mode */ start() { if (this.selfDrivenMode) { if (this.webXRMode) { this.renderer.setAnimationLoop(this.selfDrivenUpdateFunc); } else { this.requestFrameId = requestAnimationFrame(this.selfDrivenUpdateFunc); } this.selfDrivenModeRunning = true; } else { throw new Error('Cannot start viewer unless it is in self driven mode.'); } } /** * Stop self-driven mode */ stop() { if (this.selfDrivenMode && this.selfDrivenModeRunning) { if (!this.webXRMode) { cancelAnimationFrame(this.requestFrameId); } this.selfDrivenModeRunning = false; } } /** * Dispose of all resources held directly and indirectly by this viewer. */ async dispose() { this.disposing = true; var waitPromises = []; var promisesToAbort = []; for (var promiseKey in this.splatSceneDownloadPromises) { if (this.splatSceneDownloadPromises.hasOwnProperty(promiseKey)) { var downloadPromiseToAbort = this.splatSceneDownloadPromises[promiseKey]; promisesToAbort.push(downloadPromiseToAbort); waitPromises.push(downloadPromiseToAbort.promise); } } if (this.sortPromise) { waitPromises.push(this.sortPromise); } var disposePromise = Promise.all(waitPromises).finally(() => { this.stop(); if (this.controls) { this.controls.dispose(); this.controls = null; } if (this.splatMesh) { this.splatMesh.dispose(); this.splatMesh = null; } if (this.sceneHelper) { this.sceneHelper.dispose(); this.sceneHelper = null; } if (this.resizeObserver) { this.resizeObserver.unobserve(this.rootElement); this.resizeObserver = null; } this.disposeSortWorker(); this.removeEventHandlers(); this.loadingSpinner.removeAllTasks(); this.loadingSpinner.setContainer(null); this.loadingProgressBar.hide(); this.loadingProgressBar.setContainer(null); this.infoPanel.setContainer(null); this.camera = null; this.threeScene = null; this.splatRenderReady = false; this.initialized = false; if (this.renderer) { if (!this.usingExternalRenderer) { this.rootElement.removeChild(this.renderer.domElement); this.renderer.dispose(); } this.renderer = null; } if (!this.usingExternalRenderer) { document.body.removeChild(this.rootElement); } this.sortWorkerSortedIndexes = null; this.sortWorkerIndexesToSort = null; this.sortWorkerPrecomputedDistances = null; this.sortWorkerTransforms = null; this.disposed = true; this.disposing = false; }); promisesToAbort.forEach(toAbort => { toAbort.abort(); }); return disposePromise; } selfDrivenUpdate() { /* if (this.selfDrivenMode && !this.webXRMode) { //xzw delete this.requestFrameId = requestAnimationFrame(this.selfDrivenUpdateFunc); } */ this.update(); if (this.shouldRender()) { this.render(); this.consecutiveRenderFrames++; } else { this.consecutiveRenderFrames = 0; } this.renderNextFrame = false; } forceRenderNextFrame() { this.renderNextFrame = true; } update(renderer, camera) { if (this.dropInMode) this.updateForDropInMode(renderer, camera); if (!this.initialized || !this.splatRenderReady) return; if (this.controls) { this.controls.update(); if (this.camera.isOrthographicCamera && !this.usingExternalCamera) { Viewer.setCameraPositionFromZoom(this.camera, this.camera, this.controls); } } this.splatMesh.updateVisibleRegionFadeDistance(this.sceneRevealMode); this.updateSplatSort(); this.updateForRendererSizeChanges(); this.updateSplatMesh(); this.updateMeshCursor(); this.updateFPS(); this.timingSensitiveUpdates(); this.updateInfoPanel(); this.updateControlPlane(); } updateForDropInMode(renderer, camera) { this.renderer = renderer; if (this.splatMesh) this.splatMesh.setRenderer(this.renderer); this.camera = camera; if (this.controls) this.controls.object = camera; this.init(); } updateControlPlane() { if (this.showControlPlane) { this.sceneHelper.setControlPlaneVisibility(true); this.sceneHelper.positionAndOrientControlPlane(this.controls.target, this.camera.up); } else { this.sceneHelper.setControlPlaneVisibility(false); } } getSplatMesh() { return this.splatMesh; } /** * Get a reference to a splat scene. * @param {number} sceneIndex The index of the scene to which the reference will be returned * @return {SplatScene} */ getSplatScene(sceneIndex) { return this.splatMesh.getScene(sceneIndex); } isMobile() { return navigator.userAgent.includes('Mobi'); } } /** * DropInViewer: Wrapper for a Viewer instance that enables it to be added to a Three.js scene like * any other Three.js scene object (Mesh, Object3D, etc.) */ _defineProperty(Viewer, "setCameraPositionFromZoom", function () { var tempVector = new Vector3(); return function (positionCamera, zoomedCamera, controls) { var toLookAtDistance = 1 / (zoomedCamera.zoom * 0.001); tempVector.copy(controls.target).sub(positionCamera.position).normalize().multiplyScalar(toLookAtDistance).negate(); positionCamera.position.copy(controls.target).add(tempVector); }; }()); _defineProperty(Viewer, "setCameraZoomFromPosition", function () { var tempVector = new Vector3(); return function (zoomCamera, positionZamera, controls) { var toLookAtDistance = tempVector.copy(controls.target).sub(positionZamera.position).length(); zoomCamera.zoom = 1 / (toLookAtDistance * .001); }; }()); class DropInViewer extends Group { constructor() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(); options.selfDrivenMode = false; options.useBuiltInControls = false; options.rootElement = null; options.ignoreDevicePixelRatio = false; options.dropInMode = true; options.camera = undefined; options.renderer = undefined; this.viewer = new Viewer(options); this.splatMesh = null; this.callbackMesh = DropInViewer.createCallbackMesh(); this.add(this.callbackMesh); this.callbackMesh.onBeforeRender = DropInViewer.onBeforeRender.bind(this, this.viewer); } /** * Add a single splat scene to the viewer. * @param {string} path Path to splat scene to be loaded * @param {object} options { * * splatAlphaRemovalThreshold: Ignore any splats with an alpha less than the specified * value (valid range: 0 - 255), defaults to 1 * * showLoadingUI: Display a loading spinner while the scene is loading, defaults to true * * position (Array): Position of the scene, acts as an offset from its default position, defaults to [0, 0, 0] * * rotation (Array): Rotation of the scene represented as a quaternion, defaults to [0, 0, 0, 1] * * scale (Array): Scene's scale, defaults to [1, 1, 1] * * onProgress: Function to be called as file data are received * * } * @return {AbortablePromise} */ addSplatScene(path) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (options.showLoadingUI !== false) options.showLoadingUI = true; return this.viewer.addSplatScene(path, options); } /** * Add multiple splat scenes to the viewer. * @param {Array} sceneOptions Array of per-scene options: { * * path: Path to splat scene to be loaded * * splatAlphaRemovalThreshold: Ignore any splats with an alpha less than the specified * value (valid range: 0 - 255), defaults to 1 * * position (Array): Position of the scene, acts as an offset from its default position, defaults to [0, 0, 0] * * rotation (Array): Rotation of the scene represented as a quaternion, defaults to [0, 0, 0, 1] * * scale (Array): Scene's scale, defaults to [1, 1, 1] * } * @param {boolean} showLoadingUI Display a loading spinner while the scene is loading, defaults to true * @return {AbortablePromise} */ addSplatScenes(sceneOptions, showLoadingUI) { if (showLoadingUI !== false) showLoadingUI = true; return this.viewer.addSplatScenes(sceneOptions, showLoadingUI); } /** * Get a reference to a splat scene. * @param {number} sceneIndex The index of the scene to which the reference will be returned * @return {SplatScene} */ getSplatScene(sceneIndex) { return this.viewer.getSplatScene(sceneIndex); } removeSplatScene(index) { return this.viewer.removeSplatScene(index); } dispose() { return this.viewer.dispose(); } static onBeforeRender(viewer, renderer, threeScene, camera) { if (this.splatMesh !== this.viewer.splatMesh) { if (this.splatMesh) { this.remove(this.splatMesh); } this.splatMesh = this.viewer.splatMesh; this.add(this.viewer.splatMesh); } viewer.update(renderer, camera); } static createCallbackMesh() { var geometry = new SphereGeometry(1, 8, 8); var material = new MeshBasicMaterial(); material.colorWrite = false; material.depthWrite = false; var mesh = new Mesh(geometry, material); mesh.frustumCulled = false; return mesh; } } //2022.11.11 copyfrom : https://unpkg.com/three@0.146.0/examples/jsm/loaders/DRACOLoader.js var _taskCache = new WeakMap(); class DRACOLoader extends Loader { constructor(manager) { super(manager); this.decoderPath = ''; this.decoderConfig = {}; this.decoderBinary = null; this.decoderPending = null; this.workerLimit = 4; this.workerPool = []; this.workerNextTaskID = 1; this.workerSourceURL = ''; this.defaultAttributeIDs = { position: 'POSITION', normal: 'NORMAL', color: 'COLOR', uv: 'TEX_COORD' }; this.defaultAttributeTypes = { position: 'Float32Array', normal: 'Float32Array', color: 'Float32Array', uv: 'Float32Array' }; } setDecoderPath(path) { this.decoderPath = path; return this; } setDecoderConfig(config) { this.decoderConfig = config; return this; } setWorkerLimit(workerLimit) { this.workerLimit = workerLimit; return this; } load(url, onLoad, onProgress, onError) { var loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setResponseType('arraybuffer'); loader.setRequestHeader(this.requestHeader); loader.setWithCredentials(this.withCredentials); loader.load(url, buffer => { this.decodeDracoFile(buffer, onLoad).catch(onError); }, onProgress, onError); } decodeDracoFile(buffer, callback, attributeIDs, attributeTypes) { var taskConfig = { attributeIDs: attributeIDs || this.defaultAttributeIDs, attributeTypes: attributeTypes || this.defaultAttributeTypes, useUniqueIDs: !!attributeIDs }; return this.decodeGeometry(buffer, taskConfig).then(callback); } decodeGeometry(buffer, taskConfig) { var taskKey = JSON.stringify(taskConfig); // Check for an existing task using this buffer. A transferred buffer cannot be transferred // again from this thread. if (_taskCache.has(buffer)) { var cachedTask = _taskCache.get(buffer); if (cachedTask.key === taskKey) { return cachedTask.promise; } else if (buffer.byteLength === 0) { // Technically, it would be possible to wait for the previous task to complete, // transfer the buffer back, and decode again with the second configuration. That // is complex, and I don't know of any reason to decode a Draco buffer twice in // different ways, so this is left unimplemented. throw new Error('THREE.DRACOLoader: Unable to re-decode a buffer with different ' + 'settings. Buffer has already been transferred.'); } } // var worker; var taskID = this.workerNextTaskID++; var taskCost = buffer.byteLength; // Obtain a worker and assign a task, and construct a geometry instance // when the task completes. var geometryPending = this._getWorker(taskID, taskCost).then(_worker => { worker = _worker; return new Promise((resolve, reject) => { worker._callbacks[taskID] = { resolve, reject }; worker.postMessage({ type: 'decode', id: taskID, taskConfig, buffer }, [buffer]); // this.debug(); }); }).then(message => this._createGeometry(message.geometry)); // Remove task from the task list. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416) geometryPending.catch(() => true).then(() => { if (worker && taskID) { this._releaseTask(worker, taskID); // this.debug(); } }); // Cache the task result. _taskCache.set(buffer, { key: taskKey, promise: geometryPending }); return geometryPending; } _createGeometry(geometryData) { var geometry = new BufferGeometry(); if (geometryData.index) { geometry.setIndex(new BufferAttribute(geometryData.index.array, 1)); } for (var i = 0; i < geometryData.attributes.length; i++) { var attribute = geometryData.attributes[i]; var name = attribute.name; var array = attribute.array; var itemSize = attribute.itemSize; geometry.setAttribute(name, new BufferAttribute(array, itemSize)); } return geometry; } _loadLibrary(url, responseType) { var loader = new FileLoader(this.manager); loader.setPath(this.decoderPath); loader.setResponseType(responseType); loader.setWithCredentials(this.withCredentials); return new Promise((resolve, reject) => { loader.load(url, resolve, undefined, reject); }); } preload() { this._initDecoder(); return this; } _initDecoder() { if (this.decoderPending) return this.decoderPending; var useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js'; var librariesPending = []; if (useJS) { librariesPending.push(this._loadLibrary('draco_decoder.js', 'text')); } else { librariesPending.push(this._loadLibrary('draco_wasm_wrapper.js', 'text')); librariesPending.push(this._loadLibrary('draco_decoder.wasm', 'arraybuffer')); } this.decoderPending = Promise.all(librariesPending).then(libraries => { var jsContent = libraries[0]; if (!useJS) { this.decoderConfig.wasmBinary = libraries[1]; } var fn = DRACOWorker.toString(); var body = ['/* draco decoder */', jsContent, '', '/* worker */', fn.substring(fn.indexOf('{') + 1, fn.lastIndexOf('}'))].join('\n'); this.workerSourceURL = URL.createObjectURL(new Blob([body])); }); return this.decoderPending; } _getWorker(taskID, taskCost) { return this._initDecoder().then(() => { if (this.workerPool.length < this.workerLimit) { var _worker2 = new Worker(this.workerSourceURL); _worker2._callbacks = {}; _worker2._taskCosts = {}; _worker2._taskLoad = 0; _worker2.postMessage({ type: 'init', decoderConfig: this.decoderConfig }); _worker2.onmessage = function (e) { var message = e.data; switch (message.type) { case 'decode': _worker2._callbacks[message.id].resolve(message); break; case 'error': _worker2._callbacks[message.id].reject(message); break; default: console.error('THREE.DRACOLoader: Unexpected message, "' + message.type + '"'); } }; this.workerPool.push(_worker2); } else { this.workerPool.sort(function (a, b) { return a._taskLoad > b._taskLoad ? -1 : 1; }); } var worker = this.workerPool[this.workerPool.length - 1]; worker._taskCosts[taskID] = taskCost; worker._taskLoad += taskCost; return worker; }); } _releaseTask(worker, taskID) { worker._taskLoad -= worker._taskCosts[taskID]; delete worker._callbacks[taskID]; delete worker._taskCosts[taskID]; } debug() { console.log('Task load: ', this.workerPool.map(worker => worker._taskLoad)); } dispose() { for (var i = 0; i < this.workerPool.length; ++i) { this.workerPool[i].terminate(); } this.workerPool.length = 0; return this; } } /* WEB WORKER */ function DRACOWorker() { var decoderConfig; var decoderPending; onmessage = function onmessage(e) { var message = e.data; switch (message.type) { case 'init': decoderConfig = message.decoderConfig; decoderPending = new Promise(function (resolve /*, reject*/) { decoderConfig.onModuleLoaded = function (draco) { // Module is Promise-like. Wrap before resolving to avoid loop. resolve({ draco: draco }); }; DracoDecoderModule(decoderConfig); // eslint-disable-line no-undef }); break; case 'decode': var buffer = message.buffer; var taskConfig = message.taskConfig; decoderPending.then(module => { var draco = module.draco; var decoder = new draco.Decoder(); var decoderBuffer = new draco.DecoderBuffer(); decoderBuffer.Init(new Int8Array(buffer), buffer.byteLength); try { var geometry = decodeGeometry(draco, decoder, decoderBuffer, taskConfig); var buffers = geometry.attributes.map(attr => attr.array.buffer); if (geometry.index) buffers.push(geometry.index.array.buffer); self.postMessage({ type: 'decode', id: message.id, geometry }, buffers); } catch (error) { console.error(error); self.postMessage({ type: 'error', id: message.id, error: error.message }); } finally { draco.destroy(decoderBuffer); draco.destroy(decoder); } }); break; } }; function decodeGeometry(draco, decoder, decoderBuffer, taskConfig) { var attributeIDs = taskConfig.attributeIDs; var attributeTypes = taskConfig.attributeTypes; var dracoGeometry; var decodingStatus; var geometryType = decoder.GetEncodedGeometryType(decoderBuffer); if (geometryType === draco.TRIANGULAR_MESH) { dracoGeometry = new draco.Mesh(); decodingStatus = decoder.DecodeBufferToMesh(decoderBuffer, dracoGeometry); } else if (geometryType === draco.POINT_CLOUD) { dracoGeometry = new draco.PointCloud(); decodingStatus = decoder.DecodeBufferToPointCloud(decoderBuffer, dracoGeometry); } else { throw new Error('THREE.DRACOLoader: Unexpected geometry type.'); } if (!decodingStatus.ok() || dracoGeometry.ptr === 0) { throw new Error('THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg()); } var geometry = { index: null, attributes: [] }; // Gather all vertex attributes. for (var attributeName in attributeIDs) { var attributeType = self[attributeTypes[attributeName]]; var attribute = void 0; var attributeID = void 0; // A Draco file may be created with default vertex attributes, whose attribute IDs // are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively, // a Draco file may contain a custom set of attributes, identified by known unique // IDs. glTF files always do the latter, and `.drc` files typically do the former. if (taskConfig.useUniqueIDs) { attributeID = attributeIDs[attributeName]; attribute = decoder.GetAttributeByUniqueId(dracoGeometry, attributeID); } else { attributeID = decoder.GetAttributeId(dracoGeometry, draco[attributeIDs[attributeName]]); if (attributeID === -1) continue; attribute = decoder.GetAttribute(dracoGeometry, attributeID); } geometry.attributes.push(decodeAttribute(draco, decoder, dracoGeometry, attributeName, attributeType, attribute)); } // Add index. if (geometryType === draco.TRIANGULAR_MESH) { geometry.index = decodeIndex(draco, decoder, dracoGeometry); } draco.destroy(dracoGeometry); return geometry; } function decodeIndex(draco, decoder, dracoGeometry) { var numFaces = dracoGeometry.num_faces(); var numIndices = numFaces * 3; var byteLength = numIndices * 4; var ptr = draco._malloc(byteLength); decoder.GetTrianglesUInt32Array(dracoGeometry, byteLength, ptr); var index = new Uint32Array(draco.HEAPF32.buffer, ptr, numIndices).slice(); draco._free(ptr); return { array: index, itemSize: 1 }; } function decodeAttribute(draco, decoder, dracoGeometry, attributeName, attributeType, attribute) { var numComponents = attribute.num_components(); var numPoints = dracoGeometry.num_points(); var numValues = numPoints * numComponents; var byteLength = numValues * attributeType.BYTES_PER_ELEMENT; var dataType = getDracoDataType(draco, attributeType); var ptr = draco._malloc(byteLength); decoder.GetAttributeDataArrayForAllPoints(dracoGeometry, attribute, dataType, byteLength, ptr); var array = new attributeType(draco.HEAPF32.buffer, ptr, numValues).slice(); draco._free(ptr); return { name: attributeName, array: array, itemSize: numComponents }; } function getDracoDataType(draco, attributeType) { switch (attributeType) { case Float32Array: return draco.DT_FLOAT32; case Int8Array: return draco.DT_INT8; case Int16Array: return draco.DT_INT16; case Int32Array: return draco.DT_INT32; case Uint8Array: return draco.DT_UINT8; case Uint16Array: return draco.DT_UINT16; case Uint32Array: return draco.DT_UINT32; } } } /** * @author Deepkolos / https://github.com/deepkolos */ //用于KTX2Loader class WorkerPool$1 { constructor() { var pool = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 4; this.pool = pool; this.queue = []; this.workers = []; this.workersResolve = []; this.workerStatus = 0; } _initWorker(workerId) { if (!this.workers[workerId]) { var worker = this.workerCreator(); worker.addEventListener('message', this._onMessage.bind(this, workerId)); this.workers[workerId] = worker; } } _getIdleWorker() { for (var i = 0; i < this.pool; i++) if (!(this.workerStatus & 1 << i)) return i; return -1; } _onMessage(workerId, msg) { var resolve = this.workersResolve[workerId]; resolve && resolve(msg); if (this.queue.length) { var { resolve: _resolve, msg: _msg, transfer } = this.queue.shift(); this.workersResolve[workerId] = _resolve; this.workers[workerId].postMessage(_msg, transfer); } else { this.workerStatus ^= 1 << workerId; } } setWorkerCreator(workerCreator) { this.workerCreator = workerCreator; } setWorkerLimit(pool) { this.pool = pool; } postMessage(msg, transfer) { return new Promise(resolve => { var workerId = this._getIdleWorker(); if (workerId !== -1) { this._initWorker(workerId); this.workerStatus |= 1 << workerId; this.workersResolve[workerId] = resolve; this.workers[workerId].postMessage(msg, transfer); } else { this.queue.push({ resolve, msg, transfer }); } }); } dispose() { this.workers.forEach(worker => worker.terminate()); this.workersResolve.length = 0; this.workers.length = 0; this.queue.length = 0; this.workerStatus = 0; } } var t = 0, e$1 = 1, n$1 = 2, i$2 = 3, s = 0, a$1 = 0, r = 2, o$1 = 0, l$1 = 1, f = 160, U$1 = 161, c$1 = 162, h$2 = 163, _$1 = 0, p = 1, g = 0, y = 1, x$2 = 2, u$2 = 3, b$1 = 4, d = 5, m = 6, w$1 = 7, D = 8, B = 9, L = 10, A = 11, k = 12, v = 13, S$1 = 14, I = 15, O = 16, T$1 = 17, V = 18, E = 0, F = 1, P = 2, C = 3, z = 4, M$1 = 5, W = 6, N = 7, H = 8, K = 9, X = 10, j = 11, R = 0, Y = 1, q = 2, G = 13, J = 14, Q = 15, Z = 128, $$1 = 64, tt = 32, et = 16, nt = 0, it = 1, st = 2, at = 3, rt = 4, ot = 5, lt = 6, ft = 7, Ut = 8, ct = 9, ht = 10, _t = 13, pt = 14, gt = 15, yt = 16, xt = 17, ut = 20, bt = 21, dt = 22, mt = 23, wt = 24, Dt = 27, Bt = 28, Lt = 29, At = 30, kt = 31, vt = 34, St = 35, It = 36, Ot = 37, Tt = 38, Vt = 41, Et = 42, Ft = 43, Pt = 44, Ct = 45, zt = 48, Mt = 49, Wt = 50, Nt = 58, Ht = 59, Kt = 62, Xt = 63, jt = 64, Rt = 65, Yt = 68, qt = 69, Gt = 70, Jt = 71, Qt = 74, Zt = 75, $t = 76, te = 77, ee = 78, ne = 81, ie = 82, se = 83, ae = 84, re = 85, oe = 88, le = 89, fe = 90, Ue = 91, ce = 92, he = 95, _e = 96, pe = 97, ge = 98, ye = 99, xe = 100, ue = 101, be = 102, de = 103, me = 104, we = 105, De = 106, Be = 107, Le = 108, Ae = 109, ke = 110, ve = 111, Se = 112, Ie = 113, Oe = 114, Te = 115, Ve = 116, Ee = 117, Fe = 118, Pe = 119, Ce = 120, ze = 121, Me = 122, We = 123, Ne = 124, He = 125, Ke = 126, Xe = 127, je = 128, Re = 129, Ye = 130, qe = 131, Ge = 132, Je = 133, Qe = 134, Ze = 135, $e = 136, tn = 137, en = 138, nn = 139, sn = 140, an = 141, rn = 142, on = 143, ln = 144, fn = 145, Un = 146, cn = 147, hn = 148, _n = 149, pn = 150, gn = 151, yn = 152, xn = 153, un = 154, bn = 155, dn = 156, mn = 157, wn = 158, Dn = 159, Bn = 160, Ln = 161, An = 162, kn = 163, vn = 164, Sn = 165, In = 166, On = 167, Tn = 168, Vn = 169, En = 170, Fn = 171, Pn = 172, Cn = 173, zn = 174, Mn = 175, Wn = 176, Nn = 177, Hn = 178, Kn = 179, Xn = 180, jn = 181, Rn = 182, Yn = 183, qn = 184, Gn = 1000156007, Jn = 1000156008, Qn = 1000156009, Zn = 1000156010, $n = 1000156011, ti = 1000156017, ei = 1000156018, ni = 1000156019, ii = 1000156020, si = 1000156021, ai = 1000054e3, ri = 1000054001, oi = 1000054002, li = 1000054003, fi = 1000054004, Ui = 1000054005, ci = 1000054006, hi = 1000054007, _i = 1000066e3, pi = 1000066001, gi = 1000066002, yi = 1000066003, xi = 1000066004, ui = 1000066005, bi = 1000066006, di = 1000066007, mi = 1000066008, wi = 1000066009, Di = 1000066010, Bi = 1000066011, Li = 1000066012, Ai = 1000066013, ki = 100034e4, vi = 1000340001; class Si { constructor() { this.vkFormat = 0, this.typeSize = 1, this.pixelWidth = 0, this.pixelHeight = 0, this.pixelDepth = 0, this.layerCount = 0, this.faceCount = 1, this.supercompressionScheme = 0, this.levels = [], this.dataFormatDescriptor = [{ vendorId: 0, descriptorType: 0, descriptorBlockSize: 0, versionNumber: 2, colorModel: 0, colorPrimaries: 1, transferFunction: 2, flags: 0, texelBlockDimension: [0, 0, 0, 0], bytesPlane: [0, 0, 0, 0, 0, 0, 0, 0], samples: [] }], this.keyValue = {}, this.globalData = null; } } class Ii { constructor(t, e, n, i) { this._dataView = new DataView(t.buffer, t.byteOffset + e, n), this._littleEndian = i, this._offset = 0; } _nextUint8() { var t = this._dataView.getUint8(this._offset); return this._offset += 1, t; } _nextUint16() { var t = this._dataView.getUint16(this._offset, this._littleEndian); return this._offset += 2, t; } _nextUint32() { var t = this._dataView.getUint32(this._offset, this._littleEndian); return this._offset += 4, t; } _nextUint64() { var t = this._dataView.getUint32(this._offset, this._littleEndian) + 2 ** 32 * this._dataView.getUint32(this._offset + 4, this._littleEndian); return this._offset += 8, t; } _nextInt32() { var t = this._dataView.getInt32(this._offset, this._littleEndian); return this._offset += 4, t; } _skip(t) { return this._offset += t, this; } _scan(t) { var e = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var n = this._offset; var i = 0; for (; this._dataView.getUint8(this._offset) !== e && i < t;) i++, this._offset++; return i < t && this._offset++, new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + n, i); } } var Oi = new Uint8Array([0]), Ti = [171, 75, 84, 88, 32, 50, 48, 187, 13, 10, 26, 10]; function Vi(t) { return "undefined" != typeof TextEncoder ? new TextEncoder().encode(t) : Buffer.from(t); } function Ei(t) { return "undefined" != typeof TextDecoder ? new TextDecoder().decode(t) : Buffer.from(t).toString("utf8"); } function Fi(t) { var e = 0; for (var _n2 of t) e += _n2.byteLength; var n = new Uint8Array(e); var i = 0; for (var _e2 of t) n.set(new Uint8Array(_e2), i), i += _e2.byteLength; return n; } function Pi(t) { var e = new Uint8Array(t.buffer, t.byteOffset, Ti.length); if (e[0] !== Ti[0] || e[1] !== Ti[1] || e[2] !== Ti[2] || e[3] !== Ti[3] || e[4] !== Ti[4] || e[5] !== Ti[5] || e[6] !== Ti[6] || e[7] !== Ti[7] || e[8] !== Ti[8] || e[9] !== Ti[9] || e[10] !== Ti[10] || e[11] !== Ti[11]) throw new Error("Missing KTX 2.0 identifier."); var n = new Si(), i = 17 * Uint32Array.BYTES_PER_ELEMENT, s = new Ii(t, Ti.length, i, !0); n.vkFormat = s._nextUint32(), n.typeSize = s._nextUint32(), n.pixelWidth = s._nextUint32(), n.pixelHeight = s._nextUint32(), n.pixelDepth = s._nextUint32(), n.layerCount = s._nextUint32(), n.faceCount = s._nextUint32(); var a = s._nextUint32(); n.supercompressionScheme = s._nextUint32(); var r = s._nextUint32(), o = s._nextUint32(), l = s._nextUint32(), f = s._nextUint32(), U = s._nextUint64(), c = s._nextUint64(), h = new Ii(t, Ti.length + i, 3 * a * 8, !0); for (var _e3 = 0; _e3 < a; _e3++) n.levels.push({ levelData: new Uint8Array(t.buffer, t.byteOffset + h._nextUint64(), h._nextUint64()), uncompressedByteLength: h._nextUint64() }); var _ = new Ii(t, r, o, !0), p = { vendorId: _._skip(4)._nextUint16(), descriptorType: _._nextUint16(), versionNumber: _._nextUint16(), descriptorBlockSize: _._nextUint16(), colorModel: _._nextUint8(), colorPrimaries: _._nextUint8(), transferFunction: _._nextUint8(), flags: _._nextUint8(), texelBlockDimension: [_._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8()], bytesPlane: [_._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8()], samples: [] }, g = (p.descriptorBlockSize / 4 - 6) / 4; for (var _t2 = 0; _t2 < g; _t2++) { var _e4 = { bitOffset: _._nextUint16(), bitLength: _._nextUint8(), channelType: _._nextUint8(), samplePosition: [_._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8()], sampleLower: -Infinity, sampleUpper: Infinity }; 64 & _e4.channelType ? (_e4.sampleLower = _._nextInt32(), _e4.sampleUpper = _._nextInt32()) : (_e4.sampleLower = _._nextUint32(), _e4.sampleUpper = _._nextUint32()), p.samples[_t2] = _e4; } n.dataFormatDescriptor.length = 0, n.dataFormatDescriptor.push(p); var y = new Ii(t, l, f, !0); for (; y._offset < f;) { var _t3 = y._nextUint32(), _e5 = y._scan(_t3), _i2 = Ei(_e5), _s = y._scan(_t3 - _e5.byteLength); n.keyValue[_i2] = _i2.match(/^ktx/i) ? Ei(_s) : _s, y._offset % 4 && y._skip(4 - y._offset % 4); } if (c <= 0) return n; var x = new Ii(t, U, c, !0), u = x._nextUint16(), b = x._nextUint16(), d = x._nextUint32(), m = x._nextUint32(), w = x._nextUint32(), D = x._nextUint32(), B = []; for (var _t4 = 0; _t4 < a; _t4++) B.push({ imageFlags: x._nextUint32(), rgbSliceByteOffset: x._nextUint32(), rgbSliceByteLength: x._nextUint32(), alphaSliceByteOffset: x._nextUint32(), alphaSliceByteLength: x._nextUint32() }); var L = U + x._offset, A = L + d, k = A + m, v = k + w, S = new Uint8Array(t.buffer, t.byteOffset + L, d), I = new Uint8Array(t.buffer, t.byteOffset + A, m), O = new Uint8Array(t.buffer, t.byteOffset + k, w), T = new Uint8Array(t.buffer, t.byteOffset + v, D); return n.globalData = { endpointCount: u, selectorCount: b, imageDescs: B, endpointsData: S, selectorsData: I, tablesData: O, extendedData: T }, n; } function Ci() { return (Ci = Object.assign || function (t) { for (var e = 1; e < arguments.length; e++) { var n = arguments[e]; for (var i in n) Object.prototype.hasOwnProperty.call(n, i) && (t[i] = n[i]); } return t; }).apply(this, arguments); } var zi = { keepWriter: !1 }; function Mi(t) { var e = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; e = Ci({}, zi, e); var n = new ArrayBuffer(0); if (t.globalData) { var _e6 = new ArrayBuffer(20 + 5 * t.globalData.imageDescs.length * 4), _i3 = new DataView(_e6); _i3.setUint16(0, t.globalData.endpointCount, !0), _i3.setUint16(2, t.globalData.selectorCount, !0), _i3.setUint32(4, t.globalData.endpointsData.byteLength, !0), _i3.setUint32(8, t.globalData.selectorsData.byteLength, !0), _i3.setUint32(12, t.globalData.tablesData.byteLength, !0), _i3.setUint32(16, t.globalData.extendedData.byteLength, !0); for (var _e7 = 0; _e7 < t.globalData.imageDescs.length; _e7++) { var _n3 = t.globalData.imageDescs[_e7]; _i3.setUint32(20 + 5 * _e7 * 4 + 0, _n3.imageFlags, !0), _i3.setUint32(20 + 5 * _e7 * 4 + 4, _n3.rgbSliceByteOffset, !0), _i3.setUint32(20 + 5 * _e7 * 4 + 8, _n3.rgbSliceByteLength, !0), _i3.setUint32(20 + 5 * _e7 * 4 + 12, _n3.alphaSliceByteOffset, !0), _i3.setUint32(20 + 5 * _e7 * 4 + 16, _n3.alphaSliceByteLength, !0); } n = Fi([_e6, t.globalData.endpointsData, t.globalData.selectorsData, t.globalData.tablesData, t.globalData.extendedData]); } var i = []; var s = t.keyValue; e.keepWriter || (s = Ci({}, t.keyValue, { KTXwriter: "KTX-Parse v0.3.1" })); for (var _t5 in s) { var _e8 = s[_t5], _n4 = Vi(_t5), _a = "string" == typeof _e8 ? Vi(_e8) : _e8, _r = _n4.byteLength + 1 + _a.byteLength + 1, _o = _r % 4 ? 4 - _r % 4 : 0; i.push(Fi([new Uint32Array([_r]), _n4, Oi, _a, Oi, new Uint8Array(_o).fill(0)])); } var a = Fi(i); if (1 !== t.dataFormatDescriptor.length || 0 !== t.dataFormatDescriptor[0].descriptorType) throw new Error("Only BASICFORMAT Data Format Descriptor output supported."); var r = t.dataFormatDescriptor[0], o = new ArrayBuffer(28 + 16 * r.samples.length), l = new DataView(o), f = 24 + 16 * r.samples.length; if (l.setUint32(0, o.byteLength, !0), l.setUint16(4, r.vendorId, !0), l.setUint16(6, r.descriptorType, !0), l.setUint16(8, r.versionNumber, !0), l.setUint16(10, f, !0), l.setUint8(12, r.colorModel), l.setUint8(13, r.colorPrimaries), l.setUint8(14, r.transferFunction), l.setUint8(15, r.flags), !Array.isArray(r.texelBlockDimension)) throw new Error("texelBlockDimension is now an array. For dimensionality `d`, set `d - 1`."); l.setUint8(16, r.texelBlockDimension[0]), l.setUint8(17, r.texelBlockDimension[1]), l.setUint8(18, r.texelBlockDimension[2]), l.setUint8(19, r.texelBlockDimension[3]); for (var _t6 = 0; _t6 < 8; _t6++) l.setUint8(20 + _t6, r.bytesPlane[_t6]); for (var _t7 = 0; _t7 < r.samples.length; _t7++) { var _e9 = r.samples[_t7], _n5 = 28 + 16 * _t7; if (_e9.channelID) throw new Error("channelID has been renamed to channelType."); l.setUint16(_n5 + 0, _e9.bitOffset, !0), l.setUint8(_n5 + 2, _e9.bitLength), l.setUint8(_n5 + 3, _e9.channelType), l.setUint8(_n5 + 4, _e9.samplePosition[0]), l.setUint8(_n5 + 5, _e9.samplePosition[1]), l.setUint8(_n5 + 6, _e9.samplePosition[2]), l.setUint8(_n5 + 7, _e9.samplePosition[3]), 64 & _e9.channelType ? (l.setInt32(_n5 + 8, _e9.sampleLower, !0), l.setInt32(_n5 + 12, _e9.sampleUpper, !0)) : (l.setUint32(_n5 + 8, _e9.sampleLower, !0), l.setUint32(_n5 + 12, _e9.sampleUpper, !0)); } var U = Ti.length + 68 + 3 * t.levels.length * 8, c = U + o.byteLength; var h = n.byteLength > 0 ? c + a.byteLength : 0; h % 8 && (h += 8 - h % 8); var _ = [], p = new DataView(new ArrayBuffer(3 * t.levels.length * 8)); var g = (h || c + a.byteLength) + n.byteLength; for (var _e10 = 0; _e10 < t.levels.length; _e10++) { var _n6 = t.levels[_e10]; _.push(_n6.levelData), p.setBigUint64(24 * _e10 + 0, BigInt(g), !0), p.setBigUint64(24 * _e10 + 8, BigInt(_n6.levelData.byteLength), !0), p.setBigUint64(24 * _e10 + 16, BigInt(_n6.uncompressedByteLength), !0), g += _n6.levelData.byteLength; } var y = new ArrayBuffer(68), x = new DataView(y); return x.setUint32(0, t.vkFormat, !0), x.setUint32(4, t.typeSize, !0), x.setUint32(8, t.pixelWidth, !0), x.setUint32(12, t.pixelHeight, !0), x.setUint32(16, t.pixelDepth, !0), x.setUint32(20, t.layerCount, !0), x.setUint32(24, t.faceCount, !0), x.setUint32(28, t.levels.length, !0), x.setUint32(32, t.supercompressionScheme, !0), x.setUint32(36, U, !0), x.setUint32(40, o.byteLength, !0), x.setUint32(44, c, !0), x.setUint32(48, a.byteLength, !0), x.setBigUint64(52, BigInt(n.byteLength > 0 ? h : 0), !0), x.setBigUint64(60, BigInt(n.byteLength), !0), new Uint8Array(Fi([new Uint8Array(Ti).buffer, y, p.buffer, o, a, h > 0 ? new ArrayBuffer(h - (c + a.byteLength)) : new ArrayBuffer(0), n, ..._])); } /** * @author Don McCurdy / https://www.donmccurdy.com */ var init, instance, heap; var importObject = { env: { emscripten_notify_memory_growth: function emscripten_notify_memory_growth(index) { heap = new Uint8Array(instance.exports.memory.buffer); } } }; /** * ZSTD (Zstandard) decoder. * * Compiled from https://github.com/facebook/zstd/tree/dev/contrib/single_file_libs, with the * following steps: * * ``` * ./combine.sh -r ../../lib -o zstddeclib.c zstddeclib-in.c * emcc zstddeclib.c -Oz -s EXPORTED_FUNCTIONS="['_ZSTD_decompress', '_ZSTD_findDecompressedSize', '_ZSTD_isError', '_malloc', '_free']" -s ALLOW_MEMORY_GROWTH=1 -s MALLOC=emmalloc -o zstddec.wasm * base64 zstddec.wasm > zstddec.txt * ``` * * The base64 string written to `zstddec.txt` is embedded as the `wasm` variable at the bottom * of this file. The rest of this file is written by hand, in order to avoid an additional JS * wrapper generated by Emscripten. */ class ZSTDDecoder { init() { if (!init) { init = fetch('data:application/wasm;base64,' + wasm).then(response => response.arrayBuffer()).then(arrayBuffer => WebAssembly.instantiate(arrayBuffer, importObject)).then(result => { instance = result.instance; importObject.env.emscripten_notify_memory_growth(0); // initialize heap. }); } return init; } decode(array) { var uncompressedSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; // Write compressed data into WASM memory. var compressedSize = array.byteLength; var compressedPtr = instance.exports.malloc(compressedSize); heap.set(array, compressedPtr); // Decompress into WASM memory. uncompressedSize = uncompressedSize || Number(instance.exports.ZSTD_findDecompressedSize(compressedPtr, compressedSize)); var uncompressedPtr = instance.exports.malloc(uncompressedSize); var actualSize = instance.exports.ZSTD_decompress(uncompressedPtr, uncompressedSize, compressedPtr, compressedSize); // Read decompressed data and free WASM memory. var dec = heap.slice(uncompressedPtr, uncompressedPtr + actualSize); instance.exports.free(compressedPtr); instance.exports.free(uncompressedPtr); return dec; } } /** * BSD License * * For Zstandard software * * Copyright (c) 2016-present, Yann Collet, Facebook, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name Facebook nor the names of its contributors may be used to * endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ var wasm = 'AGFzbQEAAAABpQEVYAF/AX9gAn9/AGADf39/AX9gBX9/f39/AX9gAX8AYAJ/fwF/YAR/f39/AX9gA39/fwBgBn9/f39/fwF/YAd/f39/f39/AX9gAn9/AX5gAn5+AX5gAABgBX9/f39/AGAGf39/f39/AGAIf39/f39/f38AYAl/f39/f39/f38AYAABf2AIf39/f39/f38Bf2ANf39/f39/f39/f39/fwF/YAF/AX4CJwEDZW52H2Vtc2NyaXB0ZW5fbm90aWZ5X21lbW9yeV9ncm93dGgABANpaAEFAAAFAgEFCwACAQABAgIFBQcAAwABDgsBAQcAEhMHAAUBDAQEAAANBwQCAgYCBAgDAwMDBgEACQkHBgICAAYGAgQUBwYGAwIGAAMCAQgBBwUGCgoEEQAEBAEIAwgDBQgDEA8IAAcABAUBcAECAgUEAQCAAgYJAX8BQaCgwAILB2AHBm1lbW9yeQIABm1hbGxvYwAoBGZyZWUAJgxaU1REX2lzRXJyb3IAaBlaU1REX2ZpbmREZWNvbXByZXNzZWRTaXplAFQPWlNURF9kZWNvbXByZXNzAEoGX3N0YXJ0ACQJBwEAQQELASQKussBaA8AIAAgACgCBCABajYCBAsZACAAKAIAIAAoAgRBH3F0QQAgAWtBH3F2CwgAIABBiH9LC34BBH9BAyEBIAAoAgQiA0EgTQRAIAAoAggiASAAKAIQTwRAIAAQDQ8LIAAoAgwiAiABRgRAQQFBAiADQSBJGw8LIAAgASABIAJrIANBA3YiBCABIARrIAJJIgEbIgJrIgQ2AgggACADIAJBA3RrNgIEIAAgBCgAADYCAAsgAQsUAQF/IAAgARACIQIgACABEAEgAgv3AQECfyACRQRAIABCADcCACAAQQA2AhAgAEIANwIIQbh/DwsgACABNgIMIAAgAUEEajYCECACQQRPBEAgACABIAJqIgFBfGoiAzYCCCAAIAMoAAA2AgAgAUF/ai0AACIBBEAgAEEIIAEQFGs2AgQgAg8LIABBADYCBEF/DwsgACABNgIIIAAgAS0AACIDNgIAIAJBfmoiBEEBTQRAIARBAWtFBEAgACABLQACQRB0IANyIgM2AgALIAAgAS0AAUEIdCADajYCAAsgASACakF/ai0AACIBRQRAIABBADYCBEFsDwsgAEEoIAEQFCACQQN0ams2AgQgAgsWACAAIAEpAAA3AAAgACABKQAINwAICy8BAX8gAUECdEGgHWooAgAgACgCAEEgIAEgACgCBGprQR9xdnEhAiAAIAEQASACCyEAIAFCz9bTvtLHq9lCfiAAfEIfiUKHla+vmLbem55/fgsdAQF/IAAoAgggACgCDEYEfyAAKAIEQSBGBUEACwuCBAEDfyACQYDAAE8EQCAAIAEgAhBnIAAPCyAAIAJqIQMCQCAAIAFzQQNxRQRAAkAgAkEBSARAIAAhAgwBCyAAQQNxRQRAIAAhAgwBCyAAIQIDQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADTw0BIAJBA3ENAAsLAkAgA0F8cSIEQcAASQ0AIAIgBEFAaiIFSw0AA0AgAiABKAIANgIAIAIgASgCBDYCBCACIAEoAgg2AgggAiABKAIMNgIMIAIgASgCEDYCECACIAEoAhQ2AhQgAiABKAIYNgIYIAIgASgCHDYCHCACIAEoAiA2AiAgAiABKAIkNgIkIAIgASgCKDYCKCACIAEoAiw2AiwgAiABKAIwNgIwIAIgASgCNDYCNCACIAEoAjg2AjggAiABKAI8NgI8IAFBQGshASACQUBrIgIgBU0NAAsLIAIgBE8NAQNAIAIgASgCADYCACABQQRqIQEgAkEEaiICIARJDQALDAELIANBBEkEQCAAIQIMAQsgA0F8aiIEIABJBEAgACECDAELIAAhAgNAIAIgAS0AADoAACACIAEtAAE6AAEgAiABLQACOgACIAIgAS0AAzoAAyABQQRqIQEgAkEEaiICIARNDQALCyACIANJBEADQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADRw0ACwsgAAsMACAAIAEpAAA3AAALQQECfyAAKAIIIgEgACgCEEkEQEEDDwsgACAAKAIEIgJBB3E2AgQgACABIAJBA3ZrIgE2AgggACABKAAANgIAQQALDAAgACABKAIANgAAC/cCAQJ/AkAgACABRg0AAkAgASACaiAASwRAIAAgAmoiBCABSw0BCyAAIAEgAhALDwsgACABc0EDcSEDAkACQCAAIAFJBEAgAwRAIAAhAwwDCyAAQQNxRQRAIAAhAwwCCyAAIQMDQCACRQ0EIAMgAS0AADoAACABQQFqIQEgAkF/aiECIANBAWoiA0EDcQ0ACwwBCwJAIAMNACAEQQNxBEADQCACRQ0FIAAgAkF/aiICaiIDIAEgAmotAAA6AAAgA0EDcQ0ACwsgAkEDTQ0AA0AgACACQXxqIgJqIAEgAmooAgA2AgAgAkEDSw0ACwsgAkUNAgNAIAAgAkF/aiICaiABIAJqLQAAOgAAIAINAAsMAgsgAkEDTQ0AIAIhBANAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIARBfGoiBEEDSw0ACyACQQNxIQILIAJFDQADQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASACQX9qIgINAAsLIAAL8wICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIEayICQSBJDQAgAa0iBUIghiAFhCEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCyAACy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAIajYCACADCy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAFajYCACADCx8AIAAgASACKAIEEAg2AgAgARAEGiAAIAJBCGo2AgQLCAAgAGdBH3MLugUBDX8jAEEQayIKJAACfyAEQQNNBEAgCkEANgIMIApBDGogAyAEEAsaIAAgASACIApBDGpBBBAVIgBBbCAAEAMbIAAgACAESxsMAQsgAEEAIAEoAgBBAXRBAmoQECENQVQgAygAACIGQQ9xIgBBCksNABogAiAAQQVqNgIAIAMgBGoiAkF8aiEMIAJBeWohDiACQXtqIRAgAEEGaiELQQQhBSAGQQR2IQRBICAAdCIAQQFyIQkgASgCACEPQQAhAiADIQYCQANAIAlBAkggAiAPS3JFBEAgAiEHAkAgCARAA0AgBEH//wNxQf//A0YEQCAHQRhqIQcgBiAQSQR/IAZBAmoiBigAACAFdgUgBUEQaiEFIARBEHYLIQQMAQsLA0AgBEEDcSIIQQNGBEAgBUECaiEFIARBAnYhBCAHQQNqIQcMAQsLIAcgCGoiByAPSw0EIAVBAmohBQNAIAIgB0kEQCANIAJBAXRqQQA7AQAgAkEBaiECDAELCyAGIA5LQQAgBiAFQQN1aiIHIAxLG0UEQCAHKAAAIAVBB3EiBXYhBAwCCyAEQQJ2IQQLIAYhBwsCfyALQX9qIAQgAEF/anEiBiAAQQF0QX9qIgggCWsiEUkNABogBCAIcSIEQQAgESAEIABIG2shBiALCyEIIA0gAkEBdGogBkF/aiIEOwEAIAlBASAGayAEIAZBAUgbayEJA0AgCSAASARAIABBAXUhACALQX9qIQsMAQsLAn8gByAOS0EAIAcgBSAIaiIFQQN1aiIGIAxLG0UEQCAFQQdxDAELIAUgDCIGIAdrQQN0awshBSACQQFqIQIgBEUhCCAGKAAAIAVBH3F2IQQMAQsLQWwgCUEBRyAFQSBKcg0BGiABIAJBf2o2AgAgBiAFQQdqQQN1aiADawwBC0FQCyEAIApBEGokACAACwkAQQFBBSAAGwsMACAAIAEoAAA2AAALqgMBCn8jAEHwAGsiCiQAIAJBAWohDiAAQQhqIQtBgIAEIAVBf2p0QRB1IQxBACECQQEhBkEBIAV0IglBf2oiDyEIA0AgAiAORkUEQAJAIAEgAkEBdCINai8BACIHQf//A0YEQCALIAhBA3RqIAI2AgQgCEF/aiEIQQEhBwwBCyAGQQAgDCAHQRB0QRB1ShshBgsgCiANaiAHOwEAIAJBAWohAgwBCwsgACAFNgIEIAAgBjYCACAJQQN2IAlBAXZqQQNqIQxBACEAQQAhBkEAIQIDQCAGIA5GBEADQAJAIAAgCUYNACAKIAsgAEEDdGoiASgCBCIGQQF0aiICIAIvAQAiAkEBajsBACABIAUgAhAUayIIOgADIAEgAiAIQf8BcXQgCWs7AQAgASAEIAZBAnQiAmooAgA6AAIgASACIANqKAIANgIEIABBAWohAAwBCwsFIAEgBkEBdGouAQAhDUEAIQcDQCAHIA1ORQRAIAsgAkEDdGogBjYCBANAIAIgDGogD3EiAiAISw0ACyAHQQFqIQcMAQsLIAZBAWohBgwBCwsgCkHwAGokAAsjAEIAIAEQCSAAhUKHla+vmLbem55/fkLj3MqV/M7y9YV/fAsQACAAQn43AwggACABNgIACyQBAX8gAARAIAEoAgQiAgRAIAEoAgggACACEQEADwsgABAmCwsfACAAIAEgAi8BABAINgIAIAEQBBogACACQQRqNgIEC0oBAX9BoCAoAgAiASAAaiIAQX9MBEBBiCBBMDYCAEF/DwsCQCAAPwBBEHRNDQAgABBmDQBBiCBBMDYCAEF/DwtBoCAgADYCACABC9cBAQh/Qbp/IQoCQCACKAIEIgggAigCACIJaiIOIAEgAGtLDQBBbCEKIAkgBCADKAIAIgtrSw0AIAAgCWoiBCACKAIIIgxrIQ0gACABQWBqIg8gCyAJQQAQKSADIAkgC2o2AgACQAJAIAwgBCAFa00EQCANIQUMAQsgDCAEIAZrSw0CIAcgDSAFayIAaiIBIAhqIAdNBEAgBCABIAgQDxoMAgsgBCABQQAgAGsQDyEBIAIgACAIaiIINgIEIAEgAGshBAsgBCAPIAUgCEEBECkLIA4hCgsgCgubAgEBfyMAQYABayINJAAgDSADNgJ8AkAgAkEDSwRAQX8hCQwBCwJAAkACQAJAIAJBAWsOAwADAgELIAZFBEBBuH8hCQwEC0FsIQkgBS0AACICIANLDQMgACAHIAJBAnQiAmooAgAgAiAIaigCABA7IAEgADYCAEEBIQkMAwsgASAJNgIAQQAhCQwCCyAKRQRAQWwhCQwCC0EAIQkgC0UgDEEZSHINAUEIIAR0QQhqIQBBACECA0AgAiAATw0CIAJBQGshAgwAAAsAC0FsIQkgDSANQfwAaiANQfgAaiAFIAYQFSICEAMNACANKAJ4IgMgBEsNACAAIA0gDSgCfCAHIAggAxAYIAEgADYCACACIQkLIA1BgAFqJAAgCQsLACAAIAEgAhALGgsQACAALwAAIAAtAAJBEHRyCy8AAn9BuH8gAUEISQ0AGkFyIAAoAAQiAEF3Sw0AGkG4fyAAQQhqIgAgACABSxsLCwkAIAAgATsAAAsDAAELigYBBX8gACAAKAIAIgVBfnE2AgBBACAAIAVBAXZqQYQgKAIAIgQgAEYbIQECQAJAIAAoAgQiAkUNACACKAIAIgNBAXENACACQQhqIgUgA0EBdkF4aiIDQQggA0EISxtnQR9zQQJ0QYAfaiIDKAIARgRAIAMgAigCDDYCAAsgAigCCCIDBEAgAyACKAIMNgIECyACKAIMIgMEQCADIAIoAgg2AgALIAIgAigCACAAKAIAQX5xajYCAEGEICEAAkACQCABRQ0AIAEgAjYCBCABKAIAIgNBAXENASADQQF2QXhqIgNBCCADQQhLG2dBH3NBAnRBgB9qIgMoAgAgAUEIakYEQCADIAEoAgw2AgALIAEoAggiAwRAIAMgASgCDDYCBAsgASgCDCIDBEAgAyABKAIINgIAQYQgKAIAIQQLIAIgAigCACABKAIAQX5xajYCACABIARGDQAgASABKAIAQQF2akEEaiEACyAAIAI2AgALIAIoAgBBAXZBeGoiAEEIIABBCEsbZ0Efc0ECdEGAH2oiASgCACEAIAEgBTYCACACIAA2AgwgAkEANgIIIABFDQEgACAFNgIADwsCQCABRQ0AIAEoAgAiAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAigCACABQQhqRgRAIAIgASgCDDYCAAsgASgCCCICBEAgAiABKAIMNgIECyABKAIMIgIEQCACIAEoAgg2AgBBhCAoAgAhBAsgACAAKAIAIAEoAgBBfnFqIgI2AgACQCABIARHBEAgASABKAIAQQF2aiAANgIEIAAoAgAhAgwBC0GEICAANgIACyACQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgIoAgAhASACIABBCGoiAjYCACAAIAE2AgwgAEEANgIIIAFFDQEgASACNgIADwsgBUEBdkF4aiIBQQggAUEISxtnQR9zQQJ0QYAfaiICKAIAIQEgAiAAQQhqIgI2AgAgACABNgIMIABBADYCCCABRQ0AIAEgAjYCAAsLDgAgAARAIABBeGoQJQsLgAIBA38CQCAAQQ9qQXhxQYQgKAIAKAIAQQF2ayICEB1Bf0YNAAJAQYQgKAIAIgAoAgAiAUEBcQ0AIAFBAXZBeGoiAUEIIAFBCEsbZ0Efc0ECdEGAH2oiASgCACAAQQhqRgRAIAEgACgCDDYCAAsgACgCCCIBBEAgASAAKAIMNgIECyAAKAIMIgFFDQAgASAAKAIINgIAC0EBIQEgACAAKAIAIAJBAXRqIgI2AgAgAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAygCACECIAMgAEEIaiIDNgIAIAAgAjYCDCAAQQA2AgggAkUNACACIAM2AgALIAELtwIBA38CQAJAIABBASAAGyICEDgiAA0AAkACQEGEICgCACIARQ0AIAAoAgAiA0EBcQ0AIAAgA0EBcjYCACADQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgAgAEEIakYEQCABIAAoAgw2AgALIAAoAggiAQRAIAEgACgCDDYCBAsgACgCDCIBBEAgASAAKAIINgIACyACECchAkEAIQFBhCAoAgAhACACDQEgACAAKAIAQX5xNgIAQQAPCyACQQ9qQXhxIgMQHSICQX9GDQIgAkEHakF4cSIAIAJHBEAgACACaxAdQX9GDQMLAkBBhCAoAgAiAUUEQEGAICAANgIADAELIAAgATYCBAtBhCAgADYCACAAIANBAXRBAXI2AgAMAQsgAEUNAQsgAEEIaiEBCyABC7kDAQJ/IAAgA2ohBQJAIANBB0wEQANAIAAgBU8NAiAAIAItAAA6AAAgAEEBaiEAIAJBAWohAgwAAAsACyAEQQFGBEACQCAAIAJrIgZBB00EQCAAIAItAAA6AAAgACACLQABOgABIAAgAi0AAjoAAiAAIAItAAM6AAMgAEEEaiACIAZBAnQiBkHAHmooAgBqIgIQFyACIAZB4B5qKAIAayECDAELIAAgAhAMCyACQQhqIQIgAEEIaiEACwJAAkACQAJAIAUgAU0EQCAAIANqIQEgBEEBRyAAIAJrQQ9Kcg0BA0AgACACEAwgAkEIaiECIABBCGoiACABSQ0ACwwFCyAAIAFLBEAgACEBDAQLIARBAUcgACACa0EPSnINASAAIQMgAiEEA0AgAyAEEAwgBEEIaiEEIANBCGoiAyABSQ0ACwwCCwNAIAAgAhAHIAJBEGohAiAAQRBqIgAgAUkNAAsMAwsgACEDIAIhBANAIAMgBBAHIARBEGohBCADQRBqIgMgAUkNAAsLIAIgASAAa2ohAgsDQCABIAVPDQEgASACLQAAOgAAIAFBAWohASACQQFqIQIMAAALAAsLQQECfyAAIAAoArjgASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+OABIABCADcDuOABIABBwOABakIANwMAIABBqNAAaiIBQYyAgOAANgIAIABBADYCmOIBIABCADcDiOEBIABCAzcDgOEBIABBrNABakHgEikCADcCACAAQbTQAWpB6BIoAgA2AgAgACABNgIMIAAgAEGYIGo2AgggACAAQaAwajYCBCAAIABBEGo2AgALYQEBf0G4fyEDAkAgAUEDSQ0AIAIgABAhIgFBA3YiADYCCCACIAFBAXE2AgQgAiABQQF2QQNxIgM2AgACQCADQX9qIgFBAksNAAJAIAFBAWsOAgEAAgtBbA8LIAAhAwsgAwsMACAAIAEgAkEAEC4LiAQCA38CfiADEBYhBCAAQQBBKBAQIQAgBCACSwRAIAQPCyABRQRAQX8PCwJAAkAgA0EBRg0AIAEoAAAiBkGo6r5pRg0AQXYhAyAGQXBxQdDUtMIBRw0BQQghAyACQQhJDQEgAEEAQSgQECEAIAEoAAQhASAAQQE2AhQgACABrTcDAEEADwsgASACIAMQLyIDIAJLDQAgACADNgIYQXIhAyABIARqIgVBf2otAAAiAkEIcQ0AIAJBIHEiBkUEQEFwIQMgBS0AACIFQacBSw0BIAVBB3GtQgEgBUEDdkEKaq2GIgdCA4h+IAd8IQggBEEBaiEECyACQQZ2IQMgAkECdiEFAkAgAkEDcUF/aiICQQJLBEBBACECDAELAkACQAJAIAJBAWsOAgECAAsgASAEai0AACECIARBAWohBAwCCyABIARqLwAAIQIgBEECaiEEDAELIAEgBGooAAAhAiAEQQRqIQQLIAVBAXEhBQJ+AkACQAJAIANBf2oiA0ECTQRAIANBAWsOAgIDAQtCfyAGRQ0DGiABIARqMQAADAMLIAEgBGovAACtQoACfAwCCyABIARqKAAArQwBCyABIARqKQAACyEHIAAgBTYCICAAIAI2AhwgACAHNwMAQQAhAyAAQQA2AhQgACAHIAggBhsiBzcDCCAAIAdCgIAIIAdCgIAIVBs+AhALIAMLWwEBf0G4fyEDIAIQFiICIAFNBH8gACACakF/ai0AACIAQQNxQQJ0QaAeaigCACACaiAAQQZ2IgFBAnRBsB5qKAIAaiAAQSBxIgBFaiABRSAAQQV2cWoFQbh/CwsdACAAKAKQ4gEQWiAAQQA2AqDiASAAQgA3A5DiAQu1AwEFfyMAQZACayIKJABBuH8hBgJAIAVFDQAgBCwAACIIQf8BcSEHAkAgCEF/TARAIAdBgn9qQQF2IgggBU8NAkFsIQYgB0GBf2oiBUGAAk8NAiAEQQFqIQdBACEGA0AgBiAFTwRAIAUhBiAIIQcMAwUgACAGaiAHIAZBAXZqIgQtAABBBHY6AAAgACAGQQFyaiAELQAAQQ9xOgAAIAZBAmohBgwBCwAACwALIAcgBU8NASAAIARBAWogByAKEFMiBhADDQELIAYhBEEAIQYgAUEAQTQQECEJQQAhBQNAIAQgBkcEQCAAIAZqIggtAAAiAUELSwRAQWwhBgwDBSAJIAFBAnRqIgEgASgCAEEBajYCACAGQQFqIQZBASAILQAAdEEBdSAFaiEFDAILAAsLQWwhBiAFRQ0AIAUQFEEBaiIBQQxLDQAgAyABNgIAQQFBASABdCAFayIDEBQiAXQgA0cNACAAIARqIAFBAWoiADoAACAJIABBAnRqIgAgACgCAEEBajYCACAJKAIEIgBBAkkgAEEBcXINACACIARBAWo2AgAgB0EBaiEGCyAKQZACaiQAIAYLxhEBDH8jAEHwAGsiBSQAQWwhCwJAIANBCkkNACACLwAAIQogAi8AAiEJIAIvAAQhByAFQQhqIAQQDgJAIAMgByAJIApqakEGaiIMSQ0AIAUtAAohCCAFQdgAaiACQQZqIgIgChAGIgsQAw0BIAVBQGsgAiAKaiICIAkQBiILEAMNASAFQShqIAIgCWoiAiAHEAYiCxADDQEgBUEQaiACIAdqIAMgDGsQBiILEAMNASAAIAFqIg9BfWohECAEQQRqIQZBASELIAAgAUEDakECdiIDaiIMIANqIgIgA2oiDiEDIAIhBCAMIQcDQCALIAMgEElxBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgCS0AAyELIAcgBiAFQUBrIAgQAkECdGoiCS8BADsAACAFQUBrIAktAAIQASAJLQADIQogBCAGIAVBKGogCBACQQJ0aiIJLwEAOwAAIAVBKGogCS0AAhABIAktAAMhCSADIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgDS0AAyENIAAgC2oiCyAGIAVB2ABqIAgQAkECdGoiAC8BADsAACAFQdgAaiAALQACEAEgAC0AAyEAIAcgCmoiCiAGIAVBQGsgCBACQQJ0aiIHLwEAOwAAIAVBQGsgBy0AAhABIActAAMhByAEIAlqIgkgBiAFQShqIAgQAkECdGoiBC8BADsAACAFQShqIAQtAAIQASAELQADIQQgAyANaiIDIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgACALaiEAIAcgCmohByAEIAlqIQQgAyANLQADaiEDIAVB2ABqEA0gBUFAaxANciAFQShqEA1yIAVBEGoQDXJFIQsMAQsLIAQgDksgByACS3INAEFsIQsgACAMSw0BIAxBfWohCQNAQQAgACAJSSAFQdgAahAEGwRAIAAgBiAFQdgAaiAIEAJBAnRqIgovAQA7AAAgBUHYAGogCi0AAhABIAAgCi0AA2oiACAGIAVB2ABqIAgQAkECdGoiCi8BADsAACAFQdgAaiAKLQACEAEgACAKLQADaiEADAEFIAxBfmohCgNAIAVB2ABqEAQgACAKS3JFBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgACAJLQADaiEADAELCwNAIAAgCk0EQCAAIAYgBUHYAGogCBACQQJ0aiIJLwEAOwAAIAVB2ABqIAktAAIQASAAIAktAANqIQAMAQsLAkAgACAMTw0AIAAgBiAFQdgAaiAIEAIiAEECdGoiDC0AADoAACAMLQADQQFGBEAgBUHYAGogDC0AAhABDAELIAUoAlxBH0sNACAFQdgAaiAGIABBAnRqLQACEAEgBSgCXEEhSQ0AIAVBIDYCXAsgAkF9aiEMA0BBACAHIAxJIAVBQGsQBBsEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiIAIAYgBUFAayAIEAJBAnRqIgcvAQA7AAAgBUFAayAHLQACEAEgACAHLQADaiEHDAEFIAJBfmohDANAIAVBQGsQBCAHIAxLckUEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwNAIAcgDE0EQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwJAIAcgAk8NACAHIAYgBUFAayAIEAIiAEECdGoiAi0AADoAACACLQADQQFGBEAgBUFAayACLQACEAEMAQsgBSgCREEfSw0AIAVBQGsgBiAAQQJ0ai0AAhABIAUoAkRBIUkNACAFQSA2AkQLIA5BfWohAgNAQQAgBCACSSAFQShqEAQbBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2oiACAGIAVBKGogCBACQQJ0aiIELwEAOwAAIAVBKGogBC0AAhABIAAgBC0AA2ohBAwBBSAOQX5qIQIDQCAFQShqEAQgBCACS3JFBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsDQCAEIAJNBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsCQCAEIA5PDQAgBCAGIAVBKGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBKGogAi0AAhABDAELIAUoAixBH0sNACAFQShqIAYgAEECdGotAAIQASAFKAIsQSFJDQAgBUEgNgIsCwNAQQAgAyAQSSAFQRBqEAQbBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2oiACAGIAVBEGogCBACQQJ0aiICLwEAOwAAIAVBEGogAi0AAhABIAAgAi0AA2ohAwwBBSAPQX5qIQIDQCAFQRBqEAQgAyACS3JFBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsDQCADIAJNBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsCQCADIA9PDQAgAyAGIAVBEGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBEGogAi0AAhABDAELIAUoAhRBH0sNACAFQRBqIAYgAEECdGotAAIQASAFKAIUQSFJDQAgBUEgNgIUCyABQWwgBUHYAGoQCiAFQUBrEApxIAVBKGoQCnEgBUEQahAKcRshCwwJCwAACwALAAALAAsAAAsACwAACwALQWwhCwsgBUHwAGokACALC7UEAQ5/IwBBEGsiBiQAIAZBBGogABAOQVQhBQJAIARB3AtJDQAgBi0ABCEHIANB8ARqQQBB7AAQECEIIAdBDEsNACADQdwJaiIJIAggBkEIaiAGQQxqIAEgAhAxIhAQA0UEQCAGKAIMIgQgB0sNASADQdwFaiEPIANBpAVqIREgAEEEaiESIANBqAVqIQEgBCEFA0AgBSICQX9qIQUgCCACQQJ0aigCAEUNAAsgAkEBaiEOQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgASALaiAKNgIAIAVBAWohBSAKIAxqIQoMAQsLIAEgCjYCAEEAIQUgBigCCCELA0AgBSALRkUEQCABIAUgCWotAAAiDEECdGoiDSANKAIAIg1BAWo2AgAgDyANQQF0aiINIAw6AAEgDSAFOgAAIAVBAWohBQwBCwtBACEBIANBADYCqAUgBEF/cyAHaiEJQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgAyALaiABNgIAIAwgBSAJanQgAWohASAFQQFqIQUMAQsLIAcgBEEBaiIBIAJrIgRrQQFqIQgDQEEBIQUgBCAIT0UEQANAIAUgDk9FBEAgBUECdCIJIAMgBEE0bGpqIAMgCWooAgAgBHY2AgAgBUEBaiEFDAELCyAEQQFqIQQMAQsLIBIgByAPIAogESADIAIgARBkIAZBAToABSAGIAc6AAYgACAGKAIENgIACyAQIQULIAZBEGokACAFC8ENAQt/IwBB8ABrIgUkAEFsIQkCQCADQQpJDQAgAi8AACEKIAIvAAIhDCACLwAEIQYgBUEIaiAEEA4CQCADIAYgCiAMampBBmoiDUkNACAFLQAKIQcgBUHYAGogAkEGaiICIAoQBiIJEAMNASAFQUBrIAIgCmoiAiAMEAYiCRADDQEgBUEoaiACIAxqIgIgBhAGIgkQAw0BIAVBEGogAiAGaiADIA1rEAYiCRADDQEgACABaiIOQX1qIQ8gBEEEaiEGQQEhCSAAIAFBA2pBAnYiAmoiCiACaiIMIAJqIg0hAyAMIQQgCiECA0AgCSADIA9JcQRAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAACAGIAVBQGsgBxACQQF0aiIILQAAIQsgBUFAayAILQABEAEgAiALOgAAIAYgBUEoaiAHEAJBAXRqIggtAAAhCyAFQShqIAgtAAEQASAEIAs6AAAgBiAFQRBqIAcQAkEBdGoiCC0AACELIAVBEGogCC0AARABIAMgCzoAACAGIAVB2ABqIAcQAkEBdGoiCC0AACELIAVB2ABqIAgtAAEQASAAIAs6AAEgBiAFQUBrIAcQAkEBdGoiCC0AACELIAVBQGsgCC0AARABIAIgCzoAASAGIAVBKGogBxACQQF0aiIILQAAIQsgBUEoaiAILQABEAEgBCALOgABIAYgBUEQaiAHEAJBAXRqIggtAAAhCyAFQRBqIAgtAAEQASADIAs6AAEgA0ECaiEDIARBAmohBCACQQJqIQIgAEECaiEAIAkgBUHYAGoQDUVxIAVBQGsQDUVxIAVBKGoQDUVxIAVBEGoQDUVxIQkMAQsLIAQgDUsgAiAMS3INAEFsIQkgACAKSw0BIApBfWohCQNAIAVB2ABqEAQgACAJT3JFBEAgBiAFQdgAaiAHEAJBAXRqIggtAAAhCyAFQdgAaiAILQABEAEgACALOgAAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAASAAQQJqIQAMAQsLA0AgBUHYAGoQBCAAIApPckUEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCwNAIAAgCkkEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCyAMQX1qIQADQCAFQUBrEAQgAiAAT3JFBEAgBiAFQUBrIAcQAkEBdGoiCi0AACEJIAVBQGsgCi0AARABIAIgCToAACAGIAVBQGsgBxACQQF0aiIKLQAAIQkgBUFAayAKLQABEAEgAiAJOgABIAJBAmohAgwBCwsDQCAFQUBrEAQgAiAMT3JFBEAgBiAFQUBrIAcQAkEBdGoiAC0AACEKIAVBQGsgAC0AARABIAIgCjoAACACQQFqIQIMAQsLA0AgAiAMSQRAIAYgBUFAayAHEAJBAXRqIgAtAAAhCiAFQUBrIAAtAAEQASACIAo6AAAgAkEBaiECDAELCyANQX1qIQADQCAFQShqEAQgBCAAT3JFBEAgBiAFQShqIAcQAkEBdGoiAi0AACEKIAVBKGogAi0AARABIAQgCjoAACAGIAVBKGogBxACQQF0aiICLQAAIQogBUEoaiACLQABEAEgBCAKOgABIARBAmohBAwBCwsDQCAFQShqEAQgBCANT3JFBEAgBiAFQShqIAcQAkEBdGoiAC0AACECIAVBKGogAC0AARABIAQgAjoAACAEQQFqIQQMAQsLA0AgBCANSQRAIAYgBUEoaiAHEAJBAXRqIgAtAAAhAiAFQShqIAAtAAEQASAEIAI6AAAgBEEBaiEEDAELCwNAIAVBEGoQBCADIA9PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIAYgBUEQaiAHEAJBAXRqIgAtAAAhAiAFQRBqIAAtAAEQASADIAI6AAEgA0ECaiEDDAELCwNAIAVBEGoQBCADIA5PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIANBAWohAwwBCwsDQCADIA5JBEAgBiAFQRBqIAcQAkEBdGoiAC0AACECIAVBEGogAC0AARABIAMgAjoAACADQQFqIQMMAQsLIAFBbCAFQdgAahAKIAVBQGsQCnEgBUEoahAKcSAFQRBqEApxGyEJDAELQWwhCQsgBUHwAGokACAJC8oCAQR/IwBBIGsiBSQAIAUgBBAOIAUtAAIhByAFQQhqIAIgAxAGIgIQA0UEQCAEQQRqIQIgACABaiIDQX1qIQQDQCAFQQhqEAQgACAET3JFBEAgAiAFQQhqIAcQAkEBdGoiBi0AACEIIAVBCGogBi0AARABIAAgCDoAACACIAVBCGogBxACQQF0aiIGLQAAIQggBUEIaiAGLQABEAEgACAIOgABIABBAmohAAwBCwsDQCAFQQhqEAQgACADT3JFBEAgAiAFQQhqIAcQAkEBdGoiBC0AACEGIAVBCGogBC0AARABIAAgBjoAACAAQQFqIQAMAQsLA0AgACADT0UEQCACIAVBCGogBxACQQF0aiIELQAAIQYgBUEIaiAELQABEAEgACAGOgAAIABBAWohAAwBCwsgAUFsIAVBCGoQChshAgsgBUEgaiQAIAILtgMBCX8jAEEQayIGJAAgBkEANgIMIAZBADYCCEFUIQQCQAJAIANBQGsiDCADIAZBCGogBkEMaiABIAIQMSICEAMNACAGQQRqIAAQDiAGKAIMIgcgBi0ABEEBaksNASAAQQRqIQogBkEAOgAFIAYgBzoABiAAIAYoAgQ2AgAgB0EBaiEJQQEhBANAIAQgCUkEQCADIARBAnRqIgEoAgAhACABIAU2AgAgACAEQX9qdCAFaiEFIARBAWohBAwBCwsgB0EBaiEHQQAhBSAGKAIIIQkDQCAFIAlGDQEgAyAFIAxqLQAAIgRBAnRqIgBBASAEdEEBdSILIAAoAgAiAWoiADYCACAHIARrIQhBACEEAkAgC0EDTQRAA0AgBCALRg0CIAogASAEakEBdGoiACAIOgABIAAgBToAACAEQQFqIQQMAAALAAsDQCABIABPDQEgCiABQQF0aiIEIAg6AAEgBCAFOgAAIAQgCDoAAyAEIAU6AAIgBCAIOgAFIAQgBToABCAEIAg6AAcgBCAFOgAGIAFBBGohAQwAAAsACyAFQQFqIQUMAAALAAsgAiEECyAGQRBqJAAgBAutAQECfwJAQYQgKAIAIABHIAAoAgBBAXYiAyABa0F4aiICQXhxQQhHcgR/IAIFIAMQJ0UNASACQQhqC0EQSQ0AIAAgACgCACICQQFxIAAgAWpBD2pBeHEiASAAa0EBdHI2AgAgASAANgIEIAEgASgCAEEBcSAAIAJBAXZqIAFrIgJBAXRyNgIAQYQgIAEgAkH/////B3FqQQRqQYQgKAIAIABGGyABNgIAIAEQJQsLygIBBX8CQAJAAkAgAEEIIABBCEsbZ0EfcyAAaUEBR2oiAUEESSAAIAF2cg0AIAFBAnRB/B5qKAIAIgJFDQADQCACQXhqIgMoAgBBAXZBeGoiBSAATwRAIAIgBUEIIAVBCEsbZ0Efc0ECdEGAH2oiASgCAEYEQCABIAIoAgQ2AgALDAMLIARBHksNASAEQQFqIQQgAigCBCICDQALC0EAIQMgAUEgTw0BA0AgAUECdEGAH2ooAgAiAkUEQCABQR5LIQIgAUEBaiEBIAJFDQEMAwsLIAIgAkF4aiIDKAIAQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgBGBEAgASACKAIENgIACwsgAigCACIBBEAgASACKAIENgIECyACKAIEIgEEQCABIAIoAgA2AgALIAMgAygCAEEBcjYCACADIAAQNwsgAwvhCwINfwV+IwBB8ABrIgckACAHIAAoAvDhASIINgJcIAEgAmohDSAIIAAoAoDiAWohDwJAAkAgBUUEQCABIQQMAQsgACgCxOABIRAgACgCwOABIREgACgCvOABIQ4gAEEBNgKM4QFBACEIA0AgCEEDRwRAIAcgCEECdCICaiAAIAJqQazQAWooAgA2AkQgCEEBaiEIDAELC0FsIQwgB0EYaiADIAQQBhADDQEgB0EsaiAHQRhqIAAoAgAQEyAHQTRqIAdBGGogACgCCBATIAdBPGogB0EYaiAAKAIEEBMgDUFgaiESIAEhBEEAIQwDQCAHKAIwIAcoAixBA3RqKQIAIhRCEIinQf8BcSEIIAcoAkAgBygCPEEDdGopAgAiFUIQiKdB/wFxIQsgBygCOCAHKAI0QQN0aikCACIWQiCIpyEJIBVCIIghFyAUQiCIpyECAkAgFkIQiKdB/wFxIgNBAk8EQAJAIAZFIANBGUlyRQRAIAkgB0EYaiADQSAgBygCHGsiCiAKIANLGyIKEAUgAyAKayIDdGohCSAHQRhqEAQaIANFDQEgB0EYaiADEAUgCWohCQwBCyAHQRhqIAMQBSAJaiEJIAdBGGoQBBoLIAcpAkQhGCAHIAk2AkQgByAYNwNIDAELAkAgA0UEQCACBEAgBygCRCEJDAMLIAcoAkghCQwBCwJAAkAgB0EYakEBEAUgCSACRWpqIgNBA0YEQCAHKAJEQX9qIgMgA0VqIQkMAQsgA0ECdCAHaigCRCIJIAlFaiEJIANBAUYNAQsgByAHKAJINgJMCwsgByAHKAJENgJIIAcgCTYCRAsgF6chAyALBEAgB0EYaiALEAUgA2ohAwsgCCALakEUTwRAIAdBGGoQBBoLIAgEQCAHQRhqIAgQBSACaiECCyAHQRhqEAQaIAcgB0EYaiAUQhiIp0H/AXEQCCAUp0H//wNxajYCLCAHIAdBGGogFUIYiKdB/wFxEAggFadB//8DcWo2AjwgB0EYahAEGiAHIAdBGGogFkIYiKdB/wFxEAggFqdB//8DcWo2AjQgByACNgJgIAcoAlwhCiAHIAk2AmggByADNgJkAkACQAJAIAQgAiADaiILaiASSw0AIAIgCmoiEyAPSw0AIA0gBGsgC0Egak8NAQsgByAHKQNoNwMQIAcgBykDYDcDCCAEIA0gB0EIaiAHQdwAaiAPIA4gESAQEB4hCwwBCyACIARqIQggBCAKEAcgAkERTwRAIARBEGohAgNAIAIgCkEQaiIKEAcgAkEQaiICIAhJDQALCyAIIAlrIQIgByATNgJcIAkgCCAOa0sEQCAJIAggEWtLBEBBbCELDAILIBAgAiAOayICaiIKIANqIBBNBEAgCCAKIAMQDxoMAgsgCCAKQQAgAmsQDyEIIAcgAiADaiIDNgJkIAggAmshCCAOIQILIAlBEE8EQCADIAhqIQMDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALDAELAkAgCUEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgCUECdCIDQcAeaigCAGoiAhAXIAIgA0HgHmooAgBrIQIgBygCZCEDDAELIAggAhAMCyADQQlJDQAgAyAIaiEDIAhBCGoiCCACQQhqIgJrQQ9MBEADQCAIIAIQDCACQQhqIQIgCEEIaiIIIANJDQAMAgALAAsDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALCyAHQRhqEAQaIAsgDCALEAMiAhshDCAEIAQgC2ogAhshBCAFQX9qIgUNAAsgDBADDQFBbCEMIAdBGGoQBEECSQ0BQQAhCANAIAhBA0cEQCAAIAhBAnQiAmpBrNABaiACIAdqKAJENgIAIAhBAWohCAwBCwsgBygCXCEIC0G6fyEMIA8gCGsiACANIARrSw0AIAQEfyAEIAggABALIABqBUEACyABayEMCyAHQfAAaiQAIAwLkRcCFn8FfiMAQdABayIHJAAgByAAKALw4QEiCDYCvAEgASACaiESIAggACgCgOIBaiETAkACQCAFRQRAIAEhAwwBCyAAKALE4AEhESAAKALA4AEhFSAAKAK84AEhDyAAQQE2AozhAUEAIQgDQCAIQQNHBEAgByAIQQJ0IgJqIAAgAmpBrNABaigCADYCVCAIQQFqIQgMAQsLIAcgETYCZCAHIA82AmAgByABIA9rNgJoQWwhECAHQShqIAMgBBAGEAMNASAFQQQgBUEESBshFyAHQTxqIAdBKGogACgCABATIAdBxABqIAdBKGogACgCCBATIAdBzABqIAdBKGogACgCBBATQQAhBCAHQeAAaiEMIAdB5ABqIQoDQCAHQShqEARBAksgBCAXTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEJIAcoAkggBygCREEDdGopAgAiH0IgiKchCCAeQiCIISAgHUIgiKchAgJAIB9CEIinQf8BcSIDQQJPBEACQCAGRSADQRlJckUEQCAIIAdBKGogA0EgIAcoAixrIg0gDSADSxsiDRAFIAMgDWsiA3RqIQggB0EoahAEGiADRQ0BIAdBKGogAxAFIAhqIQgMAQsgB0EoaiADEAUgCGohCCAHQShqEAQaCyAHKQJUISEgByAINgJUIAcgITcDWAwBCwJAIANFBEAgAgRAIAcoAlQhCAwDCyAHKAJYIQgMAQsCQAJAIAdBKGpBARAFIAggAkVqaiIDQQNGBEAgBygCVEF/aiIDIANFaiEIDAELIANBAnQgB2ooAlQiCCAIRWohCCADQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAg2AlQLICCnIQMgCQRAIAdBKGogCRAFIANqIQMLIAkgC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgAmohAgsgB0EoahAEGiAHIAcoAmggAmoiCSADajYCaCAKIAwgCCAJSxsoAgAhDSAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogB0EoaiAfQhiIp0H/AXEQCCEOIAdB8ABqIARBBHRqIgsgCSANaiAIazYCDCALIAg2AgggCyADNgIEIAsgAjYCACAHIA4gH6dB//8DcWo2AkQgBEEBaiEEDAELCyAEIBdIDQEgEkFgaiEYIAdB4ABqIRogB0HkAGohGyABIQMDQCAHQShqEARBAksgBCAFTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEIIAcoAkggBygCREEDdGopAgAiH0IgiKchCSAeQiCIISAgHUIgiKchDAJAIB9CEIinQf8BcSICQQJPBEACQCAGRSACQRlJckUEQCAJIAdBKGogAkEgIAcoAixrIgogCiACSxsiChAFIAIgCmsiAnRqIQkgB0EoahAEGiACRQ0BIAdBKGogAhAFIAlqIQkMAQsgB0EoaiACEAUgCWohCSAHQShqEAQaCyAHKQJUISEgByAJNgJUIAcgITcDWAwBCwJAIAJFBEAgDARAIAcoAlQhCQwDCyAHKAJYIQkMAQsCQAJAIAdBKGpBARAFIAkgDEVqaiICQQNGBEAgBygCVEF/aiICIAJFaiEJDAELIAJBAnQgB2ooAlQiCSAJRWohCSACQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAk2AlQLICCnIRQgCARAIAdBKGogCBAFIBRqIRQLIAggC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgDGohDAsgB0EoahAEGiAHIAcoAmggDGoiGSAUajYCaCAbIBogCSAZSxsoAgAhHCAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogByAHQShqIB9CGIinQf8BcRAIIB+nQf//A3FqNgJEIAcgB0HwAGogBEEDcUEEdGoiDSkDCCIdNwPIASAHIA0pAwAiHjcDwAECQAJAAkAgBygCvAEiDiAepyICaiIWIBNLDQAgAyAHKALEASIKIAJqIgtqIBhLDQAgEiADayALQSBqTw0BCyAHIAcpA8gBNwMQIAcgBykDwAE3AwggAyASIAdBCGogB0G8AWogEyAPIBUgERAeIQsMAQsgAiADaiEIIAMgDhAHIAJBEU8EQCADQRBqIQIDQCACIA5BEGoiDhAHIAJBEGoiAiAISQ0ACwsgCCAdpyIOayECIAcgFjYCvAEgDiAIIA9rSwRAIA4gCCAVa0sEQEFsIQsMAgsgESACIA9rIgJqIhYgCmogEU0EQCAIIBYgChAPGgwCCyAIIBZBACACaxAPIQggByACIApqIgo2AsQBIAggAmshCCAPIQILIA5BEE8EQCAIIApqIQoDQCAIIAIQByACQRBqIQIgCEEQaiIIIApJDQALDAELAkAgDkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgDkECdCIKQcAeaigCAGoiAhAXIAIgCkHgHmooAgBrIQIgBygCxAEhCgwBCyAIIAIQDAsgCkEJSQ0AIAggCmohCiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAKSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAKSQ0ACwsgCxADBEAgCyEQDAQFIA0gDDYCACANIBkgHGogCWs2AgwgDSAJNgIIIA0gFDYCBCAEQQFqIQQgAyALaiEDDAILAAsLIAQgBUgNASAEIBdrIQtBACEEA0AgCyAFSARAIAcgB0HwAGogC0EDcUEEdGoiAikDCCIdNwPIASAHIAIpAwAiHjcDwAECQAJAAkAgBygCvAEiDCAepyICaiIKIBNLDQAgAyAHKALEASIJIAJqIhBqIBhLDQAgEiADayAQQSBqTw0BCyAHIAcpA8gBNwMgIAcgBykDwAE3AxggAyASIAdBGGogB0G8AWogEyAPIBUgERAeIRAMAQsgAiADaiEIIAMgDBAHIAJBEU8EQCADQRBqIQIDQCACIAxBEGoiDBAHIAJBEGoiAiAISQ0ACwsgCCAdpyIGayECIAcgCjYCvAEgBiAIIA9rSwRAIAYgCCAVa0sEQEFsIRAMAgsgESACIA9rIgJqIgwgCWogEU0EQCAIIAwgCRAPGgwCCyAIIAxBACACaxAPIQggByACIAlqIgk2AsQBIAggAmshCCAPIQILIAZBEE8EQCAIIAlqIQYDQCAIIAIQByACQRBqIQIgCEEQaiIIIAZJDQALDAELAkAgBkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgBkECdCIGQcAeaigCAGoiAhAXIAIgBkHgHmooAgBrIQIgBygCxAEhCQwBCyAIIAIQDAsgCUEJSQ0AIAggCWohBiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAGSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAGSQ0ACwsgEBADDQMgC0EBaiELIAMgEGohAwwBCwsDQCAEQQNHBEAgACAEQQJ0IgJqQazQAWogAiAHaigCVDYCACAEQQFqIQQMAQsLIAcoArwBIQgLQbp/IRAgEyAIayIAIBIgA2tLDQAgAwR/IAMgCCAAEAsgAGoFQQALIAFrIRALIAdB0AFqJAAgEAslACAAQgA3AgAgAEEAOwEIIABBADoACyAAIAE2AgwgACACOgAKC7QFAQN/IwBBMGsiBCQAIABB/wFqIgVBfWohBgJAIAMvAQIEQCAEQRhqIAEgAhAGIgIQAw0BIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahASOgAAIAMgBEEIaiAEQRhqEBI6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0FIAEgBEEQaiAEQRhqEBI6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBSABIARBCGogBEEYahASOgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEjoAACABIAJqIABrIQIMAwsgAyAEQRBqIARBGGoQEjoAAiADIARBCGogBEEYahASOgADIANBBGohAwwAAAsACyAEQRhqIAEgAhAGIgIQAw0AIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahAROgAAIAMgBEEIaiAEQRhqEBE6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0EIAEgBEEQaiAEQRhqEBE6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBCABIARBCGogBEEYahAROgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEToAACABIAJqIABrIQIMAgsgAyAEQRBqIARBGGoQEToAAiADIARBCGogBEEYahAROgADIANBBGohAwwAAAsACyAEQTBqJAAgAgtpAQF/An8CQAJAIAJBB00NACABKAAAQbfIwuF+Rw0AIAAgASgABDYCmOIBQWIgAEEQaiABIAIQPiIDEAMNAhogAEKBgICAEDcDiOEBIAAgASADaiACIANrECoMAQsgACABIAIQKgtBAAsLrQMBBn8jAEGAAWsiAyQAQWIhCAJAIAJBCUkNACAAQZjQAGogAUEIaiIEIAJBeGogAEGY0AAQMyIFEAMiBg0AIANBHzYCfCADIANB/ABqIANB+ABqIAQgBCAFaiAGGyIEIAEgAmoiAiAEaxAVIgUQAw0AIAMoAnwiBkEfSw0AIAMoAngiB0EJTw0AIABBiCBqIAMgBkGAC0GADCAHEBggA0E0NgJ8IAMgA0H8AGogA0H4AGogBCAFaiIEIAIgBGsQFSIFEAMNACADKAJ8IgZBNEsNACADKAJ4IgdBCk8NACAAQZAwaiADIAZBgA1B4A4gBxAYIANBIzYCfCADIANB/ABqIANB+ABqIAQgBWoiBCACIARrEBUiBRADDQAgAygCfCIGQSNLDQAgAygCeCIHQQpPDQAgACADIAZBwBBB0BEgBxAYIAQgBWoiBEEMaiIFIAJLDQAgAiAFayEFQQAhAgNAIAJBA0cEQCAEKAAAIgZBf2ogBU8NAiAAIAJBAnRqQZzQAWogBjYCACACQQFqIQIgBEEEaiEEDAELCyAEIAFrIQgLIANBgAFqJAAgCAtGAQN/IABBCGohAyAAKAIEIQJBACEAA0AgACACdkUEQCABIAMgAEEDdGotAAJBFktqIQEgAEEBaiEADAELCyABQQggAmt0C4YDAQV/Qbh/IQcCQCADRQ0AIAItAAAiBEUEQCABQQA2AgBBAUG4fyADQQFGGw8LAn8gAkEBaiIFIARBGHRBGHUiBkF/Sg0AGiAGQX9GBEAgA0EDSA0CIAUvAABBgP4BaiEEIAJBA2oMAQsgA0ECSA0BIAItAAEgBEEIdHJBgIB+aiEEIAJBAmoLIQUgASAENgIAIAVBAWoiASACIANqIgNLDQBBbCEHIABBEGogACAFLQAAIgVBBnZBI0EJIAEgAyABa0HAEEHQEUHwEiAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBmCBqIABBCGogBUEEdkEDcUEfQQggASABIAZqIAgbIgEgAyABa0GAC0GADEGAFyAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBoDBqIABBBGogBUECdkEDcUE0QQkgASABIAZqIAgbIgEgAyABa0GADUHgDkGQGSAAKAKM4QEgACgCnOIBIAQQHyIAEAMNACAAIAFqIAJrIQcLIAcLrQMBCn8jAEGABGsiCCQAAn9BUiACQf8BSw0AGkFUIANBDEsNABogAkEBaiELIABBBGohCUGAgAQgA0F/anRBEHUhCkEAIQJBASEEQQEgA3QiB0F/aiIMIQUDQCACIAtGRQRAAkAgASACQQF0Ig1qLwEAIgZB//8DRgRAIAkgBUECdGogAjoAAiAFQX9qIQVBASEGDAELIARBACAKIAZBEHRBEHVKGyEECyAIIA1qIAY7AQAgAkEBaiECDAELCyAAIAQ7AQIgACADOwEAIAdBA3YgB0EBdmpBA2ohBkEAIQRBACECA0AgBCALRkUEQCABIARBAXRqLgEAIQpBACEAA0AgACAKTkUEQCAJIAJBAnRqIAQ6AAIDQCACIAZqIAxxIgIgBUsNAAsgAEEBaiEADAELCyAEQQFqIQQMAQsLQX8gAg0AGkEAIQIDfyACIAdGBH9BAAUgCCAJIAJBAnRqIgAtAAJBAXRqIgEgAS8BACIBQQFqOwEAIAAgAyABEBRrIgU6AAMgACABIAVB/wFxdCAHazsBACACQQFqIQIMAQsLCyEFIAhBgARqJAAgBQvjBgEIf0FsIQcCQCACQQNJDQACQAJAAkACQCABLQAAIgNBA3EiCUEBaw4DAwEAAgsgACgCiOEBDQBBYg8LIAJBBUkNAkEDIQYgASgAACEFAn8CQAJAIANBAnZBA3EiCEF+aiIEQQFNBEAgBEEBaw0BDAILIAVBDnZB/wdxIQQgBUEEdkH/B3EhAyAIRQwCCyAFQRJ2IQRBBCEGIAVBBHZB//8AcSEDQQAMAQsgBUEEdkH//w9xIgNBgIAISw0DIAEtAARBCnQgBUEWdnIhBEEFIQZBAAshBSAEIAZqIgogAksNAgJAIANBgQZJDQAgACgCnOIBRQ0AQQAhAgNAIAJBg4ABSw0BIAJBQGshAgwAAAsACwJ/IAlBA0YEQCABIAZqIQEgAEHw4gFqIQIgACgCDCEGIAUEQCACIAMgASAEIAYQXwwCCyACIAMgASAEIAYQXQwBCyAAQbjQAWohAiABIAZqIQEgAEHw4gFqIQYgAEGo0ABqIQggBQRAIAggBiADIAEgBCACEF4MAQsgCCAGIAMgASAEIAIQXAsQAw0CIAAgAzYCgOIBIABBATYCiOEBIAAgAEHw4gFqNgLw4QEgCUECRgRAIAAgAEGo0ABqNgIMCyAAIANqIgBBiOMBakIANwAAIABBgOMBakIANwAAIABB+OIBakIANwAAIABB8OIBakIANwAAIAoPCwJ/AkACQAJAIANBAnZBA3FBf2oiBEECSw0AIARBAWsOAgACAQtBASEEIANBA3YMAgtBAiEEIAEvAABBBHYMAQtBAyEEIAEQIUEEdgsiAyAEaiIFQSBqIAJLBEAgBSACSw0CIABB8OIBaiABIARqIAMQCyEBIAAgAzYCgOIBIAAgATYC8OEBIAEgA2oiAEIANwAYIABCADcAECAAQgA3AAggAEIANwAAIAUPCyAAIAM2AoDiASAAIAEgBGo2AvDhASAFDwsCfwJAAkACQCADQQJ2QQNxQX9qIgRBAksNACAEQQFrDgIAAgELQQEhByADQQN2DAILQQIhByABLwAAQQR2DAELIAJBBEkgARAhIgJBj4CAAUtyDQFBAyEHIAJBBHYLIQIgAEHw4gFqIAEgB2otAAAgAkEgahAQIQEgACACNgKA4gEgACABNgLw4QEgB0EBaiEHCyAHC0sAIABC+erQ0OfJoeThADcDICAAQgA3AxggAELP1tO+0ser2UI3AxAgAELW64Lu6v2J9eAANwMIIABCADcDACAAQShqQQBBKBAQGgviAgICfwV+IABBKGoiASAAKAJIaiECAn4gACkDACIDQiBaBEAgACkDECIEQgeJIAApAwgiBUIBiXwgACkDGCIGQgyJfCAAKQMgIgdCEol8IAUQGSAEEBkgBhAZIAcQGQwBCyAAKQMYQsXP2bLx5brqJ3wLIAN8IQMDQCABQQhqIgAgAk0EQEIAIAEpAAAQCSADhUIbiUKHla+vmLbem55/fkLj3MqV/M7y9YV/fCEDIAAhAQwBCwsCQCABQQRqIgAgAksEQCABIQAMAQsgASgAAK1Ch5Wvr5i23puef34gA4VCF4lCz9bTvtLHq9lCfkL5893xmfaZqxZ8IQMLA0AgACACSQRAIAAxAABCxc/ZsvHluuonfiADhUILiUKHla+vmLbem55/fiEDIABBAWohAAwBCwsgA0IhiCADhULP1tO+0ser2UJ+IgNCHYggA4VC+fPd8Zn2masWfiIDQiCIIAOFC+8CAgJ/BH4gACAAKQMAIAKtfDcDAAJAAkAgACgCSCIDIAJqIgRBH00EQCABRQ0BIAAgA2pBKGogASACECAgACgCSCACaiEEDAELIAEgAmohAgJ/IAMEQCAAQShqIgQgA2ogAUEgIANrECAgACAAKQMIIAQpAAAQCTcDCCAAIAApAxAgACkAMBAJNwMQIAAgACkDGCAAKQA4EAk3AxggACAAKQMgIABBQGspAAAQCTcDICAAKAJIIQMgAEEANgJIIAEgA2tBIGohAQsgAUEgaiACTQsEQCACQWBqIQMgACkDICEFIAApAxghBiAAKQMQIQcgACkDCCEIA0AgCCABKQAAEAkhCCAHIAEpAAgQCSEHIAYgASkAEBAJIQYgBSABKQAYEAkhBSABQSBqIgEgA00NAAsgACAFNwMgIAAgBjcDGCAAIAc3AxAgACAINwMICyABIAJPDQEgAEEoaiABIAIgAWsiBBAgCyAAIAQ2AkgLCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQEBogAwVBun8LCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQCxogAwVBun8LC6gCAQZ/IwBBEGsiByQAIABB2OABaikDAEKAgIAQViEIQbh/IQUCQCAEQf//B0sNACAAIAMgBBBCIgUQAyIGDQAgACgCnOIBIQkgACAHQQxqIAMgAyAFaiAGGyIKIARBACAFIAYbayIGEEAiAxADBEAgAyEFDAELIAcoAgwhBCABRQRAQbp/IQUgBEEASg0BCyAGIANrIQUgAyAKaiEDAkAgCQRAIABBADYCnOIBDAELAkACQAJAIARBBUgNACAAQdjgAWopAwBCgICACFgNAAwBCyAAQQA2ApziAQwBCyAAKAIIED8hBiAAQQA2ApziASAGQRRPDQELIAAgASACIAMgBSAEIAgQOSEFDAELIAAgASACIAMgBSAEIAgQOiEFCyAHQRBqJAAgBQtnACAAQdDgAWogASACIAAoAuzhARAuIgEQAwRAIAEPC0G4fyECAkAgAQ0AIABB7OABaigCACIBBEBBYCECIAAoApjiASABRw0BC0EAIQIgAEHw4AFqKAIARQ0AIABBkOEBahBDCyACCycBAX8QVyIERQRAQUAPCyAEIAAgASACIAMgBBBLEE8hACAEEFYgAAs/AQF/AkACQAJAIAAoAqDiAUEBaiIBQQJLDQAgAUEBaw4CAAECCyAAEDBBAA8LIABBADYCoOIBCyAAKAKU4gELvAMCB38BfiMAQRBrIgkkAEG4fyEGAkAgBCgCACIIQQVBCSAAKALs4QEiBRtJDQAgAygCACIHQQFBBSAFGyAFEC8iBRADBEAgBSEGDAELIAggBUEDakkNACAAIAcgBRBJIgYQAw0AIAEgAmohCiAAQZDhAWohCyAIIAVrIQIgBSAHaiEHIAEhBQNAIAcgAiAJECwiBhADDQEgAkF9aiICIAZJBEBBuH8hBgwCCyAJKAIAIghBAksEQEFsIQYMAgsgB0EDaiEHAn8CQAJAAkAgCEEBaw4CAgABCyAAIAUgCiAFayAHIAYQSAwCCyAFIAogBWsgByAGEEcMAQsgBSAKIAVrIActAAAgCSgCCBBGCyIIEAMEQCAIIQYMAgsgACgC8OABBEAgCyAFIAgQRQsgAiAGayECIAYgB2ohByAFIAhqIQUgCSgCBEUNAAsgACkD0OABIgxCf1IEQEFsIQYgDCAFIAFrrFINAQsgACgC8OABBEBBaiEGIAJBBEkNASALEEQhDCAHKAAAIAynRw0BIAdBBGohByACQXxqIQILIAMgBzYCACAEIAI2AgAgBSABayEGCyAJQRBqJAAgBgsuACAAECsCf0EAQQAQAw0AGiABRSACRXJFBEBBYiAAIAEgAhA9EAMNARoLQQALCzcAIAEEQCAAIAAoAsTgASABKAIEIAEoAghqRzYCnOIBCyAAECtBABADIAFFckUEQCAAIAEQWwsL0QIBB38jAEEQayIGJAAgBiAENgIIIAYgAzYCDCAFBEAgBSgCBCEKIAUoAgghCQsgASEIAkACQANAIAAoAuzhARAWIQsCQANAIAQgC0kNASADKAAAQXBxQdDUtMIBRgRAIAMgBBAiIgcQAw0EIAQgB2shBCADIAdqIQMMAQsLIAYgAzYCDCAGIAQ2AggCQCAFBEAgACAFEE5BACEHQQAQA0UNAQwFCyAAIAogCRBNIgcQAw0ECyAAIAgQUCAMQQFHQQAgACAIIAIgBkEMaiAGQQhqEEwiByIDa0EAIAMQAxtBCkdyRQRAQbh/IQcMBAsgBxADDQMgAiAHayECIAcgCGohCEEBIQwgBigCDCEDIAYoAgghBAwBCwsgBiADNgIMIAYgBDYCCEG4fyEHIAQNASAIIAFrIQcMAQsgBiADNgIMIAYgBDYCCAsgBkEQaiQAIAcLRgECfyABIAAoArjgASICRwRAIAAgAjYCxOABIAAgATYCuOABIAAoArzgASEDIAAgATYCvOABIAAgASADIAJrajYCwOABCwutAgIEfwF+IwBBQGoiBCQAAkACQCACQQhJDQAgASgAAEFwcUHQ1LTCAUcNACABIAIQIiEBIABCADcDCCAAQQA2AgQgACABNgIADAELIARBGGogASACEC0iAxADBEAgACADEBoMAQsgAwRAIABBuH8QGgwBCyACIAQoAjAiA2shAiABIANqIQMDQAJAIAAgAyACIARBCGoQLCIFEAMEfyAFBSACIAVBA2oiBU8NAUG4fwsQGgwCCyAGQQFqIQYgAiAFayECIAMgBWohAyAEKAIMRQ0ACyAEKAI4BEAgAkEDTQRAIABBuH8QGgwCCyADQQRqIQMLIAQoAighAiAEKQMYIQcgAEEANgIEIAAgAyABazYCACAAIAIgBmytIAcgB0J/URs3AwgLIARBQGskAAslAQF/IwBBEGsiAiQAIAIgACABEFEgAigCACEAIAJBEGokACAAC30BBH8jAEGQBGsiBCQAIARB/wE2AggCQCAEQRBqIARBCGogBEEMaiABIAIQFSIGEAMEQCAGIQUMAQtBVCEFIAQoAgwiB0EGSw0AIAMgBEEQaiAEKAIIIAcQQSIFEAMNACAAIAEgBmogAiAGayADEDwhBQsgBEGQBGokACAFC4cBAgJ/An5BABAWIQMCQANAIAEgA08EQAJAIAAoAABBcHFB0NS0wgFGBEAgACABECIiAhADRQ0BQn4PCyAAIAEQVSIEQn1WDQMgBCAFfCIFIARUIQJCfiEEIAINAyAAIAEQUiICEAMNAwsgASACayEBIAAgAmohAAwBCwtCfiAFIAEbIQQLIAQLPwIBfwF+IwBBMGsiAiQAAn5CfiACQQhqIAAgARAtDQAaQgAgAigCHEEBRg0AGiACKQMICyEDIAJBMGokACADC40BAQJ/IwBBMGsiASQAAkAgAEUNACAAKAKI4gENACABIABB/OEBaigCADYCKCABIAApAvThATcDICAAEDAgACgCqOIBIQIgASABKAIoNgIYIAEgASkDIDcDECACIAFBEGoQGyAAQQA2AqjiASABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALKgECfyMAQRBrIgAkACAAQQA2AgggAEIANwMAIAAQWCEBIABBEGokACABC4cBAQN/IwBBEGsiAiQAAkAgACgCAEUgACgCBEVzDQAgAiAAKAIINgIIIAIgACkCADcDAAJ/IAIoAgAiAQRAIAIoAghBqOMJIAERBQAMAQtBqOMJECgLIgFFDQAgASAAKQIANwL04QEgAUH84QFqIAAoAgg2AgAgARBZIAEhAwsgAkEQaiQAIAMLywEBAn8jAEEgayIBJAAgAEGBgIDAADYCtOIBIABBADYCiOIBIABBADYC7OEBIABCADcDkOIBIABBADYCpOMJIABBADYC3OIBIABCADcCzOIBIABBADYCvOIBIABBADYCxOABIABCADcCnOIBIABBpOIBakIANwIAIABBrOIBakEANgIAIAFCADcCECABQgA3AhggASABKQMYNwMIIAEgASkDEDcDACABKAIIQQh2QQFxIQIgAEEANgLg4gEgACACNgKM4gEgAUEgaiQAC3YBA38jAEEwayIBJAAgAARAIAEgAEHE0AFqIgIoAgA2AiggASAAKQK80AE3AyAgACgCACEDIAEgAigCADYCGCABIAApArzQATcDECADIAFBEGoQGyABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALzAEBAX8gACABKAK00AE2ApjiASAAIAEoAgQiAjYCwOABIAAgAjYCvOABIAAgAiABKAIIaiICNgK44AEgACACNgLE4AEgASgCuNABBEAgAEKBgICAEDcDiOEBIAAgAUGk0ABqNgIMIAAgAUGUIGo2AgggACABQZwwajYCBCAAIAFBDGo2AgAgAEGs0AFqIAFBqNABaigCADYCACAAQbDQAWogAUGs0AFqKAIANgIAIABBtNABaiABQbDQAWooAgA2AgAPCyAAQgA3A4jhAQs7ACACRQRAQbp/DwsgBEUEQEFsDwsgAiAEEGAEQCAAIAEgAiADIAQgBRBhDwsgACABIAIgAyAEIAUQZQtGAQF/IwBBEGsiBSQAIAVBCGogBBAOAn8gBS0ACQRAIAAgASACIAMgBBAyDAELIAAgASACIAMgBBA0CyEAIAVBEGokACAACzQAIAAgAyAEIAUQNiIFEAMEQCAFDwsgBSAESQR/IAEgAiADIAVqIAQgBWsgABA1BUG4fwsLRgEBfyMAQRBrIgUkACAFQQhqIAQQDgJ/IAUtAAkEQCAAIAEgAiADIAQQYgwBCyAAIAEgAiADIAQQNQshACAFQRBqJAAgAAtZAQF/QQ8hAiABIABJBEAgAUEEdCAAbiECCyAAQQh2IgEgAkEYbCIAQYwIaigCAGwgAEGICGooAgBqIgJBA3YgAmogAEGACGooAgAgAEGECGooAgAgAWxqSQs3ACAAIAMgBCAFQYAQEDMiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQMgVBuH8LC78DAQN/IwBBIGsiBSQAIAVBCGogAiADEAYiAhADRQRAIAAgAWoiB0F9aiEGIAUgBBAOIARBBGohAiAFLQACIQMDQEEAIAAgBkkgBUEIahAEGwRAIAAgAiAFQQhqIAMQAkECdGoiBC8BADsAACAFQQhqIAQtAAIQASAAIAQtAANqIgQgAiAFQQhqIAMQAkECdGoiAC8BADsAACAFQQhqIAAtAAIQASAEIAAtAANqIQAMAQUgB0F+aiEEA0AgBUEIahAEIAAgBEtyRQRAIAAgAiAFQQhqIAMQAkECdGoiBi8BADsAACAFQQhqIAYtAAIQASAAIAYtAANqIQAMAQsLA0AgACAES0UEQCAAIAIgBUEIaiADEAJBAnRqIgYvAQA7AAAgBUEIaiAGLQACEAEgACAGLQADaiEADAELCwJAIAAgB08NACAAIAIgBUEIaiADEAIiA0ECdGoiAC0AADoAACAALQADQQFGBEAgBUEIaiAALQACEAEMAQsgBSgCDEEfSw0AIAVBCGogAiADQQJ0ai0AAhABIAUoAgxBIUkNACAFQSA2AgwLIAFBbCAFQQhqEAobIQILCwsgBUEgaiQAIAILkgIBBH8jAEFAaiIJJAAgCSADQTQQCyEDAkAgBEECSA0AIAMgBEECdGooAgAhCSADQTxqIAgQIyADQQE6AD8gAyACOgA+QQAhBCADKAI8IQoDQCAEIAlGDQEgACAEQQJ0aiAKNgEAIARBAWohBAwAAAsAC0EAIQkDQCAGIAlGRQRAIAMgBSAJQQF0aiIKLQABIgtBAnRqIgwoAgAhBCADQTxqIAotAABBCHQgCGpB//8DcRAjIANBAjoAPyADIAcgC2siCiACajoAPiAEQQEgASAKa3RqIQogAygCPCELA0AgACAEQQJ0aiALNgEAIARBAWoiBCAKSQ0ACyAMIAo2AgAgCUEBaiEJDAELCyADQUBrJAALowIBCX8jAEHQAGsiCSQAIAlBEGogBUE0EAsaIAcgBmshDyAHIAFrIRADQAJAIAMgCkcEQEEBIAEgByACIApBAXRqIgYtAAEiDGsiCGsiC3QhDSAGLQAAIQ4gCUEQaiAMQQJ0aiIMKAIAIQYgCyAPTwRAIAAgBkECdGogCyAIIAUgCEE0bGogCCAQaiIIQQEgCEEBShsiCCACIAQgCEECdGooAgAiCEEBdGogAyAIayAHIA4QYyAGIA1qIQgMAgsgCUEMaiAOECMgCUEBOgAPIAkgCDoADiAGIA1qIQggCSgCDCELA0AgBiAITw0CIAAgBkECdGogCzYBACAGQQFqIQYMAAALAAsgCUHQAGokAA8LIAwgCDYCACAKQQFqIQoMAAALAAs0ACAAIAMgBCAFEDYiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQNAVBuH8LCyMAIAA/AEEQdGtB//8DakEQdkAAQX9GBEBBAA8LQQAQAEEBCzsBAX8gAgRAA0AgACABIAJBgCAgAkGAIEkbIgMQCyEAIAFBgCBqIQEgAEGAIGohACACIANrIgINAAsLCwYAIAAQAwsLqBUJAEGICAsNAQAAAAEAAAACAAAAAgBBoAgLswYBAAAAAQAAAAIAAAACAAAAJgAAAIIAAAAhBQAASgAAAGcIAAAmAAAAwAEAAIAAAABJBQAASgAAAL4IAAApAAAALAIAAIAAAABJBQAASgAAAL4IAAAvAAAAygIAAIAAAACKBQAASgAAAIQJAAA1AAAAcwMAAIAAAACdBQAASgAAAKAJAAA9AAAAgQMAAIAAAADrBQAASwAAAD4KAABEAAAAngMAAIAAAABNBgAASwAAAKoKAABLAAAAswMAAIAAAADBBgAATQAAAB8NAABNAAAAUwQAAIAAAAAjCAAAUQAAAKYPAABUAAAAmQQAAIAAAABLCQAAVwAAALESAABYAAAA2gQAAIAAAABvCQAAXQAAACMUAABUAAAARQUAAIAAAABUCgAAagAAAIwUAABqAAAArwUAAIAAAAB2CQAAfAAAAE4QAAB8AAAA0gIAAIAAAABjBwAAkQAAAJAHAACSAAAAAAAAAAEAAAABAAAABQAAAA0AAAAdAAAAPQAAAH0AAAD9AAAA/QEAAP0DAAD9BwAA/Q8AAP0fAAD9PwAA/X8AAP3/AAD9/wEA/f8DAP3/BwD9/w8A/f8fAP3/PwD9/38A/f//AP3//wH9//8D/f//B/3//w/9//8f/f//P/3//38AAAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAB0AAAAeAAAAHwAAAAMAAAAEAAAABQAAAAYAAAAHAAAACAAAAAkAAAAKAAAACwAAAAwAAAANAAAADgAAAA8AAAAQAAAAEQAAABIAAAATAAAAFAAAABUAAAAWAAAAFwAAABgAAAAZAAAAGgAAABsAAAAcAAAAHQAAAB4AAAAfAAAAIAAAACEAAAAiAAAAIwAAACUAAAAnAAAAKQAAACsAAAAvAAAAMwAAADsAAABDAAAAUwAAAGMAAACDAAAAAwEAAAMCAAADBAAAAwgAAAMQAAADIAAAA0AAAAOAAAADAAEAQeAPC1EBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAEAAAABQAAAAcAAAAIAAAACQAAAAoAAAALAAAADAAAAA0AAAAOAAAADwAAABAAQcQQC4sBAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABIAAAAUAAAAFgAAABgAAAAcAAAAIAAAACgAAAAwAAAAQAAAAIAAAAAAAQAAAAIAAAAEAAAACAAAABAAAAAgAAAAQAAAAIAAAAAAAQBBkBIL5gQBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAAAEAAAAEAAAACAAAAAAAAAABAAEBBgAAAAAAAAQAAAAAEAAABAAAAAAgAAAFAQAAAAAAAAUDAAAAAAAABQQAAAAAAAAFBgAAAAAAAAUHAAAAAAAABQkAAAAAAAAFCgAAAAAAAAUMAAAAAAAABg4AAAAAAAEFEAAAAAAAAQUUAAAAAAABBRYAAAAAAAIFHAAAAAAAAwUgAAAAAAAEBTAAAAAgAAYFQAAAAAAABwWAAAAAAAAIBgABAAAAAAoGAAQAAAAADAYAEAAAIAAABAAAAAAAAAAEAQAAAAAAAAUCAAAAIAAABQQAAAAAAAAFBQAAACAAAAUHAAAAAAAABQgAAAAgAAAFCgAAAAAAAAULAAAAAAAABg0AAAAgAAEFEAAAAAAAAQUSAAAAIAABBRYAAAAAAAIFGAAAACAAAwUgAAAAAAADBSgAAAAAAAYEQAAAABAABgRAAAAAIAAHBYAAAAAAAAkGAAIAAAAACwYACAAAMAAABAAAAAAQAAAEAQAAACAAAAUCAAAAIAAABQMAAAAgAAAFBQAAACAAAAUGAAAAIAAABQgAAAAgAAAFCQAAACAAAAULAAAAIAAABQwAAAAAAAAGDwAAACAAAQUSAAAAIAABBRQAAAAgAAIFGAAAACAAAgUcAAAAIAADBSgAAAAgAAQFMAAAAAAAEAYAAAEAAAAPBgCAAAAAAA4GAEAAAAAADQYAIABBgBcLhwIBAAEBBQAAAAAAAAUAAAAAAAAGBD0AAAAAAAkF/QEAAAAADwX9fwAAAAAVBf3/HwAAAAMFBQAAAAAABwR9AAAAAAAMBf0PAAAAABIF/f8DAAAAFwX9/38AAAAFBR0AAAAAAAgE/QAAAAAADgX9PwAAAAAUBf3/DwAAAAIFAQAAABAABwR9AAAAAAALBf0HAAAAABEF/f8BAAAAFgX9/z8AAAAEBQ0AAAAQAAgE/QAAAAAADQX9HwAAAAATBf3/BwAAAAEFAQAAABAABgQ9AAAAAAAKBf0DAAAAABAF/f8AAAAAHAX9//8PAAAbBf3//wcAABoF/f//AwAAGQX9//8BAAAYBf3//wBBkBkLhgQBAAEBBgAAAAAAAAYDAAAAAAAABAQAAAAgAAAFBQAAAAAAAAUGAAAAAAAABQgAAAAAAAAFCQAAAAAAAAULAAAAAAAABg0AAAAAAAAGEAAAAAAAAAYTAAAAAAAABhYAAAAAAAAGGQAAAAAAAAYcAAAAAAAABh8AAAAAAAAGIgAAAAAAAQYlAAAAAAABBikAAAAAAAIGLwAAAAAAAwY7AAAAAAAEBlMAAAAAAAcGgwAAAAAACQYDAgAAEAAABAQAAAAAAAAEBQAAACAAAAUGAAAAAAAABQcAAAAgAAAFCQAAAAAAAAUKAAAAAAAABgwAAAAAAAAGDwAAAAAAAAYSAAAAAAAABhUAAAAAAAAGGAAAAAAAAAYbAAAAAAAABh4AAAAAAAAGIQAAAAAAAQYjAAAAAAABBicAAAAAAAIGKwAAAAAAAwYzAAAAAAAEBkMAAAAAAAUGYwAAAAAACAYDAQAAIAAABAQAAAAwAAAEBAAAABAAAAQFAAAAIAAABQcAAAAgAAAFCAAAACAAAAUKAAAAIAAABQsAAAAAAAAGDgAAAAAAAAYRAAAAAAAABhQAAAAAAAAGFwAAAAAAAAYaAAAAAAAABh0AAAAAAAAGIAAAAAAAEAYDAAEAAAAPBgOAAAAAAA4GA0AAAAAADQYDIAAAAAAMBgMQAAAAAAsGAwgAAAAACgYDBABBpB0L2QEBAAAAAwAAAAcAAAAPAAAAHwAAAD8AAAB/AAAA/wAAAP8BAAD/AwAA/wcAAP8PAAD/HwAA/z8AAP9/AAD//wAA//8BAP//AwD//wcA//8PAP//HwD//z8A//9/AP///wD///8B////A////wf///8P////H////z////9/AAAAAAEAAAACAAAABAAAAAAAAAACAAAABAAAAAgAAAAAAAAAAQAAAAIAAAABAAAABAAAAAQAAAAEAAAABAAAAAgAAAAIAAAACAAAAAcAAAAIAAAACQAAAAoAAAALAEGgIAsDwBBQ'; /** * Loader for KTX 2.0 GPU Texture containers. * * KTX 2.0 is a container format for various GPU texture formats. The loader * supports Basis Universal GPU textures, which can be quickly transcoded to * a wide variety of GPU texture compression formats, as well as some * uncompressed DataTexture and Data3DTexture formats. * * References: * - KTX: http://github.khronos.org/KTX-Specification/ * - DFD: https://www.khronos.org/registry/DataFormat/specs/1.3/dataformat.1.3.html#basicdescriptor */ var _taskCache$1 = new WeakMap(); var _activeLoaders = 0; var _zstd; class KTX2Loader extends Loader { constructor(manager) { super(manager); this.transcoderPath = ''; this.transcoderBinary = null; this.transcoderPending = null; this.workerPool = new WorkerPool$1(); this.workerSourceURL = ''; this.workerConfig = null; if (typeof MSC_TRANSCODER !== 'undefined') { console.warn('THREE.KTX2Loader: Please update to latest "basis_transcoder".' + ' "msc_basis_transcoder" is no longer supported in three.js r125+.'); } } setTranscoderPath(path) { this.transcoderPath = path; return this; } setWorkerLimit(num) { this.workerPool.setWorkerLimit(num); return this; } detectSupport(renderer) { this.workerConfig = { astcSupported: renderer.extensions.has('WEBGL_compressed_texture_astc'), etc1Supported: renderer.extensions.has('WEBGL_compressed_texture_etc1'), etc2Supported: renderer.extensions.has('WEBGL_compressed_texture_etc'), dxtSupported: renderer.extensions.has('WEBGL_compressed_texture_s3tc'), bptcSupported: renderer.extensions.has('EXT_texture_compression_bptc'), pvrtcSupported: renderer.extensions.has('WEBGL_compressed_texture_pvrtc') || renderer.extensions.has('WEBKIT_WEBGL_compressed_texture_pvrtc') }; if (renderer.capabilities.isWebGL2) { // https://github.com/mrdoob/three.js/pull/22928 this.workerConfig.etc1Supported = false; } return this; } init() { if (!this.transcoderPending) { // Load transcoder wrapper. var jsLoader = new FileLoader(this.manager); jsLoader.setPath(this.transcoderPath); jsLoader.setWithCredentials(this.withCredentials); var jsContent = jsLoader.loadAsync('basis_transcoder.js'); // Load transcoder WASM binary. var binaryLoader = new FileLoader(this.manager); binaryLoader.setPath(this.transcoderPath); binaryLoader.setResponseType('arraybuffer'); binaryLoader.setWithCredentials(this.withCredentials); var binaryContent = binaryLoader.loadAsync('basis_transcoder.wasm'); this.transcoderPending = Promise.all([jsContent, binaryContent]).then(_ref => { var [jsContent, binaryContent] = _ref; var fn = KTX2Loader.BasisWorker.toString(); var body = ['/* constants */', 'let _EngineFormat = ' + JSON.stringify(KTX2Loader.EngineFormat), 'let _TranscoderFormat = ' + JSON.stringify(KTX2Loader.TranscoderFormat), 'let _BasisFormat = ' + JSON.stringify(KTX2Loader.BasisFormat), '/* basis_transcoder.js */', jsContent, '/* worker */', fn.substring(fn.indexOf('{') + 1, fn.lastIndexOf('}'))].join('\n'); this.workerSourceURL = URL.createObjectURL(new Blob([body])); this.transcoderBinary = binaryContent; this.workerPool.setWorkerCreator(() => { var worker = new Worker(this.workerSourceURL); var transcoderBinary = this.transcoderBinary.slice(0); worker.postMessage({ type: 'init', config: this.workerConfig, transcoderBinary }, [transcoderBinary]); return worker; }); }); if (_activeLoaders > 0) { // Each instance loads a transcoder and allocates workers, increasing network and memory cost. console.warn('THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues.' + ' Use a single KTX2Loader instance, or call .dispose() on old instances.'); } _activeLoaders++; } return this.transcoderPending; } load(url, onLoad, onProgress, onError) { if (this.workerConfig === null) { throw new Error('THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.'); } var loader = new FileLoader(this.manager); loader.setResponseType('arraybuffer'); loader.setWithCredentials(this.withCredentials); loader.load(url, buffer => { // Check for an existing task using this buffer. A transferred buffer cannot be transferred // again from this thread. if (_taskCache$1.has(buffer)) { var cachedTask = _taskCache$1.get(buffer); return cachedTask.promise.then(onLoad).catch(onError); } this._createTexture(buffer).then(texture => onLoad ? onLoad(texture) : null).catch(onError); }, onProgress, onError); } _createTextureFrom(transcodeResult, container) { var { mipmaps, width, height, format, type, error, dfdTransferFn, dfdFlags } = transcodeResult; if (type === 'error') return Promise.reject(error); var texture = container.layerCount > 1 ? new CompressedArrayTexture(mipmaps, width, height, container.layerCount, format, UnsignedByteType) : new CompressedTexture(mipmaps, width, height, format, UnsignedByteType); texture.minFilter = mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter; texture.magFilter = LinearFilter; texture.generateMipmaps = false; texture.needsUpdate = true; texture.encoding = dfdTransferFn === x$2 ? sRGBEncoding : LinearEncoding; texture.premultiplyAlpha = !!(dfdFlags & p); return texture; } /** * @param {ArrayBuffer} buffer * @param {object?} config * @return {Promise} */ async _createTexture(buffer) { var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var container = Pi(new Uint8Array(buffer)); if (container.vkFormat !== nt) { return createDataTexture(container); } // var taskConfig = config; var texturePending = this.init().then(() => { return this.workerPool.postMessage({ type: 'transcode', buffer, taskConfig: taskConfig }, [buffer]); }).then(e => this._createTextureFrom(e.data, container)); // Cache the task result. _taskCache$1.set(buffer, { promise: texturePending }); return texturePending; } dispose() { this.workerPool.dispose(); if (this.workerSourceURL) URL.revokeObjectURL(this.workerSourceURL); _activeLoaders--; return this; } } /* CONSTANTS */ KTX2Loader.BasisFormat = { ETC1S: 0, UASTC_4x4: 1 }; KTX2Loader.TranscoderFormat = { ETC1: 0, ETC2: 1, BC1: 2, BC3: 3, BC4: 4, BC5: 5, BC7_M6_OPAQUE_ONLY: 6, BC7_M5: 7, PVRTC1_4_RGB: 8, PVRTC1_4_RGBA: 9, ASTC_4x4: 10, ATC_RGB: 11, ATC_RGBA_INTERPOLATED_ALPHA: 12, RGBA32: 13, RGB565: 14, BGR565: 15, RGBA4444: 16 }; KTX2Loader.EngineFormat = { RGBAFormat: RGBAFormat, RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format, RGBA_BPTC_Format: RGBA_BPTC_Format, RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format, RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format$1, RGB_ETC1_Format: RGB_ETC1_Format, RGB_ETC2_Format: RGB_ETC2_Format, RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format }; /* WEB WORKER */ KTX2Loader.BasisWorker = function () { var config; var transcoderPending; var BasisModule; var EngineFormat = _EngineFormat; // eslint-disable-line no-undef var TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef var BasisFormat = _BasisFormat; // eslint-disable-line no-undef self.addEventListener('message', function (e) { var message = e.data; switch (message.type) { case 'init': config = message.config; init(message.transcoderBinary); break; case 'transcode': transcoderPending.then(() => { try { var { width, height, hasAlpha, mipmaps, format, dfdTransferFn, dfdFlags } = transcode(message.buffer); var buffers = []; for (var i = 0; i < mipmaps.length; ++i) { buffers.push(mipmaps[i].data.buffer); } self.postMessage({ type: 'transcode', id: message.id, width, height, hasAlpha, mipmaps, format, dfdTransferFn, dfdFlags }, buffers); } catch (error) { console.error(error); self.postMessage({ type: 'error', id: message.id, error: error.message }); } }); break; } }); function init(wasmBinary) { transcoderPending = new Promise(resolve => { BasisModule = { wasmBinary, onRuntimeInitialized: resolve }; BASIS(BasisModule); // eslint-disable-line no-undef }).then(() => { BasisModule.initializeBasis(); if (BasisModule.KTX2File === undefined) { console.warn('THREE.KTX2Loader: Please update Basis Universal transcoder.'); } }); } function transcode(buffer) { var ktx2File = new BasisModule.KTX2File(new Uint8Array(buffer)); function cleanup() { ktx2File.close(); ktx2File.delete(); } if (!ktx2File.isValid()) { cleanup(); throw new Error('THREE.KTX2Loader: Invalid or unsupported .ktx2 file'); } var basisFormat = ktx2File.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S; var width = ktx2File.getWidth(); var height = ktx2File.getHeight(); var layers = ktx2File.getLayers() || 1; var levels = ktx2File.getLevels(); var hasAlpha = ktx2File.getHasAlpha(); var dfdTransferFn = ktx2File.getDFDTransferFunc(); var dfdFlags = ktx2File.getDFDFlags(); var { transcoderFormat, engineFormat } = getTranscoderFormat(basisFormat, width, height, hasAlpha); if (!width || !height || !levels) { cleanup(); throw new Error('THREE.KTX2Loader: Invalid texture'); } if (!ktx2File.startTranscoding()) { cleanup(); throw new Error('THREE.KTX2Loader: .startTranscoding failed'); } var mipmaps = []; for (var mip = 0; mip < levels; mip++) { var layerMips = []; var mipWidth = void 0, mipHeight = void 0; for (var layer = 0; layer < layers; layer++) { var levelInfo = ktx2File.getImageLevelInfo(mip, layer, 0); mipWidth = levelInfo.origWidth; mipHeight = levelInfo.origHeight; var dst = new Uint8Array(ktx2File.getImageTranscodedSizeInBytes(mip, layer, 0, transcoderFormat)); var status = ktx2File.transcodeImage(dst, mip, layer, 0, transcoderFormat, 0, -1, -1); if (!status) { cleanup(); throw new Error('THREE.KTX2Loader: .transcodeImage failed.'); } layerMips.push(dst); } mipmaps.push({ data: concat(layerMips), width: mipWidth, height: mipHeight }); } cleanup(); return { width, height, hasAlpha, mipmaps, format: engineFormat, dfdTransferFn, dfdFlags }; } // // Optimal choice of a transcoder target format depends on the Basis format (ETC1S or UASTC), // device capabilities, and texture dimensions. The list below ranks the formats separately // for ETC1S and UASTC. // // In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at // significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently // chooses RGBA32 only as a last resort and does not expose that option to the caller. var FORMAT_OPTIONS = [{ if: 'astcSupported', basisFormat: [BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4], engineFormat: [EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format], priorityETC1S: Infinity, priorityUASTC: 1, needsPowerOfTwo: false }, { if: 'bptcSupported', basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5], engineFormat: [EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format], priorityETC1S: 3, priorityUASTC: 2, needsPowerOfTwo: false }, { if: 'dxtSupported', basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.BC1, TranscoderFormat.BC3], engineFormat: [EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format], priorityETC1S: 4, priorityUASTC: 5, needsPowerOfTwo: false }, { if: 'etc2Supported', basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.ETC1, TranscoderFormat.ETC2], engineFormat: [EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format], priorityETC1S: 1, priorityUASTC: 3, needsPowerOfTwo: false }, { if: 'etc1Supported', basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.ETC1], engineFormat: [EngineFormat.RGB_ETC1_Format], priorityETC1S: 2, priorityUASTC: 4, needsPowerOfTwo: false }, { if: 'pvrtcSupported', basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA], engineFormat: [EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format], priorityETC1S: 5, priorityUASTC: 6, needsPowerOfTwo: true }]; var ETC1S_OPTIONS = FORMAT_OPTIONS.sort(function (a, b) { return a.priorityETC1S - b.priorityETC1S; }); var UASTC_OPTIONS = FORMAT_OPTIONS.sort(function (a, b) { return a.priorityUASTC - b.priorityUASTC; }); function getTranscoderFormat(basisFormat, width, height, hasAlpha) { var transcoderFormat; var engineFormat; var options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS; for (var i = 0; i < options.length; i++) { var opt = options[i]; if (!config[opt.if]) continue; if (!opt.basisFormat.includes(basisFormat)) continue; if (hasAlpha && opt.transcoderFormat.length < 2) continue; if (opt.needsPowerOfTwo && !(isPowerOfTwo(width) && isPowerOfTwo(height))) continue; transcoderFormat = opt.transcoderFormat[hasAlpha ? 1 : 0]; engineFormat = opt.engineFormat[hasAlpha ? 1 : 0]; return { transcoderFormat, engineFormat }; } console.warn('THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32.'); transcoderFormat = TranscoderFormat.RGBA32; engineFormat = EngineFormat.RGBAFormat; return { transcoderFormat, engineFormat }; } function isPowerOfTwo(value) { if (value <= 2) return true; return (value & value - 1) === 0 && value !== 0; } /** Concatenates N byte arrays. */ function concat(arrays) { var totalByteLength = 0; for (var array of arrays) { totalByteLength += array.byteLength; } var result = new Uint8Array(totalByteLength); var byteOffset = 0; for (var _array of arrays) { result.set(_array, byteOffset); byteOffset += _array.byteLength; } return result; } }; // // DataTexture and Data3DTexture parsing. var FORMAT_MAP = { [Ae]: RGBAFormat, [pe]: RGBAFormat, [Ot]: RGBAFormat, [Ft]: RGBAFormat, [de]: RGFormat, [se]: RGFormat, [yt]: RGFormat, [dt]: RGFormat, [xe]: RedFormat, [$t]: RedFormat, [gt]: RedFormat, [ct]: RedFormat }; var TYPE_MAP = { [Ae]: FloatType, [pe]: HalfFloatType, [Ot]: UnsignedByteType, [Ft]: UnsignedByteType, [de]: FloatType, [se]: HalfFloatType, [yt]: UnsignedByteType, [dt]: UnsignedByteType, [xe]: FloatType, [$t]: HalfFloatType, [gt]: UnsignedByteType, [ct]: UnsignedByteType }; var ENCODING_MAP = { [Ft]: sRGBEncoding, [dt]: sRGBEncoding, [gt]: sRGBEncoding }; async function createDataTexture(container) { var { vkFormat, pixelWidth, pixelHeight, pixelDepth } = container; if (FORMAT_MAP[vkFormat] === undefined) { throw new Error('THREE.KTX2Loader: Unsupported vkFormat.'); } var level = container.levels[0]; var levelData; var view; if (container.supercompressionScheme === t) { levelData = level.levelData; } else if (container.supercompressionScheme === n$1) { if (!_zstd) { _zstd = new Promise(async resolve => { var zstd = new ZSTDDecoder(); await zstd.init(); resolve(zstd); }); } levelData = (await _zstd).decode(level.levelData, level.uncompressedByteLength); } else { throw new Error('THREE.KTX2Loader: Unsupported supercompressionScheme.'); } if (TYPE_MAP[vkFormat] === FloatType) { view = new Float32Array(levelData.buffer, levelData.byteOffset, levelData.byteLength / Float32Array.BYTES_PER_ELEMENT); } else if (TYPE_MAP[vkFormat] === HalfFloatType) { view = new Uint16Array(levelData.buffer, levelData.byteOffset, levelData.byteLength / Uint16Array.BYTES_PER_ELEMENT); } else { view = levelData; } // var texture = pixelDepth === 0 ? new DataTexture(view, pixelWidth, pixelHeight) : new Data3DTexture(view, pixelWidth, pixelHeight, pixelDepth); texture.type = TYPE_MAP[vkFormat]; texture.format = FORMAT_MAP[vkFormat]; texture.encoding = ENCODING_MAP[vkFormat] || LinearEncoding; texture.needsUpdate = true; // return Promise.resolve(texture); } // This file is part of meshoptimizer library and is distributed under the terms of MIT License. // Copyright (C) 2016-2020, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com) var MeshoptDecoder = function () { "use strict"; // Built with clang version 11.0.0 (https://github.com/llvm/llvm-project.git 0160ad802e899c2922bc9b29564080c22eb0908c) // Built from meshoptimizer 0.14 var wasm_base = "B9h9z9tFBBBF8fL9gBB9gLaaaaaFa9gEaaaB9gFaFa9gEaaaFaEMcBFFFGGGEIIILF9wFFFLEFBFKNFaFCx/IFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBF8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBGy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBEn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBIi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBKI9z9iqlBOc+x8ycGBM/qQFTa8jUUUUBCU/EBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAGTkUUUBRNCUoBAG9uC/wgBZHKCUGAKCUG9JyRVAECFJRICBRcGXEXAcAF9PQFAVAFAclAcAVJAF9JyRMGXGXAG9FQBAMCbJHKC9wZRSAKCIrCEJCGrRQANCUGJRfCBRbAIRTEXGXAOATlAQ9PQBCBRISEMATAQJRIGXAS9FQBCBRtCBREEXGXAOAIlCi9PQBCBRISLMANCU/CBJAEJRKGXGXGXGXGXATAECKrJ2BBAtCKZrCEZfIBFGEBMAKhB83EBAKCNJhB83EBSEMAKAI2BIAI2BBHmCKrHYAYCE6HYy86BBAKCFJAICIJAYJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCGJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCEJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCIJAYAmJHY2BBAI2BFHmCKrHPAPCE6HPy86BBAKCLJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCKJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCOJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCNJAYAmJHY2BBAI2BGHmCKrHPAPCE6HPy86BBAKCVJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCcJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCMJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCSJAYAmJHm2BBAI2BEHICKrHYAYCE6HYy86BBAKCQJAmAYJHm2BBAICIrCEZHYAYCE6HYy86BBAKCfJAmAYJHm2BBAICGrCEZHYAYCE6HYy86BBAKCbJAmAYJHK2BBAICEZHIAICE6HIy86BBAKAIJRISGMAKAI2BNAI2BBHmCIrHYAYCb6HYy86BBAKCFJAICNJAYJHY2BBAmCbZHmAmCb6Hmy86BBAKCGJAYAmJHm2BBAI2BFHYCIrHPAPCb6HPy86BBAKCEJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCIJAmAYJHm2BBAI2BGHYCIrHPAPCb6HPy86BBAKCLJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCKJAmAYJHm2BBAI2BEHYCIrHPAPCb6HPy86BBAKCOJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCNJAmAYJHm2BBAI2BIHYCIrHPAPCb6HPy86BBAKCVJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCcJAmAYJHm2BBAI2BLHYCIrHPAPCb6HPy86BBAKCMJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCSJAmAYJHm2BBAI2BKHYCIrHPAPCb6HPy86BBAKCQJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCfJAmAYJHm2BBAI2BOHICIrHYAYCb6HYy86BBAKCbJAmAYJHK2BBAICbZHIAICb6HIy86BBAKAIJRISFMAKAI8pBB83BBAKCNJAICNJ8pBB83BBAICTJRIMAtCGJRtAECTJHEAS9JQBMMGXAIQBCBRISEMGXAM9FQBANAbJ2BBRtCBRKAfREEXAEANCU/CBJAKJ2BBHTCFrCBATCFZl9zAtJHt86BBAEAGJREAKCFJHKAM9HQBMMAfCFJRfAIRTAbCFJHbAG9HQBMMABAcAG9sJANCUGJAMAG9sTkUUUBpANANCUGJAMCaJAG9sJAGTkUUUBpMAMCBAIyAcJRcAIQBMC9+RKSFMCBC99AOAIlAGCAAGCA9Ly6yRKMALCU/EBJ8kUUUUBAKM+OmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUFT+JUUUBpALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM+lLKFaF99GaG99FaG99GXGXAGCI9HQBAF9FQFEXGXGX9DBBB8/9DBBB+/ABCGJHG1BB+yAB1BBHE+yHI+L+TABCFJHL1BBHK+yHO+L+THN9DBBBB9gHVyAN9DBB/+hANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE86BBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG86BBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG86BBABCIJRBAFCaJHFQBSGMMAF9FQBEXGXGX9DBBB8/9DBBB+/ABCIJHG8uFB+yAB8uFBHE+yHI+L+TABCGJHL8uFBHK+yHO+L+THN9DBBBB9gHVyAN9DB/+g6ANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE87FBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG87FBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG87FBABCNJRBAFCaJHFQBMMM/SEIEaE99EaF99GXAF9FQBCBREABRIEXGXGX9D/zI818/AICKJ8uFBHLCEq+y+VHKAI8uFB+y+UHO9DB/+g6+U9DBBB8/9DBBB+/AO9DBBBB9gy+SHN+L9DBBB9P9d9FQBAN+oRVSFMCUUUU94RVMAICIJ8uFBRcAICGJ8uFBRMABALCFJCEZAEqCFWJAV87FBGXGXAKAM+y+UHN9DB/+g6+U9DBBB8/9DBBB+/AN9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRMSFMCUUUU94RMMABALCGJCEZAEqCFWJAM87FBGXGXAKAc+y+UHK9DB/+g6+U9DBBB8/9DBBB+/AK9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRcSFMCUUUU94RcMABALCaJCEZAEqCFWJAc87FBGXGX9DBBU8/AOAO+U+TANAN+U+TAKAK+U+THO9DBBBBAO9DBBBB9gy+R9DB/+g6+U9DBBB8/+SHO+L9DBBB9P9d9FQBAO+oRcSFMCUUUU94RcMABALCEZAEqCFWJAc87FBAICNJRIAECIJREAFCaJHFQBMMM9JBGXAGCGrAF9sHF9FQBEXABAB8oGBHGCNWCN91+yAGCi91CnWCUUU/8EJ+++U84GBABCIJRBAFCaJHFQBMMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEM/lFFFaGXGXAFABqCEZ9FQBABRESFMGXGXAGCT9PQBABRESFMABREEXAEAF8oGBjGBAECIJAFCIJ8oGBjGBAECNJAFCNJ8oGBjGBAECSJAFCSJ8oGBjGBAECTJREAFCTJRFAGC9wJHGCb9LQBMMAGCI9JQBEXAEAF8oGBjGBAFCIJRFAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF2BB86BBAECFJREAFCFJRFAGCaJHGQBMMABMoFFGaGXGXABCEZ9FQBABRESFMAFCgFZC+BwsN9sRIGXGXAGCT9PQBABRESFMABREEXAEAIjGBAECSJAIjGBAECNJAIjGBAECIJAIjGBAECTJREAGC9wJHGCb9LQBMMAGCI9JQBEXAEAIjGBAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF86BBAECFJREAGCaJHGQBMMABMMMFBCUNMIT9kBB"; var wasm_simd = "B9h9z9tFBBBFiI9gBB9gLaaaaaFa9gEaaaB9gFaFaEMcBBFBFFGGGEILF9wFFFLEFBFKNFaFCx/aFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBG8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBIy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBKi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBOn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBNI9z9iqlBVc+N9IcIBTEM9+FLa8jUUUUBCTlRBCBRFEXCBRGCBREEXABCNJAGJAECUaAFAGrCFZHIy86BBAEAIJREAGCFJHGCN9HQBMAFCx+YUUBJAE86BBAFCEWCxkUUBJAB8pEN83EBAFCFJHFCUG9HQBMMk8lLbaE97F9+FaL978jUUUUBCU/KBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAG/8cBBCUoBAG9uC/wgBZHKCUGAKCUG9JyRNAECFJRKCBRVGXEXAVAF9PQFANAFAVlAVANJAF9JyRcGXGXAG9FQBAcCbJHIC9wZHMCE9sRSAMCFWRQAICIrCEJCGrRfCBRbEXAKRTCBRtGXEXGXAOATlAf9PQBCBRKSLMALCU/CBJAtAM9sJRmATAfJRKCBREGXAMCoB9JQBAOAKlC/gB9JQBCBRIEXAmAIJREGXGXGXGXGXATAICKrJ2BBHYCEZfIBFGEBMAECBDtDMIBSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAEAKDBBBDMIBAKCTJRKMGXGXGXGXGXAYCGrCEZfIBFGEBMAECBDtDMITSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAEAKDBBBDMITAKCTJRKMGXGXGXGXGXAYCIrCEZfIBFGEBMAECBDtDMIASEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAEAKDBBBDMIAAKCTJRKMGXGXGXGXGXAYCKrfIBFGEBMAECBDtDMI8wSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCIJAeDeBJAYCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCNJAeDeBJAYCx+YUUBJ2BBJRKSFMAEAKDBBBDMI8wAKCTJRKMAICoBJREAICUFJAM9LQFAERIAOAKlC/fB9LQBMMGXAEAM9PQBAECErRIEXGXAOAKlCi9PQBCBRKSOMAmAEJRYGXGXGXGXGXATAECKrJ2BBAICKZrCEZfIBFGEBMAYCBDtDMIBSEMAYAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAYAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAYAKDBBBDMIBAKCTJRKMAICGJRIAECTJHEAM9JQBMMGXAK9FQBAKRTAtCFJHtCI6QGSFMMCBRKSEMGXAM9FQBALCUGJAbJREALAbJDBGBReCBRYEXAEALCU/CBJAYJHIDBIBHdCFD9tAdCFDbHPD9OD9hD9RHdAIAMJDBIBH8ZCFD9tA8ZAPD9OD9hD9RH8ZDQBTFtGmEYIPLdKeOnHpAIAQJDBIBHyCFD9tAyAPD9OD9hD9RHyAIASJDBIBH8cCFD9tA8cAPD9OD9hD9RH8cDQBTFtGmEYIPLdKeOnH8dDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGEAeD9uHeDyBjGBAEAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJHIAeApA8dDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHeDyBjGBAIAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJHIAeAdA8ZDQNiV8ZcpMyS8cQ8df8eb8fHdAyA8cDQNiV8ZcpMyS8cQ8df8eb8fH8ZDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGED9uHeDyBjGBAIAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJHIAeAdA8ZDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHeDyBjGBAIAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJREAYCTJHYAM9JQBMMAbCIJHbAG9JQBMMABAVAG9sJALCUGJAcAG9s/8cBBALALCUGJAcCaJAG9sJAG/8cBBMAcCBAKyAVJRVAKQBMC9+RKSFMCBC99AOAKlAGCAAGCA9Ly6yRKMALCU/KBJ8kUUUUBAKMNBT+BUUUBM+KmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUF/8MBALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM/dLEK97FaF97GXGXAGCI9HQBAF9FQFCBRGEXABABDBBBHECiD+rFCiD+sFD/6FHIAECND+rFCiD+sFD/6FAID/gFAECTD+rFCiD+sFD/6FHLD/gFD/kFD/lFHKCBDtD+2FHOAICUUUU94DtHND9OD9RD/kFHI9DBB/+hDYAIAID/mFAKAKD/mFALAOALAND9OD9RD/kFHIAID/mFD/kFD/kFD/jFD/nFHLD/mF9DBBX9LDYHOD/kFCgFDtD9OAECUUU94DtD9OD9QAIALD/mFAOD/kFCND+rFCU/+EDtD9OD9QAKALD/mFAOD/kFCTD+rFCUU/8ODtD9OD9QDMBBABCTJRBAGCIJHGAF9JQBSGMMAF9FQBCBRGEXABCTJHVAVDBBBHECBDtHOCUU98D8cFCUU98D8cEHND9OABDBBBHKAEDQILKOSQfbPden8c8d8e8fCggFDtD9OD/6FAKAEDQBFGENVcMTtmYi8ZpyHECTD+sFD/6FHID/gFAECTD+rFCTD+sFD/6FHLD/gFD/kFD/lFHE9DB/+g6DYALAEAOD+2FHOALCUUUU94DtHcD9OD9RD/kFHLALD/mFAEAED/mFAIAOAIAcD9OD9RD/kFHEAED/mFD/kFD/kFD/jFD/nFHID/mF9DBBX9LDYHOD/kFCTD+rFALAID/mFAOD/kFCggEDtD9OD9QHLAEAID/mFAOD/kFCaDbCBDnGCBDnECBDnKCBDnOCBDncCBDnMCBDnfCBDnbD9OHEDQNVi8ZcMpySQ8c8dfb8e8fD9QDMBBABAKAND9OALAEDQBFTtGEmYILPdKOenD9QDMBBABCAJRBAGCIJHGAF9JQBMMM/hEIGaF97FaL978jUUUUBCTlREGXAF9FQBCBRIEXAEABDBBBHLABCTJHKDBBBHODQILKOSQfbPden8c8d8e8fHNCTD+sFHVCID+rFDMIBAB9DBBU8/DY9D/zI818/DYAVCEDtD9QD/6FD/nFHVALAODQBFGENVcMTtmYi8ZpyHLCTD+rFCTD+sFD/6FD/mFHOAOD/mFAVALCTD+sFD/6FD/mFHcAcD/mFAVANCTD+rFCTD+sFD/6FD/mFHNAND/mFD/kFD/kFD/lFCBDtD+4FD/jF9DB/+g6DYHVD/mF9DBBX9LDYHLD/kFCggEDtHMD9OAcAVD/mFALD/kFCTD+rFD9QHcANAVD/mFALD/kFCTD+rFAOAVD/mFALD/kFAMD9OD9QHVDQBFTtGEmYILPdKOenHLD8dBAEDBIBDyB+t+J83EBABCNJALD8dFAEDBIBDyF+t+J83EBAKAcAVDQNVi8ZcMpySQ8c8dfb8e8fHVD8dBAEDBIBDyG+t+J83EBABCiJAVD8dFAEDBIBDyE+t+J83EBABCAJRBAICIJHIAF9JQBMMM9jFF97GXAGCGrAF9sHG9FQBCBRFEXABABDBBBHECND+rFCND+sFD/6FAECiD+sFCnD+rFCUUU/8EDtD+uFD/mFDMBBABCTJRBAFCIJHFAG9JQBMMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEMMMFBCUNMIT9tBB"; // Uses bulk-memory and simd extensions var detector = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 3, 2, 0, 0, 5, 3, 1, 0, 1, 12, 1, 0, 10, 22, 2, 12, 0, 65, 0, 65, 0, 65, 0, 252, 10, 0, 0, 11, 7, 0, 65, 0, 253, 15, 26, 11]); // Used to unpack wasm var wasmpack = new Uint8Array([32, 0, 65, 253, 3, 1, 2, 34, 4, 106, 6, 5, 11, 8, 7, 20, 13, 33, 12, 16, 128, 9, 116, 64, 19, 113, 127, 15, 10, 21, 22, 14, 255, 66, 24, 54, 136, 107, 18, 23, 192, 26, 114, 118, 132, 17, 77, 101, 130, 144, 27, 87, 131, 44, 45, 74, 156, 154, 70, 167]); if (typeof WebAssembly !== 'object') { // This module requires WebAssembly to function return { supported: false }; } var wasm = wasm_base; if (WebAssembly.validate(detector)) { wasm = wasm_simd; console.log("Warning: meshopt_decoder is using experimental SIMD support"); } var instance; var promise = WebAssembly.instantiate(unpack(wasm), {}).then(function (result) { instance = result.instance; instance.exports.__wasm_call_ctors(); }); function unpack(data) { var result = new Uint8Array(data.length); for (var i = 0; i < data.length; ++i) { var ch = data.charCodeAt(i); result[i] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62; } var write = 0; for (var i = 0; i < data.length; ++i) { result[write++] = result[i] < 60 ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i]; } return result.buffer.slice(0, write); } function decode(fun, target, count, size, source, filter) { var sbrk = instance.exports.sbrk; var count4 = count + 3 & ~3; // pad for SIMD filter var tp = sbrk(count4 * size); var sp = sbrk(source.length); var heap = new Uint8Array(instance.exports.memory.buffer); heap.set(source, sp); var res = fun(tp, count, size, sp, source.length); if (res == 0 && filter) { filter(tp, count4, size); } target.set(heap.subarray(tp, tp + count * size)); sbrk(tp - sbrk(0)); if (res != 0) { throw new Error("Malformed buffer data: " + res); } } ; var filters = { // legacy index-based enums for glTF 0: "", 1: "meshopt_decodeFilterOct", 2: "meshopt_decodeFilterQuat", 3: "meshopt_decodeFilterExp", // string-based enums for glTF NONE: "", OCTAHEDRAL: "meshopt_decodeFilterOct", QUATERNION: "meshopt_decodeFilterQuat", EXPONENTIAL: "meshopt_decodeFilterExp" }; var decoders = { // legacy index-based enums for glTF 0: "meshopt_decodeVertexBuffer", 1: "meshopt_decodeIndexBuffer", 2: "meshopt_decodeIndexSequence", // string-based enums for glTF ATTRIBUTES: "meshopt_decodeVertexBuffer", TRIANGLES: "meshopt_decodeIndexBuffer", INDICES: "meshopt_decodeIndexSequence" }; return { ready: promise, supported: true, decodeVertexBuffer: function decodeVertexBuffer(target, count, size, source, filter) { decode(instance.exports.meshopt_decodeVertexBuffer, target, count, size, source, instance.exports[filters[filter]]); }, decodeIndexBuffer: function decodeIndexBuffer(target, count, size, source) { decode(instance.exports.meshopt_decodeIndexBuffer, target, count, size, source); }, decodeIndexSequence: function decodeIndexSequence(target, count, size, source) { decode(instance.exports.meshopt_decodeIndexSequence, target, count, size, source); }, decodeGltfBuffer: function decodeGltfBuffer(target, count, size, source, mode, filter) { decode(instance.exports[decoders[mode]], target, count, size, source, instance.exports[filters[filter]]); } }; }(); var DDSLoader = function DDSLoader(manager) { CompressedTextureLoader.call(this, manager); }; DDSLoader.prototype = Object.assign(Object.create(CompressedTextureLoader.prototype), { constructor: DDSLoader, parse: function parse(buffer, loadMipmaps) { var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 }; // Adapted from @toji's DDS utils // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js // All values and structures referenced from: // http://msdn.microsoft.com/en-us/library/bb943991.aspx/ var DDS_MAGIC = 0x20534444; // var DDSD_CAPS = 0x1; // var DDSD_HEIGHT = 0x2; // var DDSD_WIDTH = 0x4; // var DDSD_PITCH = 0x8; // var DDSD_PIXELFORMAT = 0x1000; var DDSD_MIPMAPCOUNT = 0x20000; // var DDSD_LINEARSIZE = 0x80000; // var DDSD_DEPTH = 0x800000; // var DDSCAPS_COMPLEX = 0x8; // var DDSCAPS_MIPMAP = 0x400000; // var DDSCAPS_TEXTURE = 0x1000; var DDSCAPS2_CUBEMAP = 0x200; var DDSCAPS2_CUBEMAP_POSITIVEX = 0x400; var DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800; var DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000; var DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000; var DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000; var DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000; // var DDSCAPS2_VOLUME = 0x200000; // var DDPF_ALPHAPIXELS = 0x1; // var DDPF_ALPHA = 0x2; var DDPF_FOURCC = 0x4; // var DDPF_RGB = 0x40; // var DDPF_YUV = 0x200; // var DDPF_LUMINANCE = 0x20000; function fourCCToInt32(value) { return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24); } function int32ToFourCC(value) { return String.fromCharCode(value & 0xff, value >> 8 & 0xff, value >> 16 & 0xff, value >> 24 & 0xff); } function loadARGBMip(buffer, dataOffset, width, height) { var dataLength = width * height * 4; var srcBuffer = new Uint8Array(buffer, dataOffset, dataLength); var byteArray = new Uint8Array(dataLength); var dst = 0; var src = 0; for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var b = srcBuffer[src]; src++; var g = srcBuffer[src]; src++; var r = srcBuffer[src]; src++; var a = srcBuffer[src]; src++; byteArray[dst] = r; dst++; //r byteArray[dst] = g; dst++; //g byteArray[dst] = b; dst++; //b byteArray[dst] = a; dst++; //a } } return byteArray; } var FOURCC_DXT1 = fourCCToInt32('DXT1'); var FOURCC_DXT3 = fourCCToInt32('DXT3'); var FOURCC_DXT5 = fourCCToInt32('DXT5'); var FOURCC_ETC1 = fourCCToInt32('ETC1'); var headerLengthInt = 31; // The header length in 32 bit ints // Offsets into the header array var off_magic = 0; var off_size = 1; var off_flags = 2; var off_height = 3; var off_width = 4; var off_mipmapCount = 7; var off_pfFlags = 20; var off_pfFourCC = 21; var off_RGBBitCount = 22; var off_RBitMask = 23; var off_GBitMask = 24; var off_BBitMask = 25; var off_ABitMask = 26; // var off_caps = 27; var off_caps2 = 28; // var off_caps3 = 29; // var off_caps4 = 30; // Parse header var header = new Int32Array(buffer, 0, headerLengthInt); if (header[off_magic] !== DDS_MAGIC) { console.error('THREE.DDSLoader.parse: Invalid magic number in DDS header.'); return dds; } if (!header[off_pfFlags] & DDPF_FOURCC) { console.error('THREE.DDSLoader.parse: Unsupported format, must contain a FourCC code.'); return dds; } var blockBytes; var fourCC = header[off_pfFourCC]; var isRGBAUncompressed = false; switch (fourCC) { case FOURCC_DXT1: blockBytes = 8; dds.format = RGB_S3TC_DXT1_Format; break; case FOURCC_DXT3: blockBytes = 16; dds.format = RGBA_S3TC_DXT3_Format; break; case FOURCC_DXT5: blockBytes = 16; dds.format = RGBA_S3TC_DXT5_Format$1; break; case FOURCC_ETC1: blockBytes = 8; dds.format = RGB_ETC1_Format; break; default: if (header[off_RGBBitCount] === 32 && header[off_RBitMask] & 0xff0000 && header[off_GBitMask] & 0xff00 && header[off_BBitMask] & 0xff && header[off_ABitMask] & 0xff000000) { isRGBAUncompressed = true; blockBytes = 64; dds.format = RGBAFormat; } else { console.error('THREE.DDSLoader.parse: Unsupported FourCC code ', int32ToFourCC(fourCC)); return dds; } } dds.mipmapCount = 1; if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) { dds.mipmapCount = Math.max(1, header[off_mipmapCount]); } var caps2 = header[off_caps2]; dds.isCubemap = caps2 & DDSCAPS2_CUBEMAP ? true : false; if (dds.isCubemap && (!(caps2 & DDSCAPS2_CUBEMAP_POSITIVEX) || !(caps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) || !(caps2 & DDSCAPS2_CUBEMAP_POSITIVEY) || !(caps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) || !(caps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) || !(caps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ))) { console.error('THREE.DDSLoader.parse: Incomplete cubemap faces'); return dds; } dds.width = header[off_width]; dds.height = header[off_height]; var dataOffset = header[off_size] + 4; // Extract mipmaps buffers var faces = dds.isCubemap ? 6 : 1; for (var face = 0; face < faces; face++) { var width = dds.width; var height = dds.height; for (var i = 0; i < dds.mipmapCount; i++) { if (isRGBAUncompressed) { var byteArray = loadARGBMip(buffer, dataOffset, width, height); var dataLength = byteArray.length; } else { var dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes; var byteArray = new Uint8Array(buffer, dataOffset, dataLength); } var mipmap = { 'data': byteArray, 'width': width, 'height': height }; dds.mipmaps.push(mipmap); dataOffset += dataLength; width = Math.max(width >> 1, 1); height = Math.max(height >> 1, 1); } } return dds; } }); //2022.11.11 copyfrom : https://unpkg.com/three@0.146.0/examples/jsm/loaders/GLTFLoader.js //xzw add:---- var unknownExtensions = {}; var oldSet = MeshBasicMaterial.prototype.setValues; MeshBasicMaterial.prototype.setValues = function (values) { return oldSet.call(this, values); }; class GLTFLoader extends Loader { constructor(manager, renderer, urlPrefix) { super(manager); //xzw add: this.dracoLoader = new DRACOLoader(); this.ktx2Loader = new KTX2Loader(); this.meshoptDecoder = MeshoptDecoder; this.ddsLoader = new DDSLoader(); //这个没测过 //路径相对于index.html this.dracoLoader.setDecoderPath(urlPrefix + 'three.js/loaders/draco/' /*or 'https://unpkg.com/three@0.144.0/examples/js/libs/draco/gltf/' 版本可升级 */); //这两个路径可以自己改。在laser的环境也要放一份这个路径 this.ktx2Loader.setTranscoderPath(urlPrefix + 'three.js/loaders/basis/' /*or 'https://unpkg.com/three@0.144.0/examples/js/libs/basis/' 版本可升级 */).detectSupport(renderer); this.pluginCallbacks = []; this.register(function (parser) { return new GLTFMaterialsClearcoatExtension(parser); }); this.register(function (parser) { return new GLTFTextureBasisUExtension(parser); }); this.register(function (parser) { return new GLTFTextureWebPExtension(parser); }); this.register(function (parser) { return new GLTFMaterialsSheenExtension(parser); }); this.register(function (parser) { return new GLTFMaterialsTransmissionExtension(parser); }); this.register(function (parser) { return new GLTFMaterialsVolumeExtension(parser); }); this.register(function (parser) { return new GLTFMaterialsIorExtension(parser); }); this.register(function (parser) { return new GLTFMaterialsEmissiveStrengthExtension(parser); }); this.register(function (parser) { return new GLTFMaterialsSpecularExtension(parser); }); this.register(function (parser) { return new GLTFMaterialsIridescenceExtension(parser); }); this.register(function (parser) { return new GLTFLightsExtension(parser); }); this.register(function (parser) { return new GLTFMeshoptCompression(parser); }); this.register(function (parser) { return new GLTFMeshGpuInstancing(parser); }); } load(url, onLoad, onProgress, onError) { var scope = this; var resourcePath; if (this.resourcePath !== '') { resourcePath = this.resourcePath; } else if (this.path !== '') { resourcePath = this.path; } else { resourcePath = LoaderUtils.extractUrlBase(url); } // Tells the LoadingManager to track an extra item, which resolves after // the model is fully loaded. This means the count of items loaded will // be incorrect, but ensures manager.onLoad() does not fire early. this.manager.itemStart(url); var _onError = function _onError(e) { if (onError) { onError(e); } else { console.error(e); } scope.manager.itemError(url); scope.manager.itemEnd(url); }; var loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setResponseType('arraybuffer'); loader.setRequestHeader(this.requestHeader); loader.setWithCredentials(this.withCredentials); loader.load(url, function (data) { try { scope.parse(data, resourcePath, function (gltf) { onLoad(gltf); scope.manager.itemEnd(url); }, _onError); } catch (e) { _onError(e); } }, onProgress, _onError); } setDRACOLoader(dracoLoader) { this.dracoLoader = dracoLoader; return this; } setDDSLoader() { throw new Error('THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".'); } setKTX2Loader(ktx2Loader) { this.ktx2Loader = ktx2Loader; return this; } setMeshoptDecoder(meshoptDecoder) { this.meshoptDecoder = meshoptDecoder; return this; } register(callback) { if (this.pluginCallbacks.indexOf(callback) === -1) { this.pluginCallbacks.push(callback); } return this; } unregister(callback) { if (this.pluginCallbacks.indexOf(callback) !== -1) { this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1); } return this; } parse(data, path, onLoad, onError) { var json; var extensions = {}; var plugins = {}; if (typeof data === 'string') { json = JSON.parse(data); } else if (data instanceof ArrayBuffer) { var magic = LoaderUtils.decodeText(new Uint8Array(data, 0, 4)); if (magic === BINARY_EXTENSION_HEADER_MAGIC) { try { extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data); } catch (error) { if (onError) onError(error); return; } json = JSON.parse(extensions[EXTENSIONS.KHR_BINARY_GLTF].content); } else { json = JSON.parse(LoaderUtils.decodeText(new Uint8Array(data))); } } else { json = data; } if (json.asset === undefined || json.asset.version[0] < 2) { if (onError) onError(new Error('THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.')); return; } var parser = new GLTFParser(json, { path: path || this.resourcePath || '', crossOrigin: this.crossOrigin, requestHeader: this.requestHeader, manager: this.manager, ktx2Loader: this.ktx2Loader, meshoptDecoder: this.meshoptDecoder }); parser.fileLoader.setRequestHeader(this.requestHeader); for (var i = 0; i < this.pluginCallbacks.length; i++) { var plugin = this.pluginCallbacks[i](parser); plugins[plugin.name] = plugin; // Workaround to avoid determining as unknown extension // in addUnknownExtensionsToUserData(). // Remove this workaround if we move all the existing // extension handlers to plugin system extensions[plugin.name] = true; } if (json.extensionsUsed) { for (var _i = 0; _i < json.extensionsUsed.length; ++_i) { var extensionName = json.extensionsUsed[_i]; var extensionsRequired = json.extensionsRequired || []; switch (extensionName) { case EXTENSIONS.KHR_MATERIALS_UNLIT: extensions[extensionName] = new GLTFMaterialsUnlitExtension(); break; case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: extensions[extensionName] = new GLTFMaterialsPbrSpecularGlossinessExtension(); break; case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION: extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader); break; case EXTENSIONS.KHR_TEXTURE_TRANSFORM: extensions[extensionName] = new GLTFTextureTransformExtension(); break; case EXTENSIONS.KHR_MESH_QUANTIZATION: extensions[extensionName] = new GLTFMeshQuantizationExtension(); break; default: if (extensionsRequired.indexOf(extensionName) >= 0 && plugins[extensionName] === undefined) { if (!unknownExtensions[extensionName]) { console.warn('GLTFLoader: Unknown extension "' + extensionName + '".', '使用默认的KHR_materials_unlit材质'); unknownExtensions[extensionName] = 1; } //xzw add: 默认 json.extensionsRequired = 'KHR_materials_unlit'; json.materials = [{ extensions: { KHR_materials_unlit: {} }, pbrMetallicRoughness: { baseColorFactor: [1, 1, 1, 1], baseColorTexture: { index: 0, texCoord: 0 }, metallicFactor: 0, roughnessFactor: 0.5 } }]; extensions[json.extensionsRequired] = new GLTFMaterialsUnlitExtension(); } /* 如原先: json.materials = KHR_techniques_webgl:{ technique: 0, values:{u_diffuse:{index: 0,texCoord: 0}} } */ } } } parser.setExtensions(extensions); parser.setPlugins(plugins); parser.parse(onLoad, onError); } parseAsync(data, path) { var scope = this; return new Promise(function (resolve, reject) { scope.parse(data, path, resolve, reject); }); } } /* GLTFREGISTRY */ function GLTFRegistry() { var objects = {}; return { get: function get(key) { return objects[key]; }, add: function add(key, object) { objects[key] = object; }, remove: function remove(key) { delete objects[key]; }, removeAll: function removeAll() { objects = {}; } }; } /*********************************/ /********** EXTENSIONS ***********/ /*********************************/ var EXTENSIONS = { KHR_BINARY_GLTF: 'KHR_binary_glTF', KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression', KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual', KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat', KHR_MATERIALS_IOR: 'KHR_materials_ior', KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness', KHR_MATERIALS_SHEEN: 'KHR_materials_sheen', KHR_MATERIALS_SPECULAR: 'KHR_materials_specular', KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission', KHR_MATERIALS_IRIDESCENCE: 'KHR_materials_iridescence', KHR_MATERIALS_UNLIT: 'KHR_materials_unlit', KHR_MATERIALS_VOLUME: 'KHR_materials_volume', KHR_TEXTURE_BASISU: 'KHR_texture_basisu', KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform', KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization', KHR_MATERIALS_EMISSIVE_STRENGTH: 'KHR_materials_emissive_strength', EXT_TEXTURE_WEBP: 'EXT_texture_webp', EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression', EXT_MESH_GPU_INSTANCING: 'EXT_mesh_gpu_instancing' }; /** * Punctual Lights Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual */ class GLTFLightsExtension { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL; // Object3D instance caches this.cache = { refs: {}, uses: {} }; } _markDefs() { var parser = this.parser; var nodeDefs = this.parser.json.nodes || []; for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) { var nodeDef = nodeDefs[nodeIndex]; if (nodeDef.extensions && nodeDef.extensions[this.name] && nodeDef.extensions[this.name].light !== undefined) { parser._addNodeRef(this.cache, nodeDef.extensions[this.name].light); } } } _loadLight(lightIndex) { var parser = this.parser; var cacheKey = 'light:' + lightIndex; var dependency = parser.cache.get(cacheKey); if (dependency) return dependency; var json = parser.json; var extensions = json.extensions && json.extensions[this.name] || {}; var lightDefs = extensions.lights || []; var lightDef = lightDefs[lightIndex]; var lightNode; var color = new Color(0xffffff); if (lightDef.color !== undefined) color.fromArray(lightDef.color); var range = lightDef.range !== undefined ? lightDef.range : 0; switch (lightDef.type) { case 'directional': lightNode = new DirectionalLight(color); lightNode.target.position.set(0, 0, -1); lightNode.add(lightNode.target); break; case 'point': lightNode = new PointLight(color); lightNode.distance = range; break; case 'spot': lightNode = new SpotLight(color); lightNode.distance = range; // Handle spotlight properties. lightDef.spot = lightDef.spot || {}; lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0; lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0; lightNode.angle = lightDef.spot.outerConeAngle; lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle; lightNode.target.position.set(0, 0, -1); lightNode.add(lightNode.target); break; default: throw new Error('THREE.GLTFLoader: Unexpected light type: ' + lightDef.type); } // Some lights (e.g. spot) default to a position other than the origin. Reset the position // here, because node-level parsing will only override position if explicitly specified. lightNode.position.set(0, 0, 0); lightNode.decay = 2; if (lightDef.intensity !== undefined) lightNode.intensity = lightDef.intensity; lightNode.name = parser.createUniqueName(lightDef.name || 'light_' + lightIndex); dependency = Promise.resolve(lightNode); parser.cache.add(cacheKey, dependency); return dependency; } createNodeAttachment(nodeIndex) { var self = this; var parser = this.parser; var json = parser.json; var nodeDef = json.nodes[nodeIndex]; var lightDef = nodeDef.extensions && nodeDef.extensions[this.name] || {}; var lightIndex = lightDef.light; if (lightIndex === undefined) return null; return this._loadLight(lightIndex).then(function (light) { return parser._getNodeRef(self.cache, lightIndex, light); }); } } /** * Unlit Materials Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit */ class GLTFMaterialsUnlitExtension { constructor() { this.name = EXTENSIONS.KHR_MATERIALS_UNLIT; } getMaterialType() { return MeshBasicMaterial; } extendParams(materialParams, materialDef, parser) { var pending = []; materialParams.color = new Color(1.0, 1.0, 1.0); materialParams.opacity = 1.0; var metallicRoughness = materialDef.pbrMetallicRoughness; if (metallicRoughness) { if (Array.isArray(metallicRoughness.baseColorFactor)) { var array = metallicRoughness.baseColorFactor; materialParams.color.fromArray(array); materialParams.opacity = array[3]; } if (metallicRoughness.baseColorTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture, sRGBEncoding)); } } return Promise.all(pending); } } /** * Materials Emissive Strength Extension * * Specification: https://github.com/KhronosGroup/glTF/blob/5768b3ce0ef32bc39cdf1bef10b948586635ead3/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md */ class GLTFMaterialsEmissiveStrengthExtension { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH; } extendMaterialParams(materialIndex, materialParams) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex] || parser.json.materials[0]; //xzw change if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } var emissiveStrength = materialDef.extensions[this.name].emissiveStrength; if (emissiveStrength !== undefined) { materialParams.emissiveIntensity = emissiveStrength; } return Promise.resolve(); } } /** * Clearcoat Materials Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat */ class GLTFMaterialsClearcoatExtension { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT; } getMaterialType(materialIndex) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex] || parser.json.materials[0]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex] || parser.json.materials[0]; //曾因这里报错加了一句 || parser.json.materials; 但是加载的图会先变白 if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } var pending = []; var extension = materialDef.extensions[this.name]; if (extension.clearcoatFactor !== undefined) { materialParams.clearcoat = extension.clearcoatFactor; } if (extension.clearcoatTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'clearcoatMap', extension.clearcoatTexture)); } if (extension.clearcoatRoughnessFactor !== undefined) { materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor; } if (extension.clearcoatRoughnessTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture)); } if (extension.clearcoatNormalTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture)); if (extension.clearcoatNormalTexture.scale !== undefined) { var scale = extension.clearcoatNormalTexture.scale; materialParams.clearcoatNormalScale = new Vector2(scale, scale); } } return Promise.all(pending); } } /** * Iridescence Materials Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_iridescence */ class GLTFMaterialsIridescenceExtension { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_IRIDESCENCE; } getMaterialType(materialIndex) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex] || parser.json.materials[0]; ; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex] || parser.json.materials[0]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } var pending = []; var extension = materialDef.extensions[this.name]; if (extension.iridescenceFactor !== undefined) { materialParams.iridescence = extension.iridescenceFactor; } if (extension.iridescenceTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'iridescenceMap', extension.iridescenceTexture)); } if (extension.iridescenceIor !== undefined) { materialParams.iridescenceIOR = extension.iridescenceIor; } if (materialParams.iridescenceThicknessRange === undefined) { materialParams.iridescenceThicknessRange = [100, 400]; } if (extension.iridescenceThicknessMinimum !== undefined) { materialParams.iridescenceThicknessRange[0] = extension.iridescenceThicknessMinimum; } if (extension.iridescenceThicknessMaximum !== undefined) { materialParams.iridescenceThicknessRange[1] = extension.iridescenceThicknessMaximum; } if (extension.iridescenceThicknessTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'iridescenceThicknessMap', extension.iridescenceThicknessTexture)); } return Promise.all(pending); } } /** * Sheen Materials Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen */ class GLTFMaterialsSheenExtension { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_SHEEN; } getMaterialType(materialIndex) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex] || parser.json.materials[0]; ; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex] || parser.json.materials[0]; ; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } var pending = []; materialParams.sheenColor = new Color(0, 0, 0); materialParams.sheenRoughness = 0; materialParams.sheen = 1; var extension = materialDef.extensions[this.name]; if (extension.sheenColorFactor !== undefined) { materialParams.sheenColor.fromArray(extension.sheenColorFactor); } if (extension.sheenRoughnessFactor !== undefined) { materialParams.sheenRoughness = extension.sheenRoughnessFactor; } if (extension.sheenColorTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'sheenColorMap', extension.sheenColorTexture, sRGBEncoding)); } if (extension.sheenRoughnessTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'sheenRoughnessMap', extension.sheenRoughnessTexture)); } return Promise.all(pending); } } /** * Transmission Materials Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission * Draft: https://github.com/KhronosGroup/glTF/pull/1698 */ class GLTFMaterialsTransmissionExtension { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION; } getMaterialType(materialIndex) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex] || parser.json.materials[0]; ; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex] || parser.json.materials[0]; ; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } var pending = []; var extension = materialDef.extensions[this.name]; if (extension.transmissionFactor !== undefined) { materialParams.transmission = extension.transmissionFactor; } if (extension.transmissionTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'transmissionMap', extension.transmissionTexture)); } return Promise.all(pending); } } /** * Materials Volume Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume */ class GLTFMaterialsVolumeExtension { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_VOLUME; } getMaterialType(materialIndex) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex] || parser.json.materials[0]; ; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } var pending = []; var extension = materialDef.extensions[this.name]; materialParams.thickness = extension.thicknessFactor !== undefined ? extension.thicknessFactor : 0; if (extension.thicknessTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'thicknessMap', extension.thicknessTexture)); } materialParams.attenuationDistance = extension.attenuationDistance || Infinity; var colorArray = extension.attenuationColor || [1, 1, 1]; materialParams.attenuationColor = new Color(colorArray[0], colorArray[1], colorArray[2]); return Promise.all(pending); } } /** * Materials ior Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior */ class GLTFMaterialsIorExtension { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_IOR; } getMaterialType(materialIndex) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex] || parser.json.materials[0]; ; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } var extension = materialDef.extensions[this.name]; materialParams.ior = extension.ior !== undefined ? extension.ior : 1.5; return Promise.resolve(); } } /** * Materials specular Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular */ class GLTFMaterialsSpecularExtension { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR; } getMaterialType(materialIndex) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex] || parser.json.materials[0]; ; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex] || parser.json.materials[0]; ; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } var pending = []; var extension = materialDef.extensions[this.name]; materialParams.specularIntensity = extension.specularFactor !== undefined ? extension.specularFactor : 1.0; if (extension.specularTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'specularIntensityMap', extension.specularTexture)); } var colorArray = extension.specularColorFactor || [1, 1, 1]; materialParams.specularColor = new Color(colorArray[0], colorArray[1], colorArray[2]); if (extension.specularColorTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'specularColorMap', extension.specularColorTexture, sRGBEncoding)); } return Promise.all(pending); } } /** * BasisU Texture Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu */ class GLTFTextureBasisUExtension { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_TEXTURE_BASISU; } loadTexture(textureIndex) { var parser = this.parser; var json = parser.json; var textureDef = json.textures[textureIndex]; if (!textureDef.extensions || !textureDef.extensions[this.name]) { return null; } var extension = textureDef.extensions[this.name]; var loader = parser.options.ktx2Loader; if (!loader) { if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) { throw new Error('THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures'); } else { // Assumes that the extension is optional and that a fallback texture is present return null; } } return parser.loadTextureImage(textureIndex, extension.source, loader); } } /** * WebP Texture Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp */ class GLTFTextureWebPExtension { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.EXT_TEXTURE_WEBP; this.isSupported = null; } loadTexture(textureIndex) { var name = this.name; var parser = this.parser; var json = parser.json; var textureDef = json.textures[textureIndex]; if (!textureDef.extensions || !textureDef.extensions[name]) { return null; } var extension = textureDef.extensions[name]; var source = json.images[extension.source]; var loader = parser.textureLoader; if (source.uri) { var handler = parser.options.manager.getHandler(source.uri); if (handler !== null) loader = handler; } return this.detectSupport().then(function (isSupported) { if (isSupported) return parser.loadTextureImage(textureIndex, extension.source, loader); if (json.extensionsRequired && json.extensionsRequired.indexOf(name) >= 0) { throw new Error('THREE.GLTFLoader: WebP required by asset but unsupported.'); } // Fall back to PNG or JPEG. return parser.loadTexture(textureIndex); }); } detectSupport() { if (!this.isSupported) { this.isSupported = new Promise(function (resolve) { var image = new Image(); // Lossy test image. Support for lossy images doesn't guarantee support for all // WebP images, unfortunately. image.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA'; image.onload = image.onerror = function () { resolve(image.height === 1); }; }); } return this.isSupported; } } /** * meshopt BufferView Compression Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression */ class GLTFMeshoptCompression { constructor(parser) { this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION; this.parser = parser; } loadBufferView(index) { var json = this.parser.json; var bufferView = json.bufferViews[index]; if (bufferView.extensions && bufferView.extensions[this.name]) { var extensionDef = bufferView.extensions[this.name]; var buffer = this.parser.getDependency('buffer', extensionDef.buffer); var decoder = this.parser.options.meshoptDecoder; if (!decoder || !decoder.supported) { if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) { throw new Error('THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files'); } else { // Assumes that the extension is optional and that fallback buffer data is present return null; } } return buffer.then(function (res) { var byteOffset = extensionDef.byteOffset || 0; var byteLength = extensionDef.byteLength || 0; var count = extensionDef.count; var stride = extensionDef.byteStride; var source = new Uint8Array(res, byteOffset, byteLength); if (decoder.decodeGltfBufferAsync) { return decoder.decodeGltfBufferAsync(count, stride, source, extensionDef.mode, extensionDef.filter).then(function (res) { return res.buffer; }); } else { // Support for MeshoptDecoder 0.18 or earlier, without decodeGltfBufferAsync return decoder.ready.then(function () { var result = new ArrayBuffer(count * stride); decoder.decodeGltfBuffer(new Uint8Array(result), count, stride, source, extensionDef.mode, extensionDef.filter); return result; }); } }); } else { return null; } } } /** * GPU Instancing Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_mesh_gpu_instancing * */ class GLTFMeshGpuInstancing { constructor(parser) { this.name = EXTENSIONS.EXT_MESH_GPU_INSTANCING; this.parser = parser; } createNodeMesh(nodeIndex) { var _this = this; var json = this.parser.json; var nodeDef = json.nodes[nodeIndex]; if (!nodeDef.extensions || !nodeDef.extensions[this.name] || nodeDef.mesh === undefined) { return null; } var meshDef = json.meshes[nodeDef.mesh]; // No Points or Lines + Instancing support yet for (var primitive of meshDef.primitives) { if (primitive.mode !== WEBGL_CONSTANTS.TRIANGLES && primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_STRIP && primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_FAN && primitive.mode !== undefined) { return null; } } var extensionDef = nodeDef.extensions[this.name]; var attributesDef = extensionDef.attributes; // @TODO: Can we support InstancedMesh + SkinnedMesh? var pending = []; var attributes = {}; var _loop = function _loop(key) { pending.push(_this.parser.getDependency('accessor', attributesDef[key]).then(accessor => { attributes[key] = accessor; return attributes[key]; })); }; for (var key in attributesDef) { _loop(key); } if (pending.length < 1) { return null; } pending.push(this.parser.createNodeMesh(nodeIndex)); return Promise.all(pending).then(results => { var nodeObject = results.pop(); var meshes = nodeObject.isGroup ? nodeObject.children : [nodeObject]; var count = results[0].count; // All attribute counts should be same var instancedMeshes = []; for (var mesh of meshes) { // Temporal variables var m = new Matrix4(); var p = new Vector3(); var q = new Quaternion(); var s = new Vector3(1, 1, 1); var instancedMesh = new InstancedMesh(mesh.geometry, mesh.material, count); for (var i = 0; i < count; i++) { if (attributes.TRANSLATION) { p.fromBufferAttribute(attributes.TRANSLATION, i); } if (attributes.ROTATION) { q.fromBufferAttribute(attributes.ROTATION, i); } if (attributes.SCALE) { s.fromBufferAttribute(attributes.SCALE, i); } instancedMesh.setMatrixAt(i, m.compose(p, q, s)); } // Add instance attributes to the geometry, excluding TRS. for (var attributeName in attributes) { if (attributeName !== 'TRANSLATION' && attributeName !== 'ROTATION' && attributeName !== 'SCALE') { mesh.geometry.setAttribute(attributeName, attributes[attributeName]); } } // Just in case Object3D.prototype.copy.call(instancedMesh, mesh); // https://github.com/mrdoob/three.js/issues/18334 instancedMesh.frustumCulled = false; this.parser.assignFinalMaterial(instancedMesh); instancedMeshes.push(instancedMesh); } if (nodeObject.isGroup) { nodeObject.clear(); nodeObject.add(...instancedMeshes); return nodeObject; } return instancedMeshes[0]; }); } } /* BINARY EXTENSION */ var BINARY_EXTENSION_HEADER_MAGIC = 'glTF'; var BINARY_EXTENSION_HEADER_LENGTH = 12; var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 }; class GLTFBinaryExtension { constructor(data) { this.name = EXTENSIONS.KHR_BINARY_GLTF; this.content = null; this.body = null; var headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH); this.header = { magic: LoaderUtils.decodeText(new Uint8Array(data.slice(0, 4))), version: headerView.getUint32(4, true), length: headerView.getUint32(8, true) }; if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) { throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.'); } else if (this.header.version < 2.0) { throw new Error('THREE.GLTFLoader: Legacy binary file detected.'); } var chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH; var chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH); var chunkIndex = 0; while (chunkIndex < chunkContentsLength) { var chunkLength = chunkView.getUint32(chunkIndex, true); chunkIndex += 4; var chunkType = chunkView.getUint32(chunkIndex, true); chunkIndex += 4; if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) { var contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength); this.content = LoaderUtils.decodeText(contentArray); } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) { var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex; this.body = data.slice(byteOffset, byteOffset + chunkLength); } // Clients must ignore chunks with unknown types. chunkIndex += chunkLength; } if (this.content === null) { throw new Error('THREE.GLTFLoader: JSON content not found.'); } } } /** * DRACO Mesh Compression Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression */ class GLTFDracoMeshCompressionExtension { constructor(json, dracoLoader) { if (!dracoLoader) { throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.'); } this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION; this.json = json; this.dracoLoader = dracoLoader; this.dracoLoader.preload(); } decodePrimitive(primitive, parser) { var json = this.json; var dracoLoader = this.dracoLoader; var bufferViewIndex = primitive.extensions[this.name].bufferView; var gltfAttributeMap = primitive.extensions[this.name].attributes; var threeAttributeMap = {}; var attributeNormalizedMap = {}; var attributeTypeMap = {}; for (var attributeName in gltfAttributeMap) { var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase(); threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName]; } for (var _attributeName in primitive.attributes) { var _threeAttributeName = ATTRIBUTES[_attributeName] || _attributeName.toLowerCase(); if (gltfAttributeMap[_attributeName] !== undefined) { var accessorDef = json.accessors[primitive.attributes[_attributeName]]; var componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; attributeTypeMap[_threeAttributeName] = componentType.name; attributeNormalizedMap[_threeAttributeName] = accessorDef.normalized === true; } } return parser.getDependency('bufferView', bufferViewIndex).then(function (bufferView) { return new Promise(function (resolve) { dracoLoader.decodeDracoFile(bufferView, function (geometry) { for (var _attributeName2 in geometry.attributes) { var attribute = geometry.attributes[_attributeName2]; var normalized = attributeNormalizedMap[_attributeName2]; if (normalized !== undefined) attribute.normalized = normalized; } resolve(geometry); }, threeAttributeMap, attributeTypeMap); }); }); } } /** * Texture Transform Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform */ class GLTFTextureTransformExtension { constructor() { this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM; } extendTexture(texture, transform) { if (transform.texCoord !== undefined) { console.warn('THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.'); } if (transform.offset === undefined && transform.rotation === undefined && transform.scale === undefined) { // See https://github.com/mrdoob/three.js/issues/21819. return texture; } texture = texture.clone(); if (transform.offset !== undefined) { texture.offset.fromArray(transform.offset); } if (transform.rotation !== undefined) { texture.rotation = transform.rotation; } if (transform.scale !== undefined) { texture.repeat.fromArray(transform.scale); } texture.needsUpdate = true; return texture; } } /** * Specular-Glossiness Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness */ /** * A sub class of StandardMaterial with some of the functionality * changed via the `onBeforeCompile` callback * @pailhead */ class GLTFMeshStandardSGMaterial extends MeshStandardMaterial { constructor(params) { super(); this.isGLTFSpecularGlossinessMaterial = true; //various chunks that need replacing var specularMapParsFragmentChunk = ['#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif'].join('\n'); var glossinessMapParsFragmentChunk = ['#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif'].join('\n'); var specularMapFragmentChunk = ['vec3 specularFactor = specular;', '#ifdef USE_SPECULARMAP', ' vec4 texelSpecular = texture2D( specularMap, vUv );', ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture', ' specularFactor *= texelSpecular.rgb;', '#endif'].join('\n'); var glossinessMapFragmentChunk = ['float glossinessFactor = glossiness;', '#ifdef USE_GLOSSINESSMAP', ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );', ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture', ' glossinessFactor *= texelGlossiness.a;', '#endif'].join('\n'); var lightPhysicalFragmentChunk = ['PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );', 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );', 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );', 'material.roughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.', 'material.roughness += geometryRoughness;', 'material.roughness = min( material.roughness, 1.0 );', 'material.specularColor = specularFactor;'].join('\n'); var uniforms = { specular: { value: new Color().setHex(0xffffff) }, glossiness: { value: 1 }, specularMap: { value: null }, glossinessMap: { value: null } }; this._extraUniforms = uniforms; this.onBeforeCompile = function (shader) { for (var uniformName in uniforms) { shader.uniforms[uniformName] = uniforms[uniformName]; } shader.fragmentShader = shader.fragmentShader.replace('uniform float roughness;', 'uniform vec3 specular;').replace('uniform float metalness;', 'uniform float glossiness;').replace('#include ', specularMapParsFragmentChunk).replace('#include ', glossinessMapParsFragmentChunk).replace('#include ', specularMapFragmentChunk).replace('#include ', glossinessMapFragmentChunk).replace('#include ', lightPhysicalFragmentChunk); }; Object.defineProperties(this, { specular: { get: function get() { return uniforms.specular.value; }, set: function set(v) { uniforms.specular.value = v; } }, specularMap: { get: function get() { return uniforms.specularMap.value; }, set: function set(v) { uniforms.specularMap.value = v; if (v) { this.defines.USE_SPECULARMAP = ''; // USE_UV is set by the renderer for specular maps } else { delete this.defines.USE_SPECULARMAP; } } }, glossiness: { get: function get() { return uniforms.glossiness.value; }, set: function set(v) { uniforms.glossiness.value = v; } }, glossinessMap: { get: function get() { return uniforms.glossinessMap.value; }, set: function set(v) { uniforms.glossinessMap.value = v; if (v) { this.defines.USE_GLOSSINESSMAP = ''; this.defines.USE_UV = ''; } else { delete this.defines.USE_GLOSSINESSMAP; delete this.defines.USE_UV; } } } }); delete this.metalness; delete this.roughness; delete this.metalnessMap; delete this.roughnessMap; this.setValues(params); } copy(source) { super.copy(source); this.specularMap = source.specularMap; this.specular.copy(source.specular); this.glossinessMap = source.glossinessMap; this.glossiness = source.glossiness; delete this.metalness; delete this.roughness; delete this.metalnessMap; delete this.roughnessMap; return this; } } class GLTFMaterialsPbrSpecularGlossinessExtension { constructor() { this.name = EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS; this.specularGlossinessParams = ['color', 'map', 'lightMap', 'lightMapIntensity', 'aoMap', 'aoMapIntensity', 'emissive', 'emissiveIntensity', 'emissiveMap', 'bumpMap', 'bumpScale', 'normalMap', 'normalMapType', 'displacementMap', 'displacementScale', 'displacementBias', 'specularMap', 'specular', 'glossinessMap', 'glossiness', 'alphaMap', 'envMap', 'envMapIntensity']; } getMaterialType() { return GLTFMeshStandardSGMaterial; } extendParams(materialParams, materialDef, parser) { var pbrSpecularGlossiness = materialDef.extensions[this.name]; materialParams.color = new Color(1.0, 1.0, 1.0); materialParams.opacity = 1.0; var pending = []; if (Array.isArray(pbrSpecularGlossiness.diffuseFactor)) { var array = pbrSpecularGlossiness.diffuseFactor; materialParams.color.fromArray(array); materialParams.opacity = array[3]; } if (pbrSpecularGlossiness.diffuseTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'map', pbrSpecularGlossiness.diffuseTexture, sRGBEncoding)); } materialParams.emissive = new Color(0.0, 0.0, 0.0); materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0; materialParams.specular = new Color(1.0, 1.0, 1.0); if (Array.isArray(pbrSpecularGlossiness.specularFactor)) { materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor); } if (pbrSpecularGlossiness.specularGlossinessTexture !== undefined) { var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture; pending.push(parser.assignTexture(materialParams, 'glossinessMap', specGlossMapDef)); pending.push(parser.assignTexture(materialParams, 'specularMap', specGlossMapDef, sRGBEncoding)); } return Promise.all(pending); } createMaterial(materialParams) { var material = new GLTFMeshStandardSGMaterial(materialParams); material.fog = true; material.color = materialParams.color; material.map = materialParams.map === undefined ? null : materialParams.map; material.lightMap = null; material.lightMapIntensity = 1.0; material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap; material.aoMapIntensity = 1.0; material.emissive = materialParams.emissive; material.emissiveIntensity = materialParams.emissiveIntensity === undefined ? 1.0 : materialParams.emissiveIntensity; material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap; material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap; material.bumpScale = 1; material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap; material.normalMapType = TangentSpaceNormalMap; if (materialParams.normalScale) material.normalScale = materialParams.normalScale; material.displacementMap = null; material.displacementScale = 1; material.displacementBias = 0; material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap; material.specular = materialParams.specular; material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap; material.glossiness = materialParams.glossiness; material.alphaMap = null; material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap; material.envMapIntensity = 1.0; return material; } } /** * Mesh Quantization Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization */ class GLTFMeshQuantizationExtension { constructor() { this.name = EXTENSIONS.KHR_MESH_QUANTIZATION; } } /*********************************/ /********** INTERPOLATION ********/ /*********************************/ // Spline Interpolation // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation class GLTFCubicSplineInterpolant extends Interpolant { constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { super(parameterPositions, sampleValues, sampleSize, resultBuffer); } copySampleValue_(index) { // Copies a sample value to the result buffer. See description of glTF // CUBICSPLINE values layout in interpolate_() function below. var result = this.resultBuffer, values = this.sampleValues, valueSize = this.valueSize, offset = index * valueSize * 3 + valueSize; for (var i = 0; i !== valueSize; i++) { result[i] = values[offset + i]; } return result; } interpolate_(i1, t0, t, t1) { var result = this.resultBuffer; var values = this.sampleValues; var stride = this.valueSize; var stride2 = stride * 2; var stride3 = stride * 3; var td = t1 - t0; var p = (t - t0) / td; var pp = p * p; var ppp = pp * p; var offset1 = i1 * stride3; var offset0 = offset1 - stride3; var s2 = -2 * ppp + 3 * pp; var s3 = ppp - pp; var s0 = 1 - s2; var s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations: // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ] for (var i = 0; i !== stride; i++) { var p0 = values[offset0 + i + stride]; // splineVertex_k var m0 = values[offset0 + i + stride2] * td; // outTangent_k * (t_k+1 - t_k) var p1 = values[offset1 + i + stride]; // splineVertex_k+1 var m1 = values[offset1 + i] * td; // inTangent_k+1 * (t_k+1 - t_k) result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1; } return result; } } var _q = new Quaternion(); class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant { interpolate_(i1, t0, t, t1) { var result = super.interpolate_(i1, t0, t, t1); _q.fromArray(result).normalize().toArray(result); return result; } } /*********************************/ /********** INTERNALS ************/ /*********************************/ /* CONSTANTS */ var WEBGL_CONSTANTS = { FLOAT: 5126, //FLOAT_MAT2: 35674, FLOAT_MAT3: 35675, FLOAT_MAT4: 35676, FLOAT_VEC2: 35664, FLOAT_VEC3: 35665, FLOAT_VEC4: 35666, LINEAR: 9729, REPEAT: 10497, SAMPLER_2D: 35678, POINTS: 0, LINES: 1, LINE_LOOP: 2, LINE_STRIP: 3, TRIANGLES: 4, TRIANGLE_STRIP: 5, TRIANGLE_FAN: 6, UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123 }; var WEBGL_COMPONENT_TYPES = { 5120: Int8Array, 5121: Uint8Array, 5122: Int16Array, 5123: Uint16Array, 5125: Uint32Array, 5126: Float32Array }; var WEBGL_FILTERS = { 9728: NearestFilter, 9729: LinearFilter, 9984: NearestMipmapNearestFilter, 9985: LinearMipmapNearestFilter, 9986: NearestMipmapLinearFilter, 9987: LinearMipmapLinearFilter }; var WEBGL_WRAPPINGS = { 33071: ClampToEdgeWrapping, 33648: MirroredRepeatWrapping, 10497: RepeatWrapping }; var WEBGL_TYPE_SIZES = { 'SCALAR': 1, 'VEC2': 2, 'VEC3': 3, 'VEC4': 4, 'MAT2': 4, 'MAT3': 9, 'MAT4': 16 }; var ATTRIBUTES = { POSITION: 'position', NORMAL: 'normal', TANGENT: 'tangent', TEXCOORD_0: 'uv', TEXCOORD_1: 'uv2', COLOR_0: 'color', WEIGHTS_0: 'skinWeight', JOINTS_0: 'skinIndex' }; var PATH_PROPERTIES = { scale: 'scale', translation: 'position', rotation: 'quaternion', weights: 'morphTargetInfluences' }; var INTERPOLATION = { CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each // keyframe track will be initialized with a default interpolation type, then modified. LINEAR: InterpolateLinear, STEP: InterpolateDiscrete }; var ALPHA_MODES = { OPAQUE: 'OPAQUE', MASK: 'MASK', BLEND: 'BLEND' }; /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material */ function createDefaultMaterial(cache) { if (cache['DefaultMaterial'] === undefined) { cache['DefaultMaterial'] = new MeshStandardMaterial({ color: 0xFFFFFF, emissive: 0x000000, metalness: 1, roughness: 1, transparent: false, depthTest: true, side: FrontSide }); } return cache['DefaultMaterial']; } function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) { // Add unknown glTF extensions to an object's userData. for (var name in objectDef.extensions) { if (knownExtensions[name] === undefined) { object.userData.gltfExtensions = object.userData.gltfExtensions || {}; object.userData.gltfExtensions[name] = objectDef.extensions[name]; } } } /** * @param {Object3D|Material|BufferGeometry} object * @param {GLTF.definition} gltfDef */ function assignExtrasToUserData(object, gltfDef) { if (gltfDef.extras !== undefined) { if (typeof gltfDef.extras === 'object') { Object.assign(object.userData, gltfDef.extras); } else { console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras); } } } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets * * @param {BufferGeometry} geometry * @param {Array} targets * @param {GLTFParser} parser * @return {Promise} */ function addMorphTargets(geometry, targets, parser) { var hasMorphPosition = false; var hasMorphNormal = false; var hasMorphColor = false; for (var i = 0, il = targets.length; i < il; i++) { var target = targets[i]; if (target.POSITION !== undefined) hasMorphPosition = true; if (target.NORMAL !== undefined) hasMorphNormal = true; if (target.COLOR_0 !== undefined) hasMorphColor = true; if (hasMorphPosition && hasMorphNormal && hasMorphColor) break; } if (!hasMorphPosition && !hasMorphNormal && !hasMorphColor) return Promise.resolve(geometry); var pendingPositionAccessors = []; var pendingNormalAccessors = []; var pendingColorAccessors = []; for (var _i2 = 0, _il = targets.length; _i2 < _il; _i2++) { var _target = targets[_i2]; if (hasMorphPosition) { var pendingAccessor = _target.POSITION !== undefined ? parser.getDependency('accessor', _target.POSITION) : geometry.attributes.position; pendingPositionAccessors.push(pendingAccessor); } if (hasMorphNormal) { var _pendingAccessor = _target.NORMAL !== undefined ? parser.getDependency('accessor', _target.NORMAL) : geometry.attributes.normal; pendingNormalAccessors.push(_pendingAccessor); } if (hasMorphColor) { var _pendingAccessor2 = _target.COLOR_0 !== undefined ? parser.getDependency('accessor', _target.COLOR_0) : geometry.attributes.color; pendingColorAccessors.push(_pendingAccessor2); } } return Promise.all([Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors), Promise.all(pendingColorAccessors)]).then(function (accessors) { var morphPositions = accessors[0]; var morphNormals = accessors[1]; var morphColors = accessors[2]; if (hasMorphPosition) geometry.morphAttributes.position = morphPositions; if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals; if (hasMorphColor) geometry.morphAttributes.color = morphColors; geometry.morphTargetsRelative = true; return geometry; }); } /** * @param {Mesh} mesh * @param {GLTF.Mesh} meshDef */ function updateMorphTargets(mesh, meshDef) { mesh.updateMorphTargets(); if (meshDef.weights !== undefined) { for (var i = 0, il = meshDef.weights.length; i < il; i++) { mesh.morphTargetInfluences[i] = meshDef.weights[i]; } } // .extras has user-defined data, so check that .extras.targetNames is an array. if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) { var targetNames = meshDef.extras.targetNames; if (mesh.morphTargetInfluences.length === targetNames.length) { mesh.morphTargetDictionary = {}; for (var _i3 = 0, _il2 = targetNames.length; _i3 < _il2; _i3++) { mesh.morphTargetDictionary[targetNames[_i3]] = _i3; } } else { console.warn('THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.'); } } } function createPrimitiveKey(primitiveDef) { var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]; var geometryKey; if (dracoExtension) { geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey(dracoExtension.attributes); } else { geometryKey = primitiveDef.indices + ':' + createAttributesKey(primitiveDef.attributes) + ':' + primitiveDef.mode; } return geometryKey; } function createAttributesKey(attributes) { var attributesKey = ''; var keys = Object.keys(attributes).sort(); for (var i = 0, il = keys.length; i < il; i++) { attributesKey += keys[i] + ':' + attributes[keys[i]] + ';'; } return attributesKey; } function getNormalizedComponentScale(constructor) { // Reference: // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization#encoding-quantized-data switch (constructor) { case Int8Array: return 1 / 127; case Uint8Array: return 1 / 255; case Int16Array: return 1 / 32767; case Uint16Array: return 1 / 65535; default: throw new Error('THREE.GLTFLoader: Unsupported normalized accessor component type.'); } } function getImageURIMimeType(uri) { if (uri.search(/\.jpe?g($|\?)/i) > 0 || uri.search(/^data\:image\/jpeg/) === 0) return 'image/jpeg'; if (uri.search(/\.webp($|\?)/i) > 0 || uri.search(/^data\:image\/webp/) === 0) return 'image/webp'; return 'image/png'; } /* GLTF PARSER */ class GLTFParser { constructor() { var json = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; this.json = json; this.extensions = {}; this.plugins = {}; this.options = options; // loader object cache this.cache = new GLTFRegistry(); // associations between Three.js objects and glTF elements this.associations = new Map(); // BufferGeometry caching this.primitiveCache = {}; // Object3D instance caches this.meshCache = { refs: {}, uses: {} }; this.cameraCache = { refs: {}, uses: {} }; this.lightCache = { refs: {}, uses: {} }; this.sourceCache = {}; this.textureCache = {}; // Track node names, to ensure no duplicates this.nodeNamesUsed = {}; // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the // expensive work of uploading a texture to the GPU off the main thread. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent) === true; var isFirefox = navigator.userAgent.indexOf('Firefox') > -1; var firefoxVersion = isFirefox ? navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1] : -1; // if ( typeof createImageBitmap === 'undefined' || isSafari || ( isFirefox && firefoxVersion < 98 ) ) { this.textureLoader = new TextureLoader(this.options.manager); /*} else { //为了防止chrome出现报错 The source image could not be decoded. 导致reject,改用TextureLoader by xzw this.textureLoader = new ImageBitmapLoader( this.options.manager ); } */ this.textureLoader.setCrossOrigin(this.options.crossOrigin); this.textureLoader.setRequestHeader(this.options.requestHeader); this.fileLoader = new FileLoader(this.options.manager); this.fileLoader.setResponseType('arraybuffer'); if (this.options.crossOrigin === 'use-credentials') { this.fileLoader.setWithCredentials(true); } } setExtensions(extensions) { this.extensions = extensions; } setPlugins(plugins) { this.plugins = plugins; } parse(onLoad, onError) { var parser = this; var json = this.json; var extensions = this.extensions; // Clear the loader cache this.cache.removeAll(); // Mark the special nodes/meshes in json for efficient parse this._invokeAll(function (ext) { return ext._markDefs && ext._markDefs(); }); Promise.all(this._invokeAll(function (ext) { return ext.beforeRoot && ext.beforeRoot(); })).then(function () { return Promise.all([parser.getDependencies('scene'), parser.getDependencies('animation'), parser.getDependencies('camera')]); }).then(function (dependencies) { var result = { scene: dependencies[0][json.scene || 0], scenes: dependencies[0], animations: dependencies[1], cameras: dependencies[2], asset: json.asset, parser: parser, userData: {} }; addUnknownExtensionsToUserData(extensions, result, json); assignExtrasToUserData(result, json); Promise.all(parser._invokeAll(function (ext) { return ext.afterRoot && ext.afterRoot(result); })).then(function () { onLoad(result); }); }).catch(onError); } /** * Marks the special nodes/meshes in json for efficient parse. */ _markDefs() { var nodeDefs = this.json.nodes || []; var skinDefs = this.json.skins || []; var meshDefs = this.json.meshes || []; // Nothing in the node definition indicates whether it is a Bone or an // Object3D. Use the skins' joint references to mark bones. for (var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) { var joints = skinDefs[skinIndex].joints; for (var i = 0, il = joints.length; i < il; i++) { nodeDefs[joints[i]].isBone = true; } } // Iterate over all nodes, marking references to shared resources, // as well as skeleton joints. for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) { var nodeDef = nodeDefs[nodeIndex]; if (nodeDef.mesh !== undefined) { this._addNodeRef(this.meshCache, nodeDef.mesh); // Nothing in the mesh definition indicates whether it is // a SkinnedMesh or Mesh. Use the node's mesh reference // to mark SkinnedMesh if node has skin. if (nodeDef.skin !== undefined) { meshDefs[nodeDef.mesh].isSkinnedMesh = true; } } if (nodeDef.camera !== undefined) { this._addNodeRef(this.cameraCache, nodeDef.camera); } } } /** * Counts references to shared node / Object3D resources. These resources * can be reused, or "instantiated", at multiple nodes in the scene * hierarchy. Mesh, Camera, and Light instances are instantiated and must * be marked. Non-scenegraph resources (like Materials, Geometries, and * Textures) can be reused directly and are not marked here. * * Example: CesiumMilkTruck sample model reuses "Wheel" meshes. */ _addNodeRef(cache, index) { if (index === undefined) return; if (cache.refs[index] === undefined) { cache.refs[index] = cache.uses[index] = 0; } cache.refs[index]++; } /** Returns a reference to a shared resource, cloning it if necessary. */ _getNodeRef(cache, index, object) { if (cache.refs[index] <= 1) return object; var ref = object.clone(); // Propagates mappings to the cloned object, prevents mappings on the // original object from being lost. var updateMappings = (original, clone) => { var mappings = this.associations.get(original); if (mappings != null) { this.associations.set(clone, mappings); } for (var [i, child] of original.children.entries()) { updateMappings(child, clone.children[i]); } }; updateMappings(object, ref); ref.name += '_instance_' + cache.uses[index]++; return ref; } _invokeOne(func) { var extensions = Object.values(this.plugins); extensions.push(this); for (var i = 0; i < extensions.length; i++) { var result = func(extensions[i]); if (result) return result; } return null; } _invokeAll(func) { var extensions = Object.values(this.plugins); extensions.unshift(this); var pending = []; for (var i = 0; i < extensions.length; i++) { var result = func(extensions[i]); if (result) pending.push(result); } return pending; } /** * Requests the specified dependency asynchronously, with caching. * @param {string} type * @param {number} index * @return {Promise} */ getDependency(type, index) { var cacheKey = type + ':' + index; var dependency = this.cache.get(cacheKey); if (!dependency) { switch (type) { case 'scene': dependency = this.loadScene(index); break; case 'node': dependency = this.loadNode(index); break; case 'mesh': dependency = this._invokeOne(function (ext) { return ext.loadMesh && ext.loadMesh(index); }); break; case 'accessor': dependency = this.loadAccessor(index); break; case 'bufferView': dependency = this._invokeOne(function (ext) { return ext.loadBufferView && ext.loadBufferView(index); }); break; case 'buffer': dependency = this.loadBuffer(index); break; case 'material': dependency = this._invokeOne(function (ext) { return ext.loadMaterial && ext.loadMaterial(index); }); break; case 'texture': dependency = this._invokeOne(function (ext) { return ext.loadTexture && ext.loadTexture(index); }); break; case 'skin': dependency = this.loadSkin(index); break; case 'animation': dependency = this._invokeOne(function (ext) { return ext.loadAnimation && ext.loadAnimation(index); }); break; case 'camera': dependency = this.loadCamera(index); break; default: throw new Error('Unknown type: ' + type); } this.cache.add(cacheKey, dependency); } return dependency; } /** * Requests all dependencies of the specified type asynchronously, with caching. * @param {string} type * @return {Promise>} */ getDependencies(type) { var dependencies = this.cache.get(type); if (!dependencies) { var parser = this; var defs = this.json[type + (type === 'mesh' ? 'es' : 's')] || []; dependencies = Promise.all(defs.map(function (def, index) { return parser.getDependency(type, index); })); this.cache.add(type, dependencies); } return dependencies; } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views * @param {number} bufferIndex * @return {Promise} */ loadBuffer(bufferIndex) { var bufferDef = this.json.buffers[bufferIndex]; var loader = this.fileLoader; if (bufferDef.type && bufferDef.type !== 'arraybuffer') { throw new Error('THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.'); } // If present, GLB container is required to be the first buffer. if (bufferDef.uri === undefined && bufferIndex === 0) { return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body); } var options = this.options; return new Promise(function (resolve, reject) { loader.load(LoaderUtils.resolveURL(bufferDef.uri, options.path), resolve, undefined, function () { reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".')); }); }); } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views * @param {number} bufferViewIndex * @return {Promise} */ loadBufferView(bufferViewIndex) { var bufferViewDef = this.json.bufferViews[bufferViewIndex]; return this.getDependency('buffer', bufferViewDef.buffer).then(function (buffer) { var byteLength = bufferViewDef.byteLength || 0; var byteOffset = bufferViewDef.byteOffset || 0; return buffer.slice(byteOffset, byteOffset + byteLength); }); } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors * @param {number} accessorIndex * @return {Promise} */ loadAccessor(accessorIndex) { var parser = this; var json = this.json; var accessorDef = this.json.accessors[accessorIndex]; if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) { // Ignore empty accessors, which may be used to declare runtime // information about attributes coming from another source (e.g. Draco // compression extension). return Promise.resolve(null); } var pendingBufferViews = []; if (accessorDef.bufferView !== undefined) { pendingBufferViews.push(this.getDependency('bufferView', accessorDef.bufferView)); } else { pendingBufferViews.push(null); } if (accessorDef.sparse !== undefined) { pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.indices.bufferView)); pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.values.bufferView)); } return Promise.all(pendingBufferViews).then(function (bufferViews) { var bufferView = bufferViews[0]; var itemSize = WEBGL_TYPE_SIZES[accessorDef.type]; var TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12. var elementBytes = TypedArray.BYTES_PER_ELEMENT; var itemBytes = elementBytes * itemSize; var byteOffset = accessorDef.byteOffset || 0; var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined; var normalized = accessorDef.normalized === true; var array, bufferAttribute; // The buffer is not interleaved if the stride is the item size in bytes. if (byteStride && byteStride !== itemBytes) { // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer // This makes sure that IBA.count reflects accessor.count properly var ibSlice = Math.floor(byteOffset / byteStride); var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count; var ib = parser.cache.get(ibCacheKey); if (!ib) { array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes); // Integer parameters to IB/IBA are in array elements, not bytes. ib = new InterleavedBuffer(array, byteStride / elementBytes); parser.cache.add(ibCacheKey, ib); } bufferAttribute = new InterleavedBufferAttribute(ib, itemSize, byteOffset % byteStride / elementBytes, normalized); } else { if (bufferView === null) { array = new TypedArray(accessorDef.count * itemSize); } else { array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize); } bufferAttribute = new BufferAttribute(array, itemSize, normalized); } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors if (accessorDef.sparse !== undefined) { var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR; var TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType]; var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0; var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0; var sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices); var sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize); if (bufferView !== null) { // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes. bufferAttribute = new BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized); } for (var i = 0, il = sparseIndices.length; i < il; i++) { var index = sparseIndices[i]; bufferAttribute.setX(index, sparseValues[i * itemSize]); if (itemSize >= 2) bufferAttribute.setY(index, sparseValues[i * itemSize + 1]); if (itemSize >= 3) bufferAttribute.setZ(index, sparseValues[i * itemSize + 2]); if (itemSize >= 4) bufferAttribute.setW(index, sparseValues[i * itemSize + 3]); if (itemSize >= 5) throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.'); } } return bufferAttribute; }); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures * @param {number} textureIndex * @return {Promise} */ loadTexture(textureIndex) { var json = this.json; var options = this.options; var textureDef = json.textures[textureIndex]; var sourceIndex = textureDef.source; var sourceDef = json.images[sourceIndex]; var loader = this.textureLoader; if (sourceDef.uri) { var handler = options.manager.getHandler(sourceDef.uri); if (handler !== null) loader = handler; } return this.loadTextureImage(textureIndex, sourceIndex, loader); } loadTextureImage(textureIndex, sourceIndex, loader) { var parser = this; var json = this.json; var textureDef = json.textures[textureIndex]; var sourceDef = json.images[sourceIndex]; var cacheKey = (sourceDef.uri || sourceDef.bufferView) + ':' + textureDef.sampler; if (this.textureCache[cacheKey]) { // See https://github.com/mrdoob/three.js/issues/21559. return this.textureCache[cacheKey]; } var promise = this.loadImageSource(sourceIndex, loader).then(function (texture) { texture.flipY = false; texture.name = textureDef.name || sourceDef.name || ''; var samplers = json.samplers || {}; var sampler = samplers[textureDef.sampler] || {}; Potree.Utils.makeTexDontResize(texture); //add /* //xzw 删除设置,因为已经makeTexDontResize texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || LinearFilter; texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || LinearMipmapLinearFilter; texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || RepeatWrapping; texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || RepeatWrapping; */ parser.associations.set(texture, { textures: textureIndex }); return texture; }).catch(function () { return null; }); this.textureCache[cacheKey] = promise; return promise; } loadImageSource(sourceIndex, loader) { var parser = this; var json = this.json; var options = this.options; if (this.sourceCache[sourceIndex] !== undefined) { return this.sourceCache[sourceIndex].then(texture => texture.clone()); } var sourceDef = json.images[sourceIndex]; var URL = self.URL || self.webkitURL; var sourceURI = sourceDef.uri || ''; var isObjectURL = false; if (sourceDef.bufferView !== undefined) { // Load binary image data from bufferView, if provided. sourceURI = parser.getDependency('bufferView', sourceDef.bufferView).then(function (bufferView) { isObjectURL = true; var blob = new Blob([bufferView], { type: sourceDef.mimeType }); sourceURI = URL.createObjectURL(blob); return sourceURI; }); } else if (sourceDef.uri === undefined) { throw new Error('THREE.GLTFLoader: Image ' + sourceIndex + ' is missing URI and bufferView'); } var promise = Promise.resolve(sourceURI).then(function (sourceURI) { return new Promise(function (resolve, reject) { if (json.asset.generator == 'gltfpack 0.18') { //4dkk场景的模型 var onLoad = resolve; if (loader.isImageBitmapLoader === true) { onLoad = function onLoad(imageBitmap) { var texture = new Texture(imageBitmap); texture.needsUpdate = true; resolve(texture); }; } //loader.load( LoaderUtils.resolveURL( sourceURI, options.path ), onLoad, undefined, reject ); var url = parser.textureLoader.manager.resolveURL(sourceURI, options.path); loader.load(url, onLoad, undefined, reject); } else { //为了防止chrome出现报错 The source image could not be decoded. 导致reject,重新写贴图加载方式: xzw //但不知道为何有的场景(如4dkk的)不成功 parser.textureLoader.load(sourceURI, tex => { //原本:NearestMipMapNearestFilter 闪烁 有一个block文件离远了有裂缝,只能使用LinearFilter,但是这样似乎更卡,且锯齿 /* {//处理裂缝 tex.minFilter = THREE.LinearFilter tex.generateMipmaps = false } */ //console.log(tex.image.width, tex.image.height) resolve(tex); }, null, e => { console.log('error load tex', e); }); } }); }).then(function (texture) { // Clean up resources and configure Texture. if (isObjectURL === true) { URL.revokeObjectURL(sourceURI); } texture.userData = {}; //xzw add texture.userData.mimeType = sourceDef.mimeType || getImageURIMimeType(sourceDef.uri || sourceDef.mimeType); return texture; }).catch(function (error) { console.error('THREE.GLTFLoader: Couldn\'t load texture', sourceURI); throw error; }); this.sourceCache[sourceIndex] = promise; return promise; } /** * Asynchronously assigns a texture to the given material parameters. * @param {Object} materialParams * @param {string} mapName * @param {Object} mapDef * @return {Promise} */ assignTexture(materialParams, mapName, mapDef, encoding) { var parser = this; return this.getDependency('texture', mapDef.index).then(function (texture) { // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured // However, we will copy UV set 0 to UV set 1 on demand for aoMap if (mapDef.texCoord !== undefined && mapDef.texCoord != 0 && !(mapName === 'aoMap' && mapDef.texCoord == 1)) { console.warn('THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.'); } if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) { var transform = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined; if (transform) { var gltfReference = parser.associations.get(texture); texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform); parser.associations.set(texture, gltfReference); } } if (encoding !== undefined) { texture.encoding = encoding; } materialParams[mapName] = texture; return texture; }); } /** * Assigns final material to a Mesh, Line, or Points instance. The instance * already has a material (generated from the glTF material options alone) * but reuse of the same glTF material may require multiple threejs materials * to accommodate different primitive types, defines, etc. New materials will * be created if necessary, and reused from a cache. * @param {Object3D} mesh Mesh, Line, or Points instance. */ assignFinalMaterial(mesh) { var geometry = mesh.geometry; var material = mesh.material; var useDerivativeTangents = geometry.attributes.tangent === undefined; var useVertexColors = geometry.attributes.color !== undefined; var useFlatShading = geometry.attributes.normal === undefined; if (mesh.isPoints) { var cacheKey = 'PointsMaterial:' + material.uuid; var pointsMaterial = this.cache.get(cacheKey); if (!pointsMaterial) { pointsMaterial = new PointsMaterial(); Material.prototype.copy.call(pointsMaterial, material); pointsMaterial.color.copy(material.color); pointsMaterial.map = material.map; pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px this.cache.add(cacheKey, pointsMaterial); } material = pointsMaterial; } else if (mesh.isLine) { var _cacheKey = 'LineBasicMaterial:' + material.uuid; var lineMaterial = this.cache.get(_cacheKey); if (!lineMaterial) { lineMaterial = new LineBasicMaterial(); Material.prototype.copy.call(lineMaterial, material); lineMaterial.color.copy(material.color); this.cache.add(_cacheKey, lineMaterial); } material = lineMaterial; } // Clone the material if it will be modified if (useDerivativeTangents || useVertexColors || useFlatShading) { var _cacheKey2 = 'ClonedMaterial:' + material.uuid + ':'; if (material.isGLTFSpecularGlossinessMaterial) _cacheKey2 += 'specular-glossiness:'; if (useDerivativeTangents) _cacheKey2 += 'derivative-tangents:'; if (useVertexColors) _cacheKey2 += 'vertex-colors:'; if (useFlatShading) _cacheKey2 += 'flat-shading:'; var cachedMaterial = this.cache.get(_cacheKey2); if (!cachedMaterial) { cachedMaterial = material.clone(); if (useVertexColors) cachedMaterial.vertexColors = true; if (useFlatShading) cachedMaterial.flatShading = true; if (useDerivativeTangents) { // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995 if (cachedMaterial.normalScale) cachedMaterial.normalScale.y *= -1; if (cachedMaterial.clearcoatNormalScale) cachedMaterial.clearcoatNormalScale.y *= -1; } this.cache.add(_cacheKey2, cachedMaterial); this.associations.set(cachedMaterial, this.associations.get(material)); } material = cachedMaterial; } // workarounds for mesh and geometry if (material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined) { geometry.setAttribute('uv2', geometry.attributes.uv); } mesh.material = material; } getMaterialType( /* materialIndex */ ) { return MeshStandardMaterial; } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials * @param {number} materialIndex * @return {Promise} */ loadMaterial(materialIndex) { var parser = this; var json = this.json; var extensions = this.extensions; var materialDef = json.materials[materialIndex]; if (!materialDef) { console.error('gltf材质数据有问题, 可能引起一些列错误'); //add materialDef = json.materials[0] || {}; } var materialType; var materialParams = {}; var materialExtensions = materialDef.extensions || {}; var pending = []; if (materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]) { var sgExtension = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]; materialType = BasicMaterial; //sgExtension.getMaterialType(); //xzw 改 pending.push(sgExtension.extendParams(materialParams, materialDef, parser)); } else if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) { var kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT]; materialType = BasicMaterial; //kmuExtension.getMaterialType(); //xzw 改 pending.push(kmuExtension.extendParams(materialParams, materialDef, parser)); } else { // Specification: // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material var metallicRoughness = materialDef.pbrMetallicRoughness || {}; materialParams.color = new Color(1.0, 1.0, 1.0); materialParams.opacity = 1.0; if (Array.isArray(metallicRoughness.baseColorFactor)) { var array = metallicRoughness.baseColorFactor; materialParams.color.fromArray(array); materialParams.opacity = array[3]; } if (metallicRoughness.baseColorTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture, sRGBEncoding)); } materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0; materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0; if (metallicRoughness.metallicRoughnessTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture)); pending.push(parser.assignTexture(materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture)); } materialType = this._invokeOne(function (ext) { //return BasicMaterial //2024.7放弃使用这个,因为纯色的看上去连成一片 //kmuExtension.getMaterialType(); //xzw 改 return ext.getMaterialType && ext.getMaterialType(materialIndex); }); pending.push(Promise.all(this._invokeAll(function (ext) { return ext.extendMaterialParams && ext.extendMaterialParams(materialIndex, materialParams); }))); } if (materialDef.doubleSided === true) { materialParams.side = DoubleSide; } var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE; if (alphaMode === ALPHA_MODES.BLEND) { materialParams.transparent = true; // See: https://github.com/mrdoob/three.js/issues/17706 materialParams.depthWrite = false; } else { materialParams.transparent = false; if (alphaMode === ALPHA_MODES.MASK) { materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5; } } if (materialDef.normalTexture !== undefined && materialType !== MeshBasicMaterial) { pending.push(parser.assignTexture(materialParams, 'normalMap', materialDef.normalTexture)); materialParams.normalScale = new Vector2(1, 1); if (materialDef.normalTexture.scale !== undefined) { var scale = materialDef.normalTexture.scale; materialParams.normalScale.set(scale, scale); } } if (materialDef.occlusionTexture !== undefined && materialType !== MeshBasicMaterial) { pending.push(parser.assignTexture(materialParams, 'aoMap', materialDef.occlusionTexture)); if (materialDef.occlusionTexture.strength !== undefined) { materialParams.aoMapIntensity = materialDef.occlusionTexture.strength; } } if (materialDef.emissiveFactor !== undefined && materialType !== MeshBasicMaterial) { materialParams.emissive = new Color().fromArray(materialDef.emissiveFactor); } if (materialDef.emissiveTexture !== undefined && materialType !== MeshBasicMaterial) { pending.push(parser.assignTexture(materialParams, 'emissiveMap', materialDef.emissiveTexture, sRGBEncoding)); } return Promise.all(pending).then(function () { var material; if (materialType === GLTFMeshStandardSGMaterial) { material = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams); } else { material = new materialType(materialParams); } if (materialDef.name) material.name = materialDef.name; assignExtrasToUserData(material, materialDef); parser.associations.set(material, { materials: materialIndex }); if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef); return material; }); } /** When Object3D instances are targeted by animation, they need unique names. */ createUniqueName(originalName) { var sanitizedName = PropertyBinding.sanitizeNodeName(originalName || ''); var name = sanitizedName; for (var i = 1; this.nodeNamesUsed[name]; ++i) { name = sanitizedName + '_' + i; } this.nodeNamesUsed[name] = true; return name; } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry * * Creates BufferGeometries from primitives. * * @param {Array} primitives * @return {Promise>} */ loadGeometries(primitives) { var parser = this; var extensions = this.extensions; var cache = this.primitiveCache; function createDracoPrimitive(primitive) { return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function (geometry) { return addPrimitiveAttributes(geometry, primitive, parser); }); } var pending = []; for (var i = 0, il = primitives.length; i < il; i++) { var primitive = primitives[i]; var cacheKey = createPrimitiveKey(primitive); // See if we've already created this geometry var cached = cache[cacheKey]; if (cached) { // Use the cached geometry if it exists pending.push(cached.promise); } else { var geometryPromise = void 0; if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) { // Use DRACO geometry if available geometryPromise = createDracoPrimitive(primitive); } else { // Otherwise create a new geometry geometryPromise = addPrimitiveAttributes(new BufferGeometry(), primitive, parser); } // Cache this geometry cache[cacheKey] = { primitive: primitive, promise: geometryPromise }; pending.push(geometryPromise); } } return Promise.all(pending); } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes * @param {number} meshIndex * @return {Promise} */ loadMesh(meshIndex) { var parser = this; var json = this.json; var extensions = this.extensions; var meshDef = json.meshes[meshIndex]; var primitives = meshDef.primitives; var pending = []; for (var i = 0, il = primitives.length; i < il; i++) { var material = primitives[i].material === undefined ? createDefaultMaterial(this.cache) : this.getDependency('material', primitives[i].material); pending.push(material); } pending.push(parser.loadGeometries(primitives)); return Promise.all(pending).then(function (results) { var materials = results.slice(0, results.length - 1); var geometries = results[results.length - 1]; var meshes = []; for (var _i4 = 0, _il3 = geometries.length; _i4 < _il3; _i4++) { var geometry = geometries[_i4]; var primitive = primitives[_i4]; // 1. create Mesh var mesh = void 0; var _material = materials[_i4]; if (primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === undefined) { // .isSkinnedMesh isn't in glTF spec. See ._markDefs() mesh = meshDef.isSkinnedMesh === true ? new SkinnedMesh(geometry, _material) : new Mesh(geometry, _material); if (mesh.isSkinnedMesh === true && !mesh.geometry.attributes.skinWeight.normalized) { // we normalize floating point skin weight array to fix malformed assets (see #15319) // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs mesh.normalizeSkinWeights(); } if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP) { mesh.geometry = toTrianglesDrawMode(mesh.geometry, TriangleStripDrawMode); } else if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN) { mesh.geometry = toTrianglesDrawMode(mesh.geometry, TriangleFanDrawMode); } } else if (primitive.mode === WEBGL_CONSTANTS.LINES) { mesh = new LineSegments(geometry, _material); } else if (primitive.mode === WEBGL_CONSTANTS.LINE_STRIP) { mesh = new Line(geometry, _material); } else if (primitive.mode === WEBGL_CONSTANTS.LINE_LOOP) { mesh = new LineLoop(geometry, _material); } else if (primitive.mode === WEBGL_CONSTANTS.POINTS) { mesh = new Points(geometry, _material); } else { throw new Error('THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode); } if (Object.keys(mesh.geometry.morphAttributes).length > 0) { updateMorphTargets(mesh, meshDef); } mesh.name = parser.createUniqueName(meshDef.name || 'mesh_' + meshIndex); assignExtrasToUserData(mesh, meshDef); if (primitive.extensions) addUnknownExtensionsToUserData(extensions, mesh, primitive); parser.assignFinalMaterial(mesh); meshes.push(mesh); } for (var _i5 = 0, _il4 = meshes.length; _i5 < _il4; _i5++) { parser.associations.set(meshes[_i5], { meshes: meshIndex, primitives: _i5 }); } if (meshes.length === 1) { return meshes[0]; } var group = new Group(); parser.associations.set(group, { meshes: meshIndex }); for (var _i6 = 0, _il5 = meshes.length; _i6 < _il5; _i6++) { group.add(meshes[_i6]); } return group; }); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras * @param {number} cameraIndex * @return {Promise} */ loadCamera(cameraIndex) { var camera; var cameraDef = this.json.cameras[cameraIndex]; var params = cameraDef[cameraDef.type]; if (!params) { console.warn('THREE.GLTFLoader: Missing camera parameters.'); return; } if (cameraDef.type === 'perspective') { camera = new PerspectiveCamera(MathUtils.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6); } else if (cameraDef.type === 'orthographic') { camera = new OrthographicCamera(-params.xmag, params.xmag, params.ymag, -params.ymag, params.znear, params.zfar); } if (cameraDef.name) camera.name = this.createUniqueName(cameraDef.name); assignExtrasToUserData(camera, cameraDef); return Promise.resolve(camera); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins * @param {number} skinIndex * @return {Promise} */ loadSkin(skinIndex) { var skinDef = this.json.skins[skinIndex]; var skinEntry = { joints: skinDef.joints }; if (skinDef.inverseBindMatrices === undefined) { return Promise.resolve(skinEntry); } return this.getDependency('accessor', skinDef.inverseBindMatrices).then(function (accessor) { skinEntry.inverseBindMatrices = accessor; return skinEntry; }); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations * @param {number} animationIndex * @return {Promise} */ loadAnimation(animationIndex) { var json = this.json; var animationDef = json.animations[animationIndex]; var pendingNodes = []; var pendingInputAccessors = []; var pendingOutputAccessors = []; var pendingSamplers = []; var pendingTargets = []; for (var i = 0, il = animationDef.channels.length; i < il; i++) { var channel = animationDef.channels[i]; var sampler = animationDef.samplers[channel.sampler]; var target = channel.target; var name = target.node; var input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input; var output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output; pendingNodes.push(this.getDependency('node', name)); pendingInputAccessors.push(this.getDependency('accessor', input)); pendingOutputAccessors.push(this.getDependency('accessor', output)); pendingSamplers.push(sampler); pendingTargets.push(target); } return Promise.all([Promise.all(pendingNodes), Promise.all(pendingInputAccessors), Promise.all(pendingOutputAccessors), Promise.all(pendingSamplers), Promise.all(pendingTargets)]).then(function (dependencies) { var nodes = dependencies[0]; var inputAccessors = dependencies[1]; var outputAccessors = dependencies[2]; var samplers = dependencies[3]; var targets = dependencies[4]; var tracks = []; var _loop2 = function _loop2() { var node = nodes[_i7]; var inputAccessor = inputAccessors[_i7]; var outputAccessor = outputAccessors[_i7]; var sampler = samplers[_i7]; var target = targets[_i7]; if (node === undefined) return 1; // continue node.updateMatrix(); var TypedKeyframeTrack; switch (PATH_PROPERTIES[target.path]) { case PATH_PROPERTIES.weights: TypedKeyframeTrack = NumberKeyframeTrack; break; case PATH_PROPERTIES.rotation: TypedKeyframeTrack = QuaternionKeyframeTrack; break; case PATH_PROPERTIES.position: case PATH_PROPERTIES.scale: default: TypedKeyframeTrack = VectorKeyframeTrack; break; } var targetName = node.name ? node.name : node.uuid; var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : InterpolateLinear; var targetNames = []; if (PATH_PROPERTIES[target.path] === PATH_PROPERTIES.weights) { node.traverse(function (object) { if (object.morphTargetInfluences) { targetNames.push(object.name ? object.name : object.uuid); } }); } else { targetNames.push(targetName); } var outputArray = outputAccessor.array; if (outputAccessor.normalized) { var scale = getNormalizedComponentScale(outputArray.constructor); var scaled = new Float32Array(outputArray.length); for (var j = 0, jl = outputArray.length; j < jl; j++) { scaled[j] = outputArray[j] * scale; } outputArray = scaled; } for (var _j = 0, _jl = targetNames.length; _j < _jl; _j++) { var track = new TypedKeyframeTrack(targetNames[_j] + '.' + PATH_PROPERTIES[target.path], inputAccessor.array, outputArray, interpolation); // Override interpolation with custom factory method. if (sampler.interpolation === 'CUBICSPLINE') { track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) { // A CUBICSPLINE keyframe in glTF has three output values for each input value, // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize() // must be divided by three to get the interpolant's sampleSize argument. var interpolantType = this instanceof QuaternionKeyframeTrack ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant; return new interpolantType(this.times, this.values, this.getValueSize() / 3, result); }; // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true; } tracks.push(track); } }; for (var _i7 = 0, _il6 = nodes.length; _i7 < _il6; _i7++) { if (_loop2()) continue; } var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex; return new AnimationClip(name, undefined, tracks); }); } createNodeMesh(nodeIndex) { var json = this.json; var parser = this; var nodeDef = json.nodes[nodeIndex]; if (nodeDef.mesh === undefined) return null; return parser.getDependency('mesh', nodeDef.mesh).then(function (mesh) { var node = parser._getNodeRef(parser.meshCache, nodeDef.mesh, mesh); // if weights are provided on the node, override weights on the mesh. if (nodeDef.weights !== undefined) { node.traverse(function (o) { if (!o.isMesh) return; for (var i = 0, il = nodeDef.weights.length; i < il; i++) { o.morphTargetInfluences[i] = nodeDef.weights[i]; } }); } return node; }); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy * @param {number} nodeIndex * @return {Promise} */ loadNode(nodeIndex) { var json = this.json; var extensions = this.extensions; var parser = this; var nodeDef = json.nodes[nodeIndex]; // reserve node's name before its dependencies, so the root has the intended name. var nodeName = nodeDef.name ? parser.createUniqueName(nodeDef.name) : ''; return function () { var pending = []; var meshPromise = parser._invokeOne(function (ext) { return ext.createNodeMesh && ext.createNodeMesh(nodeIndex); }); if (meshPromise) { pending.push(meshPromise); } if (nodeDef.camera !== undefined) { pending.push(parser.getDependency('camera', nodeDef.camera).then(function (camera) { return parser._getNodeRef(parser.cameraCache, nodeDef.camera, camera); })); } parser._invokeAll(function (ext) { return ext.createNodeAttachment && ext.createNodeAttachment(nodeIndex); }).forEach(function (promise) { pending.push(promise); }); return Promise.all(pending); }().then(function (objects) { var node; // .isBone isn't in glTF spec. See ._markDefs if (nodeDef.isBone === true) { node = new Bone(); } else if (objects.length > 1) { node = new Group(); } else if (objects.length === 1) { node = objects[0]; } else { node = new Object3D(); } if (node !== objects[0]) { for (var i = 0, il = objects.length; i < il; i++) { node.add(objects[i]); } } if (nodeDef.name) { node.userData.name = nodeDef.name; node.name = nodeName; } assignExtrasToUserData(node, nodeDef); if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef); if (nodeDef.matrix !== undefined) { var matrix = new Matrix4(); matrix.fromArray(nodeDef.matrix); node.applyMatrix4(matrix); } else { if (nodeDef.translation !== undefined) { node.position.fromArray(nodeDef.translation); } if (nodeDef.rotation !== undefined) { node.quaternion.fromArray(nodeDef.rotation); } if (nodeDef.scale !== undefined) { node.scale.fromArray(nodeDef.scale); } } if (!parser.associations.has(node)) { parser.associations.set(node, {}); } parser.associations.get(node).nodes = nodeIndex; return node; }); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes * @param {number} sceneIndex * @return {Promise} */ loadScene(sceneIndex) { var json = this.json; var extensions = this.extensions; var sceneDef = this.json.scenes[sceneIndex]; var parser = this; // Loader returns Group, not Scene. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172 var scene = new Group(); if (sceneDef.name) scene.name = parser.createUniqueName(sceneDef.name); assignExtrasToUserData(scene, sceneDef); if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef); var nodeIds = sceneDef.nodes || []; var pending = []; for (var i = 0, il = nodeIds.length; i < il; i++) { pending.push(buildNodeHierarchy(nodeIds[i], scene, json, parser)); } return Promise.all(pending).then(function () { // Removes dangling associations, associations that reference a node that // didn't make it into the scene. var reduceAssociations = node => { var reducedAssociations = new Map(); for (var [key, value] of parser.associations) { if (key instanceof Material || key instanceof Texture) { reducedAssociations.set(key, value); } } node.traverse(node => { var mappings = parser.associations.get(node); if (mappings != null) { reducedAssociations.set(node, mappings); } }); return reducedAssociations; }; parser.associations = reduceAssociations(scene); return scene; }); } } function buildNodeHierarchy(nodeId, parentObject, json, parser) { var nodeDef = json.nodes[nodeId]; return parser.getDependency('node', nodeId).then(function (node) { if (nodeDef.skin === undefined) return node; // build skeleton here as well var skinEntry; return parser.getDependency('skin', nodeDef.skin).then(function (skin) { skinEntry = skin; var pendingJoints = []; for (var i = 0, il = skinEntry.joints.length; i < il; i++) { pendingJoints.push(parser.getDependency('node', skinEntry.joints[i])); } return Promise.all(pendingJoints); }).then(function (jointNodes) { node.traverse(function (mesh) { if (!mesh.isMesh) return; var bones = []; var boneInverses = []; for (var j = 0, jl = jointNodes.length; j < jl; j++) { var jointNode = jointNodes[j]; if (jointNode) { bones.push(jointNode); var mat = new Matrix4(); if (skinEntry.inverseBindMatrices !== undefined) { mat.fromArray(skinEntry.inverseBindMatrices.array, j * 16); } boneInverses.push(mat); } else { console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[j]); } } mesh.bind(new Skeleton(bones, boneInverses), mesh.matrixWorld); }); return node; }); }).then(function (node) { // build node hierachy parentObject.add(node); var pending = []; if (nodeDef.children) { var children = nodeDef.children; for (var i = 0, il = children.length; i < il; i++) { var child = children[i]; pending.push(buildNodeHierarchy(child, node, json, parser)); } } return Promise.all(pending); }); } /** * @param {BufferGeometry} geometry * @param {GLTF.Primitive} primitiveDef * @param {GLTFParser} parser */ function computeBounds(geometry, primitiveDef, parser) { var attributes = primitiveDef.attributes; var box = new Box3(); if (attributes.POSITION !== undefined) { var accessor = parser.json.accessors[attributes.POSITION]; var min = accessor.min; var max = accessor.max; // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement. if (min !== undefined && max !== undefined) { box.set(new Vector3(min[0], min[1], min[2]), new Vector3(max[0], max[1], max[2])); if (accessor.normalized) { var boxScale = getNormalizedComponentScale(WEBGL_COMPONENT_TYPES[accessor.componentType]); box.min.multiplyScalar(boxScale); box.max.multiplyScalar(boxScale); } } else { console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.'); return; } } else { return; } var targets = primitiveDef.targets; if (targets !== undefined) { var maxDisplacement = new Vector3(); var vector = new Vector3(); for (var i = 0, il = targets.length; i < il; i++) { var target = targets[i]; if (target.POSITION !== undefined) { var _accessor = parser.json.accessors[target.POSITION]; var _min = _accessor.min; var _max = _accessor.max; // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement. if (_min !== undefined && _max !== undefined) { // we need to get max of absolute components because target weight is [-1,1] vector.setX(Math.max(Math.abs(_min[0]), Math.abs(_max[0]))); vector.setY(Math.max(Math.abs(_min[1]), Math.abs(_max[1]))); vector.setZ(Math.max(Math.abs(_min[2]), Math.abs(_max[2]))); if (_accessor.normalized) { var _boxScale = getNormalizedComponentScale(WEBGL_COMPONENT_TYPES[_accessor.componentType]); vector.multiplyScalar(_boxScale); } // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets // are used to implement key-frame animations and as such only two are active at a time - this results in very large // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size. maxDisplacement.max(vector); } else { console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.'); } } } // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets. box.expandByVector(maxDisplacement); } geometry.boundingBox = box; var sphere = new Sphere(); box.getCenter(sphere.center); sphere.radius = box.min.distanceTo(box.max) / 2; geometry.boundingSphere = sphere; } /** * @param {BufferGeometry} geometry * @param {GLTF.Primitive} primitiveDef * @param {GLTFParser} parser * @return {Promise} */ function addPrimitiveAttributes(geometry, primitiveDef, parser) { var attributes = primitiveDef.attributes; var pending = []; function assignAttributeAccessor(accessorIndex, attributeName) { return parser.getDependency('accessor', accessorIndex).then(function (accessor) { geometry.setAttribute(attributeName, accessor); }); } for (var gltfAttributeName in attributes) { var threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase(); // Skip attributes already provided by e.g. Draco extension. if (threeAttributeName in geometry.attributes) continue; pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName)); } if (primitiveDef.indices !== undefined && !geometry.index) { var accessor = parser.getDependency('accessor', primitiveDef.indices).then(function (accessor) { geometry.setIndex(accessor); }); pending.push(accessor); } assignExtrasToUserData(geometry, primitiveDef); computeBounds(geometry, primitiveDef, parser); return Promise.all(pending).then(function () { return primitiveDef.targets !== undefined ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry; }); } /** * @param {BufferGeometry} geometry * @param {Number} drawMode * @return {BufferGeometry} */ function toTrianglesDrawMode(geometry, drawMode) { var index = geometry.getIndex(); // generate index if not present if (index === null) { var indices = []; var position = geometry.getAttribute('position'); if (position !== undefined) { for (var i = 0; i < position.count; i++) { indices.push(i); } geometry.setIndex(indices); index = geometry.getIndex(); } else { console.error('THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.'); return geometry; } } // var numberOfTriangles = index.count - 2; var newIndices = []; if (drawMode === TriangleFanDrawMode) { // gl.TRIANGLE_FAN for (var _i8 = 1; _i8 <= numberOfTriangles; _i8++) { newIndices.push(index.getX(0)); newIndices.push(index.getX(_i8)); newIndices.push(index.getX(_i8 + 1)); } } else { // gl.TRIANGLE_STRIP for (var _i9 = 0; _i9 < numberOfTriangles; _i9++) { if (_i9 % 2 === 0) { newIndices.push(index.getX(_i9)); newIndices.push(index.getX(_i9 + 1)); newIndices.push(index.getX(_i9 + 2)); } else { newIndices.push(index.getX(_i9 + 2)); newIndices.push(index.getX(_i9 + 1)); newIndices.push(index.getX(_i9)); } } } if (newIndices.length / 3 !== numberOfTriangles) { console.error('THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.'); } // build final geometry var newGeometry = geometry.clone(); newGeometry.setIndex(newIndices); return newGeometry; } var globalThis=window;//add 有的app没有globalThis. 2023.1 var rtcCenterGlobal=false;//默认false,也就是scale.z要乘以-1 /*! ***************************************************************************** github: https://github.com/nytimes/three-loader-3dtiles Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */var visiGeoCount=0;var maxVertexVisi=5e6;var maxTexVisi=500;var maxDepth=100;function getGpuMemoryUsage(){var win=arguments.length>0&&arguments[0]!==undefined?arguments[0]:window;//总的 var c=0;viewer.setAllTilesets(model=>{var tileset3D=model.runtime.getTileset();c+=tileset3D.gpuMemoryUsageInBytes;});if(win.parent!=win){//还有父级页面。 暂时只有子级需要考虑父级,假设父级在前台时子级已经销毁 c+=getGpuMemoryUsage(win.parent);}viewer.tiles3dMemoryUsage=c;return c;}function __awaiter(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value);});}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value));}catch(e){reject(e);}}function rejected(value){try{step(generator["throw"](value));}catch(e){reject(e);}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected);}step((generator=generator.apply(thisArg,_arguments||[])).next());});}function assert$7(condition,message){if(!condition){throw new Error(message||'loader assertion failed.');}}var isBrowser$2=Boolean(typeof process!=='object'||String(process)!=='[object process]'||process.browser);var matches$1=typeof process!=='undefined'&&process.version&&/v([0-9]*)/.exec(process.version);matches$1&&parseFloat(matches$1[1])||0;var VERSION$8="3.1.4";function assert$6(condition,message){if(!condition){throw new Error(message||'loaders.gl assertion failed.');}}var globals$1={self:typeof self!=='undefined'&&self,window:typeof window!=='undefined'&&window,global:typeof global!=='undefined'&&global,document:typeof document!=='undefined'&&document};var global_=globals$1.global||globals$1.self||globals$1.window||{};var isBrowser$1=typeof process!=='object'||String(process)!=='[object process]'||process.browser;var isWorker=typeof importScripts==='function';var isMobile=typeof window!=='undefined'&&typeof window.orientation!=='undefined';var matches=typeof process!=='undefined'&&process.version&&/v([0-9]*)/.exec(process.version);matches&&parseFloat(matches[1])||0;function _defineProperty$1(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;}class WorkerJob{constructor(jobName,workerThread){_defineProperty$1(this,"name",void 0);_defineProperty$1(this,"workerThread",void 0);_defineProperty$1(this,"isRunning",void 0);_defineProperty$1(this,"result",void 0);_defineProperty$1(this,"_resolve",void 0);_defineProperty$1(this,"_reject",void 0);this.name=jobName;this.workerThread=workerThread;this.isRunning=true;this._resolve=()=>{};this._reject=()=>{};this.result=new Promise((resolve,reject)=>{this._resolve=resolve;this._reject=reject;});}postMessage(type,payload){this.workerThread.postMessage({source:'loaders.gl',type,payload});}done(value){assert$6(this.isRunning);this.isRunning=false;this._resolve(value);}error(error){assert$6(this.isRunning);this.isRunning=false;this._reject(error);}}var workerURLCache=new Map();function getLoadableWorkerURL(props){assert$6(props.source&&!props.url||!props.source&&props.url);var workerURL=workerURLCache.get(props.source||props.url);if(!workerURL){if(props.url){workerURL=getLoadableWorkerURLFromURL(props.url);workerURLCache.set(props.url,workerURL);}if(props.source){workerURL=getLoadableWorkerURLFromSource(props.source);workerURLCache.set(props.source,workerURL);}}assert$6(workerURL);return workerURL;}function getLoadableWorkerURLFromURL(url){if(!url.startsWith('http')){return url;}var workerSource=buildScriptSource(url);return getLoadableWorkerURLFromSource(workerSource);}function getLoadableWorkerURLFromSource(workerSource){var blob=new Blob([workerSource],{type:'application/javascript'});return URL.createObjectURL(blob);}function buildScriptSource(workerUrl){return "try {\n importScripts('".concat(workerUrl,"');\n} catch (error) {\n console.error(error);\n throw error;\n}");}function getTransferList(object){var recursive=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;var transfers=arguments.length>2?arguments[2]:undefined;var transfersSet=transfers||new Set();if(!object);else if(isTransferable(object)){transfersSet.add(object);}else if(isTransferable(object.buffer)){transfersSet.add(object.buffer);}else if(ArrayBuffer.isView(object));else if(recursive&&typeof object==='object'){for(var key in object){getTransferList(object[key],recursive,transfersSet);}}return transfers===undefined?Array.from(transfersSet):[];}function isTransferable(object){if(!object){return false;}if(object instanceof ArrayBuffer){return true;}if(typeof MessagePort!=='undefined'&&object instanceof MessagePort){return true;}if(typeof ImageBitmap!=='undefined'&&object instanceof ImageBitmap){return true;}if(typeof OffscreenCanvas!=='undefined'&&object instanceof OffscreenCanvas){return true;}return false;}var NOOP=()=>{};class WorkerThread{static isSupported(){return typeof Worker!=='undefined';}constructor(props){_defineProperty$1(this,"name",void 0);_defineProperty$1(this,"source",void 0);_defineProperty$1(this,"url",void 0);_defineProperty$1(this,"terminated",false);_defineProperty$1(this,"worker",void 0);_defineProperty$1(this,"onMessage",void 0);_defineProperty$1(this,"onError",void 0);_defineProperty$1(this,"_loadableURL",'');var{name,source,url}=props;assert$6(source||url);this.name=name;this.source=source;this.url=url;this.onMessage=NOOP;this.onError=error=>console.log(error);this.worker=this._createBrowserWorker();}destroy(){this.onMessage=NOOP;this.onError=NOOP;this.worker.terminate();this.terminated=true;}get isRunning(){return Boolean(this.onMessage);}postMessage(data,transferList){transferList=transferList||getTransferList(data);this.worker.postMessage(data,transferList);}_getErrorFromErrorEvent(event){var message='Failed to load ';message+="worker ".concat(this.name," from ").concat(this.url,". ");if(event.message){message+="".concat(event.message," in ");}if(event.lineno){message+=":".concat(event.lineno,":").concat(event.colno);}return new Error(message);}_createBrowserWorker(){this._loadableURL=getLoadableWorkerURL({source:this.source,url:this.url});var worker=new Worker(this._loadableURL,{name:this.name});worker.onmessage=event=>{if(!event.data){this.onError(new Error('No data received'));}else {this.onMessage(event.data);}};worker.onerror=error=>{this.onError(this._getErrorFromErrorEvent(error));this.terminated=true;};worker.onmessageerror=event=>console.error(event);return worker;}}class WorkerPool$2{constructor(props){_defineProperty$1(this,"name",'unnamed');_defineProperty$1(this,"source",void 0);_defineProperty$1(this,"url",void 0);_defineProperty$1(this,"maxConcurrency",1);_defineProperty$1(this,"maxMobileConcurrency",1);_defineProperty$1(this,"onDebug",()=>{});_defineProperty$1(this,"reuseWorkers",true);_defineProperty$1(this,"props",{});_defineProperty$1(this,"jobQueue",[]);_defineProperty$1(this,"idleQueue",[]);_defineProperty$1(this,"count",0);_defineProperty$1(this,"isDestroyed",false);this.source=props.source;this.url=props.url;this.setProps(props);}destroy(){this.idleQueue.forEach(worker=>worker.destroy());this.isDestroyed=true;}setProps(props){this.props=_objectSpread2(_objectSpread2({},this.props),props);if(props.name!==undefined){this.name=props.name;}if(props.maxConcurrency!==undefined){this.maxConcurrency=props.maxConcurrency;}if(props.maxMobileConcurrency!==undefined){this.maxMobileConcurrency=props.maxMobileConcurrency;}if(props.reuseWorkers!==undefined){this.reuseWorkers=props.reuseWorkers;}if(props.onDebug!==undefined){this.onDebug=props.onDebug;}}async startJob(name){var onMessage=arguments.length>1&&arguments[1]!==undefined?arguments[1]:(job,type,data)=>job.done(data);var onError=arguments.length>2&&arguments[2]!==undefined?arguments[2]:(job,error)=>job.error(error);var startPromise=new Promise(onStart=>{this.jobQueue.push({name,onMessage,onError,onStart});return this;});this._startQueuedJob();return await startPromise;}async _startQueuedJob(){if(!this.jobQueue.length){return;}var workerThread=this._getAvailableWorker();if(!workerThread){return;}var queuedJob=this.jobQueue.shift();if(queuedJob){this.onDebug({message:'Starting job',name:queuedJob.name,workerThread,backlog:this.jobQueue.length});var job=new WorkerJob(queuedJob.name,workerThread);workerThread.onMessage=data=>queuedJob.onMessage(job,data.type,data.payload);workerThread.onError=error=>queuedJob.onError(job,error);queuedJob.onStart(job);try{await job.result;}finally{this.returnWorkerToQueue(workerThread);}}}returnWorkerToQueue(worker){var shouldDestroyWorker=this.isDestroyed||!this.reuseWorkers||this.count>this._getMaxConcurrency();if(shouldDestroyWorker){worker.destroy();this.count--;}else {this.idleQueue.push(worker);}if(!this.isDestroyed){this._startQueuedJob();}}_getAvailableWorker(){if(this.idleQueue.length>0){return this.idleQueue.shift()||null;}if(this.count{},reuseWorkers:true};class WorkerFarm{static isSupported(){return WorkerThread.isSupported();}static getWorkerFarm(){var props=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};WorkerFarm._workerFarm=WorkerFarm._workerFarm||new WorkerFarm({});WorkerFarm._workerFarm.setProps(props);return WorkerFarm._workerFarm;}constructor(props){_defineProperty$1(this,"props",void 0);_defineProperty$1(this,"workerPools",new Map());this.props=_objectSpread2({},DEFAULT_PROPS$3);this.setProps(props);this.workerPools=new Map();}destroy(){for(var workerPool of this.workerPools.values()){workerPool.destroy();}}setProps(props){this.props=_objectSpread2(_objectSpread2({},this.props),props);for(var workerPool of this.workerPools.values()){workerPool.setProps(this._getWorkerPoolProps());}}getWorkerPool(options){var{name,source,url}=options;var workerPool=this.workerPools.get(name);if(!workerPool){workerPool=new WorkerPool$2({name,source,url});workerPool.setProps(this._getWorkerPoolProps());this.workerPools.set(name,workerPool);}return workerPool;}_getWorkerPoolProps(){return {maxConcurrency:this.props.maxConcurrency,maxMobileConcurrency:this.props.maxMobileConcurrency,reuseWorkers:this.props.reuseWorkers,onDebug:this.props.onDebug};}}_defineProperty$1(WorkerFarm,"_workerFarm",void 0);var NPM_TAG='latest';function getWorkerURL(worker){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var workerOptions=options[worker.id]||{};var workerFile="".concat(worker.id,"-worker.js");var url=workerOptions.workerUrl;if(!url&&worker.id==='compression'){url=options.workerUrl;}if(options._workerType==='test'){url="modules/".concat(worker.module,"/dist/").concat(workerFile);}if(!url){var version=worker.version;if(version==='latest'){version=NPM_TAG;}var versionTag=version?"@".concat(version):'';url="https://unpkg.com/@loaders.gl/".concat(worker.module).concat(versionTag,"/dist/").concat(workerFile);}assert$6(url);return url;}function validateWorkerVersion(worker){var coreVersion=arguments.length>1&&arguments[1]!==undefined?arguments[1]:VERSION$8;assert$6(worker,'no worker provided');var workerVersion=worker.version;if(!coreVersion||!workerVersion){return false;}return true;}var ChildProcessProxy={};var node=/*#__PURE__*/Object.freeze(/*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(null),ChildProcessProxy,{'default':ChildProcessProxy}));var VERSION$7="3.1.4";var loadLibraryPromises={};async function loadLibrary(libraryUrl){var moduleName=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};if(moduleName){libraryUrl=getLibraryUrl(libraryUrl,moduleName,options);}loadLibraryPromises[libraryUrl]=loadLibraryPromises[libraryUrl]||loadLibraryFromFile(libraryUrl);return await loadLibraryPromises[libraryUrl];}function getLibraryUrl(library,moduleName,options){if(library.startsWith('http')){return library;}var modules=options.modules||{};if(modules[library]){return modules[library];}if(!isBrowser$1){return "modules/".concat(moduleName,"/dist/libs/").concat(library);}if(options.CDN){assert$6(options.CDN.startsWith('http'));return "".concat(options.CDN,"/").concat(moduleName,"@").concat(VERSION$7,"/dist/libs/").concat(library);}if(isWorker){return "../src/libs/".concat(library);}return "modules/".concat(moduleName,"/src/libs/").concat(library);}async function loadLibraryFromFile(libraryUrl){if(libraryUrl.endsWith('wasm')){var _response=await fetch(libraryUrl);return await _response.arrayBuffer();}if(!isBrowser$1){try{return node&&ChildProcessProxy.requireFromFile&&(await ChildProcessProxy.requireFromFile(libraryUrl));}catch(_unused){return null;}}if(isWorker){return importScripts(libraryUrl);}var response=await fetch(libraryUrl);var scriptSource=await response.text();return loadLibraryFromString(scriptSource,libraryUrl);}function loadLibraryFromString(scriptSource,id){if(!isBrowser$1){return ChildProcessProxy.requireFromString&&ChildProcessProxy.requireFromString(scriptSource,id);}if(isWorker){eval.call(global_,scriptSource);return null;}var script=document.createElement('script');script.id=id;try{script.appendChild(document.createTextNode(scriptSource));}catch(e){script.text=scriptSource;}document.body.appendChild(script);return null;}function canParseWithWorker(loader,options){if(!WorkerFarm.isSupported()){return false;}return loader.worker&&(options===null||options===void 0?void 0:options.worker);}async function parseWithWorker(loader,data,options,context,parseOnMainThread){var name=loader.id;var url=getWorkerURL(loader,options);var workerFarm=WorkerFarm.getWorkerFarm(options);var workerPool=workerFarm.getWorkerPool({name,url});options=JSON.parse(JSON.stringify(options));var job=await workerPool.startJob('process-on-worker',onMessage.bind(null,parseOnMainThread));job.postMessage('process',{input:data,options});var result=await job.result;return await result.result;}async function onMessage(parseOnMainThread,job,type,payload){switch(type){case'done':job.done(payload);break;case'error':job.error(new Error(payload.error));break;case'process':var{id,input,options}=payload;try{var result=await parseOnMainThread(input,options);job.postMessage('done',{id,result});}catch(error){var message=error instanceof Error?error.message:'unknown error';job.postMessage('error',{id,error:message});}break;default:console.warn("parse-with-worker unknown message ".concat(type));}}function getFirstCharacters$1(data){var length=arguments.length>1&&arguments[1]!==undefined?arguments[1]:5;if(typeof data==='string'){return data.slice(0,length);}else if(ArrayBuffer.isView(data)){return getMagicString$3(data.buffer,data.byteOffset,length);}else if(data instanceof ArrayBuffer){var byteOffset=0;return getMagicString$3(data,byteOffset,length);}return '';}function getMagicString$3(arrayBuffer,byteOffset,length){if(arrayBuffer.byteLength<=byteOffset+length){return '';}var dataView=new DataView(arrayBuffer);var magic='';for(var _i=0;_isource2 instanceof ArrayBuffer?new Uint8Array(source2):source2);var byteLength=sourceArrays.reduce((length,typedArray)=>length+typedArray.byteLength,0);var result=new Uint8Array(byteLength);var offset=0;for(var sourceArray of sourceArrays){result.set(sourceArray,offset);offset+=sourceArray.byteLength;}return result.buffer;}function sliceArrayBuffer(arrayBuffer,byteOffset,byteLength){var subArray=byteLength!==undefined?new Uint8Array(arrayBuffer).subarray(byteOffset,byteOffset+byteLength):new Uint8Array(arrayBuffer).subarray(byteOffset);var arrayCopy=new Uint8Array(subArray);return arrayCopy.buffer;}function padToNBytes(byteLength,padding){assert$7(byteLength>=0);assert$7(padding>0);return byteLength+(padding-1)&~(padding-1);}function copyToArray(source,target,targetOffset){var sourceArray;if(source instanceof ArrayBuffer){sourceArray=new Uint8Array(source);}else {var srcByteOffset=source.byteOffset;var srcByteLength=source.byteLength;sourceArray=new Uint8Array(source.buffer||source.arrayBuffer,srcByteOffset,srcByteLength);}target.set(sourceArray,targetOffset);return targetOffset+padToNBytes(sourceArray.byteLength,4);}async function concatenateArrayBuffersAsync(asyncIterator){var arrayBuffers=[];var _iteratorAbruptCompletion=false;var _didIteratorError=false;var _iteratorError;try{for(var _iterator=_asyncIterator(asyncIterator),_step;_iteratorAbruptCompletion=!(_step=await _iterator.next()).done;_iteratorAbruptCompletion=false){var chunk=_step.value;{arrayBuffers.push(chunk);}}}catch(err){_didIteratorError=true;_iteratorError=err;}finally{try{if(_iteratorAbruptCompletion&&_iterator.return!=null){await _iterator.return();}}finally{if(_didIteratorError){throw _iteratorError;}}}return concatenateArrayBuffers(...arrayBuffers);}function getHiResTimestamp$1(){var timestamp;if(typeof window!=='undefined'&&window.performance){timestamp=window.performance.now();}else if(typeof process!=='undefined'&&process.hrtime){var timeParts=process.hrtime();timestamp=timeParts[0]*1000+timeParts[1]/1e6;}else {timestamp=Date.now();}return timestamp;}class Stat{constructor(name,type){_defineProperty$1(this,"name",void 0);_defineProperty$1(this,"type",void 0);_defineProperty$1(this,"sampleSize",1);_defineProperty$1(this,"time",void 0);_defineProperty$1(this,"count",void 0);_defineProperty$1(this,"samples",void 0);_defineProperty$1(this,"lastTiming",void 0);_defineProperty$1(this,"lastSampleTime",void 0);_defineProperty$1(this,"lastSampleCount",void 0);_defineProperty$1(this,"_count",0);_defineProperty$1(this,"_time",0);_defineProperty$1(this,"_samples",0);_defineProperty$1(this,"_startTime",0);_defineProperty$1(this,"_timerPending",false);this.name=name;this.type=type;this.reset();}setSampleSize(samples){this.sampleSize=samples;return this;}incrementCount(){this.addCount(1);return this;}decrementCount(){this.subtractCount(1);return this;}addCount(value){this._count+=value;this._samples++;this._checkSampling();return this;}subtractCount(value){this._count-=value;this._samples++;this._checkSampling();return this;}addTime(time){this._time+=time;this.lastTiming=time;this._samples++;this._checkSampling();return this;}timeStart(){this._startTime=getHiResTimestamp$1();this._timerPending=true;return this;}timeEnd(){if(!this._timerPending){return this;}this.addTime(getHiResTimestamp$1()-this._startTime);this._timerPending=false;this._checkSampling();return this;}getSampleAverageCount(){return this.sampleSize>0?this.lastSampleCount/this.sampleSize:0;}getSampleAverageTime(){return this.sampleSize>0?this.lastSampleTime/this.sampleSize:0;}getSampleHz(){return this.lastSampleTime>0?this.sampleSize/(this.lastSampleTime/1000):0;}getAverageCount(){return this.samples>0?this.count/this.samples:0;}getAverageTime(){return this.samples>0?this.time/this.samples:0;}getHz(){return this.time>0?this.samples/(this.time/1000):0;}reset(){this.time=0;this.count=0;this.samples=0;this.lastTiming=0;this.lastSampleTime=0;this.lastSampleCount=0;this._count=0;this._time=0;this._samples=0;this._startTime=0;this._timerPending=false;return this;}_checkSampling(){if(this._samples===this.sampleSize){this.lastSampleTime=this._time;this.lastSampleCount=this._count;this.count+=this._count;this.time+=this._time;this.samples+=this._samples;this._time=0;this._count=0;this._samples=0;}}}class Stats$1{constructor(options){_defineProperty$1(this,"id",void 0);_defineProperty$1(this,"stats",{});this.id=options.id;this.stats={};this._initializeStats(options.stats);Object.seal(this);}get(name){var type=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'count';return this._getOrCreate({name,type});}get size(){return Object.keys(this.stats).length;}reset(){for(var key in this.stats){this.stats[key].reset();}return this;}forEach(fn){for(var key in this.stats){fn(this.stats[key]);}}getTable(){var table={};this.forEach(stat=>{table[stat.name]={time:stat.time||0,count:stat.count||0,average:stat.getAverageTime()||0,hz:stat.getHz()||0};});return table;}_initializeStats(){var stats=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];stats.forEach(stat=>this._getOrCreate(stat));}_getOrCreate(stat){if(!stat||!stat.name){return null;}var{name,type}=stat;if(!this.stats[name]){if(stat instanceof Stat){this.stats[name]=stat;}else {this.stats[name]=new Stat(name,type);}}return this.stats[name];}}var STAT_QUEUED_REQUESTS='Queued Requests';var STAT_ACTIVE_REQUESTS='Active Requests';var STAT_CANCELLED_REQUESTS='Cancelled Requests';var STAT_QUEUED_REQUESTS_EVER='Queued Requests Ever';var STAT_ACTIVE_REQUESTS_EVER='Active Requests Ever';var DEFAULT_PROPS$2={id:'request-scheduler',throttleRequests:true,maxRequests:6};class RequestScheduler{constructor(){var props=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};_defineProperty$1(this,"props",void 0);_defineProperty$1(this,"stats",void 0);_defineProperty$1(this,"activeRequestCount",0);_defineProperty$1(this,"requestQueue",[]);_defineProperty$1(this,"requestMap",new Map());_defineProperty$1(this,"deferredUpdate",null);this.props=_objectSpread2(_objectSpread2({},DEFAULT_PROPS$2),props);this.stats=new Stats$1({id:this.props.id});this.stats.get(STAT_QUEUED_REQUESTS);this.stats.get(STAT_ACTIVE_REQUESTS);this.stats.get(STAT_CANCELLED_REQUESTS);this.stats.get(STAT_QUEUED_REQUESTS_EVER);this.stats.get(STAT_ACTIVE_REQUESTS_EVER);}scheduleRequest(handle){var getPriority=arguments.length>1&&arguments[1]!==undefined?arguments[1]:()=>0;if(!this.props.throttleRequests){return Promise.resolve({done:()=>{}});}if(this.requestMap.has(handle)){return this.requestMap.get(handle);}var request={handle,priority:0,getPriority};var promise=new Promise(resolve=>{request.resolve=resolve;return request;});this.requestQueue.push(request);this.requestMap.set(handle,promise);this._issueNewRequests();return promise;}_issueRequest(request){var{handle,resolve}=request;var isDone=false;var done=()=>{if(!isDone){isDone=true;this.requestMap.delete(handle);this.activeRequestCount--;this._issueNewRequests();}};this.activeRequestCount++;return resolve?resolve({done}):Promise.resolve({done});}_issueNewRequests(){if(!this.deferredUpdate){this.deferredUpdate=setTimeout(()=>this._issueNewRequestsAsync(),0);}}_issueNewRequestsAsync(){this.deferredUpdate=null;var freeSlots=Math.max(this.props.maxRequests-this.activeRequestCount,0);if(freeSlots===0){return;}this._updateAllRequests();for(var _i3=0;_i3a.priority-b.priority);}_updateRequest(request){request.priority=request.getPriority(request.handle);if(request.priority<0){request.resolve(null);return false;}return true;}}var pathPrefix='';var fileAliases={};function resolvePath(filename){for(var alias in fileAliases){if(filename.startsWith(alias)){var replacement=fileAliases[alias];filename=filename.replace(alias,replacement);}}if(!filename.startsWith('http://')&&!filename.startsWith('https://')){filename="".concat(pathPrefix).concat(filename);}return filename;}function filename(url){var slashIndex=url&&url.lastIndexOf('/');return slashIndex>=0?url.substr(slashIndex+1):'';}function dirname(url){var slashIndex=url&&url.lastIndexOf('/');return slashIndex>=0?url.substr(0,slashIndex):'';}var isBoolean=x=>typeof x==='boolean';var isFunction=x=>typeof x==='function';var isObject=x=>x!==null&&typeof x==='object';var isPureObject=x=>isObject(x)&&x.constructor==={}.constructor;var isIterable=x=>x&&typeof x[Symbol.iterator]==='function';var isAsyncIterable=x=>x&&typeof x[Symbol.asyncIterator]==='function';var isResponse=x=>typeof Response!=='undefined'&&x instanceof Response||x&&x.arrayBuffer&&x.text&&x.json;var isBlob=x=>typeof Blob!=='undefined'&&x instanceof Blob;var isBuffer=x=>x&&typeof x==='object'&&x.isBuffer;var isReadableDOMStream=x=>typeof ReadableStream!=='undefined'&&x instanceof ReadableStream||isObject(x)&&isFunction(x.tee)&&isFunction(x.cancel)&&isFunction(x.getReader);var isReadableNodeStream=x=>isObject(x)&&isFunction(x.read)&&isFunction(x.pipe)&&isBoolean(x.readable);var isReadableStream=x=>isReadableDOMStream(x)||isReadableNodeStream(x);var DATA_URL_PATTERN=/^data:([-\w.]+\/[-\w.+]+)(;|,)/;var MIME_TYPE_PATTERN=/^([-\w.]+\/[-\w.+]+)/;function parseMIMEType(mimeString){var matches=MIME_TYPE_PATTERN.exec(mimeString);if(matches){return matches[1];}return mimeString;}function parseMIMETypeFromURL(url){var matches=DATA_URL_PATTERN.exec(url);if(matches){return matches[1];}return '';}var QUERY_STRING_PATTERN=/\?.*/;function getResourceUrlAndType(resource){if(isResponse(resource)){var url=stripQueryString(resource.url||'');var contentTypeHeader=resource.headers.get('content-type')||'';return {url,type:parseMIMEType(contentTypeHeader)||parseMIMETypeFromURL(url)};}if(isBlob(resource)){return {url:stripQueryString(resource.name||''),type:resource.type||''};}if(typeof resource==='string'){return {url:stripQueryString(resource),type:parseMIMETypeFromURL(resource)};}return {url:'',type:''};}function getResourceContentLength(resource){if(isResponse(resource)){return resource.headers['content-length']||-1;}if(isBlob(resource)){return resource.size;}if(typeof resource==='string'){return resource.length;}if(resource instanceof ArrayBuffer){return resource.byteLength;}if(ArrayBuffer.isView(resource)){return resource.byteLength;}return -1;}function stripQueryString(url){return url.replace(QUERY_STRING_PATTERN,'');}async function makeResponse(resource){if(isResponse(resource)){return resource;}var headers={};var contentLength=getResourceContentLength(resource);if(contentLength>=0){headers['content-length']=String(contentLength);}var{url,type}=getResourceUrlAndType(resource);if(type){headers['content-type']=type;}var initialDataUrl=await getInitialDataUrl(resource);if(initialDataUrl){headers['x-first-bytes']=initialDataUrl;}if(typeof resource==='string'){resource=new TextEncoder().encode(resource);}var response=new Response(resource,{headers});Object.defineProperty(response,'url',{value:url});return response;}async function checkResponse(response){if(!response.ok){var message=await getResponseError(response);throw new Error(message);}}async function getResponseError(response){var message="Failed to fetch resource ".concat(response.url," (").concat(response.status,"): ");try{var contentType=response.headers.get('Content-Type');var text=response.statusText;if(contentType.includes('application/json')){text+=" ".concat(await response.text());}message+=text;message=message.length>60?"".concat(message.slice(60),"..."):message;}catch(error){}return message;}async function getInitialDataUrl(resource){var INITIAL_DATA_LENGTH=5;if(typeof resource==='string'){return "data:,".concat(resource.slice(0,INITIAL_DATA_LENGTH));}if(resource instanceof Blob){var blobSlice=resource.slice(0,5);return await new Promise(resolve=>{var reader=new FileReader();reader.onload=event=>{var _event$target;return resolve(event===null||event===void 0?void 0:(_event$target=event.target)===null||_event$target===void 0?void 0:_event$target.result);};reader.readAsDataURL(blobSlice);});}if(resource instanceof ArrayBuffer){var slice=resource.slice(0,INITIAL_DATA_LENGTH);var base64=arrayBufferToBase64(slice);return "data:base64,".concat(base64);}return null;}function arrayBufferToBase64(buffer){var binary='';var bytes=new Uint8Array(buffer);for(var _i5=0;_i5=0){return true;}return false;}function isBrowser(){var isNode=typeof process==='object'&&String(process)==='[object process]'&&!process.browser;return !isNode||isElectron();}var globals={self:typeof self!=='undefined'&&self,window:typeof window!=='undefined'&&window,global:typeof global!=='undefined'&&global,document:typeof document!=='undefined'&&document,process:typeof process==='object'&&process};var window_=globals.window||globals.self||globals.global;var process_=globals.process||{};var VERSION$6=typeof __VERSION__!=='undefined'?__VERSION__:'untranspiled source';isBrowser();function getStorage(type){try{var storage=window[type];var x='__storage_test__';storage.setItem(x,x);storage.removeItem(x);return storage;}catch(e){return null;}}class LocalStorage{constructor(id){var defaultSettings=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var type=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'sessionStorage';_defineProperty$1(this,"storage",void 0);_defineProperty$1(this,"id",void 0);_defineProperty$1(this,"config",{});this.storage=getStorage(type);this.id=id;this.config={};Object.assign(this.config,defaultSettings);this._loadConfiguration();}getConfiguration(){return this.config;}setConfiguration(configuration){this.config={};return this.updateConfiguration(configuration);}updateConfiguration(configuration){Object.assign(this.config,configuration);if(this.storage){var serialized=JSON.stringify(this.config);this.storage.setItem(this.id,serialized);}return this;}_loadConfiguration(){var configuration={};if(this.storage){var serializedConfiguration=this.storage.getItem(this.id);configuration=serializedConfiguration?JSON.parse(serializedConfiguration):{};}Object.assign(this.config,configuration);return this;}}function formatTime(ms){var formatted;if(ms<10){formatted="".concat(ms.toFixed(2),"ms");}else if(ms<100){formatted="".concat(ms.toFixed(1),"ms");}else if(ms<1000){formatted="".concat(ms.toFixed(0),"ms");}else {formatted="".concat((ms/1000).toFixed(2),"s");}return formatted;}function leftPad(string){var length=arguments.length>1&&arguments[1]!==undefined?arguments[1]:8;var padLength=Math.max(length-string.length,0);return "".concat(' '.repeat(padLength)).concat(string);}function formatImage(image,message,scale){var maxWidth=arguments.length>3&&arguments[3]!==undefined?arguments[3]:600;var imageUrl=image.src.replace(/\(/g,'%28').replace(/\)/g,'%29');if(image.width>maxWidth){scale=Math.min(scale,maxWidth/image.width);}var width=image.width*scale;var height=image.height*scale;var style=['font-size:1px;',"padding:".concat(Math.floor(height/2),"px ").concat(Math.floor(width/2),"px;"),"line-height:".concat(height,"px;"),"background:url(".concat(imageUrl,");"),"background-size:".concat(width,"px ").concat(height,"px;"),'color:transparent;'].join('');return ["".concat(message," %c+"),style];}var COLOR;(function(COLOR){COLOR[COLOR["BLACK"]=30]="BLACK";COLOR[COLOR["RED"]=31]="RED";COLOR[COLOR["GREEN"]=32]="GREEN";COLOR[COLOR["YELLOW"]=33]="YELLOW";COLOR[COLOR["BLUE"]=34]="BLUE";COLOR[COLOR["MAGENTA"]=35]="MAGENTA";COLOR[COLOR["CYAN"]=36]="CYAN";COLOR[COLOR["WHITE"]=37]="WHITE";COLOR[COLOR["BRIGHT_BLACK"]=90]="BRIGHT_BLACK";COLOR[COLOR["BRIGHT_RED"]=91]="BRIGHT_RED";COLOR[COLOR["BRIGHT_GREEN"]=92]="BRIGHT_GREEN";COLOR[COLOR["BRIGHT_YELLOW"]=93]="BRIGHT_YELLOW";COLOR[COLOR["BRIGHT_BLUE"]=94]="BRIGHT_BLUE";COLOR[COLOR["BRIGHT_MAGENTA"]=95]="BRIGHT_MAGENTA";COLOR[COLOR["BRIGHT_CYAN"]=96]="BRIGHT_CYAN";COLOR[COLOR["BRIGHT_WHITE"]=97]="BRIGHT_WHITE";})(COLOR||(COLOR={}));function getColor$1(color){return typeof color==='string'?COLOR[color.toUpperCase()]||COLOR.WHITE:color;}function addColor(string,color,background){if(!isBrowser&&typeof string==='string'){if(color){color=getColor$1(color);string="\x1B[".concat(color,"m").concat(string,"\x1B[39m");}if(background){color=getColor$1(background);string="\x1B[".concat(background+10,"m").concat(string,"\x1B[49m");}}return string;}function autobind(obj){var predefined=arguments.length>1&&arguments[1]!==undefined?arguments[1]:['constructor'];var proto=Object.getPrototypeOf(obj);var propNames=Object.getOwnPropertyNames(proto);var _loop=function _loop(key){if(typeof obj[key]==='function'){if(!predefined.find(name=>key===name)){obj[key]=obj[key].bind(obj);}}};for(var key of propNames){_loop(key);}}function assert$5(condition,message){if(!condition){throw new Error(message||'Assertion failed');}}function getHiResTimestamp(){var timestamp;if(isBrowser&&'performance'in window_){var _window$performance,_window$performance$n;timestamp=window_===null||window_===void 0?void 0:(_window$performance=window_.performance)===null||_window$performance===void 0?void 0:(_window$performance$n=_window$performance.now)===null||_window$performance$n===void 0?void 0:_window$performance$n.call(_window$performance);}else if('hrtime'in process_){var _process$hrtime;var timeParts=process_===null||process_===void 0?void 0:(_process$hrtime=process_.hrtime)===null||_process$hrtime===void 0?void 0:_process$hrtime.call(process_);timestamp=timeParts[0]*1000+timeParts[1]/1e6;}else {timestamp=Date.now();}return timestamp;}var originalConsole={debug:isBrowser?console.debug||console.log:console.log,log:console.log,info:console.info,warn:console.warn,error:console.error};var DEFAULT_SETTINGS={enabled:true,level:0};function noop$1(){}var cache={};var ONCE={once:true};class Log{constructor(){var{id}=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{id:''};_defineProperty$1(this,"id",void 0);_defineProperty$1(this,"VERSION",VERSION$6);_defineProperty$1(this,"_startTs",getHiResTimestamp());_defineProperty$1(this,"_deltaTs",getHiResTimestamp());_defineProperty$1(this,"_storage",void 0);_defineProperty$1(this,"userData",{});_defineProperty$1(this,"LOG_THROTTLE_TIMEOUT",0);this.id=id;this._storage=new LocalStorage("__probe-".concat(this.id,"__"),DEFAULT_SETTINGS);this.userData={};this.timeStamp("".concat(this.id," started"));autobind(this);Object.seal(this);}set level(newLevel){this.setLevel(newLevel);}get level(){return this.getLevel();}isEnabled(){return this._storage.config.enabled;}getLevel(){return this._storage.config.level;}getTotal(){return Number((getHiResTimestamp()-this._startTs).toPrecision(10));}getDelta(){return Number((getHiResTimestamp()-this._deltaTs).toPrecision(10));}set priority(newPriority){this.level=newPriority;}get priority(){return this.level;}getPriority(){return this.level;}enable(){var enabled=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;this._storage.updateConfiguration({enabled});return this;}setLevel(level){this._storage.updateConfiguration({level});return this;}get(setting){return this._storage.config[setting];}set(setting,value){this._storage.updateConfiguration({[setting]:value});}settings(){if(console.table){console.table(this._storage.config);}else {console.log(this._storage.config);}}assert(condition,message){assert$5(condition,message);}warn(message){return this._getLogFunction(0,message,originalConsole.warn,arguments,ONCE);}error(message){return this._getLogFunction(0,message,originalConsole.error,arguments);}deprecated(oldUsage,newUsage){return this.warn("`".concat(oldUsage,"` is deprecated and will be removed in a later version. Use `").concat(newUsage,"` instead"));}removed(oldUsage,newUsage){return this.error("`".concat(oldUsage,"` has been removed. Use `").concat(newUsage,"` instead"));}probe(logLevel,message){return this._getLogFunction(logLevel,message,originalConsole.log,arguments,{time:true,once:true});}log(logLevel,message){return this._getLogFunction(logLevel,message,originalConsole.debug,arguments);}info(logLevel,message){return this._getLogFunction(logLevel,message,console.info,arguments);}once(logLevel,message){for(var _len=arguments.length,args=new Array(_len>2?_len-2:0),_key=2;_key<_len;_key++){args[_key-2]=arguments[_key];}return this._getLogFunction(logLevel,message,originalConsole.debug||originalConsole.info,arguments,ONCE);}table(logLevel,table,columns){if(table){return this._getLogFunction(logLevel,table,console.table||noop$1,columns&&[columns],{tag:getTableHeader(table)});}return noop$1;}image(_ref){var{logLevel,priority,image,message='',scale=1}=_ref;if(!this._shouldLog(logLevel||priority)){return noop$1;}return isBrowser?logImageInBrowser({image,message,scale}):logImageInNode({image,message,scale});}time(logLevel,message){return this._getLogFunction(logLevel,message,console.time?console.time:console.info);}timeEnd(logLevel,message){return this._getLogFunction(logLevel,message,console.timeEnd?console.timeEnd:console.info);}timeStamp(logLevel,message){return this._getLogFunction(logLevel,message,console.timeStamp||noop$1);}group(logLevel,message){var opts=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{collapsed:false};var options=normalizeArguments({logLevel,message,opts});var{collapsed}=opts;options.method=(collapsed?console.groupCollapsed:console.group)||console.info;return this._getLogFunction(options);}groupCollapsed(logLevel,message){var opts=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};return this.group(logLevel,message,Object.assign({},opts,{collapsed:true}));}groupEnd(logLevel){return this._getLogFunction(logLevel,'',console.groupEnd||noop$1);}withGroup(logLevel,message,func){this.group(logLevel,message)();try{func();}finally{this.groupEnd(logLevel)();}}trace(){if(console.trace){console.trace();}}_shouldLog(logLevel){return this.isEnabled()&&this.getLevel()>=normalizeLogLevel(logLevel);}_getLogFunction(logLevel,message,method,args,opts){if(this._shouldLog(logLevel)){opts=normalizeArguments({logLevel,message,args,opts});method=method||opts.method;assert$5(method);opts.total=this.getTotal();opts.delta=this.getDelta();this._deltaTs=getHiResTimestamp();var tag=opts.tag||opts.message;if(opts.once){if(!cache[tag]){cache[tag]=getHiResTimestamp();}else {return noop$1;}}message=decorateMessage(this.id,opts.message,opts);return method.bind(console,message,...opts.args);}return noop$1;}}_defineProperty$1(Log,"VERSION",VERSION$6);function normalizeLogLevel(logLevel){if(!logLevel){return 0;}var resolvedLevel;switch(typeof logLevel){case'number':resolvedLevel=logLevel;break;case'object':resolvedLevel=logLevel.logLevel||logLevel.priority||0;break;default:return 0;}assert$5(Number.isFinite(resolvedLevel)&&resolvedLevel>=0);return resolvedLevel;}function normalizeArguments(opts){var{logLevel,message}=opts;opts.logLevel=normalizeLogLevel(logLevel);var args=opts.args?Array.from(opts.args):[];while(args.length&&args.shift()!==message){}switch(typeof logLevel){case'string':case'function':if(message!==undefined){args.unshift(message);}opts.message=logLevel;break;case'object':Object.assign(opts,logLevel);break;}if(typeof opts.message==='function'){opts.message=opts.message();}var messageType=typeof opts.message;assert$5(messageType==='string'||messageType==='object');return Object.assign(opts,{args},opts.opts);}function decorateMessage(id,message,opts){if(typeof message==='string'){var time=opts.time?leftPad(formatTime(opts.total)):'';message=opts.time?"".concat(id,": ").concat(time," ").concat(message):"".concat(id,": ").concat(message);message=addColor(message,opts.color,opts.background);}return message;}function logImageInNode(_ref2){var{image,message='',scale=1}=_ref2;var asciify=null;try{asciify=module.require('asciify-image');}catch(error){}if(asciify){return ()=>asciify(image,{fit:'box',width:"".concat(Math.round(80*scale),"%")}).then(data=>console.log(data));}return noop$1;}function logImageInBrowser(_ref3){var{image,message='',scale=1}=_ref3;if(typeof image==='string'){var img=new Image();img.onload=()=>{var args=formatImage(img,message,scale);console.log(...args);};img.src=image;return noop$1;}var element=image.nodeName||'';if(element.toLowerCase()==='img'){console.log(...formatImage(image,message,scale));return noop$1;}if(element.toLowerCase()==='canvas'){var _img=new Image();_img.onload=()=>console.log(...formatImage(_img,message,scale));_img.src=image.toDataURL();return noop$1;}return noop$1;}function getTableHeader(table){for(var key in table){for(var title in table[key]){return title||'untitled';}}return 'empty';}var probeLog=new Log({id:'loaders.gl'});class NullLog{log(){return ()=>{};}info(){return ()=>{};}warn(){return ()=>{};}error(){return ()=>{};}}class ConsoleLog{constructor(){_defineProperty$1(this,"console",void 0);this.console=console;}log(){for(var _len3=arguments.length,args=new Array(_len3),_key3=0;_key3<_len3;_key3++){args[_key3]=arguments[_key3];}return this.console.log.bind(this.console,...args);}info(){for(var _len4=arguments.length,args=new Array(_len4),_key4=0;_key4<_len4;_key4++){args[_key4]=arguments[_key4];}return this.console.info.bind(this.console,...args);}warn(){for(var _len5=arguments.length,args=new Array(_len5),_key5=0;_key5<_len5;_key5++){args[_key5]=arguments[_key5];}return this.console.warn.bind(this.console,...args);}error(){for(var _len6=arguments.length,args=new Array(_len6),_key6=0;_key6<_len6;_key6++){args[_key6]=arguments[_key6];}return this.console.error.bind(this.console,...args);}}var DEFAULT_LOADER_OPTIONS={fetch:null,mimeType:undefined,nothrow:false,log:new ConsoleLog(),CDN:'https://unpkg.com/@loaders.gl',worker:true,maxConcurrency:3,maxMobileConcurrency:1,reuseWorkers:true,_workerType:'',limit:0,_limitMB:0,batchSize:'auto',batchDebounceMs:0,metadata:false,transforms:[]};var REMOVED_LOADER_OPTIONS={throws:'nothrow',dataType:'(no longer used)',uri:'baseUri',method:'fetch.method',headers:'fetch.headers',body:'fetch.body',mode:'fetch.mode',credentials:'fetch.credentials',cache:'fetch.cache',redirect:'fetch.redirect',referrer:'fetch.referrer',referrerPolicy:'fetch.referrerPolicy',integrity:'fetch.integrity',keepalive:'fetch.keepalive',signal:'fetch.signal'};function getGlobalLoaderState(){globalThis.loaders=globalThis.loaders||{};var{loaders}=globalThis;loaders._state=loaders._state||{};return loaders._state;}var getGlobalLoaderOptions=()=>{var state=getGlobalLoaderState();state.globalOptions=state.globalOptions||_objectSpread2({},DEFAULT_LOADER_OPTIONS);return state.globalOptions;};function normalizeOptions(options,loader,loaders,url){loaders=loaders||[];loaders=Array.isArray(loaders)?loaders:[loaders];validateOptions(options,loaders);return normalizeOptionsInternal(loader,options,url);}function getFetchFunction(options,context){var globalOptions=getGlobalLoaderOptions();var fetchOptions=options||globalOptions;if(typeof fetchOptions.fetch==='function'){return fetchOptions.fetch;}if(isObject(fetchOptions.fetch)){return url=>fetchFile(url,fetchOptions);}if(context!==null&&context!==void 0&&context.fetch){return context===null||context===void 0?void 0:context.fetch;}return fetchFile;}function validateOptions(options,loaders){validateOptionsObject(options,null,DEFAULT_LOADER_OPTIONS,REMOVED_LOADER_OPTIONS,loaders);for(var loader of loaders){var idOptions=options&&options[loader.id]||{};var loaderOptions=loader.options&&loader.options[loader.id]||{};var deprecatedOptions=loader.deprecatedOptions&&loader.deprecatedOptions[loader.id]||{};validateOptionsObject(idOptions,loader.id,loaderOptions,deprecatedOptions,loaders);}}function validateOptionsObject(options,id,defaultOptions,deprecatedOptions,loaders){var loaderName=id||'Top level';var prefix=id?"".concat(id,"."):'';for(var key in options){var isSubOptions=!id&&isObject(options[key]);var isBaseUriOption=key==='baseUri'&&!id;var isWorkerUrlOption=key==='workerUrl'&&id;if(!(key in defaultOptions)&&!isBaseUriOption&&!isWorkerUrlOption){if(key in deprecatedOptions){probeLog.warn("".concat(loaderName," loader option '").concat(prefix).concat(key,"' no longer supported, use '").concat(deprecatedOptions[key],"'"))();}else if(!isSubOptions){var suggestion=findSimilarOption(key,loaders);probeLog.warn("".concat(loaderName," loader option '").concat(prefix).concat(key,"' not recognized. ").concat(suggestion))();}}}}function findSimilarOption(optionKey,loaders){var lowerCaseOptionKey=optionKey.toLowerCase();var bestSuggestion='';for(var loader of loaders){for(var key in loader.options){if(optionKey===key){return "Did you mean '".concat(loader.id,".").concat(key,"'?");}var lowerCaseKey=key.toLowerCase();var isPartialMatch=lowerCaseOptionKey.startsWith(lowerCaseKey)||lowerCaseKey.startsWith(lowerCaseOptionKey);if(isPartialMatch){bestSuggestion=bestSuggestion||"Did you mean '".concat(loader.id,".").concat(key,"'?");}}}return bestSuggestion;}function normalizeOptionsInternal(loader,options,url){var loaderDefaultOptions=loader.options||{};var mergedOptions=_objectSpread2({},loaderDefaultOptions);addUrlOptions(mergedOptions,url);if(mergedOptions.log===null){mergedOptions.log=new NullLog();}mergeNestedFields(mergedOptions,getGlobalLoaderOptions());mergeNestedFields(mergedOptions,options);return mergedOptions;}function mergeNestedFields(mergedOptions,options){for(var key in options){if(key in options){var value=options[key];if(isPureObject(value)&&isPureObject(mergedOptions[key])){mergedOptions[key]=_objectSpread2(_objectSpread2({},mergedOptions[key]),options[key]);}else {mergedOptions[key]=options[key];}}}}function addUrlOptions(options,url){if(url&&!('baseUri'in options)){options.baseUri=url;}}function isLoaderObject(loader){var _loader;if(!loader){return false;}if(Array.isArray(loader)){loader=loader[0];}var hasExtensions=Array.isArray((_loader=loader)===null||_loader===void 0?void 0:_loader.extensions);return hasExtensions;}function normalizeLoader(loader){var _loader2,_loader3;assert$7(loader,'null loader');assert$7(isLoaderObject(loader),'invalid loader');var options;if(Array.isArray(loader)){options=loader[1];loader=loader[0];loader=_objectSpread2(_objectSpread2({},loader),{},{options:_objectSpread2(_objectSpread2({},loader.options),options)});}if((_loader2=loader)!==null&&_loader2!==void 0&&_loader2.parseTextSync||(_loader3=loader)!==null&&_loader3!==void 0&&_loader3.parseText){loader.text=true;}if(!loader.text){loader.binary=true;}return loader;}var getGlobalLoaderRegistry=()=>{var state=getGlobalLoaderState();state.loaderRegistry=state.loaderRegistry||[];return state.loaderRegistry;};function getRegisteredLoaders(){return getGlobalLoaderRegistry();}var EXT_PATTERN=/\.([^.]+)$/;async function selectLoader(data){var loaders=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];var options=arguments.length>2?arguments[2]:undefined;var context=arguments.length>3?arguments[3]:undefined;if(!validHTTPResponse(data)){return null;}var loader=selectLoaderSync(data,loaders,_objectSpread2(_objectSpread2({},options),{},{nothrow:true}),context);if(loader){return loader;}if(isBlob(data)){data=await data.slice(0,10).arrayBuffer();loader=selectLoaderSync(data,loaders,options,context);}if(!loader&&!(options!==null&&options!==void 0&&options.nothrow)){throw new Error(getNoValidLoaderMessage(data));}return loader;}function selectLoaderSync(data){var loaders=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];var options=arguments.length>2?arguments[2]:undefined;var context=arguments.length>3?arguments[3]:undefined;if(!validHTTPResponse(data)){return null;}if(loaders&&!Array.isArray(loaders)){return normalizeLoader(loaders);}var candidateLoaders=[];if(loaders){candidateLoaders=candidateLoaders.concat(loaders);}if(!(options!==null&&options!==void 0&&options.ignoreRegisteredLoaders)){candidateLoaders.push(...getRegisteredLoaders());}normalizeLoaders(candidateLoaders);var loader=selectLoaderInternal(data,candidateLoaders,options,context);if(!loader&&!(options!==null&&options!==void 0&&options.nothrow)){throw new Error(getNoValidLoaderMessage(data));}return loader;}function selectLoaderInternal(data,loaders,options,context){var{url,type}=getResourceUrlAndType(data);var testUrl=url||(context===null||context===void 0?void 0:context.url);var loader=null;if(options!==null&&options!==void 0&&options.mimeType){loader=findLoaderByMIMEType(loaders,options===null||options===void 0?void 0:options.mimeType);}loader=loader||findLoaderByUrl(loaders,testUrl);loader=loader||findLoaderByMIMEType(loaders,type);loader=loader||findLoaderByInitialBytes(loaders,data);loader=loader||findLoaderByMIMEType(loaders,options===null||options===void 0?void 0:options.fallbackMimeType);return loader;}function validHTTPResponse(data){if(data instanceof Response){if(data.status===204){return false;}}return true;}function getNoValidLoaderMessage(data){var{url,type}=getResourceUrlAndType(data);var message='No valid loader found (';message+=url?"".concat(filename(url),", "):'no url provided, ';message+="MIME type: ".concat(type?"\"".concat(type,"\""):'not provided',", ");var firstCharacters=data?getFirstCharacters(data):'';message+=firstCharacters?" first bytes: \"".concat(firstCharacters,"\""):'first bytes: not available';message+=')';return message;}function normalizeLoaders(loaders){for(var loader of loaders){normalizeLoader(loader);}}function findLoaderByUrl(loaders,url){var match=url&&EXT_PATTERN.exec(url);var extension=match&&match[1];return extension?findLoaderByExtension(loaders,extension):null;}function findLoaderByExtension(loaders,extension){extension=extension.toLowerCase();for(var loader of loaders){for(var loaderExtension of loader.extensions){if(loaderExtension.toLowerCase()===extension){return loader;}}}return null;}function findLoaderByMIMEType(loaders,mimeType){for(var loader of loaders){if(loader.mimeTypes&&loader.mimeTypes.includes(mimeType)){return loader;}if(mimeType==="application/x.".concat(loader.id)){return loader;}}return null;}function findLoaderByInitialBytes(loaders,data){if(!data){return null;}for(var loader of loaders){if(typeof data==='string'){if(testDataAgainstText(data,loader)){return loader;}}else if(ArrayBuffer.isView(data)){if(testDataAgainstBinary(data.buffer,data.byteOffset,loader)){return loader;}}else if(data instanceof ArrayBuffer){var byteOffset=0;if(testDataAgainstBinary(data,byteOffset,loader)){return loader;}}}return null;}function testDataAgainstText(data,loader){if(loader.testText){return loader.testText(data);}var tests=Array.isArray(loader.tests)?loader.tests:[loader.tests];return tests.some(test=>data.startsWith(test));}function testDataAgainstBinary(data,byteOffset,loader){var tests=Array.isArray(loader.tests)?loader.tests:[loader.tests];return tests.some(test=>testBinary(data,byteOffset,loader,test));}function testBinary(data,byteOffset,loader,test){if(test instanceof ArrayBuffer){return compareArrayBuffers(test,data,test.byteLength);}switch(typeof test){case'function':return test(data,loader);case'string':var magic=getMagicString$2(data,byteOffset,test.length);return test===magic;default:return false;}}function getFirstCharacters(data){var length=arguments.length>1&&arguments[1]!==undefined?arguments[1]:5;if(typeof data==='string'){return data.slice(0,length);}else if(ArrayBuffer.isView(data)){return getMagicString$2(data.buffer,data.byteOffset,length);}else if(data instanceof ArrayBuffer){var byteOffset=0;return getMagicString$2(data,byteOffset,length);}return '';}function getMagicString$2(arrayBuffer,byteOffset,length){if(arrayBuffer.byteLength1&&arguments[1]!==undefined?arguments[1]:{};return function*(){var{chunkSize=DEFAULT_CHUNK_SIZE$1}=options;var byteOffset=0;while(byteOffset2&&arguments[2]!==undefined?arguments[2]:null;if(previousContext){return previousContext;}var resolvedContext=_objectSpread2({fetch:getFetchFunction(options,context)},context);if(!Array.isArray(resolvedContext.loaders)){resolvedContext.loaders=null;}return resolvedContext;}function getLoadersFromContext(loaders,context){if(!context&&loaders&&!Array.isArray(loaders)){return loaders;}var candidateLoaders;if(loaders){candidateLoaders=Array.isArray(loaders)?loaders:[loaders];}if(context&&context.loaders){var contextLoaders=Array.isArray(context.loaders)?context.loaders:[context.loaders];candidateLoaders=candidateLoaders?[...candidateLoaders,...contextLoaders]:contextLoaders;}return candidateLoaders&&candidateLoaders.length?candidateLoaders:null;}async function parse$3(data,loaders,options,context){assert$6(!context||typeof context==='object');if(loaders&&!Array.isArray(loaders)&&!isLoaderObject(loaders)){context=undefined;options=loaders;loaders=undefined;}data=await data;options=options||{};var{url}=getResourceUrlAndType(data);var typedLoaders=loaders;var candidateLoaders=getLoadersFromContext(typedLoaders,context);var loader=await selectLoader(data,candidateLoaders,options);if(!loader){return null;}options=normalizeOptions(options,loader,candidateLoaders,url);context=getLoaderContext({url,parse:parse$3,loaders:candidateLoaders},options,context);return await parseWithLoader(loader,data,options,context);}async function parseWithLoader(loader,data,options,context){validateWorkerVersion(loader);data=await getArrayBufferOrStringFromData(data,loader,options);if(loader.parseTextSync&&typeof data==='string'){options.dataType='text';return loader.parseTextSync(data,options,context,loader);}if(canParseWithWorker(loader,options)){return await parseWithWorker(loader,data,options,context,parse$3);}if(loader.parseText&&typeof data==='string'){return await loader.parseText(data,options,context,loader);}if(loader.parse){return await loader.parse(data,options,context,loader);}assert$6(!loader.parseSync);throw new Error("".concat(loader.id," loader - no parser found and worker is disabled"));}async function load(url,loaders,options,context){if(!Array.isArray(loaders)&&!isLoaderObject(loaders)){options=loaders;loaders=undefined;}var fetch=getFetchFunction(options);var data=url;if(typeof url==='string'){data=await fetch(url);}if(isBlob(url)){data=await fetch(url);}return await parse$3(data,loaders,options);}function assert$4(condition,message){if(!condition){throw new Error("math.gl assertion ".concat(message));}}var RADIANS_TO_DEGREES=1/Math.PI*180;var DEGREES_TO_RADIANS=1/180*Math.PI;var config$2={};config$2.EPSILON=1e-12;config$2.debug=false;config$2.precision=4;config$2.printTypes=false;config$2.printDegrees=false;config$2.printRowMajor=true;function round(value){return Math.round(value/config$2.EPSILON)*config$2.EPSILON;}function formatValue(value){var{precision=config$2.precision||4}=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};value=round(value);return "".concat(parseFloat(value.toPrecision(precision)));}function isArray(value){return Array.isArray(value)||ArrayBuffer.isView(value)&&!(value instanceof DataView);}function duplicateArray(array){return array.clone?array.clone():new Array(array.length);}function map$1(value,func,result){if(isArray(value)){result=result||duplicateArray(value);for(var _i7=0;_i7degrees*DEGREES_TO_RADIANS,result);}function degrees(radians,result){return map$1(radians,radians=>radians*RADIANS_TO_DEGREES,result);}function clamp$1(value,min,max){return map$1(value,value=>Math.max(min,Math.min(max,value)));}function equals$1(a,b,epsilon){var oldEpsilon=config$2.EPSILON;if(epsilon){config$2.EPSILON=epsilon;}try{if(a===b){return true;}if(isArray(a)&&isArray(b)){if(a.length!==b.length){return false;}for(var _i8=0;_i81&&arguments[1]!==undefined?arguments[1]:0;for(var _i9=0;_i90&&arguments[0]!==undefined?arguments[0]:[];var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;for(var _i10=0;_i100?', ':'')+formatValue(this[_i11],opts);}return "".concat(opts.printTypes?this.constructor.name:'',"[").concat(string,"]");}equals(array){if(!array||this.length!==array.length){return false;}for(var _i12=0;_i122&&arguments[2]!==undefined?arguments[2]:'';if(config$2.debug&&!validateVector(v,length)){throw new Error("math.gl: ".concat(callerName," some fields set to invalid numbers'"));}return v;}var map={};function deprecated(method,version){if(!map[method]){map[method]=true;console.warn("".concat(method," has been removed in version ").concat(version,", see upgrade guide for more information"));}}class Vector extends MathArray{get ELEMENTS(){assert$4(false);return 0;}copy(vector){assert$4(false);return this;}get x(){return this[0];}set x(value){this[0]=checkNumber(value);}get y(){return this[1];}set y(value){this[1]=checkNumber(value);}len(){return Math.sqrt(this.lengthSquared());}magnitude(){return this.len();}lengthSquared(){var length=0;for(var _i28=0;_i28=0&&i=0&&i0&&arguments[0]!==undefined?arguments[0]:0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;super(2);if(isArray(x)&&arguments.length===1){this.copy(x);}else {if(config$2.debug){checkNumber(x);checkNumber(y);}this[0]=x;this[1]=y;}}set(x,y){this[0]=x;this[1]=y;return this.check();}copy(array){this[0]=array[0];this[1]=array[1];return this.check();}fromObject(object){if(config$2.debug){checkNumber(object.x);checkNumber(object.y);}this[0]=object.x;this[1]=object.y;return this.check();}toObject(object){object.x=this[0];object.y=this[1];return object;}get ELEMENTS(){return 2;}horizontalAngle(){return Math.atan2(this.y,this.x);}verticalAngle(){return Math.atan2(this.x,this.y);}transform(matrix4){return this.transformAsPoint(matrix4);}transformAsPoint(matrix4){transformMat4$2(this,this,matrix4);return this.check();}transformAsVector(matrix4){vec2_transformMat4AsVector(this,this,matrix4);return this.check();}transformByMatrix3(matrix3){transformMat3$1(this,this,matrix3);return this.check();}transformByMatrix2x3(matrix2x3){transformMat2d(this,this,matrix2x3);return this.check();}transformByMatrix2(matrix2){transformMat2(this,this,matrix2);return this.check();}}/** * 3 Dimensional Vector * @module vec3 */ /** * Creates a new, empty vec3 * * @returns {vec3} a new 3D vector */function create$3(){var out=new ARRAY_TYPE(3);if(ARRAY_TYPE!=Float32Array){out[0]=0;out[1]=0;out[2]=0;}return out;}/** * Calculates the length of a vec3 * * @param {ReadonlyVec3} a vector to calculate length of * @returns {Number} length of a */function length$2(a){var x=a[0];var y=a[1];var z=a[2];return Math.hypot(x,y,z);}/** * Creates a new vec3 initialized with the given values * * @param {Number} x X component * @param {Number} y Y component * @param {Number} z Z component * @returns {vec3} a new 3D vector */function fromValues(x,y,z){var out=new ARRAY_TYPE(3);out[0]=x;out[1]=y;out[2]=z;return out;}/** * Normalize a vec3 * * @param {vec3} out the receiving vector * @param {ReadonlyVec3} a vector to normalize * @returns {vec3} out */function normalize$2(out,a){var x=a[0];var y=a[1];var z=a[2];var len=x*x+y*y+z*z;if(len>0){//TODO: evaluate use of glm_invsqrt here? len=1/Math.sqrt(len);}out[0]=a[0]*len;out[1]=a[1]*len;out[2]=a[2]*len;return out;}/** * Calculates the dot product of two vec3's * * @param {ReadonlyVec3} a the first operand * @param {ReadonlyVec3} b the second operand * @returns {Number} dot product of a and b */function dot$2(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2];}/** * Computes the cross product of two vec3's * * @param {vec3} out the receiving vector * @param {ReadonlyVec3} a the first operand * @param {ReadonlyVec3} b the second operand * @returns {vec3} out */function cross(out,a,b){var ax=a[0],ay=a[1],az=a[2];var bx=b[0],by=b[1],bz=b[2];out[0]=ay*bz-az*by;out[1]=az*bx-ax*bz;out[2]=ax*by-ay*bx;return out;}/** * Transforms the vec3 with a mat4. * 4th vector component is implicitly '1' * * @param {vec3} out the receiving vector * @param {ReadonlyVec3} a the vector to transform * @param {ReadonlyMat4} m matrix to transform with * @returns {vec3} out */function transformMat4$1(out,a,m){var x=a[0],y=a[1],z=a[2];var w=m[3]*x+m[7]*y+m[11]*z+m[15];w=w||1.0;out[0]=(m[0]*x+m[4]*y+m[8]*z+m[12])/w;out[1]=(m[1]*x+m[5]*y+m[9]*z+m[13])/w;out[2]=(m[2]*x+m[6]*y+m[10]*z+m[14])/w;return out;}/** * Transforms the vec3 with a mat3. * * @param {vec3} out the receiving vector * @param {ReadonlyVec3} a the vector to transform * @param {ReadonlyMat3} m the 3x3 matrix to transform with * @returns {vec3} out */function transformMat3(out,a,m){var x=a[0],y=a[1],z=a[2];out[0]=x*m[0]+y*m[3]+z*m[6];out[1]=x*m[1]+y*m[4]+z*m[7];out[2]=x*m[2]+y*m[5]+z*m[8];return out;}/** * Transforms the vec3 with a quat * Can also be used for dual quaternions. (Multiply it with the real part) * * @param {vec3} out the receiving vector * @param {ReadonlyVec3} a the vector to transform * @param {ReadonlyQuat} q quaternion to transform with * @returns {vec3} out */function transformQuat$1(out,a,q){// benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed var qx=q[0],qy=q[1],qz=q[2],qw=q[3];var x=a[0],y=a[1],z=a[2];// var qvec = [qx, qy, qz]; // var uv = vec3.cross([], qvec, a); var uvx=qy*z-qz*y,uvy=qz*x-qx*z,uvz=qx*y-qy*x;// var uuv = vec3.cross([], qvec, uv); var uuvx=qy*uvz-qz*uvy,uuvy=qz*uvx-qx*uvz,uuvz=qx*uvy-qy*uvx;// vec3.scale(uv, uv, 2 * w); var w2=qw*2;uvx*=w2;uvy*=w2;uvz*=w2;// vec3.scale(uuv, uuv, 2); uuvx*=2;uuvy*=2;uuvz*=2;// return vec3.add(out, a, vec3.add(out, uv, uuv)); out[0]=x+uvx+uuvx;out[1]=y+uvy+uuvy;out[2]=z+uvz+uuvz;return out;}/** * Rotate a 3D vector around the x-axis * @param {vec3} out The receiving vec3 * @param {ReadonlyVec3} a The vec3 point to rotate * @param {ReadonlyVec3} b The origin of the rotation * @param {Number} rad The angle of rotation in radians * @returns {vec3} out */function rotateX$2(out,a,b,rad){var p=[],r=[];//Translate point to the origin p[0]=a[0]-b[0];p[1]=a[1]-b[1];p[2]=a[2]-b[2];//perform rotation r[0]=p[0];r[1]=p[1]*Math.cos(rad)-p[2]*Math.sin(rad);r[2]=p[1]*Math.sin(rad)+p[2]*Math.cos(rad);//translate to correct position out[0]=r[0]+b[0];out[1]=r[1]+b[1];out[2]=r[2]+b[2];return out;}/** * Rotate a 3D vector around the y-axis * @param {vec3} out The receiving vec3 * @param {ReadonlyVec3} a The vec3 point to rotate * @param {ReadonlyVec3} b The origin of the rotation * @param {Number} rad The angle of rotation in radians * @returns {vec3} out */function rotateY$2(out,a,b,rad){var p=[],r=[];//Translate point to the origin p[0]=a[0]-b[0];p[1]=a[1]-b[1];p[2]=a[2]-b[2];//perform rotation r[0]=p[2]*Math.sin(rad)+p[0]*Math.cos(rad);r[1]=p[1];r[2]=p[2]*Math.cos(rad)-p[0]*Math.sin(rad);//translate to correct position out[0]=r[0]+b[0];out[1]=r[1]+b[1];out[2]=r[2]+b[2];return out;}/** * Rotate a 3D vector around the z-axis * @param {vec3} out The receiving vec3 * @param {ReadonlyVec3} a The vec3 point to rotate * @param {ReadonlyVec3} b The origin of the rotation * @param {Number} rad The angle of rotation in radians * @returns {vec3} out */function rotateZ$2(out,a,b,rad){var p=[],r=[];//Translate point to the origin p[0]=a[0]-b[0];p[1]=a[1]-b[1];p[2]=a[2]-b[2];//perform rotation r[0]=p[0]*Math.cos(rad)-p[1]*Math.sin(rad);r[1]=p[0]*Math.sin(rad)+p[1]*Math.cos(rad);r[2]=p[2];//translate to correct position out[0]=r[0]+b[0];out[1]=r[1]+b[1];out[2]=r[2]+b[2];return out;}/** * Get the angle between two 3D vectors * @param {ReadonlyVec3} a The first operand * @param {ReadonlyVec3} b The second operand * @returns {Number} The angle in radians */function angle$1(a,b){var ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag1=Math.sqrt(ax*ax+ay*ay+az*az),mag2=Math.sqrt(bx*bx+by*by+bz*bz),mag=mag1*mag2,cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1));}/** * Alias for {@link vec3.length} * @function */var len=length$2;/** * Perform some operation over an array of vec3s. * * @param {Array} a the array of vectors to iterate over * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed * @param {Number} offset Number of elements to skip at the beginning of the array * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array * @param {Function} fn Function to call for each vector in the array * @param {Object} [arg] additional argument to pass to fn * @returns {Array} a * @function */(function(){var vec=create$3();return function(a,stride,offset,count,fn,arg){var i,l;if(!stride){stride=3;}if(!offset){offset=0;}if(count){l=Math.min(count*stride+offset,a.length);}else {l=a.length;}for(i=offset;i0&&arguments[0]!==undefined?arguments[0]:0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var z=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;super(-0,-0,-0);if(arguments.length===1&&isArray(x)){this.copy(x);}else {if(config$2.debug){checkNumber(x);checkNumber(y);checkNumber(z);}this[0]=x;this[1]=y;this[2]=z;}}set(x,y,z){this[0]=x;this[1]=y;this[2]=z;return this.check();}copy(array){this[0]=array[0];this[1]=array[1];this[2]=array[2];return this.check();}fromObject(object){if(config$2.debug){checkNumber(object.x);checkNumber(object.y);checkNumber(object.z);}this[0]=object.x;this[1]=object.y;this[2]=object.z;return this.check();}toObject(object){object.x=this[0];object.y=this[1];object.z=this[2];return object;}get ELEMENTS(){return 3;}get z(){return this[2];}set z(value){this[2]=checkNumber(value);}angle(vector){return angle$1(this,vector);}cross(vector){cross(this,this,vector);return this.check();}rotateX(_ref4){var{radians,origin=ORIGIN}=_ref4;rotateX$2(this,this,origin,radians);return this.check();}rotateY(_ref5){var{radians,origin=ORIGIN}=_ref5;rotateY$2(this,this,origin,radians);return this.check();}rotateZ(_ref6){var{radians,origin=ORIGIN}=_ref6;rotateZ$2(this,this,origin,radians);return this.check();}transform(matrix4){return this.transformAsPoint(matrix4);}transformAsPoint(matrix4){transformMat4$1(this,this,matrix4);return this.check();}transformAsVector(matrix4){vec3_transformMat4AsVector(this,this,matrix4);return this.check();}transformByMatrix3(matrix3){transformMat3(this,this,matrix3);return this.check();}transformByMatrix2(matrix2){vec3_transformMat2(this,this,matrix2);return this.check();}transformByQuaternion(quaternion){transformQuat$1(this,this,quaternion);return this.check();}}class Matrix extends MathArray{get ELEMENTS(){assert$4(false);return 0;}get RANK(){assert$4(false);return 0;}toString(){var string='[';if(config$2.printRowMajor){string+='row-major:';for(var row=0;row1&&arguments[1]!==undefined?arguments[1]:new Array(this.RANK).fill(-0);var firstIndex=columnIndex*this.RANK;for(var _i35=0;_i350){len=1/Math.sqrt(len);}out[0]=x*len;out[1]=y*len;out[2]=z*len;out[3]=w*len;return out;}/** * Calculates the dot product of two vec4's * * @param {ReadonlyVec4} a the first operand * @param {ReadonlyVec4} b the second operand * @returns {Number} dot product of a and b */function dot$1(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3];}/** * Performs a linear interpolation between two vec4's * * @param {vec4} out the receiving vector * @param {ReadonlyVec4} a the first operand * @param {ReadonlyVec4} b the second operand * @param {Number} t interpolation amount, in the range [0-1], between the two inputs * @returns {vec4} out */function lerp$1$1(out,a,b,t){var ax=a[0];var ay=a[1];var az=a[2];var aw=a[3];out[0]=ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);out[2]=az+t*(b[2]-az);out[3]=aw+t*(b[3]-aw);return out;}/** * Transforms the vec4 with a mat4. * * @param {vec4} out the receiving vector * @param {ReadonlyVec4} a the vector to transform * @param {ReadonlyMat4} m matrix to transform with * @returns {vec4} out */function transformMat4(out,a,m){var x=a[0],y=a[1],z=a[2],w=a[3];out[0]=m[0]*x+m[4]*y+m[8]*z+m[12]*w;out[1]=m[1]*x+m[5]*y+m[9]*z+m[13]*w;out[2]=m[2]*x+m[6]*y+m[10]*z+m[14]*w;out[3]=m[3]*x+m[7]*y+m[11]*z+m[15]*w;return out;}/** * Transforms the vec4 with a quat * * @param {vec4} out the receiving vector * @param {ReadonlyVec4} a the vector to transform * @param {ReadonlyQuat} q quaternion to transform with * @returns {vec4} out */function transformQuat(out,a,q){var x=a[0],y=a[1],z=a[2];var qx=q[0],qy=q[1],qz=q[2],qw=q[3];// calculate quat * vec 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;// calculate result * inverse quat out[0]=ix*qw+iw*-qx+iy*-qz-iz*-qy;out[1]=iy*qw+iw*-qy+iz*-qx-ix*-qz;out[2]=iz*qw+iw*-qz+ix*-qy-iy*-qx;out[3]=a[3];return out;}/** * Perform some operation over an array of vec4s. * * @param {Array} a the array of vectors to iterate over * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed * @param {Number} offset Number of elements to skip at the beginning of the array * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array * @param {Function} fn Function to call for each vector in the array * @param {Object} [arg] additional argument to pass to fn * @returns {Array} a * @function */(function(){var vec=create$1();return function(a,stride,offset,count,fn,arg){var i,l;if(!stride){stride=4;}if(!offset){offset=0;}if(count){l=Math.min(count*stride+offset,a.length);}else {l=a.length;}for(i=offset;iMath.PI*2){throw Error('radians');}var halfY=fovy/2;var top=focalDistance*Math.tan(halfY);var right=top*aspect;return new Matrix4$1().ortho({left:-right,right,bottom:-top,top,near,far});}perspective(){var{fovy=undefined,fov=45*Math.PI/180,aspect=1,near=0.1,far=500}=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};fovy=fovy||fov;if(fovy>Math.PI*2){throw Error('radians');}perspective(this,fovy,aspect,near,far);return this.check();}determinant(){return determinant(this);}getScale(){var result=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[-0,-0,-0];result[0]=Math.sqrt(this[0]*this[0]+this[1]*this[1]+this[2]*this[2]);result[1]=Math.sqrt(this[4]*this[4]+this[5]*this[5]+this[6]*this[6]);result[2]=Math.sqrt(this[8]*this[8]+this[9]*this[9]+this[10]*this[10]);return result;}getTranslation(){var result=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[-0,-0,-0];result[0]=this[12];result[1]=this[13];result[2]=this[14];return result;}getRotation(){var result=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0];var scaleResult=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var scale=this.getScale(scaleResult||[-0,-0,-0]);var inverseScale0=1/scale[0];var inverseScale1=1/scale[1];var inverseScale2=1/scale[2];result[0]=this[0]*inverseScale0;result[1]=this[1]*inverseScale1;result[2]=this[2]*inverseScale2;result[3]=0;result[4]=this[4]*inverseScale0;result[5]=this[5]*inverseScale1;result[6]=this[6]*inverseScale2;result[7]=0;result[8]=this[8]*inverseScale0;result[9]=this[9]*inverseScale1;result[10]=this[10]*inverseScale2;result[11]=0;result[12]=0;result[13]=0;result[14]=0;result[15]=1;return result;}getRotationMatrix3(){var result=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[-0,-0,-0,-0,-0,-0,-0,-0,-0];var scaleResult=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var scale=this.getScale(scaleResult||[-0,-0,-0]);var inverseScale0=1/scale[0];var inverseScale1=1/scale[1];var inverseScale2=1/scale[2];result[0]=this[0]*inverseScale0;result[1]=this[1]*inverseScale1;result[2]=this[2]*inverseScale2;result[3]=this[4]*inverseScale0;result[4]=this[5]*inverseScale1;result[5]=this[6]*inverseScale2;result[6]=this[8]*inverseScale0;result[7]=this[9]*inverseScale1;result[8]=this[10]*inverseScale2;return result;}transpose(){transpose(this,this);return this.check();}invert(){invert$1(this,this);return this.check();}multiplyLeft(a){multiply$1(this,a,this);return this.check();}multiplyRight(a){multiply$1(this,this,a);return this.check();}rotateX(radians){rotateX$1(this,this,radians);return this.check();}rotateY(radians){rotateY$1(this,this,radians);return this.check();}rotateZ(radians){rotateZ$1(this,this,radians);return this.check();}rotateXYZ(_ref10){var[rx,ry,rz]=_ref10;return this.rotateX(rx).rotateY(ry).rotateZ(rz);}rotateAxis(radians,axis){rotate(this,this,radians,axis);return this.check();}scale(factor){if(Array.isArray(factor)){scale$2(this,this,factor);}else {scale$2(this,this,[factor,factor,factor]);}return this.check();}translate(vec){translate(this,this,vec);return this.check();}transform(vector,result){if(vector.length===4){result=transformMat4(result||[-0,-0,-0,-0],vector,this);checkVector(result,4);return result;}return this.transformAsPoint(vector,result);}transformAsPoint(vector,result){var{length}=vector;switch(length){case 2:result=transformMat4$2(result||[-0,-0],vector,this);break;case 3:result=transformMat4$1(result||[-0,-0,-0],vector,this);break;default:throw new Error('Illegal vector');}checkVector(result,vector.length);return result;}transformAsVector(vector,result){switch(vector.length){case 2:result=vec2_transformMat4AsVector(result||[-0,-0],vector,this);break;case 3:result=vec3_transformMat4AsVector(result||[-0,-0,-0],vector,this);break;default:throw new Error('Illegal vector');}checkVector(result,vector.length);return result;}makeRotationX(radians){return this.identity().rotateX(radians);}makeTranslation(x,y,z){return this.identity().translate([x,y,z]);}transformPoint(vector,result){deprecated('Matrix4.transformPoint','3.0');return this.transformAsPoint(vector,result);}transformVector(vector,result){deprecated('Matrix4.transformVector','3.0');return this.transformAsPoint(vector,result);}transformDirection(vector,result){deprecated('Matrix4.transformDirection','3.0');return this.transformAsVector(vector,result);}}/** * Quaternion * @module quat */ /** * Creates a new identity quat * * @returns {quat} a new quaternion */function create(){var out=new ARRAY_TYPE(4);if(ARRAY_TYPE!=Float32Array){out[0]=0;out[1]=0;out[2]=0;}out[3]=1;return out;}/** * Set a quat to the identity quaternion * * @param {quat} out the receiving quaternion * @returns {quat} out */function identity(out){out[0]=0;out[1]=0;out[2]=0;out[3]=1;return out;}/** * Sets a quat from the given angle and rotation axis, * then returns it. * * @param {quat} out the receiving quaternion * @param {ReadonlyVec3} axis the axis around which to rotate * @param {Number} rad the angle in radians * @returns {quat} out **/function setAxisAngle(out,axis,rad){rad=rad*0.5;var s=Math.sin(rad);out[0]=s*axis[0];out[1]=s*axis[1];out[2]=s*axis[2];out[3]=Math.cos(rad);return out;}/** * Multiplies two quat's * * @param {quat} out the receiving quaternion * @param {ReadonlyQuat} a the first operand * @param {ReadonlyQuat} b the second operand * @returns {quat} out */function multiply(out,a,b){var ax=a[0],ay=a[1],az=a[2],aw=a[3];var bx=b[0],by=b[1],bz=b[2],bw=b[3];out[0]=ax*bw+aw*bx+ay*bz-az*by;out[1]=ay*bw+aw*by+az*bx-ax*bz;out[2]=az*bw+aw*bz+ax*by-ay*bx;out[3]=aw*bw-ax*bx-ay*by-az*bz;return out;}/** * Rotates a quaternion by the given angle about the X axis * * @param {quat} out quat receiving operation result * @param {ReadonlyQuat} a quat to rotate * @param {number} rad angle (in radians) to rotate * @returns {quat} out */function rotateX(out,a,rad){rad*=0.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3];var bx=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw+aw*bx;out[1]=ay*bw+az*bx;out[2]=az*bw-ay*bx;out[3]=aw*bw-ax*bx;return out;}/** * Rotates a quaternion by the given angle about the Y axis * * @param {quat} out quat receiving operation result * @param {ReadonlyQuat} a quat to rotate * @param {number} rad angle (in radians) to rotate * @returns {quat} out */function rotateY(out,a,rad){rad*=0.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3];var by=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw-az*by;out[1]=ay*bw+aw*by;out[2]=az*bw+ax*by;out[3]=aw*bw-ay*by;return out;}/** * Rotates a quaternion by the given angle about the Z axis * * @param {quat} out quat receiving operation result * @param {ReadonlyQuat} a quat to rotate * @param {number} rad angle (in radians) to rotate * @returns {quat} out */function rotateZ(out,a,rad){rad*=0.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3];var bz=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw+ay*bz;out[1]=ay*bw-ax*bz;out[2]=az*bw+aw*bz;out[3]=aw*bw-az*bz;return out;}/** * Calculates the W component of a quat from the X, Y, and Z components. * Assumes that quaternion is 1 unit in length. * Any existing W component will be ignored. * * @param {quat} out the receiving quaternion * @param {ReadonlyQuat} a quat to calculate W component of * @returns {quat} out */function calculateW(out,a){var x=a[0],y=a[1],z=a[2];out[0]=x;out[1]=y;out[2]=z;out[3]=Math.sqrt(Math.abs(1.0-x*x-y*y-z*z));return out;}/** * Performs a spherical linear interpolation between two quat * * @param {quat} out the receiving quaternion * @param {ReadonlyQuat} a the first operand * @param {ReadonlyQuat} b the second operand * @param {Number} t interpolation amount, in the range [0-1], between the two inputs * @returns {quat} out */function slerp(out,a,b,t){// benchmarks: // http://jsperf.com/quaternion-slerp-implementations var ax=a[0],ay=a[1],az=a[2],aw=a[3];var bx=b[0],by=b[1],bz=b[2],bw=b[3];var omega,cosom,sinom,scale0,scale1;// calc cosine cosom=ax*bx+ay*by+az*bz+aw*bw;// adjust signs (if necessary) if(cosom<0.0){cosom=-cosom;bx=-bx;by=-by;bz=-bz;bw=-bw;}// calculate coefficients if(1.0-cosom>EPSILON){// standard case (slerp) omega=Math.acos(cosom);sinom=Math.sin(omega);scale0=Math.sin((1.0-t)*omega)/sinom;scale1=Math.sin(t*omega)/sinom;}else {// "from" and "to" quaternions are very close // ... so we can do a linear interpolation scale0=1.0-t;scale1=t;}// calculate final values out[0]=scale0*ax+scale1*bx;out[1]=scale0*ay+scale1*by;out[2]=scale0*az+scale1*bz;out[3]=scale0*aw+scale1*bw;return out;}/** * Calculates the inverse of a quat * * @param {quat} out the receiving quaternion * @param {ReadonlyQuat} a quat to calculate inverse of * @returns {quat} out */function invert(out,a){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var dot=a0*a0+a1*a1+a2*a2+a3*a3;var invDot=dot?1.0/dot:0;// TODO: Would be faster to return [0,0,0,0] immediately if dot == 0 out[0]=-a0*invDot;out[1]=-a1*invDot;out[2]=-a2*invDot;out[3]=a3*invDot;return out;}/** * Calculates the conjugate of a quat * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. * * @param {quat} out the receiving quaternion * @param {ReadonlyQuat} a quat to calculate conjugate of * @returns {quat} out */function conjugate(out,a){out[0]=-a[0];out[1]=-a[1];out[2]=-a[2];out[3]=a[3];return out;}/** * Creates a quaternion from the given 3x3 rotation matrix. * * NOTE: The resultant quaternion is not normalized, so you should be sure * to renormalize the quaternion yourself where necessary. * * @param {quat} out the receiving quaternion * @param {ReadonlyMat3} m rotation matrix * @returns {quat} out * @function */function fromMat3(out,m){// Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes // article "Quaternion Calculus and Fast Animation". var fTrace=m[0]+m[4]+m[8];var fRoot;if(fTrace>0.0){// |w| > 1/2, may as well choose w > 1/2 fRoot=Math.sqrt(fTrace+1.0);// 2w out[3]=0.5*fRoot;fRoot=0.5/fRoot;// 1/(4w) out[0]=(m[5]-m[7])*fRoot;out[1]=(m[6]-m[2])*fRoot;out[2]=(m[1]-m[3])*fRoot;}else {// |w| <= 1/2 var i=0;if(m[4]>m[0])i=1;if(m[8]>m[i*3+i])i=2;var j=(i+1)%3;var k=(i+2)%3;fRoot=Math.sqrt(m[i*3+i]-m[j*3+j]-m[k*3+k]+1.0);out[i]=0.5*fRoot;fRoot=0.5/fRoot;out[3]=(m[j*3+k]-m[k*3+j])*fRoot;out[j]=(m[j*3+i]+m[i*3+j])*fRoot;out[k]=(m[k*3+i]+m[i*3+k])*fRoot;}return out;}/** * Adds two quat's * * @param {quat} out the receiving quaternion * @param {ReadonlyQuat} a the first operand * @param {ReadonlyQuat} b the second operand * @returns {quat} out * @function */var add=add$1;/** * Scales a quat by a scalar number * * @param {quat} out the receiving vector * @param {ReadonlyQuat} a the vector to scale * @param {Number} b amount to scale the vector by * @returns {quat} out * @function */var scale=scale$1;/** * Calculates the dot product of two quat's * * @param {ReadonlyQuat} a the first operand * @param {ReadonlyQuat} b the second operand * @returns {Number} dot product of a and b * @function */var dot=dot$1;/** * Performs a linear interpolation between two quat's * * @param {quat} out the receiving quaternion * @param {ReadonlyQuat} a the first operand * @param {ReadonlyQuat} b the second operand * @param {Number} t interpolation amount, in the range [0-1], between the two inputs * @returns {quat} out * @function */var lerp$2=lerp$1$1;/** * Calculates the length of a quat * * @param {ReadonlyQuat} a vector to calculate length of * @returns {Number} length of a */var length=length$1;/** * Calculates the squared length of a quat * * @param {ReadonlyQuat} a vector to calculate squared length of * @returns {Number} squared length of a * @function */var squaredLength=squaredLength$1;/** * Normalize a quat * * @param {quat} out the receiving quaternion * @param {ReadonlyQuat} a quaternion to normalize * @returns {quat} out * @function */var normalize=normalize$1;/** * Sets a quaternion to represent the shortest rotation from one * vector to another. * * Both vectors are assumed to be unit length. * * @param {quat} out the receiving quaternion. * @param {ReadonlyVec3} a the initial vector * @param {ReadonlyVec3} b the destination vector * @returns {quat} out */var rotationTo=function(){var tmpvec3=create$3();var xUnitVec3=fromValues(1,0,0);var yUnitVec3=fromValues(0,1,0);return function(out,a,b){var dot=dot$2(a,b);if(dot<-0.999999){cross(tmpvec3,xUnitVec3,a);if(len(tmpvec3)<0.000001)cross(tmpvec3,yUnitVec3,a);normalize$2(tmpvec3,tmpvec3);setAxisAngle(out,tmpvec3,Math.PI);return out;}else if(dot>0.999999){out[0]=0;out[1]=0;out[2]=0;out[3]=1;return out;}else {cross(tmpvec3,a,b);out[0]=tmpvec3[0];out[1]=tmpvec3[1];out[2]=tmpvec3[2];out[3]=1+dot;return normalize(out,out);}};}();/** * Performs a spherical linear interpolation with two control points * * @param {quat} out the receiving quaternion * @param {ReadonlyQuat} a the first operand * @param {ReadonlyQuat} b the second operand * @param {ReadonlyQuat} c the third operand * @param {ReadonlyQuat} d the fourth operand * @param {Number} t interpolation amount, in the range [0-1], between the two inputs * @returns {quat} out */(function(){var temp1=create();var temp2=create();return function(out,a,b,c,d,t){slerp(temp1,a,d,t);slerp(temp2,b,c,t);slerp(out,temp1,temp2,2*t*(1-t));return out;};})();/** * Sets the specified quaternion with values corresponding to the given * axes. Each axis is a vec3 and is expected to be unit length and * perpendicular to all other specified axes. * * @param {ReadonlyVec3} view the vector representing the viewing direction * @param {ReadonlyVec3} right the vector representing the local "right" direction * @param {ReadonlyVec3} up the vector representing the local "up" direction * @returns {quat} out */(function(){var matr=create$2();return function(out,view,right,up){matr[0]=right[0];matr[3]=right[1];matr[6]=right[2];matr[1]=up[0];matr[4]=up[1];matr[7]=up[2];matr[2]=-view[0];matr[5]=-view[1];matr[8]=-view[2];return normalize(out,fromMat3(out,matr));};})();var IDENTITY_QUATERNION=[0,0,0,1];class Quaternion$1 extends MathArray{constructor(){var x=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var z=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var w=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;super(-0,-0,-0,-0);if(Array.isArray(x)&&arguments.length===1){this.copy(x);}else {this.set(x,y,z,w);}}copy(array){this[0]=array[0];this[1]=array[1];this[2]=array[2];this[3]=array[3];return this.check();}set(x,y,z,w){this[0]=x;this[1]=y;this[2]=z;this[3]=w;return this.check();}fromMatrix3(m){fromMat3(this,m);return this.check();}identity(){identity(this);return this.check();}fromAxisRotation(axis,rad){setAxisAngle(this,axis,rad);return this.check();}setAxisAngle(axis,rad){return this.fromAxisRotation(axis,rad);}get ELEMENTS(){return 4;}get x(){return this[0];}set x(value){this[0]=checkNumber(value);}get y(){return this[1];}set y(value){this[1]=checkNumber(value);}get z(){return this[2];}set z(value){this[2]=checkNumber(value);}get w(){return this[3];}set w(value){this[3]=checkNumber(value);}len(){return length(this);}lengthSquared(){return squaredLength(this);}dot(a,b){if(b!==undefined){throw new Error('Quaternion.dot only takes one argument');}return dot(this,a);}rotationTo(vectorA,vectorB){rotationTo(this,vectorA,vectorB);return this.check();}add(a,b){if(b!==undefined){throw new Error('Quaternion.add only takes one argument');}add(this,this,a);return this.check();}calculateW(){calculateW(this,this);return this.check();}conjugate(){conjugate(this,this);return this.check();}invert(){invert(this,this);return this.check();}lerp(a,b,t){lerp$2(this,a,b,t);return this.check();}multiplyRight(a,b){assert$4(!b);multiply(this,this,a);return this.check();}multiplyLeft(a,b){assert$4(!b);multiply(this,a,this);return this.check();}normalize(){var length=this.len();var l=length>0?1/length:0;this[0]=this[0]*l;this[1]=this[1]*l;this[2]=this[2]*l;this[3]=this[3]*l;if(length===0){this[3]=1;}return this.check();}rotateX(rad){rotateX(this,this,rad);return this.check();}rotateY(rad){rotateY(this,this,rad);return this.check();}rotateZ(rad){rotateZ(this,this,rad);return this.check();}scale(b){scale(this,this,b);return this.check();}slerp(start,target,ratio){switch(arguments.length){case 1:({start=IDENTITY_QUATERNION,target,ratio}=arguments[0]);break;case 2:[target,ratio]=arguments;start=this;break;}slerp(this,start,target,ratio);return this.check();}transformVector4(vector){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:vector;transformQuat(result,vector,this);return checkVector(result,4);}lengthSq(){return this.lengthSquared();}setFromAxisAngle(axis,rad){return this.setAxisAngle(axis,rad);}premultiply(a,b){return this.multiplyLeft(a,b);}multiply(a,b){return this.multiplyRight(a,b);}}var _MathUtils={EPSILON1:1e-1,EPSILON2:1e-2,EPSILON3:1e-3,EPSILON4:1e-4,EPSILON5:1e-5,EPSILON6:1e-6,EPSILON7:1e-7,EPSILON8:1e-8,EPSILON9:1e-9,EPSILON10:1e-10,EPSILON11:1e-11,EPSILON12:1e-12,EPSILON13:1e-13,EPSILON14:1e-14,EPSILON15:1e-15,EPSILON16:1e-16,EPSILON17:1e-17,EPSILON18:1e-18,EPSILON19:1e-19,EPSILON20:1e-20,PI_OVER_TWO:Math.PI/2,PI_OVER_FOUR:Math.PI/4,PI_OVER_SIX:Math.PI/6,TWO_PI:Math.PI*2};var WGS84_RADIUS_X$1=6378137.0;var WGS84_RADIUS_Y$1=6378137.0;var WGS84_RADIUS_Z$1=6356752.3142451793;var noop$2=x=>x;var scratchVector$6=new Vector3$1();function fromCartographic(cartographic,result){var map=arguments.length>2&&arguments[2]!==undefined?arguments[2]:noop$2;if(isArray(cartographic)){result[0]=map(cartographic[0]);result[1]=map(cartographic[1]);result[2]=cartographic[2];}else if('longitude'in cartographic){result[0]=map(cartographic.longitude);result[1]=map(cartographic.latitude);result[2]=cartographic.height;}else {result[0]=map(cartographic.x);result[1]=map(cartographic.y);result[2]=cartographic.z;}return result;}function fromCartographicToRadians(cartographic){var vector=arguments.length>1&&arguments[1]!==undefined?arguments[1]:scratchVector$6;return fromCartographic(cartographic,vector,config$2._cartographicRadians?noop$2:toRadians);}function toCartographic(vector,cartographic){var map=arguments.length>2&&arguments[2]!==undefined?arguments[2]:noop$2;if(isArray(cartographic)){cartographic[0]=map(vector[0]);cartographic[1]=map(vector[1]);cartographic[2]=vector[2];}else if('longitude'in cartographic){cartographic.longitude=map(vector[0]);cartographic.latitude=map(vector[1]);cartographic.height=vector[2];}else {cartographic.x=map(vector[0]);cartographic.y=map(vector[1]);cartographic.z=vector[2];}return cartographic;}function toCartographicFromRadians(vector,cartographic){return toCartographic(vector,cartographic,config$2._cartographicRadians?noop$2:toDegrees);}var scratchVector$5=new Vector3$1();var scaleToGeodeticSurfaceIntersection=new Vector3$1();var scaleToGeodeticSurfaceGradient=new Vector3$1();function scaleToGeodeticSurface(cartesian,ellipsoid){var result=arguments.length>2&&arguments[2]!==undefined?arguments[2]:new Vector3$1();var{oneOverRadii,oneOverRadiiSquared,centerToleranceSquared}=ellipsoid;scratchVector$5.from(cartesian);var positionX=cartesian.x;var positionY=cartesian.y;var positionZ=cartesian.z;var oneOverRadiiX=oneOverRadii.x;var oneOverRadiiY=oneOverRadii.y;var oneOverRadiiZ=oneOverRadii.z;var x2=positionX*positionX*oneOverRadiiX*oneOverRadiiX;var y2=positionY*positionY*oneOverRadiiY*oneOverRadiiY;var z2=positionZ*positionZ*oneOverRadiiZ*oneOverRadiiZ;var squaredNorm=x2+y2+z2;var ratio=Math.sqrt(1.0/squaredNorm);if(!Number.isFinite(ratio)){return undefined;}var intersection=scaleToGeodeticSurfaceIntersection;intersection.copy(cartesian).scale(ratio);if(squaredNorm_MathUtils.EPSILON12);return scratchVector$5.scale([xMultiplier,yMultiplier,zMultiplier]).to(result);}var EPSILON14=1e-14;var scratchOrigin=new Vector3$1();var VECTOR_PRODUCT_LOCAL_FRAME={up:{south:'east',north:'west',west:'south',east:'north'},down:{south:'west',north:'east',west:'north',east:'south'},south:{up:'west',down:'east',west:'down',east:'up'},north:{up:'east',down:'west',west:'up',east:'down'},west:{up:'north',down:'south',north:'down',south:'up'},east:{up:'south',down:'north',north:'up',south:'down'}};var degeneratePositionLocalFrame={north:[-1,0,0],east:[0,1,0],up:[0,0,1],south:[1,0,0],west:[0,-1,0],down:[0,0,-1]};var scratchAxisVectors={east:new Vector3$1(),north:new Vector3$1(),up:new Vector3$1(),west:new Vector3$1(),south:new Vector3$1(),down:new Vector3$1()};var scratchVector1=new Vector3$1();var scratchVector2$1=new Vector3$1();var scratchVector3$1=new Vector3$1();function localFrameToFixedFrame(ellipsoid,firstAxis,secondAxis,thirdAxis,cartesianOrigin,result){var thirdAxisInferred=VECTOR_PRODUCT_LOCAL_FRAME[firstAxis]&&VECTOR_PRODUCT_LOCAL_FRAME[firstAxis][secondAxis];assert$4(thirdAxisInferred&&(!thirdAxis||thirdAxis===thirdAxisInferred));var firstAxisVector;var secondAxisVector;var thirdAxisVector;var origin=scratchOrigin.copy(cartesianOrigin);var atPole=equals$1(origin.x,0.0,EPSILON14)&&equals$1(origin.y,0.0,EPSILON14);if(atPole){var sign=Math.sign(origin.z);firstAxisVector=scratchVector1.fromArray(degeneratePositionLocalFrame[firstAxis]);if(firstAxis!=='east'&&firstAxis!=='west'){firstAxisVector.scale(sign);}secondAxisVector=scratchVector2$1.fromArray(degeneratePositionLocalFrame[secondAxis]);if(secondAxis!=='east'&&secondAxis!=='west'){secondAxisVector.scale(sign);}thirdAxisVector=scratchVector3$1.fromArray(degeneratePositionLocalFrame[thirdAxis]);if(thirdAxis!=='east'&&thirdAxis!=='west'){thirdAxisVector.scale(sign);}}else {var{up,east,north}=scratchAxisVectors;east.set(-origin.y,origin.x,0.0).normalize();ellipsoid.geodeticSurfaceNormal(origin,up);north.copy(up).cross(east);var{down,west,south}=scratchAxisVectors;down.copy(up).scale(-1);west.copy(east).scale(-1);south.copy(north).scale(-1);firstAxisVector=scratchAxisVectors[firstAxis];secondAxisVector=scratchAxisVectors[secondAxis];thirdAxisVector=scratchAxisVectors[thirdAxis];}result[0]=firstAxisVector.x;result[1]=firstAxisVector.y;result[2]=firstAxisVector.z;result[3]=0.0;result[4]=secondAxisVector.x;result[5]=secondAxisVector.y;result[6]=secondAxisVector.z;result[7]=0.0;result[8]=thirdAxisVector.x;result[9]=thirdAxisVector.y;result[10]=thirdAxisVector.z;result[11]=0.0;result[12]=origin.x;result[13]=origin.y;result[14]=origin.z;result[15]=1.0;return result;}var scratchVector$4=new Vector3$1();var scratchNormal$2=new Vector3$1();var scratchK=new Vector3$1();var scratchPosition$2=new Vector3$1();var scratchHeight=new Vector3$1();var scratchCartesian=new Vector3$1();var wgs84;class Ellipsoid{static get WGS84(){wgs84=wgs84||new Ellipsoid(WGS84_RADIUS_X$1,WGS84_RADIUS_Y$1,WGS84_RADIUS_Z$1);return wgs84;}constructor(){var x=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0.0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0.0;var z=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0.0;assert$4(x>=0.0);assert$4(y>=0.0);assert$4(z>=0.0);this.radii=new Vector3$1(x,y,z);this.radiiSquared=new Vector3$1(x*x,y*y,z*z);this.radiiToTheFourth=new Vector3$1(x*x*x*x,y*y*y*y,z*z*z*z);this.oneOverRadii=new Vector3$1(x===0.0?0.0:1.0/x,y===0.0?0.0:1.0/y,z===0.0?0.0:1.0/z);this.oneOverRadiiSquared=new Vector3$1(x===0.0?0.0:1.0/(x*x),y===0.0?0.0:1.0/(y*y),z===0.0?0.0:1.0/(z*z));this.minimumRadius=Math.min(x,y,z);this.maximumRadius=Math.max(x,y,z);this.centerToleranceSquared=_MathUtils.EPSILON1;if(this.radiiSquared.z!==0){this.squaredXOverSquaredZ=this.radiiSquared.x/this.radiiSquared.z;}Object.freeze(this);}equals(right){return this===right||Boolean(right&&this.radii.equals(right.radii));}toString(){return this.radii.toString();}cartographicToCartesian(cartographic){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0];var normal=scratchNormal$2;var k=scratchK;var[,,height]=cartographic;this.geodeticSurfaceNormalCartographic(cartographic,normal);k.copy(this.radiiSquared).scale(normal);var gamma=Math.sqrt(normal.dot(k));k.scale(1/gamma);normal.scale(height);k.add(normal);return k.to(result);}cartesianToCartographic(cartesian){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0];scratchCartesian.from(cartesian);var point=this.scaleToGeodeticSurface(scratchCartesian,scratchPosition$2);if(!point){return undefined;}var normal=this.geodeticSurfaceNormal(point,scratchNormal$2);var h=scratchHeight;h.copy(scratchCartesian).subtract(point);var longitude=Math.atan2(normal.y,normal.x);var latitude=Math.asin(normal.z);var height=Math.sign(dot$2(h,scratchCartesian))*length$2(h);return toCartographicFromRadians([longitude,latitude,height],result);}eastNorthUpToFixedFrame(origin){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Matrix4$1();return localFrameToFixedFrame(this,'east','north','up',origin,result);}localFrameToFixedFrame(firstAxis,secondAxis,thirdAxis,origin){var result=arguments.length>4&&arguments[4]!==undefined?arguments[4]:new Matrix4$1();return localFrameToFixedFrame(this,firstAxis,secondAxis,thirdAxis,origin,result);}geocentricSurfaceNormal(cartesian){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0];return scratchVector$4.from(cartesian).normalize().to(result);}geodeticSurfaceNormalCartographic(cartographic){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0];var cartographicVectorRadians=fromCartographicToRadians(cartographic);var longitude=cartographicVectorRadians[0];var latitude=cartographicVectorRadians[1];var cosLatitude=Math.cos(latitude);scratchVector$4.set(cosLatitude*Math.cos(longitude),cosLatitude*Math.sin(longitude),Math.sin(latitude)).normalize();return scratchVector$4.to(result);}geodeticSurfaceNormal(cartesian){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0];return scratchVector$4.from(cartesian).scale(this.oneOverRadiiSquared).normalize().to(result);}scaleToGeodeticSurface(cartesian,result){return scaleToGeodeticSurface(cartesian,this,result);}scaleToGeocentricSurface(cartesian){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0];scratchPosition$2.from(cartesian);var positionX=scratchPosition$2.x;var positionY=scratchPosition$2.y;var positionZ=scratchPosition$2.z;var oneOverRadiiSquared=this.oneOverRadiiSquared;var beta=1.0/Math.sqrt(positionX*positionX*oneOverRadiiSquared.x+positionY*positionY*oneOverRadiiSquared.y+positionZ*positionZ*oneOverRadiiSquared.z);return scratchPosition$2.multiplyScalar(beta).to(result);}transformPositionToScaledSpace(position){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0];return scratchPosition$2.from(position).scale(this.oneOverRadii).to(result);}transformPositionFromScaledSpace(position){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0];return scratchPosition$2.from(position).scale(this.radii).to(result);}getSurfaceNormalIntersectionWithZAxis(position){var buffer=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0.0;var result=arguments.length>2&&arguments[2]!==undefined?arguments[2]:[0,0,0];assert$4(equals$1(this.radii.x,this.radii.y,_MathUtils.EPSILON15));assert$4(this.radii.z>0);scratchPosition$2.from(position);var z=scratchPosition$2.z*(1-this.squaredXOverSquaredZ);if(Math.abs(z)>=this.radii.z-buffer){return undefined;}return scratchPosition$2.set(0.0,0.0,z).to(result);}}class DoublyLinkedListNode{constructor(item,previous,next){_defineProperty$1(this,"item",void 0);_defineProperty$1(this,"previous",void 0);_defineProperty$1(this,"next",void 0);this.item=item;this.previous=previous;this.next=next;}}class DoublyLinkedList{constructor(){_defineProperty$1(this,"head",null);_defineProperty$1(this,"tail",null);_defineProperty$1(this,"_length",0);}get length(){return this._length;}add(item){var node=new DoublyLinkedListNode(item,this.tail,null);if(this.tail){this.tail.next=node;this.tail=node;}else {this.head=node;this.tail=node;}++this._length;return node;}remove(node){if(!node){return;}if(node.previous&&node.next){node.previous.next=node.next;node.next.previous=node.previous;}else if(node.previous){node.previous.next=null;this.tail=node.previous;}else if(node.next){node.next.previous=null;this.head=node.next;}else {this.head=null;this.tail=null;}node.next=null;node.previous=null;--this._length;}splice(node,nextNode){if(node===nextNode){return;}this.remove(nextNode);this._insert(node,nextNode);}_insert(node,nextNode){var oldNodeNext=node.next;node.next=nextNode;if(this.tail===node){this.tail=nextNode;}else {oldNodeNext.previous=nextNode;}nextNode.next=oldNodeNext;nextNode.previous=node;++this._length;}}function defined$5(x){return x!==undefined&&x!==null;}class TilesetCache{constructor(){_defineProperty$1(this,"_list",void 0);_defineProperty$1(this,"_sentinel",void 0);_defineProperty$1(this,"_trimTiles",void 0);this._list=new DoublyLinkedList();this._sentinel=this._list.add('sentinel');this._trimTiles=false;}reset(){this._list.splice(this._list.tail,this._sentinel);}touch(tile){var node=tile._cacheNode;if(defined$5(node)){this._list.splice(this._sentinel,node);}}add(tileset,tile,addCallback){if(!defined$5(tile._cacheNode)){tile._cacheNode=this._list.add(tile);if(addCallback){addCallback(tileset,tile);}}}unloadTile(tileset,tile,unloadCallback){var node=tile._cacheNode;if(!defined$5(node)){return;}this._list.remove(node);tile._cacheNode=undefined;if(unloadCallback){unloadCallback(tileset,tile);}}unloadTiles(tileset,unloadCallback){var trimTiles=this._trimTiles;this._trimTiles=false;var list=this._list;var maximumMemoryUsageInBytes=(Potree.settings.tiles3DMaxMemory||tileset.maximumMemoryUsage)*1024*1024;var sentinel=this._sentinel;var node=list.head;/* while (node !== sentinel && (tileset.gpuMemoryUsageInBytes > maximumMemoryUsageInBytes || trimTiles)) { const tile = node.item; node = node.next; this.unloadTile(tileset, tile, unloadCallback); } */ //改 while(node!==sentinel&&(getGpuMemoryUsage()>maximumMemoryUsageInBytes||trimTiles)){var tile=node.item;node=node.next;this.unloadTile(tileset,tile,unloadCallback);if(viewer.visiVertexCount>1500000){//add: 针对部分特别精细的很卡如 https://4dkk.4dage.com/scene_view_data/SG-t-WReTBN204dQ/images/3dtiles/tileset.json tileset.options.maximumScreenSpaceError*=1.1;tileset.options.maximumScreenSpaceError=Math.min(1000,tileset.options.maximumScreenSpaceError);}}}trim(){this._trimTiles=true;}}function calculateTransformProps(tileHeader,tile){assert$7(tileHeader);assert$7(tile);var{rtcCenter,gltfUpAxis}=tile;var{computedTransform,boundingVolume:{center}}=tileHeader;var modelMatrix=new Matrix4$1(computedTransform);if(rtcCenter){modelMatrix.translate(rtcCenter);}switch(gltfUpAxis){case'Z':break;case'Y':var rotationY=new Matrix4$1().rotateX(Math.PI/2);modelMatrix=modelMatrix.multiplyRight(rotationY);break;case'X':var rotationX=new Matrix4$1().rotateY(-Math.PI/2);modelMatrix=modelMatrix.multiplyRight(rotationX);break;}if(tile.isQuantized){modelMatrix.translate(tile.quantizedVolumeOffset).scale(tile.quantizedVolumeScale);}var cartesianOrigin=new Vector3$1(center);tile.cartesianModelMatrix=modelMatrix;tile.cartesianOrigin=cartesianOrigin;var cartographicOrigin=Ellipsoid.WGS84.cartesianToCartographic(cartesianOrigin,new Vector3$1());var fromFixedFrameMatrix=Ellipsoid.WGS84.eastNorthUpToFixedFrame(cartesianOrigin);var toFixedFrameMatrix=fromFixedFrameMatrix.invert();tile.cartographicModelMatrix=toFixedFrameMatrix.multiplyRight(modelMatrix);tile.cartographicOrigin=cartographicOrigin;if(!tile.coordinateSystem){tile.modelMatrix=tile.cartographicModelMatrix;}}var INTERSECTION=Object.freeze({OUTSIDE:-1,INTERSECTING:0,INSIDE:1});new Vector3$1();new Vector3$1();var scratchVector$3=new Vector3$1();var scratchVector2=new Vector3$1();class BoundingSphere{constructor(){var center=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[0,0,0];var radius=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0.0;this.radius=-0;this.center=new Vector3$1();this.fromCenterRadius(center,radius);}fromCenterRadius(center,radius){this.center.from(center);this.radius=radius;return this;}fromCornerPoints(corner,oppositeCorner){oppositeCorner=scratchVector$3.from(oppositeCorner);this.center=new Vector3$1().from(corner).add(oppositeCorner).scale(0.5);this.radius=this.center.distance(oppositeCorner);return this;}equals(right){return this===right||Boolean(right)&&this.center.equals(right.center)&&this.radius===right.radius;}clone(){return new BoundingSphere(this.center,this.radius);}union(boundingSphere){var leftCenter=this.center;var leftRadius=this.radius;var rightCenter=boundingSphere.center;var rightRadius=boundingSphere.radius;var toRightCenter=scratchVector$3.copy(rightCenter).subtract(leftCenter);var centerSeparation=toRightCenter.magnitude();if(leftRadius>=centerSeparation+rightRadius){return this.clone();}if(rightRadius>=centerSeparation+leftRadius){return boundingSphere.clone();}var halfDistanceBetweenTangentPoints=(leftRadius+centerSeparation+rightRadius)*0.5;scratchVector2.copy(toRightCenter).scale((-leftRadius+halfDistanceBetweenTangentPoints)/centerSeparation).add(leftCenter);this.center.copy(scratchVector2);this.radius=halfDistanceBetweenTangentPoints;return this;}expand(point){point=scratchVector$3.from(point);var radius=point.subtract(this.center).magnitude();if(radius>this.radius){this.radius=radius;}return this;}transform(transform){this.center.transform(transform);var scale=getScaling(scratchVector$3,transform);this.radius=Math.max(scale[0],Math.max(scale[1],scale[2]))*this.radius;return this;}distanceSquaredTo(point){var d=this.distanceTo(point);return d*d;}distanceTo(point){point=scratchVector$3.from(point);var delta=point.subtract(this.center);return Math.max(0,delta.len()-this.radius);}intersectPlane(plane){var center=this.center;var radius=this.radius;var normal=plane.normal;var distanceToPlane=normal.dot(center)+plane.distance;if(distanceToPlane<-radius){return INTERSECTION.OUTSIDE;}if(distanceToPlane0&&arguments[0]!==undefined?arguments[0]:[0,0,0];var halfAxes=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0,0,0,0,0,0,0];this.center=new Vector3$1().from(center);this.halfAxes=new Matrix3$1(halfAxes);}get halfSize(){var xAxis=this.halfAxes.getColumn(0);var yAxis=this.halfAxes.getColumn(1);var zAxis=this.halfAxes.getColumn(2);return [new Vector3$1(xAxis).len(),new Vector3$1(yAxis).len(),new Vector3$1(zAxis).len()];}get quaternion(){var xAxis=this.halfAxes.getColumn(0);var yAxis=this.halfAxes.getColumn(1);var zAxis=this.halfAxes.getColumn(2);var normXAxis=new Vector3$1(xAxis).normalize();var normYAxis=new Vector3$1(yAxis).normalize();var normZAxis=new Vector3$1(zAxis).normalize();return new Quaternion$1().fromMatrix3(new Matrix3$1([...normXAxis,...normYAxis,...normZAxis]));}fromCenterHalfSizeQuaternion(center,halfSize,quaternion){var quaternionObject=new Quaternion$1(quaternion);var directionsMatrix=new Matrix3$1().fromQuaternion(quaternionObject);directionsMatrix[0]=directionsMatrix[0]*halfSize[0];directionsMatrix[1]=directionsMatrix[1]*halfSize[0];directionsMatrix[2]=directionsMatrix[2]*halfSize[0];directionsMatrix[3]=directionsMatrix[3]*halfSize[1];directionsMatrix[4]=directionsMatrix[4]*halfSize[1];directionsMatrix[5]=directionsMatrix[5]*halfSize[1];directionsMatrix[6]=directionsMatrix[6]*halfSize[2];directionsMatrix[7]=directionsMatrix[7]*halfSize[2];directionsMatrix[8]=directionsMatrix[8]*halfSize[2];this.center=new Vector3$1().from(center);this.halfAxes=directionsMatrix;return this;}clone(){return new OrientedBoundingBox(this.center,this.halfAxes);}equals(right){return this===right||Boolean(right)&&this.center.equals(right.center)&&this.halfAxes.equals(right.halfAxes);}getBoundingSphere(){var result=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new BoundingSphere();var halfAxes=this.halfAxes;var u=halfAxes.getColumn(0,scratchVectorU);//前三个 var v=halfAxes.getColumn(1,scratchVectorV);var w=halfAxes.getColumn(2,scratchVectorW);var cornerVector=scratchVector3.copy(u).add(v).add(w);result.center.copy(this.center);result.radius=cornerVector.magnitude();return result;}intersectPlane(plane){var center=this.center;var normal=plane.normal;var halfAxes=this.halfAxes;var normalX=normal.x;var normalY=normal.y;var normalZ=normal.z;var radEffective=Math.abs(normalX*halfAxes[MATRIX3.COLUMN0ROW0]+normalY*halfAxes[MATRIX3.COLUMN0ROW1]+normalZ*halfAxes[MATRIX3.COLUMN0ROW2])+Math.abs(normalX*halfAxes[MATRIX3.COLUMN1ROW0]+normalY*halfAxes[MATRIX3.COLUMN1ROW1]+normalZ*halfAxes[MATRIX3.COLUMN1ROW2])+Math.abs(normalX*halfAxes[MATRIX3.COLUMN2ROW0]+normalY*halfAxes[MATRIX3.COLUMN2ROW1]+normalZ*halfAxes[MATRIX3.COLUMN2ROW2]);var distanceToPlane=normal.dot(center)+plane.distance;if(distanceToPlane<=-radEffective){return INTERSECTION.OUTSIDE;}else if(distanceToPlane>=radEffective){return INTERSECTION.INSIDE;}return INTERSECTION.INTERSECTING;//在相机frustum内 }distanceTo(point){return Math.sqrt(this.distanceSquaredTo(point));}/* distanceSquaredTo(point) {//相机到bound外壳的距离平方 let center = this.center.clone() center.z *= -1 const offset = scratchOffset.from(point).subtract(center); const halfAxes = this.halfAxes; const u = halfAxes.getColumn(0, scratchVectorU); const v = halfAxes.getColumn(1, scratchVectorV); const w = halfAxes.getColumn(2, scratchVectorW); u.z *= -1 v.z *= -1 w.z *= -1 const uHalf = u.magnitude(); const vHalf = v.magnitude(); const wHalf = w.magnitude(); u.normalize(); v.normalize(); w.normalize(); let distanceSquared = 0.0; let d; d = Math.abs(offset.dot(u)) - uHalf; if (d > 0) { distanceSquared += d * d; } d = Math.abs(offset.dot(v)) - vHalf; if (d > 0) { distanceSquared += d * d; } d = Math.abs(offset.dot(w)) - wHalf; if (d > 0) { distanceSquared += d * d; } return distanceSquared; } */distanceSquaredTo(point){//相机到bound外壳的距离平方 var offset=scratchOffset.from(point).subtract(this.center);var halfAxes=this.halfAxes;var u=halfAxes.getColumn(0,scratchVectorU);var v=halfAxes.getColumn(1,scratchVectorV);var w=halfAxes.getColumn(2,scratchVectorW);var uHalf=u.magnitude();var vHalf=v.magnitude();var wHalf=w.magnitude();u.normalize();v.normalize();w.normalize();var distanceSquared=0.0;var d;d=Math.abs(offset.dot(u))-uHalf;if(d>0){distanceSquared+=d*d;}d=Math.abs(offset.dot(v))-vHalf;if(d>0){distanceSquared+=d*d;}d=Math.abs(offset.dot(w))-wHalf;if(d>0){distanceSquared+=d*d;}return distanceSquared;}computePlaneDistances(position,direction){var result=arguments.length>2&&arguments[2]!==undefined?arguments[2]:[-0,-0];var minDist=Number.POSITIVE_INFINITY;var maxDist=Number.NEGATIVE_INFINITY;var center=this.center;var halfAxes=this.halfAxes;var u=halfAxes.getColumn(0,scratchVectorU);var v=halfAxes.getColumn(1,scratchVectorV);var w=halfAxes.getColumn(2,scratchVectorW);var corner=scratchCorner.copy(u).add(v).add(w).add(center);var toCenter=scratchToCenter.copy(corner).subtract(position);var mag=direction.dot(toCenter);minDist=Math.min(mag,minDist);maxDist=Math.max(mag,maxDist);corner.copy(center).add(u).add(v).subtract(w);toCenter.copy(corner).subtract(position);mag=direction.dot(toCenter);minDist=Math.min(mag,minDist);maxDist=Math.max(mag,maxDist);corner.copy(center).add(u).subtract(v).add(w);toCenter.copy(corner).subtract(position);mag=direction.dot(toCenter);minDist=Math.min(mag,minDist);maxDist=Math.max(mag,maxDist);corner.copy(center).add(u).subtract(v).subtract(w);toCenter.copy(corner).subtract(position);mag=direction.dot(toCenter);minDist=Math.min(mag,minDist);maxDist=Math.max(mag,maxDist);center.copy(corner).subtract(u).add(v).add(w);toCenter.copy(corner).subtract(position);mag=direction.dot(toCenter);minDist=Math.min(mag,minDist);maxDist=Math.max(mag,maxDist);center.copy(corner).subtract(u).add(v).subtract(w);toCenter.copy(corner).subtract(position);mag=direction.dot(toCenter);minDist=Math.min(mag,minDist);maxDist=Math.max(mag,maxDist);center.copy(corner).subtract(u).subtract(v).add(w);toCenter.copy(corner).subtract(position);mag=direction.dot(toCenter);minDist=Math.min(mag,minDist);maxDist=Math.max(mag,maxDist);center.copy(corner).subtract(u).subtract(v).subtract(w);toCenter.copy(corner).subtract(position);mag=direction.dot(toCenter);minDist=Math.min(mag,minDist);maxDist=Math.max(mag,maxDist);result[0]=minDist;result[1]=maxDist;return result;}transform(transformation){this.center.transformAsPoint(transformation);var xAxis=this.halfAxes.getColumn(0,scratchVectorU);xAxis.transformAsPoint(transformation);var yAxis=this.halfAxes.getColumn(1,scratchVectorV);yAxis.transformAsPoint(transformation);var zAxis=this.halfAxes.getColumn(2,scratchVectorW);zAxis.transformAsPoint(transformation);this.halfAxes=new Matrix3$1([...xAxis,...yAxis,...zAxis]);return this;}getTransform(){throw new Error('not implemented');}}var scratchPosition$1=new Vector3$1();var scratchNormal$1=new Vector3$1();class Plane$1{constructor(){var normal=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[0,0,1];var distance=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;this.normal=new Vector3$1();this.distance=-0;this.fromNormalDistance(normal,distance);}fromNormalDistance(normal,distance){assert$4(Number.isFinite(distance));this.normal.from(normal).normalize();this.distance=distance;return this;}fromPointNormal(point,normal){point=scratchPosition$1.from(point);this.normal.from(normal).normalize();var distance=-this.normal.dot(point);this.distance=distance;return this;}fromCoefficients(a,b,c,d){this.normal.set(a,b,c);assert$4(equals$1(this.normal.len(),1));this.distance=d;return this;}clone(plane){return new Plane$1(this.normal,this.distance);}equals(right){return equals$1(this.distance,right.distance)&&equals$1(this.normal,right.normal);}getPointDistance(point){return this.normal.dot(point)+this.distance;}transform(matrix4){var normal=scratchNormal$1.copy(this.normal).transformAsVector(matrix4).normalize();var point=this.normal.scale(-this.distance).transform(matrix4);return this.fromPointNormal(point,normal);}projectPointOntoPlane(point){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0];point=scratchPosition$1.from(point);var pointDistance=this.getPointDistance(point);var scaledNormal=scratchNormal$1.copy(this.normal).scale(pointDistance);return point.subtract(scaledNormal).to(result);}}var faces=[new Vector3$1([1,0,0]),new Vector3$1([0,1,0]),new Vector3$1([0,0,1])];var scratchPlaneCenter=new Vector3$1();var scratchPlaneNormal$1=new Vector3$1();new Plane$1(new Vector3$1(1.0,0.0,0.0),0.0);class CullingVolume{static get MASK_OUTSIDE(){return 0xffffffff;}static get MASK_INSIDE(){return 0x00000000;}static get MASK_INDETERMINATE(){return 0x7fffffff;}constructor(){var planes=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];this.planes=planes;assert$4(this.planes.every(plane=>plane instanceof Plane$1));}fromBoundingSphere(boundingSphere){this.planes.length=2*faces.length;var center=boundingSphere.center;var radius=boundingSphere.radius;var planeIndex=0;for(var faceNormal of faces){var plane0=this.planes[planeIndex];var plane1=this.planes[planeIndex+1];if(!plane0){plane0=this.planes[planeIndex]=new Plane$1();}if(!plane1){plane1=this.planes[planeIndex+1]=new Plane$1();}var plane0Center=scratchPlaneCenter.copy(faceNormal).scale(-radius).add(center);-faceNormal.dot(plane0Center);plane0.fromPointNormal(plane0Center,faceNormal);var plane1Center=scratchPlaneCenter.copy(faceNormal).scale(radius).add(center);var negatedFaceNormal=scratchPlaneNormal$1.copy(faceNormal).negate();-negatedFaceNormal.dot(plane1Center);plane1.fromPointNormal(plane1Center,negatedFaceNormal);planeIndex+=2;}return this;}computeVisibility(boundingVolume){assert$4(boundingVolume);var intersect=INTERSECTION.INSIDE;for(var plane of this.planes){var result=boundingVolume.intersectPlane(plane);switch(result){case INTERSECTION.OUTSIDE:return INTERSECTION.OUTSIDE;case INTERSECTION.INTERSECTING:intersect=INTERSECTION.INTERSECTING;break;}}return intersect;}computeVisibilityWithPlaneMask(boundingVolume,parentPlaneMask){assert$4(boundingVolume,'boundingVolume is required.');assert$4(Number.isFinite(parentPlaneMask),'parentPlaneMask is required.');if(parentPlaneMask===CullingVolume.MASK_OUTSIDE||parentPlaneMask===CullingVolume.MASK_INSIDE){return parentPlaneMask;}var mask=CullingVolume.MASK_INSIDE;var planes=this.planes;for(var k=0;k0&&arguments[0]!==undefined?arguments[0]:{};options=_objectSpread2({near:1.0,far:500000000.0},options);this.left=options.left;this._left=undefined;this.right=options.right;this._right=undefined;this.top=options.top;this._top=undefined;this.bottom=options.bottom;this._bottom=undefined;this.near=options.near;this._near=this.near;this.far=options.far;this._far=this.far;this._cullingVolume=new CullingVolume([new Plane$1(),new Plane$1(),new Plane$1(),new Plane$1(),new Plane$1(),new Plane$1()]);this._perspectiveMatrix=new Matrix4$1();this._infinitePerspective=new Matrix4$1();}clone(){return new PerspectiveOffCenterFrustum({right:this.right,left:this.left,top:this.top,bottom:this.bottom,near:this.near,far:this.far});}equals(other){return other&&other instanceof PerspectiveOffCenterFrustum&&this.right===other.right&&this.left===other.left&&this.top===other.top&&this.bottom===other.bottom&&this.near===other.near&&this.far===other.far;}get projectionMatrix(){update$1(this);return this._perspectiveMatrix;}get infiniteProjectionMatrix(){update$1(this);return this._infinitePerspective;}computeCullingVolume(position,direction,up){assert$4(position,'position is required.');assert$4(direction,'direction is required.');assert$4(up,'up is required.');var planes=this._cullingVolume.planes;up=scratchPlaneUpVector.copy(up).normalize();var right=scratchPlaneRightVector.copy(direction).cross(up).normalize();var nearCenter=scratchPlaneNearCenter.copy(direction).multiplyByScalar(this.near).add(position);var farCenter=scratchPlaneFarCenter.copy(direction).multiplyByScalar(this.far).add(position);var normal=scratchPlaneNormal;normal.copy(right).multiplyByScalar(this.left).add(nearCenter).subtract(position).cross(up);planes[0].fromPointNormal(position,normal);normal.copy(right).multiplyByScalar(this.right).add(nearCenter).subtract(position).cross(up).negate();planes[1].fromPointNormal(position,normal);normal.copy(up).multiplyByScalar(this.bottom).add(nearCenter).subtract(position).cross(right).negate();planes[2].fromPointNormal(position,normal);normal.copy(up).multiplyByScalar(this.top).add(nearCenter).subtract(position).cross(right);planes[3].fromPointNormal(position,normal);normal=new Vector3$1().copy(direction);planes[4].fromPointNormal(nearCenter,normal);normal.negate();planes[5].fromPointNormal(farCenter,normal);return this._cullingVolume;}getPixelDimensions(drawingBufferWidth,drawingBufferHeight,distance,result){update$1(this);assert$4(Number.isFinite(drawingBufferWidth)&&Number.isFinite(drawingBufferHeight));assert$4(drawingBufferWidth>0);assert$4(drawingBufferHeight>0);assert$4(distance>0);assert$4(result);var inverseNear=1.0/this.near;var tanTheta=this.top*inverseNear;var pixelHeight=2.0*distance*tanTheta/drawingBufferHeight;tanTheta=this.right*inverseNear;var pixelWidth=2.0*distance*tanTheta/drawingBufferWidth;result.x=pixelWidth;result.y=pixelHeight;return result;}}function update$1(frustum){assert$4(Number.isFinite(frustum.right)&&Number.isFinite(frustum.left)&&Number.isFinite(frustum.top)&&Number.isFinite(frustum.bottom)&&Number.isFinite(frustum.near)&&Number.isFinite(frustum.far));var{top,bottom,right,left,near,far}=frustum;if(top!==frustum._top||bottom!==frustum._bottom||left!==frustum._left||right!==frustum._right||near!==frustum._near||far!==frustum._far){assert$4(frustum.near>0&&frustum.nearval!==null&&typeof val!=='undefined';class PerspectiveFrustum{constructor(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};options=_objectSpread2({near:1.0,far:500000000.0,xOffset:0.0,yOffset:0.0},options);this._offCenterFrustum=new PerspectiveOffCenterFrustum();this.fov=options.fov;this._fov=undefined;this._fovy=undefined;this._sseDenominator=undefined;this.aspectRatio=options.aspectRatio;this._aspectRatio=undefined;this.near=options.near;this._near=this.near;this.far=options.far;this._far=this.far;this.xOffset=options.xOffset;this._xOffset=this.xOffset;this.yOffset=options.yOffset;this._yOffset=this.yOffset;}clone(){return new PerspectiveFrustum({aspectRatio:this.aspectRatio,fov:this.fov,near:this.near,far:this.far});}equals(other){if(!defined$4(other)||!(other instanceof PerspectiveFrustum)){return false;}update(this);update(other);return this.fov===other.fov&&this.aspectRatio===other.aspectRatio&&this.near===other.near&&this.far===other.far&&this._offCenterFrustum.equals(other._offCenterFrustum);}get projectionMatrix(){update(this);return this._offCenterFrustum.projectionMatrix;}get infiniteProjectionMatrix(){update(this);return this._offCenterFrustum.infiniteProjectionMatrix;}get fovy(){update(this);return this._fovy;}get sseDenominator(){update(this);return this._sseDenominator;}computeCullingVolume(position,direction,up){update(this);return this._offCenterFrustum.computeCullingVolume(position,direction,up);}getPixelDimensions(drawingBufferWidth,drawingBufferHeight,distance,result){update(this);return this._offCenterFrustum.getPixelDimensions(drawingBufferWidth,drawingBufferHeight,distance,result);}}function update(frustum){assert$4(Number.isFinite(frustum.fov)&&Number.isFinite(frustum.aspectRatio)&&Number.isFinite(frustum.near)&&Number.isFinite(frustum.far));var f=frustum._offCenterFrustum;if(frustum.fov!==frustum._fov||frustum.aspectRatio!==frustum._aspectRatio||frustum.near!==frustum._near||frustum.far!==frustum._far||frustum.xOffset!==frustum._xOffset||frustum.yOffset!==frustum._yOffset){assert$4(frustum.fov>=0&&frustum.fov 0); if(frustum.aspectRatio==0){console.log(1);}assert$4(frustum.near>=0&&frustum.near0&&arguments[0]!==undefined?arguments[0]:0;_defineProperty$1(this,"_map",new Map());_defineProperty$1(this,"_array",void 0);_defineProperty$1(this,"_length",void 0);this._array=new Array(length);this._length=length;}get length(){return this._length;}set length(length){this._length=length;if(length>this._array.length){this._array.length=length;}}get values(){return this._array;}get(index){assert$7(index=0);if(index>=this.length){this.length=index+1;}if(this._map.has(this._array[index])){this._map.delete(this._array[index]);}this._array[index]=element;this._map.set(element,index);}delete(element){var index=this._map.get(element);if(index>=0){this._array.splice(index,1);this._map.delete(element);this.length--;}}peek(){return this._array[this._length-1];}push(element){if(!this._map.has(element)){var index=this.length++;this._array[index]=element;this._map.set(element,index);}}pop(){var element=this._array[--this.length];this._map.delete(element);return element;}reserve(length){assert$7(length>=0);if(length>this._array.length){this._array.length=length;}}resize(length){assert$7(length>=0);this.length=length;}trim(length){if(length===null||length===undefined){length=this.length;}this._array.length=length;}reset(){this._array=[];this._map=new Map();this._length=0;}find(target){return this._map.has(target);}}var DEFAULT_PROPS$1={loadSiblings:false,skipLevelOfDetail:false,maximumScreenSpaceError:2,updateTransforms:true,onTraversalEnd:()=>{},viewportTraversersMap:{},basePath:''};class TilesetTraverser{constructor(options){_defineProperty$1(this,"options",void 0);_defineProperty$1(this,"root",void 0);_defineProperty$1(this,"requestedTiles",void 0);_defineProperty$1(this,"selectedTiles",void 0);_defineProperty$1(this,"emptyTiles",void 0);_defineProperty$1(this,"_traversalStack",void 0);_defineProperty$1(this,"_emptyTraversalStack",void 0);_defineProperty$1(this,"_frameNumber",void 0);this.options=_objectSpread2(_objectSpread2({},DEFAULT_PROPS$1),options);this._traversalStack=new ManagedArray();this._emptyTraversalStack=new ManagedArray();this._frameNumber=null;this.root=null;this.selectedTiles={};this.requestedTiles={};this.emptyTiles={};}traverse(root,frameState,options){this.root=root;this.options=_objectSpread2(_objectSpread2({},this.options),options);this.reset();this.updateTile(root,frameState);this._frameNumber=frameState.frameNumber;this.executeTraversal(root,frameState);}reset(){this.requestedTiles={};this.selectedTiles={};this.emptyTiles={};this._traversalStack.reset();this._emptyTraversalStack.reset();}executeTraversal(root,frameState){// 遍历root var stack=this._traversalStack;root._selectionDepth=1;stack.push(root);while(stack.length>0){var tile=stack.pop();var shouldRefine=false;// !zeg改 循环遍历子tile, maxDepth用来限制可加载的最大深度 if(this.canTraverse(tile,frameState)&&(tile.depth2&&arguments[2]!==undefined?arguments[2]:false;var ignoreVisibility=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;if(!tile.hasChildren){return false;}if(tile.hasTilesetContent){return !tile.contentExpired;}if(!ignoreVisibility&&!tile.isVisibleAndInRequestVolume){return false;}return this.shouldRefine(tile,frameState,useParentMetric);}shouldLoadTile(tile){return tile.hasUnloadedContent||tile.contentExpired;}shouldSelectTile(tile){return tile.contentAvailable&&!this.options.skipLevelOfDetail;}shouldRefine(tile,frameState,useParentMetric){var screenSpaceError=tile._screenSpaceError;if(useParentMetric){screenSpaceError=tile.getScreenSpaceError(frameState,true);}return screenSpaceError>this.options.maximumScreenSpaceError;}updateTileVisibility(tile,frameState){var viewportIds=[];if(this.options.viewportTraversersMap){for(var key in this.options.viewportTraversersMap){var value=this.options.viewportTraversersMap[key];if(value===frameState.viewport.id){viewportIds.push(key);}}}else {viewportIds.push(frameState.viewport.id);}tile.updateVisibility(frameState,viewportIds);}compareDistanceToCamera(b,a){return b._distanceToCamera-a._distanceToCamera;}anyChildrenVisible(tile,frameState){var anyVisible=false;for(var child of tile.children){child.updateVisibility(frameState);anyVisible=anyVisible||child.isVisibleAndInRequestVolume;}return anyVisible;}executeEmptyTraversal(root,frameState){var allDescendantsLoaded=true;var stack=this._emptyTraversalStack;stack.push(root);while(stack.length>0&&allDescendantsLoaded){var tile=stack.pop();this.updateTile(tile,frameState);if(!tile.isVisibleAndInRequestVolume){this.loadTile(tile,frameState);}this.touchTile(tile,frameState);var traverse=!tile.hasRenderContent&&this.canTraverse(tile,frameState,false,true);if(traverse){var children=tile.children;for(var child of children){if(stack.find(child)){stack.delete(child);}stack.push(child);}}else if(!tile.contentAvailable){allDescendantsLoaded=false;}}return allDescendantsLoaded;}}var scratchVector=new Vector3$1();function defined$2(x){return x!==undefined&&x!==null;}class TileHeader{constructor(tileset,header,parentHeader){var extendedId=arguments.length>3&&arguments[3]!==undefined?arguments[3]:'';_defineProperty$1(this,"tileset",void 0);_defineProperty$1(this,"header",void 0);_defineProperty$1(this,"id",void 0);_defineProperty$1(this,"url",void 0);_defineProperty$1(this,"parent",void 0);_defineProperty$1(this,"refine",void 0);_defineProperty$1(this,"type",void 0);_defineProperty$1(this,"contentUrl",void 0);_defineProperty$1(this,"lodMetricType",void 0);_defineProperty$1(this,"lodMetricValue",void 0);_defineProperty$1(this,"boundingVolume",void 0);_defineProperty$1(this,"content",void 0);_defineProperty$1(this,"contentState",void 0);_defineProperty$1(this,"gpuMemoryUsageInBytes",void 0);_defineProperty$1(this,"children",void 0);_defineProperty$1(this,"depth",void 0);_defineProperty$1(this,"viewportIds",void 0);_defineProperty$1(this,"transform",void 0);_defineProperty$1(this,"extensions",void 0);_defineProperty$1(this,"userData",void 0);_defineProperty$1(this,"computedTransform",void 0);_defineProperty$1(this,"hasEmptyContent",void 0);_defineProperty$1(this,"hasTilesetContent",void 0);_defineProperty$1(this,"traverser",void 0);_defineProperty$1(this,"_cacheNode",void 0);_defineProperty$1(this,"_frameNumber",void 0);_defineProperty$1(this,"_lodJudge",void 0);_defineProperty$1(this,"_expireDate",void 0);_defineProperty$1(this,"_expiredContent",void 0);_defineProperty$1(this,"_shouldRefine",void 0);_defineProperty$1(this,"_distanceToCamera",void 0);_defineProperty$1(this,"_centerZDepth",void 0);_defineProperty$1(this,"_screenSpaceError",void 0);_defineProperty$1(this,"_visibilityPlaneMask",void 0);_defineProperty$1(this,"_visible",void 0);_defineProperty$1(this,"_inRequestVolume",void 0);_defineProperty$1(this,"_stackLength",void 0);_defineProperty$1(this,"_selectionDepth",void 0);_defineProperty$1(this,"_touchedFrame",void 0);_defineProperty$1(this,"_visitedFrame",void 0);_defineProperty$1(this,"_selectedFrame",void 0);_defineProperty$1(this,"_requestedFrame",void 0);_defineProperty$1(this,"_priority",void 0);_defineProperty$1(this,"_contentBoundingVolume",void 0);_defineProperty$1(this,"_viewerRequestVolume",void 0);_defineProperty$1(this,"_initialTransform",void 0);_defineProperty$1(this,"tilesetMatrix",void 0);//add _defineProperty$1(this,"tileContent",void 0);//add _defineProperty$1(this,"contentTransform",void 0);//add _defineProperty$1(this,"volumeBox",void 0);//add _defineProperty$1(this,"boundUntransformed",void 0);//add _defineProperty$1(this,"rtcCenterState",rtcCenterGlobal);//add 初始时的状态,当mesh加载完检查下 this.header=header;this.tileset=tileset;this.id=extendedId||header.id;this.url=header.url;this.parent=parentHeader;this.refine=this._getRefine(header.refine);this.type=header.type;this.contentUrl=header.contentUrl;this.lodMetricType='geometricError';this.lodMetricValue=0;this.boundingVolume=null;this.content=null;this.contentState=TILE_CONTENT_STATE.UNLOADED;this.gpuMemoryUsageInBytes=0;this.children=[];this.hasEmptyContent=false;this.hasTilesetContent=false;this.depth=0;this.viewportIds=[];this.userData={};this.extensions=null;this._priority=0;this._touchedFrame=0;this._visitedFrame=0;this._selectedFrame=0;this._requestedFrame=0;this._screenSpaceError=0;this._cacheNode=null;this._frameNumber=null;this._cacheNode=null;this.traverser=new TilesetTraverser({});this._shouldRefine=false;this._distanceToCamera=0;this._centerZDepth=0;this._visible=undefined;this._inRequestVolume=false;this._stackLength=0;this._selectionDepth=0;this._initialTransform=new Matrix4$1();this.transform=new Matrix4$1();this._initializeLodMetric(header);this._initializeTransforms(header);this._initializeBoundingVolumes(header);this._initializeContent(header);this._initializeRenderingState(header);this._lodJudge=null;this._expireDate=null;this._expiredContent=null;Object.seal(this);}destroy(){this.header=null;}isDestroyed(){return this.header===null;}get selected(){return this._selectedFrame===this.tileset._frameNumber;}get isVisible(){return this._visible;}get isVisibleAndInRequestVolume(){var v=/* this._visible && */this.tileset.visible&&this._inRequestVolume;//用_updateBoundingVolume这个算的在相机靠近时不准确,容易缺块 if(window.tileVisi2)v=this._visible&&v;return v;}get hasRenderContent(){return !this.hasEmptyContent&&!this.hasTilesetContent;}get hasChildren(){return this.children.length>0||this.header.children&&this.header.children.length>0;}get contentReady(){return this.contentState===TILE_CONTENT_STATE.READY||this.hasEmptyContent;}get contentAvailable(){return Boolean(this.contentReady&&this.hasRenderContent||this._expiredContent&&!this.contentFailed);}get hasUnloadedContent(){return this.hasRenderContent&&this.contentUnloaded;}get contentUnloaded(){return this.contentState===TILE_CONTENT_STATE.UNLOADED;}get contentExpired(){return this.contentState===TILE_CONTENT_STATE.EXPIRED;}get contentFailed(){return this.contentState===TILE_CONTENT_STATE.FAILED;}getScreenSpaceError(frameState,useParentLodMetric){switch(this.tileset.type){case TILESET_TYPE.I3S:return getProjectedRadius(this,frameState);case TILESET_TYPE.TILES3D:return getTiles3DScreenSpaceError(this,frameState,useParentLodMetric);default:throw new Error('Unsupported tileset type');}}_getPriority(){var traverser=this.tileset._traverser;var{skipLevelOfDetail}=traverser.options;var maySkipTile=this.refine===TILE_REFINEMENT.ADD||skipLevelOfDetail;if(maySkipTile&&!this.isVisible&&this._visible!==undefined){return -1;}if(this.tileset._frameNumber-this._touchedFrame>=1){return -1;}if(this.contentState===TILE_CONTENT_STATE.UNLOADED){return -1;}var parent=this.parent;var useParentScreenSpaceError=parent&&(!maySkipTile||this._screenSpaceError===0.0||parent.hasTilesetContent);var screenSpaceError=useParentScreenSpaceError?parent._screenSpaceError:this._screenSpaceError;var rootScreenSpaceError=traverser.root?traverser.root._screenSpaceError:0.0;var v=Math.max(rootScreenSpaceError-screenSpaceError,0);if(!this._visible){v=THREE.Math.clamp(v*0.1,-0.9,100);//xzw add 因为this._visible我也令其显示所以这里降低这些的优先级 }return v;}async loadContent(){if(this.hasEmptyContent){return false;}if(this.content){return true;}var expired=this.contentExpired;if(expired){this._expireDate=null;}this.contentState=TILE_CONTENT_STATE.LOADING;var requestToken=await this.tileset._requestScheduler.scheduleRequest(this.id,this._getPriority.bind(this));if(!requestToken){this.contentState=TILE_CONTENT_STATE.UNLOADED;return false;}try{var contentUrl=this.tileset.getTileUrl(this.contentUrl)+"?_=".concat(this.tileset.options.updateTime);// !zeg改 添加version后缀 原:imageVersion var loader=this.tileset.loader;var options=_objectSpread2(_objectSpread2({},this.tileset.loadOptions),{},{[loader.id]:_objectSpread2(_objectSpread2({},this.tileset.loadOptions[loader.id]),{},{isTileset:this.type==='json'},this._getLoaderSpecificOptions(loader.id))});this.content=await load(contentUrl,loader,options);// !zeg改 if(/* this.tileset.options. */maxDepth1 this.unloadContent();return false;}if(this.tileset.options.contentLoader){await this.tileset.options.contentLoader(this);}if(this._isTileset()){this.tileset._initializeTileHeaders(this.content,this);}this.contentState=TILE_CONTENT_STATE.READY;this._onContentLoaded();return true;}catch(error){this.contentState=TILE_CONTENT_STATE.FAILED;throw error;}finally{requestToken.done();}}unloadContent(){if(this.content&&this.content.destroy){this.content.destroy();}this.content=null;if(this.header.content&&this.header.content.destroy){this.header.content.destroy();}this.header.content=null;this.contentState=TILE_CONTENT_STATE.UNLOADED;return true;}updateVisibility(frameState,viewportIds){if(this._frameNumber===frameState.frameNumber){return;}var parent=this.parent;var parentVisibilityPlaneMask=parent?parent._visibilityPlaneMask:CullingVolume.MASK_INDETERMINATE;if(this.tileset._traverser.options.updateTransforms){var parentTransform=parent?parent.computedTransform:new Matrix4$1().elements;//this.tileset.modelMatrix; 改:去掉左乘modelMatrix this._updateTransform(parentTransform);}this._distanceToCamera=this.distanceToTile(frameState);this._screenSpaceError=this.getScreenSpaceError(frameState,false);this._visibilityPlaneMask=this.visibility(frameState,parentVisibilityPlaneMask);this._visible=this._visibilityPlaneMask!==CullingVolume.MASK_OUTSIDE;this._inRequestVolume=this.insideViewerRequestVolume(frameState);this._frameNumber=frameState.frameNumber;this.viewportIds=viewportIds;}visibility(frameState,parentVisibilityPlaneMask){var{cullingVolume}=frameState;var{boundingVolume}=this;return cullingVolume.computeVisibilityWithPlaneMask(boundingVolume,parentVisibilityPlaneMask);}contentVisibility(){return true;}distanceToTile(frameState){var boundingVolume=this.boundingVolume;return Math.sqrt(Math.max(boundingVolume.distanceSquaredTo(frameState.camera.position),0));}cameraSpaceZDepth(_ref11){var{camera}=_ref11;var boundingVolume=this.boundingVolume;scratchVector.subVectors(boundingVolume.center,camera.position);return camera.direction.dot(scratchVector);}insideViewerRequestVolume(frameState){var viewerRequestVolume=this._viewerRequestVolume;return !viewerRequestVolume||viewerRequestVolume.distanceSquaredTo(frameState.camera.position)<=0;}updateExpiration(){if(defined$2(this._expireDate)&&this.contentReady&&!this.hasEmptyContent){var now=Date.now();if(Date.lessThan(this._expireDate,now)){this.contentState=TILE_CONTENT_STATE.EXPIRED;this._expiredContent=this.content;}}}get extras(){return this.header.extras;}_initializeLodMetric(header){if('lodMetricType'in header){this.lodMetricType=header.lodMetricType;}else {this.lodMetricType=this.parent&&this.parent.lodMetricType||this.tileset.lodMetricType;console.warn("3D Tile: Required prop lodMetricType is undefined. Using parent lodMetricType");}if('lodMetricValue'in header){this.lodMetricValue=header.lodMetricValue;}else {this.lodMetricValue=this.parent&&this.parent.lodMetricValue||this.tileset.lodMetricValue;console.warn('3D Tile: Required prop lodMetricValue is undefined. Using parent lodMetricValue');}}_initializeTransforms(tileHeader){this.transform=tileHeader.transform?new Matrix4$1(tileHeader.transform):new Matrix4$1();var parent=this.parent;var tileset=this.tileset;var parentTransform=parent&&parent.computedTransform?parent.computedTransform.clone():new Matrix4$1().elements;// tileset.modelMatrix.clone(); 改:去掉左乘modelMatrix this.computedTransform=new Matrix4$1(parentTransform).multiplyRight(this.transform);var parentInitialTransform=parent&&parent._initialTransform?parent._initialTransform.clone():new Matrix4$1();this._initialTransform=new Matrix4$1(parentInitialTransform).multiplyRight(this.transform);}_initializeBoundingVolumes(tileHeader){this._contentBoundingVolume=null;this._viewerRequestVolume=null;this._updateBoundingVolume(tileHeader);}_initializeContent(tileHeader){this.content={_tileset:this.tileset,_tile:this};this.hasEmptyContent=true;this.contentState=TILE_CONTENT_STATE.UNLOADED;this.hasTilesetContent=false;if(tileHeader.contentUrl){this.content=null;this.hasEmptyContent=false;}}_initializeRenderingState(header){this.depth=header.level||(this.parent?this.parent.depth+1:0);this._shouldRefine=false;this._distanceToCamera=0;this._centerZDepth=0;this._screenSpaceError=0;this._visibilityPlaneMask=CullingVolume.MASK_INDETERMINATE;this._visible=undefined;this._inRequestVolume=false;this._stackLength=0;this._selectionDepth=0;this._frameNumber=0;this._touchedFrame=0;this._visitedFrame=0;this._selectedFrame=0;this._requestedFrame=0;this._priority=0.0;}_getRefine(refine){return refine||this.parent&&this.parent.refine||TILE_REFINEMENT.REPLACE;}_isTileset(){return this.contentUrl.indexOf('.json')!==-1;}_onContentLoaded(){switch(this.content&&this.content.type){case'vctr':case'geom':this.tileset._traverser.disableSkipLevelOfDetail=true;break;}if(this._isTileset()){this.hasTilesetContent=true;}}_updateBoundingVolume(header){var computedTransform;/* if(header.id == 'root_0' || !header.id){ console.log('root_0') } */if(!this.tileset.lastRootTransform){//没事过后会因_updateTransform重算 computedTransform=new Matrix4$1(this.tileset.modelMatrix).multiplyRight(this.computedTransform);//add }else {computedTransform=new Matrix4$1(new Matrix4().multiplyMatrices(this.tileset.lastRootTransform,this.getContentTransform()).elements);}this.boundingVolume=createBoundingVolume(header.boundingVolume,computedTransform/* this.computedTransform */,this.boundingVolume);var content=header.content;if(!content){return;}if(content.boundingVolume){this._contentBoundingVolume=createBoundingVolume(content.boundingVolume,computedTransform,this._contentBoundingVolume);}if(header.viewerRequestVolume){this._viewerRequestVolume=createBoundingVolume(header.viewerRequestVolume,computedTransform,this._viewerRequestVolume);}}getBoundUntransformed(){//add 这个会在mesh加载好后才会执行 if(!this.contentTransform){console.error('?');}this.getContentTransform();var computedTransform2=new Matrix4$1(this.contentTransform.elements);this.boundUntransformed=createBoundingVolume(this.header.boundingVolume,computedTransform2,this.boundUntransformed);//add return this.boundUntransformed;}getContentTransform(force){//add 获取该tile在创建boundingVolume时需要的matrix,不包含最外层对整体模型的变换. var rtcCenter,contentTransform;if(this.contentTransform&&!force){//无需更新 return this.contentTransform.clone();}if(!this.tileset.tileTransInvert){this.tileset.tileTransInvert=new Matrix4$1();}this.contentTransform=new Matrix4().fromArray(this.computedTransform).premultiply(new Matrix4().fromArray(this.tileset.tileTransInvert));if(this.tileContent){rtcCenter=this.content.rtcCenter;}else {rtcCenter=this.rtcCenterState;}if(!rtcCenter){var tranM=new Matrix4();tranM.makeScale(1,1,-1);//大部分是这种情况. 就是因为这个变换才加的这个函数,之前bounding没考虑这个不准。不知道为什么原生的代码不用scaleZ this.contentTransform.premultiply(tranM);}//如果有rtcCenter的话一开始boundingVolume不准?会不会有显示问题? return this.contentTransform.clone();}_updateTransform(){var parentTransform=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new Matrix4$1();var computedTransform=parentTransform.clone().multiplyRight(this.transform);var didTransformChange=!computedTransform.equals(this.computedTransform)||!this.tilesetMatrix||!this.tilesetMatrix.equals(this.tileset.modelMatrix);//改 后面加了两个判断,为了在模型移动后更新_updateBoundingVolume if(!didTransformChange){return;}this.tileset.modelMatrix;this.computedTransform=computedTransform;this.tilesetMatrix=this.tileset.modelMatrix;//add 标记 this._updateBoundingVolume(this.header);}_getLoaderSpecificOptions(loaderId){switch(loaderId){case'i3s':return _objectSpread2(_objectSpread2({},this.tileset.options.i3s),{},{tile:this.header,tileset:this.tileset.tileset,isTileHeader:false});case'3d-tiles':case'cesium-ion':default:return get3dTilesOptions(this.tileset.tileset);}}}class Tileset3DTraverser extends TilesetTraverser{compareDistanceToCamera(a,b){return b._distanceToCamera===0&&a._distanceToCamera===0?b._centerZDepth-a._centerZDepth:b._distanceToCamera-a._distanceToCamera;}updateTileVisibility(tile,frameState){super.updateTileVisibility(tile,frameState);if(!tile.isVisibleAndInRequestVolume){return;}var hasChildren=tile.children.length>0;if(tile.hasTilesetContent&&hasChildren){var firstChild=tile.children[0];this.updateTileVisibility(firstChild,frameState);tile._visible=firstChild._visible;return;}if(this.meetsScreenSpaceErrorEarly(tile,frameState)){tile._visible=false;return;}var replace=tile.refine===TILE_REFINEMENT.REPLACE;var useOptimization=tile._optimChildrenWithinParent===TILE3D_OPTIMIZATION_HINT.USE_OPTIMIZATION;if(replace&&useOptimization&&hasChildren){if(!this.anyChildrenVisible(tile,frameState)){tile._visible=false;return;}}}meetsScreenSpaceErrorEarly(tile,frameState){var{parent}=tile;if(!parent||parent.hasTilesetContent||parent.refine!==TILE_REFINEMENT.ADD){return false;}return !this.shouldRefine(tile,frameState,true);}}var STATUS={REQUESTED:'REQUESTED',COMPLETED:'COMPLETED',ERROR:'ERROR'};class I3STileManager{constructor(){_defineProperty$1(this,"_statusMap",void 0);this._statusMap={};}add(request,key,callback,frameState){if(!this._statusMap[key]){this._statusMap[key]={request,callback,key,frameState,status:STATUS.REQUESTED};request().then(data=>{this._statusMap[key].status=STATUS.COMPLETED;this._statusMap[key].callback(data,frameState);}).catch(error=>{this._statusMap[key].status=STATUS.ERROR;callback(error);});}}update(key,frameState){if(this._statusMap[key]){this._statusMap[key].frameState=frameState;}}find(key){return this._statusMap[key];}}class I3STilesetTraverser extends TilesetTraverser{constructor(options){super(options);_defineProperty$1(this,"_tileManager",void 0);this._tileManager=new I3STileManager();}shouldRefine(tile,frameState){tile._lodJudge=getLodStatus(tile,frameState);return tile._lodJudge==='DIG';}updateChildTiles(tile,frameState){var _this=this;var children=tile.header.children||[];var childTiles=tile.children;var tileset=tile.tileset;var _loop2=function _loop2(child){var extendedId="".concat(child.id,"-").concat(frameState.viewport.id);var childTile=childTiles&&childTiles.find(t=>t.id===extendedId);if(!childTile){var request=()=>_this._loadTile(child.id,tileset);var cachedRequest=_this._tileManager.find(extendedId);if(!cachedRequest){if(tileset.tileset.nodePages){request=()=>tileset.tileset.nodePagesTile.formTileFromNodePages(child.id);}_this._tileManager.add(request,extendedId,header=>_this._onTileLoad(header,tile,extendedId),frameState);}else {_this._tileManager.update(extendedId,frameState);}}else if(childTile){_this.updateTile(childTile,frameState);}};for(var child of children){_loop2(child);}return false;}async _loadTile(nodeId,tileset){var{loader}=tileset;var nodeUrl=tileset.getTileUrl("".concat(tileset.url,"/nodes/").concat(nodeId));var options=_objectSpread2(_objectSpread2({},tileset.loadOptions),{},{i3s:_objectSpread2(_objectSpread2({},tileset.loadOptions.i3s),{},{isTileHeader:true,loadContent:false})});return await load(nodeUrl,loader,options);}_onTileLoad(header,tile,extendedId){var childTile=new TileHeader(tile.tileset,header,tile,extendedId);tile.children.push(childTile);var frameState=this._tileManager.find(childTile.id).frameState;this.updateTile(childTile,frameState);if(this._frameNumber===frameState.frameNumber){this.executeTraversal(childTile,frameState);}}}var DEFAULT_PROPS={description:'',ellipsoid:Ellipsoid.WGS84,modelMatrix:new Matrix4$1(),throttleRequests:true,maxRequests:64,maximumMemoryUsage:32,onTileLoad:()=>{},onTileUnload:()=>{},onTileError:()=>{},onTraversalComplete:selectedTiles=>selectedTiles,contentLoader:undefined,viewDistanceScale:1.0,maximumScreenSpaceError:8,loadTiles:true,updateTransforms:true,viewportTraversersMap:null,loadOptions:{fetch:{}},attributions:[],basePath:'',i3s:{}};var TILES_TOTAL='Tiles In Tileset(s)';var TILES_IN_MEMORY='Tiles In Memory';var TILES_IN_VIEW='Tiles In View';var TILES_RENDERABLE='Tiles To Render';var TILES_LOADED='Tiles Loaded';var TILES_LOADING='Tiles Loading';var TILES_UNLOADED='Tiles Unloaded';var TILES_LOAD_FAILED='Failed Tile Loads';var POINTS_COUNT='Points';var TILES_GPU_MEMORY='Tile Memory Use';var tilesetSid=0;//add class Tileset3D extends EventDispatcher{//xzw add EventDispatcher constructor(json,options){super();viewer.visiVertexCount=viewer.visiVertexCount||0;_defineProperty$1(this,"options",void 0);_defineProperty$1(this,"loadOptions",void 0);_defineProperty$1(this,"type",void 0);_defineProperty$1(this,"tileset",void 0);_defineProperty$1(this,"loader",void 0);_defineProperty$1(this,"url",void 0);_defineProperty$1(this,"basePath",void 0);_defineProperty$1(this,"modelMatrix",void 0);_defineProperty$1(this,"ellipsoid",void 0);_defineProperty$1(this,"lodMetricType",void 0);_defineProperty$1(this,"lodMetricValue",void 0);_defineProperty$1(this,"refine",void 0);_defineProperty$1(this,"root",void 0);_defineProperty$1(this,"roots",void 0);_defineProperty$1(this,"asset",void 0);_defineProperty$1(this,"description",void 0);_defineProperty$1(this,"properties",void 0);_defineProperty$1(this,"extras",void 0);_defineProperty$1(this,"attributions",void 0);_defineProperty$1(this,"credits",void 0);_defineProperty$1(this,"stats",void 0);_defineProperty$1(this,"traverseCounter",void 0);_defineProperty$1(this,"geometricError",void 0);_defineProperty$1(this,"selectedTiles",void 0);_defineProperty$1(this,"cartographicCenter",void 0);_defineProperty$1(this,"cartesianCenter",void 0);_defineProperty$1(this,"zoom",void 0);_defineProperty$1(this,"boundingVolume",void 0);_defineProperty$1(this,"gpuMemoryUsageInBytes",void 0);_defineProperty$1(this,"dynamicScreenSpaceErrorComputedDensity",void 0);_defineProperty$1(this,"_traverser",void 0);_defineProperty$1(this,"_cache",void 0);_defineProperty$1(this,"_requestScheduler",void 0);_defineProperty$1(this,"_frameNumber",void 0);_defineProperty$1(this,"_queryParamsString",void 0);_defineProperty$1(this,"_queryParams",void 0);_defineProperty$1(this,"_extensionsUsed",void 0);_defineProperty$1(this,"_tiles",void 0);_defineProperty$1(this,"_pendingCount",void 0);_defineProperty$1(this,"lastUpdatedVieports",void 0);_defineProperty$1(this,"_requestedTiles",void 0);_defineProperty$1(this,"_emptyTiles",void 0);_defineProperty$1(this,"frameStateData",void 0);_defineProperty$1(this,"maximumMemoryUsage",void 0);_defineProperty$1(this,"visible",true);//add assert$7(json);this.options=_objectSpread2(_objectSpread2({},DEFAULT_PROPS),options);this.tileset=json;this.loader=json.loader;this.type=json.type;this.url=json.url;this.basePath=json.basePath||dirname(this.url);this.modelMatrix=this.options.modelMatrix;this.ellipsoid=this.options.ellipsoid;this.lodMetricType=json.lodMetricType;this.lodMetricValue=json.lodMetricValue;this.refine=json.root.refine;this.loadOptions=this.options.loadOptions||{};this.root=null;this.roots={};this.cartographicCenter=null;this.cartesianCenter=null;this.zoom=1;this.boundingVolume=null;this.traverseCounter=0;this.geometricError=0;this._traverser=this._initializeTraverser();this._cache=new TilesetCache();this._requestScheduler=new RequestScheduler({throttleRequests:this.options.throttleRequests,maxRequests:this.options.maxRequests});this._frameNumber=0;this._pendingCount=0;this._tiles={};this.selectedTiles=[];this._emptyTiles=[];this._requestedTiles=[];this.frameStateData={};this.lastUpdatedVieports=null;this._queryParams={};this._queryParamsString='';this.maximumMemoryUsage=this.options.maximumMemoryUsage||32;this.gpuMemoryUsageInBytes=0;this.stats=new Stats$1({id:this.url});this._initializeStats();this._extensionsUsed=undefined;this.dynamicScreenSpaceErrorComputedDensity=0.0;this.extras=null;this.asset={};this.credits={};this.description=this.options.description||'';this._initializeTileSet(json);}destroy(){this._destroy();}isLoaded(){return this._pendingCount===0&&this._frameNumber!==0;}get tiles(){return Object.values(this._tiles);}get frameNumber(){return this._frameNumber;}get queryParams(){if(!this._queryParamsString){this._queryParamsString=getQueryParamString(this._queryParams);}return this._queryParamsString;}setProps(props){this.options=_objectSpread2(_objectSpread2({},this.options),props);}setOptions(options){this.options=_objectSpread2(_objectSpread2({},this.options),options);}getTileUrl(tilePath){var isDataUrl=tilePath.startsWith('data:');tilePath=Potree.Common.dealURL(tilePath);//add 去除'+' if(isDataUrl){return tilePath;}return "".concat(tilePath).concat(this.queryParams);}hasExtension(extensionName){return Boolean(this._extensionsUsed&&this._extensionsUsed.indexOf(extensionName)>-1);}update(viewports){if('loadTiles'in this.options&&!this.options.loadTiles){return;}if(this.traverseCounter>0){return;}if(!viewports&&this.lastUpdatedVieports){viewports=this.lastUpdatedVieports;}else {this.lastUpdatedVieports=viewports;}if(!(viewports instanceof Array)){viewports=[viewports];}this._cache.reset();this._frameNumber++;this.traverseCounter=viewports.length;var viewportsToTraverse=[];for(var viewport of viewports){var id=viewport.id;if(this._needTraverse(id)){viewportsToTraverse.push(id);}else {this.traverseCounter--;}}for(var _viewport of viewports){var _id=_viewport.id;if(!this.roots[_id]){this.roots[_id]=this._initializeTileHeaders(this.tileset,null);}if(!viewportsToTraverse.includes(_id)){continue;}var frameState=getFrameState(_viewport,this._frameNumber);this._traverser.traverse(this.roots[_id],frameState,this.options);}}_needTraverse(viewportId){var traverserId=viewportId;if(this.options.viewportTraversersMap){traverserId=this.options.viewportTraversersMap[viewportId];}if(traverserId!==viewportId){return false;}return true;}_onTraversalEnd(frameState){var id=frameState.viewport.id;if(!this.frameStateData[id]){this.frameStateData[id]={selectedTiles:[],_requestedTiles:[],_emptyTiles:[]};}var currentFrameStateData=this.frameStateData[id];var selectedTiles=Object.values(this._traverser.selectedTiles);currentFrameStateData.selectedTiles=selectedTiles;currentFrameStateData._requestedTiles=Object.values(this._traverser.requestedTiles);currentFrameStateData._emptyTiles=Object.values(this._traverser.emptyTiles);this.traverseCounter--;if(this.traverseCounter>0){return;}this._updateTiles();}_updateTiles(){this.selectedTiles=[];this._requestedTiles=[];this._emptyTiles=[];for(var frameStateKey in this.frameStateData){var frameStateDataValue=this.frameStateData[frameStateKey];this.selectedTiles=this.selectedTiles.concat(frameStateDataValue.selectedTiles);this._requestedTiles=this._requestedTiles.concat(frameStateDataValue._requestedTiles);this._emptyTiles=this._emptyTiles.concat(frameStateDataValue._emptyTiles);}this.selectedTiles=this.options.onTraversalComplete(this.selectedTiles);for(var tile of this.selectedTiles){this._tiles[tile.id]=tile;}this._loadTiles();this._unloadTiles();this._updateStats();}_tilesChanged(oldSelectedTiles,selectedTiles){if(oldSelectedTiles.length!==selectedTiles.length){return true;}var set1=new Set(oldSelectedTiles.map(t=>t.id));var set2=new Set(selectedTiles.map(t=>t.id));var changed=oldSelectedTiles.filter(x=>!set2.has(x.id)).length>0;changed=changed||selectedTiles.filter(x=>!set1.has(x.id)).length>0;return changed;}_loadTiles(){for(var tile of this._requestedTiles){if(tile.contentUnloaded){this._loadTile(tile);}}}_unloadTiles(){this._cache.unloadTiles(this,(tileset,tile)=>tileset._unloadTile(tile));}_updateStats(){var tilesRenderable=0;var pointsRenderable=0;for(var tile of this.selectedTiles){if(tile.contentAvailable&&tile.content){tilesRenderable++;if(tile.content.pointCount){pointsRenderable+=tile.content.pointCount;}}}this.stats.get(TILES_IN_VIEW).count=this.selectedTiles.length;this.stats.get(TILES_RENDERABLE).count=tilesRenderable;this.stats.get(POINTS_COUNT).count=pointsRenderable;}_initializeTileSet(tilesetJson){this.root=this._initializeTileHeaders(tilesetJson,null);if(this.type===TILESET_TYPE.TILES3D){this._initializeCesiumTileset(tilesetJson);}if(this.type===TILESET_TYPE.I3S){this._initializeI3STileset();}this._calculateViewProps();}_calculateViewProps(){var root=this.root;assert$7(root);var{center}=root.boundingVolume;if(!center){console.warn('center was not pre-calculated for the root tile');this.cartographicCenter=new Vector3$1();this.zoom=1;return;}this.cartographicCenter=Ellipsoid.WGS84.cartesianToCartographic(center,new Vector3$1());this.cartesianCenter=center;this.zoom=getZoomFromBoundingVolume(root.boundingVolume);}_initializeStats(){this.stats.get(TILES_TOTAL);this.stats.get(TILES_LOADING);this.stats.get(TILES_IN_MEMORY);this.stats.get(TILES_IN_VIEW);this.stats.get(TILES_RENDERABLE);this.stats.get(TILES_LOADED);this.stats.get(TILES_UNLOADED);this.stats.get(TILES_LOAD_FAILED);this.stats.get(POINTS_COUNT,'memory');this.stats.get(TILES_GPU_MEMORY,'memory');}_initializeTileHeaders(tilesetJson,parentTileHeader){var rootTile=new TileHeader(this,tilesetJson.root,parentTileHeader,parentTileHeader==void 0&&'root_'+tilesetSid++);if(parentTileHeader){parentTileHeader.children.push(rootTile);rootTile.depth=parentTileHeader.depth+1;}if(this.type===TILESET_TYPE.TILES3D){var _stack=[];_stack.push(rootTile);while(_stack.length>0){var tile=_stack.pop();this.stats.get(TILES_TOTAL).incrementCount();var children=tile.header.children||[];// !zeg改 if(tile.depthtileset._updateCacheStats(tile));}_updateCacheStats(tile){this.stats.get(TILES_LOADED).incrementCount();this.stats.get(TILES_IN_MEMORY).incrementCount();this.gpuMemoryUsageInBytes+=tile.content.byteLength||0;this.stats.get(TILES_GPU_MEMORY).count=this.gpuMemoryUsageInBytes;}_unloadTile(tile){this.gpuMemoryUsageInBytes-=tile.content&&tile.content.byteLength||0;this.stats.get(TILES_IN_MEMORY).decrementCount();this.stats.get(TILES_UNLOADED).incrementCount();this.stats.get(TILES_GPU_MEMORY).count=this.gpuMemoryUsageInBytes;this.options.onTileUnload(tile);tile.unloadContent();}_destroy(){var stack=[];if(this.root){stack.push(this.root);}while(stack.length>0){var tile=stack.pop();for(var child of tile.children){stack.push(child);}this._destroyTile(tile);}this.root=null;}_destroySubtree(tile){var root=tile;var stack=[];stack.push(root);while(stack.length>0){tile=stack.pop();for(var child of tile.children){stack.push(child);}if(tile!==root){this._destroyTile(tile);}}root.children=[];}_destroyTile(tile){this._cache.unloadTile(this,tile);this._unloadTile(tile);tile.destroy();}_initializeCesiumTileset(tilesetJson){this.asset=tilesetJson.asset;if(!this.asset){throw new Error('Tileset must have an asset property.');}if(this.asset.version!=='0.0'&&this.asset.version!=='1.0'){throw new Error('The tileset must be 3D Tiles version 0.0 or 1.0.');}if('tilesetVersion'in this.asset){this._queryParams.v=this.asset.tilesetVersion;}this.credits={attributions:this.options.attributions||[]};this.description=this.options.description||'';this.properties=tilesetJson.properties;this.geometricError=tilesetJson.geometricError;this._extensionsUsed=tilesetJson.extensionsUsed;this.extras=tilesetJson.extras;}_initializeI3STileset(){if(this.loadOptions.i3s&&'token'in this.loadOptions.i3s){this._queryParams.token=this.loadOptions.i3s.token;}}}function getQueryParamString(queryParams){var queryParamStrings=[];for(var key of Object.keys(queryParams)){queryParamStrings.push("".concat(key,"=").concat(queryParams[key]));}switch(queryParamStrings.length){case 0:return '';case 1:return "?".concat(queryParamStrings[0]);default:return "?".concat(queryParamStrings.join('&'));}}var VERSION$5="3.1.4";var TILE3D_TYPE={COMPOSITE:'cmpt',POINT_CLOUD:'pnts',BATCHED_3D_MODEL:'b3dm',INSTANCED_3D_MODEL:'i3dm',GEOMETRY:'geom',VECTOR:'vect',GLTF:'glTF'};function getStringFromArrayBuffer(arrayBuffer,byteOffset,byteLength){assert$7(arrayBuffer instanceof ArrayBuffer);var textDecoder=new TextDecoder('utf8');var typedArray=new Uint8Array(arrayBuffer,byteOffset,byteLength);var string=textDecoder.decode(typedArray);return string;}function getMagicString$1(arrayBuffer){var byteOffset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var dataView=new DataView(arrayBuffer);return "".concat(String.fromCharCode(dataView.getUint8(byteOffset+0))).concat(String.fromCharCode(dataView.getUint8(byteOffset+1))).concat(String.fromCharCode(dataView.getUint8(byteOffset+2))).concat(String.fromCharCode(dataView.getUint8(byteOffset+3)));}var VERSION$4="3.1.4";var DEFAULT_DRACO_OPTIONS={draco:{decoderType:typeof WebAssembly==='object'?'wasm':'js',libraryPath:'libs/',extraAttributes:{},attributeNameEntry:undefined}};var DracoLoader$1={name:'Draco',id:'draco',module:'draco',shapes:['mesh'],version:VERSION$4,worker:true,extensions:['drc'],mimeTypes:['application/octet-stream'],binary:true,tests:['DRACO'],options:DEFAULT_DRACO_OPTIONS};function getMeshBoundingBox(attributes){var minX=Infinity;var minY=Infinity;var minZ=Infinity;var maxX=-Infinity;var maxY=-Infinity;var maxZ=-Infinity;var positions=attributes.POSITION?attributes.POSITION.value:[];var len=positions&&positions.length;for(var _i37=0;_i37maxX?x:maxX;maxY=y>maxY?y:maxY;maxZ=z>maxZ?z:maxZ;}return [[minX,minY,minZ],[maxX,maxY,maxZ]];}function assert$3(condition,message){if(!condition){throw new Error(message||'loader assertion failed.');}}class Schema{constructor(fields,metadata){_defineProperty$1(this,"fields",void 0);_defineProperty$1(this,"metadata",void 0);assert$3(Array.isArray(fields));checkNames(fields);this.fields=fields;this.metadata=metadata||new Map();}compareTo(other){if(this.metadata!==other.metadata){return false;}if(this.fields.length!==other.fields.length){return false;}for(var _i38=0;_i38nameMap[field.name]);return new Schema(selectedFields,this.metadata);}selectAt(){for(var _len12=arguments.length,columnIndices=new Array(_len12),_key12=0;_key12<_len12;_key12++){columnIndices[_key12]=arguments[_key12];}var selectedFields=columnIndices.map(index=>this.fields[index]).filter(Boolean);return new Schema(selectedFields,this.metadata);}assign(schemaOrFields){var fields;var metadata=this.metadata;if(schemaOrFields instanceof Schema){var otherSchema=schemaOrFields;fields=otherSchema.fields;metadata=mergeMaps(mergeMaps(new Map(),this.metadata),otherSchema.metadata);}else {fields=schemaOrFields;}var fieldMap=Object.create(null);for(var field of this.fields){fieldMap[field.name]=field;}for(var _field of fields){fieldMap[_field.name]=_field;}var mergedFields=Object.values(fieldMap);return new Schema(mergedFields,metadata);}}function checkNames(fields){var usedNames={};for(var field of fields){if(usedNames[field.name]){console.warn('Schema: duplicated field name',field.name,field);}usedNames[field.name]=true;}}function mergeMaps(m1,m2){return new Map([...(m1||new Map()),...(m2||new Map())]);}class Field{constructor(name,type){var nullable=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var metadata=arguments.length>3&&arguments[3]!==undefined?arguments[3]:new Map();_defineProperty$1(this,"name",void 0);_defineProperty$1(this,"type",void 0);_defineProperty$1(this,"nullable",void 0);_defineProperty$1(this,"metadata",void 0);this.name=name;this.type=type;this.nullable=nullable;this.metadata=metadata;}get typeId(){return this.type&&this.type.typeId;}clone(){return new Field(this.name,this.type,this.nullable,this.metadata);}compareTo(other){return this.name===other.name&&this.type===other.type&&this.nullable===other.nullable&&this.metadata===other.metadata;}toString(){return "".concat(this.type).concat(this.nullable?', nullable':'').concat(this.metadata?", metadata: ".concat(this.metadata):'');}}var Type;(function(Type){Type[Type["NONE"]=0]="NONE";Type[Type["Null"]=1]="Null";Type[Type["Int"]=2]="Int";Type[Type["Float"]=3]="Float";Type[Type["Binary"]=4]="Binary";Type[Type["Utf8"]=5]="Utf8";Type[Type["Bool"]=6]="Bool";Type[Type["Decimal"]=7]="Decimal";Type[Type["Date"]=8]="Date";Type[Type["Time"]=9]="Time";Type[Type["Timestamp"]=10]="Timestamp";Type[Type["Interval"]=11]="Interval";Type[Type["List"]=12]="List";Type[Type["Struct"]=13]="Struct";Type[Type["Union"]=14]="Union";Type[Type["FixedSizeBinary"]=15]="FixedSizeBinary";Type[Type["FixedSizeList"]=16]="FixedSizeList";Type[Type["Map"]=17]="Map";Type[Type["Dictionary"]=-1]="Dictionary";Type[Type["Int8"]=-2]="Int8";Type[Type["Int16"]=-3]="Int16";Type[Type["Int32"]=-4]="Int32";Type[Type["Int64"]=-5]="Int64";Type[Type["Uint8"]=-6]="Uint8";Type[Type["Uint16"]=-7]="Uint16";Type[Type["Uint32"]=-8]="Uint32";Type[Type["Uint64"]=-9]="Uint64";Type[Type["Float16"]=-10]="Float16";Type[Type["Float32"]=-11]="Float32";Type[Type["Float64"]=-12]="Float64";Type[Type["DateDay"]=-13]="DateDay";Type[Type["DateMillisecond"]=-14]="DateMillisecond";Type[Type["TimestampSecond"]=-15]="TimestampSecond";Type[Type["TimestampMillisecond"]=-16]="TimestampMillisecond";Type[Type["TimestampMicrosecond"]=-17]="TimestampMicrosecond";Type[Type["TimestampNanosecond"]=-18]="TimestampNanosecond";Type[Type["TimeSecond"]=-19]="TimeSecond";Type[Type["TimeMillisecond"]=-20]="TimeMillisecond";Type[Type["TimeMicrosecond"]=-21]="TimeMicrosecond";Type[Type["TimeNanosecond"]=-22]="TimeNanosecond";Type[Type["DenseUnion"]=-23]="DenseUnion";Type[Type["SparseUnion"]=-24]="SparseUnion";Type[Type["IntervalDayTime"]=-25]="IntervalDayTime";Type[Type["IntervalYearMonth"]=-26]="IntervalYearMonth";})(Type||(Type={}));var _Symbol$toStringTag,_Symbol$toStringTag2,_Symbol$toStringTag7;class DataType{static isNull(x){return x&&x.typeId===Type.Null;}static isInt(x){return x&&x.typeId===Type.Int;}static isFloat(x){return x&&x.typeId===Type.Float;}static isBinary(x){return x&&x.typeId===Type.Binary;}static isUtf8(x){return x&&x.typeId===Type.Utf8;}static isBool(x){return x&&x.typeId===Type.Bool;}static isDecimal(x){return x&&x.typeId===Type.Decimal;}static isDate(x){return x&&x.typeId===Type.Date;}static isTime(x){return x&&x.typeId===Type.Time;}static isTimestamp(x){return x&&x.typeId===Type.Timestamp;}static isInterval(x){return x&&x.typeId===Type.Interval;}static isList(x){return x&&x.typeId===Type.List;}static isStruct(x){return x&&x.typeId===Type.Struct;}static isUnion(x){return x&&x.typeId===Type.Union;}static isFixedSizeBinary(x){return x&&x.typeId===Type.FixedSizeBinary;}static isFixedSizeList(x){return x&&x.typeId===Type.FixedSizeList;}static isMap(x){return x&&x.typeId===Type.Map;}static isDictionary(x){return x&&x.typeId===Type.Dictionary;}get typeId(){return Type.NONE;}compareTo(other){return this===other;}}_Symbol$toStringTag=Symbol.toStringTag;class Int extends DataType{constructor(isSigned,bitWidth){super();_defineProperty$1(this,"isSigned",void 0);_defineProperty$1(this,"bitWidth",void 0);this.isSigned=isSigned;this.bitWidth=bitWidth;}get typeId(){return Type.Int;}get[_Symbol$toStringTag](){return 'Int';}toString(){return "".concat(this.isSigned?'I':'Ui',"nt").concat(this.bitWidth);}}class Int8 extends Int{constructor(){super(true,8);}}class Int16 extends Int{constructor(){super(true,16);}}class Int32 extends Int{constructor(){super(true,32);}}class Uint8 extends Int{constructor(){super(false,8);}}class Uint16 extends Int{constructor(){super(false,16);}}class Uint32 extends Int{constructor(){super(false,32);}}var Precision={HALF:16,SINGLE:32,DOUBLE:64};_Symbol$toStringTag2=Symbol.toStringTag;class Float extends DataType{constructor(precision){super();_defineProperty$1(this,"precision",void 0);this.precision=precision;}get typeId(){return Type.Float;}get[_Symbol$toStringTag2](){return 'Float';}toString(){return "Float".concat(this.precision);}}class Float32 extends Float{constructor(){super(Precision.SINGLE);}}class Float64 extends Float{constructor(){super(Precision.DOUBLE);}}_Symbol$toStringTag7=Symbol.toStringTag;class FixedSizeList extends DataType{constructor(listSize,child){super();_defineProperty$1(this,"listSize",void 0);_defineProperty$1(this,"children",void 0);this.listSize=listSize;this.children=[child];}get typeId(){return Type.FixedSizeList;}get valueType(){return this.children[0].type;}get valueField(){return this.children[0];}get[_Symbol$toStringTag7](){return 'FixedSizeList';}toString(){return "FixedSizeList[".concat(this.listSize,"]<").concat(this.valueType,">");}}function getArrowTypeFromTypedArray(array){switch(array.constructor){case Int8Array:return new Int8();case Uint8Array:return new Uint8();case Int16Array:return new Int16();case Uint16Array:return new Uint16();case Int32Array:return new Int32();case Uint32Array:return new Uint32();case Float32Array:return new Float32();case Float64Array:return new Float64();default:throw new Error('array type not supported');}}function deduceMeshField(attributeName,attribute,optionalMetadata){var type=getArrowTypeFromTypedArray(attribute.value);var metadata=optionalMetadata?optionalMetadata:makeMeshAttributeMetadata(attribute);var field=new Field(attributeName,new FixedSizeList(attribute.size,new Field('value',type)),false,metadata);return field;}function makeMeshAttributeMetadata(attribute){var result=new Map();if('byteOffset'in attribute){result.set('byteOffset',attribute.byteOffset.toString(10));}if('byteStride'in attribute){result.set('byteStride',attribute.byteStride.toString(10));}if('normalized'in attribute){result.set('normalized',attribute.normalized.toString());}return result;}function getDracoSchema(attributes,loaderData,indices){var metadataMap=makeMetadata(loaderData.metadata);var fields=[];var namedLoaderDataAttributes=transformAttributesLoaderData(loaderData.attributes);for(var attributeName in attributes){var attribute=attributes[attributeName];var field=getArrowFieldFromAttribute(attributeName,attribute,namedLoaderDataAttributes[attributeName]);fields.push(field);}if(indices){var indicesField=getArrowFieldFromAttribute('indices',indices);fields.push(indicesField);}return new Schema(fields,metadataMap);}function transformAttributesLoaderData(loaderData){var result={};for(var key in loaderData){var dracoAttribute=loaderData[key];result[dracoAttribute.name||'undefined']=dracoAttribute;}return result;}function getArrowFieldFromAttribute(attributeName,attribute,loaderData){var metadataMap=loaderData?makeMetadata(loaderData.metadata):undefined;var field=deduceMeshField(attributeName,attribute,metadataMap);return field;}function makeMetadata(metadata){var metadataMap=new Map();for(var key in metadata){metadataMap.set("".concat(key,".string"),JSON.stringify(metadata[key]));}return metadataMap;}var DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP={POSITION:'POSITION',NORMAL:'NORMAL',COLOR:'COLOR_0',TEX_COORD:'TEXCOORD_0'};var DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP={1:Int8Array,2:Uint8Array,3:Int16Array,4:Uint16Array,5:Int32Array,6:Uint32Array,9:Float32Array};var INDEX_ITEM_SIZE=4;class DracoParser{constructor(draco){_defineProperty$1(this,"draco",void 0);_defineProperty$1(this,"decoder",void 0);_defineProperty$1(this,"metadataQuerier",void 0);this.draco=draco;this.decoder=new this.draco.Decoder();this.metadataQuerier=new this.draco.MetadataQuerier();}destroy(){this.draco.destroy(this.decoder);this.draco.destroy(this.metadataQuerier);}parseSync(arrayBuffer){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var buffer=new this.draco.DecoderBuffer();buffer.Init(new Int8Array(arrayBuffer),arrayBuffer.byteLength);this._disableAttributeTransforms(options);var geometry_type=this.decoder.GetEncodedGeometryType(buffer);var dracoGeometry=geometry_type===this.draco.TRIANGULAR_MESH?new this.draco.Mesh():new this.draco.PointCloud();try{var dracoStatus;switch(geometry_type){case this.draco.TRIANGULAR_MESH:dracoStatus=this.decoder.DecodeBufferToMesh(buffer,dracoGeometry);break;case this.draco.POINT_CLOUD:dracoStatus=this.decoder.DecodeBufferToPointCloud(buffer,dracoGeometry);break;default:throw new Error('DRACO: Unknown geometry type.');}if(!dracoStatus.ok()||!dracoGeometry.ptr){var message="DRACO decompression failed: ".concat(dracoStatus.error_msg());throw new Error(message);}var loaderData=this._getDracoLoaderData(dracoGeometry,geometry_type,options);var geometry=this._getMeshData(dracoGeometry,loaderData,options);var boundingBox=getMeshBoundingBox(geometry.attributes);var schema=getDracoSchema(geometry.attributes,loaderData,geometry.indices);var data=_objectSpread2(_objectSpread2({loader:'draco',loaderData,header:{vertexCount:dracoGeometry.num_points(),boundingBox}},geometry),{},{schema});return data;}finally{this.draco.destroy(buffer);if(dracoGeometry){this.draco.destroy(dracoGeometry);}}}_getDracoLoaderData(dracoGeometry,geometry_type,options){var metadata=this._getTopLevelMetadata(dracoGeometry);var attributes=this._getDracoAttributes(dracoGeometry,options);return {geometry_type,num_attributes:dracoGeometry.num_attributes(),num_points:dracoGeometry.num_points(),num_faces:dracoGeometry instanceof this.draco.Mesh?dracoGeometry.num_faces():0,metadata,attributes};}_getDracoAttributes(dracoGeometry,options){var dracoAttributes={};for(var attributeId=0;attributeIdthis.decoder[type]).includes(attribute_type);if(skip){var transform=new this.draco.AttributeQuantizationTransform();try{if(transform.InitFromAttribute(dracoAttribute)){return {quantization_bits:transform.quantization_bits(),range:transform.range(),min_values:new Float32Array([1,2,3]).map(i=>transform.min_value(i))};}}finally{this.draco.destroy(transform);}}return null;}_getOctahedronTransform(dracoAttribute,options){var{octahedronAttributes=[]}=options;var attribute_type=dracoAttribute.attribute_type();var octahedron=octahedronAttributes.map(type=>this.decoder[type]).includes(attribute_type);if(octahedron){var transform=new this.draco.AttributeQuantizationTransform();try{if(transform.InitFromAttribute(dracoAttribute)){return {quantization_bits:transform.quantization_bits()};}}finally{this.draco.destroy(transform);}}return null;}}function getDracoDataType(draco,attributeType){switch(attributeType){case Float32Array:return draco.DT_FLOAT32;case Int8Array:return draco.DT_INT8;case Int16Array:return draco.DT_INT16;case Int32Array:return draco.DT_INT32;case Uint8Array:return draco.DT_UINT8;case Uint16Array:return draco.DT_UINT16;case Uint32Array:return draco.DT_UINT32;default:return draco.DT_INVALID;}}function getInt32Array(dracoArray){var numValues=dracoArray.size();var intArray=new Int32Array(numValues);for(var _i39=0;_i39{return {draco};});}else {loadDecoderPromise=loadDecoderPromise||loadDracoDecoder(options);}return await loadDecoderPromise;}async function loadDracoDecoder(options){var DracoDecoderModule;var wasmBinary;switch(options.draco&&options.draco.decoderType){case'js':DracoDecoderModule=await loadLibrary(DRACO_JS_DECODER_URL,'draco',options);break;case'wasm':default:[DracoDecoderModule,wasmBinary]=await Promise.all([await loadLibrary(DRACO_WASM_WRAPPER_URL,'draco',options),await loadLibrary(DRACO_WASM_DECODER_URL,'draco',options)]);}DracoDecoderModule=DracoDecoderModule||globalThis.DracoDecoderModule;return await initializeDracoDecoder(DracoDecoderModule,wasmBinary);}function initializeDracoDecoder(DracoDecoderModule,wasmBinary){var options={};if(wasmBinary){options.wasmBinary=wasmBinary;}return new Promise(resolve=>{DracoDecoderModule(_objectSpread2(_objectSpread2({},options),{},{onModuleLoaded:draco=>resolve({draco})}));});}var DracoLoader=_objectSpread2(_objectSpread2({},DracoLoader$1),{},{parse:parse$2});async function parse$2(arrayBuffer,options){var{draco}=await loadDracoDecoderModule(options);var dracoParser=new DracoParser(draco);try{return dracoParser.parseSync(arrayBuffer,options===null||options===void 0?void 0:options.draco);}finally{dracoParser.destroy();}}var GL_PRIMITIVE_MODE={POINTS:0x0000,LINES:0x0001,LINE_LOOP:0x0002,LINE_STRIP:0x0003,TRIANGLES:0x0004,TRIANGLE_STRIP:0x0005,TRIANGLE_FAN:0x0006};var GL_TYPE={BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,INT:5124,UNSIGNED_INT:5125,FLOAT:5126,DOUBLE:5130};var GL$1=_objectSpread2(_objectSpread2({},GL_PRIMITIVE_MODE),GL_TYPE);var GL_TYPE_TO_ARRAY_TYPE={[GL_TYPE.DOUBLE]:Float64Array,[GL_TYPE.FLOAT]:Float32Array,[GL_TYPE.UNSIGNED_SHORT]:Uint16Array,[GL_TYPE.UNSIGNED_INT]:Uint32Array,[GL_TYPE.UNSIGNED_BYTE]:Uint8Array,[GL_TYPE.BYTE]:Int8Array,[GL_TYPE.SHORT]:Int16Array,[GL_TYPE.INT]:Int32Array};var NAME_TO_GL_TYPE={DOUBLE:GL_TYPE.DOUBLE,FLOAT:GL_TYPE.FLOAT,UNSIGNED_SHORT:GL_TYPE.UNSIGNED_SHORT,UNSIGNED_INT:GL_TYPE.UNSIGNED_INT,UNSIGNED_BYTE:GL_TYPE.UNSIGNED_BYTE,BYTE:GL_TYPE.BYTE,SHORT:GL_TYPE.SHORT,INT:GL_TYPE.INT};var ERR_TYPE_CONVERSION='Failed to convert GL type';class GLType{static fromTypedArray(arrayOrType){arrayOrType=ArrayBuffer.isView(arrayOrType)?arrayOrType.constructor:arrayOrType;for(var glType in GL_TYPE_TO_ARRAY_TYPE){var ArrayType=GL_TYPE_TO_ARRAY_TYPE[glType];if(ArrayType===arrayOrType){return glType;}}throw new Error(ERR_TYPE_CONVERSION);}static fromName(name){var glType=NAME_TO_GL_TYPE[name];if(!glType){throw new Error(ERR_TYPE_CONVERSION);}return glType;}static getArrayType(glType){switch(glType){case GL_TYPE.UNSIGNED_SHORT_5_6_5:case GL_TYPE.UNSIGNED_SHORT_4_4_4_4:case GL_TYPE.UNSIGNED_SHORT_5_5_5_1:return Uint16Array;default:var ArrayType=GL_TYPE_TO_ARRAY_TYPE[glType];if(!ArrayType){throw new Error(ERR_TYPE_CONVERSION);}return ArrayType;}}static getByteSize(glType){var ArrayType=GLType.getArrayType(glType);return ArrayType.BYTES_PER_ELEMENT;}static validate(glType){return Boolean(GLType.getArrayType(glType));}static createTypedArray(glType,buffer){var byteOffset=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var length=arguments.length>3?arguments[3]:undefined;if(length===undefined){length=(buffer.byteLength-byteOffset)/GLType.getByteSize(glType);}var ArrayType=GLType.getArrayType(glType);return new ArrayType(buffer,byteOffset,length);}}function assert$2(condition,message){if(!condition){throw new Error("math.gl assertion failed. ".concat(message));}}function decodeRGB565(rgb565){var target=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0];var r5=rgb565>>11&31;var g6=rgb565>>5&63;var b5=rgb565&31;target[0]=r5<<3;target[1]=g6<<2;target[2]=b5<<3;return target;}new Vector2$1();new Vector3$1();new Vector2$1();new Vector2$1();function fromSNorm(value){var rangeMaximum=arguments.length>1&&arguments[1]!==undefined?arguments[1]:255;return clamp$1(value,0.0,rangeMaximum)/rangeMaximum*2.0-1.0;}function signNotZero(value){return value<0.0?-1.0:1.0;}function octDecodeInRange(x,y,rangeMax,result){assert$2(result);if(x<0||x>rangeMax||y<0||y>rangeMax){throw new Error("x and y must be unsigned normalized integers between 0 and ".concat(rangeMax));}result.x=fromSNorm(x,rangeMax);result.y=fromSNorm(y,rangeMax);result.z=1.0-(Math.abs(result.x)+Math.abs(result.y));if(result.z<0.0){var oldVX=result.x;result.x=(1.0-Math.abs(result.y))*signNotZero(oldVX);result.y=(1.0-Math.abs(oldVX))*signNotZero(result.y);}return result.normalize();}function octDecode(x,y,result){return octDecodeInRange(x,y,255,result);}class Tile3DFeatureTable{constructor(featureTableJson,featureTableBinary){_defineProperty$1(this,"json",void 0);_defineProperty$1(this,"buffer",void 0);_defineProperty$1(this,"featuresLength",0);_defineProperty$1(this,"_cachedTypedArrays",{});this.json=featureTableJson;this.buffer=featureTableBinary;}getExtension(extensionName){return this.json.extensions&&this.json.extensions[extensionName];}hasProperty(propertyName){return Boolean(this.json[propertyName]);}getGlobalProperty(propertyName){var componentType=arguments.length>1&&arguments[1]!==undefined?arguments[1]:GL$1.UNSIGNED_INT;var componentLength=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;var jsonValue=this.json[propertyName];if(jsonValue&&Number.isFinite(jsonValue.byteOffset)){return this._getTypedArrayFromBinary(propertyName,componentType,componentLength,1,jsonValue.byteOffset);}return jsonValue;}getPropertyArray(propertyName,componentType,componentLength){var jsonValue=this.json[propertyName];if(jsonValue&&Number.isFinite(jsonValue.byteOffset)){if('componentType'in jsonValue){componentType=GLType.fromName(jsonValue.componentType);}return this._getTypedArrayFromBinary(propertyName,componentType,componentLength,this.featuresLength,jsonValue.byteOffset);}return this._getTypedArrayFromArray(propertyName,componentType,jsonValue);}getProperty(propertyName,componentType,componentLength,featureId,result){var jsonValue=this.json[propertyName];if(!jsonValue){return jsonValue;}var typedArray=this.getPropertyArray(propertyName,componentType,componentLength);if(componentLength===1){return typedArray[featureId];}for(var _i41=0;_i41values[i],VEC2:(values,i)=>[values[2*i+0],values[2*i+1]],VEC3:(values,i)=>[values[3*i+0],values[3*i+1],values[3*i+2]],VEC4:(values,i)=>[values[4*i+0],values[4*i+1],values[4*i+2],values[4*i+3]],MAT2:(values,i)=>[values[4*i+0],values[4*i+1],values[4*i+2],values[4*i+3]],MAT3:(values,i)=>[values[9*i+0],values[9*i+1],values[9*i+2],values[9*i+3],values[9*i+4],values[9*i+5],values[9*i+6],values[9*i+7],values[9*i+8]],MAT4:(values,i)=>[values[16*i+0],values[16*i+1],values[16*i+2],values[16*i+3],values[16*i+4],values[16*i+5],values[16*i+6],values[16*i+7],values[16*i+8],values[16*i+9],values[16*i+10],values[16*i+11],values[16*i+12],values[16*i+13],values[16*i+14],values[16*i+15]]};var PACKER={SCALAR:(x,values,i)=>{values[i]=x;},VEC2:(x,values,i)=>{values[2*i+0]=x[0];values[2*i+1]=x[1];},VEC3:(x,values,i)=>{values[3*i+0]=x[0];values[3*i+1]=x[1];values[3*i+2]=x[2];},VEC4:(x,values,i)=>{values[4*i+0]=x[0];values[4*i+1]=x[1];values[4*i+2]=x[2];values[4*i+3]=x[3];},MAT2:(x,values,i)=>{values[4*i+0]=x[0];values[4*i+1]=x[1];values[4*i+2]=x[2];values[4*i+3]=x[3];},MAT3:(x,values,i)=>{values[9*i+0]=x[0];values[9*i+1]=x[1];values[9*i+2]=x[2];values[9*i+3]=x[3];values[9*i+4]=x[4];values[9*i+5]=x[5];values[9*i+6]=x[6];values[9*i+7]=x[7];values[9*i+8]=x[8];values[9*i+9]=x[9];},MAT4:(x,values,i)=>{values[16*i+0]=x[0];values[16*i+1]=x[1];values[16*i+2]=x[2];values[16*i+3]=x[3];values[16*i+4]=x[4];values[16*i+5]=x[5];values[16*i+6]=x[6];values[16*i+7]=x[7];values[16*i+8]=x[8];values[16*i+9]=x[9];values[16*i+10]=x[10];values[16*i+11]=x[11];values[16*i+12]=x[12];values[16*i+13]=x[13];values[16*i+14]=x[14];values[16*i+15]=x[15];}};function createTypedArrayFromAccessor(tile3DAccessor,buffer,byteOffset,length){var{componentType}=tile3DAccessor;assert$7(tile3DAccessor.componentType);var type=typeof componentType==='string'?GLType.fromName(componentType):componentType;var size=COMPONENTS_PER_ATTRIBUTE[tile3DAccessor.type];var unpacker=UNPACKER[tile3DAccessor.type];var packer=PACKER[tile3DAccessor.type];byteOffset+=tile3DAccessor.byteOffset;var values=GLType.createTypedArray(type,buffer,byteOffset,size*length);return {values,type,size,unpacker,packer};}var defined$1=x=>x!==undefined;function initializeHierarchy(batchTable,jsonHeader,binaryBody){if(!jsonHeader){return null;}var hierarchy=batchTable.getExtension('3DTILES_batch_table_hierarchy');var legacyHierarchy=jsonHeader.HIERARCHY;if(legacyHierarchy){console.warn('3D Tile Parser: HIERARCHY is deprecated. Use 3DTILES_batch_table_hierarchy.');jsonHeader.extensions=jsonHeader.extensions||{};jsonHeader.extensions['3DTILES_batch_table_hierarchy']=legacyHierarchy;hierarchy=legacyHierarchy;}if(!hierarchy){return null;}return initializeHierarchyValues(hierarchy,binaryBody);}function initializeHierarchyValues(hierarchyJson,binaryBody){var i;var classId;var binaryAccessor;var instancesLength=hierarchyJson.instancesLength;var classes=hierarchyJson.classes;var classIds=hierarchyJson.classIds;var parentCounts=hierarchyJson.parentCounts;var parentIds=hierarchyJson.parentIds;var parentIdsLength=instancesLength;if(defined$1(classIds.byteOffset)){classIds.componentType=defaultValue(classIds.componentType,GL.UNSIGNED_SHORT);classIds.type=AttributeType.SCALAR;binaryAccessor=getBinaryAccessor(classIds);classIds=binaryAccessor.createArrayBufferView(binaryBody.buffer,binaryBody.byteOffset+classIds.byteOffset,instancesLength);}var parentIndexes;if(defined$1(parentCounts)){if(defined$1(parentCounts.byteOffset)){parentCounts.componentType=defaultValue(parentCounts.componentType,GL.UNSIGNED_SHORT);parentCounts.type=AttributeType.SCALAR;binaryAccessor=getBinaryAccessor(parentCounts);parentCounts=binaryAccessor.createArrayBufferView(binaryBody.buffer,binaryBody.byteOffset+parentCounts.byteOffset,instancesLength);}parentIndexes=new Uint16Array(instancesLength);parentIdsLength=0;for(i=0;i0){return traverseHierarchyMultipleParents(hierarchy,instanceIndex,endConditionCallback);}return traverseHierarchySingleParent(hierarchy,instanceIndex,endConditionCallback);}function traverseHierarchyMultipleParents(hierarchy,instanceIndex,endConditionCallback){var classIds=hierarchy.classIds;var parentCounts=hierarchy.parentCounts;var parentIds=hierarchy.parentIds;var parentIndexes=hierarchy.parentIndexes;var instancesLength=classIds.length;var visited=scratchVisited;visited.length=Math.max(visited.length,instancesLength);var visitedMarker=++marker;var stack=scratchStack;stack.length=0;stack.push(instanceIndex);while(stack.length>0){instanceIndex=stack.pop();if(visited[instanceIndex]===visitedMarker){continue;}visited[instanceIndex]=visitedMarker;var result=endConditionCallback(hierarchy,instanceIndex);if(defined$1(result)){return result;}var parentCount=parentCounts[instanceIndex];var parentIndex=parentIndexes[instanceIndex];for(var _i42=0;_i42x;var IGNORED_PROPERTY_FIELDS={HIERARCHY:true,extensions:true,extras:true};class Tile3DBatchTableParser{constructor(json,binary,featureCount){var options=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{};var _this$json;_defineProperty$1(this,"json",void 0);_defineProperty$1(this,"binary",void 0);_defineProperty$1(this,"featureCount",void 0);_defineProperty$1(this,"_extensions",void 0);_defineProperty$1(this,"_properties",void 0);_defineProperty$1(this,"_binaryProperties",void 0);_defineProperty$1(this,"_hierarchy",void 0);assert$7(featureCount>=0);this.json=json||{};this.binary=binary;this.featureCount=featureCount;this._extensions=((_this$json=this.json)===null||_this$json===void 0?void 0:_this$json.extensions)||{};this._properties={};for(var propertyName in this.json){if(!IGNORED_PROPERTY_FIELDS[propertyName]){this._properties[propertyName]=this.json[propertyName];}}this._binaryProperties=this._initializeBinaryProperties();if(options['3DTILES_batch_table_hierarchy']){this._hierarchy=initializeHierarchy(this,this.json,this.binary);}}getExtension(extensionName){return this.json&&this.json.extensions&&this.json.extensions[extensionName];}memorySizeInBytes(){return 0;}isClass(batchId,className){this._checkBatchId(batchId);assert$7(typeof className==='string',className);if(this._hierarchy){var result=traverseHierarchy(this._hierarchy,batchId,(hierarchy,instanceIndex)=>{var classId=hierarchy.classIds[instanceIndex];var instanceClass=hierarchy.classes[classId];return instanceClass.name===className;});return defined(result);}return false;}isExactClass(batchId,className){assert$7(typeof className==='string',className);return this.getExactClassName(batchId)===className;}getExactClassName(batchId){this._checkBatchId(batchId);if(this._hierarchy){var classId=this._hierarchy.classIds[batchId];var instanceClass=this._hierarchy.classes[classId];return instanceClass.name;}return undefined;}hasProperty(batchId,name){this._checkBatchId(batchId);assert$7(typeof name==='string',name);return defined(this._properties[name])||this._hasPropertyInHierarchy(batchId,name);}getPropertyNames(batchId,results){this._checkBatchId(batchId);results=defined(results)?results:[];results.length=0;var propertyNames=Object.keys(this._properties);results.push(...propertyNames);if(this._hierarchy){this._getPropertyNamesInHierarchy(batchId,results);}return results;}getProperty(batchId,name){this._checkBatchId(batchId);assert$7(typeof name==='string',name);if(this._binaryProperties){var binaryProperty=this._binaryProperties[name];if(defined(binaryProperty)){return this._getBinaryProperty(binaryProperty,batchId);}}var propertyValues=this._properties[name];if(defined(propertyValues)){return clone(propertyValues[batchId]);}if(this._hierarchy){var hierarchyProperty=this._getHierarchyProperty(batchId,name);if(defined(hierarchyProperty)){return hierarchyProperty;}}return undefined;}setProperty(batchId,name,value){var featureCount=this.featureCount;this._checkBatchId(batchId);assert$7(typeof name==='string',name);if(this._binaryProperties){var binaryProperty=this._binaryProperties[name];if(binaryProperty){this._setBinaryProperty(binaryProperty,batchId,value);return;}}if(this._hierarchy){if(this._setHierarchyProperty(this,batchId,name,value)){return;}}var propertyValues=this._properties[name];if(!defined(propertyValues)){this._properties[name]=new Array(featureCount);propertyValues=this._properties[name];}propertyValues[batchId]=clone(value);}_checkBatchId(batchId){var valid=batchId>=0&&batchId{var classId=hierarchy.classIds[instanceIndex];var instances=hierarchy.classes[classId].instances;return defined(instances[name]);});return defined(result);}_getPropertyNamesInHierarchy(batchId,results){traverseHierarchy(this._hierarchy,batchId,(hierarchy,instanceIndex)=>{var classId=hierarchy.classIds[instanceIndex];var instances=hierarchy.classes[classId].instances;for(var _name4 in instances){if(instances.hasOwnProperty(_name4)){if(results.indexOf(_name4)===-1){results.push(_name4);}}}});}_getHierarchyProperty(batchId,name){return traverseHierarchy(this._hierarchy,batchId,(hierarchy,instanceIndex)=>{var classId=hierarchy.classIds[instanceIndex];var instanceClass=hierarchy.classes[classId];var indexInClass=hierarchy.classIndexes[instanceIndex];var propertyValues=instanceClass.instances[name];if(defined(propertyValues)){if(defined(propertyValues.typedArray)){return this._getBinaryProperty(propertyValues,indexInClass);}return clone(propertyValues[indexInClass]);}return null;});}_setHierarchyProperty(batchTable,batchId,name,value){var result=traverseHierarchy(this._hierarchy,batchId,(hierarchy,instanceIndex)=>{var classId=hierarchy.classIds[instanceIndex];var instanceClass=hierarchy.classes[classId];var indexInClass=hierarchy.classIndexes[instanceIndex];var propertyValues=instanceClass.instances[name];if(defined(propertyValues)){assert$7(instanceIndex===batchId,"Inherited property \"".concat(name,"\" is read-only."));if(defined(propertyValues.typedArray)){this._setBinaryProperty(propertyValues,indexInClass,value);}else {propertyValues[indexInClass]=clone(value);}return true;}return false;});return defined(result);}}var SIZEOF_UINT32$1=4;function parse3DTileHeaderSync(tile,arrayBuffer){var byteOffset=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var view=new DataView(arrayBuffer);tile.magic=view.getUint32(byteOffset,true);byteOffset+=SIZEOF_UINT32$1;tile.version=view.getUint32(byteOffset,true);byteOffset+=SIZEOF_UINT32$1;tile.byteLength=view.getUint32(byteOffset,true);byteOffset+=SIZEOF_UINT32$1;if(tile.version!==1){throw new Error("3D Tile Version ".concat(tile.version," not supported"));}return byteOffset;}var SIZEOF_UINT32=4;var DEPRECATION_WARNING='b3dm tile in legacy format.';function parse3DTileTablesHeaderSync(tile,arrayBuffer,byteOffset){var view=new DataView(arrayBuffer);var batchLength;tile.header=tile.header||{};var featureTableJsonByteLength=view.getUint32(byteOffset,true);byteOffset+=SIZEOF_UINT32;var featureTableBinaryByteLength=view.getUint32(byteOffset,true);byteOffset+=SIZEOF_UINT32;var batchTableJsonByteLength=view.getUint32(byteOffset,true);byteOffset+=SIZEOF_UINT32;var batchTableBinaryByteLength=view.getUint32(byteOffset,true);byteOffset+=SIZEOF_UINT32;if(batchTableJsonByteLength>=570425344){byteOffset-=SIZEOF_UINT32*2;batchLength=featureTableJsonByteLength;batchTableJsonByteLength=featureTableBinaryByteLength;batchTableBinaryByteLength=0;featureTableJsonByteLength=0;featureTableBinaryByteLength=0;console.warn(DEPRECATION_WARNING);}else if(batchTableBinaryByteLength>=570425344){byteOffset-=SIZEOF_UINT32;batchLength=batchTableJsonByteLength;batchTableJsonByteLength=featureTableJsonByteLength;batchTableBinaryByteLength=featureTableBinaryByteLength;featureTableJsonByteLength=0;featureTableBinaryByteLength=0;console.warn(DEPRECATION_WARNING);}tile.header.featureTableJsonByteLength=featureTableJsonByteLength;tile.header.featureTableBinaryByteLength=featureTableBinaryByteLength;tile.header.batchTableJsonByteLength=batchTableJsonByteLength;tile.header.batchTableBinaryByteLength=batchTableBinaryByteLength;tile.header.batchLength=batchLength;return byteOffset;}function parse3DTileTablesSync(tile,arrayBuffer,byteOffset,options){byteOffset=parse3DTileFeatureTable(tile,arrayBuffer,byteOffset);byteOffset=parse3DTileBatchTable(tile,arrayBuffer,byteOffset);return byteOffset;}function parse3DTileFeatureTable(tile,arrayBuffer,byteOffset,options){var{featureTableJsonByteLength,featureTableBinaryByteLength,batchLength}=tile.header;tile.featureTableJson={BATCH_LENGTH:batchLength||0};if(featureTableJsonByteLength>0){var featureTableString=getStringFromArrayBuffer(arrayBuffer,byteOffset,featureTableJsonByteLength);tile.featureTableJson=JSON.parse(featureTableString);}byteOffset+=featureTableJsonByteLength;tile.featureTableBinary=new Uint8Array(arrayBuffer,byteOffset,featureTableBinaryByteLength);byteOffset+=featureTableBinaryByteLength;return byteOffset;}function parse3DTileBatchTable(tile,arrayBuffer,byteOffset,options){var{batchTableJsonByteLength,batchTableBinaryByteLength}=tile.header;if(batchTableJsonByteLength>0){var batchTableString=getStringFromArrayBuffer(arrayBuffer,byteOffset,batchTableJsonByteLength);tile.batchTableJson=JSON.parse(batchTableString);byteOffset+=batchTableJsonByteLength;if(batchTableBinaryByteLength>0){tile.batchTableBinary=new Uint8Array(arrayBuffer,byteOffset,batchTableBinaryByteLength);tile.batchTableBinary=new Uint8Array(tile.batchTableBinary);byteOffset+=batchTableBinaryByteLength;}}return byteOffset;}function normalize3DTileColorAttribute(tile,colors,batchTable){if(!colors&&(!tile||!tile.batchIds||!batchTable)){return null;}var{batchIds,isRGB565,pointCount}=tile;if(batchIds&&batchTable){var colorArray=new Uint8ClampedArray(pointCount*3);for(var _i45=0;_i45d*255);colorArray[_i45*3]=color[0];colorArray[_i45*3+1]=color[1];colorArray[_i45*3+2]=color[2];}return {type:GL$1.UNSIGNED_BYTE,value:colorArray,size:3,normalized:true};}if(isRGB565){var _colorArray=new Uint8ClampedArray(pointCount*3);for(var _i46=0;_i46{BasisModule(options).then(module=>{var{BasisFile,initializeBasis}=module;initializeBasis();resolve({BasisFile});});});}var loadBasisEncoderPromise;async function loadBasisEncoderModule(options){var modules=options.modules||{};if(modules.basisEncoder){return modules.basisEncoder;}loadBasisEncoderPromise=loadBasisEncoderPromise||loadBasisEncoder(options);return await loadBasisEncoderPromise;}async function loadBasisEncoder(options){var BASIS_ENCODER=null;var wasmBinary=null;[BASIS_ENCODER,wasmBinary]=await Promise.all([await loadLibrary(BASIS_CDN_ENCODER_JS,'textures',options),await loadLibrary(BASIS_CDN_ENCODER_WASM,'textures',options)]);BASIS_ENCODER=BASIS_ENCODER||globalThis.BASIS;return await initializeBasisEncoderModule(BASIS_ENCODER,wasmBinary);}function initializeBasisEncoderModule(BasisEncoderModule,wasmBinary){var options={};if(wasmBinary){options.wasmBinary=wasmBinary;}return new Promise(resolve=>{BasisEncoderModule(options).then(module=>{var{BasisFile,KTX2File,initializeBasis,BasisEncoder}=module;initializeBasis();resolve({BasisFile,KTX2File,BasisEncoder});});});}var GL_EXTENSIONS_CONSTANTS={COMPRESSED_RGB_S3TC_DXT1_EXT:0x83f0,COMPRESSED_RGBA_S3TC_DXT1_EXT:0x83f1,COMPRESSED_RGBA_S3TC_DXT3_EXT:0x83f2,COMPRESSED_RGBA_S3TC_DXT5_EXT:0x83f3,COMPRESSED_R11_EAC:0x9270,COMPRESSED_SIGNED_R11_EAC:0x9271,COMPRESSED_RG11_EAC:0x9272,COMPRESSED_SIGNED_RG11_EAC:0x9273,COMPRESSED_RGB8_ETC2:0x9274,COMPRESSED_RGBA8_ETC2_EAC:0x9275,COMPRESSED_SRGB8_ETC2:0x9276,COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:0x9277,COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:0x9278,COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:0x9279,COMPRESSED_RGB_PVRTC_4BPPV1_IMG:0x8c00,COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:0x8c02,COMPRESSED_RGB_PVRTC_2BPPV1_IMG:0x8c01,COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:0x8c03,COMPRESSED_RGB_ETC1_WEBGL:0x8d64,COMPRESSED_RGB_ATC_WEBGL:0x8c92,COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL:0x8c93,COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL:0x87ee,COMPRESSED_RGBA_ASTC_4X4_KHR:0x93b0,COMPRESSED_RGBA_ASTC_5X4_KHR:0x93b1,COMPRESSED_RGBA_ASTC_5X5_KHR:0x93b2,COMPRESSED_RGBA_ASTC_6X5_KHR:0x93b3,COMPRESSED_RGBA_ASTC_6X6_KHR:0x93b4,COMPRESSED_RGBA_ASTC_8X5_KHR:0x93b5,COMPRESSED_RGBA_ASTC_8X6_KHR:0x93b6,COMPRESSED_RGBA_ASTC_8X8_KHR:0x93b7,COMPRESSED_RGBA_ASTC_10X5_KHR:0x93b8,COMPRESSED_RGBA_ASTC_10X6_KHR:0x93b9,COMPRESSED_RGBA_ASTC_10X8_KHR:0x93ba,COMPRESSED_RGBA_ASTC_10X10_KHR:0x93bb,COMPRESSED_RGBA_ASTC_12X10_KHR:0x93bc,COMPRESSED_RGBA_ASTC_12X12_KHR:0x93bd,COMPRESSED_SRGB8_ALPHA8_ASTC_4X4_KHR:0x93d0,COMPRESSED_SRGB8_ALPHA8_ASTC_5X4_KHR:0x93d1,COMPRESSED_SRGB8_ALPHA8_ASTC_5X5_KHR:0x93d2,COMPRESSED_SRGB8_ALPHA8_ASTC_6X5_KHR:0x93d3,COMPRESSED_SRGB8_ALPHA8_ASTC_6X6_KHR:0x93d4,COMPRESSED_SRGB8_ALPHA8_ASTC_8X5_KHR:0x93d5,COMPRESSED_SRGB8_ALPHA8_ASTC_8X6_KHR:0x93d6,COMPRESSED_SRGB8_ALPHA8_ASTC_8X8_KHR:0x93d7,COMPRESSED_SRGB8_ALPHA8_ASTC_10X5_KHR:0x93d8,COMPRESSED_SRGB8_ALPHA8_ASTC_10X6_KHR:0x93d9,COMPRESSED_SRGB8_ALPHA8_ASTC_10X8_KHR:0x93da,COMPRESSED_SRGB8_ALPHA8_ASTC_10X10_KHR:0x93db,COMPRESSED_SRGB8_ALPHA8_ASTC_12X10_KHR:0x93dc,COMPRESSED_SRGB8_ALPHA8_ASTC_12X12_KHR:0x93dd,COMPRESSED_RED_RGTC1_EXT:0x8dbb,COMPRESSED_SIGNED_RED_RGTC1_EXT:0x8dbc,COMPRESSED_RED_GREEN_RGTC2_EXT:0x8dbd,COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT:0x8dbe,COMPRESSED_SRGB_S3TC_DXT1_EXT:0x8c4c,COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:0x8c4d,COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT:0x8c4e,COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:0x8c4f};var BROWSER_PREFIXES=['','WEBKIT_','MOZ_'];var WEBGL_EXTENSIONS={WEBGL_compressed_texture_s3tc:'dxt',WEBGL_compressed_texture_s3tc_srgb:'dxt-srgb',WEBGL_compressed_texture_etc1:'etc1',WEBGL_compressed_texture_etc:'etc2',WEBGL_compressed_texture_pvrtc:'pvrtc',WEBGL_compressed_texture_atc:'atc',WEBGL_compressed_texture_astc:'astc',EXT_texture_compression_rgtc:'rgtc'};var formats=null;function getSupportedGPUTextureFormats(gl){if(!formats){gl=gl||getWebGLContext()||undefined;formats=new Set();for(var prefix of BROWSER_PREFIXES){for(var extension in WEBGL_EXTENSIONS){if(gl&&gl.getExtension("".concat(prefix).concat(extension))){var gpuTextureFormat=WEBGL_EXTENSIONS[extension];formats.add(gpuTextureFormat);}}}}return formats;}function getWebGLContext(){try{var canvas=document.createElement('canvas');return canvas.getContext('webgl');}catch(error){return null;}}var n$2,i$3,s$1,a$2,r$1,o$2,l$2,f$1;!function(t){t[t.NONE=0]="NONE",t[t.BASISLZ=1]="BASISLZ",t[t.ZSTD=2]="ZSTD",t[t.ZLIB=3]="ZLIB";}(n$2||(n$2={})),function(t){t[t.BASICFORMAT=0]="BASICFORMAT";}(i$3||(i$3={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.ETC1S=163]="ETC1S",t[t.UASTC=166]="UASTC";}(s$1||(s$1={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.SRGB=1]="SRGB";}(a$2||(a$2={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.LINEAR=1]="LINEAR",t[t.SRGB=2]="SRGB",t[t.ITU=3]="ITU",t[t.NTSC=4]="NTSC",t[t.SLOG=5]="SLOG",t[t.SLOG2=6]="SLOG2";}(r$1||(r$1={})),function(t){t[t.ALPHA_STRAIGHT=0]="ALPHA_STRAIGHT",t[t.ALPHA_PREMULTIPLIED=1]="ALPHA_PREMULTIPLIED";}(o$2||(o$2={})),function(t){t[t.RGB=0]="RGB",t[t.RRR=3]="RRR",t[t.GGG=4]="GGG",t[t.AAA=15]="AAA";}(l$2||(l$2={})),function(t){t[t.RGB=0]="RGB",t[t.RGBA=3]="RGBA",t[t.RRR=4]="RRR",t[t.RRRG=5]="RRRG";}(f$1||(f$1={}));var KTX2_ID=[0xab,0x4b,0x54,0x58,0x20,0x32,0x30,0xbb,0x0d,0x0a,0x1a,0x0a];function isKTX(data){var id=new Uint8Array(data);var notKTX=id.byteLength{try{image.onload=()=>resolve(image);image.onerror=err=>reject(new Error("Could not load image ".concat(url,": ").concat(err)));}catch(error){reject(error);}});}var EMPTY_OBJECT={};var imagebitmapOptionsSupported=true;async function parseToImageBitmap(arrayBuffer,options,url){var blob;if(isSVG(url)){var image=await parseToImage(arrayBuffer,options,url);blob=image;}else {blob=getBlob(arrayBuffer,url);}var imagebitmapOptions=options&&options.imagebitmap;return await safeCreateImageBitmap(blob,imagebitmapOptions);}async function safeCreateImageBitmap(blob){var imagebitmapOptions=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;if(isEmptyObject(imagebitmapOptions)||!imagebitmapOptionsSupported){imagebitmapOptions=null;}if(imagebitmapOptions){try{return await createImageBitmap(blob,imagebitmapOptions);}catch(error){console.warn(error);imagebitmapOptionsSupported=false;}}return await createImageBitmap(blob);}function isEmptyObject(object){for(var key in object||EMPTY_OBJECT){return false;}return true;}var BIG_ENDIAN=false;var LITTLE_ENDIAN=true;function getBinaryImageMetadata(binaryData){var dataView=toDataView(binaryData);return getPngMetadata(dataView)||getJpegMetadata(dataView)||getGifMetadata(dataView)||getBmpMetadata(dataView);}function getPngMetadata(binaryData){var dataView=toDataView(binaryData);var isPng=dataView.byteLength>=24&&dataView.getUint32(0,BIG_ENDIAN)===0x89504e47;if(!isPng){return null;}return {mimeType:'image/png',width:dataView.getUint32(16,BIG_ENDIAN),height:dataView.getUint32(20,BIG_ENDIAN)};}function getGifMetadata(binaryData){var dataView=toDataView(binaryData);var isGif=dataView.byteLength>=10&&dataView.getUint32(0,BIG_ENDIAN)===0x47494638;if(!isGif){return null;}return {mimeType:'image/gif',width:dataView.getUint16(6,LITTLE_ENDIAN),height:dataView.getUint16(8,LITTLE_ENDIAN)};}function getBmpMetadata(binaryData){var dataView=toDataView(binaryData);var isBmp=dataView.byteLength>=14&&dataView.getUint16(0,BIG_ENDIAN)===0x424d&&dataView.getUint32(2,LITTLE_ENDIAN)===dataView.byteLength;if(!isBmp){return null;}return {mimeType:'image/bmp',width:dataView.getUint32(18,LITTLE_ENDIAN),height:dataView.getUint32(22,LITTLE_ENDIAN)};}function getJpegMetadata(binaryData){var dataView=toDataView(binaryData);var isJpeg=dataView.byteLength>=3&&dataView.getUint16(0,BIG_ENDIAN)===0xffd8&&dataView.getUint8(2)===0xff;if(!isJpeg){return null;}var{tableMarkers,sofMarkers}=getJpegMarkers();var i=2;while(i+9Boolean(getBinaryImageMetadata(new DataView(arrayBuffer)))],options:DEFAULT_IMAGE_LOADER_OPTIONS};var NODE_FORMAT_SUPPORT=['image/png','image/jpeg','image/gif'];var mimeTypeSupported={};function _isImageFormatSupported(mimeType){if(mimeTypeSupported[mimeType]===undefined){mimeTypeSupported[mimeType]=checkFormatSupport(mimeType);}return mimeTypeSupported[mimeType];}function checkFormatSupport(mimeType){switch(mimeType){case'image/webp':return checkWebPSupport();case'image/svg':return isBrowser$2;default:if(!isBrowser$2){var{_parseImageNode:_parseImageNode2}=globalThis;return Boolean(_parseImageNode2)&&NODE_FORMAT_SUPPORT.includes(mimeType);}return true;}}function checkWebPSupport(){if(!isBrowser$2){return false;}try{var element=document.createElement('canvas');return element.toDataURL('image/webp').indexOf('data:image/webp')===0;}catch(_unused2){return false;}}function assert$1(condition,message){if(!condition){throw new Error(message||'assert failed: gltf');}}function resolveUrl(url,options){var absolute=url.startsWith('data:')||url.startsWith('http:')||url.startsWith('https:');if(absolute){return url;}var baseUrl=options.baseUri||options.uri;if(!baseUrl){throw new Error("'baseUri' must be provided to resolve relative url ".concat(url));}return baseUrl.substr(0,baseUrl.lastIndexOf('/')+1)+url;}function getTypedArrayForBufferView(json,buffers,bufferViewIndex){var bufferView=json.bufferViews[bufferViewIndex];assert$1(bufferView);var bufferIndex=bufferView.buffer;var binChunk=buffers[bufferIndex];assert$1(binChunk);var byteOffset=(bufferView.byteOffset||0)+binChunk.byteOffset;return new Uint8Array(binChunk.arrayBuffer,byteOffset,bufferView.byteLength);}var TYPES=['SCALAR','VEC2','VEC3','VEC4'];var ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT=[[Int8Array,5120],[Uint8Array,5121],[Int16Array,5122],[Uint16Array,5123],[Uint32Array,5125],[Float32Array,5126],[Float64Array,5130]];var ARRAY_TO_COMPONENT_TYPE=new Map(ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT);var ATTRIBUTE_TYPE_TO_COMPONENTS={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16};var ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};var ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array};function getAccessorTypeFromSize(size){var type=TYPES[size-1];return type||TYPES[0];}function getComponentTypeFromArray(typedArray){var componentType=ARRAY_TO_COMPONENT_TYPE.get(typedArray.constructor);if(!componentType){throw new Error('Illegal typed array');}return componentType;}function getAccessorArrayTypeAndLength(accessor,bufferView){var ArrayType=ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY[accessor.componentType];var components=ATTRIBUTE_TYPE_TO_COMPONENTS[accessor.type];var bytesPerComponent=ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE[accessor.componentType];var length=accessor.count*components;var byteLength=accessor.count*components*bytesPerComponent;assert$1(byteLength>=0&&byteLength<=bufferView.byteLength);return {ArrayType,length,byteLength};}var DEFAULT_GLTF_JSON={asset:{version:'2.0',generator:'loaders.gl'},buffers:[]};class GLTFScenegraph{constructor(gltf){_defineProperty$1(this,"gltf",void 0);_defineProperty$1(this,"sourceBuffers",void 0);_defineProperty$1(this,"byteLength",void 0);this.gltf=gltf||{json:_objectSpread2({},DEFAULT_GLTF_JSON),buffers:[]};this.sourceBuffers=[];this.byteLength=0;if(this.gltf.buffers&&this.gltf.buffers[0]){this.byteLength=this.gltf.buffers[0].byteLength;this.sourceBuffers=[this.gltf.buffers[0]];}}get json(){return this.gltf.json;}getApplicationData(key){var data=this.json[key];return data;}getExtraData(key){var extras=this.json.extras||{};return extras[key];}getExtension(extensionName){var isExtension=this.getUsedExtensions().find(name=>name===extensionName);var extensions=this.json.extensions||{};return isExtension?extensions[extensionName]||true:null;}getRequiredExtension(extensionName){var isRequired=this.getRequiredExtensions().find(name=>name===extensionName);return isRequired?this.getExtension(extensionName):null;}getRequiredExtensions(){return this.json.extensionsRequired||[];}getUsedExtensions(){return this.json.extensionsUsed||[];}getObjectExtension(object,extensionName){var extensions=object.extensions||{};return extensions[extensionName];}getScene(index){return this.getObject('scenes',index);}getNode(index){return this.getObject('nodes',index);}getSkin(index){return this.getObject('skins',index);}getMesh(index){return this.getObject('meshes',index);}getMaterial(index){return this.getObject('materials',index);}getAccessor(index){return this.getObject('accessors',index);}getTexture(index){return this.getObject('textures',index);}getSampler(index){return this.getObject('samplers',index);}getImage(index){return this.getObject('images',index);}getBufferView(index){return this.getObject('bufferViews',index);}getBuffer(index){return this.getObject('buffers',index);}getObject(array,index){if(typeof index==='object'){return index;}var object=this.json[array]&&this.json[array][index];if(!object){throw new Error("glTF file error: Could not find ".concat(array,"[").concat(index,"]"));}return object;}getTypedArrayForBufferView(bufferView){bufferView=this.getBufferView(bufferView);var bufferIndex=bufferView.buffer;var binChunk=this.gltf.buffers[bufferIndex];assert$1(binChunk);var byteOffset=(bufferView.byteOffset||0)+binChunk.byteOffset;return new Uint8Array(binChunk.arrayBuffer,byteOffset,bufferView.byteLength);}getTypedArrayForAccessor(accessor){accessor=this.getAccessor(accessor);var bufferView=this.getBufferView(accessor.bufferView);var buffer=this.getBuffer(bufferView.buffer);var arrayBuffer=buffer.data;var{ArrayType,length}=getAccessorArrayTypeAndLength(accessor,bufferView);var byteOffset=bufferView.byteOffset+accessor.byteOffset;return new ArrayType(arrayBuffer,byteOffset,length);}getTypedArrayForImageData(image){image=this.getAccessor(image);var bufferView=this.getBufferView(image.bufferView);var buffer=this.getBuffer(bufferView.buffer);var arrayBuffer=buffer.data;var byteOffset=bufferView.byteOffset||0;return new Uint8Array(arrayBuffer,byteOffset,bufferView.byteLength);}addApplicationData(key,data){this.json[key]=data;return this;}addExtraData(key,data){this.json.extras=this.json.extras||{};this.json.extras[key]=data;return this;}addObjectExtension(object,extensionName,data){object.extensions=object.extensions||{};object.extensions[extensionName]=data;this.registerUsedExtension(extensionName);return this;}setObjectExtension(object,extensionName,data){var extensions=object.extensions||{};extensions[extensionName]=data;}removeObjectExtension(object,extensionName){var extensions=object.extensions||{};var extension=extensions[extensionName];delete extensions[extensionName];return extension;}addExtension(extensionName){var extensionData=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};assert$1(extensionData);this.json.extensions=this.json.extensions||{};this.json.extensions[extensionName]=extensionData;this.registerUsedExtension(extensionName);return extensionData;}addRequiredExtension(extensionName){var extensionData=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};assert$1(extensionData);this.addExtension(extensionName,extensionData);this.registerRequiredExtension(extensionName);return extensionData;}registerUsedExtension(extensionName){this.json.extensionsUsed=this.json.extensionsUsed||[];if(!this.json.extensionsUsed.find(ext=>ext===extensionName)){this.json.extensionsUsed.push(extensionName);}}registerRequiredExtension(extensionName){this.registerUsedExtension(extensionName);this.json.extensionsRequired=this.json.extensionsRequired||[];if(!this.json.extensionsRequired.find(ext=>ext===extensionName)){this.json.extensionsRequired.push(extensionName);}}removeExtension(extensionName){if(this.json.extensionsRequired){this._removeStringFromArray(this.json.extensionsRequired,extensionName);}if(this.json.extensionsUsed){this._removeStringFromArray(this.json.extensionsUsed,extensionName);}if(this.json.extensions){delete this.json.extensions[extensionName];}}setDefaultScene(sceneIndex){this.json.scene=sceneIndex;}addScene(scene){var{nodeIndices}=scene;this.json.scenes=this.json.scenes||[];this.json.scenes.push({nodes:nodeIndices});return this.json.scenes.length-1;}addNode(node){var{meshIndex,matrix}=node;this.json.nodes=this.json.nodes||[];var nodeData={mesh:meshIndex};if(matrix){nodeData.matrix=matrix;}this.json.nodes.push(nodeData);return this.json.nodes.length-1;}addMesh(mesh){var{attributes,indices,material,mode=4}=mesh;var accessors=this._addAttributes(attributes);var glTFMesh={primitives:[{attributes:accessors,mode}]};if(indices){var indicesAccessor=this._addIndices(indices);glTFMesh.primitives[0].indices=indicesAccessor;}if(Number.isFinite(material)){glTFMesh.primitives[0].material=material;}this.json.meshes=this.json.meshes||[];this.json.meshes.push(glTFMesh);return this.json.meshes.length-1;}addPointCloud(attributes){var accessorIndices=this._addAttributes(attributes);var glTFMesh={primitives:[{attributes:accessorIndices,mode:0}]};this.json.meshes=this.json.meshes||[];this.json.meshes.push(glTFMesh);return this.json.meshes.length-1;}addImage(imageData,mimeTypeOpt){var metadata=getBinaryImageMetadata(imageData);var mimeType=mimeTypeOpt||(metadata===null||metadata===void 0?void 0:metadata.mimeType);var bufferViewIndex=this.addBufferView(imageData);var glTFImage={bufferView:bufferViewIndex,mimeType};this.json.images=this.json.images||[];this.json.images.push(glTFImage);return this.json.images.length-1;}addBufferView(buffer){var byteLength=buffer.byteLength;assert$1(Number.isFinite(byteLength));this.sourceBuffers=this.sourceBuffers||[];this.sourceBuffers.push(buffer);var glTFBufferView={buffer:0,byteOffset:this.byteLength,byteLength};this.byteLength+=padToNBytes(byteLength,4);this.json.bufferViews=this.json.bufferViews||[];this.json.bufferViews.push(glTFBufferView);return this.json.bufferViews.length-1;}addAccessor(bufferViewIndex,accessor){var glTFAccessor={bufferView:bufferViewIndex,type:getAccessorTypeFromSize(accessor.size),componentType:accessor.componentType,count:accessor.count,max:accessor.max,min:accessor.min};this.json.accessors=this.json.accessors||[];this.json.accessors.push(glTFAccessor);return this.json.accessors.length-1;}addBinaryBuffer(sourceBuffer){var accessor=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{size:3};var bufferViewIndex=this.addBufferView(sourceBuffer);var minMax={min:accessor.min,max:accessor.max};if(!minMax.min||!minMax.max){minMax=this._getAccessorMinMax(sourceBuffer,accessor.size);}var accessorDefaults={size:accessor.size,componentType:getComponentTypeFromArray(sourceBuffer),count:Math.round(sourceBuffer.length/accessor.size),min:minMax.min,max:minMax.max};return this.addAccessor(bufferViewIndex,Object.assign(accessorDefaults,accessor));}addTexture(texture){var{imageIndex}=texture;var glTFTexture={source:imageIndex};this.json.textures=this.json.textures||[];this.json.textures.push(glTFTexture);return this.json.textures.length-1;}addMaterial(pbrMaterialInfo){this.json.materials=this.json.materials||[];this.json.materials.push(pbrMaterialInfo);return this.json.materials.length-1;}createBinaryChunk(){var _this$json,_this$json$buffers;this.gltf.buffers=[];var totalByteLength=this.byteLength;var arrayBuffer=new ArrayBuffer(totalByteLength);var targetArray=new Uint8Array(arrayBuffer);var dstByteOffset=0;for(var sourceBuffer of this.sourceBuffers||[]){dstByteOffset=copyToArray(sourceBuffer,targetArray,dstByteOffset);}if((_this$json=this.json)!==null&&_this$json!==void 0&&(_this$json$buffers=_this$json.buffers)!==null&&_this$json$buffers!==void 0&&_this$json$buffers[0]){this.json.buffers[0].byteLength=totalByteLength;}else {this.json.buffers=[{byteLength:totalByteLength}];}this.gltf.binary=arrayBuffer;this.sourceBuffers=[arrayBuffer];}_removeStringFromArray(array,string){var found=true;while(found){var index=array.indexOf(string);if(index>-1){array.splice(index,1);}else {found=false;}}}_addAttributes(){var attributes=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var result={};for(var attributeKey in attributes){var attributeData=attributes[attributeKey];var attrName=this._getGltfAttributeName(attributeKey);var accessor=this.addBinaryBuffer(attributeData.value,attributeData);result[attrName]=accessor;}return result;}_addIndices(indices){return this.addBinaryBuffer(indices,{size:1});}_getGltfAttributeName(attributeName){switch(attributeName.toLowerCase()){case'position':case'positions':case'vertices':return 'POSITION';case'normal':case'normals':return 'NORMAL';case'color':case'colors':return 'COLOR_0';case'texcoord':case'texcoords':return 'TEXCOORD_0';default:return attributeName;}}_getAccessorMinMax(buffer,size){var result={min:null,max:null};if(buffer.length5&&arguments[5]!==undefined?arguments[5]:'NONE';var instance=await loadWasmInstance();decode$5(instance,instance.exports[DECODERS[mode]],target,count,size,source,instance.exports[FILTERS[filter||'NONE']]);}var wasmPromise;async function loadWasmInstance(){if(!wasmPromise){wasmPromise=loadWasmModule();}return wasmPromise;}async function loadWasmModule(){var wasm=wasm_base;if(WebAssembly.validate(detector)){wasm=wasm_simd;console.log('Warning: meshopt_decoder is using experimental SIMD support');}var result=await WebAssembly.instantiate(unpack(wasm),{});await result.instance.exports.__wasm_call_ctors();return result.instance;}function unpack(data){var result=new Uint8Array(data.length);for(var _i50=0;_i5096?ch-71:ch>64?ch-65:ch>47?ch+4:ch>46?63:62;}var write=0;for(var _i51=0;_i512&&arguments[2]!==undefined?arguments[2]:false;if(!array){return null;}if(Array.isArray(array)){return new ArrayType(array);}if(convertTypedArrays&&!(array instanceof ArrayType)){return new ArrayType(array);}return array;}var KHR_DRACO_MESH_COMPRESSION='KHR_draco_mesh_compression';var name$3=KHR_DRACO_MESH_COMPRESSION;function preprocess$1(gltfData,options,context){var scenegraph=new GLTFScenegraph(gltfData);for(var primitive of makeMeshPrimitiveIterator(scenegraph)){if(scenegraph.getObjectExtension(primitive,KHR_DRACO_MESH_COMPRESSION));}}async function decode$3(gltfData,options,context){var _options$gltf;if(!(options!==null&&options!==void 0&&(_options$gltf=options.gltf)!==null&&_options$gltf!==void 0&&_options$gltf.decompressMeshes)){return;}var scenegraph=new GLTFScenegraph(gltfData);var promises=[];for(var primitive of makeMeshPrimitiveIterator(scenegraph)){if(scenegraph.getObjectExtension(primitive,KHR_DRACO_MESH_COMPRESSION)){promises.push(decompressPrimitive(scenegraph,primitive,options,context));}}await Promise.all(promises);scenegraph.removeExtension(KHR_DRACO_MESH_COMPRESSION);}function encode$3(gltfData){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var scenegraph=new GLTFScenegraph(gltfData);for(var mesh of scenegraph.json.meshes||[]){compressMesh(mesh);scenegraph.addRequiredExtension(KHR_DRACO_MESH_COMPRESSION);}}async function decompressPrimitive(scenegraph,primitive,options,context){var dracoExtension=scenegraph.getObjectExtension(primitive,KHR_DRACO_MESH_COMPRESSION);if(!dracoExtension){return;}var buffer=scenegraph.getTypedArrayForBufferView(dracoExtension.bufferView);var bufferCopy=sliceArrayBuffer(buffer.buffer,buffer.byteOffset);var{parse}=context;var dracoOptions=_objectSpread2({},options);delete dracoOptions['3d-tiles'];var decodedData=await parse(bufferCopy,DracoLoader,dracoOptions,context);var decodedAttributes=getGLTFAccessors(decodedData.attributes);for(var[attributeName,decodedAttribute]of Object.entries(decodedAttributes)){if(attributeName in primitive.attributes){var accessorIndex=primitive.attributes[attributeName];var accessor=scenegraph.getAccessor(accessorIndex);if(accessor!==null&&accessor!==void 0&&accessor.min&&accessor!==null&&accessor!==void 0&&accessor.max){decodedAttribute.min=accessor.min;decodedAttribute.max=accessor.max;}}}primitive.attributes=decodedAttributes;if(decodedData.indices){primitive.indices=getGLTFAccessor(decodedData.indices);}checkPrimitive(primitive);}function compressMesh(attributes,indices){var mode=arguments.length>2&&arguments[2]!==undefined?arguments[2]:4;var options=arguments.length>3?arguments[3]:undefined;var context=arguments.length>4?arguments[4]:undefined;var _context$parseSync;if(!options.DracoWriter){throw new Error('options.gltf.DracoWriter not provided');}var compressedData=options.DracoWriter.encodeSync({attributes});var decodedData=context===null||context===void 0?void 0:(_context$parseSync=context.parseSync)===null||_context$parseSync===void 0?void 0:_context$parseSync.call(context,{attributes});var fauxAccessors=options._addFauxAttributes(decodedData.attributes);var bufferViewIndex=options.addBufferView(compressedData);var glTFMesh={primitives:[{attributes:fauxAccessors,mode,extensions:{[KHR_DRACO_MESH_COMPRESSION]:{bufferView:bufferViewIndex,attributes:fauxAccessors}}}]};return glTFMesh;}function checkPrimitive(primitive){if(!primitive.attributes&&Object.keys(primitive.attributes).length>0){throw new Error('glTF: Empty primitive detected: Draco decompression failure?');}}function*makeMeshPrimitiveIterator(scenegraph){for(var mesh of scenegraph.json.meshes||[]){for(var primitive of mesh.primitives){yield primitive;}}}var KHR_draco_mesh_compression=/*#__PURE__*/Object.freeze({__proto__:null,name:name$3,preprocess:preprocess$1,decode:decode$3,encode:encode$3});var KHR_LIGHTS_PUNCTUAL='KHR_lights_punctual';var name$2=KHR_LIGHTS_PUNCTUAL;async function decode$2(gltfData){var gltfScenegraph=new GLTFScenegraph(gltfData);var{json}=gltfScenegraph;var extension=gltfScenegraph.getExtension(KHR_LIGHTS_PUNCTUAL);if(extension){gltfScenegraph.json.lights=extension.lights;gltfScenegraph.removeExtension(KHR_LIGHTS_PUNCTUAL);}for(var _node of json.nodes||[]){var nodeExtension=gltfScenegraph.getObjectExtension(_node,KHR_LIGHTS_PUNCTUAL);if(nodeExtension){_node.light=nodeExtension.light;}gltfScenegraph.removeObjectExtension(_node,KHR_LIGHTS_PUNCTUAL);}}async function encode$2(gltfData){var gltfScenegraph=new GLTFScenegraph(gltfData);var{json}=gltfScenegraph;if(json.lights){var extension=gltfScenegraph.addExtension(KHR_LIGHTS_PUNCTUAL);assert$1(!extension.lights);extension.lights=json.lights;delete json.lights;}if(gltfScenegraph.json.lights){for(var light of gltfScenegraph.json.lights){var _node2=light.node;gltfScenegraph.addObjectExtension(_node2,KHR_LIGHTS_PUNCTUAL,light);}delete gltfScenegraph.json.lights;}}var KHR_lights_punctual=/*#__PURE__*/Object.freeze({__proto__:null,name:name$2,decode:decode$2,encode:encode$2});var KHR_MATERIALS_UNLIT='KHR_materials_unlit';var name$1=KHR_MATERIALS_UNLIT;async function decode$1(gltfData){var gltfScenegraph=new GLTFScenegraph(gltfData);var{json}=gltfScenegraph;gltfScenegraph.removeExtension(KHR_MATERIALS_UNLIT);for(var material of json.materials||[]){var extension=material.extensions&&material.extensions.KHR_materials_unlit;if(extension){material.unlit=true;}gltfScenegraph.removeObjectExtension(material,KHR_MATERIALS_UNLIT);}}function encode$1(gltfData){var gltfScenegraph=new GLTFScenegraph(gltfData);var{json}=gltfScenegraph;if(gltfScenegraph.materials){for(var material of json.materials||[]){if(material.unlit){delete material.unlit;gltfScenegraph.addObjectExtension(material,KHR_MATERIALS_UNLIT,{});gltfScenegraph.addExtension(KHR_MATERIALS_UNLIT);}}}}var KHR_materials_unlit=/*#__PURE__*/Object.freeze({__proto__:null,name:name$1,decode:decode$1,encode:encode$1});var KHR_TECHNIQUES_WEBGL='KHR_techniques_webgl';var name$7=KHR_TECHNIQUES_WEBGL;async function decode(gltfData){var gltfScenegraph=new GLTFScenegraph(gltfData);var{json}=gltfScenegraph;var extension=gltfScenegraph.getExtension(KHR_TECHNIQUES_WEBGL);if(extension){var techniques=resolveTechniques(extension,gltfScenegraph);for(var material of json.materials||[]){var materialExtension=gltfScenegraph.getObjectExtension(material,KHR_TECHNIQUES_WEBGL);if(materialExtension){material.technique=Object.assign({},materialExtension,techniques[materialExtension.technique]);material.technique.values=resolveValues(material.technique,gltfScenegraph);}gltfScenegraph.removeObjectExtension(material,KHR_TECHNIQUES_WEBGL);}gltfScenegraph.removeExtension(KHR_TECHNIQUES_WEBGL);}}async function encode(gltfData,options){}function resolveTechniques(techniquesExtension,gltfScenegraph){var{programs=[],shaders=[],techniques=[]}=techniquesExtension;var textDecoder=new TextDecoder();shaders.forEach(shader=>{if(Number.isFinite(shader.bufferView)){shader.code=textDecoder.decode(gltfScenegraph.getTypedArrayForBufferView(shader.bufferView));}else {throw new Error('KHR_techniques_webgl: no shader code');}});programs.forEach(program=>{program.fragmentShader=shaders[program.fragmentShader];program.vertexShader=shaders[program.vertexShader];});techniques.forEach(technique=>{technique.program=programs[technique.program];});return techniques;}function resolveValues(technique,gltfScenegraph){var values=Object.assign({},technique.values);Object.keys(technique.uniforms||{}).forEach(uniform=>{if(technique.uniforms[uniform].value&&!(uniform in values)){values[uniform]=technique.uniforms[uniform].value;}});Object.keys(values).forEach(uniform=>{if(typeof values[uniform]==='object'&&values[uniform].index!==undefined){values[uniform].texture=gltfScenegraph.getTexture(values[uniform].index);}});return values;}var KHR_techniques_webgl=/*#__PURE__*/Object.freeze({__proto__:null,name:name$7,decode:decode,encode:encode});var EXTENSIONS$2=[EXT_meshopt_compression,EXT_texture_webp,KHR_texture_basisu,KHR_draco_mesh_compression,KHR_lights_punctual,KHR_materials_unlit,KHR_techniques_webgl];function preprocessExtensions(gltf){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var context=arguments.length>2?arguments[2]:undefined;var extensions=EXTENSIONS$2.filter(extension=>useExtension(extension.name,options));for(var extension of extensions){var _extension$preprocess;(_extension$preprocess=extension.preprocess)===null||_extension$preprocess===void 0?void 0:_extension$preprocess.call(extension,gltf,options,context);}}async function decodeExtensions(gltf){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var context=arguments.length>2?arguments[2]:undefined;var extensions=EXTENSIONS$2.filter(extension=>useExtension(extension.name,options));for(var extension of extensions){var _extension$decode;await((_extension$decode=extension.decode)===null||_extension$decode===void 0?void 0:_extension$decode.call(extension,gltf,options,context));}}function useExtension(extensionName,options){var _options$gltf;var excludes=(options===null||options===void 0?void 0:(_options$gltf=options.gltf)===null||_options$gltf===void 0?void 0:_options$gltf.excludeExtensions)||{};var exclude=extensionName in excludes&&!excludes[extensionName];return !exclude;}var KHR_BINARY_GLTF='KHR_binary_glTF';function preprocess(gltfData){var gltfScenegraph=new GLTFScenegraph(gltfData);var{json}=gltfScenegraph;for(var image of json.images||[]){var extension=gltfScenegraph.getObjectExtension(image,KHR_BINARY_GLTF);if(extension){Object.assign(image,extension);}gltfScenegraph.removeObjectExtension(image,KHR_BINARY_GLTF);}if(json.buffers&&json.buffers[0]){delete json.buffers[0].uri;}gltfScenegraph.removeExtension(KHR_BINARY_GLTF);}var GLTF_ARRAYS={accessors:'accessor',animations:'animation',buffers:'buffer',bufferViews:'bufferView',images:'image',materials:'material',meshes:'mesh',nodes:'node',samplers:'sampler',scenes:'scene',skins:'skin',textures:'texture'};var GLTF_KEYS={accessor:'accessors',animations:'animation',buffer:'buffers',bufferView:'bufferViews',image:'images',material:'materials',mesh:'meshes',node:'nodes',sampler:'samplers',scene:'scenes',skin:'skins',texture:'textures'};class GLTFV1Normalizer{constructor(){_defineProperty$1(this,"idToIndexMap",{animations:{},accessors:{},buffers:{},bufferViews:{},images:{},materials:{},meshes:{},nodes:{},samplers:{},scenes:{},skins:{},textures:{}});_defineProperty$1(this,"json",void 0);}normalize(gltf,options){this.json=gltf.json;var json=gltf.json;switch(json.asset&&json.asset.version){case'2.0':return;case undefined:case'1.0':break;default:console.warn("glTF: Unknown version ".concat(json.asset.version));return;}if(!options.normalize){throw new Error('glTF v1 is not supported.');}console.warn('Converting glTF v1 to glTF v2 format. This is experimental and may fail.');this._addAsset(json);this._convertTopLevelObjectsToArrays(json);preprocess(gltf);this._convertObjectIdsToArrayIndices(json);this._updateObjects(json);this._updateMaterial(json);}_addAsset(json){json.asset=json.asset||{};json.asset.version='2.0';json.asset.generator=json.asset.generator||'Normalized to glTF 2.0 by loaders.gl';}_convertTopLevelObjectsToArrays(json){for(var arrayName in GLTF_ARRAYS){this._convertTopLevelObjectToArray(json,arrayName);}}_convertTopLevelObjectToArray(json,mapName){var objectMap=json[mapName];if(!objectMap||Array.isArray(objectMap)){return;}json[mapName]=[];for(var id in objectMap){var object=objectMap[id];object.id=object.id||id;var index=json[mapName].length;json[mapName].push(object);this.idToIndexMap[mapName][id]=index;}}_convertObjectIdsToArrayIndices(json){for(var arrayName in GLTF_ARRAYS){this._convertIdsToIndices(json,arrayName);}if('scene'in json){json.scene=this._convertIdToIndex(json.scene,'scene');}for(var texture of json.textures){this._convertTextureIds(texture);}for(var mesh of json.meshes){this._convertMeshIds(mesh);}for(var _node3 of json.nodes){this._convertNodeIds(_node3);}for(var _node4 of json.scenes){this._convertSceneIds(_node4);}}_convertTextureIds(texture){if(texture.source){texture.source=this._convertIdToIndex(texture.source,'image');}}_convertMeshIds(mesh){for(var primitive of mesh.primitives){var{attributes,indices,material}=primitive;for(var attributeName in attributes){attributes[attributeName]=this._convertIdToIndex(attributes[attributeName],'accessor');}if(indices){primitive.indices=this._convertIdToIndex(indices,'accessor');}if(material){primitive.material=this._convertIdToIndex(material,'material');}}}_convertNodeIds(node){if(node.children){node.children=node.children.map(child=>this._convertIdToIndex(child,'node'));}if(node.meshes){node.meshes=node.meshes.map(mesh=>this._convertIdToIndex(mesh,'mesh'));}}_convertSceneIds(scene){if(scene.nodes){scene.nodes=scene.nodes.map(node=>this._convertIdToIndex(node,'node'));}}_convertIdsToIndices(json,topLevelArrayName){if(!json[topLevelArrayName]){console.warn("gltf v1: json doesn't contain attribute ".concat(topLevelArrayName));json[topLevelArrayName]=[];}for(var object of json[topLevelArrayName]){for(var key in object){var id=object[key];var index=this._convertIdToIndex(id,key);object[key]=index;}}}_convertIdToIndex(id,key){var arrayName=GLTF_KEYS[key];if(arrayName in this.idToIndexMap){var index=this.idToIndexMap[arrayName][id];if(!Number.isFinite(index)){throw new Error("gltf v1: failed to resolve ".concat(key," with id ").concat(id));}return index;}return id;}_updateObjects(json){for(var buffer of this.json.buffers){delete buffer.type;}}_updateMaterial(json){var _loop3=function _loop3(){material.pbrMetallicRoughness={baseColorFactor:[1,1,1,1],metallicFactor:1,roughnessFactor:1};var textureId=material.values&&material.values.tex;var textureIndex=json.textures.findIndex(texture=>texture.id===textureId);if(textureIndex!==-1){material.pbrMetallicRoughness.baseColorTexture={index:textureIndex};}};for(var material of json.materials){_loop3();}}}function normalizeGLTFV1(gltf){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};return new GLTFV1Normalizer().normalize(gltf,options);}var COMPONENTS={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16};var BYTES={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};var GL_SAMPLER={TEXTURE_MAG_FILTER:0x2800,TEXTURE_MIN_FILTER:0x2801,TEXTURE_WRAP_S:0x2802,TEXTURE_WRAP_T:0x2803,REPEAT:0x2901,LINEAR:0x2601,NEAREST_MIPMAP_LINEAR:0x2702};var SAMPLER_PARAMETER_GLTF_TO_GL={magFilter:GL_SAMPLER.TEXTURE_MAG_FILTER,minFilter:GL_SAMPLER.TEXTURE_MIN_FILTER,wrapS:GL_SAMPLER.TEXTURE_WRAP_S,wrapT:GL_SAMPLER.TEXTURE_WRAP_T};var DEFAULT_SAMPLER={[GL_SAMPLER.TEXTURE_MAG_FILTER]:GL_SAMPLER.LINEAR,[GL_SAMPLER.TEXTURE_MIN_FILTER]:GL_SAMPLER.NEAREST_MIPMAP_LINEAR,[GL_SAMPLER.TEXTURE_WRAP_S]:GL_SAMPLER.REPEAT,[GL_SAMPLER.TEXTURE_WRAP_T]:GL_SAMPLER.REPEAT};function getBytesFromComponentType(componentType){return BYTES[componentType];}function getSizeFromAccessorType(type){return COMPONENTS[type];}class GLTFPostProcessor{constructor(){_defineProperty$1(this,"baseUri",'');_defineProperty$1(this,"json",{});_defineProperty$1(this,"buffers",[]);_defineProperty$1(this,"images",[]);}postProcess(gltf){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var{json,buffers=[],images=[],baseUri=''}=gltf;assert$1(json);this.baseUri=baseUri;this.json=json;this.buffers=buffers;this.images=images;this._resolveTree(this.json,options);return this.json;}_resolveTree(json){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(json.bufferViews){json.bufferViews=json.bufferViews.map((bufView,i)=>this._resolveBufferView(bufView,i));}if(json.images){json.images=json.images.map((image,i)=>this._resolveImage(image,i));}if(json.samplers){json.samplers=json.samplers.map((sampler,i)=>this._resolveSampler(sampler,i));}if(json.textures){json.textures=json.textures.map((texture,i)=>this._resolveTexture(texture,i));}if(json.accessors){json.accessors=json.accessors.map((accessor,i)=>this._resolveAccessor(accessor,i));}if(json.materials){json.materials=json.materials.map((material,i)=>this._resolveMaterial(material,i));}if(json.meshes){json.meshes=json.meshes.map((mesh,i)=>this._resolveMesh(mesh,i));}if(json.nodes){json.nodes=json.nodes.map((node,i)=>this._resolveNode(node,i));}if(json.skins){json.skins=json.skins.map((skin,i)=>this._resolveSkin(skin,i));}if(json.scenes){json.scenes=json.scenes.map((scene,i)=>this._resolveScene(scene,i));}if(json.scene!==undefined){json.scene=json.scenes[this.json.scene];}}getScene(index){return this._get('scenes',index);}getNode(index){return this._get('nodes',index);}getSkin(index){return this._get('skins',index);}getMesh(index){return this._get('meshes',index);}getMaterial(index){return this._get('materials',index);}getAccessor(index){return this._get('accessors',index);}getCamera(index){return null;}getTexture(index){return this._get('textures',index);}getSampler(index){return this._get('samplers',index);}getImage(index){return this._get('images',index);}getBufferView(index){return this._get('bufferViews',index);}getBuffer(index){return this._get('buffers',index);}_get(array,index){if(typeof index==='object'){return index;}var object=this.json[array]&&this.json[array][index];if(!object){console.warn("glTF file error: Could not find ".concat(array,"[").concat(index,"]"));}return object;}_resolveScene(scene,index){scene.id=scene.id||"scene-".concat(index);scene.nodes=(scene.nodes||[]).map(node=>this.getNode(node));return scene;}_resolveNode(node,index){node.id=node.id||"node-".concat(index);if(node.children){node.children=node.children.map(child=>this.getNode(child));}if(node.mesh!==undefined){node.mesh=this.getMesh(node.mesh);}else if(node.meshes!==undefined&&node.meshes.length){node.mesh=node.meshes.reduce((accum,meshIndex)=>{var mesh=this.getMesh(meshIndex);accum.id=mesh.id;accum.primitives=accum.primitives.concat(mesh.primitives);return accum;},{primitives:[]});}if(node.camera!==undefined){node.camera=this.getCamera(node.camera);}if(node.skin!==undefined){node.skin=this.getSkin(node.skin);}return node;}_resolveSkin(skin,index){skin.id=skin.id||"skin-".concat(index);skin.inverseBindMatrices=this.getAccessor(skin.inverseBindMatrices);return skin;}_resolveMesh(mesh,index){mesh.id=mesh.id||"mesh-".concat(index);if(mesh.primitives){mesh.primitives=mesh.primitives.map(primitive=>{primitive=_objectSpread2({},primitive);var attributes=primitive.attributes;primitive.attributes={};for(var attribute in attributes){primitive.attributes[attribute]=this.getAccessor(attributes[attribute]);}if(primitive.indices!==undefined){primitive.indices=this.getAccessor(primitive.indices);}if(primitive.material!==undefined){primitive.material=this.getMaterial(primitive.material);}return primitive;});}return mesh;}_resolveMaterial(material,index){material.id=material.id||"material-".concat(index);if(material.normalTexture){material.normalTexture=_objectSpread2({},material.normalTexture);material.normalTexture.texture=this.getTexture(material.normalTexture.index);}if(material.occlusionTexture){material.occlustionTexture=_objectSpread2({},material.occlustionTexture);material.occlusionTexture.texture=this.getTexture(material.occlusionTexture.index);}if(material.emissiveTexture){material.emmisiveTexture=_objectSpread2({},material.emmisiveTexture);material.emissiveTexture.texture=this.getTexture(material.emissiveTexture.index);}if(!material.emissiveFactor){material.emissiveFactor=material.emmisiveTexture?[1,1,1]:[0,0,0];}if(material.pbrMetallicRoughness){material.pbrMetallicRoughness=_objectSpread2({},material.pbrMetallicRoughness);var mr=material.pbrMetallicRoughness;if(mr.baseColorTexture){mr.baseColorTexture=_objectSpread2({},mr.baseColorTexture);mr.baseColorTexture.texture=this.getTexture(mr.baseColorTexture.index);}if(mr.metallicRoughnessTexture){mr.metallicRoughnessTexture=_objectSpread2({},mr.metallicRoughnessTexture);mr.metallicRoughnessTexture.texture=this.getTexture(mr.metallicRoughnessTexture.index);}}return material;}_resolveAccessor(accessor,index){accessor.id=accessor.id||"accessor-".concat(index);if(accessor.bufferView!==undefined){accessor.bufferView=this.getBufferView(accessor.bufferView);}accessor.bytesPerComponent=getBytesFromComponentType(accessor.componentType);accessor.components=getSizeFromAccessorType(accessor.type);accessor.bytesPerElement=accessor.bytesPerComponent*accessor.components;if(accessor.bufferView){var buffer=accessor.bufferView.buffer;var{ArrayType,byteLength}=getAccessorArrayTypeAndLength(accessor,accessor.bufferView);var byteOffset=(accessor.bufferView.byteOffset||0)+(accessor.byteOffset||0)+buffer.byteOffset;var cutBuffer=buffer.arrayBuffer.slice(byteOffset,byteOffset+byteLength);if(accessor.bufferView.byteStride){cutBuffer=this._getValueFromInterleavedBuffer(buffer,byteOffset,accessor.bufferView.byteStride,accessor.bytesPerElement,accessor.count);}accessor.value=new ArrayType(cutBuffer);}return accessor;}_getValueFromInterleavedBuffer(buffer,byteOffset,byteStride,bytesPerElement,count){var result=new Uint8Array(count*bytesPerElement);for(var _i52=0;_i521&&arguments[1]!==undefined?arguments[1]:0;return "".concat(String.fromCharCode(dataView.getUint8(byteOffset+0))).concat(String.fromCharCode(dataView.getUint8(byteOffset+1))).concat(String.fromCharCode(dataView.getUint8(byteOffset+2))).concat(String.fromCharCode(dataView.getUint8(byteOffset+3)));}function isGLB(arrayBuffer){var byteOffset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var dataView=new DataView(arrayBuffer);var{magic=MAGIC_glTF}=options;var magic1=dataView.getUint32(byteOffset,false);return magic1===magic||magic1===MAGIC_glTF;}function parseGLBSync(glb,arrayBuffer){var byteOffset=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var options=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{};var dataView=new DataView(arrayBuffer);var type=getMagicString(dataView,byteOffset+0);var version=dataView.getUint32(byteOffset+4,LE);var byteLength=dataView.getUint32(byteOffset+8,LE);Object.assign(glb,{header:{byteOffset,byteLength,hasBinChunk:false},type,version,json:{},binChunks:[]});byteOffset+=GLB_FILE_HEADER_SIZE;switch(glb.version){case 1:return parseGLBV1(glb,dataView,byteOffset);case 2:return parseGLBV2(glb,dataView,byteOffset,options={});default:throw new Error("Invalid GLB version ".concat(glb.version,". Only supports v1 and v2."));}}function parseGLBV1(glb,dataView,byteOffset){assert$7(glb.header.byteLength>GLB_FILE_HEADER_SIZE+GLB_CHUNK_HEADER_SIZE);var contentLength=dataView.getUint32(byteOffset+0,LE);var contentFormat=dataView.getUint32(byteOffset+4,LE);byteOffset+=GLB_CHUNK_HEADER_SIZE;assert$7(contentFormat===GLB_V1_CONTENT_FORMAT_JSON);parseJSONChunk(glb,dataView,byteOffset,contentLength);byteOffset+=contentLength;byteOffset+=parseBINChunk(glb,dataView,byteOffset,glb.header.byteLength);return byteOffset;}function parseGLBV2(glb,dataView,byteOffset,options){assert$7(glb.header.byteLength>GLB_FILE_HEADER_SIZE+GLB_CHUNK_HEADER_SIZE);parseGLBChunksSync(glb,dataView,byteOffset,options);return byteOffset+glb.header.byteLength;}function parseGLBChunksSync(glb,dataView,byteOffset,options){while(byteOffset+8<=glb.header.byteLength){var chunkLength=dataView.getUint32(byteOffset+0,LE);var chunkFormat=dataView.getUint32(byteOffset+4,LE);byteOffset+=GLB_CHUNK_HEADER_SIZE;switch(chunkFormat){case GLB_CHUNK_TYPE_JSON:parseJSONChunk(glb,dataView,byteOffset,chunkLength);break;case GLB_CHUNK_TYPE_BIN:parseBINChunk(glb,dataView,byteOffset,chunkLength);break;case GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED:if(!options.strict){parseJSONChunk(glb,dataView,byteOffset,chunkLength);}break;case GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED:if(!options.strict){parseBINChunk(glb,dataView,byteOffset,chunkLength);}break;}byteOffset+=padToNBytes(chunkLength,4);}return byteOffset;}function parseJSONChunk(glb,dataView,byteOffset,chunkLength){var jsonChunk=new Uint8Array(dataView.buffer,byteOffset,chunkLength);var textDecoder=new TextDecoder('utf8');var jsonText=textDecoder.decode(jsonChunk);glb.json=JSON.parse(jsonText);return padToNBytes(chunkLength,4);}function parseBINChunk(glb,dataView,byteOffset,chunkLength){glb.header.hasBinChunk=true;glb.binChunks.push({byteOffset,byteLength:chunkLength,arrayBuffer:dataView.buffer});return padToNBytes(chunkLength,4);}async function parseGLTF(gltf,arrayBufferOrString){var byteOffset=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var options=arguments.length>3?arguments[3]:undefined;var context=arguments.length>4?arguments[4]:undefined;var _options$gltf,_options$gltf2,_options$gltf3,_options$gltf4;parseGLTFContainerSync(gltf,arrayBufferOrString,byteOffset,options);normalizeGLTFV1(gltf,{normalize:options===null||options===void 0?void 0:(_options$gltf=options.gltf)===null||_options$gltf===void 0?void 0:_options$gltf.normalize});preprocessExtensions(gltf,options,context);var promises=[];if(options!==null&&options!==void 0&&(_options$gltf2=options.gltf)!==null&&_options$gltf2!==void 0&&_options$gltf2.loadBuffers&&gltf.json.buffers){await loadBuffers(gltf,options,context);}if(options!==null&&options!==void 0&&(_options$gltf3=options.gltf)!==null&&_options$gltf3!==void 0&&_options$gltf3.loadImages){var _promise=loadImages(gltf,options,context);promises.push(_promise);}var promise=decodeExtensions(gltf,options,context);promises.push(promise);await Promise.all(promises);gltf.json.gltfArrayBuffer=arrayBufferOrString;// !zeg add 兼容gltf return options!==null&&options!==void 0&&(_options$gltf4=options.gltf)!==null&&_options$gltf4!==void 0&&_options$gltf4.postProcess?postProcessGLTF(gltf,options):gltf;}function parseGLTFContainerSync(gltf,data,byteOffset,options){if(options.uri){gltf.baseUri=options.uri;}if(data instanceof ArrayBuffer&&!isGLB(data,byteOffset,options)){var textDecoder=new TextDecoder();data=textDecoder.decode(data);}if(typeof data==='string'){gltf.json=parseJSON(data);}else if(data instanceof ArrayBuffer){var glb={};byteOffset=parseGLBSync(glb,data,byteOffset,options.glb);assert$1(glb.type==='glTF',"Invalid GLB magic string ".concat(glb.type));gltf._glb=glb;gltf.json=glb.json;}else {assert$1(false,'GLTF: must be ArrayBuffer or string');}var buffers=gltf.json.buffers||[];gltf.buffers=new Array(buffers.length).fill(null);if(gltf._glb&&gltf._glb.header.hasBinChunk){var{binChunks}=gltf._glb;gltf.buffers[0]={arrayBuffer:binChunks[0].arrayBuffer,byteOffset:binChunks[0].byteOffset,byteLength:binChunks[0].byteLength};}var images=gltf.json.images||[];gltf.images=new Array(images.length).fill({});}async function loadBuffers(gltf,options,context){var buffers=gltf.json.buffers||[];for(var _i53=0;_i531&&arguments[1]!==undefined?arguments[1]:{};var context=arguments.length>2?arguments[2]:undefined;options=_objectSpread2(_objectSpread2({},GLTFLoader$1.options),options);options.gltf=_objectSpread2(_objectSpread2({},GLTFLoader$1.options.gltf),options.gltf);var{byteOffset=0}=options;var gltf={};return await parseGLTF(gltf,arrayBuffer,byteOffset,options,context);}var GLTF_FORMAT={URI:0,EMBEDDED:1};function parse3DTileGLTFViewSync(tile,arrayBuffer,byteOffset,options){tile.rotateYtoZ=true;var gltfByteLength=tile.byteOffset+tile.byteLength-byteOffset;if(gltfByteLength===0){throw new Error('glTF byte length must be greater than 0.');}tile.gltfUpAxis=options['3d-tiles']&&options['3d-tiles'].assetGltfUpAxis?options['3d-tiles'].assetGltfUpAxis:'Y';tile.gltfArrayBuffer=sliceArrayBuffer(arrayBuffer,byteOffset,gltfByteLength);tile.gltfByteOffset=0;tile.gltfByteLength=gltfByteLength;if(byteOffset%4===0);else {console.warn("".concat(tile.type,": embedded glb is not aligned to a 4-byte boundary."));}return tile.byteOffset+tile.byteLength;}async function extractGLTF(tile,gltfFormat,options,context){var tile3DOptions=options['3d-tiles']||{};extractGLTFBufferOrURL(tile,gltfFormat);if(tile3DOptions.loadGLTF){var{parse:_parse,fetch:_fetch2}=context;if(tile.gltfUrl){tile.gltfArrayBuffer=await _fetch2(tile.gltfUrl,options);tile.gltfByteOffset=0;}if(tile.gltfArrayBuffer){tile.gltf=await _parse(tile.gltfArrayBuffer,GLTFLoader$1,options,context);delete tile.gltfArrayBuffer;delete tile.gltfByteOffset;delete tile.gltfByteLength;}}}function extractGLTFBufferOrURL(tile,gltfFormat,options){switch(gltfFormat){case GLTF_FORMAT.URI:var gltfUrlBytes=new Uint8Array(tile.gltfArrayBuffer,tile.gltfByteOffset);var textDecoder=new TextDecoder();var gltfUrl=textDecoder.decode(gltfUrlBytes);tile.gltfUrl=gltfUrl.replace(/[\s\0]+$/,'');delete tile.gltfArrayBuffer;delete tile.gltfByteOffset;delete tile.gltfByteLength;break;case GLTF_FORMAT.EMBEDDED:break;default:throw new Error('b3dm: Illegal glTF format field');}}async function parseBatchedModel3DTile(tile,arrayBuffer,byteOffset,options,context){var _tile$gltf;byteOffset=parseBatchedModel(tile,arrayBuffer,byteOffset,options);await extractGLTF(tile,GLTF_FORMAT.EMBEDDED,options,context);var extensions=tile===null||tile===void 0?void 0:(_tile$gltf=tile.gltf)===null||_tile$gltf===void 0?void 0:_tile$gltf.extensions;if(extensions&&extensions.CESIUM_RTC){tile.rtcCenter=extensions.CESIUM_RTC.center;}return byteOffset;}function parseBatchedModel(tile,arrayBuffer,byteOffset,options,context){byteOffset=parse3DTileHeaderSync(tile,arrayBuffer,byteOffset);byteOffset=parse3DTileTablesHeaderSync(tile,arrayBuffer,byteOffset);byteOffset=parse3DTileTablesSync(tile,arrayBuffer,byteOffset);byteOffset=parse3DTileGLTFViewSync(tile,arrayBuffer,byteOffset,options);var featureTable=new Tile3DFeatureTable(tile.featureTableJson,tile.featureTableBinary);tile.rtcCenter=featureTable.getGlobalProperty('RTC_CENTER',GL$1.FLOAT,3);return byteOffset;}async function parseInstancedModel3DTile(tile,arrayBuffer,byteOffset,options,context){byteOffset=parseInstancedModel(tile,arrayBuffer,byteOffset,options);await extractGLTF(tile,tile.gltfFormat,options,context);return byteOffset;}function parseInstancedModel(tile,arrayBuffer,byteOffset,options,context){byteOffset=parse3DTileHeaderSync(tile,arrayBuffer,byteOffset);if(tile.version!==1){throw new Error("Instanced 3D Model version ".concat(tile.version," is not supported"));}byteOffset=parse3DTileTablesHeaderSync(tile,arrayBuffer,byteOffset);var view=new DataView(arrayBuffer);tile.gltfFormat=view.getUint32(byteOffset,true);byteOffset+=4;byteOffset=parse3DTileTablesSync(tile,arrayBuffer,byteOffset);byteOffset=parse3DTileGLTFViewSync(tile,arrayBuffer,byteOffset,options);if(tile.featureTableJsonByteLength===0){throw new Error('i3dm parser: featureTableJsonByteLength is zero.');}var featureTable=new Tile3DFeatureTable(tile.featureTableJson,tile.featureTableBinary);var instancesLength=featureTable.getGlobalProperty('INSTANCES_LENGTH');featureTable.featuresLength=instancesLength;if(!Number.isFinite(instancesLength)){throw new Error('i3dm parser: INSTANCES_LENGTH must be defined');}tile.eastNorthUp=featureTable.getGlobalProperty('EAST_NORTH_UP');tile.rtcCenter=featureTable.getGlobalProperty('RTC_CENTER',GL$1.FLOAT,3);var batchTable=new Tile3DBatchTableParser(tile.batchTableJson,tile.batchTableBinary,instancesLength);extractInstancedAttributes(tile,featureTable,batchTable,instancesLength);return byteOffset;}function extractInstancedAttributes(tile,featureTable,batchTable,instancesLength){var collectionOptions={instances:new Array(instancesLength),batchTable:tile._batchTable,cull:false,url:undefined,gltf:undefined,basePath:undefined,incrementallyLoadTextures:false,forwardAxis:[1,0,0]};var instances=collectionOptions.instances;var instancePosition=new Vector3$1();new Vector3$1();new Vector3$1();new Vector3$1();var instanceRotation=new Matrix3$1();var instanceQuaternion=new Quaternion$1();var instanceScale=new Vector3$1();var instanceTranslationRotationScale={};var instanceTransform=new Matrix4$1();var scratch1=[];var scratch2=[];var scratchVector1=new Vector3$1();var scratchVector2=new Vector3$1();for(var _i54=0;_i5412){var subtile={};tile.tiles.push(subtile);byteOffset=await parse3DTile(arrayBuffer,byteOffset,options,context,subtile);}return byteOffset;}async function parseGltf3DTile(tile,arrayBuffer,options,context){tile.rotateYtoZ=true;tile.gltfUpAxis=options['3d-tiles']&&options['3d-tiles'].assetGltfUpAxis?options['3d-tiles'].assetGltfUpAxis:'Y';var{parse}=context;tile.gltf=await parse(arrayBuffer,GLTFLoader$1,options,context);}async function parse3DTile(arrayBuffer){var byteOffset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var options=arguments.length>2?arguments[2]:undefined;var context=arguments.length>3?arguments[3]:undefined;var tile=arguments.length>4&&arguments[4]!==undefined?arguments[4]:{};tile.byteOffset=byteOffset;tile.type=getMagicString$1(arrayBuffer,byteOffset);switch(tile.type){case TILE3D_TYPE.COMPOSITE:return await parseComposite3DTile(tile,arrayBuffer,byteOffset,options,context,parse3DTile);case TILE3D_TYPE.BATCHED_3D_MODEL:return await parseBatchedModel3DTile(tile,arrayBuffer,byteOffset,options,context);case TILE3D_TYPE.GLTF:return await parseGltf3DTile(tile,arrayBuffer,options,context);case TILE3D_TYPE.INSTANCED_3D_MODEL:return await parseInstancedModel3DTile(tile,arrayBuffer,byteOffset,options,context);case TILE3D_TYPE.POINT_CLOUD:return await parsePointCloud3DTile(tile,arrayBuffer,byteOffset,options,context);default:throw new Error("3DTileLoader: unknown type ".concat(tile.type));}}var SUBTREE_FILE_MAGIC=0x74627573;var SUBTREE_FILE_VERSION=1;async function parse3DTilesSubtree(data){var magic=new Uint32Array(data.slice(0,4));if(magic[0]!==SUBTREE_FILE_MAGIC){throw new Error('Wrong subtree file magic number');}var version=new Uint32Array(data.slice(4,8));if(version[0]!==SUBTREE_FILE_VERSION){throw new Error('Wrong subtree file verson, must be 1');}var jsonByteLength=parseUint64Value(data.slice(8,16));var stringAttribute=new Uint8Array(data,24,jsonByteLength);var textDecoder=new TextDecoder('utf8');var string=textDecoder.decode(stringAttribute);var subtree=JSON.parse(string);var binaryByteLength=parseUint64Value(data.slice(16,24));var internalBinaryBuffer=new ArrayBuffer(0);if(binaryByteLength){internalBinaryBuffer=data.slice(24+jsonByteLength);}if('bufferView'in subtree.tileAvailability){subtree.tileAvailability.explicitBitstream=await getExplicitBitstream(subtree,'tileAvailability',internalBinaryBuffer);}if('bufferView'in subtree.contentAvailability){subtree.contentAvailability.explicitBitstream=await getExplicitBitstream(subtree,'contentAvailability',internalBinaryBuffer);}if('bufferView'in subtree.childSubtreeAvailability){subtree.childSubtreeAvailability.explicitBitstream=await getExplicitBitstream(subtree,'childSubtreeAvailability',internalBinaryBuffer);}return subtree;}async function getExplicitBitstream(subtree,name,internalBinaryBuffer){var bufferViewIndex=subtree[name].bufferView;var bufferView=subtree.bufferViews[bufferViewIndex];var buffer=subtree.buffers[bufferView.buffer];if(buffer.uri){var response=await fetchFile(buffer.uri);var data=await response.arrayBuffer();return new Uint8Array(data,bufferView.byteOffset,bufferView.byteLength);}return new Uint8Array(internalBinaryBuffer,bufferView.byteOffset,bufferView.byteLength);}function parseUint64Value(buffer){var dataView=new DataView(buffer);var left=dataView.getUint32(0,true);var right=dataView.getUint32(4,true);return left+2**32*right;}var Tile3DSubtreeLoader={id:'3d-tiles-subtree',name:'3D Tiles Subtree',module:'3d-tiles',version:VERSION$5,extensions:['subtree'],mimeTypes:['application/octet-stream'],tests:['subtree'],parse:parse3DTilesSubtree,options:{}};var QUADTREE_DEVISION_COUNT=4;var OCTREE_DEVISION_COUNT=8;var SUBDIVISION_COUNT_MAP={QUADTREE:QUADTREE_DEVISION_COUNT,OCTREE:OCTREE_DEVISION_COUNT};async function parseImplicitTiles(subtree,options){var parentData=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{mortonIndex:0,x:0,y:0,z:0};var childIndex=arguments.length>3&&arguments[3]!==undefined?arguments[3]:0;var level=arguments.length>4&&arguments[4]!==undefined?arguments[4]:0;var globalData=arguments.length>5&&arguments[5]!==undefined?arguments[5]:{level:0,mortonIndex:0,x:0,y:0,z:0};var{subdivisionScheme,subtreeLevels,maximumLevel,contentUrlTemplate,subtreesUriTemplate,basePath}=options;var tile={children:[],lodMetricValue:0,contentUrl:''};var childrenPerTile=SUBDIVISION_COUNT_MAP[subdivisionScheme];var childX=childIndex&0b01;var childY=childIndex>>1&0b01;var childZ=childIndex>>2&0b01;var levelOffset=(childrenPerTile**level-1)/(childrenPerTile-1);var childTileMortonIndex=concatBits(parentData.mortonIndex,childIndex);var tileAvailabilityIndex=levelOffset+childTileMortonIndex;var childTileX=concatBits(parentData.x,childX);var childTileY=concatBits(parentData.y,childY);var childTileZ=concatBits(parentData.z,childZ);var isChildSubtreeAvailable=false;if(level+1>subtreeLevels){isChildSubtreeAvailable=getAvailabilityResult(subtree.childSubtreeAvailability,childTileMortonIndex);}var x=concatBits(globalData.x,childTileX);var y=concatBits(globalData.y,childTileY);var z=concatBits(globalData.z,childTileZ);var lev=level+globalData.level;if(isChildSubtreeAvailable){var subtreePath="".concat(basePath,"/").concat(subtreesUriTemplate);var childSubtreeUrl=replaceContentUrlTemplate(subtreePath,lev,x,y,z);var childSubtree=await load(childSubtreeUrl,Tile3DSubtreeLoader);subtree=childSubtree;globalData.mortonIndex=childTileMortonIndex;globalData.x=childTileX;globalData.y=childTileY;globalData.z=childTileZ;globalData.level=level;childTileMortonIndex=0;tileAvailabilityIndex=0;childTileX=0;childTileY=0;childTileZ=0;level=0;}var isTileAvailable=getAvailabilityResult(subtree.tileAvailability,tileAvailabilityIndex);if(!isTileAvailable||level>maximumLevel){return tile;}var isContentAvailable=getAvailabilityResult(subtree.contentAvailability,tileAvailabilityIndex);if(isContentAvailable){tile.contentUrl=replaceContentUrlTemplate(contentUrlTemplate,lev,x,y,z);}var childTileLevel=level+1;var pData={mortonIndex:childTileMortonIndex,x:childTileX,y:childTileY,z:childTileZ};for(var index=0;indexmapUrl[matched]);}function generateMapUrl(items){var mapUrl={};for(var key in items){mapUrl["{".concat(key,"}")]=items[key];}return mapUrl;}function getBooleanValueFromBitstream(availabilityIndex,availabilityBuffer){var byteIndex=Math.floor(availabilityIndex/8);var bitIndex=availabilityIndex%8;var bitValue=availabilityBuffer[byteIndex]>>bitIndex&1;return bitValue===1;}function getTileType(tile){if(!tile.contentUrl){return TILE_TYPE.EMPTY;}var contentUrl=tile.contentUrl;var fileExtension=contentUrl.split('.').pop();switch(fileExtension){case'pnts':return TILE_TYPE.POINTCLOUD;case'i3dm':case'b3dm':case'glb':case'gltf':return TILE_TYPE.SCENEGRAPH;default:return fileExtension;}}function getRefine(refine){switch(refine){case'REPLACE':case'replace':return TILE_REFINEMENT.REPLACE;case'ADD':case'add':return TILE_REFINEMENT.ADD;default:return refine;}}function normalizeTileData(tile,options){if(!tile){return null;}if(tile.content){var contentUri=tile.content.uri||tile.content.url;tile.contentUrl="".concat(options.basePath,"/").concat(contentUri);}tile.id=tile.contentUrl;tile.lodMetricType=LOD_METRIC_TYPE.GEOMETRIC_ERROR;tile.lodMetricValue=tile.geometricError;tile.transformMatrix=tile.transform;tile.type=getTileType(tile);tile.refine=getRefine(tile.refine);return tile;}function normalizeTileHeaders(tileset){var basePath=tileset.basePath;var root=normalizeTileData(tileset.root,tileset);var stack=[];stack.push(root);while(stack.length>0){var tile=stack.pop()||{};var children=tile.children||[];for(var childHeader of children){normalizeTileData(childHeader,{basePath});stack.push(childHeader);}}return root;}async function normalizeImplicitTileHeaders(tileset){if(!tileset.root){return null;}var basePath=tileset.basePath;var implicitTilingExtension=tileset.root.extensions['3DTILES_implicit_tiling'];var{subdivisionScheme,maximumLevel,subtreeLevels,subtrees:{uri:subtreesUriTemplate}}=implicitTilingExtension;var subtreeUrl=replaceContentUrlTemplate(subtreesUriTemplate,0,0,0,0);var rootSubtreeUrl="".concat(basePath,"/").concat(subtreeUrl);var rootSubtree=await load(rootSubtreeUrl,Tile3DSubtreeLoader);var contentUrlTemplate="".concat(basePath,"/").concat(tileset.root.content.uri);var refine=tileset.root.refine;var rootLodMetricValue=tileset.root.geometricError;var rootBoundingVolume=tileset.root.boundingVolume;var options={contentUrlTemplate,subtreesUriTemplate,subdivisionScheme,subtreeLevels,maximumLevel,refine,basePath,lodMetricType:LOD_METRIC_TYPE.GEOMETRIC_ERROR,rootLodMetricValue,rootBoundingVolume,getTileType,getRefine};return await normalizeImplicitTileData(tileset.root,rootSubtree,options);}async function normalizeImplicitTileData(tile,rootSubtree,options){if(!tile){return null;}tile.lodMetricType=LOD_METRIC_TYPE.GEOMETRIC_ERROR;tile.lodMetricValue=tile.geometricError;tile.transformMatrix=tile.transform;var{children,contentUrl}=await parseImplicitTiles(rootSubtree,options);if(contentUrl){tile.contentUrl=contentUrl;tile.content={uri:contentUrl.replace("".concat(options.basePath,"/"),'')};}tile.refine=getRefine(tile.refine);tile.type=getTileType(tile);tile.children=children;tile.id=tile.contentUrl;return tile;}var IMPLICIT_TILING_EXTENSION_NAME='3DTILES_implicit_tiling';var Tiles3DLoader={id:'3d-tiles',name:'3D Tiles',module:'3d-tiles',version:VERSION$5,extensions:['cmpt','pnts','b3dm','i3dm'],mimeTypes:['application/octet-stream'],tests:['cmpt','pnts','b3dm','i3dm'],parse,options:{'3d-tiles':{loadGLTF:true,decodeQuantizedPositions:false,isTileset:'auto',assetGltfUpAxis:null}}};function getBaseUri(tileset){return dirname(tileset.url);}async function parseTile(arrayBuffer,options,context){var tile={content:{featureIds:null}};var byteOffset=0;await parse3DTile(arrayBuffer,byteOffset,options,context,tile.content);return tile.content;}async function parseTileset(data,options,context){var _tilesetJson$root;var tilesetJson=JSON.parse(new TextDecoder().decode(data));tilesetJson.loader=options.loader||Tiles3DLoader;tilesetJson.url=context.url;tilesetJson.basePath=getBaseUri(tilesetJson);tilesetJson.root=hasImplicitTilingExtension(tilesetJson)?await normalizeImplicitTileHeaders(tilesetJson):normalizeTileHeaders(tilesetJson);tilesetJson.type=TILESET_TYPE.TILES3D;tilesetJson.lodMetricType=LOD_METRIC_TYPE.GEOMETRIC_ERROR;tilesetJson.lodMetricValue=((_tilesetJson$root=tilesetJson.root)===null||_tilesetJson$root===void 0?void 0:_tilesetJson$root.lodMetricValue)||0;return tilesetJson;}async function parse(data,options,context){var loaderOptions=options['3d-tiles']||{};var isTileset;if(loaderOptions.isTileset==='auto'){isTileset=context.url&&context.url.indexOf('.json')!==-1;}else {isTileset=loaderOptions.isTileset;}if(isTileset){data=await parseTileset(data,options,context);}else {data=await parseTile(data,options,context);}return data;}function hasImplicitTilingExtension(tilesetJson){var _tilesetJson$extensio,_tilesetJson$extensio2;return (tilesetJson===null||tilesetJson===void 0?void 0:(_tilesetJson$extensio=tilesetJson.extensionsRequired)===null||_tilesetJson$extensio===void 0?void 0:_tilesetJson$extensio.includes(IMPLICIT_TILING_EXTENSION_NAME))&&(tilesetJson===null||tilesetJson===void 0?void 0:(_tilesetJson$extensio2=tilesetJson.extensionsUsed)===null||_tilesetJson$extensio2===void 0?void 0:_tilesetJson$extensio2.includes(IMPLICIT_TILING_EXTENSION_NAME));}var CESIUM_ION_URL='https://api.cesium.com/v1/assets';async function getIonTilesetMetadata(accessToken,assetId){if(!assetId){var assets=await getIonAssets(accessToken);for(var item of assets.items){if(item.type==='3DTILES'){assetId=item.id;}}}var ionAssetMetadata=await getIonAssetMetadata(accessToken,assetId);var{type,url}=ionAssetMetadata;assert$7(type==='3DTILES'&&url);ionAssetMetadata.headers={Authorization:"Bearer ".concat(ionAssetMetadata.accessToken)};return ionAssetMetadata;}async function getIonAssets(accessToken){assert$7(accessToken);var url=CESIUM_ION_URL;var headers={Authorization:"Bearer ".concat(accessToken)};var response=await fetchFile(url,{fetch:{headers}});if(!response.ok){throw new Error(response.statusText);}return await response.json();}async function getIonAssetMetadata(accessToken,assetId){assert$7(accessToken,assetId);var headers={Authorization:"Bearer ".concat(accessToken)};var url="".concat(CESIUM_ION_URL,"/").concat(assetId);var response=await fetchFile("".concat(url),{fetch:{headers}});if(!response.ok){throw new Error(response.statusText);}var metadata=await response.json();response=await fetchFile("".concat(url,"/endpoint"),{fetch:{headers}});if(!response.ok){throw new Error(response.statusText);}var tilesetInfo=await response.json();metadata=_objectSpread2(_objectSpread2({},metadata),tilesetInfo);return metadata;}async function preload(url){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};options=options['cesium-ion']||{};var{accessToken}=options;var assetId=options.assetId;if(!Number.isFinite(assetId)){var matched=url.match(/\/([0-9]+)\/tileset.json/);assetId=matched&&matched[1];}return getIonTilesetMetadata(accessToken,assetId);}var CesiumIonLoader=_objectSpread2(_objectSpread2({},Tiles3DLoader),{},{id:'cesium-ion',name:'Cesium Ion',preload,parse:async(data,options,context)=>{options=_objectSpread2({},options);options['3d-tiles']=options['cesium-ion'];options.loader=CesiumIonLoader;return Tiles3DLoader.parse(data,options,context);},options:{'cesium-ion':_objectSpread2(_objectSpread2({},Tiles3DLoader.options['3d-tiles']),{},{accessToken:null})}});// From https://github.com/potree/potree/blob/master/src/materials/PointCloudMaterial.js function generateGradientTexture(gradient){var size=64;// create canvas var canvas=document.createElement('canvas');canvas.width=size;canvas.height=size;// get context var context=canvas.getContext('2d');// draw gradient context.rect(0,0,size,size);var ctxGradient=context.createLinearGradient(0,0,size,size);for(var _i55=0;_i55{if(label.sprite.material.opacity<1)return;window.hoverTile=tile;console.log('hoverLabel',tile.id,tile._distanceToCamera);});/* let s = 0.6 label.scale.set(s,s,s) */var s=tile.tileset.options.maximumScreenSpaceError/400;label.scale.set(s,s,s);dispPlane.add(label);label.position.set(...boundUntransformed.center);//label.position.z *= -1 /* if(tile.content.byteLength == void 0){ let oldUpdate = dispPlane.updateMatrixWorld.bind(dispPlane) dispPlane.updateMatrixWorld = (a,b)=>{ oldUpdate(a,b) } let oldU = dispPlane.updateMatrix.bind(dispPlane) dispPlane.updateMatrix = (a,b)=>{ oldU(a,b) } } */tile.volumeBox=dispPlane;return dispPlane;}function getMatrix4FromHalfAxes(halfAxes){var m=halfAxes;var rotateMatrix=new Matrix4().fromArray([m[0]*2,m[1]*2,m[2]*2,0,m[3]*2,m[4]*2,m[5]*2,0,m[6]*2,m[7]*2,m[8]*2,0,0,0,0,1]);return rotateMatrix;}/* * from https://github.com/tentone/geo-three * Tree-shaking did not work, probably due to static class methods */function datumsToSpherical(latitude,longitude){var EARTH_RADIUS=6378137;var EARTH_PERIMETER=2*Math.PI*EARTH_RADIUS;var EARTH_ORIGIN=EARTH_PERIMETER/2.0;var x=longitude*EARTH_ORIGIN/180.0;var y=Math.log(Math.tan((90+latitude)*Math.PI/360.0))/(Math.PI/180.0);y=y*EARTH_ORIGIN/180.0;return new Vector2(x,y);}var Gradients$1={// From chroma spectral http://gka.github.io/chroma.js/ SPECTRAL:[[0,new Color(0.3686,0.3098,0.6353)],[0.1,new Color(0.1961,0.5333,0.7412)],[0.2,new Color(0.4,0.7608,0.6471)],[0.3,new Color(0.6706,0.8667,0.6431)],[0.4,new Color(0.902,0.9608,0.5961)],[0.5,new Color(1.0,1.0,0.749)],[0.6,new Color(0.9961,0.8784,0.5451)],[0.7,new Color(0.9922,0.6824,0.3804)],[0.8,new Color(0.9569,0.4275,0.2627)],[0.9,new Color(0.8353,0.2431,0.3098)],[1,new Color(0.6196,0.0039,0.2588)]],PLASMA:[[0.0,new Color(0.241,0.015,0.61)],[0.1,new Color(0.387,0.001,0.654)],[0.2,new Color(0.524,0.025,0.653)],[0.3,new Color(0.651,0.125,0.596)],[0.4,new Color(0.752,0.227,0.513)],[0.5,new Color(0.837,0.329,0.431)],[0.6,new Color(0.907,0.435,0.353)],[0.7,new Color(0.963,0.554,0.272)],[0.8,new Color(0.992,0.681,0.195)],[0.9,new Color(0.987,0.822,0.144)],[1.0,new Color(0.94,0.975,0.131)]],YELLOW_GREEN:[[0,new Color(0.1647,0.2824,0.3451)],[0.1,new Color(0.1338,0.3555,0.4227)],[0.2,new Color(0.061,0.4319,0.4864)],[0.3,new Color(0.0,0.5099,0.5319)],[0.4,new Color(0.0,0.5881,0.5569)],[0.5,new Color(0.137,0.665,0.5614)],[0.6,new Color(0.2906,0.7395,0.5477)],[0.7,new Color(0.4453,0.8099,0.5201)],[0.8,new Color(0.6102,0.8748,0.485)],[0.9,new Color(0.7883,0.9323,0.4514)],[1,new Color(0.9804,0.9804,0.4314)]],VIRIDIS:[[0.0,new Color(0.267,0.005,0.329)],[0.1,new Color(0.283,0.141,0.458)],[0.2,new Color(0.254,0.265,0.53)],[0.3,new Color(0.207,0.372,0.553)],[0.4,new Color(0.164,0.471,0.558)],[0.5,new Color(0.128,0.567,0.551)],[0.6,new Color(0.135,0.659,0.518)],[0.7,new Color(0.267,0.749,0.441)],[0.8,new Color(0.478,0.821,0.318)],[0.9,new Color(0.741,0.873,0.15)],[1.0,new Color(0.993,0.906,0.144)]],INFERNO:[[0.0,new Color(0.077,0.042,0.206)],[0.1,new Color(0.225,0.036,0.388)],[0.2,new Color(0.373,0.074,0.432)],[0.3,new Color(0.522,0.128,0.42)],[0.4,new Color(0.665,0.182,0.37)],[0.5,new Color(0.797,0.255,0.287)],[0.6,new Color(0.902,0.364,0.184)],[0.7,new Color(0.969,0.516,0.063)],[0.8,new Color(0.988,0.683,0.072)],[0.9,new Color(0.961,0.859,0.298)],[1.0,new Color(0.988,0.998,0.645)]],GRAYSCALE:[[0,new Color(0,0,0)],[1,new Color(1,1,1)]],// 16 samples of the TURBU color scheme // values taken from: https://gist.github.com/mikhailov-work/ee72ba4191942acecc03fe6da94fc73f // original file licensed under Apache-2.0 TURBO:[[0.0,new Color(0.18995,0.07176,0.23217)],[0.07,new Color(0.25107,0.25237,0.63374)],[0.13,new Color(0.27628,0.42118,0.89123)],[0.2,new Color(0.25862,0.57958,0.99876)],[0.27,new Color(0.15844,0.73551,0.92305)],[0.33,new Color(0.09267,0.86554,0.7623)],[0.4,new Color(0.19659,0.94901,0.59466)],[0.47,new Color(0.42778,0.99419,0.38575)],[0.53,new Color(0.64362,0.98999,0.23356)],[0.6,new Color(0.80473,0.92452,0.20459)],[0.67,new Color(0.93301,0.81236,0.22667)],[0.73,new Color(0.99314,0.67408,0.20348)],[0.8,new Color(0.9836,0.49291,0.12849)],[0.87,new Color(0.92105,0.31489,0.05475)],[0.93,new Color(0.81608,0.18462,0.01809)],[1.0,new Color(0.66449,0.08436,0.00424)]],RAINBOW:[[0,new Color(0.278,0,0.714)],[1/6,new Color(0,0,1)],[2/6,new Color(0,1,1)],[3/6,new Color(0,1,0)],[4/6,new Color(1,1,0)],[5/6,new Color(1,0.64,0)],[1,new Color(1,0,0)]],CONTOUR:[[0.0,new Color(0,0,0)],[0.03,new Color(0,0,0)],[0.04,new Color(1,1,1)],[1.0,new Color(1,1,1)]]};var PointCloudFS="\n varying vec3 vColor;\n uniform float alpha;\n\n void main() {\n if (vColor == vec3(0.0, 0.0, 0.0)) {\n discard;\n } else {\n gl_FragColor = vec4( vColor, alpha);\n }\n }\n";var PointCloudVS="\n varying vec3 vColor;\n uniform sampler2D gradient;\n uniform sampler2D grayscale;\n attribute float intensity;\n attribute float classification;\n uniform vec3 rootCenter;\n uniform vec3 rootNormal;\n uniform vec2 elevationRange;\n uniform int coloring;\n uniform bool hideGround;\n uniform float maxIntensity;\n uniform float intensityContrast;\n uniform float pointSize;\n\n #ifdef USE_COLOR\n vec3 getRGB() {\n vec3 rgb = color;\n return rgb;\n }\n #endif\n\n vec3 getElevation(){\n vec4 world = modelMatrix * vec4( position, 1.0 );\n float diff = abs(dot(rootNormal, (vec3(world) - rootCenter)));\n float w = max(diff - elevationRange.x,0.0) / max(elevationRange.y - elevationRange.x,1.0);\n vec3 cElevation = texture2D(gradient, vec2(w,1.0-w)).rgb;\n\n return cElevation;\n }\n\n vec3 getIntensity(){\n // TODO: real contrast enhancement. Check https://github.com/yuki-koyama/enhancer/blob/master/shaders/enhancer.fs\n float intmod = pow(intensity, intensityContrast);\n vec3 cIntensity = texture2D(grayscale, vec2(intmod / maxIntensity ,1.0-(intmod / maxIntensity))).rgb;\n return cIntensity;\n }\n\n vec3 getClassification(){\n float classNormalized = classification / 255.0;\n vec3 cClassification = texture2D(gradient, vec2(classNormalized * 5.0,1.0-classNormalized * 5.0)).rgb;\n return cClassification;\n }\n\n vec3 getColor(){\n vec3 color;\n if (hideGround && classification == 2.0) {\n return vec3(0.0, 0.0, 0.0); \n }\n\n if (coloring == 1) {\n color = getIntensity();\n }\n else if (coloring == 2) {\n color = getClassification();\n } else if (coloring == 3) {\n color = getElevation();\n } \n #ifdef USE_COLOR\n else if (coloring == 4) {\n color = getRGB();\n }\n #endif\n else {\n color = vec3(1.0, 1.0, 1.0);\n }\n return color;\n }\n\n void main() {\n vColor = getColor();\n\n gl_PointSize = pointSize;\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n }\n";/** Types of coloring used when viewing point cloud tiles */var PointCloudColoring;(function(PointCloudColoring){PointCloudColoring[PointCloudColoring["Intensity"]=1]="Intensity";PointCloudColoring[PointCloudColoring["Classification"]=2]="Classification";PointCloudColoring[PointCloudColoring["Elevation"]=3]="Elevation";PointCloudColoring[PointCloudColoring["RGB"]=4]="RGB";PointCloudColoring[PointCloudColoring["White"]=5]="White";})(PointCloudColoring||(PointCloudColoring={}));/** Types of shading used when viewing b3dm (mesh) tiles */var Shading;(function(Shading){Shading[Shading["FlatTexture"]=1]="FlatTexture";Shading[Shading["ShadedTexture"]=2]="ShadedTexture";Shading[Shading["ShadedNoTexture"]=3]="ShadedNoTexture";})(Shading||(Shading={}));var GeoTransform;(function(GeoTransform){GeoTransform[GeoTransform["Reset"]=1]="Reset";GeoTransform[GeoTransform["Mercator"]=2]="Mercator";GeoTransform[GeoTransform["WGS84Cartesian"]=3]="WGS84Cartesian";})(GeoTransform||(GeoTransform={}));var gradient=Gradients$1.RAINBOW;var gradientTexture=typeof document!='undefined'?generateGradientTexture(gradient):null;var grayscale=Gradients$1.GRAYSCALE;var grayscaleTexture=typeof document!='undefined'?generateGradientTexture(grayscale):null;var defaultOptions={throttleRequests:true,maxRequests:64,updateInterval:0.1,maxConcurrency:1,maximumScreenSpaceError:16,maximumMemoryUsage:32,viewDistanceScale:1.0,skipLevelOfDetail:false,updateTransforms:true,shading:Shading.FlatTexture,transparent:false,pointCloudColoring:PointCloudColoring.White,pointSize:1.0,worker:true,wireframe:false,debug:false,basisTranscoderPath:null,dracoDecoderPath:null,material:null,computeNormals:false,shaderCallback:null,geoTransform:GeoTransform.Reset,preloadTilesCount:null};/** 3D Tiles Loader */class Loader3DTiles{/** * Loads a tileset of 3D Tiles according to the given {@link LoaderProps} * @public * * @param props - Properties for this load call {@link LoaderProps}. * @returns An object containing the 3D Model to be added to the scene * and a runtime engine to be updated every frame. */static load(props){return __awaiter(this,void 0,void 0,function*(){var options=Object.assign(Object.assign({},defaultOptions),props.options);var{url}=props;var UPDATE_INTERVAL=options.updateInterval;var MAX_DEPTH_FOR_ORIENTATION=5;var loadersGLOptions={};if(options.cesiumIONToken){loadersGLOptions['cesium-ion']={accessToken:options.cesiumIONToken};var metadata=yield CesiumIonLoader.preload(url,loadersGLOptions);loadersGLOptions['fetch']={headers:metadata.headers};}if(props.loadingManager){props.loadingManager.itemStart(url);}var tilesetJson=yield load(url,Tiles3DLoader,Object.assign({},loadersGLOptions));var renderMap={};var boxMap={};var unloadQueue=[];var root=new Group();var tileBoxes=new Group();tileBoxes.matrixAutoUpdate=false;//add if(!options.debug){tileBoxes.visible=false;}else {options.parent.add(tileBoxes);//add }var pointcloudUniforms={pointSize:{type:'f',value:options.pointSize},gradient:{type:'t',value:gradientTexture},grayscale:{type:'t',value:grayscaleTexture},rootCenter:{type:'vec3',value:new Vector3()},rootNormal:{type:'vec3',value:new Vector3()},coloring:{type:'i',value:options.pointCloudColoring},hideGround:{type:'b',value:true},elevationRange:{type:'vec2',value:new Vector2(0,400)},maxIntensity:{type:'f',value:1.0},intensityContrast:{type:'f',value:1.0},alpha:{type:'f',value:1.0}};var pointcloudMaterial=new ShaderMaterial({uniforms:pointcloudUniforms,vertexShader:PointCloudVS,fragmentShader:PointCloudFS,transparent:options.transparent,vertexColors:true});var cameraReference=null;var rendererReference=null;var gltfLoader=props.gltfLoader||new GLTFLoader();//xzw改 var ktx2Loader=undefined;var dracoLoader=undefined;if(options.basisTranscoderPath){ktx2Loader=new KTX2Loader();ktx2Loader.detectSupport(props.renderer);ktx2Loader.setTranscoderPath(options.basisTranscoderPath+'/');ktx2Loader.setWorkerLimit(1);gltfLoader.setKTX2Loader(ktx2Loader);}if(options.dracoDecoderPath){dracoLoader=new DRACOLoader();dracoLoader.setDecoderPath(options.dracoDecoderPath+'/');dracoLoader.setWorkerLimit(options.maxConcurrency);gltfLoader.setDRACOLoader(dracoLoader);}var unlitMaterial=new BasicMaterial({transparent:options.transparent});var tileOptions={maximumMemoryUsage:options.maximumMemoryUsage,maximumScreenSpaceError:options.maximumScreenSpaceError,viewDistanceScale:options.viewDistanceScale,skipLevelOfDetail:options.skipLevelOfDetail,updateTransforms:options.updateTransforms,throttleRequests:options.throttleRequests,maxRequests:options.maxRequests,updateTime:options.updateTime||0,//add //maxDepth: options.maxDepth || 50, // !zeg改 contentLoader:tile=>__awaiter(this,void 0,void 0,function*(){var tileContent=null;switch(tile.type){case TILE_TYPE.POINTCLOUD:{tileContent=createPointNodes(tile,pointcloudMaterial,options,rootTransformInverse);break;}case TILE_TYPE.SCENEGRAPH:case TILE_TYPE.MESH:{tileContent=yield createGLTFNodes(gltfLoader,tile,unlitMaterial,options,rootTransformInverse);break;}}if(tileContent){tileContent.visible=false;renderMap[tile.id]=tileContent;tileContent.name=tile.id;//add tileContent.tile=tile;//add root.add(renderMap[tile.id]);if(options.debug){var box=loadersBoundingBoxToMesh(tile);tileBoxes.add(box);boxMap[tile.id]=box;}//xzw : tileset.dispatchEvent({type:'tileLoaded',tileContent});//每一个tile加载完要更改透明度等 }}),onTileLoad:tile=>__awaiter(this,void 0,void 0,function*(){if(tileset){if(!orientationDetected&&(tile===null||tile===void 0?void 0:tile.depth)<=MAX_DEPTH_FOR_ORIENTATION){detectOrientation(tile);}tileset._frameNumber++;tilesetUpdate(tileset,renderMap,rendererReference,cameraReference);}}),onTileUnload:tile=>{unloadQueue.push(tile);},onTileError:(tile,message)=>{console.error('Tile error',tile.id,message);}};var tileset=new Tileset3D(tilesetJson,Object.assign(Object.assign({},tileOptions),{loadOptions:Object.assign(Object.assign({},loadersGLOptions),{maxConcurrency:options.maxConcurrency,worker:options.worker,gltf:{loadImages:false},'3d-tiles':{loadGLTF:false}})}));tileset.boxMap=boxMap;//add // transformations var threeMat=new Matrix4();var tileTransform=new Matrix4();var rootCenter=new Vector3();var orientationDetected=false;if(tileset.root.boundingVolume){if(tileset.root.header.boundingVolume.region){// TODO: Handle region type bounding volumes // https://github.com/visgl/loaders.gl/issues/1994 console.warn("Cannot apply a model matrix to bounding volumes of type region. Tileset stays in original geo-coordinates.");options.geoTransform=GeoTransform.WGS84Cartesian;}tileTransform.setPosition(tileset.root.boundingVolume.center[0],tileset.root.boundingVolume.center[1],tileset.root.boundingVolume.center[2]);}else {console.warn("Bounding volume not found, no transformations applied");}if(options.debug){var box=loadersBoundingBoxToMesh(tileset.root);tileBoxes.add(box);boxMap[tileset.root.id]=box;}var disposeFlag=false;var loadingEnded=false;pointcloudUniforms.rootCenter.value.copy(rootCenter);pointcloudUniforms.rootNormal.value.copy(new Vector3(0,0,1).normalize());// Extra stats tileset.stats.get('Loader concurrency').count=options.maxConcurrency;tileset.stats.get('Maximum SSE').count=options.maximumScreenSpaceError;tileset.stats.get('Maximum mem usage').count=options.maximumMemoryUsage;var timer=0;var lastCameraTransform=null;var lastCameraAspect=null;var lastCameraPosition=new Vector3(Infinity,Infinity,Infinity);var sseDenominator=null;root.updateMatrixWorld(true);var lastRootTransform=new Matrix4().copy(root.matrixWorld);var rootTransformInverse=new Matrix4().copy(lastRootTransform).invert();tileset.lastRootTransform=lastRootTransform;//add detectOrientation(tileset.root);updateResetTransform();if(options.debug){boxMap[tileset.root.id].applyMatrix4(threeMat);tileBoxes.matrixWorld.copy(root.matrixWorld);}if(options.geoTransform==GeoTransform.Mercator){var coords=datumsToSpherical(tileset.cartographicCenter[1],tileset.cartographicCenter[0]);rootCenter.set(coords.x,0,-coords.y);root.position.copy(rootCenter);root.rotation.set(-Math.PI/2,0,0);root.updateMatrixWorld(true);}else if(options.geoTransform==GeoTransform.WGS84Cartesian){root.applyMatrix4(tileTransform);root.updateMatrixWorld(true);rootCenter.copy(root.position);}function detectOrientation(tile){if(!tile.boundingVolume.halfAxes){return;}var halfAxes=tile.boundingVolume.halfAxes;var orientationMatrix=new Matrix4().extractRotation(getMatrix4FromHalfAxes(halfAxes)).premultiply(new Matrix4().extractRotation(rootTransformInverse));var rotation=new Euler().setFromRotationMatrix(orientationMatrix);if(!rotation.equals(new Euler())){orientationDetected=true;var pos=new Vector3(tileTransform.elements[12],tileTransform.elements[13],tileTransform.elements[14]);tileTransform.extractRotation(orientationMatrix);tileTransform.setPosition(pos);updateResetTransform();}}function updateResetTransform(){if(options.geoTransform!=GeoTransform.WGS84Cartesian){// Reset the current model matrix and apply our own transformation //threeMat.copy(tileTransform).invert(); //threeMat.premultiply(lastRootTransform); //xzw删 被下面copy这句覆盖了 var tileTransInvert=new Matrix4().copy(tileTransform).invert();threeMat.copy(lastRootTransform).multiply(tileTransInvert);tileset.modelMatrix=new Matrix4$1(threeMat.toArray());//console.log('update tileset ModelMatrix', tileset.modelMatrix.elements) tileset.tileTransInvert=tileTransInvert.toArray();// add for volumebox }}// 更新瓦片显隐和瓦片迭代更新 function tilesetUpdate(tileset,renderMap,renderer,camera){if(disposeFlag||options.pauseTilesetUpdate){// !zeg改 pauseTilesetUpdate return;}// Assumes camera fov, near and far are not changing if(!sseDenominator||camera.aspect!=lastCameraAspect){var loadersFrustum=new PerspectiveFrustum({fov:camera.fov/180*Math.PI,aspectRatio:camera.aspect,near:camera.near,far:camera.far});sseDenominator=loadersFrustum.sseDenominator;lastCameraAspect=camera.aspect;if(camera.aspect==0)return;//add if(options.debug){console.log('Updated sse denonimator:',sseDenominator);}}var frustum=_getCameraFrustum(camera);var planes=frustum.planes.map(plane=>new Plane$1(plane.normal.toArray(),plane.constant));var cullingVolume=new CullingVolume(planes);var rendererSize=new Vector2();renderer.getSize(rendererSize);var frameState={camera:{position:lastCameraPosition.toArray()},height:rendererSize.y,frameNumber:tileset._frameNumber,sseDenominator:sseDenominator,cullingVolume:cullingVolume,viewport:{id:0}};tileset._cache.reset();tileset._traverser.traverse(tileset.root,frameState,tileset.options);for(var tile of tileset.tiles){if(tile.selected){if(!renderMap[tile.id]){console.error('TILE SELECTED BUT NOT LOADED!!',tile.id);}else {// Make sure it's visible if(!renderMap[tile.id].visible){if(viewer.visiVertexCount0){var _tile=unloadQueue.pop();if(renderMap[_tile.id]&&_tile.contentState==TILE_CONTENT_STATE.UNLOADED){//console.log('removevisi', renderMap[tile.id].visible) 如果是true,visiVertexCount要减 root.remove(renderMap[_tile.id]);disposeNode(renderMap[_tile.id]);delete renderMap[_tile.id];}if(boxMap[_tile.id]){disposeNode(boxMap[_tile.id]);tileBoxes.remove(boxMap[_tile.id]);delete boxMap[_tile.id];}}var tilesLoaded=tileset.stats.get('Tiles Loaded').count;var tilesLoading=tileset.stats.get('Tiles Loading').count;if(props.onProgress){props.onProgress(tilesLoaded,tilesLoaded+tilesLoading);}if(props.loadingManager&&!loadingEnded){if(tilesLoading==0&&(options.preloadTilesCount==null||tilesLoaded>=options.preloadTilesCount)){loadingEnded=true;props.loadingManager.itemEnd(props.url);}}return frameState;}return {model:root,runtime:{getTileset:()=>{return tileset;},getStats:()=>{return tileset.stats;},showTiles:visible=>{tileBoxes.visible=visible;},setWireframe:wireframe=>{options.wireframe=wireframe;root.traverse(object=>{if(object instanceof Mesh){object.material.wireframe=wireframe;}});},setDebug:debug=>{options.debug=debug;tileBoxes.visible=debug;},setShading:shading=>{options.shading=shading;},getTileBoxes:()=>{return tileBoxes;},setViewDistanceScale:scale=>{tileset.options.viewDistanceScale=scale;tileset._frameNumber++;tilesetUpdate(tileset,renderMap,rendererReference,cameraReference);},setHideGround:enabled=>{pointcloudUniforms.hideGround.value=enabled;},setPointCloudColoring:selection=>{pointcloudUniforms.coloring.value=selection;},setElevationRange:range=>{pointcloudUniforms.elevationRange.value.set(range[0],range[1]);},setMaxIntensity:intensity=>{pointcloudUniforms.maxIntensity.value=intensity;},setIntensityContrast:contrast=>{pointcloudUniforms.intensityContrast.value=contrast;},setPointAlpha:alpha=>{pointcloudUniforms.alpha.value=alpha;},getLatLongHeightFromPosition:position=>{var cartographicPosition=tileset.ellipsoid.cartesianToCartographic(new Vector3().copy(position).applyMatrix4(new Matrix4().copy(threeMat).invert()).toArray());return {lat:cartographicPosition[1],long:cartographicPosition[0],height:cartographicPosition[2]};},getPositionFromLatLongHeight:coord=>{var cartesianPosition=tileset.ellipsoid.cartographicToCartesian([coord.long,coord.lat,coord.height]);return new Vector3(...cartesianPosition).applyMatrix4(threeMat);},getCameraFrustum:camera=>{var frustum=_getCameraFrustum(camera);var meshes=frustum.planes.map(plane=>new Plane$1(plane.normal.toArray(),plane.constant)).map(loadersPlane=>loadersPlaneToMesh(loadersPlane));var model=new Group();for(var mesh of meshes)model.add(mesh);return model;},update:function update(dt,renderer,camera,ifForce){cameraReference=camera;rendererReference=renderer;timer+=dt;if(!ifForce)ifForce=tileset.nextForceUpdate;tileset.nextForceUpdate=false;if(tileset.needRenderNext){//必须在下一帧渲染刷新否则无法显示 viewer.dispatchEvent('content_changed');}tileset.needRenderNext=ifForce;if(tileset&&(timer>=UPDATE_INTERVAL||ifForce)){if(!lastRootTransform.equals(root.matrixWorld)){timer=0;lastRootTransform.copy(root.matrixWorld);updateResetTransform();var _rootCenter=new Vector3().setFromMatrixPosition(lastRootTransform);pointcloudUniforms.rootCenter.value.copy(_rootCenter);pointcloudUniforms.rootNormal.value.copy(new Vector3(0,0,1).applyMatrix4(lastRootTransform).normalize());rootTransformInverse.copy(lastRootTransform).invert();if(options.debug){/* console.log('move', tileset.root.id, boxMap[tileset.root.id].matrix.elements, boxMap[tileset.root.id].matrixWorld.elements) boxMap[tileset.root.id].matrix.copy(root.matrixWorld); boxMap[tileset.root.id].matrixWorld.copy(root.matrixWorld); */ //boxMap[tileset.root.id].applyMatrix4(threeMat); tileBoxes.matrix.copy(root.matrixWorld);//boxMap[tileset.root.id].matrixWorld.copy(threeMat); //boxMap[tileset.root.id].applyMatrix4(lastRootTransform);//boxMap[tileset.root.id].applyMatrix4(lastRootTransform); //boxMap[tileset.root.id].updateWorldMatrix() }}if(this.lastCameraTransform==null){this.lastCameraTransform=new Matrix4().copy(camera.matrixWorld);}else {var cameraChanged=!camera.matrixWorld.equals(this.lastCameraTransform)||!(camera.aspect==lastCameraAspect);if(cameraChanged||ifForce){timer=0;tileset._frameNumber++;camera.getWorldPosition(lastCameraPosition);this.lastCameraTransform.copy(camera.matrixWorld);tilesetUpdate(tileset,renderMap,renderer,camera);}}}/* else{ console.log('11') } */},dispose:function dispose(){disposeFlag=true;tileset._destroy();while(root.children.length>0){var obj=root.children[0];disposeNode(obj);root.remove(obj);}while(tileBoxes.children.length>0){var _obj=tileBoxes.children[0];tileBoxes.remove(_obj);_obj.geometry.dispose();_obj.material.dispose();}if(ktx2Loader){ktx2Loader.dispose();}if(dracoLoader){dracoLoader.dispose();}},limit2lowestDepth:isLowest=>{//zeg add 设置是否限制为最低精度tile深度 maxDepth=isLowest?1:100;//影响到shouldRefine, 检查方法:可以看到当maxDepth降低了之后viewer.objs.children[0].runtime.getTileset().tiles.filter(e=> e.tileContent.visible)变少 if(cameraReference){tileset._frameNumber++;tilesetUpdate(tileset,renderMap,rendererReference,cameraReference);}}}};});}}function createGLTFNodes(gltfLoader,tile,unlitMaterial,options,rootTransformInverse){return __awaiter(this,void 0,void 0,function*(){return new Promise((resolve,reject)=>{var _a;var rotateX=new Matrix4().makeRotationAxis(new Vector3(1,0,0),Math.PI/2);var shouldRotate=((_a=tile.tileset.asset)===null||_a===void 0?void 0:_a.gltfUpAxis)!=="Z";// The computed trasnform already contains the root's transform, so we have to invert it //const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(tileMatrix)//.premultiply(rootTransformInverse); //xzw 删。原先的会造成移动后tiles错乱 //const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(tile.tileset.modelMatrix).premultiply(rootTransformInverse) // 这句同tile.computedTransform左乘tileTransform。 因为tileTransform拿不到所以使用modelMatrix。modelMatrix为tileTransform左乘rootTransform, 所以再左乘rootTransformInverse //改动:contentTransform中的computedTransform 去掉左乘 root.modelMatrixWorld , 因为移动过后这个computedTransform没更新 gltfLoader.parse(tile.content.type=='glTF'?tile.content.gltf.gltfArrayBuffer:tile.content.gltfArrayBuffer,//tile.content.gltfArrayBuffer, tile.contentUrl?tile.contentUrl.substr(0,tile.contentUrl.lastIndexOf('/')+1):'',gltf=>{var tileContent=gltf.scenes[0];tileContent.vertexCount=0;//xzw add tile.tileContent=tileContent;//xzw add var needUpdate;if(tile.rtcCenterState!=!!tile.content.rtcCenter){// 等mesh加载好才知道rtcCenter,每个mesh坐标都不一样 needUpdate=true;//console.error('rtcCenter有变化?!') }tile.rtcCenterState=rtcCenterGlobal=!!tile.content.rtcCenter;var contentTransform=tile.getContentTransform(needUpdate);if(tile.content.rtcCenter){//大部分模型无 rtcCenter //console.error('rtcCenter有?!') //似乎bounding中包含这个信息了 所以getContentTransform不含这个 var tranM=new Matrix4();tranM.makeTranslation(tile.content.rtcCenter[0],tile.content.rtcCenter[1],tile.content.rtcCenter[2]);contentTransform.premultiply(tranM);}if(needUpdate){tile._updateBoundingVolume(tile.header);//add 重新更新 }if(shouldRotate){//大部分模型 无需 Rotate contentTransform.multiply(rotateX);// convert from GLTF Y-up to Z-up }tileContent.applyMatrix4(contentTransform);//'https://testgis.4dage.com/LVBADUI_qp/tileset.json', //村庄 这个案例是 要rotateX 且有rtcCenter的。boundingVolume已经是转换这两者后的值所以getContentTransform不加这个 //tile总共要左乘的矩阵 rotateX -> tileTransInvert * computedTransform -> 对geometry的tranM修改 -> 整个模型的matrixWorld tileContent.traverse(object=>{if(object.type=="Mesh"){var mesh=object;//mesh.tileId = tile.id//add var originalMaterial=mesh.material;var originalMap=originalMaterial.map;if(options.material){mesh.material=options.material.clone();originalMaterial.dispose();}else if(options.shading==Shading.FlatTexture){mesh.material=unlitMaterial.clone();originalMaterial.dispose();}if(options.shading!=Shading.ShadedNoTexture){if(mesh.material.type=="ShaderMaterial"&&!(mesh.material instanceof BasicMaterial)){//改 mesh.material.uniforms.map={value:originalMap};}else {mesh.material.map=originalMap;}}else {if(originalMap){originalMap.dispose();}mesh.material.map=null;}if(options.shaderCallback){mesh.onBeforeRender=options.shaderCallback;}mesh.material.wireframe=options.wireframe;if(options.computeNormals){mesh.geometry.computeVertexNormals();}//xzw add: tileContent.vertexCount+=mesh.geometry.attributes.position.count;//------------------add on 2023.1.16----zeg //mesh.geometry.applyMatrix4(contentTransform) /* if (tile.content.rtcCenter) { // 有些b3dm模型会将坐标写在源码的rtcCenter里 如https://testgis.4dage.com/LVBADUI_qp/tileset.json mesh.geometry.translate(tile.content.rtcCenter[0], tile.content.rtcCenter[1], tile.content.rtcCenter[2]) } else { mesh.geometry.scale(1, 1, -1) // 调整缩放,对应box也要进行变换(scaleZ对应box[2]) } */ //--------------------- }});resolve(tileContent);},e=>{reject(new Error("error parsing gltf in tile ".concat(tile.id,": ").concat(e)));});});});}function createPointNodes(tile,pointcloudMaterial,options,rootTransformInverse){var d={rtc_center:tile.content.rtcCenter,points:tile.content.attributes.positions,intensities:tile.content.attributes.intensity,classifications:tile.content.attributes.classification,rgb:null,rgba:null};var{colors}=tile.content.attributes;if(colors&&colors.size===3){d.rgb=colors.value;}if(colors&&colors.size===4){d.rgba=colors.value;}var geometry=new BufferGeometry();geometry.setAttribute('position',new Float32BufferAttribute(d.points,3));var contentTransform=new Matrix4().fromArray(tile.computedTransform).premultiply(rootTransformInverse);if(d.rgba){geometry.setAttribute('color',new Float32BufferAttribute(d.rgba,4));}else if(d.rgb){geometry.setAttribute('color',new Uint8BufferAttribute(d.rgb,3,true));}if(d.intensities){geometry.setAttribute('intensity',// Handles both 16bit or 8bit intensity values new BufferAttribute(d.intensities,1,true));}if(d.classifications){geometry.setAttribute('classification',new Uint8BufferAttribute(d.classifications,1,false));}var tileContent=new Points(geometry,options.material||pointcloudMaterial);if(d.rtc_center){var c=d.rtc_center;contentTransform.multiply(new Matrix4().makeTranslation(c[0],c[1],c[2]));}tileContent.applyMatrix4(contentTransform);return tileContent;}function disposeMaterial(material){var _a,_b,_c,_d;if((_a=material===null||material===void 0?void 0:material.uniforms)===null||_a===void 0?void 0:_a.map){(_c=(_b=material===null||material===void 0?void 0:material.uniforms)===null||_b===void 0?void 0:_b.map.value)===null||_c===void 0?void 0:_c.dispose();}else if(material.map){(_d=material.map)===null||_d===void 0?void 0:_d.dispose();}material.dispose();}function disposeNode(node){node.traverse(object=>{if(object.isMesh){object.geometry.dispose();if(object.material.isMaterial){disposeMaterial(object.material);}else {// an array of materials for(var material of object.material){disposeMaterial(material);}}}});for(var _i56=node.children.length-1;_i56>=0;_i56--){var obj=node.children[_i56];node.remove(obj);}}/* 关键搜寻: Loader3DTiles : const tileset = new Tileset3D tileset.dispatchEvent({type:'tileLoaded',tileContent}) createGLTFNodes(gltfLoader 创建tile executeTraversal(root, frameState) 遍历root lastRootTransform rootTransformInverse tileset._loadTiles 依次加载tiles _getPriority 加载优先级 加了一句 笔记: 主要类: class tileset3D 最外层整体。 获取方法: viewer.objs.children[index].runtime.getTileset()。 .tiles包含所有tiles class tileHeader 也就是tileset里面的一个个tile 。 其上有.tileset tileset里算的tileTransform之后是不会改变的, tile.transform也是,是json里的。 tileset.modelMatrix (通常这个值很大) 会随着位移改变 tile.computedTransform 被我修改了,之前左乘了tileset.modelMatrix,现只包含了transform信息 _updateTransform(parentTransfor 其中有_updateBoundingVolume,这个影响可见性, 在computeVisibilityWithPlaneMask中计算 tileset._cache.trim(), 然后再update //可以将所有不可见的tiles dispose 相机靠近容易缺块的bug暂时修改如下: _visible是由computeVisibilityWithPlaneMask计算得 get isVisibleAndInRequestVolume() { return this._inRequestVolume; //去掉了_visible || } 显示所有tile似乎也不会卡顿. 但好像影响了加载顺序从而变慢了。visiVertexCount过量。 怀疑应该还是文件的bound有问题。 原本会消失的地方虽然不会消失了但一直是模糊的 ========= 访问所有tile: viewer.objs.children[0].runtime.getTileset().tiles 它的mesh: tile.tileContent 或者直接得到所有mesh: viewer.objs.children[0].children tile.depth最低为1 , root是0 */ var OBJLoader = function () { // o object_name | g group_name var object_pattern = /^[og]\s*(.+)?/; // mtllib file_reference var material_library_pattern = /^mtllib /; // usemtl material_name var material_use_pattern = /^usemtl /; // usemap map_name var map_use_pattern = /^usemap /; var vA = new Vector3(); var vB = new Vector3(); var vC = new Vector3(); var ab = new Vector3(); var cb = new Vector3(); function ParserState() { var state = { objects: [], object: {}, vertices: [], normals: [], colors: [], uvs: [], materials: {}, materialLibraries: [], startObject: function startObject(name, fromDeclaration) { // If the current object (initial from reset) is not from a g/o declaration in the parsed // file. We need to use it for the first parsed g/o to keep things in sync. if (this.object && this.object.fromDeclaration === false) { this.object.name = name; this.object.fromDeclaration = fromDeclaration !== false; return; } var previousMaterial = this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined; if (this.object && typeof this.object._finalize === 'function') { this.object._finalize(true); } this.object = { name: name || '', fromDeclaration: fromDeclaration !== false, geometry: { vertices: [], normals: [], colors: [], uvs: [], hasUVIndices: false }, materials: [], smooth: true, startMaterial: function startMaterial(name, libraries) { var previous = this._finalize(false); // New usemtl declaration overwrites an inherited material, except if faces were declared // after the material, then it must be preserved for proper MultiMaterial continuation. if (previous && (previous.inherited || previous.groupCount <= 0)) { this.materials.splice(previous.index, 1); } var material = { index: this.materials.length, name: name || '', mtllib: Array.isArray(libraries) && libraries.length > 0 ? libraries[libraries.length - 1] : '', smooth: previous !== undefined ? previous.smooth : this.smooth, groupStart: previous !== undefined ? previous.groupEnd : 0, groupEnd: -1, groupCount: -1, inherited: false, clone: function clone(index) { var cloned = { index: typeof index === 'number' ? index : this.index, name: this.name, mtllib: this.mtllib, smooth: this.smooth, groupStart: 0, groupEnd: -1, groupCount: -1, inherited: false }; cloned.clone = this.clone.bind(cloned); return cloned; } }; this.materials.push(material); return material; }, currentMaterial: function currentMaterial() { if (this.materials.length > 0) { return this.materials[this.materials.length - 1]; } return undefined; }, _finalize: function _finalize(end) { var lastMultiMaterial = this.currentMaterial(); if (lastMultiMaterial && lastMultiMaterial.groupEnd === -1) { lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3; lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart; lastMultiMaterial.inherited = false; } // Ignore objects tail materials if no face declarations followed them before a new o/g started. if (end && this.materials.length > 1) { for (var mi = this.materials.length - 1; mi >= 0; mi--) { if (this.materials[mi].groupCount <= 0) { this.materials.splice(mi, 1); } } } // Guarantee at least one empty material, this makes the creation later more straight forward. if (end && this.materials.length === 0) { this.materials.push({ name: '', smooth: this.smooth }); } return lastMultiMaterial; } }; // Inherit previous objects material. // Spec tells us that a declared material must be set to all objects until a new material is declared. // If a usemtl declaration is encountered while this new object is being parsed, it will // overwrite the inherited material. Exception being that there was already face declarations // to the inherited material, then it will be preserved for proper MultiMaterial continuation. if (previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function') { var declared = previousMaterial.clone(0); declared.inherited = true; this.object.materials.push(declared); } this.objects.push(this.object); }, finalize: function finalize() { if (this.object && typeof this.object._finalize === 'function') { this.object._finalize(true); } }, parseVertexIndex: function parseVertexIndex(value, len) { var index = parseInt(value, 10); return (index >= 0 ? index - 1 : index + len / 3) * 3; }, parseNormalIndex: function parseNormalIndex(value, len) { var index = parseInt(value, 10); return (index >= 0 ? index - 1 : index + len / 3) * 3; }, parseUVIndex: function parseUVIndex(value, len) { var index = parseInt(value, 10); return (index >= 0 ? index - 1 : index + len / 2) * 2; }, addVertex: function addVertex(a, b, c) { var src = this.vertices; var dst = this.object.geometry.vertices; dst.push(src[a + 0], src[a + 1], src[a + 2]); dst.push(src[b + 0], src[b + 1], src[b + 2]); dst.push(src[c + 0], src[c + 1], src[c + 2]); }, addVertexPoint: function addVertexPoint(a) { var src = this.vertices; var dst = this.object.geometry.vertices; dst.push(src[a + 0], src[a + 1], src[a + 2]); }, addVertexLine: function addVertexLine(a) { var src = this.vertices; var dst = this.object.geometry.vertices; dst.push(src[a + 0], src[a + 1], src[a + 2]); }, addNormal: function addNormal(a, b, c) { var src = this.normals; var dst = this.object.geometry.normals; dst.push(src[a + 0], src[a + 1], src[a + 2]); dst.push(src[b + 0], src[b + 1], src[b + 2]); dst.push(src[c + 0], src[c + 1], src[c + 2]); }, addFaceNormal: function addFaceNormal(a, b, c) { var src = this.vertices; var dst = this.object.geometry.normals; vA.fromArray(src, a); vB.fromArray(src, b); vC.fromArray(src, c); cb.subVectors(vC, vB); ab.subVectors(vA, vB); cb.cross(ab); cb.normalize(); dst.push(cb.x, cb.y, cb.z); dst.push(cb.x, cb.y, cb.z); dst.push(cb.x, cb.y, cb.z); }, addColor: function addColor(a, b, c) { var src = this.colors; var dst = this.object.geometry.colors; if (src[a] !== undefined) dst.push(src[a + 0], src[a + 1], src[a + 2]); if (src[b] !== undefined) dst.push(src[b + 0], src[b + 1], src[b + 2]); if (src[c] !== undefined) dst.push(src[c + 0], src[c + 1], src[c + 2]); }, addUV: function addUV(a, b, c) { var src = this.uvs; var dst = this.object.geometry.uvs; dst.push(src[a + 0], src[a + 1]); dst.push(src[b + 0], src[b + 1]); dst.push(src[c + 0], src[c + 1]); }, addDefaultUV: function addDefaultUV() { var dst = this.object.geometry.uvs; dst.push(0, 0); dst.push(0, 0); dst.push(0, 0); }, addUVLine: function addUVLine(a) { var src = this.uvs; var dst = this.object.geometry.uvs; dst.push(src[a + 0], src[a + 1]); }, addFace: function addFace(a, b, c, ua, ub, uc, na, nb, nc) { var vLen = this.vertices.length; var ia = this.parseVertexIndex(a, vLen); var ib = this.parseVertexIndex(b, vLen); var ic = this.parseVertexIndex(c, vLen); this.addVertex(ia, ib, ic); this.addColor(ia, ib, ic); // normals if (na !== undefined && na !== '') { var nLen = this.normals.length; ia = this.parseNormalIndex(na, nLen); ib = this.parseNormalIndex(nb, nLen); ic = this.parseNormalIndex(nc, nLen); this.addNormal(ia, ib, ic); } else { this.addFaceNormal(ia, ib, ic); } // uvs if (ua !== undefined && ua !== '') { var uvLen = this.uvs.length; ia = this.parseUVIndex(ua, uvLen); ib = this.parseUVIndex(ub, uvLen); ic = this.parseUVIndex(uc, uvLen); this.addUV(ia, ib, ic); this.object.geometry.hasUVIndices = true; } else { // add placeholder values (for inconsistent face definitions) this.addDefaultUV(); } }, addPointGeometry: function addPointGeometry(vertices) { this.object.geometry.type = 'Points'; var vLen = this.vertices.length; for (var vi = 0, l = vertices.length; vi < l; vi++) { var index = this.parseVertexIndex(vertices[vi], vLen); this.addVertexPoint(index); this.addColor(index); } }, addLineGeometry: function addLineGeometry(vertices, uvs) { this.object.geometry.type = 'Line'; var vLen = this.vertices.length; var uvLen = this.uvs.length; for (var vi = 0, l = vertices.length; vi < l; vi++) { this.addVertexLine(this.parseVertexIndex(vertices[vi], vLen)); } for (var uvi = 0, l = uvs.length; uvi < l; uvi++) { this.addUVLine(this.parseUVIndex(uvs[uvi], uvLen)); } } }; state.startObject('', false); return state; } // function OBJLoader(manager) { Loader.call(this, manager); this.materials = null; } OBJLoader.prototype = Object.assign(Object.create(Loader.prototype), { constructor: OBJLoader, load: function load(url, onLoad, onProgress, onError) { var scope = this; var loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setRequestHeader(this.requestHeader); loader.setWithCredentials(this.withCredentials); loader.load(url, function (text, total) { // xzw add total try { onLoad(scope.parse(text), total); } catch (e) { if (onError) { onError(e); } else { console.error(e); } scope.manager.itemError(url); } }, onProgress, onError); }, setMaterials: function setMaterials(materials) { this.materials = materials; return this; }, parse: function parse(text) { var state = new ParserState(); if (text.indexOf('\r\n') !== -1) { // This is faster than String.split with regex that splits on both text = text.replace(/\r\n/g, '\n'); } if (text.indexOf('\\\n') !== -1) { // join lines separated by a line continuation character (\) text = text.replace(/\\\n/g, ''); } var lines = text.split('\n'); var line = '', lineFirstChar = ''; var lineLength = 0; var result = []; // Faster to just trim left side of the line. Use if available. var trimLeft = typeof ''.trimLeft === 'function'; for (var i = 0, l = lines.length; i < l; i++) { line = lines[i]; line = trimLeft ? line.trimLeft() : line.trim(); lineLength = line.length; if (lineLength === 0) continue; lineFirstChar = line.charAt(0); // @todo invoke passed in handler if any if (lineFirstChar === '#') continue; if (lineFirstChar === 'v') { var data = line.split(/\s+/); switch (data[0]) { case 'v': state.vertices.push(parseFloat(data[1]), parseFloat(data[2]), parseFloat(data[3])); if (data.length >= 7) { state.colors.push(parseFloat(data[4]), parseFloat(data[5]), parseFloat(data[6])); } else { // if no colors are defined, add placeholders so color and vertex indices match state.colors.push(undefined, undefined, undefined); } break; case 'vn': state.normals.push(parseFloat(data[1]), parseFloat(data[2]), parseFloat(data[3])); break; case 'vt': state.uvs.push(parseFloat(data[1]), parseFloat(data[2])); break; } } else if (lineFirstChar === 'f') { var lineData = line.substr(1).trim(); var vertexData = lineData.split(/\s+/); var faceVertices = []; // Parse the face vertex data into an easy to work with format for (var j = 0, jl = vertexData.length; j < jl; j++) { var vertex = vertexData[j]; if (vertex.length > 0) { var vertexParts = vertex.split('/'); faceVertices.push(vertexParts); } } // Draw an edge between the first vertex and all subsequent vertices to form an n-gon var v1 = faceVertices[0]; for (var j = 1, jl = faceVertices.length - 1; j < jl; j++) { var v2 = faceVertices[j]; var v3 = faceVertices[j + 1]; state.addFace(v1[0], v2[0], v3[0], v1[1], v2[1], v3[1], v1[2], v2[2], v3[2]); } } else if (lineFirstChar === 'l') { var lineParts = line.substring(1).trim().split(' '); var lineVertices = [], lineUVs = []; if (line.indexOf('/') === -1) { lineVertices = lineParts; } else { for (var li = 0, llen = lineParts.length; li < llen; li++) { var parts = lineParts[li].split('/'); if (parts[0] !== '') lineVertices.push(parts[0]); if (parts[1] !== '') lineUVs.push(parts[1]); } } state.addLineGeometry(lineVertices, lineUVs); } else if (lineFirstChar === 'p') { var lineData = line.substr(1).trim(); var pointData = lineData.split(' '); state.addPointGeometry(pointData); } else if ((result = object_pattern.exec(line)) !== null) { // o object_name // or // g group_name // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869 // var name = result[ 0 ].substr( 1 ).trim(); var name = (' ' + result[0].substr(1).trim()).substr(1); state.startObject(name); } else if (material_use_pattern.test(line)) { // material state.object.startMaterial(line.substring(7).trim(), state.materialLibraries); } else if (material_library_pattern.test(line)) { // mtl file state.materialLibraries.push(line.substring(7).trim()); } else if (map_use_pattern.test(line)) { // the line is parsed but ignored since the loader assumes textures are defined MTL files // (according to https://www.okino.com/conv/imp_wave.htm, 'usemap' is the old-style Wavefront texture reference method) console.warn('THREE.OBJLoader: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.'); } else if (lineFirstChar === 's') { result = line.split(' '); // smooth shading // @todo Handle files that have varying smooth values for a set of faces inside one geometry, // but does not define a usemtl for each face set. // This should be detected and a dummy material created (later MultiMaterial and geometry groups). // This requires some care to not create extra material on each smooth value for "normal" obj files. // where explicit usemtl defines geometry groups. // Example asset: examples/models/obj/cerberus/Cerberus.obj /* * http://paulbourke.net/dataformats/obj/ * or * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf * * From chapter "Grouping" Syntax explanation "s group_number": * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form * surfaces, smoothing groups are either turned on or off; there is no difference between values greater * than 0." */ if (result.length > 1) { var value = result[1].trim().toLowerCase(); state.object.smooth = value !== '0' && value !== 'off'; } else { // ZBrush can produce "s" lines #11707 state.object.smooth = true; } var material = state.object.currentMaterial(); if (material) material.smooth = state.object.smooth; } else { // Handle null terminated files without exception if (line === '\0') continue; console.warn('THREE.OBJLoader: Unexpected line: "' + line + '"'); } } state.finalize(); var container = new Group(); container.materialLibraries = [].concat(state.materialLibraries); var hasPrimitives = !(state.objects.length === 1 && state.objects[0].geometry.vertices.length === 0); if (hasPrimitives === true) { for (var i = 0, l = state.objects.length; i < l; i++) { var object = state.objects[i]; var geometry = object.geometry; var materials = object.materials; var isLine = geometry.type === 'Line'; var isPoints = geometry.type === 'Points'; var hasVertexColors = false; // Skip o/g line declarations that did not follow with any faces if (geometry.vertices.length === 0) continue; var buffergeometry = new BufferGeometry(); buffergeometry.setAttribute('position', new Float32BufferAttribute(geometry.vertices, 3)); if (geometry.normals.length > 0) { buffergeometry.setAttribute('normal', new Float32BufferAttribute(geometry.normals, 3)); } if (geometry.colors.length > 0) { hasVertexColors = true; buffergeometry.setAttribute('color', new Float32BufferAttribute(geometry.colors, 3)); } if (geometry.hasUVIndices === true) { buffergeometry.setAttribute('uv', new Float32BufferAttribute(geometry.uvs, 2)); } // Create materials var createdMaterials = []; for (var mi = 0, miLen = materials.length; mi < miLen; mi++) { var sourceMaterial = materials[mi]; var materialHash = sourceMaterial.name + '_' + sourceMaterial.smooth + '_' + hasVertexColors; var material = state.materials[materialHash]; if (this.materials !== null) { material = this.materials.create(sourceMaterial.name); // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material. if (isLine && material && !(material instanceof LineBasicMaterial)) { var materialLine = new LineBasicMaterial(); Material.prototype.copy.call(materialLine, material); materialLine.color.copy(material.color); material = materialLine; } else if (isPoints && material && !(material instanceof PointsMaterial)) { var materialPoints = new PointsMaterial({ size: 10, sizeAttenuation: false }); Material.prototype.copy.call(materialPoints, material); materialPoints.color.copy(material.color); materialPoints.map = material.map; material = materialPoints; } } if (material === undefined) { if (isLine) { material = new LineBasicMaterial(); } else if (isPoints) { material = new PointsMaterial({ size: 1, sizeAttenuation: false }); } else { material = new MeshPhongMaterial(); } material.name = sourceMaterial.name; material.flatShading = sourceMaterial.smooth ? false : true; material.vertexColors = hasVertexColors; state.materials[materialHash] = material; } createdMaterials.push(material); } // Create mesh var mesh; if (createdMaterials.length > 1) { for (var mi = 0, miLen = materials.length; mi < miLen; mi++) { var sourceMaterial = materials[mi]; buffergeometry.addGroup(sourceMaterial.groupStart, sourceMaterial.groupCount, mi); } if (isLine) { mesh = new LineSegments(buffergeometry, createdMaterials); } else if (isPoints) { mesh = new Points(buffergeometry, createdMaterials); } else { mesh = new Mesh(buffergeometry, createdMaterials); } } else { if (isLine) { mesh = new LineSegments(buffergeometry, createdMaterials[0]); } else if (isPoints) { mesh = new Points(buffergeometry, createdMaterials[0]); } else { mesh = new Mesh(buffergeometry, createdMaterials[0]); } } mesh.name = object.name; container.add(mesh); } } else { // if there is only the default parser state object with no geometry data, interpret data as point cloud if (state.vertices.length > 0) { var material = new PointsMaterial({ size: 1, sizeAttenuation: false }); var buffergeometry = new BufferGeometry(); buffergeometry.setAttribute('position', new Float32BufferAttribute(state.vertices, 3)); if (state.colors.length > 0 && state.colors[0] !== undefined) { buffergeometry.setAttribute('color', new Float32BufferAttribute(state.colors, 3)); material.vertexColors = true; } var points = new Points(buffergeometry, material); container.add(points); } } return container; } }); return OBJLoader; }(); /** * Loads a Wavefront .mtl file specifying materials */ var MTLLoader = function MTLLoader(manager) { Loader.call(this, manager); }; MTLLoader.prototype = Object.assign(Object.create(Loader.prototype), { constructor: MTLLoader, /** * Loads and parses a MTL asset from a URL. * * @param {String} url - URL to the MTL file. * @param {Function} [onLoad] - Callback invoked with the loaded object. * @param {Function} [onProgress] - Callback for download progress. * @param {Function} [onError] - Callback for download errors. * * @see setPath setResourcePath * * @note In order for relative texture references to resolve correctly * you must call setResourcePath() explicitly prior to load. */ load: function load(url, onLoad, onProgress, onError) { var scope = this; var path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path; var loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setRequestHeader(this.requestHeader); loader.setWithCredentials(this.withCredentials); loader.load(url, function (text) { try { onLoad(scope.parse(text, path)); } catch (e) { if (onError) { onError(e); } else { console.error(e); } scope.manager.itemError(url); } }, onProgress, onError); }, setMaterialOptions: function setMaterialOptions(value) { this.materialOptions = value; return this; }, /** * Parses a MTL file. * * @param {String} text - Content of MTL file * @return {MTLLoader.MaterialCreator} * * @see setPath setResourcePath * * @note In order for relative texture references to resolve correctly * you must call setResourcePath() explicitly prior to parse. */ parse: function parse(text, path) { var lines = text.split('\n'); var info = {}; var delimiter_pattern = /\s+/; var materialsInfo = {}; for (var i = 0; i < lines.length; i++) { var line = lines[i]; line = line.trim(); if (line.length === 0 || line.charAt(0) === '#') { // Blank line or comment ignore continue; } var pos = line.indexOf(' '); var key = pos >= 0 ? line.substring(0, pos) : line; key = key.toLowerCase(); var value = pos >= 0 ? line.substring(pos + 1) : ''; value = value.trim(); if (key === 'newmtl') { // New material info = { name: value }; materialsInfo[value] = info; } else { if (key === 'ka' || key === 'kd' || key === 'ks' || key === 'ke') { var ss = value.split(delimiter_pattern, 3); info[key] = [parseFloat(ss[0]), parseFloat(ss[1]), parseFloat(ss[2])]; } else { info[key] = value; } } } var materialCreator = new MTLLoader.MaterialCreator(this.resourcePath || path, this.materialOptions); materialCreator.setCrossOrigin(this.crossOrigin); materialCreator.setManager(this.manager); materialCreator.setMaterials(materialsInfo); return materialCreator; } }); /** * Create a new MTLLoader.MaterialCreator * @param baseUrl - Url relative to which textures are loaded * @param options - Set of options on how to construct the materials * side: Which side to apply the material * FrontSide (default), THREE.BackSide, THREE.DoubleSide * wrap: What type of wrapping to apply for textures * RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255 * Default: false, assumed to be already normalized * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's * Default: false * @constructor */ MTLLoader.MaterialCreator = function (baseUrl, options) { this.baseUrl = baseUrl || ''; this.options = options; this.materialsInfo = {}; this.materials = {}; this.materialsArray = []; this.nameLookup = {}; this.side = this.options && this.options.side ? this.options.side : FrontSide; this.wrap = this.options && this.options.wrap ? this.options.wrap : RepeatWrapping; }; MTLLoader.MaterialCreator.prototype = { constructor: MTLLoader.MaterialCreator, crossOrigin: 'anonymous', setCrossOrigin: function setCrossOrigin(value) { this.crossOrigin = value; return this; }, setManager: function setManager(value) { this.manager = value; }, setMaterials: function setMaterials(materialsInfo) { this.materialsInfo = this.convert(materialsInfo); this.materials = {}; this.materialsArray = []; this.nameLookup = {}; }, convert: function convert(materialsInfo) { if (!this.options) return materialsInfo; var converted = {}; for (var mn in materialsInfo) { // Convert materials info into normalized form based on options var mat = materialsInfo[mn]; var covmat = {}; converted[mn] = covmat; for (var prop in mat) { var save = true; var value = mat[prop]; var lprop = prop.toLowerCase(); switch (lprop) { case 'kd': case 'ka': case 'ks': // Diffuse color (color under white light) using RGB values if (this.options && this.options.normalizeRGB) { value = [value[0] / 255, value[1] / 255, value[2] / 255]; } if (this.options && this.options.ignoreZeroRGBs) { if (value[0] === 0 && value[1] === 0 && value[2] === 0) { // ignore save = false; } } break; default: break; } if (save) { covmat[lprop] = value; } } } return converted; }, preload: function preload() { for (var mn in this.materialsInfo) { this.create(mn); } }, getIndex: function getIndex(materialName) { return this.nameLookup[materialName]; }, getAsArray: function getAsArray() { var index = 0; for (var mn in this.materialsInfo) { this.materialsArray[index] = this.create(mn); this.nameLookup[mn] = index; index++; } return this.materialsArray; }, create: function create(materialName) { if (this.materials[materialName] === undefined) { this.createMaterial_(materialName); } return this.materials[materialName]; }, createMaterial_: function createMaterial_(materialName) { // Create material var scope = this; var mat = this.materialsInfo[materialName]; var params = { name: materialName, side: this.side }; function resolveURL(baseUrl, url) { if (typeof url !== 'string' || url === '') return ''; // Absolute URL if (/^https?:\/\//i.test(url)) return url; return baseUrl + url; } function setMapForType(mapType, value) { if (params[mapType]) return; // Keep the first encountered texture var texParams = scope.getTextureParams(value, params); var map = scope.loadTexture(resolveURL(scope.baseUrl, texParams.url)); map.repeat.copy(texParams.scale); map.offset.copy(texParams.offset); map.wrapS = scope.wrap; map.wrapT = scope.wrap; params[mapType] = map; } for (var prop in mat) { var value = mat[prop]; var n; if (value === '') continue; switch (prop.toLowerCase()) { // Ns is material specular exponent case 'kd': // Diffuse color (color under white light) using RGB values params.color = new Color().fromArray(value); break; case 'ks': // Specular color (color when light is reflected from shiny surface) using RGB values //params.specular = new Color().fromArray( value ); //console.log('specular',value) break; case 'ke': // Emissive using RGB values params.emissive = new Color().fromArray(value); break; case 'map_kd': // Diffuse texture map setMapForType('map', value); break; case 'map_ks': // Specular map setMapForType('specularMap', value); break; case 'map_ke': // Emissive map setMapForType('emissiveMap', value); break; case 'norm': setMapForType('normalMap', value); break; case 'map_bump': case 'bump': // Bump texture map setMapForType('bumpMap', value); break; case 'map_d': // Alpha map setMapForType('alphaMap', value); params.transparent = true; break; case 'ns': // The specular exponent (defines the focus of the specular highlight) // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000. //params.shininess = parseFloat( value ); //console.log('shininess',value) break; case 'd': n = parseFloat(value); if (n < 1) { params.opacity = n; params.transparent = true; } break; case 'tr': n = parseFloat(value); if (this.options && this.options.invertTrProperty) n = 1 - n; if (n > 0) { params.opacity = 1 - n; params.transparent = true; } break; default: break; } } this.materials[materialName] = new MeshStandardMaterial(params); //MeshPhongMaterial( params ); return this.materials[materialName]; }, getTextureParams: function getTextureParams(value, matParams) { var texParams = { scale: new Vector2(1, 1), offset: new Vector2(0, 0) }; var items = value.split(/\s+/); var pos; pos = items.indexOf('-bm'); if (pos >= 0) { matParams.bumpScale = parseFloat(items[pos + 1]); items.splice(pos, 2); } pos = items.indexOf('-s'); if (pos >= 0) { texParams.scale.set(parseFloat(items[pos + 1]), parseFloat(items[pos + 2])); items.splice(pos, 4); // we expect 3 parameters here! } pos = items.indexOf('-o'); if (pos >= 0) { texParams.offset.set(parseFloat(items[pos + 1]), parseFloat(items[pos + 2])); items.splice(pos, 4); // we expect 3 parameters here! } texParams.url = items.join(' ').trim(); return texParams; }, loadTexture: function loadTexture(url, mapping, onLoad, onProgress, onError) { var texture; var manager = this.manager !== undefined ? this.manager : DefaultLoadingManager; var loader = manager.getHandler(url); if (loader === null) { loader = new TextureLoader(manager); } if (loader.setCrossOrigin) loader.setCrossOrigin(this.crossOrigin); texture = loader.load(url, onLoad, onProgress, onError); if (mapping !== undefined) texture.mapping = mapping; return texture; } }; /** * Description: A THREE loader for PLY ASCII files (known as the Polygon * File Format or the Stanford Triangle Format). * * Limitations: ASCII decoding assumes file is UTF-8. * * Usage: * var loader = new PLYLoader(); * loader.load('./models/ply/ascii/dolphins.ply', function (geometry) { * * scene.add( new THREE.Mesh( geometry ) ); * * } ); * * If the PLY file uses non standard property names, they can be mapped while * loading. For example, the following maps the properties * “diffuse_(red|green|blue)” in the file to standard color names. * * loader.setPropertyNameMapping( { * diffuse_red: 'red', * diffuse_green: 'green', * diffuse_blue: 'blue' * } ); * */ var PLYLoader = function PLYLoader(manager) { Loader.call(this, manager); this.propertyNameMapping = {}; }; PLYLoader.prototype = Object.assign(Object.create(Loader.prototype), { constructor: PLYLoader, load: function load(url, onLoad, onProgress, onError) { var scope = this; var loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setResponseType('arraybuffer'); loader.setRequestHeader(this.requestHeader); loader.setWithCredentials(this.withCredentials); loader.load(url, function (text) { try { onLoad(scope.parse(text)); } catch (e) { if (onError) { onError(e); } else { console.error(e); } scope.manager.itemError(url); } }, onProgress, onError); }, setPropertyNameMapping: function setPropertyNameMapping(mapping) { this.propertyNameMapping = mapping; }, parse: function parse(data) { function parseHeader(data) { var patternHeader = /ply([\s\S]*)end_header\r?\n/; var headerText = ''; var headerLength = 0; var result = patternHeader.exec(data); if (result !== null) { headerText = result[1]; headerLength = new Blob([result[0]]).size; } var header = { comments: [], elements: [], headerLength: headerLength, objInfo: '' }; var lines = headerText.split('\n'); var currentElement; var lineType, lineValues; function make_ply_element_property(propertValues, propertyNameMapping) { var property = { type: propertValues[0] }; if (property.type === 'list') { property.name = propertValues[3]; property.countType = propertValues[1]; property.itemType = propertValues[2]; } else { property.name = propertValues[1]; } if (property.name in propertyNameMapping) { property.name = propertyNameMapping[property.name]; } return property; } for (var i = 0; i < lines.length; i++) { var line = lines[i]; line = line.trim(); if (line === '') continue; lineValues = line.split(/\s+/); lineType = lineValues.shift(); line = lineValues.join(' '); switch (lineType) { case 'format': header.format = lineValues[0]; header.version = lineValues[1]; break; case 'comment': header.comments.push(line); break; case 'element': if (currentElement !== undefined) { header.elements.push(currentElement); } currentElement = {}; currentElement.name = lineValues[0]; currentElement.count = parseInt(lineValues[1]); currentElement.properties = []; break; case 'property': currentElement.properties.push(make_ply_element_property(lineValues, scope.propertyNameMapping)); break; case 'obj_info': header.objInfo = line; break; default: console.log('unhandled', lineType, lineValues); } } if (currentElement !== undefined) { header.elements.push(currentElement); } return header; } function parseASCIINumber(n, type) { switch (type) { case 'char': case 'uchar': case 'short': case 'ushort': case 'int': case 'uint': case 'int8': case 'uint8': case 'int16': case 'uint16': case 'int32': case 'uint32': return parseInt(n); case 'float': case 'double': case 'float32': case 'float64': return parseFloat(n); } } function parseASCIIElement(properties, line) { var values = line.split(/\s+/); var element = {}; for (var i = 0; i < properties.length; i++) { if (properties[i].type === 'list') { var list = []; var n = parseASCIINumber(values.shift(), properties[i].countType); for (var j = 0; j < n; j++) { list.push(parseASCIINumber(values.shift(), properties[i].itemType)); } element[properties[i].name] = list; } else { element[properties[i].name] = parseASCIINumber(values.shift(), properties[i].type); } } return element; } function parseASCII(data, header) { // PLY ascii format specification, as per http://en.wikipedia.org/wiki/PLY_(file_format) var buffer = { indices: [], vertices: [], normals: [], uvs: [], faceVertexUvs: [], colors: [] }; var result; var patternBody = /end_header\s([\s\S]*)$/; var body = ''; if ((result = patternBody.exec(data)) !== null) { body = result[1]; } var lines = body.split('\n'); var currentElement = 0; var currentElementCount = 0; for (var i = 0; i < lines.length; i++) { var line = lines[i]; line = line.trim(); if (line === '') { continue; } if (currentElementCount >= header.elements[currentElement].count) { currentElement++; currentElementCount = 0; } var element = parseASCIIElement(header.elements[currentElement].properties, line); handleElement(buffer, header.elements[currentElement].name, element); currentElementCount++; } return postProcess(buffer); } function postProcess(buffer) { var geometry = new BufferGeometry(); // mandatory buffer data if (buffer.indices.length > 0) { geometry.setIndex(buffer.indices); } geometry.setAttribute('position', new Float32BufferAttribute(buffer.vertices, 3)); // optional buffer data if (buffer.normals.length > 0) { geometry.setAttribute('normal', new Float32BufferAttribute(buffer.normals, 3)); } if (buffer.uvs.length > 0) { geometry.setAttribute('uv', new Float32BufferAttribute(buffer.uvs, 2)); } if (buffer.colors.length > 0) { geometry.setAttribute('color', new Float32BufferAttribute(buffer.colors, 3)); } if (buffer.faceVertexUvs.length > 0) { geometry = geometry.toNonIndexed(); geometry.setAttribute('uv', new Float32BufferAttribute(buffer.faceVertexUvs, 2)); } geometry.computeBoundingSphere(); return geometry; } function handleElement(buffer, elementName, element) { if (elementName === 'vertex') { buffer.vertices.push(element.x, element.y, element.z); if ('nx' in element && 'ny' in element && 'nz' in element) { buffer.normals.push(element.nx, element.ny, element.nz); } if ('s' in element && 't' in element) { buffer.uvs.push(element.s, element.t); } if ('red' in element && 'green' in element && 'blue' in element) { buffer.colors.push(element.red / 255.0, element.green / 255.0, element.blue / 255.0); } } else if (elementName === 'face') { var vertex_indices = element.vertex_indices || element.vertex_index; // issue #9338 var texcoord = element.texcoord; if (vertex_indices.length === 3) { buffer.indices.push(vertex_indices[0], vertex_indices[1], vertex_indices[2]); if (texcoord && texcoord.length === 6) { buffer.faceVertexUvs.push(texcoord[0], texcoord[1]); buffer.faceVertexUvs.push(texcoord[2], texcoord[3]); buffer.faceVertexUvs.push(texcoord[4], texcoord[5]); } } else if (vertex_indices.length === 4) { buffer.indices.push(vertex_indices[0], vertex_indices[1], vertex_indices[3]); buffer.indices.push(vertex_indices[1], vertex_indices[2], vertex_indices[3]); } } } function binaryRead(dataview, at, type, little_endian) { switch (type) { // corespondences for non-specific length types here match rply: case 'int8': case 'char': return [dataview.getInt8(at), 1]; case 'uint8': case 'uchar': return [dataview.getUint8(at), 1]; case 'int16': case 'short': return [dataview.getInt16(at, little_endian), 2]; case 'uint16': case 'ushort': return [dataview.getUint16(at, little_endian), 2]; case 'int32': case 'int': return [dataview.getInt32(at, little_endian), 4]; case 'uint32': case 'uint': return [dataview.getUint32(at, little_endian), 4]; case 'float32': case 'float': return [dataview.getFloat32(at, little_endian), 4]; case 'float64': case 'double': return [dataview.getFloat64(at, little_endian), 8]; } } function binaryReadElement(dataview, at, properties, little_endian) { var element = {}; var result, read = 0; for (var i = 0; i < properties.length; i++) { if (properties[i].type === 'list') { var list = []; result = binaryRead(dataview, at + read, properties[i].countType, little_endian); var n = result[0]; read += result[1]; for (var j = 0; j < n; j++) { result = binaryRead(dataview, at + read, properties[i].itemType, little_endian); list.push(result[0]); read += result[1]; } element[properties[i].name] = list; } else { result = binaryRead(dataview, at + read, properties[i].type, little_endian); element[properties[i].name] = result[0]; read += result[1]; } } return [element, read]; } function parseBinary(data, header) { var buffer = { indices: [], vertices: [], normals: [], uvs: [], faceVertexUvs: [], colors: [] }; var little_endian = header.format === 'binary_little_endian'; var body = new DataView(data, header.headerLength); var result, loc = 0; for (var currentElement = 0; currentElement < header.elements.length; currentElement++) { for (var currentElementCount = 0; currentElementCount < header.elements[currentElement].count; currentElementCount++) { result = binaryReadElement(body, loc, header.elements[currentElement].properties, little_endian); loc += result[1]; var element = result[0]; handleElement(buffer, header.elements[currentElement].name, element); } } return postProcess(buffer); } // var geometry; var scope = this; if (data instanceof ArrayBuffer) { var text = LoaderUtils.decodeText(new Uint8Array(data)); var header = parseHeader(text); geometry = header.format === 'ascii' ? parseASCII(text, header) : parseBinary(data, header); } else { geometry = parseASCII(data, parseHeader(data)); } return geometry; } }); var renderOrders = { line: 0, spot: 15 //高过模型 }; var planeGeo$2 = new PlaneGeometry(1, 1); var texLoader$7 = new TextureLoader(); var lineMat = new LineBasicMaterial({ color: '#ffffff' }); var spotMat; var defaultLineLength = 0.6; var defaultSpotScale = 0.4; class Tag extends Object3D { constructor(o) { super(); this.lineLength = o.lineLength != void 0 ? o.lineLength : defaultLineLength; this.position.copy(o.position); this.normal = o.normal != void 0 ? o.normal : new Vector3(0, 0, -1); this.root = o.root; //this.matrixAutoUpdate = false this.build(); /* this.spot.addEventListener('mouseover',()=>{ }) */ } build() { if (!spotMat) { spotMat = new MeshBasicMaterial({ transparent: true, map: texLoader$7.load(Potree.resourcePath + '/textures/spot_default.png') }); } var endPos = this.normal.clone().multiplyScalar(this.lineLength); this.line = LineDraw.createLine([new Vector3(0, 0, 0), endPos], { mat: lineMat }); var group = new Object3D(); this.spot = new Mesh(planeGeo$2, spotMat); this.spot.scale.set(defaultSpotScale, defaultSpotScale, defaultSpotScale); this.titleLabel = new TextSprite$2({ root: group, text: '1', sizeInfo: { width2d: 200 }, textColor: { r: 255, g: 255, b: 255, a: 1.0 }, backgroundColor: { r: 0, g: 0, b: 0, a: 0.8 }, borderRadius: 6, fontsize: 13, fontWeight: '', //thick renderOrder: renderOrders.spot, pickOrder: renderOrders.spot }); //更新sprite时,实际更新的是root: spot的矩阵 this.spot.renderOrder = renderOrders.spot; /* const mainLabelProp = { backgroundColor: {r: defaultColor.r*255, g: defaultColor.g*255, b: defaultColor.b*255, a:config.measure.default.opacity}, textColor: {r: textColor.r*255, g: textColor.g*255, b: textColor.b*255, a: 1.0}, fontsize:16, useDepth : true , renderOrder : 5, pickOrder:5, } */ this.titleLabel.position.set(0, 0.4, 0); this.titleLabel.sprite.material.depthTest = this.titleLabel.sprite.material.depthWrite = true; group.position.copy(endPos); group.add(this.spot); group.add(this.titleLabel); this.add(group); this.add(this.line); viewer.scene.tags.add(this); } changeTitle(title) { this.titleLabel.changeText(title); } updateMatrixWorld(force) { //重写,只为了将root当做parent this.updateMatrix(); this.matrixWorld.multiplyMatrices(this.root.matrixWorld, this.matrix); var children = this.children; for (var i = 0, l = children.length; i < l; i++) { children[i].updateMatrixWorld(force); } } updateWorldMatrix(updateParents, updateChildren) { //重写,只为了将root当做parent if (updateParents === true && this.root !== null) { this.root.updateWorldMatrix(true, false); } if (this.matrixAutoUpdate) this.updateMatrix(); this.matrixWorld.multiplyMatrices(this.root.matrixWorld, this.matrix); if (updateChildren === true) { var children = this.children; for (var i = 0, l = children.length; i < l; i++) { children[i].updateWorldMatrix(false, true); } } } dispose() { this.parent.remove(this); this.titleLabel.dispose(); } } class TagTool extends EventDispatcher { constructor(viewer) { super(); this.viewer = viewer; this.viewer.addEventListener('start_inserting_tag', e => { this.viewer.dispatchEvent({ type: 'cancel_insertions' }); }); } createTagFromData(data) { var tag = new Tag({ title: data.title, position: data.position, normal: data.normal, root: data.root //e.intersect.pointcloud || e.intersect.object }); return tag; } startInsertion() { var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var callback = arguments.length > 1 ? arguments[1] : undefined; var cancelFun = arguments.length > 2 ? arguments[2] : undefined; var deferred = $.Deferred(); this.viewer.dispatchEvent({ type: 'start_inserting_tag' }); this.adding = true; var cancel = () => { end(); }; var end = () => { this.adding = false; viewer.dispatchEvent({ type: "endTagMove" }); this.viewer.removeEventListener('global_click', click); }; var click = e => { var worldPos = e.intersect && ( /* e.intersect.orthoIntersect || */e.intersect.location); if (!worldPos) { return; } var localPos = Potree.Utils.datasetPosTransform({ toDataset: true, pointcloud: e.intersect.pointcloud, object: e.intersect.object, position: worldPos }); var tag = new Tag({ title: '1', position: localPos, normal: e.intersect.normal, root: e.intersect.pointcloud || e.intersect.object }); //pointcloud里加一个normal 的非float32 end(); e.consume && e.consume(); deferred.resolve(tag); return { stopContinue: true }; }; this.viewer.addEventListener('global_click', click, { importance: 10 }); return deferred.promise(); } } var initDir = new Vector3(0, 1, 0); //指南针模型的北方向 向屏幕里 class Compass extends EventDispatcher { constructor(dom, viewport) { super(); this.angle = 0; this.show = false; if (dom) { this.dom = $(dom); } this.viewport = viewport; this.init(); } init() { var width = 100, height = 100; if (!this.dom) { this.dom = $('
'); $(viewer.renderArea).append(this.dom); } this.dom.css({ display: "none", position: "absolute", right: "1%", top: "60px", width: width + "px", height: height + "px", "z-index": 100, "pointer-events": "none" }); var child = $("
" + /* (config.lang=='zh'? */'北' /* :'N') */ + "
"); this.dom.append(child); this.dom.find(".dirText").css({ textAlign: "center", "font-size": "10px", "position": "absolute", width: "100%", height: "25px", "line-height": "25px" }); this.dom.find(".north").css({ "color": "#02a0e9", "top": "0" }); this.dom.find(".south").css({ "color": "#ff1414", "bottom": "0" }); this.dom.find(".center").css({ //"background":`url(${config.getStaticResource('img')}/dire.png)`, width: width / 2 + "px", height: height / 2 + "px", "background-size": "contain", "background-position": "center", left: "50%", top: "50%", transform: "translate(-50%,-50%)", position: "absolute" }); this.dom.find(".dirText").css({ "text-align": "center", "font-size": "10px", "color": "rgb(255, 255, 255)", "position": "absolute", "top": "50%", "left": "50%", "width": "45%", "height": "0px", "transform-origin": "left center" }); this.dom.find(".dirText span").css({ display: "block", position: "absolute", right: "5px", top: "0", width: "20px", height: "20px", "line-height": "20px", // "font-size": ".75rem ", "margin-top": "-10px" }); try { this.renderer = new WebGLRenderer({ antialias: true, alpha: true }); //许钟文 添加个抗锯齿,否则添加的线条锯齿严重, this.renderer.autoClear = !0; this.renderer.setPixelRatio(window.devicePixelRatio ? window.devicePixelRatio : 1); this.renderer.domElement.setAttribute('name', 'compass'); this.renderer.setClearAlpha(0.0); //xst修改 //this.renderer.setSize(width/2, height/2, false, window.devicePixelRatio ? window.devicePixelRatio : 1); //xst修改 //this.renderer.setPixelRatio(window.devicePixelRatio ? window.devicePixelRatio : 1); //this.renderer.setSize(width/2, height/2); //xst修改 this.renderer.setDrawingBufferSize(width / 2, height / 2, window.devicePixelRatio ? window.devicePixelRatio : 1); //this.emit(SceneRendererEvents.ContextCreated) } catch (e) { viewer.dispatchEvent('webglError', { msg: e }); } this.dom.find(".center")[0].appendChild(this.renderer.domElement); this.renderer.domElement.style.width = this.renderer.domElement.style.height = '100%'; this.camera = new PerspectiveCamera(); this.camera.fov = 50; this.camera.updateProjectionMatrix(); this.scene = new Scene(), this.scene.add(this.camera); this.createCompass(); viewer.addEventListener('camera_changed', e => { if (e.viewport == this.viewport && e.changeInfo.quaternionChanged /* || e.changeInfo.quaternionChanged */) { this.update(); } }); this.setDomPos(); if (this.viewport) this.setDisplay(true); } createCompass() { //ConeBufferGeometry(radius : Float, height : Float, radialSegments : Integer, heightSegments : Integer, openEnded : Boolean, thetaStart : Float, thetaLength : Float) var height = 2; var geometry1 = new ConeBufferGeometry(0.7, height, 4, true); var geometry2 = new ConeBufferGeometry(0.7, height, 4, true); var material = new MeshBasicMaterial({ vertexColors: true }); //指南针由两个四棱锥拼成,为了渐变颜色,采用指定vertexColor的方式。 var setColor = function setColor(geometry, color1, color2) { var colors = []; for (var i = 0, n = geometry.attributes.position.count; i < n; ++i) { colors.push(1, 1, 1); } var set = function set(index, color) { //设置第index个点的颜色 colors[index * 3 + 0] = color[0]; colors[index * 3 + 1] = color[1]; colors[index * 3 + 2] = color[2]; }; var mid = [(color1[0] + color2[0]) / 2, (color1[1] + color2[1]) / 2, (color1[2] + color2[2]) / 2]; set(1, color1); set(5, color1); set(6, color1); set(2, mid); set(3, mid); set(7, mid); set(4, color2); set(8, color2); set(9, color2); geometry.setAttribute("color", new BufferAttribute(new Float32Array(colors), 3)); }; var blue1 = [1 / 255, 238 / 255, 245 / 255]; //逐渐变深 var blue2 = [20 / 255, 146 / 255, 170 / 255]; var blue3 = [40 / 255, 60 / 255, 103 / 255]; setColor(geometry1, blue1, blue2); setColor(geometry2, blue2, blue3); /* 朝箭头方向看点构成如下 虽然geometry.attributes.position.count = 19 只有1-9设置的颜色是有效的 另外为什么7决定了上下两边的颜色呢…… 5、9可将其分成上下两个颜色 6 /|\ / | \ 7 /_2|1_\ 5 \ 3|4 / 9 \ | / \|/ 8 */ var cone = new Mesh(geometry1, material); cone.position.setY(height / 2); geometry1.computeVertexNormals(); //computeFaceNormals geometry2.computeVertexNormals(); var cones = new Object3D(); cones.add(cone); var cone2 = new Mesh(geometry2, material); cone2.rotation.x = Math.PI; cone2.position.setY(-height / 2); cones.add(cone2); //cones.rotation.x = Math.PI / 2;//转向initDir的方向 //cones.rotation.z = Math.PI / 2; cones.rotation.z = Math.PI; //转向initDir的方向 cones.scale.set(0.7, 0.7, 0.7); this.scene.add(cones); this.cones = cones; } setNorth() { //设置北方向,这决定了指南针自身的朝向。 var floors = store.getters['scene/houstFloor'].floors; if (!floors || !floors.length) { return; } var floor = floors[0]; var metadata = app.store.getters['scene/metadata'] || {}; this.angle = (floor && floor.dire || 0) + MathUtils.radToDeg(parseFloat(metadata.floorPlanAngle || 0)); //基础朝向 this.cones.rotation.y = Math.PI / 2 - MathUtils.degToRad(this.angle); //console.log("dir:"+floor.dire+", floorPlanAngle:"+metadata.floorPlanAngle) this.update(); } update(quaternion) { if (!this.show) return; if (!quaternion) quaternion = this.viewport.camera.quaternion.clone(); this.updateCamera(quaternion); this.updateLabel(quaternion); this.render(); } /*updateLabel(quaternion){//更新北标签 var dir = viewer.mainViewport.view.direction; var oriDir = initDir.clone() //指南针最初始时的北方向 var extraQua if(objects.player.mode == "transitioning"){//当transitioning时,相机的quaternion不是用control的lookAt算出来,而是直接由一个quaternion过渡到另一个,这样相机将会是歪的,投影面也就不会是原先的水平面。 var tempCamera = new THREE.Camera(); //借用camera的lookAt算出如果正视同样的target, quaternion会是什么值。 将它乘以当前相机quaternion,得到的就是相机歪的旋转值。 tempCamera.position.copy(this.camera.position); tempCamera.lookAt(tempCamera.position.clone().add(dir)) var q = tempCamera.quaternion.inverse() extraQua = q.premultiply(quaternion) //歪掉的额外旋转值 } //北标签的方向为指南针轮盘方向,也就是要将camera的方向投影到水平面上。 但是如果相机歪了,看到的世界都会歪一定角度,投影面也要歪一定角度。 var up = new THREE.Vector3(0,0,1) //投影水平面的法线,也是相机的摆正的up方向 extraQua && up.applyQuaternion(extraQua) dir.projectOnPlane(up) //将方向投影到水平面上; 如果相机不是正视(extraQua不为0001),就要将水平面也转动 oriDir.projectOnPlane(up)//为什么initDir投影了和没有投影angle结果一样 var angle = dir.angleTo(oriDir) if(dir.cross(oriDir).y > 0)angle = -angle var deg = this.angle - 90 + THREE.Math.radToDeg(angle) //因为css写的样式初始是指向右方,和initDir差了90°,所以减去。 this.dom.find(".dirText").css( "transform","rotate("+deg+"deg)" ) this.dom.find(".dirText span").css("transform","rotate("+(-deg)+"deg)") } */ updateLabel(quaternion) { //更新北标签 var deg = MathUtils.radToDeg(this.viewport.view.yaw) - 90; this.dom.find(".dirText").css("transform", "rotate(" + deg + "deg)"); this.dom.find(".dirText span").css("transform", "rotate(" + -deg + "deg)"); } updateCamera(quaternion) { //更新canvas中的指南针表现,也就是更新相机,和场景中的相机朝向一致。 var radius = 5; //相机距离 this.camera.quaternion.copy(quaternion); var dir = this.viewport.view.direction; //相机朝向 this.camera.position.copy(dir.multiplyScalar(radius).negate()); //相机绕着指南针中心(000)转动 } changeViewport(viewport) { this.viewport = viewport; this.update(); //因相机更新了 } render() { this.renderer.render(this.scene, this.camera); } setDisplay(state) { this.show = !!state; if (this.show) { this.update(); this.dom.fadeIn(100); } else { this.dom.fadeOut(100); } } setAutoDisplay(state) { //被直接改变了dom的显示 this.autoJudgeShow = state; if (state) { this._autoDisplayEvent = () => { var oldShow = this.show; this.show = !!this.renderer.domElement.clientHeight; if (oldShow != this.show) { this.update(); } }; viewer.addEventListener('update_start', this._autoDisplayEvent); } else { viewer.removeEventListener('update_start', this._autoDisplayEvent); } } setDomPos() { if (!this.viewport) return; var right = this.viewport.left + this.viewport.width; this.dom.css({ 'right': (1 - right) * 100 + 1 + '%' }); } } class AxisViewer extends ViewerBase { constructor(listenViewport, parentArea) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var domElement = $("
")); $(parentArea).append(domElement); var posInfo = Object.assign({ //default: right: 0, top: 0, width: '100px', height: '100px' }, options.domStyle, { position: 'absolute' }); if (options.domStyle) { if (options.domStyle.bottom != void 0) { delete posInfo.top; } if (options.domStyle.left != void 0) { delete posInfo.right; } } domElement.css(posInfo); super(domElement[0], { name: 'axis', antialias: true }); this.listenViewport = listenViewport; Object.defineProperty(listenViewport, 'axis', { value: this, writable: true, // 可写(可选) enumerable: false, // 不可枚举 configurable: true // 可配置(可选) }); this.scene = new Scene(); //this.camera = new THREE.PerspectiveCamera(30, 1, 1, this.radius*3); var w = 50; this.camera = new OrthographicCamera(-w / 2, w / 2, w / 2, -w / 2, 1, w * 4); this.camera.zoom = 2.7; //(domElement.clientWidth || 300) / w * 1.267//zoom越大视野越小 this.camera.updateProjectionMatrix(); this.view = new ExtendView(); this.view.radius = 70; this.viewports = [new Viewport(this.view, this.camera, { left: 0, bottom: 0, width: 1, height: 1, name: 'axis' })]; this.updateScreenSize(); this.createAxis(); var updateCamera = e => { if (e.viewport == listenViewport && e.changeInfo.quaternionChanged) { this.update(); } }; viewer.addEventListener('camera_changed', updateCamera); var repos = () => { if (!listenViewport.active || listenViewport.width == 0 || listenViewport.height == 0) { return domElement.css('visibility', 'hidden'); } domElement.css('visibility', 'visible'); var props = [['left', 'right', 'width'], ['bottom', 'top', 'height']]; var set = prop => { var str; var name = posInfo[prop[1]] != void 0 ? prop[1] : prop[0]; var percent = posInfo[prop[1]] != void 0 ? 1 - listenViewport[prop[0]] - listenViewport[prop[2]] : listenViewport[prop[0]]; if (posInfo[name] == 0 || posInfo[name].includes('%')) { str = parseFloat(posInfo[name]) + percent * 100 + '%'; } else { //px str = 'calc(' + percent * 100 + '% + ' + posInfo[name] + ')'; } domElement.css(name, str); }; set(props[0]); set(props[1]); }; this.listenViewport.addEventListener('resize', repos); this.addEventListener('dispose', () => { viewer.removeEventListener('camera_changed', updateCamera); viewer.removeEventListener('resize', repos); }); repos(); this.update(); } createAxis() { var axis = new Object3D(); ['x', 'y', 'z'].forEach(axisText => { var color = new Color().set(Potree.config.axis[axisText].color); var group = new Object3D(); var line = LineDraw.createLine([new Vector3(), new Vector3(0, 0, 7)], { color }); var label = this.createLabel(axisText, color); label.position.set(0, 0, 11 /* + this.renderArea.clientWidth/200 */); if (axisText == 'y') { group.rotation.x = -Math.PI / 2; } else if (axisText == 'x') { group.rotation.y = Math.PI / 2; } group.add(line); group.add(label); axis.add(group); }); this.axis = axis; this.scene.add(this.axis); } createLabel(text, color) { var fontsize = this.renderArea.clientWidth / 5; //20//Math.round( Potree.math.linearClamp(this.renderArea.clientWidth, [80,500],[12,50])) var s = 3100 / this.renderArea.clientWidth; console.log('fontsize', fontsize); var label = new TextSprite$2({ backgroundColor: { r: 0, g: 0, b: 0, a: 0 }, textColor: { r: color.r * 255, g: color.g * 255, b: color.b * 255, a: 1 }, fontsize, //useDepth : true , renderOrder: 5, // pickOrder:5, fontWeight: 'Lighter', text, name: 'axis', viewports: this.viewports }); label.scale.set(s, s, s); return label; } update() { this.updateCamera(); this.render(); } updateCamera() { var view = this.listenViewport.view; this.view.yaw = view.yaw; this.view.pitch = view.pitch; var dir = view.direction; //相机朝向 this.view.position.copy(dir.multiplyScalar(this.view.radius).negate()); //相机绕着指南针中心(000)转动 this.view.applyToCamera(this.camera); } render() { viewer.dispatchEvent({ type: "render.begin", viewport: this.viewports[0] }); //update sprite this.renderer.render(this.scene, this.camera); } dispose() { this.axis.traverse(child => { if (child instanceof TextSprite$2) { child.dispose(); } else if (child instanceof LineSegments) { child.material.dispose(); child.geometry.dispose(); } }); super.dispose(); delete this.listenViewport.axis; } } // // Algorithm by Christian Boucheny // shader code taken and adapted from CloudCompare // // see // https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL // http://www.kitware.com/source/home/post/9 // https://tel.archives-ouvertes.fr/tel-00438464/document p. 115+ (french) class ExtendEyeDomeLightingMaterial extends EyeDomeLightingMaterial { constructor() { var parameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(parameters); delete this.uniforms.screenWidth; delete this.uniforms.screenHeight; this.uniforms.resolution = { type: 'v2', value: new Vector2() }; this.uniforms.useEDL = { type: 'i', value: 1 }; var defines = this.getDefines(); var { vs, fs } = Common.changeShaderToWebgl2(defines + Shaders['edl_new.vs'], defines + Shaders['edl_new.fs'], 'RawShaderMaterial'); this.glslVersion = '300 es'; this.vertexShader = vs; this.fragmentShader = fs; /* this.vertexShader = this.getDefines() + Shaders['edl_new.vs'] //改 this.fragmentShader = this.getDefines() + Shaders['edl_new.fs'] //改 */ } } var copyShader = { uniforms: { tDiffuse: { type: "t", value: null }, opacity: { type: "f", value: 1 }, depthTex: { type: "t", value: null } }, vertexShader: " \n varying vec2 vUv;\n void main() {\n vUv = uv; \n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n }\n ", fragmentShader: "\n #extension GL_EXT_frag_depth : enable\n uniform float opacity;\n uniform sampler2D tDiffuse;\n #if defined(GL_EXT_frag_depth) && defined(useDepth) \n uniform sampler2D depthTex;\n #endif\n \n varying vec2 vUv;\n void main() { \n #if defined(GL_EXT_frag_depth) && defined(useDepth) \n float depth = texture2D(depthTex, vUv).r;\n /* if(depth >= 1.0){ //\u8D85\u7EA7\u8FDC\uFF08\u4F46\u662F\u5728modelTex\u91CC\u6211\u628A\u5929\u7A7A\u8DDD\u79BB\u8D85\u51FAfar\u4E86\uFF0C\u6240\u4EE5\u4E0D\u5220\uFF09\n discard;\n } */\n gl_FragDepthEXT = depth; \n #endif\n \n \n \n vec4 texel = texture2D( tDiffuse, vUv );\n gl_FragColor = opacity * texel; \n \n \n } \n " }; //import DepthTexSampler from "../custom/utils/DepthTexSampler.js"; class EDLRenderer { //Eye-Dome Lighting 眼罩照明 constructor(viewer) { this.viewer = viewer; this.edlMaterial = null; //this.rtRegular; this.rtEDLs = new Map(); this.gl = viewer.renderer.getContext(); //反正也没用到,注释了: //this.shadowMap = new PointCloudSM(this.viewer.pRenderer); viewer.addEventListener('resize', this.resize.bind(this)); this.initEDL(viewer); } initEDL(viewer) { if (this.edlMaterial != null || !Features.EXT_DEPTH.isSupported()) { return; } this.edlMaterial = new ExtendEyeDomeLightingMaterial(); this.edlMaterial.depthTest = true; this.edlMaterial.depthWrite = true; this.edlMaterial.transparent = true; var copyUniforms = UniformsUtils.clone(copyShader.uniforms); var { vs, fs } = Common.changeShaderToWebgl2(copyShader.vertexShader, copyShader.fragmentShader, 'ShaderMaterial'); this.recoverToScreenMat = new ShaderMaterial({ uniforms: copyUniforms, vertexShader: vs, fragmentShader: fs, transparent: true, defines: { useDepth: true //开启后,其他物体才能被遮挡 } }); /* let copyUniforms = THREE.UniformsUtils.clone( copyShader.uniforms ); this.copyMaterial = new THREE.ShaderMaterial( { uniforms: copyUniforms, vertexShader: copyShader.vertexShader, fragmentShader: copyShader.fragmentShader, //premultipliedAlpha: true, transparent: true, //blending: THREE.AdditiveBlending, depthTest: false, depthWrite: false }); */ if (Potree.settings.useRTskybox != Potree.settings.useRTPoint) { //如果两个只开了一个 viewer.images360.addEventListener('endChangeMode', () => { this.resize({ viewport: viewer.mainViewport }); }); } //this.depthTexSampler = new DepthTexSampler(this); } resize(e) { if (Features.EXT_DEPTH.isSupported()) { var viewport = e.viewport; var size = (Potree.settings.displayMode == 'showPanos' ? Potree.settings.useRTskybox : Potree.settings.useRTPoint) ? viewport.resolution2 : viewport.resolution; //若要渲染skybox,需要和设备一样精度的rt this.getRtEDL(viewport).setSize(size.x, size.y); //理论上可以是任意尺寸,但会影响精度,且aspect最好和渲染的一致 } } clearTargets() { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var viewer = this.viewer; var { renderer } = viewer; var oldTarget = renderer.getRenderTarget(); if (params.target) { //add renderer.setRenderTarget(params.target); renderer.clear(); } if (Features.EXT_DEPTH.isSupported()) { if (params.rtEDL) { renderer.setRenderTarget(params.rtEDL); renderer.clear(); } else { var rtEDL = this.getRtEDL(params.viewport); if (rtEDL) { renderer.setRenderTarget(rtEDL); renderer.setClearAlpha(0); renderer.clear(true, true, true); } } } //renderer.setRenderTarget( this.rtRegular ); //renderer.clear( true, true, false ); renderer.setRenderTarget(oldTarget); } getRtEDL(viewport) { //根据不同viewport返回rtEDL的texture if (!viewport) { console.warn('getRtEDL没传viewport!!!! !!!!!!!!!!'); viewport = viewer.mainViewport; } var rtEDL = this.rtEDLs.get(viewport); if (!rtEDL) { if (Features.EXT_DEPTH.isSupported()) { rtEDL = new WebGLRenderTarget(viewport.resolution.x, viewport.resolution.y, { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat, type: FloatType, depthTexture: new DepthTexture(undefined, undefined, UnsignedIntType) }); //注: 部分手机在resize时会崩溃,经检验去掉rtEDL的resize可以解决,所以更应该注释掉这个 this.rtEDLs.set(viewport, rtEDL); } } //注:当pc窗口缩小,deviceRatio变小后,resolution2会小于resolution,然后遮挡会出现精度损失而有细微不准,是正常现象。 return rtEDL; } renderShadowMap(visiblePointClouds, camera, lights) { var { viewer } = this; var doShadows = lights.length > 0 && !lights[0].disableShadowUpdates; if (doShadows) { var light = lights[0]; this.shadowMap.setLight(light); var originalAttributes = new Map(); for (var pointcloud of viewer.scene.pointclouds) { // TODO IMPORTANT !!! check originalAttributes.set(pointcloud, pointcloud.material.activeAttributeName); pointcloud.material.disableEvents(); pointcloud.material.activeAttributeName = "depth"; //pointcloud.material.pointColorType = PointColorType.DEPTH; } this.shadowMap.render(viewer.scene.scenePointCloud, camera); for (var _pointcloud of visiblePointClouds) { var originalAttribute = originalAttributes.get(_pointcloud); // TODO IMPORTANT !!! check _pointcloud.material.activeAttributeName = originalAttribute; _pointcloud.material.enableEvents(); } viewer.shadowTestCam.updateMatrixWorld(); viewer.shadowTestCam.matrixWorldInverse.copy(viewer.shadowTestCam.matrixWorld).invert(); viewer.shadowTestCam.updateProjectionMatrix(); } } render() { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var viewer = this.viewer; var camera = params.camera ? params.camera : viewer.scene.getActiveCamera(); var rtEDL = (Potree.settings.pointEnableRT || Potree.settings.displayMode == 'showPanos' || viewer.useEDL) && Features.EXT_DEPTH.isSupported() && camera.type != "OrthographicCamera" && !params.dontRenderRtEDL && (params.rtEDL || this.getRtEDL(params.viewport)); // 平面相机不用depthTex直接打开depthTest?且不使用edl var useEDL = viewer.useEDL && rtEDL && Potree.settings.displayMode != 'showPanos'; var target = params.target || null; var resolution = rtEDL && Potree.settings.useRTPoint ? new Vector2(rtEDL.width, rtEDL.height) : params.target ? new Vector2(params.target.width, params.target.height) : params.viewport ? params.viewport.resolution2 : this.viewer.renderer.getSize(new Vector2()); //截图时需要用target的大小 var renderer = params.renderer || viewer.renderer; var pRenderer = params.pRenderer || viewer.pRenderer; renderer.setRenderTarget(target); //viewer.dispatchEvent({type: "render.pass.begin",viewer: viewer}); var lights = []; /* viewer.scene.scene.traverse(node => { if(node.type === "SpotLight"){ lights.push(node); } }); */ //skybox 全景图 if (!params.magnifier) { if (Potree.settings.displayMode == 'showPanos' || Potree.settings.testCube) { Potree.Utils.setCameraLayers(camera, ['skybox']); if (Potree.settings.displayMode == 'showPanos' && (viewer.images360.currentPano.pointcloud.hasDepthTex || Potree.settings.modelSkybox && viewer.images360.currentPano.pointcloud.is4dkkModel) && rtEDL) { //渲染深度图 renderer.setRenderTarget(rtEDL); //将带有深度图的skybox画在rtEDL一下,这样就不需要绘制后边的点云了 renderer.render(viewer.scene.scene, camera); renderer.setRenderTarget(target); if (Potree.settings.useRTskybox) { //直接使用rtEDL,但是会失去抗锯齿,不知在skybox上需要抗锯齿吗 this.recoverToScreenMat.uniforms.depthTex.value = rtEDL.depthTexture; this.recoverToScreenMat.uniforms.tDiffuse.value = rtEDL.texture; Utils.screenPass.render(renderer, this.recoverToScreenMat, target); } else { renderer.render(viewer.scene.scene, camera); } } else { renderer.render(viewer.scene.scene, camera); } if (Potree.settings.displayMode == 'showPanos') { if (Potree.settings.fastTran && viewer.images360.fastTranMaskPass.enabled) { viewer.images360.fastTranMaskPass.render(); } return; } } } var visiblePointClouds2 = viewer.scene.pointclouds.filter(pc => Potree.Utils.getObjVisiByReason(pc, 'datasetSelection')); //需要绘制到rtEDL的 var showPointClouds = params.magnifier ? visiblePointClouds2.length > 0 : viewer.scene.pointclouds.some(e => e.visible); //是否有需要绘制到屏幕的 visiblePointClouds2.forEach(e => { //为了绘制到depthTexture,先显示(展示全景图时隐藏了点云,所以需要显示下。且放大镜需要绘制点云) e.oldVisi = e.visible; e.visible = true; }); Potree.Utils.setCameraLayers(camera, ['pointcloud']); //设置多少都会渲染出来,因为渲染里没有sort //camera.layers.set(Potree.config.renderLayers.pointcloud); //TODO adapt to multiple lights //this.renderShadowMap(visiblePointClouds2, camera, lights); //??????? { for (var pointcloud of visiblePointClouds2) { var material = pointcloud.material; var octreeSize = pointcloud.pcoGeometry.boundingBox.getSize(new Vector3()).x; material.fov = MathUtils.degToRad(camera.fov); material.resolution = resolution; material.spacing = pointcloud.pcoGeometry.spacing; // * Math.max(this.scale.x, this.scale.y, this.scale.z); material.near = camera.near; material.far = camera.far; material.uniforms.octreeSize.value = octreeSize; if (useEDL) { material.useEDL = true; //material.fakeEDL = false; //add } else { material.useEDL = false; //material.fakeEDL = true; //add 使也输出深度 } } if (rtEDL) { //借用rtEDL存储深度信息 renderer.setRenderTarget(rtEDL); if (visiblePointClouds2.length > 0) { //渲染scenePointCloud到rtEDL pRenderer.render(viewer.scene.scenePointCloud, camera, rtEDL, { shadowMaps: lights.length > 0 ? [this.shadowMap] : null, clipSpheres: viewer.scene.volumes.filter(v => v instanceof SphereVolume$1), transparent: true, //如果点云透明需要透明 notAdditiveBlending: Potree.settings.notAdditiveBlending }); } if (Potree.settings.intersectOnObjs) { // model也要渲染到rtEDL Potree.Utils.setCameraLayers(camera, ['model', 'light']); viewer.objs.traverse(e => { if (e.material) e._OlddepthWrite = e.material.depthWrite, e.material.depthWrite = true; }); //否则半透明的mesh无法遮住测量线 renderer.render(viewer.scene.scene, camera); viewer.objs.traverse(e => { if (e.material) e.material.depthWrite = e._OlddepthWrite; }); //缺点:半透明的model 就算完全透明, 也会遮住测量线 } } } //渲染到rtEDL完毕 viewer.dispatchEvent({ type: "render.pass.scene", viewer: viewer }); renderer.setRenderTarget(target); if (!params.magnifier) visiblePointClouds2.forEach(e => { //放大镜显示点云 e.visible = e.oldVisi; }); if (showPointClouds) { //绘制点云到画布 if (useEDL) { //设置edlMaterial //Features.EXT_DEPTH不支持的话不会到这一块 var uniforms = this.edlMaterial.uniforms; uniforms.resolution.value.copy(resolution); uniforms.edlStrength.value = viewer.edlStrength; uniforms.radius.value = viewer.edlRadius; uniforms.useEDL.value = 1; //add var proj = camera.projectionMatrix; var projArray = new Float32Array(16); projArray.set(proj.elements); uniforms.uProj.value = projArray; uniforms.uEDLColor.value = rtEDL.texture; uniforms.opacity.value = viewer.edlOpacity; // HACK Utils.screenPass.render(renderer, this.edlMaterial, target); //相当于一个描边后期特效。 缺点: 因为target上的没有抗锯齿,所以点云在晃动镜头时会不稳定地闪烁1px位置。优点:比不打开edl少绘制一次点云,更流畅了?! } else if (Potree.settings.useRTPoint && rtEDL) { this.recoverToScreenMat.uniforms.tDiffuse.value = rtEDL.texture; if (this.recoverToScreenMat.defines.useDepth) { this.recoverToScreenMat.uniforms.depthTex.value = rtEDL.depthTexture; } Utils.screenPass.render(renderer, this.recoverToScreenMat, target /* , Potree.settings.useFxaa && viewer.composer2 */); params.drawedModelOnRT = Potree.settings.intersectOnObjs; } else { //渲染点云 (直接用rtEDL上的会失去抗锯齿, 导致频闪、密集时出现条纹, 自己写抗锯齿也要渲染好几次。另外透明度也要处理下) var prop = { shadowMaps: lights.length > 0 ? [this.shadowMap] : null, clipSpheres: viewer.scene.volumes.filter(v => v instanceof SphereVolume$1), notAdditiveBlending: Potree.settings.notAdditiveBlending //add 否则透明的点云会挡住后面的模型。 加上这句后竟然透明不会叠加了! }; pRenderer.render(viewer.scene.scenePointCloud, camera, null, prop); } } visiblePointClouds2.forEach(e => { e.visible = e.oldVisi; }); //viewer.dispatchEvent({type: "render.pass.end",viewer: viewer}); } /* 渲染顺序: 底层:背景 -> skybox(也可中间) 中间层(含有深度信息):1 点云、marker等mesh, 2 测量线(现在被做成借用depthTex 顶层:maginifier magnifier的贴图渲染不需要顶层、中间层只需要点云。 */ } class NavigationCube extends Object3D { constructor(viewer) { super(); this.viewer = viewer; var createPlaneMaterial = img => { var material = new MeshBasicMaterial({ depthTest: true, depthWrite: true, side: DoubleSide }); new TextureLoader().load(exports.resourcePath + '/textures/navigation/' + img, function (texture) { texture.anisotropy = viewer.renderer.capabilities.getMaxAnisotropy(); material.map = texture; material.needsUpdate = true; }); return material; }; var planeGeometry = new PlaneGeometry(1, 1); this.front = new Mesh(planeGeometry, createPlaneMaterial('F.png')); this.front.position.y = -0.5; this.front.rotation.x = Math.PI / 2.0; this.front.updateMatrixWorld(); this.front.name = "F"; this.add(this.front); this.back = new Mesh(planeGeometry, createPlaneMaterial('B.png')); this.back.position.y = 0.5; this.back.rotation.x = Math.PI / 2.0; this.back.updateMatrixWorld(); this.back.name = "B"; this.add(this.back); this.left = new Mesh(planeGeometry, createPlaneMaterial('L.png')); this.left.position.x = -0.5; this.left.rotation.y = Math.PI / 2.0; this.left.updateMatrixWorld(); this.left.name = "L"; this.add(this.left); this.right = new Mesh(planeGeometry, createPlaneMaterial('R.png')); this.right.position.x = 0.5; this.right.rotation.y = Math.PI / 2.0; this.right.updateMatrixWorld(); this.right.name = "R"; this.add(this.right); this.bottom = new Mesh(planeGeometry, createPlaneMaterial('D.png')); this.bottom.position.z = -0.5; this.bottom.updateMatrixWorld(); this.bottom.name = "D"; this.add(this.bottom); this.top = new Mesh(planeGeometry, createPlaneMaterial('U.png')); this.top.position.z = 0.5; this.top.updateMatrixWorld(); this.top.name = "U"; this.add(this.top); this.width = 150; // in px this.camera = new OrthographicCamera(-1, 1, 1, -1, -1, 1); this.camera.position.copy(new Vector3(0, 0, 0)); this.camera.lookAt(new Vector3(0, 1, 0)); this.camera.updateMatrixWorld(); this.camera.rotation.order = "ZXY"; var onMouseDown = event => { if (!this.visible) { return; } this.pickedFace = null; var mouse = new Vector2(); mouse.x = event.clientX - (window.innerWidth - this.width); mouse.y = event.clientY; if (mouse.x < 0 || mouse.y > this.width) return; mouse.x = mouse.x / this.width * 2 - 1; mouse.y = -(mouse.y / this.width) * 2 + 1; var raycaster = new Raycaster(); raycaster.setFromCamera(mouse, this.camera); raycaster.ray.origin.sub(this.camera.getWorldDirection(new Vector3())); var intersects = raycaster.intersectObjects(this.children); var minDistance = 1000; for (var i = 0; i < intersects.length; i++) { if (intersects[i].distance < minDistance) { this.pickedFace = intersects[i].object.name; minDistance = intersects[i].distance; } } if (this.pickedFace) { this.viewer.setView(this.pickedFace); } }; this.viewer.renderer.domElement.addEventListener('mousedown', onMouseDown, false); } update(rotation) { this.camera.rotation.copy(rotation); this.visible && this.camera.updateMatrixWorld(); } } /** * * @author sigeom sa / http://sigeom.ch * @author Ioda-Net Sàrl / https://www.ioda-net.ch/ * @author Markus Schütz / http://potree.org * */ class GeoJSONExporter { static measurementToFeatures(measurement) { var coords = measurement.points.map(e => e.position.toArray()); var features = []; if (coords.length === 1) { var feature = { type: 'Feature', geometry: { type: 'Point', coordinates: coords[0] }, properties: { name: measurement.name } }; features.push(feature); } else if (coords.length > 1 && !measurement.closed) { var object = { 'type': 'Feature', 'geometry': { 'type': 'LineString', 'coordinates': coords }, 'properties': { name: measurement.name } }; features.push(object); } else if (coords.length > 1 && measurement.closed) { var _object = { 'type': 'Feature', 'geometry': { 'type': 'Polygon', 'coordinates': [[...coords, coords[0]]] }, 'properties': { name: measurement.name } }; features.push(_object); } if (measurement.showDistances) { measurement.edgeLabels.forEach(label => { var labelPoint = { type: 'Feature', geometry: { type: 'Point', coordinates: label.position.toArray() }, properties: { distance: label.text } }; features.push(labelPoint); }); } if (measurement.showArea) { var point = measurement.areaLabel.position; var labelArea = { type: 'Feature', geometry: { type: 'Point', coordinates: point.toArray() }, properties: { area: measurement.areaLabel.text } }; features.push(labelArea); } return features; } static toString(measurements) { if (!(measurements instanceof Array)) { measurements = [measurements]; } measurements = measurements.filter(m => m instanceof Measure); var features = []; for (var measure of measurements) { var f = GeoJSONExporter.measurementToFeatures(measure); features = features.concat(f); } var geojson = { 'type': 'FeatureCollection', 'features': features }; return JSON.stringify(geojson, null, '\t'); } } /** * * @author sigeom sa / http://sigeom.ch * @author Ioda-Net Sàrl / https://www.ioda-net.ch/ * @author Markus Schuetz / http://potree.org * */ class DXFExporter { static measurementPointSection(measurement) { var position = measurement.points[0].position; if (!position) { return ''; } var dxfSection = "0\nCIRCLE\n8\nlayer_point\n10\n".concat(position.x, "\n20\n").concat(position.y, "\n30\n").concat(position.z, "\n40\n1.0\n"); return dxfSection; } static measurementPolylineSection(measurement) { // bit code for polygons/polylines: // https://www.autodesk.com/techpubs/autocad/acad2000/dxf/polyline_dxf_06.htm var geomCode = 8; if (measurement.closed) { geomCode += 1; } var dxfSection = "0\nPOLYLINE\n8\nlayer_polyline\n62\n1\n66\n1\n10\n0.0\n20\n0.0\n30\n0.0\n70\n".concat(geomCode, "\n"); var xMax = 0.0; var yMax = 0.0; var zMax = 0.0; for (var point of measurement.points) { point = point.position; xMax = Math.max(xMax, point.x); yMax = Math.max(yMax, point.y); zMax = Math.max(zMax, point.z); dxfSection += "0\nVERTEX\n8\n0\n10\n".concat(point.x, "\n20\n").concat(point.y, "\n30\n").concat(point.z, "\n70\n32\n"); } dxfSection += "0\nSEQEND\n"; return dxfSection; } static measurementSection(measurement) { // if(measurement.points.length <= 1){ // return ""; // } if (measurement.points.length === 0) { return ''; } else if (measurement.points.length === 1) { return DXFExporter.measurementPointSection(measurement); } else if (measurement.points.length >= 2) { return DXFExporter.measurementPolylineSection(measurement); } } static toString(measurements) { if (!(measurements instanceof Array)) { measurements = [measurements]; } measurements = measurements.filter(m => m instanceof Measure); var points = measurements.filter(m => m instanceof Measure).map(m => m.points).reduce((a, v) => a.concat(v)).map(p => p.position); var min = new Vector3(Infinity, Infinity, Infinity); var max = new Vector3(-Infinity, -Infinity, -Infinity); for (var point of points) { min.min(point); max.max(point); } var dxfHeader = "999\nDXF created from potree\n0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1006\n9\n$INSBASE\n10\n0.0\n20\n0.0\n30\n0.0\n9\n$EXTMIN\n10\n".concat(min.x, "\n20\n").concat(min.y, "\n30\n").concat(min.z, "\n9\n$EXTMAX\n10\n").concat(max.x, "\n20\n").concat(max.y, "\n30\n").concat(max.z, "\n0\nENDSEC\n"); var dxfBody = "0\nSECTION\n2\nENTITIES\n"; for (var measurement of measurements) { dxfBody += DXFExporter.measurementSection(measurement); } dxfBody += "0\nENDSEC\n"; var dxf = dxfHeader + dxfBody + '0\nEOF'; return dxf; } } class HandleSvg extends EventDispatcher { constructor(position, color) { super(); this.position = position; this.color = '#' + new Color(color).getHexString(); this.svg = this.create(); this.visible_ = true; var update = () => { this.update(); }; viewer.addEventListener("camera_changed", update); this.addEventListener('dispose', () => { viewer.removeEventListener("camera_changed", update); }); } create() { var svgns = "http://www.w3.org/2000/svg"; var svg = document.createElementNS(svgns, "svg"); svg.setAttribute("width", "2em"); svg.setAttribute("height", "2em"); svg.setAttribute("position", "absolute"); svg.style.left = "50px"; svg.style.top = "50px"; svg.style.position = "absolute"; svg.style.zIndex = "10000"; svg.style.cursor = 'grab'; svg.style.transform = 'translate(-50%,-50%)'; var circle = document.createElementNS(svgns, 'circle'); circle.setAttributeNS(null, 'cx', "1em"); circle.setAttributeNS(null, 'cy', "1em"); circle.setAttributeNS(null, 'r', "0.5em"); circle.setAttributeNS(null, 'style', 'fill: ' + this.color + '; stroke: black; stroke-width: 0.2em;'); svg.appendChild(circle); var element = viewer.renderer.domElement.parentElement; element.appendChild(svg); var startDrag = evt => { /* if(evt.button === THREE.MOUSE.RIGHT){ return } */ this.selectedElement = svg; document.addEventListener("mousemove", drag); }; var endDrag = evt => { this.selectedElement = null; document.removeEventListener("mousemove", drag); }; var drag = evt => { if (this.selectedElement) { evt.preventDefault(); var rect = viewer.renderer.domElement.getBoundingClientRect(); var x = evt.clientX - rect.x; var y = evt.clientY - rect.y; var { width, height } = viewer.renderer.getSize(new Vector2()); var camera = viewer.scene.getActiveCamera(); var projected = this.position.clone().project(camera); projected.x = (x / width - 0.5) / 0.5; projected.y = (-(y - height) / height - 0.5) / 0.5; var unprojected = projected.clone().unproject(camera); this.position.set(unprojected.x, unprojected.y, unprojected.z); this.update(); this.dispatchEvent({ type: 'dragged', position: this.position }); } }; svg.addEventListener('mousedown', startDrag); svg.addEventListener('mouseup', endDrag); svg.style.display = this.visible ? "" : "none"; this.addEventListener('dispose', () => { svg.removeEventListener('mousedown', startDrag); svg.removeEventListener('mouseup', endDrag); }); return svg; } set visible(v) { this.visible_ = v; if (v) { this.update(); } else { this.svg.style.display = "none"; } } get visible() { return this.visible_; } update() { if (!this.visible) return; var camera = viewer.scene.getActiveCamera(); var p = Potree.Utils.getPos2d(this.position, viewer.mainViewport, viewer.renderArea); if (!p.trueSide) { return this.svg.style.display = 'none'; } this.svg.style.left = p.posInViewport.x; this.svg.style.top = p.posInViewport.y; this.svg.style.display = ''; } dispose() { this.svg.remove(); this.dispatchEvent('dispose'); } } /* 两种拖拽方式: 1 只依附在点云上 2 平行于镜头view移动 */ var geo$1 = new PlaneBufferGeometry(1, 1); class HandleSprite extends Sprite$2 { constructor(position) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; options.sizeInfo = { width2d: 60 }; super(options); this.position.copy(position); this.dragStyle = options.dragStyle || 'default'; //'default'||'onPointCloud' this.bindEvent(); } bindEvent() { var projectedStart, pointerStart; var drag = e => { /* if(e.hoverViewport != e.drag.dragViewport){//不能使用e.dragViewport,要使用drag中的,因为drag中存储的要一直继承下来,不因mouseup了而改变。 viewer.dispatchEvent({ type : "CursorChange", action : "add", name:"polygon_AtWrongPlace" }) return } */ var camera = viewer.scene.getActiveCamera(); if (projectedStart) { var move2d = new Vector2().subVectors(e.pointer, pointerStart); var projectNow = projectedStart.clone(); projectNow.x += move2d.x; projectNow.y += move2d.y; var unprojected = projectNow.clone().unproject(camera); this.position.set(unprojected.x, unprojected.y, unprojected.z); } else { projectedStart = this.position.clone().project(camera); pointerStart = e.pointer.clone(); } this.update(); this.dispatchEvent({ type: 'dragged', position: this.position }); }; var drop = e => { projectedStart = null, pointerStart = null; }; var mouseover = e => { viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "markerMove" }); }; var mouseleave = e => { viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "markerMove" }); }; this.addEventListener('drag', drag); this.addEventListener('drop', drop); this.addEventListener('mouseover', mouseover); this.addEventListener('mouseleave', mouseleave); } } var sphere = new Mesh(new SphereBufferGeometry(0.08, 0.08, 3, 2), new MeshBasicMaterial({ color: '#f88' })); class CurveCtrl extends Object3D { constructor(points, lineMat, color, name) { var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; super(); this.curve = new CatmullRomCurve3(points, false, "centripetal" /* , tension */); this.name = name || 'curveNode'; this.handleMat = options.handleMat; this.lineMat = lineMat; this.createPath(); this.color = color; this.handles = []; this.wholeLength = 0; this.viewports = options.viewports || [viewer.mainViewport]; //for HandleSprite for (var i = 0, j = this.points.length; i < j; i++) { this.handles.push(this.createHandle(this.points[i])); } this.visible_ = true; if (Potree.settings.isTest) { this.spheres = new Object3D(); /* let i = Count+1; while(i>0){ this.spheres.add(sphere.clone()); i--; } */ this.add(this.spheres); } this.updatePath(); } addPoint(position, index, ifUpdate) { var length = this.points.length; if (index == void 0) { index = length; } var handle = this.createHandle(position); this.handles = [...this.handles.slice(0, index), handle, ...this.handles.slice(index, length)]; this.points = [...this.points.slice(0, index), position, ...this.points.slice(index, length)]; ifUpdate && (this.updatePath(), this.updateHandle(index)); } removePoint(index) { var handle = this.handles[index]; handle.dispose(); this.handles.splice(index, 1); this.points.splice(index, 1); this.updatePath(); } createPath() { var line = LineDraw.createFatLine([], this.lineMat); this.line = line; this.add(line); } updatePath() { this.curve.needsUpdate = true; //如果不更新,得到的点不均匀,开头点少。 var points, length = this.points.length; this.wholeLength = this.points.reduce((total, currentValue, currentIndex, arr) => { //所有端点的距离总和 if (currentIndex == 0) return 0; return total + currentValue.distanceTo(arr[currentIndex - 1]); }, 0); if (length > 1) { var count = MathUtils.clamp(Math.ceil(this.wholeLength * 5), 30, 500); points = this.curve.getSpacedPoints(count); if (this.needsPercent) { //获取每个节点在整条中的百分比,便于定位(但不精确) this.pointsPercent = [0]; var sums = [0]; var sum = 0, last = points[0]; for (var i = 1; i < length; i++) { var point = this.points[i]; sum += point.distanceTo(last); //参考getLengths函数,根据长度得到百分比 last = point; sums.push(sum); } for (var _i = 1; _i < length; _i++) { this.pointsPercent.push(sum == 0 ? _i / length : sums[_i] / sum); } } if (Potree.settings.isTest) { this.spheres.children.forEach(e => e.visible = false); points.forEach((e, i) => { var sphere1 = this.spheres.children[i]; if (!sphere1) { sphere1 = sphere.clone(); this.spheres.add(sphere1); } sphere1.position.copy(e); sphere1.visible = true; }); } } else { points = []; } LineDraw.updateLine(this.line, points); this.dispatchEvent('updatePath'); } createHandle(position) { if (this.handleMat) { var handle = new HandleSprite(position, { mat: this.handleMat, viewports: this.viewports }); this.add(handle); } else { var handle = new HandleSvg(position, this.color); } handle.visible = this.visible; handle.addEventListener('dragged', e => { var index = this.handles.indexOf(handle); this.points[index].copy(e.position); this.updatePath(); this.dispatchEvent({ type: 'dragCurvePoint', index }); }); return handle; } updateHandle(index) { if (!this.visible) return; this.handles[index].update(); } updateHandles() { this.handles.forEach((handle, index) => { this.updateHandle(index); }); } update() { this.updateHandles(); this.updatePath(); } set visible(v) { if (v != this.visible_) { this.visible_ = v; this.visible = v; if (this.handles) { this.handles.forEach(e => e.visible = v); if (v) this.updateHandles(); //因为不可见时没更新位置 } } } get visible() { return this.visible_; } /* set visible(v){ this.handles.forEach(e=>e.svg.style.display = v ? "" : "none" ) if(v) this.updateHandles() //因为不可见时没更新位置 } */ get points() { return this.curve.points; } set points(points) { this.curve.points = points; } getPointAt(t) { return this.curve.getPointAt(t); } getSpacedPoints(t) { return this.curve.getSpacedPoints(t); } dispose() { this.parent && this.parent.remove(this); this.handles.forEach(e => e.dispose()); this.line.geometry && this.line.geometry.dispose(); } } var colors$1 = { position: 'red', target: 'blue' }; var lineMats$1; var getLineMat = function getLineMat(name) { if (!lineMats$1) { lineMats$1 = { position: LineDraw.createFatLineMat({ color: colors$1.position, lineWidth: 3 }), target: LineDraw.createFatLineMat({ color: colors$1.target, lineWidth: 3 }), frustum: LineDraw.createFatLineMat({ color: colors$1.position, lineWidth: 2 }), aimAtTarget: new LineBasicMaterial({ color: colors$1.target, depthTest: false }) }; } return lineMats$1[name]; }; class CameraAnimation$1 extends EventDispatcher { constructor(viewer) { super(); this.viewer = viewer; this.selectedElement = null; //this.controlPoints = []; this.uuid = MathUtils.generateUUID(); this.node = new Object3D(); this.node.name = "camera animation"; this.viewer.scene.scene.add(this.node); this.frustum = this.createFrustum(); this.node.add(this.frustum); this.name = "Camera Animation"; // "centripetal", "chordal", "catmullrom" this.curveType = "centripetal"; this.visible = true; this.targets = []; this.createPath(); this.duration = 5; this.percent = 0; this.currentIndex = 0; this.durations = []; this.quaternions = []; if (!Potree.settings.isTest && Potree.settings.isOfficial) { this.setVisible(false); } this.addEventListener('dispose', () => { this.dispose(); }); this.targetLines = new Object3D(); this.node.add(this.targetLines); } static defaultFromView(viewer) { var animation = new CameraAnimation$1(viewer); var camera = viewer.scene.getActiveCamera(); var target = viewer.scene.view.getPivot(); var cpCenter = new Vector3(0.3 * camera.position.x + 0.7 * target.x, 0.3 * camera.position.y + 0.7 * target.y, 0.3 * camera.position.z + 0.7 * target.z); var targetCenter = new Vector3(0.05 * camera.position.x + 0.95 * target.x, 0.05 * camera.position.y + 0.95 * target.y, 0.05 * camera.position.z + 0.95 * target.z); var r = 2; //camera.position.distanceTo(target) * 0.3; //const dir = target.clone().sub(camera.position).normalize(); var angle = Utils.computeAzimuth(camera.position, target); var n = 5; for (var i = 0; i < n; i++) { var u = 1.5 * Math.PI * (i / n) + angle; var dx = r * Math.cos(u); var dy = r * Math.sin(u); var cpPos = new Vector3(cpCenter.x + dx, cpCenter.y + dy, cpCenter.z); var targetPos = new Vector3(targetCenter.x + dx * 0.1, targetCenter.y + dy * 0.1, targetCenter.z); animation.createControlPoint(null, { position: cpPos, target: targetPos }); } animation.changeCallback(); return animation; } createControlPoint(index, posInfo) { var length = this.posCurve.points.length; var position = new Vector3(); var target = new Vector3(); if (index == void 0) { index = length; } if (!posInfo) { if (length >= 2 && index === 0) { var dir = new Vector3().subVectors(this.posCurve.points[0], this.posCurve.points[1]); position.copy(this.posCurve.points[0]).add(dir); var tDir = new Vector3().subVectors(this.targets[0].position, this.targets[1].position); target.copy(this.targets[0].position).add(dir); } else if (length >= 2 && index === length) { var _dir = new Vector3().subVectors(this.posCurve.points[length - 1], this.posCurve.points[length - 2]); position.copy(this.posCurve.points[length - 2]).add(_dir); var _tDir = new Vector3().subVectors(this.targets[length - 1].position, this.targets[length - 2].position); target.copy(this.targets[length - 2].position).add(_dir); } else if (length >= 2) { position.copy(this.posCurve.points[index - 1].clone().add(this.posCurve.points[index]).multiplyScalar(0.5)); target.copy(this.targets[index - 1].position.clone().add(this.targets[index].position).multiplyScalar(0.5)); } } else { position.copy(posInfo.position); target.copy(posInfo.target); } this.posCurve.addPoint(position, index /* , true */); //this.targetCurve.addPoint(target, index/* , true */) var targetSvg = new HandleSvg(target, colors$1.target); targetSvg.visible = this.visible; this.targets = [...this.targets.slice(0, index), targetSvg, ...this.targets.slice(index, length)]; if (this.useDurSlice) { //不使用全局的duration,而是分段的 this.durations = [...this.durations.slice(0, index), posInfo.duration, ...this.durations.slice(index, length)]; } this.dispatchEvent({ type: "controlpoint_added", index }); { var targetLine = LineDraw.createLine([position, target], { mat: getLineMat('aimAtTarget') }); this.targetLines.children = [...this.targetLines.children.slice(0, index), targetLine, ...this.targetLines.children.slice(index, length)]; this.targets[index].addEventListener('dragged', e => { this.updatePathCallback(); this.dragPointCallback(e); }); } } dragPointCallback(e) { var index = e.index; if (e.index == void 0) { index = this.targets.indexOf(e.target); } LineDraw.moveLine(this.targetLines.children[index], [this.posCurve.points[index], this.targets[index].position]); viewer.dispatchEvent('content_changed'); this.updateFrustum(); } updatePathCallback() { { this.quaternions = []; var length = this.posCurve.points.length; for (var i = 0; i < length; i++) { var quaternion = math.getQuaFromPosAim(this.posCurve.points[i], this.targets[i].position); this.quaternions.push(quaternion); } } this.reMapCurvePercent(); } removeControlPoint(index) { this.posCurve.removePoint(index); //this.targetCurve.removePoint(index) this.targets[index].dispose(); this.targets.splice(index, 1); this.dispatchEvent({ type: "controlpoint_removed", index }); this.targetLines.remove(this.targetLines.children[index]); if (this.useDurSlice) { this.durations.splice(index, 1); } } createPath() { this.posCurve = new CurveCtrl([], getLineMat('position'), colors$1.position, 'posCurve'); //this.targetCurve = new CurveCtrl([], getLineMat('target'), colors.target, 'targetCurve', {noLine:true}); this.posCurve.needsPercent = true; this.node.add(this.posCurve); //this.node.add(this.targetCurve) this.posCurve.addEventListener('dragCurvePoint', this.dragPointCallback.bind(this)); this.posCurve.addEventListener('updatePath', this.updatePathCallback.bind(this)); } createFrustum() { var f = 0.3; var positions = [new Vector3(0, 0, 0), new Vector3(-f, -f, +1), new Vector3(0, 0, 0), new Vector3(f, -f, +1), new Vector3(0, 0, 0), new Vector3(f, f, +1), new Vector3(0, 0, 0), new Vector3(-f, f, +1), new Vector3(-f, -f, +1), new Vector3(f, -f, +1), new Vector3(f, -f, +1), new Vector3(f, f, +1), new Vector3(f, f, +1), new Vector3(-f, f, +1), new Vector3(-f, f, +1), new Vector3(-f, -f, +1)]; positions.forEach(e => e.z *= -1); //因为得到的rotation是camera的,作用在物体上要反向,所以这里反向一下 //geometry.computeBoundingSphere();//? var line = LineDraw.createFatLine(positions, { mat: getLineMat('frustum') }); //line.scale.set(20, 20, 20); line.visible = false; return line; } reMapCurvePercent() { //因在不同点在相同位置旋转,由于间隔仅和位置距离相关,导致时间间隔为0,采取重新调整间隔的策略。 var length = this.posCurve.points.length; if (length < 2) { return this.newPointsPercents = []; } var newPercents = [0]; if (this.useDurSlice) { //已经设定好了每一段的duration的话 var sums = [0]; var sum = 0, last; for (var i = 0; i < length - 1; i++) { //去掉最后一个duration,因为已到终点 var duration = this.durations[i]; sum += duration; last = duration; sums.push(sum); } for (var _i = 1; _i < length; _i++) { newPercents.push(sum == 0 ? _i / length : sums[_i] / sum); } } else { var maxSpaceDur = this.duration / length; //每两点之间修改间隔时间后,最大时间 var durPerRad = 0.8; //每弧度应该占用的时间 var minSpaceDur = Math.min(0.8, maxSpaceDur); //每两点之间修改间隔时间后,最小时间 var maxAngleSpaceDur = MathUtils.clamp(durPerRad * Math.PI, minSpaceDur, maxSpaceDur); // 最大可能差距是180度 var percents = this.posCurve.pointsPercent; for (var _i2 = 1; _i2 < length; _i2++) { var diff = (percents[_i2] - percents[_i2 - 1]) * this.duration; //间隔时间 var percent = void 0; var curMin = minSpaceDur; if (diff < maxAngleSpaceDur) { //若小于最大旋转时间 var rad = this.quaternions[_i2].angleTo(this.quaternions[_i2 - 1]); curMin = MathUtils.clamp(rad * durPerRad, minSpaceDur, maxSpaceDur); } diff = Math.max(diff, curMin); percent = newPercents[_i2 - 1] + diff / this.duration; //得到新的percent newPercents.push(percent); } var maxPercent = newPercents[length - 1]; //最后一个,若扩充过时间,就会>1 if (!math.closeTo(maxPercent, 1)) { var scale = 1 / maxPercent; //需要压缩的比例 <1 这一步会让实际得到的间隔更小 newPercents = newPercents.map(e => e *= scale); } } this.newPointsPercents = newPercents; //console.log(newPercents) } at(originPercent, delta, transitionRatio) { originPercent = MathUtils.clamp(originPercent, 0, 1); //修改第一层:起始时间 var percent = originPercent; /* const easePercent = 0.3; //缓动占比 //如果能在所有从静止到运动的中间加缓动就好了呀:lastPos * 0.9 + currentPos * 0.1 ? if(originPercent < easePercent){ console.log('easeIn') percent = easing.easeInSine(originPercent, 0, easePercent, easePercent) //currentTime, startY, wholeY, duration 选了一个衔接时接近斜率1的缓动函数 }else if(originPercent > 1-easePercent){ console.log('easeOut') percent = easing.easeOutSine(originPercent-(1-easePercent), 1-easePercent, easePercent, easePercent) } */ var quaternion; if (percent < 1) { //修改第二层:使用每个点的重定位的 newPointsPercents this.currentIndex = this.newPointsPercents.findIndex(e => e > percent) - 1; //假设每个节点的百分比是精确的,那么: var curIndexPercent = this.newPointsPercents[this.currentIndex]; var nextIndexPercent = this.newPointsPercents[this.currentIndex + 1]; var progress = (percent - curIndexPercent) / (nextIndexPercent - curIndexPercent); //在这两个节点间的百分比 //投影到原本的 posCurve.pointsPercent上: var curIndexOriPercent = this.posCurve.pointsPercent[this.currentIndex]; var nextIndexOriPercent = this.posCurve.pointsPercent[this.currentIndex + 1]; percent = curIndexOriPercent + (nextIndexOriPercent - curIndexOriPercent) * progress; var endQuaternion = this.quaternions[this.currentIndex + 1]; var startQuaternion = this.quaternions[this.currentIndex]; quaternion = new Quaternion().copy(startQuaternion); lerp.quaternion(quaternion, endQuaternion)(progress); } else { this.currentIndex = this.posCurve.points.length - 1; quaternion = math.getQuaFromPosAim(this.posCurve.points[this.currentIndex], this.targets[this.currentIndex].position); } var position = this.posCurve.getPointAt(percent); // 需要this.posCurve.points.length>1 否则报错 //console.log(this.currentIndex, originPercent) //缓动: var aimQua, aimPos; if (delta != void 0) { if (Potree.settings.tourTestCameraMove) { aimQua = this.frustum.quaternion.clone(); aimPos = this.frustum.position.clone(); } else { var camera = viewer.scene.getActiveCamera(); aimQua = camera.quaternion.clone(); aimPos = camera.position.clone(); } transitionRatio = transitionRatio || 1 / Potree.settings.cameraAniSmoothRatio; //渐变系数,越小缓动程度越高,越平滑 transitionRatio *= delta * 60; //假设标准帧率为60fps,当帧率低时(delta大时)要降低缓动 //console.log(transitionRatio, delta) //画面ui变化会使delta变大 transitionRatio = MathUtils.clamp(transitionRatio, 0, 1); lerp.quaternion(aimQua, quaternion)(transitionRatio); //每次只改变一点点 lerp.vector(aimPos, position)(transitionRatio); } else { aimQua = quaternion; aimPos = position; } var rotation = new Euler().setFromQuaternion(aimQua); var frame = { position: aimPos, rotation }; return frame; } set(percent) { this.percent = percent; } setVisible(visible) { this.node.visible = visible; this.posCurve.visible = visible; this.targets.forEach(e => e.visible = visible); this.visible = visible; } setDuration(duration) { if (duration != this.duration) { this.duration = duration; if (this.quaternions.length == this.posCurve.points.length) this.reMapCurvePercent(); } } getDuration(duration) { return this.duration; } play() { var startOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (this.onUpdate) { return console.error('已经开始播放'); } var startPercent = 0, currentIndex = 0; if (startOptions.percent != void 0) { startPercent = startOptions.percent; } else if (startOptions.index) { currentIndex = index; //startPercent = index/(this.posCurve.points.length-1) startPercent = this.posCurve.pointsPercent[index]; } //const tStart = performance.now(); var duration = this.duration; this.originalyVisible = this.visible; Potree.settings.tourTestCameraMove || this.setVisible(false); var tStart, startTransitionRatio = 0.2; var startDelay = 1 / startTransitionRatio / 20; //因为缓动所以延迟开始,前面前都是at(0),使过渡到开始点位(但是依旧不能准确停在起始点,因为缓动是乘百分比有残留。所以直接平滑衔接到开始后的位置) var hasPlayedTime = 0; var finishDelay = Potree.settings.cameraAniSmoothRatio / 60 * 3; //结束后还需要多久时间才能大致达到缓动的最终目标 var hasStoppedTime = 0; this.onUpdate = e => { if (this.posCurve.points.length < 2) { if (this.posCurve.points.length == 1) { viewer.scene.view.position.copy(this.posCurve.points[0]); viewer.scene.view.rotation = new Euler().setFromQuaternion(this.quaternions[0]); } this.pause(); return; } var percent, transitionRatio; if (tStart) { var tNow = performance.now(); var elapsed = (tNow - tStart) / 1000; percent = elapsed / duration + startPercent; } else { //从当前位置过渡到开始位置 percent = 0; hasPlayedTime += e.delta; transitionRatio = startTransitionRatio; //console.log('延迟开始') if (hasPlayedTime > startDelay) { tStart = performance.now(); } } this.set(percent); var frame = this.at(percent, e.delta, transitionRatio); if (currentIndex != this.currentIndex) { currentIndex = this.currentIndex; console.log('updateCurrentIndex', currentIndex); this.dispatchEvent({ type: 'updateCurrentIndex', currentIndex }); } if (!Potree.settings.tourTestCameraMove) { viewer.scene.view.position.copy(frame.position); //viewer.scene.view.lookAt(frame.target); viewer.scene.view.rotation = frame.rotation; } this.updateFrustum(frame); if (percent >= 1) { if (hasStoppedTime > finishDelay) { this.pause(); } else { hasStoppedTime += e.delta; //console.log('延迟结束') } } }; this.viewer.addEventListener("update", this.onUpdate); } pause() { this.setVisible(this.originalyVisible); this.viewer.removeEventListener("update", this.onUpdate); this.dispatchEvent('playDone'); this.onUpdate = null; } updateFrustum(frame) { var frustum = this.frustum; if (this.posCurve.points.length > 1) { frustum.visible = true; } else { frustum.visible = false; return; } frame = frame || this.at(this.percent); frustum.position.copy(frame.position); //frustum.lookAt(...frame.target.toArray()); frustum.rotation.copy(frame.rotation); viewer.dispatchEvent('content_changed'); } changeCallback(i) { this.posCurve.update(); //this.targets.forEach(e=>e.update()) this.updatePathCallback(); if (i == void 0) { var length = this.posCurve.points.length; for (var _i3 = 0; _i3 < length; _i3++) { this.dragPointCallback({ index: _i3 }); } } else this.dragPointCallback({ index: i }); this.updateFrustum(); } dispose() { //add this.posCurve.dispose(); //this.targetCurve.dispatchEvent({type:'dispose'}) this.targets.forEach(e => e.dispose()); this.durations = []; this.node.parent.remove(this.node); } } //scene.removeCameraAnimation //修改:不使用targetCurve作为target曲线,因为播放时posCuve的节点和targetCurve并没有对应,且使用target的曲线会使角度变化大的情况过渡生硬。 // 改完旋转了。但是位置也有问题。速度完全和路程相关,当在同一位置设置多点时,这段的总时长为0. (是否要设置最小时长?不过也做不到 - -) class MeasurePanel { constructor(viewer, measurement, propertiesPanel) { this.viewer = viewer; this.measurement = measurement; this.propertiesPanel = propertiesPanel; this._update = () => { this.update(); }; } createCoordinatesTable(points) { var _this = this; var table = $("\n\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t
xyz
\n\t\t"); var copyIconPath = Potree.resourcePath + '/icons/copy.svg'; var _loop = function _loop(point) { var x = Utils.addCommas(point.x.toFixed(3)); var y = Utils.addCommas(point.y.toFixed(3)); var z = Utils.addCommas(point.z.toFixed(3)); var row = $("\n\t\t\t\t\n\t\t\t\t\t".concat(x, "\n\t\t\t\t\t").concat(y, "\n\t\t\t\t\t").concat(z, "\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t")); _this.elCopy = row.find("img[name=copy]"); _this.elCopy.click(() => { var msg = point.toArray().map(c => c.toFixed(3)).join(", "); Utils.clipboardCopy(msg); _this.viewer.postMessage("Copied value to clipboard:
'".concat(msg, "'"), { duration: 3000 }); }); table.append(row); }; for (var point of points) { _loop(point); } return table; } createAttributesTable() { var elTable = $('
'); var point = this.measurement.points[0]; /* for(let attributeName of Object.keys(point)){ if(attributeName === "position"){ }else if(attributeName === "rgba"){ let color = point.rgba; let text = color.join(', '); elTable.append($(` rgb ${text} `)); }else{ let value = point[attributeName]; let text = value.join(', '); elTable.append($(` ${attributeName} ${text} `)); } } */ return elTable; } update() {} } ; class DistancePanel extends MeasurePanel { constructor(viewer, measurement, propertiesPanel) { super(viewer, measurement, propertiesPanel); var removeIconPath = Potree.resourcePath + '/icons/remove.svg'; this.elContent = $("\n\t\t\t
\n\t\t\t\t\n\t\t\t\t
\n\t\t\t\t
\n\n\t\t\t\t\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t
\n\t\t")); this.elRemove = this.elContent.find("img[name=remove]"); this.elRemove.click(() => { this.viewer.scene.removeMeasurement(measurement); }); this.elMakeProfile = this.elContent.find("input[name=make_profile]"); this.elMakeProfile.click(() => { //measurement.points; var profile = new Profile(); profile.name = measurement.name; profile.width = measurement.getTotalDistance() / 50; for (var point of measurement.points) { profile.addMarker(point.position.clone()); } this.viewer.scene.addProfile(profile); }); this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update); this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update); this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update); this.update(); } update() { var elCoordiantesContainer = this.elContent.find('.coordinates_table_container'); elCoordiantesContainer.empty(); elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points.map(p => p.position))); var positions = this.measurement.points.map(p => p.position); var distances = []; for (var i = 0; i < positions.length - 1; i++) { var d = positions[i].distanceTo(positions[i + 1]); distances.push(d.toFixed(3)); } var totalDistance = this.measurement.getTotalDistance().toFixed(3); var elDistanceTable = this.elContent.find("#distances_table"); elDistanceTable.empty(); for (var _i = 0; _i < distances.length; _i++) { var label = _i === 0 ? 'Distances: ' : ''; var distance = distances[_i]; var elDistance = $("\n\t\t\t\t\n\t\t\t\t\t".concat(label, "\n\t\t\t\t\t").concat(distance, "\n\t\t\t\t")); elDistanceTable.append(elDistance); } var elTotal = $("\n\t\t\t\n\t\t\t\tTotal: ".concat(totalDistance, "\n\t\t\t")); elDistanceTable.append(elTotal); } } ; class PointPanel extends MeasurePanel { constructor(viewer, measurement, propertiesPanel) { super(viewer, measurement, propertiesPanel); var removeIconPath = Potree.resourcePath + '/icons/remove.svg'; this.elContent = $("\n\t\t\t
\n\t\t\t\t\n\t\t\t\t
\n\t\t\t\t\n\n\t\t\t\t\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t
\n\t\t")); this.elRemove = this.elContent.find("img[name=remove]"); this.elRemove.click(() => { this.viewer.scene.removeMeasurement(measurement); }); this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update); this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update); this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update); this.update(); } update() { var elCoordiantesContainer = this.elContent.find('.coordinates_table_container'); elCoordiantesContainer.empty(); elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points)); var elAttributesContainer = this.elContent.find('.attributes_table_container'); elAttributesContainer.empty(); elAttributesContainer.append(this.createAttributesTable()); } } ; class AreaPanel extends MeasurePanel { constructor(viewer, measurement, propertiesPanel) { super(viewer, measurement, propertiesPanel); var removeIconPath = Potree.resourcePath + '/icons/remove.svg'; this.elContent = $("\n\t\t\t
\n\t\t\t\t\n\t\t\t\t
\n\t\t\t\tArea: \n\t\t\t\t\n\n\t\t\t\t\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t
\n\t\t")); this.elRemove = this.elContent.find("img[name=remove]"); this.elRemove.click(() => { this.viewer.scene.removeMeasurement(measurement); }); this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update); this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update); this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update); this.update(); } update() { var elCoordiantesContainer = this.elContent.find('.coordinates_table_container'); elCoordiantesContainer.empty(); elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points)); var elArea = this.elContent.find("#measurement_area"); elArea.html(this.measurement.area.value.toFixed(3)); } } ; class AnglePanel extends MeasurePanel { constructor(viewer, measurement, propertiesPanel) { super(viewer, measurement, propertiesPanel); var removeIconPath = Potree.resourcePath + '/icons/remove.svg'; this.elContent = $("\n\t\t\t
\n\t\t\t\t\n\t\t\t\t
\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t
\u03B1\u03B2\u03B3
\n\n\t\t\t\t\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t
\n\t\t")); this.elRemove = this.elContent.find("img[name=remove]"); this.elRemove.click(() => { this.viewer.scene.removeMeasurement(measurement); }); this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update); this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update); this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update); this.update(); } update() { var elCoordiantesContainer = this.elContent.find('.coordinates_table_container'); elCoordiantesContainer.empty(); elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points.map(p => p.position))); var angles = []; for (var i = 0; i < this.measurement.points.length; i++) { angles.push(this.measurement.getAngle(i) * (180.0 / Math.PI)); } angles = angles.map(a => a.toFixed(1) + '\u00B0'); var elAlpha = this.elContent.find("#angle_cell_alpha"); var elBetta = this.elContent.find("#angle_cell_betta"); var elGamma = this.elContent.find("#angle_cell_gamma"); elAlpha.html(angles[0]); elBetta.html(angles[1]); elGamma.html(angles[2]); } } ; class CirclePanel extends MeasurePanel { constructor(viewer, measurement, propertiesPanel) { super(viewer, measurement, propertiesPanel); var removeIconPath = Potree.resourcePath + '/icons/remove.svg'; this.elContent = $("\n\t\t\t
\n\t\t\t\t\n\t\t\t\t
\n\t\t\t\t
\n\n\t\t\t\t\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t
\n\t\t")); this.elRemove = this.elContent.find("img[name=remove]"); this.elRemove.click(() => { this.viewer.scene.removeMeasurement(measurement); }); this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update); this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update); this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update); this.update(); } update() { var elCoordiantesContainer = this.elContent.find('.coordinates_table_container'); elCoordiantesContainer.empty(); elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points.map(p => p.position))); var elInfos = this.elContent.find("#infos_table"); if (this.measurement.points.length !== 3) { elInfos.empty(); return; } var A = this.measurement.points[0].position; var B = this.measurement.points[1].position; var C = this.measurement.points[2].position; var center = Potree.Utils.computeCircleCenter(A, B, C); var radius = center.distanceTo(A); var circumference = 2 * Math.PI * radius; var format = number => { return Potree.Utils.addCommas(number.toFixed(3)); }; var txtCenter = "".concat(format(center.x), " ").concat(format(center.y), " ").concat(format(center.z)); var txtRadius = format(radius); var txtCircumference = format(circumference); var thStyle = "style=\"text-align: left\""; var tdStyle = "style=\"width: 100%; padding: 5px;\""; elInfos.html("\n\t\t\t\n\t\t\t\tCenter: \n\t\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\t\n\t\t\t\t\t").concat(txtCenter, "\n\t\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\tRadius: \n\t\t\t\t").concat(txtRadius, "\n\t\t\t\n\t\t\t\n\t\t\t\tCircumference: \n\t\t\t\t").concat(txtCircumference, "\n\t\t\t\n\t\t")); } } ; class HeightPanel extends MeasurePanel { constructor(viewer, measurement, propertiesPanel) { super(viewer, measurement, propertiesPanel); var removeIconPath = Potree.resourcePath + '/icons/remove.svg'; this.elContent = $("\n\t\t\t
\n\t\t\t\t\n\t\t\t\t
\n\t\t\t\tHeight:
\n\n\t\t\t\t\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t
\n\t\t")); this.elRemove = this.elContent.find("img[name=remove]"); this.elRemove.click(() => { this.viewer.scene.removeMeasurement(measurement); }); this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update); this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update); this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update); this.update(); } update() { var elCoordiantesContainer = this.elContent.find('.coordinates_table_container'); elCoordiantesContainer.empty(); elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points.map(p => p.position))); { var points = this.measurement.points; var sorted = points.slice().sort((a, b) => a.position.z - b.position.z); var lowPoint = sorted[0].position.clone(); var highPoint = sorted[sorted.length - 1].position.clone(); var min = lowPoint.z; var max = highPoint.z; var height = max - min; height = height.toFixed(3); this.elHeightLabel = this.elContent.find("#height_label"); this.elHeightLabel.html("Height: ".concat(height)); } } } ; class VolumePanel extends MeasurePanel { constructor(viewer, measurement, propertiesPanel) { super(viewer, measurement, propertiesPanel); var copyIconPath = Potree.resourcePath + '/icons/copy.svg'; var removeIconPath = Potree.resourcePath + '/icons/remove.svg'; var lblLengthText = new Map([[BoxVolume, "length"], [SphereVolume$1, "rx"]]).get(measurement.constructor); var lblWidthText = new Map([[BoxVolume, "width"], [SphereVolume$1, "ry"]]).get(measurement.constructor); var lblHeightText = new Map([[BoxVolume, "height"], [SphereVolume$1, "rz"]]).get(measurement.constructor); this.elContent = $("\n\t\t\t
\n\t\t\t\t\n\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t
\u03B1\u03B2\u03B3
\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t
\n\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t
").concat(lblLengthText, "").concat(lblWidthText, "").concat(lblHeightText, "
\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t
\n\n\t\t\t\t
\n\t\t\t\tVolume: \n\t\t\t\t\n\n\t\t\t\t\n\n\t\t\t\t
  • \n\t\t\t\t\t\n\t\t\t\t
  • \n\n\t\t\t\t
  • \n\t\t\t\t\t\n\t\t\t\t\t
    \n\t\t\t\t
  • \n\n\n\t\t\t\t\n\t\t\t\t
  • \n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t
  • \n\t\t\t\t
    \n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t
    \n\t\t\t
    \n\t\t")); { // download this.elDownloadButton = this.elContent.find("input[name=download_volume]"); if (this.propertiesPanel.viewer.server) { this.elDownloadButton.click(() => this.download()); } else { this.elDownloadButton.hide(); } } this.elCopyRotation = this.elContent.find("img[name=copyRotation]"); this.elCopyRotation.click(() => { var rotation = this.measurement.rotation.toArray().slice(0, 3); var msg = rotation.map(c => c.toFixed(3)).join(", "); Utils.clipboardCopy(msg); this.viewer.postMessage("Copied value to clipboard:
    '".concat(msg, "'"), { duration: 3000 }); }); this.elCopyScale = this.elContent.find("img[name=copyScale]"); this.elCopyScale.click(() => { var scale = this.measurement.scale.toArray(); var msg = scale.map(c => c.toFixed(3)).join(", "); Utils.clipboardCopy(msg); this.viewer.postMessage("Copied value to clipboard:
    '".concat(msg, "'"), { duration: 3000 }); }); this.elRemove = this.elContent.find("img[name=remove]"); this.elRemove.click(() => { this.viewer.scene.removeVolume(measurement); }); this.elContent.find("#volume_reset_orientation").click(() => { measurement.rotation.set(0, 0, 0); }); this.elContent.find("#volume_make_uniform").click(() => { var mean = (measurement.scale.x + measurement.scale.y + measurement.scale.z) / 3; measurement.scale.set(mean, mean, mean); }); this.elCheckClip = this.elContent.find('#volume_clip'); this.elCheckClip.click(event => { this.measurement.clip = event.target.checked; }); this.elCheckShow = this.elContent.find('#volume_show'); this.elCheckShow.click(event => { this.measurement.visible = event.target.checked; }); this.propertiesPanel.addVolatileListener(measurement, "position_changed", this._update); this.propertiesPanel.addVolatileListener(measurement, "orientation_changed", this._update); this.propertiesPanel.addVolatileListener(measurement, "scale_changed", this._update); this.propertiesPanel.addVolatileListener(measurement, "clip_changed", this._update); this.update(); } async download() { var clipBox = this.measurement; var regions = []; //for(let clipBox of boxes){ { var toClip = clipBox.matrixWorld; var px = new Vector3(+0.5, 0, 0).applyMatrix4(toClip); var nx = new Vector3(-0.5, 0, 0).applyMatrix4(toClip); var py = new Vector3(0, +0.5, 0).applyMatrix4(toClip); var ny = new Vector3(0, -0.5, 0).applyMatrix4(toClip); var pz = new Vector3(0, 0, +0.5).applyMatrix4(toClip); var nz = new Vector3(0, 0, -0.5).applyMatrix4(toClip); var pxN = new Vector3().subVectors(nx, px).normalize(); var nxN = pxN.clone().multiplyScalar(-1); var pyN = new Vector3().subVectors(ny, py).normalize(); var nyN = pyN.clone().multiplyScalar(-1); var pzN = new Vector3().subVectors(nz, pz).normalize(); var nzN = pzN.clone().multiplyScalar(-1); var planes = [new Plane().setFromNormalAndCoplanarPoint(pxN, px), new Plane().setFromNormalAndCoplanarPoint(nxN, nx), new Plane().setFromNormalAndCoplanarPoint(pyN, py), new Plane().setFromNormalAndCoplanarPoint(nyN, ny), new Plane().setFromNormalAndCoplanarPoint(pzN, pz), new Plane().setFromNormalAndCoplanarPoint(nzN, nz)]; var planeQueryParts = []; for (var plane of planes) { var part = [plane.normal.toArray(), plane.constant].join(","); part = "[".concat(part, "]"); planeQueryParts.push(part); } var region = "[" + planeQueryParts.join(",") + "]"; regions.push(region); } var regionsArg = regions.join(","); var pointcloudArgs = []; for (var pointcloud of this.viewer.scene.pointclouds) { if (!pointcloud.visible) { continue; } var offset = pointcloud.pcoGeometry.offset.clone(); var negateOffset = new Matrix4().makeTranslation(...offset.multiplyScalar(-1).toArray()); var matrixWorld = pointcloud.matrixWorld; var transform = new Matrix4().multiplyMatrices(matrixWorld, negateOffset); var path = "".concat(window.location.pathname, "/../").concat(pointcloud.pcoGeometry.url); var arg = { path: path, transform: transform.elements }; var argString = JSON.stringify(arg); pointcloudArgs.push(argString); } var pointcloudsArg = pointcloudArgs.join(","); var elMessage = this.elContent.find("div[name=download_message]"); var error = message => { elMessage.html("
    ERROR: ".concat(message, "
    ")); }; var info = message => { elMessage.html("".concat(message)); }; var handle = null; { // START FILTER var url = "".concat(viewer.server, "/create_regions_filter?pointclouds=[").concat(pointcloudsArg, "]®ions=[").concat(regionsArg, "]"); //console.log(url); info("estimating results ..."); var response = await fetch(url); var jsResponse = await response.json(); //console.log(jsResponse); if (!jsResponse.handle) { error(jsResponse.message); return; } else { handle = jsResponse.handle; } } { // WAIT, CHECK PROGRESS, HANDLE FINISH var _url = "".concat(viewer.server, "/check_regions_filter?handle=").concat(handle); var sleep = function sleep(duration) { return new Promise((res, rej) => { setTimeout(() => { res(); }, duration); }); }; var handleFiltering = jsResponse => { var { progress, estimate } = jsResponse; var progressFract = progress["processed points"] / estimate.points; var progressPercents = parseInt(progressFract * 100); info("progress: ".concat(progressPercents, "%")); }; var handleFinish = jsResponse => { var message = "downloads ready:
    "; message += "
      "; for (var i = 0; i < jsResponse.pointclouds.length; i++) { var _url2 = "".concat(viewer.server, "/download_regions_filter_result?handle=").concat(handle, "&index=").concat(i); message += "
    • result_").concat(i, ".las
    • \n"); } var reportURL = "".concat(viewer.server, "/download_regions_filter_report?handle=").concat(handle); message += "
    • report.json
    • \n"); message += "
    "; info(message); }; var handleUnexpected = jsResponse => { var message = "Unexpected Response.
    status: ".concat(jsResponse.status, "
    message: ").concat(jsResponse.message); info(message); }; var handleError = jsResponse => { var message = "ERROR: ".concat(jsResponse.message); error(message); throw new Error(message); }; var start = Date.now(); while (true) { var _response = await fetch(_url); var _jsResponse = await _response.json(); if (_jsResponse.status === "ERROR") { handleError(_jsResponse); } else if (_jsResponse.status === "FILTERING") { handleFiltering(_jsResponse); } else if (_jsResponse.status === "FINISHED") { handleFinish(_jsResponse); break; } else { handleUnexpected(_jsResponse); } var durationS = (Date.now() - start) / 1000; var sleepAmountMS = durationS < 10 ? 100 : 1000; await sleep(sleepAmountMS); } } } update() { var elCoordiantesContainer = this.elContent.find('.coordinates_table_container'); elCoordiantesContainer.empty(); elCoordiantesContainer.append(this.createCoordinatesTable([this.measurement.position])); { var angles = this.measurement.rotation.toVector3(); angles = angles.toArray(); //angles = [angles.z, angles.x, angles.y]; angles = angles.map(v => 180 * v / Math.PI); angles = angles.map(a => a.toFixed(1) + '\u00B0'); var elAlpha = this.elContent.find("#angle_cell_alpha"); var elBetta = this.elContent.find("#angle_cell_betta"); var elGamma = this.elContent.find("#angle_cell_gamma"); elAlpha.html(angles[0]); elBetta.html(angles[1]); elGamma.html(angles[2]); } { var dimensions = this.measurement.scale.toArray(); dimensions = dimensions.map(v => Utils.addCommas(v.toFixed(2))); var elLength = this.elContent.find("#cell_length"); var elWidth = this.elContent.find("#cell_width"); var elHeight = this.elContent.find("#cell_height"); elLength.html(dimensions[0]); elWidth.html(dimensions[1]); elHeight.html(dimensions[2]); } { var elVolume = this.elContent.find("#measurement_volume"); var volume = this.measurement.getVolume(); elVolume.html(Utils.addCommas(volume.toFixed(2))); } this.elCheckClip.prop("checked", this.measurement.clip); this.elCheckShow.prop("checked", this.measurement.visible); } } ; class ProfilePanel extends MeasurePanel { constructor(viewer, measurement, propertiesPanel) { super(viewer, measurement, propertiesPanel); var removeIconPath = Potree.resourcePath + '/icons/remove.svg'; this.elContent = $("\n\t\t\t
    \n\t\t\t\t\n\t\t\t\t
    \n\t\t\t\t\n\t\t\t\t\tWidth: \n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t
    \n\n\t\t\t\t
  • \n\t\t\t\t\t\n\t\t\t\t\t
    \n\t\t\t\t
  • \n\n\t\t\t\t
    \n\n\t\t\t\t\n\n\t\t\t\t\n\t\t\t\t
    \n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t
    \n\t\t\t
    \n\t\t")); this.elRemove = this.elContent.find("img[name=remove]"); this.elRemove.click(() => { this.viewer.scene.removeProfile(measurement); }); { // download this.elDownloadButton = this.elContent.find("input[name=download_profile]"); if (this.propertiesPanel.viewer.server) { this.elDownloadButton.click(() => this.download()); } else { this.elDownloadButton.hide(); } } { // width spinner var elWidthSlider = this.elContent.find("#sldProfileWidth"); elWidthSlider.spinner({ min: 0, max: 10 * 1000 * 1000, step: 0.01, numberFormat: 'n', start: () => {}, spin: (event, ui) => { var value = elWidthSlider.spinner('value'); measurement.setWidth(value); }, change: (event, ui) => { var value = elWidthSlider.spinner('value'); measurement.setWidth(value); }, stop: (event, ui) => { var value = elWidthSlider.spinner('value'); measurement.setWidth(value); }, incremental: count => { var value = elWidthSlider.spinner('value'); var step = elWidthSlider.spinner('option', 'step'); var delta = value * 0.05; var increments = Math.max(1, parseInt(delta / step)); return increments; } }); elWidthSlider.spinner('value', measurement.getWidth()); elWidthSlider.spinner('widget').css('width', '100%'); var widthListener = event => { var value = elWidthSlider.spinner('value'); if (value !== measurement.getWidth()) { elWidthSlider.spinner('value', measurement.getWidth()); } }; this.propertiesPanel.addVolatileListener(measurement, "width_changed", widthListener); } var elShow2DProfile = this.elContent.find("#show_2d_profile"); elShow2DProfile.click(() => { this.propertiesPanel.viewer.profileWindow.show(); this.propertiesPanel.viewer.profileWindowController.setProfile(measurement); }); this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update); this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update); this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update); this.update(); } update() { var elCoordiantesContainer = this.elContent.find('.coordinates_table_container'); elCoordiantesContainer.empty(); elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points)); } async download() { var profile = this.measurement; var regions = []; { var segments = profile.getSegments(); var width = profile.width; for (var segment of segments) { var start = segment.start.clone().multiply(new Vector3(1, 1, 0)); var end = segment.end.clone().multiply(new Vector3(1, 1, 0)); var center = new Vector3().addVectors(start, end).multiplyScalar(0.5); var startEndDir = new Vector3().subVectors(end, start).normalize(); var endStartDir = new Vector3().subVectors(start, end).normalize(); var upDir = new Vector3(0, 0, 1); var rightDir = new Vector3().crossVectors(startEndDir, upDir); var leftDir = new Vector3().crossVectors(endStartDir, upDir); console.log(leftDir); var right = rightDir.clone().multiplyScalar(width * 0.5).add(center); var left = leftDir.clone().multiplyScalar(width * 0.5).add(center); var planes = [new Plane().setFromNormalAndCoplanarPoint(startEndDir, start), new Plane().setFromNormalAndCoplanarPoint(endStartDir, end), new Plane().setFromNormalAndCoplanarPoint(leftDir, right), new Plane().setFromNormalAndCoplanarPoint(rightDir, left)]; var planeQueryParts = []; for (var plane of planes) { var part = [plane.normal.toArray(), plane.constant].join(","); part = "[".concat(part, "]"); planeQueryParts.push(part); } var region = "[" + planeQueryParts.join(",") + "]"; regions.push(region); } } var regionsArg = regions.join(","); var pointcloudArgs = []; for (var pointcloud of this.viewer.scene.pointclouds) { if (!pointcloud.visible) { continue; } var offset = pointcloud.pcoGeometry.offset.clone(); var negateOffset = new Matrix4().makeTranslation(...offset.multiplyScalar(-1).toArray()); var matrixWorld = pointcloud.matrixWorld; var transform = new Matrix4().multiplyMatrices(matrixWorld, negateOffset); var path = "".concat(window.location.pathname, "/../").concat(pointcloud.pcoGeometry.url); var arg = { path: path, transform: transform.elements }; var argString = JSON.stringify(arg); pointcloudArgs.push(argString); } var pointcloudsArg = pointcloudArgs.join(","); var elMessage = this.elContent.find("div[name=download_message]"); var error = message => { elMessage.html("
    ERROR: ".concat(message, "
    ")); }; var info = message => { elMessage.html("".concat(message)); }; var handle = null; { // START FILTER var url = "".concat(viewer.server, "/create_regions_filter?pointclouds=[").concat(pointcloudsArg, "]®ions=[").concat(regionsArg, "]"); //console.log(url); info("estimating results ..."); var response = await fetch(url); var jsResponse = await response.json(); //console.log(jsResponse); if (!jsResponse.handle) { error(jsResponse.message); return; } else { handle = jsResponse.handle; } } { // WAIT, CHECK PROGRESS, HANDLE FINISH var _url = "".concat(viewer.server, "/check_regions_filter?handle=").concat(handle); var sleep = function sleep(duration) { return new Promise((res, rej) => { setTimeout(() => { res(); }, duration); }); }; var handleFiltering = jsResponse => { var { progress, estimate } = jsResponse; var progressFract = progress["processed points"] / estimate.points; var progressPercents = parseInt(progressFract * 100); info("progress: ".concat(progressPercents, "%")); }; var handleFinish = jsResponse => { var message = "downloads ready:
    "; message += "
      "; for (var i = 0; i < jsResponse.pointclouds.length; i++) { var _url2 = "".concat(viewer.server, "/download_regions_filter_result?handle=").concat(handle, "&index=").concat(i); message += "
    • result_").concat(i, ".las
    • \n"); } var reportURL = "".concat(viewer.server, "/download_regions_filter_report?handle=").concat(handle); message += "
    • report.json
    • \n"); message += "
    "; info(message); }; var handleUnexpected = jsResponse => { var message = "Unexpected Response.
    status: ".concat(jsResponse.status, "
    message: ").concat(jsResponse.message); info(message); }; var handleError = jsResponse => { var message = "ERROR: ".concat(jsResponse.message); error(message); throw new Error(message); }; var _start = Date.now(); while (true) { var _response = await fetch(_url); var _jsResponse = await _response.json(); if (_jsResponse.status === "ERROR") { handleError(_jsResponse); } else if (_jsResponse.status === "FILTERING") { handleFiltering(_jsResponse); } else if (_jsResponse.status === "FINISHED") { handleFinish(_jsResponse); break; } else { handleUnexpected(_jsResponse); } var durationS = (Date.now() - _start) / 1000; var sleepAmountMS = durationS < 10 ? 100 : 1000; await sleep(sleepAmountMS); } } } } ; class CameraPanel { constructor(viewer, propertiesPanel) { this.viewer = viewer; this.propertiesPanel = propertiesPanel; this._update = () => { this.update(); }; var copyIconPath = Potree.resourcePath + '/icons/copy.svg'; this.elContent = $("\n\t\t
    \n\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t
    position
    \n\t\t\t\t\t\t\n\t\t\t\t\t
    target
    \n\t\t\t\t\t\t\n\t\t\t\t\t
    \n\t\t
    \n\t\t")); this.elCopyPosition = this.elContent.find("img[name=copyPosition]"); this.elCopyPosition.click(() => { var pos = this.viewer.scene.getActiveCamera().position.toArray(); var msg = pos.map(c => c.toFixed(3)).join(", "); Utils.clipboardCopy(msg); this.viewer.postMessage("Copied value to clipboard:
    '".concat(msg, "'"), { duration: 3000 }); }); this.elCopyTarget = this.elContent.find("img[name=copyTarget]"); this.elCopyTarget.click(() => { var pos = this.viewer.scene.view.getPivot().toArray(); var msg = pos.map(c => c.toFixed(3)).join(", "); Utils.clipboardCopy(msg); this.viewer.postMessage("Copied value to clipboard:
    '".concat(msg, "'"), { duration: 3000 }); }); this.propertiesPanel.addVolatileListener(viewer, "camera_changed", this._update); this.update(); } update() { //console.log("updating camera panel"); var camera = this.viewer.scene.getActiveCamera(); var view = this.viewer.scene.view; var pos = camera.position.toArray().map(c => Utils.addCommas(c.toFixed(3))); this.elContent.find("#camera_position_x").html(pos[0]); this.elContent.find("#camera_position_y").html(pos[1]); this.elContent.find("#camera_position_z").html(pos[2]); var target = view.getPivot().toArray().map(c => Utils.addCommas(c.toFixed(3))); this.elContent.find("#camera_target_x").html(target[0]); this.elContent.find("#camera_target_y").html(target[1]); this.elContent.find("#camera_target_z").html(target[2]); } } ; class AnnotationPanel { constructor(viewer, propertiesPanel, annotation) { this.viewer = viewer; this.propertiesPanel = propertiesPanel; this.annotation = annotation; this._update = () => { this.update(); }; var copyIconPath = "".concat(Potree.resourcePath, "/icons/copy.svg"); this.elContent = $("\n\t\t
    \n\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\n\t\t\t
    position
    \n\t\t\t\t\t\t\n\t\t\t\t\t
    \n\n\t\t\t
    \n\n\t\t\t\t
    Title
    \n\t\t\t\t
    \n\t\t\t\t\tAnnotation Title\n\t\t\t\t
    \n\n\t\t\t\t
    Description
    \n\t\t\t\t
    \n\t\t\t\t\tA longer description of this annotation. \n\t\t\t\t\t\tCan be multiple lines long. TODO: the user should be able\n\t\t\t\t\t\tto modify title and description. \n\t\t\t\t
    \n\n\t\t\t
    \n\n\t\t
    \n\t\t")); this.elCopyPosition = this.elContent.find("img[name=copyPosition]"); this.elCopyPosition.click(() => { var pos = this.annotation.position.toArray(); var msg = pos.map(c => c.toFixed(3)).join(", "); Utils.clipboardCopy(msg); this.viewer.postMessage("Copied value to clipboard:
    '".concat(msg, "'"), { duration: 3000 }); }); this.elTitle = this.elContent.find("#annotation_title").html(annotation.title); this.elDescription = this.elContent.find("#annotation_description").html(annotation.description); this.elTitle[0].addEventListener("input", () => { var title = this.elTitle.html(); annotation.title = title; }, false); this.elDescription[0].addEventListener("input", () => { var description = this.elDescription.html(); annotation.description = description; }, false); this.update(); } update() { var { annotation, elContent, elTitle, elDescription } = this; var pos = annotation.position.toArray().map(c => Utils.addCommas(c.toFixed(3))); elContent.find("#annotation_position_x").html(pos[0]); elContent.find("#annotation_position_y").html(pos[1]); elContent.find("#annotation_position_z").html(pos[2]); elTitle.html(annotation.title); elDescription.html(annotation.description); } } ; class CameraAnimationPanel { constructor(viewer, propertiesPanel, animation) { this.viewer = viewer; this.propertiesPanel = propertiesPanel; this.animation = animation; this.elContent = $("\n\t\t\t
    \n\t\t\t\t\n\n\t\t\t\t\n\n\t\t\t\t\t\n\t\t\t\t\t\tDuration: \n\t\t\t\t\t\t\n\t\t\t\t\t\n\n\t\t\t\t\tTime:
    \n\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t
    \n\t\t\t
    \n\t\t"); var elPlay = this.elContent.find("input[name=play]"); elPlay.click(() => { animation.play(); }); var elPause = this.elContent.find("input[name=pause]"); elPause.click(() => { animation.pause(); }); var elSlider = this.elContent.find('#sldTime'); elSlider.slider({ value: 0, min: 0, max: 1, step: 0.001, slide: (event, ui) => { animation.set(ui.value); animation.updateFrustum(); } }); var elDuration = this.elContent.find("input[name=spnDuration]"); elDuration.spinner({ min: 0, max: 300, step: 0.01, numberFormat: 'n', start: () => {}, spin: (event, ui) => { var value = elDuration.spinner('value'); animation.setDuration(value); }, change: (event, ui) => { var value = elDuration.spinner('value'); animation.setDuration(value); }, stop: (event, ui) => { var value = elDuration.spinner('value'); animation.setDuration(value); }, incremental: count => { var value = elDuration.spinner('value'); var step = elDuration.spinner('option', 'step'); var delta = value * 0.05; var increments = Math.max(1, parseInt(delta / step)); return increments; } }); elDuration.spinner('value', animation.getDuration()); elDuration.spinner('widget').css('width', '100%'); var elKeyframes = this.elContent.find("#animation_keyframes"); var updateKeyframes = () => { elKeyframes.empty(); //let index = 0; // // // var addNewKeyframeItem = index => { var elNewKeyframe = $("\n\t\t\t\t\t
    \n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t
    \n\t\t\t\t"); var elAdd = elNewKeyframe.find("input[name=add]"); elAdd.click(() => { animation.createControlPoint(index, { position: viewer.scene.view.position, target: viewer.scene.view.getPivot() }); animation.changeCallback(); }); elKeyframes.append(elNewKeyframe); }; var addKeyframeItem = index => { var elKeyframe = $("\n\t\t\t\t\t
    \n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tkeyframe\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t
    \n\t\t\t\t")); var elAssign = elKeyframe.find("img[name=assign]"); var elMove = elKeyframe.find("img[name=move]"); var elDelete = elKeyframe.find("img[name=delete]"); elAssign.click(() => { //修改 animation.posCurve.points[index].copy(viewer.scene.view.position); animation.targets[index].position.copy(viewer.scene.view.getPivot()); animation.changeCallback(index); }); elMove.click(() => { viewer.scene.view.position.copy(animation.posCurve.points[index]); viewer.scene.view.lookAt(animation.targets[index].position); }); elDelete.click(() => { animation.removeControlPoint(index); animation.changeCallback(); }); elKeyframes.append(elKeyframe); }; var index = 0; addNewKeyframeItem(index); animation.posCurve.points.forEach(e => { addKeyframeItem(index); index++; addNewKeyframeItem(index); }); }; updateKeyframes(); animation.addEventListener("controlpoint_added", updateKeyframes); animation.addEventListener("controlpoint_removed", updateKeyframes); // this._update = () => { this.update(); }; // this.update(); } update() {} } ; class PropertiesPanel { constructor(container, viewer) { this.container = container; this.viewer = viewer; this.object = null; this.cleanupTasks = []; this.scene = null; } setScene(scene) { this.scene = scene; } set(object) { if (this.object === object) { return; } this.object = object; for (var task of this.cleanupTasks) { task(); } this.cleanupTasks = []; this.container.empty(); if (object instanceof PointCloudTree) { this.setPointCloud(object); } else if (object instanceof Measure || object instanceof Profile || object instanceof Volume) { this.setMeasurement(object); } else if (object instanceof Camera) { this.setCamera(object); } else if (object instanceof Annotation) { this.setAnnotation(object); } else if (object instanceof CameraAnimation$1) { //改 this.setCameraAnimation(object); } } // // Used for events that should be removed when the property object changes. // This is for listening to materials, scene, point clouds, etc. // not required for DOM listeners, since they are automatically cleared by removing the DOM subtree. // addVolatileListener(target, type, callback) { target.addEventListener(type, callback); this.cleanupTasks.push(() => { target.removeEventListener(type, callback); }); } setPointCloud(pointcloud) { var material = pointcloud.material; var panel = $("\n\t\t\t
    \n\t\t\t\t
      \n\n\t\t\t\t
    • \n\t\t\t\t
      \n\t\t\t\t
    • \n\t\t\t\t
    • \n\t\t\t\t
      \n\t\t\t\t
    • \n\n\t\t\t\t\n\t\t\t\t
    • \n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t
    • \n\n\t\t\t\t\n\t\t\t\t
    • \n\t\t\t\t\t
      \n\t\t\t\t\t\n\t\t\t\t
    • \n\n\t\t\t\t
    • \n\t\t\t\t\n\t\t\t\t
    • \n\t\t\t\t\n\t\t\t\t\n\t\t\t\t
    • :
    • \n\n\t\t\t\t
      \n\t\t\t\t\tAttribute\n\t\t\t\t
      \n\n\t\t\t\t
    • \n\t\t\t\t\t\n\t\t\t\t
    • \n\n\t\t\t\t
      \n\t\t\t\t\t
      \n\t\t\t\t\t\tAttribute Weights\n\t\t\t\t\t
      \n\n\t\t\t\t\t
    • RGB:
      \t
    • \n\t\t\t\t\t
    • Intensity:
      \t
    • \n\t\t\t\t\t
    • Elevation:
      \t
    • \n\t\t\t\t\t
    • Classification:
      \t
    • \n\t\t\t\t\t
    • Return Number:
      \t
    • \n\t\t\t\t\t
    • Source ID:
      \t
    • \n\t\t\t\t
      \n\n\t\t\t\t
      \n\t\t\t\t\t
      \n\t\t\t\t\t\tRGB\n\t\t\t\t\t
      \n\n\t\t\t\t\t
    • Gamma:
      \t
    • \n\t\t\t\t\t
    • Brightness:
      \t
    • \n\t\t\t\t\t
    • Contrast:
      \t
    • \n\t\t\t\t
      \n\n\t\t\t\t
      \n\t\t\t\t\t
      \n\t\t\t\t\t\tExtra Attribute\n\t\t\t\t\t
      \n\n\t\t\t\t\t
    • :
    • \n\n\t\t\t\t\t
    • Gamma:
    • \n\t\t\t\t\t
    • Brightness:
    • \n\t\t\t\t\t
    • Contrast:
    • \n\t\t\t\t
      \n\t\t\t\t\n\t\t\t\t
      \n\t\t\t\t\t
      \n\t\t\t\t\t\tMATCAP\n\t\t\t\t\t
      \n\n\t\t\t\t\t
    • \n\t\t\t\t\t\t
      \n\t\t\t\t\t
    • \n\t\t\t\t
      \n\n\t\t\t\t
      \n\t\t\t\t\t
      \n\t\t\t\t\t\tColor\n\t\t\t\t\t
      \n\n\t\t\t\t\t\n\t\t\t\t
      \n\n\n\t\t\t\t
      \n\t\t\t\t\t
      \n\t\t\t\t\t\tElevation\n\t\t\t\t\t
      \n\n\t\t\t\t\t
    • :
      \t
    • \n\n\t\t\t\t\t
    • \n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t
    • \n\n\t\t\t\t\t
    • \n\t\t\t\t\t\tGradient Scheme:\n\t\t\t\t\t\t
      \n\t\t\t\t\t\t
      \n\t\t\t\t\t
    • \n\t\t\t\t
      \n\n\t\t\t\t
      \n\t\t\t\t\t
      \n\t\t\t\t\t\tTransition\n\t\t\t\t\t
      \n\n\t\t\t\t\t
    • transition:
      \t
    • \n\t\t\t\t
      \n\n\t\t\t\t
      \n\t\t\t\t\t
      \n\t\t\t\t\t\tIntensity\n\t\t\t\t\t
      \n\n\t\t\t\t\t
    • Range:
      \t
    • \n\t\t\t\t\t
    • Gamma:
      \t
    • \n\t\t\t\t\t
    • Brightness:
      \t
    • \n\t\t\t\t\t
    • Contrast:
      \t
    • \n\t\t\t\t
      \n\n\t\t\t\t
      \n\t\t\t\t\t
      \n\t\t\t\t\t\tGPS Time\n\t\t\t\t\t
      \n\n\t\t\t\t
      \n\t\t\t\t\n\t\t\t\t
      \n\t\t\t\t\t
      \n\t\t\t\t\t\tIndices\n\t\t\t\t\t
      \n\t\t\t\t
      \n\n\n\t\t\t\t
    \n\t\t\t
    \n\t\t"); panel.i18n(); this.container.append(panel); { // POINT SIZE var sldPointSize = panel.find("#sldPointSize"); var lblPointSize = panel.find("#lblPointSize"); sldPointSize.slider({ value: material.size, min: 0, max: 3, step: 0.01, slide: function slide(event, ui) { material.size = ui.value; } }); var update = e => { lblPointSize.html(material.size.toFixed(2)); sldPointSize.slider({ value: material.size }); }; this.addVolatileListener(material, "point_size_changed", update); update(); } { // MINIMUM POINT SIZE var sldMinPointSize = panel.find("#sldMinPointSize"); var lblMinPointSize = panel.find("#lblMinPointSize"); sldMinPointSize.slider({ value: material.size, min: 0, max: 3, step: 0.01, slide: function slide(event, ui) { material.minSize = ui.value; } }); var _update = e => { lblMinPointSize.html(material.minSize.toFixed(2)); sldMinPointSize.slider({ value: material.minSize }); }; this.addVolatileListener(material, "point_size_changed", _update); _update(); } { // POINT SIZING var strSizeType = Object.keys(PointSizeType)[material.pointSizeType]; var opt = panel.find("#optPointSizing"); opt.selectmenu(); opt.val(strSizeType).selectmenu('refresh'); opt.selectmenu({ change: (event, ui) => { material.pointSizeType = PointSizeType[ui.item.value]; } }); } { // SHAPE var _opt = panel.find("#optShape"); _opt.selectmenu({ change: (event, ui) => { var value = ui.item.value; material.shape = PointShape$1[value]; } }); var _update2 = () => { var typename = Object.keys(PointShape$1)[material.shape]; _opt.selectmenu().val(typename).selectmenu('refresh'); }; this.addVolatileListener(material, "point_shape_changed", _update2); _update2(); } { // BACKFACE CULLING var _opt2 = panel.find("#set_backface_culling"); _opt2.click(() => { material.backfaceCulling = _opt2.prop("checked"); }); var _update3 = () => { var value = material.backfaceCulling; _opt2.prop("checked", value); }; this.addVolatileListener(material, "backface_changed", _update3); _update3(); var blockBackface = $('#materials_backface_container'); blockBackface.css('display', 'none'); var pointAttributes = pointcloud.pcoGeometry.pointAttributes; var hasNormals = pointAttributes.hasNormals ? pointAttributes.hasNormals() : false; if (hasNormals) { blockBackface.css('display', 'block'); } /* opt.checkboxradio({ clicked: (event, ui) => { // let value = ui.item.value; let value = ui.item.checked; console.log(value); material.backfaceCulling = value; // $('#set_freeze').prop("checked"); } }); */ } { // OPACITY var sldOpacity = panel.find("#sldOpacity"); var lblOpacity = panel.find("#lblOpacity"); sldOpacity.slider({ value: material.opacity, min: 0, max: 1, step: 0.001, slide: function slide(event, ui) { material.opacity = ui.value; } }); var _update4 = e => { lblOpacity.html(material.opacity.toFixed(2)); sldOpacity.slider({ value: material.opacity }); }; this.addVolatileListener(material, "opacity_changed", _update4); _update4(); } { var attributes = pointcloud.pcoGeometry.pointAttributes.attributes; var options = []; options.push(...attributes.map(a => a.name)); var intensityIndex = options.indexOf("intensity"); if (intensityIndex >= 0) { options.splice(intensityIndex + 1, 0, "intensity gradient"); } options.push("elevation", "color", 'matcap', 'indices', 'level of detail', 'composite'); var blacklist = ["POSITION_CARTESIAN", "position"]; options = options.filter(o => !blacklist.includes(o)); var attributeSelection = panel.find('#optMaterial'); for (var option of options) { var elOption = $("")); attributeSelection.append(elOption); } var updateMaterialPanel = (event, ui) => { var selectedValue = attributeSelection.selectmenu().val(); material.activeAttributeName = selectedValue; var attribute = pointcloud.getAttribute(selectedValue); if (selectedValue === "intensity gradient") { attribute = pointcloud.getAttribute("intensity"); } var isIntensity = attribute ? ["intensity", "intensity gradient"].includes(attribute.name) : false; if (isIntensity) { if (pointcloud.material.intensityRange[0] === Infinity) { pointcloud.material.intensityRange = attribute.range; } var [min, max] = attribute.range; panel.find('#sldIntensityRange').slider({ range: true, min: min, max: max, step: 0.01, values: [min, max], slide: (event, ui) => { var min = ui.values[0]; var max = ui.values[1]; material.intensityRange = [min, max]; } }); } else if (attribute) { var [_min, _max] = attribute.range; var selectedRange = material.getRange(attribute.name); if (!selectedRange) { selectedRange = [...attribute.range]; } var minMaxAreNumbers = typeof _min === "number" && typeof _max === "number"; if (minMaxAreNumbers) { panel.find('#sldExtraRange').slider({ range: true, min: _min, max: _max, step: 0.01, values: selectedRange, slide: (event, ui) => { var [a, b] = ui.values; material.setRange(attribute.name, [a, b]); } }); } } var blockWeights = $('#materials\\.composite_weight_container'); var blockElevation = $('#materials\\.elevation_container'); var blockRGB = $('#materials\\.rgb_container'); var blockExtra = $('#materials\\.extra_container'); var blockColor = $('#materials\\.color_container'); var blockIntensity = $('#materials\\.intensity_container'); var blockIndex = $('#materials\\.index_container'); var blockTransition = $('#materials\\.transition_container'); var blockGps = $('#materials\\.gpstime_container'); var blockMatcap = $('#materials\\.matcap_container'); blockIndex.css('display', 'none'); blockIntensity.css('display', 'none'); blockElevation.css('display', 'none'); blockRGB.css('display', 'none'); blockExtra.css('display', 'none'); blockColor.css('display', 'none'); blockWeights.css('display', 'none'); blockTransition.css('display', 'none'); blockMatcap.css('display', 'none'); blockGps.css('display', 'none'); if (selectedValue === 'composite') { blockWeights.css('display', 'block'); blockElevation.css('display', 'block'); blockRGB.css('display', 'block'); blockIntensity.css('display', 'block'); } else if (selectedValue === 'elevation') { blockElevation.css('display', 'block'); } else if (selectedValue === 'RGB and Elevation') { blockRGB.css('display', 'block'); blockElevation.css('display', 'block'); } else if (selectedValue === 'rgba') { blockRGB.css('display', 'block'); } else if (selectedValue === 'color') { blockColor.css('display', 'block'); } else if (selectedValue === 'intensity') { blockIntensity.css('display', 'block'); } else if (selectedValue === 'intensity gradient') { blockIntensity.css('display', 'block'); } else if (selectedValue === "indices") { blockIndex.css('display', 'block'); } else if (selectedValue === "matcap") { blockMatcap.css('display', 'block'); } else if (selectedValue === "classification") { // add classification color selctor? } else if (selectedValue === "gps-time") { blockGps.css('display', 'block'); } else if (selectedValue === "number of returns") {} else if (selectedValue === "return number") {} else if (["source id", "point source id"].includes(selectedValue)) {} else { blockExtra.css('display', 'block'); } }; attributeSelection.selectmenu({ change: updateMaterialPanel }); var _update5 = () => { attributeSelection.val(material.activeAttributeName).selectmenu('refresh'); }; this.addVolatileListener(material, "point_color_type_changed", _update5); this.addVolatileListener(material, "active_attribute_changed", _update5); _update5(); updateMaterialPanel(); } { var schemes = Object.keys(Potree.Gradients).map(name => ({ name: name, values: Gradients[name] })); var elSchemeContainer = panel.find("#elevation_gradient_scheme_selection"); var _loop = function _loop(scheme) { var elScheme = $("\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t"); var svg = Potree.Utils.createSvgGradient(scheme.values); svg.setAttributeNS(null, "class", "button-icon"); elScheme.append($(svg)); elScheme.click(() => { material.gradient = Gradients[scheme.name]; }); elSchemeContainer.append(elScheme); }; for (var scheme of schemes) { _loop(scheme); } } { var matcaps = [{ name: "Normals", icon: "".concat(Potree.resourcePath, "/icons/matcap/check_normal+y.jpg") }, { name: "Basic 1", icon: "".concat(Potree.resourcePath, "/icons/matcap/basic_1.jpg") }, { name: "Basic 2", icon: "".concat(Potree.resourcePath, "/icons/matcap/basic_2.jpg") }, { name: "Basic Dark", icon: "".concat(Potree.resourcePath, "/icons/matcap/basic_dark.jpg") }, { name: "Basic Side", icon: "".concat(Potree.resourcePath, "/icons/matcap/basic_side.jpg") }, { name: "Ceramic Dark", icon: "".concat(Potree.resourcePath, "/icons/matcap/ceramic_dark.jpg") }, { name: "Ceramic Lightbulb", icon: "".concat(Potree.resourcePath, "/icons/matcap/ceramic_lightbulb.jpg") }, { name: "Clay Brown", icon: "".concat(Potree.resourcePath, "/icons/matcap/clay_brown.jpg") }, { name: "Clay Muddy", icon: "".concat(Potree.resourcePath, "/icons/matcap/clay_muddy.jpg") }, { name: "Clay Studio", icon: "".concat(Potree.resourcePath, "/icons/matcap/clay_studio.jpg") }, { name: "Resin", icon: "".concat(Potree.resourcePath, "/icons/matcap/resin.jpg") }, { name: "Skin", icon: "".concat(Potree.resourcePath, "/icons/matcap/skin.jpg") }, { name: "Jade", icon: "".concat(Potree.resourcePath, "/icons/matcap/jade.jpg") }, { name: "Metal_ Anisotropic", icon: "".concat(Potree.resourcePath, "/icons/matcap/metal_anisotropic.jpg") }, { name: "Metal Carpaint", icon: "".concat(Potree.resourcePath, "/icons/matcap/metal_carpaint.jpg") }, { name: "Metal Lead", icon: "".concat(Potree.resourcePath, "/icons/matcap/metal_lead.jpg") }, { name: "Metal Shiny", icon: "".concat(Potree.resourcePath, "/icons/matcap/metal_shiny.jpg") }, { name: "Pearl", icon: "".concat(Potree.resourcePath, "/icons/matcap/pearl.jpg") }, { name: "Toon", icon: "".concat(Potree.resourcePath, "/icons/matcap/toon.jpg") }, { name: "Check Rim Light", icon: "".concat(Potree.resourcePath, "/icons/matcap/check_rim_light.jpg") }, { name: "Check Rim Dark", icon: "".concat(Potree.resourcePath, "/icons/matcap/check_rim_dark.jpg") }, { name: "Contours 1", icon: "".concat(Potree.resourcePath, "/icons/matcap/contours_1.jpg") }, { name: "Contours 2", icon: "".concat(Potree.resourcePath, "/icons/matcap/contours_2.jpg") }, { name: "Contours 3", icon: "".concat(Potree.resourcePath, "/icons/matcap/contours_3.jpg") }, { name: "Reflection Check Horizontal", icon: "".concat(Potree.resourcePath, "/icons/matcap/reflection_check_horizontal.jpg") }, { name: "Reflection Check Vertical", icon: "".concat(Potree.resourcePath, "/icons/matcap/reflection_check_vertical.jpg") }]; var elMatcapContainer = panel.find("#matcap_scheme_selection"); var _loop2 = function _loop2(matcap) { var elMatcap = $("\n\t\t\t\t\t\t\n\t\t\t\t")); elMatcap.click(() => { material.matcap = matcap.icon.substring(matcap.icon.lastIndexOf('/')); }); elMatcapContainer.append(elMatcap); }; for (var matcap of matcaps) { _loop2(matcap); } } { panel.find('#sldRGBGamma').slider({ value: material.rgbGamma, min: 0, max: 4, step: 0.01, slide: (event, ui) => { material.rgbGamma = ui.value; } }); panel.find('#sldRGBContrast').slider({ value: material.rgbContrast, min: -1, max: 1, step: 0.01, slide: (event, ui) => { material.rgbContrast = ui.value; } }); panel.find('#sldRGBBrightness').slider({ value: material.rgbBrightness, min: -1, max: 1, step: 0.01, slide: (event, ui) => { material.rgbBrightness = ui.value; } }); panel.find('#sldExtraGamma').slider({ value: material.extraGamma, min: 0, max: 4, step: 0.01, slide: (event, ui) => { material.extraGamma = ui.value; } }); panel.find('#sldExtraBrightness').slider({ value: material.extraBrightness, min: -1, max: 1, step: 0.01, slide: (event, ui) => { material.extraBrightness = ui.value; } }); panel.find('#sldExtraContrast').slider({ value: material.extraContrast, min: -1, max: 1, step: 0.01, slide: (event, ui) => { material.extraContrast = ui.value; } }); panel.find('#sldHeightRange').slider({ range: true, min: 0, max: 1000, step: 0.01, values: [0, 1000], slide: (event, ui) => { material.heightMin = ui.values[0]; material.heightMax = ui.values[1]; } }); panel.find('#sldIntensityGamma').slider({ value: material.intensityGamma, min: 0, max: 4, step: 0.01, slide: (event, ui) => { material.intensityGamma = ui.value; } }); panel.find('#sldIntensityContrast').slider({ value: material.intensityContrast, min: -1, max: 1, step: 0.01, slide: (event, ui) => { material.intensityContrast = ui.value; } }); panel.find('#sldIntensityBrightness').slider({ value: material.intensityBrightness, min: -1, max: 1, step: 0.01, slide: (event, ui) => { material.intensityBrightness = ui.value; } }); panel.find('#sldWeightRGB').slider({ value: material.weightRGB, min: 0, max: 1, step: 0.01, slide: (event, ui) => { material.weightRGB = ui.value; } }); panel.find('#sldWeightIntensity').slider({ value: material.weightIntensity, min: 0, max: 1, step: 0.01, slide: (event, ui) => { material.weightIntensity = ui.value; } }); panel.find('#sldWeightElevation').slider({ value: material.weightElevation, min: 0, max: 1, step: 0.01, slide: (event, ui) => { material.weightElevation = ui.value; } }); panel.find('#sldWeightClassification').slider({ value: material.weightClassification, min: 0, max: 1, step: 0.01, slide: (event, ui) => { material.weightClassification = ui.value; } }); panel.find('#sldWeightReturnNumber').slider({ value: material.weightReturnNumber, min: 0, max: 1, step: 0.01, slide: (event, ui) => { material.weightReturnNumber = ui.value; } }); panel.find('#sldWeightSourceID').slider({ value: material.weightSourceID, min: 0, max: 1, step: 0.01, slide: (event, ui) => { material.weightSourceID = ui.value; } }); panel.find("#materials\\.color\\.picker").spectrum({ flat: true, showInput: true, preferredFormat: 'rgb', cancelText: '', chooseText: 'Apply', color: "#".concat(material.color.getHexString()), move: color => { var cRGB = color.toRgb(); var tc = new Color().setRGB(cRGB.r / 255, cRGB.g / 255, cRGB.b / 255); material.color = tc; }, change: color => { var cRGB = color.toRgb(); var tc = new Color().setRGB(cRGB.r / 255, cRGB.g / 255, cRGB.b / 255); material.color = tc; } }); this.addVolatileListener(material, "color_changed", () => { panel.find("#materials\\.color\\.picker").spectrum('set', "#".concat(material.color.getHexString())); }); var updateHeightRange = function updateHeightRange() { var aPosition = pointcloud.getAttribute("position"); var bMin, bMax; if (aPosition) { // for new format 2.0 and loader that contain precomputed min/max of attributes var min = aPosition.range[0][2]; var max = aPosition.range[1][2]; var width = max - min; bMin = min - 0.2 * width; bMax = max + 0.2 * width; } else { // for format up until exlusive 2.0 var box = [pointcloud.pcoGeometry.tightBoundingBox, pointcloud.getBoundingBoxWorld()].find(v => v !== undefined); pointcloud.updateMatrixWorld(true); box = Utils.computeTransformedBoundingBox(box, pointcloud.matrixWorld); var bWidth = box.max.z - box.min.z; bMin = box.min.z - 0.2 * bWidth; bMax = box.max.z + 0.2 * bWidth; } var range = material.elevationRange; panel.find('#lblHeightRange').html("".concat(range[0].toFixed(2), " to ").concat(range[1].toFixed(2))); panel.find('#sldHeightRange').slider({ min: bMin, max: bMax, values: range }); }; var updateExtraRange = function updateExtraRange() { var attributeName = material.activeAttributeName; var attribute = pointcloud.getAttribute(attributeName); if (attribute == null) { return; } var range = material.getRange(attributeName); if (range == null) { range = attribute.range; } // currently only supporting scalar ranges. // rgba, normals, positions, etc have vector ranges, however var isValidRange = typeof range[0] === "number" && typeof range[1] === "number"; if (!isValidRange) { return; } if (range) { var msg = "".concat(range[0].toFixed(2), " to ").concat(range[1].toFixed(2)); panel.find('#lblExtraRange').html(msg); } else { panel.find("could not deduce range"); } }; var updateIntensityRange = function updateIntensityRange() { var range = material.intensityRange; panel.find('#lblIntensityRange').html("".concat(parseInt(range[0]), " to ").concat(parseInt(range[1]))); }; { updateHeightRange(); panel.find("#sldHeightRange").slider('option', 'min'); panel.find("#sldHeightRange").slider('option', 'max'); } { var elGradientRepeat = panel.find("#gradient_repeat_option"); elGradientRepeat.selectgroup({ title: "Gradient" }); elGradientRepeat.find("input").click(e => { this.viewer.setElevationGradientRepeat(ElevationGradientRepeat[e.target.value]); }); var current = Object.keys(ElevationGradientRepeat).filter(key => ElevationGradientRepeat[key] === this.viewer.elevationGradientRepeat); elGradientRepeat.find("input[value=".concat(current, "]")).trigger("click"); } var onIntensityChange = () => { var gamma = material.intensityGamma; var contrast = material.intensityContrast; var brightness = material.intensityBrightness; updateIntensityRange(); panel.find('#lblIntensityGamma').html(gamma.toFixed(2)); panel.find('#lblIntensityContrast').html(contrast.toFixed(2)); panel.find('#lblIntensityBrightness').html(brightness.toFixed(2)); panel.find('#sldIntensityGamma').slider({ value: gamma }); panel.find('#sldIntensityContrast').slider({ value: contrast }); panel.find('#sldIntensityBrightness').slider({ value: brightness }); }; var onRGBChange = () => { var gamma = material.rgbGamma; var contrast = material.rgbContrast; var brightness = material.rgbBrightness; panel.find('#lblRGBGamma').html(gamma.toFixed(2)); panel.find('#lblRGBContrast').html(contrast.toFixed(2)); panel.find('#lblRGBBrightness').html(brightness.toFixed(2)); panel.find('#sldRGBGamma').slider({ value: gamma }); panel.find('#sldRGBContrast').slider({ value: contrast }); panel.find('#sldRGBBrightness').slider({ value: brightness }); }; this.addVolatileListener(material, "material_property_changed", updateExtraRange); this.addVolatileListener(material, "material_property_changed", updateHeightRange); this.addVolatileListener(material, "material_property_changed", onIntensityChange); this.addVolatileListener(material, "material_property_changed", onRGBChange); updateExtraRange(); updateHeightRange(); onIntensityChange(); onRGBChange(); } } setMeasurement(object) { var TYPE = { DISTANCE: { panel: DistancePanel }, AREA: { panel: AreaPanel }, POINT: { panel: PointPanel }, ANGLE: { panel: AnglePanel }, HEIGHT: { panel: HeightPanel }, PROFILE: { panel: ProfilePanel }, VOLUME: { panel: VolumePanel }, CIRCLE: { panel: CirclePanel }, OTHER: { panel: PointPanel } }; var getType = measurement => { if (measurement instanceof Measure) { if (measurement.showDistances && !measurement.showArea && !measurement.showAngles) { return TYPE.DISTANCE; } else if (measurement.showDistances && measurement.showArea && !measurement.showAngles) { return TYPE.AREA; } else if (measurement.maxMarkers === 1) { return TYPE.POINT; } else if (!measurement.showDistances && !measurement.showArea && measurement.showAngles) { return TYPE.ANGLE; } else if (measurement.showHeight) { return TYPE.HEIGHT; } else if (measurement.showCircle) { return TYPE.CIRCLE; } else { return TYPE.OTHER; } } else if (measurement instanceof Profile) { return TYPE.PROFILE; } else if (measurement instanceof Volume) { return TYPE.VOLUME; } }; //this.container.html("measurement"); var type = getType(object); var Panel = type.panel; var panel = new Panel(this.viewer, object, this); this.container.append(panel.elContent); } setCamera(camera) { var panel = new CameraPanel(this.viewer, this); this.container.append(panel.elContent); } setAnnotation(annotation) { var panel = new AnnotationPanel(this.viewer, this, annotation); this.container.append(panel.elContent); } setCameraAnimation(animation) { var panel = new CameraAnimationPanel(this.viewer, this, animation); this.container.append(panel.elContent); } } function addCommas(nStr) { nStr += ''; var x = nStr.split('.'); var x1 = x[0]; var x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; } ; function format(value) { return addCommas(value.toFixed(3)); } ; class HierarchicalSlider { constructor() { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; this.element = document.createElement("div"); this.labels = []; this.sliders = []; this.range = params.range != null ? params.range : [0, 1]; this.slide = params.slide != null ? params.slide : null; this.step = params.step != null ? params.step : 0.0001; var levels = params.levels != null ? params.levels : 1; for (var level = 0; level < levels; level++) { this.addLevel(); } } setRange(range) { this.range = [...range]; { // root slider var slider = this.sliders[0]; $(slider).slider({ min: range[0], max: range[1] }); } for (var i = 1; i < this.sliders.length; i++) { var parentSlider = this.sliders[i - 1]; var _slider = this.sliders[i]; var parentValues = $(parentSlider).slider("option", "values"); var childRange = [...parentValues]; $(_slider).slider({ min: childRange[0], max: childRange[1] }); } this.updateLabels(); } setValues(values) { for (var slider of this.sliders) { $(slider).slider({ values: [...values] }); } this.updateLabels(); } addLevel() { var elLevel = document.createElement("li"); var elRange = document.createTextNode("Range: "); var label = document.createElement("span"); var slider = document.createElement("div"); var level = this.sliders.length; var [min, max] = [0, 0]; if (this.sliders.length === 0) { [min, max] = this.range; } else { var parentSlider = this.sliders[this.sliders.length - 1]; [min, max] = $(parentSlider).slider("option", "values"); } $(slider).slider({ range: true, min: min, max: max, step: this.step, values: [min, max], slide: (event, ui) => { // set all descendants to same range var levels = this.sliders.length; for (var i = level + 1; i < levels; i++) { var descendant = this.sliders[i]; $(descendant).slider({ range: true, min: ui.values[0], max: ui.values[1], values: [...ui.values] }); } if (this.slide) { var values = [...ui.values]; this.slide({ target: this, range: this.range, values: values }); } this.updateLabels(); } }); elLevel.append(elRange, label, slider); this.sliders.push(slider); this.labels.push(label); this.element.append(elLevel); this.updateLabels(); } removeLevel() {} updateSliders() {} updateLabels() { var levels = this.sliders.length; for (var i = 0; i < levels; i++) { var slider = this.sliders[i]; var label = this.labels[i]; var [min, max] = $(slider).slider("option", "values"); var strMin = format(min); var strMax = format(max); var strLabel = "".concat(strMin, " to ").concat(strMax); label.innerHTML = strLabel; } } } class OrientedImageControls extends EventDispatcher$1 { constructor(viewer) { super(); this.viewer = viewer; this.renderer = viewer.renderer; this.originalCam = viewer.scene.getActiveCamera(); this.shearCam = viewer.scene.getActiveCamera().clone(); this.shearCam.rotation.set(this.originalCam.rotation.toArray()); this.shearCam.updateProjectionMatrix(); this.shearCam.updateProjectionMatrix = () => { return this.shearCam.projectionMatrix; }; this.image = null; this.fadeFactor = 20; this.fovDelta = 0; this.fovMin = 0.1; this.fovMax = 120; this.shear = [0, 0]; // const style = ``; this.elUp = $(""); this.elRight = $(""); this.elDown = $(""); this.elLeft = $(""); this.elExit = $(""); this.elExit.click(() => { this.release(); }); this.elUp.click(() => { var fovY = viewer.getFOV(); var top = Math.tan(MathUtils.degToRad(fovY / 2)); this.shear[1] += 0.1 * top; }); this.elRight.click(() => { var fovY = viewer.getFOV(); var top = Math.tan(MathUtils.degToRad(fovY / 2)); this.shear[0] += 0.1 * top; }); this.elDown.click(() => { var fovY = viewer.getFOV(); var top = Math.tan(MathUtils.degToRad(fovY / 2)); this.shear[1] -= 0.1 * top; }); this.elLeft.click(() => { var fovY = viewer.getFOV(); var top = Math.tan(MathUtils.degToRad(fovY / 2)); this.shear[0] -= 0.1 * top; }); this.scene = null; this.sceneControls = new Scene(); var scroll = e => { this.fovDelta += -e.delta * 1.0; }; this.addEventListener('mousewheel', scroll); //this.addEventListener("mousemove", onMove); } hasSomethingCaptured() { return this.image !== null; } capture(image) { if (this.hasSomethingCaptured()) { return; } this.image = image; this.originalFOV = this.viewer.getFOV(); this.originalControls = this.viewer.getControls(); this.viewer.setControls(this); this.viewer.scene.overrideCamera = this.shearCam; var elCanvas = this.viewer.renderer.domElement; var elRoot = $(elCanvas.parentElement); this.shear = [0, 0]; elRoot.append(this.elUp); elRoot.append(this.elRight); elRoot.append(this.elDown); elRoot.append(this.elLeft); elRoot.append(this.elExit); } release() { this.image = null; this.viewer.scene.overrideCamera = null; this.elUp.detach(); this.elRight.detach(); this.elDown.detach(); this.elLeft.detach(); this.elExit.detach(); this.viewer.setFOV(this.originalFOV); this.viewer.setControls(this.originalControls); } setScene(scene) { this.scene = scene; } update(delta) { // const view = this.scene.view; // let prevTotal = this.shearCam.projectionMatrix.elements.reduce( (a, i) => a + i, 0); //const progression = Math.min(1, this.fadeFactor * delta); //const attenuation = Math.max(0, 1 - this.fadeFactor * delta); var progression = 1; var attenuation = 0; var oldFov = this.viewer.getFOV(); var fovProgression = progression * this.fovDelta; var newFov = oldFov * (1 + fovProgression / 10); newFov = Math.max(this.fovMin, newFov); newFov = Math.min(this.fovMax, newFov); var diff = newFov / oldFov; var mouse = this.viewer.inputHandler.mouse; var canvasSize = this.viewer.renderer.getSize(new Vector2()); var uv = [mouse.x / canvasSize.x, (canvasSize.y - mouse.y) / canvasSize.y]; var fovY = newFov; var aspect = canvasSize.x / canvasSize.y; var top = Math.tan(MathUtils.degToRad(fovY / 2)); var height = 2 * top; var width = aspect * height; var shearRangeX = [this.shear[0] - 0.5 * width, this.shear[0] + 0.5 * width]; var shearRangeY = [this.shear[1] - 0.5 * height, this.shear[1] + 0.5 * height]; var shx = (1 - uv[0]) * shearRangeX[0] + uv[0] * shearRangeX[1]; var shy = (1 - uv[1]) * shearRangeY[0] + uv[1] * shearRangeY[1]; var shu = 1 - diff; var newShear = [(1 - shu) * this.shear[0] + shu * shx, (1 - shu) * this.shear[1] + shu * shy]; this.shear = newShear; this.viewer.setFOV(newFov); var { originalCam, shearCam } = this; originalCam.fov = newFov; originalCam.updateMatrixWorld(); originalCam.updateProjectionMatrix(); shearCam.copy(originalCam); shearCam.rotation.set(...originalCam.rotation.toArray()); shearCam.updateMatrixWorld(); shearCam.projectionMatrix.copy(originalCam.projectionMatrix); var [sx, sy] = this.shear; var mShear = new Matrix4().set(1, 0, sx, 0, 0, 1, sy, 0, 0, 0, 1, 0, 0, 0, 0, 1); var proj = shearCam.projectionMatrix; proj.multiply(mShear); shearCam.projectionMatrixInverse.copy(proj).invert(); var total = shearCam.projectionMatrix.elements.reduce((a, i) => a + i, 0); this.fovDelta *= attenuation; } } ; // https://support.pix4d.com/hc/en-us/articles/205675256-How-are-yaw-pitch-roll-defined // https://support.pix4d.com/hc/en-us/articles/202558969-How-are-omega-phi-kappa-defined function createMaterial() { var vertexShader = "\n\tuniform float uNear;\n\tvarying vec2 vUV;\n\tvarying vec4 vDebug;\n\t\n\tvoid main(){\n\t\tvDebug = vec4(0.0, 1.0, 0.0, 1.0);\n\t\tvec4 modelViewPosition = modelViewMatrix * vec4(position, 1.0);\n\t\t// make sure that this mesh is at least in front of the near plane\n\t\tmodelViewPosition.xyz += normalize(modelViewPosition.xyz) * uNear;\n\t\tgl_Position = projectionMatrix * modelViewPosition;\n\t\tvUV = uv;\n\t}\n\t"; var fragmentShader = "\n\tuniform sampler2D tColor;\n\tuniform float uOpacity;\n\tvarying vec2 vUV;\n\tvarying vec4 vDebug;\n\tvoid main(){\n\t\tvec4 color = texture2D(tColor, vUV);\n\t\tgl_FragColor = color;\n\t\tgl_FragColor.a = uOpacity;\n\t}\n\t"; var material = new ShaderMaterial({ uniforms: { // time: { value: 1.0 }, // resolution: { value: new THREE.Vector2() } tColor: { value: new Texture() }, uNear: { value: 0.0 }, uOpacity: { value: 1.0 } }, vertexShader: vertexShader, fragmentShader: fragmentShader, side: DoubleSide }); material.side = DoubleSide; return material; } var planeGeometry = new PlaneGeometry(1, 1); var lineGeometry = new Geometry(); lineGeometry.vertices.push(new Vector3(-0.5, -0.5, 0), new Vector3(0.5, -0.5, 0), new Vector3(0.5, 0.5, 0), new Vector3(-0.5, 0.5, 0), new Vector3(-0.5, -0.5, 0)); class OrientedImage { constructor(id) { this.id = id; this.fov = 1.0; this.position = new Vector3(); this.rotation = new Vector3(); this.width = 0; this.height = 0; this.fov = 1.0; var material = createMaterial(); var lineMaterial = new LineBasicMaterial({ color: 0x00ff00 }); this.mesh = new Mesh(planeGeometry, material); this.line = new Line(lineGeometry, lineMaterial); this.texture = null; this.mesh.orientedImage = this; } set(position, rotation, dimension, fov) { var radians = rotation.map(MathUtils.degToRad); this.position.set(...position); this.mesh.position.set(...position); this.rotation.set(...radians); this.mesh.rotation.set(...radians); [this.width, this.height] = dimension; this.mesh.scale.set(this.width / this.height, 1, 1); this.fov = fov; this.updateTransform(); } updateTransform() { var { mesh, line, fov } = this; mesh.updateMatrixWorld(); var dir = mesh.getWorldDirection(); var alpha = MathUtils.degToRad(fov / 2); var d = -0.5 / Math.tan(alpha); var move = dir.clone().multiplyScalar(d); mesh.position.add(move); line.position.copy(mesh.position); line.scale.copy(mesh.scale); line.rotation.copy(mesh.rotation); } } ; class OrientedImages extends EventDispatcher$1 { constructor() { super(); this.node = null; this.cameraParams = null; this.imageParams = null; this.images = null; this._visible = true; } set visible(visible) { if (this._visible === visible) { return; } for (var image of this.images) { image.mesh.visible = visible; image.line.visible = visible; } this._visible = visible; this.dispatchEvent({ type: "visibility_changed", images: this }); } get visible() { return this._visible; } } ; class OrientedImageLoader { static async loadCameraParams(path) { var res = await fetch(path); var text = await res.text(); var parser = new DOMParser(); var doc = parser.parseFromString(text, "application/xml"); var width = parseInt(doc.getElementsByTagName("width")[0].textContent); var height = parseInt(doc.getElementsByTagName("height")[0].textContent); var f = parseFloat(doc.getElementsByTagName("f")[0].textContent); var a = height / 2 / f; var fov = 2 * MathUtils.radToDeg(Math.atan(a)); var params = { path: path, width: width, height: height, f: f, fov: fov }; return params; } static async loadImageParams(path) { var response = await fetch(path); if (!response.ok) { console.error("failed to load ".concat(path)); return; } var content = await response.text(); var lines = content.split(/\r?\n/); var imageParams = []; for (var i = 1; i < lines.length; i++) { var line = lines[i]; if (line.startsWith("#")) { continue; } var tokens = line.split(/\s+/); if (tokens.length < 6) { continue; } var params = { id: tokens[0], x: Number.parseFloat(tokens[1]), y: Number.parseFloat(tokens[2]), z: Number.parseFloat(tokens[3]), omega: Number.parseFloat(tokens[4]), phi: Number.parseFloat(tokens[5]), kappa: Number.parseFloat(tokens[6]) }; // const whitelist = ["47518.jpg"]; // if(whitelist.includes(params.id)){ // imageParams.push(params); // } imageParams.push(params); } // debug //return [imageParams[50]]; return imageParams; } static async load(cameraParamsPath, imageParamsPath, viewer) { var tStart = performance.now(); var [cameraParams, imageParams] = await Promise.all([OrientedImageLoader.loadCameraParams(cameraParamsPath), OrientedImageLoader.loadImageParams(imageParamsPath)]); var orientedImageControls = new OrientedImageControls(viewer); var raycaster = new Raycaster(); var tEnd = performance.now(); console.log(tEnd - tStart); // const sp = new THREE.PlaneGeometry(1, 1); // const lg = new THREE.Geometry(); // lg.vertices.push( // new THREE.Vector3(-0.5, -0.5, 0), // new THREE.Vector3( 0.5, -0.5, 0), // new THREE.Vector3( 0.5, 0.5, 0), // new THREE.Vector3(-0.5, 0.5, 0), // new THREE.Vector3(-0.5, -0.5, 0), // ); var { width, height } = cameraParams; var orientedImages = []; var sceneNode = new Object3D(); sceneNode.name = "oriented_images"; for (var params of imageParams) { // const material = createMaterial(); // const lm = new THREE.LineBasicMaterial( { color: 0x00ff00 } ); // const mesh = new THREE.Mesh(sp, material); var { x, y, z, omega, phi, kappa } = params; // const [rx, ry, rz] = [omega, phi, kappa] // .map(THREE.Math.degToRad); // mesh.position.set(x, y, z); // mesh.scale.set(width / height, 1, 1); // mesh.rotation.set(rx, ry, rz); // { // mesh.updateMatrixWorld(); // const dir = mesh.getWorldDirection(); // const alpha = THREE.Math.degToRad(cameraParams.fov / 2); // const d = -0.5 / Math.tan(alpha); // const move = dir.clone().multiplyScalar(d); // mesh.position.add(move); // } // sceneNode.add(mesh); // const line = new THREE.Line(lg, lm); // line.position.copy(mesh.position); // line.scale.copy(mesh.scale); // line.rotation.copy(mesh.rotation); // sceneNode.add(line); var orientedImage = new OrientedImage(params.id); // orientedImage.setPosition(x, y, z); // orientedImage.setRotation(omega, phi, kappa); // orientedImage.setDimension(width, height); var position = [x, y, z]; var rotation = [omega, phi, kappa]; var dimension = [width, height]; orientedImage.set(position, rotation, dimension, cameraParams.fov); sceneNode.add(orientedImage.mesh); sceneNode.add(orientedImage.line); orientedImages.push(orientedImage); } var hoveredElement = null; var clipVolume = null; var onMouseMove = evt => { var tStart = performance.now(); if (hoveredElement) { hoveredElement.line.material.color.setRGB(0, 1, 0); } evt.preventDefault(); //var array = getMousePosition( container, evt.clientX, evt.clientY ); var rect = viewer.renderer.domElement.getBoundingClientRect(); var [x, y] = [evt.clientX, evt.clientY]; var array = [(x - rect.left) / rect.width, (y - rect.top) / rect.height]; var onClickPosition = new Vector2(...array); //const intersects = getIntersects(onClickPosition, scene.children); var camera = viewer.scene.getActiveCamera(); var mouse = new Vector3(+(onClickPosition.x * 2) - 1, -(onClickPosition.y * 2) + 1); var objects = orientedImages.map(i => i.mesh); raycaster.setFromCamera(mouse, camera); var intersects = raycaster.intersectObjects(objects); var selectionChanged = false; if (intersects.length > 0) { //console.log(intersects); var intersection = intersects[0]; var _orientedImage = intersection.object.orientedImage; _orientedImage.line.material.color.setRGB(1, 0, 0); selectionChanged = hoveredElement !== _orientedImage; hoveredElement = _orientedImage; } else { hoveredElement = null; } var shouldRemoveClipVolume = clipVolume !== null && hoveredElement === null; var shouldAddClipVolume = clipVolume === null && hoveredElement !== null; if (clipVolume !== null && (hoveredElement === null || selectionChanged)) { // remove existing viewer.scene.removePolygonClipVolume(clipVolume); clipVolume = null; } if (shouldAddClipVolume || selectionChanged) { var img = hoveredElement; var fov = cameraParams.fov; var aspect = cameraParams.width / cameraParams.height; var near = 1.0; var far = 1000 * 1000; var _camera = new PerspectiveCamera(fov, aspect, near, far); _camera.rotation.order = viewer.scene.getActiveCamera().rotation.order; _camera.rotation.copy(img.mesh.rotation); { var mesh = img.mesh; var dir = mesh.getWorldDirection(); var pos = mesh.position; var alpha = MathUtils.degToRad(fov / 2); var d = 0.5 / Math.tan(alpha); var newCamPos = pos.clone().add(dir.clone().multiplyScalar(d)); var newCamDir = pos.clone().sub(newCamPos); var newCamTarget = new Vector3().addVectors(newCamPos, newCamDir.clone().multiplyScalar(viewer.getMoveSpeed())); _camera.position.copy(newCamPos); } var volume = new Potree.PolygonClipVolume(_camera); var m0 = new Mesh(); var m1 = new Mesh(); var m2 = new Mesh(); var m3 = new Mesh(); m0.position.set(-1, -1, 0); m1.position.set(1, -1, 0); m2.position.set(1, 1, 0); m3.position.set(-1, 1, 0); volume.markers.push(m0, m1, m2, m3); volume.initialized = true; viewer.scene.addPolygonClipVolume(volume); clipVolume = volume; } var tEnd = performance.now(); //console.log(tEnd - tStart); }; var moveToImage = image => { console.log("move to image " + image.id); var mesh = image.mesh; var newCamPos = image.position.clone(); var newCamTarget = mesh.position.clone(); viewer.scene.view.setView(newCamPos, newCamTarget, 500, () => { orientedImageControls.capture(image); }); if (image.texture === null) { var target = image; var tmpImagePath = "".concat(Potree.resourcePath, "/images/loading.jpg"); new TextureLoader().load(tmpImagePath, texture => { if (target.texture === null) { target.texture = texture; target.mesh.material.uniforms.tColor.value = texture; mesh.material.needsUpdate = true; } }); var imagePath = "".concat(imageParamsPath, "/../").concat(target.id); new TextureLoader().load(imagePath, texture => { target.texture = texture; target.mesh.material.uniforms.tColor.value = texture; mesh.material.needsUpdate = true; }); } }; var onMouseClick = evt => { if (orientedImageControls.hasSomethingCaptured()) { return; } if (hoveredElement) { moveToImage(hoveredElement); } }; viewer.renderer.domElement.addEventListener('mousemove', onMouseMove, false); viewer.renderer.domElement.addEventListener('mousedown', onMouseClick, false); viewer.addEventListener("update", () => { for (var image of orientedImages) { var world = image.mesh.matrixWorld; var { width: _width, height: _height } = image; var aspect = _width / _height; var camera = viewer.scene.getActiveCamera(); var imgPos = image.mesh.getWorldPosition(new Vector3()); var camPos = camera.position; var d = camPos.distanceTo(imgPos); var minSize = 1; // in degrees of fov var a = MathUtils.degToRad(minSize); var r = d * Math.tan(a); r = Math.max(r, 1); image.mesh.scale.set(r * aspect, r, 1); image.line.scale.set(r * aspect, r, 1); image.mesh.material.uniforms.uNear.value = camera.near; } }); var images = new OrientedImages(); images.node = sceneNode; images.cameraParamsPath = cameraParamsPath; images.imageParamsPath = imageParamsPath; images.cameraParams = cameraParams; images.imageParams = imageParams; images.images = orientedImages; Potree.debug.moveToImage = moveToImage; return images; } } // This is a generated file. Do not edit. var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/; var ID_Start = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/; var ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/; var unicode = { Space_Separator: Space_Separator, ID_Start: ID_Start, ID_Continue: ID_Continue }; var util = { isSpaceSeparator(c) { return typeof c === 'string' && unicode.Space_Separator.test(c); }, isIdStartChar(c) { return typeof c === 'string' && (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c === '$' || c === '_' || unicode.ID_Start.test(c)); }, isIdContinueChar(c) { return typeof c === 'string' && (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c === '$' || c === '_' || c === '\u200C' || c === '\u200D' || unicode.ID_Continue.test(c)); }, isDigit(c) { return typeof c === 'string' && /[0-9]/.test(c); }, isHexDigit(c) { return typeof c === 'string' && /[0-9A-Fa-f]/.test(c); } }; var source; var parseState; var stack$1; var pos; var line; var column; var token; var key; var root; var parse$4 = function parse(text, reviver) { source = String(text); parseState = 'start'; stack$1 = []; pos = 0; line = 1; column = 0; token = undefined; key = undefined; root = undefined; do { token = lex(); // This code is unreachable. // if (!parseStates[parseState]) { // throw invalidParseState() // } parseStates[parseState](); } while (token.type !== 'eof'); if (typeof reviver === 'function') { return internalize({ '': root }, '', reviver); } return root; }; function internalize(holder, name, reviver) { var value = holder[name]; if (value != null && typeof value === 'object') { for (var _key in value) { var replacement = internalize(value, _key, reviver); if (replacement === undefined) { delete value[_key]; } else { value[_key] = replacement; } } } return reviver.call(holder, name, value); } var lexState; var buffer; var doubleQuote; var sign$1; var c$2; function lex() { lexState = 'default'; buffer = ''; doubleQuote = false; sign$1 = 1; for (;;) { c$2 = peek(); // This code is unreachable. // if (!lexStates[lexState]) { // throw invalidLexState(lexState) // } var _token = lexStates[lexState](); if (_token) { return _token; } } } function peek() { if (source[pos]) { return String.fromCodePoint(source.codePointAt(pos)); } } function read() { var c = peek(); if (c === '\n') { line++; column = 0; } else if (c) { column += c.length; } else { column++; } if (c) { pos += c.length; } return c; } var lexStates = { default() { switch (c$2) { case '\t': case '\v': case '\f': case ' ': case '\u00A0': case '\uFEFF': case '\n': case '\r': case '\u2028': case '\u2029': read(); return; case '/': read(); lexState = 'comment'; return; case undefined: read(); return newToken('eof'); } if (util.isSpaceSeparator(c$2)) { read(); return; } // This code is unreachable. // if (!lexStates[parseState]) { // throw invalidLexState(parseState) // } return lexStates[parseState](); }, comment() { switch (c$2) { case '*': read(); lexState = 'multiLineComment'; return; case '/': read(); lexState = 'singleLineComment'; return; } throw invalidChar(read()); }, multiLineComment() { switch (c$2) { case '*': read(); lexState = 'multiLineCommentAsterisk'; return; case undefined: throw invalidChar(read()); } read(); }, multiLineCommentAsterisk() { switch (c$2) { case '*': read(); return; case '/': read(); lexState = 'default'; return; case undefined: throw invalidChar(read()); } read(); lexState = 'multiLineComment'; }, singleLineComment() { switch (c$2) { case '\n': case '\r': case '\u2028': case '\u2029': read(); lexState = 'default'; return; case undefined: read(); return newToken('eof'); } read(); }, value() { switch (c$2) { case '{': case '[': return newToken('punctuator', read()); case 'n': read(); literal('ull'); return newToken('null', null); case 't': read(); literal('rue'); return newToken('boolean', true); case 'f': read(); literal('alse'); return newToken('boolean', false); case '-': case '+': if (read() === '-') { sign$1 = -1; } lexState = 'sign'; return; case '.': buffer = read(); lexState = 'decimalPointLeading'; return; case '0': buffer = read(); lexState = 'zero'; return; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': buffer = read(); lexState = 'decimalInteger'; return; case 'I': read(); literal('nfinity'); return newToken('numeric', Infinity); case 'N': read(); literal('aN'); return newToken('numeric', NaN); case '"': case "'": doubleQuote = read() === '"'; buffer = ''; lexState = 'string'; return; } throw invalidChar(read()); }, identifierNameStartEscape() { if (c$2 !== 'u') { throw invalidChar(read()); } read(); var u = unicodeEscape(); switch (u) { case '$': case '_': break; default: if (!util.isIdStartChar(u)) { throw invalidIdentifier(); } break; } buffer += u; lexState = 'identifierName'; }, identifierName() { switch (c$2) { case '$': case '_': case '\u200C': case '\u200D': buffer += read(); return; case '\\': read(); lexState = 'identifierNameEscape'; return; } if (util.isIdContinueChar(c$2)) { buffer += read(); return; } return newToken('identifier', buffer); }, identifierNameEscape() { if (c$2 !== 'u') { throw invalidChar(read()); } read(); var u = unicodeEscape(); switch (u) { case '$': case '_': case '\u200C': case '\u200D': break; default: if (!util.isIdContinueChar(u)) { throw invalidIdentifier(); } break; } buffer += u; lexState = 'identifierName'; }, sign() { switch (c$2) { case '.': buffer = read(); lexState = 'decimalPointLeading'; return; case '0': buffer = read(); lexState = 'zero'; return; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': buffer = read(); lexState = 'decimalInteger'; return; case 'I': read(); literal('nfinity'); return newToken('numeric', sign$1 * Infinity); case 'N': read(); literal('aN'); return newToken('numeric', NaN); } throw invalidChar(read()); }, zero() { switch (c$2) { case '.': buffer += read(); lexState = 'decimalPoint'; return; case 'e': case 'E': buffer += read(); lexState = 'decimalExponent'; return; case 'x': case 'X': buffer += read(); lexState = 'hexadecimal'; return; } return newToken('numeric', sign$1 * 0); }, decimalInteger() { switch (c$2) { case '.': buffer += read(); lexState = 'decimalPoint'; return; case 'e': case 'E': buffer += read(); lexState = 'decimalExponent'; return; } if (util.isDigit(c$2)) { buffer += read(); return; } return newToken('numeric', sign$1 * Number(buffer)); }, decimalPointLeading() { if (util.isDigit(c$2)) { buffer += read(); lexState = 'decimalFraction'; return; } throw invalidChar(read()); }, decimalPoint() { switch (c$2) { case 'e': case 'E': buffer += read(); lexState = 'decimalExponent'; return; } if (util.isDigit(c$2)) { buffer += read(); lexState = 'decimalFraction'; return; } return newToken('numeric', sign$1 * Number(buffer)); }, decimalFraction() { switch (c$2) { case 'e': case 'E': buffer += read(); lexState = 'decimalExponent'; return; } if (util.isDigit(c$2)) { buffer += read(); return; } return newToken('numeric', sign$1 * Number(buffer)); }, decimalExponent() { switch (c$2) { case '+': case '-': buffer += read(); lexState = 'decimalExponentSign'; return; } if (util.isDigit(c$2)) { buffer += read(); lexState = 'decimalExponentInteger'; return; } throw invalidChar(read()); }, decimalExponentSign() { if (util.isDigit(c$2)) { buffer += read(); lexState = 'decimalExponentInteger'; return; } throw invalidChar(read()); }, decimalExponentInteger() { if (util.isDigit(c$2)) { buffer += read(); return; } return newToken('numeric', sign$1 * Number(buffer)); }, hexadecimal() { if (util.isHexDigit(c$2)) { buffer += read(); lexState = 'hexadecimalInteger'; return; } throw invalidChar(read()); }, hexadecimalInteger() { if (util.isHexDigit(c$2)) { buffer += read(); return; } return newToken('numeric', sign$1 * Number(buffer)); }, string() { switch (c$2) { case '\\': read(); buffer += escape$1(); return; case '"': if (doubleQuote) { read(); return newToken('string', buffer); } buffer += read(); return; case "'": if (!doubleQuote) { read(); return newToken('string', buffer); } buffer += read(); return; case '\n': case '\r': throw invalidChar(read()); case '\u2028': case '\u2029': separatorChar(c$2); break; case undefined: throw invalidChar(read()); } buffer += read(); }, start() { switch (c$2) { case '{': case '[': return newToken('punctuator', read()); // This code is unreachable since the default lexState handles eof. // case undefined: // return newToken('eof') } lexState = 'value'; }, beforePropertyName() { switch (c$2) { case '$': case '_': buffer = read(); lexState = 'identifierName'; return; case '\\': read(); lexState = 'identifierNameStartEscape'; return; case '}': return newToken('punctuator', read()); case '"': case "'": doubleQuote = read() === '"'; lexState = 'string'; return; } if (util.isIdStartChar(c$2)) { buffer += read(); lexState = 'identifierName'; return; } throw invalidChar(read()); }, afterPropertyName() { if (c$2 === ':') { return newToken('punctuator', read()); } throw invalidChar(read()); }, beforePropertyValue() { lexState = 'value'; }, afterPropertyValue() { switch (c$2) { case ',': case '}': return newToken('punctuator', read()); } throw invalidChar(read()); }, beforeArrayValue() { if (c$2 === ']') { return newToken('punctuator', read()); } lexState = 'value'; }, afterArrayValue() { switch (c$2) { case ',': case ']': return newToken('punctuator', read()); } throw invalidChar(read()); }, end() { // This code is unreachable since it's handled by the default lexState. // if (c === undefined) { // read() // return newToken('eof') // } throw invalidChar(read()); } }; function newToken(type, value) { return { type, value, line, column }; } function literal(s) { for (var _c of s) { var p = peek(); if (p !== _c) { throw invalidChar(read()); } read(); } } function escape$1() { var c = peek(); switch (c) { case 'b': read(); return '\b'; case 'f': read(); return '\f'; case 'n': read(); return '\n'; case 'r': read(); return '\r'; case 't': read(); return '\t'; case 'v': read(); return '\v'; case '0': read(); if (util.isDigit(peek())) { throw invalidChar(read()); } return '\0'; case 'x': read(); return hexEscape(); case 'u': read(); return unicodeEscape(); case '\n': case '\u2028': case '\u2029': read(); return ''; case '\r': read(); if (peek() === '\n') { read(); } return ''; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': throw invalidChar(read()); case undefined: throw invalidChar(read()); } return read(); } function hexEscape() { var buffer = ''; var c = peek(); if (!util.isHexDigit(c)) { throw invalidChar(read()); } buffer += read(); c = peek(); if (!util.isHexDigit(c)) { throw invalidChar(read()); } buffer += read(); return String.fromCodePoint(parseInt(buffer, 16)); } function unicodeEscape() { var buffer = ''; var count = 4; while (count-- > 0) { var _c2 = peek(); if (!util.isHexDigit(_c2)) { throw invalidChar(read()); } buffer += read(); } return String.fromCodePoint(parseInt(buffer, 16)); } var parseStates = { start() { if (token.type === 'eof') { throw invalidEOF(); } push(); }, beforePropertyName() { switch (token.type) { case 'identifier': case 'string': key = token.value; parseState = 'afterPropertyName'; return; case 'punctuator': // This code is unreachable since it's handled by the lexState. // if (token.value !== '}') { // throw invalidToken() // } pop(); return; case 'eof': throw invalidEOF(); } // This code is unreachable since it's handled by the lexState. // throw invalidToken() }, afterPropertyName() { // This code is unreachable since it's handled by the lexState. // if (token.type !== 'punctuator' || token.value !== ':') { // throw invalidToken() // } if (token.type === 'eof') { throw invalidEOF(); } parseState = 'beforePropertyValue'; }, beforePropertyValue() { if (token.type === 'eof') { throw invalidEOF(); } push(); }, beforeArrayValue() { if (token.type === 'eof') { throw invalidEOF(); } if (token.type === 'punctuator' && token.value === ']') { pop(); return; } push(); }, afterPropertyValue() { // This code is unreachable since it's handled by the lexState. // if (token.type !== 'punctuator') { // throw invalidToken() // } if (token.type === 'eof') { throw invalidEOF(); } switch (token.value) { case ',': parseState = 'beforePropertyName'; return; case '}': pop(); } // This code is unreachable since it's handled by the lexState. // throw invalidToken() }, afterArrayValue() { // This code is unreachable since it's handled by the lexState. // if (token.type !== 'punctuator') { // throw invalidToken() // } if (token.type === 'eof') { throw invalidEOF(); } switch (token.value) { case ',': parseState = 'beforeArrayValue'; return; case ']': pop(); } // This code is unreachable since it's handled by the lexState. // throw invalidToken() }, end() { // This code is unreachable since it's handled by the lexState. // if (token.type !== 'eof') { // throw invalidToken() // } } }; function push() { var value; switch (token.type) { case 'punctuator': switch (token.value) { case '{': value = {}; break; case '[': value = []; break; } break; case 'null': case 'boolean': case 'numeric': case 'string': value = token.value; break; // This code is unreachable. // default: // throw invalidToken() } if (root === undefined) { root = value; } else { var parent = stack$1[stack$1.length - 1]; if (Array.isArray(parent)) { parent.push(value); } else { parent[key] = value; } } if (value !== null && typeof value === 'object') { stack$1.push(value); if (Array.isArray(value)) { parseState = 'beforeArrayValue'; } else { parseState = 'beforePropertyName'; } } else { var current = stack$1[stack$1.length - 1]; if (current == null) { parseState = 'end'; } else if (Array.isArray(current)) { parseState = 'afterArrayValue'; } else { parseState = 'afterPropertyValue'; } } } function pop() { stack$1.pop(); var current = stack$1[stack$1.length - 1]; if (current == null) { parseState = 'end'; } else if (Array.isArray(current)) { parseState = 'afterArrayValue'; } else { parseState = 'afterPropertyValue'; } } // This code is unreachable. // function invalidParseState () { // return new Error(`JSON5: invalid parse state '${parseState}'`) // } // This code is unreachable. // function invalidLexState (state) { // return new Error(`JSON5: invalid lex state '${state}'`) // } function invalidChar(c) { if (c === undefined) { return syntaxError("JSON5: invalid end of input at ".concat(line, ":").concat(column)); } return syntaxError("JSON5: invalid character '".concat(formatChar(c), "' at ").concat(line, ":").concat(column)); } function invalidEOF() { return syntaxError("JSON5: invalid end of input at ".concat(line, ":").concat(column)); } // This code is unreachable. // function invalidToken () { // if (token.type === 'eof') { // return syntaxError(`JSON5: invalid end of input at ${line}:${column}`) // } // const c = String.fromCodePoint(token.value.codePointAt(0)) // return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`) // } function invalidIdentifier() { column -= 5; return syntaxError("JSON5: invalid identifier character at ".concat(line, ":").concat(column)); } function separatorChar(c) { console.warn("JSON5: '".concat(formatChar(c), "' in strings is not valid ECMAScript; consider escaping")); } function formatChar(c) { var replacements = { "'": "\\'", '"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', '\v': '\\v', '\0': '\\0', '\u2028': '\\u2028', '\u2029': '\\u2029' }; if (replacements[c]) { return replacements[c]; } if (c < ' ') { var hexString = c.charCodeAt(0).toString(16); return '\\x' + ('00' + hexString).substring(hexString.length); } return c; } function syntaxError(message) { var err = new SyntaxError(message); err.lineNumber = line; err.columnNumber = column; return err; } var stringify = function stringify(value, replacer, space) { var stack = []; var indent = ''; var propertyList; var replacerFunc; var gap = ''; var quote; if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { space = replacer.space; quote = replacer.quote; replacer = replacer.replacer; } if (typeof replacer === 'function') { replacerFunc = replacer; } else if (Array.isArray(replacer)) { propertyList = []; for (var v of replacer) { var item = void 0; if (typeof v === 'string') { item = v; } else if (typeof v === 'number' || v instanceof String || v instanceof Number) { item = String(v); } if (item !== undefined && propertyList.indexOf(item) < 0) { propertyList.push(item); } } } if (space instanceof Number) { space = Number(space); } else if (space instanceof String) { space = String(space); } if (typeof space === 'number') { if (space > 0) { space = Math.min(10, Math.floor(space)); gap = ' '.substr(0, space); } } else if (typeof space === 'string') { gap = space.substr(0, 10); } return serializeProperty('', { '': value }); function serializeProperty(key, holder) { var value = holder[key]; if (value != null) { if (typeof value.toJSON5 === 'function') { value = value.toJSON5(key); } else if (typeof value.toJSON === 'function') { value = value.toJSON(key); } } if (replacerFunc) { value = replacerFunc.call(holder, key, value); } if (value instanceof Number) { value = Number(value); } else if (value instanceof String) { value = String(value); } else if (value instanceof Boolean) { value = value.valueOf(); } switch (value) { case null: return 'null'; case true: return 'true'; case false: return 'false'; } if (typeof value === 'string') { return quoteString(value, false); } if (typeof value === 'number') { return String(value); } if (typeof value === 'object') { return Array.isArray(value) ? serializeArray(value) : serializeObject(value); } return undefined; } function quoteString(value) { var quotes = { "'": 0.1, '"': 0.2 }; var replacements = { "'": "\\'", '"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', '\v': '\\v', '\0': '\\0', '\u2028': '\\u2028', '\u2029': '\\u2029' }; var product = ''; for (var i = 0; i < value.length; i++) { var _c3 = value[i]; switch (_c3) { case "'": case '"': quotes[_c3]++; product += _c3; continue; case '\0': if (util.isDigit(value[i + 1])) { product += '\\x00'; continue; } } if (replacements[_c3]) { product += replacements[_c3]; continue; } if (_c3 < ' ') { var hexString = _c3.charCodeAt(0).toString(16); product += '\\x' + ('00' + hexString).substring(hexString.length); continue; } product += _c3; } var quoteChar = quote || Object.keys(quotes).reduce((a, b) => quotes[a] < quotes[b] ? a : b); product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]); return quoteChar + product + quoteChar; } function serializeObject(value) { if (stack.indexOf(value) >= 0) { throw TypeError('Converting circular structure to JSON5'); } stack.push(value); var stepback = indent; indent = indent + gap; var keys = propertyList || Object.keys(value); var partial = []; for (var _key2 of keys) { var propertyString = serializeProperty(_key2, value); if (propertyString !== undefined) { var member = serializeKey(_key2) + ':'; if (gap !== '') { member += ' '; } member += propertyString; partial.push(member); } } var final; if (partial.length === 0) { final = '{}'; } else { var properties; if (gap === '') { properties = partial.join(','); final = '{' + properties + '}'; } else { var separator = ',\n' + indent; properties = partial.join(separator); final = '{\n' + indent + properties + ',\n' + stepback + '}'; } } stack.pop(); indent = stepback; return final; } function serializeKey(key) { if (key.length === 0) { return quoteString(key, true); } var firstChar = String.fromCodePoint(key.codePointAt(0)); if (!util.isIdStartChar(firstChar)) { return quoteString(key, true); } for (var i = firstChar.length; i < key.length; i++) { if (!util.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) { return quoteString(key, true); } } return key; } function serializeArray(value) { if (stack.indexOf(value) >= 0) { throw TypeError('Converting circular structure to JSON5'); } stack.push(value); var stepback = indent; indent = indent + gap; var partial = []; for (var i = 0; i < value.length; i++) { var propertyString = serializeProperty(String(i), value); partial.push(propertyString !== undefined ? propertyString : 'null'); } var final; if (partial.length === 0) { final = '[]'; } else { if (gap === '') { var properties = partial.join(','); final = '[' + properties + ']'; } else { var separator = ',\n' + indent; var _properties = partial.join(separator); final = '[\n' + indent + _properties + ',\n' + stepback + ']'; } } stack.pop(); indent = stepback; return final; } }; var JSON5$1 = { parse: parse$4, stringify }; var lib = JSON5$1; class Sidebar { constructor(viewer) { this.viewer = viewer; this.measuringTool = viewer.measuringTool; this.profileTool = viewer.profileTool; this.volumeTool = viewer.volumeTool; this.dom = $("#sidebar_root"); } createToolIcon(icon, title, callback) { var element = $("\n\t\t\t\n\t\t")); element.click(callback); return element; } init() { if (Potree.settings.editType == 'merge') { this.initMergeBar(); this.initToolbar(); this.initScene(); this.initNavigation(); } else { this.initAccordion(); this.initAppearance(); this.initToolbar(); this.initScene(); this.initNavigation(); this.initFilters(); //this.initClippingTool(); //因为修改了clipping,所以这项有bug不能使用 this.initSettings(); if (Potree.settings.editType != 'pano') { this.initAlignment(); this.initClipModel(); this.initSiteModel(); this.initParitcle(); this.initClippingModel(); } else { this.initPanosEdit(); } } $('#potree_version_number').html(Potree.version.major + "." + Potree.version.minor + Potree.version.suffix); } initAlignment() { var Alignment = viewer.modules.Alignment; var pannel = $('#alignment'); var buttons = pannel.find('[name="transform"] button'); var applyToPointcloud = (fun, value) => { return function () { var selected = $('#alignment li[name="selectPointCloud"] input:checked'); Array.from(selected).forEach(e => { var pointcloud = viewer.scene.pointclouds.find(p => p.name == e.name); fun(pointcloud, value); }); }; }; //逆时针是正数 buttons.eq(0).on('click', applyToPointcloud(Alignment.rotate, 10)); //viewer.scene.pointclouds[0].rotation.z += THREE.Math.degToRad(10) buttons.eq(1).on('click', applyToPointcloud(Alignment.rotate, 1)); buttons.eq(2).on('click', applyToPointcloud(Alignment.rotate, 0.1)); buttons.eq(3).on('click', applyToPointcloud(Alignment.rotate, -10)); buttons.eq(4).on('click', applyToPointcloud(Alignment.rotate, -1)); buttons.eq(5).on('click', applyToPointcloud(Alignment.rotate, -0.1)); buttons.eq(6).on('click', applyToPointcloud(Alignment.translate, new Vector3(-1, 0, 0))); buttons.eq(7).on('click', applyToPointcloud(Alignment.translate, new Vector3(1, 0, 0))); buttons.eq(8).on('click', applyToPointcloud(Alignment.translate, new Vector3(0, -1, 0))); buttons.eq(9).on('click', applyToPointcloud(Alignment.translate, new Vector3(0, 1, 0))); buttons.eq(10).on('click', applyToPointcloud(Alignment.translate, new Vector3(0, 0, -1))); buttons.eq(11).on('click', applyToPointcloud(Alignment.translate, new Vector3(0, 0, 1))); pannel.find('#startAlignment').on('click', () => { Alignment.enter(); }); pannel.find('#exitAlignment').on('click', () => { Alignment.save(); Alignment.leave(); }); pannel.find('#rotTool').on('click', () => { Alignment.switchHandle('rotate'); }); pannel.find('#moveTool').on('click', () => { Alignment.switchHandle('translate'); }); } initMergeBar() { //多元融合模块 var pannel = $('#mergeModel'); var buttons = pannel.find('button'); var MergeEditor = viewer.modules.MergeEditor; var loading = false; pannel.find('ul[name="model"] li button').on('click', e => { if (loading) return console.log('还在加载', loading); var $elem = $(e.target); var parent = $elem.parent(); var name = parent.attr('name'); if ($elem.attr('name') == 'select') { return Potree.selectModel(name); } if ($elem.text() == '添加') { var startTime = Date.now(); Potree.addModel(name, () => { loading = false; //$elem.text('删除') var now = Date.now(); console.log('加载完毕', name, '用时', (now - startTime) / 1000, 's'); }); loading = name; } else { Potree.removeModel(name); $elem.text('添加'); } }); pannel.find('li button[name="splitScreen"]').on('click', e => { var $elem = $(e.target); if ($elem.text() == '分屏') { $elem.text('恢复'); MergeEditor.enterSplit(); } else { $elem.text('分屏'); MergeEditor.leaveSplit(); } }); var addingTag = false; pannel.find('li button[name="tag"]').on('click', e => { var $elem = $(e.target); viewer.tagTool.startInsertion(); }); } initClippingModel() { //实时裁剪 /* 总共两种box : 可见和不可见(都是并集) 当有可见box时,需要在任一可见box内才可见 当有不可见box时,不在所有不可见box内才可见 */ var clipping = viewer.modules.clipping; var pannel = $('#clipping'); var addBtn = pannel.find('[name="operation"] button[name="add"] '); var switchBtn = pannel.find('[name="operation"] button[name="switchView"] '); var enterBtn = pannel.find(' button[name="enter"] '); var exitBtn = pannel.find(' button[name="exit"] '); var list = pannel.find('[name="list"] ul '); enterBtn.on('click', () => { clipping.enter(); pannel.find('li[name=operation]').css('display', 'block'); pannel.find('li[name=list]').css('display', 'block'); }); exitBtn.on('click', () => { clipping.leave(); pannel.find('li[name=operation]').css('display', 'none'); pannel.find('li[name=list]').css('display', 'none'); }); switchBtn.on('click', () => { clipping.switchView(clipping.activeViewName == 'top' ? 'mainView' : 'top'); }); pannel.find('[name="operation"] button[name="translation"] ').on('click', () => { clipping.setTranMode('translation'); }); pannel.find('[name="operation"] button[name="rotation"] ').on('click', () => { clipping.setTranMode('rotation'); }); pannel.find('[name="operation"] button[name="scale"] ').on('click', () => { clipping.setTranMode('scale'); }); addBtn.on('click', () => { var volumeBox = this.volumeTool.startInsertion({ clip: true, clipTask: Potree.ClipTask.SHOW_OUTSIDE }); var li = $("
  • "); list.append(li); li.find('button[name=changeTask]').on('click', e => { if (e.target.innerText == '不可见') { volumeBox.clipTask = Potree.ClipTask.SHOW_INSIDE; e.target.innerText = '可见'; } else { volumeBox.clipTask = Potree.ClipTask.SHOW_OUTSIDE; e.target.innerText = '不可见'; } volumeBox.update(); }); li.find('button[name=chose]').on('click', e => { viewer.transformObject(volumeBox); //viewer.inputHandler.toggleSelection(volumeBox) }); li.find('button[name=delete]').on('click', e => { li.remove(); viewer.scene.removeVolume(volumeBox); }); }); pannel.find('button[name=save]').on('click', e => { var data = clipping.saveClipData(); }); } addAlignmentButton(pointcloud) { var pannel = $('#alignment li[name="selectPointCloud"]>div'); var option = $(" \n \n ")); pannel.append(option); /* option.find("input").on('change',function(){ }) */ } initClipModel() { var Clip = viewer.modules.Clip; var pannel = $('#clipModel'); var buttons = pannel.find('button'); buttons.eq(0).on('click', Clip.enter.bind(Clip)); buttons.eq(1).on('click', Clip.download.bind(Clip)); buttons.eq(2).on('click', Clip.leave.bind(Clip)); } initSiteModel() { var SiteModel = viewer.modules.SiteModel; var pannel = $('#siteModel'); pannel.find('button[name="start"] ').on('click', SiteModel.enter.bind(SiteModel)); pannel.find('button[name="exit"] ').on('click', SiteModel.leave.bind(SiteModel)); pannel.find('button[name="building"] ').on('click', SiteModel.startInsertion.bind(SiteModel, 'building')); pannel.find('button[name="floor"] ').on('click', () => { SiteModel.addFloor(SiteModel.buildings[0], 'top'); }); pannel.find('button[name="room"] ').on('click', () => { SiteModel.startInsertion('room', SiteModel.buildings[0].buildChildren[0]); }); pannel.find('button[name="digHole"] ').on('click', () => { SiteModel.selected && SiteModel.startInsertion('hole', SiteModel.selected); }); pannel.find('button[name="selectBuilding"] ').on('click', () => { SiteModel.selectEntity(SiteModel.buildings[0]); }); pannel.find('button[name="selectFloor"] ').on('click', () => { SiteModel.selectEntity(SiteModel.buildings[0].buildChildren[0]); }); pannel.find('button[name="selectRoom"] ').on('click', () => { SiteModel.selectEntity(SiteModel.buildings[0].buildChildren[0].buildChildren[0]); }); pannel.find('button[name="removeFirstBuilding"] ').on('click', () => { SiteModel.removeEntity(SiteModel.buildings[0]); }); pannel.find('button[name="removeFirstFloor"] ').on('click', () => { SiteModel.removeEntity(SiteModel.buildings[0].buildChildren[0]); }); pannel.find('button[name="removeFirstRoom"] ').on('click', () => { SiteModel.removeEntity(SiteModel.buildings[0].buildChildren[0].buildChildren[0]); }); pannel.find('button[name="removeFirstHole"] ').on('click', () => { SiteModel.selected.removeHole(SiteModel.selected.holes[0]); }); pannel.find('button[name="removeFirstMarker"] ').on('click', () => { //SiteModel.removeMarker(SiteModel.selected.markers[0]) SiteModel.selected.removeMarker(0); }); } initParitcle() { var ParticleEditor = viewer.modules.ParticleEditor; var pannel = $('#particle'); pannel.find('button[name="addFire"] ').on('click', () => { ParticleEditor.startInsertion('fire+smoke'); }); pannel.find('button[name="addExplode"] ').on('click', () => { ParticleEditor.startInsertion('explode'); }); } initPanosEdit() { var PanoEditor = viewer.modules.PanoEditor; var Alignment = viewer.modules.Alignment; var pannel = $('#panos'); pannel.find('button[name="save"] ').on('click', () => { console.log('saveData', PanoEditor.exportSavingData()); }); pannel.find('button[name="translate"] ').on('click', () => { Alignment.switchHandle('translate'); }); pannel.find('button[name="rotate"] ').on('click', () => { Alignment.switchHandle('rotate'); }); pannel.find('button[name="topView"] ').on('click', () => { PanoEditor.switchView('top'); }); pannel.find('button[name="sideView"] ').on('click', () => { PanoEditor.switchView('right'); }); pannel.find('button[name="3DView"] ').on('click', () => { PanoEditor.switchView('mainView'); }); pannel.find('button[name="addLink"] ').on('click', () => { PanoEditor.setLinkOperateState('addLink', true); }); pannel.find('button[name="removeLink"] ').on('click', () => { PanoEditor.setLinkOperateState('removeLink', true); }); pannel.find('button[name="getCloser"] ').on('click', () => { PanoEditor.setZoomInState(true); }); } initToolbar() { // ANGLE var elToolbar = $('#tools'); elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/angle.png', '[title]tt.angle_measurement', () => { $('#menu_measurements').next().slideDown(); var measurement = this.measuringTool.startInsertion({ showDistances: false, showAngles: true, showArea: false, closed: true, maxMarkers: 3, minMarkers: 3, measureType: 'Angle' }); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); // POINT elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/point.svg', '[title]tt.point_measurement', () => { $('#menu_measurements').next().slideDown(); var measurement = this.measuringTool.startInsertion({ showDistances: false, showAngles: false, showCoordinates: true, showEdges: false, showArea: false, closed: true, maxMarkers: 1, minMarkers: 1, measureType: 'Point' }); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); // DISTANCE elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/distance.svg', '[title]tt.distance_measurement', () => { $('#menu_measurements').next().slideDown(); var measurement = this.measuringTool.startInsertion({ showDistances: true, showArea: false, closed: false, minMarkers: 2, maxMarkers: 2, measureType: 'Distance' }); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); // DISTANCE2 elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/distance.svg', '[title]MulDistance', () => { $('#menu_measurements').next().slideDown(); var measurement = this.measuringTool.startInsertion({ showDistances: true, showArea: false, closed: false, minMarkers: 2, measureType: 'MulDistance' }); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); // DISTANCE2 elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/distance.svg', '[title]MulDistance Ring', () => { $('#menu_measurements').next().slideDown(); var measurement = this.measuringTool.startInsertion({ //showArea: false, closed: true, minMarkers: 3, measureType: 'MulDistance Ring' }); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/distance.svg', '[title]Ver MulDistance', () => { $('#menu_measurements').next().slideDown(); var measurement = this.measuringTool.startInsertion({ measureType: 'Ver MulDistance' }); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/distance.svg', '[title]Hor MulDistance', () => { $('#menu_measurements').next().slideDown(); var measurement = this.measuringTool.startInsertion({ measureType: 'Hor MulDistance' }); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); // HEIGHT elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/height.svg', '[title]tt.height_measurement', () => { $('#menu_measurements').next().slideDown(); var measurement = this.measuringTool.startInsertion({ showDistances: true, //false, showHeight: true, showArea: false, closed: false, maxMarkers: 2, minMarkers: 2, //showGuideLine: true: true measureType: 'Ver Distance' }); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); // CIRCLE elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/circle.svg', '[title]tt.circle_measurement', () => { $('#menu_measurements').next().slideDown(); var measurement = this.measuringTool.startInsertion({ showDistances: false, showHeight: false, showArea: false, showCircle: true, showEdges: false, closed: false, maxMarkers: 3, minMarkers: 3, measureType: 'Circle' }); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); // AZIMUTH elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/azimuth.svg', 'Azimuth', () => { $('#menu_measurements').next().slideDown(); var measurement = this.measuringTool.startInsertion({ showDistances: false, showHeight: false, showArea: false, showCircle: false, showEdges: false, showAzimuth: true, closed: false, maxMarkers: 2, minMarkers: 2, measureType: 'Azimuth' }); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); // AREA elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/area.svg', '[title]tt.area_measurement', () => { $('#menu_measurements').next().slideDown(); var measurement = this.measuringTool.startInsertion({ showDistances: true, showArea: true, closed: true, minMarkers: 3, //showGuideLine: true: true, measureType: 'Area' }); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); //Hor AREA elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/area.svg', '[title]Hor Area', () => { $('#menu_measurements').next().slideDown(); var measurement = this.measuringTool.startInsertion({ showDistances: true, showArea: true, closed: true, minMarkers: 3, measureType: 'Hor Area' }); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); // Ver Area elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/area.svg', '[title]Ver Area', () => { $('#menu_measurements').next().slideDown(); var measurement = this.measuringTool.startInsertion({ showDistances: true, showArea: true, closed: true, minMarkers: 3, measureType: 'Ver Area' }); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); // rect area freedom direction elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/area.svg', '[title]area_freedom_rect', () => { $('#menu_measurements').next().slideDown(); var measurement = this.measuringTool.startInsertion({ showDistances: true, showArea: true, closed: true, minMarkers: 4, maxMarkers: 4, //showGuideLine: true: true, isRect: true, measureType: 'Rect Area' }); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); // rect area horizontal elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/area.svg', '[title]area_horizontal_rect', () => { $('#menu_measurements').next().slideDown(); var measurement = this.measuringTool.startInsertion({ showDistances: true, showArea: true, closed: true, minMarkers: 4, maxMarkers: 4, //showGuideLine: true: true, isRect: true, faceDirection: "horizontal", measureType: 'Hor Rect Area' }); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); // rect area vertical elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/area.svg', '[title]area_vertical_rect', () => { $('#menu_measurements').next().slideDown(); var measurement = this.measuringTool.startInsertion({ showDistances: true, showArea: true, closed: true, minMarkers: 4, maxMarkers: 4, //showGuideLine: true: true, isRect: true, faceDirection: "vertical", measureType: 'Ver Rect Area' }); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); // AREA elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/area.svg', '[title]prism', () => { $('#menu_measurements').next().slideDown(); var measurement = this.measuringTool.startInsertion({ measureType: 'MulDistance Ring', unit: 'metric' }); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); // VOLUME elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/volume.svg', '[title]tt.volume_measurement', () => { var volume = this.volumeTool.startInsertion(); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === volume.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); // SPHERE VOLUME elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/sphere_distances.svg', '[title]tt.volume_measurement', () => { var volume = this.volumeTool.startInsertion({ type: SphereVolume$2 }); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === volume.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); // PROFILE elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/profile.svg', '[title]tt.height_profile', () => { $('#menu_measurements').next().slideDown(); ; var profile = this.profileTool.startInsertion(); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === profile.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); // ANNOTATION elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/annotation.svg', '[title]tt.annotation', () => { $('#menu_measurements').next().slideDown(); ; var annotation = this.viewer.annotationTool.startInsertion(); var annotationsRoot = $("#jstree_scene").jstree().get_json("annotations"); var jsonNode = annotationsRoot.children.find(child => child.data.uuid === annotation.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); // REMOVE ALL elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/reset_tools.svg', '[title]tt.remove_all_measurement', () => { this.viewer.scene.removeAllMeasurements(); })); { // SHOW / HIDE Measurements var elShow = $("#measurement_options_show"); elShow.selectgroup({ title: "Show/Hide labels" }); elShow.find("input").click(e => { var show = e.target.value === "SHOW"; this.measuringTool.showLabels = show; }); var currentShow = this.measuringTool.showLabels ? "SHOW" : "HIDE"; elShow.find("input[value=".concat(currentShow, "]")).trigger("click"); } } initScene() { var elScene = $("#menu_scene"); var elObjects = elScene.next().find("#scene_objects"); var elProperties = elScene.next().find("#scene_object_properties"); { var elExport = elScene.next().find("#scene_export"); var geoJSONIcon = "".concat(Potree.resourcePath, "/icons/file_geojson.svg"); var dxfIcon = "".concat(Potree.resourcePath, "/icons/file_dxf.svg"); var potreeIcon = "".concat(Potree.resourcePath, "/icons/file_potree.svg"); elExport.append("\n\t\t\t\tExport:
    \n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t")); var elDownloadJSON = elExport.find("img[name=geojson_export_button]").parent(); elDownloadJSON.click(event => { var scene = this.viewer.scene; var measurements = [...scene.measurements, ...scene.profiles, ...scene.volumes]; if (measurements.length > 0) { var geoJson = GeoJSONExporter.toString(measurements); var url = window.URL.createObjectURL(new Blob([geoJson], { type: 'data:application/octet-stream' })); elDownloadJSON.attr('href', url); } else { this.viewer.postError("nothing to export"); event.preventDefault(); } }); var elDownloadDXF = elExport.find("img[name=dxf_export_button]").parent(); elDownloadDXF.click(event => { var scene = this.viewer.scene; var measurements = [...scene.measurements, ...scene.profiles, ...scene.volumes]; if (measurements.length > 0) { var dxf = DXFExporter.toString(measurements); var url = window.URL.createObjectURL(new Blob([dxf], { type: 'data:application/octet-stream' })); elDownloadDXF.attr('href', url); } else { this.viewer.postError("no measurements to export"); event.preventDefault(); } }); var elDownloadPotree = elExport.find("img[name=potree_export_button]").parent(); elDownloadPotree.click(event => { var data = Potree.saveProject(this.viewer); var dataString = lib.stringify(data, null, "\t"); var url = window.URL.createObjectURL(new Blob([dataString], { type: 'data:application/octet-stream' })); elDownloadPotree.attr('href', url); }); } var propertiesPanel = new PropertiesPanel(elProperties, this.viewer); propertiesPanel.setScene(this.viewer.scene); localStorage.removeItem('jstree'); var tree = $("
    "); elObjects.append(tree); tree.jstree({ 'plugins': ["checkbox", "state"], 'core': { "dblclick_toggle": false, "state": { "checked": true }, 'check_callback': true, "expand_selected_onload": true }, "checkbox": { "keep_selected_style": true, "three_state": false, "whole_node": false, "tie_selection": false } }); var createNode = (parent, text, icon, object) => { var nodeID = tree.jstree('create_node', parent, { "text": text, "icon": icon, "data": object }, "last", false, false); if (object.visible) { tree.jstree('check_node', nodeID); } else { tree.jstree('uncheck_node', nodeID); } return nodeID; }; var pcID = tree.jstree('create_node', "#", { "text": "Point Clouds", "id": "pointclouds" }, "last", false, false); var measurementID = tree.jstree('create_node', "#", { "text": "Measurements", "id": "measurements" }, "last", false, false); var annotationsID = tree.jstree('create_node', "#", { "text": "Annotations", "id": "annotations" }, "last", false, false); var otherID = tree.jstree('create_node', "#", { "text": "Other", "id": "other" }, "last", false, false); var vectorsID = tree.jstree('create_node', "#", { "text": "Vectors", "id": "vectors" }, "last", false, false); var imagesID = tree.jstree('create_node', "#", { "text": " Images", "id": "images" }, "last", false, false); tree.jstree("check_node", pcID); tree.jstree("check_node", measurementID); tree.jstree("check_node", annotationsID); tree.jstree("check_node", otherID); tree.jstree("check_node", vectorsID); tree.jstree("check_node", imagesID); tree.on('create_node.jstree', (e, data) => { tree.jstree("open_all"); }); tree.on("select_node.jstree", (e, data) => { var object = data.node.data; propertiesPanel.set(object); this.viewer.inputHandler.deselectAll(); if (object instanceof Volume$1) { this.viewer.inputHandler.toggleSelection(object); } $(this.viewer.renderer.domElement).focus(); }); tree.on("deselect_node.jstree", (e, data) => { propertiesPanel.set(null); }); tree.on("delete_node.jstree", (e, data) => { propertiesPanel.set(null); }); tree.on('dblclick', '.jstree-anchor', e => { var instance = $.jstree.reference(e.target); var node = instance.get_node(e.target); var object = node.data; // ignore double click on checkbox if (e.target.classList.contains("jstree-checkbox")) { return; } if (object instanceof PointCloudTree) { var box = this.viewer.getBoundingBox([object]); var _node = new Object3D(); _node.boundingBox = box; this.viewer.zoomTo(_node, 1, 500); } else if (object instanceof Measure$1) { var points = object.points.map(p => p.position); var _box = new Box3().setFromPoints(points); if (_box.getSize(new Vector3()).length() == 0) { _box.min = _box.max.clone(); //禁止相同 _box.expandByVector(new Vector3(1, 1, 1)); } var _node2 = new Object3D(); _node2.boundingBox = _box; this.viewer.zoomTo(_node2, 2, 500); } else if (object instanceof Profile) { var _points = object.points; var _box2 = new Box3().setFromPoints(_points); if (_box2.getSize(new Vector3()).length() > 0) { var _node3 = new Object3D(); _node3.boundingBox = _box2; this.viewer.zoomTo(_node3, 1, 500); } } else if (object instanceof Volume$1) { var _box3 = object.boundingBox.clone().applyMatrix4(object.matrixWorld); if (_box3.getSize(new Vector3()).length() > 0) { var _node4 = new Object3D(); _node4.boundingBox = _box3; this.viewer.zoomTo(_node4, 1, 500); } } else if (object instanceof Annotation) { object.moveHere(this.viewer.scene.getActiveCamera()); } else if (object instanceof PolygonClipVolume) { var dir = object.camera.getWorldDirection(new Vector3()); var target; if (object.camera instanceof OrthographicCamera) { dir.multiplyScalar(object.camera.right); target = new Vector3().addVectors(object.camera.position, dir); this.viewer.setCameraMode(CameraMode.ORTHOGRAPHIC); } else if (object.camera instanceof PerspectiveCamera) { dir.multiplyScalar(this.viewer.scene.view.radius); target = new Vector3().addVectors(object.camera.position, dir); this.viewer.setCameraMode(CameraMode.PERSPECTIVE); } this.viewer.scene.view.position.copy(object.camera.position); this.viewer.scene.view.lookAt(target); } else if (object.type === "SpotLight") { var distance = object.distance > 0 ? object.distance / 4 : 5 * 1000; var position = object.position; var _target = new Vector3().addVectors(position, object.getWorldDirection(new Vector3()).multiplyScalar(distance)); this.viewer.scene.view.position.copy(object.position); this.viewer.scene.view.lookAt(_target); } else if (object instanceof Object3D) { var _box4 = new Box3().setFromObject(object); if (_box4.getSize(new Vector3()).length() > 0) { var _node5 = new Object3D(); _node5.boundingBox = _box4; this.viewer.zoomTo(_node5, 1, 500); } } else if (object instanceof OrientedImage) { // TODO zoom to images // let box = new THREE.Box3().setFromObject(object); // if(box.getSize(new THREE.Vector3()).length() > 0){ // let node = new THREE.Object3D(); // node.boundingBox = box; // this.viewer.zoomTo(node, 1, 500); // } } else if (object instanceof Images360) { // TODO } else if (object instanceof Geopackage) { // TODO } }); tree.on("uncheck_node.jstree", (e, data) => { var object = data.node.data; if (object) { object.visible = false; } }); tree.on("check_node.jstree", (e, data) => { var object = data.node.data; if (object) { object.visible = true; } }); var onPointCloudAdded = e => { var pointcloud = e.pointcloud; var cloudIcon = "".concat(Potree.resourcePath, "/icons/cloud.svg"); var node = createNode(pcID, pointcloud.name, cloudIcon, pointcloud); pointcloud.addEventListener("visibility_changed", () => { if (pointcloud.visible) { tree.jstree('check_node', node); } else { tree.jstree('uncheck_node', node); } }); }; var onMeasurementAdded = e => { var measurement = e.measurement; var icon = Utils.getMeasurementIcon(measurement); createNode(measurementID, measurement.name, icon, measurement); }; var onVolumeAdded = e => { var volume = e.volume; var icon = Utils.getMeasurementIcon(volume); var node = createNode(measurementID, volume.name, icon, volume); volume.addEventListener("visibility_changed", () => { if (volume.visible) { tree.jstree('check_node', node); } else { tree.jstree('uncheck_node', node); } }); }; var onProfileAdded = e => { var profile = e.profile; var icon = Utils.getMeasurementIcon(profile); createNode(measurementID, profile.name, icon, profile); }; var onAnnotationAdded = e => { var annotation = e.annotation; var annotationIcon = "".concat(Potree.resourcePath, "/icons/annotation.svg"); var parentID = this.annotationMapping.get(annotation.parent); var annotationID = createNode(parentID, annotation.title, annotationIcon, annotation); this.annotationMapping.set(annotation, annotationID); annotation.addEventListener("annotation_changed", e => { var annotationsRoot = $("#jstree_scene").jstree().get_json("annotations"); var jsonNode = annotationsRoot.children.find(child => child.data.uuid === annotation.uuid); $.jstree.reference(jsonNode.id).rename_node(jsonNode.id, annotation.title); }); }; var onCameraAnimationAdded = e => { var animation = e.animation; var animationIcon = "".concat(Potree.resourcePath, "/icons/camera_animation.svg"); createNode(otherID, "animation", animationIcon, animation); }; var onOrientedImagesAdded = e => { var images = e.images; var imagesIcon = "".concat(Potree.resourcePath, "/icons/picture.svg"); var node = createNode(imagesID, "images", imagesIcon, images); images.addEventListener("visibility_changed", () => { if (images.visible) { tree.jstree('check_node', node); } else { tree.jstree('uncheck_node', node); } }); }; var onImages360Added = e => { var images = e.images; var imagesIcon = "".concat(Potree.resourcePath, "/icons/picture.svg"); var node = createNode(imagesID, "360° images", imagesIcon, images); images.addEventListener("visibility_changed", () => { if (images.visible) { tree.jstree('check_node', node); } else { tree.jstree('uncheck_node', node); } }); }; var onGeopackageAdded = e => { var geopackage = e.geopackage; var geopackageIcon = "".concat(Potree.resourcePath, "/icons/triangle.svg"); var tree = $("#jstree_scene"); var parentNode = "vectors"; for (var layer of geopackage.node.children) { var name = layer.name; var shpPointsID = tree.jstree('create_node', parentNode, { "text": name, "icon": geopackageIcon, "object": layer, "data": layer }, "last", false, false); tree.jstree(layer.visible ? "check_node" : "uncheck_node", shpPointsID); } }; this.viewer.scene.addEventListener("pointcloud_added", onPointCloudAdded); this.viewer.scene.addEventListener("measurement_added", onMeasurementAdded); this.viewer.scene.addEventListener("profile_added", onProfileAdded); this.viewer.scene.addEventListener("volume_added", onVolumeAdded); this.viewer.scene.addEventListener("camera_animation_added", onCameraAnimationAdded); this.viewer.scene.addEventListener("oriented_images_added", onOrientedImagesAdded); this.viewer.scene.addEventListener("360_images_added", onImages360Added); this.viewer.scene.addEventListener("geopackage_added", onGeopackageAdded); this.viewer.scene.addEventListener("polygon_clip_volume_added", onVolumeAdded); this.viewer.scene.annotations.addEventListener("annotation_added", onAnnotationAdded); var onMeasurementRemoved = e => { var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.measurement.uuid); tree.jstree("delete_node", jsonNode.id); }; var onVolumeRemoved = e => { var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.volume.uuid); tree.jstree("delete_node", jsonNode.id); }; var onPolygonClipVolumeRemoved = e => { var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.volume.uuid); tree.jstree("delete_node", jsonNode.id); }; var onProfileRemoved = e => { var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.profile.uuid); tree.jstree("delete_node", jsonNode.id); }; this.viewer.scene.addEventListener("measurement_removed", onMeasurementRemoved); this.viewer.scene.addEventListener("volume_removed", onVolumeRemoved); this.viewer.scene.addEventListener("polygon_clip_volume_removed", onPolygonClipVolumeRemoved); this.viewer.scene.addEventListener("profile_removed", onProfileRemoved); { var annotationIcon = "".concat(Potree.resourcePath, "/icons/annotation.svg"); this.annotationMapping = new Map(); this.annotationMapping.set(this.viewer.scene.annotations, annotationsID); this.viewer.scene.annotations.traverseDescendants(annotation => { var parentID = this.annotationMapping.get(annotation.parent); var annotationID = createNode(parentID, annotation.title, annotationIcon, annotation); this.annotationMapping.set(annotation, annotationID); }); } var scene = this.viewer.scene; for (var pointcloud of scene.pointclouds) { onPointCloudAdded({ pointcloud: pointcloud }); } for (var measurement of scene.measurements) { onMeasurementAdded({ measurement: measurement }); } for (var volume of [...scene.volumes, ...scene.polygonClipVolumes]) { onVolumeAdded({ volume: volume }); } for (var animation of scene.cameraAnimations) { onCameraAnimationAdded({ animation: animation }); } for (var images of scene.orientedImages) { onOrientedImagesAdded({ images: images }); } for (var _images of scene.images360) { onImages360Added({ images: _images }); } for (var geopackage of scene.geopackages) { onGeopackageAdded({ geopackage: geopackage }); } for (var profile of scene.profiles) { onProfileAdded({ profile: profile }); } { createNode(otherID, "Camera", null, new Camera()); } this.viewer.addEventListener("scene_changed", e => { propertiesPanel.setScene(e.scene); e.oldScene.removeEventListener("pointcloud_added", onPointCloudAdded); e.oldScene.removeEventListener("measurement_added", onMeasurementAdded); e.oldScene.removeEventListener("profile_added", onProfileAdded); e.oldScene.removeEventListener("volume_added", onVolumeAdded); e.oldScene.removeEventListener("polygon_clip_volume_added", onVolumeAdded); e.oldScene.removeEventListener("measurement_removed", onMeasurementRemoved); e.scene.addEventListener("pointcloud_added", onPointCloudAdded); e.scene.addEventListener("measurement_added", onMeasurementAdded); e.scene.addEventListener("profile_added", onProfileAdded); e.scene.addEventListener("volume_added", onVolumeAdded); e.scene.addEventListener("polygon_clip_volume_added", onVolumeAdded); e.scene.addEventListener("measurement_removed", onMeasurementRemoved); }); } initClippingTool() { this.viewer.addEventListener("cliptask_changed", event => { console.log("TODO"); }); this.viewer.addEventListener("clipmethod_changed", event => { console.log("TODO"); }); { var elClipTask = $("#cliptask_options"); elClipTask.selectgroup({ title: "Clip Task" }); elClipTask.find("input").click(e => { this.viewer.setClipTask(ClipTask[e.target.value]); }); var currentClipTask = Object.keys(ClipTask).filter(key => ClipTask[key] === this.viewer.clipTask); elClipTask.find("input[value=".concat(currentClipTask, "]")).trigger("click"); } { var elClipMethod = $("#clipmethod_options"); elClipMethod.selectgroup({ title: "Clip Method" }); elClipMethod.find("input").click(e => { this.viewer.setClipMethod(ClipMethod[e.target.value]); }); var currentClipMethod = Object.keys(ClipMethod).filter(key => ClipMethod[key] === this.viewer.clipMethod); elClipMethod.find("input[value=".concat(currentClipMethod, "]")).trigger("click"); } var clippingToolBar = $("#clipping_tools"); // CLIP VOLUME clippingToolBar.append(this.createToolIcon(Potree.resourcePath + '/icons/clip_volume.svg', '[title]tt.clip_volume', () => { var item = this.volumeTool.startInsertion({ clip: true }); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === item.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); // CLIP POLYGON clippingToolBar.append(this.createToolIcon(Potree.resourcePath + "/icons/clip-polygon.svg", "[title]tt.clip_polygon", () => { var item = this.viewer.clippingTool.startInsertion({ type: "polygon" }); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === item.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); { // SCREEN BOX SELECT var boxSelectTool = new ScreenBoxSelectTool(this.viewer); clippingToolBar.append(this.createToolIcon(Potree.resourcePath + "/icons/clip-screen.svg", "[title]tt.screen_clip_box", () => { if (!(this.viewer.scene.getActiveCamera() instanceof OrthographicCamera)) { this.viewer.postMessage("Switch to Orthographic Camera Mode before using the Screen-Box-Select tool.", { duration: 2000 }); return; } var item = boxSelectTool.startInsertion(); var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements"); var jsonNode = measurementsRoot.children.find(child => child.data.uuid === item.uuid); $.jstree.reference(jsonNode.id).deselect_all(); $.jstree.reference(jsonNode.id).select_node(jsonNode.id); })); } { // REMOVE CLIPPING TOOLS clippingToolBar.append(this.createToolIcon(Potree.resourcePath + "/icons/remove.svg", "[title]tt.remove_all_clipping_volumes", () => { this.viewer.scene.removeAllClipVolumes(); })); } } initFilters() { this.initClassificationList(); this.initReturnFilters(); this.initGPSTimeFilters(); this.initPointSourceIDFilters(); } initReturnFilters() { var elReturnFilterPanel = $('#return_filter_panel'); { // RETURN NUMBER var sldReturnNumber = elReturnFilterPanel.find('#sldReturnNumber'); var lblReturnNumber = elReturnFilterPanel.find('#lblReturnNumber'); sldReturnNumber.slider({ range: true, min: 0, max: 7, step: 1, values: [0, 7], slide: (event, ui) => { this.viewer.setFilterReturnNumberRange(ui.values[0], ui.values[1]); } }); var onReturnNumberChanged = event => { var [from, to] = this.viewer.filterReturnNumberRange; lblReturnNumber[0].innerHTML = "".concat(from, " to ").concat(to); sldReturnNumber.slider({ values: [from, to] }); }; this.viewer.addEventListener('filter_return_number_range_changed', onReturnNumberChanged); onReturnNumberChanged(); } { // NUMBER OF RETURNS var sldNumberOfReturns = elReturnFilterPanel.find('#sldNumberOfReturns'); var lblNumberOfReturns = elReturnFilterPanel.find('#lblNumberOfReturns'); sldNumberOfReturns.slider({ range: true, min: 0, max: 7, step: 1, values: [0, 7], slide: (event, ui) => { this.viewer.setFilterNumberOfReturnsRange(ui.values[0], ui.values[1]); } }); var onNumberOfReturnsChanged = event => { var [from, to] = this.viewer.filterNumberOfReturnsRange; lblNumberOfReturns[0].innerHTML = "".concat(from, " to ").concat(to); sldNumberOfReturns.slider({ values: [from, to] }); }; this.viewer.addEventListener('filter_number_of_returns_range_changed', onNumberOfReturnsChanged); onNumberOfReturnsChanged(); } } initGPSTimeFilters() { var elGPSTimeFilterPanel = $('#gpstime_filter_panel'); { var slider = new HierarchicalSlider({ levels: 4, slide: event => { this.viewer.setFilterGPSTimeRange(...event.values); } }); var initialized = false; var initialize = () => { var elRangeContainer = $("#gpstime_multilevel_range_container"); elRangeContainer[0].prepend(slider.element); var extent = this.viewer.getGpsTimeExtent(); slider.setRange(extent); slider.setValues(extent); initialized = true; }; this.viewer.addEventListener("update", e => { var extent = this.viewer.getGpsTimeExtent(); var gpsTimeAvailable = extent[0] !== Infinity; if (!initialized && gpsTimeAvailable) { initialize(); } slider.setRange(extent); //高耗cpu }); } { var txtGpsTime = elGPSTimeFilterPanel.find("#txtGpsTime"); var btnFindGpsTime = elGPSTimeFilterPanel.find("#btnFindGpsTime"); var targetTime = null; txtGpsTime.on("input", e => { var str = txtGpsTime.val(); if (!isNaN(str)) { var value = parseFloat(str); targetTime = value; txtGpsTime.css("background-color", ""); } else { targetTime = null; txtGpsTime.css("background-color", "#ff9999"); } }); btnFindGpsTime.click(() => { if (targetTime !== null) { viewer.moveToGpsTimeVicinity(targetTime); } }); } } initPointSourceIDFilters() { var elPointSourceIDFilterPanel = $('#pointsourceid_filter_panel'); { var slider = new HierarchicalSlider({ levels: 4, range: [0, 65535], precision: 1, slide: event => { var values = event.values; this.viewer.setFilterPointSourceIDRange(values[0], values[1]); } }); var initialized = false; var initialize = () => { elPointSourceIDFilterPanel[0].prepend(slider.element); initialized = true; }; this.viewer.addEventListener("update", e => { var extent = this.viewer.filterPointSourceIDRange; if (!initialized) { initialize(); slider.setValues(extent); } }); } // let lblPointSourceID = elPointSourceIDFilterPanel.find("#lblPointSourceID"); // let elPointSourceID = elPointSourceIDFilterPanel.find("#spnPointSourceID"); // let slider = new ZoomableSlider(); // elPointSourceID[0].appendChild(slider.element); // slider.update(); // slider.change( () => { // let range = slider.chosenRange; // this.viewer.setFilterPointSourceIDRange(range[0], range[1]); // }); // let onPointSourceIDExtentChanged = (event) => { // let range = this.viewer.filterPointSourceIDExtent; // slider.setVisibleRange(range); // }; // let onPointSourceIDChanged = (event) => { // let range = this.viewer.filterPointSourceIDRange; // let precision = 1; // let from = `${Utils.addCommas(range[0].toFixed(precision))}`; // let to = `${Utils.addCommas(range[1].toFixed(precision))}`; // lblPointSourceID[0].innerHTML = `${from} to ${to}`; // slider.setRange(range); // }; // this.viewer.addEventListener('filter_point_source_id_range_changed', onPointSourceIDChanged); // this.viewer.addEventListener('filter_point_source_id_extent_changed', onPointSourceIDExtentChanged); } initClassificationList() { var elClassificationList = $('#classificationList'); var addClassificationItem = (code, name) => { var classification = this.viewer.classifications[code]; var inputID = 'chkClassification_' + code; var colorPickerID = 'colorPickerClassification_' + code; var checked = classification.visible ? "checked" : ""; var element = $("\n\t\t\t\t
  • \n\t\t\t\t\t\n\t\t\t\t
  • \n\t\t\t")); var elInput = element.find('input'); var elColorPicker = element.find("#".concat(colorPickerID)); elInput.click(event => { this.viewer.setClassificationVisibility(code, event.target.checked); }); var defaultColor = classification.color.map(c => c * 255).join(", "); defaultColor = "rgb(".concat(defaultColor, ")"); elColorPicker.spectrum({ // flat: true, color: defaultColor, showInput: true, preferredFormat: 'rgb', cancelText: '', chooseText: 'Apply', move: color => { var rgb = color.toRgb(); var c = [rgb.r / 255, rgb.g / 255, rgb.b / 255, 1]; classification.color = c; }, change: color => { var rgb = color.toRgb(); var c = [rgb.r / 255, rgb.g / 255, rgb.b / 255, 1]; classification.color = c; } }); elClassificationList.append(element); }; var addToggleAllButton = () => { // toggle all button var element = $("\n\t\t\t\t
  • \n\t\t\t\t\t\n\t\t\t\t
  • \n\t\t\t"); var elInput = element.find('input'); elInput.click(event => { this.viewer.toggleAllClassificationsVisibility(); }); elClassificationList.append(element); }; var addInvertButton = () => { var element = $("\n\t\t\t\t
  • \n\t\t\t\t\t\n\t\t\t\t
  • \n\t\t\t"); var elInput = element.find('input'); elInput.click(() => { var classifications = this.viewer.classifications; for (var key of Object.keys(classifications)) { var value = classifications[key]; this.viewer.setClassificationVisibility(key, !value.visible); } }); elClassificationList.append(element); }; var populate = () => { addToggleAllButton(); for (var classID in this.viewer.classifications) { addClassificationItem(classID, this.viewer.classifications[classID].name); } addInvertButton(); }; populate(); this.viewer.addEventListener("classifications_changed", () => { elClassificationList.empty(); populate(); }); this.viewer.addEventListener("classification_visibility_changed", () => { { // set checked state of classification buttons for (var classID of Object.keys(this.viewer.classifications)) { var classValue = this.viewer.classifications[classID]; var elItem = elClassificationList.find("#chkClassification_".concat(classID)); elItem.prop("checked", classValue.visible); } } { // set checked state of toggle button based on state of all other buttons var numVisible = 0; var numItems = 0; for (var key of Object.keys(this.viewer.classifications)) { if (this.viewer.classifications[key].visible) { numVisible++; } numItems++; } var allVisible = numVisible === numItems; var elToggle = elClassificationList.find("#toggleClassificationFilters"); elToggle.prop("checked", allVisible); } }); } initAccordion() { var _this = this; $('.accordion > h3').each(function () { var header = $(this); var content = $(this).next(); //header.addClass('accordion-header ui-widget'); //content.addClass('accordion-content ui-widget'); content.hide(); header.click(() => { content.slideToggle(); }); }); var languages = [["EN", "en"], ["FR", "fr"], ["DE", "de"], ["JP", "jp"], ["ES", "es"], ["SE", "se"], ["ZH", "zh"]]; var elLanguages = $('#potree_languages'); var _loop = function _loop() { var [key, value] = languages[i]; var element = $("".concat(key, "")); element.click(() => _this.viewer.setLanguage(value)); if (i === 0) { element.css("margin-left", "30px"); } elLanguages.append(element); if (i < languages.length - 1) { elLanguages.append($(document.createTextNode(' - '))); } }; for (var i = 0; i < languages.length; i++) { _loop(); } // to close all, call // $(".accordion > div").hide() // to open the, for example, tool menu, call: // $("#menu_tools").next().show() } initAppearance() { var sldPointBudget = this.dom.find('#sldPointBudget'); sldPointBudget.slider({ value: this.viewer.getPointBudget(), min: 100 * 1000, max: 10 * 1000 * 1000, step: 1000, slide: (event, ui) => { this.viewer.setPointBudget(ui.value); } }); this.dom.find('#sldFOV').slider({ value: this.viewer.getFOV(), min: 20, max: 100, step: 1, slide: (event, ui) => { this.viewer.setFOV(ui.value); } }); $('#sldEDLRadius').slider({ value: this.viewer.getEDLRadius(), min: 1, max: 4, step: 0.01, slide: (event, ui) => { this.viewer.setEDLRadius(ui.value); } }); $('#sldEDLStrength').slider({ value: this.viewer.getEDLStrength(), min: 0, max: 5, step: 0.01, slide: (event, ui) => { this.viewer.setEDLStrength(ui.value); } }); $('#sldEDLOpacity').slider({ value: this.viewer.getEDLOpacity(), min: 0, max: 1, step: 0.01, slide: (event, ui) => { this.viewer.setEDLOpacity(ui.value); } }); this.viewer.addEventListener('point_budget_changed', event => { $('#lblPointBudget')[0].innerHTML = Utils.addCommas(this.viewer.getPointBudget()); sldPointBudget.slider({ value: this.viewer.getPointBudget() }); }); this.viewer.addEventListener('fov_changed', event => { $('#lblFOV')[0].innerHTML = parseInt(this.viewer.getFOV()); $('#sldFOV').slider({ value: this.viewer.getFOV() }); }); this.viewer.addEventListener('use_edl_changed', event => { $('#chkEDLEnabled')[0].checked = this.viewer.getEDLEnabled(); }); this.viewer.addEventListener('edl_radius_changed', event => { $('#lblEDLRadius')[0].innerHTML = this.viewer.getEDLRadius().toFixed(1); $('#sldEDLRadius').slider({ value: this.viewer.getEDLRadius() }); }); this.viewer.addEventListener('edl_strength_changed', event => { $('#lblEDLStrength')[0].innerHTML = this.viewer.getEDLStrength().toFixed(1); $('#sldEDLStrength').slider({ value: this.viewer.getEDLStrength() }); }); this.viewer.addEventListener('background_changed', event => { $("input[name=background][value='" + this.viewer.getBackground() + "']").prop('checked', true); }); $('#lblPointBudget')[0].innerHTML = Utils.addCommas(this.viewer.getPointBudget()); $('#lblFOV')[0].innerHTML = parseInt(this.viewer.getFOV()); $('#lblEDLRadius')[0].innerHTML = this.viewer.getEDLRadius().toFixed(1); $('#lblEDLStrength')[0].innerHTML = this.viewer.getEDLStrength().toFixed(1); $('#chkEDLEnabled')[0].checked = this.viewer.getEDLEnabled(); { var elBackground = $("#background_options"); elBackground.selectgroup(); elBackground.find("input").click(e => { this.viewer.setBackground(e.target.value); }); var currentBackground = this.viewer.getBackground(); try { $("input[name=background_options][value=".concat(currentBackground, "]")).trigger("click"); } catch (e) {} } $('#chkEDLEnabled').click(() => { this.viewer.setEDLEnabled($('#chkEDLEnabled').prop("checked")); }); } initNavigation() { var elNavigation = $('#navigation'); var sldMoveSpeed = $('#sldMoveSpeed'); var lblMoveSpeed = $('#lblMoveSpeed'); elNavigation.append(this.createToolIcon(Potree.resourcePath + '/icons/earth_controls_1.png', '[title]tt.earth_control', () => { this.viewer.setControls(this.viewer.earthControls); })); elNavigation.append(this.createToolIcon(Potree.resourcePath + '/icons/fps_controls.svg', '[title]tt.flight_control', () => { this.viewer.setControls(this.viewer.fpControls); this.viewer.fpControls.lockElevation = false; })); elNavigation.append(this.createToolIcon(Potree.resourcePath + '/icons/helicopter_controls.svg', '[title]tt.heli_control', () => { this.viewer.setControls(this.viewer.fpControls); this.viewer.fpControls.lockElevation = true; })); elNavigation.append(this.createToolIcon(Potree.resourcePath + '/icons/orbit_controls.svg', '[title]tt.orbit_control', () => { this.viewer.setControls(this.viewer.orbitControls); })); elNavigation.append(this.createToolIcon(Potree.resourcePath + '/icons/focus.svg', '[title]tt.focus_control', () => { this.viewer.fitToScreen(); })); elNavigation.append(this.createToolIcon(Potree.resourcePath + "/icons/navigation_cube.svg", "[title]tt.navigation_cube_control", () => { this.viewer.toggleNavigationCube(); })); elNavigation.append(this.createToolIcon(Potree.resourcePath + "/images/compas.svg", "[title]tt.compass", () => { var visible = !this.viewer.compass.isVisible(); this.viewer.compass.setVisible(visible); })); elNavigation.append(this.createToolIcon(Potree.resourcePath + "/icons/camera_animation.svg", "[title]tt.camera_animation", () => { var animation = CameraAnimation$1.defaultFromView(this.viewer); viewer.scene.addCameraAnimation(animation); })); elNavigation.append("
    "); elNavigation.append(this.createToolIcon(Potree.resourcePath + "/icons/left.svg", "[title]tt.left_view_control", () => { this.viewer.setLeftView(); })); elNavigation.append(this.createToolIcon(Potree.resourcePath + "/icons/right.svg", "[title]tt.right_view_control", () => { this.viewer.setRightView(); })); elNavigation.append(this.createToolIcon(Potree.resourcePath + "/icons/front.svg", "[title]tt.front_view_control", () => { this.viewer.setFrontView(); })); elNavigation.append(this.createToolIcon(Potree.resourcePath + "/icons/back.svg", "[title]tt.back_view_control", () => { this.viewer.setBackView(); })); elNavigation.append(this.createToolIcon(Potree.resourcePath + "/icons/top.svg", "[title]tt.top_view_control", () => { this.viewer.setTopView(); })); elNavigation.append(this.createToolIcon(Potree.resourcePath + "/icons/bottom.svg", "[title]tt.bottom_view_control", () => { this.viewer.setBottomView(); })); var elCameraProjection = $("\n\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t"); elNavigation.append(elCameraProjection); elCameraProjection.selectgroup({ title: "Camera Projection" }); elCameraProjection.find("input").click(e => { this.viewer.setCameraMode(CameraMode[e.target.value]); }); var cameraMode = Object.keys(CameraMode).filter(key => CameraMode[key] === this.viewer.scene.cameraMode); elCameraProjection.find("input[value=".concat(cameraMode, "]")).trigger("click"); var speedRange = new Vector2(1, 10 * 1000); var toLinearSpeed = value => { return Math.pow(value, 4) * speedRange.y + speedRange.x; }; var toExpSpeed = value => { return Math.pow((value - speedRange.x) / speedRange.y, 1 / 4); }; sldMoveSpeed.slider({ value: toExpSpeed(this.viewer.getMoveSpeed()), min: 0, max: 1, step: 0.01, slide: (event, ui) => { this.viewer.setMoveSpeed(toLinearSpeed(ui.value)); } }); this.viewer.addEventListener('move_speed_changed', event => { lblMoveSpeed.html(this.viewer.getMoveSpeed().toFixed(1)); sldMoveSpeed.slider({ value: toExpSpeed(this.viewer.getMoveSpeed()) }); }); lblMoveSpeed.html(this.viewer.getMoveSpeed().toFixed(1)); } initSettings() { { $('#sldMinNodeSize').slider({ value: this.viewer.getMinNodeSize(), min: 0, max: 1000, step: 0.01, slide: (event, ui) => { this.viewer.setMinNodeSize(ui.value); } }); this.viewer.addEventListener('minnodesize_changed', event => { $('#lblMinNodeSize').html(parseInt(this.viewer.getMinNodeSize())); $('#sldMinNodeSize').slider({ value: this.viewer.getMinNodeSize() }); }); $('#lblMinNodeSize').html(parseInt(this.viewer.getMinNodeSize())); } { var elSplatQuality = $("#splat_quality_options"); elSplatQuality.selectgroup({ title: "Splat Quality" }); elSplatQuality.find("input").click(e => { if (e.target.value === "standard") { this.viewer.useHQ = false; } else if (e.target.value === "hq") { this.viewer.useHQ = true; } }); var currentQuality = this.viewer.useHQ ? "hq" : "standard"; elSplatQuality.find("input[value=".concat(currentQuality, "]")).trigger("click"); } $('#show_bounding_box').click(() => { this.viewer.setShowBoundingBox($('#show_bounding_box').prop("checked")); }); $('#set_freeze').click(() => { this.viewer.setFreeze($('#set_freeze').prop("checked")); }); } } class AnnotationTool extends EventDispatcher$1 { constructor(viewer) { super(); this.viewer = viewer; this.renderer = viewer.renderer; this.sg = new SphereGeometry(0.1); this.sm = new MeshNormalMaterial(); this.s = new Mesh(this.sg, this.sm); } startInsertion() { var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var domElement = this.viewer.renderer.domElement; var annotation = new Annotation({ position: [589748.270, 231444.540, 753.675], title: "Annotation Title", description: "Annotation Description" }); this.dispatchEvent({ type: 'start_inserting_annotation', annotation: annotation }); var annotations = this.viewer.scene.annotations; annotations.add(annotation); var callbacks = { cancel: null, finish: null }; var insertionCallback = e => { if (e.button === MOUSE.LEFT) { callbacks.finish(); } else if (e.button === MOUSE.RIGHT) { callbacks.cancel(); } }; callbacks.cancel = e => { annotations.remove(annotation); domElement.removeEventListener('mouseup', insertionCallback, true); }; callbacks.finish = e => { domElement.removeEventListener('mouseup', insertionCallback, true); }; domElement.addEventListener('mouseup', insertionCallback, true); var drag = e => { var I = Utils.getMousePointCloudIntersection(e.drag.end, e.viewer.scene.getActiveCamera(), e.viewer, e.viewer.scene.pointclouds, { pickClipped: true }); if (I) { this.s.position.copy(I.location); annotation.position.copy(I.location); } }; var drop = e => { viewer.scene.scene.remove(this.s); this.s.removeEventListener("drag", drag); this.s.removeEventListener("drop", drop); }; this.s.addEventListener('drag', drag); this.s.addEventListener('drop', drop); this.viewer.scene.scene.add(this.s); this.viewer.inputHandler.startDragging(this.s); return annotation; } update() { // let camera = this.viewer.scene.getActiveCamera(); // let domElement = this.renderer.domElement; // let measurements = this.viewer.scene.measurements; // const renderAreaSize = this.renderer.getSize(new THREE.Vector2()); // let clientWidth = renderAreaSize.width; // let clientHeight = renderAreaSize.height; } render() { //this.viewer.renderer.render(this.scene, this.viewer.scene.getActiveCamera()); } } ; //处理cursor优先级 var CursorDeal = { priorityEvent: [ //在前面的优先级高 { 'zoomInCloud': 'zoom-in' }, { 'hoverPano': 'pointer' }, { 'connectPano': "url({Potree.resourcePath}/images/connect.png),auto" }, { 'disconnectPano': "url({Potree.resourcePath}/images/connect-dis.png),auto" }, { 'hoverLine': 'pointer' }, { 'hoverTranHandle': 'grab' }, { "movePointcloud": 'move' }, { "polygon_isIntersectSelf": 'not-allowed' }, { "polygon_AtWrongPlace": 'not-allowed' }, { 'delPoint': 'url("https://4dkk.4dage.com/v4-test/www/sdk/images/polygon_mark/pic_pen_sub.png"), auto' }, { "markerMove": 'grab' }, { 'addPoint': 'url("https://4dkk.4dage.com/v4-test/www/sdk/images/polygon_mark/pic_pen_add.png"), auto' }, { 'mapClipMove': 'move' }, { 'mapClipRotate': "url({Potree.resourcePath}/images/rotate-cursor.png),auto" }, { 'rotatePointcloud': "url({Potree.resourcePath}/images/rotate-cursor.png),auto" }, { 'siteModelFloorDrag': 'row-resize' }, { 'addSth': 'cell' } //or crosshair ], list: [], //当前存在的cursor状态 currentCursorIndex: null, init: function init(viewer, viewers) { this.priorityEvent.forEach(e => { //刚开始Potree.resourcePath没值,现在换 for (var i in e) { e[i] = Common.replaceAll(e[i], '{Potree.resourcePath}', Potree.resourcePath); } }); this.domElements = viewers.map(e => e.renderArea); viewer.addEventListener("CursorChange", e => { if (e.action == 'add') { this.add(e.name); } else { this.remove(e.name); } }); }, add: function add(name) { var priorityItem = this.priorityEvent.find(e => e[name]); if (!priorityItem) { console.error('CursorDeal 未定义优先级 name:' + name); return; } if (!this.list.includes(name)) { this.judge({ addItem: priorityItem, name }); this.list.push(name); } }, remove: function remove(name) { var index = this.list.indexOf(name); if (index > -1) { this.list.splice(index, 1); this.judge(); } }, judge: function judge() { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; //console.log(o,this.list) if (o.addItem) { var addIndex = this.priorityEvent.indexOf(o.addItem); if (addIndex < this.currentCursorIndex || this.currentCursorIndex == void 0) { this.domElements.forEach(e => e.style.cursor = o.addItem[o.name]); this.currentCursorIndex = addIndex; } } else { var levelMax = { index: Infinity, cursor: null }; this.list.forEach(name => { var priorityItem = this.priorityEvent.find(e => e[name]); var index = this.priorityEvent.indexOf(priorityItem); if (index < levelMax.index) { levelMax.index = index; levelMax.cursor = priorityItem[name]; } }); this.currentCursorIndex = levelMax.index; this.domElements.forEach(e => e.style.cursor = levelMax.cursor || ''); } } }; class SplitScreen extends EventDispatcher { constructor() { var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(); } /* viewport.targetPlane // bound中心点处的plane,方向和view一致 viewport.shiftTarget // camera的位置project在targetPlane上的位置 这两个参数的主要目的是为了getPosOutOfModel,以及rotateSideCamera时保持相对位置 */ splitStart(cameraProps) { var _this = this; this.splited = true; var viewports = []; var subViewports = [viewer.mainViewport]; if (viewer.mapViewer) { subViewports.push(viewer.mapViewer.viewports[0]); } var length = cameraProps.length; var _loop = function _loop() { var prop = cameraProps[i]; var viewport; var v = subViewports.find(e => e.name == (prop.name2 || prop.name)); if (v) { viewport = v; viewport.left = prop.left; viewport.bottom = prop.bottom; viewport.width = prop.width; viewport.height = prop.height; } if (!viewport) { var view = new ExtendView(); if (prop.limitBound) view.limitBound = prop.limitBound; prop.direction && (view.direction = prop.direction); viewport = new Viewport(view, _this.getOrthoCamera(), prop); if (prop.viewContainsPoints) viewport.viewContainsPoints = prop.viewContainsPoints; //viewport.unableDepth = true //depthBasicMaterial等在此viewport中不开启depth } if (viewport.camera.type == 'OrthographicCamera') { viewport.targetPlane = new Plane(); viewport.shiftTarget = new Vector3(); //project在targetPlane上的位置 } viewport.fitMargin = prop.margin; viewports.push(viewport); }; for (var i = 0; i < length; i++) { _loop(); } viewer.viewports = viewports; viewer.updateScreenSize({ forceUpdateSize: true }); viewports.forEach(viewport => { if (viewport.name == 'MainView') return; this.viewportFitBound(viewport, viewer.bound.boundingBox, viewer.bound.center, 0, viewport.fitMargin); }); return viewports; } unSplit() { this.splited = false; this.unfocusViewport(); viewer.inputHandler.hoverViewport = null; //清空 viewer.viewports = [viewer.mainViewport]; viewer.mainViewport.width = 1; viewer.mainViewport.height = 1; viewer.mainViewport.left = 0; viewer.mainViewport.bottom = 0; viewer.updateScreenSize({ forceUpdateSize: true }); } viewportFitBound(viewport, bound, center) { var duration = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; var margin = arguments.length > 4 ? arguments[4] : undefined; var view = viewport.view; var info = { bound }; var { boundSize, boundCenter } = this.getViewBound(viewport, bound); //this.setShiftTarget(viewport, boundCenter) viewport.targetPlane.setFromNormalAndCoplanarPoint(view.direction.clone(), boundCenter); viewport.targetPlane.projectPoint(center, viewport.shiftTarget); //target转换到过模型中心的平面,以保证镜头一定在模型外 this.shiftTarget是得到的 info.endPosition = this.getPosOutOfModel(viewport, boundSize); //if(viewport.name == 'mapViewport')info.endPosition.z = Math.max(Potree.config.map.cameraHeight, info.endPosition.z) info.margin = margin || { x: 30, y: 30 }; view.moveOrthoCamera(viewport, info, duration); } getViewBound(viewport, boundingBox) { if (boundingBox) { boundSize = boundingBox.getSize(new Vector3()); center = boundingBox.getCenter(new Vector3()); } else { var { boundSize, center, boundingBox } = viewer.bound; } var containsPoints = []; this.focusCenter && containsPoints.push(this.focusCenter); viewport.viewContainsPoints && containsPoints.push(...viewport.viewContainsPoints); if (containsPoints.length) { //视野范围内必须要包含的点,直接算入模型区域。这时候得到的boundCenter和模型中心不重合 boundingBox = boundingBox.clone(); containsPoints.forEach(point => { boundingBox.expandByPoint(point); }); boundSize = boundingBox.getSize(new Vector3()); center = boundingBox.getCenter(new Vector3()); } return { boundSize, boundCenter: center }; } getPosOutOfModel(viewport, boundSize) { //let {boundSize, center} = viewer.bound boundSize = boundSize || this.getViewBound(viewport).boundSize; var expand = 10; var radius = boundSize.length() * 2; var position = viewport.shiftTarget.clone().sub(viewport.view.direction.clone().multiplyScalar(radius + expand)); return position; } updateCameraOutOfModel() { //因为移动模型导致模型超出相机外,所以更新位置 viewer.viewports.forEach((viewport, i) => { if (viewport.camera.isOrthographicCamera) { //or if(viewport.targetPlane) var { boundSize, boundCenter } = this.getViewBound(viewport); /* viewport.targetPlane.setFromNormalAndCoplanarPoint( viewport.view.direction.clone(), boundCenter) viewport.targetPlane.projectPoint(viewport.view.position, viewport.shiftTarget) //target转换到过模型中心的平面,以保证镜头一定在模型外 this.shiftTarget是得到的 */ this.setShiftTarget(viewport, boundCenter); var endPosition = this.getPosOutOfModel(viewport, boundSize); //if(viewport.name == 'mapViewport')endPosition.z = Math.max(Potree.config.map.cameraHeight, endPosition.z) viewport.view.position.copy(endPosition); } }); } setShiftTarget(viewport, center) { if (!viewport.targetPlane) { viewport.targetPlane = new Plane(); viewport.shiftTarget = new Vector3(); //project在targetPlane上的位置 } viewport.targetPlane.setFromNormalAndCoplanarPoint(viewport.view.direction, center); viewport.targetPlane.projectPoint(viewport.view.position, viewport.shiftTarget); //target转换到过模型中心的平面,以保证镜头一定在模型外 } rotateSideCamera(viewport, angle) { //侧视图或俯视图绕模型中心水平旋转 //let {boundSize, center} = viewer.bound var { boundSize, boundCenter } = this.getViewBound(viewport); var center = this.focusCenter || boundCenter; //旋转中心,一般是所有模型的中心,除非想指定中心点 this.setShiftTarget(viewport, center); //找到平移向量 var vec = new Vector3().subVectors(center, viewport.shiftTarget); //相对于中心的偏移值,旋转后偏移值也旋转 //旋转 var rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0, 0, 1), angle); viewport.view.direction = viewport.view.direction.applyMatrix4(rotMatrix); vec.applyMatrix4(rotMatrix); viewport.shiftTarget.subVectors(center, vec); //新的 viewport.view.position = this.getPosOutOfModel(viewport, boundSize); } getOrthoCamera() { var camera = new OrthographicCamera(-100, 100, 100, 100, 0.01, 10000); camera.up.set(0, 0, 1); return camera; } focusOnViewport(name) { //全屏 viewer.viewports.forEach((viewport, i) => { if (viewport.name == name) { this.focusInfo = { name, left: viewport.left, bottom: viewport.bottom, height: viewport.height, width: viewport.width }; viewport.left = 0; viewport.bottom = 0; viewport.height = 1; viewport.width = 1; } else { viewport.active = false; } }); viewer.updateScreenSize({ forceUpdateSize: true }); } unfocusViewport() { if (!this.focusInfo) return; viewer.viewports.forEach((viewport, i) => { if (this.focusInfo.name == viewport.name) { //全屏的恢复 viewport.left = this.focusInfo.left; viewport.bottom = this.focusInfo.bottom; viewport.height = this.focusInfo.height; viewport.width = this.focusInfo.width; } viewport.active = true; }); viewer.updateScreenSize({ forceUpdateSize: true }); this.focusInfo = null; } } var FEET_TO_INCHES_FACTOR = 12; var EIGHTHS_SYMBOLS = ["", "⅛", "¼", "⅜", "½", "⅝", "¾", "⅞"]; //eighths 八分之…… class UnitOfMeasurement { //转化单位工具 constructor(t, e, n, i) { this.name = t, this.symbol = e, this.base = n, this.factor = i; } toBase(t) { //换算到base return t * this.factor; } fromBase(t) { //换算到当前 return t / this.factor; } } /* var o = function t(e) { this.gettext = e, t.METRIC = this.gettext("metric", void 0, "measurement system"), t.IMPERIAL = this.gettext("imperial", void 0, "measurement system") }; e.UoMSystem = o; let UoMSystem = { } */ /* var MeasurementDomain = { DISTANCE : "DISTANCE", t.AREA = "AREA", t.VOLUME = "VOLUME", t.DATA = "DATA", t } */ var UnitsOfMeasurement = { MILLIMETER: ["Millimeter", "mm"], CENTIMETER: ["Centimeter", "cm"], METER: ["Meter", "m"], KILOMETER: ["Kilometer", "km"], INCH: ["Inch", "in"], FOOT: ["Foot", "ft"], MILE: ["Mile", "mi"], SQUAREMETER: ["SquareMeter", "m²"], SQUAREFOOT: ["SquareFoot", "ft²"], CUBICMETER: ["CubicMeter", "m³"], CUBICFOOT: ["CubicFoot", "ft³"], BYTE: ["Byte", "B"], KILOBYTE: ["Kilobyte", "kB"], MEGABYTE: ["Megabyte", "MB"], GIGABYTE: ["Gigabyte", "GB"], TERABYTE: ["Terabyte", "TB"], PETABYTE: ["Petabyte", "PB"], init: function init() { var e, n, i, a, s, c, l, u, d, p, h, f = new UnitOfMeasurement(UnitsOfMeasurement.METER[0], UnitsOfMeasurement.METER[1], void 0, 1), g = new UnitOfMeasurement(UnitsOfMeasurement.SQUAREMETER[0], UnitsOfMeasurement.SQUAREMETER[1], void 0, 1), m = new UnitOfMeasurement(UnitsOfMeasurement.CUBICMETER[0], UnitsOfMeasurement.CUBICMETER[1], void 0, 1), v = new UnitOfMeasurement(UnitsOfMeasurement.BYTE[0], UnitsOfMeasurement.BYTE[1], void 0, 1); UnitsOfMeasurement.DISTANCE = ((e = {})['metric'] = ((n = {})[UnitsOfMeasurement.MILLIMETER[0]] = new UnitOfMeasurement(UnitsOfMeasurement.MILLIMETER[0], UnitsOfMeasurement.MILLIMETER[1], f, .001), n[UnitsOfMeasurement.CENTIMETER[0]] = new UnitOfMeasurement(UnitsOfMeasurement.CENTIMETER[0], UnitsOfMeasurement.CENTIMETER[1], f, .01), n[UnitsOfMeasurement.METER[0]] = f, n[UnitsOfMeasurement.KILOMETER[0]] = new UnitOfMeasurement(UnitsOfMeasurement.KILOMETER[0], UnitsOfMeasurement.KILOMETER[1], f, 1e3), n), e['imperial'] = ((i = {})[UnitsOfMeasurement.INCH[0]] = new UnitOfMeasurement(UnitsOfMeasurement.INCH[0], UnitsOfMeasurement.INCH[1], f, .0254), i[UnitsOfMeasurement.FOOT[0]] = new UnitOfMeasurement(UnitsOfMeasurement.FOOT[0], UnitsOfMeasurement.FOOT[1], f, .3048), i[UnitsOfMeasurement.MILE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.MILE[0], UnitsOfMeasurement.MILE[1], f, 1609.344), i), e); UnitsOfMeasurement.AREA = ((a = {})['metric'] = ((s = {})[UnitsOfMeasurement.SQUAREMETER[0]] = g, s), a['imperial'] = ((c = {})[UnitsOfMeasurement.SQUAREFOOT[0]] = new UnitOfMeasurement(UnitsOfMeasurement.SQUAREFOOT[0], UnitsOfMeasurement.SQUAREFOOT[1], g, .092903), c), a); UnitsOfMeasurement.VOLUME = ((l = {})['metric'] = ((u = {})[UnitsOfMeasurement.CUBICMETER[0]] = m, u), l['imperial'] = ((d = {})[UnitsOfMeasurement.CUBICFOOT[0]] = new UnitOfMeasurement(UnitsOfMeasurement.CUBICFOOT[0], UnitsOfMeasurement.CUBICFOOT[1], m, .0283168), d), l); //数据大小 var y = ((p = {})[UnitsOfMeasurement.BYTE[0]] = v, p[UnitsOfMeasurement.KILOBYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.KILOBYTE[0], UnitsOfMeasurement.KILOBYTE[1], v, 1e3), p[UnitsOfMeasurement.MEGABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.MEGABYTE[0], UnitsOfMeasurement.MEGABYTE[1], v, 1e6), p[UnitsOfMeasurement.GIGABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.GIGABYTE[0], UnitsOfMeasurement.GIGABYTE[1], v, 1e9), p[UnitsOfMeasurement.TERABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.TERABYTE[0], UnitsOfMeasurement.TERABYTE[1], v, 1e12), p[UnitsOfMeasurement.PETABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.PETABYTE[0], UnitsOfMeasurement.PETABYTE[1], v, 1e15), p); UnitsOfMeasurement.DATA = ((h = {})['metric'] = y, h['imperial'] = y, h); }, getUnitsOfMeasurementByDomain: function getUnitsOfMeasurementByDomain(e) { return this[e.toUpperCase()]; /* switch (e.toUpperCase()) { case a.DISTANCE: return t.DISTANCE; case a.AREA: return t.AREA; case a.VOLUME: return t.VOLUME; case a.DATA: return t.DATA; default: console.error(e + " measurement domain is not supported.") } */ }, getUnitsOfMeasurementByDomainAndSystem: function getUnitsOfMeasurementByDomainAndSystem(domain, system) { var r = this.getUnitsOfMeasurementByDomain(domain); if (r.hasOwnProperty(system.toLowerCase())) return r[system.toLowerCase()]; console.error(n + " measurement system is not supported."); }, getDefaultUnitByDomainAndSystem: function getDefaultUnitByDomainAndSystem(e, n) { switch (e.toUpperCase()) { case 'DISTANCE': switch (n.toLowerCase()) { case 'metric': return this.DISTANCE['metric'][this.METER[0]]; case 'imperial': return this.DISTANCE['imperial'][this.FOOT[0]]; default: console.error(n + " measurement system is not supported."); } case 'AREA': switch (n.toLowerCase()) { case 'metric': return this.AREA['metric'][this.SQUAREMETER[0]]; case 'imperial': return this.AREA['imperial'][this.SQUAREFOOT[0]]; default: console.error(n + " measurement system is not supported."); } case 'VOLUME': switch (n.toLowerCase()) { case 'metric': return this.VOLUME['metric'][this.CUBICMETER[0]]; case 'imperial': return this.VOLUME['imperial'][this.CUBICFOOT[0]]; default: console.error(n + " measurement system is not supported."); } case 'DATA': switch (n.toLowerCase()) { case 'metric': return this.DATA['metric'][this.BYTE[0]]; case 'imperial': return this.DATA['imperial'][this.BYTE[0]]; default: console.error(n + " measurement system is not supported."); } default: console.error(e + " measurement domain is not supported."); } } }; class UnitService { constructor( /* e, n, i */ ) { //this.LanguageService = e, //this.localStorageService = n, //this.gettext = i, //this.unitChanged = new r.Signal, this.LOCAL_STORAGE_KEY = "iv_unit_key"; //? UnitsOfMeasurement.init(); this.unitSystems = ['metric', 'imperial']; //[o.UoMSystem.METRIC, o.UoMSystem.IMPERIAL], this.defaultSystem = 'metric'; //'imperial' //var a = this.LanguageService.getBrowserLocaleString().toLowerCase(); //this.defaultSystem = t.isLocaleImperial(a) ? o.UoMSystem.IMPERIAL : o.UoMSystem.METRIC, //this.initUnit() } /* initUnit() { var t = this.localStorageService.get(this.LOCAL_STORAGE_KEY); if (t) for (var e = 0, n = this.unitSystems; e < n.length; e++) { var i = n[e]; if (i === t) return void this.setUnit(i, !0) } this.setUnit(this.defaultSystem, !1) } setUnit(t, e) { this.currentSystem !== t && (this.currentSystem = t, this.unitChanged.emit()), e && this.localStorageService.set(this.LOCAL_STORAGE_KEY, t) } */ /*isLocaleImperial(e) { return t.IMPERIAL_LOCALES.indexOf(e.toLowerCase()) >= 0 } , t.IMPERIAL_LOCALES = ["en_us"], t.ɵfac(e) { return new (e || t)(c.ɵɵinject(l.LanguageService), c.ɵɵinject("localStorageService"),c.ɵɵinject("gettext")) } , t.ɵprov = c.ɵɵdefineInjectable({ token: t, factory: t.ɵfac, providedIn: "root" }), */ } class UoMService { constructor( /* UnitService */ ) { this.UnitService = new UnitService(); /* UnitService */ } scopedConvert(t, n) { var precision = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2; var r = arguments.length > 3 ? arguments[3] : undefined; var minFactor = arguments.length > 4 ? arguments[4] : undefined; return this.convert(t, n, precision, r, minFactor); } convert(number, domain) { var precision = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2; var system = arguments.length > 3 ? arguments[3] : undefined; var ifEighths = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : !1; var o /* minFactor, ifRestrict */ = arguments.length > 5 ? arguments[5] : undefined; var { minFactor, restrictUnit } = o[system]; //if (!number) return ""; var s = this.getMostRelevantMeasurement(domain, system || this.UnitService.currentSystem, number, minFactor, restrictUnit); return this.getFormattedMeasurementString(s[0], s[1], precision, ifEighths); } convertBack(number, domain) { var precision = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2; var fromSystem = arguments.length > 3 ? arguments[3] : undefined; var minFactor = arguments.length > 4 ? arguments[4] : undefined; //从英制转到'metric' if (!number) return ""; var d = UnitsOfMeasurement.getDefaultUnitByDomainAndSystem(domain, 'metric'); var s = this.getMostRelevantMeasurement2(domain, fromSystem, number, minFactor); return this.getFormattedMeasurementString(s[0], d, precision); /* 栗子: viewer.unitConvert.convertBack(1, 'area', 5, 'imperial') '0.09290 m²' viewer.unitConvert.convertBack(1, 'Distance', 2, 'imperial') '0.03 m' */ } getFormattedMeasurementString(number, unit, precision, ifEighths) { var result; if (ifEighths && unit.name === UnitsOfMeasurement.FOOT[0]) { result = this.formatImperialDistance(number * FEET_TO_INCHES_FACTOR); } else if (ifEighths && unit.name === UnitsOfMeasurement.INCH[0]) { result = this.formatImperialDistance(number); } else { result = number.toLocaleString(void 0, { minimumFractionDigits: precision, maximumFractionDigits: precision }) + " " + unit.symbol; } return result; } formatImperialDistance(e) { var n = Math.round(8 * e), i = Math.floor(n / 8), r = Math.floor(i / FEET_TO_INCHES_FACTOR), o = i - r * FEET_TO_INCHES_FACTOR, a = EIGHTHS_SYMBOLS[Math.abs(n % 8)], s = 0 === o && "" !== a ? "" : o; "" !== s && "" !== a && (a = " " + a); return 0 !== r ? r + "' " + s + a + '"' : "" + s + a + '"'; } getMostRelevantMeasurement(domain, system, number) { var minFactor = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; var restrictUnit = arguments.length > 4 ? arguments[4] : undefined; /* var a = r.values(UnitsOfMeasurement.getUnitsOfMeasurementByDomainAndSystem(domain, system)) , s = r.filter(a, function(t) { return t.factor >= i }) , c = r.reduce(s, function(t, e) { return e.fromBase(number) < t.fromBase(number) && e.fromBase(number) >= 1 ? e : t }); */ var a = []; var u = UnitsOfMeasurement.getUnitsOfMeasurementByDomainAndSystem(domain, system); for (var i in u) { a.push(u[i]); } var s = a; if (s.length > 1) { if (restrictUnit) { //是否只用这一单位,如只用mm。如果不是,就会寻找最大的接近的单位,如设置最小为mmminFactor=0.001),则1.2米时是'1.2m'、0.2米时是'20cm'、0.002米时是'2mm' s = a.filter(m => m.name == restrictUnit); } else { s = a.filter(m => m.factor >= minFactor); } } var c = s.reduce(function (prev, currentValue) { //reduce最终值是最后一次return的值 ( 没看懂这句话作用) return currentValue.fromBase(number) < prev.fromBase(number) && currentValue.fromBase(number) >= 1 ? currentValue : prev; }); return c ? [c.fromBase(number), c] : void 0; } getMostRelevantMeasurement2(domain, system, number) { var minFactor = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; //add var a = []; var u = UnitsOfMeasurement.getUnitsOfMeasurementByDomainAndSystem(domain, system); for (var i in u) { a.push(u[i]); } var s = a.filter(m => m.factor >= minFactor); var c = s.reduce(function (prev, currentValue) { //reduce最终值是最后一次return的值 ( 没看懂这句话作用) return currentValue.toBase(number) < prev.toBase(number) && currentValue.toBase(number) >= 1 ? currentValue : prev; }); return c ? [c.toBase(number), c] : void 0; } /* ɵfac(e){ return new (e || t)(c.ɵɵinject(l.UnitService)) } ɵprov = c.ɵɵdefineInjectable({ token: t, factory: t.ɵfac, providedIn: "root" }) */ } var texLoader$8 = new TextureLoader(); var color$1 = new Color(config$1.clip.color); var markerMats$1; var markerSizeInfo$1 = { width2d: 40 }; var pickOrders = { marker: 1, area: 0 }; class mapClipBox extends ctrlPolygon { constructor(center, scale) { center = center.clone().setZ(0); //所有Z都为0 var prop = { points: getPoints(center, scale, 0), closed: true, atPlane: true, isRect: true, dimension: '2d' }; super('mapClipBox', prop); this.angle = 0; this.createRotateBar(); this.edgeMarkers = []; //addMarkers: this.initData(prop); { //areaPlane event 能拖动 this.areaPlane.addEventListener('mouseover', () => { viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "mapClipMove" }); }); this.areaPlane.addEventListener('mouseleave', () => { viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "mapClipMove" }); }); var lastPos; var drag = e => { var intersect = e.intersect.orthoIntersect; if (lastPos) { var moveVec = new Vector3().subVectors(intersect, lastPos).setZ(0); this.center.add(moveVec); this.updatePoints(); this.dispatchEvent({ type: 'repos' }); } lastPos = intersect.clone(); }; var drop = e => { lastPos = null; }; this.areaPlane.addEventListener('drag', drag); this.areaPlane.addEventListener('drop', drop); } /* this.addEventListener('dragChange',()=>{ this.updateTwoMidMarker(index+1) }) */ Potree.Utils.setObjectLayers(this, 'mapObjects'); } getScale() { return new Vector3(this.points[0].distanceTo(this.points[1]), this.points[1].distanceTo(this.points[2]), 1); } addMarker() { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var marker = new Sprite$2({ mat: this.getMarkerMaterial('default'), pickOrder: pickOrders.marker, sizeInfo: markerSizeInfo$1, dontFixOrient: true, viewports: viewer.mapViewer.viewports, name: "mapClipBox_marker" }); marker.renderOrder = 3; //marker.markerSelectStates = {} var edge = LineDraw.createLine([new Vector3(), new Vector3()], { color: color$1 }); var edgeMarker = new Sprite$2({ mat: this.getMarkerMaterial('default'), pickOrder: pickOrders.marker, sizeInfo: markerSizeInfo$1, dontFixOrient: true, viewports: viewer.mapViewer.viewports, name: "mapClipBox_edgePoint" }); var mouseover = e => { this.setMarkerSelected(e.object, true, 'single'); viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "markerMove" }); }; var mouseleave = e => { this.setMarkerSelected(e.object, false, 'single'); viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "markerMove" }); }; edgeMarker.addEventListener('mouseover', mouseover); edgeMarker.addEventListener('mouseleave', mouseleave); var dragInfo = { lastPos: null }; edgeMarker.addEventListener('drag', this.dragEdge.bind(this, dragInfo)); edgeMarker.addEventListener('drop', this.dropEdge.bind(this, dragInfo)); this.edgeMarkers.push(edgeMarker); this.add(edgeMarker); marker.dispatchEvent('addHoverEvent'); super.addMarker({ point: o.point, marker: marker, edge }); } dragEdge(dragInfo, e) { //拖拽一个边(或一个边类型的marker),带动它的两个端点。 可以转化为拖拽marker往法线方向 var I, atMap; atMap = e.dragViewport.name == 'mapViewport'; I = e.intersect.orthoIntersect; if (I && dragInfo.lastPos) { var i = this.edgeMarkers.indexOf(e.drag.object); if (i !== -1) { var lineNormal = math.getNormal2d({ p1: this.points[i], p2: this.points[(i + 1) % 4] }); var moveVec = new Vector3().subVectors(I, dragInfo.lastPos).setZ(0); //移动的向量 var dragVec = moveVec.projectOnVector(lineNormal).setZ(0); //在法线上移动的向量 var newPos = new Vector3().addVectors(this.points[i], dragVec); //marker应到的位置 this.dragChange(newPos, i, atMap); //转化为这个marker的拖拽 } } dragInfo.lastPos = I.clone(); } dropEdge(dragInfo, e) { dragInfo.lastPos = null; this.setMarkerSelected(e.drag.object, false, 'single'); //拖拽时似乎没有触发mouseout } createAreaPlane() { var planeMat = new MeshBasicMaterial({ color: color$1, //"#00eeff", side: DoubleSide, opacity: 0.3, transparent: true, depthTest: false }); return super.createAreaPlane(planeMat); } getMarkerMaterial(type) { if (!markerMats$1) { markerMats$1 = { default: new MeshBasicMaterial({ transparent: !0, color: color$1, opacity: 0.8, map: texLoader$8.load(Potree.resourcePath + '/textures/whiteCircle.png') }), select: new MeshBasicMaterial({ transparent: !0, color: color$1, opacity: 1, map: texLoader$8.load(Potree.resourcePath + '/textures/whiteCircle.png') }) }; mapClipBox.markerMats = markerMats$1; } return markerMats$1[type]; } setMarkerSelected(marker, state, hoverObject) { //console.warn(marker.id , state, hoverObject) if (state == 'hover') { marker.material = this.getMarkerMaterial('select'); } else { marker.material = this.getMarkerMaterial('default'); } /* marker.markerSelectStates[hoverObject] = state let absoluteState = false for(var i in marker.markerSelectStates){ if(marker.markerSelectStates[i]){ absoluteState = true; break; } } if(absoluteState){ marker.material = this.getMarkerMaterial('select') }else{ marker.material = this.getMarkerMaterial('default') } marker.selected = absoluteState */ viewer.mapViewer.dispatchEvent('content_changed'); } createRotateBar() { //中心点在线的一端,整体初始在box上方 var lineLen = 1.5, circleWidth = 2, barOpacity = 0.7; var object = new Object3D(); var bar = new Sprite$2({ mat: new MeshBasicMaterial({ side: DoubleSide, opacity: barOpacity, transparent: true, depthTest: false, map: texLoader$8.load(Potree.resourcePath + '/textures/rotation_circle.png') }), root: object, sizeInfo: markerSizeInfo$1, dontFixOrient: true, viewports: viewer.mapViewer.viewports, name: "mapClipRotateBar" }); bar.position.set(0, lineLen + circleWidth / 2, 0); bar.scale.set(circleWidth, circleWidth, circleWidth); bar.addEventListener('mouseover', () => { bar.material.opacity = 1; viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "mapClipRotate" }); viewer.mapViewer.dispatchEvent('content_changed'); }); var leave = () => { bar.material.opacity = barOpacity; viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "mapClipRotate" }); viewer.mapViewer.dispatchEvent('content_changed'); }; bar.addEventListener('mouseleave', leave); this.addEventListener('dispose', leave); var lastPos; bar.addEventListener('drag', e => { var intersect = e.intersect.orthoIntersect; if (lastPos) { var vec1 = new Vector3().subVectors(lastPos, this.center).setZ(0); var vec2 = new Vector3().subVectors(intersect, this.center).setZ(0); var angle = math.getAngle(vec1, vec2, 'z'); this.angle += angle; this.rotateBar.rotation.z = this.angle; this.updatePoints(); this.dispatchEvent({ type: 'rotate', angle: this.angle }); } lastPos = intersect.clone(); }); bar.addEventListener('drop', () => { lastPos = null; viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "mapClipRotate" }); }); var line = LineDraw.createLine([new Vector3(), new Vector3(0, lineLen, 0)], { color: color$1 }); object.add(bar); object.add(line); this.add(object); this.rotateBar = object; this.rotateBar.bar = bar; } updatePoints(scale) { this.points = getPoints(this.center, scale || this.getScale(), this.angle); this.getPoint2dInfo(this.points); this.update({ ifUpdateMarkers: true }); } update() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super.update(options); { //update rotateBar var center = new Vector3().addVectors(this.points[0], this.points[1]).multiplyScalar(0.5); this.rotateBar.position.copy(center); this.rotateBar.bar.waitUpdate(); //更新sprite matrix } { for (var i = 0; i < 4; i++) { var current = this.points[i]; var next = this.points[(i + 1) % 4]; var mid = new Vector3().addVectors(current, next).multiplyScalar(0.5); this.updateMarker(this.edgeMarkers[i], mid); } } } dispose() { super.dispose(); this.dispatchEvent('dispose'); this.rotateBar.bar.dispose(); } } function getPoints(center, scale) { var angle = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var points = [new Vector3(-scale.x / 2, +scale.y / 2, 0), new Vector3(+scale.x / 2, +scale.y / 2, 0), new Vector3(+scale.x / 2, -scale.y / 2, 0), new Vector3(-scale.x / 2, -scale.y / 2, 0)]; var rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0, 0, 1), angle); //再旋转 points.forEach(e => { e.applyMatrix4(rotMatrix); e.add(center); }); return points; } var defaultBoxWidth = 16; //navvis: 10 //navvis position: si {x: 0, y: 0, z: 0} var cameraProps = [{ name: 'top', axis: ["x", "y"], direction: new Vector3(0, 0, -1), //镜头朝向 openCount: 0 }, { name: 'front', axis: ["x", "z"], direction: new Vector3(0, 1, 0), openCount: 0 }, { name: 'mainView', openCount: 0 }]; var Clip = { bus: new EventDispatcher(), selectedDatasets: [], changeCallback(force) { if (this.activeViewName != 'mainView') { this.splitScreenTool.updateCameraOutOfModel(); //更新相机位置 } if (Potree.settings.isOfficial && this.showMap) { var fun = () => { var pointclouds = this.getIntersectPointcloud(); if (Common.getDifferenceSet(pointclouds, this.selectedDatasets).length) { this.selectedDatasets = pointclouds; //console.error('clipSelectedDatasets',selectedDatasets) this.bus.dispatchEvent({ type: 'updateSelectedDatasets', selectedDatasets: pointclouds.map(e => e.dataset_id) }); } }; if (force) fun();else Common.intervalTool.isWaiting('clipSelectedDatasets', fun, 300); } }, enter: function enter() { this.initViews(); this.previousView = { position: viewer.images360.position, target: viewer.scene.view.getPivot(), displayMode: Potree.settings.displayMode, //--- ifShowMarker: Potree.settings.ifShowMarker }; var pointcloud = this.getPointcloud(); var bound = pointcloud.bound; //只选取其中一个数据集的bound,而非整体,是因为担心两个数据集中间有空隙,于是刚好落在没有点云的地方。 var boundSize = bound.getSize(new Vector3()); var target = this.getTarget(bound.getCenter(new Vector3())); //navvis的位置xy是用相机位置 this.ViewService.mainView.getCamera().position 我觉得也可以用第一个漫游点的,或者最接近bound中心的漫游点 var scale = new Vector3(defaultBoxWidth, defaultBoxWidth, boundSize.z); //z和navvis一样 var eyeDir = viewer.scene.view.direction.clone().setZ(0 /* -boundSize.z/3 */).multiplyScalar(-defaultBoxWidth); //为了使所在楼层不变,不修改z //let eyeDir = scale.clone().setZ(boundSize.z/3).multiplyScalar(1.3) var position = new Vector3().addVectors(target, eyeDir); Potree.settings.displayMode = 'showPointCloud'; viewer.setView({ position, target, duration: 300, callback: function callback() {} }); //viewer.setControls(viewer.orbitControls); viewer.setLimitFar(false); //viewer.setClipState(false) //暂时关闭旧的clipping /* new AxisViewer(viewer.mainViewport, viewer.renderArea,{domStyle:{ bottom: '2px',right: '20px', width:'80px',height:'80px'} }) */ { this.box = new BoxVolume$1({ clip: true }); this.box.clipTask = ClipTask['SHOW_INSIDE_Big' /* "SHOW_INSIDE" */]; this.box.showBox = false; this.box.name = "ClipBox"; this.box.position.copy(target); this.box.scale.copy(scale); viewer.controls.setTarget(this.box.position); //绕其旋转 this.splitScreenTool.focusCenter = this.box.position; //带动mapBox this.box.addEventListener('position_changed', e => { if (this.showMap) { this.mapBox.center.setX(this.box.position.x); this.mapBox.center.setY(this.box.position.y); this.mapBox.updatePoints(); } this.changeCallback(); }); this.box.addEventListener('scale_changed', e => { if (this.showMap) { var scale = this.box.scale; this.mapBox.updatePoints(scale); } this.changeCallback(); }); this.box.addEventListener('orientation_changed', e => { if (this.showMap) { this.mapBox.angle = this.box.rotation.z; this.mapBox.rotateBar.rotation.z = this.mapBox.angle; this.mapBox.updatePoints(); } this.changeCallback(); }); viewer.scene.addVolume(this.box); } if (this.showMap) { //map var boxRotateBack = () => { //不知道是不是这么写。 因为可能z的旋转不一定都在z this.box.rotation.x = 0; this.box.rotation.y = 0; }; this.mapBox = new mapClipBox(target, scale); viewer.mapViewer.scene.add(this.mapBox); //带动box this.mapBox.addEventListener('repos', e => { this.box.position.setX(this.mapBox.center.x); this.box.position.setY(this.mapBox.center.y); boxRotateBack(); this.changeCallback(); }); this.mapBox.addEventListener('dragChange', e => { var scale = this.mapBox.getScale(); this.box.scale.setX(scale.x); this.box.scale.setY(scale.y); this.box.position.setX(this.mapBox.center.x); this.box.position.setY(this.mapBox.center.y); boxRotateBack(); this.changeCallback(); }); this.mapBox.addEventListener('rotate', e => { this.box.rotation.z = this.mapBox.angle; boxRotateBack(); this.changeCallback(); }); } this.switchView('mainView'); { //viewer.setClipTask(ClipTask["SHOW_INSIDE"]) } Potree.settings.unableNavigate = true; Potree.settings.ifShowMarker = false; Potree.Utils.updateVisible(viewer.measuringTool.scene, 'clipModel', false); //Potree.Utils.updateVisible(viewer.mapViewer.cursor, 'clipModel', false)//隐藏地图游标 viewer.inputHandler.toggleSelection(this.box); viewer.inputHandler.fixSelection = true; viewer.transformationTool.setModeEnable(['scale', 'translation', 'rotation']); viewer.transformationTool.frame.material.color.set(Potree.config.clip.color); //navvis 15899953 viewer.setPointStandardMat(true); if (this.showMap) { var mapVisi = false; this.events = { flyToPos: e => { var dis = 2; var target = e.position; target = this.box.position; position = e.position; //为了方便缩放操作,直接使用box中心作为target var duration = e.duration == void 0 ? 1000 : e.duration; viewer.scene.view.setView({ position, duration, target }); }, mapVisiChange(e) { mapVisi = e.visible; var delay = 100; //因resize了camera需要时间更新projectionMatrix setTimeout(() => { var boundingBox = Clip.box.boundingBox.clone().applyMatrix4(Clip.box.matrixWorld); if (mapVisi) { //切换地图 if (viewer.fpVisiDatasets.length == 0) { //不会显示任何一个floorplan图,就要就近移动到一个可见数据集里 var clouds = viewer.scene.pointclouds.filter(e => e.visible); if (clouds.length == 0) clouds = viewer.scene.pointclouds; var scores = clouds.map((e, i) => { return [-viewer.scene.view.position.distanceToSquared(e.bound2), i]; }); scores = scores.sort((a, b) => a[0] - b[0]); var neareast = clouds[scores[0][1]]; viewer.flyToDataset({ pointcloud: neareast, duration: 0 }); } if (Clip.switchMapCount == 0 || !Potree.Utils.getPos2d(viewer.scene.view.position, viewer.mapViewer.viewports[0], viewer.mapViewer.renderArea).inSight || !Potree.Utils.isInsideFrustum(boundingBox, viewer.mapViewer.camera)) { //要使box框和游标都在屏幕内。因为游标是3d的当前位置,很可能是准备去框住的位置 var _bound = boundingBox.clone(); _bound.expandByPoint(viewer.scene.view.position); var size = _bound.getSize(new Vector3()); var center = _bound.getCenter(new Vector3()); var margin = viewer.mainViewport.resolution.clone().multiplyScalar(0.3); viewer.mapViewer.moveTo(center, size, 100, margin); } Clip.switchMapCount++; //关于究竟是focus box还是dataset有点纠结,又或是两个的union。box和数据集可能离得很远,且无法确定当前想选择的数据集,且数据集可能无floorplan, 即使有可能也不展示…… } else { //切换3d if (!Potree.Utils.isInsideFrustum(boundingBox, viewer.scene.getActiveCamera())) { //屏幕上没有box的话 viewer.focusOnObject({ boundingBox }, 'boundingBox', 100); } } }, delay); } }; this.switchMapCount = 0; this.bus.addEventListener('flyToPos', this.events.flyToPos); viewer.mapViewer.addEventListener('forceVisible', this.events.mapVisiChange); } this.editing = true; setTimeout(() => { this.changeCallback(true); }, 1); }, leave: function leave() { viewer.inputHandler.fixSelection = false; viewer.scene.removeVolume(this.box); this.showMap && this.mapBox.dispose(); //viewer.setControls(viewer.fpControls); this.switchView('mainView'); Potree.settings.unableNavigate = false; Potree.settings.ifShowMarker = this.previousView.ifShowMarker; Potree.Utils.updateVisible(viewer.measuringTool.scene, 'clipModel', true); //Potree.Utils.updateVisible(viewer.mapViewer.cursor, 'clipModel', true) viewer.setView(this.previousView); viewer.setLimitFar(true); viewer.setPointStandardMat(false); //viewer.setClipState(true) viewer.controls.setTarget(null); this.splitScreenTool.focusCenter = null; //viewer.mainViewport.axis.dispose() cameraProps.forEach(e => e.openCount = 0); if (this.showMap) { this.bus.removeEventListener('flyToPos', this.events.flyToPos); viewer.mapViewer.removeEventListener('forceVisible', this.events.mapVisiChange); this.events = null; } this.editing = false; }, initViews() { if (this.views) { this.views.top.pitch = -Math.PI; this.views.top.yaw = 0; this.views.front.pitch = 0; this.views.front.yaw = 0; //--还原for bugID 44757 return; } this.views = {}; this.cameras = {}; this.orthoCamera = new OrthographicCamera(-100, 100, 100, 100, 0.01, 10000); this.orthoCamera.up.set(0, 0, 1); this.splitScreenTool = new SplitScreen(); this.targetPlane = viewer.mainViewport.targetPlane = new Plane(); this.shiftTarget = viewer.mainViewport.shiftTarget = new Vector3(); //project在targetPlane上的位置 for (var i = 0; i < 2; i++) { var prop = cameraProps[i]; var view = new ExtendView(); this.views[prop.name] = view; this.cameras[prop.name] = this.orthoCamera; view.name = prop.name; view.direction = prop.direction; } this.views.mainView = viewer.mainViewport.view; this.cameras.mainView = viewer.mainViewport.camera; }, switchView(name) { //替换view和camera到mainViewport if (this.activeViewName == name) return; var view = this.views[name]; var camera = this.cameras[name]; var prop = cameraProps.find(e => e.name == name); var { boundSize, center, boundingBox } = viewer.bound; this.lastViewName = this.activeViewName; this.activeViewName = name; var lastView = this.views[this.lastViewName]; var lastCamera = this.cameras[this.lastViewName]; viewer.mainViewport.view = view; viewer.mainViewport.camera = camera; if (lastCamera) lastView.zoom = lastCamera.zoom; view.zoom && (camera.zoom = view.zoom); viewer.updateScreenSize({ forceUpdateSize: true }); //更新camera aspect left等 view.applyToCamera(camera); var ifFocus; var boxBound = Clip.box.boundingBox.clone().applyMatrix4(Clip.box.matrixWorld); if (!Potree.Utils.isInsideFrustum(boxBound, camera)) { //屏幕上没有box的话 ifFocus = true; } if (name == 'mainView') { if (lastView) {//2d->3d } if (prop.openCount == 0) ifFocus = false; //viewer.fpControls.lockKey = false } else { this.targetPlane.setFromNormalAndCoplanarPoint(view.direction.clone(), center); this.targetPlane.projectPoint(view.position, this.shiftTarget); //target转换到过模型中心的平面,以保证镜头一定在模型外 //view.position.copy(this.splitScreenTool.getPosOutOfModel(viewer.mainViewport)) //if(view.zoom)camera.zoom = view.zoom//恢复上次的zoom if (prop.openCount == 0) { //至多执行一次 ifFocus = true; } if (this.lastViewName == 'mainView') {//3d->2d } else {} ifFocus || this.splitScreenTool.updateCameraOutOfModel(); //更新相机位置 //if(name == 'top') viewer.mainViewport.alignment = {rotate:true,translate:true}; if (name == 'front') { //viewer.mainViewport.alignment = {translate:true, rotateSide:true, translateVec:new THREE.Vector3(0,0,1)}; //只能上下移动 viewer.mainViewport.rotateSide = true; } else { viewer.mainViewport.rotateSide = false; } //viewer.fpControls.lockKey = true } ifFocus && this.focusOnObject(this.box); //首次到front最好能自动对准box的长边的角度上 prop.openCount++; }, focusOnObject(box) { var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; if (this.activeViewName == 'mainView') { viewer.focusOnObject({ boundingBox: box.boundingBox.clone().applyMatrix4(box.matrixWorld) }, 'boundingBox', duration); } else { this.orthoMoveFit(box.position, { bound: box.boundingBox.clone().applyMatrix4(box.matrixWorld) }, duration); } }, transform(type, axis, value) { //使用按键微调 this.box[type][axis] += value; }, setModeEnable(type, enable) { var modes = []; ['scale', 'translation', 'rotation'].forEach(e => { if (e == type) { enable && modes.push(e); } else { viewer.transformationTool.modesEnabled[e] && modes.push(e); } }); viewer.transformationTool.setModeEnable(modes); viewer.dispatchEvent('content_changed'); }, rotateSideCamera(angle) { //侧视图绕模型中心水平旋转到的角度 angle: -180 ~ 180 var diff = MathUtils.degToRad(angle) - viewer.mainViewport.view.yaw; this.splitScreenTool.rotateSideCamera(viewer.mainViewport, diff); }, orthoMoveFit(pos, info, duration) { var margin = { x: viewer.mainViewport.resolution.x * 0.4, y: viewer.mainViewport.resolution.y * 0.4 }; this.splitScreenTool.viewportFitBound(viewer.mainViewport, info.bound, pos, duration, margin); }, getPointcloud: function getPointcloud() { //找一个离当前最近的点云,且最好有漫游点 var pointclouds = viewer.scene.pointclouds.filter(e => e.panos.length > 0); if (pointclouds.length == 0) pointclouds = viewer.scene.pointclouds; var result = Common.sortByScore(pointclouds, [], [e => { var center = e.bound.getCenter(new Vector3()); var size = e.bound.getSize(new Vector3()).length() / 2; var posToCenter = viewer.images360.position.distanceTo(center); return size / posToCenter; }]); return result[0].item; }, getTarget: function getTarget(boundCenter) { //box位置。要找一个有点云的地方。方案1相机位置, 方案2接近相机的漫游点, 方案3接近中心的漫游点。选择方案2,因最大概率有点云 var target = new Vector3(); var cameraPos = viewer.images360.position; var pano = Common.find(viewer.images360.panos, [], [Images360.sortFunctions.floorDisSquaredToPoint(cameraPos)]); if (pano) { target.copy(pano.position); target.setZ(boundCenter.z); } else { target.copy(boundCenter); } return target; }, /* switchMap:function(state){ }, */ download: function download() { if (this.getIntersectPointcloud().length == 0) { return null; } var visiPointclouds = viewer.scene.pointclouds.filter(e => Potree.Utils.getObjVisiByReason(e, 'datasetSelection')); visiPointclouds.sort((a, b) => { return a.dataset_id - b.dataset_id; }); //缓存需要固定排序好比较 var data = { transformation_matrix: visiPointclouds.map(cloud => { var data = { id: cloud.dataset_id, matrix: this.getTransformationMatrix(cloud).elements, //剪裁大框 visiMatrixes: cloud.material.clipBoxes_in.map(e => this.getTransformationMatrix(cloud, e.inverse).elements), //若干个可见型小框(虽然现在用不到了,因为普通界面不展示这些剪裁区域) unVisiMatrixes: cloud.material.clipBoxes_out.map(e => this.getTransformationMatrix(cloud, e.inverse).elements), //若干个不可见型小框 modelMatrix: new Matrix4().copy(cloud.transformMatrix).transpose().elements }; return data; }), aabb: "b-0.5 -0.5 -0.5 0.5 0.5 0.5" //剪裁空间( 所有点在乘上这个矩阵后, 还能落在 1 * 1 * 1的box内的点就是所裁剪的 }; return data; }, downloadNoCrop() { //不剪裁 下载整个点云 var visiPointclouds = viewer.scene.pointclouds.filter(e => Potree.Utils.getObjVisiByReason(e, 'datasetSelection')); visiPointclouds.sort((a, b) => { return a.dataset_id - b.dataset_id; }); //缓存需要固定排序好比较 var data = { transformation_matrix: visiPointclouds.map(cloud => { var data = { id: cloud.dataset_id, matrix: new Matrix4().elements, //固定值 modelMatrix: new Matrix4().copy(cloud.transformMatrix).transpose().elements }; return data; }), aabb: "b-12742000 -12742000 -12742000 12742000 12742000 12742000" //固定剪裁空间 }; console.log(data); return data; }, getTransformationMatrix: function getTransformationMatrix(pointcloud, invMatrix) { //剪裁矩阵 var invMatrix = invMatrix || this.box.matrixWorld.clone().invert(); return new Matrix4().multiplyMatrices(invMatrix, pointcloud.transformMatrix).transpose(); }, getIntersectPointcloud() { var intersect = pointcloud => { if (pointcloud.intersectBox(this.box.matrixWorld)) return true; }; return viewer.scene.pointclouds.filter(e => intersect(e)); }, getRulerBound() { //坐标尺边界 var camera = viewer.mainViewport.camera; if (!camera.isOrthographicCamera) return; var w = camera.right / camera.zoom; //half var h = camera.top / camera.zoom; var points = []; var boundAtCamera = new Box3(); Clip.box.children[0].geometry.vertices.forEach(e => { //模仿getPosWithFullBound var p = e.clone().applyMatrix4(Clip.box.matrixWorld); points.push(p); var p1 = p.clone().applyMatrix4(camera.matrixWorldInverse); boundAtCamera.expandByPoint(p1); }); //需要找出clipbox的bound的左上角,它在标尺中是原点 var ClipBoxLeftTop = new Vector2(boundAtCamera.min.x, boundAtCamera.max.y); //相对于相机的位置 var camPos = new Vector2(-ClipBoxLeftTop.x, ClipBoxLeftTop.y); //由于ClipBoxLeftTop要变换到原点,所以相机位置就成了ClipBoxLeftTop的相反数, 但因是从上到下所以y再乘-1 var bound_ = { left: camPos.x - w, right: camPos.x + w, bottom: camPos.y + h, //注意从上到下增大 top: camPos.y - h }; //console.log(bound) return bound_; }, screenshot: async function screenshot(rulerBound, rulerMargin) { var unitText = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '像素 : 米'; //测绘图下载。顶视图|侧视图 return new Promise((resolve, reject) => { if (Clip.screenshoting) return reject(); var visiPointclouds = viewer.scene.pointclouds.filter(e => Potree.Utils.getObjVisiByReason(e, 'datasetSelection')); var camera = viewer.mainViewport.camera; //if(Clip.activeViewName == 'mainView')return reject() var maxWidth = 8192, minWidth = Potree.browser.urlHasValue('clipMinWidth', true) || 1024; //图片尺寸最大最小值。 //Potree.settings.pointDensity = 'ultraHigh' viewer.inputHandler.deselectAll(); Clip.box.visible = false; Clip.screenshoting = true; var material = new ExtendPointCloudMaterial(); material.pointSizeType = Potree.PointSizeType.FIXED; //Potree.PointSizeType material.size = Potree.browser.urlHasValue('clipPointSize', true) || 1; material.uniforms.minSize.value = 0.1; material.activeAttributeName = 'rgba'; //material.classification = pointcloud.material.classification; material.clipBoxBig_in = visiPointclouds[0].material.clipBoxBig_in; material.shaderNeedsUpdate = true; material.bigClipInBox = visiPointclouds[0].material.bigClipInBox; var materials = visiPointclouds.map(e => { var mat = e.material; e.material = material; return mat; }); //根据boundingBox尺寸来定图片尺寸 var boundingBox = Clip.box.boundingBox.clone().applyMatrix4(Clip.box.matrixWorld); var points = []; var bound = new Box3(); Clip.box.children[0].geometry.vertices.forEach(e => { //模仿getPosWithFullBound var p = e.clone().applyMatrix4(Clip.box.matrixWorld); points.push(p); var p1 = p.clone().applyMatrix4(camera.matrixWorldInverse); bound.expandByPoint(p1); }); var boundSize = bound.getSize(new Vector3()); var minZoom = Potree.browser.urlHasValue('clipZoom', true) || 80; //1px = 1个点 = 1cm , 如果一个点都是1cm的话 //zoom不宜过大或过小,过小点云重叠、画面模糊;过大点云有间隙,纹理就看不清 //中间部分75-80为佳,文字100,边缘50. 最好支持调节 . 且当下载尺寸变大往往点云也多,可能冲破pointbudget限制 //let text = `1 : ${(1 / camera.zoom).toFixed(4)}(像素 : 米)` var w = boundSize.x * minZoom; var h = boundSize.y * minZoom; var max = Math.max(w, h); var s = 1; if (max > maxWidth) { s = maxWidth / max; } else if (max < minWidth) { s = minWidth / max; } w *= s, h *= s; material.size *= s; s != 1 && console.log('宽度缩放倍数', s); //虽然size>1就是浪费像素,但是太小了视觉效果有点差……可能因为fov不真实。 点云大就像是老式电视机虽然显示像素量少但感觉不出画面模糊,且边缘锐利。 w = Math.round(w); h = Math.round(h); var focusObjectInfo = [{ boundingBox, points }, 'boundingBox', 0, { dontChangeCamDir: true, dontMoveMap: true, boundScale: 1 }]; //分块渲染截图,最后拼合图片。需要使每一块的点数不超过pointBudget, 且尺寸不超过4096(会崩溃),过小的话一般不会超过pointBudget,除非是深度较大后排点云多。 var r = MathUtils.clamp(Math.sqrt(3.5e7 / boundSize.z) * s, 1024, 4096); //每多少米分一块。 推理 wc*hc = w / r * h / r = zoom * w * s * zoom * h * s / r^2 = xyz / V(常数,每多少立方米会超出pointBudget,就是括号里的数字,给大概值) //let r = THREE.Math.clamp(1024 / boundSize.z, 256, 4096); var wc = w / r; //横向块数 var hc = h / r; //纵向块数 var splitRenderInfo = (wc > 1 || hc > 1) && { wc: Math.ceil(wc), hc: Math.ceil(hc) }; //因为结果需要化为整数所以可能不太理想, 分割数过多。 另外如果面积小但是因z过长而超出pointBudget没关系,因后排点云无需绘制 console.log({ wc, hc, w, h }); var meterPerPixel = boundSize.x / w; var text = "1 : ".concat(meterPerPixel.toFixed(4), "\uFF08").concat(unitText, "\uFF09"); var beforeScreenshot = () => { if (rulerBound) { var ruler = Clip.getRulerBound(); Object.assign(rulerBound, ruler); } }; var { getImagePromise, finishPromise } = viewer.startScreenshot({ type: 'default', bgOpacity: 0, focusObjectInfo, maxTimeForPointLoad: 3e5, pointDensity: 'screenshot2', splitRenderInfo, beforeScreenshot }, w, h, 1); finishPromise.done(_ref => { var { dataUrl } = _ref; viewer.inputHandler.toggleSelection(Clip.box); Clip.box.visible = true; var img = new Image(); img.src = dataUrl; img.onload = async () => { //加上标尺比例水印 //固定文字大小和边距像素 //如果有一边过小,可能超出画面外,暂时不管这种可能 var fontsize = math.linearClamp(w, [100, 700, 8000], [12, 20, 30]); var marginSelf = { //img外的margin(标尺内) left: rulerBound ? 76 : 40, right: rulerBound ? 30 : 40, bottom: rulerBound ? 20 + fontsize * 2 : 40 + fontsize * 2, top: rulerBound ? 60 : 40 }; //const Margin = rulerMargin + marginSelf //文字的边距 var bottomRatioToImg = -Math.min(fontsize * 2.5, rulerBound ? marginSelf.bottom : marginSelf.bottom * 0.9) / h; //- (marginSelf.bottom - fontsize)/ h //在img之下. text底部到img底部的距离 //let leftRatioToImg = Margin / w var labelInfo = { bottomRatioToImg, horizonCenter: true, //leftRatioToImg, textColor: rulerBound ? { r: 0, g: 0, b: 0, a: 1 } : { r: 255, g: 255, b: 255, a: 1 }, textBorderColor: { r: 30, g: 30, b: 30, a: 1 }, textBorderThick: rulerBound ? 0 : 1, fontsize, fontWeight: rulerBound ? 'normal' : 'Bold', outputCanvas: !!rulerBound, bgColor: rulerBound ? { r: 255, g: 255, b: 255, a: 255 } : null }; labelInfo.bgMargin = { //img外需要多少margin left: marginSelf.left + rulerMargin, //rulerMargin是在标尺外的margin bottom: marginSelf.bottom + rulerMargin, right: marginSelf.right + rulerMargin, top: marginSelf.top + rulerMargin }; if (rulerBound) { //因为margin 扩大bound rulerBound.left -= marginSelf.left * meterPerPixel; rulerBound.right += marginSelf.right * meterPerPixel; rulerBound.top -= marginSelf.top * meterPerPixel; rulerBound.bottom += marginSelf.bottom * meterPerPixel; } //console.log('topRatioToImg',topRatioToImg,'leftRatioToImg',leftRatioToImg,'fontsize', labelInfo.fontsize) var result = await Potree.Utils.imgAddText(img, text, labelInfo); //Common.downloadFile(finalDataUrl, 'screenshot11.png') visiPointclouds.forEach((e, i) => e.material = materials[i]); Clip.screenshoting = false; viewer.viewports = [viewer.mainViewport]; resolve(result); }; }); }); /* 隐患:无法获知最大可加载的点的数量,也未知需要加载的点的数量。需要掌控好分块数量,避免因pointBudget限制造成周围的点稀疏。 加载点云时间过久 */ return finishPromise; } }; /* 裁剪点云时,2D界面显示全部平面图,按楼层切换显示。 所有点云下载后点云所带的本地坐标都是场景显示的local坐标,这样才能看起来一样。 且为了使之和坐标页面对应,坐标页面的本地坐标也是local,而非mesh_local. //保存box viewer.modules.Clip.box.matrix //恢复box let a = new THREE.Matrix4().fromArray([ 14.189120116830964, 0, 0, 0, 0, 9.924790069368392, 0, 0, 0, 0, 0.8751009568437951, 0, -7.433819981633984, 1.528696446650445, 2.9412375879215977, 1 ]) a.decompose(viewer.modules.Clip.box.position,viewer.modules.Clip.box.quaternion,viewer.modules.Clip.box.scale) viewer.modules.Clip.rotateSideCamera(-93) */ var viewportProps = [{ left: 0.5, bottom: 0.5, width: 0.5, height: 0.5, name: 'MainView', //view: viewer.scene.view, active: true }, { left: 0, bottom: 0.5, width: 0.5, height: 0.5, name: 'top', name2: 'mapViewport', axis: ["x", "y"], direction: new Vector3(0, 0, -1), //镜头朝向 //axisSign:[1,1], active: true //相机位置在z轴正向 }, { left: 0.5, bottom: 0, width: 0.5, height: 0.5, name: 'right', axis: ["y", "z"], direction: new Vector3(1, 0, 0), //axisSign:[1,1], active: true //相机位置在x轴负向 右下角屏 }, { left: 0, bottom: 0, width: 0.5, height: 0.5, name: 'back', axis: ["x", "z"], direction: new Vector3(0, -1, 0), //axisSign:[-1,1], // 从镜头方向看 x向左 所以取负 active: true //相机位置在y轴正向 左下角屏 }]; var SplitScreen4Views = new SplitScreen(); SplitScreen4Views.split = function () { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var defaultCamera = viewer.scene.getActiveCamera(); var { boundSize, center } = viewer.bound; viewer.setLimitFar(false); viewer.mapViewer.attachToMainViewer(true, 'split4Screens', 'dontSet'); viewer.renderer.clear(); //clear back的viewport左边的1px宽的部分,因setScissor的bug var viewports = this.splitStart(viewportProps); //覆盖在map上、点云等其他物体之下的一层背景 var mapViewport = viewer.mapViewer.viewports[0]; mapViewport.noPointcloud = false; //隐藏地图游标 //Potree.Utils.updateVisible(viewer.mapViewer.cursor, 'split4Screens', false) /* viewer.images360.panos.forEach(pano=>{ Potree.Utils.updateVisible(pano.mapMarker, 'split4Screens', false) //希望这时候mapMarker已经建好了吧 }) */ /* viewer.images360.panos.forEach(pano=>{ pano.addLabel2() Potree.Utils.updateVisible(pano.label2, 'notDisplay', true) pano.dispatchEvent({type:'changeMarkerTex',name:'ring'}) }) */ //材质 this.statesBefore = { pointDensity: Potree.settings.pointDensity, displayMode: Potree.settings.displayMode, position: viewer.images360.position, target: viewer.scene.view.getPivot(), currentPano: viewer.images360.currentPano //--- //ifShowMarker : Potree.settings.ifShowMarker, }; viewer.setPointStandardMat(true, null, true); //切换到标准模式(主要为了mainViewport) 点云使用标准大小 var matBefore = { opacity: new Map() }; var newOpacityMap = new Map(); viewer.scene.pointclouds.forEach(e => { matBefore.opacity.set(e, e.temp.pointOpacity); matBefore.colorType = e.material.activeAttributeName; /* { var map = new Map() newOpacityMap.set(e, map ) var size = e.bound.getSize() viewports.forEach(viewport=>{//根据bound设置opacity,越小的要靠越近,需要大的opacity。但似乎影响太大了 if(viewport.name == 'MainView')return; var prop = viewportProps.find(v => viewport.name == v.name2||viewport.name == v.name) let axis = prop.axis var width = size[axis[0]] var height = size[axis[1]] var area = width * height map.set(viewport, 5000/area); }) } */ }); var beforeRender = function beforeRender() { viewer.dealBeforeRender = true; //使不全部渲染 viewer.scene.pointclouds.forEach(e => { if (this.name == "MainView") { e.material.activeAttributeName = matBefore.colorType; // 'rgba' e.material.useFilterByNormal = false; //e.material.pointSizeType = Potree.config.material.pointSizeType e.changePointOpacity(matBefore.opacity.get(e)); //1 //恢复下 e.temp.pointOpacity 其实就是1 Potree.settings.pointDensity = 'fourViewportsMain'; /* 'fourViewports' */ //本来想比另外三屏高一点质量,结果发现会闪烁,因为点云加载需要时间 (navvis仿版也是一样,以后看看能否优化) } else { e.material.activeAttributeName = "color"; e.material.useFilterByNormal = true; //e.material.pointSizeType = 'ADAPTIVE' Potree.settings.pointDensity = 'fourViewports'; //强制降低点云质量 //侧面重叠概率更大,所以透明度调小 e.changePointOpacity(this.name == "mapViewport" ? 0.5 : 0.1 /* newOpacityMap.get(e).get(viewport), true */); //多数据集有的数据集很小,放大后显示特别淡 //console.log(e.name, viewport.name, e.temp.pointOpacity, e.material.opacity) } viewer.images360.panos.forEach(pano => { if (this.name == 'mapViewport') { Potree.Utils.updateVisible(pano.marker, 'showOnMap', true, 1, 'add'); } else { Potree.Utils.updateVisible(pano.marker, 'showOnMap', false, 1, 'cancel'); } }); }); viewer.dealBeforeRender = false; }; viewports.forEach(viewport => { viewport.beforeRender = beforeRender; new AxisViewer(viewport, viewer.renderArea, { domStyle: { top: '22px', //viewport.name == 'mapViewport' ? '2px' : '-25px', right: viewport.name == 'mapViewport' ? '30px' : '2px', width: '80px', height: '80px' } }); }); this.enableMap(false); this.enableFloorplan(false); viewer.mapViewer.setViewLimit('null'); //多数据集距离远时可以任意远,所以不限制了。但是这样就会看到地图边界了怎么办?超出后让地图隐藏? //viewer.dispatchEvent({'type': 'beginSplitView' }) //viewer.updateScreenSize({forceUpdateSize:true}) //this.viewportFitBound(mapViewport, boundSize, center) //Potree.settings.ifShowMarker = false Potree.settings.displayMode = 'showPointCloud'; }; SplitScreen4Views.recover = function () { viewer.viewports.forEach(e => { e.axis.dispose(); }); this.unSplit(); viewer.mapViewer.viewports[0].beforeRender = null; /* const {width, height} = viewer.renderer.getSize(new THREE.Vector2()); viewer.renderer.setViewport(0,0,width,height) viewer.renderer.setScissorTest( false ); */ viewer.setView({ position: this.statesBefore.position, target: this.statesBefore.target, currentPano: this.statesBefore.currentPano, duration: 300, callback: function callback() {} }); viewer.mainViewport.beforeRender = null; viewer.setLimitFar(true); var mapViewport = viewer.mapViewer.viewports[0]; viewer.mapViewer.attachToMainViewer(false); //Potree.Utils.updateVisible(viewer.mapViewer.cursor, 'split4Screens', true) /* viewer.images360.panos.forEach(pano=>{ Potree.Utils.updateVisible(pano.mapMarker, 'split4Screens', true) }) */ /* viewer.images360.panos.forEach(pano=>{ Potree.Utils.updateVisible(pano.label2, 'notDisplay', false ) pano.dispatchEvent({type:'changeMarkerTex',name:'default'}) }) */ mapViewport.noPointcloud = true; { this.enableMap(Potree.settings.mapEnable); this.enableFloorplan(Potree.settings.floorplanEnable); if (this.floorplanListener) { viewer.mapViewer.mapLayer.removeEventListener('floorplanLoaded', this.floorplanListener); this.floorplanListener = null; } } Potree.settings.pointDensity = this.statesBefore.pointDensity; if (!Potree.settings.isOfficial) { Potree.settings.displayMode = this.statesBefore.displayMode; } viewer.scene.pointclouds.forEach(e => { e.material.useFilterByNormal = false; //e.material.pointSizeType = Potree.config.material.pointSizeType }); viewer.setPointStandardMat(false); viewer.mapViewer.setViewLimit('standard'); viewer.images360.panos.forEach(pano => { Potree.Utils.updateVisible(pano.marker, 'showOnMap', false, 1, 'cancel'); }); //Potree.settings.ifShowMarker = this.statesBefore.ifShowMarker //viewer.dispatchEvent({'type': 'finishSplitView' }) //viewer.updateScreenSize({forceUpdateSize:true}) }; SplitScreen4Views.updateMapViewerBG = function () { var mapViewport = viewer.mapViewer.viewports[0]; if (this.splited && (this.floorplanEnabled || this.mapEnabled)) { mapViewport.background = 'overlayColor'; mapViewport.backgroundColor = new Color(0, 0, 0); mapViewport.backgroundOpacity = 0.5; } else { mapViewport.background = null; mapViewport.backgroundColor = null; mapViewport.backgroundOpacity = null; } viewer.mapViewer.mapChanged = true; viewer.mapViewer.needUpdate = true; }; SplitScreen4Views.setFloorplanDisplay = function (e) { var show = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; e.floorplan.setEnable(show); }; SplitScreen4Views.enableMap = function (enable) { var map = viewer.mapViewer.mapLayer.maps.find(e => e.name == 'map'); map.setEnable(!!enable); //viewer.mapViewer.mapGradientBG = viewer.background == 'gradient' && !enable this.mapEnabled = enable; this.updateMapViewerBG(); }, //直接覆盖原设置 SplitScreen4Views.enableFloorplan = function (enable) { //是否让自定义的平面图显示 var floorplans = viewer.mapViewer.mapLayer.maps.filter(e => e.name.includes('floorplan')); if (this.floorplanListener) { viewer.mapViewer.mapLayer.removeEventListener('floorplanLoaded', this.floorplanListener); } this.floorplanListener = e => { this.setFloorplanDisplay(e, enable); }; viewer.mapViewer.mapLayer.addEventListener('floorplanLoaded', this.floorplanListener); //万一之后才加载 if (!enable) { //隐藏平面图 floorplans.forEach(floorplan => this.setFloorplanDisplay({ floorplan }, false)); } else { floorplans.forEach(floorplan => this.setFloorplanDisplay({ floorplan }, true)); } if (enable && floorplans.length == 0) Potree.loadMapEntity('all', true); this.floorplanEnabled = enable; this.updateMapViewerBG(); }, /* viewportFitBound:function(viewport, boundSize, center){ //使一个viewport聚焦在某个范围 var prop = viewportProps.find(v => viewport.name == v.name2||viewport.name == v.name) let axis = prop.axis let expand = 10; let position = center.clone() var moveAtAxis = ['x','y','z'].find(e=>!(axis.includes(e))) if(viewport.name == 'mapViewport'){ let ori = viewport.view.position[moveAtAxis] position[moveAtAxis] = ori //不改变这个值,尤其是mapViewer中的z }else{ position[moveAtAxis] += boundSize[moveAtAxis]/2+expand//移动到bounding边缘外 } viewport.view.position.copy(position) var width = Math.max(boundSize[axis[0]], boundSize[axis[1]] * viewport.camera.aspect)//视口宽度(米) var margin = 50 //px viewport.camera.zoom = (viewport.resolution.x - margin) / width viewport.camera.updateProjectionMatrix() }, */ SplitScreen4Views.focusOnPointCloud = function (pointcloud) { //三个屏都聚焦在这个点云 var boundSize = pointcloud.bound.getSize(new Vector3()); var center = pointcloud.bound.getCenter(new Vector3()); var target = pointcloud.panosBound && pointcloud.panosBound.center; //看向pano集中的地方,也就是真正有点云的地方。(因为需要展示所有点云,所以没办法用这个做为center) this.focusOnObject(pointcloud.bound, center, target); viewer.flyToDataset({ pointcloud, dontMoveMap: true, duration: 0 }); }; SplitScreen4Views.focusOnObject = function (bound, center, target) { var duration = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; viewer.viewports.forEach(e => { if (e.name == 'MainView') { /* let len = boundSize.length() let distance = THREE.Math.clamp(e.view.position.distanceTo(center), len * 0.01, len*0.3 ) //距离限制 //viewer.focusOnObject({position:center}, 'point', duration, {distance, direction: e.view.direction,dontMoveMap:true} )//平移镜头 //为了方便定位,直接飞到中心位置: e.view.setView({ position:center, duration, target }) */ } else { this.viewportFitBound(e, bound, center); } }); }; var Alignment = { SplitScreen: SplitScreen4Views, handleState: null, //操作状态 'translate'|'rotate' bus: new EventDispatcher(), /* prepareRecord : true, writeToHistory(pointclouds){ if(!this.prepareRecord)return; this.prepareRecord = false let content = this.getTemp(pointclouds) this.history.writeIn(content) }, undo(){//撤销一步 let last = this.history.pop(); last && last.forEach(item=>{ this.applyTemp(item) }) }, */ applyTemp(item) { var pointcloud = viewer.scene.pointclouds.find(p => p.dataset_id + p.name == item.sid); pointcloud.orientationUser = item.orientationUser; pointcloud.translateUser = item.translateUser; this.setMatrix(pointcloud); }, getTemp(pointclouds) { //记录最近一次保存后的状态,便于恢复 pointclouds = pointclouds || viewer.scene.pointclouds; return pointclouds.map(e => { return { sid: e.dataset_id + e.name, orientationUser: e.orientationUser, translateUser: e.translateUser.clone() }; }); }, init: function init() { var transfromInfo; this.history = new History({ applyData: data => { data.forEach(item => { Alignment.applyTemp(item); }); return true; }, getData: pointclouds => { return Alignment.getTemp(pointclouds); } }); viewer.fpControls.addEventListener("transformPointcloud", e => { if (e.pointclouds[0].dataset_id == Potree.settings.originDatasetId) { //禁止手动移动初始数据集 return this.bus.dispatchEvent('forbitMoveOriginDataset'); } this.history.beforeChange(e.pointclouds); //this.writeToHistory( e.pointclouds ) if (!transfromInfo) { transfromInfo = { pointclouds: e.pointclouds }; } if (this.handleState == 'translate') { e.pointclouds.forEach(cloud => Alignment.translate(cloud, e.moveVec)); } else if (this.handleState == 'rotate') { if (Potree.settings.editType == 'pano') { //旋转中心是intersectStart的版本 /* let center = e.intersectStart //旋转中心是mousedown的位置 if(e.intersect.equals(center))return if(!transfromInfo){ transfromInfo = { orientationUser : e.pointclouds[0].orientationUser, //vecStart : e.moveVec, // 首次移动向量 只有八个方向,精度太小,所以延迟 pointclouds: e.pointclouds } this.bus.dispatchEvent({type:'rotateStart', startPoint:center}) return }else if(!transfromInfo.vecStart){ let vec = new THREE.Vector3().subVectors(e.intersect, center).setZ(0) if(vec.length() * e.camera.zoom > 30){ //在屏幕上距离初始点有一定距离后开始算 //console.log('moveVec',vec) transfromInfo.vecStart = vec } */ var center = e.pointclouds[0].translateUser; //旋转中心是第一个点云的位置 if (e.intersect.equals(center)) return; if (!transfromInfo.vecStart) { transfromInfo.orientationUser = e.pointclouds[0].orientationUser; transfromInfo.vecStart = new Vector3().subVectors(e.intersectStart, center).setZ(0); } else { var vec = new Vector3().subVectors(e.intersect, center).setZ(0); var angle = math.getAngle(transfromInfo.vecStart, vec, 'z'); var diffAngle = transfromInfo.orientationUser + angle - transfromInfo.pointclouds[0].orientationUser; transfromInfo.pointclouds.forEach(cloud => { /* let centerNoTranfrom = Potree.Utils.datasetPosTransform({ toDataset: true, pointcloud:cloud, position: center }) //中心点在数据集中的位置 Alignment.rotate(cloud, null, diffAngle) let centerNow = Potree.Utils.datasetPosTransform({ fromDataset: true, pointcloud:cloud, position: centerNoTranfrom }) //中心点的现在位置 let shift = new THREE.Vector3().subVectors( center, centerNow); //偏移量 Alignment.translate(cloud,shift) //使center还保留在原位 //let centerNow1 = Potree.Utils.datasetPosTransform({ fromDataset: true, pointcloud:transfromInfo.pointcloud, position: centerNoTranfrom }) //中心点的现在位置 */ Alignment.rotateAround(center, cloud, null, diffAngle); }); } //this.bus.dispatchEvent({type:'rotate', endPoint: e.intersect}) } else { var _center = e.pointclouds[0].translateUser; //移动到的位置就是中心 if (e.intersect.equals(_center)) return; if (!transfromInfo.vecStart) { transfromInfo.orientationUser = e.pointclouds[0].orientationUser; transfromInfo.vecStart = new Vector3().subVectors(e.intersectStart, _center).setZ(0); } else { var _vec = new Vector3().subVectors(e.intersect, _center).setZ(0); var _angle = math.getAngle(transfromInfo.vecStart, _vec, 'z'); var _diffAngle = transfromInfo.orientationUser + _angle - transfromInfo.pointclouds[0].orientationUser; Alignment.rotate(transfromInfo.pointclouds[0], null, _diffAngle); } } } }); viewer.fpControls.addEventListener("end", e => { transfromInfo && this.history.afterChange(transfromInfo.pointclouds); transfromInfo = null; }); // cursor: var updateCursor = e => { if (e.drag || !this.editing) return; //仅在鼠标不按下时更新: var handleState = Alignment.handleState; if (e.hoverViewport.alignment && handleState && e.hoverViewport.alignment[handleState]) { if (handleState == 'translate') { if (e.intersect && e.intersect.location) { viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "movePointcloud" }); } else { viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "movePointcloud" }); } } else if (handleState == 'rotate') { if (e.intersect && e.intersect.location) { viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "rotatePointcloud" }); } else { viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "rotatePointcloud" }); } } } else { //清空: viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "movePointcloud" }); viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "rotatePointcloud" }); } }; viewer.addEventListener('global_mousemove', updateCursor); viewer.addEventListener('global_drop', updateCursor); //拖拽结束 viewer.addEventListener('updateModelBound', e => { if (this.editing) { this.SplitScreen.updateCameraOutOfModel(); } }); }, setMatrix: function setMatrix(pointcloud) { var vec1 = pointcloud.position; //position为数据集内部的偏移,在navvis中对应的是dataset.pointCloudSceneNode的children[0].position var vec2 = pointcloud.translateUser; var angle = pointcloud.orientationUser; var pos1Matrix = new Matrix4().setPosition(vec1); //先移动到点云本身应该在的初始位置(在4dkk里和其他应用中都是在这个位置的,也能和漫游点对应上) var rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0, 0, 1), angle); //再旋转 var pos2Matrix = new Matrix4().setPosition(vec2); //最后是平移 var matrix = new Matrix4().multiplyMatrices(pos2Matrix, rotMatrix); pointcloud.transformMatrix = matrix.clone(); //为该数据集的变化矩阵。 对应navvis的m2w_ pointcloud.transformInvMatrix.copy(pointcloud.transformMatrix).invert(); pointcloud.rotateMatrix = rotMatrix; pointcloud.rotateInvMatrix.copy(rotMatrix).invert(); pointcloud.panos.forEach(e => e.transformByPointcloud()); matrix = new Matrix4().multiplyMatrices(matrix, pos1Matrix); //matrix.premultiply(viewer.scene.scene.matrix);////////////////////////add pointcloud.matrix = matrix; //pointcloud.matrixWorldNeedsUpdate = true //更新matrixWorld (非计算,直接赋值) pointcloud.updateMatrixWorld(true); if (this.editing) { Alignment.changeCallBack && Alignment.changeCallBack(); } if (pointcloud.spriteNodeRoot) { pointcloud.spriteNodeRoot.matrixWorld.copy(pointcloud.matrixWorld); //.multiplyMatrices(pointcloud.matrixWorld, pointcloud.matrixWorld); } viewer.boundNeedUpdate = true; //pointcloud.updateBound() pointcloud.getPanosBound(); viewer.dispatchEvent('content_changed'); }, rotateAround(center, pointcloud, deg, angle) { //绕center点转动 var angle = angle != void 0 ? angle : MathUtils.degToRad(deg); var vec1 = new Vector3().subVectors(pointcloud.translateUser, center); var rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0, 0, 1), angle); var vec2 = vec1.clone().applyMatrix4(rotMatrix); //将到旋转中心的偏差也转动 var vec3 = new Vector3().subVectors(vec2, vec1); //这个就是多出来的一步translateUser this.rotate(pointcloud, deg, angle); this.translate(pointcloud, vec3); //绕点转动就是比普通转动多一步移动到相对center的某个位置。 1 初始点云移动到自己的position; 2 移动一个vec1 3绕原点旋转 4再移动一个原本的translateUser。 绘制出来后发现移动量就是第二步vec旋转后的偏移 }, rotate: function rotate(pointcloud, deg, angle) { //绕各自中心转动(各自的position) 假设点云位移position后0,0,0就是它的中心了(根据navvis观察这样做是绕同一个点旋转的) var angle = angle != void 0 ? angle : MathUtils.degToRad(deg); //正逆负顺 pointcloud.orientationUser += angle; Alignment.setMatrix(pointcloud); }, translate: function translate(pointcloud, vec) { pointcloud.translateUser.add(vec); Alignment.setMatrix(pointcloud); }, enter: function enter() { //this.saveTemp() this.originData = this.getTemp(); this.SplitScreen.split({ alignment: true }); /* viewer.images360.panos.forEach(pano=>{ Potree.Utils.updateVisible(pano.mapMarker, 'split4Screens', false) }) */ viewer.viewports.find(e => e.name == 'mapViewport').alignment = { rotate: true, translate: true }; viewer.viewports.find(e => e.name == 'right').alignment = { translate: true, translateVec: new Vector3(0, 0, 1) }; //只能上下移动 viewer.viewports.find(e => e.name == 'back').alignment = { translate: true, translateVec: new Vector3(0, 0, 1) }; //只能上下移动 this.editing = true; viewer.updateFpVisiDatasets(); }, leave: function leave() { this.switchHandle(null); /* this.originData.forEach(e=>{//恢复 var pointcloud = viewer.scene.pointclouds.find(p=>p.dataset_id == e.id) this.translate(pointcloud, new THREE.Vector3().subVectors(e.translateUser , pointcloud.translateUser)) this.rotate(pointcloud, null, e.orientationUser - pointcloud.orientationUser) }) */ this.originData.forEach(e => { //恢复 this.applyTemp(e); }); this.SplitScreen.recover(); /* viewer.images360.panos.forEach(pano=>{ Potree.Utils.updateVisible(pano.mapMarker, 'split4Screens', true) }) */ this.editing = false; this.history.clear(); viewer.updateFpVisiDatasets(); viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "movePointcloud" }); viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "rotatePointcloud" }); }, switchHandle: function switchHandle(state) { this.handleState = state; //清空: viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "movePointcloud" }); viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "rotatePointcloud" }); this.bus.dispatchEvent({ type: 'switchHandle', state }); }, save: function save() { //保存所有数据集的位置和旋转 var callback = () => { //保存成功后 this.originData = this.getTemp(); //this.saveTemp(); //需要修改 测量线的position。漫游点已经实时修改了 viewer.scene.measurements.forEach(e => e.transformByPointcloud()); viewer.images360.updateCube(viewer.bound); }; var data = viewer.scene.pointclouds.map(e => { var pos = viewer.transform.lonlatToLocal.inverse(e.translateUser.clone()); var initialPointcloud = viewer.scene.pointclouds.find(e => e.dataset_id == Potree.settings.originDatasetId); return { id: e.dataset_id, orientation: e.orientationUser, location: [pos.x, pos.y, pos.z + initialPointcloud.datasetData.location[2]] //transformMatrix: e.transformMatrix.elements, }; }); //data = JSON.stringify(data) //test: 退出后保留结果 if (!Potree.settings.isOfficial) { callback(); } return { data, callback }; } }; var texLoader$9 = new TextureLoader(); var markerMats$2; var markerSizeInfo$2 = { width2d: 35 }; var color$2 = new Color('#FFF'); var faceMats; var getFaceMat = name => { if (!faceMats) { //navvis材质可以搜gridTexture var gridTex = texLoader$9.load(Potree.resourcePath + '/textures/gridmap.png'); gridTex.wrapS = gridTex.wrapT = RepeatWrapping; //gridTex.repeat.set(0.5,0.5)//放大一些 faceMats = { dataset: new MeshStandardMaterial({ color: 812922, side: DoubleSide, opacity: 0.2, transparent: true, depthTest: false, wireframe: true }), building: new MeshStandardMaterial({ color: 812922, metalness: 0.2, roughness: 0.8, side: DoubleSide, opacity: 0.1, transparent: true, depthTest: true }), buildingSelect: new MeshStandardMaterial({ color: 36582, metalness: 0, roughness: 1, side: DoubleSide, opacity: 0.1, transparent: true, depthTest: true }), floor: new MeshStandardMaterial({ color: 11708469, metalness: 0.1, roughness: 1, side: DoubleSide, //BackSide, opacity: 0.05, transparent: true, depthTest: true }), floorSelect: new DepthBasicMaterial({ map: gridTex, color: 16707151, side: DoubleSide, //BackSide, opacity: 1, transparent: true, useDepth: true, clipDistance: 1, occlusionDistance: 1, /* occlusionDistance:变为backColor距离, clipDistance:opacity到达0或者1-maxClipFactor时的距离 */ maxClipFactor: 0.9, backColor: '#efe' //backColor:"#669988" , }), room: new MeshStandardMaterial({ color: "#ff44ee", metalness: 0, roughness: 1, side: DoubleSide, //BackSide, opacity: 0.08, transparent: true, depthTest: false }), roomSelect: new DepthBasicMaterial({ map: gridTex, color: "#ff44ee", side: DoubleSide, //BackSide, opacity: 1, transparent: true, useDepth: true, clipDistance: 1, occlusionDistance: 0.5, /* occlusionDistance:变为backColor距离, clipDistance:opacity到达0或者1-maxClipFactor时的距离 */ maxClipFactor: 0.8, backColor: '#ff88dd' //"#cc99c2" , }) }; } return faceMats[name]; }; class BuildingBox extends ctrlPolygon { //建筑实体,包括building, floor, room constructor(prop) { prop.dimension = '3d'; //prop.name = Potree.config.siteModel.names[prop.buildType] + super('siteModel_' + prop.buildType, prop); this.midMarkers = []; this.buildChildren = []; //子实体 this.holes = []; //在这创建的hole this.parentHoles = []; //floor从building那得到的当层holes this.mats = {}; //材质 this.panos = this.panos || []; this.center; //中心点 if (this.buildType == 'floor') { this.points = prop.points = this.buildParent.points; //完全等于建筑的点 this.buildParent.holes.forEach(hole => { //从building获取holes var floorHole = new BuildingBox({ buildType: 'hole', buildParent: this, originHole: hole, //整栋大楼在当层的hole ifDraw: this.ifDraw || Potree.settings.drawEntityData }); this.parentHoles.push(floorHole); this.add(floorHole); floorHole.points = hole.points; //完全等于建筑的点 }); } if (this.buildType == 'room' || this.buildType == 'hole') { this.restrictArea = this.buildParent; //不能超出的区域 } if (this.buildParent) this.dontDragFloorHeight = this.buildParent.dontDragFloorHeight; if (this.buildType != 'hole') { this.box = this.createBox(); //无论是否edit都绘制的原因:为了将在外的点移到在内,需要用mesh来获取intersect this.add(this.box); this.box.visible = !!this.ifDraw; } if (this.ifDraw) { //只存储空间模型信息,不绘制 { this.createPrismLines(color$2); this.lineMesh.visible = false; Potree.Utils.setObjectLayers(this.lineMesh, 'bothMapAndScene'); } this.addEventListener('dragChange', e => { //修改中点 this.updateTwoMidMarker(e.index); }); } this.initData(prop); } initData(prop) { if (prop.ifDraw) { super.initData(prop); } else { if (prop.points) { this.points = prop.points; } } } intersectPointcloudVolume(pointcloud) { //和pointcloud的重叠体积 return this.intersectPointcloudArea(pointcloud) * this.coverPointcloudHeight(pointcloud); } coverPointcloudHeight(pointcloud, getPercent) { var bound2 = pointcloud.bound; var { zMin, zMax } = this.getRealZ(); var min = Math.min(zMin, bound2.min.z); var max = Math.max(zMax, bound2.max.z); var height1 = zMax - zMin; var height2 = bound2.max.z - bound2.min.z; var coverHeight = height1 + height2 - (max - min); //重叠高度 <=0是没重叠 if (getPercent) { return coverHeight / height1; } return coverHeight; } intersectPointcloudArea(pointcloud, getPercent) { //和pointcloud的重叠面积 var bound = this.getBound(); var bound2 = pointcloud.bound; if (!bound.intersectsBox(bound2)) return 0; var boxPoints = pointcloud.getUnrotBoundPoint(); //获取tightBound的四个点。 如果是有旋转角度的点云,这个和pointcloud.bound的四个点是不一致的,覆盖面积小于pointcloud.bound var areaWhole = 0; var area1 = this.getArea(); var area2 = Math.abs(math.getArea(boxPoints)); { //计算points与点云总面积 (但是把hole也加入了面积)(并集,重叠部分只算一次) var rings = math.getPolygonsMixedRings([this.points, boxPoints]); rings.forEach(e => { areaWhole += e.area; }); } var coverHoleArea = 0; //holes与数据集重叠的部分 var holes = this.holes.concat(this.parentHoles); var holesArea = 0; //所有holes面积相加 var areaHoleWithPointcloud = 0; //hole和点云的面积并集 if (holes.length > 0) { //还要再扣除holes与数据集重叠的部分。其中holes为mix轮廓 var outHoles = []; //没有重合的holes的外轮廓 /* if(holes.length>=2){//合并holes。如果能在绘制时直接合并holes就好啦,这步就转移到那去,但是要删除hole好麻烦 let holes_ = holes.map(e=>e.points) outHoles = math.getPolygonsMixedRings(holes_, true ) outHoles.forEach(e=>{ holesArea+=e.area }) outHoles = outHoles.map(e=>e.points) }else{ outHoles = holes.map(e=>e.points) outHoles.forEach(e=> holesArea += Math.abs(math.getArea(e))) } */ holesArea = this.getHolesArea(); //holes与数据集重叠的部分 { var polygons = outHoles.concat([boxPoints]); var _rings = math.getPolygonsMixedRings(polygons); _rings.forEach(e => { areaHoleWithPointcloud += e.area; }); coverHoleArea = holesArea + area2 - areaHoleWithPointcloud; //hole和点云的交集 } } var coverArea = area1 + area2 - areaWhole - coverHoleArea; //重叠面积 if (getPercent) { return { toEntity: coverArea / this.getArea(true), //占entity toPointcloud: coverArea / area2 //占点云 }; } return coverArea; } addHole() { var points = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var prop = { buildType: 'hole', zMin: this.zMin, zMax: this.zMax, points, buildParent: this, ifDraw: this.ifDraw || Potree.settings.drawEntityData }; //hole的zMin zMax跟随buildParent var hole = new BuildingBox(prop); this.holes.push(hole); if (this.buildType == 'building') { //为每一层添加对应的hole this.buildChildren.forEach(floor => { var floorHole = new BuildingBox({ buildType: 'hole', zMin: this.zMin, zMax: this.zMax, buildParent: floor, originHole: hole, //整栋大楼在当层的hole ifDraw: this.ifDraw || Potree.settings.drawEntityData }); floor.parentHoles.push(floorHole); floor.add(floorHole); floorHole.points = hole.points; //完全等于建筑的点 }); } this.add(hole); //直接加在这,不加meshGroup了 this.update(); //update box mesh return hole; //hole不创建box,只有它的buildParent需要更新box。 但有线条和marker. hole不在buildChildren里,但有buildParent } removeHole(hole) { // 这个hole不会是parentHoles里的。 hole.dispose(); if (this.buildType == 'building') { //若是整栋大楼的hole,在每层去除它的对应hole this.buildChildren.forEach(floor => { var holeAtFloor = floor.parentHoles.find(e => e.originHole == this); var index = floor.parentHoles.indexOf(holeAtFloor); index > -1 && floor.parentHoles.splice(index, 1); holeAtFloor.dispose(); }); } var index = this.holes.indexOf(hole); if (index > -1) { this.holes.splice(index, 1); } this.remove(hole); this.update(); } createBox() { var geometry = new Geometry(); this.mats.boxDefault = getFaceMat(this.buildType); this.mats.boxSelected = getFaceMat(this.buildType + 'Select'); var mesh = new Mesh(geometry, this.mats.boxDefault); mesh.name = 'buildingBox'; if (this.buildType == 'floor') { Potree.Utils.setObjectLayers(mesh, 'siteModelMapUnvisi'); //楼层默认在地图不显示,为了不会叠加透明度 //mesh.renderOrder = 1 } else { /* if(this.buildType == 'room'){ mesh.renderOrder = 2 } */ Potree.Utils.setObjectLayers(mesh, 'bothMapAndScene'); } //mesh.frustumCulled = false; return mesh; } addMarker() { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (this.buildType == 'floor') return; //楼层不需要marker var marker = new Sprite$2({ mat: this.getMarkerMaterial('default'), renderOrder: 3, sizeInfo: markerSizeInfo$2, dontFixOrient: true, name: "building_marker" }); Potree.Utils.setObjectLayers(marker, 'siteModeOnlyMapVisi'); o.marker = marker; super.addMarker(o); if (!this.selected) Potree.Utils.updateVisible(marker, 'select', false); var addClickEvent = e => { var click = e => { this.dispatchEvent({ type: 'clickMarker', marker }); //由entity发送给sitemodel统一处理 }; marker.addEventListener('click', click); marker.addEventListener('clickSelect', e => { this.setMarkerSelected(marker, e.state ? 'select' : 'unselect'); }); marker.removeEventListener('addHoverEvent', addClickEvent); }; marker.addEventListener('addHoverEvent', addClickEvent); //当非isNew时才添加事件 if (!this.isNew) { marker.dispatchEvent('addHoverEvent'); } return marker; } removeMarker(index) { super.removeMarker(index); if (!this.isNew) { //重新添加midMarkers this.midMarkers.forEach(e => this.remove(e)); this.midMarkers = []; this.addMidMarkers(); } this.update(); if (this.points.length == 2 && this.box) { //清除原先length>=3时候的 this.box.geometry = new Geometry(); } } addMidMarker(index, point) { if (this.buildType == 'floor') return; //楼层不需要marker var marker = new Sprite$2({ mat: this.getMarkerMaterial('midPrepare'), sizeInfo: markerSizeInfo$2, dontFixOrient: true, name: "building_midMarker" }); this.midMarkers = [...this.midMarkers.slice(0, index), marker, ...this.midMarkers.slice(index, this.midMarkers.length)]; marker.renderOrder = 3; Potree.Utils.setObjectLayers(marker, 'siteModeOnlyMapVisi'); { // Event Listeners var mouseover = e => { this.setMarkerSelected(e.object, 'hover', 'single'); viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "markerMove" }); }; var mouseleave = e => { this.setMarkerSelected(e.object, 'unhover', 'single'); viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "markerMove" }); }; var drag = e => { this.dispatchEvent('startDragging'); var index = this.midMarkers.indexOf(marker); var newMarker = this.addMarker({ index: index + 1, point: marker.position.clone() }); this.addMidMarker(index + 1, new Vector3()); this.updateTwoMidMarker(index + 1); this.setMarkerSelected(marker, 'unhover'); viewer.inputHandler.startDragging(newMarker, {/* dragViewport:viewer.mapViewer.viewports[0], */}); //notPressMouse代表不是通过按下鼠标来拖拽. dragViewport指定了只能在地图上拖拽 }; marker.addEventListener('drag', drag); marker.addEventListener('mouseover', mouseover); marker.addEventListener('mouseleave', mouseleave); } this.add(marker); this.updateMarker(marker, point); if (!this.selected) Potree.Utils.updateVisible(marker, 'select', false); return marker; } addMidMarkers() { //第一次画好所有marker后,一次性为线段增加中点marker var length = this.points.length; this.points.forEach((point, index) => { var nextPoint = this.points[(index + 1) % length]; var midPoint = new Vector3().addVectors(point, nextPoint).multiplyScalar(0.5); this.addMidMarker(index, midPoint); }); } updateTwoMidMarker(index) { //更新第index个marker两边的midMarker if (!this.midMarkers.length) return; var length = this.points.length; var last = this.points[(index - 1 + length) % length]; //它之前的marker位置 var next = this.points[(index + 1) % length]; //它之后的marker位置 var current = this.points[index]; //当前位置 var lastMid = new Vector3().addVectors(last, current).multiplyScalar(0.5); //上一个中点 var nextMid = new Vector3().addVectors(next, current).multiplyScalar(0.5); //下一个中点 var lastMidMarker = this.midMarkers[(index - 1 + length) % length]; var nextMidMarker = this.midMarkers[index]; this.updateMarker(lastMidMarker, lastMid); this.updateMarker(nextMidMarker, nextMid); } dispose() { //销毁geo、remove from parent super.dispose(); this.box && this.box.geometry.dispose(); this.lineMesh && this.lineMesh.geometry.dispose(); this.holes.forEach(e => e.dispose()); this.parentHoles.forEach(e => e.dispose()); //this.buildChildren.forEach(e=>e.dispose()) this.dispatchEvent('dispose'); } updateBox() { if (!this.box) return; this.box.geometry.dispose(); var shrink = this.buildType == 'room' ? 0.11 : this.buildType == 'floor' ? 0.082 : 0.2; //防止mesh重叠冲突(给一个不寻常的数字) 但离远了还是会有点闪烁 if (this.points.length >= 3) { var holes = this.holes.concat(this.parentHoles); var holesPoints = holes.filter(e => e.points.length > 2).map(e => e.points); this.box.geometry = MeshDraw.getExtrudeGeo(this.points, holesPoints, { depth: this.zMax - this.zMin - shrink, UVGenerator: new MetricUVGenerator() }); if (this.buildType == 'building') { this.box.position.z = this.zMin - shrink / 2; } else { this.box.position.z = this.zMin + shrink / 2; } } } update() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super.update(this.buildType != 'floor' && options.ifUpdateMarkers); var length = this.points.length; { //确保一下一样 if (this.originHole) { this.points = this.originHole.points; //完全等于building的hole } if (this.buildType == 'hole') { this.zMin = this.buildParent.zMin; this.zMax = this.buildParent.zMax; } } if (!options.dontUpdateBox) { var boxOwner; if (this.buildType == 'hole') { if (this.buildParent.buildType == 'building') { //若是整栋大楼的hole,在每层都要更新下它的对应hole this.buildParent.buildChildren.forEach(floor => { var holeAtFloor = floor.parentHoles.find(e => e.originHole == this); holeAtFloor && holeAtFloor.update(); //刚开始创建时还没创建对应的 holeAtFloor会为null }); } boxOwner = this.buildParent; } else { boxOwner = this; } boxOwner.updateBox(); } this.updatePrismLines(); //update lines if (!options.dontUpdateChildren) { if (this.buildType == 'building') { this.buildChildren.forEach(floor => { floor.points = this.points; floor.update(); }); } { var holes = this.holes.concat(this.parentHoles); holes.forEach(hole => { hole.update({ dontUpdateBox: true }); //父级更新了box,hole就不需要更新box了 }); } } } getHolesArea() { var holes = this.holes.concat(this.parentHoles); var outHoles, holesArea = 0; if (holes.length >= 2) { //合并holes。如果能在绘制时直接合并holes就好啦,这步就转移到那去,但是要删除hole好麻烦 var holes_ = holes.map(e => e.points); outHoles = math.getPolygonsMixedRings(holes_, true); outHoles.forEach(e => { holesArea += e.area; }); outHoles = outHoles.map(e => e.points); } else { outHoles = holes.map(e => e.points); outHoles.forEach(e => holesArea += Math.abs(math.getArea(e))); } return holesArea; } getArea(ifRidOfHoles) { //面积 //不排除hole return Math.abs(math.getArea(this.points)) - (ifRidOfHoles ? this.getHolesArea() : 0); } getVolume(ifRidOfHoles) { //体积 var { zMin, zMax } = this.getRealZ(); var height = zMax - zMin; if (isNaN(height)) height = 0; return this.getArea(ifRidOfHoles) * height; } getRealZ() { //求真实高度时用到的 var zMin, zMax; if (this.buildType == 'building') { //因为building只有一个地基平面 所以自身的zMin == 自身的zMax 所以要算 var top = this.buildChildren[this.buildChildren.length - 1]; var btm = this.buildChildren[0]; zMin = btm ? btm.zMin : 0; //建好的建筑不加楼的话是0。 zMax = top ? top.zMax : 0; } else if (this.buildType == 'hole') { return this.buildParent.getRealZ(); } else { zMin = this.zMin, zMax = this.zMax; } return { zMin, zMax }; } //架站式多楼层SG-t-ihjV2cDVFlE 有初始的z, 但是总高度范围小于数据集。 不允许修改高度。 /* getDrawZ(){ //画线和box时用到的z let zMin , zMax if(this.buildType == 'hole'){ if(this.buildParent.buildType == 'building' && atFloor){ zMin = atFloor.zMin, zMax = atFloor.zMax }else{ zMin = this.buildParent.zMin, zMax = this.buildParent.zMax } }else{ zMin = this.zMin, zMax = this.zMax } return {zMin, zMax} } */ getBound() { var bound = new Box3(); var { zMin, zMax } = this.getRealZ(); var points = this.buildType == 'floor' ? this.buildParent.points : this.points; points.forEach(p => { bound.expandByPoint(p.clone().setZ(zMin)); bound.expandByPoint(p.clone().setZ(zMax)); }); return bound; } getMarkerMaterial(type) { if (!markerMats$2) { markerMats$2 = { default: new MeshBasicMaterial({ transparent: !0, color: color$2, opacity: 0.8, map: texLoader$9.load(Potree.resourcePath + '/textures/whiteCircle.png'), depthTest: false }), midPrepare: new MeshBasicMaterial({ //线中心的半透明点 transparent: !0, color: color$2, opacity: 0.4, map: texLoader$9.load(Potree.resourcePath + '/textures/whiteCircle.png'), depthTest: false }), hover: new MeshBasicMaterial({ transparent: !0, color: color$2, opacity: 1, map: texLoader$9.load(Potree.resourcePath + '/textures/whiteCircle.png'), depthTest: false }), select: new MeshBasicMaterial({ transparent: !0, color: new Color('#00C8AF'), opacity: 1, map: texLoader$9.load(Potree.resourcePath + '/textures/whiteCircle.png'), depthTest: false }) }; } return markerMats$2[type]; } setMarkerSelected(marker, state, hoverObject) { //console.warn(marker.id , state, hoverObject) if (state == 'select') { marker.selected = true; marker.material = this.getMarkerMaterial('select'); } else if (state == 'unselect') { marker.selected = false; marker.material = this.getMarkerMaterial('default'); } else { if (marker.selected) return; //选中时不允许修改为除了'unselect'以外的状态 if (state == 'hover') { marker.material = this.getMarkerMaterial('hover'); } else if (state == 'unhover') { if (marker.name.includes('mid')) { marker.material = this.getMarkerMaterial('midPrepare'); } else { marker.material = this.getMarkerMaterial('default'); } } } } select() { //最多再显示一层子级的线,如building不会显示room中的hole的线 //box是一直显示的,但会切换材质 /* 选中 box 线 building 自己(底盘)选中 自己, floor不带hole floor 自己选中 自己, room不带hole room 自己选中 自己 */ //注:自己的就代表定包括hole,如果有parentHoles的也(building上的hole的对应) //console.log('select '+this.name, this.selected) if (this.selected) return; if (this.box) { this.box.material = this.mats.boxSelected; } if (this.buildType == 'building' || this.buildType == 'floor') { this.buildChildren.forEach(e => { e.lineMesh.visible = true; }); if (this.buildType == 'floor') { Potree.Utils.setObjectLayers(this.box, 'bothMapAndScene'); Potree.Utils.setObjectLayers(this.buildParent.box, 'siteModelMapUnvisi'); //当选中floor或room时,building在地图不可见 } } else if (this.buildType == 'room') { Potree.Utils.setObjectLayers(this.buildParent.box, 'bothMapAndScene'); Potree.Utils.setObjectLayers(this.buildParent.buildParent.box, 'siteModelMapUnvisi'); } this.lineMesh.visible = true; this.markers && this.markers.forEach(e => Potree.Utils.updateVisible(e, 'select', true)); this.midMarkers && this.midMarkers.forEach(e => Potree.Utils.updateVisible(e, 'select', true)); var holes = this.holes.concat(this.parentHoles); holes.forEach(e => e.select()); this.selected = true; this.dispatchEvent({ type: 'select' }); } unselect() { if (!this.selected) return; //console.log('unselect '+this.name ) if (this.box) { this.box.material = this.mats.boxDefault; } if (this.buildType == 'building' || this.buildType == 'floor') { this.buildChildren.forEach(e => { //(这里要保证选中前要先取消选中,否则如选中房间后取消了楼层,房间线就隐藏了) e.lineMesh.visible = false; }); if (this.buildType == 'floor') { Potree.Utils.setObjectLayers(this.box, 'siteModelMapUnvisi'); Potree.Utils.setObjectLayers(this.buildParent.box, 'bothMapAndScene'); } } else if (this.buildType == 'room') { Potree.Utils.setObjectLayers(this.buildParent.box, 'siteModelMapUnvisi'); Potree.Utils.setObjectLayers(this.buildParent.buildParent.box, 'bothMapAndScene'); } this.lineMesh.visible = false; this.markers && this.markers.forEach(e => Potree.Utils.updateVisible(e, 'select', false)); this.midMarkers && this.midMarkers.forEach(e => Potree.Utils.updateVisible(e, 'select', false)); var holes = this.holes.concat(this.parentHoles); holes.forEach(e => e.unselect()); this.selected = false; this.dispatchEvent({ type: 'unselect' }); } ifContainsPoint(position) { //看它所定义的空间是否包含某个坐标(要排除hole) var { zMin, zMax } = this.getRealZ(); if (position.z < zMin || position.z > zMax) return; var holes = this.holes.concat(this.parentHoles); var holesPoints = holes.filter(e => e != this && e.points.length > 2).map(e => e.points); var inShape = math.isPointInArea(this.points, holesPoints, position); return !!inShape; } } class MetricUVGenerator { constructor() { this.a = new Vector3(), this.b = new Vector3(), this.c = new Vector3(), this.d = new Vector3(); } generateTopUV(t, e, n, r, o) { return [new Vector2(e[3 * n], e[3 * n + 1]), new Vector2(e[3 * r], e[3 * r + 1]), new Vector2(e[3 * o], e[3 * o + 1])]; } generateSideWallUV(t, e, n, r, o, a) { var s = e; this.a.set(s[3 * n], s[3 * n + 1], s[3 * n + 2]), this.b.set(s[3 * r], s[3 * r + 1], s[3 * r + 2]), this.c.set(s[3 * o], s[3 * o + 1], s[3 * o + 2]), this.d.set(s[3 * a], s[3 * a + 1], s[3 * a + 2]); var c = this.a.x !== this.b.x, l = c ? this.b : this.d, u = this.a.distanceTo(l), d = l.distanceTo(this.c); return [new Vector2(this.a.x, 0), c ? new Vector2(this.a.x + u, 0) : new Vector2(this.a.x, d), new Vector2(this.a.x + u, d), c ? new Vector2(this.a.x, d) : new Vector2(this.a.x + u, 0)]; } } var minFloorHeight = 0.5; var ifDrawDatasetBound = true; //显示一下数据集的tightBound线框 var minMarkers = 3; var Limit = { zMin: -config$1.map.cameraHeight, zMax: config$1.map.cameraHeight }; //不能超过camera的高度,为了对称所以也限制了最低 var SiteModel = { bus: new EventDispatcher(), entities: [], //所有实体 buildings: [], //所有建筑父集 meshGroup: new Object3D(), inEntity: null, lastPos: new Vector3(Infinity, Infinity, Infinity), init: function init() { viewer.scene.scene.add(this.meshGroup); this.meshGroup.name = 'siteModel'; this.SplitScreen = SplitScreen4Views; if (Potree.settings.editType == 'pano') { return; } this.createHeightPull(); this.history = new History({ applyData: data => { if (data.entity.parent && data.entity.selected) { data = Potree.Common.CloneObject(data); //避免使用后更改数据又被使用 data.entity.reDraw(); data.entity.initData(data); data.isNew || data.entity.addMidMarkers(); data.entity.isNew = data.isNew; data.entity.dispatchEvent('changeByHistory'); return true; } }, getData: entity => { //if(entity.isNew)return return { entity, points: entity.points.map(e => e.clone()), ifDraw: true, isNew: entity.isNew }; } }); if (Potree.settings.isTest && ifDrawDatasetBound) { viewer.addEventListener('allLoaded', () => { viewer.scene.pointclouds.forEach(pointcloud => { var boxPoints = pointcloud.getUnrotBoundPoint(); var boundingBox = new BuildingBox({ name: '数据集tightBound_' + pointcloud.dataset_id, points: boxPoints, buildType: 'dataset', zMax: pointcloud.bound.max.z, zMin: pointcloud.bound.min.z, ifDraw: true }); this.meshGroup.add(boundingBox); //boundingBox.markers.forEach(e=>e.visible = false) }); }); } if (Potree.settings.isOfficial) { viewer.addEventListener('camera_changed', e => { if (e.changeInfo && e.changeInfo.positionChanged) { this.updateEntityAt(); } }); } { var pressDelete = e => { if (e.keyCode == KeyCodes.BACKSPACE || e.keyCode == KeyCodes.DELETE) { if (this.selectedMarker) { var entity = this.selectedMarker.parent; var index = entity.markers.indexOf(this.selectedMarker); entity.removeMarker(index); if (entity.points.length < 2) { //删到只剩一个点时重新画(如果是hole的点,直接删除hole吧?) this.startInsertion('resume', entity); } } } }; viewer.inputHandler.addEventListener('keydown', pressDelete); } { var updated = false; this.bus.addEventListener('updated', () => { Common.intervalTool.isWaiting('siteModelUpdated', () => { this.changedCallback(); }, 500); }); } }, changedCallback() { this.findPanos(); this.findEntityForDataset(); this.updateEntityAt(true); //更新所在建筑,更新marker显示 //console.log('changedCallback') }, updateEntityAt(force) { var { measure } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; //if(!this.entities.length || this.editing) return //编辑时也要根据位置显示不同楼层的漫游点与cad var fun = () => { //延时update,防止卡顿 var currPos = viewer.mainViewport.view.position; if (this.pauseUpdateEntity) return; // console.error('pauseUpdateEntity') //if(force || !currPos.equals(this.lastPos) ){ //console.log('currPos ', currPos.toArray()) this.lastPos.copy(currPos); var entity; if (measure) { //因为测量线的点可能在多个房间,所以干脆直接找在哪个楼层 var list = []; measure.points.forEach(e => { var entity = this.pointInWhichEntity(e, 'floor'); //每个点都找到其所在楼层 var item = list.find(e => e.entity == entity); if (item) { item.count++; } else { list.push({ entity, count: 1 }); } }); list.sort((a, b) => { return b.count - a.count; }); //找出出现次数最多的楼层 if (list[0]) { entity = list[0].entity; } } else { var searchPos = Potree.settings.displayMode == 'showPanos' ? viewer.images360.currentPano : currPos; entity = this.pointInWhichEntity(searchPos, 'room'); } if (force || this.inEntity != entity) { var oldEntity = this.inEntity; this.inEntity = entity; //console.log('buildingChange', entity) this.bus.dispatchEvent({ type: 'buildingChange', entity }); //this.updatePanosVisible(oldEntity, this.inEntity) var lastFloor = this.currentFloor; //oldEntity ? oldEntity.buildType == 'floor' ? oldEntity : oldEntity.buildType == 'room' ? oldEntity.buildParent : null : null; //基本只会是floor或room var currentFloor = entity ? entity.buildType == 'floor' ? entity : entity.buildType == 'room' ? entity.buildParent : null : null; //基本只会是floor或room if (force || currentFloor != lastFloor) { //console.log('改变了floor',lastFloor,currentFloor) this.currentFloor = currentFloor; this.bus.dispatchEvent({ type: 'FloorChange', currentFloor }); } } force = false; //} }; if (force) fun();else Common.intervalTool.isWaiting('sitemodelCameraInterval', fun, 500); }, enter: function enter() { Potree.Log('sitemodel enter'); this.clear(); //确保全部清空 this.editing = true; //this.updatePanosVisible(null, null, true)//show all viewer.updateFpVisiDatasets(); var mapViewport = viewer.mapViewer.viewports[0]; this.SplitScreen.split({ siteModel: true /* , viewports:[{name:'Top',viewport : mapViewport }] */ }); viewer.viewports.forEach(e => { if (e.name != 'mapViewport') { e.layersAdd('siteModelMapUnvisi'); } if (e.name == 'right' || e.name == 'back') { e.layersAdd('siteModeSideVisi'); } }); viewer.images360.panos.forEach(pano => { Potree.Utils.setObjectLayers(pano.marker, 'siteModelMapUnvisi'); //Potree.Utils.setObjectLayers(pano.label2, 'bothMapAndScene') }); mapViewport.layersAdd('siteModeOnlyMapVisi'); //只有mapViewport能看到marker }, leave: function leave() { Potree.Log('sitemodel leave'); var mapViewport = viewer.mapViewer.viewports[0]; this.SplitScreen.recover(); viewer.viewports.forEach(e => { if (e.name != 'mapViewport') { e.layersRemove('siteModelMapUnvisi'); } if (e.name == 'right' || e.name == 'back') { e.layersRemove('siteModeSideVisi'); } }); viewer.images360.panos.forEach(pano => { Potree.Utils.setObjectLayers(pano.marker, 'sceneObjects'); //Potree.Utils.setObjectLayers(pano.label2, 'bothMapAndScene') }); mapViewport.layersRemove('siteModeOnlyMapVisi'); this.clear(); this.editing = false; this.updateEntityAt(true); viewer.updateFpVisiDatasets(); }, addFloor: function addFloor(parent, dirType, sid, name) { //dirType:'top'|'bottom'在上方建还是下方。如果建筑中没有楼层,默认在基底建一个 var buildType = 'floor'; var zMin, zMax; if (parent.buildChildren.length == 0) { zMin = parent.zMin; zMax = zMin + Potree.config.siteModel.floorHeightDefault; } else { if (dirType == 'bottom') { //var btm = Common.find(parent.buildChildren,null,[e=>e.zMin]) var btm = parent.buildChildren[0]; zMax = btm.zMin; zMin = zMax - Potree.config.siteModel.floorHeightDefault; } else { //var top = Common.find(parent.buildChildren,null,[e=>e.zMax]) var top = parent.buildChildren[parent.buildChildren.length - 1]; zMin = top.zMax; zMax = zMin + Potree.config.siteModel.floorHeightDefault; } } var prop = { buildType, //name : Potree.config.siteModel.names[buildType], zMin, zMax, buildParent: parent, sid, name, ifDraw: true }; var floor = new BuildingBox(prop); /* parent.buildChildren.push(floor) this.meshGroup.add(floor); this.entities.push(floor) */ floor.update(); this.addEntity(floor, parent); //this.selectEntity(floor) if (this.selected == parent) { //重新选择下,为了显示新楼层线框 parent.unselect(); parent.select(); } this.bus.dispatchEvent('updated'); return floor; }, startInsertion: function startInsertion(buildType, parent, sid, name, callback, cancelFun) { var _this = this; var zMin, zMax, entity, resume; var mapViewport = viewer.mapViewer.viewports[0]; if (buildType == 'resume') { //继续画(使用最后一个点或者新加的点) resume = true; entity = parent; buildType = parent.buildType; //删除原先所有的点,因为它们已经添加了事件,会很麻烦: entity.reDraw(0); entity.isNew = true; //当作新的来画 } if (!resume) { if (buildType == 'hole' || buildType == 'room') { zMin = parent.zMin; zMax = parent.zMax; } else if (buildType == 'building') { parent = null; zMin = viewer.bound.boundingBox.min.z; zMax = viewer.bound.boundingBox.min.z; } if (buildType == 'hole') { entity = parent.addHole(); entity.isNew = true; this.selectEntity(parent); entity.select(); console.log('挖洞 ', entity.uuid); } else { var prop = { buildType, //name : Potree.config.siteModel.names[buildType],//'building', zMin, zMax, buildParent: parent, sid, name, ifDraw: true }; entity = new BuildingBox(prop); entity.isNew = true; this.selectEntity(entity); } this.addEntity(entity, parent); } var timer; var endDragFun = e => { if (e.button == MOUSE.LEFT) { this.history.beforeChange(entity); var marker = entity.addMarker({ point: entity.points[entity.points.length - 1].clone() }); this.history.afterChange(entity); //entity.editStateChange(true) //重新激活reticule状态 entity.continueDrag(marker, e); } else if (e.button === MOUSE.RIGHT) { if (e.pressDistance < Potree.config.clickMaxDragDis) end(e); //非拖拽的话 else entity.continueDrag(null, e /* .drag.object */); } }; var finish = () => { //结束绘画 viewer.removeEventListener('cancel_insertions', Exit); entity.removeEventListener('unselect', Exit); clearTimeout(timer); entity.editStateChange(false); //pressExit && viewer.inputHandler.removeEventListener('keydown', pressExit); callback && callback(entity); viewer.dispatchEvent('endBuildEntity'); }; var end = function end() { var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; //尝试结束 /* 退出的三种形式: 1 普通:如果大于三个marker,结束且保留;否则重新画。() 2 删除:直接结束且删除。(remove) 3 结束:如果大于三个marker,结束且保留;否则结束且删除。 (finish) 4 保留:无论几个marker,都保留着,结束。(remain) */ if (e.remove) { finish(); return _this.removeEntity(entity); } if (!e.remain && !e.finish && !e.remove && entity.markers.length <= minMarkers) { //右键 当个数不够时取消 //重新开始画 entity.reDraw(1); Potree.Utils.updateVisible(entity.markers[0], 'unMove', false); var f = () => { Potree.Utils.updateVisible(entity.markers[0], 'unMove', true); entity.removeEventListener('dragChange', f); }; entity.addEventListener('dragChange', f); //console.log('waitcontinue') entity.continueDrag(entity.markers[0], e); return; } finish(); if (e.remain || !e.remove && entity.markers.length > 3) { //保留 entity.removeMarker(entity.points.length - 1); entity.markers.forEach(marker => { marker.dispatchEvent('addHoverEvent'); }); if (buildType == 'room') { _this.fitPullBox(); } entity.isNew = false; entity.addMidMarkers(); var boundingBox = entity.getBound(); var center = boundingBox.getCenter(new Vector3()); viewer.controls.setTarget(center, 2); } else { _this.removeEntity(entity); //直接删除没画好的,比较简单。这样就不用担心旧的continueDrag仍旧触发了 } return entity; }; var Exit = e => { //强制结束 entity.removeEventListener('unselect', Exit); if (viewer.inputHandler.drag) { //还未触发drop的话 viewer.inputHandler.drag.object.dispatchEvent({ type: 'drop', drag: viewer.inputHandler.drag, viewer: viewer, pressDistance: 0, button: MOUSE.RIGHT }); viewer.inputHandler.drag.object.isDragging = false; } else { end({ remain: true }); } viewer.inputHandler.drag = null; }; viewer.dispatchEvent('cancel_insertions'); //取消之前的 viewer.addEventListener('cancel_insertions', Exit); setTimeout(() => { entity.isNew && entity.addEventListener('unselect', Exit); }, 1); //因为刚创建会unselect一下所以延迟 var marker = entity.addMarker({ point: new Vector3(0, 0, 0) }); Potree.Utils.updateVisible(marker, 'unMove', false); //这时候的位置是假的(0,0,0)所以先不可见 var f = () => { Potree.Utils.updateVisible(marker, 'unMove', true); entity.removeEventListener('dragChange', f); }; entity.addEventListener('dragChange', f); marker.isDragging = true; viewer.inputHandler.startDragging(marker, { dragViewport: mapViewport, endDragFun, notPressMouse: true }); //notPressMouse代表不是通过按下鼠标来拖拽. dragViewport指定了只能在地图上拖拽 viewer.dispatchEvent('startBuildEntity'); var changeByHistory = e => { if (!entity.isNew) return; var marker = entity.markers[entity.points.length - 1]; viewer.inputHandler.startDragging(marker, { dragViewport: mapViewport, endDragFun, notPressMouse: true }); var I = viewer.inputHandler.intersect && (viewer.inputHandler.intersect.orthoIntersect || viewer.inputHandler.intersect.location); if (I) { entity.dragChange(I.clone(), entity.points.length - 1); //使最后一个点在鼠标处 } }; entity.addEventListener('changeByHistory', changeByHistory); return entity; }, getPreDealData(points, zMin, zMax, initial, buildType, parent) { /* if( buildType == 'building' ){ zMax = zMin //强制变得一样,作为基底。如果有必要,保存时再算真实的zMax。目前zMin没有保存所以数据是错的,会直接根据floor计算 } */ var bound = viewer.bound.boundingBox; if (buildType == 'building' && initial) { //初始数据错的,要自己建(只有一个building和floor) 原posIsLonlat console.log('空间模型未编辑过, 初始化了一个'); points = [new Vector3(bound.min.x, bound.min.y, 0), new Vector3(bound.max.x, bound.min.y, 0), new Vector3(bound.max.x, bound.max.y, 0), new Vector3(bound.min.x, bound.max.y, 0)]; zMin = bound.min.z; zMax = bound.max.z; /* points = points.map(e=>{ return viewer.transform.lonlatToLocal.forward(e) }) */ } else { //相对于初始数据集的模型内坐标 points = points.map(e => this.transform(e, 'fromDataset')); if (buildType == 'floor' && initial) { zMin = bound.min.z; zMax = bound.max.z; } } return { points, zMax, zMin }; }, resetFromData: function resetFromData(entity) { var _this2 = this; var points = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var holes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; var zMin = arguments.length > 3 ? arguments[3] : undefined; var zMax = arguments.length > 4 ? arguments[4] : undefined; return function (points, zMin, zMax) { var { points, zMax, zMin } = _this2.getPreDealData(points, zMin, zMax, _this2.autoBuild, entity.buildType, entity.buildParent); if (entity.buildType != 'floor') entity.points = points; if (entity.buildType == 'room') { entity.zMin = zMin; entity.zMax = zMax; } else if (entity.buildType == 'floor') { //改楼高 var height = zMax - zMin; var zMax2 = entity.zMin + height; SiteModel.changeZ(entity, 'zMax', zMax2); } { //删除旧的holes重新添加 var holesOld = entity.holes; holesOld.forEach(e => { entity.removeHole(e); }); holes.forEach(points => { var ps = points.map(e => _this2.transform(e, 'fromDataset')); var hole = entity.addHole(ps); hole.addMidMarkers(); }); } entity.update(); return entity; }(points, zMin, zMax); }, createFromData: function createFromData(buildType, parent, sid, name) { var _this3 = this; var points = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : []; var holes = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : []; var zMin = arguments.length > 6 ? arguments[6] : undefined; var zMax = arguments.length > 7 ? arguments[7] : undefined; var initial = arguments.length > 8 ? arguments[8] : undefined; var panos_ = arguments.length > 9 ? arguments[9] : undefined; var flagPano = arguments.length > 10 ? arguments[10] : undefined; return function (points, zMin, zMax) { if (buildType != 'building' && buildType != 'floor' && buildType != 'room') return; var { points, zMax, zMin } = _this3.getPreDealData(points, zMin, zMax, initial, buildType, parent); var panos = []; { if (panos_) { panos_.forEach(sid => { var pano = viewer.images360.getPano(sid, 'sid'); if (pano) panos.push(pano); }); } flagPano = flagPano != void 0 ? viewer.images360.getPano(flagPano, 'sid') : null; //最中心的pano 或者 最靠近该实体的pano(当panos为空时) if (!_this3.editing && buildType == 'floor' && !flagPano) { //没有的话可能是自动添加的floor,直接用parent的吧 panos = parent.panos; flagPano = parent.flagPano; } } var prop = { buildType, points, name, sid, zMin, zMax, buildParent: parent, ifDraw: _this3.editing || Potree.settings.drawEntityData, panos, flagPano, autoBuild: initial }; var entity = new BuildingBox(prop); SiteModel.addEntity(entity, parent); if (_this3.editing) { if (buildType == 'building' || buildType == 'room') { entity.addMidMarkers(); } } holes.forEach(points => { var ps = points.map(e => _this3.transform(e, 'fromDataset')); var hole = entity.addHole(ps); _this3.editing && hole.addMidMarkers(); }); /* if(buildType == 'floor'){ this.updateBuildingZ(parent) } */ return entity; }(points, zMin, zMax); }, transform: function transform(pos, type) { if (Potree.settings.editType == 'pano') { // 模型不经转换 return new Vector3().copy(pos).setZ(0); } if (type == 'toDataset') { var point = Potree.Utils.datasetPosTransform({ toDataset: true, position: pos.clone(), datasetId: Potree.settings.originDatasetId }); return new Vector2().copy(point); } else { var position = new Vector3().copy(pos).setZ(0); return Potree.Utils.datasetPosTransform({ fromDataset: true, position, datasetId: Potree.settings.originDatasetId }); } }, addEntity: function addEntity(entity, parent) { if (entity.buildType != 'hole') { this.meshGroup.add(entity); this.entities.push(entity); if (entity.buildType == 'building') { this.buildings.push(entity); } else { parent.buildChildren.push(entity); } } if (entity.buildType == 'room') { entity.addEventListener('marker_dropped', () => { this.fitPullBox(); }); } else if (entity.buildType == 'floor') { this.updateBuildingZ(parent); parent.dispatchEvent({ type: 'addFloor' }); } { //仅能存在一个marker被选中。选中的点可以被删除 entity.addEventListener('clickMarker', e => { if (this.selectedMarker == e.marker) { this.selectedMarker.dispatchEvent({ type: 'clickSelect', state: false }); this.selectedMarker = null; } else { if (this.selectedMarker) { this.selectedMarker.dispatchEvent({ type: 'clickSelect', state: false }); } this.selectedMarker = e.marker; this.selectedMarker.dispatchEvent({ type: 'clickSelect', state: true }); } }); entity.addEventListener('removeMarker', e => { if (this.selectedMarker == e.marker) { this.selectedMarker = null; } }); var unselect = e => { //取消选中实体或删除后 if (this.selectedMarker && entity.markers.includes(this.selectedMarker)) { this.selectedMarker.dispatchEvent({ type: 'clickSelect', state: false }); this.selectedMarker = null; } }; entity.addEventListener('dispose', unselect); entity.addEventListener('unselect', unselect); } //console.log('添加实体:', entity.buildType, entity.sid, entity.uuid) this.bus.dispatchEvent('updated'); entity.addEventListener('startDragging', () => { this.history.beforeChange(entity); }); entity.addEventListener('marker_dropped', () => { this.bus.dispatchEvent('updated'); this.history.afterChange(entity); }); }, removeEntity: function removeEntity(entity) { if (!this.entities.includes(entity)) return; console.log('删除实体:', entity.buildType, entity.sid); if (this.selected == entity) { this.height_pull_box && (this.height_pull_box.visible = false); this.selectEntity(null); } if (entity.buildType == 'building') { var index = this.buildings.indexOf(entity); if (index > -1) { this.buildings.splice(index, 1); } } else { var index = entity.buildParent.buildChildren.indexOf(entity); if (index > -1) { entity.buildParent.buildChildren.splice(index, 1); if (entity.buildType == 'floor' && index == 0) { this.updateBuildingZ(entity.buildParent); } } } var index = this.entities.indexOf(entity); if (index > -1) { this.entities.splice(index, 1); } entity.dispose(); var buildChildren = entity.buildChildren.slice(); buildChildren.forEach(e => this.removeEntity(e)); this.bus.dispatchEvent('updated'); }, updateBuildingZ: function updateBuildingZ(building) { building.buildChildren = building.buildChildren.sort((e, a) => e.zMin - a.zMin); //从低到高排序 building.buildChildren[0] && (building.zMin = building.zMax = building.buildChildren[0].zMin); //基底高度 //building.zMax = building.buildChildren[building.buildChildren.length-1].zMax if (this.editing) building.update({ dontUpdateChildren: true }); building.dispatchEvent('updateBuildingZ'); }, selectEntity: function selectEntity(entity) { var state = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; viewer.dispatchEvent('content_changed'); if (state === false) { entity.unselect(); if (this.selected == entity) this.selected = null; viewer.controls.setTarget(null, 2); return; } if (this.selected == entity || entity && entity.buildType == 'hole') return; //this.buildings.forEach(e=>e.unselect()) this.selected && this.selected.unselect(); this.height_pull_box && (this.height_pull_box.visible = false); if (entity) { entity.select(); if (!entity.isNew) { var boundingBox = entity.getBound(); var center = boundingBox.getCenter(new Vector3()); //中心点不一定在entity中,比如半环形建筑(所以要不要改成到漫游点呢) viewer.controls.setTarget(center, 2); } } else { viewer.controls.setTarget(null, 2); } this.selected = entity; if (entity && !entity.dontDragFloorHeight && (entity.buildType == 'floor' || entity.buildType == 'room')) { this.height_pull_box && (this.height_pull_box.visible = true); this.fitPullBox(); } if (entity && !entity.isNew && (entity.buildType == 'building' || entity.buildType == 'room') && entity.points.length < 2) { this.startInsertion('resume', entity); //继续画 } }, fitPullBox: function fitPullBox() { //自适应拖拽楼层的pullMesh if (!this.height_pull_box || !this.selected || this.selected.buildType != 'floor' && this.selected.buildType != 'room') return; var bound = new Box3(); bound.expandByObject(this.selected.box); var center = bound.getCenter(new Vector3()); var size = bound.getSize(new Vector3()); this.height_pull_box.scale.copy(size); this.height_pull_box.position.copy(center); }, changeZ: function changeZ(entity, dirType, value) { // floor or room 修改zMin or zMax var max, min; //limit if (entity.buildType == 'floor') { //楼层 var index = entity.buildParent.buildChildren.indexOf(entity); if (dirType == 'zMax') { var upper = entity.buildParent.buildChildren[index + 1]; entity.zMax = Math.min(Limit.zMax, value); min = entity.zMin + minFloorHeight; if (entity.zMax < min) { entity.zMax = min; } else { if (upper) { max = upper.zMax - minFloorHeight; if (entity.zMax > max) { entity.zMax = max; } } } if (upper) { upper.zMin = entity.zMax; upper.update(); upper.dispatchEvent({ type: 'changeHeight' }); } } else { var lower = entity.buildParent.buildChildren[index - 1]; entity.zMin = Math.max(Limit.zMin, value); max = entity.zMax - minFloorHeight; if (entity.zMin > max) { entity.zMin = max; } else { if (lower) { min = lower.zMin + minFloorHeight; if (entity.zMin < min) { entity.zMin = min; } } } if (lower) { lower.zMax = entity.zMin; lower.update(); lower.dispatchEvent({ type: 'changeHeight' }); } if (index == 0) this.updateBuildingZ(entity.buildParent); } } else if (entity.buildType == 'room') { //房间 //按照navvis的是不一定限制在当前楼层,只要高度不超过当前楼层即可。 var maxHeight = entity.buildParent.zMax - entity.buildParent.zMin; if (dirType == 'zMax') { min = entity.zMin + minFloorHeight; max = entity.zMin + maxHeight; entity.zMax = MathUtils.clamp(value, min, max); } else { min = entity.zMax - maxHeight; max = entity.zMax - minFloorHeight; entity.zMin = MathUtils.clamp(value, min, max); } } entity.update(); entity.dispatchEvent({ type: 'changeHeight' }); //this.selected.emit('update') this.fitPullBox(); this.bus.dispatchEvent('updated'); }, createHeightPull: function createHeightPull() { //拖拽楼层的bounding box var boxGeo = new BoxBufferGeometry(1, 1, 1 / 4); var boxMat = new MeshBasicMaterial({ color: "#F00", opacity: 0, transparent: true, depthTest: false, side: 2 }); var height_pull_box_up = new Mesh(boxGeo, boxMat); var height_pull_box_down = new Mesh(boxGeo, boxMat); height_pull_box_up.name = 'height_pull_box_up'; height_pull_box_down.name = 'height_pull_box_down'; this.height_pull_box = new Object3D(); this.height_pull_box.name = 'height_pull_box'; this.height_pull_box.add(height_pull_box_up); this.height_pull_box.add(height_pull_box_down); this.height_pull_box.visible = false; this.meshGroup.add(this.height_pull_box); height_pull_box_up.position.set(0, 0, 1 / 2 /* 3/8 */); height_pull_box_down.position.set(0, 0, -1 / 2 /* -3/8 */); Potree.Utils.setObjectLayers(this.height_pull_box, 'siteModeSideVisi'); var mouseover = e => { viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "siteModelFloorDrag" }); }; var mouseleave = e => { viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "siteModelFloorDrag" }); }; var firstZ, firstIntersect; var drag = e => { var intersect = e.intersect.orthoIntersect; //不要点云的intersect,只要orthocamera算出的平面intersect if (firstIntersect != void 0) { var moveZ = intersect.z - firstIntersect; if (this.selected.buildType == 'floor') { //楼层 //限制高度不能超过上下 if (e.target == height_pull_box_up) { if (firstZ == void 0) firstZ = this.selected.zMax; this.changeZ(this.selected, 'zMax', firstZ + moveZ); } else { if (firstZ == void 0) firstZ = this.selected.zMin; this.changeZ(this.selected, 'zMin', firstZ + moveZ); } } else if (this.selected.buildType == 'room') { //房屋 if (e.target == height_pull_box_up) { if (firstZ == void 0) firstZ = this.selected.zMax; this.changeZ(this.selected, 'zMax', firstZ + moveZ); } else { if (firstZ == void 0) firstZ = this.selected.zMin; this.changeZ(this.selected, 'zMin', firstZ + moveZ); } } } else { firstIntersect = intersect.z; } }; var drop = e => { firstZ = firstIntersect = null; }; height_pull_box_up.addEventListener('mousemove', mouseover); height_pull_box_down.addEventListener('mousemove', mouseover); height_pull_box_up.addEventListener('mouseleave', mouseleave); height_pull_box_down.addEventListener('mouseleave', mouseleave); height_pull_box_up.addEventListener('drag', drag); height_pull_box_down.addEventListener('drag', drag); height_pull_box_up.addEventListener('drop', drop); height_pull_box_down.addEventListener('drop', drop); }, pointInWhichEntity(location, buildType, ifIgnoreHole) { //buildType是要找的建筑类型 //location 可以是pano或者坐标 //由于房间可能在building外,所以房间要另外单独识别。 var lastResult; //最接近的上一层结果,如果没有result返回这个 var result; var level = { building: 0, floor: 1, room: 2 }; var traverse = (parent, buildType) => { //返回第一个符合标准的实体 var contains; if (location instanceof Vector3) { contains = parent.ifContainsPoint(location); } else { //is pano contains = parent.panos.includes(location); } if (contains) { if (!lastResult || level[lastResult.buildType] < level[parent.buildType]) lastResult = parent; if (parent.buildType == buildType) { return parent; } else { for (var i = 0, len = parent.buildChildren.length; i < len; i++) { var result1 = traverse(parent.buildChildren[i]); if (result1) return result1; } } } }; //因为建筑可能重叠,所以需要先找到最接近其中心的建筑物 result = Common.sortByScore(this.buildings, [building => { return traverse(building, 'building'); //在building中 }], [building => { //写法类似pointInWhichPointcloud var boundingBox = building.getBound(); var center = boundingBox.getCenter(new Vector3()); var position = location instanceof Vector3 ? location : location.position; var dis = position.distanceTo(center); var size = boundingBox.getSize(new Vector3()); var length = size.length() / 2; return length / dis; }]); var building = result && result[0] && result[0].score > 1 && result[0].item; if (buildType == 'building' || !building) return building; result = traverse(building, buildType); /* if(!result && buildType == 'room'){//如果要找的是room, 且按刚才的顺序找不到的话,就单独从所有rooms中找一遍。因为room可能不在floor和building内。 let rooms = this.entities.filter(e=>e.buildType == 'room'); result = rooms.find(e=>e.ifContainsPoint(position)) }*/ //虽然房间可以画到上级之外,但是为了方便起见,假定房间绝对在楼层之内。找不到的话要调整空间模型了。 return result || lastResult; }, findPanos: function findPanos() { { this.entities.forEach(entity => { //清空: entity.panos = []; entity.flagPano = null; viewer.images360.panos.forEach(pano => { if (entity.ifContainsPoint(pano.position)) { entity.panos.push(pano); } }); }); } /* viewer.images360.panos.forEach(pano=>{ //一个漫游点只对应一个实体的话 let result = this.pointInWhichEntity(pano.position, 'room'); {//get panos for every entities let entity = result while(entity){ entity.panos.push(pano); entity = entity.buildParent } } }) */ { //search center pano this.entities.forEach(entity => { var panos = entity.panos; if (panos.length == 0) return; var bound = entity.getBound(); var center = bound.getCenter(new Vector3()); var request = []; var rank = [Images360.scoreFunctions.distanceSquared({ position: center })]; //let panos = entity.panos && entity.panos.length ? entity.panos : viewer.images360.panos //entity没有panos的话,就扩大到所有panos var r = Common.sortByScore(panos, request, rank); if (r && r.length) { entity.flagPano = r[0].item; } else { console.error('no flagPano??'); } }); } }, findEntityForDataset: function findEntityForDataset() { //为每一个数据集寻找它所属的最小实体 /* var entities = this.entities.filter(e=>e.buildType == 'room' || e.buildType == 'floor' && e.buildChildren.length == 0) viewer.scene.pointclouds.forEach(pointcloud=>{ let cloudVolume = pointcloud.getVolume() let scores = [] entities.forEach(entity=>{ let volume = entity.intersectPointcloudVolume(pointcloud) //注:默认已经findPanos过 let panos = entity.panos.filter(e=>pointcloud.panos.includes(e)); let panoCount = panos.length let score = volume / cloudVolume + panoCount / pointcloud.panos.length scores.push({entity, volume, panoCount, score}) }) scores.sort((a,b)=>{ return b.score-a.score }) if(scores.length == 0 || scores[0].volume/cloudVolume < 0.0001 && scores[0].volume < 3 ){//如果约等于0 pointcloud.belongToEntity = null }else{ pointcloud.belongToEntity = scores[0].entity; } }) */ var getScores = (pointcloud, entities, cloudVolume) => { var scores = []; entities.forEach(entity => { var volume = entity.intersectPointcloudVolume(pointcloud); //注:默认已经findPanos过 var panos = entity.panos.filter(e => pointcloud.panos.includes(e)); var panoCount = panos.length; var score = volume / cloudVolume; if (pointcloud.panos.length > 0) { score += panoCount / pointcloud.panos.length; } else { //score += 1 } scores.push({ entity, volume, panoCount, score }); }); scores.sort((a, b) => { return b.score - a.score; }); return scores; }; viewer.scene.pointclouds.forEach(pointcloud => { //先判断父级,如果父集不通过就不判断子级。 var cloudVolume = pointcloud.getVolume(); var entities = this.buildings; while (1) { var scores = getScores(pointcloud, entities, cloudVolume); if (scores.length == 0 || scores[0].volume / cloudVolume < 0.0001 && scores[0].volume < 3) { //如果约等于0 if (scores[0] && scores[0].entity.buildType == 'room') { pointcloud.belongToEntity = scores[0].entity; //当该数据集在楼层中,但不在楼层中的任意一个房间时,任意挂载在其中一个房间上。 break; } pointcloud.belongToEntity = null; break; } else { entities = scores[0].entity.buildChildren; if (entities.length == 0) { pointcloud.belongToEntity = scores[0].entity; break; } } } }); /* 旧版: 只需要考虑 floor 和 room, 因为building的只有一个基底没高度 floor 和 room 在空间中没有完全的从属关系,因为room可以超出floor之外。所以直接混在一起来查找,但要排除有房间的楼层。 (现在改为层层递进查找,否则数据集包含entity多的,会直接挂载到体积最大的房间里,即使看起来主体点云并不在该房间) 有的数据集虽然很高,但只有近地面的部分才是主体,这部分一般含有全部漫游点。为了防止上层的实体因体积较大而分数高,就把包含漫游点的个数也加入考虑。 重叠体积大、且包含漫游点最多的最小实体将会拥有该点云。 期望: 最好不挂载到最小子级,因为现在有房间都到房间里了。 */ }, clear: function clear() { //清空 /* entities:[], //所有实体 buildings:[], //所有建筑父集 meshGroup: new THREE.Object3D, */ this.selectEntity(null); var length = this.entities.length; for (var i = 0; i < length; i++) { this.entities[i].dispose(); } this.entities = []; this.buildings = []; this.inEntity = null; }, gotoEntity(id, isNearBy) { var duration = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1000; var entity = this.entities.find(e => e.sid == id); var aimPano; if (!entity) { return console.error('没找到entity '); } if (Potree.settings.displayMode == 'showPanos') { if (isNearBy && entity.panos.length) { if (entity.panos.includes(viewer.images360.currentPano)) return 'posNoChange'; //已在当前实体中 var position = viewer.scene.getActiveCamera().position; var request = []; var rank = [Images360.scoreFunctions.distanceSquared({ position })]; var r = Common.sortByScore(entity.panos, request, rank); aimPano = r[0].item; } else { if (!entity.flagPano) { return console.log('没有flagPano'); } aimPano = entity.flagPano; } if (aimPano == viewer.images360.currentPano) return 'posNoChange'; viewer.images360.flyToPano(aimPano); } else { if (isNearBy && entity.ifContainsPoint(viewer.images360.position)) { return 'posNoChange'; //已在当前实体中 } var boundingBox = entity.getBound(); var _position = boundingBox.getCenter(new Vector3()); //中心点不一定在entity中,比如半环形建筑(所以要不要改成到漫游点呢) var size = boundingBox.getSize(new Vector3()); if (viewer.modules.Clip && viewer.modules.Clip.editing) { viewer.modules.Clip.bus.dispatchEvent({ type: 'flyToPos', position: _position }); } else { if (math.closeTo(_position, viewer.images360.position)) return 'posNoChange'; viewer.scene.view.setView({ position: _position, duration }); } viewer.mapViewer.moveTo(_position, size, duration); } return true; }, focusEntity(id) { var entity = this.entities.find(e => e.sid == id); var boundingBox = entity.getBound(); //let boundSize = boundingBox.getSize(new THREE.Vector3()) var center = boundingBox.getCenter(new Vector3()); this.SplitScreen.focusOnObject(boundingBox, center); this.gotoEntity(id, false, 0); }, removeIlligalArchi() { //删除marker数量小于3个的建筑,当保存时 var needDelete = []; this.entities.forEach(e => { if (e.points.length < 3) { needDelete.push(e); } }); needDelete.forEach(e => this.removeEntity(e)); } }; // Author: Fyrestar https://mevedia.com (https://github.com/Fyrestar/THREE.InfiniteGridHelper) class InfiniteGridHelper extends Mesh { constructor(size1, size2, color, distance) { var opacity1 = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0.2; var opacity2 = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 1; color = color || new Color('white'); size1 = size1 || 10; size2 = size2 || 100; distance = distance || 8000; //可视距离?越远越模糊 var geometry = new PlaneBufferGeometry(2, 2, 1, 1); var material = new ShaderMaterial({ side: DoubleSide, uniforms: { uSize1: { value: size1 }, uSize2: { value: size2 }, opacity1: { //线条1的 小格子 value: opacity1 }, opacity2: { //线条2的 value: opacity2 }, uColor: { value: color }, uDistance: { value: distance } }, transparent: true, vertexShader: "\n \n varying vec3 worldPosition;\n \n uniform float uDistance;\n \n void main() {\n \n vec3 pos = position.xyz * uDistance;\n pos.xy += cameraPosition.xy;\n \n worldPosition = pos;\n \n gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);\n \n }\n ", fragmentShader: "\n \n varying vec3 worldPosition;\n \n uniform float uSize1;\n uniform float uSize2;\n uniform float opacity1;\n uniform float opacity2;\n uniform vec3 uColor;\n uniform float uDistance;\n \n \n \n float getGrid(float size) {\n \n vec2 r = worldPosition.xy / size;\n \n \n vec2 grid = abs(fract(r - 0.5) - 0.5) / fwidth(r);\n float line = min(grid.x, grid.y);\n \n \n return 1.0 - min(line, 1.0);\n }\n //\u4E3A\u4F55\u4FA7\u9762\u770B\u4E0D\u5230\u7EBF\uFF0C\u56E0\u4E3Amesh\u7684\u6B63\u4FA7\u9762\u90FD\u770B\u4E0D\u5230\uFF1F\n\n void main() {\n \n \n float d = 1.0 - min(distance(cameraPosition.xy, worldPosition.xy) / uDistance, 1.0);\n \n float g1 = getGrid(uSize1);\n float g2 = getGrid(uSize2);\n \n \n gl_FragColor = vec4(uColor.rgb, mix(g2, g1, g1) * pow(d, 3.0));\n //gl_FragColor.a = mix(0.5 * gl_FragColor.a, gl_FragColor.a, g2);\n gl_FragColor.a = mix(opacity1 * gl_FragColor.a, opacity2 * gl_FragColor.a, g2);\n \n \n if ( gl_FragColor.a <= 0.0 ) discard;\n \n \n }\n \n ", extensions: { derivatives: true } }); super(geometry, material); this.frustumCulled = false; } } ; /* THREE.InfiniteGridHelper.prototype = { ...THREE.Mesh.prototype, ...THREE.Object3D.prototype, ...THREE.EventDispatcher.prototype }; */ var TransformControls = function TransformControls(camera, domElement, options) { if (domElement === undefined) { console.warn('THREE.TransformControls: The second parameter "domElement" is now mandatory.'); domElement = document; } Object3D.call(this); Potree.Utils.updateVisible(this, 'attach', false); this.domElement = domElement; var _gizmo = new TransformControlsGizmo(options); this.add(_gizmo); this._gizmo = _gizmo; var _plane = new TransformControlsPlane(options); this.add(_plane); /* this.linesAssistance = new TransformControlsLines(options); //水平 垂直 辅助 this.add( this.linesAssistance ); */ var scope = this; //this.player = options.player;//xzw add this.options = options; //xzw add // Define properties with getters/setter // Setting the defined property will automatically trigger change event // Defined properties are passed down to gizmo and plane defineProperty("camera", camera); defineProperty("object", undefined); defineProperty("enabled", true); defineProperty("axis", null); defineProperty("mode", "translate"); defineProperty("translationSnap", null); defineProperty("rotationSnap", null); defineProperty("scaleSnap", null); defineProperty("space", "world"); defineProperty("size", 1); defineProperty("dragging", false); defineProperty("showX", true); defineProperty("showY", true); defineProperty("showZ", true); var changeEvent = { type: "change" }; var mouseDownEvent = { type: "mouseDown" }; var mouseUpEvent = { type: "mouseUp", mode: scope.mode }; var objectChangeEvent = { type: "objectChange" }; // Reusable utility variables var ray = new Raycaster(); var _tempVector = new Vector3(); var _tempVector2 = new Vector3(); var _tempQuaternion = new Quaternion(); var _unit = { X: new Vector3(1, 0, 0), Y: new Vector3(0, 1, 0), Z: new Vector3(0, 0, 1) }; var pointStart = new Vector3(); var pointEnd = new Vector3(); var offset = new Vector3(); var rotationAxis = new Vector3(); var startNorm = new Vector3(); var endNorm = new Vector3(); var rotationAngle = 0; var cameraPosition = new Vector3(); var cameraQuaternion = new Quaternion(); var cameraScale = new Vector3(); var parentPosition = new Vector3(); var parentQuaternion = new Quaternion(); var parentQuaternionInv = new Quaternion(); var parentScale = new Vector3(); var worldPositionStart = new Vector3(); var worldQuaternionStart = new Quaternion(); var worldScaleStart = new Vector3(); var worldPosition = new Vector3(); var worldQuaternion = new Quaternion(); var worldQuaternionInv = new Quaternion(); var worldScale = new Vector3(); var eye = new Vector3(); var positionStart = new Vector3(); var quaternionStart = new Quaternion(); var scaleStart = new Vector3(); // TODO: remove properties unused in plane and gizmo defineProperty("worldPosition", worldPosition); defineProperty("worldPositionStart", worldPositionStart); defineProperty("worldQuaternion", worldQuaternion); defineProperty("worldQuaternionStart", worldQuaternionStart); defineProperty("cameraPosition", cameraPosition); defineProperty("cameraQuaternion", cameraQuaternion); defineProperty("pointStart", pointStart); defineProperty("pointEnd", pointEnd); defineProperty("rotationAxis", rotationAxis); defineProperty("rotationAngle", rotationAngle); defineProperty("eye", eye); { domElement.addEventListener("mousedown", onPointerDown, false); domElement.addEventListener("touchstart", onPointerDown, false); domElement.addEventListener("mousemove", onPointerHover, false); domElement.addEventListener("touchmove", onPointerHover, false); domElement.addEventListener("touchmove", onPointerMove, false); document.addEventListener("mouseup", onPointerUp, false); domElement.addEventListener("touchend", onPointerUp, false); domElement.addEventListener("touchcancel", onPointerUp, false); domElement.addEventListener("touchleave", onPointerUp, false); var drag = () => { if (this.dragging) { this.pointerMove(); return { stopContinue: true }; } }; this.addEventListener('dragging', drag, { importance: 10 }); viewer.addEventListener('global_drag', drag, { importance: 10 }); } this.setRotateMethod = function (number) { //add 注意为2时 旋转期间不能改变位置 space可能不能为local ._gizmo.hideAxis = { rotate:[这里必须包含'e' ] } this.rotateMethod = number; }; this.dispose = function () { domElement.removeEventListener("mousedown", onPointerDown); domElement.removeEventListener("touchstart", onPointerDown); domElement.removeEventListener("mousemove", onPointerHover); domElement.removeEventListener("mousemove", onPointerMove); domElement.removeEventListener("touchmove", onPointerHover); domElement.removeEventListener("touchmove", onPointerMove); document.removeEventListener("mouseup", onPointerUp); domElement.removeEventListener("touchend", onPointerUp); domElement.removeEventListener("touchcancel", onPointerUp); domElement.removeEventListener("touchleave", onPointerUp); this.traverse(function (child) { if (child.geometry) child.geometry.dispose(); if (child.material) child.material.dispose(); }); }; // Set current object this.attach = function (object, clickPos) { this.object = object; Potree.Utils.updateVisible(this, 'attach', true); //Config.keyCon = false;//add //this.linesAssistance.setVisible(true) this.clickPos = clickPos !== null && clickPos !== void 0 && clickPos.isVector3 ? clickPos : null; viewer.dispatchEvent('content_changed'); return this; }; // Detatch from object this.detach = function () { this.object = undefined; this.axis = null; //Config.keyCon = true;//add Potree.Utils.updateVisible(this, 'attach', false); //this.linesAssistance.setVisible(false) viewer.dispatchEvent('content_changed'); return this; }; //this.space = 'local' /* this.hideAxis = function ( mode, axis=[] ) {//xzw add 设置不可见的axis var handles = []; handles = handles.concat( this._gizmo.picker[ mode ].children ); handles = handles.concat( this._gizmo.gizmo[ mode ].children ); handles = handles.concat( this._gizmo.helper[ mode ].children ); handles.forEach(e=>e.visible = false) axis.forEach(name=>{ handles.filter(handle =>!handle.name.includes(name)) }) handles.forEach(e=>e.visible = true) }; */ // Defined getter, setter and store for a property function defineProperty(propName, defaultValue) { var propValue = defaultValue; Object.defineProperty(scope, propName, { get: function get() { return propValue !== undefined ? propValue : defaultValue; }, set: function set(value) { if (propValue !== value) { propValue = value; _plane[propName] = value; _gizmo[propName] = value; scope.dispatchEvent({ type: propName + "-changed", value: value }); scope.dispatchEvent(changeEvent); } } }); scope[propName] = defaultValue; _plane[propName] = defaultValue; _gizmo[propName] = defaultValue; } // updateMatrixWorld updates key transformation variables this.updateMatrixWorld = function () { if (!this.visible) return; //add if (this.object !== undefined) { this.object.updateMatrixWorld(); this.object.parent.matrixWorld.decompose(parentPosition, parentQuaternion, parentScale); this.object.matrixWorld.decompose(worldPosition, worldQuaternion, worldScale); if (Potree.settings.mergeTransCtlOnClick && this.mode == 'translate' && this.clickPos) { //允许位移控件出现在点击的位置 var pos = this.clickPos.clone().applyMatrix4(this.object.matrixWorld); worldPosition.copy(pos); } else if (this.object.boundingBox) { var boundingBox = this.object.boundingBox.clone().applyMatrix4(this.object.matrixWorld); boundingBox.getCenter(worldPosition); //bound中心 if (this.pivotOnBottom) { worldPosition.setZ(boundingBox.min.z); //中心点居于模型bound底部,因固定离地高度,旋转时旋转中心在地面上就不会变位置 } } parentQuaternionInv.copy(parentQuaternion).invert(); worldQuaternionInv.copy(worldQuaternion).invert(); } this.camera.updateMatrixWorld(); this.camera.matrixWorld.decompose(cameraPosition, cameraQuaternion, cameraScale); if (this.camera.type == "OrthographicCamera") { //xzw add eye.copy(this.view.direction); } else { eye.copy(cameraPosition).sub(worldPosition).normalize(); } Object3D.prototype.updateMatrixWorld.call(this); }; this.pointerHover = function () { var pointer = viewer.inputHandler.pointer; if (this.object === undefined) return; //if(this.dragging === true /* || ( pointer.button !== undefined && pointer.button !== 0 ) */) return; if (!this.dragging) { var oldAxis = this.axis; //ray.setFromCamera( pointer, this.camera ); //这句会在floorplan模式get不到intersect var { origin, direction } = viewer.inputHandler.getMouseDirection(); ray.set(origin, direction); Potree.Utils.setCameraLayers(ray, //设置能识别到的layers ['sceneObjects', 'mapObjects', 'measure', 'transformationTool', 'model'], viewer.inputHandler.hoverViewport && viewer.inputHandler.hoverViewport.extraEnableLayers); var intersect = ray.intersectObjects(_gizmo.picker[this.mode].children.filter(e => e.visible), true)[0] || false; if (intersect) { this.axis = intersect.object.name; } else { this.axis = null; } if (oldAxis != this.axis) { viewer.dispatchEvent('content_changed'); } } else { //this.pointerMove() } }; this.pointerDown = function /* pointer */ () { var pointer = viewer.inputHandler.pointer; if (this.object === undefined || this.dragging === true /* || ( pointer.button !== undefined && pointer.button !== 0 ) */) return; if ( /* ( pointer.button === 0 || pointer.button === undefined ) && */this.axis !== null) { //ray.setFromCamera( pointer, this.camera ); //这句会在floorplan模式get不到intersect var { origin, direction } = viewer.inputHandler.getMouseDirection(); ray.set(origin, direction); Potree.Utils.setCameraLayers(ray, //设置能识别到的layers ['sceneObjects', 'mapObjects', 'measure', 'transformationTool', 'model'], viewer.inputHandler.hoverViewport && viewer.inputHandler.hoverViewport.extraEnableLayers); var planeIntersect = ray.intersectObjects([_plane], true)[0] || false; if (planeIntersect) { var space = this.space; if (this.mode === 'scale') { space = 'local'; } else if (this.axis === 'E' || this.axis === 'XYZE' || this.axis === 'XYZ') { space = 'world'; } if (space === 'local' && this.mode === 'rotate') { var snap = this.rotationSnap; if (this.axis === 'X' && snap) this.object.rotation.x = Math.round(this.object.rotation.x / snap) * snap; if (this.axis === 'Y' && snap) this.object.rotation.y = Math.round(this.object.rotation.y / snap) * snap; if (this.axis === 'Z' && snap) this.object.rotation.z = Math.round(this.object.rotation.z / snap) * snap; } this.object.updateMatrixWorld(); this.object.parent.updateMatrixWorld(); positionStart.copy(this.object.position); quaternionStart.copy(this.object.quaternion); scaleStart.copy(this.object.scale); this.object.matrixWorld.decompose(worldPositionStart, worldQuaternionStart, worldScaleStart); //add: 使坐标轴在boundingBox中心 this.object.boundingBox && this.object.boundingBox.getCenter(worldPositionStart).applyMatrix4(this.object.matrixWorld); pointStart.copy(planeIntersect.point).sub(worldPositionStart); /* if(this.player.cameraControls.activeControl){ //this.player.cameraControls.activeControl.locked = true; //add this.player.cameraControls.activeControl.enabled = false; //add } */ } this.dragging = true; mouseDownEvent.mode = this.mode; this.dispatchEvent(mouseDownEvent); } }; this.pointerMove = function /* pointer */ () { var pointer = viewer.inputHandler.pointer; var axis = this.axis; var mode = this.mode; var object = this.object; var space = this.space; if (mode === 'scale') { space = 'local'; } else if (axis === 'E' || axis === 'XYZE' || axis === 'XYZ') { space = 'world'; } if (object === undefined || axis === null || this.dragging === false || pointer.button !== undefined && pointer.button !== 0) return; //ray.setFromCamera( pointer, this.camera ); //这句会在floorplan模式get不到intersect var { origin, direction } = viewer.inputHandler.getMouseDirection(); ray.set(origin, direction); Potree.Utils.setCameraLayers(ray, //设置能识别到的layers ['sceneObjects', 'mapObjects', 'measure', 'transformationTool', 'model'], viewer.inputHandler.hoverViewport && viewer.inputHandler.hoverViewport.extraEnableLayers); var planeIntersect = ray.intersectObjects([_plane], true)[0] || false; if (planeIntersect === false) return; pointEnd.copy(planeIntersect.point).sub(worldPositionStart); if (mode === 'translate') { // Apply translate offset.copy(pointEnd).sub(pointStart); if (space === 'local' && axis !== 'XYZ') { offset.applyQuaternion(worldQuaternionInv); } if (axis.indexOf('X') === -1) offset.x = 0; if (axis.indexOf('Y') === -1) offset.y = 0; if (axis.indexOf('Z') === -1) offset.z = 0; if (space === 'local' && axis !== 'XYZ') { //xzw 加,否则会反向--------------- object.scale.x < 0 && (offset.x *= -1); object.scale.y < 0 && (offset.y *= -1); object.scale.z < 0 && (offset.z *= -1); //--------------------------------- offset.applyQuaternion(quaternionStart).divide(parentScale); } else { offset.applyQuaternion(parentQuaternionInv).divide(parentScale); } object.position.copy(offset).add(positionStart); // Apply translation snap if (this.translationSnap) { if (space === 'local') { object.position.applyQuaternion(_tempQuaternion.copy(quaternionStart).invert()); if (axis.search('X') !== -1) { object.position.x = Math.round(object.position.x / this.translationSnap) * this.translationSnap; } if (axis.search('Y') !== -1) { object.position.y = Math.round(object.position.y / this.translationSnap) * this.translationSnap; } if (axis.search('Z') !== -1) { object.position.z = Math.round(object.position.z / this.translationSnap) * this.translationSnap; } object.position.applyQuaternion(quaternionStart); } if (space === 'world') { if (object.parent) { object.position.add(_tempVector.setFromMatrixPosition(object.parent.matrixWorld)); } if (axis.search('X') !== -1) { object.position.x = Math.round(object.position.x / this.translationSnap) * this.translationSnap; } if (axis.search('Y') !== -1) { object.position.y = Math.round(object.position.y / this.translationSnap) * this.translationSnap; } if (axis.search('Z') !== -1) { object.position.z = Math.round(object.position.z / this.translationSnap) * this.translationSnap; } if (object.parent) { object.position.sub(_tempVector.setFromMatrixPosition(object.parent.matrixWorld)); } } } //add: object.dispatchEvent({ type: "position_changed" }); } else if (mode === 'scale') { if (axis.search('XYZ') !== -1) { var d = pointEnd.length() / pointStart.length(); if (pointEnd.dot(pointStart) < 0) d *= -1; if (options.NoScaleZ) { //xzw add _tempVector2.set(d, d, 1); } else { _tempVector2.set(d, d, d); } } else if (axis.search('XY') !== -1) { //add 等比例for plane var d = pointEnd.length() / pointStart.length(); if (pointEnd.dot(pointStart) < 0) d *= -1; _tempVector2.set(d, d, 1); } else { _tempVector.copy(pointStart); _tempVector2.copy(pointEnd); _tempVector.applyQuaternion(worldQuaternionInv); _tempVector2.applyQuaternion(worldQuaternionInv); _tempVector2.divide(_tempVector); if (axis.search('X') === -1) { _tempVector2.x = 1; } if (axis.search('Y') === -1) { _tempVector2.y = 1; } if (axis.search('Z') === -1) { _tempVector2.z = 1; } } // Apply scale object.scale.copy(scaleStart).multiply(_tempVector2); if (this.scaleSnap) { if (axis.search('X') !== -1) { object.scale.x = Math.round(object.scale.x / this.scaleSnap) * this.scaleSnap || this.scaleSnap; } if (axis.search('Y') !== -1) { object.scale.y = Math.round(object.scale.y / this.scaleSnap) * this.scaleSnap || this.scaleSnap; } if (axis.search('Z') !== -1) { object.scale.z = Math.round(object.scale.z / this.scaleSnap) * this.scaleSnap || this.scaleSnap; } } //add: object.dispatchEvent({ type: "scale_changed" }); } else if (mode === 'rotate') { if (this.rotateMethod == 2) { //新版参照transfromTool的写法,更跟手,但是有bug,在同时移动位置时或e轴上有问题 if (axis === 'E') { //绕着视线转 rotationAxis.copy(eye); //旋转轴 rotationAngle = pointEnd.angleTo(pointStart); startNorm.copy(pointStart).normalize(); endNorm.copy(pointEnd).normalize(); rotationAngle *= endNorm.cross(startNorm).dot(eye) < 0 ? 1 : -1; //角度 } else { if (axis === 'XYZE') { //像滚球一样拨动,鼠标滑动方向为拨动方向,在plane面上滚动 offset.copy(pointEnd).sub(pointStart); rotationAxis.copy(offset).cross(eye).normalize(); } else { rotationAxis.copy(_unit[axis]); } var center = new Vector3(); //坐标轴位置 /* if(this.object.boundingBox){ center.copy(worldPosition) //center设置为boundingbox的中心。但center一直更改会导致虽然在按某个时针旋转,但v2相对v1可能会时不时逆向,导致闪烁。所以固定住center,虽然这样计算的角度和绕模型中心的感觉偏颇 }else{ */ center.copy(worldPositionStart); //} var rotationAxis_ = space === 'local' ? rotationAxis.clone().applyQuaternion(worldQuaternion) : rotationAxis; var plane = new Plane().setFromNormalAndCoplanarPoint(rotationAxis_, center); //旋转过程中rotationAxis不会变化,但center可能会 var { origin: _origin, direction: _direction } = viewer.inputHandler.getMouseDirection(); ray.set(_origin, _direction); var I = ray.ray.intersectPlane(plane, new Vector3()); if (I) { var v2 = I.clone().sub(center); //.normalize(); if (!this.rotateStart) { this.rotateStart = { v1: v2 }; return; } var v1 = this.rotateStart.v1; rotationAngle = math.getAngle(v1, v2, rotationAxis_); //console.log('rot', rotationAngle, center.toArray()) if (Number.isNaN(rotationAngle)) { return; } this.rotateStart.v1 = v2; } } } else { //pointStart 是起始intersect - object中心的向量 //pointEnd 是当前intersect - object中心的向量 offset.copy(pointEnd).sub(pointStart); var ROTATION_SPEED = 2 / worldPosition.distanceTo(_tempVector.setFromMatrixPosition(this.camera.matrixWorld)); if (axis === 'E') { //绕着视线转 rotationAxis.copy(eye); //旋转轴 rotationAngle = pointEnd.angleTo(pointStart); startNorm.copy(pointStart).normalize(); endNorm.copy(pointEnd).normalize(); rotationAngle *= endNorm.cross(startNorm).dot(eye) < 0 ? 1 : -1; //角度 } else if (axis === 'XYZE') { //像滚球一样拨动,鼠标滑动方向为拨动方向,在plane面上滚动 rotationAxis.copy(offset).cross(eye).normalize(); rotationAngle = offset.dot(_tempVector.copy(rotationAxis).cross(this.eye)) * ROTATION_SPEED; } else if (axis === 'X' || axis === 'Y' || axis === 'Z') { rotationAxis.copy(_unit[axis]); _tempVector.copy(_unit[axis]); if (space === 'local') { _tempVector.applyQuaternion(worldQuaternion); } rotationAngle = offset.dot(_tempVector.cross(eye).normalize()) * ROTATION_SPEED; } // Apply rotation snap if (this.rotationSnap) rotationAngle = Math.round(rotationAngle / this.rotationSnap) * this.rotationSnap; this.rotationAngle = rotationAngle; } // Apply rotate if (space === 'local' && axis !== 'E' && axis !== 'XYZE') { object.scale[axis.toLowerCase()] < 0 && (rotationAngle *= -1); //xzw 加,否则会反向 object.quaternion.copy(quaternionStart); object.quaternion.multiply(_tempQuaternion.setFromAxisAngle(rotationAxis, rotationAngle)).normalize(); } else { rotationAxis.applyQuaternion(parentQuaternionInv); object.quaternion.copy(_tempQuaternion.setFromAxisAngle(rotationAxis, rotationAngle)); object.quaternion.multiply(quaternionStart).normalize(); } if (this.rotateMethod == 2 && axis != 'E') { quaternionStart.copy(object.quaternion); } //add: object.dispatchEvent({ type: "rotation_changed" }); } this.dispatchEvent(changeEvent); this.dispatchEvent(objectChangeEvent); viewer.dispatchEvent('content_changed'); }; this.pointerUp = function (pointer) { //if ( pointer.button !== undefined && pointer.button !== 0 ) return; if (this.dragging && this.axis !== null) { mouseUpEvent.mode = this.mode; this.dispatchEvent(mouseUpEvent); /* if(this.player.cameraControls.activeControl){ //this.player.cameraControls.activeControl.locked = false; //add this.player.cameraControls.activeControl.pointerDragOn = false //add this.player.cameraControls.activeControl.enabled = true } */ this.rotateStart = null; //add } this.dragging = false; //if ( pointer.button === undefined ) this.axis = null; /* if(this.player.cameraControls.activeControl){ //this.player.cameraControls.activeControl.locked = false; //add this.player.cameraControls.activeControl.pointerDragOn = false //add this.player.cameraControls.activeControl.enabled = true } */ }; // normalize mouse / touch pointer and remap {x,y} to view space. function getPointer(event) { if (!event) { console.log('hhahhhahah'); return; } if (document.pointerLockElement) { return { x: 0, y: 0, button: event.button }; } else { var pointer = event.changedTouches ? event.changedTouches[0] : event; var rect = domElement.getBoundingClientRect(); return { x: (pointer.clientX - rect.left) / rect.width * 2 - 1, y: -(pointer.clientY - rect.top) / rect.height * 2 + 1, button: event.button }; } } // mouse / touch event handlers function onPointerHover(event) { if (!scope.enabled) return; //scope.pointerHover( getPointer( event ) ); scope.pointerHover(); } function onPointerDown(event) { if (!scope.enabled) return; //document.addEventListener( "mousemove", onPointerMove, false ); /* scope.pointerHover( getPointer( event ) ); scope.pointerDown( getPointer( event ) ); */ scope.pointerHover(); scope.pointerDown(); } this.onPointerDown = onPointerDown; function onPointerMove(event) { if (!scope.enabled || !this.dragging) return; //xzw change //scope.pointerMove( getPointer( event ) ); scope.pointerMove(); } this.onPointerMove = onPointerMove; function onPointerUp(event) { if (!scope.enabled) return; //document.removeEventListener( "mousemove", onPointerMove, false ); //scope.pointerUp( getPointer( event ) ); scope.pointerUp(); } this.onPointerUp = onPointerUp; // TODO: deprecate this.getMode = function () { return scope.mode; }; this.setMode = function (mode) { scope.mode = mode; }; this.setTranslationSnap = function (translationSnap) { scope.translationSnap = translationSnap; }; this.setRotationSnap = function (rotationSnap) { scope.rotationSnap = rotationSnap; }; this.setScaleSnap = function (scaleSnap) { scope.scaleSnap = scaleSnap; }; this.setSize = function (size) { scope.size = size; }; this.setSpace = function (space) { scope.space = space; }; this.update = function () { console.warn('THREE.TransformControls: update function has no more functionality and therefore has been deprecated.'); }; }; var TransformControlsGizmo = function TransformControlsGizmo(options) { 'use strict'; Object3D.call(this); this.type = 'TransformControlsGizmo'; // shared materials this.hideAxis = {}; var gizmoMaterial = new MeshBasicMaterial({ depthTest: false, depthWrite: false, transparent: true, side: DoubleSide, fog: false }); var gizmoLineMaterial = new LineBasicMaterial({ depthTest: false, depthWrite: false, transparent: true, fog: false }); // Make unique material for each axis/color var matInvisible = gizmoMaterial.clone(); matInvisible.opacity = 0.15; var matHelper = gizmoMaterial.clone(); matHelper.opacity = 0.1; var matRed = gizmoMaterial.clone(); matRed.color.set(0xff0000); var matGreen = gizmoMaterial.clone(); matGreen.color.set(0x00ff00); var matBlue = gizmoMaterial.clone(); matBlue.color.set(0x0000ff); var matWhiteTransparent = gizmoMaterial.clone(); matWhiteTransparent.opacity = 0.35; matWhiteTransparent.color.set(0x00d0fd); //xzw add var matYellowTransparent = matWhiteTransparent.clone(); matYellowTransparent.color.set(0xffff00); var matCyanTransparent = matWhiteTransparent.clone(); matCyanTransparent.color.set(0x00ffff); var matMagentaTransparent = matWhiteTransparent.clone(); matMagentaTransparent.color.set(0xff00ff); var matYellow = gizmoMaterial.clone(); matYellow.color.set(0xffff00); var matLineRed = gizmoLineMaterial.clone(); matLineRed.color.set(0xff0000); var matLineGreen = gizmoLineMaterial.clone(); matLineGreen.color.set(0x00ff00); var matLineBlue = gizmoLineMaterial.clone(); matLineBlue.color.set(0x0000ff); var matLineCyan = gizmoLineMaterial.clone(); matLineCyan.color.set(0x00ffff); var matLineMagenta = gizmoLineMaterial.clone(); matLineMagenta.color.set(0xff00ff); var matLineYellow = gizmoLineMaterial.clone(); matLineYellow.color.set(0xffff00); var matLineGray = gizmoLineMaterial.clone(); matLineGray.color.set(0x787878); var matLineYellowTransparent = matLineYellow.clone(); matLineYellowTransparent.opacity = 0.25; // reusable geometry var arrowGeometry = new CylinderBufferGeometry(0, 0.05, 0.2, 12, 1, false); var scaleHandleGeometry = new BoxBufferGeometry(0.125, 0.125, 0.125); var lineGeometry = new BufferGeometry(); //lineGeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( [ 0, 0, 0, 1, 0, 0 ], 3 ) ); lineGeometry.setAttribute("position", new BufferAttribute(new Float32Array([0, 0, 0, 1, 0, 0]), 3)); var CircleGeometry = function CircleGeometry(radius, arc) { var geometry = new BufferGeometry(); var vertices = []; for (var i = 0; i <= 64 * arc; ++i) { vertices.push(0, Math.cos(i / 32 * Math.PI) * radius, Math.sin(i / 32 * Math.PI) * radius); } //geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) ); geometry.setAttribute("position", new BufferAttribute(new Float32Array(vertices), 3)); return geometry; }; // Special geometry for transform helper. If scaled with position vector it spans from [0,0,0] to position var TranslateHelperGeometry = function TranslateHelperGeometry() { var geometry = new BufferGeometry(); //geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( [ 0, 0, 0, 1, 1, 1 ], 3 ) ); geometry.setAttribute("position", new BufferAttribute(new Float32Array([0, 0, 0, 1, 1, 1]), 3)); return geometry; }; // Gizmo definitions - custom hierarchy definitions for setupGizmo() function var gizmoTranslate = { X: [[new Mesh(arrowGeometry, matRed), [1, 0, 0], [0, 0, -Math.PI / 2], null, 'fwd'], //[ new THREE.Mesh( arrowGeometry, matRed ), [ 1, 0, 0 ], [ 0, 0, Math.PI / 2 ], null, 'bwd' ], [new Line(lineGeometry, matLineRed)]], Y: [[new Mesh(arrowGeometry, matGreen), [0, 1, 0], null, null, 'fwd'], //[ new THREE.Mesh( arrowGeometry, matGreen ), [ 0, 1, 0 ], [ Math.PI, 0, 0 ], null, 'bwd' ], [new Line(lineGeometry, matLineGreen), null, [0, 0, Math.PI / 2]]], Z: [[new Mesh(arrowGeometry, matBlue), [0, 0, 1], [Math.PI / 2, 0, 0], null, 'fwd'], //[ new THREE.Mesh( arrowGeometry, matBlue ), [ 0, 0, 1 ], [ - Math.PI / 2, 0, 0 ], null, 'bwd' ], [new Line(lineGeometry, matLineBlue), null, [0, -Math.PI / 2, 0]]], /* XYZ: [ [ new THREE.Mesh( new THREE.OctahedronBufferGeometry( 0.1, 0 ), matWhiteTransparent.clone() ), [ 0, 0, 0 ], [ 0, 0, 0 ]] ], */ XY: [[new Mesh(new PlaneBufferGeometry(0.295, 0.295), matYellowTransparent.clone()), [0.15, 0.15, 0]], [new Line(lineGeometry, matLineYellow), [0.18, 0.3, 0], null, [0.125, 1, 1]], [new Line(lineGeometry, matLineYellow), [0.3, 0.18, 0], [0, 0, Math.PI / 2], [0.125, 1, 1]]], YZ: [[new Mesh(new PlaneBufferGeometry(0.295, 0.295), matCyanTransparent.clone()), [0, 0.15, 0.15], [0, Math.PI / 2, 0]], [new Line(lineGeometry, matLineCyan), [0, 0.18, 0.3], [0, 0, Math.PI / 2], [0.125, 1, 1]], [new Line(lineGeometry, matLineCyan), [0, 0.3, 0.18], [0, -Math.PI / 2, 0], [0.125, 1, 1]]], XZ: [[new Mesh(new PlaneBufferGeometry(0.295, 0.295), matMagentaTransparent.clone()), [0.15, 0, 0.15], [-Math.PI / 2, 0, 0]], [new Line(lineGeometry, matLineMagenta), [0.18, 0, 0.3], null, [0.125, 1, 1]], [new Line(lineGeometry, matLineMagenta), [0.3, 0, 0.18], [0, -Math.PI / 2, 0], [0.125, 1, 1]]] }; var pickerTranslate = { X: [[new Mesh(new CylinderBufferGeometry(0.2, 0, 1, 4, 1, false), matInvisible), [0.6, 0, 0], [0, 0, -Math.PI / 2]]], Y: [[new Mesh(new CylinderBufferGeometry(0.2, 0, 1, 4, 1, false), matInvisible), [0, 0.6, 0]]], Z: [[new Mesh(new CylinderBufferGeometry(0.2, 0, 1, 4, 1, false), matInvisible), [0, 0, 0.6], [Math.PI / 2, 0, 0]]], /* XYZ: [ [ new THREE.Mesh( new THREE.OctahedronBufferGeometry( 0.2, 0 ), matInvisible ) ] ], */ XY: [[new Mesh(new PlaneBufferGeometry(0.4, 0.4), matInvisible), [0.2, 0.2, 0]]], YZ: [[new Mesh(new PlaneBufferGeometry(0.4, 0.4), matInvisible), [0, 0.2, 0.2], [0, Math.PI / 2, 0]]], XZ: [[new Mesh(new PlaneBufferGeometry(0.4, 0.4), matInvisible), [0.2, 0, 0.2], [-Math.PI / 2, 0, 0]]] }; var helperTranslate = { START: [[new Mesh(new OctahedronBufferGeometry(0.01, 2), matHelper), null, null, null, 'helper']], END: [[new Mesh(new OctahedronBufferGeometry(0.01, 2), matHelper), null, null, null, 'helper']], DELTA: [[new Line(TranslateHelperGeometry(), matHelper), null, null, null, 'helper']], X: [[new Line(lineGeometry, matHelper.clone()), [-1e3, 0, 0], null, [1e6, 1, 1], 'helper']], Y: [[new Line(lineGeometry, matHelper.clone()), [0, -1e3, 0], [0, 0, Math.PI / 2], [1e6, 1, 1], 'helper']], Z: [[new Line(lineGeometry, matHelper.clone()), [0, 0, -1e3], [0, -Math.PI / 2, 0], [1e6, 1, 1], 'helper']] }; var arc = options.rotFullCircle ? 1 : 0.5; //add var gizmoRotate = { X: [[new Line(CircleGeometry(1, arc), matLineRed)], [new Mesh(new OctahedronBufferGeometry(0.04, 0), matRed), [0, 0, 0.99], null, [1, 3, 1]]], Y: [[new Line(CircleGeometry(1, arc), matLineGreen), null, [0, 0, -Math.PI / 2]], [new Mesh(new OctahedronBufferGeometry(0.04, 0), matGreen), [0, 0, 0.99], null, [3, 1, 1]]], Z: [[new Line(CircleGeometry(1, arc), matLineBlue), null, [0, Math.PI / 2, 0]], [new Mesh(new OctahedronBufferGeometry(0.04, 0), matBlue), [0.99, 0, 0], null, [1, 3, 1]]], E: [[new Line(CircleGeometry(1.25, 1), matLineYellowTransparent), null, [0, Math.PI / 2, 0]], [new Mesh(new CylinderBufferGeometry(0.03, 0, 0.15, 4, 1, false), matLineYellowTransparent), [1.17, 0, 0], [0, 0, -Math.PI / 2], [1, 1, 0.001]], [new Mesh(new CylinderBufferGeometry(0.03, 0, 0.15, 4, 1, false), matLineYellowTransparent), [-1.17, 0, 0], [0, 0, Math.PI / 2], [1, 1, 0.001]], [new Mesh(new CylinderBufferGeometry(0.03, 0, 0.15, 4, 1, false), matLineYellowTransparent), [0, -1.17, 0], [Math.PI, 0, 0], [1, 1, 0.001]], [new Mesh(new CylinderBufferGeometry(0.03, 0, 0.15, 4, 1, false), matLineYellowTransparent), [0, 1.17, 0], [0, 0, 0], [1, 1, 0.001]]], XYZE: [[new Line(CircleGeometry(1, 1), matLineGray), null, [0, Math.PI / 2, 0]]] }; var helperRotate = { AXIS: [[new Line(lineGeometry, matHelper.clone()), [-1e3, 0, 0], null, [1e6, 1, 1], 'helper']] }; var pickerRotate = { X: [[new Mesh(new TorusBufferGeometry(1, 0.1, 4, 24), matInvisible), [0, 0, 0], [0, -Math.PI / 2, -Math.PI / 2]]], Y: [[new Mesh(new TorusBufferGeometry(1, 0.1, 4, 24), matInvisible), [0, 0, 0], [Math.PI / 2, 0, 0]]], Z: [[new Mesh(new TorusBufferGeometry(1, 0.1, 4, 24), matInvisible), [0, 0, 0], [0, 0, -Math.PI / 2]]], E: [[new Mesh(new TorusBufferGeometry(1.25, 0.1, 2, 24), matInvisible)]], XYZE: [[new Mesh(new SphereBufferGeometry(0.7, 10, 8), matInvisible)]] }; var gizmoScale = { X: [[new Mesh(scaleHandleGeometry, matRed), [0.8, 0, 0], [0, 0, -Math.PI / 2]], [new Line(lineGeometry, matLineRed), null, null, [0.8, 1, 1]]], Y: [[new Mesh(scaleHandleGeometry, matGreen), [0, 0.8, 0]], [new Line(lineGeometry, matLineGreen), null, [0, 0, Math.PI / 2], [0.8, 1, 1]]], Z: [[new Mesh(scaleHandleGeometry, matBlue), [0, 0, 0.8], [Math.PI / 2, 0, 0]], [new Line(lineGeometry, matLineBlue), null, [0, -Math.PI / 2, 0], [0.8, 1, 1]]], XY: [[new Mesh(scaleHandleGeometry, matYellowTransparent), [0.85, 0.85, 0], null, [2, 2, 0.2]], [new Line(lineGeometry, matLineYellow), [0.855, 0.98, 0], null, [0.125, 1, 1]], [new Line(lineGeometry, matLineYellow), [0.98, 0.855, 0], [0, 0, Math.PI / 2], [0.125, 1, 1]]], /* YZ: [ [ new THREE.Mesh( scaleHandleGeometry, matCyanTransparent ), [ 0, 0.85, 0.85 ], null, [ 0.2, 2, 2 ]], [ new THREE.Line( lineGeometry, matLineCyan ), [ 0, 0.855, 0.98 ], [ 0, 0, Math.PI / 2 ], [ 0.125, 1, 1 ]], [ new THREE.Line( lineGeometry, matLineCyan ), [ 0, 0.98, 0.855 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]] ], XZ: [ [ new THREE.Mesh( scaleHandleGeometry, matMagentaTransparent ), [ 0.85, 0, 0.85 ], null, [ 2, 0.2, 2 ]], [ new THREE.Line( lineGeometry, matLineMagenta ), [ 0.855, 0, 0.98 ], null, [ 0.125, 1, 1 ]], [ new THREE.Line( lineGeometry, matLineMagenta ), [ 0.98, 0, 0.855 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]] ], XYZX: [ [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransparent.clone() ), [ 1.1, 0, 0 ]], ],*/ XYZY: [[new Mesh(new BoxBufferGeometry(0.125, 0.125, 0.125), matWhiteTransparent.clone()), [0, 1.1, 0]]] /* , XYZZ: [ [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransparent.clone() ), [ 0, 0, 1.1 ]], ] */ }; var pickerScale = { X: [[new Mesh(new CylinderBufferGeometry(0.2, 0, 0.8, 4, 1, false), matInvisible), [0.5, 0, 0], [0, 0, -Math.PI / 2]]], Y: [[new Mesh(new CylinderBufferGeometry(0.2, 0, 0.8, 4, 1, false), matInvisible), [0, 0.5, 0]]], Z: [[new Mesh(new CylinderBufferGeometry(0.2, 0, 0.8, 4, 1, false), matInvisible), [0, 0, 0.5], [Math.PI / 2, 0, 0]]], XY: [[new Mesh(scaleHandleGeometry, matInvisible), [0.85, 0.85, 0], null, [3, 3, 0.2]]], /*YZ: [ [ new THREE.Mesh( scaleHandleGeometry, matInvisible ), [ 0, 0.85, 0.85 ], null, [ 0.2, 3, 3 ]], ], XZ: [ [ new THREE.Mesh( scaleHandleGeometry, matInvisible ), [ 0.85, 0, 0.85 ], null, [ 3, 0.2, 3 ]], ], XYZX: [ [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.2, 0.2, 0.2 ), matInvisible ), [ 1.1, 0, 0 ]], ],*/ XYZY: [[new Mesh(new BoxBufferGeometry(0.2, 0.2, 0.2), matInvisible), [0, 1.1, 0]]] /* , XYZZ: [ [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.2, 0.2, 0.2 ), matInvisible ), [ 0, 0, 1.1 ]], ] */ }; var helperScale = { X: [[new Line(lineGeometry, matHelper.clone()), [-1e3, 0, 0], null, [1e6, 1, 1], 'helper']], Y: [[new Line(lineGeometry, matHelper.clone()), [0, -1e3, 0], [0, 0, Math.PI / 2], [1e6, 1, 1], 'helper']], Z: [[new Line(lineGeometry, matHelper.clone()), [0, 0, -1e3], [0, -Math.PI / 2, 0], [1e6, 1, 1], 'helper']] }; // Creates an THREE.Object3D with gizmos described in custom hierarchy definition. var setupGizmo = function setupGizmo(gizmoMap) { var gizmo = new Object3D(); for (var name in gizmoMap) { for (var i = gizmoMap[name].length; i--;) { var object = gizmoMap[name][i][0].clone(); var position = gizmoMap[name][i][1]; var rotation = gizmoMap[name][i][2]; var scale = gizmoMap[name][i][3]; var tag = gizmoMap[name][i][4]; // name and tag properties are essential for picking and updating logic. object.name = name; object.tag = tag; if (position) { object.position.set(position[0], position[1], position[2]); } if (rotation) { object.rotation.set(rotation[0], rotation[1], rotation[2]); } if (scale) { object.scale.set(scale[0], scale[1], scale[2]); } object.updateMatrix(); var tempGeometry = object.geometry.clone(); tempGeometry.applyMatrix4(object.matrix); object.geometry = tempGeometry; object.renderOrder = Infinity; object.position.set(0, 0, 0); object.rotation.set(0, 0, 0); object.scale.set(1, 1, 1); gizmo.add(object); } } return gizmo; }; // Reusable utility variables var tempVector = new Vector3(0, 0, 0); var tempEuler = new Euler(); var alignVector = new Vector3(0, 1, 0); var zeroVector = new Vector3(0, 0, 0); var lookAtMatrix = new Matrix4(); var tempQuaternion = new Quaternion(); var tempQuaternion2 = new Quaternion(); var identityQuaternion = new Quaternion(); var unitX = new Vector3(1, 0, 0); var unitY = new Vector3(0, 1, 0); var unitZ = new Vector3(0, 0, 1); // Gizmo creation this.gizmo = {}; this.picker = {}; this.helper = {}; this.add(this.gizmo["translate"] = setupGizmo(gizmoTranslate)); this.add(this.gizmo["rotate"] = setupGizmo(gizmoRotate)); this.add(this.gizmo["scale"] = setupGizmo(gizmoScale)); this.add(this.picker["translate"] = setupGizmo(pickerTranslate)); this.add(this.picker["rotate"] = setupGizmo(pickerRotate)); this.add(this.picker["scale"] = setupGizmo(pickerScale)); this.add(this.helper["translate"] = setupGizmo(helperTranslate)); this.add(this.helper["rotate"] = setupGizmo(helperRotate)); this.add(this.helper["scale"] = setupGizmo(helperScale)); // Pickers should be hidden always this.picker["translate"].visible = false; this.picker["rotate"].visible = false; this.picker["scale"].visible = false; // updateMatrixWorld will update transformations and appearance of individual handles this.updateMatrixWorld = function () { if (!this.parent.visible) return; //add var space = this.space; if (this.mode === 'scale') space = 'local'; // scale always oriented to local rotation var quaternion = space === "local" ? this.worldQuaternion : identityQuaternion; // Show only gizmos for current transform mode this.gizmo["translate"].visible = this.mode === "translate"; this.gizmo["rotate"].visible = this.mode === "rotate"; this.gizmo["scale"].visible = this.mode === "scale"; this.helper["translate"].visible = this.mode === "translate"; this.helper["rotate"].visible = this.mode === "rotate"; this.helper["scale"].visible = this.mode === "scale"; var handles = []; handles = handles.concat(this.picker[this.mode].children); handles = handles.concat(this.gizmo[this.mode].children); handles = handles.concat(this.helper[this.mode].children); for (var i = 0; i < handles.length; i++) { var handle = handles[i]; //add if (this.hideAxis[this.mode] && this.hideAxis[this.mode].some(e => handle.name.includes(e.toUpperCase()))) { Potree.Utils.updateVisible(handle, 'hidden', false); continue; } var visible = true; // hide aligned to camera handle.rotation.set(0, 0, 0); handle.position.copy(this.worldPosition); if (this.camera.type == "OrthographicCamera") { var eyeDistance = 800 / this.camera.zoom; } else { var eyeDistance = this.worldPosition.distanceTo(this.cameraPosition); } handle.scale.set(1, 1, 1).multiplyScalar(eyeDistance * this.size / 7); // TODO: simplify helpers and consider decoupling from gizmo if (handle.tag === 'helper') { visible = false; if (handle.name === 'AXIS') { handle.position.copy(this.worldPositionStart); visible = !!this.axis; if (this.axis === 'X') { tempQuaternion.setFromEuler(tempEuler.set(0, 0, 0)); handle.quaternion.copy(quaternion).multiply(tempQuaternion); if (Math.abs(alignVector.copy(unitX).applyQuaternion(quaternion).dot(this.eye)) > 0.9) { visible = false; } } if (this.axis === 'Y') { tempQuaternion.setFromEuler(tempEuler.set(0, 0, Math.PI / 2)); handle.quaternion.copy(quaternion).multiply(tempQuaternion); if (Math.abs(alignVector.copy(unitY).applyQuaternion(quaternion).dot(this.eye)) > 0.9) { visible = false; } } if (this.axis === 'Z') { tempQuaternion.setFromEuler(tempEuler.set(0, Math.PI / 2, 0)); handle.quaternion.copy(quaternion).multiply(tempQuaternion); if (Math.abs(alignVector.copy(unitZ).applyQuaternion(quaternion).dot(this.eye)) > 0.9) { visible = false; } } if (this.axis === 'XYZE') { tempQuaternion.setFromEuler(tempEuler.set(0, Math.PI / 2, 0)); alignVector.copy(this.rotationAxis); handle.quaternion.setFromRotationMatrix(lookAtMatrix.lookAt(zeroVector, alignVector, unitY)); handle.quaternion.multiply(tempQuaternion); visible = this.dragging; } if (this.axis === 'E') { visible = false; } } else if (handle.name === 'START') { handle.position.copy(this.worldPositionStart); visible = this.dragging; } else if (handle.name === 'END') { handle.position.copy(this.worldPosition); visible = this.dragging; } else if (handle.name === 'DELTA') { handle.position.copy(this.worldPositionStart); handle.quaternion.copy(this.worldQuaternionStart); tempVector.set(1e-10, 1e-10, 1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1); tempVector.applyQuaternion(this.worldQuaternionStart.clone().invert()); handle.scale.copy(tempVector); visible = this.dragging; } else { handle.quaternion.copy(quaternion); if (this.dragging) { handle.position.copy(this.worldPositionStart); } else { handle.position.copy(this.worldPosition); } if (this.axis) { visible = this.axis.search(handle.name) !== -1; } } // If updating helper, skip rest of the loop Potree.Utils.updateVisible(handle, 'hidden', !!visible); continue; } // Align handles to current local or world rotation handle.quaternion.copy(quaternion); if (this.mode === 'translate' || this.mode === 'scale') { // Hide translate and scale axis facing the camera var AXIS_HIDE_TRESHOLD = 0.99; var PLANE_HIDE_TRESHOLD = 0.2; var AXIS_FLIP_TRESHOLD = 0.0; if (options.dontHideWhenFaceCamera) {//xzw add //正对镜头时不隐藏箭头 } else { if (handle.name === 'X' || handle.name === 'XYZX') { if (Math.abs(alignVector.copy(unitX).applyQuaternion(quaternion).dot(this.eye)) > AXIS_HIDE_TRESHOLD) { handle.scale.set(1e-10, 1e-10, 1e-10); visible = false; } } if (handle.name === 'Y' || handle.name === 'XYZY') { if (Math.abs(alignVector.copy(unitY).applyQuaternion(quaternion).dot(this.eye)) > AXIS_HIDE_TRESHOLD) { handle.scale.set(1e-10, 1e-10, 1e-10); visible = false; } } if (handle.name === 'Z' || handle.name === 'XYZZ') { if (Math.abs(alignVector.copy(unitZ).applyQuaternion(quaternion).dot(this.eye)) > AXIS_HIDE_TRESHOLD) { handle.scale.set(1e-10, 1e-10, 1e-10); visible = false; } } if (handle.name === 'XY') { if (Math.abs(alignVector.copy(unitZ).applyQuaternion(quaternion).dot(this.eye)) < PLANE_HIDE_TRESHOLD) { handle.scale.set(1e-10, 1e-10, 1e-10); visible = false; } } if (handle.name === 'YZ') { if (Math.abs(alignVector.copy(unitX).applyQuaternion(quaternion).dot(this.eye)) < PLANE_HIDE_TRESHOLD) { handle.scale.set(1e-10, 1e-10, 1e-10); visible = false; } } if (handle.name === 'XZ') { if (Math.abs(alignVector.copy(unitY).applyQuaternion(quaternion).dot(this.eye)) < PLANE_HIDE_TRESHOLD) { handle.scale.set(1e-10, 1e-10, 1e-10); visible = false; } } } // Flip translate and scale axis ocluded behind another axis //xzw 改 去掉反向箭头 if (handle.name.search('X') !== -1) { if (alignVector.copy(unitX).applyQuaternion(quaternion).dot(this.eye) < AXIS_FLIP_TRESHOLD) { /* if ( handle.tag === 'fwd' ) { handle.visible = false; } else { handle.scale.x *= - 1; } } else if ( handle.tag === 'bwd' ) { handle.visible = false;*/ handle.scale.x *= -1; } } if (handle.name.search('Y') !== -1) { if (alignVector.copy(unitY).applyQuaternion(quaternion).dot(this.eye) < AXIS_FLIP_TRESHOLD) { /* if ( handle.tag === 'fwd' ) { handle.visible = false; } else { handle.scale.y *= - 1; } } else if ( handle.tag === 'bwd' ) { handle.visible = false; */ handle.scale.y *= -1; } } if (handle.name.search('Z') !== -1) { if (alignVector.copy(unitZ).applyQuaternion(quaternion).dot(this.eye) < AXIS_FLIP_TRESHOLD) { /* if ( handle.tag === 'fwd' ) { handle.visible = false; } else { handle.scale.z *= - 1; } } else if ( handle.tag === 'bwd' ) { handle.visible = false; */ handle.scale.z *= -1; } } } else if (this.mode === 'rotate') { // Align handles to current local or world rotation tempQuaternion2.copy(quaternion); alignVector.copy(this.eye).applyQuaternion(tempQuaternion.copy(quaternion).invert()); if (handle.name.search("E") !== -1) { handle.quaternion.setFromRotationMatrix(lookAtMatrix.lookAt(this.eye, zeroVector, unitY)); } if (handle.name === 'X') { tempQuaternion.setFromAxisAngle(unitX, Math.atan2(-alignVector.y, alignVector.z)); tempQuaternion.multiplyQuaternions(tempQuaternion2, tempQuaternion); handle.quaternion.copy(tempQuaternion); } if (handle.name === 'Y') { tempQuaternion.setFromAxisAngle(unitY, Math.atan2(alignVector.x, alignVector.z)); tempQuaternion.multiplyQuaternions(tempQuaternion2, tempQuaternion); handle.quaternion.copy(tempQuaternion); } if (handle.name === 'Z') { tempQuaternion.setFromAxisAngle(unitZ, Math.atan2(alignVector.y, alignVector.x)); tempQuaternion.multiplyQuaternions(tempQuaternion2, tempQuaternion); handle.quaternion.copy(tempQuaternion); } } // Hide disabled axes visible = visible && (handle.name.indexOf("X") === -1 || this.showX); visible = visible && (handle.name.indexOf("Y") === -1 || this.showY); visible = visible && (handle.name.indexOf("Z") === -1 || this.showZ); visible = visible && (handle.name.indexOf("E") === -1 || this.showX && this.showY && this.showZ); Potree.Utils.updateVisible(handle, 'hidden', !!visible); // highlight selected axis handle.material._opacity = handle.material._opacity || handle.material.opacity; handle.material._color = handle.material._color || handle.material.color.clone(); handle.material.color.copy(handle.material._color); handle.material.opacity = handle.material._opacity; if (!this.enabled) { handle.material.opacity *= 0.5; handle.material.color.lerp(new Color(1, 1, 1), 0.5); } else if (this.axis) { if (handle.name === this.axis) { handle.material.opacity = 1.0; handle.material.color.lerp(new Color(1, 1, 1), 0.5); } else if (this.axis.split('').some(function (a) { return handle.name === a; })) { handle.material.opacity = 1.0; handle.material.color.lerp(new Color(1, 1, 1), 0.5); } else { handle.material.opacity *= 0.25; handle.material.color.lerp(new Color(1, 1, 1), 0.5); } } } Object3D.prototype.updateMatrixWorld.call(this); }; }; /* var TransformControlsLines = function (options) { THREE.Object3D.call( this) let label1 = new Label2D({ innerHTML:`
    与相机水平距离
    ` , domElement:$("#otherLabels")[0] ,autoUpdate:true }) let label2 = new Label2D({ innerHTML:`
    与相机高度差
    ` , domElement:$("#otherLabels")[0] ,autoUpdate:true }) let css = {'opacity': 0.7, 'color': '#07fceb', transform:'translate(-50%, -50%)'} label1.elem.css(css); label2.elem.css(css) //for(let i=0;i<2;i++){ // let line = LineDraw.createLine([new THREE.THREE.Vector3, new THREE.THREE.Vector3],{color:'#07fceb', opacity:0.7 }) // this.add(line) //} this.updateTransform = function(object){ object = object || this.parent.object; let A = player.position.clone(); //当前相机位置 let B = object.position //物体位置 let C = B.clone().setY(A.y); //物体在相机的高度的位置 let D = A.clone().setY(B.y); //相机在物体的高度的位置 //LineDraw.moveLine(this.children[0], [B, C]) // 垂直线 //LineDraw.moveLine(this.children[1], [D, B]) // 水平线 let dis1 = toPrecision(D.distanceTo(B),1) let dis2 = C.y - B.y label1.elem.text('与相机水平距离: '+dis1+'米') label2.elem.text('在相机之'+ (dis2>0?'下' : '上') +' :'+ toPrecision(dis2 , 1) +'米') label1.setPos(new THREE.THREE.Vector3().addVectors(D,B).multiplyScalar(0.5)) label2.setPos(new THREE.THREE.Vector3().addVectors(B,C).multiplyScalar(0.5)) } this.setVisible = (v,reason)=>{ label1.setVisible(v, reason || 'unvisi') label2.setVisible(v, reason || 'unvisi') this.visible = label1.visible if(this.visible){ this.updateTransform() } } this.setVisible(false) player.on("mode.changing",(currentMode, mode, pano, duration)=>{ if(mode != 'panorama'){ this.setVisible(false, 'isPanorama') }else{ this.setVisible(true, 'isPanorama') } }) player.on("flying.started",( )=>{ this.setVisible(false, 'flying') }) player.on("flying.ended",( )=>{ this.setVisible(true, 'flying') }) } */ var TransformControlsPlane = function TransformControlsPlane(options) { 'use strict'; Mesh.call(this, new PlaneBufferGeometry(100000, 100000, 2, 2), new MeshBasicMaterial({ color: "#ff0000", visible: false, wireframe: false, side: DoubleSide, transparent: true, opacity: 0.2 })); this.type = 'TransformControlsPlane'; var unitX = new Vector3(1, 0, 0); var unitY = new Vector3(0, 1, 0); var unitZ = new Vector3(0, 0, 1); var tempVector = new Vector3(); var dirVector = new Vector3(); var alignVector = new Vector3(); var tempMatrix = new Matrix4(); var identityQuaternion = new Quaternion(); this.updateMatrixWorld = function () { if (!this.visible) return; //add var space = this.space; this.position.copy(this.worldPosition); if (this.mode === 'scale') space = 'local'; // scale always oriented to local rotation unitX.set(1, 0, 0).applyQuaternion(space === "local" ? this.worldQuaternion : identityQuaternion); unitY.set(0, 1, 0).applyQuaternion(space === "local" ? this.worldQuaternion : identityQuaternion); unitZ.set(0, 0, 1).applyQuaternion(space === "local" ? this.worldQuaternion : identityQuaternion); // Align the plane for current transform mode, axis and space. alignVector.copy(unitY); switch (this.mode) { case 'translate': case 'scale': switch (this.axis) { case 'X': alignVector.copy(this.eye).cross(unitX); dirVector.copy(unitX).cross(alignVector); break; case 'Y': alignVector.copy(this.eye).cross(unitY); dirVector.copy(unitY).cross(alignVector); break; case 'Z': alignVector.copy(this.eye).cross(unitZ); dirVector.copy(unitZ).cross(alignVector); break; case 'XY': dirVector.copy(unitZ); break; case 'YZ': dirVector.copy(unitX); break; case 'XZ': alignVector.copy(unitZ); dirVector.copy(unitY); break; case 'XYZ': case 'E': default: //xzw add for scale xyzz dirVector.set(0, 0, 0); break; } break; case 'rotate': default: // special case for rotate dirVector.set(0, 0, 0); } if (dirVector.length() === 0) { //使物体在视线中平移 // If in rotate mode, make the plane parallel to camera this.quaternion.copy(this.cameraQuaternion); } else { //方向滑动所在面 tempMatrix.lookAt(tempVector.set(0, 0, 0), dirVector, alignVector); this.quaternion.setFromRotationMatrix(tempMatrix); } Object3D.prototype.updateMatrixWorld.call(this); }; }; TransformControls.prototype = Object.assign(Object.create(Object3D.prototype), { constructor: TransformControls, isTransformControls: true }); TransformControlsGizmo.prototype = Object.assign(Object.create(Object3D.prototype), { constructor: TransformControlsGizmo, isTransformControlsGizmo: true }); TransformControlsPlane.prototype = Object.assign(Object.create(Mesh.prototype), { constructor: TransformControlsPlane, isTransformControlsPlane: true }); /* 备注: //这里虽然 使坐标轴在boundingBox中心 boundingBox && this.object.boundingBox.getCenter(worldPosition).applyMatrix4(this.object.matrixWorld); 但是旋转中心并不是这个坐标轴显示的位置,需要再执行 MergeEditor.maintainBoundXY()才能维持在这个中心 */ var texLoader$a = new TextureLoader(); texLoader$a.crossOrigin = "anonymous"; var edgeStrengths = { pointcloud: 4, glb: 100 }; var viewportProps$1 = [{ left: 0, bottom: 0, width: 0.5, height: 1, name: 'top', axis: ["x", "y"], direction: new Vector3(0, 0, -1), //镜头朝向 active: true, //相机位置在z轴正向 limitBound: new Box3(new Vector3(-Infinity, -Infinity, 1), new Vector3(Infinity, Infinity, 5000)), //在地面以上 margin: { x: 50, y: 150 } }, { left: 0.5, bottom: 0, width: 0.5, height: 1, name: 'right', axis: ["y", "z"], direction: new Vector3(1, 0, 0), active: true, //相机位置在x轴负向 右下角屏 viewContainsPoints: [new Vector3(0, 0, 0)], margin: { x: 300, y: 250 } }]; var cylinderSkyGeo, oldSkyGeo; var MergeEditor = { bus: new EventDispatcher(), SplitScreen: new SplitScreen(), init() { this.boxHelper = new Box3Helper$1(new Box3(new Vector3(-0.5, -0.5, -0.5), new Vector3(0.5, 0.5, 0.5))); viewer.scene.scene.add(this.boxHelper); Potree.Utils.updateVisible(this.boxHelper, 'unselect', false); this.history = new History({ applyData: data => { if (data.object.parent /* && data.object == this.selected */) { data = Potree.Common.CloneObject(data); //避免使用后更改数据又被使用 data.matrix.decompose(data.object.position, data.object.quaternion, data.object.scale); data.object.boundCenter.copy(data.boundCenter); data.object.dispatchEvent('changeByHistory'); data.object.dispatchEvent('transformChanged'); viewer.dispatchEvent('content_changed'); return true; } }, getData: object => { return { object, matrix: object.matrixWorld.clone(), boundCenter: object.boundCenter.clone() }; } }); { Potree.settings.notAdditiveBlending = true; var ground = this.ground = new InfiniteGridHelper(1, 10000, new Color('#eee'), 10000, 0.2, 0.3); viewer.scene.scene.add(ground); //再加两条线否则在正侧边看不到 var line1 = LineDraw.createLine([new Vector3(-10000, 0, 0), new Vector3(10000, 0, 0)], { color: '#aaa' }); var line2 = LineDraw.createLine([new Vector3(0, -10000, 0), new Vector3(0, 10000, 0)], { mat: line1.material }); ground.renderOrder = Potree.config.renderOrders.model + 1; //line1.renderOrder + 1 //要比模型低,否则模型透明时效果不对 ground.add(line1); ground.add(line2); ground.material.opacity = 0.9; //为了滞后渲染,否则被rt遮住 ground.material.polygonOffset = true; //多边形偏移(视觉上没有移动模型位置),防止闪烁 ground.material.polygonOffsetFactor = 100; //多边形偏移因子 ground.material.polygonOffsetUnits = 10; //多边形偏移单位 ground.material.depthWrite = false; //ground.material.depthTest = false line1.material.polygonOffset = true; line1.material.polygonOffsetFactor = 130; line1.material.polygonOffsetUnits = 10; line1.material.depthWrite = false; //见笔记:透明物体的材质设置 } var oriEdgeStrength = viewer.outlinePass.edgeStrength; { this.transformControls = new TransformControls(viewer.mainViewport.camera, viewer.renderArea, { dontHideWhenFaceCamera: true }); //this.transformControls.space = 'local'//为了在当前方向上平移 this.transformControls.setSize(1.5); viewer.scene.scene.add(this.transformControls); this.transformControls._gizmo.hideAxis = { rotate: ['e'] }; this.transformControls.setRotateMethod(2); //右屏 this.transformControls2 = new TransformControls(viewer.mainViewport.camera, viewer.renderArea, { dontHideWhenFaceCamera: true }); this.transformControls2.setSize(1.5); viewer.scene.scene.add(this.transformControls2); Potree.Utils.setObjectLayers(this.transformControls2, 'layer2'); var mouseDown = e => { viewer.outlinePass.edgeStrength = 0; //暂时消失线 }; var mouseUp = e => { //this.updateEdgeStrength() viewer.outlinePass.edgeStrength = oriEdgeStrength; }; this.transformControls.addEventListener('mouseDown', mouseDown); this.transformControls2.addEventListener('mouseDown', mouseDown); this.transformControls.addEventListener('mouseUp', mouseUp); this.transformControls2.addEventListener('mouseUp', mouseUp); this.transformControls.addEventListener('mouseDown', () => { //dragstart this.history.beforeChange(this.selected); }); this.transformControls.addEventListener('mouseUp', () => { this.history.afterChange(this.selected); }); } { this.secondCompass = new Compass(null); } viewer.setControls(viewer.orbitControls); //viewer.mainViewport.view.fixZWhenPan = true viewer.orbitControls.constantlyForward = true; viewer.addEventListener('global_single_click', e => { if (this.noNeedSelection //如模型查看页 || viewer.scene.cameraAnimations.some(c => c.onUpdate) //正在播放 || e.drag && e.drag.notPressMouse //在加测量线 || viewer.mainViewport.view.isFlying() //有其他校准 || this.split //分屏中 || e.clickElement //触发别的点击事件,如测量时click marker /* && e.clickElement != e.intersect.object */ ) { return; } if (e.intersect) { var object = e.intersect.object || e.intersect.pointcloud; var objects = this.getAllObjects(); if (objects.includes(object) && this.selected != object) { var posInModel = Potree.Utils.datasetPosTransform({ toDataset: true, position: e.intersect.location.clone(), object }); this.selectModel(object, posInModel); } else { //if(!viewer.inputHandler.selection[0]){//正在平移和旋转,不允许取消 this.selectModel(null); //} } } else { //if(!viewer.inputHandler.selection[0]){ this.selectModel(null); //} } }); viewer.inputHandler.addEventListener('keydown', e => { if (e.event.key.toLowerCase() == "h") { this.fadeOutlineAuto = !this.fadeOutlineAuto; this.showModelOutline(this.selected, !!this.selected); } }); //viewer.fxaaPass.enabled = false//viewer.ssaaRenderPass.enabled = false viewer.outlinePass.enabled = true; //Potree.settings.intersectWhenHover = false //Potree.Utils.updateVisible(viewer.reticule, 'force', false) viewer.composer.scaleRatio = 1; viewer.composer.readTarget = false; viewer.mainViewport.camera.near = 0.05; // too small will result in z-fighting viewer.addEventListener('updateModelBound', e => { if (this.split) { this.SplitScreen.updateCameraOutOfModel( /* this.selected && [this.selected] */); } }); { //校准页面拖拽 //左右屏都可以拖拽模型,旋转只能左屏 var dragInfo; var drag = e => { if (this.split && this.selected && this.transformState && (e.dragViewport.name == 'top' || this.transformState == 'translate')) { if (e.type == 'global_mousedown') { //开始 //if((e.intersect.object || e.intersect.pointcloud) == this.selected){ if (e.intersect.pointclouds.includes(this.selected) || e.intersect.allElements.some(e => e.object == this.selected)) { dragInfo = {}; //if(this.selected.isPointcloud){ viewer.outlinePass.edgeStrength = 0; //暂时消失线 //} } } if (e.type == 'global_drag' && dragInfo) { if (this.transformState == 'translate') { var moveVec = Potree.Utils.getOrthoCameraMoveVec(e.drag.pointerDelta, e.dragViewport.camera); //最近一次移动向量 this.selected.position.add(moveVec); this.selected.dispatchEvent("position_changed"); } else if (this.transformState == 'rotate') { var vec = new Vector3().subVectors(e.intersect.orthoIntersect || e.intersect.location, this.selected.boundCenter).setZ(0); if (dragInfo.lastVec == void 0) { //global_mousedown dragInfo.lastVec = vec; return; } var angle = math.getAngle(dragInfo.lastVec, vec, 'z'); dragInfo.lastVec = vec; //this.selected.rotation.z += angle //局部 /* object.quaternion.copy( .setFromAxisAngle( new THREE.Vector3(0,0,1), angle ) ); object.quaternion.multiply( quaternionStart ).normalize(); */ var diffQua = new Quaternion().setFromAxisAngle(new Vector3(0, 0, 1), angle); this.selected.quaternion.premultiply(diffQua); //世界 this.selected.dispatchEvent("rotation_changed"); } return { stopContinue: true }; } } }; viewer.addEventListener('global_mousedown', drag); viewer.addEventListener('global_drag', drag, { importance: 10 }); viewer.addEventListener('global_mousemove', e => { if (this.split && this.transformState && !e.drag && (e.hoverViewport.name == 'top' || this.transformState == 'translate')) { /* if(this.lastHoverViewport != e.hoverViewport){ this.lastHoverViewport = e.hoverViewport this.transformControls.view = e.hoverViewport.view this.transformControls.camera = e.hoverViewport.camera this.transformControls.hideAxis( this.transformState, e.hoverViewport.name == 'top' ? [z] : [x,y]); } */ var mouseover = e.intersect.pointclouds.includes(this.selected) || e.intersect.allElements.some(e => e.object == this.selected); //let mouseover = (e.intersect.object || e.intersect.pointcloud) == this.selected if (mouseover) { if (this.transformState == 'translate') { viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "movePointcloud" }); } else { viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "rotatePointcloud" }); } } else { this.clearTranCursor(); } } }); viewer.addEventListener('global_drop', e => { dragInfo = null; this.clearTranCursor(); //this.updateEdgeStrength() viewer.outlinePass.edgeStrength = oriEdgeStrength; }); } /* viewer.addEventListener('background_changed',()=>{ }) */ viewer.addEventListener('camera_changed', () => { Common.intervalTool.isWaiting('updateMemoryUsage', () => { this.updateMemoryUsage(); }, 1000); }); viewer.addEventListener('setDisplay', this.updateMemoryUsage.bind(this)); }, clearTranCursor() { viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "movePointcloud" }); viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "rotatePointcloud" }); }, enterSplit() { this.split = true; if (this.selected) this.SplitScreen.focusCenter = this.selected.boundCenter; //旋转中心。注意 boundCenter不能直接赋值,否则改变后focusCenter也要改 else this.SplitScreen.focusCenter = null; this.SplitScreen.splitStart(viewportProps$1); this.beforeSplit = { pointDensity: Potree.settings.pointDensity }; Potree.settings.pointDensity = 'fourViewports'; //强制降低点云质量 viewer.setControls(viewer.fpControls); var rightViewport = viewer.viewports.find(e => e.name == 'right'); var topViewport = viewer.viewports.find(e => e.name == 'top'); topViewport.alignment = true; rightViewport.rotateSide = true; rightViewport.skyboxFixPos = true; rightViewport.skyboxMinZoom = 10; rightViewport.skyboxRenderFun = () => { // 使cube的一面永远正向镜头。 因侧视图的camera是ortho类型,需要平视mesh才不会拉伸 viewer.skybox.scene.children[0].rotation.copy(rightViewport.camera.rotation); }; topViewport.skyboxRenderFun = () => { viewer.skybox.scene.children[0].rotation.set(0, 0, 0); }; viewer.viewports[1].layersAdd('layer2'); viewer.viewports[0].layersAdd('layer1'); Potree.Utils.setObjectLayers(this.transformControls, 'layer1'); this.transformControls.view = viewer.viewports[0].view; this.transformControls.camera = viewer.viewports[0].camera; this.transformControls._gizmo.hideAxis = { translate: ['z'], rotate: ['x', 'y', 'z'] }; this.transformControls2.view = viewer.viewports[1].view; this.transformControls2.camera = viewer.viewports[1].camera; this.transformControls2._gizmo.hideAxis = { translate: ['x', 'y'], rotate: ['x', 'y', 'z'] }; this.secondCompass.changeViewport(viewer.viewports[0]); this.secondCompass.setDomPos(); this.secondCompass.setDisplay(true); viewer.compass.changeViewport(viewer.viewports[1]); viewer.compass.setDomPos(); //this.changeSkyboxGeo(true) }, leaveSplit() { this.split = false; this.SplitScreen.unSplit(); viewer.setControls(viewer.orbitControls); Potree.settings.pointDensity = this.beforeSplit.pointDensity; /* if(this.selected && this.selected.isPointcloud){ this.showModelOutline(this.selected, true) this.selected.material.activeAttributeName = "rgba" } */ this.transformControls.camera = viewer.viewports[0].camera; this.transformControls.view = viewer.viewports[0].view; this.transformControls._gizmo.hideAxis = { rotate: ['e'] }; Potree.Utils.setObjectLayers(this.transformControls, 'sceneObjects'); //恢复 viewer.compass.changeViewport(viewer.viewports[0]); //恢复 viewer.compass.setDomPos(); this.secondCompass.setDisplay(false); }, rotateSideCamera(angle) { this.SplitScreen.rotateSideCamera(viewer.viewports.find(e => e.name == 'right'), angle); }, setTransformState(state) { //校准时 this.transformState = state; this.clearTranCursor(); }, //--------------------------- getAllObjects() { return viewer.objs.children.concat(viewer.scene.pointclouds); }, getModel(id) { var models = this.getAllObjects(); return models.find(e => e.dataset_id == id); }, removeModel(model) { if (this.selected == model) this.selectModel(null); var dispose = e => { e.geometry && e.geometry.dispose(); e.material && e.material.dispose(); }; if (model.isPointcloud) { dispose(model); viewer.scene.removePointCloud(model); } else { model.traverse(e => { dispose(e); }); viewer.objs.remove(model); this.updateMemoryUsage(); } }, selectModel(model) { var state = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var fitBound = arguments.length > 2 ? arguments[2] : undefined; var by2d = arguments.length > 3 ? arguments[3] : undefined; if (!model) { model = this.selected; state = false; } if (state) { if (this.selected) { if (this.selected == model) return;else { var transToolAttached = !!this.transformControls.object; this.selectModel(this.selected, false, fitBound, by2d); transToolAttached && this.transformControls.attach(model); } } this.selected = model; MergeEditor.focusOn(model, 500, !!fitBound); //通过在场景里点击模型的话,不focus this.showModelOutline(model); //this.updateEdgeStrength() //console.log('selectModel', model) } else { if (this.selected != model) return; //model本来就没选中,不需要处理(防止2d先选中新的再取消旧的) this.showModelOutline(model, false); this.selected = null; this.transformControls.detach(); //viewer.transformObject(null); //console.log('selectModel', null) } if (!by2d && model) { model.dispatchEvent({ type: 'changeSelect', selected: state, clickPos: state }); } }, updateBoxHelper(model) { var size = new Vector3(); model.boundingBox.getSize(size); size.multiply(model.scale); this.boxHelper.scale.copy(size); var center = new Vector3(); model.boundingBox.getCenter(center); center.applyMatrix4(model.matrixWorld); //center.add(model.position) this.boxHelper.position.copy(center); this.boxHelper.quaternion.copy(model.quaternion); }, showModelOutline(model, state) { if (Potree.settings.mergeType2 || (model ? model.fileType == '3dgs' : this.boxHelper.visible)) { //高斯很卡 if (state !== false) { this.updateBoxHelper(model); Potree.Utils.updateVisible(this.boxHelper, 'unselect', true); } else { Potree.Utils.updateVisible(this.boxHelper, 'unselect', false); } return; } if (this.fadeOutlineAuto) { if (state === false) { viewer.outlinePass.selectedObjects = []; clearTimeout(this.timer); return; } viewer.outlinePass.selectedObjects = [model]; if (this.timer) { clearTimeout(this.timer); } this.timer = setTimeout(() => { viewer.outlinePass.selectedObjects = []; viewer.dispatchEvent('content_changed'); }, 1000); } else { if (state === false) { viewer.outlinePass.selectedObjects = []; } else { viewer.outlinePass.selectedObjects = [model]; } } viewer.dispatchEvent('content_changed'); }, /*updateEdgeStrength(){ if(!this.selected)return if(this.selected.isPointcloud){ viewer.outlinePass.edgeStrength = edgeStrengths.pointcloud// / this.selected.material.opacity }else{ viewer.outlinePass.edgeStrength = edgeStrengths.glb } },*/ focusOn(objects) { var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 400; var fitBound = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var dontLookUp = arguments.length > 3 ? arguments[3] : undefined; if (!(objects instanceof Array)) { objects = [objects]; } var boundingBox = new Box3(); objects.forEach(object => { boundingBox.union(object.boundingBox.clone().applyMatrix4(object.matrixWorld)); }); var len = boundingBox.getSize(new Vector3()).length(); Potree.settings.cameraFar = Math.max(Potree.settings.cameraFar, len * 3); if (fitBound) { viewer.focusOnObject({ boundingBox }, 'boundingBox', duration, { dontLookUp, dontChangeCamDir: true }); } else { /* let position = viewer.inputHandler.intersect ? viewer.inputHandler.intersect.location : boundingBox.getCenter(new THREE.Vector3) position && viewer.focusOnObject({position}, 'point', duration, {dontChangePos: true}) */ var position = viewer.inputHandler.intersect ? viewer.inputHandler.intersect.location : boundingBox.getCenter(new Vector3()); if (!position) return; /* let targetOld = viewer.mainViewport.view.getPivot() let projected1 = targetOld.clone().project(viewer.mainViewport.camera); let projected2 = position.clone().project(viewer.mainViewport.camera); //使用其z let targetNew = projected1.clone().setZ(projected2.z).unproject(viewer.mainViewport.camera); viewer.mainViewport.view.lookAt(targetNew) */ viewer.mainViewport.view.radius = viewer.mainViewport.camera.position.distanceTo(position); //为了不改画面,不调节方向了,只能调调radius,一定程度将target靠近model } }, moveBoundCenterTo(model, pos) { //使boundCenter在所要的位置 var diff = new Vector3().subVectors(pos, model.boundCenter); model.position.add(diff); }, getBoundCenter(model) { if (!model.boundCenter) model.boundCenter = new Vector3(); model.boundingBox.getCenter(model.boundCenter).applyMatrix4(model.matrixWorld); }, setModelBtmHeight(model, z) { //无论模型怎么缩放、旋转,都使最低点为z if (z == void 0) z = model.btmHeight; //维持离地高度 else model.btmHeight = z; if (model.btmHeight == void 0) return; model.updateMatrixWorld(); var boundingBox2 = model.boundingBox.clone().applyMatrix4(model.matrixWorld); var size = boundingBox2.getSize(new Vector3()); var center = boundingBox2.getCenter(new Vector3()); var hopeZ = z + size.z / 2; //model.position.z = z + size.z / 2 - center.z model.position.z += hopeZ - center.z; }, computeBtmHeight(model) { //位移之后重新计算btmHeight model.updateMatrixWorld(); var boundingBox2 = model.boundingBox.clone().applyMatrix4(model.matrixWorld); var size = boundingBox2.getSize(new Vector3()); var center = boundingBox2.getCenter(new Vector3()); model.btmHeight = center.z - size.z / 2; }, maintainBoundXY(model) { //在旋转和缩放后,立即执行这个函数,使boundCenter保持原位 model.updateMatrixWorld(); var center1 = model.boundCenter.clone(); //还未更新的 this.getBoundCenter(model); //更新 var center2 = model.boundCenter.clone(); var diff = new Vector2().subVectors(center1, center2); model.position.x += diff.x; model.position.y += diff.y; model.boundCenter.copy(center1); }, maintainBoundCenter(model) { model.updateMatrixWorld(); var center1 = model.boundCenter.clone(); //还未更新的 this.getBoundCenter(model); //更新 var center2 = model.boundCenter.clone(); var diff = new Vector3().subVectors(center1, center2); model.position.add(diff); model.boundCenter.copy(center1); }, modelTransformCallback(model, force) { model.updateMatrixWorld(); if (!force && model.matrixWorld.equals(model.lastMatrixWorld)) return; viewer.scene.measurements.forEach(measure => { var changed; measure.points_datasets.forEach((dataset_id, i) => { if (dataset_id == model.dataset_id) { changed = true; measure.points[i] = Potree.Utils.datasetPosTransform({ fromDataset: true, datasetId: dataset_id, position: measure.dataset_points[i].clone() }); measure.updateMarker(measure.markers[i], measure.points[i]); } }); if (changed) { //仿transformByPointcloud measure.getPoint2dInfo(measure.points); measure.update(); measure.setSelected(false); //隐藏edgelabel } }); //反向求transformMatrix 参考Alignment.js 移动漫游点 if (model.isPointcloud && model.transformMatrix) { model.transformMatrix.multiplyMatrices(model.matrix, model.pos1MatrixInvert); model.transformInvMatrix.copy(model.transformMatrix).invert(); model.rotateMatrix = new Matrix4().makeRotationFromEuler(model.rotation); model.panos.forEach(e => e.transformByPointcloud()); } else if (model.panos) { model.rotateMatrix = new Matrix4().makeRotationFromEuler(model.rotation).multiply(model.rot1MatrixInvert); model.transformMatrix.multiplyMatrices(model.matrix, model.posRot1MatrixInvert); model.panos.forEach(e => e.transformByPointcloud()); model.bound = model.boundingBox.clone().applyMatrix4(model.matrixWorld); } model.lastMatrixWorld = model.matrixWorld.clone(); viewer.dispatchEvent('content_changed'); viewer.mapViewer && Potree.settings.showObjectsOnMap && viewer.mapViewer.dispatchEvent('content_changed'); //-------- this.updateBoxHelper(model); }, changeOpacity(model, opacity) { var isRoot = model.dataset_id != void 0; //是否是最外层 if (model.isPointcloud) { model.changePointOpacity(opacity); //MergeEditor.updateEdgeStrength() } else { //model.traverse(e=>e.material && setOp(e, opacity)) model.traverse(mesh => { if (mesh.material) { if (mesh.material.originOpacity == void 0) { mesh.material.originOpacity = mesh.material.opacity; } mesh.material.opacity = mesh.material.originOpacity * opacity; if (mesh.material.opacity < 1) { mesh.material.transparent = true; /* if(model.isPointcloud){ mesh.changePointOpacity(realOpacity) }else{ mesh.material.opacity = realOpacity } */ mesh.renderOrder = Potree.config.renderOrders.model + 1; //mesh.material.depthWrite = false } else { mesh.material.transparent = false; mesh.renderOrder = Potree.config.renderOrders.model; //mesh.material.depthWrite = true } mesh.material.depthWrite = mesh.material.opacity > 0.3; } }); } isRoot && (model.opacity = opacity); //记录在最外层 viewer.dispatchEvent('content_changed'); }, modelAdded(model) { model.addEventListener('isVisible', e => { if (e.reason == "overlinePass") return; //console.log(e) viewer.addEventListener('update', () => { //下一次更新结束后 this.updateMemoryUsage(); }, { once: true }); }); this.updateMemoryUsage(); }, updateMemoryUsage() { //obj暂时不管其贴图大小, 因为顶点造成的不仅是内存还有卡顿所以先只看顶点 var maxMemory = Potree.config.tiles3DMaxMemory + 100; //M 实际估计是这个的10倍 var eachObjPosWeight = 100 / 1000 / 1000; //M 每个顶点pos是3*4个字节?法线3*4和uv2*4 其实还有贴图 var eachCloudPointWeight = 12 / 1000 / 1000; //M 每个点 pos + 颜色 + 法线 大概 var eachVisiCPointWeight = eachCloudPointWeight * 5; // 或 maxMemory / (6*1000*1000) 大概值接近 (再除以一个数是因为显示的要比内存中的耗更多资源 var eachGltfPosWeight = 100 / 1000 / 1000; //M 每个顶点pos是3*4个字节?法线3*4和uv2*4 其实还有贴图 var posCount = 0; viewer.objs.children.forEach(e => { if (!e.visible) return; if (e.fileType == 'glb' || e.fileType == 'obj') { e.traverse(mesh => { if (mesh.geometry) { posCount += mesh.geometry.attributes.position.count; } }); } else if (e.fileType == '3dTiles') {} }); //获取点云的内存限制 var objWeight = posCount * eachObjPosWeight; var laserWeight = Potree.numVisiblePoints * eachCloudPointWeight; //点云实际显示所占大小 var laserMemoryWeight = Potree.lru.numPoints * eachCloudPointWeight; //点云所使用内存大小 var tiles3DWeight = viewer.tiles3dVisiVCount * eachGltfPosWeight; //M 3dTiles所占内存大小 var tiles3DMemoryWeight = viewer.tiles3dMemoryUsage / 1000 / 1000; //M 3dTiles显示的所占内存大小 /* let min = 0.1, max = 6, minP = 100, maxP = 1000000; let ratio = Math.round(math.linearClamp(score, minP, maxP, max, min )); */ var rest = maxMemory - objWeight - tiles3DWeight; Potree.pointBudget = MathUtils.clamp(Math.round(rest / eachVisiCPointWeight), Potree.config.pointDensity.low.pointBudget, 1.5 * Potree.config.pointDensity.high.pointBudget); //获取3dTiles的内存限制 var tiles3DMaxMemory = maxMemory - Math.round(objWeight + laserWeight); Potree.settings.tiles3DMaxMemory = MathUtils.clamp(tiles3DMaxMemory, 30, Potree.config.tiles3DMaxMemory); //还存在的问题:仍然有隐患,因为没用到真实缓存的大小: tiles3DMemoryWeight laserMemoryWeight, 它们比真实可见的要多。不使用是因为它们无法反应出实际需要的内存量,缓存是只增不减 //obj等普通mesh限制不了 //console.log('objWeight',objWeight.toFixed(1), 'laserMemoryWeight',laserMemoryWeight.toFixed(1), 'tiles3DWeight',tiles3DWeight.toFixed(1), 'pointBudget',Potree.pointBudget, 'tiles3DMaxMemory',tiles3DMaxMemory) //总内存 = 内存占用空间+图片缓存 , obj的缓存比较多在图片中 }, setGroundPlaneImg(src, scale, angle) { //设置地面图 this.goundScale = scale || 1, this.goundAngle = angle || 0; var oldSrc = this.curGroundImgSrc; this.curGroundImgSrc = src; var ratio = 0.03; if (src) { if (oldSrc == src && this.groundPlane.material.map.image) { //仅修改大小 var s = ratio * this.goundScale; var { width, height } = this.groundPlane.material.map.image; this.groundPlane.scale.set(width * s, height * s); viewer.dispatchEvent('content_changed'); this.groundPlane.rotation.z = MathUtils.degToRad(this.goundAngle); return; } var map = texLoader$a.load(src, tex => { if (this.curGroundImgSrc == src) { var _s = ratio * this.goundScale; this.groundPlane.scale.set(tex.image.width * _s, tex.image.height * _s); this.groundPlane.rotation.z = MathUtils.degToRad(this.goundAngle); viewer.dispatchEvent('content_changed'); } }); Potree.Utils.makeTexDontResize(map); if (!this.groundPlane) { this.groundPlane = new Mesh(new PlaneBufferGeometry(1, 1, 1), new MeshBasicMaterial({ map, side: 2 })); viewer.scene.scene.add(this.groundPlane); this.groundPlane.position.z = 0.1; } else { this.groundPlane.material.map = map; } Potree.Utils.updateVisible(this.groundPlane, 'show', true); } else { this.groundPlane && Potree.Utils.updateVisible(this.groundPlane, 'show', false); } } }; /* note: 要注意getHoveredElements只在getIntersect时才使interactables包含加载的model, 也就是model上不能有使之成为interactables的事件,否则在鼠标hover到模型上开始转动的一瞬间很卡。 */ var texLoader$b = new TextureLoader(); var arrowSpacing = 1; //间隔 var arrowSize = arrowSpacing * 0.5; var planeGeo$3 = new PlaneBufferGeometry(1, 1); var sphereSizeInfo = { nearBound: 0.1, farBound: 25, minSize: 50, maxSize: 200 //scale:arrowSize, restricMeshScale : true, }; //const arrowsShowingCount = 25; //场景里最多展示多少个箭头 var arrowShowMinDis = 10; class RouteGuider extends EventDispatcher { constructor() { super(); this.route = []; this.curve = []; this.scenePoints = []; this.sceneMeshGroup = new Object3D(); this.mapMeshGroup = new Object3D(); this.generateDeferred; viewer.addEventListener('loadPointCloudDone', this.init.bind(this)); this.lastResult; //保存上一个的结果,以便于反向 this.datasetIds = []; //起始和终点的datasetId } init() { if (this.inited) return; var zoom, resolution = new Vector2(); viewer.mapViewer.addEventListener('camera_changed', e => { if (!this.routeStart || !this.routeEnd) return; var camera = e.viewport.camera; if (camera.zoom != zoom || !resolution.equals(e.viewport.resolution)) { Common.intervalTool.isWaiting('routeCameraInterval', () => { //延时update,防止卡顿 if (camera.zoom != zoom || !resolution.equals(e.viewport.resolution)) { //console.log('updateMapArrows') this.updateMapArrows(true); zoom = camera.zoom; resolution.copy(e.viewport.resolution); } }, browser.isMobile() ? 500 : 200); } }); viewer.addEventListener('camera_changed', e => { if (!this.routeStart || !this.routeEnd || !e.changeInfo.positionChanged) return; Common.intervalTool.isWaiting('routeCameraInterval2', () => { //延时update,防止卡顿 this.updateArrowDisplay(); }, 1000); }); var polesMats = { shadowMat: new MeshBasicMaterial({ transparent: true, depthTest: false, map: texLoader$b.load(Potree.resourcePath + '/textures/pano_instruction_bottomMarker.png') }), sphereMat: new MeshBasicMaterial({ transparent: true, depthTest: false, map: texLoader$b.load(Potree.resourcePath + '/textures/whiteCircle.png') }), hatMats: { start: new MeshBasicMaterial({ transparent: true, depthTest: false, map: texLoader$b.load(Potree.resourcePath + '/textures/pano_instruction_start_route.png') }), end: new MeshBasicMaterial({ transparent: true, depthTest: false, map: texLoader$b.load(Potree.resourcePath + '/textures/pano_instruction_target_reached.png') }) } }; polesMats.shadowMat.map.anisotropy = 4; this.poleStart = this.createPole(polesMats, 'start'); this.poleEnd = this.createPole(polesMats, 'end'); this.sceneMeshGroup.add(this.poleStart); this.sceneMeshGroup.add(this.poleEnd); var map = texLoader$b.load(Potree.resourcePath + '/textures/routePoint_panorama.png'); map.anisotropy = 4; // 各向异性过滤 .防止倾斜模糊 this.arrow = new Mesh(planeGeo$3, new MeshBasicMaterial({ transparent: true, depthTest: false, map })); this.arrow.scale.set(arrowSize, arrowSize, arrowSize); Potree.Utils.setObjectLayers(this.arrow, 'sceneObjects'); /* this.testArrow = this.arrow.clone(); this.testArrow.material = this.arrow.material.clone() this.testArrow.material.color = 'red' */ this.arrows = new Object3D(); this.sceneMeshGroup.add(this.arrows); Potree.Utils.setObjectLayers(this.sceneMeshGroup, 'sceneObjects'); //this.sceneMeshGroup.traverse(e=>e.renderOrder = 90) viewer.scene.scene.add(this.sceneMeshGroup); this.sceneMeshGroup.visible = false; this.poleStart.visible = false; this.poleEnd.visible = false; //-------------map--------------------- /* this.mapMarkStart = new THREE.Mesh( planeGeo, new THREE.MeshBasicMaterial({ transparent:true, depthTest:false, map: texLoader.load(Potree.resourcePath+'/textures/map_instruction_start_route.png' ) })) this.mapMarkEnd = new THREE.Mesh( planeGeo, new THREE.MeshBasicMaterial({ transparent:true, depthTest:false, map: texLoader.load(Potree.resourcePath+'/textures/map_instruction_target_reached.png' ) })) this.mapMarkStart.renderOrder = this.mapMarkEnd.renderOrder = 2//在箭头之上 */ var map2 = texLoader$b.load(Potree.resourcePath + '/textures/routePoint_map_fsna.png'); this.mapArrowMats = { default: new MeshBasicMaterial({ transparent: true, depthTest: false, map: map2 }), fade: new MeshBasicMaterial({ transparent: true, depthTest: false, map: map2, opacity: 0.4 }) }; this.mapArrow = new Mesh(planeGeo$3, this.mapArrowMats.default); this.mapArrow.scale.set(arrowSize, arrowSize, arrowSize); this.mapArrows = new Object3D(); this.mapArrows.name = 'mapArrows'; this.mapMeshGroup.add(this.mapArrows); this.mapMeshGroup.name = 'mapRouteLayer'; this.mapMeshGroup.visible = false; viewer.mapViewer.dispatchEvent({ type: 'add', object: this.mapMeshGroup, name: 'route' }); this.mapArrow.layers.mask = this.mapArrows.layers.mask; // 修改成和map中的layer一样的 viewer.modules.SiteModel.bus.addEventListener('FloorChange', () => { if (this.routeStart && this.routeEnd) { this.updateOpacityAtMap(); } }); this.inited = true; } updateOpacityAtMap() { //只有当前楼层的透明度为1 var currentFloor = viewer.modules.SiteModel.currentFloor; //console.log('updateOpacityAtMap', currentFloor && currentFloor.name) var lift = 0.3; // 因为发送请求时用的是floorPosition的高度,而它可能会到画好的floor之下,所以有误差 this.mapArrows.children.forEach((arrow, index) => { var pos = this.mapPoints[index].clone(); pos.z += lift; var inSide = currentFloor && currentFloor.ifContainsPoint(pos); arrow.material = inSide ? this.mapArrowMats.default : this.mapArrowMats.fade; //console.log('arrow',index, arrow.material.opacity) }); viewer.mapViewer.dispatchEvent('content_changed'); } //但是如果楼层刚好只框柱相机位置而没框住地面位置就不好了…… createPole(polesMats, name) { var height = 1.5, sphereCount = 6, shadowSize = 0.5 /* sphereSizeInfo.scale */, sphereSize = 0.05; var group = new Object3D(); group.name = 'pole_' + name; var shadow = new Mesh(planeGeo$3, polesMats.shadowMat); shadow.scale.set(shadowSize, shadowSize, shadowSize); var sliceDis = height / (sphereCount + 1); group.add(shadow); for (var i = 0; i < sphereCount; i++) { var sphere = new Sprite$2({ mat: polesMats.sphereMat, renderOrder: 3 }); sphere.position.set(0, 0, sliceDis * (i + 1)); sphere.scale.set(sphereSize, sphereSize, sphereSize); //sphere.visible = false group.add(sphere); } var hatSphere = new Sprite$2({ mat: polesMats.hatMats[name], sizeInfo: sphereSizeInfo, renderOrder: 4 }); //sphere.visible = false hatSphere.position.set(0, 0, height); hatSphere.scale.copy(shadow.scale); group.add(hatSphere); group.hatSphere = hatSphere; return group; } addTestArrow() {} addArrow(position) { var arrow = this.arrow.clone(); arrow.position.copy(position); this.arrows.add(arrow); } addMapArrow(position) { var mapArrow = this.mapArrow.clone(); mapArrow.position.copy(position).setZ(0); this.mapArrows.add(mapArrow); } setArrowDir(arrows, index) { var arrow = arrows[index]; var nextOne = arrows[index + 1]; var nextPos = nextOne ? nextOne.position : this.endPolePos; //routeEnd var direction = new Vector3().subVectors(arrow.position, nextPos).setZ(0); //direction.normalize(); //console.log(direction.toArray()) var angle = Math.atan2(direction.y, direction.x) + Math.PI / 2; //Math.PI/2是因为贴图本身箭头方向不朝x arrow.rotation.z = angle; //console.log(angle) } setRouteStart(pos, dealZ, datasetId) { if (this.routeStart && pos && this.routeStart.equals(pos)) return; //可能重复设置 this.routeStart = pos && new Vector3().copy(pos); if (dealZ && this.routeStart) { this.routeStart.setZ(this.getZAtMap()); this.bus && this.bus.emit('reposStartMarker', this.routeStart); } console.log('setRouteStart', this.routeStart && this.routeStart.toArray()); this.datasetIds[0] = datasetId; //this.setStartPole(pos) this.poleStart.visible = !!pos; pos && this.poleStart.position.copy(this.routeStart); pos && this.poleStart.hatSphere.waitUpdate(); this.generateRoute(); viewer.dispatchEvent('content_changed'); } setStartPole(pos) { this.startPolePos = pos; this.bus && this.bus.emit('reposStartMarker', pos); } setRouteEnd(pos, dealZ, datasetId) { if (this.routeEnd && pos && this.routeEnd.equals(pos)) return; this.routeEnd = pos && new Vector3().copy(pos); if (dealZ && this.routeEnd) { this.routeEnd.setZ(this.getZAtMap()); this.bus && this.bus.emit('reposEndMarker', this.routeEnd); } console.log('setRouteEnd', this.routeEnd && this.routeEnd.toArray()); this.datasetIds[1] = datasetId; //this.setEndPole(pos) this.poleEnd.visible = !!pos; pos && this.poleEnd.position.copy(this.routeEnd); pos && this.poleEnd.hatSphere.waitUpdate(); this.generateRoute(); viewer.dispatchEvent('content_changed'); } getZAtMap() { //找到position.z与当前高度最接近的漫游点 var result = Common.sortByScore(viewer.images360.panos, [], [e => -Math.abs(e.position.z - viewer.images360.position.z)]); var pano = result && result[0] && result[0].item; return pano ? pano.floorPosition.z : viewer.bound.boundingBox.min.z + 1; //若在平面图上画实在得不到当前楼层的,大概率是楼层画得不好,那就只能去获取当前楼层的了 //navvis的高度取的是主视图所在楼层的中心高度(可能再高些) } setEndPole(pos) { this.endPolePos = pos; this.bus && this.bus.emit('reposEndMarker', pos); } getSourceProjectionIndex(route) { //真正的起始 var e = route.findIndex(function (t) { return t.instruction && t.instruction.type === 'source_projection_to_navgraph'; }); return e < 0 ? 0 : e; } getDestinationProjectionIndex(route) { //真正的终点 var e = route.findIndex(function (t) { return t.instruction && t.instruction.type === "destination_projection_to_navgraph"; }); return e < 0 ? route.length - 1 : e; } generateRoute() { this.sceneMeshGroup.visible = true; if (!this.routeStart || !this.routeEnd) { return; } var initialPointcloud = viewer.scene.pointclouds.find(e => e.dataset_id == Potree.settings.originDatasetId); //array.reduce(function(total, currentValue, currentIndex, arr), initialValue) var create = () => { this.routeLength = this.route.reduce((total, currentValue, currentIndex, arr) => { if (currentIndex == 0) return 0; return total + currentValue.distanceTo(arr[currentIndex - 1]); }, 0); var count = Math.max(2, Math.round(this.routeLength / arrowSpacing)); //点数 var curve = new CatmullRomCurve3(this.route); curve.curveType = 'chordal'; //'centripetal' 'catmullrom'这个可能会超出路径外 this.curve = curve; var scenePoints = curve.getSpacedPoints(count); //更平均 //const scenePoints = curve.getPoints( count ); scenePoints.splice(0, 1); //去掉首尾 scenePoints.pop(); this.scenePoints = scenePoints; this.updateMapArrows(); this.displayRoute(); { //map focus on this area var minBound = new Vector2(1, 1); //针对垂直线,在地图上只有一个点 var bound = new Box2(); this.route.forEach(e => { bound.expandByPoint(e); }); var size = bound.getSize(new Vector2()); var markerSize = new Vector2(115, 40); //起始和终点的标识呈长方形 var areaSize = viewer.mapViewer.viewports[0].resolution2; var areaArea = areaSize.x * areaSize.y; if (areaArea > 800 * 400) { //是放大的 markerSize.multiplyScalar(areaArea / (800 * 400) /* / (size.x * size.y) */); } var margin = size.clone().divide(viewer.mapViewer.viewports[0].resolution2).multiply(markerSize); ///边距 重点是起始和终点的标识占据较大 size.add(margin); var center = bound.getCenter(new Vector2()); size.x = Math.max(size.x, minBound.x); size.y = Math.max(size.y, minBound.y); var duration = 1000; viewer.mapViewer.moveTo(center, size, duration); } this.bus.emit('gotResult', { dis: this.routeLength }); /* this.generateDeferred && this.generateDeferred.resolve({dis:this.routeLength}) this.generateDeferred = null */ }; if (Potree.fileServer) { var dealData = data => { if (!data.data) { console.log('没有数据'); var result; if (data && data.code == 4002) { result = data; //正被修改数据集 } else if (this.routeStart.distanceTo(this.routeEnd) < 1) { result = { code: 500, msg: '距离太短,无法规划路线' }; } else { result = { code: 500, msg: '超出数据集范围,无法规划路线' }; } this.clearRoute(); this.setStartPole(this.routeStart); this.setEndPole(this.routeEnd); this.displayRoute(); //还是要显示一下起始 this.bus && this.bus.emit('gotResult', result); return; //this.generateDeferred && this.generateDeferred.resolve() } data = data.data; this.clearRoute(); var length = data.length; if (length < 2) { //可能距离太短 console.log('路径点数为' + length + ',直接取起点和终点连线'); this.route = [this.routeStart, this.routeEnd]; } else { var startIndex = this.getSourceProjectionIndex(data); var endIndex = this.getDestinationProjectionIndex(data); var effectiveItems = data.slice(startIndex, endIndex + 1); //只要点云范围内的点 effectiveItems.forEach((item, i) => { //let pos = viewer.transform.lonlatToLocal.forward(item.location.slice(0)/* ,true */) var pos = item.location.slice(0); pos = new Vector3().fromArray(pos); //.setZ(item.z) pos.z -= initialPointcloud.datasetData.location[2]; this.route.push(pos); }); //console.log('route', this.route) } this.setStartPole(this.route[0]); this.setEndPole(this.route[this.route.length - 1]); create(); /* distance: 0.17581000000000116 distance_to_previous: 0.17581000000000116 id: 567 instruction: {type: 'source_projection_to_navgraph'} latitude: 22.366605927999238 location: (3) [113.5957510575092, 22.366605927999238, -1.12419] longitude: 113.5957510575092 z: -1.12419 */ }; if (this.lastResult && (this.lastResult.data || this.lastResult.data.code != 4002)) { //正被修改数据集的话要重新计算 var data = Common.CloneObject(this.lastResult.data), use; //直接用上次的结果 if (this.lastResult.routeStart.equals(this.routeStart) && this.lastResult.routeEnd.equals(this.routeEnd)) { //和上次请求相同 use = true; } else if (this.lastResult.routeStart.equals(this.routeEnd) && this.lastResult.routeEnd.equals(this.routeStart)) { //..反向 use = true; if (data.data) { data.data = this.lastResult.data.data.slice(0).reverse(); } } if (use) { console.log('直接用上次的结果'); return setTimeout(() => { dealData(data); }, 1); //延迟是为了等待获得 RouteGuider.generateDeferred } } var start = this.routeStart.clone(); var end = this.routeEnd.clone(); //let startLonlat = viewer.transform.lonlatToLocal.inverse(start/* , true */) //let endLonlat = viewer.transform.lonlatToLocal.inverse(end/* , true */) /* var query = { source_longitude: start.x, source_latitude: start.y, source_z: start.z, destination_longitude: end.x, destination_latitude: end.y, destination_z: end.z }; */ var query = { source_longitude: start.x, source_latitude: start.y, source_z: start.z + initialPointcloud.datasetData.location[2], destination_longitude: end.x, destination_latitude: end.y, destination_z: end.z + initialPointcloud.datasetData.location[2] }; /* var query = { source_longitude: startLonlat.x, source_latitude: startLonlat.y, source_z: start.z, destination_longitude: endLonlat.x, destination_latitude: endLonlat.y, destination_z: end.z }; */ //let url = `/laser/route/${Potree.settings.number}/getRoute/${this.datasetIds[0]}/${this.datasetIds[1]}?` var url = "/laser/route/".concat(Potree.settings.number, "/getRoute/").concat(Potree.settings.originDatasetId, "?"); for (var i in query) { url += i + '=' + query[i] + '&'; } Potree.fileServer.get(url).then(data => { //console.log('data', data.data) if (!this.routeStart || !this.routeEnd) return; this.lastResult = { //保存数据 routeStart: this.routeStart.clone(), routeEnd: this.routeEnd.clone(), data }; dealData(data); }); } else { //创个直线 /* const sliceDis = 1 let dis = this.routeStart.distanceTo(this.routeEnd); let count = Math.max(2,Math.round(dis / sliceDis))//点数 let realSlideDis = dis / (count-1); let dir = new THREE.Vector3().subVectors(this.routeEnd, this.routeStart).normalize().multiplyScalar(realSlideDis); this.route = [this.routeStart]; for(let i=0;i 300; var count = Math.max(2, Math.round(this.routeLength * zoom / arrowSpacing / (isBig ? 35 : 30))); //点数 if (count == this.mapPoints.length + 1) return; //没变 var mapPoints = this.curve.getSpacedPoints(count); mapPoints.splice(0, 1); //去掉首尾 mapPoints.pop(); this.mapPoints = mapPoints; var scale = (isBig ? 26 : 22) / zoom; this.mapArrow.scale.set(scale, scale, scale); /* this.mapMarkStart.scale.set(scale,scale,scale) this.mapMarkEnd.scale.set(scale,scale,scale) */ if (ifReset) { //因为缩放而重新排布箭头 this.clearRoute({ resetMap: true }); this.displayRoute({ resetMap: true }); } this.updateOpacityAtMap(); } updateArrowDisplay() { //根据当前位置更新显示一定范围内的箭头 if (this.scenePoints.length == 0) return; /* var a = Common.sortByScore(this.scenePoints , null, [(point)=>{ //是否还要再requires里限制最远距离? var playerPos = viewer.scene.getActiveCamera().position.clone().setZ(0) var pos = point.clone().setZ(0) return -pos.distanceTo(playerPos); }]); //获得展示的起始点 let start = a[0].item let startIndex = this.scenePoints.indexOf(start) this.arrows.children.forEach((e,i)=>{ if(istartIndex+arrowsShowingCount)e.visible = false else e.visible = true }) */ var cameraPos = viewer.scene.getActiveCamera().position; this.arrows.children.forEach((e, i) => { if (e.position.distanceTo(cameraPos) < arrowShowMinDis) e.visible = true;else e.visible = false; }); viewer.dispatchEvent('content_changed'); } displayRoute() { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (!o.resetMap) { this.poleStart.position.copy(this.startPolePos || this.routeStart); this.poleEnd.position.copy(this.endPolePos || this.routeEnd); /* this.mapMarkStart.position.copy(this.routeStart).setZ(0) this.mapMarkEnd.position.copy(this.routeEnd).setZ(0) */ this.scenePoints.forEach(e => this.addArrow(e)); this.arrows.children.forEach((e, i) => this.setArrowDir(this.arrows.children, i)); } this.sceneMeshGroup.visible = true; //.traverse(e=>e.visible = true) this.mapMeshGroup.visible = true; this.mapPoints.forEach(e => this.addMapArrow(e)); this.mapArrows.children.forEach((e, i) => this.setArrowDir(this.mapArrows.children, i)); viewer.mapViewer.dispatchEvent({ 'type': 'content_changed' }); this.updateArrowDisplay(); } clearRoute() { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (!o.resetMap) { this.routeLength = 0; this.route = []; this.scenePoints = []; this.mapPoints = []; var arrows = this.arrows.children.slice(0); arrows.forEach(e => { this.arrows.remove(e); }); } var mapArrows = this.mapArrows.children.slice(0); mapArrows.forEach(e => { this.mapArrows.remove(e); }); this.sceneMeshGroup.visible = false; //this.sceneMeshGroup.traverse(e=>e.visible = false) //包括sprite也要设置,防止update this.mapMeshGroup.visible = false; viewer.mapViewer.dispatchEvent({ 'type': 'content_changed' }); viewer.dispatchEvent('content_changed'); } clear() { //退出 console.log('导航clear'); this.routeStart = null; this.routeEnd = null; this.clearRoute(); } } //大概每十米要花一秒 /* 存在的问题: 路径不准确。起始点和终点偏移。 https://uat-laser.4dkankan.com/routeDebug/ 可查整个map的通路点位图 */ //import History from "../../utils/History.js" var cameraProps$1 = [{ name: 'top', axis: ["x", "y"], direction: new Vector3(0, 0, -1), //镜头朝向 openCount: 0 }]; class Clipping extends EventDispatcher { //实时剪裁 constructor() { super(); this.views = {}; this.cameras = {}; this.orthoCamera = new OrthographicCamera(-100, 100, 100, 100, 0.01, 10000); this.orthoCamera.up.set(0, 0, 1); } init() { if (this.inited) return; this.initViews(); this.inited = true; this.prepareRecord = true; this.activeViewName = 'mainView'; this.events = { transfromCallback: e => { //拖拽变化时 this.adjustCamHeight(); //检测漫游点、回退等 /* if(this.prepareRecord){ let box = viewer.transformationTool.selection[0] this.history.writeIn({box, matrix:box.matrix.clone()}) this.prepareRecord = false } */ }, /* onTransfromEnd:(e)=>{//拖拽结束、松开 this.prepareRecord = true }, */ selectCallback: e => { this.adjustCamHeight(); var unableNavigate = this.activeViewName != 'mainView' || e.selection.length > 0; if (Potree.settings.unableNavigate && !unableNavigate) { setTimeout(() => { Potree.settings.unableNavigate = this.activeViewName != 'mainView' || e.selection.length > 0; }, 300); //延迟是因为点击时取消选择后可能立即就会触发flyToPano。 而且有的人喜欢点两下 } else Potree.settings.unableNavigate = unableNavigate; }, onkeydown: e => { if (e.keyCode == 8 || e.keyCode == 46) { // Backspace or Delete viewer.inputHandler.selection[0] && viewer.scene.removeVolume(viewer.inputHandler.selection[0]); } } }; /* this.history = new History({ //也可以写到全局,但需要加个判断物品是否存在的函数 applyData: (data)=>{ if(viewer.scene.volumes.includes(data.box)){ data.matrix.decompose( data.box.position, data.box.quaternion, data.box.scale ); }else{ this.history.undo()//找不到就回退下一个。(直接写这?) } } }) */ } initViews() { this.splitScreenTool = new SplitScreen(); for (var i = 0; i < 1; i++) { var prop = cameraProps$1[i]; var view = new ExtendView(); this.views[prop.name] = view; this.cameras[prop.name] = this.orthoCamera; view.direction = prop.direction; } this.views.mainView = viewer.mainViewport.view; this.cameras.mainView = viewer.mainViewport.camera; } switchView(name) { //替换view和camera到mainViewport if (this.activeViewName == name) return; var view = this.views[name]; var camera = this.cameras[name]; var prop = cameraProps$1.find(e => e.name == name); var { boundSize, center, boundingBox } = viewer.bound; this.lastViewName = this.activeViewName; this.activeViewName = name; var lastView = this.views[this.lastViewName]; var lastCamera = this.cameras[this.lastViewName]; viewer.mainViewport.view = view; viewer.mainViewport.camera = camera; if (lastCamera) lastView.zoom = lastCamera.zoom; /* if(lastView){//2d->3d view.copy(lastView) } */ if (name == 'mainView') { Potree.settings.unableNavigate = false; /* viewer.transformationTool.handles['scale.z+'].node.visible = true viewer.transformationTool.handles['scale.z-'].node.visible = true */ } else { Potree.settings.unableNavigate = true; /* viewer.transformationTool.handles['scale.z+'].node.visible = false viewer.transformationTool.handles['scale.z-'].node.visible = false */ if (prop.openCount == 0) { //至多执行一次 //this.viewportFitBound(name, boundSize, center) this.orthoMoveFit(center, { bound: boundingBox }, 0); this.camHeightOutOfModel = view.position.z; //记录下此刻相机高度。 } prop.openCount++; this.adjustCamHeight(); /* this.targetPlane.setFromNormalAndCoplanarPoint( view.direction.clone(), center ) this.targetPlane.projectPoint(view.position, this.shiftTarget ) //target转换到过模型中心的平面,以保证镜头一定在模型外 view.position.copy(this.splitScreenTool.getPosOutOfModel(viewer.mainViewport)) */ if (view.zoom) camera.zoom = view.zoom; //恢复上次的zoom } viewer.updateScreenSize({ forceUpdateSize: true }); //更新camera aspect left等 if (viewer.inputHandler.selection.length) { this.focusOnObject(viewer.inputHandler.selection[0]); } } focusOnObject(box) { var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; if (this.activeViewName == 'mainView') { viewer.focusOnObject({ boundingBox: box.boundingBox.clone().applyMatrix4(box.matrixWorld) }, 'boundingBox', duration); } else { this.orthoMoveFit(box.position, { bound: box.boundingBox.clone().applyMatrix4(box.matrixWorld) }, duration); } this.adjustCamHeight(); } orthoMoveFit(pos, info, duration) { var margin = { x: viewer.mainViewport.resolution.x * 0.4, y: viewer.mainViewport.resolution.y * 0.4 }; this.splitScreenTool.viewportFitBound(viewer.mainViewport, info.bound, pos, duration, margin); } adjustCamHeight() { if (this.activeViewName != 'top') return; var view = this.views.top; var height; if (viewer.inputHandler.selection.length) { //相机高度位于选中的box的顶部 var box = viewer.inputHandler.selection[0]; height = box.boundingBox.clone().applyMatrix4(box.matrixWorld).max.z; } else { height = this.camHeightOutOfModel; //显示全部点云 } view.position.z = height; //console.log('adjustCamHeight',height) //缺点:1 会导致缩放很小的时候,transformationTool的轴因放大到了相机背面。(只有scale轴做了处理) //2 无法直接切换 看不到的box,但可以先取消选择 //3 但是俯视图中无法切换到被上层盖住的box(不过把俯视图作为辅助,只针对单个box调动的话,问题不大) } enter() { this.init(); viewer.transformationTool.setModeEnable(['translation']); //viewer.transformationTool.handles['rotation.x'].node.visible = false viewer.transformationTool.frame.material.visible = false; //不盖住boxVolume的frame this.targetPlane = viewer.mainViewport.targetPlane = new Plane(); this.shiftTarget = viewer.mainViewport.shiftTarget = new Vector3(); //project在targetPlane上的位置 this.getAllBoxes().forEach(box => { Potree.Utils.updateVisible(box, 'hidden', true); //显现 }); viewer.transformationTool.history.clear(); viewer.transformationTool.addEventListener('transformed', this.events.transfromCallback); //viewer.transformationTool.addEventListener('stopDrag', this.events.onTransfromEnd) viewer.inputHandler.addEventListener('selection_changed', this.events.selectCallback); viewer.inputHandler.addEventListener('keydown', this.events.onkeydown); this.setPointLevelAuto(); var initialPointcloud = viewer.scene.pointclouds.find(p => p.dataset_id == Potree.settings.originDatasetId); //隐藏 初始数据集以外的数据集 viewer.scene.pointclouds.forEach(e => { if (e.dataset_id != Potree.settings.originDatasetId) { Potree.Utils.updateVisible(e, 'enterClipping', false); //Potree.settings.floorplanEnables[e.dataset_id] = false e.panos.forEach(pano => pano.setEnable(false)); //禁止漫游 } else { Potree.Utils.updateVisible(e, 'enterClipping', true, 1, 'add'); //Potree.settings.floorplanEnables[e.dataset_id] = true } }); viewer.flyToDataset({ pointcloud: initialPointcloud, duration: 0 }); } enter2() { //在土方量界面的 viewer.transformationTool.setModeEnable(['translation']); viewer.transformationTool.frame.material.visible = false; //不盖住boxVolume的frame viewer.transformationTool.history.clear(); //viewer.inputHandler.addEventListener('keydown', this.events.onkeydown) } leave() { viewer.transformationTool.setModeEnable(['scale', 'translation', 'rotation']); viewer.transformationTool.frame.material.visible = true; //恢复 this.switchView('mainView'); this.getAllBoxes().forEach(box => { Potree.Utils.updateVisible(box, 'hidden', false); //隐身 }); viewer.transformationTool.removeEventListener('transformed', this.events.transfromCallback); //viewer.transformationTool.removeEventListener('stopDrag', this.events.onTransfromEnd) viewer.inputHandler.removeEventListener('selection_changed', this.events.selectCallback); //viewer.inputHandler.removeEventListener('keydown', this.events.onkeydown) viewer.transformObject(null); viewer.transformationTool.history.clear(); //恢复 初始数据集以外的数据集 viewer.scene.pointclouds.forEach(e => { if (e.dataset_id != Potree.settings.originDatasetId) { Potree.Utils.updateVisible(e, 'enterClipping', true); e.panos.forEach(pano => pano.setEnable(true)); } else { Potree.Utils.updateVisible(e, 'enterClipping', false, 0, 'cancel'); } }); } setTranMode(mode) { //rotate or translate this.tranMode = mode; viewer.transformationTool.setModeEnable([mode]); viewer.dispatchEvent('content_changed'); } //问:是否要显示其他数据集 setPointLevelAuto() { /* let visiCount = viewer.images360.panos.length let maxCount = 200, minCount = 20, minPer = 0.7, maxPer = 1 let percent = maxPer - ( maxPer - minPer) * THREE.Math.clamp((visiCount - minCount) / (maxCount - minCount),0,1) Potree.settings.UserDensityPercent = percent ---还是不限制了,尤其是平面图希望更细致点,毕竟剪裁主要要看清剪裁的部位。 */ viewer.setPointBudget(5 * 1000 * 1000); //给个中等到高等之间的质量 Potree.settings.sizeFitToLevel = true; viewer.setPointLevels(); } getAllBoxes() { return viewer.scene.volumes.filter(v => v.clip && v instanceof Potree.BoxVolume); } getCalcData() { //给后台矩阵数据,以裁剪点云。 var Clip = viewer.modules.Clip; //裁剪下载模块 var data = { transformation_matrix: viewer.scene.pointclouds.filter(p => p.dataset_id == Potree.settings.originDatasetId).map(cloud => { var data = { id: cloud.dataset_id, matrix: new Matrix4().elements, //参照downloadNoCrop,给默认值,表示没有最外层裁剪 visiMatrixes: cloud.material.clipBoxes_in.filter(e => !e.box.isNew).map(e => Clip.getTransformationMatrix(cloud, e.inverse).elements), unVisiMatrixes: cloud.material.clipBoxes_out.filter(e => !e.box.isNew).map(e => Clip.getTransformationMatrix(cloud, e.inverse).elements), modelMatrix: new Matrix4().elements //(new THREE.Matrix4).copy(cloud.transformMatrix).transpose().elements //需要保证没有位移,否则剪裁后的模型位置会变化 }; return data; }), aabb: "b-12742000 -12742000 -12742000 12742000 12742000 12742000" //剪裁空间 }; return data; } saveClipData(boxes) { //输出所有的clip volumeBox var oldState = !viewer.clipUnabled; //viewer.setClipState(true) var data = (boxes || this.getAllBoxes()).filter(e => !e.isNew).map(volume => { return { clipTask: volume.clipTask, position: Potree.Utils.datasetPosTransform({ position: volume.position, toDataset: true, datasetId: Potree.settings.originDatasetId }).toArray(), rotation: Potree.Utils.datasetRotTransform({ rotation: volume.rotation, toDataset: true, datasetId: Potree.settings.originDatasetId, getRotation: true }).toArray().slice(0, 3), scale: volume.scale.toArray() }; }); //console.log(data) //console.log(JSON.stringify(data)) //viewer.setClipState(oldState) return data; } loadFromData() { var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; data.forEach(v => { var volume = new Potree.BoxVolume({ clip: true, clipTask: v.clipTask }); volume.scale.fromArray(v.scale); volume.position.fromArray(v.position); volume.rotation.fromArray(v.rotation); volume.position.copy(Potree.Utils.datasetPosTransform({ position: volume.position, fromDataset: true, datasetId: Potree.settings.originDatasetId })); volume.rotation.copy(Potree.Utils.datasetRotTransform({ rotation: volume.rotation, fromDataset: true, datasetId: Potree.settings.originDatasetId, getRotation: true })); viewer.scene.addVolume(volume); viewer.volumeTool.scene.add(volume); }); } } //注意:实时裁剪只对初始数据集有效,其他数据集已经隐藏 /* 备注: 2023 发送给后台数据样例: {"transformation_matrix":[{"id":"1626189981883699200","matrix":[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],"visiMatrixes":[],"unVisiMatrixes":[[0.18610746638254325,-0.0005022517888587003,0,-0.01638495865566026,0.0002721420073982042,0.10084117292688818,0,0.25897037181878035,0,0,0.17066427841288187,-0.1913158687770112,0,0,0,1]],"modelMatrix":[0.999996358477288,-0.0026987093514294095,0,3.275872500136923e-8,0.0026987093514294095,0.999996358477288,0,-4.2486927309681385e-9,0,0,1,0,0,0,0,1]}],"aabb":"b-12742000 -12742000 -12742000 12742000 12742000 12742000"} 发送给算法部的数据样例: { "model": [ { "cut_transformation": "1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0", "file": "/mnt/data/pvt000004/1079784714115481600/pvt000004_202302271512444930_laserData/laserData/laser.las", "visiMatrixes": [[..],[..]], "dataSetId": "1630105213031026688", "sceneCode": "SS-t-MVQ1Jb80oMG", "modelMatrix": "-0.9338946595415051 -0.35754826930060274 0.0 -3.483651134875185E-8 0.35754826930060274 -0.9338946595415051 0.0 5.664923641290965E-9 0.0 0.0 0.9999999999999999 0.0 0.0 0.0 0.0 1.0", "unVisiMatrixes": [[..],[..]] } ], "aabb": "b-12742000 -12742000 -12742000 12742000 12742000 12742000" } */ var vertexShader = "\n attribute float randam;\n attribute float sprite;\n attribute float centerHeight; //add\n \n //uniform float fireHeight; //add \n uniform float time;\n uniform float size;\n uniform float heightOfNearPlane;\n \n \n \n \n //varying float heightRatio;\n varying float vSprite;\n varying float vOpacity; \n float PI = 3.14;\n\n float quadraticIn( float t ) \n { \n float tt = t * t;\n return tt * tt; \n //\u53D8\u5316\u66F2\u7EBF \u8D8A\u6765\u8D8A\u5FEB\n } \n \n void main() {\n float progress = fract( time + ( 2.0 * randam - 1.0 ) );\n float progressNeg = 1.0 - progress;\n float ease = quadraticIn( progress );\n float influence = sin( PI * ease );\n //vec3 newPosition = position * vec3( 1.0, 1.0 , ease);\n vec3 newPosition = position;\n newPosition.z = (newPosition.z - centerHeight) * ease + centerHeight;\n \n gl_Position = projectionMatrix * modelViewMatrix * vec4( newPosition, 1.0 );\n gl_PointSize = ( heightOfNearPlane * size ) / gl_Position.w;\n vOpacity = min( influence * 4.0, 1.0 ) * progressNeg;\n vSprite = sprite;\n \n //heightRatio = (newPosition.z - centerHeight) / fireHeight ;\n \n }\n"; var fragmentShader = "\n uniform vec3 color;\n uniform sampler2D u_sampler;\n\n varying float vSprite;\n varying float vOpacity;\n //varying float heightRatio;\n\n void main() \n {\n \n \n vec2 texCoord = vec2(gl_PointCoord.x * 0.25 + vSprite, gl_PointCoord.y);\n \n gl_FragColor = vec4( texture2D( u_sampler, texCoord ).xyz * color * vOpacity, 1.0 );\n \n \n }\n"; // import { vertexShader, fragmentShader } from './shaders' var ONE_SPRITE_ROW_LENGTH = 0.25; //对应着色器的0.25 var texture; var getTexture = () => { if (!texture) { texture = new TextureLoader().load(Potree.resourcePath + '/textures/fire.png'); } return texture; }; var boxGeo = new BoxBufferGeometry(1, 1, 1, 1); var boxMat = new MeshBasicMaterial({ wireframe: true, color: "#ffffff" }); class FireParticle extends Points { constructor(prop) { super(); for (var key in prop) { this[key] = prop[key]; } this.strength = this.strength || 1; this.radius = prop.radius || 1; this.height = prop.height || 5; this.computeParams(); this.geometry = this.createGeometry(this.radius, this.height, this.particleCount); if (this.color == void 0) this.color = 0xff3200; this.createMaterial(); //小蓝火:0x00338f //---?: this.velocity = new Vector3(); this.acceleration = new Vector3(); this.angle = 0; this.angleVelocity = 0; this.angleAcceleration = 0; this.size = 16; this.opacity = 1; this.age = 0; this.alive = 0; this.sizeTween = null; this.colorTween = null; this.opacityTween = null; this.setSize({ viewport: viewer.mainViewport }); this.setFov(viewer.fov); var setSize = e => { if (e.viewport.name != "MainView") return; this.setSize(e); }; var setFov = e => { this.setFov(e.fov); }; viewer.addEventListener('resize', setSize); viewer.addEventListener('fov_changed', setFov); this.addEventListener('dispose', () => { viewer.removeEventListener('resize', setSize); viewer.removeEventListener('fov_changed', setFov); }); } computeParams() { var length = (this.curve ? this.curve.wholeLength : 0) + this.radius * 2; //加上首尾的半径 var minSize = 0.3, maxSize = 3, minRadiusBound = 0.3, maxRadiusBound = 10; this.size = minSize + (maxSize - minSize) * MathUtils.smoothstep(this.radius, minRadiusBound, maxRadiusBound); //console.log('fire material particle size:', size ) this.particleCount = Math.ceil(length * Math.sqrt(this.strength * this.height) * this.radius / (this.size * this.size) * 25); //console.log('fire particleCount',this.particleCount) } getPointsForBound() { return this.boundPoints; //可以用于expand实时bound的点, 不含particle的size等边距 } getBound(points) { // points为生成点(圆心) this.boundPoints = []; var boundingBox = new Box3(); var margin = this.size * 0.13 + 0.3; points.forEach(bottom => { var top = bottom.clone(); top.z += this.height; boundingBox.expandByPoint(bottom); boundingBox.expandByPoint(top); this.boundPoints.push(bottom, top); }); var xyExpand = this.radius + margin; boundingBox.expandByVector(new Vector3(xyExpand, xyExpand, margin)); this.boundingBox = boundingBox; /* if(!this.debugBox){ this.debugBox = new THREE.Mesh(boxGeo, boxMat) this.add(this.debugBox) } this.debugBox.scale.copy(boundingBox.getSize(new THREE.Vector3)) this.debugBox.position.copy(boundingBox.getCenter(new THREE.Vector3)) */ } createGeometry(radius, height, particleCount) { var geometry = new BufferGeometry(); var count, points; if (this.positions.length > 1) { var spaceDis = 0.2; //间隔距离 count = Math.ceil(this.curve.wholeLength / spaceDis) + 1; //console.log('count', count) points = this.curve.getSpacedPoints(count); //得到的数量会比count多一个 count = points.length; //得到的点不太均匀,两端容易点少。 this.getBound(points); } else { this.getBound(this.positions); } var position = new Float32Array(particleCount * 3); var randam = new Float32Array(particleCount); var sprite = new Float32Array(particleCount); var centerHeight = new Float32Array(particleCount); for (var i = 0; i < particleCount; i++) { var center = new Vector3().copy(this.positions.length > 1 ? points[Math.floor(i / particleCount * count)] : this.positions[0]); centerHeight[i] = center.z; if (i === 0) { // to avoid going out of Frustum position[i * 3 + 0] = center.x; position[i * 3 + 1] = center.y; position[i * 3 + 2] = center.z; } else { var r = Math.sqrt(Math.random()) * radius; var angle = Math.random() * 2 * Math.PI; position[i * 3 + 0] = center.x + Math.cos(angle) * r; position[i * 3 + 1] = center.y + Math.sin(angle) * r; position[i * 3 + 2] = center.z + (radius - r) / radius * height / 2 + height / 2; //不太明白这句为什么能达到height高度 sprite[i] = 0.25 * (Math.random() * 4 | 0); randam[i] = Math.random(); //center在底部 } } geometry.setAttribute('centerHeight', new BufferAttribute(centerHeight, 1)); geometry.setAttribute('position', new BufferAttribute(position, 3)); geometry.setAttribute('randam', new BufferAttribute(randam, 1)); geometry.setAttribute('sprite', new BufferAttribute(sprite, 1)); return geometry; } updateGeometry() { this.computeParams(); this.geometry.dispose(); this.geometry = this.createGeometry(this.radius, this.height, this.particleCount); this.material.uniforms.size.value = this.size; } createMaterial() { var material = new ShaderMaterial({ uniforms: { color: { type: "c", value: new Color(this.color) }, size: { type: "f", value: this.size }, u_sampler: { type: "t", value: getTexture() }, time: { type: "f", value: 0.0 }, heightOfNearPlane: { type: "f", value: 0 }, //相对far ,以确保画面缩放时点的大小也会缩放 height: { type: "f", value: this.height } }, vertexShader, fragmentShader, blending: AdditiveBlending, //加法融合模式 glBlendFunc(GL_ONE, GL_ONE) depthTest: true, depthWrite: false, transparent: true }); this.material = material; this.setPerspective(this.fov, this.screenHeight); } setSize(e) { var viewport = e.viewport; this.screenHeight = viewport.resolution.y; this.setPerspective(this.fov, this.screenHeight); } setFov(fov) { this.fov = fov; this.setPerspective(this.fov, this.screenHeight); } setPerspective(fov, height) { //this.uniforms.heightOfNearPlane.value = Math.abs(height / (2 * Math.tan(THREE.Math.degToRad(fov * 0.5)))); var far = Math.abs(height / (2 * Math.tan(MathUtils.degToRad(fov * 0.5)))); this.material.uniforms.heightOfNearPlane.value = far; } update(delta) { if (!Potree.Utils.getObjVisiByReason(this, 'force')) { //被手动隐藏了 return; } if (!Potree.Utils.isInsideFrustum(this.boundingBox, viewer.scene.getActiveCamera())) { Potree.Utils.updateVisible(this, 'isInsideFrustum', false); //不在视野范围 //console.log('unvi') return; } else { Potree.Utils.updateVisible(this, 'isInsideFrustum', true); } delta *= 1; //更改速度 this.material.uniforms.time.value = (this.material.uniforms.time.value + delta) % 1; viewer.dispatchEvent('content_changed'); } dispose() { this.geometry.dispose(); this.material.dispose(); this.dispatchEvent('dispose'); } } class Tween { constructor(times, values) { this.times = times || []; this.values = values || []; } lerp(t) { if (this.times.length == 0) return; var i = 0, n = this.times.length; while (i < n && t > this.times[i]) i++; if (i == 0) return this.values[0]; if (i == n) return this.values[n - 1]; var ratio = (t - this.times[i - 1]) / (this.times[i] - this.times[i - 1]); if (this.values[0] instanceof Vector3) { return this.values[i - 1].clone().lerp(this.values[i], ratio); } else { return this.values[i - 1] + ratio * (this.values[i] - this.values[i - 1]); } } clone() { return Common.CloneClassObject(this); } } class Particle$1 { constructor() { var prop = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; this.position = new Vector3(); this.velocity = new Vector3(); // units per second this.angle = 0; this.angleVelocity = 0; // degrees per second this.angleAcceleration = 0; // degrees per second, per second this.size = 16.0; this.color = new Color(); this.opacity = 1.0; this.age = 0; this.alive = 0; // use float instead of boolean for shader purposes this.lastChangeVage = 0; //add this.sizeTween = prop.sizeTween || new Tween([0, 1], [32, 128]); this.opacityTween = prop.opacityTween || new Tween([0.8, 2], [0.5, 0]); this.colorTween = prop.colorTween || new Tween([0.4, 1], [new Vector3(0, 0, 0.2), new Vector3(0, 0, 0.5)]); } update(dt) { this.position.add(this.velocity.clone().multiplyScalar(dt)); this.velocity.multiplyScalar(1 + this.acceleration * dt); // convert from degrees to radians: 0.01745329251 = Math.PI/180 this.angle += this.angleVelocity * 0.01745329251 * dt; this.angleVelocity += this.angleAcceleration * 0.01745329251 * dt; this.age += dt; // if the tween for a given attribute is nonempty, // then use it to update the attribute's value if (this.sizeTween.times.length > 0) this.size = this.sizeTween.lerp(this.age / this.deathAge); if (this.colorTween.times.length > 0) { var colorHSL = this.colorTween.lerp(this.age / this.deathAge); this.color = new Color().setHSL(colorHSL.x, colorHSL.y, colorHSL.z); } if (this.opacityTween.times.length > 0) { this.opacity = this.opacityTween.lerp(this.age / this.deathAge); } viewer.dispatchEvent('content_changed'); } } var vertexShader$1 = "\n attribute vec3 customColor;\n attribute float customOpacity;\n attribute float customSize;\n attribute float customAngle;\n attribute float customVisible; \n uniform float heightOfNearPlane;\n \n \n varying vec4 vColor;\n varying float vAngle;\n void main()\n {\n if ( customVisible > 0.5 ) \t\t\t\t\n vColor = vec4( customColor, customOpacity ); \n else\t\t\t\t\t\t\t\n vColor = vec4(0.0, 0.0, 0.0, 0.0);\t\t\n \n vAngle = customAngle;\n\n vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n //gl_PointSize = customSize * ( 300.0 / length( mvPosition.xyz ) ); \n gl_Position = projectionMatrix * mvPosition;\n gl_PointSize = ( heightOfNearPlane * customSize ) / gl_Position.w;\n \n \n }\n"; var fragmentShader$1 = "\n uniform sampler2D u_sampler;\n varying vec4 vColor;\t\n varying float vAngle; \n void main()\n {\n gl_FragColor = vColor;\n \n float c = cos(vAngle);\n float s = sin(vAngle);\n vec2 rotatedUV = vec2(c * (gl_PointCoord.x - 0.5) + s * (gl_PointCoord.y - 0.5) + 0.5, c * (gl_PointCoord.y - 0.5) - s * (gl_PointCoord.x - 0.5) + 0.5); \n vec4 rotatedTexture = texture2D( u_sampler, rotatedUV );\n gl_FragColor = gl_FragColor * rotatedTexture; \n }\n"; var Type$1 = Object.freeze({ "CUBE": 1, "SPHERE": 2 }); var particleTexture; var getTexture$1 = () => { if (!particleTexture) { particleTexture = new TextureLoader().load(Potree.resourcePath + '/textures/smokeparticle.png'); } return particleTexture; }; var boxGeo$1 = new BoxBufferGeometry(1, 1, 1, 1); var boxMat$1 = new MeshBasicMaterial({ wireframe: true, color: "#ffffff" }); var defaults = { positions: [], positionStyle: "sphere", positionBase: new Vector3(0, 0, 0), positionSpread: new Vector3(1, 1, 0), //cube radius: 1, // sphere velocityStyle: 'cube', velocityBase: new Vector3(0, 0, 0.5), // cube 基础速度 velocitySpread: new Vector3(1, 1, 0.3), accelerationBase: 0.3, //基础加速度 accelerationSpread: 0.6, //没使用 speedBase: 0.1, //sphere speedSpread: 0.5, angleBase: 0, angleSpread: 360, angleVelocityBase: 1, angleVelocitySpread: 30, angleAccelerationBase: 1, angleAccelerationSpread: 5, sizeBase: 0, sizeSpread: 0, sizeTween: [[0, 0.3, 1], [0.3, 1.4, 6]], colorBase: new Vector3(0.0, 1.0, 0.5), colorSpread: new Vector3(0.0, 0.0, 0.0), colorTween: new Tween([0.2, 1], [new Vector3(0, 0, 0.4), new Vector3(0, 0, 0.1)]), opacityBase: 0.1, //1.0, opacitySpread: 0.2, opacityTween: [[0, 0.1, 0.9, 1], [0.1, 0.4, 0.03, 0]], //particlesPerSecond : 20, strength: 1, particleDeathAge: 3, //从底下升起后能持续的时间 //emitterDeathAge : 60 // time (seconds) at which to stop creating particles. height: 3 }; var debugSphere = new Mesh(new SphereBufferGeometry(0.03, 5, 5), new MeshBasicMaterial({ color: 'white', depthTest: false })); class SmokeParticle extends Points { constructor() { var prop = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(); this.blendStyle = NormalBlending; // false; this.emitterAge = 0.0; //this.emitterAlive = true; prop = $.extend({}, defaults, prop); for (var key in prop) { var value = prop[key]; if (value instanceof Array && value[0] instanceof Array) this[key] = new Tween(...value);else if (value instanceof Vector3 || value instanceof Color) { this[key] = value.clone(); } else { this[key] = value; } } this.defaultSizeTween = this.sizeTween.clone(); this.defaultOpacityTween = this.opacityTween.clone(); this.geometry = new BufferGeometry(); this.computeParams(); this.createMaterial(); this.createGeometry(); this.dynamic = true; this.sortParticles = true; this.frustumCulled = false; //似乎是禁止相机裁剪,否则会在某些角度消失。但是会不会更耗性能呢? prop.position && this.position.copy(prop.position); //--------------------------------------- this.setSize({ viewport: viewer.mainViewport }); this.setFov(viewer.fov); var setSize = e => { if (e.viewport.name != "MainView") return; this.setSize(e); }; var setFov = e => { this.setFov(e.fov); }; /* let reStart = (e)=>{ if(e.v){//重新一个个放出粒子,否则会一股脑儿全部出来,因为同时大于粒子周期了一起重新生成出现。 setTimeout(()=>{//会先update一次delta为pageUnvisile的时间才触发 //console.log('归零') //this.reStart() },1) } } */ viewer.addEventListener('resize', setSize); viewer.addEventListener('fov_changed', setFov); //viewer.addEventListener('pageVisible', reStart) this.addEventListener('dispose', () => { viewer.removeEventListener('resize', setSize); viewer.removeEventListener('fov_changed', setFov); //viewer.removeEventListener('pageVisible', reStart) }); } computeParams() { var length = (this.curve ? this.curve.wholeLength : 0) + this.radius * 2; //加上首尾的半径 //注意:烟最低高度一米, 0 e * size); } { var _minSize = 1, _maxSize = 1.5, _minBound = 0.01, _maxBound = 1; var opac = _minSize + (_maxSize - _minSize) * MathUtils.smoothstep(this.strength, _minBound, _maxBound); this.opacityTween.values = this.defaultOpacityTween.values.map(e => e * opac); } //console.log('smoke particleCount',this.particleCount) } reStart() { this.emitterAge = 0; this.createGeometry(); } updateGeometry() { this.computeParams(); this.reStart(); } createParticle(center) { var particle = new Particle$1({ sizeTween: this.sizeTween, opacityTween: this.opacityTween, colorTween: this.colorTween }); particle.deathAge = this.particleDeathAge; particle.center = center; if (this.positionStyle == 'cube') particle.position = this.randomVector3(this.positionBase, this.positionSpread); if (this.positionStyle == 'sphere') { /* var z = 2 * Math.random() - 1 var t = Math.PI * 2 * Math.random(); var r = Math.sqrt( 1 - z*z ) ; var vec3 = new THREE.Vector3( r * Math.cos(t), r * Math.sin(t), z ); particle.position = new THREE.Vector3().addVectors( this.positionBase, vec3.multiplyScalar( this.radius ) ); */ //怎么改半径 var y = 2 * Math.random() - 1; var t = Math.PI * 2 * Math.random(); var r = Math.sqrt(1 - y * y); //因为 r*r = 1-y*y = x*x + z*z = r*r(cos^2 + sin^2 ); var lowDownRatio = 0.2; //压低近平面 var vec3 = new Vector3(r * Math.cos(t), y, Math.abs(r * Math.sin(t)) * lowDownRatio); particle.position = new Vector3().addVectors(this.positionBase, vec3.multiplyScalar(this.radius)); } particle.position.add(center); //add if (this.velocityStyle == 'cube') { particle.velocity = this.randomVector3(this.velocityBase, this.velocitySpread); } if (this.velocityStyle == 'sphere') { //var direction = particle.position.clone() var direction = new Vector3(0, 0, 1); //烟应该都是向上的 var speed = this.randomValue(this.speedBase, this.speedSpread); particle.velocity = direction.normalize().multiplyScalar(speed); } particle.acceleration = this.randomValue(this.accelerationBase, this.accelerationSpread); particle.angle = this.randomValue(this.angleBase, this.angleSpread); particle.angleVelocity = this.randomValue(this.angleVelocityBase, this.angleVelocitySpread); particle.angleAcceleration = this.randomValue(this.angleAccelerationBase, this.angleAccelerationSpread); particle.size = this.randomValue(this.sizeBase, this.sizeSpread); var color = this.randomVector3(this.colorBase, this.colorSpread); particle.color = new Color().setHSL(color.x, color.y, color.z); particle.opacity = this.randomValue(this.opacityBase, this.opacitySpread); particle.age = 0; particle.alive = 0; // particles initialize as inactive return particle; } getPointsForBound() { return this.boundPoints; //可以用于expand实时bound的点, 不含particle的size等边距 } getBound(points) { // points为生成点(圆心) this.boundPoints = []; var boundingBox = new Box3(); var maxSize = this.sizeTween.values.slice().sort((a, b) => b - a)[0]; var margin0 = maxSize * 0.11; var margin1 = margin0 + 0.5; //保守估计还会飘出这么多距离吧: size + 飘动 points.forEach(bottom => { var top = bottom.clone(); top.z += this.height; boundingBox.expandByPoint(bottom); boundingBox.expandByPoint(top); this.boundPoints.push(bottom, top); }); var xyExpand = this.radius + margin1; boundingBox.expandByVector(new Vector3(xyExpand, xyExpand, 0)); boundingBox.min.z -= margin0; boundingBox.max.z += margin1; this.boundingBox = boundingBox; /* if(!this.debugBox){ this.debugBox = new THREE.Mesh(boxGeo, boxMat) this.add(this.debugBox) } this.debugBox.scale.copy(boundingBox.getSize(new THREE.Vector3)) this.debugBox.position.copy(boundingBox.getCenter(new THREE.Vector3)) */ } createGeometry() { this.particleArray = []; var positions = []; var colors = []; var alives = []; var opacitys = []; var sizes = []; var angles = []; var count, points; if (this.positions.length > 1) { var spaceDis = 0.6; //间隔距离 count = Math.ceil(this.curve.wholeLength / spaceDis) + 1; points = this.curve.getSpacedPoints(count); count = points.length; /* points.forEach(e=> { var sphere = debugSphere.clone(); sphere.position.copy(e) viewer.scene.scene.add(sphere) }) */ var haventGetPoints = points.slice(); var getRanPoints = function getRanPoints(i) { var a = Math.random(); var choseIndex = Math.floor(haventGetPoints.length * a); var point = haventGetPoints[choseIndex]; if (haventGetPoints.length == 1) { haventGetPoints = points.slice(); } else { haventGetPoints.splice(choseIndex, 1); } return point; }; this.getBound(points); } else { this.getBound(this.positions); } for (var i = 0; i < this.particleCount; i++) { var center = new Vector3().copy(this.positions.length > 1 ? getRanPoints(i) : this.positions[0]); //var center = new THREE.Vector3().copy(this.positions.length>1 ? points[Math.floor(i/this.particleCount * count)] : this.positions[0]) // remove duplicate code somehow, here and in update function below. this.particleArray[i] = this.createParticle(center); positions[3 * i] = this.particleArray[i].position.x; positions[3 * i + 1] = this.particleArray[i].position.y; positions[3 * i + 2] = this.particleArray[i].position.z; colors[3 * i] = this.particleArray[i].color.r; colors[3 * i + 1] = this.particleArray[i].color.g; colors[3 * i + 2] = this.particleArray[i].color.b; alives[i] = this.particleArray[i].alive; opacitys[i] = this.particleArray[i].opacity; sizes[i] = this.particleArray[i].size; angles[i] = this.particleArray[i].angle; } this.geometry.setAttribute('position', new BufferAttribute(new Float32Array(positions), 3)); this.geometry.setAttribute('customColor', new BufferAttribute(new Float32Array(colors), 3)); this.geometry.setAttribute('customVisible', new BufferAttribute(new Float32Array(alives), 1)); this.geometry.setAttribute('customOpacity', new BufferAttribute(new Float32Array(opacitys), 1)); this.geometry.setAttribute('customSize', new BufferAttribute(new Float32Array(sizes), 1)); this.geometry.setAttribute('customAngle', new BufferAttribute(new Float32Array(angles), 1)); } createMaterial() { this.material = new ShaderMaterial({ uniforms: { u_sampler: { type: "t", value: getTexture$1() }, heightOfNearPlane: { type: "f", value: 0 } //相对far ,以确保画面缩放时点的大小也会缩放 }, vertexShader: vertexShader$1, vertexShader: vertexShader$1, fragmentShader: fragmentShader$1, transparent: true, alphaTest: 0.5, // if having transparency issues, try including: alphaTest: 0.5, blending: this.blendStyle, depthTest: this.blendStyle != NormalBlending }); this.setPerspective(this.fov, this.screenHeight); } update(dt) { if (!Potree.Utils.getObjVisiByReason(this, 'force')) { //被手动隐藏了 return; } if (!Potree.Utils.isInsideFrustum(this.boundingBox, viewer.scene.getActiveCamera())) { Potree.Utils.updateVisible(this, 'isInsideFrustum', false); //不在视野范围 //console.log('unvi') return; } else { Potree.Utils.updateVisible(this, 'isInsideFrustum', true); } if (dt > 1) { console.log('update dt>1', dt); } //dt *= 0.5; var recycleIndices = []; var recycleAges = []; var positions = []; var colors = []; var alives = []; var opacitys = []; var sizes = []; var angles = []; for (var i = 0; i < this.particleCount; i++) { if (this.particleArray[i].alive) { if (this.velocityStyle == 'cube') { //一定几率改变下方向 var ratio = Math.random(); if (this.particleArray[i].age - this.particleArray[i].lastChangeVage > this.particleDeathAge * ratio) { this.particleArray[i].velocity = this.randomVector3(this.velocityBase, this.velocitySpread); this.particleArray[i].lastChangeVage = this.particleArray[i].age; } } else { /* if(this.particleArray[i].age - this.particleArray[i].lastChangeVage > this.particleDeathAge*0.3 ){ if( Math.random()>0.1){//一定几率改变下方向 var speed = this.randomValue( this.speedBase, this.speedSpread ); this.particleArray[i].velocity = this.randomVector3( new THREE.Vector3, new THREE.Vector3(1,1,1) ); this.particleArray[i].velocity.normalize().multiplyScalar( speed ); } this.particleArray[i].lastChangeVage = this.particleArray[i].age } */ } this.particleArray[i].update(dt); // check if particle should expire // could also use: death by size<0 or alpha<0. if (this.particleArray[i].age > this.particleDeathAge) { this.particleArray[i].alive = 0.0; recycleIndices.push(i); recycleAges.push((this.particleArray[i].age - this.particleDeathAge) % this.particleDeathAge); } // update particle properties in shader positions[3 * i] = this.particleArray[i].position.x; positions[3 * i + 1] = this.particleArray[i].position.y; positions[3 * i + 2] = this.particleArray[i].position.z; colors[3 * i] = this.particleArray[i].color.r; colors[3 * i + 1] = this.particleArray[i].color.g; colors[3 * i + 2] = this.particleArray[i].color.b; alives[i] = this.particleArray[i].alive; opacitys[i] = this.particleArray[i].opacity; sizes[i] = this.particleArray[i].size; angles[i] = this.particleArray[i].angle; } } // check if particle emitter is still running //if ( !this.emitterAlive ) return; this.geometry.setAttribute('position', new BufferAttribute(new Float32Array(positions), 3)); this.geometry.setAttribute('customColor', new BufferAttribute(new Float32Array(colors), 3)); this.geometry.setAttribute('customVisible', new BufferAttribute(new Float32Array(alives), 1)); this.geometry.setAttribute('customOpacity', new BufferAttribute(new Float32Array(opacitys), 1)); this.geometry.setAttribute('customSize', new BufferAttribute(new Float32Array(sizes), 1)); this.geometry.setAttribute('customAngle', new BufferAttribute(new Float32Array(angles), 1)); this.geometry.attributes.customColor.needsUpdate = true; this.geometry.attributes.customVisible.needsUpdate = true; this.geometry.attributes.customOpacity.needsUpdate = true; this.geometry.attributes.customSize.needsUpdate = true; this.geometry.attributes.customAngle.needsUpdate = true; // if no particles have died yet, then there are still particles to activate if (this.emitterAge < this.particleDeathAge) //开始时一个个放出来 { var particlesPerSecond = this.particleCount / this.particleDeathAge; // determine indices of particles to activate var startIndex = Math.round(particlesPerSecond * (this.emitterAge + 0)); var endIndex = Math.round(particlesPerSecond * (this.emitterAge + dt)); if (endIndex > this.particleCount) endIndex = this.particleCount; for (var i = startIndex; i < endIndex; i++) this.particleArray[i].alive = 1.0; } // if any particles have died while the emitter is still running, we imediately recycle them for (var j = 0; j < recycleIndices.length; j++) { var i = recycleIndices[j]; this.particleArray[i] = this.createParticle(this.particleArray[i].center); this.particleArray[i].alive = 1.0; // activate right away this.particleArray[i].age = recycleAges[j]; positions[3 * i] = this.particleArray[i].position.x; positions[3 * i + 1] = this.particleArray[i].position.y; positions[3 * i + 2] = this.particleArray[i].position.z; } this.geometry.setAttribute('position', new BufferAttribute(new Float32Array(positions), 3)); this.geometry.attributes.position.needsUpdate = true; // stop emitter? this.emitterAge += dt; //if ( this.emitterAge > this.emitterDeathAge ) this.emitterAlive = false; } randomValue(base, spread) { //return base + spread * (Math.random() - 0.5); var p = Math.random(); return base * p + spread * (1 - p); } randomVector3(base, spread) { var rand3 = new Vector3(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5); return new Vector3().addVectors(base, new Vector3().multiplyVectors(spread, rand3)); } setSize(e) { var viewport = e.viewport; this.screenHeight = viewport.resolution.y; this.setPerspective(this.fov, this.screenHeight); } setFov(fov) { this.fov = fov; this.setPerspective(this.fov, this.screenHeight); } setPerspective(fov, height) { //this.uniforms.heightOfNearPlane.value = Math.abs(height / (2 * Math.tan(THREE.Math.degToRad(fov * 0.5)))); var far = Math.abs(height / (2 * Math.tan(MathUtils.degToRad(fov * 0.5)))); this.material.uniforms.heightOfNearPlane.value = far; } dispose() { this.geometry.dispose(); this.material.dispose(); this.dispatchEvent('dispose'); } } /* 改进:如果有必要 根据curve中分成的点,分成多个簇,每个簇掌管该部分的可见性和particle的数量。 在camera_changed时根据远近修改每个簇的particle的数量,当然不会大于初始创建的个数。多出的随机隐藏。 */ var vertexShader$2 = "\n attribute vec3 color;\n attribute float size;\n attribute float angle;\n attribute float opacity;\n attribute float visible;\n varying vec4 vColor;\n varying float vAngle;\n uniform float heightOfNearPlane;\n \n void main() {\n if(visible > 0.5) {\n vColor = vec4(color, opacity);\n } else {\n vColor = vec4(0.0, 0.0, 0.0, 0.0);\n }\n vAngle = angle;\n vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);\n gl_Position = projectionMatrix * mvPosition;\n \n gl_PointSize = ( heightOfNearPlane * size ) / gl_Position.w;\n }\n"; var fragmentShader$2 = "\n uniform sampler2D u_sampler;\n varying vec4 vColor;\n varying float vAngle;\n void main() {\n gl_FragColor = vColor;\n float u = cos(vAngle);\n float v = sin(vAngle);\n vec2 uv = vec2(\n u * (gl_PointCoord.x - 0.5) + v * (gl_PointCoord.y - 0.5) + 0.5, \n u * (gl_PointCoord.y - 0.5) - v * (gl_PointCoord.x - 0.5) + 0.5\n );\n vec4 texture = texture2D(u_sampler, uv);\n gl_FragColor = gl_FragColor * texture;\n }\n"; // import { vertexShader, fragmentShader } from './shader' var DEG2RAD = Math.PI / 180; class Particle$2 { constructor() { this.position = new Vector3(); this.velocity = new Vector3(); this.angle = 0; this.angleVelocity = 0; this.angleAcceleration = 0; this.size = 16; this.color = new Color(); this.opacity = 1; this.rebornCount = 0; //重生次数 this.age = 0; this.alive = 0; //注意,一开始时是未出生的 this.deadAge = 0; //已死亡时间 this.sizeTween = null; this.colorTween = null; this.opacityTween = null; } update(dt) { //s = s0 + (v0 + at) * t 或 lastS + delta(vt) this.position.add(this.velocity.clone().multiplyScalar(dt)); this.velocity.multiplyScalar(1 + this.acceleration * dt); this.angle += this.angleVelocity * DEG2RAD * dt; this.angleVelocity += this.angleAcceleration * DEG2RAD * dt; this.age += dt; if (this.sizeTween.times.length > 0) { this.size = this.sizeTween.lerp(this.age / this.deathAge); } if (this.colorTween.times.length > 0) { var colorHSL = this.colorTween.lerp(this.age / this.deathAge); this.color = new Color().setHSL(colorHSL.x, colorHSL.y, colorHSL.z); } if (this.opacityTween.times.length > 0) { this.opacity = this.opacityTween.lerp(this.age / this.deathAge); } viewer.dispatchEvent('content_changed'); } } class Util { constructor() {} randomValue(min, max) { //return min + max * (Math.random() - 0.5) var p = Math.random(); return min * p + max * (1 - p); } randomVector3(min, max) { var rand3 = new Vector3(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5); return new Vector3().addVectors(min, new Vector3().multiplyVectors(max, rand3)); } } var util$1 = new Util(); var Shape$1 = { CUBE: 1, SPHERE: 2 }; var particleTexture$1; var getTexture$2 = () => { if (!particleTexture$1) { particleTexture$1 = new TextureLoader().load(Potree.resourcePath + '/textures/explode.png'); } return particleTexture$1; }; var sphereGeo = new SphereBufferGeometry(1, 10, 4); var sphereMat = new MeshBasicMaterial({ wireframe: true, color: "#ffffff" }); var defaults$1 = { position: new Vector3(0, 0, 1), positionShape: Shape$1.SPHERE, positionRange: new Vector3(1, 1, 1), //cube radius: 1.3, //sphere velocityShape: Shape$1.SPHERE, velocity: new Vector3(0, 0, 2), //cube velocityRange: new Vector3(0, 0, 3), //sphere speed: 0.4, speedRange: 1, size: 0.4, sizeRange: 2, //sizeTween: new Tween( [0, 0.05, 0.3, 0.45], [0, 1, 3, 0.1] ), sizeTween: [[0, 0.04, 0.2, 1], [0.1, 1, 6, 8]], color: new Vector3(1.0, 1.0, 1.0), colorRange: new Vector3(0, 0, 0), colorTween: new Tween(), opacity: 1.0, opacityRange: 0.0, opacityTween: new Tween([0, 0.06, 0.3, 0.8, 1], [0, 1, 0.3, 0.05, 0]), blendMode: AdditiveBlending, acceleration: 0.5, accelerationRange: 0, angle: 0, angleRange: 0, angleVelocity: 0, angleVelocityRange: 0, angleAcceleration: 0, angleAccelerationRange: 0, strength: 1, //particlesPerSecond: 8, particleDeathAge: 0.7, recycleTimes: 3, //每个粒子在一次爆炸后循环次数,循环完毕进入particleSpaceTime,等待下一次爆炸. //爆炸时长: particleDeathAge * (recycleTimes+1) particleSpaceTime: 3 //间隔 }; class ExplodeParticle extends Points { constructor(params) { super(); this.age = 0; this.alive = true; //this.deathAge = 60 this.loop = true; this.blendMode = NormalBlending; this.setParameters(params); this.createParticles(); this.frustumCulled = false; //似乎是禁止相机裁剪,否则会在某些角度消失。但是会不会更耗性能呢? //------------------------------------ this.setSize({ viewport: viewer.mainViewport }); this.setFov(viewer.fov); var setSize = e => { if (e.viewport.name != "MainView") return; this.setSize(e); }; var setFov = e => { this.setFov(e.fov); }; /* let reStart = (e)=>{ if(e.v){//重新一个个放出粒子,否则会一股脑儿全部出来,因为同时大于粒子周期了一起重新生成出现。 setTimeout(()=>{//会先update一次delta为pageUnvisile的时间才触发 //console.log('归零') //this.reStart() },1) } } */ viewer.addEventListener('resize', setSize); viewer.addEventListener('fov_changed', setFov); //viewer.addEventListener('pageVisible', reStart) this.addEventListener('dispose', () => { viewer.removeEventListener('resize', setSize); viewer.removeEventListener('fov_changed', setFov); //viewer.removeEventListener('pageVisible', reStart) }); } computeParams() { if (this.curve) { this.position.copy(this.curve.points[0]); } var minSize = 0.8, maxSize = 10, minRadiusBound = 0.2, maxRadiusBound = 20; var size = minSize + (maxSize - minSize) * MathUtils.smoothstep(this.radius * this.strength, minRadiusBound, maxRadiusBound); this.sizeTween.values = this.defaultSizeTween.values.map(e => e * size); this.particleCount = Math.ceil(this.strength * this.radius * 5 /* * this.radius * this.radius */); this.speed = defaults$1.speed * this.radius; this.speedRange = defaults$1.speedRange * this.radius; console.log(this.particleCount); { this.boundPoints = []; this.boundPoints.push(this.position.clone()); var _maxSize = this.sizeTween.values.slice().sort((a, b) => b - a)[0]; var margin = _maxSize * 0.35 + 0.5; var scale = this.radius + margin; var sphere = new Sphere(this.position, scale); //加上防止剪裁 this.boundingSphere = sphere; //虽然还是会有一些后续移动的会超出 this.boundingBox = new Box3().setFromCenterAndSize(this.position, new Vector3(scale * 2, scale * 2, scale * 2)); /* if(!this.debugSphere){ this.debugSphere = new THREE.Mesh(sphereGeo, sphereMat) this.add(this.debugSphere) } this.debugSphere.scale.set(scale,scale,scale) */ } } getPointsForBound() { return this.boundPoints; //可以用于expand实时bound的点, 不含particle的size等边距 } reStart() { this.age = 0; this.createParticles(); } setParameters(params) { params = $.extend({}, defaults$1, params); for (var key in params) { var value = params[key]; if (key == 'position') this.position.copy(value);else if (value instanceof Array && value[0] instanceof Array) { this[key] = new Tween(...value); } else if (value instanceof Vector3 || value instanceof Color) { this[key] = value.clone(); } else { this[key] = value; } } this.defaultSizeTween = this.sizeTween.clone(); //Object.assign(this, params) this.particles = []; this.age = 0.0; this.alive = true; this.geometry = new BufferGeometry(); this.computeParams(); this.material = new ShaderMaterial({ uniforms: { u_sampler: { value: this.texture || getTexture$2() }, heightOfNearPlane: { type: "f", value: 0 } //相对far ,以确保画面缩放时点的大小也会缩放 }, vertexShader: vertexShader$2, fragmentShader: fragmentShader$2, transparent: true, alphaTest: 0.5, depthTest: this.blendMode == NormalBlending, blending: this.blendMode }); } createParticles() { this.particles = []; var count = this.particleCount; var positionArray = new Float32Array(count * 3); var colorArray = new Float32Array(count * 3); var sizeArray = new Float32Array(count); var angleArray = new Float32Array(count); var opacityArray = new Float32Array(count); var visibleArray = new Float32Array(count); for (var i = 0; i < count; i++) { var particle = this.createParticle(); /* positionArray[i * 3] = particle.position.x positionArray[i * 3 + 1] = particle.position.y positionArray[i * 3 + 2] = particle.position.z colorArray[i * 3] = particle.color.r colorArray[i * 3 + 1] = particle.color.g colorArray[i * 3 + 2] = particle.color.b sizeArray[i] = particle.size angleArray[i] = particle.angel opacityArray[i] = particle.opacity visibleArray[i] = particle.alive */ this.particles[i] = particle; } this.geometry.setAttribute('position', new BufferAttribute(positionArray, 3)); this.geometry.setAttribute('color', new BufferAttribute(colorArray, 3)); this.geometry.setAttribute('angle', new BufferAttribute(angleArray, 1)); this.geometry.setAttribute('size', new BufferAttribute(sizeArray, 1)); this.geometry.setAttribute('visible', new BufferAttribute(visibleArray, 1)); this.geometry.setAttribute('opacity', new BufferAttribute(opacityArray, 1)); } createParticle() { var particle = new Particle$2(); particle.sizeTween = this.sizeTween; particle.colorTween = this.colorTween; particle.opacityTween = this.opacityTween; particle.deathAge = this.particleDeathAge; if (this.positionShape == Shape$1.CUBE) { particle.position = util$1.randomVector3(new Vector3(), this.positionRange); } if (this.positionShape == Shape$1.SPHERE) { /* const z = 2 * Math.random() - 1 const t = Math.PI * 2 * Math.random() const r = Math.sqrt(1 - z*z) const vec3 = new THREE.Vector3(r * Math.cos(t), r * Math.sin(t), z) particle.position = vec3.multiplyScalar(this.radius) */ var y = 2 * Math.random() - 1; var t = Math.PI * 2 * Math.random(); var r = Math.sqrt(1 - y * y); var vec3 = new Vector3(r * Math.cos(t), y, r * Math.sin(t)); particle.position = vec3.multiplyScalar(this.radius); } if (this.velocityShape == Shape$1.CUBE) { particle.velocity = util$1.randomVector3(this.velocity, this.velocityRange); } if (this.velocityShape == Shape$1.SPHERE) { var direction = new Vector3().addVectors(particle.position, new Vector3(0, 0, this.radius * 2)); //向上升? var speed = util$1.randomValue(this.speed, this.speedRange); particle.velocity = direction.normalize().multiplyScalar(speed); } particle.acceleration = util$1.randomValue(this.acceleration, this.accelerationRange); particle.angle = util$1.randomValue(this.angle, this.angleRange); particle.angleVelocity = util$1.randomValue(this.angleVelocity, this.angleVelocityRange); particle.angleAcceleration = util$1.randomValue(this.angleAcceleration, this.angleAccelerationRange); particle.size = util$1.randomValue(this.size, this.sizeRange); var color = util$1.randomVector3(this.color, this.colorRange); particle.color = new Color().setHSL(color.x, color.y, color.z); particle.opacity = util$1.randomValue(this.opacity, this.opacityRange); return particle; } update(dt) { if (!Potree.Utils.getObjVisiByReason(this, 'force')) { //被手动隐藏了 return; } if (this.delayStartTime > 0) { // 爆炸延迟 return this.delayStartTime -= dt; } if (!Potree.Utils.isInsideFrustum(this.boundingSphere, viewer.scene.getActiveCamera())) { Potree.Utils.updateVisible(this, 'isInsideFrustum', false); //不在视野范围 return; } else { Potree.Utils.updateVisible(this, 'isInsideFrustum', true); } //const timeRatio = 0.5 if (dt > 1) { console.log('update dt>1', dt); } //dt *= timeRatio var particleDeathAge = this.particleDeathAge; /* * timeRatio */ var particleSpaceTime = this.particleSpaceTime; /* * timeRatio */ var recycleIndices = []; var recycleAges = []; var recycleRebornCount = []; var positionArray = this.geometry.attributes.position.array; var opacityArray = this.geometry.attributes.opacity.array; var visibleArray = this.geometry.attributes.visible.array; var colorArray = this.geometry.attributes.color.array; var angleArray = this.geometry.attributes.angle.array; var sizeArray = this.geometry.attributes.size.array; for (var i = 0; i < this.particleCount; i++) { var particle = this.particles[i]; if (particle.alive) { particle.update(dt); if (particle.age > particleDeathAge) { particle.alive = 0.0; if (particle.rebornCount >= this.recycleTimes) { particle.deadAge = particle.age - particleDeathAge; //已死亡时间 } else { //直接循环 recycleIndices.push(i); recycleAges.push( /* ( */particle.age - particleDeathAge /* )%(this.particleDeathAge ) */); recycleRebornCount.push(particle.rebornCount + 1); } } positionArray[i * 3] = particle.position.x; positionArray[i * 3 + 1] = particle.position.y; positionArray[i * 3 + 2] = particle.position.z; colorArray[i * 3] = particle.color.r; colorArray[i * 3 + 1] = particle.color.g; colorArray[i * 3 + 2] = particle.color.b; visibleArray[i] = particle.alive; opacityArray[i] = particle.opacity; angleArray[i] = particle.angle; sizeArray[i] = particle.size; } else { if (particle.rebornCount >= this.recycleTimes) { if (particle.age > particleDeathAge) { //其他已经死亡的粒子的时间继续增加 particle.deadAge += dt; } } } if (particle.rebornCount >= this.recycleTimes && particle.age > particleDeathAge) { //已经死亡 if (particle.deadAge >= particleSpaceTime) { //死亡时间超过设定的间隔时间后重启 recycleIndices.push(i); var wholeTime = particleDeathAge * (this.recycleTimes + 1) + particleSpaceTime; recycleAges.push((particle.deadAge - particleSpaceTime) % wholeTime); //剩余时间就是重生后的age recycleRebornCount.push(0); } } } this.geometry.attributes.size.needsUpdate = true; this.geometry.attributes.color.needsUpdate = true; this.geometry.attributes.angle.needsUpdate = true; this.geometry.attributes.visible.needsUpdate = true; this.geometry.attributes.opacity.needsUpdate = true; this.geometry.attributes.position.needsUpdate = true; if (!this.alive) return; if (this.age < particleDeathAge) { var startIndex = Math.round(this.particleCount * (this.age + 0) / particleDeathAge); var endIndex = Math.round(this.particleCount * (this.age + dt) / particleDeathAge); if (endIndex > this.particleCount) { endIndex = this.particleCount; } for (var _i = startIndex; _i < endIndex; _i++) { this.particles[_i].alive = 1.0; } } for (var j = 0; j < recycleIndices.length; j++) { var _i2 = recycleIndices[j]; this.particles[_i2] = this.createParticle(); this.particles[_i2].alive = 1.0; //出生 this.particles[_i2].age = recycleAges[j]; this.particles[_i2].rebornCount = recycleRebornCount[j]; /* if(this.particles[i].age < particleDeathAge){ positionArray[i * 3] = this.particles[i].position.x positionArray[i * 3 + 1] = this.particles[i].position.y positionArray[i * 3 + 2] = this.particles[i].position.z visibleArray[i] = particle.alive? } */ } this.geometry.attributes.position.needsUpdate = true; this.age += dt; if (this.age > this.deathAge && !this.loop) { this.alive = false; } } setSize(e) { var viewport = e.viewport; this.screenHeight = viewport.resolution.y; this.setPerspective(this.fov, this.screenHeight); } setFov(fov) { this.fov = fov; this.setPerspective(this.fov, this.screenHeight); } setPerspective(fov, height) { //this.uniforms.heightOfNearPlane.value = Math.abs(height / (2 * Math.tan(THREE.Math.degToRad(fov * 0.5)))); var far = Math.abs(height / (2 * Math.tan(MathUtils.degToRad(fov * 0.5)))); this.material.uniforms.heightOfNearPlane.value = far; } updateGeometry() { this.computeParams(); this.reStart(); } dispose() { this.geometry.dispose(); this.material.dispose(); this.dispatchEvent('dispose'); } } var colors$2 = { 'fire+smoke': 0xffffff, 'smoke': 0xffffff, 'explode': 0xffffff }; var depthMatPrefix = { clipDistance: 100, occlusionDistance: 60, /* 变为backColor距离 */ maxClipFactor: 0.5, backColor: "#777", useDepth: true, transparent: !0 }; var lineMats$2; var getLineMat$1 = function getLineMat(type) { if (!lineMats$2) { lineMats$2 = { 'fire+smoke': LineDraw.createFatLineMat($.extend(depthMatPrefix, { color: colors$2['fire+smoke'], lineWidth: 2 })), 'smoke': LineDraw.createFatLineMat($.extend(depthMatPrefix, { color: colors$2['smoke'], lineWidth: 2 })), 'explode': LineDraw.createFatLineMat($.extend(depthMatPrefix, { color: colors$2['explode'], lineWidth: 2 })) }; } return lineMats$2[type]; }; var handleMats; var getHandleMat = function getHandleMat(type) { if (!handleMats) { var texLoader = new TextureLoader(); handleMats = { "fire+smoke": new DepthBasicMaterial($.extend(depthMatPrefix, { map: texLoader.load(Potree.resourcePath + '/textures/icon-fire.png'), color: colors$2['fire+smoke'] })), "smoke": new DepthBasicMaterial($.extend(depthMatPrefix, { map: texLoader.load(Potree.resourcePath + '/textures/icon-smoke.png'), color: colors$2['smoke'] })), "explode": new DepthBasicMaterial($.extend(depthMatPrefix, { map: texLoader.load(Potree.resourcePath + '/textures/icon-explode.png'), color: colors$2['explode'] })) }; } return handleMats[type]; }; var ParticleEditor = { bus: new EventDispatcher(), particleGroup: new Object3D(), curveGroup: new Object3D(), init: function init() { this.particleGroup.name = 'particles'; viewer.scene.scene.add(this.particleGroup); this.curveGroup.name = 'particles-curves'; viewer.scene.scene.add(this.curveGroup); }, addParticle: function addParticle() { var prop = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var particle; if (prop.type == 'fire') { particle = new FireParticle(prop); } else if (prop.type == 'smoke') { particle = new SmokeParticle(prop); } else if (prop.type == 'explode') { particle = new ExplodeParticle(prop); } this.particleGroup.add(particle); return particle; }, removeParticle(particle) { //particle.dispatchEvent('delete') particle.dispose(); this.particleGroup.remove(particle); particle.curve.dispose(); }, update(delta) { this.particleGroup.children.forEach(e => e.update(delta)); }, startInsertion() { var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'fire'; var prop = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; //viewer.modules.ParticleEditor.startInsertion() var deferred = $.Deferred(); var particles = []; var finish = ifDone => { if (ifDone) { deferred.resolve(particles); } viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "addSth" }); viewer.removeEventListener('global_click', click); this.bus.removeEventListener('cancel_insertions', cancel); }; var curve = new CurveCtrl([], getLineMat$1(type), colors$2[type], type + '_curve', { handleMat: getHandleMat(type) }); this.curveGroup.add(curve); prop.curve = curve; prop.type = type; //console.log('创建curve',type,curve.uuid) var cancel = () => { console.log('cancel_insertions', curve.uuid); curve.dispose(); finish(false); }; this.bus.dispatchEvent('cancel_insertions'); //删除旧的 this.bus.addEventListener('cancel_insertions', cancel); var click = e => { if (e.button === MOUSE.RIGHT) { if (curve.points.length >= 1) { //if(type.includes('fire') || type.includes('smoke') ){ particles = this.createFromData(prop); finish(true); } return; } var I = e.intersect && (e.intersect.orthoIntersect || e.intersect.location); if (!I) return; curve.addPoint(I, null, true); if (type == 'explode') { particles = this.createFromData(prop); finish(true); } return { stopContinue: true }; //防止继续执行别的侦听,如flytopano }; viewer.addEventListener('global_click', click, { importance: 10 }); //add importance viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "addSth" }); return deferred.promise(); }, createFromData(prop) { var type = prop.type; var particles = []; var curve = prop.curve; if (!curve) { curve = new CurveCtrl(prop.points, getLineMat$1(type), colors$2[type], type + '_curve', { handleMat: getHandleMat(type) }); this.curveGroup.add(curve); } if (type.includes('fire') || type.includes('smoke')) { if (type.includes('fire')) { var fire = this.addParticle({ type: 'fire', positions: curve.points, curve, radius: prop.radius, height: prop.height, strength: prop.strength }); particles.push(fire); } if (type.includes('smoke')) { var smoke = this.addParticle({ type: 'smoke', positions: curve.points, curve, positionStyle: 'sphere', strength: prop.smokeStrength, radius: prop.smokeRadius, height: prop.smokeHeight }); particles.push(smoke); } } else if (type == 'explode') { var explode = this.addParticle({ type: 'explode', position: curve.points[0], strength: prop.strength, radius: prop.radius, particleSpaceTime: prop.particleSpaceTime, curve, delayStartTime: prop.delayStartTime }); particles.push(explode); } curve.addEventListener('dragCurvePoint', () => { Common.intervalTool.isWaiting('particlePointChange', () => { //延时update,防止卡顿 particles.forEach(e => e.updateGeometry()); //geoNeedsUpdate = false curve.dispatchEvent('sendUpdatePoints'); }, 400); }); return particles; } }; var CamAniEditor = { createAnimation(data) { var animation = new CameraAnimation$1(viewer); if (data) { animation.name = data.name; animation.duration = data.duration; animation.useDurSlice = data.useDurSlice; for (var cpdata of data.points) { /* const position = Potree.Utils.datasetPosTransform({ fromDataset: true, position: cpdata.position, datasetId: Potree.settings.originDatasetId }) const target = Potree.Utils.datasetPosTransform({ fromDataset: true, position: cpdata.target, datasetId: Potree.settings.originDatasetId }) */ var position = new Vector3().copy(cpdata.position); var target = new Vector3().copy(cpdata.target); var duration = cpdata.time; var cp = animation.createControlPoint(null, { position, target, duration }); } } animation.changeCallback(); viewer.scene.addCameraAnimation(animation); return animation; }, removeAnimation(animation) { animation.dispatchEvent('dispose'); viewer.scene.removeCameraAnimation(animation); }, createMulAnimation(data) { //新版,包含漫游点 var event_ = new EventDispatcher(); var sections = []; //分段 var aniIndex = 0; var curAni, addAnimation = () => { if (curAni) { var data_ = { name: 'animation_' + aniIndex, duration: curAni.slice(0, curAni.length - 1).reduce(function (total, currentValue) { return total + currentValue.time; }, 0), //总时长(要去掉最后一个,因为已到终点,该点time无意义) useDurSlice: data.useDurSlice, points: curAni }; var ani = createAnimation(data_); sections.push(ani); ani.originIndexStart = data.indexOf(curAni[0]); ani.addEventListener('updateCurrentIndex', e => { emitIndex(e.currentIndex); }); curAni = null; } }; data.points.forEach((e, i) => { //切分为若干个animation,中间是漫游点的衔接 if (e.inPano) { var pano = e.model.panos.find(a => a.originID == e.panoId); if (pano) { addAnimation(); //如果前面是动画,先截断 e.pano = pano; e.quaternion = Potree.Utils.datasetRotTransform({ fromDataset: true, quaternion: e.rotInModel, getQuaternion: true, object: e.model }); sections.push(e); } } else { if (curAni) { curAni.push(e); } else { //非pano if (sections.length > 0) { var last = sections[sections.length - 1]; //因为要从上一个pano出来,所以起始点是上一个pano last.position = last.pano.position; last.target = last.position.clone().add(new Vector3(0, 0, -1).applyQuaternion(last.quaternion)); curAni = [last, e]; } else { curAni = [e]; } } } }); addAnimation(); var currentPlay; var emitIndex = function emitIndex() { var indexInAni = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var ani = sections[currentPlay]; var currentIndex = 0; if (ani instanceof CameraAnimation$1) { currentIndex = ani.originIndexStart + indexInAni; } else { currentIndex = data.indexOf(ani); } event_.dispatchEvent({ type: 'updateCurrentIndex', currentIndex }); }; var result = { event_, play() { //从头播放 var playNext = index => { if (index == sections.length) { return event_.dispatchEvent('playDone'); } var ani = sections[index]; currentPlay = index; emitIndex(); if (ani instanceof CameraAnimation$1) { Potree.settings.displayMode = 'showPointCloud'; ani.addEventListener('playDone', () => { playNext(index + 1); }, { once: true }); ani.play(); } else { var last = sections[index - 1], duration, quaternion = ani.quaternion; if (last) { var pano = ani.pano; if (last instanceof CameraAnimation$1) { duration = last.durations[last.durations.length - 1]; //最后一个时间 } else { duration = last.time; } duration *= 1000; viewer.images360.flyToPano({ pano, quaternion, duration, callback: () => { if (ani.displayMode == 'showPanos' && potree.settings.displayMode != 'showPanos') { //刚加载完就飞走吗? potree.settings.displayMode = 'showPanos'; viewer.images360.addEventListener('endChangeMode', () => { currentPlay != void 0 && playNext(index + 1); }, { once: true }); } else { currentPlay != void 0 && playNext(index + 1); } } }); } } }; playNext(0); }, stop() { var ani = sections[currentPlay]; if (ani instanceof CameraAnimation$1) { ani.pause(); } else { var view = viewer.mainViewport.view; if (!view.isFlying('pos')) { //前后是相同漫游点,仅旋转 view.cancelFlying('rotate'); } else { //加快结束 var o = transitions.getById(view.FlyTransition); var restDur = o.duration - o.current; var hopeStopTime = 300; //希望最多等待时间 if (restDur > hopeStopTime) { var r = o.duration / (o.current + hopeStopTime); transitions.adjustSpeed(view.FlyTransition, r); transitions.adjustSpeed(view.LookTransition, r); } } //如果有地图,还要改地图的view } currentPlay = null; }, remove() { sections.forEach(ani => { if (ani instanceof CameraAnimation$1) { this.removeAnimation(ani); } }); } //再把中间的缓动去除 }; return result; } }; var clickPanoToDisLink = false; //是否在编辑漫游点连接时,通过点击漫游点能断开连接 var images360, Alignment$1, SiteModel$1, suggestCircleMat; var texLoader$c = new TextureLoader(); texLoader$c.crossOrigin = "anonymous"; var rotQua = new Quaternion().setFromAxisAngle(new Vector3(0, 0, 1), Math.PI); var lineMats$3 = {}; var circleMats = {}; var renderOrders$1 = { circleSelected: 3, circle: 2, line: 1 }; var pointColor = { /* selected:"#c80", default:'#1ac' */ selected: "#c60", default: '#17c' }; var opacitys = { //点云透明度 'topView': { default: 0.4, selected: 0.6 }, 'sideView': { //侧面重叠概率高 default: 0.2, selected: 0.5 } }; //调这么低是因为有的重叠边缘太亮了 var cameraProps$2 = [{ name: 'top', axis: ["x", "y"], direction: new Vector3(0, 0, -1), //镜头朝向 openCount: 0 }, { name: 'right', axis: ["y", "z"], direction: new Vector3(1, 0, 0), openCount: 0 }, { name: 'mainView', openCount: 0 }]; class PanoEditor extends EventDispatcher { constructor() { super(); this.panoGroup = [], //分组 this.viewports = {}, this.panoLink = {}, this.panoMeshs = new Object3D(), this.lineMeshes = new Object3D(); this.views = {}; this.cameras = {}; this.orthoCamera = new OrthographicCamera(-100, 100, 100, 100, 0.01, 10000); this.orthoCamera.up.set(0, 0, 1); this.selectedPano; this.selectedGroup; this.operation; this.visiblePanos = []; this.suggestLines = []; } init() { { //init lineMats lineMats$3.default = LineDraw.createFatLineMat({ color: '#eeeeee', lineWidth: 2, depthTest: false }); lineMats$3.hovered = LineDraw.createFatLineMat({ color: '#00c8af', lineWidth: 2, depthTest: false }); lineMats$3.selected = LineDraw.createFatLineMat({ color: '#00c8af', lineWidth: 3, depthTest: false }); lineMats$3.suggestLink = LineDraw.createFatLineMat({ color: '#ff2222', lineWidth: 4, dashed: true, depthTest: false }); } suggestCircleMat = new MeshBasicMaterial({ map: texLoader$c.load(Potree.resourcePath + '/textures/whiteCircle.png'), color: '#ff2222', transparent: true, depthTest: false, depthWrite: false }); this.initViews(); /* { this.box = new BoxVolume({ clip:true }) this.box.clipTask = ClipTask['SHOW_INSIDE_Big' ] this.box.name = "panoEditClipBox"; } */ viewer.addEventListener('allLoaded', () => { images360 = viewer.images360; Alignment$1 = viewer.modules.Alignment; SiteModel$1 = viewer.modules.SiteModel; this.panoMeshs.name = 'panoMeshs'; viewer.scene.scene.add(this.panoMeshs); this.lineMeshes.name = 'lineMeshes'; viewer.scene.scene.add(this.lineMeshes); Potree.settings.ifShowMarker = false; { this.transformControls = new TransformControls(viewer.mainViewport.camera, viewer.renderArea, { dontHideWhenFaceCamera: true, rotFullCircle: true }); this.transformControls.setSize(1.5); viewer.scene.scene.add(this.transformControls); this.transformControls._gizmo.hideAxis = { /* translate:['x','y'], */rotate: ['x', 'y', 'e'] }; this.transformControls.setRotateMethod(2); this.fakeMarkerForTran = new Mesh(new BoxBufferGeometry(0.3, 0.3, 0.3), new MeshBasicMaterial({ color: "#FFFFFF", opacity: 0.4, transparent: true, visible: false })); //一个看不见的mesh,只是为了让transformControls移动点云 viewer.scene.scene.add(this.fakeMarkerForTran); var afterMoveCircle = type => { if (type == 'position') { var moveVec = new Vector3().subVectors(this.fakeMarkerForTran.position, this.fakeMarkerForTran.oldState.position); this.selectedClouds.forEach(cloud => Alignment$1.translate(cloud, moveVec)); } else { var center = this.selectedPano.position; var forward = new Vector3(0, 1, 0); var vec1 = forward.clone().applyQuaternion(this.fakeMarkerForTran.oldState.quaternion); var vec2 = forward.clone().applyQuaternion(this.fakeMarkerForTran.quaternion); var diffAngle = math.getAngle(vec1, vec2, 'z'); this.selectedClouds.forEach(cloud => { Alignment$1.rotateAround(center, cloud, null, diffAngle); }); } this.fakeMarkerForTran.oldState = { position: this.fakeMarkerForTran.position.clone(), quaternion: this.fakeMarkerForTran.quaternion.clone() }; Alignment$1.history.beforeChange(this.selectedClouds); }; this.fakeMarkerForTran.addEventListener('position_changed', afterMoveCircle.bind(this, 'position')); this.fakeMarkerForTran.addEventListener("rotation_changed", afterMoveCircle.bind(this, 'rotation')); this.transformControls.addEventListener('mouseUp', () => { Alignment$1.history.afterChange(this.selectedClouds); }); Alignment$1.history.addEventListener('undo', () => { this.updateTranCtl(); }); } this.initPanoLink(); this.addPanoMesh(); viewer.scene.pointclouds.forEach(e => { e.material.color = pointColor.default; }); viewer.setEDLEnabled(true); //为了降一倍的绘制. 同时用描边增强立体感,弥补点云稀疏 viewer.setEDLRadius(3); viewer.setEDLStrength(0.02); this.switchView('top'); { //默认选择一个楼层 var panoVisiReady, siteModelReady; var floorInit = () => { if (!panoVisiReady || !siteModelReady) return; setTimeout(() => { if (this.currentFloor == 'all') { //还未选择楼层的话 var floor = SiteModel$1.entities.find(e => e.buildType == 'floor' && e.panos.length); //选择有漫游点的一层 if (!floor) { floor = 'all'; //SiteModel.entities.find(e=>e.buildType == 'floor') console.log('没有一层有漫游点?!'); } console.log('initDataDone'); console.log('gotoFloor 1'); this.gotoFloor(floor); } }, 1); //2d那边用了nextTick ,so setTimeout here }; SiteModel$1.bus.addEventListener('initDataDone', () => { siteModelReady = true; floorInit(); }, { once: true }); this.addEventListener('panoVisiReady', () => { //2d初始化完成,才可以由3d修改pano显示 (因为在之前2d会给每个pano传来显示的消息,在这之前的修改都会别覆盖) panoVisiReady = true; floorInit(); }, { once: true }); } Alignment$1.bus.addEventListener('switchHandle', this.updateCursor.bind(this)); viewer.addEventListener('global_click', e => { if (e.button === MOUSE.RIGHT) { //取消旋转和平移 //console.log('right click',e) this.setLinkOperateState('addLink', false); this.setLinkOperateState('removeLink', false); } else if (this.clickToZoomInEnabled) { if (this.activeViewName == 'mainView') { viewer.controls.zoomToLocation(e.mouse); } else { this.zoomIn(e.intersect.orthoIntersect, e.pointer); } this.setZoomInState(false); } }); /* {//旋转时的辅助线--绕某个点旋转的版本 this.rotGuideLine = LineDraw.createLine([], {color:'#aaffee'}) this.rotGuideLine.visible = false this.rotGuideLine.name = 'rotGuideLine' this.rotGuideLine.renderOrder = renderOrders.line viewer.scene.scene.add(this.rotGuideLine) let startPoint Alignment.bus.addEventListener('rotateStart', (e)=>{ startPoint = e.startPoint }) Alignment.bus.addEventListener('rotate', (e)=>{ LineDraw.updateLine(this.rotGuideLine, [startPoint, e.endPoint] ) this.rotGuideLine.visible = true }) viewer.fpControls.addEventListener("end",(e)=>{ startPoint = null this.rotGuideLine.visible = false }) } */ { //连接时的辅助线 this.linkGuideLine = LineDraw.createLine([], { color: '#ddd', deshed: true, dashSize: 0.1, gapSize: 0.05, depthTest: false }); this.linkGuideLine.visible = false; this.linkGuideLine.name = 'linkGuideLine'; viewer.scene.scene.add(this.linkGuideLine); this.linkGuideLine.renderOrder = renderOrders$1.line; var update = e => { if (this.operation != 'addLink' || this.activeViewName != 'top' && this.activeViewName != 'mainView' || !this.selectedPano) { return this.linkGuideLine.visible = false; } var endPos; if (this.activeViewName == 'top') { endPos = e.intersect.orthoIntersect.clone().setZ(this.selectedPano.position.z); } else if (this.activeViewName == 'mainView') { if (!e.intersect || !e.intersect.point) return; endPos = e.intersect.point.position; } LineDraw.updateLine(this.linkGuideLine, [this.selectedPano.position, endPos]); this.linkGuideLine.visible = true; viewer.dispatchEvent('content_changed'); }; viewer.addEventListener('global_mousemove', e => { update(e); }); //this.addEventListener('updateLinkGuideLine', update) } /* viewer.inputHandler.addEventListener('keydown', (e)=>{ if(e.event.key == "r" ){ this.setTranMode('rotate') }else if(e.event.key == "t"){ this.setTranMode('translate') } }) */ /* { viewer.addEventListener('camera_changed', (e)=>{ Common.intervalTool.isWaiting('updatePointLevels', ()=>{ this.updatePointLevels() }, 1050) }) setTimeout(()=>{ this.updatePointLevels() }, viewer.scene.pointclouds.length*150) //等待差不多updat出了正确的visibleNode时 } */ this.panoReposCallback = () => { viewer.controls.setTarget(this.selectedPano.position); //3d时绕其为中心转动 }; }); } setTranMode(mode) { //rotate or translate console.log('setTranMode', mode); this.tranMode = mode; if (this.activeViewName == 'mainView') { mode && this.transformControls.setMode(mode); this.updateTranCtl(); } else { Alignment$1.switchHandle(mode); } this.updateIntersectEnable(); } updateIntersectEnable() { //侧面容易因intersect卡住, 如果非必要关闭intersect. 3d页面也会卡,但controls需要所以不能去掉 Potree.settings.intersectWhenHover = !!(this.activeViewName == 'mainView' || this.selectedPano && this.tranMode); } updateTranCtl() { // 设置3D页面的transformControls相关 if (!this.tranMode || !this.selectedPano || this.activeViewName != 'mainView') { return this.transformControls.detach(); } else if (this.checkIfAllLinked({ group: this.selectedGroup })) { this.dispatchEvent('needToDisConnect'); return this.transformControls.detach(); } this.transformControls.attach(this.fakeMarkerForTran); var { position, quaternion } = this.getPanoPose(this.selectedPano); this.fakeMarkerForTran.position.copy(position); this.fakeMarkerForTran.quaternion.copy(quaternion); this.fakeMarkerForTran.oldState = { position: position.clone(), quaternion: quaternion.clone() }; } ////////////////////////////////// initViews() { this.splitScreenTool = new SplitScreen(); this.targetPlane = viewer.mainViewport.targetPlane = new Plane(); this.shiftTarget = viewer.mainViewport.shiftTarget = new Vector3(); //project在targetPlane上的位置 for (var i = 0; i < 2; i++) { var prop = cameraProps$2[i]; var view = new ExtendView(); this.views[prop.name] = view; this.cameras[prop.name] = this.orthoCamera; view.name = prop.name; view.direction = prop.direction; } this.views.mainView = viewer.mainViewport.view; this.cameras.mainView = viewer.mainViewport.camera; } switchView(name) { //替换view和camera到mainViewport var view = this.views[name]; var camera = this.cameras[name]; var prop = cameraProps$2.find(e => e.name == name); var { boundSize, center } = viewer.bound; this.lastViewName = this.activeViewName; this.activeViewName = name; var lastView = this.views[this.lastViewName]; var lastCamera = this.cameras[this.lastViewName]; viewer.mainViewport.view = view; viewer.mainViewport.camera = camera; if (lastCamera) lastView.zoom = lastCamera.zoom; this.targetPlane.setFromNormalAndCoplanarPoint(view.direction.clone(), center); this.targetPlane.projectPoint(view.position, this.shiftTarget); //target转换到过模型中心的平面,以保证镜头一定在模型外 view.position.copy(this.splitScreenTool.getPosOutOfModel(viewer.mainViewport)); if (view.zoom) camera.zoom = view.zoom; //恢复上次的zoom viewer.updateScreenSize({ forceUpdateSize: true }); //更新camera aspect left等 this.updateCursor(); if (name == 'mainView') { viewer.mainViewport.alignment = null; var changeMat = () => { viewer.scene.pointclouds.forEach(e => { e.material.activeAttributeName = 'rgba'; e.material.useFilterByNormal = false; e.changePointOpacity(1); }); }; /* if(prop.openCount == 0){ //点数较多时,首次转到3D视角会卡顿,因为要切换材质。 let delay1 = THREE.Math.clamp(viewer.scene.pointclouds.length*0.5, 1, 200) setTimeout(()=>{ this.activeViewName == 'mainView' && changeMat() },delay1) //console.log('switchview',delay1 ) }else{ */ changeMat(); //} Potree.Utils.updateVisible(viewer.reticule, 'force', true); if (lastView) { //2d->3d view.copy(lastView); var direction = view.direction; var panos = images360.panos.filter(e => e.circle.visible); var nearestPano = Common.sortByScore(panos, [], [pano => { var vec = new Vector3().subVectors(pano.position, view.position); return -vec.dot(direction); }], true); //console.log('最近',nearestPano ) if (nearestPano && nearestPano[0]) { //尽量不变画面范围,使pano点保持原位,转换到mainView var halfHeight = lastCamera.top / lastCamera.zoom; var dis = halfHeight / Math.tan(MathUtils.degToRad(camera.fov / 2)); view.position.add(direction.clone().multiplyScalar(-nearestPano[0].score - dis)); //console.log('getCloser', -nearestPano[0].score - dis) this.lastDisToPano = dis; //记录一下 } } viewer.fpControls.lockKey = false; } else { if (this.lastViewName == 'mainView') { //3d->2d var _direction = lastView.direction; var _panos = images360.panos.filter(e => e.circle.visible); //尽量靠近画布中心,且距离相机较近 var _nearestPano = Common.sortByScore(_panos, [], [pano => { var vec = new Vector3().subVectors(pano.position, lastView.position); var dis = vec.dot(_direction); return dis < 0 ? dis * 10 : -dis; }, pano => { var vec = new Vector3().subVectors(pano.position, lastView.position); var angle = vec.angleTo(_direction); return -angle * 70; }], true); //目前还存在的问题就是不知selectedPano和最近点的取舍 //console.log('panos',nearestPano ) if (_nearestPano && _nearestPano[0]) { //console.log('nearestPano',nearestPano[0].item.id ) var pos1 = _nearestPano[0].item.position.clone(); var pos2 = pos1.clone(); var _dis = new Vector3().subVectors(_nearestPano[0].item.position, lastView.position).dot(_direction); //-nearestPano[0].score //根据2d->3d的式子逆求zoom var _halfHeight = Math.abs(_dis) * Math.tan(MathUtils.degToRad(lastCamera.fov / 2)); camera.zoom = camera.top / _halfHeight; camera.updateProjectionMatrix(); if (name == 'right') { //侧视图 view.direction = _direction.clone().setZ(0); //水平方向设定为3d的方向 this.targetPlane.setFromNormalAndCoplanarPoint(view.direction.clone(), center); this.targetPlane.projectPoint(view.position, this.shiftTarget); //target转换到过模型中心的平面,以保证镜头一定在模型外 view.position.copy(this.splitScreenTool.getPosOutOfModel(viewer.mainViewport)); } view.applyToCamera(camera); //update pos1.project(lastCamera); pos2.project(camera); //目标是找到画面上最接近中心的一点(最好是漫游点,不然就是点云),让其在转换画面后在画面上的位置不变。万一找到的点不在屏幕中(比如当屏幕中没点云时),就默认让那个点移动到屏幕中央,也就是假设当前它pos1在屏幕中央位置。 // if (pos1.z > 1) { console.warn('选取的点在相机背后了!?'); } //如果最近点超出屏幕范围 (-1,1), 最好将其拉到边缘,甚至居中 。这样屏幕上就不会没有漫游点了 var bound = 0.9; pos1.x = MathUtils.clamp(pos1.x, -bound, bound); pos1.y = MathUtils.clamp(pos1.y, -bound, bound); var vecOnscreen = new Vector3().subVectors(pos1, pos2); var moveVec = Potree.Utils.getOrthoCameraMoveVec(vecOnscreen, camera); //console.log('pos1', pos1) view.position.sub(moveVec); } } else { if (prop.openCount == 0) { //至多执行一次 this.viewportFitBound(name, boundSize, center); } } viewer.scene.pointclouds.forEach(e => { e.material.activeAttributeName = 'color'; e.material.useFilterByNormal = true; var opaProp = name == 'top' ? opacitys.topView : opacitys.sideView; if (this.selectedPano && this.selectedClouds.includes(e)) { e.changePointOpacity(opaProp.selected, true); e.material.color = pointColor.selected; } else { e.changePointOpacity(opaProp.default, true); e.material.color = pointColor.default; } }); Potree.Utils.updateVisible(viewer.reticule, 'force', false); if (name == 'top') viewer.mainViewport.alignment = { rotate: true, translate: true }; if (name == 'right') { viewer.mainViewport.alignment = { translate: true, rotateSide: true, translateVec: new Vector3(0, 0, 1) }; //只能上下移动 viewer.mainViewport.rotateSide = true; } else { viewer.mainViewport.rotateSide = false; } viewer.fpControls.lockKey = true; } this.updateTranCtl(); this.setTranMode(this.tranMode); // update this.setZoomInState(false); //取消放大模式 //this.updatePointLevels() this.updateIntersectEnable(); prop.openCount++; } viewportFitBound() { //使一个viewport聚焦在某个范围 if (viewer.mainViewport.resolution.x == 0 || viewer.mainViewport.resolution.y == 0) { return setTimeout(() => { this.viewportFitBound(); }, 10); } this.gotoFloor(this.currentFloor, true, 0, null, true); } rotateSideCamera(angle) { //侧视图绕模型中心水平旋转 this.splitScreenTool.rotateSideCamera(viewer.mainViewport, angle); } zoomIn(intersect, pointer) { var camera = viewer.mainViewport.camera; var endZoom = 200; //this.orthoMoveFit(intersect, {endZoom:viewer.mainViewport.camera.zoom < aimZoom ? aimZoom : null} , 300) var startZoom = camera.zoom; if (startZoom >= endZoom) { return; } viewer.mainViewport.view.zoomOrthoCamera(camera, endZoom, pointer, 300); } orthoMoveFit(pos, info, duration) { var margin = { x: 200, y: 230 }; this.splitScreenTool.viewportFitBound(viewer.mainViewport, info.bound, pos, duration, margin); } setZoomInState(state, informinformBy2d) { //是否点击后可放大 //if(state && this.activeViewName == 'mainView')return console.log('3D不可放大') this.clickToZoomInEnabled = !!state; if (state) { viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "zoomInCloud" }); } else { viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "zoomInCloud" }); } if (!state && !informinformBy2d) { this.dispatchEvent({ type: 'operationCancel', operation: 'zoomIn' }); } } gotoFloor(floor, force) { var duration = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 600; var informBy2d = arguments.length > 3 ? arguments[3] : undefined; var fitBound = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true; // 选择不同楼层, 切换点位显示。 'all'为全部显示 floor = floor || 'all'; if (this.currentFloor == floor && !force) return; if (this.currentFloor != floor) { //如果楼层没变,不修改可视 //let pointclouds = viewer.findPointcloudsAtFloor(floor) var panos = floor == 'all' ? viewer.images360.panos : floor.panos; viewer.images360.panos.forEach(pano => { var v = panos.includes(pano); this.switchPanoVisible(pano, v); }); } this.updateLinesVisible(); //切换楼层时清空选择状态 if (this.selectedPano && floor != 'all' && !floor.panos.includes(this.selectedPano)) { this.selectedPano.circle.dispatchEvent('click'); } if (this.selectedLine) { this.selectedLine.dispatchEvent('click'); } var bound, center; if (floor == 'all') { bound = viewer.images360.bound.bounding; center = viewer.images360.bound.center; } else { bound = this.getPanosBound(floor); center = bound.getCenter(new Vector3()); if (floor.panos.length == 0) console.log(floor.name, 'floor无漫游点'); } if (this.activeViewName != 'mainView') { fitBound && this.orthoMoveFit(center, { bound }, duration); } else if (this.activeViewName == 'mainView') { //if(floor != 'all'){ //切换一下位置,因为原处点云会消失 //viewer.scene.view.setView({position:center, duration }) viewer.focusOnObject({ boundingBox: bound }, 'boundingBox'); //} } this.currentFloor = floor; //if(!informBy2d){ //注释原因:2d居然不会自己变 this.dispatchEvent({ type: 'changeFloor', floor }); //} } getPanosBound(floor) { if (!floor.panosBound) { if (floor.panos.length == 0) { floor.panosBound = viewer.images360.bound.bounding.clone(); } else { var minSize = new Vector3(10, 10, 10); var bound = math.getBoundByPoints(floor.panos.map(e => e.position), minSize); floor.panosBound = bound.bounding; } } return floor.panosBound; } switchPanoVisible(pano, v, informBy2d) { //console.log(pano.id,v) Potree.Utils.updateVisible(pano.circle, 'panoEditor', v); Potree.Utils.updateVisible(pano, 'panoEditor', v); Potree.Utils.updateVisible(pano.pointcloud, 'panoEditor', v); if (v) { this.visiblePanos.includes(pano) || this.visiblePanos.push(pano); } else { var index = this.visiblePanos.indexOf(pano); index > -1 && this.visiblePanos.splice(index, 1); } if (informBy2d) { this.dispatchEvent('panoVisiReady'); this.updateLinesVisible(); } informBy2d || this.dispatchEvent({ type: "switchPanoVisible", pano, v }); /* { setTimeout(()=>{ Common.intervalTool.isWaiting('updatePointLevels2', ()=>{ this.updatePointLevels() }, 50) },1)//等update过visibleNodes } */ } updateLinesVisible() { this.lineMeshes.children.forEach(line => { var names = line.name.split('-'); var pano0 = images360.getPano(names[0]); var pano1 = images360.getPano(names[1]); line.visible = this.visiblePanos.includes(pano0) || this.visiblePanos.includes(pano1); }); } updateCursor() { var cursor; if (this.activeViewName == 'mainView' || !this.selectedPano) { cursor = null; } else { cursor = Alignment$1.handleState; } if (cursor == 'rotate') { viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "rotatePointcloud" }); viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "movePointcloud" }); } else if (cursor == 'translate') { viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "movePointcloud" }); viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "rotatePointcloud" }); } else { viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "movePointcloud" }); viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "rotatePointcloud" }); } //this.cursorState = cursor } setLinkOperateState(name, state, informinformBy2d) { if (state && name == this.operation || !state && name != this.operation) return; var old = this.operation; this.operation = state ? name : null; if (this.operation == 'removeLink') { if (this.selectedLine) { this.selectedLine.dispatchEvent('click'); //删除 } if (this.selectedPano && clickPanoToDisLink) { this.selectedPano.circle.dispatchEvent('click'); //删除 } } if (this.operation != 'addLink') { this.linkGuideLine.visible = false; } if (!state && !informinformBy2d) { this.dispatchEvent({ type: "operationCancel", operation: old }); } if (this.operation == 'addLink') { viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "connectPano" }); } else { viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "connectPano" }); } if (this.operation == 'removeLink') { viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "disconnectPano" }); } else { viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "disconnectPano" }); } viewer.dispatchEvent('content_changed'); } ///////////////////////////////// initPanoLink() { images360.panos.forEach(pano => { this.panoLink[pano.id] = {}; this.panoGroup.push([pano]); }); images360.panos.forEach(pano => { pano.visibles.forEach(index => { //visibles中存的是下标! this.linkChange(pano, images360.getPano(index, 'index'), 'add'); }); }); //console.log('panoLink',this.panoLink) } linkChange(pano0, pano1, type) { //修改link (type == 'remove'时,pano1可以为空) var temp = []; if (type == 'add') { if (!pano1) return console.error('不支持add时pano1为空'); this.panoLink[pano0.id][pano1.id] = this.panoLink[pano0.id][pano1.id] || {}; this.panoLink[pano1.id][pano0.id] = this.panoLink[pano1.id][pano0.id] || {}; } else { if (!pano1) { for (var id in this.panoLink[pano0.id]) { if (this.panoLink[pano0.id][id]) { this.panoLink[id][pano0.id] = false; temp.push(id); } } this.panoLink[pano0.id] = {}; //全部断连 } else { this.panoLink[pano0.id][pano1.id] = false; this.panoLink[pano1.id][pano0.id] = false; } } if (!pano1) { //全部断连 temp.forEach(id => { this.lineChange(pano0, images360.getPano(id), type); }); } else { this.lineChange(pano0, pano1, type); } this.groupChange(pano0, pano1, type); //this.updateSelectGroup() this.selectPano(this.selectedPano, false, true); //更新选中点云显示 } lineChange(pano0, pano1, type) { //修改line if (type == 'add') { if (this.panoLink[pano0.id][pano1.id].line) return; var line = LineDraw.createFatLine([pano0.position, pano1.position], { mat: lineMats$3.default }); line.name = "".concat(pano0.id, "-").concat(pano1.id); line.renderOrder = line.pickOrder = renderOrders$1.line; this.lineMeshes.add(line); this.panoLink[pano0.id][pano1.id].line = this.panoLink[pano1.id][pano0.id].line = line; line.addEventListener('mouseover', () => { if (this.clickToZoomInEnabled) return; //if(this.activeViewName == 'mainView')return if (this.selectedLine != line) line.material = lineMats$3.hovered; viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "hoverLine" }); }); line.addEventListener('mouseleave', () => { if (this.clickToZoomInEnabled) return; //if(this.activeViewName == 'mainView')return if (this.selectedLine != line) line.material = lineMats$3.default; viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "hoverLine" }); }); line.addEventListener('click', e => { if (this.clickToZoomInEnabled) return; //if(this.activeViewName == 'mainView')return if (this.operation == 'removeLink') { if (this.selectedLine == line) this.selectLine(null); return this.linkChange(pano0, pano1, 'remove'); } this.selectLine(line); }); } else { var _line = this.lineMeshes.children.find(e => e.name == "".concat(pano0.id, "-").concat(pano1.id) || e.name == "".concat(pano1.id, "-").concat(pano0.id)); if (_line) { this.lineMeshes.remove(_line); _line.geometry.dispose(); } } } groupChange(pano0, pano1, type) { //修改group (type == 'remove'时,pano1可以为空) if (type == 'add') { Common.pushToGroupAuto([pano0, pano1], this.panoGroup); } else { var atGroup = this.panoGroup.find(e => e.includes(pano0) && (e.includes(pano1) || !pano1)); //所在组 if (!atGroup) { if (pano1) { console.log('这两个pano原本就不在一个组', pano0.id, pano1.id); } else { console.log('pano0不在任何组', pano0); } return; } //断开连接时,因为组内没有其他成员的连接信息,所以需要清除整组,并将剩余的一个个重新连接 this.panoGroup.splice(this.panoGroup.indexOf(atGroup), 1); //删除 atGroup.forEach(pano => { //然后再重新生成这两个和组的关系,各自分组 this.panoGroup.push([pano]); for (var id in this.panoLink[pano.id]) { if (this.panoLink[pano.id][id]) { var pano_ = images360.getPano(id); Common.pushToGroupAuto([pano, pano_], this.panoGroup); } } }); } } selectLine(line) { if (this.selectedLine == line) return; if (this.selectedLine) { this.selectedLine.material = lineMats$3.default; } if (line) { line.material = lineMats$3.selected; } this.selectedLine = line; } addPanoMesh() { var map = texLoader$c.load(Potree.resourcePath + '/textures/correct_n.png'); /* circleMats.default_normal = new THREE.MeshBasicMaterial({ map, color: 0xffffff, transparent: true, depthTest: false, depthWrite: false, }) */ window.circleMats = circleMats; circleMats.default_normal = new DepthBasicMaterial({ map, color: 0xffffff, transparent: true, useDepth: true, backColor: 0x33ffdd, occlusionDistance: 10, //变为backColor距离 clipDistance: 5, //消失距离 maxClipFactor: 0.8, maxOcclusionFactor: 0.8 }); circleMats.default_rtk_on = circleMats.default_normal.clone(); circleMats.default_rtk_on.map = texLoader$c.load(Potree.resourcePath + '/textures/rtk-y-n.png'); circleMats.default_rtk_off = circleMats.default_normal.clone(); circleMats.default_rtk_off.map = texLoader$c.load(Potree.resourcePath + '/textures/rtk-f-n.png'); circleMats.selected_normal = circleMats.default_normal.clone(); circleMats.selected_normal.map = texLoader$c.load(Potree.resourcePath + '/textures/correct_s.png'); circleMats.selected_normal.useDepth = false; circleMats.selected_rtk_on = circleMats.selected_normal.clone(); circleMats.selected_rtk_on.map = texLoader$c.load(Potree.resourcePath + '/textures/rtk-y-s.png'); circleMats.selected_rtk_off = circleMats.selected_normal.clone(); circleMats.selected_rtk_off.map = texLoader$c.load(Potree.resourcePath + '/textures/rtk-f-s.png'); circleMats.hovered_normal = circleMats.default_normal.clone(); circleMats.hovered_normal.color.set(0x00ff00); circleMats.hovered_normal.useDepth = false; circleMats.hovered_rtk_on = circleMats.default_rtk_on.clone(); circleMats.hovered_rtk_on.color.set(0x00ff00); circleMats.hovered_rtk_on.useDepth = false; circleMats.hovered_rtk_off = circleMats.default_rtk_off.clone(); circleMats.hovered_rtk_off.color.set(0x00ff00); circleMats.hovered_rtk_off.useDepth = false; var setPos = circle => { circle.position.copy(circle.pano.position); for (var id in this.panoLink[circle.pano.id]) { var linkInfo = this.panoLink[circle.pano.id][id]; if (linkInfo) { LineDraw.updateLine(linkInfo.line, [circle.pano.position, images360.getPano(id).position]); } } circle.waitUpdate(); //update sprite Matrix }; images360.panos.forEach(pano => { var circle = new Sprite$2({ mat: circleMats['default' + '_' + this.getPanoRtkState(pano)], sizeInfo: { minSize: 50, maxSize: 120, nearBound: 2, farBound: 10 }, renderOrder: renderOrders$1.circle, pickOrder: renderOrders$1.circle }); circle.pickDontCheckDis = true; circle.name = 'panoCircle'; circle.sid = pano.id; circle.pano = pano; pano.circle = circle; this.panoMeshs.add(circle); setPos(circle); pano.addEventListener('rePos', setPos.bind(this, circle)); var drag = e => { /* if(this.activeViewName == 'mainView' && this.tranMode == 'translate'){//如果3d页不禁止xy的话,这段打开 this.transformControls.dispatchEvent('dragging')//触发拖拽 return } */ if (this.tranMode != 'translate' || this.activeViewName == 'mainView') return e.refuse(); this.selectPano(circle.pano); //为了方便拖拽点云,拖动circle就直接选中 viewer.inputHandler.drag.object = null; //取消拖拽状态,否则不触发点云拖动 }; circle.addEventListener('drag', drag); circle.addEventListener('mouseover', () => { this.hoverPano(pano, true); }); circle.addEventListener('mouseleave', () => { this.hoverPano(pano, false); }); circle.addEventListener('click', () => { //if(this.activeViewName == 'mainView')return if (this.clickToZoomInEnabled) return; if (clickPanoToDisLink && this.operation == 'removeLink') { this.linkChange(pano, null, 'remove'); //删除所有连接 } if (this.selectedPano == circle.pano) return this.selectPano(null); if (this.operation == 'addLink' && this.selectedPano) { this.linkChange(this.selectedPano, circle.pano, 'add'); //this.setLinkOperateState('addLink',false) return; } //if(this.operation == 'removeLink' && this.selectedPano){ //和选择中心点冲突 // this.linkChange(this.selectedPano, circle.pano, 'remove') // //this.setLinkOperateState('removeLink',false) // return // } this.selectPano(circle.pano); }); }); } hoverPano(pano, state) { if (this.clickToZoomInEnabled) return; if (pano && state) { //在hover一个pano之前,一定会先取消已经hover的pano, 最多存在一个hovered的pano if (this.hoveredPano == pano) return; if (this.hoveredPano) { this.hoverPano(this.hoveredPano, false); } this.hoveredPano = pano; pano.hovered = true; if ( /* this.activeViewName == 'mainView' || */Alignment$1.handleState && this.selectedPano && this.selectedPano == pano) return; if (this.operation != 'addLink' || !this.selectedPano || this.selectedPano == pano) { // this.selectedPano == pano? viewer.dispatchEvent({ type: "CursorChange", action: "add", name: "hoverPano" }); } if (this.selectedPano != pano) pano.circle.material = circleMats['hovered' + '_' + this.getPanoRtkState(pano)]; } else if (pano && !state) { //unhover if (this.hoveredPano != pano) return; pano.hovered = false; viewer.dispatchEvent({ type: "CursorChange", action: "remove", name: "hoverPano" }); if (this.selectedPano != pano) pano.circle.material = circleMats['default' + '_' + this.getPanoRtkState(pano)]; this.hoveredPano = null; } else { //unhover any if (this.hoveredPano) { this.hoverPano(this.hoveredPano, false); } } } selectPano(pano, informinformBy2d, force) { if (this.selectedPano == pano && !force) return; var lastSeletedPano = this.selectedPano; var opaProp = this.activeViewName == 'top' ? opacitys.topView : opacitys.sideView; if (this.selectedPano) { this.selectedPano.circle.material = circleMats['default' + '_' + this.getPanoRtkState(this.selectedPano)]; this.selectedPano.circle.renderOrder = renderOrders$1.circle; this.selectedPano.removeEventListener('rePos', this.panoReposCallback); if (this.activeViewName == 'mainView') {} else { this.selectedClouds.forEach(e => { e.changePointOpacity(opaProp.default, true); e.material.color = pointColor.default; }); } } this.selectedPano = pano || null; this.updateSelectGroup(); if (pano) { this.selectedPano.circle.material = circleMats['selected' + '_' + this.getPanoRtkState(this.selectedPano)]; this.selectedPano.circle.renderOrder = this.selectedPano.circle.pickOrder = renderOrders$1.circleSelected; //侧视图能显示在最前 viewer.controls.setTarget(this.selectedPano.position); //3d时绕其为中心转动 this.selectedPano.addEventListener('rePos', this.panoReposCallback); if (this.activeViewName == 'mainView') {} else { this.selectedClouds.forEach(e => { e.changePointOpacity(opaProp.selected, true); e.material.color = pointColor.selected; }); } if (this.currentFloor != 'all') { //如果原本不是展示全部楼层的话,自动切换楼层 var atFloor = SiteModel$1.entities.find(e => e.buildType == 'floor' && e.panos.includes(pano)); if (!atFloor) { atFloor = 'all'; } else {} this.gotoFloor(atFloor, false, 600); } } else { viewer.controls.setTarget(null); } this.updateCursor(); this.updateTranCtl(); if (informinformBy2d) { if (this.selectedPano) { if (this.activeViewName == 'mainView') { //平移,focus选中的pano var distance = this.lastDisToPano || 5; if (lastSeletedPano) { distance = viewer.mainViewport.camera.position.distanceTo(lastSeletedPano.position); } viewer.focusOnObject({ position: this.selectedPano.position }, 'point', null, { distance }); } else { this.orthoMoveFit(this.selectedPano.position, {}, 500); } } } else { this.dispatchEvent({ type: 'panoSelect', pano }); } this.updateIntersectEnable(); viewer.dispatchEvent('content_changed'); } /* updatePointLevels(){ if(this.pauseUpdateLevels)return let maxBudget = Potree.config.pointDensity.panoEdit.pointBudget let visiCount1 = viewer.scene.pointclouds.filter(e=>e.visible).length let visiCount2 = viewer.scene.pointclouds.filter(e=>e.visibleNodes.length>0).length //屏幕范围内可见的个数 let maxCount = 200, minCount = 1, minPer = 0.45 , maxPer = 1 let percent1 = maxPer - ( maxPer - minPer) * THREE.Math.clamp((visiCount1 - minCount) / (maxCount - minCount),0,1) let percent2 = maxPer - ( maxPer - minPer) * THREE.Math.clamp((visiCount2 - minCount) / (maxCount - minCount),0,1) let percent = percent1*percent2 if(this.activeViewName == 'mainView' ){ //假设每个pointcloud所带的点个数大致相同,那么当可见点云个数越多,所能展示的level越低,否则因总个数超过budget的话密度会参差不齐。 //pointcloud.changePointSize() //console.log('updatePointLevels', percent, visiCount) Potree.settings.UserDensityPercent = Math.sqrt(percent2) viewer.setPointBudget(maxBudget * percent2) }else{ Potree.settings.UserDensityPercent = 1 viewer.setPointBudget(maxBudget * percent) } viewer.setPointBudget(maxBudget * percent) viewer.setPointLevels() //侧面容易卡顿,但和显示的点数无关,似乎是因加载点云多而卡?为何正面不会 //console.warn('setPointBudget', Potree.pointBudget, visiCount1,visiCount2, Potree.settings.UserDensityPercent) } */ getPanoRtkState(pano) { return pano.panosData.has_rtk ? pano.rtkState ? 'rtk_on' : 'rtk_off' : 'normal'; } setPanoRtkState(pano, state) { pano.rtkState = state; pano.circle.material = circleMats[(this.selectedPano == pano ? 'selected' : 'default') + '_' + this.getPanoRtkState(pano)]; } updateSelectGroup() { //更新选中的组 this.selectedGroup = this.panoGroup.find(e => e.includes(this.selectedPano)); if (this.selectedGroup) { this.selectedGroup = [this.selectedPano, ...this.selectedGroup.filter(e => e != this.selectedPano)]; //将选中的放第一个,便于旋转时绕其旋转。 } //this.selectedClouds = this.selectedPano ? (this.selectedGroup || [this.selectedPano]).map(e=>e.pointcloud) : [] this.selectedClouds = this.selectedPano ? this.selectedGroup.map(e => e.pointcloud) : []; } checkIfCanSave() { //如果未全部相连,不能保存 for (var datasetId in Potree.settings.datasetsPanos) { if (!this.checkIfAllLinked({ datasetId })) { console.log('没有全部连通,不能保存。其中一个:', datasetId); return; } } return true; } checkIfAllLinked(o) { //某个(or组所在的)数据集是否全部连通 var datasetId, group; if (o.group) { group = o.group; var pano = o.group[0]; if (!pano) return; //会有没有漫游点的点云来编辑吗 datasetId = pano.pointcloud.dataset_id; } else if (o.datasetId) { datasetId = o.datasetId; group = this.panoGroup.find(panos => panos[0].pointcloud.dataset_id == datasetId); if (!group) return; //要找的数据集的pano全部都孤立了 } if (datasetId == void 0) return; var panos = Potree.settings.datasetsPanos[datasetId].panos; return panos.length == group.length; } getSuggestLinkPanos() { var _this = this; //给出建议连接的点 var panos = []; var startTime = Date.now(); var _loop = function _loop(datasetId) { if (!_this.checkIfAllLinked({ datasetId })) { var groups = _this.panoGroup.filter(panos => panos[0].pointcloud.dataset_id == datasetId); groups = groups.sort((a, b) => { return b.length - a.length; }); //找出个数最多的一组来连接其他组 var mainGroup = groups[0].slice(), subGroup; for (var i = 1, len = groups.length; i < len; i++) { subGroup = groups[i]; var minDis = { dis: Infinity, panos: [] }; for (var a = 0, len1 = mainGroup.length; a < len1; a++) { for (var b = 0, len2 = subGroup.length; b < len2; b++) { var dis = mainGroup[a].position.distanceToSquared(subGroup[b].position); if (dis < minDis.dis) { minDis.dis = dis; minDis.panos = [mainGroup[a], subGroup[b]]; } } } panos.push(minDis.panos); //console.log('第i次',minDis) mainGroup.push(...subGroup); //连接后,加入集合 } } }; for (var datasetId in Potree.settings.datasetsPanos) { _loop(datasetId); } //console.log('cost', Date.now() - startTime) return panos; } showSuggestLinkPanos() { var groups = this.getSuggestLinkPanos(); var s = 0.7; var createCircle = pano => { var circle = new Mesh(pano.circle.geometry, suggestCircleMat); circle.name = 'suggest-circle'; circle.scale.set(s, s, s); circle.renderOrder = 100; pano.circle.add(circle); }; groups.forEach(panos => { createCircle(panos[0]); createCircle(panos[1]); var line = LineDraw.createFatLine([panos[0].position, panos[1].position], { mat: lineMats$3.suggestLink }); this.suggestLines.push(line); line.renderOrder = renderOrders$1.line; viewer.scene.scene.add(line); }); } getPanoPose(pano) { var pose = { position: pano.position.clone(), quaternion: new Quaternion().setFromRotationMatrix(pano.panoMatrix).premultiply(rotQua) }; return pose; } exportSavingData() { //输出漫游点新的坐标和朝向、以及连接信息 var sweepLocations = {}; for (var datasetId in Potree.settings.datasetsPanos) { var { panos } = Potree.settings.datasetsPanos[datasetId]; var data = panos.map(pano => { var visibles = []; for (var id in this.panoLink[pano.id]) { if (this.panoLink[pano.id][id]) { visibles.push(viewer.images360.getPano(id).index); } } var { position, quaternion } = this.getPanoPose(pano); return Object.assign({}, pano.panosData, { uuid: pano.uuid, /* pose:{ translation: dealData(pano.position.clone() ), rotation: dealData(new THREE.Quaternion().setFromRotationMatrix(pano.panoMatrix).premultiply(rotQua) ), }, */ pose: { translation: dealData(position), rotation: dealData(quaternion) }, visibles, use_rtk: !!pano.rtkState //subgroup: 0,group: 1, "id_view":.. }); }); sweepLocations[datasetId] = { sweepLocations: data }; } /* this.lineMeshes.children.forEach(e=>{//从line中搜集连接信息,而不从linkInfo,这样visibles不会重复一次 let names = e.name.split('-') //是不是该转成数字 var pano0 = names[0] var pano1 = names[1] sweepLocations.find(s=>s.uuid == pano0).visibles.push(pano1) }) */ function dealData(value) { var v = math.toPrecision(value, 6); if (v instanceof Quaternion) { return { x: v.x, y: v.y, z: v.z, w: v.w }; } else if (v instanceof Vector3) { return { x: v.x, y: v.y, z: v.z }; } } //console.log(sweepLocations) return sweepLocations; } } /* 不同数据集之间不能连线 不同楼层可能也不能 如果楼层在不同建筑物怎么办? 楼层切换按钮只能在一个建筑内切换。 全部相连时不能移动和旋转 如果未全部相连,不能保存 */ var PanoEditor$1 = new PanoEditor(); /* import {Utils} from "../../../utils.js"; import Sprite from '../../objects/Sprite.js' import browser from '../../utils/browser.js' */ //import {Prism} from './Prism.js' var maxWidth = 4096; var surfaceThick = 0.1; //最大表面厚度 var pointDensity = 'screenshot'; var maxPointBudge = Potree.config.pointDensity[pointDensity].pointBudget; var Shaders$1 = { 'modelHeight.vs': " \n precision highp float;\n \n uniform vec2 boundZ;\n varying float heightPercent; \n \n \n \n void main() \n { \n vec3 worldPos = (modelMatrix * vec4(position, 1.0)).xyz; \n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); \n \n float zMin = boundZ.x, zMax = boundZ.y ;\n heightPercent = (worldPos.z - zMin) / (zMax - zMin); \n \n \n }\n \n \n ", 'modelHeight.fs': "\n precision highp float;\n varying float heightPercent; \n \n \n \n \n vec3 percentToByte(float num){\n //\u8F93\u51FA\u662F0-1\uFF0C shader\u7CBE\u5EA6\u4E0D\u591F\uFF0C\u53EA\u591F\u5B583\u4E2A\u6570\uFF0C\u56E0\u7B2C\u56DB\u4F4D\u603B\u662F0\n float a = 1.0;\n float result[4];\n for(int i=0;i<3;i++){\n a = i == 2 ? a/255.0 : a / 256.0 ; \n //\u5206\u6210256\u4EFD\uFF0C\u5176\u4E2D255\u4EFD\u7ED9\u5F53\u524D\u4F4D\u7F6E\uFF0C\u6700\u540E\u4E00\u4EFD\u7ED9\u540E\u4E00\u4E2A\u4F4D\u7F6E\uFF0C\u800C\u5230\u4E86\u6700\u540E\u4E00\u4E2A\u4F4D\u7F6E\u65F6\u6CA1\u6709\u4E0B\u4E00\u4E2A\u4F4D\u7F6E\u4E86\u6240\u4EE5\u53EA\u5206\u6210255\u4EFD\n if(num > a){\n float c = num / a;\n float r = floor(c);\n r = min(255.0, r);\n result[i] = r;\n num -= r * a;\n }else{\n result[i] = 0.0;\n }\n } \n return vec3(result[0]/255.0, result[1]/255.0,result[2]/255.0); \n \n } \n \n \n void main() {\n \n gl_FragColor = vec4(percentToByte(heightPercent),1.0); \n \n \n }\n " }; var horizonZ, zMin, zMax, lowest, highest, wDelta, sDelta, deferred, interrupt, timestamp, buffer1, buffer2, modelZs = []; var testPoint$1 = false; //const asyncTimeout = (delay) => new Promise(resolve => setTimeout(resolve, delay)) var delayForNotify = 5, notifyInterval = 500; var lastNotifyTime = Date.now(); var curPercent; var notify = (areas, num, str) => { //num: 0-1 return new Promise(resolve => { if (!deferred) return resolve(); var now = Date.now(); if (now - lastNotifyTime < notifyInterval) { return resolve(); } lastNotifyTime = now; if (num == void 0) { num = curPercent; } else { var s = 0, e = 1; if (num instanceof Function) { num = num(); } areas.forEach(area => { var s_ = e * area[0] + s * (1 - area[0]); var e_ = e * area[1] + s * (1 - area[1]); s = s_, e = e_; }); var p = e * num + s * (1 - num); str == 'loadpoints' && Potree.settings.isTest && console.log('notify pro', p, str); deferred.notify(p); curPercent = p; if (isNaN(p)) { console.log('nan'); } } setTimeout(resolve, delayForNotify); }); }; class VolumeComputer extends EventDispatcher { constructor() { super(); this.camera = new OrthographicCamera(-100, 100, -100, 100, 0.01, 100); this.camera.up.set(0, 0, 1); Potree.Utils.setCameraLayers(this.camera, ['model']); this.view = new ExtendView(); this.viewport = new Viewport(this.view, this.camera, { left: 0, bottom: 0, width: 1, height: 1 }); this.renderTarget = new WebGLRenderTarget(1, 1, { minFilter: LinearFilter, magFilter: NearestFilter, format: RGBAFormat }); this.renderTarget2 = new WebGLRenderTarget(1, 1, { minFilter: LinearFilter, magFilter: NearestFilter, format: RGBAFormat }); this.renderTarget2.texture.name = 'volumeCptModelTex'; this.material = new ExtendPointCloudMaterial(); this.material.activeAttributeName = testPoint$1 ? "rgba" : 'heightCpt'; // 'rgba' indices prismHeight this.prisms = []; this.modelMat = new ShaderMaterial({ uniforms: { boundZ: { type: "vec2", value: new Vector2() } }, vertexShader: Shaders$1['modelHeight.vs'], fragmentShader: Shaders$1['modelHeight.fs'], depthWrite: true, depthTest: true, transparent: false, side: DoubleSide }); this.scene = new Scene(); } init() { viewer.scene.addEventListener('measurement_added', e => { if (e.measurement.isPrism) this.add(e.measurement); }); viewer.scene.addEventListener('measurement_removed', e => { if (e.measurement.isPrism) this.remove(e.measurement); }); var this_ = this; this.events = { transformCallback: () => { if (!this_.currentPrism) return; //Common.intervalTool.isWaiting('volCptTransformed', ()=>{ //延时update,防止卡顿 var object = viewer.transformationTool.selection[0]; if (object == this_.currentPrism.baseModel) { this.updateModelBound({ modelChange: true }); } this_.currentPrism.dispatchEvent('needsCompute'); //模型变动或clipBox变动后要重算 //}, 1000) } }; } enter() { this.entered = true; viewer.measuringTool.history.clear(); //避免撤销到测量线去 this.oldStates = { rotAroundPoint: Potree.settings.rotAroundPoint }; Potree.settings.rotAroundPoint = false; //viewer.objs.traverse(e=>e.material && ( e.material = this.material)) viewer.transformationTool.addEventListener('stopDrag', this.events.transformCallback); viewer.transformationTool.addEventListener('changeByHistory', this.events.transformCallback); } leave() { this.entered = false; Potree.settings.rotAroundPoint = this.oldStates.rotAroundPoint; this.setCurrentPrism(null); viewer.transformationTool.removeEventListener('stopDrag', this.events.transformCallback); viewer.transformationTool.removeEventListener('changeByHistory', this.events.transformCallback); } add(prism) { this.prisms.push(prism); } remove(prism) { var i = this.prisms.indexOf(prism); i > -1 && this.prisms.splice(i, 1); } cancel() { if (this.computingObject) { interrupt = true; } } startCompute(model, dontCompute) { //test this.enter(); var deferred = $.Deferred(); deferred.done(e => { console.log('done', e); }); deferred.fail(e => { console.log('?fail????', e); }); /* deferred.progress((e)=>{ console.log('progress', e) }) */ if (model) { this.prisms[this.prisms.length - 1].setBaseModel(model); this.setCurrentPrism(this.prisms[this.prisms.length - 1]); dontCompute || this.compute(this.prisms[this.prisms.length - 1]); } else { this.compute(this.prisms[this.prisms.length - 1], deferred); } } setCurrentPrism(prism) { //当进入单个prism编辑后才会高亮点云 if (this.currentPrism) { this.currentPrism.removeEventListeners('updated'); } this.currentPrism = prism; //允许没有model if (!prism || !prism.baseModel /* || !prism.baseModel.visible */) { viewer.scene.pointclouds.forEach(e => { this.updateMatForModel(e.material); //取消高亮 }); return; } prism.addEventListener('updated', () => { if (this.currentPrism != prism) { return console.log('currentPrism changed? 侦听没删除'); } this.updateModelBound(); }); this.updateModelBound({ regetMap: true }); } setModelMat(model, type) { if (type == 'recover') { model.traverse(e => e.originMat_ && (e.material = e.originMat_)); } else { model.traverse(e => e.material && e.material != this.modelMat && (e.originMat_ = e.material, e.material = this.modelMat)); } } updateModelBound() { var { modelChange, regetMap } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; //regetMap是在更换currentPrism必须重绘map,但不需要needUpdate var prism = this.currentPrism; var model = this.currentPrism.baseModel; if (!model) return; model.currentBound = model.boundingBox.clone().applyMatrix4(model.matrixWorld); //作用同prismBound var oldBound = model.clipBound && model.clipBound.clone(); model.clipBound = model.currentBound.clone(); //高亮范围 model.clipBound.min.max(prism.prismBound.min); //xy为交集 model.clipBound.max.min(prism.prismBound.max); model.clipBound.min.z = Math.min(model.currentBound.min.z, prism.prismBound.min.z); //z为并集,范围覆盖prism点、点云、model三者 model.clipBound.max.z = Math.max(model.currentBound.max.z, prism.prismBound.max.z); this.modelMat.uniforms.boundZ.value.set(model.clipBound.min.z, model.clipBound.max.z); var boundChanged = !oldBound || !oldBound.equals(model.clipBound); var boundSize = this.currentPrism.baseModel.clipBound.getSize(new Vector3()); this.boundSizeZero = boundSize.x <= 0 || boundSize.y <= 0 || boundSize.z <= 0; //会造成renderTarget尺寸为0,背景变白,报错:Framebuffer is incomplete: Attachment has zero size 和 The texture is a non-power-of-two texture. if ((modelChange || regetMap || boundChanged) && !this.boundSizeZero) { this.setModelHeightMap(); //包含cad在俯视中的范围 + 高度信息 //this.setModelMat(model,this.boundSizeZero ? 'recover' : null) } viewer.scene.pointclouds.forEach(e => { //暂时先只支持一个高亮区域 this.updateMatForModel(e.material, model); }); //需要重新渲染modelHeightmap的情况:bound改变、模型变动、更换currentPrism后 //注意,即使上传几种都没发生,仅仅移动prism的marker也要重算,假设一个marker在model范围内,移动后bound可能不变但体积肯定变。 /* if(boundChanged){ if(prism.recoverNeedCptNextTime){ prism.needsCompute = 'byVolume' //初始化,有volume就不用重算 prism.recoverNeedCptNextTime = false }else{ prism.dispatchEvent('needsCompute') } } */ } updateMatForModel(material, model) { var oldMap = material.uniforms.baseHeightAreaMap.value; if (model) { material.uniforms.baseHeightAreaMap.value = this.renderTarget2.texture; //model.baseHeightAreaMap ; material.uniforms.baseHeightBoundZ.value.set(model.clipBound.min.z, model.clipBound.max.z); material.uniforms.baseHeightBoundXY.value.set(model.clipBound.min.x, model.clipBound.max.x, model.clipBound.min.y, model.clipBound.max.y); } else { material.uniforms.baseHeightAreaMap.value = null; } if (oldMap != material.uniforms.baseHeightAreaMap.value) { material.shaderNeedsUpdate = true; } } setModelHeightMap() { var oldTarget = viewer.renderer.getRenderTarget(); var oldParent = this.currentPrism.baseModel.parent; var oldVisi = this.currentPrism.baseModel.visible; var boundSize = this.currentPrism.baseModel.clipBound.getSize(new Vector3()); var boundCenter = this.currentPrism.baseModel.clipBound.getCenter(new Vector3()); var { w, h } = this.getResByBound(boundSize, 'forModel'); if (w <= 0 || h <= 0) { return console.error('w<=0 || h<=0!!!!!!!!!', w, h); } /* w = THREE.Math.floorPowerOfTwo( w ); h = THREE.Math.floorPowerOfTwo( h ); */ //for warning:The texture is a non-power-of-two texture this.camera.far = boundSize.z + 10; this.camera.right = w / 2; this.camera.left = -this.camera.right; this.camera.top = h / 2; this.camera.bottom = -this.camera.top; this.viewport.resolution.set(w, h); this.renderTarget2.setSize(w, h); viewer.renderer.setRenderTarget(this.renderTarget2); console.log('setModelHeightMap'); //最高处朝下看 var endPosition = new Vector3(); endPosition.copy(boundCenter).setZ(this.currentPrism.baseModel.clipBound.max.z + this.camera.near + 0.1); this.view.pitch = -Math.PI / 2; this.view.moveOrthoCamera(this.viewport, { boundSize, endPosition }, 0); this.view.applyToCamera(this.camera); this.scene.add(this.currentPrism.baseModel); this.setModelMat(this.currentPrism.baseModel); this.currentPrism.baseModel.visible = true; var gl = viewer.renderer.getContext(); viewer.renderer.setClearColor(new Color('#000'), 0); viewer.renderer.clear(); viewer.renderer.render(this.scene, this.camera); this.setModelMat(this.currentPrism.baseModel, 'recover'); var pixelCount = this.renderTarget2.width * this.renderTarget2.height; buffer2 = new Uint8Array(4 * pixelCount); //因为需要渲染完立即readPixels才能获取到,所以只能这时候就read了 gl.readPixels(0, 0, this.renderTarget2.width, this.renderTarget2.height, gl.RGBA, gl.UNSIGNED_BYTE, buffer2); //这句花费最多时间 pc:2-4, 即使只有1*1像素 modelZs = []; //等待计算 if (window.needDownload) { var dataUrl = Potree.Utils.renderTargetToDataUrl(this.renderTarget2, this.renderTarget2.width, this.renderTarget2.height, viewer.renderer); Common.downloadFile(dataUrl, (name || 'screenshot') + '-' + Date.now() + '.png'); } oldParent.add(this.currentPrism.baseModel); this.currentPrism.baseModel.visible = oldVisi; viewer.renderer.setRenderTarget(oldTarget); this.renderTarget2.texture.needsRebuild = true; //renderTarget在resize后会触发dispose, 然后 _gl.deleteTexture( textureProperties.__webglTexture )所以需要重新建立 否则图片变黑 return this.renderTarget2.texture; } getResByBound(boundSize, type) { //let pxPerMetric = math.linearClamp(Math.max(boundSize.x,boundSize.y), [4, 10, 20, 80, 500, 2000], [300, 200, 100, 30, 6, 3]) var pxPerMetric = math.linearClamp(Math.max(boundSize.x, boundSize.y), [10, 60, 100, 500, 2000], [150, 60, 40, 6, 3]); var w = pxPerMetric * boundSize.x, h = boundSize.y * pxPerMetric; var cW = 1, cH = 1; //横向纵向渲染次数 超过maxWidth时分批渲染 if (w > maxWidth || h > maxWidth) { /* if(){//多数据集判断是否间隔过远,是的话返回 } */ if (type == 'forCompute') { //计算可以分多次渲染 cW = Math.ceil(w / maxWidth), cH = Math.ceil(h / maxWidth); w /= cW, h /= cH; } else if (type == 'forModel') { //但是model的贴图只能有一个 if (w > h) { w = maxWidth, h = w * boundSize.y / boundSize.x; } else { h = maxWidth, w = h * boundSize.x / boundSize.y; } } } w = Math.round(w); h = Math.round(h); return { w, h, pxPerMetric, cW, cH }; } //法1:只用一个顶部相机(当挖方遮挡填方时不准,但好算) async compute(prism, deferred_, getResolveResult) { var _this = this; if (!prism || prism.modelHaventLoad) { console.log('prism有问题'); return deferred_.reject(); } if (this.computingObject) return console.log('正在计算,请稍等'); var oldCurPrism = this.currentPrism; if (prism != this.currentPrism) { //在列表外点击计算 this.setCurrentPrism(prism); } var computeDone = (_ref, deferred) => { var { highest, lowest, Vupper, Vlower } = _ref; prism && prism.setVolumeInfo({ highest, lowest, Vupper, Vlower }); if (oldCurPrism != prism) { this.setCurrentPrism(oldCurPrism); } deferred && deferred.resolve(getResolveResult && getResolveResult()); }; if (prism.baseModel && this.boundSizeZero) { //bound没有交集 或 prism的boundsize为0 return computeDone({ highest: 0, lowest: 0, Vupper: 0, Vlower: 0 }, deferred_); } this.computingObject = { prism, model: prism.baseModel }; deferred = deferred_; var computeFinish = (debugStr, makeit) => { makeit || deferred.reject(interrupt ? '主动取消' : debugStr || ''); this.computingObject = null; deferred = null; interrupt = false; debugStr && console.log('computeFinish', debugStr); Potree.settings.displayMode = statesBefore.mode; Potree.settings.pointDensity = statesBefore.pointDensity; viewer.renderer.setRenderTarget(null); viewer.renderer.state.reset(); viewer.renderer.setScissorTest(false); gl.disable(gl.SCISSOR_TEST); viewer.screenshoting = false; viewer.mainViewport.active = true; viewer.mapViewer && (viewer.mapViewer.viewports[0].active = true); viewer.magnifier.viewport.active = true; viewer.pauseTestMaxLevel = false; }; var pointcloud = viewer.scene.pointclouds[0]; var center = new Vector3(); var boundSize = new Vector3(); var bound; var gl = viewer.renderer.getContext(); var statesBefore = { mode: Potree.settings.displayMode, pointDensity: Potree.settings.pointDensity }; timestamp = Date.now(); if (!this.computingObject.model) { horizonZ = prism.horizonZ; zMin = prism.zMin; zMax = prism.zMax; bound = new Box3().copy(prism.prismBound); /* for(let i=0;i { return { inverse: box.matrixWorld.clone().invert(), box }; }); this.material.setClipBoxes(null, [], clipBoxes_out, [], [prism]); this.material.pointSizeType = 'FIXED'; //'ADAPTIVE' //node会自动根据的其level更改点大小 使用ADAPTIVE后会使baseModelMap整片是黑的,原因未知 this.material.uniforms.minSize.value = 0.1; this.material.uniforms.orthoMaxSize.value = 5; //px this.material.classification = pointcloud.material.classification; this.material.recomputeClassification(); this.material.shaderNeedsUpdate = true; pointcloud.updateMaterial(this.material, null, this.camera, viewer.renderer, this.viewport.resolution); this.material.size = 1; //this.getPointsize(pointcloud.maxLevel) //0.025 米 //视图缩小(截图面积变大)后点会自动缩小,但至少是1个像素大小 } viewer.renderer.state.buffers.depth.setTest(this.material.depthTest); viewer.renderer.state.buffers.depth.setMask(this.material.depthWrite); viewer.renderer.state.setBlending(NoBlending); //只需要设置不透明即可(使alpha不混合,后方不会影响前方的alpha,否则输出的a通道将没法用) var pixelCount = this.renderTarget.width * this.renderTarget.height; buffer1 = new Uint8Array(4 * pixelCount); viewer.renderer.setRenderTarget(this.renderTarget); var results = []; var boundSize_ = boundSize.clone(); boundSize_.x /= cW, boundSize_.y /= cH; //分批渲染:从左到右 从下到上 var _loop = async function _loop(i) { var _loop2 = async function _loop2(j) { var infos = []; var progressStart = (i * cH + j) / (cW * cH), progressEnd = (i * cH + j + 1) / (cW * cH); if (interrupt) { return { v: { v: computeFinish('23') } }; } Potree.settings.pointDensity = 'screenshot'; //恢复为nodeMaxLevel //最高处朝下看,找挖方的顶部 _this.view.pitch = -Math.PI / 2; var endPosition = new Vector3(center.x + (i - cW / 2 + 0.5) * boundSize_.x, center.y + (j - cH / 2 + 0.5) * boundSize_.y, center.z); _this.view.moveOrthoCamera(_this.viewport, { boundSize: boundSize_, endPosition }, 0); var endPercent = _this.computingObject.model ? 0.7 : 0.4; await _this.render({ i, j, index: 1, cW, cH, infos, /* maxLevels, */notifyArea: [[progressStart, progressEnd], [0, endPercent]], computeFinish }); if (interrupt) { return { v: { v: computeFinish('2123') } }; } if (!_this.computingObject.model) { //水平面朝下看,找填方 _this.view.position.z = horizonZ + _this.camera.near; await _this.render({ i, j, index: 2, cW, cH, infos, /* maxLevels, */notifyArea: [[progressStart, progressEnd], [0.4, 0.7]], computeFinish }); } //水平面朝上看,找挖方的底部 /* this.view.position.z = horizonZ + surfaceThick //排除地面(水平面)上的点 this.view.pitch = Math.PI / 2; await this.render({reverseRow:true,name:'第3张-'+i+'-'+j, infos, buffer,maxLevels }) */ //---土堆上有草地有厚度,还是去掉吧 var result = { index: { i, j }, allFills: [], fillVupper: 0, fillVlower: 0, Vupper: 0, Vlower: infos[1] ? infos[1].Vlower : infos[0].Vlower, // >= infos[0].Vlower 因能找到被上方遮挡住的凹槽 allDiffHeights: [], fillVupperCount: 0, fillVlowerCount: 0, infos }; var waitFill = []; waitFill.count = 0; var isNeighbor = (a, b) => { return Math.abs(a.u - b.u) <= 1 && Math.abs(a.v - b.v) <= 1; }; var isBelongToGroup = (group, item) => { if (item[0]) item = item[0]; var i = group.length; while (--i >= 0) { //从后往前 if (item.u - group[i].u > 1 && Math.abs(item.v - group[i].v) > 1) break; //距离超出,前面肯定不相邻了 if (isNeighbor(group[i], item)) { return true; } } }; //计算挖方(但是边缘附近垂直方向上很多点云,体积被削皮,最终得到的会比infos[0]少) var getValue = (u, v) => { //当到了左上边界是否需要向前几批的查找? if (infos[0].allHeights[u] && infos[0].allHeights[u][v] != void 0) return infos[0].allHeights[u][v]; return result.allFills[u] && result.allFills[u][v]; }; var hasValue = (u, v) => { //在边界内 return u >= 0 && u < infos[0].allHeights.length && v >= 0 && v < infos[0].allHeights[0].length; }; var getFill = (u, v) => { //使用周围的八个点的平均值补洞 var neighbours = [[-1, 0], [0, 1], [1, 0], [0, -1], [-1, -1], [1, -1], [-1, 1], [1, 1]]; //先左右右先上后下 var i = 0, c = 0, sum = 0; while (c < 4 && i < 8) { var x = neighbours[i][0] + u, y = neighbours[i][1] + v; if (hasValue(x, y)) { var neigh = getValue(x, y); if (neigh != void 0) { c++; sum += neigh; } else if (i >= 3) { //add 2024.5.27 if (c == 0) break; //节省时间,主要为了大片透明区域 } } i++; } if (c > 0) { sum /= c; result.allFills[u] || (result.allFills[u] = []); result.allFills[u][v] = sum; return sum; } }; var add = (v, fill, count) => { if (v > 0) { result.Vupper += v; fill && (result.fillVupper += v, result.fillVupperCount += count); } else { //fill的话才会有 fill && (result.fillVlower -= v, result.fillVlowerCount += count); } }; var compute = async (u, v) => { var top = infos[0].allHeights[u][v]; //let btm = infos[2].allHeights[u][v] var fill; if (top == void 0) { if (prism) { var x = endPosition.x - boundSize_.x / 2 + wDelta * (u + 0.5); var y = endPosition.y - boundSize_.y / 2 + wDelta * (v + 0.5); if (!math.isPointInArea(prism.points, null, { x, y })) { return; //出界 } } else { if (_this.getModelZByRes(u, v, cW, cH, i, j) == void 0) { return; //出界 } } fill = true; top = getFill(u, v); if (top == void 0) { //左侧边缘有缺口时会出现 if (waitFill.cancel || waitFill.count > 1000 && waitFill[waitFill.length - 1][waitFill[waitFill.length - 1].length - 1].u - waitFill[0][0].u > 4) { //跨度超过4列 waitFill.cancel = true; //丢弃,不加入补洞, 降低耗时 } else { Common.pushToGroupAuto([{ u, v }], waitFill, null, isBelongToGroup); //按邻近点分组 } waitFill.count++; //当数量达到几万以上会在这个地方花很长时间,不过很少出现这种情况 return; } } /* let diff = top-btm let useDiff if(btm != void 0 && diff > surfaceThick ){ useDiff = diff result.allDiffHeights.push(useDiff) }else{ useDiff = top //从顶部一直到水平 }*/ if (waitFill.length) { //补 之前没有值的邻居重新获取 if (interrupt) { return computeFinish('12312'); } if (waitFill.cancel) { //console.log('直接清空waitFill', waitFill.count, waitFill.map(list=>[list[0], list[list.length-1]])) waitFill.count = 0; waitFill.length = 0; waitFill.cancel = false; } else { ///* //Potree.settings.isTest && */ waitFill.count>1000 && console.log('waitFill.count', waitFill.count, 'groupLen', waitFill.length, waitFill[0][0], waitFill[0][waitFill[0].length-1]) waitFill.slice().forEach(group => { //每个组都看看是否跟它相邻 if (isBelongToGroup(group, { u, v })) { var index = waitFill.indexOf(group); waitFill.splice(index, 1); waitFill.count -= group.length; group.forEach(e => { result.allFills[e.u] || (result.allFills[e.u] = []); result.allFills[e.u][e.v] = top; //该组全部都使用该体积 }); var sum = top * group.length; add(sum, fill, group.length); } }); } } add(top, fill, 1); }; var lastNotifyTime = Date.now(); //从左到右,从下到上一列列扫描 var _loop3 = async function _loop3(_u) { for (var _v2 = 0; _v2 < _this.renderTarget.height; _v2++) { //数据是从图的下到上存储的 if (interrupt) { return { v: { v: { v: computeFinish('1121') } } }; } compute(_u, _v2); } await notify([[progressStart, progressEnd], [0.7, 1]], () => { return _u / _this.renderTarget.width; }, 'compute'); }, _ret3; for (var _u = 0; _u < _this.renderTarget.width; _u++) { _ret3 = await _loop3(_u); if (_ret3) return _ret3.v; } if (waitFill.length) { console.log('waitFill怎么还有??', waitFill); //如果是模型的话是有剩的可能,当它的周围刚好是模型的hole时,就被断开在孤立的组里了,如"回"字型,中间的口是有model但无点云处,外面的口是无model处。 } result.Vupper *= sDelta; result.fillVlower *= sDelta; result.fillVupper *= sDelta; result.Vlower += result.fillVlower; results.push(result); deferred && deferred.notify(progressEnd); }, _ret2; for (var j = 0; j < cH; j++) { _ret2 = await _loop2(j); if (_ret2) return _ret2.v; } }, _ret; for (var i = 0; i < cW; i++) { _ret = await _loop(i); if (_ret) return _ret.v; } var Vupper = 0, Vlower = 0, fillVlower = 0, fillVupper = 0; results.forEach(c => { Vupper += c.Vupper; Vlower += c.Vlower; fillVlower += c.fillVlower; fillVupper += c.fillVupper; }); computeDone({ highest, lowest, Vupper, Vlower }, deferred); computeFinish('finish', true); console.log({ Vupper, Vlower, oldVupper: Vupper - fillVupper, oldVlower: Vlower - fillVlower, highest, lowest, horizonZ, wDelta }, results, this.viewport.resolution, { cW, cH }, 'cost:', Date.now() - timestamp, 'pxPerMetric', pxPerMetric, 'boundSize', boundSize); //firefox用时是chrome两倍,edge和chrome差不多 } getModelZByRes(u, v, cW, cH, wIndex, hIndex) { //传入renderTarget2的像素index //如果两个map的尺寸不同 var x = Math.round(wIndex / cW + u / this.renderTarget.width * this.renderTarget2.width); var y = Math.round(hIndex / cH + v / this.renderTarget.height * this.renderTarget2.height); var z0 = modelZs[x][y]; return z0; //return modelZs[u][v] } async render() { var _this2 = this; var { i, j, index, cW, cH, reverseRow, infos, /* maxLevels, */notifyArea, computeFinish } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; this.view.applyToCamera(this.camera); Potree.updatePointClouds(viewer.scene.pointclouds, this.camera, this.viewport.resolution); var gl = viewer.renderer.getContext(); var screenshot = name => { //if(window.testScreen){ var dataUrl = Potree.Utils.renderTargetToDataUrl(this.renderTarget, this.renderTarget.width, this.renderTarget.height, viewer.renderer); Common.downloadFile(dataUrl, (name || 'screenshot') + '-' + timestamp + '.png'); //为什么图片上不是只有pickWindowSize区域有颜色?? //} }; var name = i + '-' + j + '-第' + index + '张'; console.log('开始渲染', name); var camera = this.camera; var viewport = this.viewport; return new Promise((resolve, reject) => { var done = async () => { gl.clearColor(0, 0, 0, 0); viewer.renderer.clear(true, true, true); //viewer.pRenderer.renderOctree(pointcloud, nodes, this.camera, this.renderTarget ,{material:this.material}); viewer.pRenderer.render(viewer.scene.scenePointCloud, this.camera, this.renderTarget, { material: this.material /* transparent:!this.computingObject.isPrism */ }); if (interrupt) { return reject(), computeFinish('re 23'); } Potree.settings.isTest && screenshot(name); gl.readPixels(0, 0, this.renderTarget.width, this.renderTarget.height, gl.RGBA, gl.UNSIGNED_BYTE, buffer1); //这句花费最多时间 pc:2-4, 即使只有1*1像素 notifyArea.push([progressEnd1, 1]); var Vupper = 0, Vlower = 0; var upperHeights = [], lowerHeights = [], allHeights = []; var _loop4 = async function _loop4(u) { var col = []; for (var v = 0; v < _this2.renderTarget.height; v++) { var _v = reverseRow ? _this2.renderTarget.height - v - 1 : v; var offset = u + _v * _this2.renderTarget.width; var rgb = buffer1.slice(4 * offset, 4 * offset + 3), a = buffer1[4 * offset + 3]; if (a == 0 /* rgb[0] == 0 && rgb[1] == 0 && rgb[2] == 0 */) { //无点 col.push(null); } else { var z = _this2.convertColorToHeight(rgb, zMin, zMax); var h = void 0; if (!_this2.computingObject.model) { h = z - horizonZ; } else { //和baseModel标准面之间的高度差 /* if(a == 128){//负数 h = -h } ///如果这个也要lowest 那需改shader ,shader不计算高度差 */ var z0 = _this2.getModelZByRes(u, v, cW, cH, i, j); h = z - z0; } z < lowest && (lowest = z); //上表面最低点 z > highest && (highest = z); //上表面最高点 if (h > 0) { Vupper += h; upperHeights.push(h); // } else { Vlower += -h; lowerHeights.push(h); } col.push(h); } if (interrupt) { return { v: (reject(), computeFinish('re 023')) }; } //notify(notifyArea, (u*this.renderTarget.height + v) /(this.renderTarget.width*this.renderTarget.height)) } allHeights.push(col); await notify(notifyArea, () => { return u / _this2.renderTarget.width; }, 'readPixels get'); }, _ret4; for (var u = 0; u < this.renderTarget.width; u++) { _ret4 = await _loop4(u); if (_ret4) return _ret4.v; } Vupper *= sDelta; Vlower *= sDelta; infos.push({ Vupper, Vlower, sDelta, upperHeights, lowerHeights, allHeights }); resolve(); }; //let finish , maxTime = 1e6 var progressEnd1 = math.linearClamp(this.camera.zoom, [1, 1000], [0.8, 0.2]); //放得越大,实际加载的点云相对越少,费时越少 var notifyArea_ = [...notifyArea, [0, progressEnd1]]; if (Potree.pointsLoading) { //如果有要加载的node var curProgress = 0, beginTime = Date.now(), unloadBefore, tryPreLoadTime = Math.round(math.linearClamp(buffer1.length / this.camera.zoom / this.camera.zoom, [50, 10000], [1000, 15000])); //console.log('tryPreLoadTime',tryPreLoadTime) var decreaseLevel = () => { //降点云level //暂时先都一起降1 var pointclouds = viewer.scene.pointclouds.filter(e => e.visibleNodes.length); console.log('准备decreaseLevel, numVisiblePoints', Potree.numVisiblePoints, '最小numVisiblePoints占比', 1 / pointclouds.length); pointclouds.forEach(e => { var percent = e.numVisiblePoints / Potree.numVisiblePoints; console.log('numVisiblePoints占总比', e.dataset_id, percent); if (percent < 1 / pointclouds.length) return; var old = e.maxLevel; var levels = e.visibleNodes.map(e => e.getLevel()); var actMaxLevel = Math.max.apply(null, levels); //实际加载到的最高的node level e.maxLevel = actMaxLevel - 1; console.warn(e.dataset_id, 'decreaseLevel,新maxLevel', actMaxLevel - 1, '原maxlevel', old); //this.material.size = this.getPointsize(e.maxLevel) //this.material.size *= 2 }); }; var finish = makeit => { //viewer.removeEventListener('overPointBudget',decreaseLevel) makeit && done(); viewer.removeEventListener('update', update); viewer.removeEventListener('pointsLoaded', loaded); }; var update = () => { Potree.updatePointClouds(viewer.scene.pointclouds, camera, viewport.resolution); /* if( Potree.numVisiblePoints > maxPointBudge * 0.9){ decreaseLevel() */ notify(notifyArea_, () => { /* console.log('unloadedGeometry',Potree.unloadedGeometry.length) return curProgress */ /* curProgress = THREE.Math.clamp(Potree.numVisiblePoints/predictPointCount,curProgress,1) //如果decreaseLevel了点会减少,也不管它,就停住吧,反正很快就加载好了 return curProgress */ if (!unloadBefore && Date.now() - beginTime < tryPreLoadTime) { curProgress = (Date.now() - beginTime) / tryPreLoadTime * 0.5; } else { if (!unloadBefore) { unloadBefore = Potree.unloadedGeometry.length; //console.log('unloadBefore', unloadBefore) } unloadBefore = Math.max(Potree.unloadedGeometry.length, unloadBefore); //unloadedGeometry 刚开始可能越涨越多 - - 所以进度条会卡住 var curProgress_ = 0.5 + 0.5 * (1 - Potree.unloadedGeometry.length / unloadBefore); curProgress = Math.max(curProgress, curProgress_); } //console.log('curProgress ', curProgress, 'numVisiblePoints', Potree.numVisiblePoints, 'unloadedGeometry',Potree.unloadedGeometry.length) return curProgress; }, 'loadpoints'); interrupt && (finish(false), reject(), computeFinish('正在loadPoints,unloadedGeometry个数' + Potree.unloadedGeometry.length)); //曾经遇到遇到bug 不发送pointsLoaded 一直update 一直有3个unloadedGeometry加载不了。。 是否为每个加载的node加个计时? }; viewer.addEventListener('update', update); var loaded = () => { //点云加载完时(不一定准确) console.warn('加载完毕', ' numVisiblePoints', Potree.numVisiblePoints); finish(true); }; viewer.addEventListener('pointsLoaded', loaded); /* let predictPointCount = Math.round(math.linearClamp(buffer.length, [1e5, maxWidth*maxWidth*4],[1e6, maxPointBudge ]))//最终要加载到的数目 */ /* let overTime = ()=>{ if(document.hidden){ return setTimeout(overTime, maxTime) } if(!finish)console.warn('超时, numVisiblePoints', Potree.numVisiblePoints) dealDone() } setTimeout(overTime, maxTime) */ } else { notify(notifyArea_, 1); done(); } }); } convertColorToHeight(color, zMin, zMax) { var percent = 0; var a = 1; for (var i = 0; i < 3; i++) { a = i == 2 ? a / 255 : a / 256; percent += a * color[i]; } var height = (zMax - zMin) * percent; return height + zMin; } getPointsize(maxLevel) { //尽量铺满 size单位是米,需要和点云缝隙同宽 return 0.01; /* adaptive:0.2 */ var s = /* this.material.spacing */100 / Math.pow(2, maxLevel - 1); //adaptive的话在shader中已经乘了spacing console.log('getPointsize', s, 'maxLevel', maxLevel); return s; //会不会直接返回1就好? //不能太小。假如gl_pointsize计算结果是0.1,那么显示就是1px;当level将级后,放大2倍为0.2,也还是1px,看起来就稀疏了。所以要保证这个数在最大level时gl_pointsize计算结果差不多是1px.(虽然我会在渲染大尺寸面积时降画布尺寸,但不能保证刚刚好,且因点云个数不可控不会降尺寸太狠) } download(prisms) { if (this.prisms.length == 0) { return null; } var visiPointclouds = viewer.scene.pointclouds.filter(e => Potree.Utils.getObjVisiByReason(e, 'datasetSelection')); visiPointclouds.sort((a, b) => { return a.dataset_id - b.dataset_id; }); //缓存需要固定排序好比较 var data = { transformation_matrix: visiPointclouds.map(cloud => { var data = { id: cloud.dataset_id, matrix: new Matrix4().elements, //参照downloadNoCrop,给默认值,表示没有最外层裁剪 visiMatrixes: prisms.map(prism => { return { matrix: prism.getTransformationMatrix(cloud).elements, //剪裁框 points: prism.points.map(p => { return { x: p.x, y: p.y }; }) }; }), modelMatrix: new Matrix4().copy(cloud.transformMatrix).transpose().elements }; return data; }), aabb: "b-12742000 -12742000 -12742000 12742000 12742000 12742000" //剪裁空间 }; return data; } //体积多边形棱柱,z需要变换到-0.5 ~ 0.5 } /* VolumeComputer.prototype.setClipBoxes = function(){ let lastPrisms = [] return function(){ let prismPolygons = this.prisms.filter(e=>!e.isNew && e.visible) let prismList = [], prismPoints = [], maxPointsCount if(prismPolygons.length){ let pointsCount = prismPolygons.pointsCount = prismPolygons.reduce((w,c)=>{return w+c.points.length},0) prismList = new Float32Array(9 * prismPolygons.length); prismPoints = new Float32Array(2 * pointsCount); prismPolygons.maxPointsCount = 0//单个prism最大点个数 if(!this.entered)this.enter() let pointIndex = 0 for(let i=0;ie.material).concat([this.material]) materials.forEach(e=>{ e.uniforms.prismList.value = prismList e.uniforms.prismPoints.value = prismPoints e.shaderNeedsUpdate = e.shaderNeedsUpdate || doUpdate e.prisms = prismPolygons }) //修改obj材质 this.material.defines.num_prism = this.material.prisms.length//土方量数 this.material.defines.prismPointCountSum = this.material.prisms.pointsCount //点总个数 this.material.defines.prism_maxPointsCount = this.material.prisms.maxPointsCount //单个prism最大点个数 if(doUpdate){ this.material.needsUpdate = true viewer.dispatchEvent('content_changed') } lastPrisms = prismPolygons } }(); */ /* 渲染像素pxPerMetric越高,边缘越细腻、准确; 点size越小,越不容易遮盖住下方点云,造成体积偏大。但会不会有底部点云透出来? 该版本计算用到两张截图,第一张为整体的俯视图,包括挖方和填方;第二张仅包含填方。 缺陷:在补洞时,只利用第一张图的结果,所以整体的挖方会偏多,填方偏少(因为在挖方填方同时存在时,没有分别补挖方和填方,而是放在一起,而上方可能遮盖下方的) 尝试过第一张只绘制挖方部分,但是在遍历时就需要多遍历一次,测得的用时更多一些,结果却没变化 也尝试过补洞时挖方填方分别补各自的,但这样要考虑更多的东西,用时多了两倍以上。(因为目前规定无论范围内实际有没有点云都补上,非挖即填;如果分开的话,填方边缘也都补上肯定是错的,无法找到挖和填的界限,无法分清是只有挖还是填还是两者均有。如果要探测周围点,耗时很多) 如果数据集修改了,土方量需要手动重算。所以场景刷新后显示的体积有可能是错的。 之前记的,太麻烦了,延期处理: 1 一般情况:我需要记录每个土方量范围内存在的数据集的位置,如 {datasetId:"1745733728954093568", location:[113.59550104511611, 22.36677932324081, 0] ,orientation: 0.1} 如果刷新后土方量范围内存在的数据集发生改变,将重算。 数据集也可能显示或隐藏 2 其他特殊情况,如裁剪,难以知道裁剪了哪块,所以只能全部重算 ------------------ baseModel 基于模型的挖方填方 由于模型高度不一致,只能把相机放最高处朝下看,而无法像prism那样在horizonZ处再渲染一张,所以更加不能有多层点云干扰。 如模型在一个房间屋顶上方,那么填方会得到两个高度,屋顶和地板的高度,地板是从屋顶的点云缝隙而得。 如果模型放房间中间,并不能按理想的那样得到其上的挖方和其下的填方,因为相机朝下看时屋顶会遮住屋底,导致填方减少挖方增多。虽然能在bound底部朝上再拍一张,但若是有更复杂的情况依旧不能保证正确。 故需要设置好zMin zMax 如果模型有可能很大,但数据集不大,可以将bound只取交集 */ var texLoader$d = new TextureLoader(); var circleGeo = new CircleGeometry(1.45, 100); var sphereGeo$1 = new SphereBufferGeometry(0.008, 8, 8); var magDisMin = 1; //相机离目标位置的距离的分界线,当离得远时要缩小fov以使看到的视野固定(望远镜效果) var magDisMax = 20; /* const radius_ = 0.2; //当相机离目标位置的距离>magDistance_时,希望看到的视野的半径 const maxFov = THREE.Math.radToDeg(Math.atan(radius_ / magDisMin )) * 2//提前计算出当相机离目标位置的距离= 2 ? (window.screen.width * window.screen.height >= maxPX ? window.devicePixelRatio / 1.2 : window.devicePixelRatio / 1.5) * w$2 : w$2); //触屏或高分辨率的可能要放大些。但在手机上不能太大 //console.log('width2dPX', width2dPX) var orthoView = new ExtendView(); class Magnifier extends Object3D { //放大镜or望远镜 constructor(viewer) { super(); this.width = this.height = width2dPX /* * window.devicePixelRatio */; this.camera = new PerspectiveCamera(50, 1, 0.01, 10000); //fov aspect near far this.camera.up = new Vector3(0, 0, 1); this.viewport = new Viewport(null, this.camera, { left: 0, bottom: 0, width: 1, height: 1, name: 'magnifier', cameraLayers: ['magnifierContent'], pixelRatio: 1 }); this.viewport.setResolution(this.width, this.height, 0, 0); { var density; var sizeType; var colorType; var opacityBefore = new Map(); var sizeBefore = new Map(); var visiMap = new Map(); this.viewport.beforeRender = () => { viewer.scene.pointclouds.forEach(e => { //因为更改pointDensity时会自动变opacity,所以这项最先获取 visiMap.set(e, e.visible); e.visible = Potree.Utils.getObjVisiByReason(e, 'datasetSelection'); //先将隐藏的点云显示 opacityBefore.set(e, e.temp.pointOpacity); sizeBefore.set(e, e.temp.pointSize); }); //使放大镜里的pointDensity是'magnifier' 最高质量。 density = Potree.settings.pointDensity; Potree.settings.pointDensity = 'magnifier'; viewer.scene.pointclouds.forEach(e => { //因为全景模式的pointSizeType是fixed所以要还原下 sizeType = e.material.pointSizeType; e.material.pointSizeType = Potree.config.material.pointSizeType; //材质 colorType = e.material.activeAttributeName; e.material.activeAttributeName = 'rgba'; e.changePointOpacity(1); //e.changePointSize(Potree.config.material.realPointSize, true) }); }; this.viewport.afterRender = () => { Potree.settings.pointDensity = density; viewer.scene.pointclouds.forEach(e => { e.visible = visiMap.get(e); e.material.pointSizeType = sizeType; e.material.activeAttributeName = colorType; e.changePointOpacity(opacityBefore.get(e)); //e.changePointSize(sizeBefore.get(e)) }); }; } this.renderTarget = new WebGLRenderTarget(this.width, this.height, { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat /* type: THREE.FloatType, minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, */ }); this.rtEDL = new WebGLRenderTarget(this.width, this.height, { //好像没用到? 因为这里不绘制测量线 minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat, type: FloatType, depthTexture: new DepthTexture(undefined, undefined, UnsignedIntType) }); this.mesh = new Mesh(circleGeo, new MeshBasicMaterial({ side: DoubleSide, map: this.renderTarget.texture, transparent: true, depthTest: !1 //depthWrite: !1, })); this.overlayMesh = new Mesh(circleGeo, new MeshBasicMaterial({ side: DoubleSide, map: texLoader$d.load(Potree.resourcePath + '/textures/crosshair.png'), transparent: true, depthTest: !1 //depthWrite: !1, })); this.targetPoint = new Object3D(); this.targetPoint.add(new Mesh(sphereGeo$1, new MeshBasicMaterial({ color: "#ff0000", transparent: true, opacity: 0.7 }))); this.targetPoint.add(new Mesh(sphereGeo$1, new MeshBasicMaterial({ color: "#ff0000", transparent: true, opacity: 0.3, depthTest: false //被遮挡层 }))); this.targetPoint.name = 'magnifierPointTarget'; viewer.scene.scene.add(this.targetPoint); Potree.Utils.setObjectLayers(this.targetPoint, 'magnifierContent'); this.add(this.mesh); this.add(this.overlayMesh); this.position.set(-1000, -1000, -100000); //令它看不见 this.mesh.renderOrder = Potree.config.renderOrders.magnifier; this.overlayMesh.renderOrder = Potree.config.renderOrders.magnifier + 1; this.aimPos; Potree.Utils.setObjectLayers(this, 'magnifier'); //viewer.inputHandler.addInputListener(this) viewer.addEventListener('camera_changed', e => { // 平移、滚轮时更新 if (e.viewport == viewer.mainViewport) this.update(); //不过intersectPoint没更新 }); this.mesh.layers.set(Potree.config.renderLayers.magnifier); this.overlayMesh.layers.set(Potree.config.renderLayers.magnifier); //this.layers.set(Potree.config.renderLayers.magnifier);//这句在外层写没用 this.dontRender = false; viewer.addEventListener('global_drag', e => { //拖拽时不渲染。主要是右键平移时渲染延迟了,会闪烁。 this.dontRender = true; }); viewer.addEventListener('global_drop', e => { this.dontRender = false; }); viewer.addEventListener('global_mouseup', e => { //测量时拖拽场景再mouseup this.dontRender = false; }); var updateVisi = e => { if (e.hoverViewport == viewer.mainViewport) { Potree.Utils.updateVisible(this, "atViewport", true); this.update(e.intersect && e.intersect.location); } else { Potree.Utils.updateVisible(this, "atViewport", false); //小地图不显示 } }; viewer.addEventListener('global_mousemove', updateVisi); viewer.addEventListener('global_touchstart', updateVisi); viewer.addEventListener('updateMagnifier', updateVisi); /* viewer.addEventListener("beginSplitView",()=>{ this.updateVisible("splitView", false) }) viewer.addEventListener("finishSplitView",()=>{ this.updateVisible("splitView", true) }) */ this.addEventListener("setEnable", e => { Potree.Utils.updateVisible(this, "enable", e.value); //界面开关 /* if(Potree.settings.displayMode == 'showPanos') && e.value){ Potree.settings.pointDensity = 'magnifier' }else if() */ viewer.dispatchEvent('content_changed'); }); if (Potree.settings.isOfficial) { Potree.Utils.updateVisible(this, "enable", false); } else { Potree.Utils.updateVisible(this, "measure", false); viewer.addEventListener("measureMovePoint", () => {//测量开始 //Potree.Utils.updateVisible(this, "measure", true) }); viewer.addEventListener("endMeasureMove", () => { Potree.Utils.updateVisible(this, "measure", false); viewer.dispatchEvent('content_changed'); }); } this.addEventListener('isVisible', e => { if (!this.visible) Potree.settings.pointDensity = Potree.settings.pointDensity; //恢复pointBudget }); viewer.scene.view.addEventListener('flyingDone', () => { if (!this.visible) return; var pickWindowSize = 100; var intersect = viewer.inputHandler.getIntersect({ viewport: viewer.mainViewport, usePointcloud: true, pickWindowSize }); this.update(intersect && intersect.location); }); } //注意:在鼠标没有移动的时候,无法获取到最新的intersect, 放大镜内的内容可能是错误的。全景模式下更奇怪,原因未知 update(aimPos) { //相机靠近 navvis的做法 var dontRender = this.dontRender || !(aimPos instanceof Vector3) || Potree.settings.displayMode == 'showPanos' && viewer.images360.flying; aimPos = aimPos instanceof Vector3 ? aimPos : this.aimPos; if (!aimPos || !this.visible) return; var playerCamera = viewer.scene.getActiveCamera(); var playerPos = playerCamera.position; //viewer.scene.view.getPivot() var dis = playerPos.distanceTo(aimPos); var dirToCamera = new Vector3().subVectors(playerPos, aimPos).normalize(); var fareast = 300; //相机位置 if (playerCamera.type == 'OrthographicCamera') { var finalDisToAim = 2; } else { var finalDisToAim = dis > magDisMin ? dis > fareast ? magDisMax : (dis - magDisMin) / (fareast - magDisMin) * (magDisMax - magDisMin) + magDisMin : dis / 2; //dis>magDistance_ ? magDistance_ : dis / 2; } this.camera.fov = playerCamera.type == 'OrthographicCamera' ? 30 : playerCamera.fov / 2; this.camera.updateProjectionMatrix(); if (playerCamera.type == 'OrthographicCamera') { orthoView.position.copy(aimPos).sub(viewer.mainViewport.view.direction.multiplyScalar(finalDisToAim)); orthoView.yaw = viewer.mainViewport.view.yaw; orthoView.pitch = viewer.mainViewport.view.pitch; orthoView.applyToCamera(this.camera); } else { this.camera.position.copy(aimPos).add(dirToCamera.multiplyScalar(finalDisToAim)); this.camera.lookAt(aimPos); } //自身位置 //let pos2d = viewer.inputHandler.pointer.clone(); //跟随鼠标 var pos2d_ = Potree.Utils.getPos2d(aimPos, viewer.mainViewport, viewer.renderArea); //更新目标点的实时二维位置 var pos2d = pos2d_.vector; var margin = width2dPX * 1.1 / viewer.mainViewport.resolution2.y * 2; //确保到鼠标的间距占放大镜的比例不变(检查mobile、上下分屏后的变化) var screenPos = pos2d.clone().setY(pos2d.y + (pos2d.y > 0 ? -margin : margin)); var newPos = new Vector3(screenPos.x, screenPos.y, 0.8).unproject(playerCamera); //z:-1朝外 if (playerCamera.type != 'OrthographicCamera') { var dir = newPos.clone().sub(playerPos).normalize().multiplyScalar(10); //这个数值要大于playerCamera.near this.position.copy(playerPos.clone().add(dir)); } else { viewer.navCubeViewer.splitScreen.setShiftTarget(viewer.mainViewport, viewer.bound.center); viewer.mainViewport.targetPlane.setFromNormalAndCoplanarPoint(viewer.mainViewport.view.direction.clone(), viewer.bound.center); viewer.mainViewport.targetPlane.projectPoint(newPos, viewer.mainViewport.shiftTarget); this.position.copy(viewer.mainViewport.shiftTarget.clone()); //this.position.copy(playerPos.clone().add(dir)) } var s = finalDisToAim * this.camera.fov / 30; this.quaternion.copy(playerCamera.quaternion); this.targetPoint.position.copy(aimPos); this.targetPoint.scale.set(s, s, s); this.aimPos = aimPos; var scale = math.getScaleForConstantSize({ // width2d: width2dPX, camera: viewer.scene.getActiveCamera(), position: this.getWorldPosition(new Vector3()), resolution: viewer.mainViewport.resolution2 }); this.scale.set(scale, scale, scale); if (!dontRender) { this.waitRender = true; } viewer.dispatchEvent('content_changed'); } /* update(aimPos){ //仅改fov的版本 aimPos = aimPos instanceof THREE.Vector3 ? aimPos : this.aimPos if(!aimPos || !this.visible)return //相机位置 var playerCamera = viewer.scene.getActiveCamera() var playerPos = playerCamera.position;//viewer.scene.view.getPivot() var dis = playerPos.distanceTo(aimPos); if(dismaxY ? -margin : margin )) let newPos = new THREE.Vector3(screenPos.x,screenPos.y,0.8).unproject(playerCamera); //z:-1朝外 let dir = newPos.clone().sub(playerPos).normalize().multiplyScalar(10);//这个数值要大于playerCamera.near this.position.copy(playerPos.clone().add(dir)) this.aimPos = aimPos this.targetPoint.position.copy(aimPos); var scale = math.getScaleForConstantSize({// width2d : width2dPX, camera:viewer.scene.getActiveCamera(), position: this.getWorldPosition(new THREE.Vector3()), resolution: viewer.mainViewport.resolution2 }) this.scale.set(scale, scale, scale); if(!this.dontRender){ this.waitRender = true } }//位置需要计算,不仅仅是点云,所以需要深度图 */ render() { if (!this.visible || !this.waitRender && !viewer.needRender) return; //viewer.needRender为true要渲染是因为可能是点云node加载完 viewer.render({ target: this.renderTarget, viewports: [this.viewport], camera: this.camera, magnifier: true, rtEDL: this.rtEDL /* width :this.renderTarget.width, height: this.renderTarget.height, */ }); this.waitRender = false; viewer.dispatchEvent('content_changed'); } } /* 如果遇到放大镜内点云很不正常,应该是深度图错误(可能全景和点云没匹配上)。 */ var texLoader$e = new TextureLoader(); var defaultOpacity = 0.6; var Buttons$2 = Potree.defines.Buttons; //鼠标指示小圆片 class Reticule extends Mesh { constructor(viewer) { var defaultTex = texLoader$e.load(Potree.resourcePath + '/textures/whiteCircle.png' /* reticule-256x256.png' */); super(new PlaneBufferGeometry(0.11, 0.11, 1, 1), new MeshBasicMaterial({ side: DoubleSide, map: defaultTex, transparent: true, depthTest: !1, opacity: defaultOpacity //depthWrite: !1, })); this.name = 'reticule'; this.defaultTex = defaultTex; this.crosshairTex = texLoader$e.load(Potree.resourcePath + '/textures/reticule_cross_hair.png'); this.forbitTex = texLoader$e.load(Potree.resourcePath + '/textures/pic-forbid.png'); this.defaultTex.anisotropy = 4; this.crosshairTex.anisotropy = 4; this.forbitTex.anisotropy = 4; //this.layers.set(0/* RenderLayers.RETICULE */); this.renderOrder = Potree.config.renderOrders.reticule; this.layers.set(Potree.config.renderLayers.marker); this.direction = new Vector3(); this.mouseLastMoveTime = Date.now(); this.hoverViewport; this.matrixMap = new Map(); this.matrixAutoUpdate = false; this.hide(0); //viewer.inputHandler.addInputListener(this); Potree.settings.intersectWhenHover && viewer.addEventListener('global_mousemove', this.move.bind(this)); //viewer.addEventListener('global_click',this.move.bind(this)) viewer.addEventListener('global_mousedown', this.move.bind(this)); //主要针对触屏 this.state = {}; var startCrossStyle = () => { this.state.cross = true; this.judgeTex(); }; var endCrossStyle = () => { this.state.cross = false; this.judgeTex(); }; viewer.addEventListener('measureMovePoint', startCrossStyle); viewer.addEventListener('endMeasureMove', endCrossStyle); viewer.addEventListener('startBuildEntity', startCrossStyle); viewer.addEventListener('endBuildEntity', endCrossStyle); viewer.addEventListener('start_inserting_tag', startCrossStyle); viewer.addEventListener('endTagMove', endCrossStyle); viewer.addEventListener('reticule_forbit', e => { if (this.state.forbit != e.v) { console.log('change forbit ', e.v); } this.state.forbit = e.v; this.judgeTex(); }); Potree.Utils.setObjectLayers(this, 'sceneObjects'); } judgeTex() { if (this.state.forbit) { this.material.map = this.forbitTex; } else if (this.state.cross) { this.material.map = this.crosshairTex; } else { this.material.map = this.defaultTex; } viewer.mapViewer && viewer.mapViewer.dispatchEvent({ type: 'content_changed' }); } move(e) { if (e.type == "global_mousemove" && (e.isTouch || e.buttons != Buttons$2.NONE) && !this.state.cross) { return; //按下时不更新,除非拖拽测量 } this.mouseLastMoveTime = Date.now(); this.updatePosition(e.intersect, e.hoverViewport); } hide() { var duration = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 500; if (this.hidden) return; this.hidden = !0; transitions$1.start(lerp.property(this.material, "opacity", 0, () => { //progress this.dispatchEvent({ type: 'update' }); //viewer.dispatchEvent('content_changed') }), duration, () => { //done this.dispatchEvent({ type: 'update', visible: false }); }); this.dispatchEvent({ type: 'update', visible: false }); setTimeout(() => {}, duration); } show() { var duration = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 300; if (!Potree.Utils.getObjVisiByReason(this, 'force')) return; //console.log("show Reticule") this.hidden = !1; if (this.material.opacity <= 0) { transitions$1.start(lerp.property(this.material, "opacity", defaultOpacity, () => { //progress this.dispatchEvent({ type: 'update' }); //viewer.dispatchEvent('content_changed') }), duration, () => { //done this.dispatchEvent({ type: 'update', visible: false }); }); this.dispatchEvent({ type: 'update', visible: true }); } } //鼠标静止一段时间它就会消失 updateVisible() { Date.now() - this.mouseLastMoveTime > 1500 && !this.hidden && this.hide(); } updateScale(viewport) { var s, camera = viewport.camera; if (camera.type == "OrthographicCamera") { var sizeInfo = this.state.cross ? { width2d: 500 } : { minSize: 100, maxSize: 400, nearBound: 100, farBound: 700 }; s = math.getScaleForConstantSize($.extend(sizeInfo, { position: this.position, camera, resolution: viewport.resolution /* 2 */ })); } else { var n = camera.position.distanceTo(this.position); s = 0.8 * Math.log2(n + 1); //底数为2 ( Math.log()底数为e ) if (this.state.cross) { //测量时更精细些 s /= viewer.images360.zoomLevel; } } this.scale.set(s, s, s); } updateAtViewports(viewport) { //当多个viewports时更新。更新大小等 if (viewport.name == 'magnifier') return; if (this.orthoPos && this.hoverViewport && this.hoverViewport.name == 'mapViewport' && viewport != this.hoverViewport) { //若是在地图上更新,在其他viewport要隐藏。因为在地图上无法得知高度。 Potree.Utils.updateVisible(this, 'hoverMap', false); return; } Potree.Utils.updateVisible(this, 'hoverMap', true); if (viewport.name == 'mapViewport') { Potree.Utils.setObjectLayers(this, "bothMapAndScene"); } else { //通常地图不显示reticule,只有在特殊编辑时才显示 Potree.Utils.setObjectLayers(this, 'sceneObjects'); } var matrix = this.matrixMap.get(viewport); if (!matrix) { this.updateScale(viewport); this.updateMatrix(); //this.updateMatrixWorld() this.matrixMap.set(viewport, this.matrix.clone()); } else { this.matrix.copy(matrix); //this.updateMatrixWorld() } } updatePosition(intersect, viewport) { //在地图(当地图融合到viewer时)和场景里都显示且完全相同(大小可能不同) if (Potree.Utils.getObjVisiByReason(this, 'force')) { //没有被强制隐藏,如进入某个页面后强制不显示 if (!intersect /* || !intersect.point.normal */) { return; //this.hide(); } var atMap = !intersect.location; var location = intersect.location || intersect.orthoIntersect.clone(); var normal; this.orthoPos = atMap; //地图上要瞬间变化 , 因为要使needRender为true很麻烦 this.show(atMap ? 0 : 300); if (atMap) { normal = new Vector3(0, 0, 1); //地图无normal location.setZ(0); //低于相机高度即可 this.direction = normal.clone(); } else { /* if(intersect.point){ if(intersect.pointcloud){ normal = new THREE.Vector3().fromArray(intersect.point.normal ).applyMatrix4( intersect.pointcloud.rotateMatrix ); }else{//mesh normal = new THREE.Vector3().copy(intersect.point.normal).applyQuaternion(intersect.object.quaternion) } }else{ normal = intersect.normal //when showPanos } */ normal = intersect.normal; if (normal) { var ratio = /* Potree.settings.useDepthTex ? 1 : */0.2; this.direction = this.direction.multiplyScalar(1 - ratio); this.direction.add(normal.clone().multiplyScalar(ratio)); } //this.direction = normal.clone() //改为瞬间变化,否则刚hover上某个点时看起来不太对 } this.position.copy(location); /* .add(normal.clone().multiplyScalar(.01)); */ this.updateMatrix(); //lookAt之前要保证得到matrix this.lookAt(this.position.clone().add(this.direction)); this.hoverViewport = viewport; //记录下最近一次hover过的viewport this.updateScale(viewport); { //存储matrix,节省计算 this.updateMatrix(); //this.updateMatrixWorld() this.matrixMap.clear(); //重新计算 this.matrixMap.set(viewport, this.matrix.clone()); //别处会updateMatrixWorld } this.dispatchEvent({ type: 'update' }); //为什么navvis在校准数据集时每个viewport里reticule的朝向都刚好垂直于屏幕,似乎限定在了一定范围内,还是在pick时就只pick范围内的点? } } //navvis在地图等地方看reticule是有厚度的 /* updateMatrixWorld(force){ console.log('updateMatrixWorld', force) super.updateMatrixWorld(force) } */ } /** * * Supersample Anti-Aliasing Render Pass * * @author bhouston / http://clara.io/ * * This manual approach to SSAA re-renders the scene ones for each sample with camera jitter and accumulates the results. * * References: https://en.wikipedia.org/wiki/Supersampling * */ //较为原始的一种抗锯齿 (超级采样抗锯齿) var SSAARenderPass = function SSAARenderPass(clearColor, clearAlpha) { Pass.call(this); //this.scene //= scene; //this.camera = camera; this.sampleLevel = 4; // specified as n, where the number of samples is 2^n, so sampleLevel = 4, is 2^4 samples, 16. this.unbiased = true; // as we need to clear the buffer in this pass, clearColor must be set to something, defaults to black. this.clearColor = clearColor !== undefined ? clearColor : 0x000000; this.clearAlpha = clearAlpha !== undefined ? clearAlpha : 0; this.renderUniforms = { bgTex: { value: null }, outlineTex: { value: null }, opacity: { value: 1 } }; this.renderMat = new ShaderMaterial({ uniforms: this.renderUniforms, vertexShader: CopyShader.vertexShader, /* fragmentShader: CopyShader.fragmentShader, */ fragmentShader: " \n uniform sampler2D bgTex; \n uniform sampler2D outlineTex; \n uniform float opacity;\n varying vec2 vUv;\n void main() {\n vec4 color1 = texture2D( bgTex, vUv );\n vec4 color2 = texture2D( outlineTex, vUv ); \n gl_FragColor = opacity * mix(color1, color2, color2.a) ;\n \n \n } \n ", premultipliedAlpha: true, blending: AdditiveBlending, depthTest: false, depthWrite: false, transparent: true }); this.renderMat2 = new ShaderMaterial({ uniforms: UniformsUtils.clone(CopyShader.uniforms), vertexShader: CopyShader.vertexShader, fragmentShader: "uniform float opacity; \n uniform sampler2D tDiffuse; \n varying vec2 vUv;\n\n void main() {\n \n vec4 texel = texture2D( tDiffuse, vUv ); \n \n if(texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0){\n discard;\n }else{\n gl_FragColor = opacity * texel;\n }\n } \n ", depthTest: false, depthWrite: false, transparent: true }); //////////////////// /* this.renderMat.blendSrc = THREE.OneFactor //即将写入缓冲区的颜色。 this.renderMat.blendDst = THREE.OneFactor //缓冲区已经存在的颜色 this.renderMat.blendEquation = THREE.AddEquation; this.renderMat.blendEquationAlpha = THREE.AddEquation; this.renderMat.blendDstAlpha = THREE.SrcAlphaFactor this.renderMat.blendSrcAlpha = THREE.SrcAlphaFactor */ this.camera2 = new OrthographicCamera(-1, 1, 1, -1, 0, 1); this.scene2 = new Scene(); this.quad2 = new Mesh(new PlaneBufferGeometry(2, 2), this.renderMat /* this.copyMaterial */); this.quad2.frustumCulled = false; // Avoid getting clipped this.scene2.add(this.quad2); this.copyPass = new ShaderPass(CopyShader); this.copyPass.renderToScreen = true; }; SSAARenderPass.prototype = Object.assign(Object.create(Pass.prototype), { constructor: SSAARenderPass, dispose: function dispose() { if (this.sampleRenderTarget) { this.sampleRenderTarget.dispose(); this.sampleRenderTarget = null; } }, setSize: function setSize(width, height) { if (this.sampleRenderTarget) this.sampleRenderTarget.setSize(width, height); this.childPass && this.childPass.setSize(width, height); }, addPass: function addPass(pass) { this.childPass = pass; }, render: function render(scene, camera, viewports, renderer, writeBuffer, readBuffer, maskActive, renderFun) { if (this.useCopy) { scene = this.copyPass.scene; camera = this.copyPass.camera; } if (!this.sampleRenderTarget) { this.sampleRenderTarget = new WebGLRenderTarget(readBuffer.width, readBuffer.height, { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat }); this.sampleRenderTarget.texture.name = "SSAARenderPass.sample"; } var jitterOffsets = SSAARenderPass.JitterVectors[Math.max(0, Math.min(this.sampleLevel, 5))]; var autoClear = renderer.autoClear; renderer.autoClear = false; var oldClearColor = renderer.getClearColor(new Color()).getHex(); var oldClearAlpha = renderer.getClearAlpha(); renderer.setClearColor(this.clearColor, this.clearAlpha); var baseSampleWeight = 1.0 / jitterOffsets.length; var roundingRange = 1 / 32; //this.copyUniforms[ "tDiffuse" ].value = this.sampleRenderTarget.texture; var oldTarget = renderer.getRenderTarget(); if (oldTarget) { if (oldTarget.scissorTest) { var width = oldTarget.scissor.w, height = oldTarget.scissor.z; } else { var width = oldTarget.width, height = oldTarget.height; } } else { var width = readBuffer.width, height = readBuffer.height; } // render the scene multiple times, each slightly jitter offset from the last and accumulate the results. var opa = 0; for (var i = 0; i < jitterOffsets.length; i++) { var jitterOffset = jitterOffsets[i]; if (camera.setViewOffset) { camera.setViewOffset(width, height, jitterOffset[0] * 0.0625, jitterOffset[1] * 0.0625, // 0.0625 = 1 / 16 width, height); } var sampleWeight = baseSampleWeight; if (this.unbiased) { //更柔和 var uniformCenteredDistribution = -0.5 + (i + 0.5) / jitterOffsets.length; sampleWeight += roundingRange * uniformCenteredDistribution; } renderer.setRenderTarget(this.sampleRenderTarget); renderer.clear(); if (this.useCopy) { this.copyPass.render(scene, camera, null, renderer, writeBuffer, readBuffer); } else { if (renderFun) { renderFun({ target: this.sampleRenderTarget }); } else { renderer.render(scene, camera); } } renderer.setRenderTarget(oldTarget); //--------------------- //获取outline tex var hasOutline = this.childPass && this.childPass.render(scene, camera, renderer, writeBuffer, readBuffer, null, renderFun); //合成到该材质 this.renderUniforms["bgTex"].value = this.sampleRenderTarget.texture; this.renderUniforms["outlineTex"].value = hasOutline ? readBuffer.texture : null; this.renderUniforms["opacity"].value = sampleWeight; /* console.log('sampleWeight', sampleWeight) opa += sampleWeight */ if (!this.renderToScreen) { renderer.setRenderTarget(writeBuffer); } if (i === 0) { renderer.setClearColor(0x000000, 0); //叠加前颜色必须0 renderer.clear(); } renderer.render(this.scene2, this.camera2); // , this.renderToScreen ? null : writeBuffer, ( i === 0 ) if (!this.renderToScreen) { renderer.setRenderTarget(oldTarget); } //if(i==2)break; } //console.log('sum:',opa) if (camera.clearViewOffset) camera.clearViewOffset(); //renderer.setRenderTarget(readBuffer) //renderer.setClearColor( 0x000000, 0 ); //renderer.clear() /* this.quad2.material = this.renderMat2 this.renderMat2.uniforms.tDiffuse.value = writeBuffer.texture; renderer.render( this.scene2, this.camera2); this.quad2.material = this.renderMat */ //renderer.setRenderTarget(oldTarget) renderer.autoClear = autoClear; renderer.setClearColor(oldClearColor, oldClearAlpha); /* 试了好几次,测量线的透明度还是还原不了。 clearAlpha十分影响结果。 因为绘制测量线需要背景透明。 或许可以先全部绘制完后,再 copyshader中 抗锯齿? 另外会有黑边。 */ } }); // These jitter vectors are specified in integers because it is easier. // I am assuming a [-8,8) integer grid, but it needs to be mapped onto [-0.5,0.5) // before being used, thus these integers need to be scaled by 1/16. // // Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396 SSAARenderPass.JitterVectors = [[[0, 0]], [[4, 4], [-4, -4]], [[-2, -6], [6, -2], [-6, 2], [2, 6]], [[1, -3], [-1, 3], [5, 1], [-3, -5], [-5, 5], [-7, -1], [3, 7], [7, -7]], [[1, 1], [-1, -3], [-3, 2], [4, -1], [-5, -2], [2, 5], [5, 3], [3, -5], [-2, 6], [0, -7], [-4, -6], [-6, 4], [-8, 0], [7, -4], [6, 7], [-7, -8]], [[-4, -7], [-7, -5], [-3, -5], [-5, -4], [-1, -4], [-2, -2], [-6, -1], [-4, 0], [-7, 1], [-1, 2], [-6, 3], [-3, 3], [-7, 6], [-3, 6], [-5, 7], [-1, 7], [5, -7], [1, -6], [6, -5], [4, -4], [2, -3], [7, -2], [1, -1], [4, -1], [2, 1], [6, 2], [0, 4], [4, 4], [2, 5], [7, 5], [5, 6], [3, 7]]]; class MaskPass extends Pass { constructor(scene, camera) { super(); this.scene = scene; this.camera = camera; this.clear = true; this.needsSwap = false; this.inverse = false; } render(renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */) { var context = renderer.getContext(); var state = renderer.state; // don't update color or depth state.buffers.color.setMask(false); state.buffers.depth.setMask(false); // lock buffers state.buffers.color.setLocked(true); state.buffers.depth.setLocked(true); // set up stencil var writeValue, clearValue; if (this.inverse) { writeValue = 0; clearValue = 1; } else { writeValue = 1; clearValue = 0; } state.buffers.stencil.setTest(true); state.buffers.stencil.setOp(context.REPLACE, context.REPLACE, context.REPLACE); state.buffers.stencil.setFunc(context.ALWAYS, writeValue, 0xffffffff); state.buffers.stencil.setClear(clearValue); state.buffers.stencil.setLocked(true); // draw into the stencil buffer renderer.setRenderTarget(readBuffer); if (this.clear) renderer.clear(); renderer.render(this.scene, this.camera); renderer.setRenderTarget(writeBuffer); if (this.clear) renderer.clear(); renderer.render(this.scene, this.camera); // unlock color and depth buffer for subsequent rendering state.buffers.color.setLocked(false); state.buffers.depth.setLocked(false); // only render where stencil is set to 1 state.buffers.stencil.setLocked(false); state.buffers.stencil.setFunc(context.EQUAL, 1, 0xffffffff); // draw if == 1 state.buffers.stencil.setOp(context.KEEP, context.KEEP, context.KEEP); state.buffers.stencil.setLocked(true); } } class ClearMaskPass extends Pass { constructor() { super(); this.needsSwap = false; } render(renderer /*, writeBuffer, readBuffer, deltaTime, maskActive */) { renderer.state.buffers.stencil.setLocked(false); renderer.state.buffers.stencil.setTest(false); } } /** * @author alteredq / http://alteredqualia.com/ */ var EffectComposer = function EffectComposer(renderer, renderTarget) { this.renderer = renderer; if (renderTarget === undefined) { var parameters = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat, stencilBuffer: false }; var size = renderer.getDrawingBufferSize(new Vector2()); renderTarget = new WebGLRenderTarget(size.width, size.height, parameters); renderTarget.texture.name = 'EffectComposer.rt1'; } this.renderTarget1 = renderTarget; this.renderTarget2 = renderTarget.clone(); this.renderTarget2.texture.name = 'EffectComposer.rt2'; this.writeBuffer = this.renderTarget1; this.readBuffer = this.renderTarget2; this.passes = []; // dependencies /* if ( THREE.CopyShader === undefined ) { console.error( 'THREE.EffectComposer relies on THREE.CopyShader' ); } if ( THREE.ShaderPass === undefined ) { console.error( 'THREE.EffectComposer relies on THREE.ShaderPass' ); } */ this.copyPass = new ShaderPass(CopyShader); viewer.addEventListener('resize', e => { //readTarget的话是渲染一整张的,暂时无法一个个viewport渲染所以不用 this.readTarget || this.setSize(e.viewport.resolution2.x, e.viewport.resolution2.y); //暂时假设composer渲染的viewer的viewports.length == 1 }); }; Object.assign(EffectComposer.prototype, { swapBuffers: function swapBuffers() { var tmp = this.readBuffer; this.readBuffer = this.writeBuffer; this.writeBuffer = tmp; }, addPass: function addPass(pass) { this.passes.push(pass); var size = this.renderer.getDrawingBufferSize(new Vector2()); pass.setSize(size.width, size.height); }, removePass: function removePass(pass) { //add var index = this.passes.indexOf(pass); index > -1 && this.passes.splice(index, 1); }, insertPass: function insertPass(pass, index) { this.passes.splice(index, 0, pass); }, render: function render(scene, camera, viewports, renderFun) { var maskActive = false; var passes = this.passes.filter(e => e.enabled); var pass, i, il = passes.length; var oldTarget = this.renderer.getRenderTarget(); if (this.readTarget && oldTarget) { //add 使用当前renderTarget中的像素 this.setSize(oldTarget.width, oldTarget.height); //所有viewports一起渲染,整个画面 因暂时没办法一个个copy oldTarget.viewport.set(0, 0, oldTarget.width, oldTarget.height); oldTarget.scissorTest = false; this.copyPass.render(scene, camera, viewports, this.renderer, this.readBuffer, oldTarget); } for (i = 0; i < il; i++) { pass = passes[i]; //if(i == il-1)pass.renderToScreen = true// pass.render(scene, camera, viewports, this.renderer, this.writeBuffer, this.readBuffer, maskActive, renderFun); if (pass.needsSwap) { if (maskActive) { var context = this.renderer.context; context.stencilFunc(context.NOTEQUAL, 1, 0xffffffff); this.copyPass.render(null, null, viewports, this.renderer, this.writeBuffer, this.readBuffer); // delta context.stencilFunc(context.EQUAL, 1, 0xffffffff); } this.swapBuffers(); } if (MaskPass !== undefined) { if (pass instanceof MaskPass) { maskActive = true; } else if (pass instanceof ClearMaskPass) { maskActive = false; } } } this.renderer.setRenderTarget(oldTarget); //add if (!pass.renderToScreen) { //最后一个如果没有绘制到屏幕or target上 this.copyPass.renderToScreen = true; this.copyPass.render(null, null, viewports, this.renderer, this.writeBuffer, this.readBuffer); } }, reset: function reset(renderTarget) { if (renderTarget === undefined) { var size = this.renderer.getDrawingBufferSize(new Vector2()); renderTarget = this.renderTarget1.clone(); renderTarget.setSize(size.width, size.height); } this.renderTarget1.dispose(); this.renderTarget2.dispose(); this.renderTarget1 = renderTarget; this.renderTarget2 = renderTarget.clone(); this.writeBuffer = this.renderTarget1; this.readBuffer = this.renderTarget2; }, setSize: function setSize(width, height, scaleRatio) { scaleRatio = scaleRatio || this.scaleRatio || 1; //console.log('setSize', width * scaleRatio, height * scaleRatio) var maxTexWidth = 4096; var w = width * scaleRatio; var h = height * scaleRatio; if (w > maxTexWidth || h > maxTexWidth) { //超出会崩溃 if (w > h) { scaleRatio = maxTexWidth / width; } else { scaleRatio = maxTexWidth / height; } } w = width * scaleRatio; h = height * scaleRatio; this.renderTarget1.setSize(w, h); this.renderTarget2.setSize(w, h); for (var i = 0; i < this.passes.length; i++) { this.passes[i].setSize(w, h); } } }); /** * @author alteredq / http://alteredqualia.com/ */ class RenderPass extends Pass { constructor(overrideMaterial, clearColor, clearAlpha) { super(); /* this.scene = scene; this.camera = camera; */ this.overrideMaterial = overrideMaterial; this.clearColor = clearColor; this.clearAlpha = clearAlpha !== undefined ? clearAlpha : 0; this.clear = true; this.clearDepth = false; this.needsSwap = false; this._oldClearColor = new Color(); } render(scene, camera, viewports, renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */) { var oldAutoClear = renderer.autoClear; renderer.autoClear = false; var oldClearAlpha, oldOverrideMaterial; if (this.overrideMaterial !== undefined) { oldOverrideMaterial = this.scene.overrideMaterial; scene.overrideMaterial = this.overrideMaterial; } if (this.clearColor) { renderer.getClearColor(this._oldClearColor); oldClearAlpha = renderer.getClearAlpha(); renderer.setClearColor(this.clearColor, this.clearAlpha); } if (this.clearDepth) { renderer.clearDepth(); } var oldTarget = renderer.getRenderTarget(); if (!this.renderToScreen) renderer.setRenderTarget(readBuffer); // TODO: Avoid using autoClear properties, see https://github.com/mrdoob/three.js/pull/15571#issuecomment-465669600 if (this.clear) renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil); renderer.render(scene, camera); if (!this.renderToScreen) renderer.setRenderTarget(oldTarget); if (this.clearColor) { renderer.setClearColor(this._oldClearColor, oldClearAlpha); } if (this.overrideMaterial !== undefined) { scene.overrideMaterial = oldOverrideMaterial; } renderer.setRenderTarget(oldTarget); renderer.autoClear = oldAutoClear; } } /** * NVIDIA FXAA by Timothy Lottes * https://developer.download.nvidia.com/assets/gamedev/files/sdk/11/FXAA_WhitePaper.pdf * - WebGL port by @supereggbert * http://www.glge.org/demos/fxaa/ * Further improved by Daniel Sturk */ var FXAAShader = { uniforms: { 'tDiffuse': { value: null }, 'resolution': { value: new Vector2(1 / 1024, 1 / 512) } }, vertexShader: /* glsl */"\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvUv = uv;\n\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t}", fragmentShader: "\n\tprecision highp float;\n\n\tuniform sampler2D tDiffuse;\n\n\tuniform vec2 resolution;\n\n\tvarying vec2 vUv;\n\n\t// FXAA 3.11 implementation by NVIDIA, ported to WebGL by Agost Biro (biro@archilogic.com)\n\n\t//----------------------------------------------------------------------------------\n\t// File: es3-keplerFXAAassetsshaders/FXAA_DefaultES.frag\n\t// SDK Version: v3.00\n\t// Email: gameworks@nvidia.com\n\t// Site: http://developer.nvidia.com/\n\t//\n\t// Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.\n\t//\n\t// Redistribution and use in source and binary forms, with or without\n\t// modification, are permitted provided that the following conditions\n\t// are met:\n\t// * Redistributions of source code must retain the above copyright\n\t// notice, this list of conditions and the following disclaimer.\n\t// * Redistributions in binary form must reproduce the above copyright\n\t// notice, this list of conditions and the following disclaimer in the\n\t// documentation and/or other materials provided with the distribution.\n\t// * Neither the name of NVIDIA CORPORATION nor the names of its\n\t// contributors may be used to endorse or promote products derived\n\t// from this software without specific prior written permission.\n\t//\n\t// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n\t// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\t// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\t// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\t// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\t// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\t// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\t// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n\t// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\t// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\t// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\t//\n\t//----------------------------------------------------------------------------------\n\n\t#ifndef FXAA_DISCARD\n\t\t\t//\n\t\t\t// Only valid for PC OpenGL currently.\n\t\t\t// Probably will not work when FXAA_GREEN_AS_LUMA = 1.\n\t\t\t//\n\t\t\t// 1 = Use discard on pixels which don't need AA.\n\t\t\t// For APIs which enable concurrent TEX+ROP from same surface.\n\t\t\t// 0 = Return unchanged color on pixels which don't need AA.\n\t\t\t//\n\t\t\t#define FXAA_DISCARD 0\n\t#endif\n\n\t/*--------------------------------------------------------------------------*/\n //\u7B2C\u4E09\u4E2A\u53C2\u6570\u52A0\u5165\u540E\u53EA\u80FD\u5728\u7247\u5143\u7740\u8272\u5668\u4E2D\u8C03\u7528\uFF0C\u4E14\u53EA\u5BF9\u91C7\u6837\u5668\u4E3Amipmap\u7C7B\u578B\u7EB9\u7406\u65F6\u6709\u6548\u3002\u4E0D\u660E\u767D\u4F5C\u7528\uFF1F\uFF1F\uFF1F \u4F46\u8B66\u544A\u8BF4\u8303\u56F4\u572816\u4E4B\u5185\n\t#define FxaaTexTop(t, p) texture2D(t, p, -15.0); //-100.0); \n\t#define FxaaTexOff(t, p, o, r) texture2D(t, p + (o * r), -15.0); //-100.0)\n\t/*--------------------------------------------------------------------------*/\n\n\t#define NUM_SAMPLES 5\n\n\t// assumes colors have premultipliedAlpha, so that the calculated color contrast is scaled by alpha\n\tfloat contrast( vec4 a, vec4 b ) {\n\t\t\tvec4 diff = abs( a - b );\n\t\t\treturn max( max( max( diff.r, diff.g ), diff.b ), diff.a );\n\t}\n\n\t/*============================================================================\n\n\t\t\t\t\t\t\t\t\tFXAA3 QUALITY - PC\n\n\t============================================================================*/\n\n\t/*--------------------------------------------------------------------------*/\n\tvec4 FxaaPixelShader(\n\t\t\tvec2 posM,\n\t\t\tsampler2D tex,\n\t\t\tvec2 fxaaQualityRcpFrame,\n\t\t\tfloat fxaaQualityEdgeThreshold,\n\t\t\tfloat fxaaQualityinvEdgeThreshold\n\t) {\n\t\t\tvec4 rgbaM = FxaaTexTop(tex, posM);\n\t\t\tvec4 rgbaS = FxaaTexOff(tex, posM, vec2( 0.0, 1.0), fxaaQualityRcpFrame.xy);\n\t\t\tvec4 rgbaE = FxaaTexOff(tex, posM, vec2( 1.0, 0.0), fxaaQualityRcpFrame.xy);\n\t\t\tvec4 rgbaN = FxaaTexOff(tex, posM, vec2( 0.0,-1.0), fxaaQualityRcpFrame.xy);\n\t\t\tvec4 rgbaW = FxaaTexOff(tex, posM, vec2(-1.0, 0.0), fxaaQualityRcpFrame.xy);\n\t\t\t// . S .\n\t\t\t// W M E\n\t\t\t// . N .\n\n\t\t\tbool earlyExit = max( max( max(\n\t\t\t\t\tcontrast( rgbaM, rgbaN ),\n\t\t\t\t\tcontrast( rgbaM, rgbaS ) ),\n\t\t\t\t\tcontrast( rgbaM, rgbaE ) ),\n\t\t\t\t\tcontrast( rgbaM, rgbaW ) )\n\t\t\t\t\t< fxaaQualityEdgeThreshold;\n\t\t\t// . 0 .\n\t\t\t// 0 0 0\n\t\t\t// . 0 .\n\n\t\t\t#if (FXAA_DISCARD == 1)\n\t\t\t\t\tif(earlyExit) FxaaDiscard;\n\t\t\t#else\n\t\t\t\t\tif(earlyExit) return rgbaM;\n\t\t\t#endif\n\n\t\t\tfloat contrastN = contrast( rgbaM, rgbaN );\n\t\t\tfloat contrastS = contrast( rgbaM, rgbaS );\n\t\t\tfloat contrastE = contrast( rgbaM, rgbaE );\n\t\t\tfloat contrastW = contrast( rgbaM, rgbaW );\n\n\t\t\tfloat relativeVContrast = ( contrastN + contrastS ) - ( contrastE + contrastW );\n\t\t\trelativeVContrast *= fxaaQualityinvEdgeThreshold;\n\n\t\t\tbool horzSpan = relativeVContrast > 0.;\n\t\t\t// . 1 .\n\t\t\t// 0 0 0\n\t\t\t// . 1 .\n\n\t\t\t// 45 deg edge detection and corners of objects, aka V/H contrast is too similar\n\t\t\tif( abs( relativeVContrast ) < .3 ) {\n\t\t\t\t\t// locate the edge\n\t\t\t\t\tvec2 dirToEdge;\n\t\t\t\t\tdirToEdge.x = contrastE > contrastW ? 1. : -1.;\n\t\t\t\t\tdirToEdge.y = contrastS > contrastN ? 1. : -1.;\n\t\t\t\t\t// . 2 . . 1 .\n\t\t\t\t\t// 1 0 2 ~= 0 0 1\n\t\t\t\t\t// . 1 . . 0 .\n\n\t\t\t\t\t// tap 2 pixels and see which ones are \"outside\" the edge, to\n\t\t\t\t\t// determine if the edge is vertical or horizontal\n\n\t\t\t\t\tvec4 rgbaAlongH = FxaaTexOff(tex, posM, vec2( dirToEdge.x, -dirToEdge.y ), fxaaQualityRcpFrame.xy);\n\t\t\t\t\tfloat matchAlongH = contrast( rgbaM, rgbaAlongH );\n\t\t\t\t\t// . 1 .\n\t\t\t\t\t// 0 0 1\n\t\t\t\t\t// . 0 H\n\n\t\t\t\t\tvec4 rgbaAlongV = FxaaTexOff(tex, posM, vec2( -dirToEdge.x, dirToEdge.y ), fxaaQualityRcpFrame.xy);\n\t\t\t\t\tfloat matchAlongV = contrast( rgbaM, rgbaAlongV );\n\t\t\t\t\t// V 1 .\n\t\t\t\t\t// 0 0 1\n\t\t\t\t\t// . 0 .\n\n\t\t\t\t\trelativeVContrast = matchAlongV - matchAlongH;\n\t\t\t\t\trelativeVContrast *= fxaaQualityinvEdgeThreshold;\n\n\t\t\t\t\tif( abs( relativeVContrast ) < .3 ) { // 45 deg edge\n\t\t\t\t\t\t\t// 1 1 .\n\t\t\t\t\t\t\t// 0 0 1\n\t\t\t\t\t\t\t// . 0 1\n\n\t\t\t\t\t\t\t// do a simple blur\n\t\t\t\t\t\t\treturn mix(\n\t\t\t\t\t\t\t\t\trgbaM,\n\t\t\t\t\t\t\t\t\t(rgbaN + rgbaS + rgbaE + rgbaW) * .25,\n\t\t\t\t\t\t\t\t\t.4\n\t\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\thorzSpan = relativeVContrast > 0.;\n\t\t\t}\n\n\t\t\tif(!horzSpan) rgbaN = rgbaW;\n\t\t\tif(!horzSpan) rgbaS = rgbaE;\n\t\t\t// . 0 . 1\n\t\t\t// 1 0 1 -> 0\n\t\t\t// . 0 . 1\n\n\t\t\tbool pairN = contrast( rgbaM, rgbaN ) > contrast( rgbaM, rgbaS );\n\t\t\tif(!pairN) rgbaN = rgbaS;\n\n\t\t\tvec2 offNP;\n\t\t\toffNP.x = (!horzSpan) ? 0.0 : fxaaQualityRcpFrame.x;\n\t\t\toffNP.y = ( horzSpan) ? 0.0 : fxaaQualityRcpFrame.y;\n\n\t\t\tbool doneN = false;\n\t\t\tbool doneP = false;\n\n\t\t\tfloat nDist = 0.;\n\t\t\tfloat pDist = 0.;\n\n\t\t\tvec2 posN = posM;\n\t\t\tvec2 posP = posM;\n\n\t\t\tint iterationsUsed = 0;\n\t\t\tint iterationsUsedN = 0;\n\t\t\tint iterationsUsedP = 0;\n\t\t\tfor( int i = 0; i < NUM_SAMPLES; i++ ) {\n\t\t\t\t\titerationsUsed = i;\n\n\t\t\t\t\tfloat increment = float(i + 1);\n\n\t\t\t\t\tif(!doneN) {\n\t\t\t\t\t\t\tnDist += increment;\n\t\t\t\t\t\t\tposN = posM + offNP * nDist;\n\t\t\t\t\t\t\tvec4 rgbaEndN = FxaaTexTop(tex, posN.xy);\n\t\t\t\t\t\t\tdoneN = contrast( rgbaEndN, rgbaM ) > contrast( rgbaEndN, rgbaN );\n\t\t\t\t\t\t\titerationsUsedN = i;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(!doneP) {\n\t\t\t\t\t\t\tpDist += increment;\n\t\t\t\t\t\t\tposP = posM - offNP * pDist;\n\t\t\t\t\t\t\tvec4 rgbaEndP = FxaaTexTop(tex, posP.xy);\n\t\t\t\t\t\t\tdoneP = contrast( rgbaEndP, rgbaM ) > contrast( rgbaEndP, rgbaN );\n\t\t\t\t\t\t\titerationsUsedP = i;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(doneN || doneP) break;\n\t\t\t}\n\n\n\t\t\tif ( !doneP && !doneN ) return rgbaM; // failed to find end of edge\n\n\t\t\tfloat dist = min(\n\t\t\t\t\tdoneN ? float( iterationsUsedN ) / float( NUM_SAMPLES - 1 ) : 1.,\n\t\t\t\t\tdoneP ? float( iterationsUsedP ) / float( NUM_SAMPLES - 1 ) : 1.\n\t\t\t);\n\n\t\t\t// hacky way of reduces blurriness of mostly diagonal edges\n\t\t\t// but reduces AA quality\n\t\t\tdist = pow(dist, .5);\n\n\t\t\tdist = 1. - dist;\n\n\t\t\treturn mix(\n\t\t\t\t\trgbaM,\n\t\t\t\t\trgbaN,\n\t\t\t\t\tdist * .5\n\t\t\t);\n\t}\n\n\tvoid main() {\n\t\t\tconst float edgeDetectionQuality = 0.1 ;//.05 ; //\u8D8A\u9AD8\uFF0C\u8D8A\u4FDD\u7559\u7EC6\u8282\uFF1B\u8D8A\u4F4E\uFF0C\u8D8A\u5E73\u6ED1 \u4F46\u6A21\u7CCA \n\t\t\tconst float invEdgeDetectionQuality = 1. / edgeDetectionQuality;\n\n\t\t\tgl_FragColor = FxaaPixelShader(\n\t\t\t\t\tvUv,\n\t\t\t\t\ttDiffuse,\n\t\t\t\t\tresolution,\n\t\t\t\t\tedgeDetectionQuality, // [0,1] contrast needed, otherwise early discard\n\t\t\t\t\tinvEdgeDetectionQuality\n\t\t\t);\n //\u5355\u72EC\u6E32\u67D3\u6D4B\u91CF\u7EBF\u6709\u9ED1\u8FB9\uFF0C\u56E0\u4E3A\u900F\u660E\u533A\u57DF\u7684clearColor\u662F(0,0,0)\uFF0C\u6A21\u7CCA\u5316\u7684\u65F6\u5019\u91C7\u7528\u4E86\u8FD9\u4E9B\u9ED1\u8272\u56E0\u5B50\u6765\u6DF7\u8272\u3002\u56E0\u4E3A\u6D4B\u91CF\u7EBF\u989C\u8272\u53EF\u80FD\u591A\u79CD\uFF0C\u4E5F\u4E0D\u80FD\u76F4\u63A5\u4FEE\u6539clearColor\u4E3A\u5176\u989C\u8272\uFF0C\u4E14\u8FD8\u6709label\u3002\n //\u6545\u800C\u65E0\u6CD5\u5355\u72EC\u6E32\u67D3\u6D4B\u91CF\u7EBF\uFF0C\u800C\u9700\u8981\u5C06\u5E95\u56FE\u4E00\u8D77\u6E32\u67D3\u3002\n }\n\t" }; /** * @author spidersharma / http://eduperiment.com/ */ var OutlinePass = function OutlinePass(selectedObjects) { /* scene = scene; camera = camera; */ this.selectedObjects = selectedObjects !== undefined ? selectedObjects : []; this.visibleEdgeColor = new Color(1, 1, 1); this.hiddenEdgeColor = new Color(0.1, 0.04, 0.02); this.edgeGlow = 0.0; this.usePatternTexture = false; //this.edgeThickness = 1.0; this.edgeStrength = 50; this.downSampleRatio = 1; //2; // 抗锯齿 值越低renderTarget size越大,抗锯齿越强,线条可越细(或许可以把模糊化去掉?) this.pulsePeriod = 0; this.showHiddenPart = false; //是否判断被遮住的部分,以设置hiddenEdgeColor。一般不需要 Pass.call(this); this.resolution = new Vector2(256, 256); var pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat }; var resx = Math.round(this.resolution.x / this.downSampleRatio); var resy = Math.round(this.resolution.y / this.downSampleRatio); this.renderTargetMaskBuffer = new WebGLRenderTarget(this.resolution.x, this.resolution.y, pars); this.renderTargetMaskBuffer.texture.name = "OutlinePass.mask"; this.renderTargetMaskBuffer.texture.generateMipmaps = false; this.depthMaterial = new MeshDepthMaterial(); this.depthMaterial.side = DoubleSide; this.depthMaterial.depthPacking = RGBADepthPacking; this.depthMaterial.blending = NoBlending; this.prepareMaskMaterial = this.getPrepareMaskMaterial(); this.prepareMaskMaterial.side = DoubleSide; this.renderTargetDepthBuffer = new WebGLRenderTarget(this.resolution.x, this.resolution.y, pars); this.renderTargetDepthBuffer.texture.name = "OutlinePass.depth"; this.renderTargetDepthBuffer.texture.generateMipmaps = false; this.edgeDetectionMaterial = this.getEdgeDetectionMaterial(this.edgeStrength); this.renderTargetEdgeBuffer1 = new WebGLRenderTarget(resx, resy, pars); this.renderTargetEdgeBuffer1.texture.name = "OutlinePass.edge1"; this.renderTargetEdgeBuffer1.texture.generateMipmaps = false; // Overlay material this.overlayMaterial = this.getOverlayMaterial(); // copy material this.copyUniforms = UniformsUtils.clone(CopyShader.uniforms); this.copyUniforms["opacity"].value = 1.0; this.materialCopy = new ShaderMaterial({ uniforms: this.copyUniforms, vertexShader: CopyShader.vertexShader, fragmentShader: CopyShader.fragmentShader, blending: NoBlending, depthTest: false, depthWrite: false, transparent: true }); this.enabled = true; this.needsSwap = false; this.oldClearColor = new Color(); this.oldClearAlpha = 1; this.camera = new OrthographicCamera(-1, 1, 1, -1, 0, 1); this.scene = new Scene(); this.quad = new Mesh(new PlaneBufferGeometry(2, 2), null); this.quad.frustumCulled = false; // Avoid getting clipped this.scene.add(this.quad); this.textureMatrix = new Matrix4(); viewer.addEventListener('viewerResize', e => { var size = viewer.renderer.getSize(new Vector2()); this.renderTargetEdgeBuffer1.setSize(size.x, size.y); this.renderTargetMaskBuffer.setSize(size.x, size.y); this.resolution.set(size.x, size.y); }); }; OutlinePass.prototype = Object.assign(Object.create(Pass.prototype), { constructor: OutlinePass, dispose: function dispose() { this.renderTargetMaskBuffer.dispose(); this.renderTargetEdgeBuffer1.dispose(); this.renderTargetDepthBuffer.dispose(); }, replaceDepthToViewZ(camera) { var type = camera.isPerspectiveCamera ? 'perspective' : 'orthographic'; if (type == this.lastCameraType) return; this.lastCameraType = type; this.prepareMaskMaterial.fragmentShader = this.prepareMaskMaterial.fragmentShader.replace(/DEPTH_TO_VIEW_Z/g, type + 'DepthToViewZ'); this.prepareMaskMaterial.needsUpdate = true; }, setSize: function setSize(width, height) {}, changeVisibilityOfSelectedObjects: function changeVisibilityOfSelectedObjects(bVisible) { function gatherSelectedMeshesCallBack(object) { /* if ( object.isMesh ) { */ if (object.isPointcloud || object.isMesh || object.isLine || object.isSprite) { /* if ( bVisible ) { object.visible = object.userData.oldVisible; delete object.userData.oldVisible; } else { object.userData.oldVisible = object.visible; object.visible = bVisible; } */ Potree.Utils.updateVisible(object, 'overlinePass', bVisible); } } for (var i = 0; i < this.selectedObjects.length; i++) { var selectedObject = this.selectedObjects[i]; selectedObject.traverse(gatherSelectedMeshesCallBack); } }, changeVisibilityOfNonSelectedObjects: function changeVisibilityOfNonSelectedObjects(bVisible, scenes) { var selectedMeshes = []; function gatherSelectedMeshesCallBack(object) { //if ( object.isMesh ) selectedMeshes.push( object ); if (object.isPointcloud || object.isMesh || object.isLine || object.isSprite) { selectedMeshes.push(object); } } for (var i = 0; i < this.selectedObjects.length; i++) { var selectedObject = this.selectedObjects[i]; selectedObject.traverse(gatherSelectedMeshesCallBack); } function VisibilityChangeCallBack(object) { if (object.isPointcloud || object.isMesh || object.isLine || object.isSprite) { var bFound = false; for (var i = 0; i < selectedMeshes.length; i++) { var selectedObjectId = selectedMeshes[i].id; if (selectedObjectId === object.id) { bFound = true; break; } } if (!bFound) { var visibility = object.visible; Potree.Utils.updateVisible(object, 'overlinePass', bVisible); //add //但保不齐在设置为false后,渲染时又true了,所以在其他地方update时设置visible 得用updateVisible if (!bVisible) { object.visible = false; } else { object.visible = !!object.bVisible; } object.bVisible = visibility; //这两种updateVisible 和 visible 设置都不能去掉, 第一块是为了防止有的visible不是通过updateVisible设置的; 第二块是为了防止渲染时updateVisible又修改了visible为true, 另外渲染时 return { stopContinue: true }; //for pointcloud } } } scenes.forEach(scene => scene.traverse(VisibilityChangeCallBack)); }, updateTextureMatrix: function updateTextureMatrix(camera) { this.textureMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0); this.textureMatrix.multiply(camera.projectionMatrix); this.textureMatrix.multiply(camera.matrixWorldInverse); }, render: function render(scenes, camera, viewports, renderer, writeBuffer, readBuffer, maskActive, renderFun) { if (!(scenes instanceof Array)) scenes = [scenes]; if (this.selectedObjects.length > 0 && this.edgeStrength > 0) { var render2 = function render2(target) { var dontRenderRtEDL = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; if (renderFun) { renderFun({ target, dontRenderRtEDL }); } else { renderer.setRenderTarget(target); renderer.clear(); scenes.forEach(scene => renderer.render(scene, camera)); } }; this.oldClearColor.copy(renderer.getClearColor(new Color())); this.oldClearAlpha = renderer.getClearAlpha(); var oldAutoClear = renderer.autoClear; var oldTarget = renderer.getRenderTarget(); renderer.autoClear = false; if (maskActive) renderer.context.disable(renderer.context.STENCIL_TEST); renderer.setClearColor(0xffffff, 1); var oldBG = viewer.background, oldBgOpacity = viewer.backgroundOpacity; viewer.background = new Color(1, 1, 1); viewer.backgroundOpacity = 1; if (this.showHiddenPart) { //几乎不会使用 viewports.forEach(e => { e.oldBeforeRender = e.beforeRender; e.beforeRender = () => { e.oldBeforeRender && e.oldBeforeRender(); this.replaceDepthToViewZ(e.camera); }; }); // Make selected objects invisible this.changeVisibilityOfSelectedObjects(false); scenes.forEach(scene => { scene.currentBackground = scene.background; scene.background = null; // 1. Draw Non Selected objects in the depth buffer scene.overrideMaterial = this.depthMaterial; }); render2(this.renderTargetDepthBuffer); // Make selected objects visible this.changeVisibilityOfSelectedObjects(true); viewports.forEach(e => { e.beforeRender = () => { e.oldBeforeRender && e.oldBeforeRender(); // Update Texture Matrix for Depth compare this.updateTextureMatrix(e.camera); this.prepareMaskMaterial.uniforms["cameraNearFar"].value = new Vector2(e.camera.near, e.camera.far); }; }); } else { //不渲染背景 scenes.forEach(scene => { scene.currentBackground = scene.background; scene.background = null; }); } var colorType, colors = new Map(), opas = new Map(); { //绘制选中部分 // Make non selected objects invisible, and draw only the selected objects, by comparing the depth buffer of non selected objects this.changeVisibilityOfNonSelectedObjects(false, scenes); scenes.forEach(scene => { scene.overrideMaterial = this.prepareMaskMaterial; }); if (this.showHiddenPart) { this.prepareMaskMaterial.uniforms["depthTexture"].value = this.renderTargetDepthBuffer.texture; this.prepareMaskMaterial.uniforms["textureMatrix"].value = this.textureMatrix; } //因为点云不受prepareMaskMaterial作用,所以手动将他们变为黑色不透明 viewer.scene.pointclouds.forEach(e => { //先将点云透明度变为1,因为点云透明度莫名其妙会影响其r值// colorType = e.material.activeAttributeName; e.material.activeAttributeName = 'color'; colors.set(e, e.material.color); e.material.color = '#000000'; opas.set(e, e.material.opacity); e.material.opacity = 1; }); } render2(this.renderTargetMaskBuffer); { //恢复 viewer.scene.pointclouds.forEach(e => { e.material.activeAttributeName = colorType; e.material.color = colors.get(e); e.material.opacity = opas.get(e); }); if (this.showHiddenPart) { viewports.forEach(e => { e.beforeRender = e.oldBeforeRender; }); } scenes.forEach(scene => { scene.overrideMaterial = null; scene.background = scene.currentBackground; }); viewer.background = oldBG; viewer.backgroundOpacity = oldBgOpacity; this.changeVisibilityOfNonSelectedObjects(true, scenes); } //检测边缘并绘制 // 3. Apply Edge Detection Pass this.quad.material = this.edgeDetectionMaterial; this.edgeDetectionMaterial.uniforms["maskTexture"].value = this.renderTargetMaskBuffer.texture; //this.renderTargetMaskDownSampleBuffer.texture; this.edgeDetectionMaterial.uniforms["texSize"].value = new Vector2(this.resolution.x, this.resolution.y); //new THREE.Vector2( this.renderTargetMaskDownSampleBuffer.width, this.renderTargetMaskDownSampleBuffer.height ); //this.edgeDetectionMaterial.uniforms[ "texSize" ].value = new THREE.Vector2(this.renderTargetMaskBuffer.width, this.renderTargetMaskBuffer.height)//new THREE.Vector2( this.renderTargetMaskDownSampleBuffer.width, this.renderTargetMaskDownSampleBuffer.height ); this.edgeDetectionMaterial.uniforms["edgeStrength"].value = this.edgeStrength; this.edgeDetectionMaterial.uniforms["visibleEdgeColor"].value = this.visibleEdgeColor; //this.tempPulseColor1; this.edgeDetectionMaterial.uniforms["hiddenEdgeColor"].value = this.hiddenEdgeColor; //this.tempPulseColor2; var buffer; if (this.renderToScreen) { this.quad.material.transparent = true; buffer = null; renderer.setClearColor(this.oldClearColor, this.oldClearAlpha); render2(null, false); //普通绘制原场景 //绘制到全屏 var renderSize = renderer.getSize(new Vector2()); //是client大小 renderer.setViewport(0, 0, renderSize.x, renderSize.y); //规定视口,影响图形变换(画布的使用范围) renderer.setScissorTest(false); } else { buffer = readBuffer; renderer.setClearColor(0x000000, 0); renderer.clear(); } renderer.setRenderTarget(buffer); renderer.render(this.scene, this.camera); //将边缘覆盖上去 renderer.setRenderTarget(oldTarget); renderer.setClearColor(this.oldClearColor, this.oldClearAlpha); renderer.autoClear = oldAutoClear; return true; } }, getPrepareMaskMaterial: function getPrepareMaskMaterial() { if (this.showHiddenPart) { return new ShaderMaterial({ uniforms: { "depthTexture": { value: null }, "cameraNearFar": { value: new Vector2(0.5, 0.5) }, "textureMatrix": { value: new Matrix4() } }, vertexShader: ['varying vec4 projTexCoord;', 'varying vec4 vPosition;', 'uniform mat4 textureMatrix;', 'void main() {', ' vPosition = modelViewMatrix * vec4( position, 1.0 );', ' vec4 worldPosition = modelMatrix * vec4( position, 1.0 );', ' projTexCoord = textureMatrix * worldPosition;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), fragmentShader: ['#include ', 'varying vec4 vPosition;', 'varying vec4 projTexCoord;', 'uniform sampler2D depthTexture;', 'uniform vec2 cameraNearFar;', 'void main() {', ' float depth = unpackRGBAToDepth(texture2DProj( depthTexture, projTexCoord ));', ' float viewZ = - DEPTH_TO_VIEW_Z( depth, cameraNearFar.x, cameraNearFar.y );', ' float depthTest = (-vPosition.z > viewZ) ? 1.0 : 0.0;', //决定是否为hiddenPart ' gl_FragColor = vec4(0.0, depthTest, 1.0, 1.0);', '}'].join('\n') }); //没有绘制部分的颜色是clearColor,255 } else { return new MeshBasicMaterial({ color: '#000000' }); //不检测深度,不判断遮挡 } }, getEdgeDetectionMaterial: function getEdgeDetectionMaterial(edgeStrength) { return new ShaderMaterial({ uniforms: { "edgeStrength": { value: edgeStrength }, "maskTexture": { value: null }, "texSize": { value: new Vector2(10, 10) }, "visibleEdgeColor": { value: new Vector3(1.0, 1.0, 1.0) }, "hiddenEdgeColor": { value: new Vector3(1.0, 1.0, 1.0) } }, vertexShader: "varying vec2 vUv;\n\ void main() {\n\ vUv = uv;\n\ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\ }", /* fragmentShader: "varying vec2 vUv;\ uniform sampler2D maskTexture;\ uniform vec2 texSize;\ uniform vec3 visibleEdgeColor;\ uniform vec3 hiddenEdgeColor;\ \ void main() {\n\ vec2 invSize = 1.0 / texSize;\ vec4 uvOffset = vec4(1.0, 0.0, 0.0, 1.0) * vec4(invSize, invSize);\ vec4 c1 = texture2D( maskTexture, vUv + uvOffset.xy);\ vec4 c2 = texture2D( maskTexture, vUv - uvOffset.xy);\ vec4 c3 = texture2D( maskTexture, vUv + uvOffset.yw);\ vec4 c4 = texture2D( maskTexture, vUv - uvOffset.yw);\ float diff1 = (c1.r - c2.r)*0.5;\ float diff2 = (c3.r - c4.r)*0.5;\ float d = length( vec2(diff1, diff2) );\ float a1 = min(c1.g, c2.g);\ float a2 = min(c3.g, c4.g);\ float visibilityFactor = min(a1, a2);\ vec3 edgeColor = 1.0 - visibilityFactor > 0.001 ? visibleEdgeColor : hiddenEdgeColor;\ gl_FragColor = vec4(edgeColor, 1.0) * vec4(d);\ }" */ fragmentShader: "varying vec2 vUv;\n\t\t\t\tuniform sampler2D maskTexture;\n uniform float edgeStrength;\n\t\t\t\tuniform vec2 texSize;\n\t\t\t\tuniform vec3 visibleEdgeColor;\n\t\t\t\tuniform vec3 hiddenEdgeColor;\n\t\t\t\t\n\t\t\t\tvoid main() { \n const float thickness = 1.0;\n vec2 invSize = thickness / texSize;\n\t\t\t\t\tvec4 uvOffset = vec4(1.0, 0.0, 0.0, 1.0) * vec4(invSize, invSize);\n\t\t\t\t\tvec4 c1 = texture2D( maskTexture, vUv + uvOffset.xy);\n\t\t\t\t\tvec4 c2 = texture2D( maskTexture, vUv - uvOffset.xy);\n\t\t\t\t\tvec4 c3 = texture2D( maskTexture, vUv + uvOffset.yw);\n\t\t\t\t\tvec4 c4 = texture2D( maskTexture, vUv - uvOffset.yw);\n\t\t\t\t\tfloat diff1 = (c1.r - c2.r)*0.5; //\u68C0\u6D4B\u8FB9\u7F18\uFF0C\n\t\t\t\t\tfloat diff2 = (c3.r - c4.r)*0.5;\n\t\t\t\t\tfloat d = length( vec2(diff1, diff2) ) * edgeStrength;\n\t\t\t\t\tfloat a1 = min(c1.g, c2.g);\n\t\t\t\t\tfloat a2 = min(c3.g, c4.g);\n\t\t\t\t\tfloat visibilityFactor = min(a1, a2); //\u68C0\u6D4B\u6DF1\u5EA6\u503C\uFF0C\u662F\u5426\u88AB\u906E\u6321\n\t\t\t\t\tvec3 edgeColor = 1.0 - visibilityFactor > 0.001 ? visibleEdgeColor : hiddenEdgeColor;\n\t\t\t\t\t//gl_FragColor = vec4(0.0,1.0,0.0,1.0); \n gl_FragColor = vec4(edgeColor, 1.0) * vec4(d); \n\t\t\t\t}" }); //为什么vec4(0.0,1.0,1.0,1.0); 显示出来的是rgb(109,255,255) ? 几乎只有绿色通道会影响红色通道 }, getSeperableBlurMaterial: function getSeperableBlurMaterial(maxRadius) { return new ShaderMaterial({ defines: { "MAX_RADIUS": maxRadius }, uniforms: { "colorTexture": { value: null }, "texSize": { value: new Vector2(0.5, 0.5) }, "direction": { value: new Vector2(0.5, 0.5) }, "kernelRadius": { value: 1.0 } }, vertexShader: "varying vec2 vUv;\n\ void main() {\n\ vUv = uv;\n\ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\ }", fragmentShader: "#include \ varying vec2 vUv;\ uniform sampler2D colorTexture;\ uniform vec2 texSize;\ uniform vec2 direction;\ uniform float kernelRadius;\ \ float gaussianPdf(in float x, in float sigma) {\ return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma;\ }\ void main() {\ vec2 invSize = 1.0 / texSize;\ float weightSum = gaussianPdf(0.0, kernelRadius);\ vec3 diffuseSum = texture2D( colorTexture, vUv).rgb * weightSum;\ vec2 delta = direction * invSize * kernelRadius/float(MAX_RADIUS);\ vec2 uvOffset = delta;\ for( int i = 1; i <= MAX_RADIUS; i ++ ) {\ float w = gaussianPdf(uvOffset.x, kernelRadius);\ vec3 sample1 = texture2D( colorTexture, vUv + uvOffset).rgb;\ vec3 sample2 = texture2D( colorTexture, vUv - uvOffset).rgb;\ diffuseSum += ((sample1 + sample2) * w);\ weightSum += (2.0 * w);\ uvOffset += delta;\ }\ gl_FragColor = vec4(diffuseSum/weightSum, 1.0);\ }" }); }, getOverlayMaterial: function getOverlayMaterial() { //对边缘线进一步处理,已被废弃 return new ShaderMaterial({ uniforms: { "maskTexture": { value: null }, "edgeTexture1": { value: null }, "edgeTexture2": { value: null }, "patternTexture": { value: null }, "edgeStrength": { value: 1.0 }, "edgeGlow": { value: 1.0 }, "usePatternTexture": { value: 0.0 } }, vertexShader: "varying vec2 vUv;\n\ void main() {\n\ vUv = uv;\n\ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\ }", /* fragmentShader: "varying vec2 vUv;\ uniform sampler2D maskTexture;\ uniform sampler2D edgeTexture1;\ uniform sampler2D edgeTexture2;\ uniform sampler2D patternTexture;\ uniform float edgeStrength;\ uniform float edgeGlow;\ uniform bool usePatternTexture;\ \ void main() {\ vec4 edgeValue1 = texture2D(edgeTexture1, vUv);\ vec4 edgeValue2 = texture2D(edgeTexture2, vUv);\ vec4 maskColor = texture2D(maskTexture, vUv);\ vec4 patternColor = texture2D(patternTexture, 6.0 * vUv);\ float visibilityFactor = 1.0 - maskColor.g > 0.0 ? 1.0 : 0.5;\ vec4 edgeValue = edgeValue1 + edgeValue2 * edgeGlow;\ vec4 finalColor = edgeStrength * maskColor.r * edgeValue;\ // 删除 * maskColor.r 也就是去掉遮罩,使模型部分也有outline if(usePatternTexture)\ finalColor += + visibilityFactor * (1.0 - maskColor.r) * (1.0 - patternColor.r);\ gl_FragColor = finalColor;\ }", */ fragmentShader: "varying vec2 vUv; \n\t\t\t\tuniform sampler2D edgeTexture1; \n\t\t\t\tuniform float edgeStrength; \n\t\t\t\t \n\t\t\t\tvoid main() { \n\t\t\t\t\tgl_FragColor = edgeStrength * texture2D(edgeTexture1, vUv); \n\t\t\t\t}", blending: AdditiveBlending, depthTest: false, depthWrite: false, transparent: true }); } }); OutlinePass.BlurDirectionX = new Vector2(1.0, 0.0); OutlinePass.BlurDirectionY = new Vector2(0.0, 1.0); /* 渲染步骤:(没有showHiddenPart时) 仅绘制选中部分,材质为普通的单色材质,颜色是黑色不透明。未绘制部分的clearColor是白色不透明。 (详见prepareMaskMaterial,输出的r要为0) 然后在上面绘制的图中,根据r的差值,得到边缘线。 正常绘制场景之后,将上面的边缘线覆盖于其上。 (如果showHiddenPart,最开始还要先隐藏选中部分,这是为了得到非选中部分的深度值,然后再绘制选中部分时去比较选中和非选中部分之间的深度差异。以判断是否被遮挡。) */ /** * @author mschuetz / http://mschuetz.at * * adapted from THREE.OrbitControls by * * @author qiao / https://github.com/qiao * @author mrdoob / http://mrdoob.com * @author alteredq / http://alteredqualia.com/ * @author WestLangley / http://github.com/WestLangley * @author erich666 / http://erichaines.com * * * */ var minRadius = 2; class OrbitControls$1 extends EventDispatcher { constructor(viewer, viewport) { super(); this.viewer = viewer; this.renderer = viewer.renderer; this.scene = null; this.sceneControls = new Scene(); this.rotationSpeed = 3; //旋转速度 viewport = viewport || viewer.viewports[0]; this.setCurrentViewport({ hoverViewport: viewport, force: true }); //this.currentViewport = viewport this.fadeFactor = 20; this.yawDelta = 0; this.pitchDelta = 0; this.panDelta = new Vector2(0, 0); this.radiusDelta = 0; this.doubleClockZoomEnabled = true; this.tweens = []; this.dollyStart = new Vector2(); this.dollyEnd = new Vector2(); this.keys = { FORWARD: ['W'.charCodeAt(0), 38], BACKWARD: ['S'.charCodeAt(0), 40], LEFT: ['A'.charCodeAt(0), 37], RIGHT: ['D'.charCodeAt(0), 39], UP: ['Q'.charCodeAt(0)], DOWN: ['E'.charCodeAt(0)] }; var drag = e => { if (!this.enabled) return; var viewport = e.dragViewport; if (!viewport /* || viewport.camera.type == "OrthographicCamera" */) return; //let camera = viewport.camera if (e.drag.object !== null) { return; } var mode; if (e.isTouch) { if (e.touches.length == 1) { mode = 'rotate'; } else { mode = 'scale-pan'; } } else { mode = e.buttons === Potree.defines.Buttons.LEFT ? 'rotate' : 'pan'; } if (e.drag.startHandled === undefined) { e.drag.startHandled = true; this.dispatchEvent({ type: 'start' }); } var ndrag = e.drag.pointerDelta.clone(); //.add(new THREE.Vector2(1,1)).multiplyScalar(0.5) ndrag.y *= -1; if (mode == 'rotate') { this.yawDelta += ndrag.x * this.rotationSpeed; this.pitchDelta += ndrag.y * this.rotationSpeed; } else if (mode == 'pan') { this.panDelta.x += ndrag.x; this.panDelta.y += ndrag.y; } else if (mode == 'scale-pan') { //add this.dollyEnd.subVectors(e.touches[0].pointer, e.touches[1].pointer); var scale = this.dollyEnd.length() / this.dollyStart.length(); this.dollyStart.copy(this.dollyEnd); this.radiusDelta = (1 - scale) * this.currentViewport.view.radius; //------------------------ //平移 var pointer = new Vector2().addVectors(e.touches[0].pointer, e.touches[1].pointer).multiplyScalar(0.5); //两个指头的中心点 var delta = new Vector2().subVectors(pointer, this.lastScalePointer); delta.y *= -1; this.panDelta.add(delta); this.lastScalePointer = pointer.clone(); //console.log('scale ',scale, this.radiusDelta) } this.stopTweens(); }; var drop = e => { if (!this.enabled) return; this.dispatchEvent({ type: 'end' }); }; var scroll = e => { if (!this.enabled) return; var resolvedRadius = this.currentViewport.view.radius + this.radiusDelta; if (resolvedRadius < 0.1 && e.delta > 0) return; //防止缩放太小,导致很慢 this.radiusDelta += -e.delta * resolvedRadius * 0.1; this.stopTweens(); }; var dblclick = e => { if (!this.enabled) return; if (this.doubleClockZoomEnabled) { this.zoomToLocation(e.mouse); } }; var previousTouch = null; var touchStart = e => { previousTouch = e; }; var touchEnd = e => { previousTouch = e; }; var touchMove = e => { if (!this.enabled) return; if (e.touches.length === 2 && previousTouch.touches.length === 2) { var prev = previousTouch; var curr = e; var prevDX = prev.touches[0].pageX - prev.touches[1].pageX; var prevDY = prev.touches[0].pageY - prev.touches[1].pageY; var prevDist = Math.sqrt(prevDX * prevDX + prevDY * prevDY); var currDX = curr.touches[0].pageX - curr.touches[1].pageX; var currDY = curr.touches[0].pageY - curr.touches[1].pageY; var currDist = Math.sqrt(currDX * currDX + currDY * currDY); var delta = currDist / prevDist; var resolvedRadius = this.currentViewport.view.radius + this.radiusDelta; var newRadius = resolvedRadius / delta; this.radiusDelta = newRadius - resolvedRadius; this.stopTweens(); } else if (e.touches.length === 3 && previousTouch.touches.length === 3) { var _prev = previousTouch; var _curr = e; var prevMeanX = (_prev.touches[0].pageX + _prev.touches[1].pageX + _prev.touches[2].pageX) / 3; var prevMeanY = (_prev.touches[0].pageY + _prev.touches[1].pageY + _prev.touches[2].pageY) / 3; var currMeanX = (_curr.touches[0].pageX + _curr.touches[1].pageX + _curr.touches[2].pageX) / 3; var currMeanY = (_curr.touches[0].pageY + _curr.touches[1].pageY + _curr.touches[2].pageY) / 3; var _delta = { x: (currMeanX - prevMeanX) / this.renderer.domElement.clientWidth, y: (currMeanY - prevMeanY) / this.renderer.domElement.clientHeight }; this.panDelta.x += _delta.x; this.panDelta.y += _delta.y; this.stopTweens(); } previousTouch = e; }; this.addEventListener('touchstart', touchStart); this.addEventListener('touchend', touchEnd); this.addEventListener('touchmove', touchMove); this.viewer.addEventListener('global_drag', drag); this.viewer.addEventListener('global_drop', drop); this.viewer.addEventListener('global_mousewheel', scroll); this.viewer.addEventListener('global_dblclick', dblclick); this.viewer.addEventListener('global_touchmove', e => { if (e.touches.length > 1) { //单指的就触发上一句 //console.log('global_touchmove' ) drag(e); } }); var prepareScale = e => { //触屏的scale this.dollyStart.subVectors(e.touches[0].pointer, e.touches[1].pointer); this.lastScalePointer = new Vector2().addVectors(e.touches[0].pointer, e.touches[1].pointer).multiplyScalar(0.5); //两个指头的中心点 }; this.viewer.addEventListener('global_touchstart', e => { if (this.enabled && e.touches.length == 2) { //只监听开头两个指头 prepareScale(e); } }); /* this.viewer.addEventListener('global_touchend', (e)=>{ if(!this.enabled)return if(e.touches.length==1){//停止scale,开始rotate prepareRotate(e) //this.pointerDragStart = null //console.log('只剩一个', e.pointer.toArray()) } }) */ this.viewer.addEventListener('focusOnObject', o => { if (o.position && o.CamTarget) { var distance = o.position.distanceTo(o.CamTarget); if (distance < minRadius) minRadius = distance * 0.5; //融合页面当focus一个很小的物体时,需要将minRadius也调小 } }); } setScene(scene) { this.scene = scene; } setCurrentViewport() { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; //add if (!this.enabled && !o.force) return; if (o.hoverViewport && this.currentViewport != o.hoverViewport) { this.currentViewport = o.hoverViewport; } } setEnable(enabled) { this.enabled = enabled; } stop() { this.yawDelta = 0; this.pitchDelta = 0; this.radiusDelta = 0; this.panDelta.set(0, 0); } /* zoomToLocation(mouse){ if(!this.enabled)return let camera = this.scene.getActiveCamera(); let I = Utils.getMousePointCloudIntersection( null, mouse, this.viewer.inputHandler.pointer, camera, this.viewer, this.scene.pointclouds, {pickClipped: true}); if (I === null) { return; } let targetRadius = 0; { let minimumJumpDistance = 0.2; let domElement = this.renderer.domElement; let ray = Utils.mouseToRay(this.viewer.inputHandler.pointer , camera, domElement.clientWidth, domElement.clientHeight); let nodes = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, ray); let lastNode = nodes[nodes.length - 1]; let radius = lastNode.getBoundingSphere(new THREE.Sphere()).radius; targetRadius = Math.min(this.currentViewport.view.radius, radius); targetRadius = Math.max(minimumJumpDistance, targetRadius); } let d = this.currentViewport.view.direction.multiplyScalar(-1); let cameraTargetPosition = new THREE.Vector3().addVectors(I.location, d.multiplyScalar(targetRadius)); // TODO Unused: let controlsTargetPosition = I.location; let animationDuration = 600; let easing = TWEEN.Easing.Quartic.Out; { // animate let value = {x: 0}; let tween = new TWEEN.Tween(value).to({x: 1}, animationDuration); tween.easing(easing); this.tweens.push(tween); let startPos = this.currentViewport.view.position.clone(); let targetPos = cameraTargetPosition.clone(); let startRadius = this.currentViewport.view.radius; let targetRadius = cameraTargetPosition.distanceTo(I.location); tween.onUpdate(() => { let t = value.x; this.currentViewport.view.position.x = (1 - t) * startPos.x + t * targetPos.x; this.currentViewport.view.position.y = (1 - t) * startPos.y + t * targetPos.y; this.currentViewport.view.position.z = (1 - t) * startPos.z + t * targetPos.z; this.currentViewport.view.radius = (1 - t) * startRadius + t * targetRadius; this.viewer.setMoveSpeed(this.currentViewport.view.radius); }); tween.onComplete(() => { this.tweens = this.tweens.filter(e => e !== tween); }); tween.start(); } } */ zoomToLocation(mouse) { var I = viewer.inputHandler.intersect; if (!I) return; var object = I.object || I.pointcloud; I = I.location; if (!I || !object) return; var dis = this.currentViewport.view.position.distanceTo(I); var bound = object.boundingBox.clone().applyMatrix4(object.matrixWorld); var size = bound.getSize(new Vector3()); var len = size.length(); var distance = MathUtils.clamp(dis, 0.1, Math.max(len * 0.1, 3)); minRadius = distance; viewer.focusOnObject({ position: I }, 'point', null, { distance }); } stopTweens() { this.tweens.forEach(e => e.stop()); this.tweens = []; } update(delta) { if (!this.enabled) return; var view = this.currentViewport.view; //this.currentViewport.view; var camera = this.currentViewport.camera; { // accelerate while input is given var ih = this.viewer.inputHandler; var moveForward = this.keys.FORWARD.some(e => ih.pressedKeys[e]); var moveBackward = this.keys.BACKWARD.some(e => ih.pressedKeys[e]); var moveLeft = this.keys.LEFT.some(e => ih.pressedKeys[e]); var moveRight = this.keys.RIGHT.some(e => ih.pressedKeys[e]); var moveUp = this.keys.UP.some(e => ih.pressedKeys[e]); var moveDown = this.keys.DOWN.some(e => ih.pressedKeys[e]); var moveSpeed = this.currentViewport.getMoveSpeed() / 20; var px = 0, py = 0, pz = 0; if (moveForward) { py = 1 * moveSpeed; } else if (moveBackward) { py = -1 * moveSpeed; } if (moveLeft) { px = -1 * moveSpeed; } else if (moveRight) { px = 1 * moveSpeed; } if (moveUp) { pz = 1 * moveSpeed; } else if (moveDown) { pz = -1 * moveSpeed; } (px != 0 || py != 0 || pz != 0) && view.translate(px, py, pz, true); } { // apply rotation var progression = Math.min(1, this.fadeFactor * delta); var yaw = view.yaw; var pitch = view.pitch; var pivot = view.getPivot(); yaw -= progression * this.yawDelta; pitch -= progression * this.pitchDelta; view.yaw = yaw; view.pitch = pitch; var V = this.currentViewport.view.direction.multiplyScalar(-view.radius); var position = new Vector3().addVectors(pivot, V); view.position.copy(position); } if (camera.type != 'OrthographicCamera') { // apply pan /* let progression = Math.min(1, this.fadeFactor * delta); let panDistance = progression * view.radius * 3; */ var panDistance = 2 * view.radius * Math.tan(MathUtils.degToRad(camera.fov / 2)); //参照4dkk。 平移target(也就是平移镜头位置),但还是难以保证跟手(navvis也不一定跟手,但是很奇怪在居中时中心点居然是跟手的,可能计算方式不同) //计算了下确实是这么算的。 平移pivot。 var _px = -this.panDelta.x * panDistance; var _py = this.panDelta.y * panDistance; view.pan(_px, _py); } { // apply zoom var _progression = 1; //Math.min(1, this.fadeFactor * delta); // let radius = view.radius + progression * this.radiusDelta * view.radius * 0.1; var radius = view.radius + _progression * this.radiusDelta; var _V = view.direction.multiplyScalar(-radius); var _position = new Vector3().addVectors(view.getPivot(), _V); if (this.constantlyForward) { // 到达中心点后还能继续向前移动,也就是能推进中心点 if (radius < minRadius) { radius = minRadius; } } view.radius = radius; view.position.copy(_position); } { var speed = view.radius; this.viewer.setMoveSpeed && this.viewer.setMoveSpeed(speed); } { // decelerate over time /* let progression = Math.min(1, this.fadeFactor * delta); let attenuation = Math.max(0, 1 - this.fadeFactor * delta); this.yawDelta *= attenuation; this.pitchDelta *= attenuation; this.panDelta.multiplyScalar(attenuation); // this.radiusDelta *= attenuation; this.radiusDelta -= progression * this.radiusDelta; */ //取消衰减,直接stop this.stop(); } } } ; // Adapted from three.js VRButton class VRButton$1 { constructor() { this.onStartListeners = []; this.onEndListeners = []; this.element = null; } onStart(callback) { this.onStartListeners.push(callback); } onEnd(callback) { this.onEndListeners.push(callback); } static async createButton(renderer, options) { if (options) { console.error('THREE.VRButton: The "options" parameter has been removed. Please set the reference space type via renderer.xr.setReferenceSpaceType() instead.'); } var button = new VRButton$1(); var element = document.createElement('button'); button.element = element; function setEnter() { button.element.innerHTML = "\n\t\t\t\t
    ENTER
    \n\t\t\t\t
    VR
    \n\t\t\t"; } function setExit() { button.element.innerHTML = "\n\t\t\t\t
    EXIT
    \n\t\t\t\t
    VR
    \n\t\t\t"; } function showEnterVR( /*device*/ ) { var currentSession = null; function onSessionStarted(session) { session.addEventListener('end', onSessionEnded); for (var listener of button.onStartListeners) { listener(); } renderer.xr.setSession(session); setExit(); currentSession = session; } function onSessionEnded( /*event*/ ) { currentSession.removeEventListener('end', onSessionEnded); for (var listener of button.onEndListeners) { listener(); } setEnter(); currentSession = null; } // button.element.style.display = ''; button.element.style.cursor = 'pointer'; setEnter(); button.element.onmouseenter = function () { button.element.style.opacity = '1.0'; }; button.element.onmouseleave = function () { button.element.style.opacity = '0.7'; }; button.element.onclick = function () { if (currentSession === null) { // WebXR's requestReferenceSpace only works if the corresponding feature // was requested at session creation time. For simplicity, just ask for // the interesting ones as optional features, but be aware that the // requestReferenceSpace call will fail if it turns out to be unavailable. // ('local' is always available for immersive sessions and doesn't need to // be requested separately.) var sessionInit = { optionalFeatures: ['local-floor', 'bounded-floor', 'hand-tracking'] }; navigator.xr.requestSession('immersive-vr', sessionInit).then(onSessionStarted); } else { currentSession.end(); } }; } function stylizeElement(element) { element.style.position = 'absolute'; element.style.bottom = '20px'; element.style.padding = '12px 6px'; element.style.border = '1px solid #fff'; element.style.borderRadius = '4px'; element.style.background = 'rgba(0,0,0,0.1)'; element.style.color = '#fff'; element.style.font = 'normal 13px sans-serif'; element.style.textAlign = 'center'; element.style.opacity = '0.7'; element.style.outline = 'none'; element.style.zIndex = '999'; } if ('xr' in navigator) { button.element.id = 'VRButton'; button.element.style.display = 'none'; stylizeElement(button.element); var supported = await navigator.xr.isSessionSupported('immersive-vr'); if (supported) { showEnterVR(); return button; } else { return null; } } else { if (window.isSecureContext === false) { console.log("WEBXR NEEDS HTTPS"); } else { console.log("WEBXR not available"); } return null; } } } !function (e, a) { "object" == typeof exports && "object" == typeof module ? module.exports = a() : "function" == typeof define && define.amd ? define([], a) : "object" == typeof exports ? exports.DxfParser = a() : e.DxfParser = a(); }("undefined" != typeof self ? self : undefined, function () { return function (e) { var a = {}; function t(r) { if (a[r]) return a[r].exports; var n = a[r] = { i: r, l: !1, exports: {} }; return e[r].call(n.exports, n, n.exports, t), n.l = !0, n.exports; } return t.m = e, t.c = a, t.d = function (e, a, r) { t.o(e, a) || Object.defineProperty(e, a, { enumerable: !0, get: r }); }, t.r = function (e) { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(e, "__esModule", { value: !0 }); }, t.t = function (e, a) { if (1 & a && (e = t(e)), 8 & a) return e; if (4 & a && "object" == typeof e && e && e.__esModule) return e; var r = Object.create(null); if (t.r(r), Object.defineProperty(r, "default", { enumerable: !0, value: e }), 2 & a && "string" != typeof e) for (var n in e) t.d(r, n, function (a) { return e[a]; }.bind(null, n)); return r; }, t.n = function (e) { var a = e && e.__esModule ? function () { return e.default; } : function () { return e; }; return t.d(a, "a", a), a; }, t.o = function (e, a) { return Object.prototype.hasOwnProperty.call(e, a); }, t.p = "", t(t.s = 1); }([function (e, a, t) { var r, n; !function (o, c) { "use strict"; void 0 === (n = "function" == typeof (r = function r() { var e = function e() {}, a = "undefined", t = ["trace", "debug", "info", "warn", "error"]; function r(e, a) { var t = e[a]; if ("function" == typeof t.bind) return t.bind(e); try { return Function.prototype.bind.call(t, e); } catch (a) { return function () { return Function.prototype.apply.apply(t, [e, arguments]); }; } } function n(a, r) { for (var n = 0; n < t.length; n++) { var o = t[n]; this[o] = n < a ? e : this.methodFactory(o, a, r); } this.log = this.debug; } function o(t, o, c) { return function (t) { "debug" === t && (t = "log"); return typeof console !== a && (void 0 !== console[t] ? r(console, t) : void 0 !== console.log ? r(console, "log") : e); }(t) || function (e, t, r) { return function () { typeof console !== a && (n.call(this, t, r), this[e].apply(this, arguments)); }; }.apply(this, arguments); } function c(e, r, c) { var i, u = this, s = "loglevel"; function l() { var e; if (typeof window !== a) { try { e = window.localStorage[s]; } catch (e) {} if (typeof e === a) try { var t = window.document.cookie, r = t.indexOf(encodeURIComponent(s) + "="); -1 !== r && (e = /^([^;]+)/.exec(t.slice(r))[1]); } catch (e) {} return void 0 === u.levels[e] && (e = void 0), e; } } e && (s += ":" + e), u.name = e, u.levels = { TRACE: 0, DEBUG: 1, INFO: 2, WARN: 3, ERROR: 4, SILENT: 5 }, u.methodFactory = c || o, u.getLevel = function () { return i; }, u.setLevel = function (r, o) { if ("string" == typeof r && void 0 !== u.levels[r.toUpperCase()] && (r = u.levels[r.toUpperCase()]), !("number" == typeof r && r >= 0 && r <= u.levels.SILENT)) throw "log.setLevel() called with invalid level: " + r; if (i = r, !1 !== o && function (e) { var r = (t[e] || "silent").toUpperCase(); if (typeof window === a) return; try { return void (window.localStorage[s] = r); } catch (e) {} try { window.document.cookie = encodeURIComponent(s) + "=" + r + ";"; } catch (e) {} }(r), n.call(u, r, e), typeof console === a && r < u.levels.SILENT) return "No console available for logging"; }, u.setDefaultLevel = function (e) { l() || u.setLevel(e, !1); }, u.enableAll = function (e) { u.setLevel(u.levels.TRACE, e); }, u.disableAll = function (e) { u.setLevel(u.levels.SILENT, e); }; var v = l(); null == v && (v = null == r ? "WARN" : r), u.setLevel(v, !1); } var i = new c(), u = {}; i.getLogger = function (e) { if ("string" != typeof e || "" === e) throw new TypeError("You must supply a name when creating a logger."); var a = u[e]; return a || (a = u[e] = new c(e, i.getLevel(), i.methodFactory)), a; }; var s = typeof window !== a ? window.log : void 0; return i.noConflict = function () { return typeof window !== a && window.log === i && (window.log = s), i; }, i.getLoggers = function () { return u; }, i; }) ? r.call(a, t, a, e) : r) || (e.exports = n); }(); }, function (e, a, t) { "use strict"; function r(e) { this._pointer = 0, this._data = e, this._eof = !1; } function n(e, a) { return e <= 9 ? a : e >= 10 && e <= 59 ? parseFloat(a) : e >= 60 && e <= 99 ? parseInt(a) : e >= 100 && e <= 109 ? a : e >= 110 && e <= 149 ? parseFloat(a) : e >= 160 && e <= 179 ? parseInt(a) : e >= 210 && e <= 239 ? parseFloat(a) : e >= 270 && e <= 289 ? parseInt(a) : e >= 290 && e <= 299 ? function (e) { if ("0" === e) return !1; if ("1" === e) return !0; throw TypeError("String '" + e + "' cannot be cast to Boolean type"); }(a) : e >= 300 && e <= 369 ? a : e >= 370 && e <= 389 ? parseInt(a) : e >= 390 && e <= 399 ? a : e >= 400 && e <= 409 ? parseInt(a) : e >= 410 && e <= 419 ? a : e >= 420 && e <= 429 ? parseInt(a) : e >= 430 && e <= 439 ? a : e >= 440 && e <= 459 ? parseInt(a) : e >= 460 && e <= 469 ? parseFloat(a) : e >= 470 && e <= 481 ? a : 999 === e ? a : e >= 1e3 && e <= 1009 ? a : e >= 1010 && e <= 1059 ? parseFloat(a) : e >= 1060 && e <= 1071 ? parseInt(a) : (console.log("WARNING: Group code does not have a defined type: %j", { code: e, value: a }), a); } t.r(a), r.prototype.next = function () { var e; if (!this.hasNext()) throw this._eof ? new Error("Cannot call 'next' after EOF group has been read") : new Error("Unexpected end of input: EOF group not read before end of file. Ended on code " + this._data[this._pointer]); return e = { code: parseInt(this._data[this._pointer]) }, this._pointer++, e.value = n(e.code, this._data[this._pointer].trim()), this._pointer++, 0 === e.code && "EOF" === e.value && (this._eof = !0), this.lastReadGroup = e, e; }, r.prototype.peek = function () { if (!this.hasNext()) throw this._eof ? new Error("Cannot call 'next' after EOF group has been read") : new Error("Unexpected end of input: EOF group not read before end of file. Ended on code " + this._data[this._pointer]); var e = { code: parseInt(this._data[this._pointer]) }; return e.value = n(e.code, this._data[this._pointer + 1].trim()), e; }, r.prototype.rewind = function (e) { e = e || 1, this._pointer = this._pointer - 2 * e; }, r.prototype.hasNext = function () { return !this._eof && !(this._pointer > this._data.length - 2); }, r.prototype.isEOF = function () { return this._eof; }; var o = [0, 16711680, 16776960, 65280, 65535, 255, 16711935, 16777215, 8421504, 12632256, 16711680, 16744319, 13369344, 13395558, 10027008, 10046540, 8323072, 8339263, 4980736, 4990502, 16727808, 16752511, 13382400, 13401958, 10036736, 10051404, 8331008, 8343359, 4985600, 4992806, 16744192, 16760703, 13395456, 13408614, 10046464, 10056268, 8339200, 8347455, 4990464, 4995366, 16760576, 16768895, 13408512, 13415014, 10056192, 10061132, 8347392, 8351551, 4995328, 4997670, 16776960, 16777087, 13421568, 13421670, 10000384, 10000460, 8355584, 8355647, 5000192, 5000230, 12582656, 14679935, 10079232, 11717734, 7510016, 8755276, 6258432, 7307071, 3755008, 4344870, 8388352, 12582783, 6736896, 10079334, 5019648, 7510092, 4161280, 6258495, 2509824, 3755046, 4194048, 10485631, 3394560, 8375398, 2529280, 6264908, 2064128, 5209919, 1264640, 3099686, 65280, 8388479, 52224, 6736998, 38912, 5019724, 32512, 4161343, 19456, 2509862, 65343, 8388511, 52275, 6737023, 38950, 5019743, 32543, 4161359, 19475, 2509871, 65407, 8388543, 52326, 6737049, 38988, 5019762, 32575, 4161375, 19494, 2509881, 65471, 8388575, 52377, 6737074, 39026, 5019781, 32607, 4161391, 19513, 2509890, 65535, 8388607, 52428, 6737100, 39064, 5019800, 32639, 4161407, 19532, 2509900, 49151, 8380415, 39372, 6730444, 29336, 5014936, 24447, 4157311, 14668, 2507340, 32767, 8372223, 26316, 6724044, 19608, 5010072, 16255, 4153215, 9804, 2505036, 16383, 8364031, 13260, 6717388, 9880, 5005208, 8063, 4149119, 4940, 2502476, 255, 8355839, 204, 6710988, 152, 5000344, 127, 4145023, 76, 2500172, 4129023, 10452991, 3342540, 8349388, 2490520, 6245528, 2031743, 5193599, 1245260, 3089996, 8323327, 12550143, 6684876, 10053324, 4980888, 7490712, 4128895, 6242175, 2490444, 3745356, 12517631, 14647295, 10027212, 11691724, 7471256, 8735896, 6226047, 7290751, 3735628, 4335180, 16711935, 16744447, 13369548, 13395660, 9961624, 9981080, 8323199, 8339327, 4980812, 4990540, 16711871, 16744415, 13369497, 13395634, 9961586, 9981061, 8323167, 8339311, 4980793, 4990530, 16711807, 16744383, 13369446, 13395609, 9961548, 9981042, 8323135, 8339295, 4980774, 4990521, 16711743, 16744351, 13369395, 13395583, 9961510, 9981023, 8323103, 8339279, 4980755, 4990511, 3355443, 5987163, 8684676, 11382189, 14079702, 16777215]; function c(e) { var a = {}; e.rewind(); var t = e.next(), r = t.code; if (a.x = t.value, r += 10, (t = e.next()).code != r) throw new Error("Expected code for point value to be " + r + " but got " + t.code + "."); return a.y = t.value, r += 10, (t = e.next()).code != r ? (e.rewind(), a) : (a.z = t.value, a); } function i(e, a) { switch (a.code) { case 0: e.type = a.value; break; case 5: e.handle = a.value; /* if(e.handle == "2FDDB"){ console.log(1) } */ break; case 6: e.lineType = a.value; break; case 8: e.layer = a.value; break; case 48: e.lineTypeScale = a.value; break; case 60: e.visible = 0 === a.value; break; case 62: e.colorIndex = a.value, e.color = (t = Math.abs(a.value), o[t]); break; case 67: e.inPaperSpace = 0 !== a.value; break; case 100: break; case 330: e.ownerHandle = a.value; break; case 347: e.materialObjectHandle = a.value; break; case 370: e.lineweight = a.value; break; case 420: e.color = a.value; break; case 1e3: e.extendedData = e.extendedData || {}, e.extendedData.customStrings = e.extendedData.customStrings || [], e.extendedData.customStrings.push(a.value); break; case 1001: e.extendedData = e.extendedData || {}, e.extendedData.applicationName = a.value; break; default: return !1; } var t; return !0; } function u() {} function s(e, a) { var t, r = [], n = !1, o = !1; for (t = 0; t <= 4; t++) { for (var c = {}; "EOF" !== a && 0 !== a.code && !o;) { switch (a.code) { case 10: case 11: case 12: case 13: if (n) { o = !0; continue; } c.x = a.value, n = !0; break; case 20: case 21: case 22: case 23: c.y = a.value; break; case 30: case 31: case 32: case 33: c.z = a.value; break; default: return r; } a = e.next(); } r.push(c), n = !1, o = !1; } return e.rewind(), r; } function l() {} function v() {} function d() {} function b() {} function p() {} function f() {} function k() {} function y() {} function x(e, a) { if (!e || e <= 0) throw Error("n must be greater than 0 verticies"); var t, r = [], n = !1, o = !1, c = a.lastReadGroup; for (t = 0; t < e; t++) { for (var i = {}; "EOF" !== c && 0 !== c.code && !o;) { switch (c.code) { case 10: if (n) { o = !0; continue; } i.x = c.value, n = !0; break; case 20: i.y = c.value; break; case 30: i.z = c.value; break; case 40: i.startWidth = c.value; break; case 41: i.endWidth = c.value; break; case 42: 0 != c.value && (i.bulge = c.value); break; default: return n && r.push(i), r; } c = a.next(); } r.push(i), n = !1, o = !1; } return a.rewind(), r; } function h() {} function g() {} function E() {} function w() {} function m(e, a) { var t = { type: a.value }; for (a = e.next(); "EOF" != a && 0 != a.code;) i(t, a), a = e.next(); return t; } function P() {} function F() {} function O() {} u.ForEntityName = "3DFACE", u.prototype.parseEntity = function (e, a) { var t = { type: a.value, vertices: [] }; for (a = e.next(); "EOF" !== a && 0 !== a.code;) { switch (a.code) { case 70: t.shape = 1 == (1 & a.value), t.hasContinuousLinetypePattern = 128 == (128 & a.value); break; case 10: t.vertices = s(e, a), a = e.lastReadGroup; break; default: i(t, a); } a = e.next(); } return t; }, l.ForEntityName = "ARC", l.prototype.parseEntity = function (e, a) { var t; for (t = { type: a.value }, a = e.next(); "EOF" !== a && 0 !== a.code;) { switch (a.code) { case 10: t.center = c(e); break; case 40: t.radius = a.value; break; case 50: t.startAngle = Math.PI / 180 * a.value; break; case 51: t.endAngle = Math.PI / 180 * a.value, t.angleLength = t.endAngle - t.startAngle; break; default: i(t, a); } a = e.next(); } return t; }, v.ForEntityName = "ATTDEF", v.prototype.parseEntity = function (e, a) { var t = { type: a.value, scale: 1, textStyle: "STANDARD" }; for (a = e.next(); "EOF" !== a && 0 !== a.code;) { switch (a.code) { case 1: t.text = a.value; break; case 2: t.tag = a.value; break; case 3: t.prompt = a.value; break; case 7: t.textStyle = a.value; break; case 10: t.startPoint = c(e); break; case 11: t.endPoint = c(e); break; case 39: t.thickness = a.value; break; case 40: t.textHeight = a.value; break; case 41: t.scale = a.value; break; case 50: t.rotation = a.value; break; case 51: t.obliqueAngle = a.value; break; case 70: t.invisible = !!(1 & a.value), t.constant = !!(2 & a.value), t.verificationRequired = !!(4 & a.value), t.preset = !!(8 & a.value); break; case 71: t.backwards = !!(2 & a.value), t.mirrored = !!(4 & a.value); break; case 72: t.horizontalJustification = a.value; break; case 73: t.fieldLength = a.value; break; case 74: t.verticalJustification = a.value; break; case 100: break; case 210: t.extrusionDirectionX = a.value; break; case 220: t.extrusionDirectionY = a.value; break; case 230: t.extrusionDirectionZ = a.value; break; default: i(t, a); } a = e.next(); } return t; }, d.ForEntityName = "CIRCLE", d.prototype.parseEntity = function (e, a) { var t, r; for (t = { type: a.value }, a = e.next(); "EOF" !== a && 0 !== a.code;) { switch (a.code) { case 10: t.center = c(e); break; case 40: t.radius = a.value; break; case 50: t.startAngle = Math.PI / 180 * a.value; break; case 51: (r = Math.PI / 180 * a.value) < t.startAngle ? t.angleLength = r + 2 * Math.PI - t.startAngle : t.angleLength = r - t.startAngle, t.endAngle = r; break; default: i(t, a); } a = e.next(); } return t; }, b.ForEntityName = "DIMENSION", b.prototype.parseEntity = function (e, a) { var t; for (t = { type: a.value }, a = e.next(); "EOF" !== a && 0 !== a.code;) { switch (a.code) { case 2: t.block = a.value; break; case 10: t.anchorPoint = c(e); break; case 11: t.middleOfText = c(e); break; case 12: t.insertionPoint = c(e); break; case 13: t.linearOrAngularPoint1 = c(e); break; case 14: t.linearOrAngularPoint2 = c(e); break; case 15: t.diameterOrRadiusPoint = c(e); break; case 16: t.arcPoint = c(e); break; case 70: t.dimensionType = a.value; break; case 71: t.attachmentPoint = a.value; break; case 42: t.actualMeasurement = a.value; break; case 1: t.text = a.value; break; case 50: t.angle = a.value; break; default: i(t, a); } a = e.next(); } return t; }, p.ForEntityName = "ELLIPSE", p.prototype.parseEntity = function (e, a) { var t; for (t = { type: a.value }, a = e.next(); "EOF" !== a && 0 !== a.code;) { switch (a.code) { case 10: t.center = c(e); break; case 11: t.majorAxisEndPoint = c(e); break; case 40: t.axisRatio = a.value; break; case 41: t.startAngle = a.value; break; case 42: t.endAngle = a.value; break; case 2: t.name = a.value; break; default: i(t, a); } a = e.next(); } return t; }, f.ForEntityName = "INSERT", f.prototype.parseEntity = function (e, a) { var t; for (t = { type: a.value }, a = e.next(); "EOF" !== a && 0 !== a.code;) { switch (a.code) { case 2: t.name = a.value; break; case 41: t.xScale = a.value; break; case 42: t.yScale = a.value; break; case 43: t.zScale = a.value; break; case 10: t.position = c(e); break; case 50: t.rotation = a.value; break; case 70: t.columnCount = a.value; break; case 71: t.rowCount = a.value; break; case 44: t.columnSpacing = a.value; break; case 45: t.rowSpacing = a.value; break; case 210: t.extrusionDirection = c(e); break; default: i(t, a); } a = e.next(); } return t; }, k.ForEntityName = "LINE", k.prototype.parseEntity = function (e, a) { var t = { type: a.value, vertices: [] }; for (a = e.next(); "EOF" !== a && 0 !== a.code;) { switch (a.code) { case 10: t.vertices.unshift(c(e)); break; case 11: t.vertices.push(c(e)); break; case 210: t.extrusionDirection = c(e); break; case 100: break; default: i(t, a); } a = e.next(); } return t; }, y.ForEntityName = "LWPOLYLINE", y.prototype.parseEntity = function (e, a) { var t = { type: a.value, vertices: [] }, r = 0; for (a = e.next(); "EOF" !== a && 0 !== a.code;) { switch (a.code) { case 38: t.elevation = a.value; break; case 39: t.depth = a.value; break; case 70: t.shape = 1 == (1 & a.value), t.hasContinuousLinetypePattern = 128 == (128 & a.value); break; case 90: r = a.value; break; case 10: //t.vertices = x(r, e); //改,因有的文件有点问题,可能版本原因 t.vertices.push(...x(r, e)); //有的文件同一个entity需要多次执行到这里,所以不能直接覆盖,要push t.vertices = t.vertices.filter(e => e.x != void 0); //而且会出现空的vertix:{},所以排除下 break; case 43: 0 !== a.value && (t.width = a.value); break; case 210: t.extrusionDirectionX = a.value; break; case 220: t.extrusionDirectionY = a.value; break; case 230: t.extrusionDirectionZ = a.value; break; default: i(t, a); } a = e.next(); } return t; }, h.ForEntityName = "MTEXT", h.prototype.parseEntity = function (e, a) { var t = { type: a.value }; for (a = e.next(); "EOF" !== a && 0 !== a.code;) { switch (a.code) { case 3: case 1: t.text ? t.text += a.value : t.text = a.value; break; case 10: t.position = c(e); break; case 40: t.height = a.value; break; case 41: t.width = a.value; break; case 50: t.rotation = a.value; break; case 71: t.attachmentPoint = a.value; break; case 72: t.drawingDirection = a.value; break; default: i(t, a); } a = e.next(); } return t; }, g.ForEntityName = "POINT", g.prototype.parseEntity = function (e, a) { var t; for (t = { type: a.value }, a = e.next(); "EOF" !== a && 0 !== a.code;) { switch (a.code) { case 10: t.position = c(e); break; case 39: t.thickness = a.value; break; case 210: t.extrusionDirection = c(e); break; case 100: break; default: i(t, a); } a = e.next(); } return t; }, E.ForEntityName = "VERTEX", E.prototype.parseEntity = function (e, a) { var t = { type: a.value }; for (a = e.next(); "EOF" !== a && 0 !== a.code;) { switch (a.code) { case 10: t.x = a.value; break; case 20: t.y = a.value; break; case 30: t.z = a.value; break; case 40: case 41: case 42: 0 != a.value && (t.bulge = a.value); break; case 70: t.curveFittingVertex = 0 != (1 & a.value), t.curveFitTangent = 0 != (2 & a.value), t.splineVertex = 0 != (8 & a.value), t.splineControlPoint = 0 != (16 & a.value), t.threeDPolylineVertex = 0 != (32 & a.value), t.threeDPolylineMesh = 0 != (64 & a.value), t.polyfaceMeshVertex = 0 != (128 & a.value); break; case 50: case 71: t.faceA = a.value; break; case 72: t.faceB = a.value; break; case 73: t.faceC = a.value; break; case 74: t.faceD = a.value; break; default: i(t, a); } a = e.next(); } return t; }, w.ForEntityName = "POLYLINE", w.prototype.parseEntity = function (e, a) { var t = { type: a.value, vertices: [] }; for (a = e.next(); "EOF" !== a && 0 !== a.code;) { switch (a.code) { case 10: case 20: case 30: case 39: t.thickness = a.value; break; case 40: case 41: break; case 70: t.shape = 0 != (1 & a.value), t.includesCurveFitVertices = 0 != (2 & a.value), t.includesSplineFitVertices = 0 != (4 & a.value), t.is3dPolyline = 0 != (8 & a.value), t.is3dPolygonMesh = 0 != (16 & a.value), t.is3dPolygonMeshClosed = 0 != (32 & a.value), t.isPolyfaceMesh = 0 != (64 & a.value), t.hasContinuousLinetypePattern = 0 != (128 & a.value); break; case 71: case 72: case 73: case 74: case 75: break; case 210: t.extrusionDirection = c(e); break; default: i(t, a); } a = e.next(); } return t.vertices = function (e, a) { var t = new E(), r = []; for (; !e.isEOF();) if (0 === a.code) if ("VERTEX" === a.value) r.push(t.parseEntity(e, a)), a = e.lastReadGroup;else if ("SEQEND" === a.value) { m(e, a); break; } return r; }(e, a), t; }, P.ForEntityName = "SOLID", P.prototype.parseEntity = function (e, a) { var t; for ((t = { type: a.value }).points = [], a = e.next(); "EOF" !== a && 0 !== a.code;) { switch (a.code) { case 10: t.points[0] = c(e); break; case 11: t.points[1] = c(e); break; case 12: t.points[2] = c(e); break; case 13: t.points[3] = c(e); break; case 210: t.extrusionDirection = c(e); break; default: i(t, a); } a = e.next(); } return t; }, F.ForEntityName = "SPLINE", F.prototype.parseEntity = function (e, a) { var t; for (t = { type: a.value }, a = e.next(); "EOF" !== a && 0 !== a.code;) { switch (a.code) { case 10: t.controlPoints || (t.controlPoints = []), t.controlPoints.push(c(e)); break; case 11: t.fitPoints || (t.fitPoints = []), t.fitPoints.push(c(e)); break; case 12: t.startTangent = c(e); break; case 13: t.endTangent = c(e); break; case 40: t.knotValues || (t.knotValues = []), t.knotValues.push(a.value); break; case 70: 0 != (1 & a.value) && (t.closed = !0), 0 != (2 & a.value) && (t.periodic = !0), 0 != (4 & a.value) && (t.rational = !0), 0 != (8 & a.value) && (t.planar = !0), 0 != (16 & a.value) && (t.planar = !0, t.linear = !0); break; case 71: t.degreeOfSplineCurve = a.value; break; case 72: t.numberOfKnots = a.value; break; case 73: t.numberOfControlPoints = a.value; break; case 74: t.numberOfFitPoints = a.value; break; case 210: t.normalVector = c(e); break; default: i(t, a); } a = e.next(); } return t; }, O.ForEntityName = "TEXT", O.prototype.parseEntity = function (e, a) { var t; for (t = { type: a.value }, a = e.next(); "EOF" !== a && 0 !== a.code;) { switch (a.code) { case 10: t.startPoint = c(e); break; case 11: t.endPoint = c(e); break; case 40: t.textHeight = a.value; break; case 41: t.xScale = a.value; break; case 50: t.rotation = a.value; break; case 1: t.text = a.value; break; case 72: t.halign = a.value; break; case 73: t.valign = a.value; break; default: i(t, a); } a = e.next(); } return t; }; var N = t(0); function T() { var e; this._entityHandlers = {}, (e = this).registerEntityHandler(u), e.registerEntityHandler(l), e.registerEntityHandler(v), e.registerEntityHandler(d), e.registerEntityHandler(b), e.registerEntityHandler(p), e.registerEntityHandler(f), e.registerEntityHandler(k), e.registerEntityHandler(y), e.registerEntityHandler(h), e.registerEntityHandler(g), e.registerEntityHandler(w), e.registerEntityHandler(P), e.registerEntityHandler(F), e.registerEntityHandler(O); } function S(e) { N.debug("unhandled group " + L(e)); } function L(e) { return e.code + ":" + e.value; } N.setLevel("error"), T.prototype.parse = function (e, a) { throw new Error("read() not implemented. Use readSync()"); }, T.prototype.registerEntityHandler = function (e) { var a = new e(); this._entityHandlers[e.ForEntityName] = a; }, T.prototype.parseSync = function (e) { return "string" == typeof e ? this._parse(e) : (console.error("Cannot read dxf source of type `" + typeof e), null); }, T.prototype.parseStream = function (e, a) { var t = "", r = this; e.on("data", function (e) { t += e; }), e.on("end", function () { try { var e = r._parse(t); } catch (e) { return a(e); } a(null, e); }), e.on("error", function (e) { a(e); }); }, T.prototype._parse = function (e) { var a, t, n = {}, c = 0, i = e.split(/\r\n|\r|\n/g); if (!(a = new r(i)).hasNext()) throw Error("Empty file"); var u = this, s = function s(e, a) { return t.code === e && t.value === a; }, l = function l() { var e = null, r = null, n = {}; for (t = a.next();;) { if (s(0, "ENDSEC")) { e && (n[e] = r); break; } 9 === t.code ? (e && (n[e] = r), e = t.value) : 10 === t.code ? r = { x: t.value } : 20 === t.code ? r.y = t.value : 30 === t.code ? r.z = t.value : r = t.value, t = a.next(); } return t = a.next(), n; }, v = function v() { var e, r = {}; for (t = a.next(); "EOF" !== t.value && !s(0, "ENDSEC");) s(0, "BLOCK") ? (N.debug("block {"), e = d(), N.debug("}"), x(e), e.name ? r[e.name] = e : N.error('block with handle "' + e.handle + '" is missing a name.')) : (S(t), t = a.next()); return r; }, d = function d() { var e = {}; for (t = a.next(); "EOF" !== t.value;) { switch (t.code) { case 1: e.xrefPath = t.value, t = a.next(); break; case 2: e.name = t.value, t = a.next(); break; case 3: e.name2 = t.value, t = a.next(); break; case 5: e.handle = t.value, t = a.next(); break; case 8: e.layer = t.value, t = a.next(); break; case 10: e.position = y(), t = a.next(); break; case 67: e.paperSpace = !(!t.value || 1 != t.value), t = a.next(); break; case 70: 0 != t.value && (e.type = t.value), t = a.next(); break; case 100: t = a.next(); break; case 330: e.ownerHandle = t.value, t = a.next(); break; case 0: if ("ENDBLK" == t.value) break; e.entities = k(!0); break; default: S(t), t = a.next(); } if (s(0, "ENDBLK")) { t = a.next(); break; } } return e; }, b = function b() { var e = {}; for (t = a.next(); "EOF" !== t.value && !s(0, "ENDSEC");) { s(0, "TABLE") ? (t = a.next(), f[t.value] ? (N.debug(t.value + " Table {"), e[f[t.value].tableName] = p(), N.debug("}")) : N.debug("Unhandled Table " + t.value)) : t = a.next(); } return t = a.next(), e; }; var p = function p() { var e, r = f[t.value], n = {}, o = 0; for (t = a.next(); !s(0, "ENDTAB");) switch (t.code) { case 5: n.handle = t.value, t = a.next(); break; case 330: n.ownerHandle = t.value, t = a.next(); break; case 100: "AcDbSymbolTable" === t.value ? t = a.next() : (S(t), t = a.next()); break; case 70: o = t.value, t = a.next(); break; case 0: t.value === r.dxfSymbolName ? n[r.tableRecordsProperty] = r.parseTableRecords() : (S(t), t = a.next()); break; default: S(t), t = a.next(); } var c = n[r.tableRecordsProperty]; return c && (c.constructor === Array ? e = c.length : "object" == typeof c && (e = Object.keys(c).length), o !== e && N.warn("Parsed " + e + " " + r.dxfSymbolName + "'s but expected " + o)), t = a.next(), n; }, f = { VPORT: { tableRecordsProperty: "viewPorts", tableName: "viewPort", dxfSymbolName: "VPORT", parseTableRecords: function parseTableRecords() { var e = [], r = {}; for (N.debug("ViewPort {"), t = a.next(); !s(0, "ENDTAB");) switch (t.code) { case 2: r.name = t.value, t = a.next(); break; case 10: r.lowerLeftCorner = y(), t = a.next(); break; case 11: r.upperRightCorner = y(), t = a.next(); break; case 12: r.center = y(), t = a.next(); break; case 13: r.snapBasePoint = y(), t = a.next(); break; case 14: r.snapSpacing = y(), t = a.next(); break; case 15: r.gridSpacing = y(), t = a.next(); break; case 16: r.viewDirectionFromTarget = y(), t = a.next(); break; case 17: r.viewTarget = y(), t = a.next(); break; case 42: r.lensLength = t.value, t = a.next(); break; case 43: r.frontClippingPlane = t.value, t = a.next(); break; case 44: r.backClippingPlane = t.value, t = a.next(); break; case 45: r.viewHeight = t.value, t = a.next(); break; case 50: r.snapRotationAngle = t.value, t = a.next(); break; case 51: r.viewTwistAngle = t.value, t = a.next(); break; case 79: r.orthographicType = t.value, t = a.next(); break; case 110: r.ucsOrigin = y(), t = a.next(); break; case 111: r.ucsXAxis = y(), t = a.next(); break; case 112: r.ucsYAxis = y(), t = a.next(); break; case 110: r.ucsOrigin = y(), t = a.next(); break; case 281: r.renderMode = t.value, t = a.next(); break; case 281: r.defaultLightingType = t.value, t = a.next(); break; case 292: r.defaultLightingOn = t.value, t = a.next(); break; case 330: r.ownerHandle = t.value, t = a.next(); break; case 63: case 421: case 431: r.ambientColor = t.value, t = a.next(); break; case 0: "VPORT" === t.value && (N.debug("}"), e.push(r), N.debug("ViewPort {"), r = {}, t = a.next()); break; default: S(t), t = a.next(); } return N.debug("}"), e.push(r), e; } }, LTYPE: { tableRecordsProperty: "lineTypes", tableName: "lineType", dxfSymbolName: "LTYPE", parseTableRecords: function parseTableRecords() { var e, r, n = {}, o = {}; for (N.debug("LType {"), t = a.next(); !s(0, "ENDTAB");) switch (t.code) { case 2: o.name = t.value, e = t.value, t = a.next(); break; case 3: o.description = t.value, t = a.next(); break; case 73: (r = t.value) > 0 && (o.pattern = []), t = a.next(); break; case 40: o.patternLength = t.value, t = a.next(); break; case 49: o.pattern.push(t.value), t = a.next(); break; case 0: N.debug("}"), r > 0 && r !== o.pattern.length && N.warn("lengths do not match on LTYPE pattern"), n[e] = o, o = {}, N.debug("LType {"), t = a.next(); break; default: t = a.next(); } return N.debug("}"), n[e] = o, n; } }, LAYER: { tableRecordsProperty: "layers", tableName: "layer", dxfSymbolName: "LAYER", parseTableRecords: function parseTableRecords() { var e, r, n = {}, c = {}; for (N.debug("Layer {"), t = a.next(); !s(0, "ENDTAB");) switch (t.code) { case 2: c.name = t.value, e = t.value, t = a.next(); break; case 62: c.visible = t.value >= 0, c.colorIndex = Math.abs(t.value), c.color = (r = c.colorIndex, o[r]), t = a.next(); break; case 70: c.frozen = 0 != (1 & t.value) || 0 != (2 & t.value), t = a.next(); break; case 0: "LAYER" === t.value && (N.debug("}"), n[e] = c, N.debug("Layer {"), c = {}, e = void 0, t = a.next()); break; default: S(t), t = a.next(); } return N.debug("}"), n[e] = c, n; } } }, k = function k(e) { var r = [], n = e ? "ENDBLK" : "ENDSEC"; for (e || (t = a.next());;) if (0 === t.code) { if (t.value === n) break; var o, c = u._entityHandlers[t.value]; if (null == c) { N.warn("Unhandled entity " + t.value), t = a.next(); continue; } N.debug(t.value + " {"), o = c.parseEntity(a, t), t = a.lastReadGroup, N.debug("}"), x(o), r.push(o); } else t = a.next(); return "ENDSEC" == n && (t = a.next()), r; }, y = function y() { var e = {}, r = t.code; if (e.x = t.value, r += 10, (t = a.next()).code != r) throw new Error("Expected code for point value to be " + r + " but got " + t.code + "."); return e.y = t.value, r += 10, (t = a.next()).code != r ? (a.rewind(), e) : (e.z = t.value, e); }, x = function x(e) { if (!e) throw new TypeError("entity cannot be undefined or null"); e.handle || (e.handle = c++); }; return function () { for (t = a.next(); !a.isEOF();) if (0 === t.code && "SECTION" === t.value) { if (2 !== (t = a.next()).code) { console.error("Unexpected code %s after 0:SECTION", L(t)), t = a.next(); continue; } "HEADER" === t.value ? (N.debug("> HEADER"), n.header = l(), N.debug("<")) : "BLOCKS" === t.value ? (N.debug("> BLOCKS"), n.blocks = v(), N.debug("<")) : "ENTITIES" === t.value ? (N.debug("> ENTITIES"), n.entities = k(!1), N.debug("<")) : "TABLES" === t.value ? (N.debug("> TABLES"), n.tables = b(), N.debug("<")) : "EOF" === t.value ? N.debug("EOF") : N.warn("Skipping section '%s'", t.value); } else t = a.next(); }(), n; }; a.default = T; }]).default; }); class DxfLoader extends EventDispatcher { constructor() { super(); this.parser = new Potree.DxfParser(); } load(url, done) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; Potree.loadFile(url, { returnText: true }, data => { var dxfJson = this.parser.parseSync(data); console.log(dxfJson); var model = this.createModel(dxfJson, options); done(model); }); } createModel(data) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var root = new Object3D(); var i, entity, obj, min_x, min_y, min_z, max_x, max_y, max_z; /* var dims = { min: { x: false, y: false, z: false}, max: { x: false, y: false, z: false} }; */ //let bound = THREE.Box3 for (i = 0; i < data.entities.length; i++) { entity = data.entities[i]; obj = drawEntity(entity, data, options.unsupportTypes); if (obj) { var bbox = new Box3().setFromObject(obj); /* if (bbox.min.x && ((dims.min.x === false) || (dims.min.x > bbox.min.x))) dims.min.x = bbox.min.x; if (bbox.min.y && ((dims.min.y === false) || (dims.min.y > bbox.min.y))) dims.min.y = bbox.min.y; if (bbox.min.z && ((dims.min.z === false) || (dims.min.z > bbox.min.z))) dims.min.z = bbox.min.z; if (bbox.max.x && ((dims.max.x === false) || (dims.max.x < bbox.max.x))) dims.max.x = bbox.max.x; if (bbox.max.y && ((dims.max.y === false) || (dims.max.y < bbox.max.y))) dims.max.y = bbox.max.y; if (bbox.max.z && ((dims.max.z === false) || (dims.max.z < bbox.max.z))) dims.max.z = bbox.max.z; */ root.add(obj); } obj = null; } return root; } } function drawEntity(entity, data, unsupportTypes, group) { var mesh; if (unsupportTypes && unsupportTypes.includes(entity.type)) { console.warn('����һ��dxf������Ƶ�type��', entity.type); return; //add �����Ƹ��� } if (entity.type === 'CIRCLE' || entity.type === 'ARC') { mesh = drawArc(entity, data, unsupportTypes, group); } else if (entity.type === 'LWPOLYLINE' || entity.type === 'LINE' || entity.type === 'POLYLINE') { mesh = drawLine(entity, data, unsupportTypes, group); } else if (entity.type === 'TEXT') { //"MTEXT" text: "{\fKaiTi|b0|i0|c134|p49;�������̨}" mesh = drawText(entity, data, unsupportTypes, group); } else if (entity.type === 'SOLID') { mesh = drawSolid(entity, data); } else if (entity.type === 'POINT') { mesh = drawPoint(entity, data); } else if (entity.type === 'INSERT') { //Ƕ������group mesh = drawBlock(entity, data, unsupportTypes, group); } else if (entity.type === 'SPLINE') { mesh = drawSpline(entity, data); } else if (entity.type === 'MTEXT') { mesh = drawMtext(entity, data, unsupportTypes, group); } else if (entity.type === 'ELLIPSE') { mesh = drawEllipse(entity, data, unsupportTypes, group); } else if (entity.type === 'DIMENSION') { var dimTypeEnum = entity.dimensionType & 7; if (dimTypeEnum === 0) { mesh = drawDimension(entity, data); } else { console.log("Unsupported Dimension type: " + dimTypeEnum); } } else { console.log("Unsupported Entity Type: " + entity.type); } if (entity.type === 'LWPOLYLINE' || entity.type === 'LINE' || entity.type === 'POLYLINE') { mesh = drawLine(entity, data); } /* if(entity.type === 'INSERT') { mesh = drawBlock(entity, data); //group } */ /* �Ŷ���arc �ƺ�ǽ�ڶ��Dz���insert���ͣ��������� */ mesh && (mesh.dxfInfo = entity); //add return mesh; } function drawEllipse(entity, data) { var color = getColor$2(entity, data); var xrad = Math.sqrt(Math.pow(entity.majorAxisEndPoint.x, 2) + Math.pow(entity.majorAxisEndPoint.y, 2)); var yrad = xrad * entity.axisRatio; var rotation = Math.atan2(entity.majorAxisEndPoint.y, entity.majorAxisEndPoint.x); var curve = new EllipseCurve(entity.center.x, entity.center.y, xrad, yrad, entity.startAngle, entity.endAngle, false, // Always counterclockwise rotation); var points = curve.getPoints(50); var geometry = new BufferGeometry().setFromPoints(points); var material = new LineBasicMaterial({ linewidth: 1, color: color }); // Create the final object to add to the scene var ellipse = new Line(geometry, material); return ellipse; } function drawMtext(entity, data) { var color = getColor$2(entity, data); //if (!font) { return console.log('font parameter not set. Ignoring text entity.')} var geometry = new TextGeometry(entity.text, { //font: font, size: entity.height * (4 / 5), height: 1 }); var material = new MeshBasicMaterial({ color: color }); var text = new Mesh(geometry, material); // Measure what we rendered. var measure = new Box3(); measure.setFromObject(text); var textWidth = measure.max.x - measure.min.x; // If the text ends up being wider than the box, it's supposed // to be multiline. Doing that in threeJS is overkill. if (textWidth > entity.width) { console.log("Can't render this multipline MTEXT entity, sorry.", entity); return undefined; } text.position.z = 0; switch (entity.attachmentPoint) { case 1: // Top Left text.position.x = entity.position.x; text.position.y = entity.position.y - entity.height; break; case 2: // Top Center text.position.x = entity.position.x - textWidth / 2; text.position.y = entity.position.y - entity.height; break; case 3: // Top Right text.position.x = entity.position.x - textWidth; text.position.y = entity.position.y - entity.height; break; case 4: // Middle Left text.position.x = entity.position.x; text.position.y = entity.position.y - entity.height / 2; break; case 5: // Middle Center text.position.x = entity.position.x - textWidth / 2; text.position.y = entity.position.y - entity.height / 2; break; case 6: // Middle Right text.position.x = entity.position.x - textWidth; text.position.y = entity.position.y - entity.height / 2; break; case 7: // Bottom Left text.position.x = entity.position.x; text.position.y = entity.position.y; break; case 8: // Bottom Center text.position.x = entity.position.x - textWidth / 2; text.position.y = entity.position.y; break; case 9: // Bottom Right text.position.x = entity.position.x - textWidth; text.position.y = entity.position.y; break; default: return undefined; } ; return text; } function drawSpline(entity, data) { var color = getColor$2(entity, data); var points = entity.controlPoints.map(function (vec) { return new Vector2(vec.x, vec.y); }); var interpolatedPoints = []; var curve; if (entity.degreeOfSplineCurve === 2 || entity.degreeOfSplineCurve === 3) { for (var i = 0; i + 2 < points.length; i = i + 2) { if (entity.degreeOfSplineCurve === 2) { curve = new QuadraticBezierCurve(points[i], points[i + 1], points[i + 2]); } else { curve = new QuadraticBezierCurve3(points[i], points[i + 1], points[i + 2]); } interpolatedPoints.push.apply(interpolatedPoints, curve.getPoints(50)); } } else { curve = new SplineCurve(points); interpolatedPoints = curve.getPoints(100); } var geometry = new BufferGeometry().setFromPoints(interpolatedPoints); var material = new LineBasicMaterial({ linewidth: 1, color: color }); var splineObject = new Line(geometry, material); return splineObject; } function drawLine(entity, data) { var geometry = new Geometry(), color = getColor$2(entity, data), material, lineType, vertex, startPoint, endPoint, bulgeGeometry, bulge, i, line; if (!entity.vertices) return console.log('entity missing vertices.'); // create geometry for (i = 0; i < entity.vertices.length; i++) { if (entity.vertices[i].bulge) { bulge = entity.vertices[i].bulge; startPoint = entity.vertices[i]; endPoint = i + 1 < entity.vertices.length ? entity.vertices[i + 1] : geometry.vertices[0]; bulgeGeometry = new THREEx.BulgeGeometry(startPoint, endPoint, bulge); geometry.vertices.push.apply(geometry.vertices, bulgeGeometry.vertices); } else { vertex = entity.vertices[i]; geometry.vertices.push(new Vector3(vertex.x, vertex.y, 0)); } } if (entity.shape) geometry.vertices.push(geometry.vertices[0]); // set material if (entity.lineType) { lineType = data.tables.lineType.lineTypes[entity.lineType]; } if (lineType && lineType.pattern && lineType.pattern.length !== 0) { material = new LineDashedMaterial({ color: color, gapSize: 4, dashSize: 4 }); } else { material = new LineBasicMaterial({ linewidth: 1, color: color }); } // if(lineType && lineType.pattern && lineType.pattern.length !== 0) { // geometry.computeLineDistances(); // // Ugly hack to add diffuse to this. Maybe copy the uniforms object so we // // don't add diffuse to a material. // lineType.material.uniforms.diffuse = { type: 'c', value: new THREE.Color(color) }; // material = new THREE.ShaderMaterial({ // uniforms: lineType.material.uniforms, // vertexShader: lineType.material.vertexShader, // fragmentShader: lineType.material.fragmentShader // }); // }else { // material = new THREE.LineBasicMaterial({ linewidth: 1, color: color }); // } line = new Line(geometry, material); return line; } function drawArc(entity, data) { var startAngle, endAngle; if (entity.type === 'CIRCLE') { startAngle = entity.startAngle || 0; endAngle = startAngle + 2 * Math.PI; } else { startAngle = entity.startAngle; endAngle = entity.endAngle; } var curve = new ArcCurve(0, 0, entity.radius, startAngle, endAngle); var points = curve.getPoints(32); var geometry = new BufferGeometry().setFromPoints(points); var material = new LineBasicMaterial({ color: getColor$2(entity, data) }); var arc = new Line(geometry, material); arc.position.x = entity.center.x; arc.position.y = entity.center.y; arc.position.z = entity.center.z; return arc; } function drawSolid(entity, data) { var material, mesh, verts, geometry = new Geometry(); verts = geometry.vertices; verts.push(new Vector3(entity.points[0].x, entity.points[0].y, entity.points[0].z)); verts.push(new Vector3(entity.points[1].x, entity.points[1].y, entity.points[1].z)); verts.push(new Vector3(entity.points[2].x, entity.points[2].y, entity.points[2].z)); verts.push(new Vector3(entity.points[3].x, entity.points[3].y, entity.points[3].z)); // Calculate which direction the points are facing (clockwise or counter-clockwise) var vector1 = new Vector3(); var vector2 = new Vector3(); vector1.subVectors(verts[1], verts[0]); vector2.subVectors(verts[2], verts[0]); vector1.cross(vector2); // If z < 0 then we must draw these in reverse order if (vector1.z < 0) { geometry.faces.push(new Face3(2, 1, 0)); geometry.faces.push(new Face3(2, 3, 1)); } else { geometry.faces.push(new Face3(0, 1, 2)); geometry.faces.push(new Face3(1, 3, 2)); } material = new MeshBasicMaterial({ color: getColor$2(entity, data) }); return new Mesh(geometry, material); } function drawText(entity, data) { var geometry, material, text; //����Ҫfont���ܻ������� /* if(!font) return console.warn('Text is not supported without a Three.js font loaded with THREE.FontLoader! Load a font of your choice and pass this into the constructor. See the sample for this repository or Three.js examples at http://threejs.org/examples/?q=text#webgl_geometry_text for more details.'); */ geometry = new TextGeometry(entity.text, { /* font: font, */height: 0, size: entity.textHeight || 12 }); if (entity.rotation) { var zRotation = entity.rotation * Math.PI / 180; geometry.rotateZ(zRotation); } material = new MeshBasicMaterial({ color: getColor$2(entity, data) }); text = new Mesh(geometry, material); text.position.x = entity.startPoint.x; text.position.y = entity.startPoint.y; text.position.z = entity.startPoint.z; return text; } function drawPoint(entity, data) { var geometry, material, point; geometry = new Geometry(); geometry.vertices.push(new Vector3(entity.position.x, entity.position.y, entity.position.z)); // TODO: could be more efficient. PointCloud per layer? var numPoints = 1; var color = getColor$2(entity, data); var colors = new Float32Array(numPoints * 3); colors[0] = color.r; colors[1] = color.g; colors[2] = color.b; geometry.colors = colors; geometry.computeBoundingBox(); material = new PointsMaterial({ size: 0.05, vertexColors: VertexColors }); point = new Points(geometry, material); //scene.add(point); return point; } function drawDimension(entity, data, unsupportTypes, parentGroup) { return drawBlock(entity, data, unsupportTypes, parentGroup, true); //�� /* var block = data.blocks[entity.block]; if (!block || !block.entities) return null; var group = new THREE.Object3D(); // if(entity.anchorPoint) { // group.position.x = entity.anchorPoint.x; // group.position.y = entity.anchorPoint.y; // group.position.z = entity.anchorPoint.z; // } for(var i = 0; i < block.entities.length; i++) { var childEntity = drawEntity(block.entities[i], data, group); if(childEntity && !group.children.includes(childEntity)) group.add(childEntity); } return group; */ } function drawBlock(entity, data, unsupportTypes, parentGroup, isDimension) { var block = data.blocks[entity.name]; if (!block.entities) return null; var group = new Object3D(); parentGroup && parentGroup.add(group); //��ǰ���� Ϊ�˻��matrixWorld if (!isDimension) { if (entity.position) { group.position.x = entity.position.x; group.position.y = entity.position.y; group.position.z = entity.position.z; } if (entity.xScale) { group.scale.x = entity.xScale; } if (entity.yScale) { group.scale.y = entity.yScale; } if (entity.rotation) { group.rotation.z = entity.rotation * Math.PI / 180; } //add: ���������еĻ������������Զ add zScale var flag; if (entity.zScale != void 0 && entity.extrusionDirection) { //see (005.dxf�� others/01.dxf) extrusionDirection ={x:0,y:0,z:-1} group.position.x *= Math.sign(entity.zScale); group.scale.x *= Math.sign(entity.zScale); group.rotation.z *= Math.sign(entity.zScale); flag = 1; //�����������extrusionDirection } } else { /* if(entity.anchorPoint) { group.position.x = entity.anchorPoint.x; group.position.y = entity.anchorPoint.y; group.position.z = entity.anchorPoint.z; } */ } //add: group.updateMatrixWorld(); var visiEntities = block.entities.filter(e => e.visible !== false); //console.log("block�Ŀɼ�children����"+block.entities.length) for (var i = 0; i < visiEntities.length; i++) { var childEntity = drawEntity(visiEntities[i], data, unsupportTypes, group); if (childEntity && !group.children.includes(childEntity)) group.add(childEntity); } return group; } function getColor$2(entity, data) { var color = 0x000000; //default if (entity.color) color = entity.color;else if (data.tables && data.tables.layer && data.tables.layer.layers[entity.layer]) color = data.tables.layer.layers[entity.layer].color; if (color == null || color === 0xffffff) { color = 0x000000; } return color; } function createLineTypeShaders(data) { var ltype, type; if (!data.tables || !data.tables.lineType) return; var ltypes = data.tables.lineType.lineTypes; for (type in ltypes) { ltype = ltypes[type]; if (!ltype.pattern) continue; ltype.material = createDashedLineShader(ltype.pattern); } } function createDashedLineShader(pattern) { var i, dashedLineShader = {}, totalLength = 0.0; for (i = 0; i < pattern.length; i++) { totalLength += Math.abs(pattern[i]); } dashedLineShader.uniforms = UniformsUtils.merge([UniformsLib['common'], UniformsLib['fog'], { 'pattern': { type: 'fv1', value: pattern }, 'patternLength': { type: 'f', value: totalLength } }]); dashedLineShader.vertexShader = ['attribute float lineDistance;', 'varying float vLineDistance;', ShaderChunk['color_pars_vertex'], 'void main() {', ShaderChunk['color_vertex'], 'vLineDistance = lineDistance;', 'gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'); dashedLineShader.fragmentShader = ['uniform vec3 diffuse;', 'uniform float opacity;', 'uniform float pattern[' + pattern.length + '];', 'uniform float patternLength;', 'varying float vLineDistance;', ShaderChunk['color_pars_fragment'], ShaderChunk['fog_pars_fragment'], 'void main() {', 'float pos = mod(vLineDistance, patternLength);', 'for ( int i = 0; i < ' + pattern.length + '; i++ ) {', 'pos = pos - abs(pattern[i]);', 'if( pos < 0.0 ) {', 'if( pattern[i] > 0.0 ) {', 'gl_FragColor = vec4(1.0, 0.0, 0.0, opacity );', 'break;', '}', 'discard;', '}', '}', ShaderChunk['color_fragment'], ShaderChunk['fog_fragment'], '}'].join('\n'); return dashedLineShader; } function findExtents(scene) { for (var child of scene.children) { var minX, maxX, minY, maxY; if (child.position) { minX = Math.min(child.position.x, minX); minY = Math.min(child.position.y, minY); maxX = Math.max(child.position.x, maxX); maxY = Math.max(child.position.y, maxY); } } return { min: { x: minX, y: minY }, max: { x: maxX, y: maxY } }; } // Three.js extension functions. Webpack doesn't seem to like it if we modify the THREE object directly. var THREEx = { Math: {} }; /** * Returns the angle in radians of the vector (p1,p2). In other words, imagine * putting the base of the vector at coordinates (0,0) and finding the angle * from vector (1,0) to (p1,p2). * @param {Object} p1 start point of the vector * @param {Object} p2 end point of the vector * @return {Number} the angle */ THREEx.Math.angle2 = function (p1, p2) { var v1 = new Vector2(p1.x, p1.y); var v2 = new Vector2(p2.x, p2.y); v2.sub(v1); // sets v2 to be our chord v2.normalize(); if (v2.y < 0) return -Math.acos(v2.x); return Math.acos(v2.x); }; THREEx.Math.polar = function (point, distance, angle) { var result = {}; result.x = point.x + distance * Math.cos(angle); result.y = point.y + distance * Math.sin(angle); return result; }; /** * Calculates points for a curve between two points * @param startPoint - the starting point of the curve * @param endPoint - the ending point of the curve * @param bulge - a value indicating how much to curve * @param segments - number of segments between the two given points */ THREEx.BulgeGeometry = function (startPoint, endPoint, bulge, segments) { var vertex, i, center, p0, p1, angle, radius, startAngle, thetaAngle; Geometry.call(this); this.startPoint = p0 = startPoint ? new Vector2(startPoint.x, startPoint.y) : new Vector2(0, 0); this.endPoint = p1 = endPoint ? new Vector2(endPoint.x, endPoint.y) : new Vector2(1, 0); this.bulge = bulge = bulge || 1; angle = 4 * Math.atan(bulge); radius = p0.distanceTo(p1) / 2 / Math.sin(angle / 2); center = THREEx.Math.polar(startPoint, radius, THREEx.Math.angle2(p0, p1) + (Math.PI / 2 - angle / 2)); this.segments = segments = segments || Math.max(Math.abs(Math.ceil(angle / (Math.PI / 18))), 6); // By default want a segment roughly every 10 degrees startAngle = THREEx.Math.angle2(center, p0); thetaAngle = angle / segments; this.vertices.push(new Vector3(p0.x, p0.y, 0)); for (i = 1; i <= segments - 1; i++) { vertex = THREEx.Math.polar(center, Math.abs(radius), startAngle + thetaAngle * i); this.vertices.push(new Vector3(vertex.x, vertex.y, 0)); } }; THREEx.BulgeGeometry.prototype = Object.create(Geometry.prototype); /* -----note-------------- */ var manager = new LoadingManager(); var loaders = {}; var mapArea; var shelterHistory = []; Potree.isIframeChild = window.parent != window; //子页面 /* if(Potree.isIframeChild){ let rootWin = Common.getRootWindow() rootWin && rootWin.viewer.dispatchEvent({type:'createIframe', window}) //给祖先页面发送信息,得不到可能跨域了或无viewer } */ /* window.addEventListener('focus',()=>{ console.log('focus',window.winIndex) }) window.addEventListener('blur',()=>{ console.log('blur',window.winIndex) }) */ class Viewer$1 extends ViewerBase { constructor(domElement, mapArea_) { var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; super(domElement, $.extend(args, { name: 'mainViewer', antialias: true, preserveDrawingBuffer: true })); //注:viewer因为要分屏,尤其是四屏,preserveDrawingBuffer需要为true, 否则无法局部clear window.viewer = this; mapArea = mapArea_; if (Potree.settings.editType == "pano" || Potree.settings.editType == "merge") { this.modules = { Alignment, SiteModel, volumeComputer: new VolumeComputer() //暂时 }; Potree.settings.useDepthTex = Potree.settings.mergeType2; if (Potree.settings.editType == "pano") { this.modules.PanoEditor = PanoEditor$1; } else if (Potree.settings.editType == "merge") { this.modules.MergeEditor = MergeEditor; this.modules.CamAniEditor = CamAniEditor; } } else { this.modules = { Clip, Alignment, SiteModel, RouteGuider: new RouteGuider(), clipping: new Clipping(), ParticleEditor, CamAniEditor, volumeComputer: new VolumeComputer(), MergeEditor }; } { Potree.timeCollect = { //median预置一个中等值,以防止cpu过低的设备首次卡顿 //depthSampler : {minCount:400, median: 1}, //旧的 实时从图片中获取色值的用时,但是现在直接从data中取 depthSamChangeImg: { minCount: 200, median: 25 } //换图的用时。 需要一开始就start }; for (var i in Potree.timeCollect) { Potree.timeCollect[i].measures = []; Potree.timeCollect[i].sum = 0; } setTimeout(() => { for (var _i in Potree.timeCollect) { Potree.timeCollect[_i].start = true; } /* setTimeout(()=>{ console.log('timeCollect', Potree.timeCollect.depthSampler.median, Potree.timeCollect.depthSampler.ave, Potree.timeCollect.depthSampler.measures.length) },10000) */ }, 2000); } this.navigateMode = 'free'; // 'panorama'; 'free'自由模式是只显示点云或者未进入到漫游点, this.isEdit = true; this.waitQueue = []; this.unitConvert = new UoMService(); this.visible = true; this.fpVisiDatasets = []; this.atDatasets = []; this.objs = new Object3D(), this.objs.name = 'objs'; this.objs.addEventListener('isVisible', () => { this.setAllTilesets(model => model.visiChangeCallback()); }); this.testMaxNodeCount = 0; this.tiles3dVisiVCount = 0; //this.lastPos = new THREE.Vector3(Infinity,Infinity,Infinity) //------------- var supportExtFragDepth = !!Potree.Features.EXT_DEPTH.isSupported(this.renderer.getContext()); //iphoneX居然不支持 //这意味着边缘增强和测量线遮挡失效 if (!supportExtFragDepth) console.error('ExtFragDepth unsupported! 边缘增强和测量线遮挡失效'); this.guiLoaded = false; this.guiLoadTasks = []; this.onVrListeners = []; this.messages = []; this.elMessages = $("\n\t\t
    \n\t\t
    "); $(domElement).append(this.elMessages); this.fakeMeasure = {}; setTimeout(() => { if (!Potree.settings.isWebgl2 && !Potree.browser.urlHasValue('webgl1')) { console.warn('不支持webgl2'); } }, 3000); try { if (!Potree.settings.isOfficial) { // generate missing dom hierarchy if ($(domElement).find('#potree_map').length === 0) { var potreeMap = $("\n
    \n
    \n
    \n
    \n
    \n "); $(domElement).append(potreeMap); } if ($(domElement).find('#potree_description').length === 0) { var potreeDescription = $("
    "); $(domElement).append(potreeDescription); } if ($(domElement).find('#potree_annotations').length === 0) { var potreeAnnotationContainer = $("\n
    "); $(domElement).append(potreeAnnotationContainer); } if ($(domElement).find('#potree_quick_buttons').length === 0) { var _potreeMap = $("\n
    \n
    \n "); $(domElement).append(_potreeMap); } //add { $(domElement).append($("
    ")); if (!mapArea && Potree.settings.editType != 'merge' /* || Potree.settings.showObjectsOnMap */) { mapArea = $("
    "); $(domElement).append(mapArea); mapArea = mapArea[0]; } } /* let domRoot = this.renderer.domElement.parentElement; let elAttach = $(""); elAttach.css({ position : "absolute", right : '10%', bottom: '20px', zIndex: "10000", fontSize:'1em', color:"black", background:'rgba(255,255,255,0.8)', }) let state = false elAttach.on("click", () => { window.buttonFunction && window.buttonFunction() }); domRoot.appendChild(elAttach[0]); */ } this.tiles3dMemoryUsage = 0; this.pointCloudLoadedCallback = args.onPointCloudLoaded || function () {}; // if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) { // defaultSettings.navigation = "Orbit"; // } this.server = null; this.fov = 60; this.isFlipYZ = false; this.useDEMCollisions = false; this.generateDEM = false; this.minNodeSize = 30; //允许加载的node的最小可见像素宽度。越大越省性能 this.edlStrength = 1.0; this.edlRadius = 1.4; this.edlOpacity = 1.0; this.useEDL = false; this.description = ""; this.classifications = ClassificationScheme.DEFAULT; this.moveSpeed = 1; this.lengthUnit = LengthUnits.METER; this.lengthUnitDisplay = LengthUnits.METER; this.showBoundingBox = false; this.showAnnotations = true; this.freeze = false; this.elevationGradientRepeat = ElevationGradientRepeat.CLAMP; this.filterReturnNumberRange = [0, 7]; this.filterNumberOfReturnsRange = [0, 7]; this.filterGPSTimeRange = [-Infinity, Infinity]; this.filterPointSourceIDRange = [0, 65535]; this.potreeRenderer = null; this.edlRenderer = null; this.pRenderer = null; this.scene = null; this.sceneVR = null; this.overlay = null; this.overlayCamera = null; this.inputHandler = null; this.controls = null; this.clippingTool = null; this.transformationTool = null; this.navigationCube = null; this.compass = null; this.skybox = null; this.clock = new Clock(); this.background = null; this.buffers = new Map(); if (args.noDragAndDrop) {} else { this.initDragAndDrop(); } if (typeof Stats !== "undefined") { this.stats = new Stats(); this.stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom document.body.appendChild(this.stats.dom); } { this.overlay = new Scene(); this.overlayCamera = new OrthographicCamera(0, 1, 1, 0, -1000, 1000); } this.pRenderer = new Renderer$1(this.renderer); { var near = 2.5; var far = 10.0; var fov = 90; this.shadowTestCam = new PerspectiveCamera(90, 1, near, far); this.shadowTestCam.position.set(3.50, -2.80, 8.561); this.shadowTestCam.lookAt(new Vector3(0, 0, 4.87)); } var scene = new ExtendScene(this.renderer); { // create VR scene this.sceneVR = new Scene(); // let texture = new THREE.TextureLoader().load(`${Potree.resourcePath}/images/vr_controller_help.jpg`); // let plane = new THREE.PlaneBufferGeometry(1, 1, 1, 1); // let infoMaterial = new THREE.MeshBasicMaterial({map: texture}); // let infoNode = new THREE.Mesh(plane, infoMaterial); // infoNode.position.set(-0.5, 1, 0); // infoNode.scale.set(0.4, 0.3, 1); // infoNode.lookAt(0, 1, 0) // this.sceneVR.add(infoNode); // window.infoNode = infoNode; } this.setScene(scene); //add: for 截图时抗锯齿 { /* this.composer = new EffectComposer( this.renderer ); this.ssaaRenderPass = new SSAARenderPass(0x000000, 0); this.composer.addPass( this.ssaaRenderPass ); */ //this.ssaaRenderPass.useCopy = true //this.ssaaRenderPass.renderToScreen = true; //this.ssaaRenderPass.needsSwap = false //见 https://threejs.org/examples/?q=AA#webgl_postprocessing_fxaa 效果和SSAA差不多,都对透明不太友好。 /* let outlinePass = this.outlinePass = new OutlinePass( ); this.ssaaRenderPass.addPass(outlinePass) */ //ssaa有透明度、发黑的问题所以不用了 //-------------------------- this.composer = new EffectComposer(this.renderer); this.composer.scaleRatio = 4; //将底图和测量线绘制在一张高倍贴图上,for测量线不模糊 this.composer.readTarget = true; //把底图和测量线一起fxaa /* const renderPass = new RenderPass(); //renderPass.clearColor = new THREE.Color( 0,0,0 ); //renderPass.clearAlpha = 0; renderPass.clear = !this.composer.readTarget this.composer.addPass( renderPass ); */ //for 融合页面 var outlinePass = this.outlinePass = new OutlinePass(); outlinePass.renderToScreen = true; //这样更流畅,不用ssaa了,缺点是outline有锯齿 outlinePass.enabled = false; this.composer.addPass(outlinePass); outlinePass.edgeStrength = 4; outlinePass.edgeGlow = 0; outlinePass.visibleEdgeColor = new Color("#09a1b3"); /* this.fxaaPass = new ShaderPass( FXAAShader ); this.fxaaPass.readTarget = true //add this.fxaaPass.setSize = function(width, height){ this.material.uniforms[ 'resolution' ].value.x = 1 / ( width ) ; this.material.uniforms[ 'resolution' ].value.y = 1 / ( height ) ; } this.fxaaPass.renderToScreen = true; this.composer.addPass( this.fxaaPass ); */ //抗锯齿截图 效果时而好时而不好,文字比较模糊 //这两个暂时不能一起用。目前刚好不需要一起用 /* this.images360.fastTranMaskPass = new FastTranPass( this.renderer ) this.composer.addPass(this.images360.fastTranMaskPass)//add */ } { this.mainViewport = new Viewport(this.scene.view, this.scene.cameraP, { left: 0, bottom: 0, width: 1, height: 1, name: 'MainView' }); this.viewports = [this.mainViewport]; Potree.settings.showCompass && (this.compass = new Compass(Potree.settings.compassDom, this.mainViewport)); //this.axis = new AxisViewer(this.mainViewport, this.renderArea ) this.magnifier = new Magnifier(this); this.reticule = new Reticule(this); this.scene.scene.add(this.magnifier); this.scene.scene.add(this.reticule); if (Potree.settings.editType != "pano" && Potree.settings.editType != 'merge' /* || Potree.settings.showObjectsOnMap */) { this.mapViewer = new MapViewer(mapArea /* $('#mapGaode')[0] */); } this.inputHandler = new InputHandler(this, this.scene.scene); this.inputHandler.containsMouse = true; //初始化,使键盘事件在mainViewer有效 //this.inputHandler.setScene(this.scene); //this.inputHandler.addInputListener(this);//add this.clippingTool = new ClippingTool(this); this.transformationTool = new TransformationTool(this); this.navigationCube = new NavigationCube(this); this.navigationCube.visible = false; this.createControls(); this.clippingTool.setScene(this.scene); var onPointcloudAdded = e => { if (this.scene.pointclouds.length === 1) { var speed = e.pointcloud.boundingBox.getSize(new Vector3()).length(); speed = speed / 2000; this.setMoveSpeed(speed); } }; var onVolumeRemoved = e => { this.inputHandler.deselect(e.volume); }; this.addEventListener('scene_changed', e => { this.inputHandler.setScene(e.scene); this.clippingTool.setScene(this.scene); if (!e.scene.hasEventListener("pointcloud_added", onPointcloudAdded)) { e.scene.addEventListener("pointcloud_added", onPointcloudAdded); } if (!e.scene.hasEventListener("volume_removed", onPointcloudAdded)) { e.scene.addEventListener("volume_removed", onVolumeRemoved); } }); this.scene.addEventListener("volume_removed", onVolumeRemoved); this.scene.addEventListener('pointcloud_added', onPointcloudAdded); } { // set defaults this.setFOV(60); this.setEDLEnabled(false); this.setEDLRadius(3); this.setEDLStrength(0.01); this.setEDLOpacity(1.0); this.setPointBudget(1 * 1000 * 1000); this.setShowBoundingBox(false); this.setFreeze(false); this.setControls(this.fpControls /* orbitControls */); this.setBackground(new Color(Potree.config.background), 1 /* 'gradient' */); this.scaleFactor = 1; this.loadSettingsFromURL(); } // start rendering! //if(args.useDefaultRenderLoop === undefined || args.useDefaultRenderLoop === true){ //requestAnimationFrame(this.loop.bind(this)); //} this.renderer.setAnimationLoop(this.loop.bind(this)); this.loadGUI = this.loadGUI.bind(this); this.annotationTool = new AnnotationTool(this); this.measuringTool = new MeasuringTool(this); //this.profileTool = new ProfileTool(this); this.volumeTool = new VolumeTool(this); this.tagTool = new TagTool(this); //----------- CursorDeal.init(this, this.mapViewer ? [this, this.mapViewer] : [this]); //ADD if (Potree.settings.editType == "pano") { this.modules.PanoEditor.init(); } else if (Potree.settings.editType == "merge") { this.modules.MergeEditor.init(); } else { this.modules.SiteModel.init(); this.modules.ParticleEditor.init(); } this.modules.Alignment.init(); this.images360 = new Images360(this); this.scene.scene.add(this.objs); loaders = { objLoader: new OBJLoader(manager), mtlLoader: new MTLLoader(manager), glbLoader: new GLTFLoader(undefined, this.renderer, Potree.settings.libsUrl), plyLoader: new PLYLoader(manager), dxfLoader: new DxfLoader(), shapeLoader: new Potree.ShapefileLoader() }; //add test /* const environment = new RoomEnvironment(); const pmremGenerator = new THREE.PMREMGenerator( this.renderer ); this.scene.scene.environment = pmremGenerator.fromScene( environment ).texture; */ //----------- this.modules.volumeComputer && this.modules.volumeComputer.init(); } catch (e) { this.onCrash(e); } //-----------------------add---------------------------------------------------- /* { let ratio this.addEventListener('resize',(e)=>{ if(ratio != e.deviceRatio){ //因为devicePixelRatio会影响到点云大小,所以改变时计算下点云大小 viewer.scene.pointclouds.forEach(p => { p.changePointSize() }) } ratio = e.deviceRatio }) } */ { var pointDensity = ''; Object.defineProperty(Potree.settings, "pointDensity", { get: function get() { return pointDensity; }, set: density => { if (density) { var config = Potree.config.pointDensity[density]; var pointBudget = config.pointBudget; if (density == 'magnifier') { //尽可能不变pointBudget,否则点云可能会闪烁,因点云被释放又加载,如SS-t-7DUfWAUZ3V pointBudget = Math.max(Potree.pointBudget, Potree.config.pointDensity['magnifier'].pointBudget); } else if (this.magnifier.visible) { //放大镜打开时要保证最低点云数量(全景模式没点) pointBudget = Math.max(pointBudget, Potree.config.pointDensity['magnifier'].pointBudget); } viewer.setMinNodeSize(config.minNodeSize || Potree.config.minNodeSize); viewer.setPointBudget(pointBudget); pointDensity = density; this.setPointLevels(); this.dispatchEvent('pointDensityChanged'); } } }); var UserPointDensity = ''; Object.defineProperty(Potree.settings, "UserPointDensity", { get: function get() { return UserPointDensity; }, set: density => { if (UserPointDensity != density) { if (Potree.settings.displayMode == 'showPointCloud' && this.viewports.length != 4) { //漫游模式和四屏时都有自己的pointDensity Potree.settings.pointDensity = density; } UserPointDensity = density; this.dispatchEvent('UserPointDensityChanged'); } } }); } { var cameraFar = Potree.settings.cameraFar; Object.defineProperty(Potree.settings, "cameraFar", { get: function get() { return cameraFar; }, set: far => { if (far != cameraFar) { if (Potree.settings.displayMode != 'showPanos' && !this.fixCamFar) { this.mainViewport.camera.far = far; this.mainViewport.camera.updateProjectionMatrix(); } cameraFar = far; } } }); } /* this.reticule.addEventListener('update',(e)=>{ this.needRender = true if(this.mapViewer && this.mapViewer.attachedToViewer)this.mapViewer.needRender = true //分屏时mapViewer也有reticule }) */ this.reticule.addEventListener('update', e => { this.reticule.hoverViewport && (this.reticule.hoverViewport.needRender = true); this.lazyRenderViewports(); if (this.mapViewer && this.mapViewer.attachedToViewer && (this.mapViewer.viewports[0].needRender || this.needRender)) this.mapViewer.needRender = true; //分屏时mapViewer也有reticule }); this.addEventListener('pointcloud_changed', e => { if (this.screenshoting) { this.viewports.filter(e => !e.noPointcloud).forEach(e => e.needRender = true); } else this.lazyRenderViewports(); }); this.addEventListener('allLoaded', () => { setTimeout(this.testPointcloudsMaxLevel.bind(this), 1000); //延迟一丢丢,等画面出现 this.scene.pointclouds.forEach(pointcloud => { pointcloud.addEventListener('isVisible', e => { //是否显示该点的mesh(不显示也能走) //console.log('pointcloud isVisible', this.id, e.visible) if (e.reason != 'displayMode' && e.reason != 'overlinePass') { this.updateModelBound('visibleChanged'); } this.dispatchEvent('pointcloud_changed'); }); pointcloud.material.addEventListener('material_property_changed', () => { this.dispatchEvent('pointcloud_changed'); }); }); window.addEventListener('unfocusPage', e => { console.log('unfocusPage', document.title); this.setDisplay(false); }); window.addEventListener('focusPage', e => { console.log('focusPage', document.title); this.setDisplay(true); }); }); if (Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge' || Potree.settings.mergeType2) { var updated, zoomLevel; var update = e => { if (e.type == 'updateModelBound' || e.viewport == this.mainViewport && (e.changeInfo.positionChanged || zoomLevel != this.images360.zoomLevel)) { zoomLevel = this.images360.zoomLevel; //对updateMarkerVisibles有影响 //e.changeInfo.positionChanged && shelterHistory.clear() //清空 (e.type == 'updateModelBound' || e.changeInfo.positionChanged) && this.updateDatasetAt(); //更新所在数据集 if (Potree.settings.ifShowMarker) { Common.intervalTool.isWaiting('updateMarkerVisibles', () => { if (!this.mainViewport.view.isFlying()) { this.updateMarkerVisibles(); } }, 500); } } }; this.addEventListener('camera_changed', update); this.addEventListener('updateModelBound', update); this.addEventListener('showMarkerChanged', () => { this.updatePanosVisibles(this.modules.SiteModel.currentFloor); this.updateMarkerVisibles(); }); /* if(!Potree.Features.EXT_DEPTH.isSupported()){ this.images360.addEventListener('endChangeMode',(e)=>{ if(e.mode == 'showPanos'){ this.updateMarkerVisibles() } }) */ this.images360.addEventListener('getNeighbourAuto', e => { if ( /* Potree.settings.displayMode == 'showPanos' && */e.panos.includes(this.images360.currentPano)) { Common.intervalTool.isWaiting('updateMarkerVisibles', () => { this.updateMarkerVisibles(); }, 500); } }); /* } */ } if (Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge') { this.addEventListener('switchFloorplanSelect', e => { //进入平面图设置后 切换选中的数据集 this.selectedFloorplan = e.pointcloud; //绝对显示 this.updateFpVisiDatasets(); var pointclouds; if (e.pointcloud) { pointclouds = [e.pointcloud]; } else if (this.fpVisiDatasets.length) { pointclouds = this.fpVisiDatasets; } pointclouds && this.mapViewer.fitToDatasets(pointclouds); }); this.modules.SiteModel.bus.addEventListener('FloorChange', e => { this.updateFpVisiDatasets(); this.updatePanosVisibles(e.currentFloor); //问:编辑空间模型时,需不需要改为显示当前选择的楼层。因为若所在楼层和选中的不一致,修改选中楼层的轮廓却改不了marker显示很奇怪,尤其刚好在一个建筑内时。 }); this.mapViewer.mapLayer.addEventListener('floorplanLoaded', () => { this.updateCadVisibles(this.fpVisiDatasets, true); //加载完成后重新更新下 }); /* this.modules.Clip.bus.addEventListener('updateSelectedDatasets',()=>{ this.updateFpVisiDatasets() }) */ } { var interval; document.addEventListener('visibilitychange', e => { var v = !document.hidden; //console.warn('visibilitychange', v ) this.dispatchEvent({ type: 'pageVisible', v }); if (this.screenshoting && !v) { //截图过程中离开页面需要照常loop。但是尽量别离开页面,效果只能达到90% interval = setInterval(() => { //console.log('force loop', Date.now()) if (this.screenshoting) { //截图完成时如果还没回来就不loop this.loop(Date.now()); } }, 50); //实际>1000, 浏览器会放慢定时器,放慢多少不确定 } else if (v && interval) { clearInterval(interval); } }); } /* if(!Potree.isIframeChild){ window.winIndex = 0; let index = 1; this.addEventListener('createIframe',(e)=>{//创建了子页面 let child = e.window; child.winIndex = index ++; }) //不知道删除iframe时是否那些模型还在内存里,需要释放吗? 如果要需要加一个事件 } */ /* { let setInteract = ()=>{ this.interacted = true //标记这一帧用户有操作屏幕 } this.addEventListener('global_mousedown', setInteract) this.addEventListener('global_touchmove', setInteract) this.addEventListener('global_mousewheel', setInteract) } {//针对数据集偏离中心很远后产生的精度损失而抖动 this.addEventListener('camera_changed', e => { if(e.viewport == this.mainViewport && (e.changeInfo.positionChanged)){ if(Potree.settings.editType != 'merge' && Potree.settings.editType != 'pano'){ if(!this.mainViewport.view.isFlying() ){ let pos = this.mainViewport.view.position.clone() // this.mainViewport.camera.getWorldPosition(new THREE.Vector3) if(pos.lengthSq() > 25000000){ Common.intervalTool.isWaiting('moveWorldCenter', ()=>{ pos = this.mainViewport.view.position.clone() this.mainViewport.view.translateWorld(-pos.x, -pos.y, -pos.z) this.scene.scene.position.sub(pos) console.log('变位置', pos) this.scene.pointclouds.forEach(cloud=>{ Alignment.setMatrix(cloud) }) },500) } } } } }) }*/ } lazyRenderViewports(updateCount) { //本来要写this.needRender = true的, 但在分四个屏时防止太卡而排队render var viewports = this.viewports; if (viewports.length == 1 || this.needRender) { return this.needRender = true; } var maxWaitTime = 200; var now = Date.now(); var maxRenderCount = 1; viewports.forEach(e => { if (now - e.lastRenderTime > maxWaitTime) { e.needRender = true; } }); var renderCount = viewports.filter(e => e.needRender).length; //console.log('renderCount', renderCount) var list = viewports.filter(e => !e.needRender).sort((a, b) => a.lastRenderTime - b.lastRenderTime); //没有准备render的,按上次渲染时间排序,作为候补 if (renderCount < maxRenderCount) { //还有名额,补齐 list.slice(0, maxRenderCount - renderCount).forEach(e => { e.needRender = true; }); } else if (list[0] && now - list[0].lastRenderTime > maxWaitTime) { //名额不足时,考虑候补队列第一个是否超时,超时的话也渲染 list[0].needRender = true; } } ifPointBlockedByIntersect(point, panoId, soon) { //点是否被遮挡 var ifShelter; var now = Date.now(); var extraPanoId = panoId != void 0; if (!this.shelterCount) return; var history = shelterHistory.find(e => e.point.equals(point)); var cameraPos = this.mainViewport.view.position.clone(); if (panoId == void 0) { if (this.images360.isAtPano(0.05)) { panoId = this.images360.currentPano.id; } } if (history) { if (panoId != void 0) { ifShelter = history.panos[panoId]; } else { if (history.notAtPano.cameraPos && history.notAtPano.cameraPos.equals(cameraPos)) { ifShelter = history.notAtPano.ifShelter; } } var index = shelterHistory.indexOf(history); //先取出,稍后放回 shelterHistory.splice(index, 1); } else { //新增 history = { point, panos: {}, notAtPano: {} }; var minCount = 100; if (shelterHistory.length > minCount) { //去除最早的 var old; while (old = shelterHistory[0], now - old.lastTime > 1000) { //因为不知热点个数,所以需要加上时间限制,超过时间才能删。 if (old == history || shelterHistory.length == minCount) break; shelterHistory.splice(0, 1); //console.log('delete') } } } if (ifShelter == void 0) { delete history.waitCompute; if (this.mainViewport.view.isFlying()) { return useLastResult(); } if (panoId != void 0) { var pano = this.images360.getPano(panoId); if ((soon || this.shelterCount.byTex < this.shelterCount.maxByTex) && pano.depthTex) { ifShelter = !!viewer.inputHandler.ifBlockedByIntersect({ point, margin: Potree.config.shelterMargin, useDepthTex: true, pano, viewport: this.mainViewport }); history.panos[panoId] = ifShelter; this.shelterCount.byTex++; //console.log('computeByTex direct', panoId, point, ifShelter) } else { //console.log('延迟tex',panoId, point ) history.waitCompute = { panoId, forceGet: extraPanoId }; return useLastResult(); } } else { if ( /* history.ifShelter == void 0 || */this.shelterCount.byCloud < this.shelterCount.maxByCloud) { //弊端:第一个总是直接计算,后面的都是延后。但无法改进,因是一个个传进来的,无法预测。 ifShelter = !!viewer.inputHandler.ifBlockedByIntersect({ point, margin: Potree.config.shelterMargin, pickWindowSize: 3 }); history.notAtPano = { cameraPos, ifShelter }; this.shelterCount.byCloud++; //console.log('computeByCloud direct', point.toArray()) } else { //console.log('延迟cloud' ) history.waitCompute = { cameraPos }; return useLastResult(); } } } history.ifShelter = ifShelter; history.lastTime = now; shelterHistory.push(history); //最新使用的保持在最后一个,使队列按照从旧到新排列 function useLastResult() { //暂时先用上一次的值 shelterHistory.push(history); history.lastTime = now; return history.ifShelter; } return ifShelter; } computeShelter() { //先算用深度图的,然后再点云; //let depthTiming = Potree.timeCollect.depthSampler.median var byTex = 0, byCloud = 0; var len = shelterHistory.length; var waitCloud = []; var maxTexCount = Common.getBestCount('shelterMaxDepthSample', 1, 50, 1, 13 /* ,true */); for (var i = len - 1; i >= 0; i--) { var history = shelterHistory[i]; if (history.waitCompute) { if (history.waitCompute.panoId != void 0) { if (!history.waitCompute.forceGet && (history.waitCompute.panoId != this.images360.currentPano.id || !this.images360.isAtPano(0.1))) { delete history.waitCompute; //取消计算 } else { if (this.images360.currentPano.depthTex) { if (byTex >= maxTexCount) break; byTex++; var ifShelter = !!viewer.inputHandler.ifBlockedByIntersect({ point: history.point, margin: Potree.config.shelterMargin, useDepthTex: true, viewport: this.mainViewport }); history.panos[this.images360.currentPano.id] = ifShelter; history.ifShelter = ifShelter; delete history.waitCompute; //console.log('补1', history.point.toArray()) } else { if (this.images360.currentPano.pointcloud.hasDepthTex) { //先等待加载完深度图 } else { waitCloud.push(history); } } } } else { waitCloud.push(history); } } } var maxCloudCount; if (byTex < maxTexCount && waitCloud.length) { maxCloudCount = this.lastFrameChanged ? Common.getBestCount('shelterMaxCloud', 0, 2, 4, 8 /* ,true */) : 5; var waitCloud2 = []; if (maxCloudCount) { for (var _i2 = 0; _i2 < waitCloud.length; _i2++) { var _history = waitCloud[_i2]; if (_history.waitCompute.cameraPos) { if (!viewer.mainViewport.view.position.equals(_history.waitCompute.cameraPos)) { delete _history.waitCompute; //console.log('delete history.waitCompute', history) continue; //取消计算 } else { waitCloud2.push(_history); } } else { waitCloud2.push(_history); } } var list = waitCloud2.map(e => e.point); var result = Common.batchHandling.getSlice('shelterByCloud', list, { maxUseCount: maxCloudCount, useEquals: true, stopWhenAllUsed: true }); //iphonex稳定后大概在7-10。 //list.length>0 && console.log('list',list, maxCloudCount) result.list.forEach(e => { var history = waitCloud2.find(a => a.point.equals(e)); var ifShelter = !!viewer.inputHandler.ifBlockedByIntersect({ point: history.point, margin: Potree.config.shelterMargin, pickWindowSize: 3, viewport: this.mainViewport }); if (history.waitCompute.cameraPos) { history.notAtPano = { cameraPos: history.waitCompute.cameraPos, ifShelter }; } else { history.panos[this.images360.currentPano.id] = ifShelter; } history.ifShelter = ifShelter; byCloud++; //console.log('补2', history.point.toArray()) delete history.waitCompute; }); } } if (byTex || byCloud) { //console.log('shelterComputed',byTex,byCloud, maxTexCount, maxCloudCount) Common.intervalTool.isWaiting('shelterComputed', () => { //console.log('shelterComputed update') this.dispatchEvent('shelterComputed'); }, 340); } } updateDatasetAt(force) { //更新所在数据集 var fun = () => { var currPos = viewer.mainViewport.view.position; //if(force || !currPos.equals(this.lastPos)){ //this.lastPos.copy(currPos) var at = this.scene.pointclouds.filter(e => (e.visible || e.unvisibleReasons && e.unvisibleReasons.length == 1 && e.unvisibleReasons[0].reason == 'displayMode') && e.ifContainsPoint(currPos)); if (Common.getDifferenceSet(at, this.atDatasets).length) { //console.log('atDatasets', at) this.atDatasets = at; if (Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge') { this.updateFpVisiDatasets(); if (!viewer.modules.SiteModel.currentFloor) { this.updatePanosVisibles(); //所在数据集的点位显示 } } this.dispatchEvent({ type: 'pointcloudAtChange', pointclouds: at }); } force = false; }; //} if (force) fun();else Common.intervalTool.isWaiting('atWhichDataset', fun, 300); } updatePanosVisibles(currentFloor) { //显示当前楼层的所有panos if (!Potree.settings.ifShowMarker) return; var inEntity = currentFloor; //console.error('updatePanosVisibles', currentFloor) viewer.images360.panos.forEach(pano => { var visible = inEntity ? inEntity.panos.includes(pano) : this.atDatasets.some(e => e.panos.includes(pano)); Potree.Utils.updateVisible(pano, 'buildingChange', visible, 2); }); this.dispatchEvent('content_changed'); } //注:非official的没有获取sitemodel的信息所以不执行楼层判断,marker显示不对是正常的 /* 2023.11.24 针对部分场景的楼层很矮,很容易就到楼层外了,且不能修改楼高。如SG-t-9NdCpxrUPLL#/,采取如下措施: 1 如果不在任何一楼层,但在某个数据集中,就显示该数据集所有的marker 2 如果当前楼层无,则显示上一次的currentFloor的marker (目前先使用方案1) */ updateMarkerVisibles() { //限制显示的marker个数,因镜头内marker多的时候可能会卡 if (!Potree.settings.ifShowMarker) return; var minRadius = 8 * this.images360.zoomLevel, //当视线垂直于marker时的最小可见距离,此范围内可见的pano绝对可见 maxRadius = 50 * this.images360.zoomLevel, //当视线垂直于marker时的最大可见距离,此范围外绝对不可见 hopeCount = browser.isMobile() ? 8 : 15; //期望达到的真实可见的marker数 var sheltered = pano => { if ( /* Potree.settings.displayMode == 'showPanos' && !Potree.Features.EXT_DEPTH.isSupported() && */this.images360.isAtPano() && !this.mainViewport.view.isFlying()) { return !this.images360.currentPano.neighbours.includes(pano) && this.images360.currentPano != pano; //起初因不支持EXT_DEPTH时无法用depthTex遮住marker, 后为了减少绘制,都判断 } }; var panoMap = new Map(); //先记录想要设置为可见的 var set = () => { //最后确定设置 var count = 0; viewer.images360.panos.forEach(pano => { var v = panoMap.get(pano).visible; v && count++; Potree.Utils.updateVisible(pano.marker, 'limitMarkerShow', v); }); //console.log('updateMarkerVisibles marker显示个数', count) this.dispatchEvent('content_changed'); }; var isWithinDis = (pano, maxDis) => { //是否marker到相机的距离 没有超出可视距离。可视距离考虑上倾斜角,倾斜越大可视距离越短 var camPos = viewer.mainViewport.camera.position; var o = panoMap.get(pano); o.dis = o.dis || camPos.distanceTo(pano.marker.position); o.sin = o.sin || Math.sqrt(Math.abs(camPos.z - pano.marker.position.z) / o.dis); //和地面夹角的sin。 按公式是不加Math.sqrt的,但是这样大马路上在贴近地面时算出的个数非常少,所以增大点…… return o.dis < maxDis * o.sin; }; viewer.images360.panos.forEach(pano => { //minRadius内的记录为可见 var o = {}; panoMap.set(pano, o); if (pano.visible && !sheltered(pano) && isWithinDis(pano, minRadius)) { o.visible = true; } }); //不超过hopeCount的话,可以直接确定设置 if (viewer.images360.panos.filter(pano => panoMap.get(pano).visible).length >= hopeCount) return set(); //距离超过maxRadius就绝对不可见 var insideOutCirle = viewer.images360.panos.filter(pano => pano.visible && !sheltered(pano) && isWithinDis(pano, maxRadius)); if (insideOutCirle.length <= hopeCount) { insideOutCirle.forEach(pano => panoMap.get(pano).visible = true); return set(); } //数量超过hopeCount时,根据距离排序 insideOutCirle.sort((a, b) => { return panoMap.get(a).dis - panoMap.get(b).dis; }); var slice = insideOutCirle.slice(0, hopeCount); slice.forEach(pano => panoMap.get(pano).visible = true); set(); } updateFpVisiDatasets() { var Clip = this.modules.Clip; var SiteModel = this.modules.SiteModel; var Alignment = this.modules.Alignment; var currentFloor = SiteModel.currentFloor; /* if(Clip.editing){//下载页面已经改为和普通时一样,根据位置判断 this.updateCadVisibles(Clip.selectedDatasets) }else */ if (this.selectedFloorplan) { //平面图设置中 或 地理设置 var pointclouds = [this.selectedFloorplan]; this.updateCadVisibles(pointclouds); } else if (SiteModel.editing || Alignment.editing) { //只显示勾选的,也就是显示的点云的 var _pointclouds = this.scene.pointclouds.filter(p => Potree.Utils.getObjVisiByReason(p, 'datasetSelection')); this.updateCadVisibles(_pointclouds); //this.updatePanosVisibles(currentFloor/* , pointclouds */) } else { var _pointclouds2 = currentFloor ? this.findPointcloudsAtFloor(currentFloor) : []; if (_pointclouds2.length == 0) { if (this.focusDatasets) { _pointclouds2 = this.focusDatasets; } } if (_pointclouds2.length == 0) { //如果当前不在任何楼层或楼层中无数据集,就用当前所在数据集 _pointclouds2 = this.atDatasets; } this.updateCadVisibles(_pointclouds2); //this.updatePanosVisibles(currentFloor/* , pointclouds */) } } /* findPointcloudsAtFloor(entity){//找当前楼层需要显示哪些数据集。 //数据集的belongToEntity 在这个entity内(否则会出现点击数据集飞过去平面图却不显示)。or 如果数据集有漫游点的话,需要包含>20%的漫游点。 (防止重叠体积很大但其实一个漫游点都不包含) //重叠体积>50% 或 包含>50%的漫游点 const ratio1 = 0.2, ratio2 = 0.5, ratio3 = 0.95 var lowScores = [] var pointclouds = viewer.scene.pointclouds.filter(e=>{ let score = 0 if(e.belongToEntity && (e.belongToEntity == entity || e.belongToEntity.buildParent == entity)){//条件1 若该数据集挂载到该楼层 或 该数据集挂载到的房间属于该楼层(这样能显示该层所有房间) return true } if(e.panos.length){//条件2 var insidePanos = e.panos.filter(a=>entity.ifContainsPoint(a.position)); let panoCountRatio = insidePanos.length / e.panos.length if(panoCountRatio > ratio2)return true score += panoCountRatio } //条件3 let volume = entity.intersectPointcloudVolume(e); let volumeRatio = volume / entity.getVolume(true) //注:hole加入计算 if(volumeRatio > ratio3){ //ratio3要高一些,因为点云bounding可能很大,包含很多无点云的空间。即使整个数据集包含entity都不一定看起来在数据集中。(千万要防止两层楼都显示了) return true }else{ score += volumeRatio } lowScores.push({score, pointcloud:e}) }) if(pointclouds.length == 0){//从低分项挑一个出来。 lowScores.sort((a,b)=>{return a.score - b.score}) if(lowScores[0].score > 0.4){ pointclouds = [lowScores[0].pointcloud] } } return pointclouds } */ findPointcloudsAtFloor(entity) { //找当前楼层需要显示哪些数据集。 //数据集的belongToEntity 在这个entity内(否则会出现点击数据集飞过去平面图却不显示)。or 如果数据集有漫游点的话,需要包含>20%的漫游点。 (防止重叠体积很大但其实一个漫游点都不包含) //重叠体积>50% 或 包含>50%的漫游点 var ratio1 = 0.2, ratio2 = 0.5, ratio3 = 0.95; var lowScores = []; var pointclouds = viewer.scene.pointclouds.filter(e => { var score = 0; if (e.belongToEntity && (e.belongToEntity == entity || e.belongToEntity.buildParent == entity)) { //条件1 若该数据集挂载到该楼层 或 该数据集挂载到的房间属于该楼层(这样能显示该层所有房间) return true; } if (e.panos.length) { //条件2 var insidePanos = e.panos.filter(a => entity.ifContainsPoint(a.position)); var panoCountRatio = insidePanos.length / e.panos.length; if (panoCountRatio > ratio2) return true; score += panoCountRatio * 2; } //条件3 var coverHeightRatio = entity.coverPointcloudHeight(e, true); //重叠高度占楼层高度的比率。 if (coverHeightRatio < 0.2) return; var { toEntity, toPointcloud } = entity.intersectPointcloudArea(e, true); //重叠面积占比 var coverAreaRatio = Math.max(toEntity, toPointcloud); //占数据集俯视面积的比率 和 占楼层的面积比率,挑一个大的。 (有的数据集被划分多个楼层,所以每层都应该显示该数据集的图。还有的数据集比较大,可能包含多个建筑,则看占楼层面积) if (coverAreaRatio < 0.2) return; score += coverAreaRatio * coverHeightRatio; lowScores.push({ score, pointcloud: e }); }); /* if(pointclouds.length == 0){//从低分项挑一个出来。 lowScores.sort((a,b)=>{return a.score - b.score}) if(lowScores[0].score > 0.4){ pointclouds = [lowScores[0].pointcloud] } } */ lowScores.forEach(e => { //一个楼层里可以包含许多个数据集 调试SG-t-ds27ym7xzjJ if (e.score > 0.5) { pointclouds.push(e.pointcloud); } }); return pointclouds; } updateCadVisibles(visiClouds, force) { //console.log('visiClouds',visiClouds) var oldVisi = this.fpVisiDatasets; var visiClouds = this.fpVisiDatasets = visiClouds; if (!force) { var difference = Common.getDifferenceSet(oldVisi, visiClouds); if (difference.length == 0) return; } //console.log('visiClouds',visiClouds.map(e=>e.name)) viewer.scene.pointclouds.forEach(pointcloud => { var floorplan = viewer.mapViewer.mapLayer.getFloorplan(pointcloud.dataset_id); var visi = visiClouds.includes(pointcloud); if (floorplan) { Potree.Utils.updateVisible(floorplan.objectGroup, 'buildingChange', visi); } /* else if(!visi){ let changeVisi = (e)=>{ Potree.Utils.updateVisible(e.floorplan.objectGroup, 'buildingChange', this.fpVisiDatasets.includes(pointcloud)) viewer.mapViewer.mapLayer.removeEventListener('floorplanLoaded', changeVisi) console.log('updateCadVisibles加载后更改显示',e) } viewer.mapViewer.mapLayer.addEventListener('floorplanLoaded', changeVisi) } */ //已经添加了全局的 floorplanLoaded后会updateCadVisibles,这段就删了 }); viewer.mapViewer.mapLayer.needUpdate = true; //可能需要更新加载的level程度 viewer.mapViewer.needRender = true; //若上句不触发加载也要立即重新绘制 } //促使点云加载出最高级别 testPointcloudsMaxLevel() { var _this = this; //所有点云都无需testMaxNodeLevel 就停止 var camera_changed, count = 0; var _test = function test() { var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; camera_changed = true; var camera = e.camera || _this.scene.getActiveCamera(); Common.intervalTool.isWaiting('testPointcloudsMaxLevel', () => { if (!camera_changed && count > 50 || Potree.settings.displayMode == 'showPanos' || _this.pauseTestMaxLevel) return; //只有当camera_changed后才继续循环, 除了最开始几次需要连续加载下 camera_changed = false; count++; //console.log('testPointcloudsMaxLevel中', camera.type /* count */) var oldCount = _this.testMaxNodeCount; var success = true; viewer.scene.pointclouds.forEach(e => { var wait = e.testMaxNodeLevel(camera); if (wait) { success = false; } }); /* if(oldCount<=Potree.config.testNodeCount1 && this.testMaxNodeCount>Potree.config.testNodeCount1 ){//差不多等当前所在数据集nodeMaxLevel加载出来 viewer.scene.pointclouds.forEach(e=>{e.changePointSize()}) //重新更新一下大小。因之前用的是nodeMaxLevelPredict (防止刚开始因nodeMaxLevel没涨完,导致过大的点云突然出现 } */ if (!success) return true; //没有全部加载完,继续循环 else { _this.removeEventListener('camera_changed', _test); console.log('testPointcloudsMaxLevel结束'); } }, count < 10 ? 250 : 500); }; this.addEventListener('camera_changed', _test); _test(); /* 检验: viewer.scene.pointclouds.sort((a,b)=>a.nodeMaxLevelPredict.min - b.nodeMaxLevelPredict.min).forEach(e=>console.log(e.nodeMaxLevel, e.nodeMaxLevelPredict.min)) */ } setPointLevels() { this.scene.pointclouds.forEach(e => { e.setPointLevel(); }); } onCrash(error) { console.error(error); $(this.renderArea).empty(); if ($(this.renderArea).find('#potree_failpage').length === 0) { var elFailPage = $("\n\t\t\t
    \n\t\t\t\t\n\t\t\t\t

    Potree Encountered An Error

    \n\n\t\t\t\t

    \n\t\t\t\tThis may happen if your browser or graphics card is not supported.\n\t\t\t\t
    \n\t\t\t\tWe recommend to use \n\t\t\t\tChrome\n\t\t\t\tor \n\t\t\t\tFirefox.\n\t\t\t\t

    \n\n\t\t\t\t

    \n\t\t\t\tPlease also visit webglreport.com and \n\t\t\t\tcheck whether your system supports WebGL.\n\t\t\t\t

    \n\t\t\t\t

    \n\t\t\t\tIf you are already using one of the recommended browsers and WebGL is enabled, \n\t\t\t\tconsider filing an issue report at github,
    \n\t\t\t\tincluding your operating system, graphics card, browser and browser version, as well as the \n\t\t\t\terror message below.
    \n\t\t\t\tPlease do not report errors on unsupported browsers.\n\t\t\t\t

    \n\n\t\t\t\t
    \n\t\t\t\t\n\t\t\t
    "); var elErrorMessage = elFailPage.find('#potree_error_console'); elErrorMessage.html(error.stack); $(this.renderArea).append(elFailPage); } throw error; } // ------------------------------------------------------------------------------------ // Viewer API // ------------------------------------------------------------------------------------ setScene(scene) { if (scene === this.scene) { return; } var oldScene = this.scene; this.scene = scene; this.dispatchEvent({ type: 'scene_changed', oldScene: oldScene, scene: scene }); { // Annotations $('.annotation').detach(); // for(let annotation of this.scene.annotations){ // this.renderArea.appendChild(annotation.domElement[0]); // } this.scene.annotations.traverse(annotation => { this.renderArea.appendChild(annotation.domElement[0]); }); if (!this.onAnnotationAdded) { this.onAnnotationAdded = e => { // console.log("annotation added: " + e.annotation.title); e.annotation.traverse(node => { $("#potree_annotation_container").append(node.domElement); //this.renderArea.appendChild(node.domElement[0]); node.scene = this.scene; }); }; } if (oldScene) { oldScene.annotations.removeEventListener('annotation_added', this.onAnnotationAdded); } this.scene.annotations.addEventListener('annotation_added', this.onAnnotationAdded); } } setControls(controls /* , setSpeed */) { if (controls !== this.controls) { if (this.controls) { this.controls.setEnable(false); //this.inputHandler.removeInputListener(this.controls); this.controls.moveSpeed = this.moveSpeed; //记录 (因为orbit的radius很大,转为firstPerson时要缩小) } this.controls = controls; controls.moveSpeed && this.setMoveSpeed(controls.moveSpeed); //add this.controls.setEnable(true); //this.inputHandler.addInputListener(this.controls); } } getControls() { if (this.renderer.xr.isPresenting) { return this.vrControls; } else { return this.controls; } } getMinNodeSize() { return this.minNodeSize; } setMinNodeSize(value) { if (this.minNodeSize !== value) { this.minNodeSize = value; this.dispatchEvent({ 'type': 'minnodesize_changed', 'viewer': this }); } } getBackground() { return this.background; } setBackground(bg, src) { /* if (this.background === bg ) { return; } */ if (bg === "skybox") { if (!src) src = Potree.resourcePath + '/textures/skybox/xingkong.jpg'; this.skybox = Utils.loadSkybox(src, this.skybox, () => { this.background = bg; }); } else { this.background = bg; } this.backgroundOpacity = 1; //add this.dispatchEvent({ 'type': 'background_changed', 'viewer': this }); } setDescription(value) { this.description = value; $('#potree_description').html(value); //$('#potree_description').text(value); } getDescription() { return this.description; } setShowBoundingBox(value) { if (this.showBoundingBox !== value) { this.showBoundingBox = value; this.dispatchEvent({ 'type': 'show_boundingbox_changed', 'viewer': this }); } } getShowBoundingBox() { return this.showBoundingBox; } setMoveSpeed(value) { if (this.getMoveSpeed() !== value) { this.mainViewport.setMoveSpeed(value); this.dispatchEvent({ 'type': 'move_speed_changed', 'viewer': this, 'speed': value }); } } getMoveSpeed() { return this.mainViewport.moveSpeed; } setWeightClassification(w) { for (var i = 0; i < this.scene.pointclouds.length; i++) { this.scene.pointclouds[i].material.weightClassification = w; this.dispatchEvent({ 'type': 'attribute_weights_changed' + i, 'viewer': this }); } } setFreeze(value) { value = Boolean(value); if (this.freeze !== value) { this.freeze = value; this.dispatchEvent({ 'type': 'freeze_changed', 'viewer': this }); } } getFreeze() { return this.freeze; } setElevationGradientRepeat(value) { if (this.elevationGradientRepeat !== value) { this.elevationGradientRepeat = value; this.dispatchEvent({ type: "elevation_gradient_repeat_changed", viewer: this }); } } setPointBudget(value) { //pointBudget: 每次刷新显示点数量的最大值。 缓存中的点数量也跟此有关,但大于这个数值。 if (Potree.pointBudget !== value && value) { Potree.pointBudget = parseInt(value); this.dispatchEvent({ 'type': 'point_budget_changed', 'viewer': this }); } } getPointBudget() { return Potree.pointBudget; } setShowAnnotations(value) { if (this.showAnnotations !== value) { this.showAnnotations = value; this.dispatchEvent({ 'type': 'show_annotations_changed', 'viewer': this }); } } getShowAnnotations() { return this.showAnnotations; } setDEMCollisionsEnabled(value) { if (this.useDEMCollisions !== value) { this.useDEMCollisions = value; this.dispatchEvent({ 'type': 'use_demcollisions_changed', 'viewer': this }); } ; } getDEMCollisionsEnabled() { return this.useDEMCollisions; } setEDLEnabled(value) { value = Boolean(value) && Features.SHADER_EDL.isSupported(); if (this.useEDL !== value) { this.useEDL = value; this.dispatchEvent({ 'type': 'use_edl_changed', 'viewer': this }); this.dispatchEvent('pointcloud_changed'); } } getEDLEnabled() { return this.useEDL; } setEDLRadius(value) { if (this.edlRadius !== value) { this.edlRadius = value; this.dispatchEvent({ 'type': 'edl_radius_changed', 'viewer': this }); this.dispatchEvent('pointcloud_changed'); } } getEDLRadius() { return this.edlRadius; } setEDLStrength(value) { if (this.edlStrength !== value) { this.edlStrength = value; this.dispatchEvent({ 'type': 'edl_strength_changed', 'viewer': this }); this.dispatchEvent('pointcloud_changed'); } } getEDLStrength() { return this.edlStrength; } setEDLOpacity(value) { if (this.edlOpacity !== value) { this.edlOpacity = value; this.dispatchEvent({ 'type': 'edl_opacity_changed', 'viewer': this }); this.dispatchEvent('pointcloud_changed'); } } getEDLOpacity() { return this.edlOpacity; } setFOV(value) { if (this.fov !== value) { var oldFov = this.fov; this.fov = value; this.scene.cameraP.fov = this.fov; //add this.scene.cameraP.updateProjectionMatrix(); //add this.dispatchEvent({ 'type': 'fov_changed', 'viewer': this, oldFov, fov: this.fov }); } } getFOV() { return this.fov; } disableAnnotations() { this.scene.annotations.traverse(annotation => { annotation.domElement.css('pointer-events', 'none'); // return annotation.visible; }); } enableAnnotations() { this.scene.annotations.traverse(annotation => { annotation.domElement.css('pointer-events', 'auto'); // return annotation.visible; }); } setClassifications(classifications) { this.classifications = classifications; this.dispatchEvent({ 'type': 'classifications_changed', 'viewer': this }); } setClassificationVisibility(key, value) { if (!this.classifications[key]) { this.classifications[key] = { visible: value, name: 'no name' }; this.dispatchEvent({ 'type': 'classification_visibility_changed', 'viewer': this }); } else if (this.classifications[key].visible !== value) { this.classifications[key].visible = value; this.dispatchEvent({ 'type': 'classification_visibility_changed', 'viewer': this }); } } toggleAllClassificationsVisibility() { var numVisible = 0; var numItems = 0; for (var key of Object.keys(this.classifications)) { if (this.classifications[key].visible) { numVisible++; } numItems++; } var visible = true; if (numVisible === numItems) { visible = false; } var somethingChanged = false; for (var _key of Object.keys(this.classifications)) { if (this.classifications[_key].visible !== visible) { this.classifications[_key].visible = visible; somethingChanged = true; } } if (somethingChanged) { this.dispatchEvent({ 'type': 'classification_visibility_changed', 'viewer': this }); } } setFilterReturnNumberRange(from, to) { this.filterReturnNumberRange = [from, to]; this.dispatchEvent({ 'type': 'filter_return_number_range_changed', 'viewer': this }); } setFilterNumberOfReturnsRange(from, to) { this.filterNumberOfReturnsRange = [from, to]; this.dispatchEvent({ 'type': 'filter_number_of_returns_range_changed', 'viewer': this }); } setFilterGPSTimeRange(from, to) { this.filterGPSTimeRange = [from, to]; this.dispatchEvent({ 'type': 'filter_gps_time_range_changed', 'viewer': this }); } setFilterPointSourceIDRange(from, to) { this.filterPointSourceIDRange = [from, to]; this.dispatchEvent({ 'type': 'filter_point_source_id_range_changed', 'viewer': this }); } setLengthUnit(value) { switch (value) { case 'm': this.lengthUnit = LengthUnits.METER; this.lengthUnitDisplay = LengthUnits.METER; break; case 'ft': this.lengthUnit = LengthUnits.FEET; this.lengthUnitDisplay = LengthUnits.FEET; break; case 'in': this.lengthUnit = LengthUnits.INCH; this.lengthUnitDisplay = LengthUnits.INCH; break; } this.dispatchEvent({ 'type': 'length_unit_changed', 'viewer': this, value: value }); } setLengthUnitAndDisplayUnit(lengthUnitValue, lengthUnitDisplayValue) { switch (lengthUnitValue) { case 'm': this.lengthUnit = LengthUnits.METER; break; case 'ft': this.lengthUnit = LengthUnits.FEET; break; case 'in': this.lengthUnit = LengthUnits.INCH; break; } switch (lengthUnitDisplayValue) { case 'm': this.lengthUnitDisplay = LengthUnits.METER; break; case 'ft': this.lengthUnitDisplay = LengthUnits.FEET; break; case 'in': this.lengthUnitDisplay = LengthUnits.INCH; break; } this.dispatchEvent({ 'type': 'length_unit_changed', 'viewer': this, value: lengthUnitValue }); } zoomTo(node, factor) { var animationDuration = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var view = this.mainViewport.view; var camera = this.scene.cameraP.clone(); camera.rotation.copy(this.scene.cameraP.rotation); camera.rotation.order = "ZXY"; camera.rotation.x = Math.PI / 2 + view.pitch; camera.rotation.z = view.yaw; camera.updateMatrix(); camera.updateMatrixWorld(); camera.zoomTo(node, factor); var bs; if (node.boundingSphere) { bs = node.boundingSphere; } else if (node.geometry && node.geometry.boundingSphere) { bs = node.geometry.boundingSphere; } else { bs = node.boundingBox.getBoundingSphere(new Sphere()); } bs = bs.clone().applyMatrix4(node.matrixWorld); var startPosition = view.position.clone(); var endPosition = camera.position.clone(); var startTarget = view.getPivot(); var endTarget = bs.center; var startRadius = view.radius; var endRadius = endPosition.distanceTo(endTarget); var easing = TWEEN.Easing.Quartic.Out; { // animate camera position var pos = startPosition.clone(); var tween = new TWEEN.Tween(pos).to(endPosition, animationDuration); tween.easing(easing); tween.onUpdate(() => { view.position.copy(pos); }); tween.start(); } { // animate camera target var target = startTarget.clone(); var _tween = new TWEEN.Tween(target).to(endTarget, animationDuration); _tween.easing(easing); _tween.onUpdate(() => { view.lookAt(target); }); _tween.onComplete(() => { view.lookAt(target); this.dispatchEvent({ type: 'focusing_finished', target: this }); }); this.dispatchEvent({ type: 'focusing_started', target: this }); _tween.start(); } } moveToGpsTimeVicinity(time) { var result = Potree.Utils.findClosestGpsTime(time, viewer); var box = result.node.pointcloud.deepestNodeAt(result.position).getBoundingBox(); var diameter = box.min.distanceTo(box.max); var camera = this.scene.getActiveCamera(); var offset = camera.getWorldDirection(new Vector3()).multiplyScalar(diameter); var newCamPos = result.position.clone().sub(offset); this.scene.view.position.copy(newCamPos); this.scene.view.lookAt(result.position); } showAbout() { $(function () { $('#about-panel').dialog(); }); } getGpsTimeExtent() { var range = [Infinity, -Infinity]; for (var pointcloud of this.scene.pointclouds) { var attributes = pointcloud.pcoGeometry.pointAttributes.attributes; var aGpsTime = attributes.find(a => a.name === "gps-time"); if (aGpsTime) { range[0] = Math.min(range[0], aGpsTime.range[0]); range[1] = Math.max(range[1], aGpsTime.range[1]); } } return range; } fitToScreen() { var factor = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; var animationDuration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var box = this.getBoundingBox(this.scene.pointclouds); var node = new Object3D(); node.boundingBox = box; this.zoomTo(node, factor, animationDuration); this.controls.stop(); } toggleNavigationCube() { this.navigationCube.visible = !this.navigationCube.visible; /* this.viewports.push({ name:'navigationCube', left:0, bottom:0, width:0.2, }) */ } /* setView(pos, view) { if(!pos) return; switch(pos) { case "F": this.setFrontView(view); break; case "B": this.setBackView(view); break; case "L": this.setLeftView(view); break; case "R": this.setRightView(view); break; case "U": this.setTopView(view); break; case "D": this.setBottomView(view); break; } } */ setTopView(view) { view = view || this.scene.view; view.setCubeView("top"); this.fitToScreen(); } setBottomView() { this.scene.view.yaw = -Math.PI; this.scene.view.pitch = Math.PI / 2; this.fitToScreen(); } setFrontView(view) { view = view || this.scene.view; view.yaw = 0; view.pitch = 0; this.fitToScreen(); } setBackView(view) { view = view || this.scene.view; view.yaw = Math.PI; view.pitch = 0; this.fitToScreen(); } setLeftView() { this.scene.view.yaw = -Math.PI / 2; this.scene.view.pitch = 0; this.fitToScreen(); } setRightView() { this.scene.view.yaw = Math.PI / 2; this.scene.view.pitch = 0; this.fitToScreen(); } flipYZ() { this.isFlipYZ = !this.isFlipYZ; // TODO flipyz console.log('TODO'); } setCameraMode(mode) { this.scene.cameraMode = mode; viewer.mainViewport.camera = mode == CameraMode.PERSPECTIVE ? this.scene.cameraP : this.scene.cameraO; //改 for (var pointcloud of this.scene.pointclouds) { pointcloud.material.useOrthographicCamera = mode == CameraMode.ORTHOGRAPHIC; } } getProjection() { var pointcloud = this.scene.pointclouds[0]; if (pointcloud) { return pointcloud.projection; } else { return null; } } async loadProject(url, done) { var response = await fetch(url); if (response.ok) { var text = await response.text(); var json = JSON5.parse(text); // const json = JSON.parse(text); if (json.type === "Potree") { Potree.loadProject(viewer, json, done); } } else { console.warn("未能加载:" + url); } } saveProject() { return Potree.saveProject(this); } loadSettingsFromURL() { if (Utils.getParameterByName("pointSize")) { this.setPointSize(parseFloat(Utils.getParameterByName("pointSize"))); } if (Utils.getParameterByName("FOV")) { this.setFOV(parseFloat(Utils.getParameterByName("FOV"))); } if (Utils.getParameterByName("opacity")) { this.setOpacity(parseFloat(Utils.getParameterByName("opacity"))); } if (Utils.getParameterByName("edlEnabled")) { var enabled = Utils.getParameterByName("edlEnabled") === "true"; this.setEDLEnabled(enabled); } if (Utils.getParameterByName('edlRadius')) { this.setEDLRadius(parseFloat(Utils.getParameterByName('edlRadius'))); } if (Utils.getParameterByName('edlStrength')) { this.setEDLStrength(parseFloat(Utils.getParameterByName('edlStrength'))); } if (Utils.getParameterByName('pointBudget')) { this.setPointBudget(parseFloat(Utils.getParameterByName('pointBudget'))); } if (Utils.getParameterByName('showBoundingBox')) { var _enabled = Utils.getParameterByName('showBoundingBox') === 'true'; if (_enabled) { this.setShowBoundingBox(true); } else { this.setShowBoundingBox(false); } } if (Utils.getParameterByName('material')) { var material = Utils.getParameterByName('material'); this.setMaterial(material); } if (Utils.getParameterByName('pointSizing')) { var sizing = Utils.getParameterByName('pointSizing'); this.setPointSizing(sizing); } if (Utils.getParameterByName('quality')) { var quality = Utils.getParameterByName('quality'); this.setQuality(quality); } if (Utils.getParameterByName('position')) { var value = Utils.getParameterByName('position'); value = value.replace('[', '').replace(']', ''); var tokens = value.split(';'); var x = parseFloat(tokens[0]); var y = parseFloat(tokens[1]); var z = parseFloat(tokens[2]); this.scene.view.position.set(x, y, z); } if (Utils.getParameterByName('target')) { var _value = Utils.getParameterByName('target'); _value = _value.replace('[', '').replace(']', ''); var _tokens = _value.split(';'); var _x = parseFloat(_tokens[0]); var _y = parseFloat(_tokens[1]); var _z = parseFloat(_tokens[2]); this.scene.view.lookAt(new Vector3(_x, _y, _z)); } if (Utils.getParameterByName('background')) { var _value2 = Utils.getParameterByName('background'); this.setBackground(_value2); } // if(Utils.getParameterByName("elevationRange")){ // let value = Utils.getParameterByName("elevationRange"); // value = value.replace("[", "").replace("]", ""); // let tokens = value.split(";"); // let x = parseFloat(tokens[0]); // let y = parseFloat(tokens[1]); // // this.setElevationRange(x, y); // //this.scene.view.target.set(x, y, z); // } } // ------------------------------------------------------------------------------------ // Viewer Internals // ------------------------------------------------------------------------------------ createControls() { { // create FIRST PERSON CONTROLS this.fpControls = new FirstPersonControls(this, this.mainViewport); this.fpControls.enabled = false; this.fpControls.addEventListener('start', this.disableAnnotations.bind(this)); this.fpControls.addEventListener('end', this.enableAnnotations.bind(this)); /* this.addEventListener("loadPointCloudDone", ()=>{ let boundPlane = new THREE.Box3() boundPlane.expandByPoint(this.bound.boundingBox.min.clone())//最低高度为bound的最低 boundPlane.expandByPoint(this.bound.boundingBox.max.clone().setZ(this.bound.center.z))//最高高度为bound的中心高度 FirstPersonControls.boundPlane = boundPlane FirstPersonControls.standardSpeed = THREE.Math.clamp( Math.sqrt(this.bound.boundSize.length() )/ 100 , 0.02,0.5); //在这个boundPlane中的速度 }) */ } // { // create GEO CONTROLS // this.geoControls = new GeoControls(this.scene.camera, this.renderer.domElement); // this.geoControls.enabled = false; // this.geoControls.addEventListener("start", this.disableAnnotations.bind(this)); // this.geoControls.addEventListener("end", this.enableAnnotations.bind(this)); // this.geoControls.addEventListener("move_speed_changed", (event) => { // this.setMoveSpeed(this.geoControls.moveSpeed); // }); // } { // create ORBIT CONTROLS this.orbitControls = new OrbitControls$1(this); this.orbitControls.enabled = false; this.orbitControls.addEventListener('start', this.disableAnnotations.bind(this)); this.orbitControls.addEventListener('end', this.enableAnnotations.bind(this)); } /* { // create EARTH CONTROLS this.earthControls = new EarthControls(this); this.earthControls.enabled = false; this.earthControls.addEventListener('start', this.disableAnnotations.bind(this)); this.earthControls.addEventListener('end', this.enableAnnotations.bind(this)); } { // create DEVICE ORIENTATION CONTROLS this.deviceControls = new DeviceOrientationControls(this); this.deviceControls.enabled = false; this.deviceControls.addEventListener('start', this.disableAnnotations.bind(this)); this.deviceControls.addEventListener('end', this.enableAnnotations.bind(this)); } */ /* { // create VR CONTROLS this.vrControls = new VRControls(this); this.vrControls.enabled = false; this.vrControls.addEventListener('start', this.disableAnnotations.bind(this)); this.vrControls.addEventListener('end', this.enableAnnotations.bind(this)); } */ } toggleSidebar() { var renderArea = $('#potree_render_area'); var isVisible = renderArea.css('left') !== '0px'; if (isVisible) { renderArea.css('left', '0px'); } else { renderArea.css('left', '300px'); } } toggleMap() { // let map = $('#potree_map'); // map.toggle(100); if (this.mapView) { this.mapView.toggle(); } } onGUILoaded(callback) { if (this.guiLoaded) { callback(); } else { this.guiLoadTasks.push(callback); } } promiseGuiLoaded() { return new Promise(resolve => { if (this.guiLoaded) { resolve(); } else { this.guiLoadTasks.push(resolve); } }); } loadGUI(callback) { if (callback) { this.onGUILoaded(callback); } var viewer = this; var sidebarContainer = $('#potree_sidebar_container'); sidebarContainer.load(new URL(Potree.scriptPath + '/' + (Potree.settings.sidebar || 'sidebar1.html')).href, () => { sidebarContainer.css('width', '300px'); sidebarContainer.css('height', '100%'); var imgMenuToggle = document.createElement('img'); imgMenuToggle.src = new URL(Potree.resourcePath + '/icons/menu_button.svg').href; imgMenuToggle.onclick = this.toggleSidebar; imgMenuToggle.classList.add('potree_menu_toggle'); var imgMapToggle = document.createElement('img'); imgMapToggle.src = new URL(Potree.resourcePath + '/icons/map_icon.png').href; imgMapToggle.style.display = 'none'; imgMapToggle.onclick = e => { this.toggleMap(); }; imgMapToggle.id = 'potree_map_toggle'; var elButtons = $("#potree_quick_buttons").get(0); elButtons.append(imgMenuToggle); elButtons.append(imgMapToggle); VRButton$1.createButton(this.renderer).then(vrButton => { if (vrButton == null) { console.log("VR not supported or active."); return; } this.renderer.xr.enabled = true; var element = vrButton.element; element.style.position = ""; element.style.bottom = ""; element.style.left = ""; element.style.margin = "4px"; element.style.fontSize = "100%"; element.style.width = "2.5em"; element.style.height = "2.5em"; element.style.padding = "0"; element.style.textShadow = "black 2px 2px 2px"; element.style.display = "block"; elButtons.append(element); vrButton.onStart(() => { this.dispatchEvent({ type: "vr_start" }); }); vrButton.onEnd(() => { this.dispatchEvent({ type: "vr_end" }); }); }); /* this.mapView = new MapView(this); this.mapView.init(); */ i18n.init({ lng: 'en', resGetPath: Potree.resourcePath + '/lang/__lng__/__ns__.json', preload: ['en', 'fr', 'de', 'jp', 'se', 'es', 'zh'], getAsync: true, debug: false }, function (t) { // Start translation once everything is loaded $('body').i18n(); }); $(() => { //initSidebar(this); var sidebar = new Sidebar(this); sidebar.init(); this.sidebar = sidebar; //if (callback) { // $(callback); //} var elProfile = $('
    ').load(new URL(Potree.scriptPath + '/profile.html').href, () => { $(document.body).append(elProfile.children()); this.profileWindow = new ProfileWindow(this); this.profileWindowController = new ProfileWindowController(this); $('#profile_window').draggable({ handle: $('#profile_titlebar'), containment: $(document.body) }); $('#profile_window').resizable({ containment: $(document.body), handles: 'n, e, s, w' }); $(() => { this.guiLoaded = true; for (var task of this.guiLoadTasks) { task(); } }); }); }); }); return this.promiseGuiLoaded(); } setLanguage(lang) { i18n.setLng(lang); $('body').i18n(); } setServer(server) { this.server = server; } initDragAndDrop() { function allowDrag(e) { e.dataTransfer.dropEffect = 'copy'; e.preventDefault(); } var dropHandler = async event => { console.log(event); event.preventDefault(); for (var item of event.dataTransfer.items) { console.log(item); if (item.kind !== "file") { continue; } var file = item.getAsFile(); var isJson = file.name.toLowerCase().endsWith(".json"); var isGeoPackage = file.name.toLowerCase().endsWith(".gpkg"); if (isJson) { try { var text = await file.text(); var json = JSON.parse(text); if (json.type === "Potree") { Potree.loadProject(viewer, json); } } catch (e) { console.error("failed to parse the dropped file as JSON"); console.error(e); } } else if (isGeoPackage) { var hasPointcloud = viewer.scene.pointclouds.length > 0; if (!hasPointcloud) { var msg = "At least one point cloud is needed that specifies the "; msg += "coordinate reference system before loading vector data."; console.error(msg); } else { proj4.defs("WGS84", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"); proj4.defs("pointcloud", this.getProjection()); var transform = proj4("WGS84", "pointcloud"); var buffer = await file.arrayBuffer(); var params = { transform: transform, source: file.name }; var geo = await Potree.GeoPackageLoader.loadBuffer(buffer, params); viewer.scene.addGeopackage(geo); } } } }; $("body")[0].addEventListener("dragenter", allowDrag); $("body")[0].addEventListener("dragover", allowDrag); $("body")[0].addEventListener("drop", dropHandler); } updateAnnotations() { if (!this.visibleAnnotations) { this.visibleAnnotations = new Set(); } this.scene.annotations.updateBounds(); this.scene.cameraP.updateMatrixWorld(); this.scene.cameraO.updateMatrixWorld(); var distances = []; var renderAreaSize = this.renderer.getSize(new Vector2()); var viewer = this; var visibleNow = []; this.scene.annotations.traverse(annotation => { if (annotation === this.scene.annotations) { return true; } if (!annotation.visible) { return false; } annotation.scene = this.scene; var element = annotation.domElement; var position = annotation.position.clone(); position.add(annotation.offset); if (!position) { position = annotation.boundingBox.getCenter(new Vector3()); } var distance = viewer.scene.cameraP.position.distanceTo(position); var radius = annotation.boundingBox.getBoundingSphere(new Sphere()).radius; var screenPos = new Vector3(); var screenSize = 0; { // SCREEN POS screenPos.copy(position).project(this.scene.getActiveCamera()); screenPos.x = renderAreaSize.x * (screenPos.x + 1) / 2; screenPos.y = renderAreaSize.y * (1 - (screenPos.y + 1) / 2); // SCREEN SIZE if (viewer.scene.cameraMode == CameraMode.PERSPECTIVE) { var fov = Math.PI * viewer.scene.cameraP.fov / 180; var slope = Math.tan(fov / 2.0); var projFactor = 0.5 * renderAreaSize.y / (slope * distance); screenSize = radius * projFactor; } else { screenSize = Utils.projectedRadiusOrtho(radius, viewer.scene.cameraO.projectionMatrix, renderAreaSize.x, renderAreaSize.y); } } element.css("left", screenPos.x + "px"); element.css("top", screenPos.y + "px"); //element.css("display", "block"); var zIndex = 10000000 - distance * (10000000 / this.scene.cameraP.far); if (annotation.descriptionVisible) { zIndex += 10000000; } element.css("z-index", parseInt(zIndex)); if (annotation.children.length > 0) { var expand = screenSize > annotation.collapseThreshold || annotation.boundingBox.containsPoint(this.scene.getActiveCamera().position); annotation.expand = expand; if (!expand) { //annotation.display = (screenPos.z >= -1 && screenPos.z <= 1); var inFrustum = screenPos.z >= -1 && screenPos.z <= 1; if (inFrustum) { visibleNow.push(annotation); } } return expand; } else { //annotation.display = (screenPos.z >= -1 && screenPos.z <= 1); var _inFrustum = screenPos.z >= -1 && screenPos.z <= 1; if (_inFrustum) { visibleNow.push(annotation); } } }); var notVisibleAnymore = new Set(this.visibleAnnotations); for (var annotation of visibleNow) { annotation.display = true; notVisibleAnymore.delete(annotation); } this.visibleAnnotations = visibleNow; for (var _annotation of notVisibleAnymore) { _annotation.display = false; } } updateMaterialDefaults(pointcloud) { // PROBLEM STATEMENT: // * [min, max] of intensity, source id, etc. are computed as point clouds are loaded // * the point cloud material won't know the range it should use until some data is loaded // * users can modify the range at runtime, but sensible default ranges should be // applied even if no GUI is present // * display ranges shouldn't suddenly change even if the actual range changes over time. // e.g. the root node has intensity range [1, 478]. One of the descendants increases range to // [0, 2047]. We should not automatically change to the new range because that would result // in sudden and drastic changes of brightness. We should adjust the min/max of the sidebar slider. var material = pointcloud.material; var attIntensity = pointcloud.getAttribute("intensity"); if (attIntensity != null && material.intensityRange[0] === Infinity) { material.intensityRange = [...attIntensity.range]; } // const attIntensity = pointcloud.getAttribute("intensity"); // if(attIntensity && material.intensityRange[0] === Infinity){ // material.intensityRange = [...attIntensity.range]; // } // let attributes = pointcloud.getAttributes(); // for(let attribute of attributes.attributes){ // if(attribute.range){ // let range = [...attribute.range]; // material.computedRange.set(attribute.name, range); // //material.setRange(attribute.name, range); // } // } } update(delta, timestamp) { viewer.addTimeMark('update', 'start'); TWEEN.update(timestamp); transitions$1.update(delta); //写在开头,因为这时候最为固定,计时准确 this.dispatchEvent({ type: 'update_start', delta: delta, timestamp: timestamp }); this.updateScreenSize(); //判断是否改变canvas大小 var scene = this.scene; var camera = scene.getActiveCamera(); var visiblePointClouds = this.scene.pointclouds.filter(pc => pc.visible); Potree.pointLoadLimit = Potree.pointBudget * 2; /* const lTarget = camera.position.clone().add(camera.getWorldDirection(new THREE.Vector3()).multiplyScalar(1000)); this.scene.directionalLight.position.copy(camera.position); this.scene.directionalLight.lookAt(lTarget); */ for (var pointcloud of visiblePointClouds) { pointcloud.showBoundingBox = this.showBoundingBox; pointcloud.generateDEM = this.generateDEM; pointcloud.minimumNodePixelSize = this.minNodeSize; var material = pointcloud.material; material.uniforms.uFilterReturnNumberRange.value = this.filterReturnNumberRange; material.uniforms.uFilterNumberOfReturnsRange.value = this.filterNumberOfReturnsRange; material.uniforms.uFilterGPSTimeClipRange.value = this.filterGPSTimeRange; material.uniforms.uFilterPointSourceIDClipRange.value = this.filterPointSourceIDRange; material.classification = this.classifications; material.recomputeClassification(); this.updateMaterialDefaults(pointcloud); } { if (this.showBoundingBox) { var bbRoot = this.scene.scene.getObjectByName("potree_bounding_box_root"); if (!bbRoot) { var node = new Object3D(); node.name = "potree_bounding_box_root"; this.scene.scene.add(node); bbRoot = node; } var visibleBoxes = []; for (var _pointcloud of this.scene.pointclouds) { for (var _node of _pointcloud.visibleNodes.filter(vn => vn.boundingBoxNode !== undefined)) { var box = _node.boundingBoxNode; visibleBoxes.push(box); } } bbRoot.children = visibleBoxes; } } if (this.boundNeedUpdate) this.updateModelBound(); //add this.scene.cameraP.fov = this.fov; var controls = this.getControls(); if (controls === this.deviceControls) { this.controls.setScene(scene); this.controls.update(delta); this.scene.cameraP.position.copy(scene.view.position); this.scene.cameraO.position.copy(scene.view.position); } else if (controls !== null) { controls.setScene(scene); controls.update(delta); //更新camera this.viewports.forEach(viewport => { if (!viewport.active) return; viewport.view.applyToCamera(viewport.camera); }); } this.lastFrameChanged = this.cameraChanged(); //判断camera画面是否改变 { // update clip boxes var boxes = []; // volumes with clipping enabled boxes.push(...this.scene.volumes.filter(v => v.clip && v instanceof BoxVolume$1)); // profile segments for (var profile of this.scene.profiles) { boxes.push(...profile.boxes); } // Needed for .getInverse(), pre-empt a determinant of 0, see #815 / #816 var degenerate = box => box.matrixWorld.determinant() !== 0 && box.clip; var clipBoxes = boxes.filter(degenerate).map(box => { box.updateMatrixWorld(); var boxInverse = box.matrixWorld.clone().invert(); //let boxPosition = box.getWorldPosition(new THREE.Vector3()); return { box: box, inverse: boxInverse /* , position: boxPosition */ }; }); //改 var bigClipInBox = clipBoxes.find(e => e.box.clipTask == ClipTask.SHOW_INSIDE_Big && !e.box.highlight); //裁剪下载 when this.modules.Clip.editing var clipBoxes_in = clipBoxes.filter(e => e.box.clipTask == ClipTask.SHOW_INSIDE && !e.box.highlight); var clipBoxes_out = clipBoxes.filter(e => e.box.clipTask == ClipTask.SHOW_OUTSIDE && !e.box.highlight); var highlightBoxes = clipBoxes.filter(e => e.box.highlight); //let prismPolygons = this.modules.volumeComputer && this.modules.volumeComputer.entered ? viewer.scene.measurements.filter(e=>(e.measureType == 'MulDistance Ring') && !e.isNew) : [] var prismPolygons = this.modules.volumeComputer ? this.modules.volumeComputer.prisms.filter(e => !e.isNew && e.visible && !e.dontHighlight && (e.baseModel || !e.modelHaventLoad)) : []; // set clip volumes in material for (var _pointcloud2 of visiblePointClouds) { _pointcloud2.material.setClipBoxes(bigClipInBox, clipBoxes_in, clipBoxes_out, highlightBoxes, prismPolygons); } } { for (var _pointcloud3 of visiblePointClouds) { _pointcloud3.material.elevationGradientRepeat = this.elevationGradientRepeat; } } { // update navigation cube this.navigationCube.update(camera.rotation); } this.updateAnnotations(); if (this.mapView) { this.mapView.update(delta); if (this.mapView.sceneProjection) { $("#potree_map_toggle").css("display", "block"); } } this.transformationTool.update(); if (Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge') { this.modules.ParticleEditor.update(delta); } this.mapViewer && this.mapViewer.update(delta); //地图更新 this.dispatchEvent({ type: 'update', delta: delta, timestamp: timestamp }); //在有sidebar时耗高cpu,占本update函数80% viewer.addTimeMark('update', 'end'); //add ------ this.reticule.updateVisible(); } updateViewPointcloud(camera, areaSize, isViewport) { var result = Potree.updatePointClouds(this.scene.pointclouds, camera, areaSize); //if(isViewport)return var tStart = performance.now(); var campos = camera.position; var closestImage = Infinity; for (var images of this.scene.orientedImages) { for (var image of images.images) { var distance = image.mesh.position.distanceTo(campos); closestImage = Math.min(closestImage, distance); } } //const tEnd = performance.now(); //改:不根据点云修改视野near far var near = camera.near, far = camera.far; if (!camera.limitFar && result.lowestSpacing !== Infinity) { //let near = result.lowestSpacing * 10.0; var _far = -this.getBoundingBox().applyMatrix4(camera.matrixWorldInverse).min.z; _far = Math.max(_far * 1.5, 10000); //near = Math.min(100.0, Math.max(0.01, near)); //near = Math.min(near, closestImage); _far = Math.max(_far, near + 10000); /* if(near === Infinity){ near = 0.1; } */ //camera.near = near; //为了其他物体的显示,不修改near camera.far = _far; } /* if(this.scene.cameraMode == CameraMode.ORTHOGRAPHIC) {//??? camera.near = -camera.far; } */ if ( /* near != camera.near || */far != camera.far) { camera.updateProjectionMatrix(); } //注:pointcloud.visibleNodes会随着near far自动更新 } getPRenderer() { if (this.useHQ) { if (!this.hqRenderer) { this.hqRenderer = new HQSplatRenderer(this); } this.hqRenderer.useEDL = this.useEDL; return this.hqRenderer; } else { /* if (this.useEDL && Features.SHADER_EDL.isSupported()) { if (!this.edlRenderer) { this.edlRenderer = new EDLRenderer(this); } return this.edlRenderer; } else { if (!this.potreeRenderer) { this.potreeRenderer = new PotreeRenderer(this); } return this.potreeRenderer; } */ if (!this.edlRenderer) { this.edlRenderer = new EDLRenderer(this); } return this.edlRenderer; } } renderVR() { //渲染部分没改完 var renderer = this.renderer; renderer.setClearColor(0x550000, 0); renderer.clear(); var xr = renderer.xr; var dbg = new PerspectiveCamera(); var xrCameras = xr.getCamera(dbg); if (xrCameras.cameras.length !== 2) { return; } var makeCam = this.vrControls.getCamera.bind(this.vrControls); { // clear framebuffer if (viewer.background === "skybox") { renderer.setClearColor(0xff0000, 1); } else if (viewer.background === "gradient") { renderer.setClearColor(0x112233, 1); } else if (viewer.background === "black") { renderer.setClearColor(0x000000, 1); } else if (viewer.background === "white") { renderer.setClearColor(0xFFFFFF, 1); } else { renderer.setClearColor(0x000000, 0); } renderer.clear(); } // render background if (this.background === "skybox") { var { skybox } = this; var _cam = makeCam(); skybox.camera.rotation.copy(_cam.rotation); skybox.camera.fov = _cam.fov; skybox.camera.aspect = _cam.aspect; // let dbg = new THREE.Object3D(); var _dbg = skybox.parent; // dbg.up.set(0, 0, 1); _dbg.rotation.x = Math.PI / 2; // skybox.camera.parent = dbg; // dbg.children.push(skybox.camera); _dbg.updateMatrix(); _dbg.updateMatrixWorld(); skybox.camera.updateMatrix(); skybox.camera.updateMatrixWorld(); skybox.camera.updateProjectionMatrix(); renderer.render(skybox.scene, skybox.camera); // renderer.render(skybox.scene, cam); } else if (this.background === "gradient") { // renderer.render(this.scene.sceneBG, this.scene.cameraBG); } this.renderer.xr.getSession().updateRenderState({ depthNear: 0.1, depthFar: 10000 }); var cam = null; var view = null; { // render world scene cam = makeCam(); cam.position.z -= 0.8 * cam.scale.x; cam.parent = null; // cam.near = 0.05; cam.near = viewer.scene.getActiveCamera().near; cam.far = viewer.scene.getActiveCamera().far; cam.updateMatrix(); cam.updateMatrixWorld(); this.scene.scene.updateMatrix(); this.scene.scene.updateMatrixWorld(); this.scene.scene.matrixAutoUpdate = false; var camWorld = cam.matrixWorld.clone(); view = camWorld.clone().invert(); this.scene.scene.matrix.copy(view); this.scene.scene.matrixWorld.copy(view); cam.matrix.identity(); cam.matrixWorld.identity(); cam.matrixWorldInverse.identity(); renderer.render(this.scene.scene, cam); this.scene.scene.matrixWorld.identity(); } for (var pointcloud of this.scene.pointclouds) { var viewport = xrCameras.cameras[0].viewport; pointcloud.material.useEDL = false; pointcloud.screenHeight = viewport.height; pointcloud.screenWidth = viewport.width; // automatically switch to paraboloids because they cause far less flickering in VR, // when point sizes are larger than around 2 pixels // if(Features.SHADER_INTERPOLATION.isSupported()){ // pointcloud.material.shape = Potree.PointShape.PARABOLOID; // } } // render point clouds for (var xrCamera of xrCameras.cameras) { var v = xrCamera.viewport; renderer.setViewport(v.x, v.y, v.width, v.height); // xrCamera.fov = 90; { // estimate VR fov var proj = xrCamera.projectionMatrix; var inv = proj.clone().invert(); var p1 = new Vector4(0, 1, -1, 1).applyMatrix4(inv); var rad = p1.y; var fov = 180 * (rad / Math.PI); xrCamera.fov = fov; } for (var _pointcloud4 of this.scene.pointclouds) { var { material } = _pointcloud4; material.useEDL = false; } var vrWorld = view.clone().invert(); vrWorld.multiply(xrCamera.matrixWorld); var vrView = vrWorld.clone().invert(); this.pRenderer.render(this.scene.scenePointCloud, xrCamera, null, { viewOverride: vrView }); } { // render VR scene var _cam2 = makeCam(); _cam2.parent = null; renderer.render(this.sceneVR, _cam2); } renderer.resetState(); } clear() { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var background = params.background || this.background; var backgroundOpacity = params.backgroundOpacity == void 0 ? this.backgroundOpacity : params.backgroundOpacity; //如果想完全透明,只需要backgroundOpacity为0 var renderer = this.renderer; //let gl = renderer.getContext() if (background instanceof Color) { //add renderer.setClearColor(background, backgroundOpacity); } else if (background === "skybox") { renderer.setClearColor(0x000000, backgroundOpacity); } else if (background === 'gradient') { renderer.setClearColor(0x000000, backgroundOpacity); } else if (background === 'black') { renderer.setClearColor(0x000000, 1); } else if (background === 'white') { renderer.setClearColor(0xFFFFFF, 1); } else { renderer.setClearColor(background, backgroundOpacity); } params.target || renderer.clear(); } getBuffer(viewport) { //根据不同viewport返回rtEDL的texture var buffer = this.buffers.get(viewport); if (!buffer) { buffer = new WebGLRenderTarget(viewport.resolution.x, viewport.resolution.y, { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat, type: FloatType }); this.buffers.set(viewport, rtEDL); } return buffer; } async renderDefault() { var params_ = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (!this.visible) return; var pRenderer = this.getPRenderer(); var viewports = params_.viewports || this.viewports; var renderer = params_.renderer || this.renderer; viewer.addTimeMark('renderDefault', 'start'); //console.log('render', viewports.map(e=>e.name).join(',')) var renderSize; if (params_.target) { renderSize = new Vector2(params_.target.width, params_.target.height); //是画布大小 //可能需要viewer.setSize } else { renderSize = renderer.getSize(new Vector2()); //是client大小 } ///let needsResize = viewports.length > 1 || params_.resize //去掉原因:因为不需要渲染的viewport不在此中所以无法判断几个viewport for (var i = 0; i < viewports.length; i++) { var viewport = viewports[i]; var params = $.extend({}, params_); params.viewport = viewport; //if(!params.target){ params.camera = params.camera || viewport.camera; params.extraEnableLayers = viewport.extraEnableLayers; params.cameraLayers = viewport.cameraLayers; //} var left, bottom, width, height; { left = Math.ceil(renderSize.x * viewport.left); bottom = Math.ceil(renderSize.y * viewport.bottom); if (params_.target) { //有target时最好viewport是专门建出来的 width = renderSize.x * viewport.width; //target的大小可能和viewport不同,比如截图,这时会更改viewport大小 height = renderSize.y * viewport.height; } else { width = viewport.resolution.x; // 用的是client的width和height height = viewport.resolution.y; } if (width == 0 || height == 0) continue; //return width = Math.ceil(width); //使用ceil,当原本有小数时,会重叠一个像素,无所谓 height = Math.ceil(height); var scissorTest = viewport.width < 1 || viewport.height < 1; if (params_.target) { params_.target.viewport.set(left, bottom, width, height); scissorTest && params_.target.scissor.set(left, bottom, width, height); params_.target.scissorTest = scissorTest; renderer.setRenderTarget(params_.target); } else { /* if(viewports.length == 1 && left == 0 && bottom == 0){ left = 1 , width-=1 //这种情况下渲染也会有问题,只有鼠标的地方刷新 估计是pick那影响的 } */ /* if(scissorTest && left == 0 && bottom == 0){ left = 1 , width-=1 } */ if (viewport.forViewOffset) { //分块渲染,渲染时的camera还是原来的,但加载点云时的camera是分块中的 viewport.forViewOffset.camera.setViewOffset(renderSize.x, renderSize.y, left, renderSize.y - bottom - height, width, height); renderer.setViewport(0, 0, renderSize.x, renderSize.y); viewport.resolution.copy(viewport.forViewOffset.originViewport.resolution); viewport.resolution2.copy(viewport.forViewOffset.originViewport.resolution2); //后续渲染都当做原先的viewport } else { renderer.setViewport(left, bottom, width, height); //规定视口,影响图形变换(画布的使用范围) } //scissorTest && console.log('setScissor', left, bottom, width, height) scissorTest && renderer.setScissor(left, bottom, width, height); //规定渲染范围 renderer.setScissorTest(scissorTest); //开启WebGL剪裁测试功能,如果不开启,.setScissor方法设置的范围不起作用 | width==1且height==1时开启会只有鼠标的地方刷新,很奇怪 } } //if(needsResize){ this.ifEmitResize({ viewport }); //} viewer.dispatchEvent({ type: "render.begin", viewer: viewer, viewport, params }); viewport.beforeRender && viewport.beforeRender(); if (viewport.render) { if (!viewport.render($.extend({}, params, { renderer, clear: params.clear || this.clear.bind(this), resize: null, renderBG: this.renderBG.bind(this), force: true //viewer content_change时map也直接渲染吧 //!viewport.noPointcloud //如果要渲染点云,必须也一直渲染地图,否则地图会被覆盖(点云目前未能获取是否改变,也可能有其他动态物体,所以还是一直渲染的好) }))) continue; //return } else { this.clear(params); pRenderer.clearTargets(params); this.renderBG(viewport); if (Potree.settings.notAdditiveBlending) { params.renderBeforeCloud = true; this.renderOverlay1(params); //先渲染不透明的model。 但drawedModelOnRT时这里提前多渲染了一遍 } } if (!viewport.noPointcloud) { if (params_.needWaitLoadPoint) { await this.waitPointLoad(null, params_.maxTimeForPointLoad, viewport); //resolution得用split前整个的viewport的 } else { this.updateViewPointcloud(params.camera, viewport.resolution, true); } pRenderer.render(params); //渲染点云 skybox。 } if (Potree.settings.notAdditiveBlending) { // 融合页面才用到 params.renderBeforeCloud = false; this.renderOverlay1(params); this.renderOverlay2(params); } else { this.renderOverlay(params); } viewport.afterRender && viewport.afterRender(); this.dispatchEvent({ type: "render.end", viewer: this, viewport }); viewport.needRender = false; viewport.lastRenderTime = Date.now(); } /* if(params_.screenshot){ //抗锯齿 this.composer.render(); } */ this.renderer.setRenderTarget(null); viewer.scene.pointclouds[0] && this.addFakeMeasure('visibleNodes', viewer.scene.pointclouds[0].visibleNodes.length); // this.addFakeMeasure('numVisiblePoints', Potree.numVisiblePoints / 100000); //十万 numVisiblePoints和帧率成反比(若每一帧都render的话),和render用时成正比 (y=kn+b)。但visibleNodes个数也影响,多的话也更卡。visibleNodes和numVisiblePoints不成正比,少的visibleNodes可能numVisiblePoints多 viewer.addTimeMark('renderDefault', 'end'); } renderBG(viewport) { var background = viewport.background || viewer.background; var backgroundOpacity = viewport.backgroundOpacity == void 0 ? viewer.backgroundOpacity : viewport.backgroundOpacity; //如果想完全透明,只需要backgroundOpacity为0 if (backgroundOpacity != 0) { //绘制背景. 为了防止相机移动后天空不动有点死板,做一定的动态 if (background === "skybox") { //限制相机到原点的距离。 var skyCamera = viewport.camera.type == "OrthographicCamera" ? viewer.skybox.cameraOrtho : viewer.skybox.camera; var safeRatio = 0.02; var safeWidth = Potree.config.skyboxBgWidth * safeRatio / 2; //相机只能在这个范围内移动 if (!viewport.skyboxFixPos) { //允许不在全景图中心,允许位移造成一定程度畸变 var dir = new Vector3().subVectors(viewport.camera.position, viewer.bound.center); var length = dir.length(); var moveMax = 100; var aimRadius = easing.easeOutQuart(Math.min(length, moveMax), 0, safeWidth, moveMax); //(x, startY, wholeY, maxX) 当自变量为0-moveMax时,相机位移量为0-safeWidth dir.multiplyScalar(aimRadius / length); skyCamera.position.copy(dir); } else { skyCamera.position.set(0, 0, 0); } skyCamera.rotation.copy(viewport.camera.rotation); skyCamera.aspect = viewport.camera.aspect; if (viewport.camera.type == "OrthographicCamera") { //调节zoom skyCamera.left = viewport.camera.left; skyCamera.right = viewport.camera.right; skyCamera.top = viewport.camera.top; skyCamera.bottom = viewport.camera.bottom; var a = Potree.config.skyboxBgWidth / 2 - safeWidth; var minY = Math.max(skyCamera.right / a, skyCamera.top / a, viewport.skyboxMinZoom || 0); //能够使skybox铺满画布的最小zoom. 提示:越远zoom越小 var maxY = Math.max(20, minY); //自定义一个 不会超过的最大实际zoom //viewport.camera.zoom自变量的变化范围: var minX = 1; var maxX = 80; var x = MathUtils.clamp(viewport.camera.zoom - minX, minX, maxX); skyCamera.zoom = easing.easeOutCubic(x - minX, minY, maxY - minY, maxX - minX); //自变量范围从0开始,所以减去minX //pos的范围先不管了 其实aimRadius是有误的,但效果还行 } else { skyCamera.fov = viewport.camera.fov; skyCamera.zoom = 1; } viewport.skyboxRenderFun && viewport.skyboxRenderFun(); skyCamera.updateProjectionMatrix(); skyCamera.updateMatrixWorld(); viewer.renderer.render(viewer.skybox.scene, skyCamera); } else if (background === 'gradient') { viewer.scene.cameraBG.layers.set(Potree.config.renderLayers.bg); viewer.renderer.render(viewer.scene.scene, viewer.scene.cameraBG); } else if (background === 'overlayColor') { //在不clear的前提下加一层背景色 viewer.scene.bg2.material.color.copy(viewport.backgroundColor); viewer.scene.bg2.material.opacity = viewport.backgroundOpacity; viewer.scene.cameraBG.layers.set(Potree.config.renderLayers.bg2); viewer.renderer.render(viewer.scene.scene, viewer.scene.cameraBG); } } //全景图的部分和点云有点相关就不移动到这了。但是如果是showPanos模式,就不要渲染背景了。 } /* 关于透明度: 由于点云和mesh是分开渲染的,且材质很不一样,所以透明和blend有冲突 1 如果点云的blend是AdditiveBlending,也就是普通的叠加模式。 则半透明点云的depthTest和depthWrite都为false 这时候mesh要后渲染,且depthWrite不能为false(除非depthTest也为false),否则将被点云遮住。 2 如果点云的blend是普通型 则半透明点云的depthTest和depthWrite都为true。(为何depthWrite不能像mesh一样为false, 否则点云自身透明会错乱,可能因为太多points了) 这时候若mesh全部先渲染,则 透过depthWrite为false的半透明mesh看不透明点云,mesh会完全被点云遮住。但是透明的物体就是depthWrite要为false,否则也会完全遮住点云 即使是后渲染半透明的mesh,若透过点云看mesh,mesh会完全被点云遮住(为什么之前遇到过 透过点云看mesh,点云会显示不出) 最终选择是先渲染不透明的mesh,然后点云,然后透明的mesh。虽然点云对mesh透明会失效。 */ renderOverlay(params) { viewer.addTimeMark('renderOverlay', 'start'); this.renderOverlay1(params); this.renderOverlay2(params); viewer.addTimeMark('renderOverlay', 'end'); } renderOverlay1(params) { //渲染主要的mesh var camera = params.camera ? params.camera : this.scene.getActiveCamera(); var renderer = params.renderer || this.renderer; this.reticule.updateAtViewports(params.viewport); renderer.setRenderTarget(params.target || null); //为什么要在点云之后渲染,否则透明失效 、 会被点云覆盖 var cameraLayers; if (params.cameraLayers) cameraLayers = params.cameraLayers;else { if (params.viewport.name == "mapViewport") cameraLayers = ['bothMapAndScene', 'light'];else { cameraLayers = ['sceneObjects', 'light', 'bothMapAndScene']; if (!params.drawedModelOnRT) { cameraLayers.push('model'); } } } if (cameraLayers.length) { Potree.Utils.setCameraLayers(camera, cameraLayers, params.extraEnableLayers); //透明贴图层 skybox 、reticule marker 不能遮住测量线 if ('renderBeforeCloud' in params) { this.scene.scene.traverse(object => { if (object.material) { var transparent = object.material.opacity < 1 || object.material.mapTransparent || !object.material.depthTest; Potree.Utils.updateVisible(object, 'renderOpa', params.renderBeforeCloud != transparent); //点云之前渲染的话隐藏半透明的, 点云之后渲染的话隐藏不透明的。 depthTest==false的也最后渲染。 mapTransparent是手动加的,代表确定该贴图含有透明部分,即使opacity为1 } }); //ground的材质中opacity为1,所以被当做不透明了 } viewer.dispatchEvent({ type: "render.begin2", name: 'scene', viewport: params.viewport }); renderer.render(this.scene.scene, camera); if ('renderBeforeCloud' in params) { this.scene.scene.traverse(object => { if (object.material) { Potree.Utils.updateVisible(object, 'renderOpa', true); //恢复 } }); } } this.dispatchEvent({ type: "render.pass.scene", viewer: viewer }); } renderOverlay2(params) { //渲染剩余部分 var renderer = params.renderer || this.renderer; var camera = params.camera ? params.camera : this.scene.getActiveCamera(); //清除深度 !!!! renderer.clearDepth(); if (!params.magnifier) { //测量线 this.dispatchEvent({ type: "render.pass.perspective_overlay", camera, screenshot: params.screenshot, viewport: params.viewport, renderer }); if (!params.screenshot && params.viewport.name != "mapViewport") { Potree.Utils.setCameraLayers(camera, ['magnifier']); //magnifier 遮住测量线 renderer.render(this.scene.scene, camera); } } if (params.viewport.name != "mapViewport") { Potree.Utils.setCameraLayers(camera, ['volume', 'transformationTool']); //viewer.dispatchEvent({type: "render.begin2" , name:'clip&trans',viewport:params.viewport }) renderer.render(this.clippingTool.sceneVolume, camera); //official 可以删 renderer.render(this.transformationTool.scene, camera); } } setLimitFar(state) { //切换是否limitFar viewer.mainViewport.camera.limitFar = !!state; if (state) { viewer.mainViewport.camera.near = 0.02; viewer.mainViewport.camera.far = Potree.settings.displayMode == 'showPanos' ? viewer.farWhenShowPano : Potree.settings.cameraFar; viewer.mainViewport.camera.updateProjectionMatrix(); } } setClipState(state) { //有时候需要暂时关闭下clip state = !!state; if (this.clipUnabled == !state) return; this.scene.volumes.filter(v => /* v.clip && */v instanceof Potree.BoxVolume).map(volume => { volume.clip = state; Potree.Utils.updateVisible(volume, 'setClipState', state); }); this.clipUnabled = !state; } /* 大规模WebGL应用引发浏览器崩溃的几种情况及解决办法 https://blog.csdn.net/weixin_30378311/article/details/94846947 */ async render() { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; //add params viewer.addTimeMark('render', 'start'); var vrActive = this.renderer.xr.isPresenting; var SiteModel = viewer.modules.SiteModel; if (this.screenshoting && !params.screenshot) return; //正在截图 var s = SiteModel.editing && SiteModel.selected && (SiteModel.selected.buildType == 'room' || SiteModel.selected.buildType == 'floor'); //空间模型的房间选中材质是需要depth的,这时候需要绘制两次点云 Potree.settings.pointEnableRT = !this.screenshoting && (this.scene.measurements.filter(e => e.visible).length > 0 || s); if (vrActive) { this.renderVR(); } else { var specialRender = !!params.viewports; var viewports = params.viewports || this.viewports; if (!this.needRender) { viewports = viewports.filter(v => v.needRender); //可以渲染的条件是viewer或viewport的needRender为true } viewports = viewports.filter(v => v.active); if (viewports.length > 0) { params.viewports = viewports; if (this.outlinePass.selectedObjects.length && this.outlinePass.edgeStrength > 0 && !params.screenshot // || this.images360.fastTranMaskPass.enabled ) { var scenes = this.inputHandler.interactiveScenes.concat(this.scene.scene).concat(viewer.scene.scenePointCloud); this.composer.render(scenes, null, this.viewports, this.renderDefault.bind(this)); } else { await this.renderDefault(params); } } if (!specialRender) this.needRender = false; } viewer.addTimeMark('render', 'end'); } startScreenshot() { var info = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var width = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 800; var height = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 400; var compressRatio = arguments.length > 3 ? arguments[3] : undefined; //add //let deferred = info.deferred || $.Deferred(); var getImageDeferred = info.getImageDeferred || $.Deferred(); var finishDeferred = info.finishDeferred || $.Deferred(); var viewerMaster = info.map ? this.mapViewer : this; //截图主体 var useMap = info.map || info.type == 'measure' || info.type.includes('prism2d'); if (Potree.settings.displayMode == 'showPanos' && viewer.mainViewport.view.isFlying('pos')) { //如果在飞,飞完再截图 info.getImageDeferred = getImageDeferred, info.finishDeferred = finishDeferred; var f = () => { this.startScreenshot(info, width, height, compressRatio); }; viewer.mainViewport.view.addEventListener('flyingDone', f, { once: true }); return { getImagePromise: getImageDeferred.promise(), finishPromise: finishDeferred.promise() }; } var startTime = Date.now(); //抗锯齿待加 1 post处理 2截图大张再抗锯齿缩小 this.pauseTestMaxLevel = true; this.screenshoting = true; console.log('startScreenshot: ' + startTime); var updateCamera = () => { viewports.forEach(e => { e.view.applyToCamera(e.camera); //因为fly时只更新了view所以要强制更新下camera this.dispatchEvent({ //update map and sprite, mapChanged type: "camera_changed", camera: e.camera, viewport: e, changeInfo: { positionChanged: true, changed: true } }); }); }; var screenshot = async () => { var pose; useMap && (viewer.mapViewer.needRender = true); info.beforeScreenshot && info.beforeScreenshot(); var render = async () => { this.needRender = true; viewports.forEach(e => e.active = true); if (info.useRenderTarget) { //离屏渲染 有抗锯齿问题、在手机上速度慢 主视图一样会变内容,还是不用这个了 var { dataUrl } = viewerMaster.makeScreenshot(new Vector2(width, height), null, compressRatio); } else { //直接渲染 会改变canvas大小 var canvas = viewerMaster.renderer.domElement; //canvas.width = width, canvas.height = height //不需要改canvas大小, 只需要 this.renderer.setSize(width, height ); 前面updateScreenSize已经执行 await viewerMaster.render({ screenshot: true, width, height, resize: true, needWaitLoadPoint: !!info.splitRenderInfo, maxTimeForPointLoad: info.maxTimeForPointLoad }); //需要resize /* if(info.type.includes('prism2d')){//o.map要为true viewer.dispatchEvent({type:'resize', viewport:viewer.mapViewer.viewports[0]}) //借用viewer通知lineMaterial resize viewerMaster.renderOverlay() } */ var dataUrl = canvas.toDataURL('image/png', compressRatio); } return dataUrl; }; var dataUrl; if (info.splitRenderInfo) { //为了防崩溃,分区域批次渲染 var { wc, hc } = info.splitRenderInfo; var camera = viewer.mainViewport.camera; var dataUrls = []; var width_ = Math.ceil(1 / wc * width), height_ = Math.ceil(1 / hc * height); //可能加起来比原图大,没事到时候边界会重合 viewer.updateScreenSize({ forceUpdateSize: true, width: width_, height: height_, forTarget: info.useRenderTarget }); //更新viewports相机透视 使focusOnObject在此窗口大小下 for (var i = 0; i < wc; i++) { var col = []; for (var j = 0; j < hc; j++) { var left = Math.ceil((-wc / 2 + 0.5 + i) * width_), top = Math.ceil((-hc / 2 + 0.5 + j) * height_); camera.setViewOffset(width_, height_, left, top, width_, height_); //顺序从上到下从左到右 var _dataUrl = await render(); //Common.downloadFile(dataUrl, 'screenshot'+ i+':'+j+'.png') col.push({ dataUrl: _dataUrl, width: width_, height: height_ }); } dataUrls.push(col); } camera.clearViewOffset(); dataUrl = await Utils.combineImgs(dataUrls, compressRatio, width, height); } else { dataUrl = await render(); } if (info.splitRenderInfo) { viewer.viewports = [viewer.mainViewport]; } if (!Potree.settings.isOfficial) { Common.downloadFile(dataUrl, 'screenshot.png'); } var finish = () => { oldStates.viewports.forEach(old => { //恢复相机 var viewport = viewports.find(v => v.name == old.name); viewport.left = old.left; viewport.bottom = old.bottom; viewport.width = old.width; viewport.height = old.height; viewport.view.copy(old.view); //viewport.view.applyToCamera(viewport.camera); if (viewport.camera.isOrthographicCamera) { viewport.camera.zoom = viewport.view.zoom; } }); viewerMaster.updateScreenSize({ forceUpdateSize: true }); //更新像素 /* oldStates.viewports.forEach(old=>{//恢复相机 var viewport = [mapViewport, mainViewport].find(v=>v.name == old.name); this.dispatchEvent({ //update map type: "camera_changed", camera: viewport.camera, viewport : viewport }) }) */ updateCamera(); finishDeferred.resolve({ dataUrl, pose }); info.map || setTimeout(() => { if (!this.screenshoting) { //Potree.settings.pointNoLimit = false Potree.settings.pointDensity = 'high'; //console.warn('恢复pointDensity') /* if(viewer.scene.pointclouds[0].material.oldSize_ ){ viewer.scene.pointclouds[0].material.size = viewer.scene.pointclouds[0].material.oldSize_ viewer.scene.pointclouds[0].material.oldSize_ = null } */ } }, 500); //延迟:避免连续多次截图时释放点云 this.screenshoting = false; console.log('screenshot done: ' + startTime, 'costTime', Date.now() - startTime + 'ms'); }; { //恢复: this.backgroundOpacity = oldStates.bgOpacity; this.background = oldStates.background; this.pauseTestMaxLevel = false; oldStates.displayMode && (Potree.settings.displayMode = oldStates.displayMode); if (info.type == 'measure' || info.type.includes('prism2d')) { this.modules.SiteModel.pauseUpdateEntity = false; this.focusDatasets = null; this.scene.measurements.forEach(e => Potree.Utils.updateVisible(e, 'screenshot', true)); info.type == 'measure' && info.measurement.setSelected(false, 'screenshot'); } if (info.type.includes('prism2d')) { //viewer.mapViewer.transparentBG = false; (info.prisms || [info.prism]).forEach(prism => { prism.changeStyleForScreenshot(false); if (info.type == 'prism2d-single') { prism.baseModel && (Potree.Utils.updateVisible(prism.baseModel, 'screenshot', false, 3, 'cancel'), Potree.Utils.setObjectLayers(prism.baseModel, 'model')); prism.setEditState(false); } }); } this.images360.panos.forEach(pano => { Potree.Utils.updateVisible(pano, 'screenshot', true); }); Potree.Utils.updateVisible(this.reticule, 'screenshot', true); if (useMap) { Potree.Utils.updateVisible(this.mapViewer.cursor, 'screenshot', true); if (oldStates.attachedToViewer != this.mapViewer.attachedToViewer) { this.mapViewer.attachToMainViewer(!!oldStates.attachedToViewer); } if (oldStates.attachedToViewer && this.mapViewer.splitDir != oldStates.oldSplitDir) { this.mapViewer.changeSplitScreenDir(oldStates.oldSplitDir); } mapViewport.noPointcloud = oldStates.noPointcloud; Potree.Utils.updateVisible(viewer.mapViewer.mapLayer.sceneGroup, 'screenshot-prism', true); } var recover = () => { if (Potree.settings.displayMode == 'showPanos') { viewer.images360.flyToPano({ pano: oldStates.pano, duration: 0, callback: () => { finish(); } }); } else { finish(); } }; if (info.ifGetPose) { Potree.sdk.scene.getPose().done(pose_ => { pose = pose_; getImageDeferred.resolve({ dataUrl, pose }); recover(); }); } else { recover(); } } }; // screenshot end var mapViewport; var mainViewport = this.mainViewport; var viewports = [], oldStates = { viewports: [], pano: Potree.settings.displayMode == 'showPanos' ? viewer.images360.currentPano : null, bgOpacity: this.backgroundOpacity, background: this.background }; if (!info.type.includes('prism2d')) { viewports.push(mainViewport); mainViewport.camera.isOrthographicCamera && (mainViewport.view.zoom = mainViewport.camera.zoom); oldStates.viewports.push(mainViewport.clone()); } if (useMap) { mapViewport = this.mapViewer.viewports[0]; mapViewport.view.zoom = mapViewport.camera.zoom; viewports.push(mapViewport); oldStates.viewports.push(mapViewport.clone()); oldStates.attachedToViewer = this.mapViewer.attachedToViewer; oldStates.noPointcloud = mapViewport.noPointcloud; oldStates.displayMode = Potree.settings.displayMode; Potree.Utils.updateVisible(this.mapViewer.cursor, 'screenshot', false); //令mapCursor不可见 } viewports.forEach(e => e.active = false); //暂停渲染 if (info.hideMarkers) { this.images360.panos.forEach(pano => { //令漫游点不可见 Potree.Utils.updateVisible(pano, 'screenshot', false); }); } Potree.Utils.updateVisible(this.reticule, 'screenshot', false); //令reticule不可见 if (info.bgOpacity != void 0) { this.backgroundOpacity = info.bgOpacity; } if (info.background != void 0) { this.background = info.background; } Potree.settings.pointDensity = info.pointDensity || 'screenshot'; var focusDatasets = measurements => { this.focusDatasets = []; measurements.forEach(measure => { measure.points_datasets.forEach(e => { var p = viewer.scene.pointclouds.find(a => a.dataset_id == e); if (p && !this.focusDatasets.includes(p)) { this.focusDatasets.push(p); } }); }); this.updateFpVisiDatasets(); }; if (info.type == 'measure') { //要截图双屏 this.scene.measurements.forEach(e => Potree.Utils.updateVisible(e, 'screenshot', e == info.measurement)); info.measurement.setSelected(true, 'screenshot'); //因为分屏后位置才最终确定,才能确定是否显示出floorplan所以先分屏 if (Potree.settings.floorplanEnable) { oldStates.oldSplitDir = this.mapViewer.splitDir; this.mapViewer.attachToMainViewer(true, 'measure', 0.5, { dir: 'leftRight' }); } viewer.updateScreenSize({ forceUpdateSize: true, width, height, forTarget: info.useRenderTarget }); //更新viewports相机透视 使focusOnObject在此窗口大小下 var begin = () => { useMap = this.mapViewer.attachedToViewer; updateCamera(); if (useMap) { var waitMap = () => { console.log('waitMap: ' + startTime, Date.now(), this.mapViewer.mapLayer.loadingInProgress); this.mapViewer.waitLoadDone(screenshot.bind(this)); //等待地图所有加载完 }; this.waitPointLoad(waitMap, info.maxTimeForPointLoad); } else { this.waitPointLoad(screenshot, info.maxTimeForPointLoad); } }; var { promise } = this.focusOnObject(info.measurement, 'measure', 0, { basePanoSize: 1024, gotoBestView: true //minMapWidth: THREE.Math.clamp(Math.min(viewer.bound.boundSize.x, viewer.bound.boundSize.y) / (20/* this.mapViewer.mapLayer.maps.find(e=>e.name == 'map').disabled ? 6 : 3*/), 2, 25) //有地图的话为了显示出名字需要更大范围 }); //注意:不同角度截图 得到三维的会不一样,因为focusOnObject是根据方向的 promise.done(() => { //console.log('promise.done') //根据当前位置更新floorplan显示 //console.log('view Pos ', this.mainViewport.view.position.toArray()) this.updateDatasetAt(true); this.modules.SiteModel.updateEntityAt(true, { measure: info.measurement }); //更新测量线所在楼层,展示俯视图 if (!this.modules.SiteModel.inEntity) { focusDatasets([info.measurement]); } this.modules.SiteModel.pauseUpdateEntity = true; //console.log('currentFloor', this.modules.SiteModel.currentFloor, 'currentDataset', this.atDatasets ) var floorplanShowed = this.mapViewer.mapLayer.maps.some(e => e.name.includes('floorplan') && e.objectGroup.visible); //如果没有floorplan展示就不分屏(如果focus时飞出数据集从而不展示怎么办。尤其是俯瞰比较长的线时容易这样,或许要根据其所在数据集强制显示) if (!floorplanShowed && this.mapViewer.attachedToViewer) { this.mapViewer.attachToMainViewer(false); //取消分屏 viewer.updateScreenSize({ forceUpdateSize: true, width, height, forTarget: info.useRenderTarget }); //更新viewports相机透视 var { promise: _promise } = this.focusOnObject(info.measurement, 'measure', 0, { basePanoSize: 1024, gotoBestView: true }); //因画面比例更改,重新focus _promise.done(() => { begin(); }); } else { begin(); } }); } else if (info.type.includes('prism2d')) { var points = [], prisms = info.type == 'prism2d-all' ? info.prisms : [info.prism]; this.mapViewer.attachToMainViewer(true, 'screenshot', 1, {/* dir:'leftRight' */}); viewer.updateScreenSize({ forceUpdateSize: true, width, height, forTarget: info.useRenderTarget }); //更新viewports相机透视 使focusOnObject在此窗口大小下 prisms.forEach(prism => { var prismPoints = prism.points.slice(); if (prism.baseModel) { var currentBound = prism.baseModel.currentBound || prism.baseModel.boundingBox.clone().applyMatrix4(prism.baseModel.matrixWorld); prismPoints = prismPoints.map(e => e.clone().setZ(Math.max(e.z, currentBound.max.z))); } points.push(...prismPoints); prism.setSelected(false); prism.changeStyleForScreenshot(true, { hideLabel: info.type != 'prism2d-all', showName: info.type == 'prism2d-all' }); if (info.type == 'prism2d-single') { prism.baseModel && (Potree.Utils.updateVisible(prism.baseModel, 'screenshot', true, 3, 'add'), Potree.Utils.setObjectLayers(prism.baseModel, 'bothMapAndScene')); prism.setEditState(true); } }); this.scene.measurements.forEach(e => Potree.Utils.updateVisible(e, 'screenshot', prisms.includes(e))); this.backgroundOpacity = 0; var { promise: _promise2 } = this.focusOnObject({ points }, 'prisms2d', 0, { minMapWidth: 0.5, onlyMap: true, focusBoundCenter: true, boundExpandRatio: 1.4 }); _promise2.done(() => { updateCamera(); if (info.type == 'prism2d-all') { //全部 带平面图 focusDatasets(prisms); //更新平面图 可能有漏洞,当不在任何一个数据集内的话? this.mapViewer.waitLoadDone(screenshot.bind(this)); //等待地图所有加载完 } else { //single mapViewport.noPointcloud = false; //显示点云,而非平面图 Potree.settings.displayMode = 'showPointCloud'; Potree.Utils.updateVisible(viewer.mapViewer.mapLayer.sceneGroup, 'screenshot-prism', false); this.waitPointLoad(screenshot, 5000); } }); } else { //default var done = () => { updateCamera(); if (info.splitRenderInfo) { screenshot(); } else { this.waitPointLoad(screenshot, info.maxTimeForPointLoad); } }; if (info.focusObjectInfo) { viewer.updateScreenSize({ forceUpdateSize: true, width, height, forTarget: info.useRenderTarget }); //更新viewports相机透视 使focusOnObject在此窗口大小下 var { promise: _promise3 } = this.focusOnObject(...info.focusObjectInfo); _promise3.done(() => { done(); }); } else { done(); } } /* 测量线的截图因为要调用分屏的,会改变画面 但是普通截图的话,不会改变画面 */ return { getImagePromise: getImageDeferred.promise(), finishPromise: finishDeferred.promise() }; } async waitPointLoad(done, maxTimeForPointLoad) { var viewport = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : viewer.mainViewport; var resolution = arguments.length > 3 ? arguments[3] : undefined; return new Promise((resolve, reject) => { var finish; var dealDone = () => { viewer.removeEventListener('update', update); viewer.removeEventListener('overPointBudget', decreaseLevel); finish || done && done(); finish = true; resolve(); }; var decreaseLevel = e => { //降点云level 但基本降完也不会再加载低等级的点云了,所以是否直接不降?即使质量不平均 if (e.restQueueSize < 10) return; //差不多完成了 var pointclouds = viewer.scene.pointclouds.filter(e => e.visibleNodes.length); console.log('准备decreaseLevel, numVisiblePoints', e.numVisiblePoints, '最小numVisiblePoints占比', 1 / pointclouds.length); pointclouds.forEach(pointcloud => { var percent = pointcloud.numVisiblePoints / e.numVisiblePoints; //console.log('numVisiblePoints占总比', pointcloud.dataset_id, percent ) if (percent < 1 / pointclouds.length) return; var old = pointcloud.maxLevel; var levels = pointcloud.visibleNodes.map(e => e.getLevel()); var actMaxLevel = Math.max.apply(null, levels); //实际加载到的最高的node level pointcloud.maxLevel = actMaxLevel - 1; console.warn(pointcloud.dataset_id, 'decreaseLevel,新maxLevel', actMaxLevel - 1, '原maxlevel', old); }); }; /* if(Potree.settings.displayMode == 'showPointCloud'){ viewer.updateScreenSize({forceUpdateSize:true, width, height, forTarget:info.useRenderTarget})//需要先setSize才能加载范围内的点云 } */ //updateCamera() //viewer.addEventListener('overPointBudget',decreaseLevel) var update = () => { //前提:已经禁止渲染,仅加载点云 var camera = viewport.forViewOffset ? viewport.forViewOffset.camera : viewport.camera; Potree.updatePointClouds(viewer.scene.pointclouds, camera, resolution || viewport.resolution); }; viewer.addEventListener('update', update); update(); var maxTime = maxTimeForPointLoad || 2000; document.hidden && (maxTime *= 6); //离开页面后会变成1秒1帧 setTimeout(() => { if (Potree.pointsLoading && Potree.settings.displayMode == 'showPointCloud') { //如果还在加载 viewer.addEventListener('pointsLoaded', () => { //点云加载完时(不一定准确) if (!finish) console.log('加载完毕', ' numVisiblePoints', Potree.numVisiblePoints); dealDone(); }, { once: true }); var overTime = () => { //超时不候(其实之后等待地图还会再加载几秒) if (document.hidden) { return setTimeout(overTime, maxTime); } if (!finish) console.warn('超时, numVisiblePoints', Potree.numVisiblePoints); dealDone(); }; setTimeout(overTime, maxTime); } else { console.log('已经加载完,无需再加载点云 numVisiblePoints', Potree.numVisiblePoints); dealDone(); } }, 200); //先加载一段时间 }); } focusOnObject(object, type, duration) { var o = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; //飞向热点、测量线等 。 //console.log('focusOnObject: ', object, type) var deferred = o.deferred || $.Deferred(); var target = new Vector3(), //相机focus的位置 position = new Vector3(), //相机最终位置 dis; //相机距离目标 duration = duration == void 0 ? 1200 : duration; var camera = o.endCamera || viewer.scene.getActiveCamera(); var cameraPos = camera.position.clone(); var boundSize; if (o.dontChangeCamDir && (o.endYaw == void 0 || o.endPitch == void 0)) { //在俯视时仅靠dir来算不准 o.endYaw = viewer.mainViewport.view.yaw; o.endPitch = viewer.mainViewport.view.pitch; } var moveMap = done => { if (this.mapViewer && !o.dontMoveMap) { //console.log('mapFocusOn: '+target.toArray()) var minMapWidth = o.minMapWidth || 2; //截图的时候要显示的地图范围较大,为了显示出地区名字 var minBound = new Vector2(minMapWidth, minMapWidth); //针对垂直线,在地图上只有一个点 //原始的bound var boundOri; if (object.points) { boundOri = new Box3(); object.points.forEach(e => { boundOri.expandByPoint(e); }); } else { boundOri = object.boundingBox; } if (o.focusBoundCenter) { boundOri.getCenter(target); target.z += 1; } var boundSizeOri = boundOri.getSize(new Vector3()); var expand = o.boundExpandRatio || math.linearClamp(Math.max(boundSizeOri.x, boundSizeOri.y), [0.5, 30], [2.5, 1.2]); //为了能同时看清测量线和地图,当测量线较短时,扩大margin,防止地图过度放大 var boundSizeMap = boundSizeOri.clone(); boundSizeMap.x *= expand, boundSizeMap.y *= expand; boundSizeMap.x = Math.max(minBound.x, boundSizeMap.x); boundSizeMap.y = Math.max(minBound.y, boundSizeMap.y); this.mapViewer.moveTo(target.clone(), boundSizeMap, duration, o.margin, null, done); } }; if (o.onlyMap) { moveMap(() => { deferred.resolve(); }); return { promise: deferred.promise() }; } var getPosWithFullBound = (points, boundingBox, target, cameraPos) => { //使boundingBox差不多占满屏幕时的相机到target的距离 // points 和 boundingBox 至少有一个 var scale; if (o.dontChangeCamDir) { var inv = camera.matrixWorldInverse; } else { var cameraTemp = camera.clone(); var view = viewer.mainViewport.view.clone(); view.position.copy(cameraPos); view.lookAt(target); if (o.endPitch != void 0) { view.pitch = o.endPitch; view.yaw = o.endYaw; } view.applyToCamera(cameraTemp); //对镜头的bound var inv = cameraTemp.matrixWorldInverse; } var bound = new Box3(); if (points) { //使用points得到的bound更小 //如果points和boundingbox的差别较大,尤其使target和points中心不一致,那么points不一定会刚好在boundingbox内 points.forEach(e => { var p = e.clone().applyMatrix4(inv); bound.expandByPoint(p); }); scale = 1.2; } else { bound = boundingBox.applyMatrix4(inv); scale = 1; //0.9; } boundSize = bound.getSize(new Vector3()); if (o.boundScale) { scale = o.boundScale; } { boundSize.x *= scale; //稍微放大一些,不然会靠到屏幕边缘 boundSize.y *= scale; var min = 0.0001; boundSize.x = Math.max(min, boundSize.x); boundSize.y = Math.max(min, boundSize.y); } if (camera.type == 'OrthographicCamera') { dis = boundSize.length() / 2; } else { var aspect = boundSize.x / boundSize.y; if (camera.aspect > aspect) { //视野更宽则用bound的纵向来决定 dis = boundSize.y / 2 / Math.tan(MathUtils.degToRad(camera.fov / 2)) + boundSize.z / 2; } else { var hfov = cameraLight.getHFOVForCamera(camera, true); dis = boundSize.x / 2 / Math.tan(hfov / 2) + boundSize.z / 2; } dis += camera.near; } dis = Math.max(0.1, dis); //三个顶点以上的由于measure的中心不等于bound的中心,所以点会超出bound外。 且由于视椎近大远小,即使是两个点的,bound居中后线看上去仍旧不居中. //获得相机最佳位置 var dir; if (o.dontChangeCamDir) { dir = viewer.mainViewport.view.direction.negate(); } else { dir = new Vector3().subVectors(cameraPos, target).normalize(); } if (o.dontLookUp && dir.z < 0) { dir.negate(); } position.copy(target).add(dir.multiplyScalar(dis)); if (false) { //打开以检查box if (!this.boundBox) { //调试 this.boundBox = new Mesh(new BoxGeometry(1, 1, 1, 1)); this.boundBox.material.wireframe = true; this.boundBox.up.set(0, 0, 1); Potree.Utils.setObjectLayers(this.boundBox, 'sceneObjects'); this.scene.scene.add(this.boundBox); } this.boundBox.position.copy(target); this.boundBox.scale.copy(boundSize); this.boundBox.lookAt(position); } return position; }; if (this.images360.flying) { var f = () => { this.focusOnObject(object, type, duration, $.extend(o, { deferred })); this.images360.removeEventListener('cameraMoveDone', f); }; this.images360.addEventListener('cameraMoveDone', f); return { promise: deferred.promise() }; } if (type == 'measure') { if (object.points.length == 0) { return { promise: deferred.resolve() }; } target.copy(object.getCenter()); //试试改变位置(方向),直视测量线。能避免倾斜角度造成的非常不居中、以及看不到面的情况 if (o.gotoBestView) { //直接沿着法线方向看 if (object.points.length > 2) { var facePlane = object.getFacePlane(target); var normal = facePlane.normal.clone(); if (normal.dot(this.mainViewport.view.direction) > 0) { normal.negate(); //顺着视线 } //normal.z = Math.max(0.2, normal.z)//尽量不要仰视 cameraPos.copy(target).add(normal); } else { var lineDir = new Vector3().subVectors(object.points[0], object.points[1]).normalize(); var _facePlane = new Plane().setFromNormalAndCoplanarPoint(lineDir, target); //if(cameraPos.z < target.z + 1)cameraPos.z = target.z + 1//尽量不要仰视 var dir = new Vector3().subVectors(cameraPos, target).normalize(); dir.z = Math.max(dir.z, 0.4); cameraPos.copy(target).add(dir); //尽量不要仰视 var _dis = cameraPos.distanceTo(target); dir = lineDir.clone().multiplyScalar(_dis); var line = new Line3().set(cameraPos.clone().add(dir), cameraPos.clone().add(dir.negate())); //过相机位置作到面的垂线 _facePlane.intersectLine(line, cameraPos); //得垂足,作为新的相机位置。就能在测量线中间看测量线 } } else { if (object.points.length > 2) { var _facePlane2 = object.getFacePlane(target); var _normal = _facePlane2.normal.clone(); var angle = this.mainViewport.view.direction.angleTo(_normal); var minDiff = MathUtils.degToRad(60); //console.log('angle',angle) if (angle > minDiff && angle < Math.PI - minDiff) { //当几乎正对时就不执行 if (angle < Math.PI / 2) { //在背面 _normal.negate(); } var _dir = new Vector3().subVectors(camera.position, target).normalize(); var newDir = new Vector3().addVectors(_dir, _normal); //两个角度的中间 cameraPos.copy(target.clone().add(newDir)); } } else if (object.points.length == 2) { //线段 var _lineDir = new Vector3().subVectors(object.points[0], object.points[1]).normalize(); var _angle = this.mainViewport.view.direction.angleTo(_lineDir); var maxDiff = Math.PI * 0.25; // 45度 if (_angle < maxDiff || _angle > Math.PI - maxDiff) { //当几乎正对时就不执行 if (_angle > Math.PI / 2) { //令dir和lineDir成钝角 _lineDir.negate(); } var _dir2 = new Vector3().subVectors(camera.position, target).normalize(); var mid = new Vector3().addVectors(_lineDir, _dir2).normalize(); //中间法向量(如果刚好dir和lineDir反向,那得到的为零向量,就不移动了,但一般不会酱紫吧) var _newDir = new Vector3().addVectors(_dir2, mid); cameraPos.copy(target.clone().add(_newDir)); } } else { console.error('measure 没有facePlane points点数还不为2?'); } } //截图时直接飞到最佳视角,也就是平视它所在面。其余时候为了避免镜头旋转过大就算了。 position = getPosWithFullBound(object.points, null, target, cameraPos); moveMap(); if (Potree.settings.displayMode == 'showPointCloud') { //点云 var minDis = 0.3; if (0) { //如果没有被选中,会被遮挡。 2023.11.15 最好展示全局(尤其截图时),虽然被遮挡,但focus的过程是选中状态全显示的,可以看出所在范围。 var checkIntersect = () => { var intersect = this.inputHandler.ifBlockedByIntersect({ point: position, cameraPos: target }); // 不一定准确 if (intersect) { var blockCount = 0, unblockCount = 0, visi; for (var i = 0; i < object.points.length; i++) { //如果顶点超过一半不可见,就要更改位置 var p = object.points[i]; var blocked = this.inputHandler.ifBlockedByIntersect({ point: p, margin: 0.3, cameraPos: position, pickWindowSize: 4 }); if (blocked) { blockCount++; if (blockCount / object.points.length >= 0.5) { visi = false; break; } } else { unblockCount++; if (unblockCount / object.points.length > 0.5) { visi = true; break; } } } if (visi == void 0) { visi = unblockCount / object.points.length > 0.5; } var shrink = () => { var dir = new Vector3().subVectors(position, target).normalize().multiplyScalar(intersect.distance); position.copy(target).add(dir); console.log('checkIntersect newPos', position.clone()); }; if (!visi) { //更改位置距离target如果小于最小距离,需要反向。 否则直接缩短距离。 if (intersect.distance < minDis) { console.log('检测到intersect 反向', intersect.distance); var position1 = position.clone(); var _dir3 = new Vector3().subVectors(position, target); position.copy(target).sub(_dir3); var intersect2 = this.inputHandler.ifBlockedByIntersect({ point: position, cameraPos: target }); // 不一定准确 if (intersect2) { if (intersect2.distance < intersect.distance) { position.copy(position1); //恢复 } shrink(); } } else { shrink(); } } } }; checkIntersect(); //多折线没有areaPlane 有时候会看向空白区域 - - } } else if (Potree.settings.displayMode == 'showPanos') { //全景 (比较难校准) var target2, _dir4; if (object.measureType.includes('MulDistance')) { //因为该线不闭合,可能看向target的方向会没有线,所以换一个target target2 = object.points[Math.round(object.points.length / 2)]; //直接看向中间点 _dir4 = new Vector3().subVectors(target2, position).normalize(); } var pano = viewer.images360.fitPanoTowardPoint({ /*point : target, //不使用目标点来判断是因为缺少measure角度的信息。比如虽然可以靠近线的中心,但是线朝向屏幕,那几乎就是一个点了。 //bestDistance : dis * 0.5, //乘以小数是为了尽量靠近 boundSphere: boundOri.getBoundingSphere(new THREE.Sphere), */ target, dir: _dir4, point: position, bestDistance: 0, checkIntersect: o.checkIntersect, gotoBestView: o.gotoBestView }); var result = { promise: deferred.promise() }; if (pano && pano.msg) { pano = pano.pano; result.msg = pano.msg; } if (pano) { viewer.images360.flyToPano({ pano, target: target2 || target, duration, deferred, dontMoveMap: true, basePanoSize: o.basePanoSize }); //dontMoveMap不要移动map,否则flytopano会自动在map中focus到漫游点的位置,而非测量线了 if (viewer.images360.currentPano == pano) { var dis1 = viewer.images360.currentPano.position.distanceTo(target); var dis2 = position.distanceTo(target); //console.log('dis1 / dis2',dis1 / dis2, 'dis1-dis2', dis1-dis2) return { msg: dis1 / dis2 > 1.5 && dis1 - dis2 > 10 ? 'tooFar' : 'posNoChange', promise: deferred.promise() }; } } return result; /* if(viewer.images360.currentPano == pano){ let dis1 = viewer.images360.currentPano.position.distanceTo(target) let dis2 = position.distanceTo(target) //console.log('dis1 / dis2',dis1 / dis2, 'dis1-dis2', dis1-dis2) return {msg: (dis1 / dis2 > 1.5 && dis1-dis2>10)? 'tooFar' : 'posNoChange', promise : deferred.promise() } }else{ return {promise : deferred.promise()} } */ //出现过到达位置后测量线标签闪烁的情况 // 测量线截图 全景 最好能放大. 但要确保该位置放大后图片加载完有点困难 } } else if (type == 'tag' || type == 'point') { //dimension = 1 target.copy(object.position); var bestDistance = o.distance || 3; if (!o.dontMoveMap && this.mapViewer) { //console.log('mapFocusOn: '+target.toArray()) this.mapViewer.moveTo(target.clone(), null, duration); } if (Potree.settings.displayMode == 'showPointCloud') { if (o.dontChangePos) { position.copy(cameraPos); } else { dis = bestDistance; var _dir5 = o.direction ? o.direction.clone().negate() : this.mainViewport.view.direction.negate(); // */new THREE.Vector3().subVectors(camera.position, target).normalize() if (o.dontLookUp && _dir5.z < 0) _dir5.z *= -1; position.copy(target).add(_dir5.multiplyScalar(dis)); } if (o.sameFloor) { //需要在同一楼层 var atFloor = this.modules.SiteModel.pointInWhichEntity(target, 'floor'); if (atFloor) { var camFloor = this.modules.SiteModel.pointInWhichEntity(position, 'floor'); if (camFloor != atFloor) { var raycaster = new Raycaster(); var origin = target; var _dir6 = new Vector3().subVectors(position, target).normalize(); raycaster.set(origin, _dir6); var intersect = Potree.Utils.getIntersect(null, [atFloor.box], null, raycaster); if (intersect) { var _dis2 = MathUtils.clamp(intersect.distance - 0.2, camera.near, intersect.distance); position.addVectors(origin, _dir6.multiplyScalar(_dis2)); console.log('移动到楼层'); } else { console.error('?no intersect?'); } } } } if (o.checkIntersect) { //识别被点云遮住的话 var _intersect; //反向查找从target到相机的第一个intersect _intersect = this.inputHandler.ifBlockedByIntersect({ point: position, margin: 0, cameraPos: target } /* {point:target, margin: 0.2, cameraPos:position} */); if (_intersect) { position.copy(_intersect.location); console.log('移近'); } } } else if (Potree.settings.displayMode == 'showPanos') { var _pano = viewer.images360.fitPanoTowardPoint({ point: target, dir: this.mainViewport.view.direction, //尽量不改相机方向,避免镜头晃动 checkIntersect: o.checkIntersect, sameFloor: o.sameFloor, bestDistance, maxDis: o.maxDis //越近越好,但不要太近,bestDistance左右差不多 }); var _result = { promise: deferred.promise() }; if (_pano && _pano.msg) { _pano = _pano.pano; _result.msg = _pano.msg; } _pano && viewer.images360.flyToPano({ pano: _pano, target, duration, deferred, dontMoveMap: true, basePanoSize: o.basePanoSize }); return _result; } } else if (object.boundingBox && type == 'boundingBox') { //使屏幕刚好看全boundingBox target = object.boundingBox.getCenter(new Vector3()); if (o.dir) { //指定方向 cameraPos.copy(target).sub(o.dir); } position = getPosWithFullBound(object.points, object.boundingBox.clone(), target, cameraPos); if (Potree.settings.displayMode == 'showPanos') { //全景 (比较难校准) var _pano2 = viewer.images360.fitPanoTowardPoint({ point: position, bestDistance: 0 }); var _result2 = { promise: deferred.promise() }; if (_pano2 && _pano2.msg) { _pano2 = _pano2.pano; _result2.msg = _pano2.msg; } _pano2 && viewer.images360.flyToPano({ pano: _pano2, target, duration, deferred, dontMoveMap: true, basePanoSize: o.basePanoSize }); //dontMoveMap不要移动map,否则flytopano会自动在map中focus到漫游点的位置,而非测量线了 if (!_pano2) { console.error('no pano'); } return _result2; //出现过到达位置后测量线标签闪烁的情况 } else { /* if(o.dontChangeCamDir){ target = null } */ moveMap(); } } if (o.startCamera && o.endCamera) { viewer.mainViewport.view.tranCamera(this.mainViewport, { endPosition: position, target, boundSize, callback: () => { //console.log('focusOnObjectSuccess: '+object.name, type) deferred.resolve(); }, startCamera: o.startCamera, endCamera: o.endCamera, midCamera: this.scene.cameraBasic, endYaw: o.endYaw, endPitch: o.endPitch }, duration); } else if (camera.type == "OrthographicCamera") { viewer.mainViewport.view.moveOrthoCamera(this.mainViewport, { endPosition: position, target, boundSize, endYaw: o.endYaw, endPitch: o.endPitch, callback: () => { //console.log('focusOnObjectSuccess: '+object.name, type) deferred.resolve(); } }, duration); } else { viewer.mainViewport.view.setView({ position, target, duration, endYaw: o.endYaw, endPitch: o.endPitch, callback: () => { //console.log('focusOnObjectSuccess: '+object.name, type) deferred.resolve(); } }); } this.dispatchEvent({ type: 'focusOnObject', CamTarget: target, position }); //给controls发送信息 return { promise: deferred.promise() }; } flyToDataset() { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var pointcloud; if (o instanceof Object3D) pointcloud = o;else if (o.pointcloud) pointcloud = o.pointcloud;else pointcloud = this.scene.pointclouds.find(p => p.dataset_id == o.id); var duration = o.duration == void 0 ? 1000 : o.duration; if (o.focusOnPoint || !pointcloud.panosBound) { //focus点云上一点,避免center区域刚好没有点 if (pointcloud.root.geometryNode) { var posArr = pointcloud.root.geometryNode.geometry.attributes.position.array; var count = pointcloud.root.geometryNode.geometry.attributes.position.count; var index = Math.ceil(count / 2); //随便取一个点 var point = new Vector3(posArr[index * 3 + 0], posArr[index * 3 + 1], posArr[index * 3 + 2]); //point.applyMatrix4(pointcloud.root.pointcloud.matrixWorld) point.applyMatrix4(pointcloud.root.sceneNode.matrixWorld); viewer.focusOnObject({ position: point }, 'point', duration, { dontChangeCamDir: true, distance: 15 }); o.dontMoveMap || viewer.mapViewer.fitToPointcloud(pointcloud, duration); console.log('flyToDataset focusOnPoint done'); return; } } var center = pointcloud.bound.getCenter(new Vector3()); var position; var getPano = () => { //获取离中心最近的pano var request = []; var rank = [Images360.scoreFunctions.distanceSquared({ position: center })]; var r = Common.sortByScore(pointcloud.panos, request, rank); if (r.length) { return r[0].item; } }; if (Potree.settings.displayMode == 'showPanos') { var pano = getPano(); if (pano) { if (pano == this.images360.currentPano) return 'posNoChange'; this.images360.flyToPano({ pano }); } else return false; } else { var target; position = center; if (pointcloud.panosBound) { var panosCenter = pointcloud.panosBound.center; //pano集中的地方,也就是真正有点云的地方 position = panosCenter.clone(); /* let ratio = 0.2 position.z = center.z * ratio + panosCenter.z * (1-ratio) //因为panos一般比较低,为了不让相机朝下时看不到点云,加一丢丢中心高度 */ var _pano3 = getPano(); if (_pano3) { target = _pano3.position; //针对像隧道一样的场景, 中心点还是panosCenter都在没有点云的地方,所以还是看向其中一个漫游点好。 position.z = target.z; //水平, 避免朝上或朝下 } } if (this.modules.Clip.editing) { position.z = center.z; //剪裁时在中心高度,因为以点云为重点 this.modules.Clip.bus.dispatchEvent({ type: 'flyToPos', position, duration }); } else { if (math.closeTo(position, this.images360.position)) return 'posNoChange'; viewer.mainViewport.view.setView({ position, target, duration }); } o.dontMoveMap || viewer.mapViewer.fitToPointcloud(pointcloud, duration); } return true; } findClosestDatasetOnMap(position) { //寻找当前平面图上离某点最近的数据集 var pointclouds = viewer.scene.pointclouds.filter(e => e.visible); var addScore = viewer.bound.boundSize.length(); var r = Potree.Common.sortByScore(pointclouds, [], [e => { //pos2d和bound2d距离排序 var pos3d = position.clone().setZ(e.panosBound ? e.panosBound.center.z : (e.bound.min.z + e.bound.max.z) / 2); return -(e.panosBound ? e.panosBound.bounding : e.bound).distanceToPoint(pos3d); }, e => { //最有可能的是地图上显示的平面图 return e in viewer.fpVisiDatasets ? addScore : 0; }]); return r[0] && r[0].item; } addTimeMark(name, type) { var record = Potree.timeCollect[name]; var needRecord = record && record.start && record.measures.length < record.minCount; if (needRecord || Potree.measureTimings) { performance.mark(name + "-" + type); if (type == 'end') { var measure = performance.measure(name, name + "-start", name + "-end"); if (needRecord) { if (!measure) { //有出现过手机的depthSamChangeImg得不到measure,可能是因为时间太长在resolveTimings被清除了? iphone8 plus ios14.1 型号MQ8F2CH/A return; //console.log('未能得到performance.measure',name) } record.measures.push(measure.duration); record.sum += measure.duration; record.ave = record.sum / record.measures.length; record.measures.sort((a, b) => a - b); record.median = record.measures[parseInt(record.measures.length / 2)]; } } } } addFakeMeasure(name, duration) { //把一些count当做duration来统计 if (!Potree.measureTimings) return; if (!this.fakeMeasure[name]) { this.fakeMeasure[name] = []; } var object = { name, duration }; this.fakeMeasure[name].push(object); } resolveTimings(timestamp, log) { //打印用时。 注:performance手机的精度只到整数位 。 sidebar中监听update时有高cpu的函数所以不要用demo测 if (!this.toggle) { this.toggle = timestamp; } var duration = timestamp - this.toggle; if (duration > 4000.0) { if (log) { var measures = performance.getEntriesByType("measure"); for (var i in this.fakeMeasure) { measures.push(...this.fakeMeasure[i]); } var names = new Set(); for (var measure of measures) { names.add(measure.name); } var groups = new Map(); for (var name of names) { groups.set(name, { measures: [], sum: 0, n: 0, min: Infinity, max: -Infinity }); } for (var _measure of measures) { var group = groups.get(_measure.name); group.measures.push(_measure); group.sum += _measure.duration; group.n++; group.min = Math.min(group.min, _measure.duration); group.max = Math.max(group.max, _measure.duration); } /* let glQueries = Potree.resolveQueries(this.renderer.getContext()); // resolveQueries 无 for(let [key, value] of glQueries){ let group = { measures: value.map(v => {return {duration: v}}), sum: value.reduce( (a, i) => a + i, 0), n: value.length, min: Math.min(...value), max: Math.max(...value) }; let groupname = `[tq] ${key}`; groups.set(groupname, group); names.add(groupname); } */ for (var [_name, _group] of groups) { _group.mean = _group.sum / _group.n; /* group.measures.sort( (a, b) => a.duration - b.duration ); if(group.n === 1){ group.median = group.measures[0].duration; }else if(group.n > 1){ group.median = group.measures[parseInt(group.n / 2)].duration; } */ var _measures = _group.measures.slice(); _measures.sort((a, b) => a.duration - b.duration); if (_group.n === 1) { _group.median = _measures[0].duration; } else if (_group.n > 1) { _group.median = _measures[parseInt(_group.n / 2)].duration; } } var cn = Array.from(names).reduce((a, i) => Math.max(a, i.length), 0) + 5; var cmin = 6; var cmed = 6; var cmax = 6; var csam = 4; var message = " ".concat("NAME".padEnd(cn), " |") + " ".concat("MIN".padStart(cmin), " |") + " ".concat("MEDIAN".padStart(cmed), " |") + " ".concat("MAX".padStart(cmax), " |") + " ".concat("AVE".padStart(cmax), " |") + " ".concat("SAMPLES".padStart(csam), " \n"); message += " ".concat("-".repeat(message.length), "\n"); names = Array.from(names).sort(); for (var _name2 of names) { var _group2 = groups.get(_name2); var min = _group2.min.toFixed(3); var median = _group2.median.toFixed(3); var max = _group2.max.toFixed(3); var ave = _group2.mean.toFixed(3); //add var n = _group2.n; message += " ".concat(_name2.padEnd(cn), " |") + " ".concat(min.padStart(cmin), " |") + " ".concat(median.padStart(cmed), " |") + " ".concat(max.padStart(cmax), " |") + " ".concat(ave.padStart(cmax), " |") + " ".concat(n.toString().padStart(csam), "\n"); } message += "\n"; console.log(message); } this.fakeMeasure = {}; //clear performance.clearMarks(); performance.clearMeasures(); this.toggle = timestamp; } //注意,console.log本身用时挺高,降4倍时可能占用0.5毫秒,所以不能每帧都打印 } loop(timestamp) { //let startTime = performance.now() //console.log('间隔:' /*, parseInt((startTime - this.lastEndTime)*100 )/100 */) if (this.paused) return; if (performance.getEntriesByName("loopWaitNext-start").length) viewer.addTimeMark('loopWaitNext', 'end'); if (this.stats) { this.stats.begin(); } performance.mark('loop-start'); // 无论有没有reportTimings都要获取,因为getBestCound需要 this.dispatchEvent('loopStart'); this.interacted = false; this.shelterCount = { byTex: 0, byCloud: 0, maxByTex: 100, maxByCloud: 0 }; //清空 因ifPointBlockedByIntersect可能在任何时候触发,所以需要一开始就定义这个,且每次计算最大可计算次数太麻烦了就定义一个吧。 var deltaTime = this.clock.getDelta(); this.update(deltaTime, timestamp); this.magnifier.render(); this.render(); this.setAllTilesets(model => model.runtime.update(deltaTime, this.renderer, this.mainViewport.camera)); // let vrActive = viewer.renderer.xr.isPresenting; // if(vrActive){ // this.update(this.clock.getDelta(), timestamp); // this.render(); // }else{ // this.update(this.clock.getDelta(), timestamp); // this.render(); // } Potree.framenumber++; //------------- this.images360.tileDownloader.update(); this.images360.panoRenderer.update(); this.images360.getNeighbours(this.interacted); this.computeShelter(); //------------- if (this.stats) { this.stats.end(); } viewer.addTimeMark('loop', 'end'); viewer.addTimeMark('loopWaitNext', 'start'); this.resolveTimings(timestamp, Potree.measureTimings); //Potree.measureTimings = 1 } postError(content) { var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var message = this.postMessage(content, params); message.element.addClass("potree_message_error"); return message; } postMessage(content) { var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var message = new Message(content); var animationDuration = 100; message.element.css("display", "none"); message.elClose.click(() => { message.element.slideToggle(animationDuration); var index = this.messages.indexOf(message); if (index >= 0) { this.messages.splice(index, 1); } }); this.elMessages.prepend(message.element); message.element.slideToggle(animationDuration); this.messages.push(message); if (params.duration !== undefined) { var fadeDuration = 500; var slideOutDuration = 200; setTimeout(() => { message.element.animate({ opacity: 0 }, fadeDuration); message.element.slideToggle(slideOutDuration); }, params.duration); } return message; } getBoundingBox(pointclouds) { //可以直接返回viewer.bound if (!this.bound) { this.updateModelBound(); } return this.bound.boundingBox.clone(); //this.scene.getBoundingBox(pointclouds); } updateModelBound(reason) { this.boundNeedUpdate = false; this.bound = Utils.computePointcloudsBound(this.scene.pointclouds.filter(pointcloud => //只求可见 pointcloud.visible || pointcloud.unvisibleReasons && pointcloud.unvisibleReasons.length == 1 && pointcloud.unvisibleReasons[0].reason == 'displayMode')); if (Potree.settings.boundAddObjs) { //加上obj的bound 需要确保都updateMatrixWorld过 this.objs.children.forEach(e => { this.bound.boundingBox.union(e.boundingBox.clone().applyMatrix4(e.matrixWorld)); }); this.bound.boundingBox.getSize(this.bound.boundSize); this.bound.boundingBox.getCenter(this.bound.center); } viewer.farWhenShowPano = this.bound.boundSize.length() * 10; //全景漫游时要能看到整个skybox 原本*2的但对于距离特远的数据集需要乘大一些否则会黑面 /* let boundPlane = new THREE.Box3() boundPlane.expandByPoint(this.bound.boundingBox.min.clone())//最低高度为bound的最低 boundPlane.expandByPoint(this.bound.boundingBox.max.clone().setZ(this.bound.center.z))//最高高度为bound的中心高度 FirstPersonControls.boundPlane = boundPlane */ //FirstPersonControls.standardSpeed = THREE.Math.clamp( Math.sqrt(this.bound.boundSize.length() )/ 100 , 0.02,0.5); //在这个boundPlane中的速度 viewer.scene.pointclouds.forEach(e => { //海拔范围 e.material.heightMin = this.bound.boundingBox.min.z; e.material.heightMax = this.bound.boundingBox.max.z; }); this.dispatchEvent({ type: 'updateModelBound' }); } waitForLoad(object, isLoadedCallback) { //等待加载时显示loading。主要是贴图 this.waitQueue.push({ object, isLoadedCallback }); //console.warn('waitForLoad',object.id,this.waitQueue.length) 1 === this.waitQueue.length && this.dispatchEvent({ type: "loading", show: true }); } ifAllLoaded() { if (this.waitQueue.length > 0) { this.waitQueue = this.waitQueue.filter(function (e) { return !e.isLoadedCallback(); }); } //console.warn('ifAllLoaded', this.waitQueue.length) 0 === this.waitQueue.length && this.dispatchEvent({ type: "loading", show: false }); } cancelLoad(object) { //add 突然出现还没加载完就被deactivateTiledPano但还在loading的情况,所以加了这个 this.waitQueue = this.waitQueue.filter(function (e) { return e.object != object; }); //console.log('cancelLoad', object.id) this.ifAllLoaded(); } setView() { var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var callback = () => { if (o.displayMode) { Potree.settings.displayMode = o.displayMode; } if (!o.pano && o.currentPano) this.images360.currentPano = o.currentPano; o.callback && o.callback(); }; if (o.pano != void 0) { //pano 权重高于 position this.images360.flyToPano(o); } else { this.mainViewport.view.setView($.extend({}, o, { callback })); } } //设置点云为标准模式 setPointStandardMat(state, pointDensity, fitPointsize) { console.log('setPointStandardMat', state); if (state) { if (this.pointStatesBefore) { return console.warn('已设置过pointStatesBefore!'); } this.pointStatesBefore = { opacity: new Map(), size: new Map(), density: Potree.settings.pointDensity, useEDL: this.getEDLEnabled(), shape: viewer.scene.pointclouds[0].material.shape }; viewer.scene.pointclouds.forEach(e => { this.pointStatesBefore.opacity.set(e, e.temp.pointOpacity); //因为更改pointDensity时会自动变opacity,所以这项最先获取 this.pointStatesBefore.colorType = e.material.activeAttributeName; fitPointsize && this.pointStatesBefore.size.set(e, e.temp.pointSize); //这项不一定有用,因为会被后期覆盖 }); if (pointDensity) Potree.settings.pointDensity = pointDensity; //万一之后切换到全景模式怎么办 if (fitPointsize) Potree.settings.sizeFitToLevel = true; viewer.scene.pointclouds.forEach(e => { e.material.activeAttributeName = 'rgba'; e.material.shape = Potree.PointShape['SQUARE']; fitPointsize && e.changePointSize(Potree.config.material.realPointSize, true); e.changePointOpacity(1); }); viewer.setEDLEnabled(false); } else { if (!this.pointStatesBefore) { return console.error('未设置过pointStatesBefore!'); } Potree.settings.sizeFitToLevel = false; if (pointDensity) Potree.settings.pointDensity = this.pointStatesBefore.pointDensity; viewer.scene.pointclouds.forEach(e => { e.material.activeAttributeName = this.pointStatesBefore.colorType; e.changePointOpacity(this.pointStatesBefore.opacity.get(e)); e.material.shape = this.pointStatesBefore.shape; var size = this.pointStatesBefore.size.get(e); if (size) e.changePointSize(size); }); viewer.setEDLEnabled(this.pointStatesBefore.useEDL); this.pointStatesBefore = null; } } //调试时显示transformControl来调节object transformObject(object) { var seleted = viewer.inputHandler.selection[0]; if (!object) { //取消 seleted && viewer.inputHandler.toggleSelection(seleted); return; } if (seleted && seleted != object) { //要更换,先取消 this.transformObject(null); } if (!object.boundingBox) { object.boundingBox = new Box3(); //任意大小 只是为了显示黄色外框 //??? computeBoundingBox } if (!viewer.inputHandler.selection.includes(object)) { viewer.inputHandler.toggleSelection(object); } } pointInWhichPointcloud(pos) { //选择最接近中心的那个 使用boundSphere var result = Common.sortByScore(this.scene.pointclouds, [], [pointcloud => { var size = pointcloud.pcoGeometry.tightBoundingBox.getSize(new Vector3()); var center = pointcloud.bound.getCenter(new Vector3()); var length = size.length() / 2; var dis = pos.distanceTo(center); return length / dis; //到数据集中心的距离占数据集大小越小越好 }]); //若要求更准确的话,可以使用ifContainsPoint判断一下是否在bound中 var r = result[0]; return r && r.score > 1 ? result[0].item : null; } /* createRoomEv(){ const environment = new RoomEnvironment(); const pmremGenerator = new THREE.PMREMGenerator( this.renderer ); } */ modelLoaded(object) { var fileInfo_ = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var done = arguments.length > 2 ? arguments[2] : undefined; //普通模型加载完以后 object.isModel = true; var boundingBox = new Box3(); if (fileInfo_.parentInfo) { object.name = fileInfo_.name; fileInfo_.parentInfo.loadedCount++; fileInfo_.parentInfo.modelGroup.add(object); if (fileInfo_.parentInfo.loadedCount == fileInfo_.parentInfo.url.length) { return this.modelLoaded(fileInfo_.parentInfo.modelGroup, fileInfo_.parentInfo, done); } else { return; } } object.name = fileInfo_.name != void 0 ? fileInfo_.name : fileInfo_.fileType; object.fileType = fileInfo_.fileType; object.boundingBox = boundingBox; //未乘上matrixWorld的本地boundingBox //object.scale.set(1,1,1);//先获取原始的大小时的boundingBox object.opacity = 1; //初始化 记录 object.updateMatrixWorld(); if (fileInfo_.id != void 0) object.dataset_id = fileInfo_.id; fileInfo_.loadCostTime = Date.now() - fileInfo_.loadStartTime; /* let weight = Math.round((total / 1024 / 1024) * 100) / 100;*/ console.log('加载完毕:', fileInfo_.name, Common.getNameFromURL(fileInfo_.url), '耗时(ms)', fileInfo_.loadCostTime /* 模型数据量:' + weight + 'M' */); if (fileInfo_.fileType == '3dTiles') { var isGroup = !object.runtime; var children = object.runtime ? [object] : object.children; children.forEach(object => { var boundingBox_ = new Box3(); var tileset = object.runtime.getTileset(); //TileHeader: tileset.root //参见另一个工程 TileRenderer.js preprocessNode //这个坐标位置几万…… let data = boundingVolume.halfAxes //但这个似乎是premultiply( transform );过后的,可能需还原下 var json = tileset.tileset; var box = json.root.boundingVolume.box; if (box) { var center = new Vector3(box[0], box[1], box[2]); var boundSize = new Vector3(); // get the extents of the bounds in each axis var vecX = new Vector3(box[3], box[4], box[5]); var vecY = new Vector3(box[6], box[7], box[8]); var vecZ = new Vector3(box[9], box[10], box[11]); var scaleX = vecX.length(); var scaleY = vecY.length(); var scaleZ = vecZ.length(); boundingBox_.min.set(-scaleX, -scaleY, -scaleZ); boundingBox_.max.set(scaleX, scaleY, scaleZ); if (isGroup) { //如果是多个拼成的,每个都保留原先在parent中的offset。 如果是外层,作为独立个体,不用理会位置信息,直接放中央。 object.position.copy(center); object.position.z *= -1; boundingBox_.translate(object.position); //由于是内层,其位移会改变整体的boundingbox } } else if (json.root.boundingVolume.sphere) { var sphereData = json.root.boundingVolume.sphere; var _center = new Vector3(...sphereData); var radius = sphereData[3] / 2; /* let sphere = new THREE.Sphere(center, radius) let box = sphere.getBoundingBox() boundingBox.copy(box) */ boundingBox_.min.set(-radius, -radius, -radius); boundingBox_.max.set(radius, radius, radius); } else { return console.error('json boundingVolume 缺少信息'); } //中心点居然没用。可能是漏用了什么信息,也许这和LVBADUI_qp是散的有关。 //console.log('3d tiles json',json) json.root.refine = 'ADD'; json.refine = 'ADD'; boundingBox.union(boundingBox_); }); } else { Potree.Utils.setObjectLayers(object, Potree.settings.showObjectsOnMap ? 'bothMapAndScene' : 'model'); object.traverse(child => { var is = child.isMesh || child instanceof Points || child.isLine; if (is) { child.renderOrder = Potree.config.renderOrders.model; //if(Potree.settings.boundAddObjs){ child.geometry.computeBoundingBox(); //console.log(child.matrixWorld.clone()) boundingBox.union(child.geometry.boundingBox.clone().applyMatrix4(child.matrixWorld)); //但感觉如果最外层object大小不为1,要还原下scale再乘 //}//获取在scale为1时,表现出的大小 //Potree.Utils.makeTexDontResize(child.material.map) //console.log(child.name, 'roughness',child.material.roughness,'metalness',child.material.metalness) if (fileInfo_.unlit && !(child.material instanceof BasicMaterial) /* || object.fileType == 'glb' */) { //注释掉是因为已经写入到loader文件里了 //let material = new THREE.MeshBasicMaterial({map:child.material.map}) var material = new BasicMaterial({ map: child.material.map, opacity: child.material.opacity, color: child.material.color }); //很奇怪glb的图会使原本的MeshBasicMaterial 会偏暗,所以自己重新写 //child.material.dispose() child.material = material; } if (fileInfo_.useStandandMat && !(child.material instanceof MeshStandardMaterial)) { child.material = new MeshStandardMaterial(); child.material.roughness = 0.7; child.material.metalness = 0.5; } //纯色的还是不能用BasicMaterial } }); } this.objs.add(object); if (fileInfo_.transform) { var setTransfrom = name => { var value = fileInfo_.transform[name]; if (!value) return; if (value instanceof Array) { object[name].fromArray(value); } else { object[name].copy(value); } }; setTransfrom('position'); setTransfrom('rotation'); setTransfrom('scale'); } if (fileInfo_.moveWithPointcloud) { object.updateMatrix(); object.matrixAutoUpdate = false; object.matrix.premultiply(viewer.scene.pointclouds[0].transformMatrix); //默认跟随第一个数据集 object.matrixWorldNeedsUpdate = true; } object.updateMatrixWorld(); MergeEditor.getBoundCenter(object); //初始化 done && done(object, fileInfo_); this.dispatchEvent({ type: 'modelLoaded', model: object }); //如果需要点击出现transform工具需要它有select事件 如 viewer.objs.children[1].addEventListener('select',()=>{}) } async loadModel(fileInfo, done, onProgress_, onError) { console.log('开始加载', fileInfo.name, Common.getNameFromURL(fileInfo.url)); var boundingBox = new Box3(); /* if(!Potree.settings.boundAddObjs){ boundingBox.min.set(-0.5,-0.5,-0.5); boundingBox.max.set(0.5,0.5,0.5) } */ if (fileInfo.objurl) { fileInfo.url = fileInfo.objurl, fileInfo.fileType = 'obj'; //兼容最早的 } if (fileInfo.url instanceof Array) { if (fileInfo.url.length == 1) { fileInfo.url = fileInfo.url[0]; } else { fileInfo.loadedCount = 0; fileInfo.modelGroup = new Object3D(); //parentGroup.name = fileInfo.title fileInfo.url.forEach((url, i) => { var fileInfoS = Common.CloneObject(fileInfo); fileInfoS.url = url; fileInfoS.name = 'child-' + i; fileInfoS.parentInfo = fileInfo; this.loadModel(fileInfoS, done, onProgress_, onError); }); return; } } fileInfo.url = Common.dealURL(fileInfo.url); //去除'+' fileInfo.loadStartTime = Date.now(); //let fileType = fileInfo.tilesUrl ? '3dTiles' : fileInfo.objurl ? 'obj' : 'glb' var loadDone = (object, fileInfo_) => { this.modelLoaded(object, fileInfo_ || fileInfo, done); }; var onProgress = function onProgress(xhr) { if (xhr.lengthComputable) { var percentComplete = xhr.loaded / xhr.total * 100; //console.log( Math.round(percentComplete, 2) + '% downloaded' ); onProgress_ && onProgress_(percentComplete); } }; if (fileInfo.fileType == 'obj') { //暂时不支持数组 if (fileInfo.mtlurl) { loaders.mtlLoader.load(fileInfo.mtlurl, materials => { materials.preload(); loaders.objLoader.setMaterials(materials).load(fileInfo.objurl, (object, total) => { loadDone(object /* , total, fileInfo.objurl */); }, onProgress, onError); }, onProgress, onError); } else { loaders.objLoader.load(fileInfo.objurl, (object, total) => { loadDone(object); }, onProgress, onError); } } else if (fileInfo.fileType == 'glb') { loaders.glbLoader.unlitMat = true; //!!fileInfo.unlit loaders.glbLoader.load(fileInfo.url, (gltf, total) => { //console.log('loadGLTF', gltf) loadDone(gltf.scene /* , total, fileInfo.url */); }, onProgress, onError); } else if (fileInfo.fileType == 'ply') { loaders.plyLoader.load(fileInfo.url, geometry => { var object; console.log('ply加载完毕', geometry); if (!geometry.index) { //点云 object = new Points(geometry, new PointsMaterial({ vertexColors: true, size: 0.02 })); //141M的点云,intersect费时300ms以上 } else { //mesh object = new Mesh(geometry); } loadDone(object); }); } else if (fileInfo.fileType == '3dTiles') { var result = await Loader3DTiles.load({ url: fileInfo.url, gltfLoader: loaders.glbLoader, //renderer: SceneRenderer.renderer options: { //dracoDecoderPath: '../utils/loaders/DRACOLoader/draco', //basisTranscoderPath: '../utils/loaders/KTX2Loader/basis', maximumScreenSpaceError: fileInfo.maximumScreenSpaceError || 80, //越小越清晰。 如果本身tiles很密很小这个值就不能很大。 //maxDepth: 100, //maximumMemoryUsage: 100, //缓存大小,见tiles3DMaxMemory。单位M(但实际结果是 2.5*maximumMemoryUsage + 750 。超过2G会崩, 所以应该小于540) 若太小,密集的tile反复加载很卡. (任务管理器刷新网页后若内存不掉就要结束进程否则虚高) debug: browser.urlHasValue('tilesBox'), //show box parent: this.scene.scene, is4dkk: fileInfo.is4dkk, //是否是4dkk中的模型. 通常maximumScreenSpaceError需要10 updateTime: fileInfo.updateTime //加后缀防止缓存 } }); //console.log(result) result.model.runtime = result.runtime; var loaded = false; var tileset = result.runtime.getTileset(); tileset.addEventListener('endTileLoading', function (data) { //Tileset3D if (data.loadingCount == 0 && !loaded) { loaded = true; //console.log('loaded!!!!!!!!!!!!!') } }); tileset.addEventListener('tileLoaded', e => { //每一个tile加载完要更改透明度 var opacity = result.model.parent == this.objs ? result.model.opacity : result.model.parent.opacity; //最多两层 MergeEditor.changeOpacity(e.tileContent, opacity); viewer.images360.judgeModelMat(e.tileContent); //set Layers ? Potree.Utils.setObjectLayers(e.tileContent, Potree.settings.showObjectsOnMap ? 'bothMapAndScene' : 'model'); }); { var vi = true; Object.defineProperty(result.model, "visible", { get: function get() { return vi; }, set: function set(v) { vi = v; result.model.visiChangeCallback(); } }); } var v = true; result.model.visiChangeCallback = () => { var visi = result.model.realVisible(); tileset.visible = visi; //同步,使不加载 if (v != visi) { tileset.nextForceUpdate = true; v = visi; } }; loadDone(result.model /* , null, fileInfo.url */); } else if (fileInfo.fileType == 'dxf') { loaders.dxfLoader.load(fileInfo.url, object => { loadDone(object); }, fileInfo); } else if (fileInfo.fileType == 'shp') { if (viewer.transform) { loaders.shapeLoader.transform = viewer.transform.lonlatToLocal; } var shp = await loaders.shapeLoader.load(fileInfo.url, fileInfo.color); var shpModel = shp.node; loadDone(shpModel); } else if (fileInfo.fileType == '3dgs') { var gsViewer = new Viewer({ rootElement: this.renderArea, threeScene: this.scene.scene, renderer: this.renderer, camera: this.mainViewport.camera, useBuiltInControls: false //dropInMode: true, // sharedMemoryForWorkers:false //否则 报错 Uncaught (in promise) DOMException: Failed to execute 'postMessage' on 'DedicatedWorkerGlobalScope': SharedArrayBuffer transfer requires self.crossOriginIsolated. }); //let path = Potree.resourcePath+'/models/gaussian/bonsai.ksplat'; gsViewer.addSplatScene(fileInfo.url, { 'streamView': true }).then(() => { gsViewer.start(); gsViewer.splatMesh.updateMatrix(); gsViewer.splatMesh.updateMatrixWorld(); gsViewer.splatMesh.onSplatTreeReadyCallback = () => { loadDone(gsViewer.splatMesh); var { sceneMax, sceneMin } = gsViewer.splatMesh.splatTree.subTrees[0]; gsViewer.splatMesh.boundingBox.min.copy(sceneMin); gsViewer.splatMesh.boundingBox.max.copy(sceneMax); }; var selfRaycaster = new Raycaster$1(); gsViewer.splatMesh.raycast = function (raycaster, intersects) { //重写 var hits = []; selfRaycaster.ray.setParameters(raycaster.ray.origin, raycaster.ray.direction); selfRaycaster.intersectSplatMesh(gsViewer.splatMesh, hits); hits.forEach(e => { e.object = gsViewer.splatMesh; e.point = e.origin; delete e.origin; }); intersects.push(...hits); }; //问题:感觉normal不准 }); //window.gsViewer = gsViewer viewer.addEventListener('render.begin2', e => { if (e.name == 'scene') { //gsViewer.selfDrivenUpdate() gsViewer.update(); if (gsViewer.initialized && gsViewer.splatRenderReady) {} } }); } } removeModel(model) { this.objs.remove(model); var dispose = e => { e.geometry && e.geometry.dispose(); e.material && e.material.dispose(); }; model.traverse(e => { dispose(e); }); if (Potree.settings.boundAddObjs) { this.updateModelBound(); } } setAllTilesets() { //让所有tileset执行fun。 objs里每个model最多两层tileset var models = arguments.length == 2 ? [arguments[0]] : this.objs.children; //如果要设定某个model的tileset,就传第一个参数 var fun = arguments[1] || arguments[0]; models.forEach(e => { if (e.fileType == '3dTiles') { e.traverse(child => { if (child.runtime) { fun(child); return { stopContinue: true }; } }); } }); } setDisplay(state) { var cause = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'setDisplay'; //如果创建了iframe,主页的需要隐藏的话需要释放一些内存出来。iframe关闭前也释放下比较保险 state = !!state; this.setAllTilesets(model => { var tileset = model.runtime.getTileset(); Potree.Utils.updateVisible(model, cause, state); if (!state) tileset._cache.trim(); //使下一次update时dispose所有不可见的tiles model.runtime.update(16, this.renderer, this.mainViewport.camera, true); if (state) this.dispatchEvent('content_changed'); }); if (state) { Potree.pointBudget = 6 * 1000 * 1000; //先随便写一个, 随后mergeEditor.updateMemoryUsage } else { Potree.pointBudget = 0; Potree.updatePointClouds(this.scene.pointclouds, this.mainViewport.camera, this.mainViewport.resolution); this.images360.panoRenderer.disposeIdelTargets(); //如果也能清空当前使用的就好了,但是恢复就需要时间 this.images360.depthSampler.clearTexData(); } this.dispatchEvent({ type: 'setDisplay', state }); this.paused = !state; } addFire() { if (Potree.settings.number == 't-CwfhfqJ') { var position = Potree.Utils.datasetPosTransform({ pointcloud: viewer.scene.pointclouds[0], position: new Vector3(4.4318, -0.580291847759, -0.78), fromDataset: true }); viewer.modules.ParticleEditor.addParticle({ type: 'fire', positions: [position], radius: 0.42, height: 10 }); viewer.modules.ParticleEditor.addParticle({ type: 'smoke', positions: [new Vector3().addVectors(position, new Vector3(0, 0, 0.3))], positionStyle: 'sphere', positionRadius: 0.3, sizeTween: [[0, 0.3, 0.9, 1], [0.05, 0.1, 1, 0.8]], opacityBase: 0.2, opacityTween: [[0, 0.3, 0.7, 0.95, 1], [0, 0.2, 1, 0.1, 0]], velocityBase: new Vector3(0, 0, 1), velocitySpread: new Vector3(0.2, 0.2, -0.3), accelerationBase: 0.2, accelerationSpread: 0.7, radius: 0, //particlesPerSecond : 30, particleDeathAge: 3.0 }); viewer.modules.ParticleEditor.addParticle({ type: 'explode', name: 'fire splash', position: new Vector3().addVectors(position, new Vector3(0, 0, 0.3)), size: 0.1, sizeRange: 0.3, sizeTween: [[0, 0.05, 0.3, 0.45], [0, 0.02, 0.1, 0.05]], opacityTween: [[0, 0.05, 0.3, 0.45], [1, 1, 0.5, 0]], speed: 1, //sphere speedRange: 4, radius: 0.1, acceleration: 0.3, accelerationRange: 1, particleSpaceTime: 0, strength: 4 }); } } addVideo() { if (Potree.settings.number != 'SS-t-P6zBR73Gke') return; var geo = new PlaneGeometry(1, 1, 1, 1); var videoInfo = this.videoInfo = [{ id: '40-2', url: 'https://laser-oss.4dkankan.com/testdata/SS-t-P6zBR73Gke/temp/poi/2022/05/10/0aabafee-36b8-455d-9c11-0780bf694786.mp4', rotation: [-1.494468618954883, -1.4987317433158989, -3.061254983446741], position: [19.801820617361624, 2.884673619844108, -0.03362305858221648], scale: [3.5741423153151763, 2.8738725275578703, 1] }, { id: 40, /* rotation:[-1.534692822378723, 0.01083403560862361, 3.141535283661569], position:[17.2934294239949861, 2.413510747928117, -0.008057029580231356], */ url: 'https://laser-oss.4dkankan.com/testdata/SS-t-P6zBR73Gke/temp/poi/2022/05/09/7896d6ef-a2d6-4fd7-949c-768782a5b484.mp4', rotation: [-1.5487684197910518, 0.021848470169552752, -3.1387534893955236], position: [17.277316608096, 2.0840432922115846, -0.0931149415437065], scale: [2.0821757723834047, 0.6129478480765236, 1], visibles: [40] }]; var add = info => { var video = $("")[0]; video.setAttribute("crossOrigin", 'Anonymous'); video.src = info.url || Potree.resourcePath + "/video/".concat(Potree.settings.number, "/").concat(info.id, ".mp4"); var map = new VideoTexture(video); var plane = this.videoPlane = new Mesh(geo, new MeshBasicMaterial({ color: "#ffffff", transparent: !0, depthTest: false, opacity: 0, //side:2, map })); plane.position.fromArray(info.position); plane.rotation.fromArray(info.rotation); info.scale && plane.scale.fromArray(info.scale); this.scene.scene.add(plane); info.plane = plane; plane.boundingBox = new Box3(new Vector3(0, -0.5, 0), new Vector3(1, -0.4, 0.2)); video.addEventListener('loadeddata', function (e) { video.play(); if (!info.visibles /* ||!viewer.images360.currentPano || info.visibles.includes(viewer.images360.currentPano.id) */) { plane.material.opacity = 1; } info.scale || plane.scale.set(video.videoWidth / 1000, video.videoHeight / 1000, 1); // 1080 * 1920 console.log('video loadeddata', info.id); }); if (info.visibles) { this.images360.addEventListener('flyToPano', e => { //飞之前 if (info.visibles.includes(e.toPano.pano.id)) { //出现 setTimeout(() => { plane.visible = true; video.currentTime = 0; video.play(); if (video.paused) { var startPlay = () => { plane.visible && video.play(); this.removeEventListener('global_mousedown', startPlay); }; this.addEventListener('global_mousedown', startPlay); } Potree.settings.zoom.enabled = false; transitions$1.start(lerp.property(plane.material, "opacity", 1), e.toPano.duration * 0.4, () => {}, 0, easing['easeInOutQuad']); }, e.toPano.duration * 0.6); //时间上不能和消失的重叠 延迟 } else { //消失 transitions$1.start(lerp.property(plane.material, "opacity", 0), e.toPano.duration * 0.4, () => { if (!info) { plane.visible = false; video.pause(); Potree.settings.zoom.enabled = true; } }, 0, easing['easeInOutQuad']); } }); } var startPlay = () => { video.play(); //video.pause() //video.currentTime = 0.1; this.removeEventListener('global_mousedown', startPlay); }; this.addEventListener('global_mousedown', startPlay); Potree.settings.isTest && plane.addEventListener('select', e => { console.log(e); }); }; videoInfo.forEach(info => { add(info); }); /* this.images360.addEventListener('flyToPano' ,(e)=>{//飞之前 if(Potree.settings.displayMode != 'showPanos') return let info = videoInfo[e.toPano.pano.id] if(info ){ //出现 setTimeout(()=>{ plane.visible = true; plane.position.fromArray(info.position) plane.rotation.fromArray(info.rotation) video.src = Potree.resourcePath+`/video/${Potree.settings.number}/${e.toPano.pano.id}.mp4` video.play(); video.currentTime = 0 Potree.settings.zoom.enabled = false transitions.start(lerp.property(plane.material, "opacity", 1 ) , e.toPano.duration*0.4 , ()=>{ }, 0, easing['easeInOutQuad']) }, e.toPano.duration*0.6) //时间上不能和消失的重叠 延迟 } //消失 transitions.start(lerp.property(plane.material, "opacity", 0, ) , e.toPano.duration*0.4, ()=>{ if(!info){ plane.visible = false video.pause() Potree.settings.zoom.enabled = true } }, 0, easing['easeInOutQuad']) }) this.images360.addEventListener('endChangeMode',(e)=>{ //暂时不处理初始加载时就在有视频的点位上的情况 if(e.mode == 'showPanos'){ let info = videoInfo[this.images360.currentPano.id] if(info ){ //出现 plane.visible = true; plane.position.fromArray(info.position) plane.rotation.fromArray(info.rotation) plane.material.opacity = 0 video.src = Potree.resourcePath+`/video/${Potree.settings.number}/${this.images360.currentPano.id}.mp4` video.play(); video.currentTime = 0 Potree.settings.zoom.enabled = false transitions.start(lerp.property(plane.material, "opacity", 1, (e)=>{console.log('fadeIn',e)}) , 300 , ()=>{ }, 0, easing['easeInOutQuad']) } }else{ plane.visible = false; Potree.settings.zoom.enabled = true } }) */ } /* addTube(){//加水管 自动生成 if(Potree.settings.number == 't-8KbK1JjubE'){ let boundingBox = new THREE.Box3() boundingBox.min.set(-1,-1,-1); boundingBox.max.set(1,1,1) let radius = 0.08; let radialSegments = 5 let radSegments = Math.PI*2 / radialSegments var circlePts = [];//横截面 for(let i=0;i{//height:在path之上的高度,负数代表在path之下 var name = 'cylinder'+count var mat = new THREE.MeshStandardMaterial({color, depthTest:false, roughness:0.4,metalness:0.5})  let linePath = path.map(e=>new THREE.Vector3().copy(e).setZ(e.z+height)) let geo = MeshDraw.getExtrudeGeo( circlePts, null,{ extrudePath:linePath, tension:0.2} ) var mesh = new THREE.Mesh(geo,mat); mesh.name = name window[name] = mesh mesh.boundingBox = boundingBox mesh.matrixAutoUpdate = false mesh.matrix.copy(viewer.scene.pointclouds[0].transformMatrix) mesh.matrixWorldNeedsUpdate = true this.scene.scene.add(mesh); count ++ } let linePath, height //地上管子 黄色 linePath = [{"x":-109.83,"y":-68.33,"z":-7.52},{"x":-95.17,"y":-59.3,"z":-7.38}, {"x":-38.75,"y":-24.01,"z":-6.01},{"x":0.5,"y":0.19,"z":-3.89},{"x":39.29,"y":24.41,"z":-1.31} ,{"x":43.58,"y":27.7,"z":-0.97},{"x":40.22,"y":35.37,"z":-0.67}// 拐弯向右 , {"x":39.18,"y":36.71,"z":0.35},{"x":38.69,"y":36.04,"z":18.04} // 拐弯向上 ] height = radius + 0.05; addMesh('#b86', linePath, height) //地下管子 藍色 linePath = [{"x":-108.24,"y":-70.61,"z":-7.52}, {"x":-57.8,"y":-39.31,"z":-6.72},{"x":-18.8,"y":-15.35,"z":-5.01},{"x":55.87,"y":31.67,"z":-0.04},{"x":110.53,"y":66.48,"z":5.14} ] height = -0.5; addMesh('#48a', linePath, height) } } */ addTube(datas) { var _this2 = this; var _loop = function _loop() { if (number == Potree.settings.number) { var data = datas[number]; var boundingBox = new Box3(); boundingBox.min.set(-1, -1, -1); boundingBox.max.set(1, 1, 1); index = 0; addMesh = function addMesh() { var { color, path, height, fromDataset, radius = 0.08, datasetId = Potree.settings.originDatasetId, spaceDis, tension = 0.1, visiEntity } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; //height:在path之上的高度,负数代表在path之下 var name = 'tube_' + index; var radialSegments = 30; //THREE.Math.clamp( Math.round(radius * 800), 10, 40) var radSegments = Math.PI * 2 / radialSegments; var circlePts = []; //横截面 for (var i = 0; i < radialSegments; i++) { var angle = radSegments * i; circlePts.push(new Vector2(radius * Math.cos(angle), radius * Math.sin(angle))); } var mat = new MeshStandardMaterial({ color, /* wireframe:true, depthTest:false,*/roughness: 0.9, metalness: 0.3 }); var linePath = path.map(e => { e instanceof Array && (e = new Vector3().fromArray(e)); var pos; if (fromDataset) { //获取:JSON.stringify(viewer.scene.measurements[0].dataset_points.map(e=>Potree.math.toPrecision(e.toArray(),3))) pos = Potree.Utils.datasetPosTransform({ fromDataset: true, position: e, datasetId }); } else { pos = new Vector3().copy(e); } return pos.setZ(pos.z + height); }); console.log(linePath); var geo = MeshDraw.getExtrudeGeo(circlePts, null, { extrudePath: linePath, tension, spaceDis }); var mesh = new Mesh(geo, mat); mesh.name = name; window[name] = mesh; mesh.boundingBox = boundingBox; mesh.matrixAutoUpdate = false; fromDataset || mesh.matrix.copy(viewer.scene.pointclouds[0].transformMatrix); mesh.matrixWorldNeedsUpdate = true; _this2.scene.scene.add(mesh); if (visiEntity) { _this2.modules.SiteModel.bus.addEventListener('buildingChange', e => { Potree.Utils.updateVisible(mesh, 'isInEntity', e.entity && e.entity.name == visiEntity); }); } }; while (index < data.length) { addMesh(data[index]); index++; } } }, index, addMesh; //加水管 自动生成 for (var number in datas) { _loop(); } /* 可能用到的 viewer.scene.measurements.forEach(e=>e.edgeLabels.forEach(e=>Potree.Utils.updateVisible(e,'f',false))) JSON.stringify(viewer.scene.measurements.find(e=>e.visible).dataset_points.map(e=>Potree.math.toPrecision(e.toArray(),3))) */ } addSprite(e) { //api var sprite; if (e.text != void 0) { sprite = new TextSprite(e); } else { var map = texLoader.load(src); e.map = map; sprite = new Sprite(e); } return sprite; } } ; //------ CLIP 默认clipTask都是clipInside ---------------------- /* 并集相当于加法,交集相当于乘法。 所有结果都能展开成多个乘积相加。 假设有4个clipBoxes,ABCD, 如果是 A*B + C*D ,那么这是最终结果。 如果是 (A+B)*(C+D) = A*C+A*D+B*C+B*D */ /* let Clips = { boxes : [], unionGroups : [], //二维数组。最外层要求并集,里层要求交集(如果只有一个元素就是本身)。总结起来就是要求一堆交集的并集 shaderParams:{}, needsUpdate : true, addClip(box, clipMethod){ //不允许重复 if(this.boxes.includes(box)){ return console.warn('addClip重复添加了box',box) } boxes.push(box) if(clipMethod == 'any'){//并 this.unionGroups.push([box]) }else if(clipMethod == 'all'){//交 this.unionGroups.forEach(mixGroup=>mixGroup.push(box)) } this.needsUpdate = true }, removeClip(box){ if(!this.boxes.includes(box)){ return console.warn('removeClip没有找到该box',box) } var newGroups = []; this.unionGroups.forEach(mixGroup=>{ if(mixGroup.length == 1 && mixGroup[0] == box)return;//直接删除 newGroups.push(mixGroup.filter(e=>e!=box)); }) this.unionGroups = newGroups; this.needsUpdate = true } , clearClip(){ this.boxes = []; this.unionGroups = [] this.needsUpdate = true } , updateShaderParams(){//没写完 - - 见 pointcloud clip.vs //uniform mat4 clipBoxes[num_clipboxes]; //uniform int clipBoxGroupCount; //uniform int mixClipIndices[clipboxGroupItemCount]; //把所有的要求都直接放到数组内 //这里需要转为Float32Array..? 参考material.setClipBoxes let everyClipGroupCount = this.unionGroups.map(e=>e.length) let mixClipIndices = [] this.unionGroups.forEach(e=>{ mixClipIndices.push(...e) }) this.shaderParams = { num_clipboxes : this.boxes.length, clipBoxGroupCount : this.unionGroups.length, everyClipGroupCount, clipBoxIndexCount: mixClipIndices.length, mixClipIndices } } , getShaderParams(){//每次要传递参数到shader中,执行这个就好 if(this.needsUpdate){ this.updateShaderParams() } return this.shaderParams } } */ /** * @author mschuetz / http://mschuetz.at * * adapted from THREE.OrbitControls by * * @author qiao / https://github.com/qiao * @author mrdoob / http://mrdoob.com * @author alteredq / http://alteredqualia.com/ * @author WestLangley / http://github.com/WestLangley * @author erich666 / http://erichaines.com * * * */ class OrbitControls$2 extends EventDispatcher$1 { constructor(viewer) { super(); this.viewer = viewer; this.renderer = viewer.renderer; this.scene = null; this.sceneControls = new Scene(); this.rotationSpeed = 5; this.fadeFactor = 20; this.yawDelta = 0; this.pitchDelta = 0; this.panDelta = new Vector2(0, 0); this.radiusDelta = 0; this.doubleClockZoomEnabled = true; this.tweens = []; var drag = e => { if (e.drag.object !== null) { return; } if (e.drag.startHandled === undefined) { e.drag.startHandled = true; this.dispatchEvent({ type: 'start' }); } var ndrag = { x: e.drag.lastDrag.x / this.renderer.domElement.clientWidth, y: e.drag.lastDrag.y / this.renderer.domElement.clientHeight }; if (e.drag.mouse === MOUSE$1.LEFT) { this.yawDelta += ndrag.x * this.rotationSpeed; this.pitchDelta += ndrag.y * this.rotationSpeed; this.stopTweens(); } else if (e.drag.mouse === MOUSE$1.RIGHT) { this.panDelta.x += ndrag.x; this.panDelta.y += ndrag.y; this.stopTweens(); } }; var drop = e => { this.dispatchEvent({ type: 'end' }); }; var scroll = e => { var resolvedRadius = this.scene.view.radius + this.radiusDelta; this.radiusDelta += -e.delta * resolvedRadius * 0.1; this.stopTweens(); }; var dblclick = e => { if (this.doubleClockZoomEnabled) { this.zoomToLocation(e.mouse); } }; var previousTouch = null; var touchStart = e => { previousTouch = e; }; var touchEnd = e => { previousTouch = e; }; var touchMove = e => { if (e.touches.length === 2 && previousTouch.touches.length === 2) { var prev = previousTouch; var curr = e; var prevDX = prev.touches[0].pageX - prev.touches[1].pageX; var prevDY = prev.touches[0].pageY - prev.touches[1].pageY; var prevDist = Math.sqrt(prevDX * prevDX + prevDY * prevDY); var currDX = curr.touches[0].pageX - curr.touches[1].pageX; var currDY = curr.touches[0].pageY - curr.touches[1].pageY; var currDist = Math.sqrt(currDX * currDX + currDY * currDY); var delta = currDist / prevDist; var resolvedRadius = this.scene.view.radius + this.radiusDelta; var newRadius = resolvedRadius / delta; this.radiusDelta = newRadius - resolvedRadius; this.stopTweens(); } else if (e.touches.length === 3 && previousTouch.touches.length === 3) { var _prev = previousTouch; var _curr = e; var prevMeanX = (_prev.touches[0].pageX + _prev.touches[1].pageX + _prev.touches[2].pageX) / 3; var prevMeanY = (_prev.touches[0].pageY + _prev.touches[1].pageY + _prev.touches[2].pageY) / 3; var currMeanX = (_curr.touches[0].pageX + _curr.touches[1].pageX + _curr.touches[2].pageX) / 3; var currMeanY = (_curr.touches[0].pageY + _curr.touches[1].pageY + _curr.touches[2].pageY) / 3; var _delta = { x: (currMeanX - prevMeanX) / this.renderer.domElement.clientWidth, y: (currMeanY - prevMeanY) / this.renderer.domElement.clientHeight }; this.panDelta.x += _delta.x; this.panDelta.y += _delta.y; this.stopTweens(); } previousTouch = e; }; this.addEventListener('touchstart', touchStart); this.addEventListener('touchend', touchEnd); this.addEventListener('touchmove', touchMove); this.addEventListener('drag', drag); this.addEventListener('drop', drop); this.addEventListener('mousewheel', scroll); this.addEventListener('dblclick', dblclick); } setScene(scene) { this.scene = scene; } stop() { this.yawDelta = 0; this.pitchDelta = 0; this.radiusDelta = 0; this.panDelta.set(0, 0); } zoomToLocation(mouse) { var camera = this.scene.getActiveCamera(); var I = Utils.getMousePointCloudIntersection(mouse, camera, this.viewer, this.scene.pointclouds, { pickClipped: true }); if (I === null) { return; } var targetRadius = 0; { var minimumJumpDistance = 0.2; var domElement = this.renderer.domElement; var ray = Utils.mouseToRay(mouse, camera, domElement.clientWidth, domElement.clientHeight); var nodes = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, ray); var lastNode = nodes[nodes.length - 1]; var radius = lastNode.getBoundingSphere(new Sphere()).radius; targetRadius = Math.min(this.scene.view.radius, radius); targetRadius = Math.max(minimumJumpDistance, targetRadius); } var d = this.scene.view.direction.multiplyScalar(-1); var cameraTargetPosition = new Vector3().addVectors(I.location, d.multiplyScalar(targetRadius)); // TODO Unused: let controlsTargetPosition = I.location; var animationDuration = 600; var easing = TWEEN.Easing.Quartic.Out; { // animate var value = { x: 0 }; var tween = new TWEEN.Tween(value).to({ x: 1 }, animationDuration); tween.easing(easing); this.tweens.push(tween); var startPos = this.scene.view.position.clone(); var targetPos = cameraTargetPosition.clone(); var startRadius = this.scene.view.radius; var _targetRadius = cameraTargetPosition.distanceTo(I.location); tween.onUpdate(() => { var t = value.x; this.scene.view.position.x = (1 - t) * startPos.x + t * targetPos.x; this.scene.view.position.y = (1 - t) * startPos.y + t * targetPos.y; this.scene.view.position.z = (1 - t) * startPos.z + t * targetPos.z; this.scene.view.radius = (1 - t) * startRadius + t * _targetRadius; this.viewer.setMoveSpeed(this.scene.view.radius); }); tween.onComplete(() => { this.tweens = this.tweens.filter(e => e !== tween); }); tween.start(); } } stopTweens() { this.tweens.forEach(e => e.stop()); this.tweens = []; } update(delta) { var view = this.scene.view; { // apply rotation var progression = Math.min(1, this.fadeFactor * delta); var yaw = view.yaw; var pitch = view.pitch; var pivot = view.getPivot(); yaw -= progression * this.yawDelta; pitch -= progression * this.pitchDelta; view.yaw = yaw; view.pitch = pitch; var V = this.scene.view.direction.multiplyScalar(-view.radius); var position = new Vector3().addVectors(pivot, V); view.position.copy(position); } { // apply pan var _progression = Math.min(1, this.fadeFactor * delta); var panDistance = _progression * view.radius * 3; var px = -this.panDelta.x * panDistance; var py = this.panDelta.y * panDistance; view.pan(px, py); } { // apply zoom var _progression2 = Math.min(1, this.fadeFactor * delta); // let radius = view.radius + progression * this.radiusDelta * view.radius * 0.1; var radius = view.radius + _progression2 * this.radiusDelta; var _V = view.direction.multiplyScalar(-radius); var _position = new Vector3().addVectors(view.getPivot(), _V); view.radius = radius; view.position.copy(_position); } { var speed = view.radius; this.viewer.setMoveSpeed(speed); } { // decelerate over time var _progression3 = Math.min(1, this.fadeFactor * delta); var attenuation = Math.max(0, 1 - this.fadeFactor * delta); this.yawDelta *= attenuation; this.pitchDelta *= attenuation; this.panDelta.multiplyScalar(attenuation); // this.radiusDelta *= attenuation; this.radiusDelta -= _progression3 * this.radiusDelta; } } } ; /** * @author mschuetz / http://mschuetz.at * * adapted from THREE.OrbitControls by * * @author qiao / https://github.com/qiao * @author mrdoob / http://mrdoob.com * @author alteredq / http://alteredqualia.com/ * @author WestLangley / http://github.com/WestLangley * @author erich666 / http://erichaines.com * * * */ class FirstPersonControls$1 extends EventDispatcher$1 { //old constructor(viewer) { super(); this.viewer = viewer; this.renderer = viewer.renderer; this.scene = null; this.sceneControls = new Scene(); this.rotationSpeed = 200; this.moveSpeed = 10; this.lockElevation = false; this.keys = { FORWARD: ['W'.charCodeAt(0), 38], BACKWARD: ['S'.charCodeAt(0), 40], LEFT: ['A'.charCodeAt(0), 37], RIGHT: ['D'.charCodeAt(0), 39], UP: ['R'.charCodeAt(0), 33], DOWN: ['F'.charCodeAt(0), 34] }; this.fadeFactor = 50; this.yawDelta = 0; this.pitchDelta = 0; this.translationDelta = new Vector3(0, 0, 0); this.translationWorldDelta = new Vector3(0, 0, 0); this.tweens = []; var drag = e => { if (e.drag.object !== null) { return; } if (e.drag.startHandled === undefined) { e.drag.startHandled = true; this.dispatchEvent({ type: 'start' }); } var moveSpeed = this.viewer.getMoveSpeed(); var ndrag = { x: e.drag.lastDrag.x / this.renderer.domElement.clientWidth, y: e.drag.lastDrag.y / this.renderer.domElement.clientHeight }; if (e.drag.mouse === MOUSE$1.LEFT) { this.yawDelta += ndrag.x * this.rotationSpeed; this.pitchDelta += ndrag.y * this.rotationSpeed; } else if (e.drag.mouse === MOUSE$1.RIGHT) { this.translationDelta.x -= ndrag.x * moveSpeed * 100; this.translationDelta.z += ndrag.y * moveSpeed * 100; } }; var drop = e => { this.dispatchEvent({ type: 'end' }); }; var scroll = e => { var speed = this.viewer.getMoveSpeed(); if (e.delta < 0) { speed = speed * 0.9; } else if (e.delta > 0) { speed = speed / 0.9; } speed = Math.max(speed, 0.1); this.viewer.setMoveSpeed(speed); }; var dblclick = e => { this.zoomToLocation(e.mouse); }; this.addEventListener('drag', drag); this.addEventListener('drop', drop); this.addEventListener('mousewheel', scroll); this.addEventListener('dblclick', dblclick); } setScene(scene) { this.scene = scene; } stop() { this.yawDelta = 0; this.pitchDelta = 0; this.translationDelta.set(0, 0, 0); } zoomToLocation(mouse) { var camera = this.scene.getActiveCamera(); var I = Utils.getMousePointCloudIntersection(mouse, camera, this.viewer, this.scene.pointclouds); if (I === null) { return; } var targetRadius = 0; { var minimumJumpDistance = 0.2; var domElement = this.renderer.domElement; var ray = Utils.mouseToRay(mouse, camera, domElement.clientWidth, domElement.clientHeight); var nodes = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, ray); var lastNode = nodes[nodes.length - 1]; var radius = lastNode.getBoundingSphere(new Sphere()).radius; targetRadius = Math.min(this.scene.view.radius, radius); targetRadius = Math.max(minimumJumpDistance, targetRadius); } var d = this.scene.view.direction.multiplyScalar(-1); var cameraTargetPosition = new Vector3().addVectors(I.location, d.multiplyScalar(targetRadius)); // TODO Unused: let controlsTargetPosition = I.location; var animationDuration = 600; var easing = TWEEN.Easing.Quartic.Out; { // animate var value = { x: 0 }; var tween = new TWEEN.Tween(value).to({ x: 1 }, animationDuration); tween.easing(easing); this.tweens.push(tween); var startPos = this.scene.view.position.clone(); var targetPos = cameraTargetPosition.clone(); var startRadius = this.scene.view.radius; var _targetRadius = cameraTargetPosition.distanceTo(I.location); tween.onUpdate(() => { var t = value.x; this.scene.view.position.x = (1 - t) * startPos.x + t * targetPos.x; this.scene.view.position.y = (1 - t) * startPos.y + t * targetPos.y; this.scene.view.position.z = (1 - t) * startPos.z + t * targetPos.z; this.scene.view.radius = (1 - t) * startRadius + t * _targetRadius; this.viewer.setMoveSpeed(this.scene.view.radius / 2.5); }); tween.onComplete(() => { this.tweens = this.tweens.filter(e => e !== tween); }); tween.start(); } } update(delta) { var view = this.scene.view; { // cancel move animations on user input var changes = [this.yawDelta, this.pitchDelta, this.translationDelta.length(), this.translationWorldDelta.length()]; var changeHappens = changes.some(e => Math.abs(e) > 0.001); if (changeHappens && this.tweens.length > 0) { this.tweens.forEach(e => e.stop()); this.tweens = []; } } { // accelerate while input is given var ih = this.viewer.inputHandler; var moveForward = this.keys.FORWARD.some(e => ih.pressedKeys[e]); var moveBackward = this.keys.BACKWARD.some(e => ih.pressedKeys[e]); var moveLeft = this.keys.LEFT.some(e => ih.pressedKeys[e]); var moveRight = this.keys.RIGHT.some(e => ih.pressedKeys[e]); var moveUp = this.keys.UP.some(e => ih.pressedKeys[e]); var moveDown = this.keys.DOWN.some(e => ih.pressedKeys[e]); if (this.lockElevation) { var dir = view.direction; dir.z = 0; dir.normalize(); if (moveForward && moveBackward) { this.translationWorldDelta.set(0, 0, 0); } else if (moveForward) { this.translationWorldDelta.copy(dir.multiplyScalar(this.viewer.getMoveSpeed())); } else if (moveBackward) { this.translationWorldDelta.copy(dir.multiplyScalar(-this.viewer.getMoveSpeed())); } } else { if (moveForward && moveBackward) { this.translationDelta.y = 0; } else if (moveForward) { this.translationDelta.y = this.viewer.getMoveSpeed(); } else if (moveBackward) { this.translationDelta.y = -this.viewer.getMoveSpeed(); } } if (moveLeft && moveRight) { this.translationDelta.x = 0; } else if (moveLeft) { this.translationDelta.x = -this.viewer.getMoveSpeed(); } else if (moveRight) { this.translationDelta.x = this.viewer.getMoveSpeed(); } if (moveUp && moveDown) { this.translationWorldDelta.z = 0; } else if (moveUp) { this.translationWorldDelta.z = this.viewer.getMoveSpeed(); } else if (moveDown) { this.translationWorldDelta.z = -this.viewer.getMoveSpeed(); } } { // apply rotation var yaw = view.yaw; var pitch = view.pitch; yaw -= this.yawDelta * delta; pitch -= this.pitchDelta * delta; view.yaw = yaw; view.pitch = pitch; } { // apply translation view.translate(this.translationDelta.x * delta, this.translationDelta.y * delta, this.translationDelta.z * delta); view.translateWorld(this.translationWorldDelta.x * delta, this.translationWorldDelta.y * delta, this.translationWorldDelta.z * delta); } { // set view target according to speed view.radius = 3 * this.viewer.getMoveSpeed(); } { // decelerate over time var attenuation = Math.max(0, 1 - this.fadeFactor * delta); this.yawDelta *= attenuation; this.pitchDelta *= attenuation; this.translationDelta.multiplyScalar(attenuation); this.translationWorldDelta.multiplyScalar(attenuation); } } } ; OrthographicCamera.prototype.zoomTo = function (node) { var factor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; if (!node.geometry && !node.boundingBox) { return; } // TODO //let minWS = new THREE.Vector4(node.boundingBox.min.x, node.boundingBox.min.y, node.boundingBox.min.z, 1); //let minVS = minWS.applyMatrix4(this.matrixWorldInverse); //let right = node.boundingBox.max.x; //let bottom = node.boundingBox.min.y; //let top = node.boundingBox.max.y; this.updateProjectionMatrix(); }; PerspectiveCamera.prototype.zoomTo = function (node, factor) { if (!node.geometry && !node.boundingSphere && !node.boundingBox) { return; } if (node.geometry && node.geometry.boundingSphere === null) { node.geometry.computeBoundingSphere(); } node.updateMatrixWorld(); var bs; if (node.boundingSphere) { bs = node.boundingSphere; } else if (node.geometry && node.geometry.boundingSphere) { bs = node.geometry.boundingSphere; } else { bs = node.boundingBox.getBoundingSphere(new Sphere()); } var _factor = factor || 1; bs = bs.clone().applyMatrix4(node.matrixWorld); var radius = bs.radius; var fovr = this.fov * Math.PI / 180; if (this.aspect < 1) { fovr = fovr * this.aspect; } var distanceFactor = Math.abs(radius / Math.sin(fovr / 2)) * _factor; var offset = this.getWorldDirection(new Vector3()).multiplyScalar(-distanceFactor); this.position.copy(bs.center.clone().add(offset)); }; Ray.prototype.distanceToPlaneWithNegative = function (plane) { var denominator = plane.normal.dot(this.direction); if (denominator === 0) { // line is coplanar, return origin if (plane.distanceToPoint(this.origin) === 0) { return 0; } // Null is preferable to undefined since undefined means.... it is undefined return null; } var t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; return t; }; //export * from "./Potree_update_visibility.js"; //因加载顺序问题,该文件直接在shim中重写 var workerPool = new WorkerPool(); var version = { major: 1, minor: 8, suffix: '.0' }; var lru = new LRU(); console.log('Potree ' + version.major + '.' + version.minor + version.suffix); var pointBudget = 1 * 1000 * 1000; var framenumber = 0; var numNodesLoading = 0; var maxNodesLoading = 6; //4; var debug = {}; exports.scriptPath = ""; if (document.currentScript && document.currentScript.src) { exports.scriptPath = new URL(document.currentScript.src + '/..').href; if (exports.scriptPath.slice(-1) === '/') { exports.scriptPath = exports.scriptPath.slice(0, -1); } } else if (({ url: (typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('potree.js', document.baseURI).href)) })) { exports.scriptPath = new URL((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('potree.js', document.baseURI).href)) + "/..").href; if (exports.scriptPath.slice(-1) === '/') { exports.scriptPath = exports.scriptPath.slice(0, -1); } } else { console.error('Potree was unable to find its script path using document.currentScript. Is Potree included with a script tag? Does your browser support this function?'); } var resourcePath = exports.scriptPath + '/resources'; //add: async function loadFile(path, params, callback, onError) { params = params || {}; var fetchMethod = params.fetchMethod || 'get'; delete params.fetchMethod; if (Potree.fileServer) { Potree.fileServer[fetchMethod](path, { params }).then(data => { if (data.data) data = data.data; if (data.data) data = data.data; //融合页面getdataset需要查找两次data callback && callback(data); }).catch(onError); } else { try { if (Object.keys(params).length > 0) { path += '?'; var index = 0; for (var i in params) { if (index > 0) path += '&'; path += i; path += '='; path += params[i]; index++; } } var info = {}; if (fetchMethod == 'post') info.method = 'POST'; var response = await fetch(path, info); var text = await response.text(); var data = params.returnText ? text : JSON.parse(text); if (data.data) data = data.data; callback && callback(data); return data; } catch (e) { console.log('loadFile出错', e); onError && onError(e); } } //查询: http://192.168.0.26:8080/doc.html#/default/filter-%E6%BC%AB%E6%B8%B8%E7%82%B9/filterUsingGET } async function loadDatasets(callback, sceneCode, onError, prefix) { //之后直接把path写进来 var path; sceneCode = sceneCode || Potree.settings.number; if (Potree.fileServer) { path = "/laser/dataset/".concat(sceneCode, "/getDataSet"); } else { //path = `${Potree.settings.urls.prefix2}/indoor/${Potree.settings.number}/api/datasets` //现在只能加载得了本地的了 path = "".concat(prefix || Potree.settings.urls.prefix, "/laser/dataset/").concat(sceneCode, "/getDataSet"); //path = `${Potree.scriptPath}/data/${sceneCode}/getDataSet.json` } return loadFile(path, null, callback, onError); } //目前上传平面图后如果不点击保存按钮,数据还是旧的不生效 async function loadMapEntity(datasetId, force) { if (!Potree.settings.floorplanEnable && !force && Potree.fileServer) return; /* 等待平面图类型定义好会加载 */ var loaded = 0; var needLoads = datasetId == 'all' ? viewer.scene.pointclouds.map(e => e.dataset_id) : [datasetId]; var callback = (dataset_id, floorplanType, data) => { if (!data || data.length == 0) return console.log('平面图没有数据', dataset_id, floorplanType); //要防止旧的比新的先获取到导致覆盖新的,因为两种type随时可能切换 if (floorplanType != Potree.settings.floorplanType[dataset_id]) return; //如果请求的floorplanType不是当前最新的floorplanType就返回 var map = viewer.mapViewer.mapLayer.maps.find(e => e.name == 'floorplan_' + dataset_id); if (map) { viewer.mapViewer.mapLayer.removeMap(map); } var mapNew = viewer.mapViewer.mapLayer.addMapEntity(data.data || data, dataset_id); if (map) { mapNew.visibleReasons = map.visibleReasons; mapNew.unvisibleReasons = map.unvisibleReasons; } loaded++; }; needLoads.forEach(dataset_id => { var floorplanType = Potree.settings.floorplanType[dataset_id], prefix = ''; if (!Potree.fileServer) { prefix = Potree.settings.urls.prefix; } if (!floorplanType) return; var path; /* if(Potree.fileServer){ path = `/laser/tiledMap/${Potree.settings.number}/tiledMap/${floorplanType}/${dataset_id}` }else{ path = `${Potree.settings.urls.prefix2}/indoor/${Potree.settings.number}/api/tiled_maps` } */ path = "".concat(prefix, "/laser/tiledMap/").concat(Potree.settings.number, "/tiledMap/").concat(floorplanType, "/").concat(dataset_id); Potree.settings.floorplanRequests[dataset_id] = true; //开始加载了 return loadFile(path, null, callback.bind(this, dataset_id, floorplanType)); }); } async function loadPanos(datasetId, callback, number) { var path; //let query = `?datasetId=${datasetId}` //`?lat=${center.lat}&lon=${center.lon}&radius=200000` if (Potree.fileServer) { path = "/laser/filter/".concat(Potree.settings.number, "/query"); } else if (Potree.settings.mergeType2) { //每个场景只加载初始数据集 path = "".concat(Potree.settings.urls.prefix, "/laser/filter/").concat(number, "/query"); } else { //path = `${Potree.settings.urls.prefix2}/indoor/${Potree.settings.number}/api/images/filter` + query //path = `${Potree.scriptPath}/data/${Potree.settings.number}/panos-${datasetId}.json` path = "".concat(Potree.settings.urls.prefix, "/laser/filter/").concat(Potree.settings.number, "/query"); } return loadFile(path, { datasetId: datasetId }, callback); } async function loadPanosInfo(callback) { var path; if (Potree.fileServer) {} else { path = "".concat(Potree.scriptPath, "/data/panoEdit/vision_edit.txt"); } return loadFile(path, null, callback); } function load4dkkPanos(sceneCode, model, done) { //加载四维看看的漫游点并转换 model.is4dkkModel = true; model.panos = []; //模拟点云,需要rotX(90)+平移一段才能和四维看看的bound一样 var rot1M = new THREE.Matrix4(); var pos1 = new THREE.Vector3(); if (model.fileType == '3dTiles') { pos1.fromArray(model.runtime.getTileset().tileset.root.boundingVolume.box.slice(0, 3)); //必须要平移一段才能重合 pos1.copy(Potree.math.convertVector.ZupToYup(pos1)); rot1M.makeRotationX(Math.PI / 2); } var pos1M = new THREE.Matrix4().setPosition(pos1); model.posRot1MatrixInvert = new THREE.Matrix4().multiplyMatrices(pos1M, rot1M).invert(); model.rot1MatrixInvert = rot1M.clone().invert(); model.transformMatrix = new THREE.Matrix4(); model.rotateMatrix = new THREE.Matrix4(); model.datasetData = { sceneVersion: 'V4' }; model.sceneCode = sceneCode; model.bound = new THREE.Box3(); var path = "https://4dkk.4dage.com/scene_view_data/".concat(sceneCode, "/images/vision.txt"); loadFile(path, {}, data => { var panoData = data.sweepLocations.map(e => { var qua = e.pose.rotation; return { file_id: e.uuid, dataset_location: new THREE.Vector3().copy(e.pose.translation).toArray(), dataset_floor_location: new THREE.Vector3().copy(e.puck).toArray(), dataset_orientation: [qua.w, qua.x, qua.y, qua.z] }; }); viewer.images360.addPanoData(panoData, model); viewer.images360.loadDone(); viewer.scene.add360Images(viewer.images360); { //neighbourMap全部填满,否则之后会被修改 data.sweepLocations.forEach(pano1Data => { var pano1 = model.panos.find(e => e.originID == pano1Data.uuid); model.panos.forEach((pano2, i) => { if (pano1 == pano2) return; var v = pano1Data.visibles.includes(i); viewer.images360.neighbourMap[pano1.id][pano2.id] = v; viewer.images360.neighbourMap[pano2.id][pano1.id] = v; if (v) { pano1.neighbours.includes(pano2) || pano1.neighbours.push(pano2); pano2.neighbours.includes(pano1) || pano2.neighbours.push(pano1); } }); }); } viewer.modules.MergeEditor.modelTransformCallback(model, true); //初始化pano的pose done(); }); /* neighbours: e.visibles3 || e.visibles, noBlocks: e.visibles2, seeMarkers: e.visibles, */ } async function loadImgVersion(callback) { var path; //let query = `?datasetId=${datasetId}` //`?lat=${center.lat}&lon=${center.lon}&radius=200000` /* if(Potree.fileServer){ path = `/laser/filter/${Potree.settings.number}/query` }else{ */ path = "/laser/init/getSceneNumVersion/".concat(Potree.settings.number); //api/laser/init //} return loadFile(path, { fetchMethod: 'post' }, callback, callback); } function setLonlat(lon, lat) { var locationLonLat = [lon, lat]; if (window.AMapWith84 && Potree.settings.mapCompany != 'google') { //需要转换为高德的,但该函数不准确,转入后再转出,和原来的有偏差. navvis的我看data中存的globalLocation直接输入到高德地图后的定位和其要展示的定位一致,而我们要转为高德后才一致,猜测是navvis后台转为了高德可用的经纬度。 若不转的话,其他看起来没问题,仅高德地图定位不准确,因其为被加密后的火星坐标系。 locationLonLat = AMapWith84.wgs84ToAMap({ x: lon, y: lat }); locationLonLat = [locationLonLat.x, locationLonLat.y]; } proj4.defs("LOCAL", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat[0].toPrecision(15) + " +lat_0=" + locationLonLat[1].toPrecision(15)); //高德坐标系 proj4.defs("LOCAL_MAP", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat[0].toPrecision(15) + " +lat_0=" + locationLonLat[1].toPrecision(15)); //地图和本地一样 proj4.defs("WGS84", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"); var transform1 = proj4("WGS84", "LOCAL"); //这个ok 是展开的平面投影 LOCAL即NAVVIS:TMERC var transform2 = proj4("+proj=tmerc +lat_0=0 +lon_0=123 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs;"); //注:转入后再转出,和原来的有偏差。如果输入是local坐标,数字越大偏差越大,当百万时就明显了。如果是lonlat,很奇怪经度小于50时就乱了。 viewer.transform = { lonlatToLocal: transform1, lonlatTo4550: transform2 // 转大地坐标EPSG:4550 }; if (window.AMapWith84 && Potree.settings.mapCompany != 'google') { //需要转换, 因本地高德用的lonlat和数据里的84不一样. (google地图在国内也用的高德,国外84) var change = transform => { var forward = transform.forward; var inverse = transform.inverse; transform.forward = function (e, not84) { var needTran = e.x == void 0; if (needTran) var a1 = { x: e[0], y: e[1] };else var a1 = e; var a = not84 ? a1 : AMapWith84.wgs84ToAMap(a1); if (needTran) { a = [a.x, a.y]; e[2] != void 0 && (a[2] = e[2]); } else { e.z != void 0 && (a.z = e.z); } return forward(a); }; transform.inverse = function (e, not84) { var needTran = e.x == void 0; var a = inverse(e); needTran && (a = { x: a[0], y: a[1] }); a = not84 ? a : AMapWith84.aMapToWgs84(a); if (needTran) { a = [a.x, a.y]; e[2] != void 0 && (a[2] = e[2]); } else { e.z != void 0 && (a.z = e.z); } return a; }; }; for (var f in viewer.transform) { change(viewer.transform[f]); } } } //site_model /* { "area": 2503.30551910935, "attributes": {}, "center": [ 113.59568277455075, 22.366566635195288, 12.78751625 ], "children": [], "geometry_hash": 1891071345, "id": 10, "name": "港湾一号", "parentId": null, "polygon": { "coordinates": [ [ [ 113.59590810534583, 22.36679132753878 ], [ 113.59590810534583, 22.366807172528629 ], [ 113.59545610274934, 22.366807172528629 ], [ 113.59545610274934, 22.36679132753878 ] ] ], "type": "Polygon" }, "type": "BUILDING", "volume": null, "z_max": null, "z_min": null } */ function Log$1() { var args = Array.from(arguments); var params = args[args.length - 1]; if (params && params.font) { params = params.font, args.pop(); } else params = {}; var str = '', color = params.color || '#13f', fontSize = params.fontSize || 12; args.forEach((e, i) => { i > 0 && (str += ' , '); /* if(params.toFixed && typeof e == 'number'){ e = e.toFixed(params.toFixed) } */ if (params.toFixed) { e = Potree.math.toPrecision(e, params.toFixed); } str += e; //object可以JSON.stringify,但不是所有都行 }); console.warn("%c".concat(str), "color:".concat(color, ";font-size:").concat(fontSize, "px")); } function loadPointCloud$1(path, name, sceneCode, timeStamp, callback, onError) { var loaded = function loaded(e) { e.pointcloud.name = name; e.pointcloud.sceneCode = sceneCode; //对应4dkk的场景码 callback(e); }; var promise = new Promise(resolve => { // load pointcloud if (!path) { // TODO: callback? comment? Hello? Bueller? Anyone? } else if (path.indexOf('ept.json') > 0) { EptLoader.load(path, function (geometry) { if (!geometry) { console.error(new Error("failed to load point cloud from URL: ".concat(path))); } else { var pointcloud = new ExtendPointCloudOctree(geometry); //loaded(pointcloud); resolve({ type: 'pointcloud_loaded', pointcloud: pointcloud }); } }); } else if (path.indexOf('cloud.js') > 0) { POCLoader.load(path, timeStamp, function (geometry) { if (!geometry) { //callback({type: 'loading_failed'}); console.error(new Error("failed to load point cloud from URL: ".concat(path))); onError && onError(); } else { var pointcloud = new ExtendPointCloudOctree(geometry); // loaded(pointcloud); resolve({ type: 'pointcloud_loaded', pointcloud: pointcloud }); } }); } /* else if (path.indexOf('metadata.json') > 0) { //部分浏览器(如uc)不支持NodeLoader中的1n的大数据写法 Potree.OctreeLoader.load(path).then(e => { let geometry = e.geometry; if(!geometry){ console.error(new Error(`failed to load point cloud from URL: ${path}`)); }else{ let pointcloud = new ExtendPointCloudOctree(geometry); let aPosition = pointcloud.getAttribute("position"); let material = pointcloud.material; material.elevationRange = [ aPosition.range[0][2], aPosition.range[1][2], ]; // loaded(pointcloud); resolve({type: 'pointcloud_loaded', pointcloud: pointcloud}); } }); OctreeLoader.load(path, function (geometry) { if (!geometry) { //callback({type: 'loading_failed'}); console.error(new Error(`failed to load point cloud from URL: ${path}`)); } else { let pointcloud = new ExtendPointCloudOctree(geometry); // loaded(pointcloud); resolve({type: 'pointcloud_loaded', pointcloud: pointcloud}); } }); } */else if (path.indexOf('.vpc') > 0) { PointCloudArena4DGeometry.load(path, function (geometry) { if (!geometry) { //callback({type: 'loading_failed'}); console.error(new Error("failed to load point cloud from URL: ".concat(path))); } else { var pointcloud = new PointCloudArena4D(geometry); // loaded(pointcloud); resolve({ type: 'pointcloud_loaded', pointcloud: pointcloud }); } }); } else { //callback({'type': 'loading_failed'}); console.error(new Error("failed to load point cloud from URL: ".concat(path))); } }); if (callback) { promise.then(pointcloud => { loaded(pointcloud); }); } else { return promise; } } ; // add selectgroup (function ($) { $.fn.extend({ selectgroup: function selectgroup() { var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var elGroup = $(this); var rootID = elGroup.prop("id"); var groupID = "".concat(rootID); var groupTitle = args.title !== undefined ? args.title : ""; var elButtons = []; elGroup.find("option").each((index, value) => { var buttonID = $(value).prop("id"); var label = $(value).html(); var optionValue = $(value).prop("value"); var elButton = $("\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t")); var elLabel = elButton.find("label"); var elInput = elButton.find("input"); elInput.change(() => { elGroup.find("label").removeClass("ui-state-active"); elGroup.find("label").addClass("ui-state-default"); if (elInput.is(":checked")) { elLabel.addClass("ui-state-active"); } else { //elLabel.addClass("ui-state-default"); } }); elButtons.push(elButton); }); var elFieldset = $("\n\t\t\t\t
    \n\t\t\t\t\t".concat(groupTitle, "\n\t\t\t\t\t\n\n\t\t\t\t\t\n\t\t\t\t
    \n\t\t\t")); var elButtonContainer = elFieldset.find("span"); for (var elButton of elButtons) { elButtonContainer.append(elButton); } elButtonContainer.find("label").each((index, value) => { $(value).css("margin", "0px"); $(value).css("border-radius", "0px"); $(value).css("border", "1px solid black"); $(value).css("border-left", "none"); }); elButtonContainer.find("label:first").each((index, value) => { $(value).css("border-radius", "4px 0px 0px 4px"); }); elButtonContainer.find("label:last").each((index, value) => { $(value).css("border-radius", "0px 4px 4px 0px"); $(value).css("border-left", "none"); }); elGroup.empty(); elGroup.append(elFieldset); } }); })(jQuery); //在这之后export的内容才赋值到Potree中 exports.Action = Action; exports.Annotation = Annotation; exports.Box3Helper = Box3Helper$1; exports.BoxVolume = BoxVolume$1; exports.CameraAnimation = CameraAnimation$1; exports.CameraMode = CameraMode; exports.ClassificationScheme = ClassificationScheme; exports.ClipMethod = ClipMethod; exports.ClipTask = ClipTask; exports.ClipVolume = ClipVolume; exports.ClippingTool = ClippingTool; exports.ElevationGradientRepeat = ElevationGradientRepeat; exports.Enum = Enum; exports.EnumItem = EnumItem; exports.EptBinaryLoader = EptBinaryLoader; exports.EptKey = EptKey; exports.EptLaszipLoader = EptLaszipLoader; exports.EptLazBatcher = EptLazBatcher; exports.EptLoader = EptLoader; exports.EptZstandardLoader = EptZstandardLoader; exports.EventDispatcher = EventDispatcher$1; exports.ExtendPointCloudMaterial = ExtendPointCloudMaterial; exports.ExtendPointCloudOctree = ExtendPointCloudOctree; exports.ExtendScene = ExtendScene; exports.EyeDomeLightingMaterial = EyeDomeLightingMaterial; exports.Features = Features; exports.FirstPersonControls = FirstPersonControls$1; exports.GeoPackageLoader = GeoPackageLoader; exports.Geopackage = Geopackage$1; exports.Gradients = Gradients; exports.HierarchicalSlider = HierarchicalSlider; exports.Images360 = Images360; exports.KeyCodes = KeyCodes; exports.LRU = LRU; exports.LRUItem = LRUItem; exports.LengthUnits = LengthUnits; exports.LineDraw = LineDraw; exports.Log = Log$1; exports.MOUSE = MOUSE$1; exports.MapViewer = MapViewer; exports.Measure = Measure$1; exports.MeasuringTool = MeasuringTool; exports.MeshDraw = MeshDraw; exports.Message = Message; exports.NodeLoader = NodeLoader; exports.NormalizationEDLMaterial = NormalizationEDLMaterial; exports.NormalizationMaterial = NormalizationMaterial; exports.OctreeLoader = OctreeLoader; exports.OrbitControls = OrbitControls$2; exports.OrientedImage = OrientedImage; exports.OrientedImageLoader = OrientedImageLoader; exports.OrientedImages = OrientedImages; exports.POCLoader = POCLoader; exports.PointAttribute = PointAttribute; exports.PointAttributeTypes = PointAttributeTypes; exports.PointAttributes = PointAttributes; exports.PointCloudEptGeometry = PointCloudEptGeometry; exports.PointCloudEptGeometryNode = PointCloudEptGeometryNode; exports.PointCloudOctreeGeometry = PointCloudOctreeGeometry; exports.PointCloudOctreeGeometryNode = PointCloudOctreeGeometryNode; exports.PointCloudSM = PointCloudSM; exports.PointCloudTree = PointCloudTree; exports.PointCloudTreeNode = PointCloudTreeNode; exports.PointShape = PointShape$1; exports.PointSizeType = PointSizeType; exports.Points = Points$1; exports.PolygonClipVolume = PolygonClipVolume; exports.Profile = Profile; exports.ProfileData = ProfileData; exports.ProfileRequest = ProfileRequest; exports.ProfileTool = ProfileTool; exports.Renderer = Renderer; exports.ScreenBoxSelectTool = ScreenBoxSelectTool; exports.ShapefileLoader = ShapefileLoader; exports.SphereVolume = SphereVolume$2; exports.SpotLightHelper = SpotLightHelper$1; exports.TextSprite = TextSprite$2; exports.TransformationTool = TransformationTool; exports.TreeType = TreeType; exports.Utils = Utils; exports.Version = Version; exports.Viewer = Viewer$1; exports.Volume = Volume$1; exports.VolumeTool = VolumeTool; exports.WorkerPool = WorkerPool; exports.XHRFactory = XHRFactory; exports.config = config$1; exports.debug = debug; exports.framenumber = framenumber; exports.load4dkkPanos = load4dkkPanos; exports.loadDatasets = loadDatasets; exports.loadFile = loadFile; exports.loadImgVersion = loadImgVersion; exports.loadMapEntity = loadMapEntity; exports.loadPanos = loadPanos; exports.loadPanosInfo = loadPanosInfo; exports.loadPointCloud = loadPointCloud$1; exports.loadProject = loadProject; exports.lru = lru; exports.maxNodesLoading = maxNodesLoading; exports.mergeEditStart = mergeEditStart; exports.numNodesLoading = numNodesLoading; exports.panoEditStart = panoEditStart; exports.pointBudget = pointBudget; exports.resourcePath = resourcePath; exports.saveProject = saveProject; exports.setLonlat = setLonlat; exports.settings = settings; exports.start = start; exports.version = version; exports.workerPool = workerPool; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=potree.js.map