/** X3DOM Runtime, http://www.x3dom.org/ 1.6.0 - 5e8c0441fe2cbe9970ffd14f1546100672a95185 - Thu May 8 20:51:15 2014 +0200 */ if(!Array.forEach){Array.forEach=function(array,fun,thisp){var len=array.length;for(var i=0;ix3dom.debug.maxLinesToLog){return;} var node=document.createElement("p");node.style.margin=0;switch(logType){case x3dom.debug.INFO:node.style.color="#00ff00";break;case x3dom.debug.WARNING:node.style.color="#cd853f";break;case x3dom.debug.ERROR:node.style.color="#ff4500";break;case x3dom.debug.EXCEPTION:node.style.color="#ffff00";break;default:node.style.color="#00ff00";break;} try{node.innerHTML=logType+": "+msg;x3dom.debug.logContainer.insertBefore(node,x3dom.debug.logContainer.firstChild);}catch(err){if(window.console.firebug!==undefined){window.console.warn(msg);}} if(x3dom.debug.isFirebugAvailable){switch(logType){case x3dom.debug.INFO:window.console.info(msg);break;case x3dom.debug.WARNING:window.console.warn(msg);break;case x3dom.debug.ERROR:window.console.error(msg);break;case x3dom.debug.EXCEPTION:window.console.debug(msg);break;default:break;}} x3dom.debug.numLinesLogged++;},logInfo:function(msg){x3dom.debug.doLog(msg,x3dom.debug.INFO);},logWarning:function(msg){x3dom.debug.doLog(msg,x3dom.debug.WARNING);},logError:function(msg){x3dom.debug.doLog(msg,x3dom.debug.ERROR);},logException:function(msg){x3dom.debug.doLog(msg,x3dom.debug.EXCEPTION);},assert:function(c,msg){if(!c){x3dom.debug.doLog("Assertion failed in "+ x3dom.debug.assert.caller.name+': '+ msg,x3dom.debug.ERROR);}},typeOf:function(obj){var type=typeof obj;return type==="object"&&!obj?"null":type;},exists:function(obj,name,type){type=type||"function";return(obj?this.typeOf(obj[name]):"null")===type;},dumpFields:function(node){var str="";for(var fName in node){str+=(fName+", ");} str+='\n';x3dom.debug.logInfo(str);return str;}};x3dom.debug.setup();x3dom.arc={};x3dom.arc.instance=null;x3dom.arc.Limits=function(min,max,initial) {this._min=min;this._max=max;this.getValue=function(value) {value=this._min+(this._max-this._min)*value;return this._max>=value?(this._min<=value?value:this._min):this._max;};};x3dom.arc.ARF=function(name,min,max,dirFac,factorGetterFunc,factorSetterFunc,getterFunc,setterFunc) {this._name=name;this._stateValue=[0.5,0.5];this._limits=new x3dom.arc.Limits(min,max);this._factorGetterFunc=factorGetterFunc;this._factorSetterFunc=factorSetterFunc;this._setterFunc=setterFunc;this._getterFunc=getterFunc;this._dirFac=dirFac;this.getFactor=function() {return this._factorGetterFunc();};this.update=function(state,step) {var stateVal=this._stateValue[state]+step*this._dirFac;this._stateValue[state]=0<=stateVal?(1>=stateVal?stateVal:1):0;this._setterFunc(this._limits.getValue(this._stateValue[state]));};this.reset=function() {this._stateValue[0]=0.5;this._stateValue[1]=0.5;};};x3dom.arc.AdaptiveRenderControl=defineClass(null,function(scene) {x3dom.arc.instance=this;this._scene=scene;this._targetFrameRate=[];this._targetFrameRate[0]=this._scene._vf.minFrameRate;this._targetFrameRate[1]=this._scene._vf.maxFrameRate;this._currentState=0;var that=this;var environment=that._scene.getEnvironment();this._arfs=[];this._arfs.push(new x3dom.arc.ARF("smallFeatureCulling",0,10,-1,function() {return environment._vf.smallFeatureFactor;},function(value) {environment._vf.smallFeatureFactor=value;},function() {return environment._vf.smallFeatureThreshold;},function(value) {environment._vf.smallFeatureThreshold=value;}));this._arfs.push(new x3dom.arc.ARF("lowPriorityCulling",0,100,1,function() {return environment._vf.lowPriorityFactor;},function(value) {environment._vf.lowPriorityFactor=value;},function() {return environment._vf.lowPriorityThreshold*100;},function(value) {environment._vf.lowPriorityThreshold=value/100;}));this._arfs.push(new x3dom.arc.ARF("tessellationDetailCulling",1,12,-1,function() {return environment._vf.tessellationErrorFactor;},function(value) {environment._vf.tessellationErrorFactor=value;},function() {return environment.tessellationErrorThreshold;},function(value) {environment.tessellationErrorThreshold=value;}));this._stepWidth=0.1;},{update:function(state,fps) {this._currentState=state;var delta=fps-this._targetFrameRate[state];this._stepWidth=Math.abs(delta)>10?0.1:0.01;var factorSum=0;var normFactors=[];var i,n=this._arfs.length;for(i=0;i0) factorSum+=normFactors[i];} var dirFac=delta<0?-1:1;for(i=0;i0) {normFactors[i]/=factorSum;this._arfs[i].update(state,this._stepWidth*normFactors[i]*dirFac);}}},reset:function() {for(var i=0,n=this._arfs.length;i1){node.prev.next=node.next;node.next.prev=node.prev;if(node==this.first){this.first=node.next;} if(node==this.last){this.last=node.prev;}}else{this.first=null;this.last=null;} node.prev=null;node.next=null;this.length--;};x3dom.DoublyLinkedList.prototype.getNode=function(index){var node=null;if(index>this.length){return node;} for(var i=0;i=3&&count<15){next=node.next;for(var i=0;i=3&&count<15){next=node.next;for(var i=0;i0)&&(b2>0)&&(b3>0));} else{return false;}},isKonvex:function(p,p1,p2,plane){var pa,pb,p1a,p1b,p2a,p2b;if(plane=='YZ'){pa=p.y;pb=p.z;p1a=p1.y;p1b=p1.z;p2a=p2.y;p2b=p2.z;}else if(plane=='XZ'){pa=p.z;pb=p.x;p1a=p1.z;p1b=p1.x;p2a=p2.z;p2b=p2.x;}else{pa=p.x;pb=p.y;p1a=p1.x;p1b=p1.y;p2a=p2.x;p2b=p2.y;} var l=((p1a-pa)*(p2b-pb)-(p1b-pb)*(p2a-pa));return(l>=0);},identifyPlane:function(p1,p2,p3){var v1x,v1y,v1z;var v2x,v2y,v2z;var v3x,v3y,v3z;v1x=p2.x-p1.x;v1y=p2.y-p1.y;v1z=p2.z-p1.z;v2x=p3.x-p1.x;v2y=p3.y-p1.y;v2z=p3.z-p1.z;v3x=Math.abs(v1y*v2z-v1z*v2y);v3y=Math.abs(v1z*v2x-v1x*v2z);v3z=Math.abs(v1x*v2y-v1y*v2x);var angle=Math.max(v3x,v3y,v3z);if(angle==v3x){return'YZ';}else if(angle==v3y){return'XZ';}else if(angle==v3z){return'XY';}else{return'XZ';}}};x3dom.Utils={};x3dom.Utils.maxIndexableCoords=65535;x3dom.Utils.needLineWidth=false;x3dom.Utils.measurements=[];window.performance=window.performance||{};performance.now=(function(){return performance.now||performance.mozNow||performance.msNow||performance.oNow||performance.webkitNow||function(){return new Date().getTime();};})();x3dom.Utils.startMeasure=function(name){var uname=name.toUpperCase();if(!x3dom.Utils.measurements[uname]){if(performance&&performance.now){x3dom.Utils.measurements[uname]=performance.now();}else{x3dom.Utils.measurements[uname]=new Date().getTime();}}};x3dom.Utils.stopMeasure=function(name){var uname=name.toUpperCase();if(x3dom.Utils.measurements[uname]){var startTime=x3dom.Utils.measurements[uname];delete x3dom.Utils.measurements[uname];if(performance&&performance.now){return performance.now()-startTime;}else{return new Date().getTime()-startTime;}} return 0;};x3dom.Utils.isNumber=function(n){return!isNaN(parseFloat(n))&&isFinite(n);};x3dom.Utils.createTexture2D=function(gl,doc,src,bgnd,withCredentials,scale,genMipMaps) {var texture=gl.createTexture();var data=new Uint8Array([0,0,0,255,0,0,0,255,0,0,0,255,0,0,0,255]);gl.bindTexture(gl.TEXTURE_2D,texture);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,2,2,0,gl.RGBA,gl.UNSIGNED_BYTE,data);if(genMipMaps){gl.generateMipmap(gl.TEXTURE_2D);} gl.bindTexture(gl.TEXTURE_2D,null);texture.ready=false;if(src==null||src=='') return texture;var image=new Image();image.crossOrigin=withCredentials?'use-credentials':'';image.src=src;doc.downloadCount++;image.onload=function(){if(scale) image=x3dom.Utils.scaleImage(image);if(bgnd==true){gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,true);} gl.bindTexture(gl.TEXTURE_2D,texture);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,image);if(genMipMaps){gl.generateMipmap(gl.TEXTURE_2D);} gl.bindTexture(gl.TEXTURE_2D,null);if(bgnd==true){gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,false);} texture.width=image.width;texture.height=image.height;texture.ready=true;doc.downloadCount--;doc.needRender=true;};image.onerror=function(){x3dom.debug.logError("[Utils|createTexture2D] Can't load Image: "+src);doc.downloadCount--;};return texture;};x3dom.Utils.createTextureCube=function(gl,doc,url,bgnd,withCredentials,scale,genMipMaps) {var texture=gl.createTexture();var faces;if(bgnd){faces=[gl.TEXTURE_CUBE_MAP_POSITIVE_Z,gl.TEXTURE_CUBE_MAP_NEGATIVE_Z,gl.TEXTURE_CUBE_MAP_POSITIVE_Y,gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,gl.TEXTURE_CUBE_MAP_POSITIVE_X,gl.TEXTURE_CUBE_MAP_NEGATIVE_X];} else {faces=[gl.TEXTURE_CUBE_MAP_NEGATIVE_Z,gl.TEXTURE_CUBE_MAP_POSITIVE_Z,gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,gl.TEXTURE_CUBE_MAP_POSITIVE_Y,gl.TEXTURE_CUBE_MAP_NEGATIVE_X,gl.TEXTURE_CUBE_MAP_POSITIVE_X];} texture.ready=false;texture.pendingTextureLoads=-1;texture.textureCubeReady=false;var width=0,height=0;for(var i=0;i-1){filename=url.substr(url.lastIndexOf("/")+1);} else if(url.lastIndexOf("\\")>-1){filename=url.substr(url.lastIndexOf("\\")+1);} else{filename=url;} return filename;};x3dom.Utils.findTextureByName=function(texture,name) {for(var i=0;i>i;} return(x+1);};x3dom.Utils.nextBestPowerOfTwo=function(x) {var log2x=Math.log(x)/0.693147180559945;return Math.pow(2,Math.round(log2x));};x3dom.Utils.getDataTypeSize=function(type) {switch(type) {case"Int8":case"Uint8":return 1;case"Int16":case"Uint16":return 2;case"Int32":case"Uint32":case"Float32":return 4;case"Float64":default:return 8;}};x3dom.Utils.getOffsetMultiplier=function(indexType,gl) {switch(indexType) {case gl.UNSIGNED_SHORT:return 1;case gl.UNSIGNED_INT:return 2;case gl.UNSIGNED_BYTE:return 0.5;default:return 1;}};x3dom.Utils.getByteAwareOffset=function(offset,indexType,gl) {switch(indexType) {case gl.UNSIGNED_SHORT:return 2*offset;case gl.UNSIGNED_INT:return 4*offset;case gl.UNSIGNED_BYTE:return offset;default:return 2*offset;}};x3dom.Utils.getVertexAttribType=function(type,gl) {var dataType=gl.NONE;switch(type) {case"Int8":dataType=gl.BYTE;break;case"Uint8":dataType=gl.UNSIGNED_BYTE;break;case"Int16":dataType=gl.SHORT;break;case"Uint16":dataType=gl.UNSIGNED_SHORT;break;case"Int32":dataType=gl.INT;break;case"Uint32":dataType=gl.UNSIGNED_INT;break;case"Float32":dataType=gl.FLOAT;break;case"Float64":default:x3dom.debug.logError("Can't find this.gl data type for "+type+", getting FLOAT...");dataType=gl.FLOAT;break;} return dataType;};x3dom.Utils.getArrayBufferView=function(type,buffer) {var array=null;switch(type) {case"Int8":array=new Int8Array(buffer);break;case"Uint8":array=new Uint8Array(buffer);break;case"Int16":array=new Int16Array(buffer);break;case"Uint16":array=new Uint16Array(buffer);break;case"Int32":array=new Int32Array(buffer);break;case"Uint32":array=new Uint32Array(buffer);break;case"Float32":array=new Float32Array(buffer);break;case"Float64":array=new Float64Array(buffer);break;default:x3dom.debug.logError("Can't create typed array view of type "+type+", trying Float32...");array=new Float32Array(buffer);break;} return array;};x3dom.Utils.isUnsignedType=function(str) {return(str=="Uint8"||str=="Uint16"||str=="Uint16"||str=="Uint32");};x3dom.Utils.checkDirtyLighting=function(viewarea) {return(viewarea.getLights().length+viewarea._scene.getNavigationInfo()._vf.headlight);};x3dom.Utils.checkDirtyEnvironment=function(viewarea,shaderProperties) {var environment=viewarea._scene.getEnvironment();return(shaderProperties.GAMMACORRECTION!=environment._vf.gammaCorrectionDefault);} x3dom.Utils.minFilterDic=function(gl,minFilter) {switch(minFilter.toUpperCase()) {case"NEAREST":return gl.NEAREST;case"LINEAR":return gl.LINEAR;case"NEAREST_MIPMAP_NEAREST":return gl.NEAREST_MIPMAP_NEAREST;case"NEAREST_MIPMAP_LINEAR":return gl.NEAREST_MIPMAP_LINEAR;case"LINEAR_MIPMAP_NEAREST":return gl.LINEAR_MIPMAP_NEAREST;case"LINEAR_MIPMAP_LINEAR":return gl.LINEAR_MIPMAP_LINEAR;case"AVG_PIXEL":return gl.LINEAR;case"AVG_PIXEL_AVG_MIPMAP":return gl.LINEAR_MIPMAP_LINEAR;case"AVG_PIXEL_NEAREST_MIPMAP":return gl.LINEAR_MIPMAP_NEAREST;case"DEFAULT":return gl.LINEAR_MIPMAP_LINEAR;case"FASTEST":return gl.NEAREST;case"NEAREST_PIXEL":return gl.NEAREST;case"NEAREST_PIXEL_AVG_MIPMAP":return gl.NEAREST_MIPMAP_LINEAR;case"NEAREST_PIXEL_NEAREST_MIPMAP":return gl.NEAREST_MIPMAP_NEAREST;case"NICEST":return gl.LINEAR_MIPMAP_LINEAR;default:return gl.LINEAR;}};x3dom.Utils.magFilterDic=function(gl,magFilter) {switch(magFilter.toUpperCase()) {case"NEAREST":return gl.NEAREST;case"LINEAR":return gl.LINEAR;case"AVG_PIXEL":return gl.LINEAR;case"DEFAULT":return gl.LINEAR;case"FASTEST":return gl.NEAREST;case"NEAREST_PIXEL":return gl.NEAREST;case"NICEST":return gl.LINEAR;default:return gl.LINEAR;}};x3dom.Utils.boundaryModesDic=function(gl,mode) {switch(mode.toUpperCase()) {case"CLAMP":return gl.CLAMP_TO_EDGE;case"CLAMP_TO_EDGE":return gl.CLAMP_TO_EDGE;case"CLAMP_TO_BOUNDARY":return gl.CLAMP_TO_EDGE;case"MIRRORED_REPEAT":return gl.MIRRORED_REPEAT;case"REPEAT":return gl.REPEAT;default:return gl.REPEAT;}};x3dom.Utils.primTypeDic=function(gl,type) {switch(type.toUpperCase()) {case"POINTS":return gl.POINTS;case"LINES":return gl.LINES;case"LINELOOP":return gl.LINE_LOOP;case"LINESTRIP":return gl.LINE_STRIP;case"TRIANGLES":return gl.TRIANGLES;case"TRIANGLESTRIP":return gl.TRIANGLE_STRIP;case"TRIANGLEFAN":return gl.TRIANGLE_FAN;default:return gl.TRIANGLES;}};x3dom.Utils.depthFunc=function(gl,func) {switch(func.toUpperCase()) {case"NEVER":return gl.NEVER;case"ALWAYS":return gl.ALWAYS;case"LESS":return gl.LESS;case"EQUAL":return gl.EQUAL;case"LEQUAL":return gl.LEQUAL;case"GREATER":return gl.GREATER;case"GEQUAL":return gl.GEQUAL;case"NOTEQUAL":return gl.NOTEQUAL;default:return gl.LEQUAL;}};x3dom.Utils.blendFunc=function(gl,func) {switch(func.toLowerCase()) {case"zero":return gl.ZERO;case"one":return gl.ONE;case"dst_color":return gl.DST_COLOR;case"dst_alpha":return gl.DST_ALPHA;case"src_color":return gl.SRC_COLOR;case"src_alpha":return gl.SRC_ALPHA;case"one_minus_dst_color":return gl.ONE_MINUS_DST_COLOR;case"one_minus_dst_alpha":return gl.ONE_MINUS_DST_ALPHA;case"one_minus_src_color":return gl.ONE_MINUS_SRC_COLOR;case"one_minus_src_alpha":return gl.ONE_MINUS_SRC_ALPHA;case"src_alpha_saturate":return gl.SRC_ALPHA_SATURATE;case"constant_color":return gl.CONSTANT_COLOR;case"constant_alpha":return gl.CONSTANT_ALPHA;case"one_minus_constant_color":return gl.ONE_MINUS_CONSTANT_COLOR;case"one_minus_constant_alpha":return gl.ONE_MINUS_CONSTANT_ALPHA;default:return 0;}};x3dom.Utils.blendEquation=function(gl,func) {switch(func.toLowerCase()) {case"func_add":return gl.FUNC_ADD;case"func_subtract":return gl.FUNC_SUBTRACT;case"func_reverse_subtract":return gl.FUNC_REVERSE_SUBTRACT;case"min":return 0;case"max":return 0;case"logic_op":return 0;default:return 0;}};x3dom.Utils.generateProperties=function(viewarea,shape) {var property={};var geometry=shape._cf.geometry.node;var appearance=shape._cf.appearance.node;var texture=appearance?appearance._cf.texture.node:null;var material=appearance?appearance._cf.material.node:null;var environment=viewarea._scene.getEnvironment();if(appearance&&appearance._shader&&x3dom.isa(appearance._shader,x3dom.nodeTypes.ComposedShader)){property.CSHADER=appearance._shader._id;} else if(geometry){property.CSHADER=-1;property.SOLID=(shape.isSolid())?1:0;property.TEXT=(x3dom.isa(geometry,x3dom.nodeTypes.Text))?1:0;property.POPGEOMETRY=(x3dom.isa(geometry,x3dom.nodeTypes.PopGeometry))?1:0;property.IMAGEGEOMETRY=(x3dom.isa(geometry,x3dom.nodeTypes.ImageGeometry))?1:0;property.BINARYGEOMETRY=(x3dom.isa(geometry,x3dom.nodeTypes.BinaryGeometry))?1:0;property.IG_PRECISION=(property.IMAGEGEOMETRY)?geometry.numCoordinateTextures():0;property.IG_INDEXED=(property.IMAGEGEOMETRY&&geometry.getIndexTexture()!=null)?1:0;property.POINTLINE2D=!geometry.needLighting()?1:0;property.VERTEXID=(property.BINARYGEOMETRY&&geometry._vf.idsPerVertex)?1:0;property.APPMAT=(appearance&&(material||property.CSSHADER))?1:0;property.SHADOW=(viewarea.getLightsShadow())?1:0;property.FOG=(viewarea._scene.getFog()._vf.visibilityRange>0)?1:0;property.CSSHADER=(appearance&&appearance._shader&&x3dom.isa(appearance._shader,x3dom.nodeTypes.CommonSurfaceShader))?1:0;property.LIGHTS=(!property.POINTLINE2D&&appearance&&shape.isLit()&&(material||property.CSSHADER))?viewarea.getLights().length+(viewarea._scene.getNavigationInfo()._vf.headlight):0;property.TEXTURED=(texture||property.TEXT)?1:0;property.TEXTRAFO=(appearance&&appearance._cf.textureTransform.node)?1:0;property.DIFFUSEMAP=(property.CSSHADER&&appearance._shader.getDiffuseMap())?1:0;property.NORMALMAP=(property.CSSHADER&&appearance._shader.getNormalMap())?1:0;property.SPECMAP=(property.CSSHADER&&appearance._shader.getSpecularMap())?1:0;property.SHINMAP=(property.CSSHADER&&appearance._shader.getShininessMap())?1:0;property.DISPLACEMENTMAP=(property.CSSHADER&&appearance._shader.getDisplacementMap())?1:0;property.DIFFPLACEMENTMAP=(property.CSSHADER&&appearance._shader.getDiffuseDisplacementMap())?1:0;property.MULTIDIFFALPMAP=(property.VERTEXID&&property.CSSHADER&&appearance._shader.getMultiDiffuseAlphaMap())?1:0;property.MULTIVISMAP=(property.VERTEXID&&property.CSSHADER&&appearance._shader.getMultiVisibilityMap())?1:0;property.CUBEMAP=(texture&&x3dom.isa(texture,x3dom.nodeTypes.X3DEnvironmentTextureNode))?1:0;property.BLENDING=(property.TEXT||property.CUBEMAP||(texture&&texture._blending))?1:0;property.REQUIREBBOX=(geometry._vf.coordType!==undefined&&geometry._vf.coordType!="Float32")?1:0;property.REQUIREBBOXNOR=(geometry._vf.normalType!==undefined&&geometry._vf.normalType!="Float32")?1:0;property.REQUIREBBOXCOL=(geometry._vf.colorType!==undefined&&geometry._vf.colorType!="Float32")?1:0;property.REQUIREBBOXTEX=(geometry._vf.texCoordType!==undefined&&geometry._vf.texCoordType!="Float32")?1:0;property.COLCOMPONENTS=geometry._mesh._numColComponents;property.NORCOMPONENTS=geometry._mesh._numNormComponents;property.POSCOMPONENTS=geometry._mesh._numPosComponents;property.SPHEREMAPPING=(geometry._cf.texCoord!==undefined&&geometry._cf.texCoord.node!==null&&geometry._cf.texCoord.node._vf.mode&&geometry._cf.texCoord.node._vf.mode.toLowerCase()=="sphere")?1:0;property.VERTEXCOLOR=(geometry._mesh._colors[0].length>0||(property.IMAGEGEOMETRY&&geometry.getColorTexture())||(property.POPGEOMETRY&&geometry.hasColor())||(geometry._vf.color!==undefined&&geometry._vf.color.length>0))?1:0;property.GAMMACORRECTION=environment._vf.gammaCorrectionDefault;} property.toIdentifier=function(){var id="";for(var p in this){if(this[p]!=this.toIdentifier&&this[p]!=this.toString){id+=this[p];}} this.id=id;return id;};property.toString=function(){var str="";for(var p in this){if(this[p]!=this.toIdentifier&&this[p]!=this.toString){str+=p+": "+this[p]+", ";}} return str;};property.toIdentifier();return property;};x3dom.Utils.wrapProgram=function(gl,program,shaderID) {var shader={shaderID:shaderID,program:program};shader.bind=function(){gl.useProgram(program);};var loc=null;var obj=null;var i,glErr;var numUniforms=gl.getProgramParameter(program,gl.ACTIVE_UNIFORMS);for(i=0;izFar) {return;} zNear=(zNear>1)?1:zNear;zFar=(zFar>1)?1:zFar;if(this.states['depthRange'].zNear!=zNear||this.states['depthRange'].zFar!=zFar) {this.gl.depthRange(zNear,zFar);this.states['depthRange'].zNear=zNear;this.states['depthRange'].zFar=zFar;}};x3dom.StateManager.prototype.viewport=function(x,y,width,height) {if(this.states['viewport'].x!=x||this.states['viewport'].y!=y||this.states['viewport'].width!=width||this.states['viewport'].height!=height) {this.gl.viewport(x,y,width,height);this.states['viewport'].x=x;this.states['viewport'].y=y;this.states['viewport'].width=width;this.states['viewport'].height=height;}};x3dom.StateManager.prototype.bindFramebuffer=function(target,framebuffer) {this.gl.bindFramebuffer(target,framebuffer);this.initStates();};x3dom.BinaryContainerLoader={outOfMemory:false,checkError:function(gl){var glErr=gl.getError();if(glErr){if(glErr==gl.OUT_OF_MEMORY){this.outOfMemory=true;x3dom.debug.logError("GL-Error "+glErr+" on loading binary container (out of memory).");console.error("WebGL: OUT_OF_MEMORY");} else{x3dom.debug.logError("GL-Error "+glErr+" on loading binary container.");}}}};x3dom.BinaryContainerLoader.setupBinGeo=function(shape,sp,gl,viewarea,currContext) {if(this.outOfMemory){return;} var t00=new Date().getTime();var that=this;var binGeo=shape._cf.geometry.node;shape._webgl.binaryGeometry=-1;shape._webgl.internalDownloadCount=((binGeo._vf.index.length>0)?1:0)+ ((binGeo._hasStrideOffset&&binGeo._vf.coord.length>0)?1:0)+ ((!binGeo._hasStrideOffset&&binGeo._vf.coord.length>0)?1:0)+ ((!binGeo._hasStrideOffset&&binGeo._vf.normal.length>0)?1:0)+ ((!binGeo._hasStrideOffset&&binGeo._vf.texCoord.length>0)?1:0)+ ((!binGeo._hasStrideOffset&&binGeo._vf.color.length>0)?1:0);var createTriangleSoup=(binGeo._vf.normalPerVertex==false)||((binGeo._vf.index.length>0)&&(binGeo._vf.indexType=="Int32"||(binGeo._vf.indexType=="Uint32"&&!x3dom.caps.INDEX_UINT)));shape._webgl.makeSeparateTris={index:null,coord:null,normal:null,texCoord:null,color:null,pushBuffer:function(name,buf){this[name]=buf;if(--shape._webgl.internalDownloadCount==0){if(this.coord) this.createMesh();shape._nameSpace.doc.needRender=true;} if(--shape._nameSpace.doc.downloadCount==0) shape._nameSpace.doc.needRender=true;},createMesh:function(){var geoNode=binGeo;if(geoNode._hasStrideOffset){x3dom.debug.logError(geoNode._vf.indexType+" index type and per-face normals not supported for interleaved arrays.");return;} for(var k=0;k3)posBuf.push(this.coord[j+3]);if(this.color){colBuf.push(this.color[j]);colBuf.push(this.color[j+1]);colBuf.push(this.color[j+2]);if(dataLen>3)colBuf.push(this.color[j+3]);} if(this.texCoord){l=texDataLen*(this.index?this.index[i]:i);texcBuf.push(this.texCoord[l]);texcBuf.push(this.texCoord[l+1]);if(texDataLen>3){texcBuf.push(this.texCoord[l+2]);texcBuf.push(this.texCoord[l+3]);}} j=dataLen*(this.index?this.index[i+1]:i+1);var p1=new x3dom.fields.SFVec3f(bgSize.x*this.coord[j]/bgPrecisionMax,bgSize.y*this.coord[j+1]/bgPrecisionMax,bgSize.z*this.coord[j+2]/bgPrecisionMax);posBuf.push(this.coord[j]);posBuf.push(this.coord[j+1]);posBuf.push(this.coord[j+2]);if(dataLen>3)posBuf.push(this.coord[j+3]);if(this.color){colBuf.push(this.color[j]);colBuf.push(this.color[j+1]);colBuf.push(this.color[j+2]);if(dataLen>3)colBuf.push(this.color[j+3]);} if(this.texCoord){l=texDataLen*(this.index?this.index[i+1]:i+1);texcBuf.push(this.texCoord[l]);texcBuf.push(this.texCoord[l+1]);if(texDataLen>3){texcBuf.push(this.texCoord[l+2]);texcBuf.push(this.texCoord[l+3]);}} j=dataLen*(this.index?this.index[i+2]:i+2);var p2=new x3dom.fields.SFVec3f(bgSize.x*this.coord[j]/bgPrecisionMax,bgSize.y*this.coord[j+1]/bgPrecisionMax,bgSize.z*this.coord[j+2]/bgPrecisionMax);posBuf.push(this.coord[j]);posBuf.push(this.coord[j+1]);posBuf.push(this.coord[j+2]);if(dataLen>3)posBuf.push(this.coord[j+3]);if(this.color){colBuf.push(this.color[j]);colBuf.push(this.color[j+1]);colBuf.push(this.color[j+2]);if(dataLen>3)colBuf.push(this.color[j+3]);} if(this.texCoord){l=texDataLen*(this.index?this.index[i+2]:i+2);texcBuf.push(this.texCoord[l]);texcBuf.push(this.texCoord[l+1]);if(texDataLen>3){texcBuf.push(this.texCoord[l+2]);texcBuf.push(this.texCoord[l+3]);}} var a=p0.subtract(p1);var b=p1.subtract(p2);var norm=a.cross(b).normalize();for(j=0;j<3;j++){normBuf.push(norm.x);normBuf.push(norm.y);normBuf.push(norm.z);}} var buffer=gl.createBuffer();shape._webgl.buffers[1]=buffer;gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,x3dom.Utils.getArrayBufferView(geoNode._vf.coordType,posBuf),gl.STATIC_DRAW);gl.vertexAttribPointer(sp.position,geoNode._mesh._numPosComponents,shape._webgl.coordType,false,shape._coordStrideOffset[0],shape._coordStrideOffset[1]);gl.enableVertexAttribArray(sp.position);buffer=gl.createBuffer();shape._webgl.buffers[2]=buffer;gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(normBuf),gl.STATIC_DRAW);gl.vertexAttribPointer(sp.normal,geoNode._mesh._numNormComponents,shape._webgl.normalType,false,shape._normalStrideOffset[0],shape._normalStrideOffset[1]);gl.enableVertexAttribArray(sp.normal);if(this.texCoord) {buffer=gl.createBuffer();shape._webgl.buffers[3]=buffer;gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,x3dom.Utils.getArrayBufferView(geoNode._vf.texCoordType,texcBuf),gl.STATIC_DRAW);gl.vertexAttribPointer(sp.texcoord,geoNode._mesh._numTexComponents,shape._webgl.texCoordType,false,shape._texCoordStrideOffset[0],shape._texCoordStrideOffset[1]);gl.enableVertexAttribArray(sp.texcoord);} if(this.color) {buffer=gl.createBuffer();shape._webgl.buffers[4]=buffer;gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,x3dom.Utils.getArrayBufferView(geoNode._vf.colorType,colBuf),gl.STATIC_DRAW);gl.vertexAttribPointer(sp.color,geoNode._mesh._numColComponents,shape._webgl.colorType,false,shape._colorStrideOffset[0],shape._colorStrideOffset[1]);gl.enableVertexAttribArray(sp.color);} geoNode._vf.vertexCount=[];geoNode._vf.vertexCount[0]=posBuf.length/dataLen;geoNode._mesh._numCoords=geoNode._vf.vertexCount[0];geoNode._mesh._numFaces=geoNode._vf.vertexCount[0]/3;shape._webgl.primType=[];shape._webgl.primType[0]=gl.TRIANGLES;posBuf=null;normBuf=null;texcBuf=null;colBuf=null;this.index=null;this.coord=null;this.normal=null;this.texCoord=null;this.color=null;that.checkError(gl);delete shape._webgl.shader;shape._webgl.shader=currContext.cache.getDynamicShader(gl,viewarea,shape);}};if(binGeo._vf.index.length>0) {var xmlhttp0=new XMLHttpRequest();xmlhttp0.open("GET",encodeURI(shape._nameSpace.getURL(binGeo._vf.index)),true);xmlhttp0.responseType="arraybuffer";shape._nameSpace.doc.downloadCount+=1;xmlhttp0.send(null);xmlhttp0.onload=function() {if(!shape._webgl) return;var XHR_buffer=xmlhttp0.response;var geoNode=binGeo;var attribTypeStr=geoNode._vf.indexType;var indexArray=x3dom.Utils.getArrayBufferView(attribTypeStr,XHR_buffer);if(createTriangleSoup){shape._webgl.makeSeparateTris.pushBuffer("index",indexArray);return;} var indicesBuffer=gl.createBuffer();shape._webgl.buffers[0]=indicesBuffer;if(x3dom.caps.INDEX_UINT&&attribTypeStr=="Uint32"){shape._webgl.indexType=gl.UNSIGNED_INT;} else{shape._webgl.indexType=gl.UNSIGNED_SHORT;} gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,indicesBuffer);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,indexArray,gl.STATIC_DRAW);shape._webgl.binaryGeometry=1;if(geoNode._vf.vertexCount[0]==0) geoNode._vf.vertexCount[0]=indexArray.length;geoNode._mesh._numFaces=0;for(var i=0;i0) {var xmlhttp=new XMLHttpRequest();xmlhttp.open("GET",encodeURI(shape._nameSpace.getURL(binGeo._vf.coord)),true);xmlhttp.responseType="arraybuffer";shape._nameSpace.doc.downloadCount+=1;xmlhttp.send(null);xmlhttp.onload=function() {if(!shape._webgl) return;var XHR_buffer=xmlhttp.response;var geoNode=binGeo;var attribTypeStr=geoNode._vf.coordType;shape._webgl.coordType=x3dom.Utils.getVertexAttribType(attribTypeStr,gl);shape._webgl.normalType=shape._webgl.coordType;shape._webgl.texCoordType=shape._webgl.coordType;shape._webgl.colorType=shape._webgl.coordType;var attributes=x3dom.Utils.getArrayBufferView(attribTypeStr,XHR_buffer);var dataLen=shape._coordStrideOffset[0]/x3dom.Utils.getDataTypeSize(attribTypeStr);if(dataLen) geoNode._mesh._numCoords=attributes.length/dataLen;if(geoNode._vf.index.length==0){for(var i=0;i0) {shape._webgl.buffers[2]=buffer;gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,attributes,gl.STATIC_DRAW);gl.vertexAttribPointer(sp.normal,geoNode._mesh._numNormComponents,shape._webgl.normalType,false,shape._normalStrideOffset[0],shape._normalStrideOffset[1]);gl.enableVertexAttribArray(sp.normal);} if(geoNode._vf.texCoord.length>0) {shape._webgl.buffers[3]=buffer;gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,attributes,gl.STATIC_DRAW);gl.vertexAttribPointer(sp.texcoord,geoNode._mesh._numTexComponents,shape._webgl.texCoordType,false,shape._texCoordStrideOffset[0],shape._texCoordStrideOffset[1]);gl.enableVertexAttribArray(sp.texcoord);} if(geoNode._vf.color.length>0) {shape._webgl.buffers[4]=buffer;gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,attributes,gl.STATIC_DRAW);gl.vertexAttribPointer(sp.color,geoNode._mesh._numColComponents,shape._webgl.colorType,false,shape._colorStrideOffset[0],shape._colorStrideOffset[1]);gl.enableVertexAttribArray(sp.color);} attributes=null;shape._nameSpace.doc.downloadCount-=1;shape._webgl.internalDownloadCount-=1;if(shape._webgl.internalDownloadCount==0) shape._nameSpace.doc.needRender=true;that.checkError(gl);var t11=new Date().getTime()-t00;x3dom.debug.logInfo("XHR/ interleaved array load time: "+t11+" ms");};} if(!binGeo._hasStrideOffset&&binGeo._vf.coord.length>0) {var xmlhttp1=new XMLHttpRequest();xmlhttp1.open("GET",encodeURI(shape._nameSpace.getURL(binGeo._vf.coord)),true);xmlhttp1.responseType="arraybuffer";shape._nameSpace.doc.downloadCount+=1;xmlhttp1.send(null);xmlhttp1.onload=function() {if(!shape._webgl) return;var XHR_buffer=xmlhttp1.response;var geoNode=binGeo;var i=0;var attribTypeStr=geoNode._vf.coordType;shape._webgl.coordType=x3dom.Utils.getVertexAttribType(attribTypeStr,gl);var vertices=x3dom.Utils.getArrayBufferView(attribTypeStr,XHR_buffer);if(createTriangleSoup){shape._webgl.makeSeparateTris.pushBuffer("coord",vertices);return;} gl.bindAttribLocation(sp.program,0,"position");var positionBuffer=gl.createBuffer();shape._webgl.buffers[1]=positionBuffer;gl.bindBuffer(gl.ARRAY_BUFFER,positionBuffer);gl.bufferData(gl.ARRAY_BUFFER,vertices,gl.STATIC_DRAW);gl.bindBuffer(gl.ARRAY_BUFFER,positionBuffer);gl.vertexAttribPointer(sp.position,geoNode._mesh._numPosComponents,shape._webgl.coordType,false,shape._coordStrideOffset[0],shape._coordStrideOffset[1]);gl.enableVertexAttribArray(sp.position);geoNode._mesh._numCoords=vertices.length/geoNode._mesh._numPosComponents;if(geoNode._vf.index.length==0){for(i=0;ivertices[i+0]){min.x=vertices[i+0];} if(min.y>vertices[i+1]){min.y=vertices[i+1];} if(min.z>vertices[i+2]){min.z=vertices[i+2];} if(max.x0) {var xmlhttp2=new XMLHttpRequest();xmlhttp2.open("GET",encodeURI(shape._nameSpace.getURL(binGeo._vf.normal)),true);xmlhttp2.responseType="arraybuffer";shape._nameSpace.doc.downloadCount+=1;xmlhttp2.send(null);xmlhttp2.onload=function() {if(!shape._webgl) return;var XHR_buffer=xmlhttp2.response;var attribTypeStr=binGeo._vf.normalType;shape._webgl.normalType=x3dom.Utils.getVertexAttribType(attribTypeStr,gl);var normals=x3dom.Utils.getArrayBufferView(attribTypeStr,XHR_buffer);if(createTriangleSoup){shape._webgl.makeSeparateTris.pushBuffer("normal",normals);return;} var normalBuffer=gl.createBuffer();shape._webgl.buffers[2]=normalBuffer;gl.bindBuffer(gl.ARRAY_BUFFER,normalBuffer);gl.bufferData(gl.ARRAY_BUFFER,normals,gl.STATIC_DRAW);gl.vertexAttribPointer(sp.normal,binGeo._mesh._numNormComponents,shape._webgl.normalType,false,shape._normalStrideOffset[0],shape._normalStrideOffset[1]);gl.enableVertexAttribArray(sp.normal);normals=null;shape._nameSpace.doc.downloadCount-=1;shape._webgl.internalDownloadCount-=1;if(shape._webgl.internalDownloadCount==0) shape._nameSpace.doc.needRender=true;that.checkError(gl);var t11=new Date().getTime()-t00;x3dom.debug.logInfo("XHR2/ normal load time: "+t11+" ms");};} if(!binGeo._hasStrideOffset&&binGeo._vf.texCoord.length>0) {var xmlhttp3=new XMLHttpRequest();xmlhttp3.open("GET",encodeURI(shape._nameSpace.getURL(binGeo._vf.texCoord)),true);xmlhttp3.responseType="arraybuffer";shape._nameSpace.doc.downloadCount+=1;xmlhttp3.send(null);xmlhttp3.onload=function() {var i,j;var tmp;if(!shape._webgl) return;var XHR_buffer=xmlhttp3.response;var attribTypeStr=binGeo._vf.texCoordType;shape._webgl.texCoordType=x3dom.Utils.getVertexAttribType(attribTypeStr,gl);var texCoords=x3dom.Utils.getArrayBufferView(attribTypeStr,XHR_buffer);if(createTriangleSoup){shape._webgl.makeSeparateTris.pushBuffer("texCoord",texCoords);return;} if(binGeo._vf["idsPerVertex"]) {var idBuffer=gl.createBuffer();shape._webgl.buffers[5]=idBuffer;gl.bindBuffer(gl.ARRAY_BUFFER,idBuffer);var texCoordStride=(shape._texCoordStrideOffset[0]===0)?2:shape._texCoordStrideOffset[0]/4;var ids=x3dom.Utils.getArrayBufferView(attribTypeStr,texCoords.length/2);for(i=0,j=0;i0) {var xmlhttp4=new XMLHttpRequest();xmlhttp4.open("GET",encodeURI(shape._nameSpace.getURL(binGeo._vf.color)),true);xmlhttp4.responseType="arraybuffer";shape._nameSpace.doc.downloadCount+=1;xmlhttp4.send(null);xmlhttp4.onload=function() {if(!shape._webgl) return;var XHR_buffer=xmlhttp4.response;var attribTypeStr=binGeo._vf.colorType;shape._webgl.colorType=x3dom.Utils.getVertexAttribType(attribTypeStr,gl);var colors=x3dom.Utils.getArrayBufferView(attribTypeStr,XHR_buffer);if(createTriangleSoup){shape._webgl.makeSeparateTris.pushBuffer("color",colors);return;} var colorBuffer=gl.createBuffer();shape._webgl.buffers[4]=colorBuffer;gl.bindBuffer(gl.ARRAY_BUFFER,colorBuffer);gl.bufferData(gl.ARRAY_BUFFER,colors,gl.STATIC_DRAW);gl.vertexAttribPointer(sp.color,binGeo._mesh._numColComponents,shape._webgl.colorType,false,shape._colorStrideOffset[0],shape._colorStrideOffset[1]);gl.enableVertexAttribArray(sp.color);colors=null;shape._nameSpace.doc.downloadCount-=1;shape._webgl.internalDownloadCount-=1;if(shape._webgl.internalDownloadCount==0) shape._nameSpace.doc.needRender=true;that.checkError(gl);var t11=new Date().getTime()-t00;x3dom.debug.logInfo("XHR4/ color load time: "+t11+" ms");};}};x3dom.BinaryContainerLoader.setupPopGeo=function(shape,sp,gl,viewarea,currContext) {if(this.outOfMemory){return;} var popGeo=shape._cf.geometry.node;if(popGeo.hasIndex()){shape._webgl.popGeometry=1;shape._webgl.buffers[0]=gl.createBuffer();gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,shape._webgl.buffers[0]);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,popGeo.getTotalNumberOfIndices()*2,gl.STATIC_DRAW);shape._webgl.buffers[5]=gl.createBuffer();var idBuffer=new Float32Array(popGeo._vf.vertexBufferSize);(function(){for(var i=0;i0){redrawNeeded=true;var indexDataView=new Uint8Array(data,0,indexDataLengthInBytes);gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,shape._webgl.buffers[0]);(function(){var indexDataOffset=0;for(var i=0;i0){redrawNeeded=true;var attributeDataView=new Uint8Array(data,indexDataLengthInBytes,vertexDataLengthInBytes);gl.bindBuffer(gl.ARRAY_BUFFER,shape._webgl.buffers[1]);if(!popGeo.hasIndex()){gl.bufferSubData(gl.ARRAY_BUFFER,shape._webgl.currentNumVertices*popGeo.getAttributeStride(),attributeDataView);} else{gl.bufferSubData(gl.ARRAY_BUFFER,popGeo.getVertexDataBufferOffset(lvl)*popGeo.getAttributeStride(),attributeDataView);} shape._webgl.numVerticesAtLevel[lvl]=vertexDataLengthInBytes/popGeo.getAttributeStride();shape._webgl.currentNumVertices+=shape._webgl.numVerticesAtLevel[lvl];} (function(){var numValidIndices=0;for(var i=shape._webgl.levelsAvailable;i0&&env._lowPriorityThreshold<1);this.sortTrans=drawableCollectionConfig.sortTrans;this.prioLevels=10;this.maxTreshold=100;this.sortBySortKey=false;this.sortByPriority=false;this.numberOfNodes=0;this.length=0;};x3dom.DrawableCollection.prototype.cull=function(transform,graphState,singlePath,planeMask){var node=graphState.boundedNode;if(!node||!node._vf.render){return 0;} var volume=node.getVolume();var MASK_SET=63;if(this.frustumCulling&&graphState.needCulling){var wvol;if(singlePath&&!graphState.worldVolume.isValid()){graphState.worldVolume.transformFrom(transform,volume);wvol=graphState.worldVolume;} else if(planeMask0||node.forceUpdateCoverage()){var modelViewMat=this.viewMatrix.mult(transform);graphState.center=modelViewMat.multMatrixPnt(volume.getCenter());var rVec=modelViewMat.multMatrixVec(volume.getRadialVec());var r=rVec.length();var dist=Math.max(-graphState.center.z-r,this.near);var projPixelLength=dist*this.pixelHeightAtDistOne;graphState.coverage=(r*2.0)/projPixelLength;if(this.smallFeatureThreshold>0&&graphState.coverage0){drawable.zPos=graphState.center.z;} else{var center=transform.multMatrixPnt(shape.getCenter());center=this.viewMatrix.multMatrixPnt(center);drawable.zPos=center.z;}} if(!this.sortBySortKey&&drawable.sortKey!=0){this.sortBySortKey=true;} if(this.collection[drawable.sortType]===undefined){this.collection[drawable.sortType]=[];} this.collection[drawable.sortType].push(drawable);this.length++;if(this.context&&this.gl){this.context.setupShape(this.gl,drawable,this.viewarea);}};x3dom.DrawableCollection.prototype.addDrawable=function(drawable){drawable.shaderID=drawable.shape.getShaderProperties(this.viewarea).id;var appearance=drawable.shape._cf.appearance.node;drawable.sortType=appearance?appearance._vf.sortType.toLowerCase():"opaque";drawable.sortKey=appearance?appearance._vf.sortKey:0;if(drawable.sortType=='transparent'){var center=drawable.transform.multMatrixPnt(drawable.shape.getCenter());center=this.viewMatrix.multMatrixPnt(center);drawable.zPos=center.z;} if(!this.sortBySortKey&&drawable.sortKey!=0){this.sortBySortKey=true;} if(this.collection[drawable.sortType]===undefined){this.collection[drawable.sortType]=[];} this.collection[drawable.sortType].push(drawable);this.length++;if(this.context&&this.gl){this.context.setupShape(this.gl,drawable,this.viewarea);}};x3dom.DrawableCollection.prototype.calculatePriority=function(graphState){var priority=Math.max(0,graphState.coverage);var pl=this.prioLevels-1;priority=Math.min(Math.round(priority/(this.maxTreshold/pl)),pl);return priority;};x3dom.DrawableCollection.prototype.concat=function(){var opaque=(this.collection['opaque']!==undefined)?this.collection['opaque']:[];var transparent=(this.collection['transparent']!==undefined)?this.collection['transparent']:[];this.collection=opaque.concat(transparent);};x3dom.DrawableCollection.prototype.get=function(idx){return this.collection[idx];};x3dom.DrawableCollection.prototype.sort=function(){var opaque=[];var transparent=[];var that=this;if(this.collection['opaque']!==undefined){if(this.sortOpaque){this.collection['opaque'].sort(function(a,b){if(a.sortKey==b.sortKey||!that.sortBySortKey){return b.priority-a.priority;} return a.sortKey-b.sortKey;});} opaque=this.collection['opaque'];} if(this.collection['transparent']!==undefined){if(this.sortTrans){this.collection['transparent'].sort(function(a,b){if(a.sortKey==b.sortKey||!that.sortBySortKey){if(a.priority==b.priority||!that.sortByPriority){return a.zPos-b.zPos;} return b.priority-a.priority;} return a.sortKey-b.sortKey;});} transparent=this.collection['transparent'];} this.collection=opaque.concat(transparent);};x3dom.DrawableCollection.prototype.forEach=function(fnc,maxPriority){maxPriority=(maxPriority!==undefined)?Math.min(maxPriority,this.prioLevels):this.prioLevels;var sortKey,priority,shaderID,drawable;for(sortKey=0;sortKey0;--priority) {if(this.collection['opaque'][sortKey][priority]!==undefined) {for(shaderID in this.collection['opaque'][sortKey][priority]) {for(drawable=0;drawable0;--priority) {if(this.collection['transparent'][sortKey][priority]!==undefined) {for(var shaderId in this.collection['transparent'][sortKey][priority]) {this.collection['transparent'][sortKey][priority][shaderId].sort(function(a,b){return a.zPos-b.zPos});for(drawable=0;drawable0&&that._buttonState!=4){var x=that._gridSize*Math.round(track.x/that._gridSize);var y=that._gridSize*Math.round(track.y/that._gridSize);var z=that._gridSize*Math.round(track.z/that._gridSize);track=new x3dom.fields.SFVec3f(x,y,z);} if(!that._matrixTrafo){if(that._buttonState==4){that._moveable.setAttribute("rotation",track.toAxisAngle().toString());} else{that._moveable.setAttribute("translation",track.toString());}} else{if(that._buttonState==4){that._matrixTrafo.setRotate(track);} else{that._matrixTrafo.setTranslate(track);} that._moveable.setAttribute("matrix",that._matrixTrafo.toGL().toString());} if(that._callback){that._callback(that._moveable,track);}} that._lastX=pos[0];that._lastY=pos[1];}}};x3dom.Moveable.prototype.stop=function(event){for(var i=0,n=this._iMove.length;i-1);this.backend=this.x3dElem.getAttribute('backend');if(this.backend) this.backend=this.backend.toLowerCase();else this.backend='none';if(this.backend=='flash'){this.backend='flash';this.canvas=this._createFlashObject(x3dElem);if(this.canvas!=null){this.canvas.parent=this;this.gl=this._initFlashContext(this.canvas,this.flash_renderType);}else{this._createInitFailedDiv(x3dElem);return;}}else{this.canvas=this._createHTMLCanvas(x3dElem);this.canvas.parent=this;this.gl=this._initContext(this.canvas,(this.backend.search("desktop")>=0),(this.backend.search("mobile")>=0),(this.backend.search("flashie")>=0),(this.backend.search("webgl2")>=0));this.backend='webgl';if(this.gl==null) {x3dom.debug.logInfo("Fallback to Flash Renderer");this.backend='flash';this.canvas=this._createFlashObject(x3dElem);if(this.canvas!=null){this.canvas.parent=this;this.gl=this._initFlashContext(this.canvas,this.flash_renderType);}else{this._createInitFailedDiv(x3dElem);return;}}} x3dom.caps.BACKEND=this.backend;var runtimeEnabled=x3dElem.getAttribute("runtimeEnabled");if(runtimeEnabled!==null){this.hasRuntime=(runtimeEnabled.toLowerCase()=="true");}else{this.hasRuntime=x3dElem.hasRuntime;} if(this.gl===null){this.hasRuntime=false;} if(this.backend!="flash"){this.showStat=x3dElem.getAttribute("showStat");this.stateViewer=new x3dom.States(x3dElem);if(this.showStat!==null&&this.showStat=="true"){this.stateViewer.display(true);} this.x3dElem.appendChild(this.stateViewer.viewer);} this.showProgress=x3dElem.getAttribute("showProgress");this.progressDiv=this._createProgressDiv();this.progressDiv.style.display=(this.showProgress!==null&&this.showProgress=="true")?"inline":"none";this.x3dElem.appendChild(this.progressDiv);this.showTouchpoints=x3dElem.getAttribute("showTouchpoints");this.showTouchpoints=this.showTouchpoints?!(this.showTouchpoints.toLowerCase()=="false"):true;this.disableTouch=x3dElem.getAttribute("disableTouch");this.disableTouch=this.disableTouch?(this.disableTouch.toLowerCase()=="true"):false;if(this.canvas!==null&&this.gl!==null&&this.hasRuntime&&this.backend!=="flash"){this.canvas.mouse_dragging=false;this.canvas.mouse_button=0;this.canvas.mouse_drag_x=0;this.canvas.mouse_drag_y=0;this.canvas.isMulti=false;this.canvas.oncontextmenu=function(evt){evt.preventDefault();evt.stopPropagation();return false;};this.canvas.addEventListener("webglcontextlost",function(event){x3dom.debug.logError("WebGL context lost");event.preventDefault();},false);this.canvas.addEventListener("webglcontextrestored",function(event){x3dom.debug.logError("recover WebGL state and resources on context lost NYI");event.preventDefault();},false);this.canvas.addEventListener('mousedown',function(evt){if(!this.isMulti){this.focus();this.classList.add('x3dom-canvas-mousedown');switch(evt.button){case 0:this.mouse_button=1;break;case 1:this.mouse_button=4;break;case 2:this.mouse_button=2;break;default:this.mouse_button=0;break;} if(evt.shiftKey){this.mouse_button=1;} if(evt.ctrlKey){this.mouse_button=4;} if(evt.altKey){this.mouse_button=2;} var pos=this.parent.mousePosition(evt);this.mouse_drag_x=pos.x;this.mouse_drag_y=pos.y;this.mouse_dragging=true;this.parent.doc.onMousePress(that.gl,this.mouse_drag_x,this.mouse_drag_y,this.mouse_button);this.parent.doc.needRender=true;}},false);this.canvas.addEventListener('mouseup',function(evt){if(!this.isMulti){var prev_mouse_button=this.mouse_button;this.classList.remove('x3dom-canvas-mousedown');this.mouse_button=0;this.mouse_dragging=false;this.parent.doc.onMouseRelease(that.gl,this.mouse_drag_x,this.mouse_drag_y,this.mouse_button,prev_mouse_button);this.parent.doc.needRender=true;}},false);this.canvas.addEventListener('mouseover',function(evt){if(!this.isMulti){this.mouse_button=0;this.mouse_dragging=false;this.parent.doc.onMouseOver(that.gl,this.mouse_drag_x,this.mouse_drag_y,this.mouse_button);this.parent.doc.needRender=true;}},false);this.canvas.addEventListener('mouseout',function(evt){if(!this.isMulti){this.mouse_button=0;this.mouse_dragging=false;this.parent.doc.onMouseOut(that.gl,this.mouse_drag_x,this.mouse_drag_y,this.mouse_button);this.parent.doc.needRender=true;}},false);this.canvas.addEventListener('dblclick',function(evt){if(!this.isMulti){this.mouse_button=0;var pos=this.parent.mousePosition(evt);this.mouse_drag_x=pos.x;this.mouse_drag_y=pos.y;this.mouse_dragging=false;this.parent.doc.onDoubleClick(that.gl,this.mouse_drag_x,this.mouse_drag_y);this.parent.doc.needRender=true;}},false);this.canvas.addEventListener('mousemove',function(evt){if(!this.isMulti){if(evt.shiftKey){this.mouse_button=1;} if(evt.ctrlKey){this.mouse_button=4;} if(evt.altKey){this.mouse_button=2;} var pos=this.parent.mousePosition(evt);this.mouse_drag_x=pos.x;this.mouse_drag_y=pos.y;if(this.mouse_dragging){this.parent.doc.onDrag(that.gl,this.mouse_drag_x,this.mouse_drag_y,this.mouse_button);} else{this.parent.doc.onMove(that.gl,this.mouse_drag_x,this.mouse_drag_y,this.mouse_button);} this.parent.doc.needRender=true;evt.preventDefault();evt.stopPropagation();}},false);this.canvas.addEventListener('DOMMouseScroll',function(evt){if(!this.isMulti){this.focus();this.mouse_drag_y+=2*evt.detail;this.parent.doc.onDrag(that.gl,this.mouse_drag_x,this.mouse_drag_y,2);this.parent.doc.needRender=true;evt.preventDefault();evt.stopPropagation();}},false);this.canvas.addEventListener('mousewheel',function(evt){if(!this.isMulti){this.focus();this.mouse_drag_y-=0.1*evt.wheelDelta;this.parent.doc.onDrag(that.gl,this.mouse_drag_x,this.mouse_drag_y,2);this.parent.doc.needRender=true;evt.preventDefault();evt.stopPropagation();}},false);this.canvas.addEventListener('keypress',function(evt){var keysEnabled=this.parent.x3dElem.getAttribute("keysEnabled");if(!keysEnabled||keysEnabled.toLowerCase()=="true"){this.parent.doc.onKeyPress(evt.charCode);} this.parent.doc.needRender=true;},true);this.canvas.addEventListener('keyup',function(evt){var keysEnabled=this.parent.x3dElem.getAttribute("keysEnabled");if(!keysEnabled||keysEnabled.toLowerCase()=="true"){this.parent.doc.onKeyUp(evt.keyCode);} this.parent.doc.needRender=true;},true);this.canvas.addEventListener('keydown',function(evt){var keysEnabled=this.parent.x3dElem.getAttribute("keysEnabled");if(!keysEnabled||keysEnabled.toLowerCase()=="true"){this.parent.doc.onKeyDown(evt.keyCode);} this.parent.doc.needRender=true;},true);var touches={numTouches:0,firstTouchTime:new Date().getTime(),firstTouchPoint:new x3dom.fields.SFVec2f(0,0),lastDrag:new x3dom.fields.SFVec2f(),lastMiddle:new x3dom.fields.SFVec2f(),lastDistance:new x3dom.fields.SFVec2f(),lastSquareDistance:0,lastAngle:0,lastLayer:[],examineNavType:true,calcAngle:function(vector) {var rotation=vector.normalize().dot(new x3dom.fields.SFVec2f(1,0));rotation=Math.acos(rotation);if(vector.y<0) rotation=Math.PI+(Math.PI-rotation);return rotation;},disableTouch:this.disableTouch,visMarker:this.showTouchpoints,visMarkerBag:[],visualizeTouches:function(evt) {if(!this.visMarker) return;var touchBag=[];var marker=null;for(var i=0;i=0){marker=document.getElementById("visMarker"+id);marker.style.left=(evt.touches[i].pageX)+"px";marker.style.top=(evt.touches[i].pageY)+"px";} else{marker=document.createElement("div");marker.appendChild(document.createTextNode("#"+id));marker.id="visMarker"+id;marker.className="x3dom-touch-marker";document.body.appendChild(marker);index=this.visMarkerBag.length;this.visMarkerBag[index]=id;} touchBag.push(id);} for(var j=this.visMarkerBag.length-1;j>=0;j--){var oldId=this.visMarkerBag[j];if(touchBag.indexOf(oldId)<0){this.visMarkerBag.splice(j,1);marker=document.getElementById("visMarker"+oldId);document.body.removeChild(marker);}}}};var mozilla_ids=[];var mozilla_touches={touches:[],preventDefault:function(){}};var touchStartHandler=function(evt,doc) {this.isMulti=true;evt.preventDefault();touches.visualizeTouches(evt);this.focus();if(doc==null) doc=this.parent.doc;var navi=doc._scene.getNavigationInfo();touches.examineNavType=(navi.getType()=="examine");touches.lastLayer=[];var i,pos;for(i=0;i=2){touches.numTouches=2;var touch0=new x3dom.fields.SFVec2f(evt.touches[0].screenX,evt.touches[0].screenY);var touch1=new x3dom.fields.SFVec2f(evt.touches[1].screenX,evt.touches[1].screenY);var distance=touch1.subtract(touch0);var middle=distance.multiply(0.5).add(touch0);var squareDistance=distance.dot(distance);touches.lastDistance=distance;touches.lastMiddle=middle;touches.lastSquareDistance=squareDistance;touches.lastAngle=touches.calcAngle(distance);} doc._scene.updateVolume();if(touches.examineNavType){for(i=0;i=2){var touch0=new x3dom.fields.SFVec2f(evt.touches[0].screenX,evt.touches[0].screenY);var touch1=new x3dom.fields.SFVec2f(evt.touches[1].screenX,evt.touches[1].screenY);var distance=touch1.subtract(touch0);var middle=distance.multiply(0.5).add(touch0);var squareDistance=distance.dot(distance);var deltaMiddle=middle.subtract(touches.lastMiddle);var deltaZoom=squareDistance-touches.lastSquareDistance;var deltaMove=new x3dom.fields.SFVec3f(deltaMiddle.x/screen.width,-deltaMiddle.y/screen.height,deltaZoom/(screen.width*screen.height*0.2));var rotation=touches.calcAngle(distance);var angleDelta=touches.lastAngle-rotation;touches.lastAngle=rotation;rotMatrix=x3dom.fields.SFMatrix4f.rotationZ(angleDelta);touches.lastMiddle=middle;touches.lastDistance=distance;touches.lastSquareDistance=squareDistance;doc.onMoveView(that.gl,deltaMove,rotMatrix);}} else if(evt.touches.length){pos=this.parent.mousePosition(evt.touches[0]);doc.onDrag(that.gl,pos.x,pos.y,1);} doc.needRender=true;};var touchMoveHandlerMoz=function(evt) {evt.preventDefault();for(var i=0;i0){version=x3dom.versionInfo.version;}else{version=x3dom.versionInfo.version.substr(3);}} swf_path="http://www.x3dom.org/download/"+version+"/x3dom.swf";x3dom.debug.logWarning("Can't find local x3dom.swf ("+version+"). X3DOM now using the online version from x3dom.org."+"The online version needs a crossdomain.xml "+"file in the root directory of your domain to access textures");} var width=this.x3dElem.getAttribute("width");var idx=-1;if(width==null){width=550;}else{idx=width.indexOf("px");if(idx!=-1){width=width.substr(0,idx);}} var height=this.x3dElem.getAttribute("height");if(height==null){height=400;}else{idx=height.indexOf("px");if(idx!=-1){height=height.substr(0,idx);}} var renderType=this.x3dElem.getAttribute("flashrenderer");if(renderType==null){this.flash_renderType="forward";}else{this.flash_renderType="deferred";} var obj=document.createElement('object');obj.setAttribute('width','100%');obj.setAttribute('height','100%');obj.setAttribute('id',id);if(!document.doctype||document.doctype&&document.doctype.publicId.search(/DTD XHTML/i)!=-1){x3dom.debug.logWarning("Flash backend doesn't like XHTML, please use HTML5!");obj.setAttribute('style','width:'+width+'px; height:'+height+'px;');}else{if(x3dElem.getAttribute('style')==null){x3dElem.setAttribute('style','width:'+width+'px; height:'+height+'px;');}} this.appendParam(obj,'menu','false');this.appendParam(obj,'quality','high');this.appendParam(obj,'wmode','direct');this.appendParam(obj,'allowScriptAccess','always');this.appendParam(obj,'flashvars','canvasIdx='+this._canvasIdx+'&renderType='+this.flash_renderType);this.appendParam(obj,'movie',swf_path);if(navigator.appName=="Microsoft Internet Explorer"){x3dElem.appendChild(obj);obj.setAttribute('classid','clsid:d27cdb6e-ae6d-11cf-96b8-444553540000');}else{obj.setAttribute('type','application/x-shockwave-flash');obj.setAttribute('data',swf_path);x3dElem.appendChild(obj);} return obj;}};x3dom.X3DCanvas.prototype._createHTMLCanvas=function(x3dElem) {x3dom.debug.logInfo("Creating canvas for (X)3D element...");var canvas=document.createElement('canvas');canvas.setAttribute("class","x3dom-canvas");var userStyle=x3dElem.getAttribute("style");if(userStyle){x3dom.debug.logInfo("Inline X3D styles detected");} var evtArr=["onmousedown","onmousemove","onmouseout","onmouseover","onmouseup","onclick","ondblclick","onkeydown","onkeypress","onkeyup","ontouchstart","ontouchmove","ontouchend","ontouchcancel","ontouchleave","ontouchenter","onMozTouchDown","onMozTouchMove","onMozTouchUp","ondragstart","ondrop","ondragover"];for(var i=0;i=0){x3dom.debug.logWarning("The width attribute is to be specified in pixels not in percent.");} canvas.style.width=w;canvas.setAttribute("width",w);} if((h=x3dElem.getAttribute("height"))!==null){if(h.indexOf("%")>=0){x3dom.debug.logWarning("The height attribute is to be specified in pixels not in percent.");} canvas.style.height=h;canvas.setAttribute("height",h);} canvas.setAttribute("tabindex","0");return canvas;};x3dom.X3DCanvas.prototype._watchForResize=function(){var new_dim=[parseInt(x3dom.getStyle(this.canvas,"width")),parseInt(x3dom.getStyle(this.canvas,"height"))];if((this._current_dim[0]!=new_dim[0])||(this._current_dim[1]!=new_dim[1])){this._current_dim=new_dim;this.x3dElem.setAttribute("width",new_dim[0]+"px");this.x3dElem.setAttribute("height",new_dim[1]+"px");}};x3dom.X3DCanvas.prototype._createProgressDiv=function(){var progressDiv=document.createElement('div');progressDiv.setAttribute("class","x3dom-progress");var _text=document.createElement('strong');_text.appendChild(document.createTextNode('Loading...'));progressDiv.appendChild(_text);var _inner=document.createElement('span');_inner.setAttribute('style',"width: 25%;");_inner.appendChild(document.createTextNode(' '));progressDiv.appendChild(_inner);progressDiv.oncontextmenu=progressDiv.onmousedown=function(evt){evt.preventDefault();evt.stopPropagation();return false;};return progressDiv;};x3dom.X3DCanvas.prototype.mousePosition=function(evt) {var x=0,y=0;if("getBoundingClientRect"in document.documentElement){var elem=evt.target.offsetParent;var box=elem.getBoundingClientRect();var scrollLeft=window.pageXOffset||document.documentElement.scrollLeft;var scrollTop=window.pageYOffset||document.documentElement.scrollTop;var compStyle=document.defaultView.getComputedStyle(elem,null);var paddingLeft=parseFloat(compStyle.getPropertyValue('padding-left'));var borderLeftWidth=parseFloat(compStyle.getPropertyValue('border-left-width'));var paddingTop=parseFloat(compStyle.getPropertyValue('padding-top'));var borderTopWidth=parseFloat(compStyle.getPropertyValue('border-top-width'));x=Math.round(evt.pageX-(box.left+paddingLeft+borderLeftWidth+scrollLeft));y=Math.round(evt.pageY-(box.top+paddingTop+borderTopWidth+scrollTop));} else{x3dom.debug.logError('NO getBoundingClientRect');} return new x3dom.fields.SFVec2f(x,y);};x3dom.X3DCanvas.prototype.tick=function() {var runtime=this.x3dElem.runtime;var d=new Date().getTime();var diff=d-this.lastTimeFPSWasTaken;var fps=1000.0/(d-this.fps_t0);this.fps_t0=d;this.doc.advanceTime(d/1000.0);var animD=new Date().getTime()-d;if(this.doc.needRender){if(diff>=1000){runtime.fps=this.framesSinceLastTime/(diff/1000.0);runtime.addMeasurement('FPS',runtime.fps);this.framesSinceLastTime=0;this.lastTimeFPSWasTaken=d;} this.framesSinceLastTime++;runtime.addMeasurement('ANIM',animD);if(runtime.isReady==false){runtime.ready();runtime.isReady=true;} runtime.enterFrame();if(this.backend=='flash'){if(this.isFlashReady){this.canvas.setFPS({fps:fps});this.doc.needRender=false;this.doc.render(this.gl);}} else{this.doc.needRender=false;this.doc.render(this.gl);if(!this.doc._scene._vf.doPickPass) runtime.removeMeasurement('PICKING');} runtime.exitFrame();} if(this.progressDiv){if(this.doc.downloadCount>0){runtime.addInfo("#LOADS:",this.doc.downloadCount);}else{runtime.removeInfo("#LOADS:");} if(this.doc.properties.getProperty("showProgress")!=='false'){if(this.progressDiv){this.progressDiv.childNodes[0].textContent='Loading: '+(+this.doc.downloadCount);if(this.doc.downloadCount>0){this.progressDiv.style.display='inline';}else{this.progressDiv.style.display='none';}}}else{this.progressDiv.style.display='none';}}};x3dom.X3DCanvas.prototype.load=function(uri,sceneElemPos,settings){this.doc=new x3dom.X3DDocument(this.canvas,this.gl,settings);var x3dCanvas=this;this.doc.onload=function(){if(x3dCanvas.hasRuntime){(function mainloop(){if(x3dCanvas.doc&&x3dCanvas.x3dElem.runtime){x3dCanvas._watchForResize();x3dCanvas.tick();window.requestAnimFrame(mainloop,x3dCanvas);}})();}else{x3dCanvas.tick();}};this.x3dElem.render=function(){if(x3dCanvas.hasRuntime){x3dCanvas.doc.needRender=true;}else{x3dCanvas.doc.render(x3dCanvas.gl);}};this.x3dElem.context=x3dCanvas.gl.ctx3d;this.doc.onerror=function(){alert('Failed to load X3D document');};this.doc.load(uri,sceneElemPos);};x3dom.runtime={};x3dom.Runtime=function(doc,canvas){this.doc=doc;this.canvas=canvas;this.config={};this.isReady=false;this.fps=0;this.states={measurements:[],infos:[]};};x3dom.Runtime.prototype.addMeasurement=function(title,value){this.states.measurements[title]=value;};x3dom.Runtime.prototype.removeMeasurement=function(title){if(this.states.measurements[title]){delete this.states.measurements[title];}};x3dom.Runtime.prototype.addInfo=function(title,value){this.states.infos[title]=value;};x3dom.Runtime.prototype.removeInfo=function(title){delete this.states.infos[title];};x3dom.Runtime.prototype.initialize=function(doc,canvas){this.doc=doc;this.canvas=canvas;this.config={};this.isReady=false;this.fps=0;};x3dom.Runtime.prototype.noBackendFound=function(){x3dom.debug.logInfo('No backend found. Unable to render.');};x3dom.Runtime.prototype.ready=function(){x3dom.debug.logInfo('System ready.');};x3dom.Runtime.prototype.enterFrame=function(){};x3dom.Runtime.prototype.exitFrame=function(){};x3dom.Runtime.prototype.triggerRedraw=function(){this.canvas.doc.needRender=true;};x3dom.Runtime.prototype.getActiveBindable=function(typeName){var stacks;var i,current,result;var type;stacks=this.canvas.doc._bindableBag._stacks;result=[];type=x3dom.nodeTypesLC[typeName.toLowerCase()];if(!type){x3dom.debug.logError('No node of type "'+typeName+'" found.');return null;} for(i=0;i0){this.canvas.doc._viewarea.animateTo(this.canvas.doc._viewarea.getLightMatrix()[0],this.canvas.doc._scene.getViewpoint());return true;}else{x3dom.debug.logInfo("No lights to navigate to.");return false;}};x3dom.Runtime.prototype.uprightView=function(){this.canvas.doc._viewarea.uprightView();};x3dom.Runtime.prototype.fitAll=function(updateCenterOfRotation) {if(updateCenterOfRotation===undefined){updateCenterOfRotation=true;} var scene=this.canvas.doc._scene;scene.updateVolume();this.canvas.doc._viewarea.fit(scene._lastMin,scene._lastMax,updateCenterOfRotation);};x3dom.Runtime.prototype.fitObject=function(obj,updateCenterOfRotation) {if(obj&&obj._x3domNode) {if(updateCenterOfRotation===undefined){updateCenterOfRotation=true;} var min=x3dom.fields.SFVec3f.MAX();var max=x3dom.fields.SFVec3f.MIN();var vol=obj._x3domNode.getVolume();vol.getBounds(min,max);var mat=obj._x3domNode.getCurrentTransform();min=mat.multMatrixPnt(min);max=mat.multMatrixPnt(max);if(x3dom.isa(obj._x3domNode,x3dom.nodeTypes.X3DTransformNode)) {var invMat=obj._x3domNode._trafo.inverse();min=invMat.multMatrixPnt(min);max=invMat.multMatrixPnt(max);} this.canvas.doc._viewarea.fit(min,max,updateCenterOfRotation);}};x3dom.Runtime.prototype.showAll=function(axis){this.canvas.doc._viewarea.showAll(axis);};x3dom.Runtime.prototype.showObject=function(obj) {if(obj&&obj._x3domNode) {var min=x3dom.fields.SFVec3f.MAX();var max=x3dom.fields.SFVec3f.MIN();var vol=obj._x3domNode.getVolume();vol.getBounds(min,max);var mat=obj._x3domNode.getCurrentTransform();min=mat.multMatrixPnt(min);max=mat.multMatrixPnt(max);var viewarea=this.canvas.doc._viewarea;var focalLen=(viewarea._widthx3dom.fields.Eps){focalLen/=ta;} var w=viewarea._width-1;var h=viewarea._height-1;var frame=0.25;var minScreenPos=new x3dom.fields.SFVec2f(frame*w,frame*h);frame=0.75;var maxScreenPos=new x3dom.fields.SFVec2f(frame*w,frame*h);var dia2=max.subtract(min).multiply(0.5);var rw=dia2.length();var pc=min.add(dia2);var vc=maxScreenPos.subtract(minScreenPos).multiply(0.5);var rs=1.5*vc.length();vc=vc.add(minScreenPos);var dist=1.0;if(rs>x3dom.fields.Eps){dist=(rw/rs)*Math.sqrt(vc.x*vc.x+vc.y*vc.y+focalLen*focalLen);} n0=mat.multMatrixVec(n0).normalize();n0=n0.multiply(dist);var p0=pc.add(n0);var qDir=x3dom.fields.Quaternion.rotateFromTo(new x3dom.fields.SFVec3f(0,0,1),n0);var R=qDir.toMatrix();var T=x3dom.fields.SFMatrix4f.translation(p0.negate());var M=x3dom.fields.SFMatrix4f.translation(p0);M=M.mult(R).mult(T).mult(M);var viewmat=M.inverse();viewarea.animateTo(viewmat,viewpoint);}};x3dom.Runtime.prototype.getCenter=function(domNode){if(domNode&&domNode._x3domNode&&(this.isA(domNode,"X3DShapeNode")||this.isA(domNode,"X3DGeometryNode"))) {return domNode._x3domNode.getCenter();} return null;};x3dom.Runtime.prototype.getCurrentTransform=function(domNode){if(domNode&&domNode._x3domNode) {return domNode._x3domNode.getCurrentTransform();} return null;};x3dom.Runtime.prototype.getBBox=function(domNode){if(domNode&&domNode._x3domNode&&this.isA(domNode,"X3DBoundedObject")) {var vol=domNode._x3domNode.getVolume();return{min:x3dom.fields.SFVec3f.copy(vol.min),max:x3dom.fields.SFVec3f.copy(vol.max)}} return null;};x3dom.Runtime.prototype.getSceneBBox=function(){var scene=this.canvas.doc._scene;scene.updateVolume();return{min:x3dom.fields.SFVec3f.copy(scene._lastMin),max:x3dom.fields.SFVec3f.copy(scene._lastMax)}};x3dom.Runtime.prototype.debug=function(show){var doc=this.canvas.doc;if(doc._viewarea._visDbgBuf===undefined) doc._viewarea._visDbgBuf=(doc._x3dElem.getAttribute("showLog")==='true');if(arguments.length>0){if(show===true){doc._viewarea._visDbgBuf=true;x3dom.debug.logContainer.style.display="block";} else{doc._viewarea._visDbgBuf=false;x3dom.debug.logContainer.style.display="none";}} else{doc._viewarea._visDbgBuf=!doc._viewarea._visDbgBuf;x3dom.debug.logContainer.style.display=(doc._viewarea._visDbgBuf==true)?"block":"none";} doc.needRender=true;return doc._viewarea._visDbgBuf;};x3dom.Runtime.prototype.navigationType=function(){return this.canvas.doc._scene.getNavigationInfo().getType();};x3dom.Runtime.prototype.noNav=function(){this.canvas.doc._scene.getNavigationInfo().setType("none");};x3dom.Runtime.prototype.examine=function(){this.canvas.doc._scene.getNavigationInfo().setType("examine");};x3dom.Runtime.prototype.turnTable=function(){this.canvas.doc._scene.getNavigationInfo().setType("turntable");};x3dom.Runtime.prototype.fly=function(){this.canvas.doc._scene.getNavigationInfo().setType("fly");};x3dom.Runtime.prototype.freeFly=function(){this.canvas.doc._scene.getNavigationInfo().setType("freefly");};x3dom.Runtime.prototype.lookAt=function(){this.canvas.doc._scene.getNavigationInfo().setType("lookat");};x3dom.Runtime.prototype.lookAround=function(){this.canvas.doc._scene.getNavigationInfo().setType("lookaround");};x3dom.Runtime.prototype.walk=function(){this.canvas.doc._scene.getNavigationInfo().setType("walk");};x3dom.Runtime.prototype.game=function(){this.canvas.doc._scene.getNavigationInfo().setType("game");};x3dom.Runtime.prototype.helicopter=function(){this.canvas.doc._scene.getNavigationInfo().setType("helicopter");};x3dom.Runtime.prototype.resetExamin=function(){var viewarea=this.canvas.doc._viewarea;viewarea._rotMat=x3dom.fields.SFMatrix4f.identity();viewarea._transMat=x3dom.fields.SFMatrix4f.identity();viewarea._movement=new x3dom.fields.SFVec3f(0,0,0);viewarea._needNavigationMatrixUpdate=true;this.canvas.doc.needRender=true;};x3dom.Runtime.prototype.togglePoints=function(lines){var doc=this.canvas.doc;var mod=(lines===true)?3:2;doc._viewarea._points=++doc._viewarea._points%mod;doc.needRender=true;return doc._viewarea._points;};x3dom.Runtime.prototype.pickRect=function(x1,y1,x2,y2){return this.canvas.doc.onPickRect(this.canvas.gl,x1,y1,x2,y2);};x3dom.Runtime.prototype.pickMode=function(options){if(options&&options.internal===true){return this.canvas.doc._scene._vf.pickMode;} return this.canvas.doc._scene._vf.pickMode.toLowerCase();};x3dom.Runtime.prototype.changePickMode=function(type){type=type.toLowerCase();switch(type){case'idbuf':type='idBuf';break;case'idbuf24':type='idBuf24';break;case'idbufid':type='idBufId';break;case'texcoord':type='texCoord';break;case'color':type='color';break;case'box':type='box';break;default:x3dom.debug.logWarning("Switch pickMode to "+type+' unknown intersect type');type=undefined;} if(type!==undefined){this.canvas.doc._scene._vf.pickMode=type;x3dom.debug.logInfo("Switched pickMode to '"+type+"'.");return true;} return false;};x3dom.Runtime.prototype.speed=function(newSpeed){var navi=this.canvas.doc._scene.getNavigationInfo();if(newSpeed){navi._vf.speed=newSpeed;x3dom.debug.logInfo("Changed navigation speed to "+navi._vf.speed);} return navi._vf.speed;};x3dom.Runtime.prototype.statistics=function(mode){var states=this.canvas.stateViewer;if(states){this.canvas.doc.needRender=true;if(mode===true){states.display(mode);return true;} else if(mode===false){states.display(mode);return false;} else{states.display(!states.active);return states.active;}} return false;};x3dom.Runtime.prototype.processIndicator=function(mode){var processDiv=this.canvas.progressDiv;if(processDiv){if(mode===true){processDiv.style.display='inline';return true;} else if(mode===false){processDiv.style.display='none';return false;} return processDiv.style.display!='none'} return false;};x3dom.Runtime.prototype.properties=function(){return this.canvas.doc.properties;};x3dom.Runtime.prototype.backendName=function(){return this.canvas.backend;};x3dom.Runtime.prototype.getFPS=function(){return this.fps;};x3dom.Runtime.prototype.isA=function(domNode,nodeType){var inherits=false;if(nodeType&&domNode&&domNode._x3domNode){if(nodeType===""){nodeType="X3DNode";} inherits=x3dom.isa(domNode._x3domNode,x3dom.nodeTypesLC[nodeType.toLowerCase()]);} return inherits;};x3dom.detectActiveX=function(){var isInstalled=false;if(window.ActiveXObject){var control=null;try{control=new ActiveXObject('AVALONATX.InstantPluginATXCtrl.1');}catch(e){} if(control){isInstalled=true;}} return isInstalled;};x3dom.rerouteSetAttribute=function(node,browser){node._setAttribute=node.setAttribute;node.setAttribute=function(name,value){var id=node.getAttribute("_x3domNode");var anode=browser.findNode(id);if(anode) return anode.parseField(name,value);else return 0;};for(var i=0;i" +x3dom.versionInfo.revision+", "+"Date "+x3dom.versionInfo.date);} x3dom.debug.logInfo("Found "+(x3ds.length-w3sg.length)+" X3D and "+ w3sg.length+" (experimental) WebSG nodes...");var x3d_element;var x3dcanvas;var altDiv,altP,aLnk,altImg;var t0,t1;for(i=0;i2.3) {font_size=2.3;}} var textX,textY;var paragraph=this.node._vf.string;var text_canvas=document.createElement('canvas');text_canvas.dir=leftToRight;var textHeight=font_size*42;var textAlignment=font_justify;document.body.appendChild(text_canvas);var text_ctx=text_canvas.getContext('2d');text_ctx.font=font_style+" "+textHeight+"px "+font_family;var maxWidth=text_ctx.measureText(paragraph[0]).width;var i;for(i=1;imaxWidth) maxWidth=text_ctx.measureText(paragraph[i]).width;} var canvas_scale=1.1;text_canvas.width=maxWidth*canvas_scale;text_canvas.height=textHeight*paragraph.length*canvas_scale;switch(textAlignment){case"left":textX=0;break;case"center":textX=text_canvas.width/2;break;case"right":textX=text_canvas.width;break;} var txtW=text_canvas.width;var txtH=text_canvas.height;text_ctx.fillStyle='rgba(0,0,0,0)';text_ctx.fillRect(0,0,text_ctx.canvas.width,text_ctx.canvas.height);text_ctx.fillStyle='white';text_ctx.lineWidth=2.5;text_ctx.strokeStyle='grey';text_ctx.textBaseline='top';text_ctx.font=font_style+" "+textHeight+"px "+font_family;text_ctx.textAlign=textAlignment;for(i=0;i1){x3dom.debug.logError("X3D element has more than one Scene child (has "+ x3dElem.childNodes.length+").");} else{return sceneElems[0];} return null;};x3dom.X3DDocument.prototype._setup=function(sceneDoc,uriDocs,sceneElemPos){var doc=this;function cleanNodeBag(bag,node){for(var i=0,n=bag.length;i0){this._viewarea.animateTo(this._viewarea.getLightMatrix()[0],this._scene.getViewpoint());} break;case 117:this._viewarea.uprightView();break;case 118:var that=this;(function(){var viewpoint=that._viewarea._scene.getViewpoint();var mat_view=that._viewarea.getViewMatrix().inverse();var rotation=new x3dom.fields.Quaternion(0,0,1,0);rotation.setValue(mat_view);var rot=rotation.toAxisAngle();var translation=mat_view.e3();x3dom.debug.logInfo('\n<Viewpoint position="'+translation.x.toFixed(5)+' ' +translation.y.toFixed(5)+' '+translation.z.toFixed(5)+'" '+'orientation="'+rot[0].x.toFixed(5)+' '+rot[0].y.toFixed(5)+' ' +rot[0].z.toFixed(5)+' '+rot[1].toFixed(5)+'" \n\t'+'zNear="'+viewpoint.getNear().toFixed(5)+'" '+'zFar="'+viewpoint.getFar().toFixed(5)+'" '+'description="'+viewpoint._vf.description+'">'+'</Viewpoint>');})();break;case 119:nav.setType("walk",this._viewarea);break;case 121:nav.setType("freefly",this._viewarea);break;default:}};x3dom.X3DDocument.prototype.shutdown=function(ctx) {if(!ctx){return;} ctx.shutdown(this._viewarea);};x3dom.MatrixMixer=function(beginTime,endTime){if(arguments.length===0){this._beginTime=0;this._endTime=1;} else{this._beginTime=beginTime;this._endTime=endTime;} this._beginMat=x3dom.fields.SFMatrix4f.identity();this._beginInvMat=x3dom.fields.SFMatrix4f.identity();this._beginLogMat=x3dom.fields.SFMatrix4f.identity();this._endMat=x3dom.fields.SFMatrix4f.identity();this._endLogMat=x3dom.fields.SFMatrix4f.identity();};x3dom.MatrixMixer.prototype.calcFraction=function(time){var fraction=(time-this._beginTime)/(this._endTime-this._beginTime);return(Math.sin((fraction*Math.PI)-(Math.PI/2))+1)/2.0;};x3dom.MatrixMixer.prototype.setBeginMatrix=function(mat){this._beginMat.setValues(mat);this._beginInvMat=mat.inverse();this._beginLogMat=x3dom.fields.SFMatrix4f.zeroMatrix();};x3dom.MatrixMixer.prototype.setEndMatrix=function(mat){this._endMat.setValues(mat);this._endLogMat=mat.mult(this._beginInvMat).log();this._logDiffMat=this._endLogMat.addScaled(this._beginLogMat,-1);};x3dom.MatrixMixer.prototype.mix=function(time){var mat=null;if(time<=this._beginTime) {mat=x3dom.fields.SFMatrix4f.copy(this._beginLogMat);} else {if(time>=this._endTime) {mat=x3dom.fields.SFMatrix4f.copy(this._endLogMat);} else {var fraction=this.calcFraction(time);mat=this._logDiffMat.multiply(fraction).add(this._beginLogMat);}} return mat.exp().mult(this._beginMat);};x3dom.InputTypes={};x3dom.InputTypes.NAVIGATION=1;x3dom.InputTypes.INTERACTION=2;x3dom.Viewarea=function(document,scene){this._doc=document;this._scene=scene;document._nodeBag.viewarea.push(this);this._pickingInfo={pickPos:new x3dom.fields.SFVec3f(0,0,0),pickNorm:new x3dom.fields.SFVec3f(0,0,1),pickObj:null,firstObj:null,lastObj:null,lastClickObj:null,shadowObjectId:-1};this._currentInputType=x3dom.InputTypes.NAVIGATION;this._rotMat=x3dom.fields.SFMatrix4f.identity();this._transMat=x3dom.fields.SFMatrix4f.identity();this._movement=new x3dom.fields.SFVec3f(0,0,0);this._needNavigationMatrixUpdate=true;this._deltaT=0;this._pitch=0;this._yaw=0;this._eyePos=new x3dom.fields.SFVec3f(0,0,0);this._width=400;this._height=300;this._dx=0;this._dy=0;this._lastX=-1;this._lastY=-1;this._pressX=-1;this._pressY=-1;this._lastButton=0;this._points=0;this._numRenderedNodes=0;this._pick=new x3dom.fields.SFVec3f(0,0,0);this._pickNorm=new x3dom.fields.SFVec3f(0,0,1);this._isAnimating=false;this._isMoving=false;this._lastTS=0;this._mixer=new x3dom.MatrixMixer();this.arc=null;};x3dom.Viewarea.prototype.tick=function(timeStamp) {var needMixAnim=false;var env=this._scene.getEnvironment();if(env._vf.enableARC&&this.arc==null) {this.arc=new x3dom.arc.AdaptiveRenderControl(this._scene);} if(this._mixer._beginTime>0) {needMixAnim=true;if(timeStamp>=this._mixer._beginTime) {if(timeStamp<=this._mixer._endTime) {var mat=this._mixer.mix(timeStamp);this._scene.getViewpoint().setView(mat);} else{this._mixer._beginTime=0;this._mixer._endTime=0;this._scene.getViewpoint().setView(this._mixer._endMat);}} else{this._mixer._beginTime=0;this._mixer._endTime=0;this._scene.getViewpoint().setView(this._mixer._beginMat);}} var needNavAnim=this.navigateTo(timeStamp);var lastIsAnimating=this._isAnimating;this._lastTS=timeStamp;this._isAnimating=(needMixAnim||needNavAnim);if(this.arc!=null) {this.arc.update(this.isMovingOrAnimating()?1:0,this._doc._x3dElem.runtime.getFPS());} return(this._isAnimating||lastIsAnimating);};x3dom.Viewarea.prototype.isMoving=function() {return this._isMoving;};x3dom.Viewarea.prototype.isAnimating=function() {return this._isAnimating;};x3dom.Viewarea.prototype.isMovingOrAnimating=function() {return(this._isMoving||this._isAnimating);};x3dom.Viewarea.prototype.navigateTo=function(timeStamp) {var navi=this._scene.getNavigationInfo();var navType=navi.getType();var needNavAnim=(this._currentInputType==x3dom.InputTypes.NAVIGATION)&&(navType==="game"||(this._lastButton>0&&(navType.indexOf("fly")>=0||navType==="walk"||navType==="helicopter"||navType.substr(0,5)==="looka")));this._deltaT=timeStamp-this._lastTS;if(needNavAnim) {var avatarRadius=0.25;var avatarHeight=1.6;var avatarKnee=0.75;if(navi._vf.avatarSize.length>2){avatarRadius=navi._vf.avatarSize[0];avatarHeight=navi._vf.avatarSize[1];avatarKnee=navi._vf.avatarSize[2];} var currViewMat=this.getViewMatrix();var dist=0;var step=(this._lastButton&2)?-1:1;step*=(this._deltaT*navi._vf.speed);var phi=2*Math.PI*this._deltaT*(this._pressX-this._lastX)/this._width;var theta=Math.PI*this._deltaT*(this._pressY-this._lastY)/this._height;if(this._needNavigationMatrixUpdate===true) {this._needNavigationMatrixUpdate=false;this._rotMat=x3dom.fields.SFMatrix4f.identity();this._transMat=x3dom.fields.SFMatrix4f.identity();this._movement=new x3dom.fields.SFVec3f(0,0,0);var angleX=0;var angleY=Math.asin(currViewMat._02);var C=Math.cos(angleY);if(Math.abs(C)>0.0001){angleX=Math.atan2(-currViewMat._12/C,currViewMat._22/C);} this._flyMat=currViewMat.inverse();this._from=this._flyMat.e3();this._at=this._from.subtract(this._flyMat.e2());if(navType==="helicopter") this._at.y=this._from.y;if(navType.substr(0,5)!=="looka") this._up=new x3dom.fields.SFVec3f(0,1,0);else this._up=this._flyMat.e1();this._pitch=angleX*180/Math.PI;this._yaw=angleY*180/Math.PI;this._eyePos=this._from.negate();} var tmpAt=null,tmpUp=null,tmpMat=null;var q,temp,fin;var lv,sv,up;if(navType==="game") {this._pitch+=this._dy;this._yaw+=this._dx;if(this._pitch>=89)this._pitch=89;if(this._pitch<=-89)this._pitch=-89;if(this._yaw>=360)this._yaw-=360;if(this._yaw<0)this._yaw=360+this._yaw;this._dx=0;this._dy=0;var xMat=x3dom.fields.SFMatrix4f.rotationX(this._pitch/180*Math.PI);var yMat=x3dom.fields.SFMatrix4f.rotationY(this._yaw/180*Math.PI);var fPos=x3dom.fields.SFMatrix4f.translation(this._eyePos);this._flyMat=xMat.mult(yMat).mult(fPos);var flyMat=this._flyMat.inverse();var tmpFrom=flyMat.e3();tmpUp=new x3dom.fields.SFVec3f(0,-1,0);tmpAt=tmpFrom.add(tmpUp);tmpUp=flyMat.e0().cross(tmpUp).normalize();tmpMat=x3dom.fields.SFMatrix4f.lookAt(tmpFrom,tmpAt,tmpUp);tmpMat=tmpMat.inverse();this._scene._nameSpace.doc.ctx.pickValue(this,this._width/2,this._height/2,this._lastButton,tmpMat,this.getProjectionMatrix().mult(tmpMat));if(this._pickingInfo.pickObj) {dist=this._pickingInfo.pickPos.subtract(tmpFrom).length();tmpFrom.y+=(avatarHeight-dist);flyMat.setTranslate(tmpFrom);this._eyePos=flyMat.e3().negate();this._flyMat=flyMat.inverse();this._pickingInfo.pickObj=null;} this._scene.getViewpoint().setView(this._flyMat);return needNavAnim;} else if(navType==="helicopter") {var typeParams=navi.getTypeParams();if(this._lastButton&2) {var stepUp=this._deltaT*this._deltaT*navi._vf.speed;stepUp*=0.1*(this._pressY-this._lastY)*Math.abs(this._pressY-this._lastY);typeParams[1]+=stepUp;navi.setTypeParams(typeParams);} if(this._lastButton&1){step*=0.01*(this._pressY-this._lastY)*Math.abs(this._pressY-this._lastY);} else{step=0;} theta=typeParams[0];this._from.y=typeParams[1];this._at.y=this._from.y;q=x3dom.fields.Quaternion.axisAngle(this._up,phi);temp=q.toMatrix();fin=x3dom.fields.SFMatrix4f.translation(this._from);fin=fin.mult(temp);temp=x3dom.fields.SFMatrix4f.translation(this._from.negate());fin=fin.mult(temp);this._at=fin.multMatrixPnt(this._at);lv=this._at.subtract(this._from).normalize();sv=lv.cross(this._up).normalize();up=sv.cross(lv).normalize();lv=lv.multiply(step);this._from=this._from.add(lv);this._at=this._at.add(lv);q=x3dom.fields.Quaternion.axisAngle(sv,theta);temp=q.toMatrix();fin=x3dom.fields.SFMatrix4f.translation(this._from);fin=fin.mult(temp);temp=x3dom.fields.SFMatrix4f.translation(this._from.negate());fin=fin.mult(temp);var at=fin.multMatrixPnt(this._at);this._flyMat=x3dom.fields.SFMatrix4f.lookAt(this._from,at,up);this._scene.getViewpoint().setView(this._flyMat.inverse());return needNavAnim;} q=x3dom.fields.Quaternion.axisAngle(this._up,phi);temp=q.toMatrix();fin=x3dom.fields.SFMatrix4f.translation(this._from);fin=fin.mult(temp);temp=x3dom.fields.SFMatrix4f.translation(this._from.negate());fin=fin.mult(temp);this._at=fin.multMatrixPnt(this._at);lv=this._at.subtract(this._from).normalize();sv=lv.cross(this._up).normalize();up=sv.cross(lv).normalize();q=x3dom.fields.Quaternion.axisAngle(sv,theta);temp=q.toMatrix();fin=x3dom.fields.SFMatrix4f.translation(this._from);fin=fin.mult(temp);temp=x3dom.fields.SFMatrix4f.translation(this._from.negate());fin=fin.mult(temp);this._at=fin.multMatrixPnt(this._at);if(navType.substr(0,5)!=="looka") {var currProjMat=this.getProjectionMatrix();if(navType!=="freefly"){if(step<0){tmpMat=new x3dom.fields.SFMatrix4f();tmpMat.setValue(this._last_mat_view.e0(),this._last_mat_view.e1(),this._last_mat_view.e2().negate(),this._last_mat_view.e3());this._scene._nameSpace.doc.ctx.pickValue(this,this._width/2,this._height/2,this._lastButton,tmpMat,currProjMat.mult(tmpMat));} else{this._scene._nameSpace.doc.ctx.pickValue(this,this._width/2,this._height/2,this._lastButton);} if(this._pickingInfo.pickObj) {dist=this._pickingInfo.pickPos.subtract(this._from).length();if(dist<=avatarRadius){step=0;}}} lv=this._at.subtract(this._from).normalize().multiply(step);this._at=this._at.add(lv);this._from=this._from.add(lv);if(navType==="walk") {tmpAt=this._from.addScaled(up,-1.0);tmpUp=sv.cross(up.negate()).normalize();tmpMat=x3dom.fields.SFMatrix4f.lookAt(this._from,tmpAt,tmpUp);tmpMat=tmpMat.inverse();this._scene._nameSpace.doc.ctx.pickValue(this,this._width/2,this._height/2,this._lastButton,tmpMat,currProjMat.mult(tmpMat));if(this._pickingInfo.pickObj) {dist=this._pickingInfo.pickPos.subtract(this._from).length();this._at=this._at.add(up.multiply(avatarHeight-dist));this._from=this._from.add(up.multiply(avatarHeight-dist));}} this._pickingInfo.pickObj=null;} this._flyMat=x3dom.fields.SFMatrix4f.lookAt(this._from,this._at,up);this._scene.getViewpoint().setView(this._flyMat.inverse());} return needNavAnim;};x3dom.Viewarea.prototype.moveFwd=function() {var navi=this._scene.getNavigationInfo();if(navi.getType()==="game") {var avatarRadius=0.25;var avatarHeight=1.6;if(navi._vf.avatarSize.length>2){avatarRadius=navi._vf.avatarSize[0];avatarHeight=navi._vf.avatarSize[1];} var speed=5*this._deltaT*navi._vf.speed;var yRotRad=(this._yaw/180*Math.PI);var xRotRad=(this._pitch/180*Math.PI);var dist=0;var fMat=this._flyMat.inverse();this._scene._nameSpace.doc.ctx.pickValue(this,this._width/2,this._height/2,this._lastButton);if(this._pickingInfo.pickObj) {dist=this._pickingInfo.pickPos.subtract(fMat.e3()).length();if(dist<=2*avatarRadius){} else{this._eyePos.x-=Math.sin(yRotRad)*speed;this._eyePos.z+=Math.cos(yRotRad)*speed;this._eyePos.y+=Math.sin(xRotRad)*speed;}}}};x3dom.Viewarea.prototype.moveBwd=function() {var navi=this._scene.getNavigationInfo();if(navi.getType()==="game") {var speed=5*this._deltaT*navi._vf.speed;var yRotRad=(this._yaw/180*Math.PI);var xRotRad=(this._pitch/180*Math.PI);this._eyePos.x+=Math.sin(yRotRad)*speed;this._eyePos.z-=Math.cos(yRotRad)*speed;this._eyePos.y-=Math.sin(xRotRad)*speed;}};x3dom.Viewarea.prototype.strafeRight=function() {var navi=this._scene.getNavigationInfo();if(navi.getType()==="game") {var speed=5*this._deltaT*navi._vf.speed;var yRotRad=(this._yaw/180*Math.PI);this._eyePos.x-=Math.cos(yRotRad)*speed;this._eyePos.z-=Math.sin(yRotRad)*speed;}};x3dom.Viewarea.prototype.strafeLeft=function() {var navi=this._scene.getNavigationInfo();if(navi.getType()==="game") {var speed=5*this._deltaT*navi._vf.speed;var yRotRad=(this._yaw/180*Math.PI);this._eyePos.x+=Math.cos(yRotRad)*speed;this._eyePos.z+=Math.sin(yRotRad)*speed;}};x3dom.Viewarea.prototype.animateTo=function(target,prev,dur) {var navi=this._scene.getNavigationInfo();if(x3dom.isa(target,x3dom.nodeTypes.X3DViewpointNode)){target=target.getViewMatrix().mult(target.getCurrentTransform().inverse());} if(navi._vf.transitionType[0].toLowerCase()!=="teleport"&&navi.getType()!=="game") {if(prev&&x3dom.isa(prev,x3dom.nodeTypes.X3DViewpointNode)){prev=prev.getViewMatrix().mult(prev.getCurrentTransform().inverse()).mult(this._transMat).mult(this._rotMat);this._mixer._beginTime=this._lastTS;if(arguments.length>=3){this._mixer._endTime=this._lastTS+dur;} else{this._mixer._endTime=this._lastTS+navi._vf.transitionTime;} this._mixer.setBeginMatrix(prev);this._mixer.setEndMatrix(target);this._scene.getViewpoint().setView(prev);} else{this._scene.getViewpoint().setView(target);}} else {this._scene.getViewpoint().setView(target);} this._rotMat=x3dom.fields.SFMatrix4f.identity();this._transMat=x3dom.fields.SFMatrix4f.identity();this._movement=new x3dom.fields.SFVec3f(0,0,0);this._needNavigationMatrixUpdate=true;};x3dom.Viewarea.prototype.getLights=function(){var enabledLights=[];for(var i=0;i0.0){return true;}} return false;};x3dom.Viewarea.prototype.updateSpecialNavigation=function(viewpoint,mat_viewpoint){var navi=this._scene.getNavigationInfo();var navType=navi.getType();if(navType=="helicopter"&&!navi._heliUpdated) {var typeParams=navi.getTypeParams();var theta=typeParams[0];var currViewMat=viewpoint.getViewMatrix().mult(mat_viewpoint.inverse()).inverse();this._from=currViewMat.e3();this._at=this._from.subtract(currViewMat.e2());this._up=new x3dom.fields.SFVec3f(0,1,0);this._from.y=typeParams[1];this._at.y=this._from.y;var sv=currViewMat.e0();var q=x3dom.fields.Quaternion.axisAngle(sv,theta);var temp=q.toMatrix();var fin=x3dom.fields.SFMatrix4f.translation(this._from);fin=fin.mult(temp);temp=x3dom.fields.SFMatrix4f.translation(this._from.negate());fin=fin.mult(temp);this._at=fin.multMatrixPnt(this._at);this._flyMat=x3dom.fields.SFMatrix4f.lookAt(this._from,this._at,this._up);this._scene.getViewpoint().setView(this._flyMat.inverse());navi._heliUpdated=true;}};x3dom.Viewarea.prototype.getViewpointMatrix=function() {var viewpoint=this._scene.getViewpoint();var mat_viewpoint=viewpoint.getCurrentTransform();this.updateSpecialNavigation(viewpoint,mat_viewpoint);return viewpoint.getViewMatrix().mult(mat_viewpoint.inverse());};x3dom.Viewarea.prototype.getViewMatrix=function() {return this.getViewpointMatrix().mult(this._transMat).mult(this._rotMat);};x3dom.Viewarea.prototype.getLightMatrix=function() {var lights=this._doc._nodeBag.lights;var i,n=lights.length;if(n>0) {var vol=this._scene.getVolume();if(vol.isValid()) {var min=x3dom.fields.SFVec3f.MAX();var max=x3dom.fields.SFVec3f.MIN();vol.getBounds(min,max);var l_arr=[];var viewpoint=this._scene.getViewpoint();var fov=viewpoint.getFieldOfView();var dia=max.subtract(min);var dist1=(dia.y/2.0)/Math.tan(fov/2.0)+(dia.z/2.0);var dist2=(dia.x/2.0)/Math.tan(fov/2.0)+(dia.z/2.0);dia=min.add(dia.multiply(0.5));for(i=0;idist2?dist1:dist2)));} l_arr[i]=lights[i].getViewMatrix(dia);} return l_arr;}} return[this.getViewMatrix()];};x3dom.Viewarea.prototype.getWCtoLCMatrix=function(lMat) {var proj=this.getProjectionMatrix();var view;if(arguments.length===0){view=this.getLightMatrix()[0];} else{view=lMat;} return proj.mult(view);};x3dom.Viewarea.prototype.getWCtoLCMatricesPointLight=function(view,lightNode,mat_proj) {var zNear=lightNode._vf.zNear;var zFar=lightNode._vf.zFar;var proj=this.getLightProjectionMatrix(view,zNear,zFar,false,mat_proj);proj._00=1;proj._11=1;var matrices=[];matrices[0]=proj.mult(view);var rotationMatrix;for(var i=1;i<=3;i++){rotationMatrix=x3dom.fields.SFMatrix4f.rotationY(i*Math.PI/2);matrices[i]=proj.mult(rotationMatrix.mult(view));} rotationMatrix=x3dom.fields.SFMatrix4f.rotationX(Math.PI/2);matrices[4]=proj.mult(rotationMatrix.mult(view));rotationMatrix=x3dom.fields.SFMatrix4f.rotationX(3*Math.PI/2);matrices[5]=proj.mult(rotationMatrix.mult(view));return matrices;};x3dom.Viewarea.prototype.getWCtoLCMatricesCascaded=function(view,lightNode,mat_proj) {var numCascades=Math.max(1,Math.min(lightNode._vf.shadowCascades,6));var splitFactor=Math.max(0,Math.min(lightNode._vf.shadowSplitFactor,1));var splitOffset=Math.max(0,Math.min(lightNode._vf.shadowSplitOffset,1));var isSpotLight=x3dom.isa(lightNode,x3dom.nodeTypes.SpotLight);var zNear=lightNode._vf.zNear;var zFar=lightNode._vf.zFar;var proj=this.getLightProjectionMatrix(view,zNear,zFar,true,mat_proj);if(isSpotLight){proj._00=1;proj._11=1;} var viewProj=proj.mult(view);var matrices=[];if(numCascades==1){matrices[0]=viewProj;return matrices;} var cascadeSplits=this.getShadowSplitDepths(numCascades,splitFactor,splitOffset,true,mat_proj);for(var i=0;i0||zFar>0){var lightPos=lMat.inverse().e3();var nearScale=0.8;var farScale=1.2;var min=x3dom.fields.SFVec3f.copy(this._scene._lastMin);var max=x3dom.fields.SFVec3f.copy(this._scene._lastMax);var dia=max.subtract(min);var sRad=dia.length()/2;var sCenter=min.add(dia.multiply(0.5));var vDist=(lightPos.subtract(sCenter)).length();var near,far;if(sRad){if(vDist>sRad) near=(vDist-sRad)*nearScale;else near=1;far=(vDist+sRad)*farScale;} if(zNear>0)near=zNear;if(zFar>0)far=zFar;proj._22=-(far+near)/(far-near);proj._23=-2.0*far*near/(far-near);return proj;} else{var cropMatrix=this.getLightCropMatrix(proj.mult(lMat));return cropMatrix.mult(proj);}};x3dom.Viewarea.prototype.getProjectionMatrix=function() {var viewpoint=this._scene.getViewpoint();return viewpoint.getProjectionMatrix(this._width/this._height);};x3dom.Viewarea.prototype.getViewfrustum=function(clipMat) {var env=this._scene.getEnvironment();if(env._vf.frustumCulling==true) {if(arguments.length==0){var proj=this.getProjectionMatrix();var view=this.getViewMatrix();return new x3dom.fields.FrustumVolume(proj.mult(view));} else{return new x3dom.fields.FrustumVolume(clipMat);}} return null;};x3dom.Viewarea.prototype.getWCtoCCMatrix=function() {var view=this.getViewMatrix();var proj=this.getProjectionMatrix();return proj.mult(view);};x3dom.Viewarea.prototype.getCCtoWCMatrix=function() {var mat=this.getWCtoCCMatrix();return mat.inverse();};x3dom.Viewarea.prototype.calcViewRay=function(x,y,mat) {var cctowc=mat?mat:this.getCCtoWCMatrix();var rx=x/(this._width-1.0)*2.0-1.0;var ry=(this._height-1.0-y)/(this._height-1.0)*2.0-1.0;var from=cctowc.multFullMatrixPnt(new x3dom.fields.SFVec3f(rx,ry,-1));var at=cctowc.multFullMatrixPnt(new x3dom.fields.SFVec3f(rx,ry,1));var dir=at.subtract(from);return new x3dom.fields.Ray(from,dir);};x3dom.Viewarea.prototype.showAll=function(axis) {if(axis===undefined) axis="negZ";var scene=this._scene;scene.updateVolume();var min=x3dom.fields.SFVec3f.copy(scene._lastMin);var max=x3dom.fields.SFVec3f.copy(scene._lastMax);var x="x",y="y",z="z";var sign=1;var to,from=new x3dom.fields.SFVec3f(0,0,-1);switch(axis){case"posX":sign=-1;case"negX":z="x";x="y";y="z";to=new x3dom.fields.SFVec3f(sign,0,0);break;case"posY":sign=-1;case"negY":z="y";x="z";y="x";to=new x3dom.fields.SFVec3f(0,sign,0);break;case"posZ":sign=-1;case"negZ":default:to=new x3dom.fields.SFVec3f(0,0,-sign);break;} var viewpoint=scene.getViewpoint();var fov=viewpoint.getFieldOfView();var dia=max.subtract(min);var diaz2=dia[z]/2.0,tanfov2=Math.tan(fov/2.0);var dist1=(dia[y]/2.0)/tanfov2+diaz2;var dist2=(dia[x]/2.0)/tanfov2+diaz2;dia=min.add(dia.multiply(0.5));dia[z]+=sign*(dist1>dist2?dist1:dist2)*1.01;var quat=x3dom.fields.Quaternion.rotateFromTo(from,to);var viewmat=quat.toMatrix();viewmat=viewmat.mult(x3dom.fields.SFMatrix4f.translation(dia.negate()));this.animateTo(viewmat,viewpoint);};x3dom.Viewarea.prototype.fit=function(min,max,updateCenterOfRotation) {if(updateCenterOfRotation===undefined){updateCenterOfRotation=true;} var dia2=max.subtract(min).multiply(0.5);var center=min.add(dia2);var bsr=dia2.length();var viewpoint=this._scene.getViewpoint();var fov=viewpoint.getFieldOfView();var viewmat=x3dom.fields.SFMatrix4f.copy(this.getViewMatrix());var rightDir=new x3dom.fields.SFVec3f(viewmat._00,viewmat._01,viewmat._02);var upDir=new x3dom.fields.SFVec3f(viewmat._10,viewmat._11,viewmat._12);var viewDir=new x3dom.fields.SFVec3f(viewmat._20,viewmat._21,viewmat._22);var tanfov2=Math.tan(fov/2.0);var dist=bsr/tanfov2;var eyePos=center.add(viewDir.multiply(dist));viewmat._03=-rightDir.dot(eyePos);viewmat._13=-upDir.dot(eyePos);viewmat._23=-viewDir.dot(eyePos);if(updateCenterOfRotation){viewpoint.setCenterOfRotation(center);} if(x3dom.isa(viewpoint,x3dom.nodeTypes.OrthoViewpoint)) {viewpoint._vf.fieldOfView[0]=-dist;viewpoint._vf.fieldOfView[1]=-dist;viewpoint._vf.fieldOfView[2]=dist;viewpoint._vf.fieldOfView[3]=dist;viewpoint._projMatrix=null;this.animateTo(viewmat,viewpoint,0);} else {this.animateTo(viewmat,viewpoint);}};x3dom.Viewarea.prototype.resetView=function() {var navi=this._scene.getNavigationInfo();if(navi._vf.transitionType[0].toLowerCase()!=="teleport"&&navi.getType()!=="game") {this._mixer._beginTime=this._lastTS;this._mixer._endTime=this._lastTS+navi._vf.transitionTime;this._mixer.setBeginMatrix(this.getViewMatrix());var target=this._scene.getViewpoint();target.resetView();target=target.getViewMatrix().mult(target.getCurrentTransform().inverse());this._mixer.setEndMatrix(target);} else {this._scene.getViewpoint().resetView();} this.resetNavHelpers();navi._heliUpdated=false;};x3dom.Viewarea.prototype.resetNavHelpers=function() {this._rotMat=x3dom.fields.SFMatrix4f.identity();this._transMat=x3dom.fields.SFMatrix4f.identity();this._movement=new x3dom.fields.SFVec3f(0,0,0);this._needNavigationMatrixUpdate=true;};x3dom.Viewarea.prototype.uprightView=function() {var mat=this.getViewMatrix().inverse();var from=mat.e3();var at=from.subtract(mat.e2());var up=new x3dom.fields.SFVec3f(0,1,0);var s=mat.e2().cross(up).normalize();var v=s.cross(up).normalize();at=from.add(v);mat=x3dom.fields.SFMatrix4f.lookAt(from,at,up);mat=mat.inverse();this.animateTo(mat,this._scene.getViewpoint());};x3dom.Viewarea.prototype.callEvtHandler=function(node,eventType,event) {if(!node||!node._xmlNode) return null;try{var attrib=node._xmlNode[eventType];if(typeof(attrib)==="function"){attrib.call(node._xmlNode,event);} else{var funcStr=node._xmlNode.getAttribute(eventType);var func=new Function('event',funcStr);func.call(node._xmlNode,event);} var list=node._listeners[event.type];if(list){for(var it=0;it0) {if(event.type=='mousedown') {for(i=0;i=0)&&navType==="lookat"&&this._pressX===x&&this._pressY===y) {var step=(this._lastButton&2)?-1:1;var dist=this._pickingInfo.pickPos.subtract(this._from).length()/tDist;var laMat=new x3dom.fields.SFMatrix4f();laMat.setValues(this.getViewMatrix());laMat=laMat.inverse();var from=laMat.e3();var at=from.subtract(laMat.e2());var up=laMat.e1();dir=this._pickingInfo.pickPos.subtract(from);var len=dir.length();dir=dir.normalize();var newAt=from.addScaled(dir,len);var s=dir.cross(up).normalize();dir=s.cross(up).normalize();if(step<0){dist=(0.5+len+dist)*2;} var newFrom=newAt.addScaled(dir,dist);laMat=x3dom.fields.SFMatrix4f.lookAt(newFrom,newAt,up);laMat=laMat.inverse();dist=newFrom.subtract(from).length();var dur=Math.max(0.5,Math.log((1+dist)/navi._vf.speed));this.animateTo(laMat,this._scene.getViewpoint(),dur);} this._dx=0;this._dy=0;this._lastX=x;this._lastY=y;this._lastButton=buttonState;this._isMoving=false;};x3dom.Viewarea.prototype.onMouseOver=function(x,y,buttonState) {this._dx=0;this._dy=0;this._lastButton=0;this._isMoving=false;this._lastX=x;this._lastY=y;this._deltaT=0;};x3dom.Viewarea.prototype.onMouseOut=function(x,y,buttonState) {this._dx=0;this._dy=0;this._lastButton=0;this._isMoving=false;this._lastX=x;this._lastY=y;this._deltaT=0;};x3dom.Viewarea.prototype.onDoubleClick=function(x,y) {if(this._doc.properties.getProperty('disableDoubleClick','false')==='true'){return;} var navi=this._scene.getNavigationInfo();if(navi.getType()=="none"){return;} var pickMode=this._scene._vf.pickMode.toLowerCase();if((pickMode=="color"||pickMode=="texcoord")){return;} var viewpoint=this._scene.getViewpoint();viewpoint.setCenterOfRotation(this._pick);x3dom.debug.logInfo("New center of Rotation: "+this._pick);var mat=this.getViewMatrix().inverse();var from=mat.e3();var at=this._pick;var up=mat.e1();var norm=mat.e0().cross(up).normalize();var dist=norm.dot(this._pick.subtract(from));from=at.addScaled(norm,-dist);mat=x3dom.fields.SFMatrix4f.lookAt(from,at,up);x3dom.debug.logInfo("New camera position: "+from);this.animateTo(mat.inverse(),viewpoint);};x3dom.Viewarea.prototype.handleMoveEvt=function(x,y,buttonState) {if(buttonState==0) {this._doc._nodeBag.affectedPointingSensors=[];} this.prepareEvents(x,y,buttonState,"onmousemove");if(this._pickingInfo.pickObj!==this._pickingInfo.lastObj) {if(this._pickingInfo.lastObj){var obj=this._pickingInfo.pickObj;this._pickingInfo.pickObj=this._pickingInfo.lastObj;this.prepareEvents(x,y,buttonState,"onmouseout");this._pickingInfo.pickObj=obj;} if(this._pickingInfo.pickObj){this.prepareEvents(x,y,buttonState,"onmouseover");} this._pickingInfo.lastObj=this._pickingInfo.pickObj;}};x3dom.Viewarea.prototype.onMove=function(x,y,buttonState) {this.handleMoveEvt(x,y,buttonState);if(this._lastX<0||this._lastY<0){this._lastX=x;this._lastY=y;} this._dx=x-this._lastX;this._dy=y-this._lastY;this._lastX=x;this._lastY=y;};x3dom.Viewarea.prototype.onMoveView=function(translation,rotation) {if(this._currentInputType==x3dom.InputTypes.NAVIGATION) {var navi=this._scene.getNavigationInfo();var viewpoint=this._scene.getViewpoint();if(navi.getType()==="examine") {if(translation) {var distance=(this._scene._lastMax.subtract(this._scene._lastMin)).length();distance=((distance=5&&navi._vf.typeParams[4]!=0) {var newDist=Math.min(zoomAmount,lastDirL-0.01);this._from=this._from.addScaled(lastDir,newDist);} else {var diff=zoomAmount-lastDirL+0.01;if(diff>=0){cor=cor.addScaled(lastDir,diff);viewpoint.setCenterOfRotation(cor);} this._from=this._from.addScaled(lastDir,zoomAmount);} this._from=this._from.addScaled(lastDir,zoomAmount);this._flyMat=x3dom.fields.SFMatrix4f.lookAt(this._from,cor,this._up);viewpoint.setView(this._flyMat.inverse());} else if(buttonState&4) {d=(this._scene._lastMax.subtract(this._scene._lastMin)).length();d=((d0) {this._currentInputType=x3dom.InputTypes.INTERACTION;} else {this._currentInputType=x3dom.InputTypes.NAVIGATION;}};x3dom.Viewarea.prototype.getRenderMode=function() {return this._points;};x3dom.Viewarea.prototype.getShadowedLights=function() {var shadowedLights=[];var shadowIndex=0;var slights=this.getLights();for(var i=0;i0.0){shadowedLights[shadowIndex]=slights[i];shadowIndex++;}} return shadowedLights;};x3dom.Viewarea.prototype.getShadowSplitDepths=function(numCascades,splitFactor,splitOffset,postProject,mat_proj) {var logSplit;var practSplit=[];var viewPoint=this._scene.getViewpoint();var zNear=viewPoint.getNear();var zFar=viewPoint.getFar();practSplit[0]=zNear;zNear=zNear+splitOffset*(zFar-zNear)/10;for(var i=1;i1.0||xMax<-1.0){xMin=-1.0;xMax=1.0;}else{xMin=Math.max(xMin,-1.0);xMax=Math.min(xMax,1.0);} if(yMin>1.0||yMax<-1.0){yMin=-1.0;yMax=1.0;}else{yMin=Math.max(yMin,-1.0);yMax=Math.min(yMax,1.0);} if(zMin>1.0||zMax<-1.0){zMin=-1.0;zMax=1.0;}else{zMin=Math.max(zMin,-1.0);zMax=Math.min(zMax,1.0);} var minValues=new x3dom.fields.SFVec3f(xMin,yMin,zMin);var maxValues=new x3dom.fields.SFVec3f(xMax,yMax,zMax);return new x3dom.fields.BoxVolume(minValues,maxValues);} var frustumBB=clip(minFrustum,maxFrustum);var scaleX=2.0/(frustumBB.max.x-frustumBB.min.x);var scaleY=2.0/(frustumBB.max.y-frustumBB.min.y);var offsetX=-(scaleX*(frustumBB.max.x+frustumBB.min.x))/2.0;var offsetY=-(scaleY*(frustumBB.max.y+frustumBB.min.y))/2.0;var fittingMatrix=x3dom.fields.SFMatrix4f.identity();fittingMatrix._00=scaleX;fittingMatrix._11=scaleY;fittingMatrix._03=offsetX;fittingMatrix._13=offsetY;return fittingMatrix;};x3dom.Mesh=function(parent) {this._parent=parent;this._vol=new x3dom.fields.BoxVolume();this._invalidate=true;this._numFaces=0;this._numCoords=0;this._primType='TRIANGLES';this._positions=[];this._normals=[];this._texCoords=[];this._colors=[];this._indices=[];this._positions[0]=[];this._normals[0]=[];this._texCoords[0]=[];this._colors[0]=[];this._indices[0]=[];};x3dom.Mesh.prototype._dynamicFields={};x3dom.Mesh.prototype._numPosComponents=3;x3dom.Mesh.prototype._numTexComponents=2;x3dom.Mesh.prototype._numColComponents=3;x3dom.Mesh.prototype._numNormComponents=3;x3dom.Mesh.prototype._lit=true;x3dom.Mesh.prototype._vol=null;x3dom.Mesh.prototype._invalidate=true;x3dom.Mesh.prototype._numFaces=0;x3dom.Mesh.prototype._numCoords=0;x3dom.Mesh.prototype.setMeshData=function(positions,normals,texCoords,colors,indices) {this._positions[0]=positions;this._normals[0]=normals;this._texCoords[0]=texCoords;this._colors[0]=colors;this._indices[0]=indices;this._invalidate=true;this._numFaces=this._indices[0].length/3;this._numCoords=this._positions[0].length/3;};x3dom.Mesh.prototype.getVolume=function() {if(this._invalidate==true&&!this._vol.isValid()) {var coords=this._positions[0];var n=coords.length;if(n>3) {var initVal=new x3dom.fields.SFVec3f(coords[0],coords[1],coords[2]);this._vol.setBounds(initVal,initVal);for(var i=3;icoords[i]){this._vol.min.x=coords[i];} if(this._vol.min.y>coords[i+1]){this._vol.min.y=coords[i+1];} if(this._vol.min.z>coords[i+2]){this._vol.min.z=coords[i+2];} if(this._vol.max.xm)?this._posSize/3:m/3;num=3*((num-Math.floor(num)>0)?Math.floor(num+1):num);for(i=0;ix3dom.fields.Eps) {for(i=0;i=0);if(k){this._indices[i]=indices.slice(i*MAX,(i+1)*MAX);}else{this._indices[i]=indices.slice(i*MAX);} if(!isMultiInd){if(i){var m=i*MAX;for(var j=0,l=this._indices[i].length;j++i*MAX*3);};x3dom.Mesh.prototype.calcTexCoords=function(mode) {this._texCoords[0]=[];if(mode.toLowerCase()==="sphere-local") {for(var i=0,j=0,n=this._normals[0].length;i=dia.y) {if(dia.x>=dia.z) {S=0;T=dia.y>=dia.z?1:2;} else {S=2;T=0;}} else {if(dia.y>=dia.z) {S=1;T=dia.x>=dia.z?0:2;} else {S=2;T=1;}} var sDenom=1,tDenom=1;var sMin=0,tMin=0;switch(S){case 0:sDenom=dia.x;sMin=min.x;break;case 1:sDenom=dia.y;sMin=min.y;break;case 2:sDenom=dia.z;sMin=min.z;break;} switch(T){case 0:tDenom=dia.x;tMin=min.x;break;case 1:tDenom=dia.y;tMin=min.y;break;case 2:tDenom=dia.z;tMin=min.z;break;} for(var k=0,l=0,m=this._positions[0].length;k=16) {if(!needTranspose){return new x3dom.fields.SFMatrix4f(arr[0],arr[1],arr[2],arr[3],arr[4],arr[5],arr[6],arr[7],arr[8],arr[9],arr[10],arr[11],arr[12],arr[13],arr[14],arr[15]);} else{return new x3dom.fields.SFMatrix4f(arr[0],arr[4],arr[8],arr[12],arr[1],arr[5],arr[9],arr[13],arr[2],arr[6],arr[10],arr[14],arr[3],arr[7],arr[11],arr[15]);}} else if(arr.length===6){return new x3dom.fields.SFMatrix4f(arr[0],arr[1],0,arr[4],arr[2],arr[3],0,arr[5],0,0,1,0,0,0,0,1);} else{x3dom.debug.logWarning("SFMatrix4f - can't parse string: "+str);return x3dom.fields.SFMatrix4f.identity();}};x3dom.fields.SFMatrix4f.prototype.mult=function(that){return new x3dom.fields.SFMatrix4f(this._00*that._00+this._01*that._10+this._02*that._20+this._03*that._30,this._00*that._01+this._01*that._11+this._02*that._21+this._03*that._31,this._00*that._02+this._01*that._12+this._02*that._22+this._03*that._32,this._00*that._03+this._01*that._13+this._02*that._23+this._03*that._33,this._10*that._00+this._11*that._10+this._12*that._20+this._13*that._30,this._10*that._01+this._11*that._11+this._12*that._21+this._13*that._31,this._10*that._02+this._11*that._12+this._12*that._22+this._13*that._32,this._10*that._03+this._11*that._13+this._12*that._23+this._13*that._33,this._20*that._00+this._21*that._10+this._22*that._20+this._23*that._30,this._20*that._01+this._21*that._11+this._22*that._21+this._23*that._31,this._20*that._02+this._21*that._12+this._22*that._22+this._23*that._32,this._20*that._03+this._21*that._13+this._22*that._23+this._23*that._33,this._30*that._00+this._31*that._10+this._32*that._20+this._33*that._30,this._30*that._01+this._31*that._11+this._32*that._21+this._33*that._31,this._30*that._02+this._31*that._12+this._32*that._22+this._33*that._32,this._30*that._03+this._31*that._13+this._32*that._23+this._33*that._33);};x3dom.fields.SFMatrix4f.prototype.multMatrixPnt=function(vec){return new x3dom.fields.SFVec3f(this._00*vec.x+this._01*vec.y+this._02*vec.z+this._03,this._10*vec.x+this._11*vec.y+this._12*vec.z+this._13,this._20*vec.x+this._21*vec.y+this._22*vec.z+this._23);};x3dom.fields.SFMatrix4f.prototype.multMatrixVec=function(vec){return new x3dom.fields.SFVec3f(this._00*vec.x+this._01*vec.y+this._02*vec.z,this._10*vec.x+this._11*vec.y+this._12*vec.z,this._20*vec.x+this._21*vec.y+this._22*vec.z);};x3dom.fields.SFMatrix4f.prototype.multFullMatrixPnt=function(vec){var w=this._30*vec.x+this._31*vec.y+this._32*vec.z+this._33;if(w){w=1.0/w;} return new x3dom.fields.SFVec3f((this._00*vec.x+this._01*vec.y+this._02*vec.z+this._03)*w,(this._10*vec.x+this._11*vec.y+this._12*vec.z+this._13)*w,(this._20*vec.x+this._21*vec.y+this._22*vec.z+this._23)*w);};x3dom.fields.SFMatrix4f.prototype.transpose=function(){return new x3dom.fields.SFMatrix4f(this._00,this._10,this._20,this._30,this._01,this._11,this._21,this._31,this._02,this._12,this._22,this._32,this._03,this._13,this._23,this._33);};x3dom.fields.SFMatrix4f.prototype.negate=function(){return new x3dom.fields.SFMatrix4f(-this._00,-this._01,-this._02,-this._03,-this._10,-this._11,-this._12,-this._13,-this._20,-this._21,-this._22,-this._23,-this._30,-this._31,-this._32,-this._33);};x3dom.fields.SFMatrix4f.prototype.multiply=function(s){return new x3dom.fields.SFMatrix4f(s*this._00,s*this._01,s*this._02,s*this._03,s*this._10,s*this._11,s*this._12,s*this._13,s*this._20,s*this._21,s*this._22,s*this._23,s*this._30,s*this._31,s*this._32,s*this._33);};x3dom.fields.SFMatrix4f.prototype.add=function(that){return new x3dom.fields.SFMatrix4f(this._00+that._00,this._01+that._01,this._02+that._02,this._03+that._03,this._10+that._10,this._11+that._11,this._12+that._12,this._13+that._13,this._20+that._20,this._21+that._21,this._22+that._22,this._23+that._23,this._30+that._30,this._31+that._31,this._32+that._32,this._33+that._33);};x3dom.fields.SFMatrix4f.prototype.addScaled=function(that,s){return new x3dom.fields.SFMatrix4f(this._00+s*that._00,this._01+s*that._01,this._02+s*that._02,this._03+s*that._03,this._10+s*that._10,this._11+s*that._11,this._12+s*that._12,this._13+s*that._13,this._20+s*that._20,this._21+s*that._21,this._22+s*that._22,this._23+s*that._23,this._30+s*that._30,this._31+s*that._31,this._32+s*that._32,this._33+s*that._33);};x3dom.fields.SFMatrix4f.prototype.setValues=function(that){this._00=that._00;this._01=that._01;this._02=that._02;this._03=that._03;this._10=that._10;this._11=that._11;this._12=that._12;this._13=that._13;this._20=that._20;this._21=that._21;this._22=that._22;this._23=that._23;this._30=that._30;this._31=that._31;this._32=that._32;this._33=that._33;};x3dom.fields.SFMatrix4f.prototype.setValue=function(v1,v2,v3,v4){this._00=v1.x;this._01=v2.x;this._02=v3.x;this._10=v1.y;this._11=v2.y;this._12=v3.y;this._20=v1.z;this._21=v2.z;this._22=v3.z;this._30=0;this._31=0;this._32=0;if(arguments.length>3){this._03=v4.x;this._13=v4.y;this._23=v4.z;this._33=1;}};x3dom.fields.SFMatrix4f.prototype.setFromArray=function(a){this._00=a[0];this._01=a[4];this._02=a[8];this._03=a[12];this._10=a[1];this._11=a[5];this._12=a[9];this._13=a[13];this._20=a[2];this._21=a[6];this._22=a[10];this._23=a[14];this._30=a[3];this._31=a[7];this._32=a[11];this._33=a[15];};x3dom.fields.SFMatrix4f.prototype.toGL=function(){return[this._00,this._10,this._20,this._30,this._01,this._11,this._21,this._31,this._02,this._12,this._22,this._32,this._03,this._13,this._23,this._33];};x3dom.fields.SFMatrix4f.prototype.at=function(i,j){var field="_"+i+j;return this[field];};x3dom.fields.SFMatrix4f.prototype.sqrt=function(){var Y=x3dom.fields.SFMatrix4f.identity();var result=x3dom.fields.SFMatrix4f.copy(this);for(var i=0;i<6;i++) {var iX=result.inverse();var iY=(i==0)?x3dom.fields.SFMatrix4f.identity():Y.inverse();var rd=result.det(),yd=Y.det();var g=Math.abs(Math.pow(rd*yd,-0.125));var ig=1.0/g;result=result.multiply(g);result=result.addScaled(iY,ig);result=result.multiply(0.5);Y=Y.multiply(g);Y=Y.addScaled(iX,ig);Y=Y.multiply(0.5);} return result;};x3dom.fields.SFMatrix4f.prototype.normInfinity=function(){var t=0,m=0;if((t=Math.abs(this._00))>m){m=t;} if((t=Math.abs(this._01))>m){m=t;} if((t=Math.abs(this._02))>m){m=t;} if((t=Math.abs(this._03))>m){m=t;} if((t=Math.abs(this._10))>m){m=t;} if((t=Math.abs(this._11))>m){m=t;} if((t=Math.abs(this._12))>m){m=t;} if((t=Math.abs(this._13))>m){m=t;} if((t=Math.abs(this._20))>m){m=t;} if((t=Math.abs(this._21))>m){m=t;} if((t=Math.abs(this._22))>m){m=t;} if((t=Math.abs(this._23))>m){m=t;} if((t=Math.abs(this._30))>m){m=t;} if((t=Math.abs(this._31))>m){m=t;} if((t=Math.abs(this._32))>m){m=t;} if((t=Math.abs(this._33))>m){m=t;} return m;};x3dom.fields.SFMatrix4f.prototype.norm1_3x3=function(){var max=Math.abs(this._00)+ Math.abs(this._10)+ Math.abs(this._20);var t=0;if((t=Math.abs(this._01)+ Math.abs(this._11)+ Math.abs(this._21))>max){max=t;} if((t=Math.abs(this._02)+ Math.abs(this._12)+ Math.abs(this._22))>max){max=t;} return max;};x3dom.fields.SFMatrix4f.prototype.normInf_3x3=function(){var max=Math.abs(this._00)+ Math.abs(this._01)+ Math.abs(this._02);var t=0;if((t=Math.abs(this._10)+ Math.abs(this._11)+ Math.abs(this._12))>max){max=t;} if((t=Math.abs(this._20)+ Math.abs(this._21)+ Math.abs(this._22))>max){max=t;} return max;};x3dom.fields.SFMatrix4f.prototype.adjointT_3x3=function(){var result=x3dom.fields.SFMatrix4f.identity();result._00=this._11*this._22-this._12*this._21;result._01=this._12*this._20-this._10*this._22;result._02=this._10*this._21-this._11*this._20;result._10=this._21*this._02-this._22*this._01;result._11=this._22*this._00-this._20*this._02;result._12=this._20*this._01-this._21*this._00;result._20=this._01*this._12-this._02*this._11;result._21=this._02*this._10-this._00*this._12;result._22=this._00*this._11-this._01*this._10;return result;};x3dom.fields.SFMatrix4f.prototype.equals=function(that){var eps=0.000000000001;return Math.abs(this._00-that._00)4){m=x3dom.fields.SFMatrix4f.translation(center.negate());m=m.mult(this);var c=x3dom.fields.SFMatrix4f.translation(center);m=m.mult(c);} else{m=x3dom.fields.SFMatrix4f.copy(this);} var flip=m.decompose(translation,rotation,scaleFactor,scaleOrientation);scaleFactor.setValues(scaleFactor.multiply(flip));};x3dom.fields.SFMatrix4f.prototype.decompose=function(t,r,s,so) {var A=x3dom.fields.SFMatrix4f.copy(this);var Q=x3dom.fields.SFMatrix4f.identity(),S=x3dom.fields.SFMatrix4f.identity(),SO=x3dom.fields.SFMatrix4f.identity();t.x=A._03;t.y=A._13;t.z=A._23;A._03=0.0;A._13=0.0;A._23=0.0;A._30=0.0;A._31=0.0;A._32=0.0;var det=A.polarDecompose(Q,S);var f=1.0;if(det<0.0){Q=Q.negate();f=-1.0;} r.setValue(Q);S.spectralDecompose(SO,s);so.setValue(SO);return f;};x3dom.fields.SFMatrix4f.prototype.polarDecompose=function(Q,S) {var TOL=0.000000000001;var Mk=this.transpose();var Ek=x3dom.fields.SFMatrix4f.identity();var Mk_one=Mk.norm1_3x3();var Mk_inf=Mk.normInf_3x3();var MkAdjT;var MkAdjT_one,MkAdjT_inf;var Ek_one,Mk_det;do {MkAdjT=Mk.adjointT_3x3();Mk_det=Mk._00*MkAdjT._00+ Mk._01*MkAdjT._01+ Mk._02*MkAdjT._02;if(Mk_det==0.0) {x3dom.debug.logWarning("polarDecompose: Mk_det == 0.0");break;} MkAdjT_one=MkAdjT.norm1_3x3();MkAdjT_inf=MkAdjT.normInf_3x3();var gamma=Math.sqrt(Math.sqrt((MkAdjT_one*MkAdjT_inf)/(Mk_one*Mk_inf))/Math.abs(Mk_det));var g1=0.5*gamma;var g2=0.5/(gamma*Mk_det);Ek.setValues(Mk);Mk=Mk.multiply(g1);Mk=Mk.addScaled(MkAdjT,g2);Ek=Ek.addScaled(Mk,-1.0);Ek_one=Ek.norm1_3x3();Mk_one=Mk.norm1_3x3();Mk_inf=Mk.normInf_3x3();}while(Ek_one>(Mk_one*TOL));Q.setValues(Mk.transpose());S.setValues(Mk.mult(this));for(var i=0;i<3;++i) {for(var j=i;j<3;++j) {S['_'+j+i]=0.5*(S['_'+j+i]+S['_'+i+j]);S['_'+i+j]=0.5*(S['_'+j+i]+S['_'+i+j]);}} return Mk_det;};x3dom.fields.SFMatrix4f.prototype.spectralDecompose=function(SO,k) {var next=[1,2,0];var maxIterations=20;var diag=[this._00,this._11,this._22];var offDiag=[this._12,this._20,this._01];for(var iter=0;iter=0;--i) {var p=next[i];var q=next[p];var absOffDiag=Math.abs(offDiag[i]);var g=100.0*absOffDiag;if(absOffDiag>0.0) {var t=0,h=diag[q]-diag[p];var absh=Math.abs(h);if(absh+g==absh) {t=offDiag[i]/h;} else {var theta=0.5*h/offDiag[i];t=1.0/(Math.abs(theta)+Math.sqrt(theta*theta+1.0));t=theta<0.0?-t:t;} var c=1.0/Math.sqrt(t*t+1.0);var s=t*c;var tau=s/(c+1.0);var ta=t*offDiag[i];offDiag[i]=0.0;diag[p]-=ta;diag[q]+=ta;var offDiagq=offDiag[q];offDiag[q]-=s*(offDiag[p]+tau*offDiagq);offDiag[p]+=s*(offDiagq-tau*offDiag[p]);for(var j=2;j>=0;--j) {var a=SO['_'+j+p];var b=SO['_'+j+q];SO['_'+j+p]-=s*(b+tau*a);SO['_'+j+q]+=s*(a-tau*b);}}}} k.x=diag[0];k.y=diag[1];k.z=diag[2];};x3dom.fields.SFMatrix4f.prototype.log=function(){var maxiter=12;var eps=1e-12;var A=x3dom.fields.SFMatrix4f.copy(this),Z=x3dom.fields.SFMatrix4f.copy(this);Z._00-=1;Z._11-=1;Z._22-=1;Z._33-=1;var k=0;while(Z.normInfinity()>0.5) {A=A.sqrt();Z.setValues(A);Z._00-=1;Z._11-=1;Z._22-=1;Z._33-=1;k++;} A._00-=1;A._11-=1;A._22-=1;A._33-=1;A=A.negate();Z.setValues(A);var result=x3dom.fields.SFMatrix4f.copy(A);var i=1;while(Z.normInfinity()>eps&&i=16) {if(!needTranspose){this._00=arr[0];this._01=arr[1];this._02=arr[2];this._03=arr[3];this._10=arr[4];this._11=arr[5];this._12=arr[6];this._13=arr[7];this._20=arr[8];this._21=arr[9];this._22=arr[10];this._23=arr[11];this._30=arr[12];this._31=arr[13];this._32=arr[14];this._33=arr[15];} else{this._00=arr[0];this._01=arr[4];this._02=arr[8];this._03=arr[12];this._10=arr[1];this._11=arr[5];this._12=arr[9];this._13=arr[13];this._20=arr[2];this._21=arr[6];this._22=arr[10];this._23=arr[14];this._30=arr[3];this._31=arr[7];this._32=arr[11];this._33=arr[15];}} else if(arr.length===6){this._00=arr[0];this._01=arr[1];this._02=0;this._03=arr[4];this._10=arr[2];this._11=arr[3];this._12=0;this._13=arr[5];this._20=0;this._21=0;this._22=1;this._23=0;this._30=0;this._31=0;this._32=0;this._33=1;} else{x3dom.debug.logWarning("SFMatrix4f - can't parse string: "+str);} return this;};x3dom.fields.SFVec2f=function(x,y){if(arguments.length===0){this.x=0;this.y=0;} else{this.x=x;this.y=y;}};x3dom.fields.SFVec2f.copy=function(v){return new x3dom.fields.SFVec2f(v.x,v.y);};x3dom.fields.SFVec2f.parse=function(str){var m=/^\s*([+\-]?\d*\.*\d*[eE]?[+\-]?\d*?)\s*,?\s*([+\-]?\d*\.*\d*[eE]?[+\-]?\d*?)\s*$/.exec(str);return new x3dom.fields.SFVec2f(+m[1],+m[2]);};x3dom.fields.SFVec2f.prototype.copy=function(){return x3dom.fields.SFVec2f.copy(this);};x3dom.fields.SFVec2f.prototype.setValues=function(that){this.x=that.x;this.y=that.y;};x3dom.fields.SFVec2f.prototype.at=function(i){switch(i){case 0:return this.x;case 1:return this.y;default:return this.x;}};x3dom.fields.SFVec2f.prototype.add=function(that){return new x3dom.fields.SFVec2f(this.x+that.x,this.y+that.y);};x3dom.fields.SFVec2f.prototype.subtract=function(that){return new x3dom.fields.SFVec2f(this.x-that.x,this.y-that.y);};x3dom.fields.SFVec2f.prototype.negate=function(){return new x3dom.fields.SFVec2f(-this.x,-this.y);};x3dom.fields.SFVec2f.prototype.dot=function(that){return this.x*that.x+this.y*that.y;};x3dom.fields.SFVec2f.prototype.reflect=function(n){var d2=this.dot(n)*2;return new x3dom.fields.SFVec2f(this.x-d2*n.x,this.y-d2*n.y);};x3dom.fields.SFVec2f.prototype.normalize=function(){var n=this.length();if(n){n=1.0/n;} return new x3dom.fields.SFVec2f(this.x*n,this.y*n);};x3dom.fields.SFVec2f.prototype.multComponents=function(that){return new x3dom.fields.SFVec2f(this.x*that.x,this.y*that.y);};x3dom.fields.SFVec2f.prototype.multiply=function(n){return new x3dom.fields.SFVec2f(this.x*n,this.y*n);};x3dom.fields.SFVec2f.prototype.divide=function(n){var denom=n?(1.0/n):1.0;return new x3dom.fields.SFVec2f(this.x*denom,this.y*denom);};x3dom.fields.SFVec2f.prototype.equals=function(that,eps){return Math.abs(this.x-that.x)x3dom.fields.Eps) {var s=Math.sin(a/2)/t;var c=Math.cos(a/2);return new x3dom.fields.Quaternion(axis.x*s,axis.y*s,axis.z*s,c);} else {return new x3dom.fields.Quaternion(0,0,0,1);}};x3dom.fields.Quaternion.prototype.copy=function(){return x3dom.fields.Quaternion(this);};x3dom.fields.Quaternion.prototype.toMatrix=function(){var xx=this.x*this.x;var xy=this.x*this.y;var xz=this.x*this.z;var yy=this.y*this.y;var yz=this.y*this.z;var zz=this.z*this.z;var wx=this.w*this.x;var wy=this.w*this.y;var wz=this.w*this.z;return new x3dom.fields.SFMatrix4f(1-2*(yy+zz),2*(xy-wz),2*(xz+wy),0,2*(xy+wz),1-2*(xx+zz),2*(yz-wx),0,2*(xz-wy),2*(yz+wx),1-2*(xx+yy),0,0,0,0,1);};x3dom.fields.Quaternion.prototype.toAxisAngle=function() {var x=0,y=0,z=0;var s=0,a=0;var that=this;if(this.w>1) {that=x3dom.fields.Quaternion.normalize(this);} a=2*Math.acos(that.w);s=Math.sqrt(1-that.w*that.w);if(s==0) {x=that.x;y=that.y;z=that.z;} else {x=that.x/s;y=that.y/s;z=that.z/s;} return[new x3dom.fields.SFVec3f(x,y,z),a];};x3dom.fields.Quaternion.prototype.angle=function() {return 2*Math.acos(this.w);};x3dom.fields.Quaternion.prototype.setValue=function(matrix) {var tr,s=1;var qt=[0,0,0];var i=0,j=0,k=0;var nxt=[1,2,0];tr=matrix._00+matrix._11+matrix._22;if(tr>0.0) {s=Math.sqrt(tr+1.0);this.w=s*0.5;s=0.5/s;this.x=(matrix._21-matrix._12)*s;this.y=(matrix._02-matrix._20)*s;this.z=(matrix._10-matrix._01)*s;} else {if(matrix._11>matrix._00){i=1;} else{i=0;} if(matrix._22>matrix.at(i,i)){i=2;} j=nxt[i];k=nxt[j];s=Math.sqrt(matrix.at(i,i)-(matrix.at(j,j)+matrix.at(k,k))+1.0);qt[i]=s*0.5;s=0.5/s;this.w=(matrix.at(k,j)-matrix.at(j,k))*s;qt[j]=(matrix.at(j,i)+matrix.at(i,j))*s;qt[k]=(matrix.at(k,i)+matrix.at(i,k))*s;this.x=qt[0];this.y=qt[1];this.z=qt[2];} if(this.w>1.0||this.w<-1.0) {var errThreshold=1+(x3dom.fields.Eps*100);if(this.w>errThreshold||this.w<-errThreshold) {x3dom.debug.logInfo("MatToQuat: BUG: |quat[4]| ("+this.w+") >> 1.0 !");} if(this.w>1.0){this.w=1.0;} else{this.w=-1.0;}}};x3dom.fields.Quaternion.prototype.setFromEuler=function(alpha,beta,gamma){var sx=Math.sin(alpha*0.5);var cx=Math.cos(alpha*0.5);var sy=Math.sin(beta*0.5);var cy=Math.cos(beta*0.5);var sz=Math.sin(gamma*0.5);var cz=Math.cos(gamma*0.5);this.x=(sx*cy*cz)-(cx*sy*sz);this.y=(cx*sy*cz)+(sx*cy*sz);this.z=(cx*cy*sz)-(sx*sy*cz);this.w=(cx*cy*cz)+(sx*sy*sz);};x3dom.fields.Quaternion.prototype.dot=function(that){return this.x*that.x+this.y*that.y+this.z*that.z+this.w*that.w;};x3dom.fields.Quaternion.prototype.add=function(that){return new x3dom.fields.Quaternion(this.x+that.x,this.y+that.y,this.z+that.z,this.w+that.w);};x3dom.fields.Quaternion.prototype.subtract=function(that){return new x3dom.fields.Quaternion(this.x-that.x,this.y-that.y,this.z-that.z,this.w-that.w);};x3dom.fields.Quaternion.prototype.setValues=function(that){this.x=that.x;this.y=that.y;this.z=that.z;this.w=that.w;};x3dom.fields.Quaternion.prototype.equals=function(that,eps){return(this.dot(that)>=1.0-eps);};x3dom.fields.Quaternion.prototype.multScalar=function(s){return new x3dom.fields.Quaternion(this.x*s,this.y*s,this.z*s,this.w*s);};x3dom.fields.Quaternion.prototype.normalize=function(that){var d2=this.dot(that);var id=1.0;if(d2){id=1.0/Math.sqrt(d2);} return new x3dom.fields.Quaternion(this.x*id,this.y*id,this.z*id,this.w*id);};x3dom.fields.Quaternion.prototype.negate=function(){return new x3dom.fields.Quaternion(-this.x,-this.y,-this.z,-this.w);};x3dom.fields.Quaternion.prototype.inverse=function(){return new x3dom.fields.Quaternion(-this.x,-this.y,-this.z,this.w);};x3dom.fields.Quaternion.prototype.slerp=function(that,t){var cosom=this.dot(that);var rot1;if(cosom<0.0) {cosom=-cosom;rot1=that.negate();} else {rot1=new x3dom.fields.Quaternion(that.x,that.y,that.z,that.w);} var scalerot0,scalerot1;if((1.0-cosom)>0.00001) {var omega=Math.acos(cosom);var sinom=Math.sin(omega);scalerot0=Math.sin((1.0-t)*omega)/sinom;scalerot1=Math.sin(t*omega)/sinom;} else {scalerot0=1.0-t;scalerot1=t;} return this.multScalar(scalerot0).add(rot1.multScalar(scalerot1));};x3dom.fields.Quaternion.rotateFromTo=function(fromVec,toVec){var from=fromVec.normalize();var to=toVec.normalize();var cost=from.dot(to);if(cost>0.99999) {return new x3dom.fields.Quaternion(0,0,0,1);} else if(cost<-0.99999) {var cAxis=new x3dom.fields.SFVec3f(1,0,0);var tmp=from.cross(cAxis);if(tmp.length()<0.00001) {cAxis.x=0;cAxis.y=1;cAxis.z=0;tmp=from.cross(cAxis);} tmp=tmp.normalize();return x3dom.fields.Quaternion.axisAngle(tmp,Math.PI);} var axis=fromVec.cross(toVec);axis=axis.normalize();var s=Math.sqrt(0.5*(1.0-cost));axis=axis.multiply(s);s=Math.sqrt(0.5*(1.0+cost));return new x3dom.fields.Quaternion(axis.x,axis.y,axis.z,s);};x3dom.fields.Quaternion.prototype.toGL=function(){var val=this.toAxisAngle();return[val[0].x,val[0].y,val[0].z,val[1]];};x3dom.fields.Quaternion.prototype.toString=function(){return this.x+" "+this.y+" "+this.z+", "+this.w;};x3dom.fields.Quaternion.prototype.setValueByStr=function(str){var m=/^\s*([+\-]?\d*\.*\d*[eE]?[+\-]?\d*?)\s*,?\s*([+\-]?\d*\.*\d*[eE]?[+\-]?\d*?)\s*,?\s*([+\-]?\d*\.*\d*[eE]?[+\-]?\d*?)\s*,?\s*([+\-]?\d*\.*\d*[eE]?[+\-]?\d*?)\s*$/.exec(str);var quat=x3dom.fields.Quaternion.axisAngle(new x3dom.fields.SFVec3f(+m[1],+m[2],+m[3]),+m[4]);this.x=quat.x;this.y=quat.y;this.z=quat.z;this.w=quat.w;return this;};x3dom.fields.SFColor=function(r,g,b){if(arguments.length===0){this.r=0;this.g=0;this.b=0;} else{this.r=r;this.g=g;this.b=b;}};x3dom.fields.SFColor.parse=function(str){try{var m=/^\s*([+\-]?\d*\.*\d*[eE]?[+\-]?\d*?)\s*,?\s*([+\-]?\d*\.*\d*[eE]?[+\-]?\d*?)\s*,?\s*([+\-]?\d*\.*\d*[eE]?[+\-]?\d*?)\s*$/.exec(str);return new x3dom.fields.SFColor(+m[1],+m[2],+m[3]);} catch(e){return x3dom.fields.SFColor.colorParse(str);}};x3dom.fields.SFColor.copy=function(that){return new x3dom.fields.SFColor(that.r,that.g,that.b);};x3dom.fields.SFColor.prototype.copy=function(){return x3dom.fields.SFColor.copy(this);};x3dom.fields.SFColor.prototype.setHSV=function(h,s,v){x3dom.debug.logWarning("SFColor.setHSV() NYI");};x3dom.fields.SFColor.prototype.getHSV=function(){var h=0,s=0,v=0;x3dom.debug.logWarning("SFColor.getHSV() NYI");return[h,s,v];};x3dom.fields.SFColor.prototype.setValues=function(color){this.r=color.r;this.g=color.g;this.b=color.b;};x3dom.fields.SFColor.prototype.equals=function(that,eps){return Math.abs(this.r-that.r)>>0;};x3dom.fields.SFColorRGBA.colorParse=function(color){var red=0,green=0,blue=0,alpha=0;var color_names={aliceblue:'f0f8ff',antiquewhite:'faebd7',aqua:'00ffff',aquamarine:'7fffd4',azure:'f0ffff',beige:'f5f5dc',bisque:'ffe4c4',black:'000000',blanchedalmond:'ffebcd',blue:'0000ff',blueviolet:'8a2be2',brown:'a52a2a',burlywood:'deb887',cadetblue:'5f9ea0',chartreuse:'7fff00',chocolate:'d2691e',coral:'ff7f50',cornflowerblue:'6495ed',cornsilk:'fff8dc',crimson:'dc143c',cyan:'00ffff',darkblue:'00008b',darkcyan:'008b8b',darkgoldenrod:'b8860b',darkgray:'a9a9a9',darkgreen:'006400',darkkhaki:'bdb76b',darkmagenta:'8b008b',darkolivegreen:'556b2f',darkorange:'ff8c00',darkorchid:'9932cc',darkred:'8b0000',darksalmon:'e9967a',darkseagreen:'8fbc8f',darkslateblue:'483d8b',darkslategray:'2f4f4f',darkturquoise:'00ced1',darkviolet:'9400d3',deeppink:'ff1493',deepskyblue:'00bfff',dimgray:'696969',dodgerblue:'1e90ff',feldspar:'d19275',firebrick:'b22222',floralwhite:'fffaf0',forestgreen:'228b22',fuchsia:'ff00ff',gainsboro:'dcdcdc',ghostwhite:'f8f8ff',gold:'ffd700',goldenrod:'daa520',gray:'808080',green:'008000',greenyellow:'adff2f',honeydew:'f0fff0',hotpink:'ff69b4',indianred:'cd5c5c',indigo:'4b0082',ivory:'fffff0',khaki:'f0e68c',lavender:'e6e6fa',lavenderblush:'fff0f5',lawngreen:'7cfc00',lemonchiffon:'fffacd',lightblue:'add8e6',lightcoral:'f08080',lightcyan:'e0ffff',lightgoldenrodyellow:'fafad2',lightgrey:'d3d3d3',lightgreen:'90ee90',lightpink:'ffb6c1',lightsalmon:'ffa07a',lightseagreen:'20b2aa',lightskyblue:'87cefa',lightslateblue:'8470ff',lightslategray:'778899',lightsteelblue:'b0c4de',lightyellow:'ffffe0',lime:'00ff00',limegreen:'32cd32',linen:'faf0e6',magenta:'ff00ff',maroon:'800000',mediumaquamarine:'66cdaa',mediumblue:'0000cd',mediumorchid:'ba55d3',mediumpurple:'9370d8',mediumseagreen:'3cb371',mediumslateblue:'7b68ee',mediumspringgreen:'00fa9a',mediumturquoise:'48d1cc',mediumvioletred:'c71585',midnightblue:'191970',mintcream:'f5fffa',mistyrose:'ffe4e1',moccasin:'ffe4b5',navajowhite:'ffdead',navy:'000080',oldlace:'fdf5e6',olive:'808000',olivedrab:'6b8e23',orange:'ffa500',orangered:'ff4500',orchid:'da70d6',palegoldenrod:'eee8aa',palegreen:'98fb98',paleturquoise:'afeeee',palevioletred:'d87093',papayawhip:'ffefd5',peachpuff:'ffdab9',peru:'cd853f',pink:'ffc0cb',plum:'dda0dd',powderblue:'b0e0e6',purple:'800080',red:'ff0000',rosybrown:'bc8f8f',royalblue:'4169e1',saddlebrown:'8b4513',salmon:'fa8072',sandybrown:'f4a460',seagreen:'2e8b57',seashell:'fff5ee',sienna:'a0522d',silver:'c0c0c0',skyblue:'87ceeb',slateblue:'6a5acd',slategray:'708090',snow:'fffafa',springgreen:'00ff7f',steelblue:'4682b4',tan:'d2b48c',teal:'008080',thistle:'d8bfd8',tomato:'ff6347',turquoise:'40e0d0',violet:'ee82ee',violetred:'d02090',wheat:'f5deb3',white:'ffffff',whitesmoke:'f5f5f5',yellow:'ffff00',yellowgreen:'9acd32'};if(color_names[color]){color="#"+color_names[color]+"ff";} if(color.substr&&color.substr(0,1)==="#"){color=color.substr(1);var len=color.length;if(len===8){red=parseInt("0x"+color.substr(0,2),16)/255.0;green=parseInt("0x"+color.substr(2,2),16)/255.0;blue=parseInt("0x"+color.substr(4,2),16)/255.0;alpha=parseInt("0x"+color.substr(6,2),16)/255.0;} else if(len===6){red=parseInt("0x"+color.substr(0,2),16)/255.0;green=parseInt("0x"+color.substr(2,2),16)/255.0;blue=parseInt("0x"+color.substr(4,2),16)/255.0;alpha=1.0;} else if(len===4){red=parseInt("0x"+color.substr(0,1),16)/15.0;green=parseInt("0x"+color.substr(1,1),16)/15.0;blue=parseInt("0x"+color.substr(2,1),16)/15.0;alpha=parseInt("0x"+color.substr(3,1),16)/15.0;} else if(len===3){red=parseInt("0x"+color.substr(0,1),16)/15.0;green=parseInt("0x"+color.substr(1,1),16)/15.0;blue=parseInt("0x"+color.substr(2,1),16)/15.0;alpha=1.0;}} return new x3dom.fields.SFColorRGBA(red,green,blue,alpha);};x3dom.fields.SFImage=function(w,h,c,arr){if(arguments.length===0||!(arr&&arr.map)){this.width=0;this.height=0;this.comp=0;this.array=[];} else{this.width=w;this.height=h;this.comp=c;var that=this.array;arr.map(function(v){that.push(v);},this.array);}};x3dom.fields.SFImage.parse=function(str){var img=new x3dom.fields.SFImage();img.setValueByStr(str);return img;};x3dom.fields.SFImage.copy=function(that){var destination=new x3dom.fields.SFImage();destination.width=that.width;destination.height=that.height;destination.comp=that.comp;destination.setPixels(that.array);return destination;};x3dom.fields.SFImage.prototype.copy=function(){return x3dom.fields.SFImage.copy(this);};x3dom.fields.SFImage.prototype.setValueByStr=function(str){var mc=str.match(/(\w+)/g);var n=mc.length;var c2=0;var hex="0123456789ABCDEF";this.array=[];if(n>2){this.width=+mc[0];this.height=+mc[1];this.comp=+mc[2];c2=2*this.comp;}else{this.width=0;this.height=0;this.comp=0;return;} var len,i;for(i=3;i>8&255;g=inp&255;this.array.push(r,g);} else if(this.comp===3){r=inp>>16&255;g=inp>>8&255;b=inp&255;this.array.push(r,g,b);} else if(this.comp===4){r=inp>>24&255;g=inp>>16&255;b=inp>>8&255;a=inp&255;this.array.push(r,g,b,a);}} else if(mc[i].substr(1,1).toLowerCase()==="x"){mc[i]=mc[i].substr(2);len=mc[i].length;if(len===c2){if(this.comp===1){r=parseInt("0x"+mc[i].substr(0,2),16);this.array.push(r);} else if(this.comp===2){r=parseInt("0x"+mc[i].substr(0,2),16);g=parseInt("0x"+mc[i].substr(2,2),16);this.array.push(r,g);} else if(this.comp===3){r=parseInt("0x"+mc[i].substr(0,2),16);g=parseInt("0x"+mc[i].substr(2,2),16);b=parseInt("0x"+mc[i].substr(4,2),16);this.array.push(r,g,b);} else if(this.comp===4){r=parseInt("0x"+mc[i].substr(0,2),16);g=parseInt("0x"+mc[i].substr(2,2),16);b=parseInt("0x"+mc[i].substr(4,2),16);a=parseInt("0x"+mc[i].substr(6,2),16);this.array.push(r,g,b,a);}}}}};x3dom.fields.SFImage.prototype.setPixel=function(x,y,color){var startIdx=(y*this.width+x)*this.comp;if(this.comp===1&&startIdx0);} return false;};x3dom.fields.MFNode.prototype.addLink=function(node){this.nodes.push(node);return true;};x3dom.fields.MFNode.prototype.rmLink=function(node){for(var i=0,n=this.nodes.length;ix3dom.fields.Eps) {r=1.0/this.dir.x;te=(low.x-this.pos.x)*r;tl=(high.x-this.pos.x)*r;if(tlisect){isect=te;}} else if(this.dir.x<-x3dom.fields.Eps) {r=1.0/this.dir.x;te=(high.x-this.pos.x)*r;tl=(low.x-this.pos.x)*r;if(tlisect){isect=te;}} else if(this.pos.xhigh.x) {return false;} if(this.dir.y>x3dom.fields.Eps) {r=1.0/this.dir.y;te=(low.y-this.pos.y)*r;tl=(high.y-this.pos.y)*r;if(tlisect){isect=te;} if(isect-out>=x3dom.fields.Eps){return false;}} else if(this.dir.y<-x3dom.fields.Eps) {r=1.0/this.dir.y;te=(high.y-this.pos.y)*r;tl=(low.y-this.pos.y)*r;if(tlisect){isect=te;} if(isect-out>=x3dom.fields.Eps){return false;}} else if(this.pos.yhigh.y) {return false;} if(this.dir.z>x3dom.fields.Eps) {r=1.0/this.dir.z;te=(low.z-this.pos.z)*r;tl=(high.z-this.pos.z)*r;if(tlisect){isect=te;}} else if(this.dir.z<-x3dom.fields.Eps) {r=1.0/this.dir.z;te=(high.z-this.pos.z)*r;tl=(low.z-this.pos.z)*r;if(tlisect){isect=te;}} else if(this.pos.zhigh.z) {return false;} this.enter=isect;this.exit=out;return(isect-outmin.x){this.min.x=min.x;} if(this.min.y>min.y){this.min.y=min.y;} if(this.min.z>min.z){this.min.z=min.z;} if(this.max.x=b){xmax+=a;xmin+=b;} else{xmax+=b;xmin+=a;} a=this.max.y*m._01;b=this.min.y*m._01;if(a>=b){xmax+=a;xmin+=b;} else{xmax+=b;xmin+=a;} a=this.max.z*m._02;b=this.min.z*m._02;if(a>=b){xmax+=a;xmin+=b;} else{xmax+=b;xmin+=a;} a=this.max.x*m._10;b=this.min.x*m._10;if(a>=b){ymax+=a;ymin+=b;} else{ymax+=b;ymin+=a;} a=this.max.y*m._11;b=this.min.y*m._11;if(a>=b){ymax+=a;ymin+=b;} else{ymax+=b;ymin+=a;} a=this.max.z*m._12;b=this.min.z*m._12;if(a>=b){ymax+=a;ymin+=b;} else{ymax+=b;ymin+=a;} a=this.max.x*m._20;b=this.min.x*m._20;if(a>=b){zmax+=a;zmin+=b;} else{zmax+=b;zmin+=a;} a=this.max.y*m._21;b=this.min.y*m._21;if(a>=b){zmax+=a;zmin+=b;} else{zmax+=b;zmin+=a;} a=this.max.z*m._22;b=this.min.z*m._22;if(a>=b){zmax+=a;zmin+=b;} else{zmax+=b;zmin+=a;} this.min.x=xmin;this.min.y=ymin;this.min.z=zmin;this.max.x=xmax;this.max.y=ymax;this.max.z=zmax;this.updateInternals();};x3dom.fields.BoxVolume.prototype.transformFrom=function(m,other) {var xmin,ymin,zmin;var xmax,ymax,zmax;xmin=xmax=m._03;ymin=ymax=m._13;zmin=zmax=m._23;var a=other.max.x*m._00;var b=other.min.x*m._00;if(a>=b){xmax+=a;xmin+=b;} else{xmax+=b;xmin+=a;} a=other.max.y*m._01;b=other.min.y*m._01;if(a>=b){xmax+=a;xmin+=b;} else{xmax+=b;xmin+=a;} a=other.max.z*m._02;b=other.min.z*m._02;if(a>=b){xmax+=a;xmin+=b;} else{xmax+=b;xmin+=a;} a=other.max.x*m._10;b=other.min.x*m._10;if(a>=b){ymax+=a;ymin+=b;} else{ymax+=b;ymin+=a;} a=other.max.y*m._11;b=other.min.y*m._11;if(a>=b){ymax+=a;ymin+=b;} else{ymax+=b;ymin+=a;} a=other.max.z*m._12;b=other.min.z*m._12;if(a>=b){ymax+=a;ymin+=b;} else{ymax+=b;ymin+=a;} a=other.max.x*m._20;b=other.min.x*m._20;if(a>=b){zmax+=a;zmin+=b;} else{zmax+=b;zmin+=a;} a=other.max.y*m._21;b=other.min.y*m._21;if(a>=b){zmax+=a;zmin+=b;} else{zmax+=b;zmin+=a;} a=other.max.z*m._22;b=other.min.z*m._22;if(a>=b){zmax+=a;zmin+=b;} else{zmax+=b;zmin+=a;} this.min.x=xmin;this.min.y=ymin;this.min.z=zmin;this.max.x=xmax;this.max.y=ymax;this.max.z=zmax;this.updateInternals();this.valid=true;};x3dom.fields.FrustumVolume=function(clipMat) {this.planeNormals=[];this.planeDistances=[];this.directionIndex=[];if(arguments.length===0){return;} var planeEquation=[];for(var i=0;i<6;i++){this.planeNormals[i]=new x3dom.fields.SFVec3f(0,0,0);this.planeDistances[i]=0;this.directionIndex[i]=0;planeEquation[i]=new x3dom.fields.SFVec4f(0,0,0,0);} planeEquation[0].x=clipMat._30-clipMat._00;planeEquation[0].y=clipMat._31-clipMat._01;planeEquation[0].z=clipMat._32-clipMat._02;planeEquation[0].w=clipMat._33-clipMat._03;planeEquation[1].x=clipMat._30+clipMat._00;planeEquation[1].y=clipMat._31+clipMat._01;planeEquation[1].z=clipMat._32+clipMat._02;planeEquation[1].w=clipMat._33+clipMat._03;planeEquation[2].x=clipMat._30+clipMat._10;planeEquation[2].y=clipMat._31+clipMat._11;planeEquation[2].z=clipMat._32+clipMat._12;planeEquation[2].w=clipMat._33+clipMat._13;planeEquation[3].x=clipMat._30-clipMat._10;planeEquation[3].y=clipMat._31-clipMat._11;planeEquation[3].z=clipMat._32-clipMat._12;planeEquation[3].w=clipMat._33-clipMat._13;planeEquation[4].x=clipMat._30+clipMat._20;planeEquation[4].y=clipMat._31+clipMat._21;planeEquation[4].z=clipMat._32+clipMat._22;planeEquation[4].w=clipMat._33+clipMat._23;planeEquation[5].x=clipMat._30-clipMat._20;planeEquation[5].y=clipMat._31-clipMat._21;planeEquation[5].z=clipMat._32-clipMat._22;planeEquation[5].w=clipMat._33-clipMat._23;for(i=0;i<6;i++){var vectorLength=Math.sqrt(planeEquation[i].x*planeEquation[i].x+ planeEquation[i].y*planeEquation[i].y+ planeEquation[i].z*planeEquation[i].z);planeEquation[i].x/=vectorLength;planeEquation[i].y/=vectorLength;planeEquation[i].z/=vectorLength;planeEquation[i].w/=-vectorLength;} var updateDirectionIndex=function(normalVec){var ind=0;if(normalVec.x>0)ind|=1;if(normalVec.y>0)ind|=2;if(normalVec.z>0)ind|=4;return ind;};this.planeNormals[3].setValues(planeEquation[0]);this.planeDistances[3]=planeEquation[0].w;this.directionIndex[3]=updateDirectionIndex(this.planeNormals[3]);this.planeNormals[2].setValues(planeEquation[1]);this.planeDistances[2]=planeEquation[1].w;this.directionIndex[2]=updateDirectionIndex(this.planeNormals[2]);this.planeNormals[5].setValues(planeEquation[2]);this.planeDistances[5]=planeEquation[2].w;this.directionIndex[5]=updateDirectionIndex(this.planeNormals[5]);this.planeNormals[4].setValues(planeEquation[3]);this.planeDistances[4]=planeEquation[3].w;this.directionIndex[4]=updateDirectionIndex(this.planeNormals[4]);this.planeNormals[0].setValues(planeEquation[4]);this.planeDistances[0]=planeEquation[4].w;this.directionIndex[0]=updateDirectionIndex(this.planeNormals[0]);this.planeNormals[1].setValues(planeEquation[5]);this.planeDistances[1]=planeEquation[5].w;this.directionIndex[1]=updateDirectionIndex(this.planeNormals[1]);};x3dom.fields.FrustumVolume.prototype.intersect=function(vol,planeMask) {if(this.planeNormals.length<6){x3dom.debug.logWarning("FrustumVolume not initialized!");return false;} var that=this;var min=vol.min,max=vol.max;var setDirectionIndexPoint=function(index){var pnt=new x3dom.fields.SFVec3f(0,0,0);if(index&1){pnt.x=min.x;} else{pnt.x=max.x;} if(index&2){pnt.y=min.y;} else{pnt.y=max.y;} if(index&4){pnt.z=min.z;} else{pnt.z=max.z;} return pnt;};var pntIsInHalfSpace=function(i,pnt){var s=that.planeNormals[i].dot(pnt)-that.planeDistances[i];return(s>=0);};var isInHalfSpace=function(i){var p=setDirectionIndexPoint(that.directionIndex[i]);return pntIsInHalfSpace(i,p);};var isOutHalfSpace=function(i){var p=setDirectionIndexPoint(that.directionIndex[i]^7);return!pntIsInHalfSpace(i,p);};var mask=1;if(planeMask<0)planeMask=0;for(var i=0;i<6;i++,mask<<=1){if((planeMask&mask)!=0) continue;if(isOutHalfSpace(i)) return-1;if(isInHalfSpace(i)) planeMask|=mask;} return planeMask;};x3dom.docs={};x3dom.docs.specURLMap={CADGeometry:"CADGeometry.html",Core:"core.html",DIS:"dis.html",CubeMapTexturing:"env_texture.html",EnvironmentalEffects:"enveffects.html",EnvironmentalSensor:"envsensor.html",Followers:"followers.html",Geospatial:"geodata.html",Geometry2D:"geometry2D.html",Geometry3D:"geometry3D.html",Grouping:"group.html","H-Anim":"hanim.html",Interpolation:"interp.html",KeyDeviceSensor:"keyboard.html",Layering:"layering.html",Layout:"layout.html",Lighting:"lighting.html",Navigation:"navigation.html",Networking:"networking.html",NURBS:"nurbs.html",ParticleSystems:"particle_systems.html",Picking:"picking.html",PointingDeviceSensor:"pointingsensor.html",Rendering:"rendering.html",RigidBodyPhysics:"rigid_physics.html",Scripting:"scripting.html",Shaders:"shaders.html",Shape:"shape.html",Sound:"sound.html",Text:"text.html",Texturing3D:"texture3D.html",Texturing:"texturing.html",Time:"time.html",EventUtilities:"utils.html",VolumeRendering:"volume.html"};x3dom.docs.specBaseURL="http://www.web3d.org/x3d/specifications/ISO-IEC-19775-1.2-X3D-AbstractSpecification/Part01/components/";x3dom.docs.getNodeTreeInfo=function(){var tn,t;var types="";var objInArray=function(array,obj){for(var i=0;i"+ t+"   "+ x3dom.nodeTypes[t]._compName+"
";for(var i in x3dom.nodeTypes[t].childTypes[t]){dump(x3dom.nodeTypes[t].childTypes[t][i],indent+1);}};for(tn in x3dom.nodeTypes){var t=x3dom.nodeTypes[tn];if(t.childTypes===undefined){t.childTypes={};} while(t.superClass){if(t.superClass.childTypes[t.superClass._typeName]===undefined){t.superClass.childTypes[t.superClass._typeName]=[];} if(!objInArray(t.superClass.childTypes[t.superClass._typeName],t._typeName)){t.superClass.childTypes[t.superClass._typeName].push(t._typeName);} t=t.superClass;}} dump("X3DNode",0);return"
"+types+"
";};x3dom.docs.getComponentInfo=function(){var components=[];var component;var result="";var c,cn;for(c in x3dom.components){components.push(c);} components.sort();for(cn in components){c=components[cn];component=x3dom.components[c];result+="

"+ c+"

";result+="
    ";for(var t in component){result+="
  • "+ t+"
  • ";} result+="
";} return result;};x3dom.shader={};x3dom.shader.PICKING="picking";x3dom.shader.PICKING_24="picking24";x3dom.shader.PICKING_ID="pickingId";x3dom.shader.PICKING_COLOR="pickingColor";x3dom.shader.PICKING_TEXCOORD="pickingTexCoord";x3dom.shader.FRONTGROUND_TEXTURE="frontgroundTexture";x3dom.shader.BACKGROUND_TEXTURE="backgroundTexture";x3dom.shader.BACKGROUND_SKYTEXTURE="backgroundSkyTexture";x3dom.shader.BACKGROUND_CUBETEXTURE="backgroundCubeTexture";x3dom.shader.SHADOW="shadow";x3dom.shader.BLUR="blur";x3dom.shader.DEPTH="depth";x3dom.shader.NORMAL="normal";x3dom.shader.TEXTURE_REFINEMENT="textureRefinement";x3dom.shader.material=function(){var shaderPart="uniform vec3 diffuseColor;\n"+"uniform vec3 specularColor;\n"+"uniform vec3 emissiveColor;\n"+"uniform float shininess;\n"+"uniform float transparency;\n"+"uniform float ambientIntensity;\n";return shaderPart;};x3dom.shader.fog=function(){var shaderPart="uniform vec3 fogColor;\n"+"uniform float fogType;\n"+"uniform float fogRange;\n"+"varying vec3 fragEyePosition;\n"+"float calcFog(in vec3 eye) {\n"+" float f0 = 0.0;\n"+" if(fogType == 0.0) {\n"+" if(length(eye) < fogRange){\n"+" f0 = (fogRange-length(eye)) / fogRange;\n"+" }\n"+" }else{\n"+" if(length(eye) < fogRange){\n"+" f0 = exp(-length(eye) / (fogRange-length(eye) ) );\n"+" }\n"+" }\n"+" f0 = clamp(f0, 0.0, 1.0);\n"+" return f0;\n"+"}\n";return shaderPart;};x3dom.shader.gammaCorrectionDecl=function(properties){var shaderPart="";if(properties.GAMMACORRECTION==="none"){}else if(properties.GAMMACORRECTION==="fastlinear"){shaderPart+="vec4 gammaEncode(vec4 color){\n"+" vec4 tmp = sqrt(color);\n"+" return vec4(tmp.rgb, color.a);\n"+"}\n";shaderPart+="vec4 gammaDecode(vec4 color){\n"+" vec4 tmp = color * color;\n"+" return vec4(tmp.rgb, color.a);\n"+"}\n";shaderPart+="vec3 gammaEncode(vec3 color){\n"+" return sqrt(color);\n"+"}\n";shaderPart+="vec3 gammaDecode(vec3 color){\n"+" return (color * color);\n"+"}\n";}else{shaderPart+="const vec4 gammaEncode4Vector = vec4(0.4545454545454545, 0.4545454545454545, 0.4545454545454545, 1.0);\n";shaderPart+="const vec4 gammaDecode4Vector = vec4(2.2, 2.2, 2.2, 1.0);\n";shaderPart+="vec4 gammaEncode(vec4 color){\n"+" return pow(color, gammaEncode4Vector);\n"+"}\n";shaderPart+="vec4 gammaDecode(vec4 color){\n"+" return pow(color, gammaDecode4Vector);\n"+"}\n";shaderPart+="const vec3 gammaEncode3Vector = vec3(0.4545454545454545, 0.4545454545454545, 0.4545454545454545);\n";shaderPart+="const vec3 gammaDecode3Vector = vec3(2.2, 2.2, 2.2);\n";shaderPart+="vec3 gammaEncode(vec3 color){\n"+" return pow(color, gammaEncode3Vector);\n"+"}\n";shaderPart+="vec3 gammaDecode(vec3 color){\n"+" return pow(color, gammaDecode3Vector);\n"+"}\n";} return shaderPart;};x3dom.shader.encodeGamma=function(properties,expr){if(properties.GAMMACORRECTION==="none"){return expr;}else{return"gammaEncode ("+expr+")";}};x3dom.shader.decodeGamma=function(properties,expr){if(properties.GAMMACORRECTION==="none"){return expr;}else{return"gammaDecode ("+expr+")";}};x3dom.shader.rgbaPacking=function(){var shaderPart="";shaderPart+="vec4 packDepth(float depth){\n"+" depth = (depth + 1.0)*0.5;\n"+" vec4 outVal = vec4(1.0, 255.0, 65025.0, 160581375.0) * depth;\n"+" outVal = fract(outVal);\n"+" outVal -= outVal.yzww * vec4(1.0/255.0, 1.0/255.0, 1.0/255.0, 0.0);\n"+" return outVal;\n"+"}\n";shaderPart+="float unpackDepth(vec4 color){\n"+" float depth = dot(color, vec4(1.0, 1.0/255.0, 1.0/65025.0, 1.0/160581375.0));\n"+" return (2.0*depth - 1.0);\n"+"}\n";return shaderPart;};x3dom.shader.shadowRendering=function(){var shaderPart="";shaderPart+="float getLightInfluence(float lType, float lShadowIntensity, float lOn, vec3 lLocation, vec3 lDirection, "+"float lCutOffAngle, float lBeamWidth, vec3 lAttenuation, float lRadius, vec3 eyeCoords) {\n"+" if (lOn == 0.0 || lShadowIntensity == 0.0){ return 0.0;\n"+" } else if (lType == 0.0) {\n"+" return 1.0;\n"+" } else {\n"+" float attenuation = 0.0;\n"+" vec3 lightVec = (lLocation - (eyeCoords));\n"+" float distance = length(lightVec);\n"+" lightVec = normalize(lightVec);\n"+" eyeCoords = normalize(-eyeCoords);\n"+" if(lRadius == 0.0 || distance <= lRadius) {\n"+" attenuation = 1.0 / max(lAttenuation.x + lAttenuation.y * distance + lAttenuation.z * (distance * distance), 1.0);\n"+" }\n"+" if (lType == 1.0) return attenuation;\n"+" float spotAngle = acos(max(0.0, dot(-lightVec, normalize(lDirection))));\n"+" if(spotAngle >= lCutOffAngle) return 0.0;\n"+" else if(spotAngle <= lBeamWidth) return attenuation;\n"+" else return attenuation * (spotAngle - lCutOffAngle) / (lBeamWidth - lCutOffAngle);\n"+" }\n"+"}\n";shaderPart+="void getShadowValues(inout vec4 shadowMapValues, inout float viewSampleDepth, in mat4 lightMatrix, in vec4 worldCoords, in sampler2D shadowMap){\n"+" vec4 lightSpaceCoords = lightMatrix*worldCoords;\n"+" vec3 lightSpaceCoordsCart = lightSpaceCoords.xyz / lightSpaceCoords.w;\n"+" vec2 textureCoords = (lightSpaceCoordsCart.xy + 1.0)*0.5;\n"+" viewSampleDepth = lightSpaceCoordsCart.z;\n"+" shadowMapValues = texture2D(shadowMap, textureCoords);\n";if(!x3dom.caps.FP_TEXTURES||x3dom.caps.MOBILE) shaderPart+=" shadowMapValues = vec4(1.0,1.0,unpackDepth(shadowMapValues),1.0);\n";shaderPart+="}\n";shaderPart+="void getShadowValuesPointLight(inout vec4 shadowMapValues, inout float viewSampleDepth, in vec3 lLocation, in vec4 worldCoords, in mat4 lightViewMatrix,"+"in mat4 lMatrix_0, in mat4 lMatrix_1, in mat4 lMatrix_2, in mat4 lMatrix_3, in mat4 lMatrix_4, in mat4 lMatrix_5,"+"in sampler2D shadowMap_0, in sampler2D shadowMap_1, in sampler2D shadowMap_2, in sampler2D shadowMap_3,"+"in sampler2D shadowMap_4, in sampler2D shadowMap_5){\n"+" vec4 transformed = lightViewMatrix * worldCoords;\n"+" vec3 lightVec = normalize(transformed.xyz/transformed.w);\n"+" vec3 lightVecAbs = abs(lightVec);\n"+" float maximum = max(max(lightVecAbs.x, lightVecAbs.y),lightVecAbs.z);\n"+" if (lightVecAbs.x == maximum) {\n"+" if (lightVec.x < 0.0) getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_3,worldCoords,shadowMap_3);\n"+" else getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_1,worldCoords,shadowMap_1);\n"+" }\n"+" else if (lightVecAbs.y == maximum) {\n"+" if (lightVec.y < 0.0) getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_4,worldCoords,shadowMap_4);\n"+" else getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_5,worldCoords,shadowMap_5);\n"+" }\n"+" else if (lightVec.z < 0.0) getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_0,worldCoords,shadowMap_0);\n"+" else getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_2,worldCoords,shadowMap_2);\n"+"}\n";shaderPart+="void getShadowValuesCascaded(inout vec4 shadowMapValues, inout float viewSampleDepth, in vec4 worldCoords, in float eyeDepth, in mat4 lMatrix_0, in mat4 lMatrix_1, in mat4 lMatrix_2,"+"in mat4 lMatrix_3, in mat4 lMatrix_4, in mat4 lMatrix_5, in sampler2D shadowMap_0, in sampler2D shadowMap_1, in sampler2D shadowMap_2,"+"in sampler2D shadowMap_3, in sampler2D shadowMap_4, in sampler2D shadowMap_5, in float split_0, in float split_1, in float split_2, in float split_3, in float split_4){\n"+" if (eyeDepth < split_0) getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_0, worldCoords, shadowMap_0);\n"+" else if (eyeDepth < split_1) getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_1, worldCoords, shadowMap_1);\n"+" else if (eyeDepth < split_2) getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_2, worldCoords, shadowMap_2);\n"+" else if (eyeDepth < split_3) getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_3, worldCoords, shadowMap_3);\n"+" else if (eyeDepth < split_4) getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_4, worldCoords, shadowMap_4);\n"+" else getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_5, worldCoords, shadowMap_5);\n"+"}\n";shaderPart+="float ESM(float shadowMapDepth, float viewSampleDepth, float offset){\n";if(!x3dom.caps.FP_TEXTURES||x3dom.caps.MOBILE) shaderPart+=" return exp(-80.0*(1.0-offset)*(viewSampleDepth - shadowMapDepth));\n";else shaderPart+=" return shadowMapDepth * exp(-80.0*(1.0-offset)*viewSampleDepth);\n";shaderPart+="}\n";shaderPart+="float VSM(vec2 moments, float viewSampleDepth, float offset){\n"+" viewSampleDepth = (viewSampleDepth + 1.0) * 0.5;\n"+" if (viewSampleDepth <= moments.x) return 1.0;\n"+" float variance = moments.y - moments.x * moments.x;\n"+" variance = max(variance, 0.00002 + offset*0.01);\n"+" float d = viewSampleDepth - moments.x;\n"+" return variance/(variance + d*d);\n"+"}\n";return shaderPart;};x3dom.shader.light=function(numLights){var shaderPart="";for(var l=0;l= lCutOffAngle) spot = 0.0;\n"+" else if(spotAngle <= lBeamWidth) spot = 1.0;\n"+" else spot = (spotAngle - lCutOffAngle ) / (lBeamWidth - lCutOffAngle);\n"+" }\n"+" }\n"+" vec3 H = normalize( L + V );\n"+" float NdotL = clamp(dot(L, N), 0.0, 1.0);\n"+" float NdotH = clamp(dot(H, N), 0.0, 1.0);\n"+" float ambientFactor = lAmbientIntensity * ambientIntensity;\n"+" float diffuseFactor = lIntensity * NdotL;\n"+" float specularFactor = lIntensity * pow(NdotH, shin*128.0);\n"+" return vec3(ambientFactor, diffuseFactor, specularFactor) * attentuation * spot;\n"+"}\n";return shaderPart;};x3dom.shader.TBNCalculation=function(){var shaderPart="";shaderPart+="mat3 cotangent_frame(vec3 N, vec3 p, vec2 uv)\n"+"{\n"+" // get edge vectors of the pixel triangle\n"+" vec3 dp1 = dFdx( p );\n"+" vec3 dp2 = dFdy( p );\n"+" vec2 duv1 = dFdx( uv );\n"+" vec2 duv2 = dFdy( uv );\n"+"\n"+" // solve the linear system\n"+" vec3 dp2perp = cross( dp2, N );\n"+" vec3 dp1perp = cross( N, dp1 );\n"+" vec3 T = dp2perp * duv1.x + dp1perp * duv2.x;\n"+" vec3 B = dp2perp * duv1.y + dp1perp * duv2.y;\n"+"\n"+" // construct a scale-invariant frame\n"+" float invmax = inversesqrt( max( dot(T,T), dot(B,B) ) );\n"+" return mat3( T * invmax, B * invmax, N );\n"+"}\n\n";shaderPart+="vec3 perturb_normal( vec3 N, vec3 V, vec2 texcoord )\n"+"{\n"+" // assume N, the interpolated vertex normal and\n"+" // V, the view vector (vertex to eye)\n"+" vec3 map = texture2D(normalMap, texcoord ).xyz;\n"+" map = map * 255./127. - 128./127.;\n"+" mat3 TBN = cotangent_frame(N, -V, texcoord);\n"+" return normalize(TBN * map);\n"+"}\n\n";return shaderPart;};x3dom.shader.DynamicShader=function(gl,properties) {this.program=gl.createProgram();var vertexShader=this.generateVertexShader(gl,properties);var fragmentShader=this.generateFragmentShader(gl,properties);gl.attachShader(this.program,vertexShader);gl.attachShader(this.program,fragmentShader);gl.bindAttribLocation(this.program,0,"position");gl.linkProgram(this.program);return this.program;};x3dom.shader.DynamicShader.prototype.generateVertexShader=function(gl,properties) {var shader="";shader+="uniform mat4 modelViewMatrix;\n";shader+="uniform mat4 modelViewProjectionMatrix;\n";if(properties.POSCOMPONENTS==3){shader+="attribute vec3 position;\n";}else if(properties.POSCOMPONENTS==4){shader+="attribute vec4 position;\n";} if(properties.IMAGEGEOMETRY){shader+="uniform vec3 IG_bboxMin;\n";shader+="uniform vec3 IG_bboxMax;\n";shader+="uniform float IG_coordTextureWidth;\n";shader+="uniform float IG_coordTextureHeight;\n";shader+="uniform vec2 IG_implicitMeshSize;\n";for(var i=0;i 0.0) {\n"+" idCoord = vec2((id + writeShadowIDs) / 256.0);\n"+" idCoord.x = floor(idCoord.x) / 255.0;\n"+" idCoord.y = fract(idCoord.y) * 1.00392156862745;\n"+" fragID = id;\n"+" }\n"+" if (imageGeometry != 0.0) {\n"+" vec2 IG_texCoord;\n"+" if(imageGeometry == 1.0) {\n"+" vec2 halfPixel = vec2(0.5/IG_indexTextureWidth,0.5/IG_indexTextureHeight);\n"+" IG_texCoord = vec2(position.x*(IG_implicitMeshSize.x/IG_indexTextureWidth), position.y*(IG_implicitMeshSize.y/IG_indexTextureHeight)) + halfPixel;\n"+" vec2 IG_index = texture2D( IG_indexTexture, IG_texCoord ).rg;\n"+" IG_texCoord = IG_index * 0.996108948;\n"+" } else {\n"+" vec2 halfPixel = vec2(0.5/IG_coordTextureWidth, 0.5/IG_coordTextureHeight);\n"+" IG_texCoord = vec2(position.x*(IG_implicitMeshSize.x/IG_coordTextureWidth), position.y*(IG_implicitMeshSize.y/IG_coordTextureHeight)) + halfPixel;\n"+" }\n"+" pos = texture2D( IG_coordinateTexture, IG_texCoord ).rgb;\n"+" pos = pos * (IG_bboxMax - IG_bboxMin) + IG_bboxMin;\n"+" } \n"+ popDecoder+" {\n"+" pos = bgCenter + bgSize * pos / bgPrecisionMax;\n"+" }\n"+" worldCoord = (modelMatrix * vec4(pos, 1.0)).xyz - from;\n"+" gl_Position = modelViewProjectionMatrix * vec4(pos, 1.0);\n"+"}\n";} else{shader="attribute vec3 position;\n"+"attribute float id;\n"+"uniform vec3 bgCenter;\n"+"uniform vec3 bgSize;\n"+"uniform float bgPrecisionMax;\n"+"uniform float writeShadowIDs;\n"+"uniform mat4 modelMatrix;\n"+"uniform mat4 modelViewProjectionMatrix;\n"+"uniform vec3 from;\n"+"varying vec3 worldCoord;\n"+"varying vec2 idCoord;\n"+"varying float fragID;\n"+ popUniforms+"void main(void) {\n"+" gl_PointSize = 2.0;\n"+" vec3 pos = position;\n"+" if (writeShadowIDs > 0.0) {\n"+" idCoord = vec2((id + writeShadowIDs) / 256.0);\n"+" idCoord.x = floor(idCoord.x) / 255.0;\n"+" idCoord.y = fract(idCoord.y) * 1.00392156862745;\n"+" fragID = id;\n"+" }\n"+ popDecoder+" {\n"+" pos = bgCenter + bgSize * pos / bgPrecisionMax;\n"+" }\n"+" worldCoord = (modelMatrix * vec4(pos, 1.0)).xyz - from;\n"+" gl_Position = modelViewProjectionMatrix * vec4(pos, 1.0);\n"+"}\n";} var vertexShader=gl.createShader(gl.VERTEX_SHADER);gl.shaderSource(vertexShader,shader);gl.compileShader(vertexShader);if(!gl.getShaderParameter(vertexShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[PickingShader] VertexShader "+gl.getShaderInfoLog(vertexShader));} return vertexShader;};x3dom.shader.PickingShader.prototype.generateFragmentShader=function(gl) {var shader="#ifdef GL_FRAGMENT_PRECISION_HIGH\n";shader+=" precision highp float;\n";shader+="#else\n";shader+=" precision mediump float;\n";shader+="#endif\n\n";shader+="uniform float writeShadowIDs;\n"+"uniform float highBit;\n"+"uniform float lowBit;\n"+"uniform float sceneSize;\n"+"uniform float visibilityMap;\n"+"uniform float multiVisibilityWidth;\n"+"uniform float multiVisibilityHeight;\n"+"varying vec3 worldCoord;\n"+"varying vec2 idCoord;\n"+"varying float fragID;\n"+"uniform sampler2D multiVisibilityMap;\n"+"void main(void) {\n"+" vec4 col = vec4(0.0, 0.0, highBit, lowBit);\n"+" if (writeShadowIDs > 0.0) {\n"+" col.ba = idCoord;\n"+" if (visibilityMap > 0.1) {\n"+" vec2 idTexCoord;\n"+" float roundedID = floor(fragID+0.5);\n"+" idTexCoord.x = (mod(roundedID, multiVisibilityWidth)) * (1.0 / multiVisibilityWidth) + (0.5 / multiVisibilityWidth);\n"+" idTexCoord.y = (floor(roundedID / multiVisibilityHeight)) * (1.0 / multiVisibilityHeight) + (0.5 / multiVisibilityHeight);\n"+" vec4 visibility = texture2D( multiVisibilityMap, idTexCoord );\n"+" if (visibility.r < 1.0) discard; \n"+" }\n"+" }\n"+" float d = length(worldCoord) / sceneSize;\n"+" vec2 comp = fract(d * vec2(256.0, 1.0));\n"+" col.rg = comp - (comp.rr * vec2(0.0, 1.0/256.0));\n"+" gl_FragColor = col;\n"+"}\n";var fragmentShader=gl.createShader(gl.FRAGMENT_SHADER);gl.shaderSource(fragmentShader,shader);gl.compileShader(fragmentShader);if(!gl.getShaderParameter(fragmentShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[PickingShader] FragmentShader "+gl.getShaderInfoLog(fragmentShader));} return fragmentShader;};x3dom.shader.Picking24Shader=function(gl) {this.program=gl.createProgram();var vertexShader=this.generateVertexShader(gl);var fragmentShader=this.generateFragmentShader(gl);gl.attachShader(this.program,vertexShader);gl.attachShader(this.program,fragmentShader);gl.bindAttribLocation(this.program,0,"position");gl.linkProgram(this.program);return this.program;};x3dom.shader.Picking24Shader.prototype.generateVertexShader=function(gl) {var shader="";if(!x3dom.caps.MOBILE){shader="attribute vec3 position;\n"+"attribute float id;\n"+"uniform vec3 bgCenter;\n"+"uniform vec3 bgSize;\n"+"uniform float bgPrecisionMax;\n"+"uniform mat4 modelMatrix;\n"+"uniform mat4 modelViewProjectionMatrix;\n"+"uniform vec3 from;\n"+"varying vec3 worldCoord;\n"+"varying vec3 idCoord;\n"+"varying float fragID;\n"+"uniform float writeShadowIDs;\n"+"uniform float imageGeometry;\n"+"uniform vec3 IG_bboxMin;\n"+"uniform vec3 IG_bboxMax;\n"+"uniform float IG_coordTextureWidth;\n"+"uniform float IG_coordTextureHeight;\n"+"uniform float IG_indexTextureWidth;\n"+"uniform float IG_indexTextureHeight;\n"+"uniform sampler2D IG_indexTexture;\n"+"uniform sampler2D IG_coordinateTexture;\n"+"uniform vec2 IG_implicitMeshSize;\n"+"void main(void) {\n"+" gl_PointSize = 2.0;\n"+" if (writeShadowIDs > 0.0) {\n"+" float ID = id + writeShadowIDs;\n"+" float h = floor(ID / 256.0);\n"+" idCoord.x = ID - (h * 256.0);\n"+" idCoord.z = floor(h / 256.0);\n"+" idCoord.y = h - (idCoord.z * 256.0);\n"+" idCoord = idCoord.zyx / 255.0;\n"+" fragID = id;\n"+" }\n"+" if (imageGeometry != 0.0) {\n"+" vec2 IG_texCoord;\n"+" if(imageGeometry == 1.0) {\n"+" vec2 halfPixel = vec2(0.5/IG_indexTextureWidth,0.5/IG_indexTextureHeight);\n"+" IG_texCoord = vec2(position.x*(IG_implicitMeshSize.x/IG_indexTextureWidth), position.y*(IG_implicitMeshSize.y/IG_indexTextureHeight)) + halfPixel;\n"+" vec2 IG_index = texture2D( IG_indexTexture, IG_texCoord ).rg;\n"+" IG_texCoord = IG_index * 0.996108948;\n"+" } else {\n"+" vec2 halfPixel = vec2(0.5/IG_coordTextureWidth, 0.5/IG_coordTextureHeight);\n"+" IG_texCoord = vec2(position.x*(IG_implicitMeshSize.x/IG_coordTextureWidth), position.y*(IG_implicitMeshSize.y/IG_coordTextureHeight)) + halfPixel;\n"+" }\n"+" vec3 pos = texture2D( IG_coordinateTexture, IG_texCoord ).rgb;\n"+" pos = pos * (IG_bboxMax - IG_bboxMin) + IG_bboxMin;\n"+" worldCoord = (modelMatrix * vec4(pos, 1.0)).xyz - from;\n"+" gl_Position = modelViewProjectionMatrix * vec4(pos, 1.0);\n"+" } else {\n"+" vec3 pos = bgCenter + bgSize * position / bgPrecisionMax;\n"+" worldCoord = (modelMatrix * vec4(pos, 1.0)).xyz - from;\n"+" gl_Position = modelViewProjectionMatrix * vec4(pos, 1.0);\n"+" }\n"+"}\n";} else{shader="attribute vec3 position;\n"+"attribute float id;\n"+"uniform vec3 bgCenter;\n"+"uniform vec3 bgSize;\n"+"uniform float bgPrecisionMax;\n"+"uniform float writeShadowIDs;\n"+"varying float fragID;\n"+"uniform mat4 modelMatrix;\n"+"uniform mat4 modelViewProjectionMatrix;\n"+"uniform vec3 from;\n"+"varying vec3 worldCoord;\n"+"varying vec3 idCoord;\n"+"void main(void) {\n"+" gl_PointSize = 2.0;\n"+" if (writeShadowIDs > 0.0) {\n"+" float ID = id + writeShadowIDs;\n"+" float h = floor(ID / 256.0);\n"+" idCoord.x = ID - (h * 256.0);\n"+" idCoord.z = floor(h / 256.0);\n"+" idCoord.y = h - (idCoord.z * 256.0);\n"+" idCoord = idCoord.zyx / 255.0;\n"+" fragID = id;\n"+" }\n"+" vec3 pos = bgCenter + bgSize * position / bgPrecisionMax;\n"+" worldCoord = (modelMatrix * vec4(pos, 1.0)).xyz - from;\n"+" gl_Position = modelViewProjectionMatrix * vec4(pos, 1.0);\n"+"}\n";} var vertexShader=gl.createShader(gl.VERTEX_SHADER);gl.shaderSource(vertexShader,shader);gl.compileShader(vertexShader);if(!gl.getShaderParameter(vertexShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[Picking24Shader] VertexShader "+gl.getShaderInfoLog(vertexShader));} return vertexShader;};x3dom.shader.Picking24Shader.prototype.generateFragmentShader=function(gl) {var shader="#ifdef GL_FRAGMENT_PRECISION_HIGH\n";shader+="precision highp float;\n";shader+="#else\n";shader+=" precision mediump float;\n";shader+="#endif\n\n";shader+="uniform float writeShadowIDs;\n"+"uniform float highBit;\n"+"uniform float lowBit;\n"+"uniform float sceneSize;\n"+"uniform float visibilityMap;\n"+"uniform float multiVisibilityWidth;\n"+"uniform float multiVisibilityHeight;\n"+"varying vec3 worldCoord;\n"+"varying vec3 idCoord;\n"+"varying float fragID;\n"+"uniform sampler2D multiVisibilityMap;\n"+"void main(void) {\n"+" vec4 col = vec4(0.0, 0.0, highBit, lowBit);\n"+" if (writeShadowIDs > 0.0) {\n"+" col.gba = idCoord;\n"+" if (visibilityMap > 0.0) {\n"+" vec2 idTexCoord;\n"+" float roundedID = floor(fragID+0.5);\n"+" idTexCoord.x = (mod(roundedID, multiVisibilityWidth)) * (1.0 / multiVisibilityWidth) + (0.5 / multiVisibilityWidth);\n"+" idTexCoord.y = (floor(roundedID / multiVisibilityHeight)) * (1.0 / multiVisibilityHeight) + (0.5 / multiVisibilityHeight);\n"+" vec4 visibility = texture2D( multiVisibilityMap, idTexCoord );\n"+" if (visibility.a < 1.0) discard; \n"+" }\n"+" }\n"+" col.r = length(worldCoord) / sceneSize;\n"+" gl_FragColor = col;\n"+"}\n";var fragmentShader=gl.createShader(gl.FRAGMENT_SHADER);gl.shaderSource(fragmentShader,shader);gl.compileShader(fragmentShader);if(!gl.getShaderParameter(fragmentShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[Picking24Shader] FragmentShader "+gl.getShaderInfoLog(fragmentShader));} return fragmentShader;};x3dom.shader.PickingIdShader=function(gl) {this.program=gl.createProgram();var vertexShader=this.generateVertexShader(gl);var fragmentShader=this.generateFragmentShader(gl);gl.attachShader(this.program,vertexShader);gl.attachShader(this.program,fragmentShader);gl.bindAttribLocation(this.program,0,"position");gl.linkProgram(this.program);return this.program;};x3dom.shader.PickingIdShader.prototype.generateVertexShader=function(gl) {var shader="attribute vec3 position;\n"+"attribute float id;\n"+"uniform vec3 bgCenter;\n"+"uniform vec3 bgSize;\n"+"uniform float bgPrecisionMax;\n"+"uniform float writeShadowIDs;\n"+"uniform mat4 modelMatrix;\n"+"uniform mat4 modelViewProjectionMatrix;\n"+"varying vec2 idCoord;\n"+"void main(void) {\n"+" if (writeShadowIDs > 0.0) {\n"+" idCoord = vec2((id + writeShadowIDs) / 256.0);\n"+" idCoord.x = floor(idCoord.x) / 255.0;\n"+" idCoord.y = fract(idCoord.y) * 1.00392156862745;\n"+" }\n"+" vec3 pos = bgCenter + bgSize * position / bgPrecisionMax;\n"+" gl_Position = modelViewProjectionMatrix * vec4(pos, 1.0);\n"+"}\n";var vertexShader=gl.createShader(gl.VERTEX_SHADER);gl.shaderSource(vertexShader,shader);gl.compileShader(vertexShader);if(!gl.getShaderParameter(vertexShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[PickingIdShader] VertexShader "+gl.getShaderInfoLog(vertexShader));} return vertexShader;};x3dom.shader.PickingIdShader.prototype.generateFragmentShader=function(gl) {var shader="#ifdef GL_FRAGMENT_PRECISION_HIGH\n";shader+=" precision highp float;\n";shader+="#else\n";shader+=" precision mediump float;\n";shader+="#endif\n\n";shader+="uniform float writeShadowIDs;\n"+"uniform float highBit;\n"+"uniform float lowBit;\n"+"varying vec2 idCoord;\n"+"void main(void) {\n"+" vec4 col = vec4(highBit, lowBit, 0.0, 0.0);\n"+" if (writeShadowIDs > 0.0) {\n"+" col.ba = idCoord;\n"+" }\n"+" gl_FragColor = col;\n"+"}\n";var fragmentShader=gl.createShader(gl.FRAGMENT_SHADER);gl.shaderSource(fragmentShader,shader);gl.compileShader(fragmentShader);if(!gl.getShaderParameter(fragmentShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[PickingIdShader] FragmentShader "+gl.getShaderInfoLog(fragmentShader));} return fragmentShader;};x3dom.shader.PickingColorShader=function(gl) {this.program=gl.createProgram();var vertexShader=this.generateVertexShader(gl);var fragmentShader=this.generateFragmentShader(gl);gl.attachShader(this.program,vertexShader);gl.attachShader(this.program,fragmentShader);gl.bindAttribLocation(this.program,0,"position");gl.linkProgram(this.program);return this.program;};x3dom.shader.PickingColorShader.prototype.generateVertexShader=function(gl) {var shader="attribute vec3 position;\n"+"attribute vec3 color;\n"+"varying vec3 fragColor;\n"+"uniform mat4 modelViewProjectionMatrix;\n"+"\n"+"void main(void) {\n"+" gl_Position = modelViewProjectionMatrix * vec4(position, 1.0);\n"+" gl_PointSize = 2.0;\n"+" fragColor = color;\n"+"}\n";var vertexShader=gl.createShader(gl.VERTEX_SHADER);gl.shaderSource(vertexShader,shader);gl.compileShader(vertexShader);if(!gl.getShaderParameter(vertexShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[PickingColorShader] VertexShader "+gl.getShaderInfoLog(vertexShader));} return vertexShader;};x3dom.shader.PickingColorShader.prototype.generateFragmentShader=function(gl) {var shader="#ifdef GL_FRAGMENT_PRECISION_HIGH\n";shader+="precision highp float;\n";shader+="#else\n";shader+=" precision mediump float;\n";shader+="#endif\n\n";shader+="uniform float lowBit;\n"+"varying vec3 fragColor;\n"+"\n"+"void main(void) {\n"+" gl_FragColor = vec4(fragColor, lowBit);\n"+"}\n";var fragmentShader=gl.createShader(gl.FRAGMENT_SHADER);gl.shaderSource(fragmentShader,shader);gl.compileShader(fragmentShader);if(!gl.getShaderParameter(fragmentShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[PickingColorShader] FragmentShader "+gl.getShaderInfoLog(fragmentShader));} return fragmentShader;};x3dom.shader.PickingTexcoordShader=function(gl) {this.program=gl.createProgram();var vertexShader=this.generateVertexShader(gl);var fragmentShader=this.generateFragmentShader(gl);gl.attachShader(this.program,vertexShader);gl.attachShader(this.program,fragmentShader);gl.bindAttribLocation(this.program,0,"position");gl.linkProgram(this.program);return this.program;};x3dom.shader.PickingTexcoordShader.prototype.generateVertexShader=function(gl) {var shader="attribute vec3 position;\n"+"attribute vec2 texcoord;\n"+"varying vec3 fragColor;\n"+"uniform mat4 modelViewProjectionMatrix;\n"+""+"void main(void) {\n"+" gl_Position = modelViewProjectionMatrix * vec4(position, 1.0);\n"+" fragColor = vec3(abs(texcoord.x), abs(texcoord.y), 0.0);\n"+"}\n";var vertexShader=gl.createShader(gl.VERTEX_SHADER);gl.shaderSource(vertexShader,shader);gl.compileShader(vertexShader);if(!gl.getShaderParameter(vertexShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[PickingTexcoordShader] VertexShader "+gl.getShaderInfoLog(vertexShader));} return vertexShader;};x3dom.shader.PickingTexcoordShader.prototype.generateFragmentShader=function(gl) {var shader="#ifdef GL_FRAGMENT_PRECISION_HIGH\n";shader+="precision highp float;\n";shader+="#else\n";shader+=" precision mediump float;\n";shader+="#endif\n\n";shader+="uniform float lowBit;\n"+"varying vec3 fragColor;\n"+"\n"+"void main(void) {\n"+" gl_FragColor = vec4(fragColor, lowBit);\n"+"}\n";var fragmentShader=gl.createShader(gl.FRAGMENT_SHADER);gl.shaderSource(fragmentShader,shader);gl.compileShader(fragmentShader);if(!gl.getShaderParameter(fragmentShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[PickingTexcoordShader] FragmentShader "+gl.getShaderInfoLog(fragmentShader));} return fragmentShader;};x3dom.shader.FrontgroundTextureShader=function(gl) {this.program=gl.createProgram();var vertexShader=this.generateVertexShader(gl);var fragmentShader=this.generateFragmentShader(gl);gl.attachShader(this.program,vertexShader);gl.attachShader(this.program,fragmentShader);gl.bindAttribLocation(this.program,0,"position");gl.linkProgram(this.program);return this.program;};x3dom.shader.FrontgroundTextureShader.prototype.generateVertexShader=function(gl) {var shader="attribute vec3 position;\n"+"varying vec2 fragTexCoord;\n"+"\n"+"void main(void) {\n"+" vec2 texCoord = (position.xy + 1.0) * 0.5;\n"+" fragTexCoord = texCoord;\n"+" gl_Position = vec4(position.xy, 0.0, 1.0);\n"+"}\n";var vertexShader=gl.createShader(gl.VERTEX_SHADER);gl.shaderSource(vertexShader,shader);gl.compileShader(vertexShader);if(!gl.getShaderParameter(vertexShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[FrontgroundTextureShader] VertexShader "+gl.getShaderInfoLog(vertexShader));} return vertexShader;};x3dom.shader.FrontgroundTextureShader.prototype.generateFragmentShader=function(gl) {var shader="#ifdef GL_FRAGMENT_PRECISION_HIGH\n";shader+="precision highp float;\n";shader+="#else\n";shader+=" precision mediump float;\n";shader+="#endif\n\n";shader+="uniform sampler2D tex;\n"+"varying vec2 fragTexCoord;\n"+"\n"+"void main(void) {\n"+" vec4 col = texture2D(tex, fragTexCoord);\n"+" gl_FragColor = vec4(col.rgb, 1.0);\n"+"}\n";var fragmentShader=gl.createShader(gl.FRAGMENT_SHADER);gl.shaderSource(fragmentShader,shader);gl.compileShader(fragmentShader);if(!gl.getShaderParameter(fragmentShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[FrontgroundTextureShader] FragmentShader "+gl.getShaderInfoLog(fragmentShader));} return fragmentShader;};x3dom.shader.BackgroundTextureShader=function(gl) {this.program=gl.createProgram();var vertexShader=this.generateVertexShader(gl);var fragmentShader=this.generateFragmentShader(gl);gl.attachShader(this.program,vertexShader);gl.attachShader(this.program,fragmentShader);gl.bindAttribLocation(this.program,0,"position");gl.linkProgram(this.program);return this.program;};x3dom.shader.BackgroundTextureShader.prototype.generateVertexShader=function(gl) {var shader="attribute vec3 position;\n"+"varying vec2 fragTexCoord;\n"+"\n"+"void main(void) {\n"+" vec2 texCoord = (position.xy + 1.0) * 0.5;\n"+" fragTexCoord = texCoord;\n"+" gl_Position = vec4(position.xy, 0.0, 1.0);\n"+"}\n";var vertexShader=gl.createShader(gl.VERTEX_SHADER);gl.shaderSource(vertexShader,shader);gl.compileShader(vertexShader);if(!gl.getShaderParameter(vertexShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[BackgroundTextureShader] VertexShader "+gl.getShaderInfoLog(vertexShader));} return vertexShader;};x3dom.shader.BackgroundTextureShader.prototype.generateFragmentShader=function(gl) {var shader="#ifdef GL_FRAGMENT_PRECISION_HIGH\n";shader+="precision highp float;\n";shader+="#else\n";shader+=" precision mediump float;\n";shader+="#endif\n\n";shader+="uniform sampler2D tex;\n"+"varying vec2 fragTexCoord;\n"+"\n"+"void main(void) {\n"+" gl_FragColor = texture2D(tex, fragTexCoord);\n"+"}";var fragmentShader=gl.createShader(gl.FRAGMENT_SHADER);gl.shaderSource(fragmentShader,shader);gl.compileShader(fragmentShader);if(!gl.getShaderParameter(fragmentShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[BackgroundTextureShader] FragmentShader "+gl.getShaderInfoLog(fragmentShader));} return fragmentShader;};x3dom.shader.BackgroundSkyTextureShader=function(gl) {this.program=gl.createProgram();var vertexShader=this.generateVertexShader(gl);var fragmentShader=this.generateFragmentShader(gl);gl.attachShader(this.program,vertexShader);gl.attachShader(this.program,fragmentShader);gl.bindAttribLocation(this.program,0,"position");gl.linkProgram(this.program);return this.program;};x3dom.shader.BackgroundSkyTextureShader.prototype.generateVertexShader=function(gl) {var shader="attribute vec3 position;\n"+"attribute vec2 texcoord;\n"+"uniform mat4 modelViewProjectionMatrix;\n"+"varying vec2 fragTexCoord;\n"+"\n"+"void main(void) {\n"+" fragTexCoord = texcoord;\n"+" gl_Position = modelViewProjectionMatrix * vec4(position, 1.0);\n"+"}\n";var vertexShader=gl.createShader(gl.VERTEX_SHADER);gl.shaderSource(vertexShader,shader);gl.compileShader(vertexShader);if(!gl.getShaderParameter(vertexShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[BackgroundSkyTextureShader] VertexShader "+gl.getShaderInfoLog(vertexShader));} return vertexShader;};x3dom.shader.BackgroundSkyTextureShader.prototype.generateFragmentShader=function(gl) {var shader="#ifdef GL_FRAGMENT_PRECISION_HIGH\n";shader+="precision highp float;\n";shader+="#else\n";shader+=" precision mediump float;\n";shader+="#endif\n\n";shader+="uniform sampler2D tex;\n"+"varying vec2 fragTexCoord;\n"+"\n"+"void main(void) {\n"+" gl_FragColor = texture2D(tex, fragTexCoord);\n"+"}\n";var fragmentShader=gl.createShader(gl.FRAGMENT_SHADER);gl.shaderSource(fragmentShader,shader);gl.compileShader(fragmentShader);if(!gl.getShaderParameter(fragmentShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[BackgroundSkyTextureShader] FragmentShader "+gl.getShaderInfoLog(fragmentShader));} return fragmentShader;};x3dom.shader.BackgroundCubeTextureShader=function(gl) {this.program=gl.createProgram();var vertexShader=this.generateVertexShader(gl);var fragmentShader=this.generateFragmentShader(gl);gl.attachShader(this.program,vertexShader);gl.attachShader(this.program,fragmentShader);gl.bindAttribLocation(this.program,0,"position");gl.linkProgram(this.program);return this.program;};x3dom.shader.BackgroundCubeTextureShader.prototype.generateVertexShader=function(gl) {var shader="attribute vec3 position;\n"+"uniform mat4 modelViewProjectionMatrix;\n"+"varying vec3 fragNormal;\n"+"\n"+"void main(void) {\n"+" fragNormal = normalize(position);\n"+" gl_Position = modelViewProjectionMatrix * vec4(position, 1.0);\n"+"}\n";var vertexShader=gl.createShader(gl.VERTEX_SHADER);gl.shaderSource(vertexShader,shader);gl.compileShader(vertexShader);if(!gl.getShaderParameter(vertexShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[BackgroundCubeTextureShader] VertexShader "+gl.getShaderInfoLog(vertexShader));} return vertexShader;};x3dom.shader.BackgroundCubeTextureShader.prototype.generateFragmentShader=function(gl) {var shader="#ifdef GL_FRAGMENT_PRECISION_HIGH\n";shader+="precision highp float;\n";shader+="#else\n";shader+=" precision mediump float;\n";shader+="#endif\n\n";shader+="uniform samplerCube tex;\n"+"varying vec3 fragNormal;\n"+"\n"+"float magn(float val) {\n"+" return ((val >= 0.0) ? val : -1.0 * val);\n"+"}"+"\n"+"void main(void) {\n"+" vec3 normal = -reflect(normalize(fragNormal), vec3(0.0,0.0,1.0));\n"+" if (magn(normal.y) >= magn(normal.x) && magn(normal.y) >= magn(normal.z))\n"+" normal.xz = -normal.xz;\n"+" gl_FragColor = textureCube(tex, normal);\n"+"}\n";var fragmentShader=gl.createShader(gl.FRAGMENT_SHADER);gl.shaderSource(fragmentShader,shader);gl.compileShader(fragmentShader);if(!gl.getShaderParameter(fragmentShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[BackgroundCubeTextureShader] FragmentShader "+gl.getShaderInfoLog(fragmentShader));} return fragmentShader;};x3dom.shader.ShadowShader=function(gl) {this.program=gl.createProgram();var vertexShader=this.generateVertexShader(gl);var fragmentShader=this.generateFragmentShader(gl);gl.attachShader(this.program,vertexShader);gl.attachShader(this.program,fragmentShader);gl.bindAttribLocation(this.program,0,"position");gl.linkProgram(this.program);return this.program;};x3dom.shader.ShadowShader.prototype.generateVertexShader=function(gl) {var shader="";if(!x3dom.caps.MOBILE){shader+="attribute vec3 position;\n"+"uniform mat4 modelViewProjectionMatrix;\n"+"varying vec4 projCoords;\n"+"uniform float imageGeometry;\n"+"uniform vec3 IG_bboxMin;\n"+"uniform vec3 IG_bboxMax;\n"+"uniform float IG_coordTextureWidth;\n"+"uniform float IG_coordTextureHeight;\n"+"uniform float IG_indexTextureWidth;\n"+"uniform float IG_indexTextureHeight;\n"+"uniform sampler2D IG_indexTexture;\n"+"uniform sampler2D IG_coordinateTexture;\n"+"uniform vec2 IG_implicitMeshSize;\n"+"uniform vec3 bgCenter;\n"+"uniform vec3 bgSize;\n"+"uniform float bgPrecisionMax;\n"+"uniform float popGeometry;\n"+"uniform float PG_precisionLevel;\n"+"uniform float PG_powPrecision;\n"+"uniform vec3 PG_maxBBSize;\n"+"uniform vec3 PG_bbMin;\n"+"uniform vec3 PG_bbMaxModF;\n"+"uniform vec3 PG_bboxShiftVec;\n"+"void main(void) {\n"+" vec3 pos;\n"+" if (imageGeometry != 0.0) {\n"+" vec2 IG_texCoord;\n"+" if(imageGeometry == 1.0) {\n"+" vec2 halfPixel = vec2(0.5/IG_indexTextureWidth,0.5/IG_indexTextureHeight);\n"+" IG_texCoord = vec2(position.x*(IG_implicitMeshSize.x/IG_indexTextureWidth), position.y*(IG_implicitMeshSize.y/IG_indexTextureHeight)) + halfPixel;\n"+" vec2 IG_index = texture2D( IG_indexTexture, IG_texCoord ).rg;\n"+" IG_texCoord = IG_index * 0.996108948;\n"+" } else {\n"+" vec2 halfPixel = vec2(0.5/IG_coordTextureWidth, 0.5/IG_coordTextureHeight);\n"+" IG_texCoord = vec2(position.x*(IG_implicitMeshSize.x/IG_coordTextureWidth), position.y*(IG_implicitMeshSize.y/IG_coordTextureHeight)) + halfPixel;\n"+" }\n"+" pos = texture2D( IG_coordinateTexture, IG_texCoord ).rgb;\n"+" pos = pos * (IG_bboxMax - IG_bboxMin) + IG_bboxMin;\n"+" } else if (popGeometry != 0.0){\n"+" pos = position;\n"+" vec3 offsetVec = step(pos / bgPrecisionMax, PG_bbMaxModF) * PG_bboxShiftVec;\n"+" if (PG_precisionLevel <= 2.0) {\n"+" pos = floor(pos / PG_powPrecision) * PG_powPrecision;\n"+" pos /= (65536.0 - PG_powPrecision);\n"+" }\n"+" else {\n"+" pos /= bgPrecisionMax;\n"+" }\n"+" pos = (pos + offsetVec + PG_bbMin) * PG_maxBBSize;\n"+" } else {\n"+" pos = bgCenter + bgSize * position / bgPrecisionMax;\n"+" }\n"+" projCoords = modelViewProjectionMatrix * vec4(pos, 1.0);\n"+" gl_Position = projCoords;\n"+"}\n";}else{shader="attribute vec3 position;\n"+"uniform vec3 bgCenter;\n"+"uniform vec3 bgSize;\n"+"uniform float bgPrecisionMax;\n"+"uniform mat4 modelViewProjectionMatrix;\n"+"varying vec4 projCoords;\n"+"void main(void) {\n"+" vec3 pos = bgCenter + bgSize * position / bgPrecisionMax;\n"+" projCoords = modelViewProjectionMatrix * vec4(pos, 1.0);\n"+" gl_Position = projCoords;\n"+"}\n";} var vertexShader=gl.createShader(gl.VERTEX_SHADER);gl.shaderSource(vertexShader,shader);gl.compileShader(vertexShader);if(!gl.getShaderParameter(vertexShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[ShadowShader] VertexShader "+gl.getShaderInfoLog(vertexShader));} return vertexShader;};x3dom.shader.ShadowShader.prototype.generateFragmentShader=function(gl) {var shader="#ifdef GL_FRAGMENT_PRECISION_HIGH\n";shader+="precision highp float;\n";shader+="#else\n";shader+=" precision mediump float;\n";shader+="#endif\n\n";shader+="varying vec4 projCoords;\n"+"uniform float offset;\n"+"uniform bool cameraView;\n";if(!x3dom.caps.FP_TEXTURES||x3dom.caps.MOBILE) shader+=x3dom.shader.rgbaPacking();shader+="void main(void) {\n"+" vec3 proj = (projCoords.xyz / projCoords.w);\n";if(!x3dom.caps.FP_TEXTURES||x3dom.caps.MOBILE){shader+="gl_FragColor = packDepth(proj.z);\n";}else{shader+=" if (!cameraView){\n"+" proj.z = (proj.z + 1.0)*0.5;\n"+" proj.y = proj.z * proj.z;\n"+" }\n";shader+=" gl_FragColor = vec4(proj, 1.0);\n";} shader+="}\n";var fragmentShader=gl.createShader(gl.FRAGMENT_SHADER);gl.shaderSource(fragmentShader,shader);gl.compileShader(fragmentShader);if(!gl.getShaderParameter(fragmentShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[ShadowShader] FragmentShader "+gl.getShaderInfoLog(fragmentShader));} return fragmentShader;};x3dom.shader.ShadowRenderingShader=function(gl,shadowedLights) {this.program=gl.createProgram();var vertexShader=this.generateVertexShader(gl);var fragmentShader=this.generateFragmentShader(gl,shadowedLights);gl.attachShader(this.program,vertexShader);gl.attachShader(this.program,fragmentShader);gl.bindAttribLocation(this.program,0,"position");gl.linkProgram(this.program);return this.program;};x3dom.shader.ShadowRenderingShader.prototype.generateVertexShader=function(gl) {var shader="";shader+="attribute vec2 position;\n";shader+="varying vec2 vPosition;\n";shader+="void main(void) {\n";shader+=" vPosition = position;\n";shader+=" gl_Position = vec4(position, -1.0, 1.0);\n";shader+="}\n";var vertexShader=gl.createShader(gl.VERTEX_SHADER);gl.shaderSource(vertexShader,shader);gl.compileShader(vertexShader);if(!gl.getShaderParameter(vertexShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[ShadowRendering] VertexShader "+gl.getShaderInfoLog(vertexShader));} return vertexShader;};x3dom.shader.ShadowRenderingShader.prototype.generateFragmentShader=function(gl,shadowedLights) {var shader="#ifdef GL_FRAGMENT_PRECISION_HIGH\n";shader+="precision highp float;\n";shader+="#else\n";shader+=" precision mediump float;\n";shader+="#endif\n\n";shader+="uniform mat4 inverseViewProj;\n";shader+="uniform mat4 inverseProj;\n";shader+="varying vec2 vPosition;\n";shader+="uniform sampler2D sceneMap;\n";for(var i=0;i<5;i++) shader+="uniform float cascade"+i+"_Depth;\n";for(var l=0;l=0||navigator.appVersion.indexOf("Mobile")>-1||x3dom.caps.MAX_VARYING_VECTORS<=8||x3dom.caps.MAX_VERTEX_TEXTURE_IMAGE_UNITS<2){x3dom.caps.MOBILE=true;} if(x3dom.caps.MOBILE){if(forbidMobileShaders){x3dom.caps.MOBILE=false;x3dom.debug.logWarning("Detected mobile graphics card! "+"But being forced to desktop shaders which might not work!");} else{x3dom.debug.logWarning("Detected mobile graphics card! "+"Using low quality shaders without ImageGeometry support!");}} else{if(forceMobileShaders){x3dom.caps.MOBILE=true;x3dom.debug.logWarning("Detected desktop graphics card! "+"But being forced to mobile shaders with lower quality!");}}} catch(ex){x3dom.debug.logWarning("Your browser probably supports an older WebGL version. "+"Please try the old mobile runtime instead:\n"+"http://www.x3dom.org/x3dom/src_mobile/x3dom.js");newCtx=null;} return newCtx;}} catch(e){x3dom.debug.logWarning(e);}} return null;} Context.prototype.setupShape=function(gl,drawable,viewarea){var q=0,q6;var textures,t;var vertices,positionBuffer;var texCoordBuffer,normalBuffer,colorBuffer;var indicesBuffer,indexArray;var shape=drawable.shape;var geoNode=shape._cf.geometry.node;if(shape._webgl!==undefined){var needFullReInit=false;if(shape._dirty.colors===true&&shape._webgl.shader.color===undefined&&geoNode._mesh._colors[0].length){needFullReInit=true;} if(needFullReInit&&shape._cleanupGLObjects){shape._cleanupGLObjects(true,false);} if(shape._dirty.texture===true){if(shape._webgl.texture.length!=shape.getTextures().length){for(t=0;t65535)){indexArray=new Uint32Array(shape._webgl.indexes[q]);shape._webgl.indexType=gl.UNSIGNED_INT;} else{indexArray=new Uint16Array(shape._webgl.indexes[q]);shape._webgl.indexType=gl.UNSIGNED_SHORT;} gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,indicesBuffer);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,indexArray,gl.STATIC_DRAW);indexArray=null;shape._webgl.positions[q]=geoNode._mesh._positions[q];gl.deleteBuffer(shape._webgl.buffers[q6+1]);positionBuffer=gl.createBuffer();shape._webgl.buffers[q6+1]=positionBuffer;gl.bindBuffer(gl.ARRAY_BUFFER,positionBuffer);gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,shape._webgl.buffers[q6]);vertices=new Float32Array(shape._webgl.positions[q]);gl.bufferData(gl.ARRAY_BUFFER,vertices,gl.STATIC_DRAW);gl.bindBuffer(gl.ARRAY_BUFFER,positionBuffer);gl.vertexAttribPointer(shape._webgl.shader.position,geoNode._mesh._numPosComponents,shape._webgl.coordType,false,shape._coordStrideOffset[0],shape._coordStrideOffset[1]);vertices=null;} shape._dirty.positions=false;shape._dirty.indexes=false;} if(shape._dirty.colors==true){if(shape._webgl.shader.color!==undefined){shape._webgl.colors[q]=geoNode._mesh._colors[q];gl.deleteBuffer(shape._webgl.buffers[q6+4]);colorBuffer=gl.createBuffer();shape._webgl.buffers[q6+4]=colorBuffer;colors=new Float32Array(shape._webgl.colors[q]);gl.bindBuffer(gl.ARRAY_BUFFER,colorBuffer);gl.bufferData(gl.ARRAY_BUFFER,colors,gl.STATIC_DRAW);gl.vertexAttribPointer(shape._webgl.shader.color,geoNode._mesh._numColComponents,shape._webgl.colorType,false,shape._colorStrideOffset[0],shape._colorStrideOffset[1]);colors=null;} shape._dirty.colors=false;} if(shape._dirty.normals==true){if(shape._webgl.shader.normal!==undefined){shape._webgl.normals[q]=geoNode._mesh._normals[q];gl.deleteBuffer(shape._webgl.buffers[q6+2]);normalBuffer=gl.createBuffer();shape._webgl.buffers[q6+2]=normalBuffer;normals=new Float32Array(shape._webgl.normals[q]);gl.bindBuffer(gl.ARRAY_BUFFER,normalBuffer);gl.bufferData(gl.ARRAY_BUFFER,normals,gl.STATIC_DRAW);gl.vertexAttribPointer(shape._webgl.shader.normal,geoNode._mesh._numNormComponents,shape._webgl.normalType,false,shape._normalStrideOffset[0],shape._normalStrideOffset[1]);normals=null;} shape._dirty.normals=false;} if(shape._dirty.texcoords==true){if(shape._webgl.shader.texcoord!==undefined){shape._webgl.texcoords[q]=geoNode._mesh._texCoords[q];gl.deleteBuffer(shape._webgl.buffers[q6+3]);texCoordBuffer=gl.createBuffer();shape._webgl.buffers[q6+3]=texCoordBuffer;texCoords=new Float32Array(shape._webgl.texcoords[q]);gl.bindBuffer(gl.ARRAY_BUFFER,texCoordBuffer);gl.bufferData(gl.ARRAY_BUFFER,texCoords,gl.STATIC_DRAW);gl.vertexAttribPointer(shape._webgl.shader.texCoord,geoNode._mesh._numTexComponents,shape._webgl.texCoordType,false,shape._texCoordStrideOffset[0],shape._texCoordStrideOffset[1]);texCoords=null;} shape._dirty.texcoords=false;} if(shape._dirty.ids==true){if(shape._webgl.shader.texcoord!==undefined){shape._webgl.texcoords[q]=geoNode._mesh._texCoords[q];gl.deleteBuffer(shape._webgl.buffers[q6+3]);texCoordBuffer=gl.createBuffer();shape._webgl.buffers[q6+3]=texCoordBuffer;texCoords=new Float32Array(shape._webgl.texcoords[q]);gl.bindBuffer(gl.ARRAY_BUFFER,texCoordBuffer);gl.bufferData(gl.ARRAY_BUFFER,texCoords,gl.STATIC_DRAW);gl.vertexAttribPointer(shape._webgl.shader.texCoord,geoNode._mesh._numTexComponents,shape._webgl.texCoordType,false,shape._texCoordStrideOffset[0],shape._texCoordStrideOffset[1]);texCoords=null;} shape._dirty.texcoords=false;}}} else {} if(shape._webgl.imageGeometry!=0){for(t=0;t0&&force)||this._parentNodes.length==0)) {var sp=this._webgl.shader;for(var q=0;q65535)){indexArray=new Uint32Array(shape._webgl.indexes[q]);shape._webgl.indexType=gl.UNSIGNED_INT;} else{indexArray=new Uint16Array(shape._webgl.indexes[q]);shape._webgl.indexType=gl.UNSIGNED_SHORT;} gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,indicesBuffer);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,indexArray,gl.STATIC_DRAW);indexArray=null;positionBuffer=gl.createBuffer();shape._webgl.buffers[q6+1]=positionBuffer;gl.bindBuffer(gl.ARRAY_BUFFER,positionBuffer);vertices=new Float32Array(shape._webgl.positions[q]);gl.bufferData(gl.ARRAY_BUFFER,vertices,gl.STATIC_DRAW);gl.bindBuffer(gl.ARRAY_BUFFER,positionBuffer);gl.vertexAttribPointer(sp.position,geoNode._mesh._numPosComponents,shape._webgl.coordType,false,shape._coordStrideOffset[0],shape._coordStrideOffset[1]);gl.enableVertexAttribArray(sp.position);vertices=null;} if(sp.normal!==undefined||shape._webgl.normals[q]){normalBuffer=gl.createBuffer();shape._webgl.buffers[q6+2]=normalBuffer;var normals=new Float32Array(shape._webgl.normals[q]);gl.bindBuffer(gl.ARRAY_BUFFER,normalBuffer);gl.bufferData(gl.ARRAY_BUFFER,normals,gl.STATIC_DRAW);gl.vertexAttribPointer(sp.normal,geoNode._mesh._numNormComponents,shape._webgl.normalType,false,shape._normalStrideOffset[0],shape._normalStrideOffset[1]);gl.enableVertexAttribArray(sp.normal);normals=null;} if(sp.texcoord!==undefined){var texcBuffer=gl.createBuffer();shape._webgl.buffers[q6+3]=texcBuffer;var texCoords=new Float32Array(shape._webgl.texcoords[q]);gl.bindBuffer(gl.ARRAY_BUFFER,texcBuffer);gl.bufferData(gl.ARRAY_BUFFER,texCoords,gl.STATIC_DRAW);gl.vertexAttribPointer(sp.texcoord,geoNode._mesh._numTexComponents,shape._webgl.texCoordType,false,shape._texCoordStrideOffset[0],shape._texCoordStrideOffset[1]);gl.enableVertexAttribArray(sp.texcoord);texCoords=null;} if(sp.color!==undefined){colorBuffer=gl.createBuffer();shape._webgl.buffers[q6+4]=colorBuffer;var colors=new Float32Array(shape._webgl.colors[q]);gl.bindBuffer(gl.ARRAY_BUFFER,colorBuffer);gl.bufferData(gl.ARRAY_BUFFER,colors,gl.STATIC_DRAW);gl.vertexAttribPointer(sp.color,geoNode._mesh._numColComponents,shape._webgl.colorType,false,shape._colorStrideOffset[0],shape._colorStrideOffset[1]);gl.enableVertexAttribArray(sp.color);colors=null;}} for(var df in geoNode._mesh._dynamicFields) {if(!geoNode._mesh._dynamicFields.hasOwnProperty(df)) continue;var attrib=geoNode._mesh._dynamicFields[df];shape._webgl.dynamicFields[currAttribs]={buf:{},name:df,numComponents:attrib.numComponents};if(sp[df]!==undefined){var attribBuffer=gl.createBuffer();shape._webgl.dynamicFields[currAttribs++].buf=attribBuffer;var attribs=new Float32Array(attrib.value);gl.bindBuffer(gl.ARRAY_BUFFER,attribBuffer);gl.bufferData(gl.ARRAY_BUFFER,attribs,gl.STATIC_DRAW);gl.vertexAttribPointer(sp[df],attrib.numComponents,gl.FLOAT,false,0,0);attribs=null;}}}};Context.prototype.setupScene=function(gl,bgnd){var sphere=null;var texture=null;var that=this;if(bgnd._webgl!==undefined){if(!bgnd._dirty){return;} if(bgnd._webgl.texture!==undefined&&bgnd._webgl.texture){gl.deleteTexture(bgnd._webgl.texture);} if(bgnd._cleanupGLObjects){bgnd._cleanupGLObjects();} bgnd._webgl={};} bgnd._dirty=false;var url=bgnd.getTexUrl();var i=0;var w=1,h=1;if(url.length>0&&url[0].length>0){if(url.length>=6&&url[1].length>0&&url[2].length>0&&url[3].length>0&&url[4].length>0&&url[5].length>0){sphere=new x3dom.nodeTypes.Sphere();bgnd._webgl={positions:sphere._mesh._positions[0],indexes:sphere._mesh._indices[0],buffers:[{},{}]};bgnd._webgl.primType=gl.TRIANGLES;bgnd._webgl.shader=this.cache.getShader(gl,x3dom.shader.BACKGROUND_CUBETEXTURE);bgnd._webgl.texture=x3dom.Utils.createTextureCube(gl,bgnd._nameSpace.doc,url,true,bgnd._vf.withCredentials,true,false);} else{bgnd._webgl={positions:[-w,-h,0,-w,h,0,w,-h,0,w,h,0],indexes:[0,1,2,3],buffers:[{},{}]};url=bgnd._nameSpace.getURL(url[0]);bgnd._webgl.texture=x3dom.Utils.createTexture2D(gl,bgnd._nameSpace.doc,url,true,bgnd._vf.withCredentials,true,false);bgnd._webgl.primType=gl.TRIANGLE_STRIP;bgnd._webgl.shader=this.cache.getShader(gl,x3dom.shader.BACKGROUND_TEXTURE);}} else{if(bgnd.getSkyColor().length>1||bgnd.getGroundColor().length){sphere=new x3dom.nodeTypes.Sphere();texture=gl.createTexture();bgnd._webgl={positions:sphere._mesh._positions[0],texcoords:sphere._mesh._texCoords[0],indexes:sphere._mesh._indices[0],buffers:[{},{},{}],texture:texture,primType:gl.TRIANGLES};var N=x3dom.Utils.nextHighestPowerOfTwo(bgnd.getSkyColor().length+bgnd.getGroundColor().length+2);N=(N<512)?512:N;var n=bgnd._vf.groundAngle.length;var tmp=[],arr=[];var colors=[],sky=[0];for(i=0;i0||bgnd._vf.groundColor.length==1){if(sky[sky.length-1]=0;i--){if((i==n-1)&&(Math.PI-bgnd._vf.groundAngle[i]<=Math.PI/2)){sky[sky.length]=Math.PI/2;colors[colors.length]=bgnd._vf.groundColor[bgnd._vf.groundColor.length-1];} sky[sky.length]=Math.PI-bgnd._vf.groundAngle[i];colors[colors.length]=bgnd._vf.groundColor[i+1];} if(n==0&&bgnd._vf.groundColor.length==1){sky[sky.length]=Math.PI/2;colors[colors.length]=bgnd._vf.groundColor[0];} sky[sky.length]=Math.PI;colors[colors.length]=bgnd._vf.groundColor[0];} else{if(sky[sky.length-1]0||s_gl.popGeometry>0){for(v=0,offset=0,v_n=s_geo._vf.vertexCount.length;v>>8)/255.0;sp.from=from.toGL();sp.sceneSize=sceneSize;sp.imageGeometry=s_gl.imageGeometry;sp.popGeometry=s_gl.popGeometry;sp.writeShadowIDs=(s_gl.binaryGeometry!=0&&s_geo._vf.idsPerVertex)?(x3dom.nodeTypes.Shape.objectID+2):0;sp.visibilityMap=0.0;if(s_gl.coordType!=gl.FLOAT){if(!s_gl.popGeometry&&(x3dom.Utils.isUnsignedType(s_geo._vf.coordType))){sp.bgCenter=s_geo.getMin().toGL();} else{sp.bgCenter=s_geo._vf.position.toGL();} sp.bgSize=s_geo._vf.size.toGL();sp.bgPrecisionMax=s_geo.getPrecisionMax('coordType');} else{sp.bgCenter=bgCenter;sp.bgSize=bgSize;sp.bgPrecisionMax=1;} if(s_gl.colorType!=gl.FLOAT){sp.bgPrecisionColMax=s_geo.getPrecisionMax('colorType');} if(s_gl.texCoordType!=gl.FLOAT){sp.bgPrecisionTexMax=s_geo.getPrecisionMax('texCoordType');} if(s_gl.imageGeometry!=0&&!x3dom.caps.MOBILE) {sp.IG_bboxMin=s_geo.getMin().toGL();sp.IG_bboxMax=s_geo.getMax().toGL();sp.IG_implicitMeshSize=s_geo._vf.implicitMeshSize.toGL();var coordTex=x3dom.Utils.findTextureByName(s_gl.texture,"IG_coords0");if(coordTex){sp.IG_coordTextureWidth=coordTex.texture.width;sp.IG_coordTextureHeight=coordTex.texture.height;} if(s_gl.imageGeometry==1){var indexTex=x3dom.Utils.findTextureByName(s_gl.texture,"IG_index");if(indexTex){sp.IG_indexTextureWidth=indexTex.texture.width;sp.IG_indexTextureHeight=indexTex.texture.height;} gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,indexTex.texture);gl.activeTexture(gl.TEXTURE1);gl.bindTexture(gl.TEXTURE_2D,coordTex.texture);} else{gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,coordTex.texture);} gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);var texUnit=0;if(s_geo.getIndexTexture()){if(!sp.IG_indexTexture){sp.IG_indexTexture=texUnit++;}} if(s_geo.getCoordinateTexture(0)){if(!sp.IG_coordinateTexture){sp.IG_coordinateTexture=texUnit++;}}} else if(s_gl.binaryGeometry!=0&&s_geo._vf.idsPerVertex){var shader=s_app._shader;if(shader&&x3dom.isa(s_app._shader,x3dom.nodeTypes.CommonSurfaceShader)){if(shader.getMultiVisibilityMap()){sp.visibilityMap=1.0;sp.multiVisibilityMap=0;var visTex=x3dom.Utils.findTextureByName(s_gl.texture,"multiVisibilityMap");sp.multiVisibilityWidth=visTex.texture.width;sp.multiVisibilityHeight=visTex.texture.height;gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,visTex.texture);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);}}} if(shape.isSolid()){this.stateManager.enable(gl.CULL_FACE);if(shape.isCCW()){this.stateManager.frontFace(gl.CCW);} else{this.stateManager.frontFace(gl.CW);}} else{this.stateManager.disable(gl.CULL_FACE);} var depthMode=s_app?s_app._cf.depthMode.node:null;if(depthMode) {if(depthMode._vf.enableDepthTest) {this.stateManager.enable(gl.DEPTH_TEST);this.stateManager.depthMask(!depthMode._vf.readOnly);this.stateManager.depthFunc(x3dom.Utils.depthFunc(gl,depthMode._vf.depthFunc));this.stateManager.depthRange(depthMode._vf.zNearRange,depthMode._vf.zFarRange);} else {this.stateManager.disable(gl.DEPTH_TEST);}} else {this.stateManager.enable(gl.DEPTH_TEST);this.stateManager.depthMask(true);this.stateManager.depthFunc(gl.LEQUAL);} if(s_gl.popGeometry){var model_view=mat_view.mult(trafo);this.updatePopState(drawable,s_geo,sp,s_gl,scene,model_view,viewarea,this.x3dElem.runtime.fps);} var q_n;if(s_gl.externalGeometry!=0) {q_n=s_gl.primType.length;} else {q_n=s_gl.positions.length;} for(var q=0;q0||s_gl.popGeometry>0){for(v=0,offset=0,v_n=s_geo._vf.vertexCount.length;v0){var polyMode=(renderMode==1)?gl.POINTS:gl.LINES;if(s_gl.binaryGeometry>0||s_gl.popGeometry>0){for(v=0,offset=0,v_n=s_geo._vf.vertexCount.length;v0||s_gl.popGeometry>0){for(v=0,offset=0,v_n=s_geo._vf.vertexCount.length;v0){var viewpoint=scene.getViewpoint();var imgPlaneHeightAtDistOne=viewpoint.getImgPlaneHeightAtDistOne();var near=viewpoint.getNear();var center=model_view.multMatrixPnt(popGeo._vf.position);var tightRad=model_view.multMatrixVec(popGeo._vf.size).length()*0.5;var largestRad=model_view.multMatrixVec(popGeo._vf.maxBBSize).length()*0.5;var dist=Math.max(-center.z-tightRad,near);var projPixelLength=dist*(imgPlaneHeightAtDistOne/viewarea._height);var arg=(2*largestRad)/(tol*projPixelLength);currentLOD=Math.ceil(Math.log(arg)/0.693147180559945);currentLOD=(currentLOD<1)?1:((currentLOD>16)?16:currentLOD);} var minPrec=popGeo._vf.minPrecisionLevel,maxPrec=popGeo._vf.maxPrecisionLevel;currentLOD=(minPrec!=-1&¤tLODmaxPrec)?maxPrec:currentLOD;var currentLOD_min=(s_gl.levelsAvailable4){mat_view=viewMat;mat_scene=sceneMat;} else{mat_view=viewarea._last_mat_view;mat_scene=viewarea._last_mat_scene;} var min=x3dom.fields.SFVec3f.copy(scene._lastMin);var max=x3dom.fields.SFVec3f.copy(scene._lastMax);var from=mat_view.inverse().e3();var _min=x3dom.fields.SFVec3f.copy(from);var _max=x3dom.fields.SFVec3f.copy(from);if(_min.x>min.x){_min.x=min.x;} if(_min.y>min.y){_min.y=min.y;} if(_min.z>min.z){_min.z=min.z;} if(_max.x0&&shapeId>>8,buttonState&255);if(objId>=baseID){objId-=baseID;var hitObject;if(pickMode!=4){viewarea._pickingInfo.pickPos=pickPos;viewarea._pick.setValues(pickPos);viewarea._pickingInfo.pickNorm=pickNorm;viewarea._pickNorm.setValues(pickNorm);viewarea._pickingInfo.pickObj=null;viewarea._pickingInfo.lastClickObj=null;hitObject=scene._xmlNode;} else{viewarea._pickingInfo.pickObj=x3dom.nodeTypes.Shape.idMap.nodeID[shapeId];hitObject=viewarea._pickingInfo.pickObj._xmlNode;} shadowObjectIdChanged=(viewarea._pickingInfo.shadowObjectId!=objId);viewarea._pickingInfo.lastShadowObjectId=viewarea._pickingInfo.shadowObjectId;viewarea._pickingInfo.shadowObjectId=objId;if((shadowObjectIdChanged||button)&&scene._xmlNode&&(scene._xmlNode["on"+eventType]||scene._xmlNode.hasAttribute("on"+eventType)||scene._listeners[eventType])) {event={target:scene._xmlNode,type:eventType,button:button,mouseup:((buttonState>>>8)>0),layerX:x,layerY:y,shadowObjectId:objId,worldX:pickPos.x,worldY:pickPos.y,worldZ:pickPos.z,normalX:pickNorm.x,normalY:pickNorm.y,normalZ:pickNorm.z,hitPnt:pickPos.toGL(),hitObject:hitObject,cancelBubble:false,stopPropagation:function(){this.cancelBubble=true;},preventDefault:function(){this.cancelBubble=true;}};scene.callEvtHandler(("on"+eventType),event);} if(scene._shadowIdMap&&scene._shadowIdMap.mapping&&objId>>8)>0),layerX:x,layerY:y,shadowObjectId:viewarea._pickingInfo.shadowObjectId,cancelBubble:false,stopPropagation:function(){this.cancelBubble=true;},preventDefault:function(){this.cancelBubble=true;}};scene.callEvtHandler(("on"+eventType),event);} if(objId>0){viewarea._pickingInfo.pickPos=pickPos;viewarea._pickingInfo.pickNorm=pickNorm;viewarea._pickingInfo.pickObj=x3dom.nodeTypes.Shape.idMap.nodeID[objId];} else{viewarea._pickingInfo.pickObj=null;viewarea._pickingInfo.lastClickObj=null;}}} var pickTime=x3dom.Utils.stopMeasure("picking");this.x3dElem.runtime.addMeasurement('PICKING',pickTime);return true;};Context.prototype.pickRect=function(viewarea,x1,y1,x2,y2) {var gl=this.ctx3d;var scene=viewarea?viewarea._scene:null;if(!gl||!scene||!scene._webgl||!scene.drawableCollection) return false;var from=viewarea._last_mat_view.inverse().e3();var sceneSize=scene._lastMax.subtract(scene._lastMin).length();var x=(x1<=x2)?x1:x2;var y=(y1>=y2)?y1:y2;var width=(1+Math.abs(x2-x1))*scene._webgl.pickScale;var height=(1+Math.abs(y2-y1))*scene._webgl.pickScale;this.renderPickingPass(gl,scene,viewarea._last_mat_view,viewarea._last_mat_scene,from,sceneSize,0,x,y,(width<1)?1:width,(height<1)?1:height);var index;var pickedObjects=[];for(index=0;scene._webgl.fboPick.pixelData&&index0) pickedObjects.push(objId);} pickedObjects.sort();var pickedObjectsTemp=(function(arr){var a=[],l=arr.length;for(var i=0;i0) scene._webgl.fboScene=x3dom.Utils.initFBO(gl,this.canvas.width,this.canvas.height,shadowType,false,true);scene._webgl.fboBlur=[];for(i=0;i0&&typeof scene._webgl.fboScene=="undefined"||scene._webgl.fboScene&&(this.canvas.width!=scene._webgl.fboScene.width||this.canvas.height!=scene._webgl.fboScene.height)){scene._webgl.fboScene=x3dom.Utils.initFBO(gl,this.canvas.width,this.canvas.height,shadowType,false,true);}} var env=scene.getEnvironment();env.checkSanity();var bgnd=scene.getBackground();this.setupScene(gl,bgnd);this.numFaces=0;this.numCoords=0;this.numDrawCalls=0;var mat_proj=viewarea.getProjectionMatrix();var mat_view=viewarea.getViewMatrix();if(!this._calledViewpointChangedHandler||!viewarea._last_mat_view.equals(mat_view)){var e_viewpoint=scene.getViewpoint();var e_eventType="viewpointChanged";try{if(e_viewpoint._xmlNode&&(e_viewpoint._xmlNode["on"+e_eventType]||e_viewpoint._xmlNode.hasAttribute("on"+e_eventType)||e_viewpoint._listeners[e_eventType])){var e_viewtrafo=e_viewpoint.getCurrentTransform();e_viewtrafo=e_viewtrafo.inverse().mult(mat_view);var e_mat=e_viewtrafo.inverse();var e_rotation=new x3dom.fields.Quaternion(0,0,1,0);e_rotation.setValue(e_mat);var e_translation=e_mat.e3();var e_event={target:e_viewpoint._xmlNode,type:e_eventType,matrix:e_viewtrafo,position:e_translation,orientation:e_rotation.toAxisAngle(),cancelBubble:false,stopPropagation:function(){this.cancelBubble=true;},preventDefault:function(){this.cancelBubble=true;}};e_viewpoint.callEvtHandler(("on"+e_eventType),e_event);this._calledViewpointChangedHandler=true;}} catch(e_e){x3dom.debug.logException(e_e);}} viewarea._last_mat_view=mat_view;viewarea._last_mat_proj=mat_proj;var mat_scene=mat_proj.mult(mat_view);viewarea._last_mat_scene=mat_scene;scene.drawableCollection=null;if(!scene.drawableCollection) {var drawableCollectionConfig={viewArea:viewarea,sortTrans:env._vf.sortTrans,viewMatrix:mat_view,projMatrix:mat_proj,sceneMatrix:mat_scene,frustumCulling:true,smallFeatureThreshold:env._smallFeatureThreshold,context:this,gl:gl};scene.drawableCollection=new x3dom.DrawableCollection(drawableCollectionConfig);x3dom.Utils.startMeasure('traverse');scene.collectDrawableObjects(x3dom.fields.SFMatrix4f.identity(),scene.drawableCollection,true,false,0);var traverseTime=x3dom.Utils.stopMeasure('traverse');this.x3dElem.runtime.addMeasurement('TRAVERSE',traverseTime);} x3dom.Utils.startMeasure('sorting');scene.drawableCollection.sort();var sortTime=x3dom.Utils.stopMeasure('sorting');this.x3dElem.runtime.addMeasurement('SORT',sortTime);var slights=viewarea.getLights();var numLights=slights.length;var mat_light;var WCToLCMatrices=[];var lMatrices=[];var shadowCount=0;x3dom.Utils.startMeasure('shadow');for(var p=0;p0.0){var lightMatrix=viewarea.getLightMatrix()[p];shadowMaps=scene._webgl.fboShadow[shadowCount];var offset=Math.max(0.0,Math.min(1.0,slights[p]._vf.shadowOffset));if(!x3dom.isa(slights[p],x3dom.nodeTypes.PointLight)){var numCascades=Math.max(1,Math.min(slights[p]._vf.shadowCascades,6));mat_light=viewarea.getWCtoLCMatricesCascaded(lightMatrix,slights[p],mat_proj);for(i=0;i0){this.renderShadowPass(gl,viewarea,mat_scene,mat_view,scene._webgl.fboScene,0.0,true);var shadowTime=x3dom.Utils.stopMeasure('shadow');this.x3dElem.runtime.addMeasurement('SHADOW',shadowTime);} else{this.x3dElem.runtime.removeMeasurement('SHADOW');} mat_light=viewarea.getWCtoLCMatrix(viewarea.getLightMatrix()[0]);for(rtl_i=0;rtl_i0) this.renderShadows(gl,viewarea,shadowedLights,WCToLCMatrices,lMatrices,mat_view,mat_proj,mat_scene);this.stateManager.disable(gl.BLEND);this.stateManager.disable(gl.DEPTH_TEST);viewarea._numRenderedNodes=n;if(viewarea._visDbgBuf!==undefined&&viewarea._visDbgBuf) {var pm=scene._vf.pickMode.toLowerCase();if(pm.indexOf("idbuf")==0||pm=="color"||pm=="texcoord"){this.stateManager.viewport(0,3*this.canvas.height/4,this.canvas.width/4,this.canvas.height/4);scene._fgnd._webgl.render(gl,scene._webgl.fboPick.tex);} if(shadowCount>0){this.stateManager.viewport(this.canvas.width/4,3*this.canvas.height/4,this.canvas.width/4,this.canvas.height/4);scene._fgnd._webgl.render(gl,scene._webgl.fboScene.tex);} var row=3,col=2;for(i=0;i1){sp.lastTex=1;gl.activeTexture(gl.TEXTURE1);gl.bindTexture(gl.TEXTURE_2D,rt._webgl.fbo.tex);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);} sp.curTex=2;gl.activeTexture(gl.TEXTURE2);gl.bindTexture(gl.TEXTURE_2D,rt._webgl.texture);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);sp.mode=rt._currLoadLevel-1;sp.repeat=rt._repeat.toGL();gl.drawArrays(gl.TRIANGLES,0,6);this.stateManager.bindFramebuffer(gl.FRAMEBUFFER,rt._webgl.fbo.fbo);gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);sp.mode=0;sp.curTex=2;gl.activeTexture(gl.TEXTURE2);gl.bindTexture(gl.TEXTURE_2D,refinementFbo.tex);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);gl.drawArrays(gl.TRIANGLES,0,6);gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,null);gl.disableVertexAttribArray(sp.position);this.stateManager.bindFramebuffer(gl.FRAMEBUFFER,null);this.stateManager.viewport(0,0,this.canvas.width,this.canvas.height);if(rt._vf.autoRefinement) rt.nextLevel();if(rt._currLoadLevel==rt._vf.maxLevel) rt._currLoadLevel++;if(rt._webgl.fbo.mipMap){gl.bindTexture(gl.TEXTURE_2D,rt._webgl.fbo.tex);gl.generateMipmap(gl.TEXTURE_2D);gl.bindTexture(gl.TEXTURE_2D,null);} if(!rt.requirePingPong()){gl.deleteTexture(rt._webgl.texture);delete rt._webgl.texture;rt._cleanupGLObjects(true);} rt._renderedImage++;};Context.prototype.renderRTPass=function(gl,viewarea,rt) {if(x3dom.isa(rt,x3dom.nodeTypes.RefinementTexture)){if(rt.requirePingPong()){this.renderPingPongPass(gl,viewarea,rt);} return;} switch(rt._vf.update.toUpperCase()){case"NONE":return;case"NEXT_FRAME_ONLY":if(!rt._needRenderUpdate){return;} rt._needRenderUpdate=false;break;case"ALWAYS":default:break;} var scene=viewarea._scene;var bgnd=null;var mat_view=rt.getViewMatrix();var mat_proj=rt.getProjectionMatrix();var mat_scene=mat_proj.mult(mat_view);var lightMatrix=viewarea.getLightMatrix()[0];var mat_light=viewarea.getWCtoLCMatrix(lightMatrix);var i,n,m=rt._cf.excludeNodes.nodes.length;var arr=new Array(m);for(i=0;i0||s_gl.popGeometry>0){for(v=0,offset=0,v_n=s_geo._vf.vertexCount.length;vtexLimit){renderSplit[renderSplit.length]=i;texUnits=7;}} renderSplit[renderSplit.length]=shadowedLights.length;var n=renderSplit.length-1;var mat_proj_inv=mat_proj.inverse();var mat_scene_inv=mat_scene.inverse();this.stateManager.enable(gl.BLEND);this.stateManager.blendFunc(gl.DST_COLOR,gl.ZERO);for(var s=0;s0){var RefList=[];for(var i=0;i0){viewarea._pickingInfo.pickPos=new x3dom.fields.SFVec3f(data.pickPosX,data.pickPosY,data.pickPosZ);viewarea._pickingInfo.pickObj=x3dom.nodeTypes.Shape.idMap.nodeID[data.objID];}else{viewarea._pickingInfo.pickObj=null;viewarea._pickingInfo.lastClickObj=null;} return true;};Context.prototype.shutdown=function(viewarea){};return setupContext;})();x3dom.NodeNameSpace=function(name,document){this.name=name;this.doc=document;this.baseURL="";this.defMap={};this.parent=null;this.childSpaces=[];};x3dom.NodeNameSpace.prototype.addNode=function(node,name){this.defMap[name]=node;node._nameSpace=this;};x3dom.NodeNameSpace.prototype.removeNode=function(name){var node=name?this.defMap[name]:null;if(node){delete this.defMap[name];node._nameSpace=null;}};x3dom.NodeNameSpace.prototype.getNamedNode=function(name){return this.defMap[name];};x3dom.NodeNameSpace.prototype.getNamedElement=function(name){var node=this.defMap[name];return(node?node._xmlNode:null);};x3dom.NodeNameSpace.prototype.addSpace=function(space){this.childSpaces.push(space);space.parent=this;};x3dom.NodeNameSpace.prototype.removeSpace=function(space){space.parent=null;for(var it=0;it=0)?url.substr(0,i+1):"";x3dom.debug.logInfo("setBaseURL: "+this.baseURL);};x3dom.NodeNameSpace.prototype.getURL=function(url){if(url===undefined||!url.length){return"";} else{return((url[0]==='/')||(url.indexOf(":")>=0))?url:(this.baseURL+url);}};x3dom.hasElementAttribute=function(attrName) {var ok=this.__hasAttribute(attrName);if(!ok&&attrName){ok=this.__hasAttribute(attrName.toLowerCase());} return ok;};x3dom.getElementAttribute=function(attrName) {var attrib=this.__getAttribute(attrName);if(!attrib&&attrib!=""&&attrName){attrib=this.__getAttribute(attrName.toLowerCase());} if(attrib||!this._x3domNode){return attrib;} else{return this._x3domNode._vf[attrName];}};x3dom.setElementAttribute=function(attrName,newVal) {this.__setAttribute(attrName,newVal);var x3dNode=this._x3domNode;if(x3dNode){x3dNode.updateField(attrName,newVal);x3dNode._nameSpace.doc.needRender=true;}};x3dom.getFieldValue=function(fieldName) {var x3dNode=this._x3domNode;if(x3dNode&&x3dNode._vf[fieldName]){return x3dNode._vf[fieldName].copy();} return null;};x3dom.setFieldValue=function(fieldName,fieldvalue){var x3dNode=this._x3domNode;if(x3dNode&&x3dNode._vf[fieldName]){if(fieldvalue instanceof Object&&'copy'in fieldvalue) {x3dNode._vf[fieldName]=fieldvalue.copy();} else x3dNode._vf[fieldName]=fieldvalue;x3dNode.fieldChanged(fieldName);x3dNode._nameSpace.doc.needRender=true;}};x3dom.requestFieldRef=function(fieldName) {var x3dNode=this._x3domNode;if(x3dNode&&x3dNode._vf[fieldName]) {return x3dNode._vf[fieldName];} return null;};x3dom.releaseFieldRef=function(fieldName) {var x3dNode=this._x3domNode;if(x3dNode&&x3dNode._vf[fieldName]) {x3dNode.fieldChanged(fieldName);x3dNode._nameSpace.doc.needRender=true;}};x3dom.NodeNameSpace.prototype.setupTree=function(domNode){var n=null;if(x3dom.isX3DElement(domNode)){if(domNode._x3domNode){x3dom.debug.logWarning('Tree is already initialized');return null;} if((domNode.tagName!==undefined)&&(!domNode.__addEventListener)&&(!domNode.__removeEventListener)) {domNode.__addEventListener=domNode.addEventListener;domNode.addEventListener=function(type,func,phase){if(!this._x3domNode._listeners[type]){this._x3domNode._listeners[type]=[];} this._x3domNode._listeners[type].push(func);this.__addEventListener(type,func,phase);};domNode.__removeEventListener=domNode.removeEventListener;domNode.removeEventListener=function(type,func,phase){var list=this._x3domNode._listeners[type];if(list){for(var it=0;it=2){var otherNS=this;while(otherNS){if(otherNS.name==nsName[0]) n=otherNS.defMap[nsName[1]];if(n) otherNS=null;else otherNS=otherNS.parent;} if(!n){n=null;x3dom.debug.logWarning('Could not USE: '+domNode.getAttribute('USE'));}}} if(n){domNode._x3domNode=n;} return n;} else{if(domNode.localName.toLowerCase()==='route'){var route=domNode;var fnAtt=route.getAttribute('fromNode')||route.getAttribute('fromnode');var tnAtt=route.getAttribute('toNode')||route.getAttribute('tonode');var fromNode=this.defMap[fnAtt];var toNode=this.defMap[tnAtt];if(!(fromNode&&toNode)){x3dom.debug.logWarning("Broken route - can't find all DEFs for "+fnAtt+" -> "+tnAtt);} else{fnAtt=route.getAttribute('fromField')||route.getAttribute('fromfield');tnAtt=route.getAttribute('toField')||route.getAttribute('tofield');fromNode.setupRoute(fnAtt,toNode,tnAtt);route._nodeNameSpace=this;} return null;} domNode.requestFieldRef=x3dom.requestFieldRef;domNode.releaseFieldRef=x3dom.releaseFieldRef;domNode.getFieldValue=x3dom.getFieldValue;domNode.setFieldValue=x3dom.setFieldValue;var nodeType=x3dom.nodeTypesLC[domNode.localName.toLowerCase()];if(nodeType===undefined){x3dom.debug.logWarning("Unrecognised X3D element <"+domNode.localName+">.");} else{if((x3dom.userAgentFeature.supportsDOMAttrModified===false)&&(domNode instanceof Element)){if(domNode.setAttribute&&!domNode.__setAttribute){domNode.__setAttribute=domNode.setAttribute;domNode.setAttribute=x3dom.setElementAttribute;} if(domNode.getAttribute&&!domNode.__getAttribute){domNode.__getAttribute=domNode.getAttribute;domNode.getAttribute=x3dom.getElementAttribute;} if(domNode.hasAttribute&&!domNode.__hasAttribute){domNode.__hasAttribute=domNode.hasAttribute;domNode.hasAttribute=x3dom.hasElementAttribute;}} var ctx={doc:this.doc,xmlNode:domNode,nameSpace:this};n=new nodeType(ctx);if(domNode.hasAttribute('DEF')){n._DEF=domNode.getAttribute('DEF');this.defMap[n._DEF]=n;} else{if(domNode.hasAttribute('id')){n._DEF=domNode.getAttribute('id');this.defMap[n._DEF]=n;}} if(domNode.highlight===undefined) {domNode.highlight=function(enable,colorStr){var color=x3dom.fields.SFColor.parse(colorStr);this._x3domNode.highlight(enable,color);this._x3domNode._nameSpace.doc.needRender=true;};} n._xmlNode=domNode;domNode._x3domNode=n;var that=this;Array.forEach(domNode.childNodes,function(childDomNode){var c=that.setupTree(childDomNode);if(c){n.addChild(c,childDomNode.getAttribute("containerField"));}});n.nodeChanged();return n;}}} else if(domNode.localName){x3dom.debug.logWarning("Unrecognised X3D element <"+domNode.localName+">.");n=null;} return n;};x3dom.registerNodeType("X3DNode","Core",defineClass(null,function(ctx){this._xmlNode=null;this._DEF=null;this._nameSpace=(ctx&&ctx.nameSpace)?ctx.nameSpace:null;this._vf={};this._vfFieldTypes={};this._cf={};this._cfFieldTypes={};this._fieldWatchers={};this._routes={};this._listeners={};this._parentNodes=[];this._childNodes=[];this.addField_SFNode('metadata',x3dom.nodeTypes.X3DMetadataObject);},{type:function(){return this.constructor;},typeName:function(){return this.constructor._typeName;},addChild:function(node,containerFieldName){if(node){var field=null;if(containerFieldName){field=this._cf[containerFieldName];} else{for(var fieldName in this._cf){if(this._cf.hasOwnProperty(fieldName)){var testField=this._cf[fieldName];if(x3dom.isa(node,testField.type)){field=testField;break;}}}} if(field&&field.addLink(node)){node._parentNodes.push(this);this._childNodes.push(node);node.parentAdded(this);return true;}} return false;},removeChild:function(node){if(node){for(var fieldName in this._cf){if(this._cf.hasOwnProperty(fieldName)){var field=this._cf[fieldName];if(field.rmLink(node)){for(var i=node._parentNodes.length-1;i>=0;i--){if(node._parentNodes[i]===this){node._parentNodes.splice(i,1);node.parentRemoved(this);}} for(var j=this._childNodes.length-1;j>=0;j--){if(this._childNodes[j]===node){this._childNodes.splice(j,1);return true;}}}}}} return false;},parentAdded:function(parent){},parentRemoved:function(parent){for(var i=0,n=this._childNodes.length;i=1){return this.transformMatrix(this._parentNodes[0].getCurrentTransform());} else{return x3dom.fields.SFMatrix4f.identity();}},transformMatrix:function(transform){return transform;},getVolume:function(){return null;},invalidateVolume:function(){},invalidateCache:function(){},volumeValid:function(){return false;},collectDrawableObjects:function(transform,drawableCollection,singlePath,invalidateCache,planeMask){},highlight:function(enable,color) {if(this._vf.hasOwnProperty("diffuseColor")) {if(enable){if(this._actDiffuseColor===undefined){this._actDiffuseColor=new x3dom.fields.SFColor();this._highlightOn=false;} if(!this._highlightOn){this._actDiffuseColor.setValues(this._vf.diffuseColor);this._highlightOn=true;} this._vf.diffuseColor.setValues(color);} else{if(this._actDiffuseColor!==undefined){this._vf.diffuseColor.setValues(this._actDiffuseColor);this._highlightOn=false;delete this._actDiffuseColor;}}} for(var i=0,n=this._childNodes.length;i0){fieldName=fromField.substr(0,fromField.length-post.length);if(this._vf[fieldName]){fromField=fieldName;}}}} if(!toNode._vf[toField]){pos=toField.indexOf(pre);if(pos===0){fieldName=toField.substr(pre.length,toField.length-1);if(toNode._vf[fieldName]){toField=fieldName;}} else{pos=toField.indexOf(post);if(pos>0){fieldName=toField.substr(0,toField.length-post.length);if(toNode._vf[fieldName]){toField=fieldName;}}}} var where=this._DEF+"&"+fromField+"&"+toNode._DEF+"&"+toField;if(!this._routes[where]){if(!this._fieldWatchers[fromField]){this._fieldWatchers[fromField]=[];} this._fieldWatchers[fromField].push(function(msg){toNode.postMessage(toField,msg);});if(!toNode._fieldWatchers[toField]){toNode._fieldWatchers[toField]=[];} toNode._fieldWatchers[toField].push(function(msg){toNode._vf[toField]=msg;toNode.fieldChanged(toField);});this._routes[where]={from:this._fieldWatchers[fromField].length-1,to:toNode._fieldWatchers[toField].length-1};}},removeRoute:function(fromField,toNode,toField){var pos;var fieldName;var pre="set_",post="_changed";if(!this._vf[fromField]){pos=fromField.indexOf(pre);if(pos===0){fieldName=fromField.substr(pre.length,fromField.length-1);if(this._vf[fieldName]){fromField=fieldName;}}else{pos=fromField.indexOf(post);if(pos>0){fieldName=fromField.substr(0,fromField.length-post.length);if(this._vf[fieldName]){fromField=fieldName;}}}} if(!toNode._vf[toField]){pos=toField.indexOf(pre);if(pos===0){fieldName=toField.substr(pre.length,toField.length-1);if(toNode._vf[fieldName]){toField=fieldName;}} else{pos=toField.indexOf(post);if(pos>0){fieldName=toField.substr(0,toField.length-post.length);if(toNode._vf[fieldName]){toField=fieldName;}}}} var where=this._DEF+"&"+fromField+"&"+toNode._DEF+"&"+toField;if(this._routes[where]){this._fieldWatchers[fromField].splice(this._routes[where].from,1);toNode._fieldWatchers[toField].splice(this._routes[where].to,1);delete this._routes[where];}},fieldChanged:function(fieldName){},nodeChanged:function(){},callEvtHandler:function(eventType,event){var node=this;if(!node._xmlNode){return event.cancelBubble;} try{var attrib=node._xmlNode[eventType];event.target=node._xmlNode;if(typeof(attrib)==="function"){attrib.call(node._xmlNode,event);} else{var funcStr=node._xmlNode.getAttribute(eventType);var func=new Function('event',funcStr);func.call(node._xmlNode,event);} var list=node._listeners[event.type];if(list){for(var it=0;it=0){this.bind(this._vf.bind);}},nodeChanged:function(){this._stack=this._nameSpace.doc._bindableBag.addBindable(this);}}));x3dom.registerNodeType("X3DInfoNode","Core",defineClass(x3dom.nodeTypes.X3DChildNode,function(ctx){x3dom.nodeTypes.X3DInfoNode.superClass.call(this,ctx);}));x3dom.registerNodeType("WorldInfo","Core",defineClass(x3dom.nodeTypes.X3DInfoNode,function(ctx){x3dom.nodeTypes.WorldInfo.superClass.call(this,ctx);this.addField_MFString(ctx,'info',[]);this.addField_SFString(ctx,'title',"");x3dom.debug.logInfo(this._vf.info);x3dom.debug.logInfo(this._vf.title);}));x3dom.registerNodeType("X3DSensorNode","Core",defineClass(x3dom.nodeTypes.X3DChildNode,function(ctx){x3dom.nodeTypes.X3DSensorNode.superClass.call(this,ctx);this.addField_SFBool(ctx,'enabled',true);}));x3dom.registerNodeType("Param","Core",defineClass(x3dom.nodeTypes.X3DNode,function(ctx){x3dom.nodeTypes.Param.superClass.call(this,ctx);x3dom.debug.logWarning('DEPRECATED: Param element needs to be child of X3D element ' +'[DOCS]');}));x3dom.registerNodeType("X3DBoundedObject","Grouping",defineClass(x3dom.nodeTypes.X3DChildNode,function(ctx){x3dom.nodeTypes.X3DBoundedObject.superClass.call(this,ctx);this.addField_SFBool(ctx,'render',true);this.addField_SFVec3f(ctx,'bboxCenter',0,0,0);this.addField_SFVec3f(ctx,'bboxSize',-1,-1,-1);this._graph={boundedNode:this,localMatrix:x3dom.fields.SFMatrix4f.identity(),globalMatrix:null,volume:new x3dom.fields.BoxVolume(),worldVolume:new x3dom.fields.BoxVolume(),center:new x3dom.fields.SFVec3f(0,0,0),coverage:-1,needCulling:true};},{fieldChanged:function(fieldName){if(this._vf.hasOwnProperty(fieldName)){this.invalidateVolume();}},nodeChanged:function(){this.invalidateVolume();},parentAdded:function(parent){this.invalidateVolume();},getVolume:function() {var vol=this._graph.volume;if(!this.volumeValid()&&this._vf.render) {for(var i=0,n=this._childNodes.length;i1)) singlePath=false;if(singlePath&&(invalidateCache=invalidateCache||this.cacheInvalid())) this.invalidateCache();planeMask=drawableCollection.cull(transform,this.graphState(),singlePath,planeMask);if(planeMask<=0){return;} var cnode,childTransform;if(singlePath){if(!this._graph.globalMatrix){this._graph.globalMatrix=this.transformMatrix(transform);} childTransform=this._graph.globalMatrix;} else{childTransform=this.transformMatrix(transform);} for(var i=0,n=this._childNodes.length;i=0&&this._vf.whichChoice1)) singlePath=false;if(singlePath&&(invalidateCache=invalidateCache||this.cacheInvalid())) this.invalidateCache();if(this._vf.whichChoice<0||this._vf.whichChoice>=this._childNodes.length||(planeMask=drawableCollection.cull(transform,this.graphState(),singlePath,planeMask))<=0){return;} var cnode,childTransform;if(singlePath){if(!this._graph.globalMatrix){this._graph.globalMatrix=this.transformMatrix(transform);} childTransform=this._graph.globalMatrix;} else{childTransform=this.transformMatrix(transform);} if((cnode=this._childNodes[this._vf.whichChoice])){cnode.collectDrawableObjects(childTransform,drawableCollection,singlePath,invalidateCache,planeMask);}},doIntersect:function(line) {if(this._vf.whichChoice<0||this._vf.whichChoice>=this._childNodes.length){return false;} var child=this._childNodes[this._vf.whichChoice];if(child){return child.doIntersect(line);} return false;}}));x3dom.registerNodeType("X3DTransformNode","Grouping",defineClass(x3dom.nodeTypes.X3DGroupingNode,function(ctx){x3dom.nodeTypes.X3DTransformNode.superClass.call(this,ctx);if(ctx) ctx.doc._nodeBag.trans.push(this);else x3dom.debug.logWarning("X3DTransformNode: No runtime context found!");this._trafo=null;this._needCssStyleUpdates=true;},{tick:function(t) {var dom=this._xmlNode;if(dom&&(dom['ontransform']||dom.hasAttribute('ontransform')||this._listeners['transform'])){var transMatrix=this.getCurrentTransform();var event={target:dom,type:'transform',worldX:transMatrix._03,worldY:transMatrix._13,worldZ:transMatrix._23,cancelBubble:false,stopPropagation:function(){this.cancelBubble=true;}};this.callEvtHandler("ontransform",event);} if(this._needCssStyleUpdates&&dom){var trans=x3dom.getStyle(dom,"-webkit-transform")||x3dom.getStyle(dom,"-moz-transform")||x3dom.getStyle(dom,"-ms-transform")||x3dom.getStyle(dom,"transform");if(trans&&(trans!='none')){this._trafo.setValueByStr(trans);this.invalidateVolume();return true;} this._needCssStyleUpdates=false;} return false;},transformMatrix:function(transform){return transform.mult(this._trafo);},getVolume:function() {var vol=this._graph.volume;if(!this.volumeValid()&&this._vf.render) {this._graph.localMatrix=this._trafo;for(var i=0,n=this._childNodes.length;i1)) singlePath=false;if(singlePath&&(invalidateCache=invalidateCache||this.cacheInvalid())) this.invalidateCache();planeMask=drawableCollection.cull(transform,this.graphState(),singlePath,planeMask);if(planeMask<=0){return;} var cnode,childTransform;if(singlePath){if(!this._graph.globalMatrix){this._graph.globalMatrix=this.transformMatrix(transform);} childTransform=this._graph.globalMatrix;} else{childTransform=this.transformMatrix(transform);} if(this.needBvhRebuild) {var drawableCollectionConfig={viewArea:drawableCollection.viewarea,sortTrans:drawableCollection.sortTrans,viewMatrix:drawableCollection.viewMatrix,projMatrix:drawableCollection.projMatrix,sceneMatrix:drawableCollection.sceneMatrix,frustumCulling:false,smallFeatureThreshold:0,context:drawableCollection.context};this.drawableCollection=new x3dom.DrawableCollection(drawableCollectionConfig);var i,n=this._childNodes.length;for(i=0;i0) {that._idList=[];var arr=x3dom.fields.MFString.parse(evt.data);var n=Math.min(arr.length,Math.abs(that._vf.maxRenderedIds));for(var i=0;i0){nodeName=nodeName.substring(0,starInd);matchNameBegin=true;} if(nodeName.length<=1) continue;if((matchNameBegin&&this._vf.label[i].indexOf(nodeName)==0)||this._vf.label[i]==nodeName){this._visibleList[i]=false;break;}}} else{this._visibleList[i]=false;}} this.invalidateVolume();} else if(fieldName=="render"){this.invalidateVolume();}},getNumRenderedObjects:function(len,isMoving) {var n=len;if(this._vf.maxRenderedIds>0) {var num=Math.max(this._vf.maxRenderedIds,16);var scale=1;if(isMoving) scale=Math.min(this._vf.scaleRenderedIdsOnMove,1);num=Math.max(Math.round(scale*num),0);n=Math.min(n,num);} return n;},collectDrawableObjects:function(transform,drawableCollection,singlePath,invalidateCache,planeMask) {if(singlePath&&(this._parentNodes.length>1)) singlePath=false;if(singlePath&&(invalidateCache=invalidateCache||this.cacheInvalid())) this.invalidateCache();planeMask=drawableCollection.cull(transform,this.graphState(),singlePath,planeMask);if(planeMask<=0){return;} var viewarea=this._nameSpace.doc._viewarea;var isMoving=viewarea.isMovingOrAnimating();var ts=new Date().getTime();var maxLiveTime=10000;var i,n,numChild=this._childNodes.length;if(!this._vf.enableCulling) {n=this.getNumRenderedObjects(numChild,isMoving);var cnt=0;for(i=0;i0&&ts-this._createTime[i]>maxLiveTime&&shape._cleanupGLObjects) {shape._cleanupGLObjects(true);this._createTime[i]=0;}}} return;} if(this._websocket) this._websocket.updateCamera();if(this._vf.label.length) {n=this.getNumRenderedObjects(this._idList.length,isMoving);for(i=0;i0&&ts-this._createTime[i]>maxLiveTime&&this._childNodes[i]._cleanupGLObjects) {this._childNodes[i]._cleanupGLObjects(true);this._createTime[i]=0;}}}}}));x3dom.registerNodeType("Scene","Grouping",defineClass(x3dom.nodeTypes.X3DGroupingNode,function(ctx){x3dom.nodeTypes.Scene.superClass.call(this,ctx);this.addField_SFString(ctx,'pickMode',"idBuf");this.addField_SFBool(ctx,'doPickPass',true);this.addField_SFString(ctx,'shadowObjectIdMapping',"");this._lastMin=new x3dom.fields.SFVec3f(0,0,0);this._lastMax=new x3dom.fields.SFVec3f(1,1,1);this._shadowIdMap=null;this.loadMapping();},{fieldChanged:function(fieldName) {if(fieldName=="shadowObjectIdMapping") this.loadMapping();},updateVolume:function() {var vol=this.getVolume();if(vol.isValid()) {this._lastMin=x3dom.fields.SFVec3f.copy(vol.min);this._lastMax=x3dom.fields.SFVec3f.copy(vol.max);}},loadMapping:function() {this._shadowIdMap=null;if(this._vf.shadowObjectIdMapping.length==0){return;} var that=this;var xhr=new XMLHttpRequest();xhr.open("GET",encodeURI(this._nameSpace.getURL(this._vf.shadowObjectIdMapping)),true);xhr.send();xhr.onload=function() {that._shadowIdMap=eval("("+xhr.response+")");if(!that._shadowIdMap||!that._shadowIdMap.mapping){x3dom.debug.logWarning("Invalid ID map: "+that._vf.shadowObjectIdMapping);} else{x3dom.debug.assert(that._shadowIdMap.maxID<=that._shadowIdMap.mapping.length,"Too few ID map entries in "+that._vf.shadowObjectIdMapping+", "+"length of mapping array is only "+that._shadowIdMap.mapping.length+" instead of "+that._shadowIdMap.ids.length+"!");}};}}));x3dom.BindableStack=function(doc,type,defaultType,getter){this._doc=doc;this._type=type;this._defaultType=defaultType;this._defaultRoot=null;this._getter=getter;this._bindBag=[];this._bindStack=[];};x3dom.BindableStack.prototype.top=function(){return((this._bindStack.length>0)?this._bindStack[this._bindStack.length-1]:null);};x3dom.BindableStack.prototype.push=function(bindable){var top=this.top();if(top===bindable){return;} if(top){top.deactivate();} this._bindStack.push(bindable);bindable.activate(top);};x3dom.BindableStack.prototype.replaceTop=function(bindable){var top=this.top();if(top===bindable){return;} if(top){top.deactivate();this._bindStack[this._bindStack.length-1]=bindable;bindable.activate(top);}};x3dom.BindableStack.prototype.pop=function(bindable){var top;if(bindable){top=this.top();if(bindable!==top){return null;}} top=this._bindStack.pop();if(top){top.deactivate();} return top;};x3dom.BindableStack.prototype.switchTo=function(target){var last=this.getActive();var n=this._bindBag.length;var toBind=0;var i=0,lastIndex=-1;if(n<=1){return;} switch(target) {case'first':toBind=this._bindBag[0];break;case'last':toBind=this._bindBag[n-1];break;default:for(i=0;i=0){i=lastIndex;while(!toBind){if(target=='next'){i=(i<(n-1))?(i+1):0;}else{i=(i>0)?(i-1):(n-1);} if(i==lastIndex){break;} if(this._bindBag[i]._vf.description.length>=0){toBind=this._bindBag[i];}}} break;} if(toBind){this.replaceTop(toBind);}else{x3dom.debug.logWarning('Cannot switch bindable; no other bindable with description found.');}};x3dom.BindableStack.prototype.getActive=function(){if(this._bindStack.length===0){if(this._bindBag.length===0){if(this._defaultRoot){x3dom.debug.logInfo('create new '+this._defaultType._typeName+' for '+this._type._typeName+'-stack');var obj=new this._defaultType({doc:this._doc,nameSpace:this._defaultRoot._nameSpace,autoGen:true});this._defaultRoot.addChild(obj);obj.nodeChanged();} else{x3dom.debug.logError('stack without defaultRoot');}} else{x3dom.debug.logInfo('activate first '+this._type._typeName+' for '+this._type._typeName+'-stack');} this._bindStack.push(this._bindBag[0]);this._bindBag[0].activate();} return this._bindStack[this._bindStack.length-1];};x3dom.BindableBag=function(doc){this._stacks=[];this.addType("X3DViewpointNode","Viewpoint","getViewpoint",doc);this.addType("X3DNavigationInfoNode","NavigationInfo","getNavigationInfo",doc);this.addType("X3DBackgroundNode","Background","getBackground",doc);this.addType("X3DFogNode","Fog","getFog",doc);this.addType("X3DEnvironmentNode","Environment","getEnvironment",doc);};x3dom.BindableBag.prototype.addType=function(typeName,defaultTypeName,getter,doc){var type=x3dom.nodeTypes[typeName];var defaultType=x3dom.nodeTypes[defaultTypeName];if(type&&defaultType){var stack=new x3dom.BindableStack(doc,type,defaultType,getter);this._stacks.push(stack);} else{x3dom.debug.logWarning('Invalid Bindable type/defaultType: '+ typeName+'/'+defaultType);}};x3dom.BindableBag.prototype.setRefNode=function(node){Array.forEach(this._stacks,function(stack){stack._defaultRoot=node;node[stack._getter]=function(){return stack.getActive();};});};x3dom.BindableBag.prototype.addBindable=function(node){for(var i=0,n=this._stacks.length;i=0;return(this._vf.lit&&hasTris);}}));x3dom.registerNodeType("Mesh","Rendering",defineClass(x3dom.nodeTypes.X3DGeometryNode,function(ctx){x3dom.nodeTypes.Mesh.superClass.call(this,ctx);this.addField_SFString(ctx,'primType',"triangle");this.addField_MFInt32(ctx,'index',[]);this.addField_MFNode('vertexAttributes',x3dom.nodeTypes.X3DVertexAttributeNode);},{nodeChanged:function() {var time0=new Date().getTime();var i,n=this._cf.vertexAttributes.nodes.length;for(i=0;i=0;j--){this._mesh._indices[0].push(cnt++,cnt);if(j==0)cnt++;}}},fieldChanged:function(fieldName){if(fieldName=="coord"){var pnts=this._cf.coord.node.getPoints();this._mesh._positions[0]=pnts.toGL();this.invalidateVolume();Array.forEach(this._parentNodes,function(node){node._dirty.positions=true;node.invalidateVolume();});} else if(fieldName=="color"){var cols=this._cf.color.node._vf.color;this._mesh._colors[0]=cols.toGL();Array.forEach(this._parentNodes,function(node){node._dirty.colors=true;});}}}));x3dom.registerNodeType("IndexedLineSet","Rendering",defineClass(x3dom.nodeTypes.X3DGeometryNode,function(ctx){x3dom.nodeTypes.IndexedLineSet.superClass.call(this,ctx);this.addField_SFBool(ctx,'colorPerVertex',true);this.addField_MFNode('attrib',x3dom.nodeTypes.X3DVertexAttributeNode);this.addField_SFNode('coord',x3dom.nodeTypes.X3DCoordinateNode);this.addField_SFNode('color',x3dom.nodeTypes.X3DColorNode);this.addField_MFInt32(ctx,'coordIndex',[]);this.addField_MFInt32(ctx,'colorIndex',[]);this._mesh._primType='LINES';x3dom.Utils.needLineWidth=true;},{nodeChanged:function() {var time0=new Date().getTime();var indexes=this._vf.coordIndex;var colorInd=this._vf.colorIndex;var hasColor=false,hasColorInd=false;var colPerVert=this._vf.colorPerVertex;if(colorInd.length>0) {hasColorInd=true;} var positions,colors;var coordNode=this._cf.coord.node;x3dom.debug.assert(coordNode);positions=coordNode.getPoints();var numColComponents=3;var colorNode=this._cf.color.node;if(colorNode) {hasColor=true;colors=colorNode._vf.color;if(x3dom.isa(colorNode,x3dom.nodeTypes.ColorRGBA)){numColComponents=4;}} else{hasColor=false;} this._mesh._indices[0]=[];this._mesh._positions[0]=[];this._mesh._colors[0]=[];var i,t,cnt,lineCnt;var p0,p1,c0,c1;if((hasColor&&hasColorInd)||positions.length>x3dom.Utils.maxIndexableCoords) {t=0;cnt=0;lineCnt=0;for(i=0;ix3dom.Utils.maxIndexableCoords) this._mesh.splitMesh(2);} else {var n=indexes.length;t=0;for(i=0;i0){positions.push(positions.length-1);} posMax=positions.length;if(!normPerVert||posMax>x3dom.Utils.maxIndexableCoords) {t=0;cnt=0;faceCnt=0;this._mesh._multiIndIndices=[];this._mesh._posSize=positions.length;for(i=0;i0)&&(i%3===0)){t=0;faceCnt++;} switch(t) {case 0:p0=+indexes[i];if(normPerVert){n0=p0;}else if(!normPerVert){n0=faceCnt;} t0=p0;if(colPerVert){c0=p0;}else if(!colPerVert){c0=faceCnt;} t=1;break;case 1:p1=+indexes[i];if(normPerVert){n1=p1;}else if(!normPerVert){n1=faceCnt;} t1=p1;if(colPerVert){c1=p1;}else if(!colPerVert){c1=faceCnt;} t=2;break;case 2:p2=+indexes[i];if(normPerVert){n2=p2;}else if(!normPerVert){n2=faceCnt;} t2=p2;if(colPerVert){c2=p2;}else if(!colPerVert){c2=faceCnt;} t=3;this._mesh._indices[0].push(cnt++,cnt++,cnt++);this._mesh._positions[0].push(positions[p0].x);this._mesh._positions[0].push(positions[p0].y);this._mesh._positions[0].push(positions[p0].z);this._mesh._positions[0].push(positions[p1].x);this._mesh._positions[0].push(positions[p1].y);this._mesh._positions[0].push(positions[p1].z);this._mesh._positions[0].push(positions[p2].x);this._mesh._positions[0].push(positions[p2].y);this._mesh._positions[0].push(positions[p2].z);if(hasNormal){this._mesh._normals[0].push(normals[n0].x);this._mesh._normals[0].push(normals[n0].y);this._mesh._normals[0].push(normals[n0].z);this._mesh._normals[0].push(normals[n1].x);this._mesh._normals[0].push(normals[n1].y);this._mesh._normals[0].push(normals[n1].z);this._mesh._normals[0].push(normals[n2].x);this._mesh._normals[0].push(normals[n2].y);this._mesh._normals[0].push(normals[n2].z);} else{this._mesh._multiIndIndices.push(p0,p1,p2);} if(hasColor){this._mesh._colors[0].push(colors[c0].r);this._mesh._colors[0].push(colors[c0].g);this._mesh._colors[0].push(colors[c0].b);if(numColComponents===4){this._mesh._colors[0].push(colors[c0].a);} this._mesh._colors[0].push(colors[c1].r);this._mesh._colors[0].push(colors[c1].g);this._mesh._colors[0].push(colors[c1].b);if(numColComponents===4){this._mesh._colors[0].push(colors[c1].a);} this._mesh._colors[0].push(colors[c2].r);this._mesh._colors[0].push(colors[c2].g);this._mesh._colors[0].push(colors[c2].b);if(numColComponents===4){this._mesh._colors[0].push(colors[c2].a);}} if(hasTexCoord){this._mesh._texCoords[0].push(texCoords[t0].x);this._mesh._texCoords[0].push(texCoords[t0].y);if(numTexComponents===3){this._mesh._texCoords[0].push(texCoords[t0].z);} this._mesh._texCoords[0].push(texCoords[t1].x);this._mesh._texCoords[0].push(texCoords[t1].y);if(numTexComponents===3){this._mesh._texCoords[0].push(texCoords[t1].z);} this._mesh._texCoords[0].push(texCoords[t2].x);this._mesh._texCoords[0].push(texCoords[t2].y);if(numTexComponents===3){this._mesh._texCoords[0].push(texCoords[t2].z);}} break;default:}} if(!hasNormal){this._mesh.calcNormals(normPerVert?Math.PI:0);} if(!hasTexCoord){this._mesh.calcTexCoords(texMode);} this._mesh.splitMesh();} else {faceCnt=0;for(i=0;i0)&&(i%3===0)){faceCnt++;} this._mesh._indices[0].push(indexes[i]);if(!normPerVert&&hasNormal){this._mesh._normals[0].push(normals[faceCnt].x);this._mesh._normals[0].push(normals[faceCnt].y);this._mesh._normals[0].push(normals[faceCnt].z);} if(!colPerVert&&hasColor){this._mesh._colors[0].push(colors[faceCnt].r);this._mesh._colors[0].push(colors[faceCnt].g);this._mesh._colors[0].push(colors[faceCnt].b);if(numColComponents===4){this._mesh._colors[0].push(colors[faceCnt].a);}}} this._mesh._positions[0]=positions.toGL();if(hasNormal){this._mesh._normals[0]=normals.toGL();} else{this._mesh.calcNormals(normPerVert?Math.PI:0);} if(hasTexCoord){this._mesh._texCoords[0]=texCoords.toGL();this._mesh._numTexComponents=numTexComponents;} else{this._mesh.calcTexCoords(texMode);} if(hasColor&&colPerVert){this._mesh._colors[0]=colors.toGL();this._mesh._numColComponents=numColComponents;}} this.invalidateVolume();this._mesh._numFaces=0;this._mesh._numCoords=0;for(i=0;ix3dom.Utils.maxIndexableCoords) {x3dom.debug.logWarning("IndexedTriangleSet: fieldChanged with "+"too many coordinates not yet implemented!");return;} if(fieldName=="coord") {this._mesh._positions[0]=pnts.toGL();this.invalidateVolume();Array.forEach(this._parentNodes,function(node){node._dirty.positions=true;node.invalidateVolume();});} else if(fieldName=="color") {pnts=this._cf.color.node._vf.color;if(this._vf.colorPerVertex){this._mesh._colors[0]=pnts.toGL();}else if(!this._vf.colorPerVertex){var faceCnt=0;var numColComponents=3;if(x3dom.isa(this._cf.color.node,x3dom.nodeTypes.ColorRGBA)){numColComponents=4;} this._mesh._colors[0]=[];var indexes=this._vf.index;for(var i=0;i0)&&(i%3===0)){faceCnt++;} this._mesh._colors[0].push(pnts[faceCnt].r);this._mesh._colors[0].push(pnts[faceCnt].g);this._mesh._colors[0].push(pnts[faceCnt].b);if(numColComponents===4){this._mesh._colors[0].push(pnts[faceCnt].a);}}} Array.forEach(this._parentNodes,function(node){node._dirty.colors=true;});} else if(fieldName=="normal") {pnts=this._cf.normal.node._vf.vector;if(this._vf.normalPerVertex){this._mesh._normals[0]=pnts.toGL();}else if(!this._vf.normalPerVertex){var indexes=this._vf.index;this._mesh._normals[0]=[];var faceCnt=0;for(var i=0;i0)&&(i%3===0)){faceCnt++;} this._mesh._normals[0].push(pnts[faceCnt].x);this._mesh._normals[0].push(pnts[faceCnt].y);this._mesh._normals[0].push(pnts[faceCnt].z);}} Array.forEach(this._parentNodes,function(node){node._dirty.normals=true;});} else if(fieldName=="texCoord") {var texCoordNode=this._cf.texCoord.node;if(x3dom.isa(texCoordNode,x3dom.nodeTypes.MultiTextureCoordinate)){if(texCoordNode._cf.texCoord.nodes.length) texCoordNode=texCoordNode._cf.texCoord.nodes[0];} pnts=texCoordNode._vf.point;this._mesh._texCoords[0]=pnts.toGL();Array.forEach(this._parentNodes,function(node){node._dirty.texcoords=true;});}}}));x3dom.registerNodeType("IndexedTriangleStripSet","Rendering",defineClass(x3dom.nodeTypes.X3DComposedGeometryNode,function(ctx){x3dom.nodeTypes.IndexedTriangleStripSet.superClass.call(this,ctx);this.addField_MFInt32(ctx,'index',[]);this._hasIndexOffset=false;this._indexOffset=null;},{hasIndexOffset:function(){return this._hasIndexOffset;},nodeChanged:function() {this.handleAttribs();var hasNormal=false,hasTexCoord=false,hasColor=false;var colPerVert=this._vf.colorPerVertex;var normPerVert=this._vf.normalPerVertex;var indexes=this._vf.index;var positions,normals,texCoords,colors;var coordNode=this._cf.coord.node;x3dom.debug.assert(coordNode);positions=coordNode._vf.point;var normalNode=this._cf.normal.node;if(normalNode){hasNormal=true;normals=normalNode._vf.vector;} else{hasNormal=false;} var texMode="",numTexComponents=2;var texCoordNode=this._cf.texCoord.node;if(x3dom.isa(texCoordNode,x3dom.nodeTypes.MultiTextureCoordinate)){if(texCoordNode._cf.texCoord.nodes.length) texCoordNode=texCoordNode._cf.texCoord.nodes[0];} if(texCoordNode){if(texCoordNode._vf.point){hasTexCoord=true;texCoords=texCoordNode._vf.point;if(x3dom.isa(texCoordNode,x3dom.nodeTypes.TextureCoordinate3D)){numTexComponents=3;}} else if(texCoordNode._vf.mode){texMode=texCoordNode._vf.mode;}} else{hasTexCoord=false;} this._mesh._numTexComponents=numTexComponents;var numColComponents=3;var colorNode=this._cf.color.node;if(colorNode){hasColor=true;colors=colorNode._vf.color;if(x3dom.isa(colorNode,x3dom.nodeTypes.ColorRGBA)){numColComponents=4;}} else{hasColor=false;} this._mesh._numColComponents=numColComponents;this._mesh._indices[0]=[];this._mesh._positions[0]=[];this._mesh._normals[0]=[];this._mesh._texCoords[0]=[];this._mesh._colors[0]=[];this.invalidateVolume();this._mesh._numFaces=0;this._mesh._numCoords=0;var faceCnt=0,cnt=0;if(hasNormal&&positions.length<=x3dom.Utils.maxIndexableCoords) {this._hasIndexOffset=true;this._indexOffset=[];this._mesh._primType='TRIANGLESTRIP';var indexOffset=[0];for(i=0;ix3dom.Utils.maxIndexableCoords)) {if(fieldName=="coord"){this._mesh._positions[0]=[];this._mesh._indices[0]=[];this._mesh._normals[0]=[];this._mesh._texCoords[0]=[];var hasNormal=false,hasTexCoord=false,hasColor=false;var colPerVert=this._vf.colorPerVertex;var normPerVert=this._vf.normalPerVertex;var indexes=this._vf.index;var positions,normals,texCoords,colors;var coordNode=this._cf.coord.node;x3dom.debug.assert(coordNode);positions=coordNode._vf.point;var normalNode=this._cf.normal.node;if(normalNode){hasNormal=true;normals=normalNode._vf.vector;} else{hasNormal=false;} var texMode="",numTexComponents=2;var texCoordNode=this._cf.texCoord.node;if(x3dom.isa(texCoordNode,x3dom.nodeTypes.MultiTextureCoordinate)){if(texCoordNode._cf.texCoord.nodes.length) texCoordNode=texCoordNode._cf.texCoord.nodes[0];} if(texCoordNode){if(texCoordNode._vf.point){hasTexCoord=true;texCoords=texCoordNode._vf.point;if(x3dom.isa(texCoordNode,x3dom.nodeTypes.TextureCoordinate3D)){numTexComponents=3;}} else if(texCoordNode._vf.mode){texMode=texCoordNode._vf.mode;}} else{hasTexCoord=false;} this._mesh._numTexComponents=numTexComponents;var numColComponents=3;var colorNode=this._cf.color.node;if(colorNode){hasColor=true;colors=colorNode._vf.color;if(x3dom.isa(colorNode,x3dom.nodeTypes.ColorRGBA)){numColComponents=4;}} else{hasColor=false;} this._mesh._numColComponents=numColComponents;this._mesh._indices[0]=[];this._mesh._positions[0]=[];this._mesh._normals[0]=[];this._mesh._texCoords[0]=[];this._mesh._colors[0]=[];var faceCnt=0,cnt=0;var p1,p2,p3,n1,n2,n3,t1,t2,t3,c1,c2,c3;var swapOrder=false;if(hasNormal||hasTexCoord||hasColor){for(var i=1;i0){this._vf.sortType='transparent';} else if(this._cf.texture.node&&this._cf.texture.node._vf.url.length){if(this._cf.texture.node._vf.url[0].toLowerCase().indexOf('.'+'png')>=0){this._vf.sortType='transparent';} else{this._vf.sortType='opaque';}} else{this._vf.sortType='opaque';}}},texTransformMatrix:function(){if(this._cf.textureTransform.node===null){return x3dom.fields.SFMatrix4f.identity();} else{return this._cf.textureTransform.node.texTransformMatrix();}},parentAdded:function(parent){if(this!=x3dom.nodeTypes.Appearance._defaultNode){parent.setAppDirty();}}}));x3dom.nodeTypes.Appearance.defaultNode=function(){if(!x3dom.nodeTypes.Appearance._defaultNode){x3dom.nodeTypes.Appearance._defaultNode=new x3dom.nodeTypes.Appearance();x3dom.nodeTypes.Appearance._defaultNode.nodeChanged();} return x3dom.nodeTypes.Appearance._defaultNode;};x3dom.registerNodeType("X3DAppearanceChildNode","Shape",defineClass(x3dom.nodeTypes.X3DNode,function(ctx){x3dom.nodeTypes.X3DAppearanceChildNode.superClass.call(this,ctx);}));x3dom.registerNodeType("BlendMode","Shape",defineClass(x3dom.nodeTypes.X3DAppearanceChildNode,function(ctx){x3dom.nodeTypes.BlendMode.superClass.call(this,ctx);this.addField_SFString(ctx,'srcFactor',"src_alpha");this.addField_SFString(ctx,'destFactor',"one_minus_src_alpha");this.addField_SFColor(ctx,'color',1,1,1);this.addField_SFFloat(ctx,'colorTransparency',0);this.addField_SFString(ctx,'alphaFunc',"none");this.addField_SFFloat(ctx,'alphaFuncValue',0);this.addField_SFString(ctx,'equation',"none");}));x3dom.registerNodeType("DepthMode","Shape",defineClass(x3dom.nodeTypes.X3DAppearanceChildNode,function(ctx){x3dom.nodeTypes.DepthMode.superClass.call(this,ctx);this.addField_SFBool(ctx,'enableDepthTest',true);this.addField_SFString(ctx,'depthFunc',"none");this.addField_SFBool(ctx,'readOnly',false);this.addField_SFFloat(ctx,'zNearRange',-1);this.addField_SFFloat(ctx,'zFarRange',-1);}));x3dom.registerNodeType("ColorMaskMode","Shape",defineClass(x3dom.nodeTypes.X3DAppearanceChildNode,function(ctx){x3dom.nodeTypes.ColorMaskMode.superClass.call(this,ctx);this.addField_SFBool(ctx,'maskR',true);this.addField_SFBool(ctx,'maskG',true);this.addField_SFBool(ctx,'maskB',true);this.addField_SFBool(ctx,'maskA',true);}));x3dom.registerNodeType("LineProperties","Shape",defineClass(x3dom.nodeTypes.X3DAppearanceChildNode,function(ctx){x3dom.nodeTypes.LineProperties.superClass.call(this,ctx);this.addField_SFBool(ctx,'applied',true);this.addField_SFInt32(ctx,'linetype',1);this.addField_SFFloat(ctx,'linewidthScaleFactor',0);}));x3dom.registerNodeType("X3DMaterialNode","Shape",defineClass(x3dom.nodeTypes.X3DAppearanceChildNode,function(ctx){x3dom.nodeTypes.X3DMaterialNode.superClass.call(this,ctx);}));x3dom.registerNodeType("Material","Shape",defineClass(x3dom.nodeTypes.X3DMaterialNode,function(ctx){x3dom.nodeTypes.Material.superClass.call(this,ctx);this.addField_SFFloat(ctx,'ambientIntensity',0.2);this.addField_SFColor(ctx,'diffuseColor',0.8,0.8,0.8);this.addField_SFColor(ctx,'emissiveColor',0,0,0);this.addField_SFFloat(ctx,'shininess',0.2);this.addField_SFColor(ctx,'specularColor',0,0,0);this.addField_SFFloat(ctx,'transparency',0);},{fieldChanged:function(fieldName){if(fieldName=="ambientIntensity"||fieldName=="diffuseColor"||fieldName=="emissiveColor"||fieldName=="shininess"||fieldName=="specularColor"||fieldName=="transparency") {Array.forEach(this._parentNodes,function(app){Array.forEach(app._parentNodes,function(shape){shape._dirty.material=true;});app.checkSortType();});}}}));x3dom.nodeTypes.Material.defaultNode=function(){if(!x3dom.nodeTypes.Material._defaultNode){x3dom.nodeTypes.Material._defaultNode=new x3dom.nodeTypes.Material();x3dom.nodeTypes.Material._defaultNode.nodeChanged();} return x3dom.nodeTypes.Material._defaultNode;};x3dom.registerNodeType("TwoSidedMaterial","Shape",defineClass(x3dom.nodeTypes.X3DMaterialNode,function(ctx){x3dom.nodeTypes.TwoSidedMaterial.superClass.call(this,ctx);this.addField_SFFloat(ctx,'backAmbientIntensity',0.2);this.addField_SFColor(ctx,'backDiffuseColor',0.8,0.8,0.8);this.addField_SFColor(ctx,'backEmissiveColor',0,0,0);this.addField_SFFloat(ctx,'backShininess',0.2);this.addField_SFColor(ctx,'backSpecularColor',0,0,0);this.addField_SFFloat(ctx,'backTransparency',0);this.addField_SFBool(ctx,'separateBackColor',false);},{fieldChanged:function(fieldName){if(fieldName=="ambientIntensity"||fieldName=="diffuseColor"||fieldName=="emissiveColor"||fieldName=="shininess"||fieldName=="specularColor"||fieldName=="transparency"||fieldName=="backAmbientIntensity"||fieldName=="backDiffuseColor"||fieldName=="backEmissiveColor"||fieldName=="backShininess"||fieldName=="backSpecularColor"||fieldName=="backTransparency"||fieldName=="separateBackColor") {Array.forEach(this._parentNodes,function(app){Array.forEach(app._parentNodes,function(shape){shape._dirty.material=true;});app.checkSortType();});}}}));x3dom.registerNodeType("X3DShapeNode","Shape",defineClass(x3dom.nodeTypes.X3DBoundedObject,function(ctx){x3dom.nodeTypes.X3DShapeNode.superClass.call(this,ctx);this.addField_SFBool(ctx,'isPickable',true);this.addField_SFNode('appearance',x3dom.nodeTypes.X3DAppearanceNode);this.addField_SFNode('geometry',x3dom.nodeTypes.X3DGeometryNode);this._objectID=0;this._shaderProperties=null;this._cleanupGLObjects=null;this._dirty={positions:true,normals:true,texcoords:true,colors:true,indexes:true,texture:true,material:true,text:true,shader:true};this._coordStrideOffset=[0,0];this._normalStrideOffset=[0,0];this._texCoordStrideOffset=[0,0];this._colorStrideOffset=[0,0];this._tessellationProperties=[];},{collectDrawableObjects:function(transform,drawableCollection,singlePath,invalidateCache,planeMask) {var graphState=this.graphState();if(singlePath&&(this._parentNodes.length>1)) singlePath=false;if(singlePath&&(invalidateCache=invalidateCache||this.cacheInvalid())) this.invalidateCache();if(!this._cf.geometry.node||drawableCollection.cull(transform,graphState,singlePath,planeMask)<=0){return false;} if(singlePath&&!this._graph.globalMatrix) this._graph.globalMatrix=transform;drawableCollection.addShape(this,transform,graphState);return true;},getVolume:function() {var vol=this._graph.volume;if(!this.volumeValid()&&this._vf.render) {var geo=this._cf.geometry.node;var childVol=geo?geo.getVolume():null;if(childVol&&childVol.isValid()) vol.extendBounds(childVol.min,childVol.max);} return vol;},getCenter:function(){var geo=this._cf.geometry.node;return(geo?geo.getCenter():new x3dom.fields.SFVec3f(0,0,0));},getDiameter:function(){var geo=this._cf.geometry.node;return(geo?geo.getDiameter():0);},doIntersect:function(line){return this._cf.geometry.node.doIntersect(line);},forceUpdateCoverage:function() {var geo=this._cf.geometry.node;return(geo?geo.forceUpdateCoverage():false);},tessellationProperties:function() {var geo=this._cf.geometry.node;if(geo&&geo._indexOffset) return geo._indexOffset;else return this._tessellationProperties;},isLit:function(){return this._cf.geometry.node._vf.lit;},isSolid:function(){return this._cf.geometry.node._vf.solid;},isCCW:function(){return this._cf.geometry.node._vf.ccw;},parentRemoved:function(parent){for(var i=0,n=this._childNodes.length;i0) this.invalidateVolume();if(this._cleanupGLObjects){this._cleanupGLObjects();}},unsetDirty:function(){this._dirty.positions=false;this._dirty.normals=false;this._dirty.texcoords=false;this._dirty.colors=false;this._dirty.indexes=false;this._dirty.texture=false;this._dirty.material=false;this._dirty.text=false;this._dirty.shader=false;},unsetGeoDirty:function(){this._dirty.positions=false;this._dirty.normals=false;this._dirty.texcoords=false;this._dirty.colors=false;this._dirty.indexes=false;},setAllDirty:function(){this._dirty.positions=true;this._dirty.normals=true;this._dirty.texcoords=true;this._dirty.colors=true;this._dirty.indexes=true;this._dirty.texture=true;this._dirty.material=true;this._dirty.text=true;this._dirty.shader=true;this.invalidateVolume();},setAppDirty:function(){this._dirty.texture=true;this._dirty.material=true;this._dirty.shader=true;},setGeoDirty:function(){this._dirty.positions=true;this._dirty.normals=true;this._dirty.texcoords=true;this._dirty.colors=true;this._dirty.indexes=true;this.invalidateVolume();},getShaderProperties:function(viewarea) {if(this._shaderProperties==null||this._dirty.shader==true||(this._webgl!==undefined&&this._webgl.dirtyLighting!=x3dom.Utils.checkDirtyLighting(viewarea))||x3dom.Utils.checkDirtyEnvironment(viewarea,this._shaderProperties)==true) {this._shaderProperties=x3dom.Utils.generateProperties(viewarea,this);this._dirty.shader=false;if(this._webgl!==undefined) {this._webgl.dirtyLighting=x3dom.Utils.checkDirtyLighting(viewarea);}} return this._shaderProperties;},getTextures:function(){var textures=[];var appearance=this._cf.appearance.node;if(appearance){var tex=appearance._cf.texture.node;if(tex){if(x3dom.isa(tex,x3dom.nodeTypes.MultiTexture)){textures=textures.concat(tex.getTextures());} else{textures.push(tex);}} var shader=appearance._cf.shaders.nodes[0];if(shader){if(x3dom.isa(shader,x3dom.nodeTypes.CommonSurfaceShader)){textures=textures.concat(shader.getTextures());}}} var geometry=this._cf.geometry.node;if(geometry){if(x3dom.isa(geometry,x3dom.nodeTypes.ImageGeometry)){textures=textures.concat(geometry.getTextures());} else if(x3dom.isa(geometry,x3dom.nodeTypes.Text)){textures=textures.concat(geometry);}} return textures;}}));x3dom.registerNodeType("Shape","Shape",defineClass(x3dom.nodeTypes.X3DShapeNode,function(ctx){x3dom.nodeTypes.Shape.superClass.call(this,ctx);},{nodeChanged:function(){if(!this._cf.appearance.node){} if(!this._cf.geometry.node){if(this._DEF) x3dom.debug.logError("No geometry given in Shape/"+this._DEF);} else if(!this._objectID){this._objectID=++x3dom.nodeTypes.Shape.objectID;x3dom.nodeTypes.Shape.idMap.nodeID[this._objectID]=this;} this.invalidateVolume();}}));x3dom.nodeTypes.Shape.shaderPartID=0;x3dom.nodeTypes.Shape.objectID=0;x3dom.nodeTypes.Shape.idMap={nodeID:{},remove:function(obj){for(var prop in this.nodeID){if(this.nodeID.hasOwnProperty(prop)){var val=this.nodeID[prop];if(val._objectID&&obj._objectID&&val._objectID===obj._objectID) {delete this.nodeID[prop];x3dom.debug.logInfo("Unreg "+val._objectID);}}}}};x3dom.registerNodeType("X3DLightNode","Lighting",defineClass(x3dom.nodeTypes.X3DChildNode,function(ctx){x3dom.nodeTypes.X3DLightNode.superClass.call(this,ctx);if(ctx) ctx.doc._nodeBag.lights.push(this);else x3dom.debug.logWarning("X3DLightNode: No runtime context found!");this._lightID=0;this._dirty=true;this.addField_SFFloat(ctx,'ambientIntensity',0);this.addField_SFColor(ctx,'color',1,1,1);this.addField_SFFloat(ctx,'intensity',1);this.addField_SFBool(ctx,'global',false);this.addField_SFBool(ctx,'on',true);this.addField_SFFloat(ctx,'shadowIntensity',0);this.addField_SFInt32(ctx,'shadowMapSize',1024);this.addField_SFInt32(ctx,'shadowFilterSize',0);this.addField_SFFloat(ctx,'shadowOffset',0);this.addField_SFFloat(ctx,'zFar',-1);},{getViewMatrix:function(vec){return x3dom.fields.SFMatrix4f.identity;},nodeChanged:function(){if(!this._lightID){this._lightID=++x3dom.nodeTypes.X3DLightNode.lightID;}},fieldChanged:function(fieldName) {if(this._vf.hasOwnProperty(fieldName)){this._dirty=true;}},parentRemoved:function(parent) {if(this._parentNodes.length===0){var doc=this.findX3DDoc();for(var i=0,n=doc._nodeBag.lights.length;i=this._vf.duration){return 1;} return this.stepResponseCore(t/this._vf.duration);},stepResponseCore:function(T) {return 0.5-0.5*Math.cos(T*Math.PI);}}));x3dom.registerNodeType("X3DChaserNode","Followers",defineClass(x3dom.nodeTypes.X3DFollowerNode,function(ctx){x3dom.nodeTypes.X3DChaserNode.superClass.call(this,ctx);this.addField_SFTime(ctx,'duration',1);this._initDone=false;this._stepTime=0;this._currTime=0;this._bufferEndTime=0;this._numSupports=60;}));x3dom.registerNodeType("X3DDamperNode","Followers",defineClass(x3dom.nodeTypes.X3DFollowerNode,function(ctx){x3dom.nodeTypes.X3DDamperNode.superClass.call(this,ctx);this.addField_SFTime(ctx,'tau',0.3);this.addField_SFFloat(ctx,'tolerance',-1);this.addField_SFInt32(ctx,'order',3);this._eps=this._vf.tolerance<0?this._eps:this._vf.tolerance;this._lastTick=0;}));x3dom.registerNodeType("ColorChaser","Followers",defineClass(x3dom.nodeTypes.X3DChaserNode,function(ctx){x3dom.nodeTypes.ColorChaser.superClass.call(this,ctx);this.addField_SFColor(ctx,'initialDestination',0.8,0.8,0.8);this.addField_SFColor(ctx,'initialValue',0.8,0.8,0.8);this.addField_SFColor(ctx,'value',0,0,0);this.addField_SFColor(ctx,'destination',0,0,0);this._buffer=new x3dom.fields.MFColor();this._previousValue=new x3dom.fields.SFColor(0,0,0);this._value=new x3dom.fields.SFColor(0,0,0);this.initialize();},{fieldChanged:function(fieldName) {if(fieldName.indexOf("destination")>=0) {this.initialize();this.updateBuffer(this._currTime);if(!this._vf.isActive){this.postMessage('isActive',true);}} else if(fieldName.indexOf("value")>=0) {this.initialize();this._previousValue.setValues(this._vf.value);for(var C=1;C=0;C--) {DeltaIn=this._buffer[C].subtract(this._buffer[C+1]);DeltaOut=DeltaIn.multiply(this.stepResponse((C+Frac)*this._stepTime));Output=Output.add(DeltaOut);} if(!Output.equals(this._value,this._eps)){this._value.setValues(Output);this.postMessage('value',this._value);} else{this.postMessage('isActive',false);} return this._vf.isActive;},updateBuffer:function(now) {var Frac=(now-this._bufferEndTime)/this._stepTime;var C;var NumToShift;var Alpha;if(Frac>=1) {NumToShift=Math.floor(Frac);Frac-=NumToShift;if(NumToShift=NumToShift;C--){this._buffer[C]=this._buffer[C-NumToShift];} for(C=0;C=0) {if(!this._value0.equals(this._vf.destination,this._eps)){this._value0=this._vf.destination;if(!this._vf.isActive){this.postMessage('isActive',true);}}} else if(fieldName.indexOf("value")>=0) {this._value1.setValues(this._vf.value);this._value2.setValues(this._vf.value);this._value3.setValues(this._vf.value);this._value4.setValues(this._vf.value);this._value5.setValues(this._vf.value);this._lastTick=0;this.postMessage('value',this._value5);if(!this._vf.isActive){this._lastTick=0;this.postMessage('isActive',true);}}},initialize:function() {this._value0.setValues(this._vf.initialDestination);this._value1.setValues(this._vf.initialValue);this._value2.setValues(this._vf.initialValue);this._value3.setValues(this._vf.initialValue);this._value4.setValues(this._vf.initialValue);this._value5.setValues(this._vf.initialValue);this._lastTick=0;var active=!this._value0.equals(this._value1,this._eps);if(this._vf.isActive!==active){this.postMessage('isActive',active);}},distance:function(a,b) {var diff=a.subtract(b);return Math.sqrt(diff.r*diff.r+diff.g*diff.g+diff.b*diff.b);},tick:function(now) {if(!this._lastTick) {this._lastTick=now;return false;} var delta=now-this._lastTick;var alpha=Math.exp(-delta/this._vf.tau);this._value1=this._vf.order>0&&this._vf.tau?this._value0.add(this._value1.subtract(this._value0).multiply(alpha)):new x3dom.fields.SFColor(this._value0.r,this._value0.g,this._value0.b);this._value2=this._vf.order>1&&this._vf.tau?this._value1.add(this._value2.subtract(this._value1).multiply(alpha)):new x3dom.fields.SFColor(this._value1.r,this._value1.g,this._value1.b);this._value3=this._vf.order>2&&this._vf.tau?this._value2.add(this._value3.subtract(this._value2).multiply(alpha)):new x3dom.fields.SFColor(this._value2.r,this._value2.g,this._value2.b);this._value4=this._vf.order>3&&this._vf.tau?this._value3.add(this._value4.subtract(this._value3).multiply(alpha)):new x3dom.fields.SFColor(this._value3.r,this._value3.g,this._value3.b);this._value5=this._vf.order>4&&this._vf.tau?this._value4.add(this._value5.subtract(this._value4).multiply(alpha)):new x3dom.fields.SFColor(this._value4.r,this._value4.g,this._value4.b);var dist=this.distance(this._value1,this._value0);if(this._vf.order>1) {var dist2=this.distance(this._value2,this._value1);if(dist2>dist){dist=dist2;}} if(this._vf.order>2) {var dist3=this.distance(this._value3,this._value2);if(dist3>dist){dist=dist3;}} if(this._vf.order>3) {var dist4=this.distance(this._value4,this._value3);if(dist4>dist){dist=dist4;}} if(this._vf.order>4) {var dist5=this.distance(this._value5,this._value4);if(dist5>dist){dist=dist5;}} if(dist<=this._eps) {this._value1.setValues(this._value0);this._value2.setValues(this._value0);this._value3.setValues(this._value0);this._value4.setValues(this._value0);this._value5.setValues(this._value0);this.postMessage('value',this._value0);this.postMessage('isActive',false);this._lastTick=0;return false;} this.postMessage('value',this._value5);this._lastTick=now;return true;}}));x3dom.registerNodeType("OrientationChaser","Followers",defineClass(x3dom.nodeTypes.X3DChaserNode,function(ctx){x3dom.nodeTypes.OrientationChaser.superClass.call(this,ctx);this.addField_SFRotation(ctx,'initialDestination',0,1,0,0);this.addField_SFRotation(ctx,'initialValue',0,1,0,0);this.addField_SFRotation(ctx,'value',0,1,0,0);this.addField_SFRotation(ctx,'destination',0,1,0,0);this._numSupports=30;this._buffer=new x3dom.fields.MFRotation();this._previousValue=new x3dom.fields.Quaternion(0,1,0,0);this._value=new x3dom.fields.Quaternion(0,1,0,0);this.initialize();},{fieldChanged:function(fieldName) {if(fieldName.indexOf("destination")>=0) {this.initialize();this.updateBuffer(this._currTime);if(!this._vf.isActive){this.postMessage('isActive',true);}} else if(fieldName.indexOf("value")>=0) {this.initialize();this._previousValue.setValues(this._vf.value);for(var C=1;C=0;C--) {DeltaIn=this._buffer[C+1].inverse().multiply(this._buffer[C]);Output=Output.slerp(Output.multiply(DeltaIn),this.stepResponse((C+Frac)*this._stepTime));} if(!Output.equals(this._value,this._eps)){Output=Output.normalize(Output);this._value.setValues(Output);this.postMessage('value',this._value);} else{this.postMessage('isActive',false);} return this._vf.isActive;},updateBuffer:function(now) {var Frac=(now-this._bufferEndTime)/this._stepTime;var C;var NumToShift;var Alpha;if(Frac>=1) {NumToShift=Math.floor(Frac);Frac-=NumToShift;if(NumToShift=NumToShift;C--){this._buffer[C]=x3dom.fields.Quaternion.copy(this._buffer[C-NumToShift]);} for(C=0;C=0) {if(!this._value0.equals(this._vf.destination,this._eps)){this._value0=this._vf.destination;if(!this._vf.isActive){this.postMessage('isActive',true);}}} else if(fieldName.indexOf("value")>=0) {this._value1.setValues(this._vf.value);this._value2.setValues(this._vf.value);this._value3.setValues(this._vf.value);this._value4.setValues(this._vf.value);this._value5.setValues(this._vf.value);this._lastTick=0;this.postMessage('value',this._value5);if(!this._vf.isActive){this._lastTick=0;this.postMessage('isActive',true);}}},initialize:function() {this._value0.setValues(this._vf.initialDestination);this._value1.setValues(this._vf.initialValue);this._value2.setValues(this._vf.initialValue);this._value3.setValues(this._vf.initialValue);this._value4.setValues(this._vf.initialValue);this._value5.setValues(this._vf.initialValue);this._lastTick=0;var active=!this._value0.equals(this._value1,this._eps);if(this._vf.isActive!==active){this.postMessage('isActive',active);}},tick:function(now) {if(!this._lastTick) {this._lastTick=now;return false;} var delta=now-this._lastTick;var alpha=Math.exp(-delta/this._vf.tau);this._value1=this._vf.order>0&&this._vf.tau?this._value0.slerp(this._value1,alpha):new x3dom.fields.Quaternion(this._value0.x,this._value0.y,this._value0.z,this._value0.w);this._value2=this._vf.order>1&&this._vf.tau?this._value1.slerp(this._value2,alpha):new x3dom.fields.Quaternion(this._value1.x,this._value1.y,this._value1.z,this._value1.w);this._value3=this._vf.order>2&&this._vf.tau?this._value2.slerp(this._value3,alpha):new x3dom.fields.Quaternion(this._value2.x,this._value2.y,this._value2.z,this._value2.w);this._value4=this._vf.order>3&&this._vf.tau?this._value3.slerp(this._value4,alpha):new x3dom.fields.Quaternion(this._value3.x,this._value3.y,this._value3.z,this._value3.w);this._value5=this._vf.order>4&&this._vf.tau?this._value4.slerp(this._value5,alpha):new x3dom.fields.Quaternion(this._value4.x,this._value4.y,this._value4.z,this._value4.w);var dist=Math.abs(this._value1.inverse().multiply(this._value0).angle());if(this._vf.order>1) {var dist2=Math.abs(this._value2.inverse().multiply(this._value1).angle());if(dist2>dist){dist=dist2;}} if(this._vf.order>2) {var dist3=Math.abs(this._value3.inverse().multiply(this._value2).angle());if(dist3>dist){dist=dist3;}} if(this._vf.order>3) {var dist4=Math.abs(this._value4.inverse().multiply(this._value3).angle());if(dist4>dist){dist=dist4;}} if(this._vf.order>4) {var dist5=Math.abs(this._value5.inverse().multiply(this._value4).angle());if(dist5>dist){dist=dist5;}} if(dist<=this._eps) {this._value1.setValues(this._value0);this._value2.setValues(this._value0);this._value3.setValues(this._value0);this._value4.setValues(this._value0);this._value5.setValues(this._value0);this.postMessage('value',this._value0);this.postMessage('isActive',false);this._lastTick=0;return false;} this.postMessage('value',this._value5);this._lastTick=now;return true;}}));x3dom.registerNodeType("PositionChaser","Followers",defineClass(x3dom.nodeTypes.X3DChaserNode,function(ctx){x3dom.nodeTypes.PositionChaser.superClass.call(this,ctx);this.addField_SFVec3f(ctx,'initialDestination',0,0,0);this.addField_SFVec3f(ctx,'initialValue',0,0,0);this.addField_SFVec3f(ctx,'value',0,0,0);this.addField_SFVec3f(ctx,'destination',0,0,0);this._buffer=new x3dom.fields.MFVec3f();this._previousValue=new x3dom.fields.SFVec3f(0,0,0);this._value=new x3dom.fields.SFVec3f(0,0,0);this.initialize();},{fieldChanged:function(fieldName) {if(fieldName.indexOf("destination")>=0) {this.initialize();this.updateBuffer(this._currTime);if(!this._vf.isActive){this.postMessage('isActive',true);}} else if(fieldName.indexOf("value")>=0) {this.initialize();this._previousValue.setValues(this._vf.value);for(var C=1;C=0;C--) {DeltaIn=this._buffer[C].subtract(this._buffer[C+1]);DeltaOut=DeltaIn.multiply(this.stepResponse((C+Frac)*this._stepTime));Output=Output.add(DeltaOut);} if(!Output.equals(this._value,this._eps)){this._value.setValues(Output);this.postMessage('value',this._value);} else{this.postMessage('isActive',false);} return this._vf.isActive;},updateBuffer:function(now) {var Frac=(now-this._bufferEndTime)/this._stepTime;var C;var NumToShift;var Alpha;if(Frac>=1) {NumToShift=Math.floor(Frac);Frac-=NumToShift;if(NumToShift=NumToShift;C--){this._buffer[C]=x3dom.fields.SFVec3f.copy(this._buffer[C-NumToShift]);} for(C=0;C=0) {this.initialize();this.updateBuffer(this._currTime);if(!this._vf.isActive){this.postMessage('isActive',true);}} else if(fieldName.indexOf("value")>=0) {this.initialize();this._previousValue.setValues(this._vf.value);for(var C=1;C=0;C--) {DeltaIn=this._buffer[C].subtract(this._buffer[C+1]);DeltaOut=DeltaIn.multiply(this.stepResponse((C+Frac)*this._stepTime));Output=Output.add(DeltaOut);} if(!Output.equals(this._value,this._eps)){this._value.setValues(Output);this.postMessage('value',this._value);} else{this.postMessage('isActive',false);} return this._vf.isActive;},updateBuffer:function(now) {var Frac=(now-this._bufferEndTime)/this._stepTime;var C;var NumToShift;var Alpha;if(Frac>=1) {NumToShift=Math.floor(Frac);Frac-=NumToShift;if(NumToShift=NumToShift;C--){this._buffer[C]=x3dom.fields.SFVec2f.copy(this._buffer[C-NumToShift]);} for(C=0;C=0) {if(!this._value0.equals(this._vf.destination,this._eps)){this._value0=this._vf.destination;if(!this._vf.isActive){this.postMessage('isActive',true);}}} else if(fieldName.indexOf("value")>=0) {this._value1.setValues(this._vf.value);this._value2.setValues(this._vf.value);this._value3.setValues(this._vf.value);this._value4.setValues(this._vf.value);this._value5.setValues(this._vf.value);this._lastTick=0;this.postMessage('value',this._value5);if(!this._vf.isActive){this._lastTick=0;this.postMessage('isActive',true);}}},initialize:function() {this._value0.setValues(this._vf.initialDestination);this._value1.setValues(this._vf.initialValue);this._value2.setValues(this._vf.initialValue);this._value3.setValues(this._vf.initialValue);this._value4.setValues(this._vf.initialValue);this._value5.setValues(this._vf.initialValue);this._lastTick=0;var active=!this._value0.equals(this._value1,this._eps);if(this._vf.isActive!==active){this.postMessage('isActive',active);}},tick:function(now) {if(!this._lastTick) {this._lastTick=now;return false;} var delta=now-this._lastTick;var alpha=Math.exp(-delta/this._vf.tau);this._value1=this._vf.order>0&&this._vf.tau?this._value0.add(this._value1.subtract(this._value0).multiply(alpha)):new x3dom.fields.SFVec3f(this._value0.x,this._value0.y,this._value0.z);this._value2=this._vf.order>1&&this._vf.tau?this._value1.add(this._value2.subtract(this._value1).multiply(alpha)):new x3dom.fields.SFVec3f(this._value1.x,this._value1.y,this._value1.z);this._value3=this._vf.order>2&&this._vf.tau?this._value2.add(this._value3.subtract(this._value2).multiply(alpha)):new x3dom.fields.SFVec3f(this._value2.x,this._value2.y,this._value2.z);this._value4=this._vf.order>3&&this._vf.tau?this._value3.add(this._value4.subtract(this._value3).multiply(alpha)):new x3dom.fields.SFVec3f(this._value3.x,this._value3.y,this._value3.z);this._value5=this._vf.order>4&&this._vf.tau?this._value4.add(this._value5.subtract(this._value4).multiply(alpha)):new x3dom.fields.SFVec3f(this._value4.x,this._value4.y,this._value4.z);var dist=this._value1.subtract(this._value0).length();if(this._vf.order>1) {var dist2=this._value2.subtract(this._value1).length();if(dist2>dist){dist=dist2;}} if(this._vf.order>2) {var dist3=this._value3.subtract(this._value2).length();if(dist3>dist){dist=dist3;}} if(this._vf.order>3) {var dist4=this._value4.subtract(this._value3).length();if(dist4>dist){dist=dist4;}} if(this._vf.order>4) {var dist5=this._value5.subtract(this._value4).length();if(dist5>dist){dist=dist5;}} if(dist<=this._eps) {this._value1.setValues(this._value0);this._value2.setValues(this._value0);this._value3.setValues(this._value0);this._value4.setValues(this._value0);this._value5.setValues(this._value0);this.postMessage('value',this._value0);this.postMessage('isActive',false);this._lastTick=0;return false;} this.postMessage('value',this._value5);this._lastTick=now;return true;}}));x3dom.registerNodeType("PositionDamper2D","Followers",defineClass(x3dom.nodeTypes.X3DDamperNode,function(ctx){x3dom.nodeTypes.PositionDamper2D.superClass.call(this,ctx);this.addField_SFVec2f(ctx,'initialDestination',0,0);this.addField_SFVec2f(ctx,'initialValue',0,0);this.addField_SFVec2f(ctx,'value',0,0);this.addField_SFVec2f(ctx,'destination',0,0);this._value0=new x3dom.fields.SFVec2f(0,0);this._value1=new x3dom.fields.SFVec2f(0,0);this._value2=new x3dom.fields.SFVec2f(0,0);this._value3=new x3dom.fields.SFVec2f(0,0);this._value4=new x3dom.fields.SFVec2f(0,0);this._value5=new x3dom.fields.SFVec2f(0,0);this.initialize();},{fieldChanged:function(fieldName) {if(fieldName==="tolerance") {this._eps=this._vf.tolerance<0?0.001:this._vf.tolerance;} else if(fieldName.indexOf("destination")>=0) {if(!this._value0.equals(this._vf.destination,this._eps)){this._value0=this._vf.destination;if(!this._vf.isActive){this.postMessage('isActive',true);}}} else if(fieldName.indexOf("value")>=0) {this._value1.setValues(this._vf.value);this._value2.setValues(this._vf.value);this._value3.setValues(this._vf.value);this._value4.setValues(this._vf.value);this._value5.setValues(this._vf.value);this._lastTick=0;this.postMessage('value',this._value5);if(!this._vf.isActive){this._lastTick=0;this.postMessage('isActive',true);}}},initialize:function() {this._value0.setValues(this._vf.initialDestination);this._value1.setValues(this._vf.initialValue);this._value2.setValues(this._vf.initialValue);this._value3.setValues(this._vf.initialValue);this._value4.setValues(this._vf.initialValue);this._value5.setValues(this._vf.initialValue);this._lastTick=0;var active=!this._value0.equals(this._value1,this._eps);if(this._vf.isActive!==active){this.postMessage('isActive',active);}},tick:function(now) {if(!this._lastTick) {this._lastTick=now;return false;} var delta=now-this._lastTick;var alpha=Math.exp(-delta/this._vf.tau);this._value1=this._vf.order>0&&this._vf.tau?this._value0.add(this._value1.subtract(this._value0).multiply(alpha)):new x3dom.fields.SFVec2f(this._value0.x,this._value0.y,this._value0.z);this._value2=this._vf.order>1&&this._vf.tau?this._value1.add(this._value2.subtract(this._value1).multiply(alpha)):new x3dom.fields.SFVec2f(this._value1.x,this._value1.y,this._value1.z);this._value3=this._vf.order>2&&this._vf.tau?this._value2.add(this._value3.subtract(this._value2).multiply(alpha)):new x3dom.fields.SFVec2f(this._value2.x,this._value2.y,this._value2.z);this._value4=this._vf.order>3&&this._vf.tau?this._value3.add(this._value4.subtract(this._value3).multiply(alpha)):new x3dom.fields.SFVec2f(this._value3.x,this._value3.y,this._value3.z);this._value5=this._vf.order>4&&this._vf.tau?this._value4.add(this._value5.subtract(this._value4).multiply(alpha)):new x3dom.fields.SFVec2f(this._value4.x,this._value4.y,this._value4.z);var dist=this._value1.subtract(this._value0).length();if(this._vf.order>1) {var dist2=this._value2.subtract(this._value1).length();if(dist2>dist){dist=dist2;}} if(this._vf.order>2) {var dist3=this._value3.subtract(this._value2).length();if(dist3>dist){dist=dist3;}} if(this._vf.order>3) {var dist4=this._value4.subtract(this._value3).length();if(dist4>dist){dist=dist4;}} if(this._vf.order>4) {var dist5=this._value5.subtract(this._value4).length();if(dist5>dist){dist=dist5;}} if(dist<=this._eps) {this._value1.setValues(this._value0);this._value2.setValues(this._value0);this._value3.setValues(this._value0);this._value4.setValues(this._value0);this._value5.setValues(this._value0);this.postMessage('value',this._value0);this.postMessage('isActive',false);this._lastTick=0;return false;} this.postMessage('value',this._value5);this._lastTick=now;return true;}}));x3dom.registerNodeType("ScalarChaser","Followers",defineClass(x3dom.nodeTypes.X3DChaserNode,function(ctx){x3dom.nodeTypes.ScalarChaser.superClass.call(this,ctx);this.addField_SFFloat(ctx,'initialDestination',0);this.addField_SFFloat(ctx,'initialValue',0);this.addField_SFFloat(ctx,'value',0);this.addField_SFFloat(ctx,'destination',0);this._buffer=[];this._previousValue=0;this._value=0;this.initialize();},{fieldChanged:function(fieldName) {if(fieldName.indexOf("destination")>=0) {this.initialize();this.updateBuffer(this._currTime);if(!this._vf.isActive){this.postMessage('isActive',true);}} else if(fieldName.indexOf("value")>=0) {this.initialize();this._previousValue=this._vf.value;for(var C=1;Cthis._eps);if(this._vf.isActive!==active){this.postMessage('isActive',active);}}},tick:function(now) {this.initialize();this._currTime=now;if(!this._bufferEndTime) {this._bufferEndTime=now;this._value=this._vf.initialValue;this.postMessage('value',this._value);return true;} var Frac=this.updateBuffer(now);var Output=this._previousValue;var DeltaIn=this._buffer[this._buffer.length-1]-this._previousValue;var DeltaOut=DeltaIn*(this.stepResponse((this._buffer.length-1+Frac)*this._stepTime));Output=Output+DeltaOut;for(var C=this._buffer.length-2;C>=0;C--) {DeltaIn=this._buffer[C]-this._buffer[C+1];DeltaOut=DeltaIn*(this.stepResponse((C+Frac)*this._stepTime));Output=Output+DeltaOut;} if(Math.abs(Output-this._value)>this._eps){this._value=Output;this.postMessage('value',this._value);} else{this.postMessage('isActive',false);} return this._vf.isActive;},updateBuffer:function(now) {var Frac=(now-this._bufferEndTime)/this._stepTime;var C;var NumToShift;var Alpha;if(Frac>=1) {NumToShift=Math.floor(Frac);Frac-=NumToShift;if(NumToShift=NumToShift;C--){this._buffer[C]=this._buffer[C-NumToShift];} for(C=0;C=0) {if(Math.abs(this._value0-this._vf.destination)>this._eps){this._value0=this._vf.destination;if(!this._vf.isActive){this.postMessage('isActive',true);}}} else if(fieldName.indexOf("value")>=0) {this._value1=this._vf.value;this._value2=this._vf.value;this._value3=this._vf.value;this._value4=this._vf.value;this._value5=this._vf.value;this._lastTick=0;this.postMessage('value',this._value5);if(!this._vf.isActive){this._lastTick=0;this.postMessage('isActive',true);}}},initialize:function() {this._value0=this._vf.initialDestination;this._value1=this._vf.initialValue;this._value2=this._vf.initialValue;this._value3=this._vf.initialValue;this._value4=this._vf.initialValue;this._value5=this._vf.initialValue;this._lastTick=0;var active=(Math.abs(this._value0-this._value1)>this._eps);if(this._vf.isActive!==active){this.postMessage('isActive',active);}},tick:function(now) {if(!this._lastTick) {this._lastTick=now;return false;} var delta=now-this._lastTick;var alpha=Math.exp(-delta/this._vf.tau);this._value1=this._vf.order>0&&this._vf.tau?this._value0+alpha*(this._value1-this._value0):this._value0;this._value2=this._vf.order>1&&this._vf.tau?this._value1+alpha*(this._value2-this._value1):this._value1;this._value3=this._vf.order>2&&this._vf.tau?this._value2+alpha*(this._value3-this._value2):this._value2;this._value4=this._vf.order>3&&this._vf.tau?this._value3+alpha*(this._value4-this._value3):this._value3;this._value5=this._vf.order>4&&this._vf.tau?this._value4+alpha*(this._value5-this._value4):this._value4;var dist=Math.abs(this._value1-this._value0);if(this._vf.order>1) {var dist2=Math.abs(this._value2-this._value1);if(dist2>dist){dist=dist2;}} if(this._vf.order>2) {var dist3=Math.abs(this._value3-this._value2);if(dist3>dist){dist=dist3;}} if(this._vf.order>3) {var dist4=Math.abs(this._value4-this._value3);if(dist4>dist){dist=dist4;}} if(this._vf.order>4) {var dist5=Math.abs(this._value5-this._value4);if(dist5>dist){dist=dist5;}} if(dist<=this._eps) {this._value1=this._value0;this._value2=this._value0;this._value3=this._value0;this._value4=this._value0;this._value5=this._value0;this.postMessage('value',this._value0);this.postMessage('isActive',false);this._lastTick=0;return false;} this.postMessage('value',this._value5);this._lastTick=now;return true;}}));x3dom.registerNodeType("CoordinateDamper","Followers",defineClass(x3dom.nodeTypes.X3DDamperNode,function(ctx){x3dom.nodeTypes.CoordinateDamper.superClass.call(this,ctx);this.addField_MFVec3f(ctx,'initialDestination',[]);this.addField_MFVec3f(ctx,'initialValue',[]);this.addField_MFVec3f(ctx,'value',[]);this.addField_MFVec3f(ctx,'destination',[]);x3dom.debug.logWarning("CoordinateDamper NYI");}));x3dom.registerNodeType("TexCoordDamper2D","Followers",defineClass(x3dom.nodeTypes.X3DDamperNode,function(ctx){x3dom.nodeTypes.TexCoordDamper2D.superClass.call(this,ctx);this.addField_MFVec2f(ctx,'initialDestination',[]);this.addField_MFVec2f(ctx,'initialValue',[]);this.addField_MFVec2f(ctx,'value',[]);this.addField_MFVec2f(ctx,'destination',[]);x3dom.debug.logWarning("TexCoordDamper2D NYI");}));x3dom.registerNodeType("X3DInterpolatorNode","Interpolation",defineClass(x3dom.nodeTypes.X3DChildNode,function(ctx){x3dom.nodeTypes.X3DInterpolatorNode.superClass.call(this,ctx);this.addField_MFFloat(ctx,'key',[]);this.addField_SFFloat(ctx,'set_fraction',0);},{linearInterp:function(time,interp){if(time<=this._vf.key[0]) return this._vf.keyValue[0];else if(time>=this._vf.key[this._vf.key.length-1]) return this._vf.keyValue[this._vf.key.length-1];for(var i=0;i0?this._vf.key.length:1;var len=arr.length/key;for(var i=0;i0){this._updateCycleStopTime();} this._backupStartTime=this._vf.startTime;this._backupStopTime=this._vf.stopTime;this._backupCycleInterval=this._vf.cycleInterval;},{tick:function(time) {if(!this._vf.enabled){this._lastTime=time;return false;} var isActive=(this._vf.cycleInterval>0&&time>=this._vf.startTime&&(time=this._vf.pauseTime&&this._vf.pauseTime>this._vf.resumeTime);if(isPaused&&!this._vf.isPaused){this.postMessage('isPaused',true);this.postMessage('pauseTime',time);}else if(!isPaused&&this._vf.isPaused){this.postMessage('isPaused',false);this.postMessage('resumeTime',time);} if(!isPaused){var cycleFrac=this._getCycleAt(time);var cycle=Math.floor(cycleFrac);var cycleTime=this._vf.startTime+cycle*this._vf.cycleInterval;var adjustTime=0;if(this._vf.stopTime>this._vf.startTime&&this._lastTime=this._vf.stopTime) adjustTime=this._vf.stopTime;else if(this._lastTime=cycleTime) adjustTime=cycleTime;if(adjustTime>0){time=adjustTime;cycleFrac=this._getCycleAt(time);cycle=Math.floor(cycleFrac);} var fraction=cycleFrac-cycle;if(fraction=0) anchor=url.slice(aPos+1);var param=this._vf.parameter.length?this._vf.parameter[0]:"";var tPos=param.search("target=");var target="";if(tPos>=0) target=param.slice(tPos+7);x3dom.debug.logInfo("Anchor url="+url+", target="+target+", #viewpoint="+anchor);if(target.length==0||target=="_blank"){window.open(this._nameSpace.getURL(url),target);} else{window.location=this._nameSpace.getURL(url);}}}));x3dom.registerNodeType("Inline","Networking",defineClass(x3dom.nodeTypes.X3DGroupingNode,function(ctx){x3dom.nodeTypes.Inline.superClass.call(this,ctx);this.addField_MFString(ctx,'url',[]);this.addField_SFBool(ctx,'load',true);this.addField_MFString(ctx,'nameSpaceName',[]);this.addField_SFBool(ctx,'mapDEFToID',false);this.initDone=false;this.count=0;this.numRetries=x3dom.nodeTypes.Inline.MaximumRetries;},{fieldChanged:function(fieldName) {if(fieldName=="url"){if(this._vf.nameSpaceName.length!=0){var node=this._xmlNode;if(node&&node.hasChildNodes()) {while(node.childNodes.length>=1) {node.removeChild(node.firstChild);}}} this.loadInline();} else if(fieldName=="render"){this.invalidateVolume();}},nodeChanged:function() {if(!this.initDone){this.initDone=true;this.loadInline();}},fireEvents:function(eventType) {if(this._xmlNode&&(this._xmlNode['on'+eventType]||this._xmlNode.hasAttribute('on'+eventType)||this._listeners[eventType])) {var event={target:this._xmlNode,type:eventType,error:(eventType=="error")?"XMLHttpRequest Error":"",cancelBubble:false,stopPropagation:function(){this.cancelBubble=true;}};try{var attrib=this._xmlNode["on"+eventType];if(typeof(attrib)==="function"){attrib.call(this._xmlNode,event);} else{var funcStr=this._xmlNode.getAttribute("on"+eventType);var func=new Function('event',funcStr);func.call(this._xmlNode,event);} var list=this._listeners[eventType];if(list){for(var i=0;i=0)) nameSpace.setBaseURL(url);else nameSpace.setBaseURL(that._nameSpace.baseURL+url);newScene=nameSpace.setupTree(inlScene);that._nameSpace.addSpace(nameSpace);if(that._vf.nameSpaceName.length!=0) {Array.forEach(inlScene.childNodes,function(childDomNode) {if(childDomNode instanceof Element) {setNamespace(that._vf.nameSpaceName,childDomNode,that._vf.mapDEFToID);that._xmlNode.appendChild(childDomNode);}});}} else{if(xml&&xml.localName) x3dom.debug.logError('No Scene in '+xml.localName);else x3dom.debug.logError('No Scene in resource');} var global=x3dom.getGlobal();if(that._childNodes.length>0&&that._childNodes[0]&&that._childNodes[0]._nameSpace) that._nameSpace.removeSpace(that._childNodes[0]._nameSpace);while(that._childNodes.length!==0) global['_remover']=that.removeChild(that._childNodes[0]);delete global['_remover'];if(newScene) {that.addChild(newScene);that.invalidateVolume();that._nameSpace.doc.downloadCount-=1;that._nameSpace.doc.needRender=true;x3dom.debug.logInfo('Inline: added '+that._vf.url[0]+' to scene.');var theScene=that._nameSpace.doc._scene;if(theScene){theScene.invalidateVolume();window.setTimeout(function(){that.invalidateVolume();theScene.updateVolume();that._nameSpace.doc.needRender=true;},1000);} that.fireEvents("load");} newScene=null;nameSpace=null;inlScene=null;xml=null;return xhr;};if(this._vf.url.length&&this._vf.url[0].length) {var xhrURI=this._nameSpace.getURL(this._vf.url[0]);if(!(xhrURI.substr(0,5)==="blob:")) {xhrURI=encodeURI(xhrURI);} xhr.open('GET',xhrURI,true);this._nameSpace.doc.downloadCount+=1;try{xhr.send(null);} catch(ex){this.fireEvents("error");x3dom.debug.logError(this._vf.url[0]+": "+ex);}}}}));x3dom.nodeTypes.Inline.AwaitTranscoding=202;x3dom.nodeTypes.Inline.MaximumRetries=15;function setNamespace(prefix,childDomNode,mapDEFToID) {if(childDomNode instanceof Element&&childDomNode.__setAttribute!==undefined){if(childDomNode.hasAttribute('id')){childDomNode.__setAttribute('id',prefix.toString().replace(' ','')+'__'+childDomNode.getAttribute('id'));}else if(childDomNode.hasAttribute('DEF')&&mapDEFToID){childDomNode.__setAttribute('id',prefix.toString().replace(' ','')+'__'+childDomNode.getAttribute('DEF'));if(!childDomNode.id) childDomNode.id=childDomNode.__getAttribute('id');}} if(childDomNode.hasChildNodes()){Array.forEach(childDomNode.childNodes,function(children){setNamespace(prefix,children,mapDEFToID);});}} x3dom.registerNodeType("MultiPart","Networking",defineClass(x3dom.nodeTypes.Inline,function(ctx){x3dom.nodeTypes.MultiPart.superClass.call(this,ctx);this.addField_MFString(ctx,'urlIDMap',[]);this._idMap=null;this._oldPixels=null;this._inlineNamespace=null;this._highlightedParts=[];},{fieldChanged:function(fieldName) {if(fieldName=="url"){if(this._vf.nameSpaceName.length!=0){var node=this._xmlNode;if(node&&node.hasChildNodes()) {while(node.childNodes.length>=1) {node.removeChild(node.firstChild);}}} this.loadInline();} else if(fieldName=="render"){this.invalidateVolume();}},nodeChanged:function() {if(!this.initDone){this.initDone=true;this.loadIDMap();this.appendAPI();this.appendEventListeners();}},appendEventListeners:function() {var that=this;this._xmlNode._shadowObjectID=-1 this._xmlNode.addEventListener("mousedown",function(e){if(!that._nameSpace.doc._viewarea._isMoving){e.partID=that._idMap.mapping[e.shadowObjectId].name;this.dispatchEvent(new CustomEvent("partclick",{detail:e}));}},false);this._xmlNode.addEventListener("mouseout",function(e){if(!that._nameSpace.doc._viewarea._isMoving){if(e.shadowObjectId==-1){e.partID=that._idMap.mapping[this._shadowObjectID].name;this._shadowObjectID=-1;var event=new CustomEvent("partout",{detail:e});this.dispatchEvent(event);}}},false);this._xmlNode.addEventListener("mousemove",function(e){if(!that._nameSpace.doc._viewarea._isMoving){e.partID=that._idMap.mapping[e.shadowObjectId].name this.dispatchEvent(new CustomEvent("partmove",{detail:e}));if(e.shadowObjectId!=this._shadowObjectID){var tmp=e.shadowObjectId;if(this._shadowObjectID!=-1){e.partID=that._idMap.mapping[this._shadowObjectID].name;this.dispatchEvent(new CustomEvent("partout",{detail:e}));} this._shadowObjectID=e.shadowObjectId=tmp;e.partID=that._idMap.mapping[e.shadowObjectId].name;this.dispatchEvent(new CustomEvent("partover",{detail:e}));}}},false);},loadIDMap:function() {if(this._vf.urlIDMap.length&&this._vf.urlIDMap[0].length) {var that=this;var idMapURI=this._nameSpace.getURL(this._vf.urlIDMap[0]);var xhr=new XMLHttpRequest();xhr.open("GET",idMapURI,true);xhr.onload=function() {that._idMap=JSON.parse(this.responseText);that._nameSpace.doc._scene._shadowIdMap=eval("("+this.response+")");that.loadInline();};xhr.send(null);}},createImageData:function() {var diffuseColor,transparency,rgba;var size=x3dom.Utils.nextHighestPowerOfTwo(Math.sqrt(this._idMap.numberOfIDs));var imageData=size+" "+size+" 4";for(var i=0;i1) {var pixels=parts.colorMap.getPixels();for(i=0;i1) {var pixels=parts.colorMap.getPixels();for(i=0;i1) {var pixels=parts.visibilityMap.getPixels();for(i=0;i1) {var pixels=parts.colorMap.getPixels();for(i=0;i1) {var pixels=parts.colorMap.getPixels();for(i=0;i=0)) {that._inlineNamespace.setBaseURL(url);} else {that._inlineNamespace.setBaseURL(that._nameSpace.baseURL+url);} that.replaceMaterials(inlScene);newScene=that._inlineNamespace.setupTree(inlScene);that._nameSpace.addSpace(that._inlineNamespace);if(that._vf.nameSpaceName.length!=0) {Array.forEach(inlScene.childNodes,function(childDomNode) {if(childDomNode instanceof Element) {setNamespace(that._vf.nameSpaceName,childDomNode,that._vf.mapDEFToID);that._xmlNode.appendChild(childDomNode);}});}} else{if(xml&&xml.localName){x3dom.debug.logError('No Scene in '+xml.localName);}else{x3dom.debug.logError('No Scene in resource');}} var global=x3dom.getGlobal();if(that._childNodes.length>0&&that._childNodes[0]&&that._childNodes[0]._nameSpace){that._nameSpace.removeSpace(that._childNodes[0]._nameSpace);} while(that._childNodes.length!==0){global['_remover']=that.removeChild(that._childNodes[0]);} delete global['_remover'];if(newScene) {that.addChild(newScene);that.invalidateVolume();that._nameSpace.doc.downloadCount-=1;that._nameSpace.doc.needRender=true;x3dom.debug.logInfo('Inline: added '+that._vf.url[0]+' to scene.');var theScene=that._nameSpace.doc._scene;if(theScene){theScene.invalidateVolume();window.setTimeout(function(){that.invalidateVolume();theScene.updateVolume();that._nameSpace.doc.needRender=true;},1000);} that.fireEvents("load");} newScene=null;inlScene=null;xml=null;return xhr;};if(this._vf.url.length&&this._vf.url[0].length) {var xhrURI=this._nameSpace.getURL(this._vf.url[0]);if(!(xhrURI.substr(0,5)==="blob:")) {xhrURI=encodeURI(xhrURI);} xhr.open('GET',xhrURI,true);this._nameSpace.doc.downloadCount+=1;try{xhr.send(null);} catch(ex){this.fireEvents("error");x3dom.debug.logError(this._vf.url[0]+": "+ex);}}}}));x3dom.registerNodeType("X3DBackgroundNode","EnvironmentalEffects",defineClass(x3dom.nodeTypes.X3DBindableNode,function(ctx){x3dom.nodeTypes.X3DBackgroundNode.superClass.call(this,ctx);var trans=(ctx&&ctx.autoGen)?1:0;this.addField_SFBool(ctx,'withCredentials',false);this.addField_MFColor(ctx,'groundColor',[]);this.addField_MFFloat(ctx,'groundAngle',[]);this.addField_MFColor(ctx,'skyColor',[new x3dom.fields.SFColor(0,0,0)]);this.addField_MFFloat(ctx,'skyAngle',[]);this.addField_SFFloat(ctx,'transparency',trans);this._dirty=true;},{getSkyColor:function(){return new x3dom.fields.SFColor(0,0,0);},getTransparency:function(){return 0;},getTexUrl:function(){return[];}}));x3dom.registerNodeType("X3DFogNode","EnvironmentalEffects",defineClass(x3dom.nodeTypes.X3DBindableNode,function(ctx){x3dom.nodeTypes.X3DFogNode.superClass.call(this,ctx);this.addField_SFColor(ctx,'color',1,1,1);this.addField_SFString(ctx,'fogType',"LINEAR");this.addField_SFFloat(ctx,'visibilityRange',0);},{}));x3dom.registerNodeType("Fog","EnvironmentalEffects",defineClass(x3dom.nodeTypes.X3DFogNode,function(ctx){x3dom.nodeTypes.Fog.superClass.call(this,ctx);},{}));x3dom.registerNodeType("Background","EnvironmentalEffects",defineClass(x3dom.nodeTypes.X3DBackgroundNode,function(ctx){x3dom.nodeTypes.Background.superClass.call(this,ctx);this.addField_MFString(ctx,'backUrl',[]);this.addField_MFString(ctx,'bottomUrl',[]);this.addField_MFString(ctx,'frontUrl',[]);this.addField_MFString(ctx,'leftUrl',[]);this.addField_MFString(ctx,'rightUrl',[]);this.addField_MFString(ctx,'topUrl',[]);},{fieldChanged:function(fieldName) {if(fieldName.indexOf("Url")>0||fieldName=="transparency"||fieldName.search("sky")>=0||fieldName.search("ground")>=0){this._dirty=true;} else if(fieldName.indexOf("bind")>=0){this.bind(this._vf.bind);}},getSkyColor:function(){return this._vf.skyColor;},getGroundColor:function(){return this._vf.groundColor;},getTransparency:function(){return this._vf.transparency;},getTexUrl:function(){return[this._nameSpace.getURL(this._vf.backUrl[0]),this._nameSpace.getURL(this._vf.frontUrl[0]),this._nameSpace.getURL(this._vf.bottomUrl[0]),this._nameSpace.getURL(this._vf.topUrl[0]),this._nameSpace.getURL(this._vf.leftUrl[0]),this._nameSpace.getURL(this._vf.rightUrl[0])];}}));x3dom.registerNodeType("X3DEnvironmentNode","EnvironmentalEffects",defineClass(x3dom.nodeTypes.X3DBindableNode,function(ctx){x3dom.nodeTypes.X3DEnvironmentNode.superClass.call(this,ctx);}));x3dom.registerNodeType("Environment","EnvironmentalEffects",defineClass(x3dom.nodeTypes.X3DEnvironmentNode,function(ctx){x3dom.nodeTypes.Environment.superClass.call(this,ctx);this.addField_SFBool(ctx,'sortTrans',true);this.addField_SFBool(ctx,'shadowExcludeTransparentObjects',false);this.addField_SFString(ctx,'gammaCorrectionDefault',"linear");this.addField_SFBool(ctx,'frustumCulling',true);this.addField_SFBool(ctx,'smallFeatureCulling',false);this.addField_SFFloat(ctx,'smallFeatureThreshold',1.0);this.addField_SFBool(ctx,'occlusionCulling',false);this.addField_SFFloat(ctx,'occlusionVisibilityThreshold',0.0);this.addField_SFBool(ctx,'lowPriorityCulling',false);this.addField_SFFloat(ctx,'lowPriorityThreshold',1.0);this.addField_SFBool(ctx,'tessellationDetailCulling',false);this.addField_SFFloat(ctx,'tessellationErrorThreshold',0.0);this.addField_SFBool(ctx,'enableARC',false);this.addField_SFFloat(ctx,'minFrameRate',1.0);this.addField_SFFloat(ctx,'maxFrameRate',62.5);this.addField_SFFloat(ctx,'userDataFactor',-1);this.addField_SFFloat(ctx,'smallFeatureFactor',-1);this.addField_SFFloat(ctx,'occlusionVisibilityFactor',-1);this.addField_SFFloat(ctx,'lowPriorityFactor',-1);this.addField_SFFloat(ctx,'tessellationErrorFactor',-1);this._validGammaCorrectionTypes=["none","fastlinear","linear"];this.checkSanity();},{checkSanity:function() {var checkParam=function(flag,value,defaultOn,defaultOff) {if(flag&&(value==defaultOff)) return defaultOn;if(!flag&&(value!=defaultOff)) return defaultOff;return value;};this._smallFeatureThreshold=checkParam(this._vf.smallFeatureCulling,this._vf.smallFeatureThreshold,10,0);this._lowPriorityThreshold=checkParam(this._vf.lowPriorityCulling,this._vf.lowPriorityThreshold,0.5,1);this._occlusionVisibilityThreshold=checkParam(this._vf.occlusionCulling,this._vf.occlusionVisibilityThreshold,1,0);this._tessellationErrorThreshold=checkParam(this._vf.tessellationDetailCulling,this._vf.tessellationErrorThreshold,1,0);var checkGamma=function(field,that){field=field.toLowerCase();if(that._validGammaCorrectionTypes.indexOf(field)>-1){return field;} else{x3dom.debug.logWarning(field+" gammaCorrectionDefault may only be linear (default), fastLinear, or none");return that._validGammaCorrectionTypes[0];}};this._vf.gammaCorrectionDefault=checkGamma(this._vf.gammaCorrectionDefault,this);}}));x3dom.registerNodeType("X3DViewpointNode","Navigation",defineClass(x3dom.nodeTypes.X3DBindableNode,function(ctx){x3dom.nodeTypes.X3DViewpointNode.superClass.call(this,ctx);if(ctx&&ctx.xmlNode){var domNode=ctx.xmlNode;if(!domNode.resetView&&!domNode.getFieldOfView&&!domNode.getNear&&!domNode.getFar) {domNode.resetView=function(){var that=this._x3domNode;that.resetView();that._nameSpace.doc.needRender=true;};domNode.getFieldOfView=function(){return this._x3domNode.getFieldOfView();};domNode.getNear=function(){return this._x3domNode.getNear();};domNode.getFar=function(){return this._x3domNode.getFar();};}}},{activate:function(prev){var viewarea=this._nameSpace.doc._viewarea;if(prev){viewarea.animateTo(this,prev._autoGen?null:prev);} viewarea._needNavigationMatrixUpdate=true;x3dom.nodeTypes.X3DBindableNode.prototype.activate.call(this,prev);},deactivate:function(prev){x3dom.nodeTypes.X3DBindableNode.prototype.deactivate.call(this,prev);},getTransformation:function(){return this.getCurrentTransform();},getCenterOfRotation:function(){return new x3dom.fields.SFVec3f(0,0,0);},setCenterOfRotation:function(cor){this._vf.centerOfRotation.setValues(cor);},getFieldOfView:function(){return 1.57079633;},setView:function(newView){var mat=this.getCurrentTransform();this._viewMatrix=newView.mult(mat);},setViewAbsolute:function(newView) {this._viewMatrix=newView},setProjectionMatrix:function(matrix) {},resetView:function(){},getNear:function(){return 0.1;},getFar:function(){return 10000;},getImgPlaneHeightAtDistOne:function(){return 2.0;},getViewMatrix:function(){return null;},getProjectionMatrix:function(aspect){return null;}}));x3dom.registerNodeType("Viewpoint","Navigation",defineClass(x3dom.nodeTypes.X3DViewpointNode,function(ctx){x3dom.nodeTypes.Viewpoint.superClass.call(this,ctx);this.addField_SFFloat(ctx,'fieldOfView',0.785398);this.addField_SFVec3f(ctx,'position',0,0,10);this.addField_SFRotation(ctx,'orientation',0,0,0,1);this.addField_SFVec3f(ctx,'centerOfRotation',0,0,0);this.addField_SFFloat(ctx,'zNear',-1);this.addField_SFFloat(ctx,'zFar',-1);this._viewMatrix=x3dom.fields.SFMatrix4f.translation(this._vf.position).mult(this._vf.orientation.toMatrix()).inverse();this._projMatrix=null;this._lastAspect=1.0;this._zRatio=10000;this._zNear=this._vf.zNear;this._zFar=this._vf.zFar;this._imgPlaneHeightAtDistOne=2.0*Math.tan(this._vf.fieldOfView/2.0);},{fieldChanged:function(fieldName){if(fieldName=="position"||fieldName=="orientation"){this.resetView();} else if(fieldName=="fieldOfView"||fieldName=="zNear"||fieldName=="zFar"){this._projMatrix=null;this._zNear=this._vf.zNear;this._zFar=this._vf.zFar;this._imgPlaneHeightAtDistOne=2.0*Math.tan(this._vf.fieldOfView/2.0);} else if(fieldName.indexOf("bind")>=0){this.bind(this._vf.bind);}},setProjectionMatrix:function(matrix) {this._projMatrix=matrix;},getCenterOfRotation:function(){return this._vf.centerOfRotation;},getViewMatrix:function(){return this._viewMatrix;},getFieldOfView:function(){return this._vf.fieldOfView;},resetView:function(){this._viewMatrix=x3dom.fields.SFMatrix4f.translation(this._vf.position).mult(this._vf.orientation.toMatrix()).inverse();},getNear:function(){return this._zNear;},getFar:function(){return this._zFar;},getImgPlaneHeightAtDistOne:function(){return this._imgPlaneHeightAtDistOne;},getProjectionMatrix:function(aspect) {var fovy=this._vf.fieldOfView;var zfar=this._vf.zFar;var znear=this._vf.zNear;if(znear<=0||zfar<=0) {var nearScale=0.8,farScale=1.2;var viewarea=this._nameSpace.doc._viewarea;var scene=viewarea._scene;var min=x3dom.fields.SFVec3f.copy(scene._lastMin);var max=x3dom.fields.SFVec3f.copy(scene._lastMax);var dia=max.subtract(min);var sRad=dia.length()/2;var mat=viewarea.getViewMatrix().inverse();var vp=mat.e3();var translation=new x3dom.fields.SFVec3f(0,0,0),scaleFactor=new x3dom.fields.SFVec3f(1,1,1);var rotation=new x3dom.fields.Quaternion(0,0,1,0),scaleOrientation=new x3dom.fields.Quaternion(0,0,1,0);mat.getTransform(translation,rotation,scaleFactor,scaleOrientation);var minScal=scaleFactor.x,maxScal=scaleFactor.x;if(maxScalscaleFactor.y)minScal=scaleFactor.y;if(maxScalscaleFactor.z)minScal=scaleFactor.z;if(maxScal>1) nearScale/=maxScal;else if(minScal>x3dom.fields.Eps&&minScal<1) farScale/=minScal;var sCenter=min.add(dia.multiply(0.5));var vDist=(vp.subtract(sCenter)).length();if(sRad){if(vDist>sRad) znear=(vDist-sRad)*nearScale;else znear=0;zfar=(vDist+sRad)*farScale;} else{znear=0.1;zfar=100000;} var zNearLimit=zfar/this._zRatio;znear=Math.max(znear,Math.max(x3dom.fields.Eps,zNearLimit));if(zfar>this._vf.zNear&&this._vf.zNear>0) znear=this._vf.zNear;if(this._vf.zFar>znear) zfar=this._vf.zFar;if(zfar<=znear) zfar=znear+1;} if(this._projMatrix==null) {this._projMatrix=x3dom.fields.SFMatrix4f.perspective(fovy,aspect,znear,zfar);} else if(this._zNear!=znear||this._zFar!=zfar) {var div=znear-zfar;this._projMatrix._22=(znear+zfar)/div;this._projMatrix._23=2*znear*zfar/div;} else if(this._lastAspect!=aspect) {this._projMatrix._00=(1/Math.tan(fovy/2))/aspect;this._lastAspect=aspect;} this._zNear=znear;this._zFar=zfar;return this._projMatrix;}}));x3dom.registerNodeType("OrthoViewpoint","Navigation",defineClass(x3dom.nodeTypes.X3DViewpointNode,function(ctx){x3dom.nodeTypes.OrthoViewpoint.superClass.call(this,ctx);this.addField_MFFloat(ctx,'fieldOfView',[-1,-1,1,1]);this.addField_SFVec3f(ctx,'position',0,0,10);this.addField_SFRotation(ctx,'orientation',0,0,0,1);this.addField_SFVec3f(ctx,'centerOfRotation',0,0,0);this.addField_SFFloat(ctx,'zNear',0.1);this.addField_SFFloat(ctx,'zFar',10000);this._viewMatrix=null;this._projMatrix=null;this._lastAspect=1.0;this.resetView();},{fieldChanged:function(fieldName){if(fieldName=="position"||fieldName=="orientation"){this.resetView();} else if(fieldName=="fieldOfView"||fieldName=="zNear"||fieldName=="zFar"){this._projMatrix=null;this.resetView();} else if(fieldName.indexOf("bind")>=0){this.bind(this._vf.bind);}},getCenterOfRotation:function(){return this._vf.centerOfRotation;},getViewMatrix:function(){return this._viewMatrix;},resetView:function(){var offset=x3dom.fields.SFMatrix4f.translation(new x3dom.fields.SFVec3f((this._vf.fieldOfView[0]+this._vf.fieldOfView[2])/2,(this._vf.fieldOfView[1]+this._vf.fieldOfView[3])/2,0));this._viewMatrix=x3dom.fields.SFMatrix4f.translation(this._vf.position).mult(this._vf.orientation.toMatrix());this._viewMatrix=this._viewMatrix.mult(offset).inverse();},getNear:function(){return this._vf.zNear;},getFar:function(){return this._vf.zFar;},getProjectionMatrix:function(aspect) {if(this._projMatrix==null||this._lastAspect!=aspect) {var near=this.getNear();var far=this.getFar();var left=this._vf.fieldOfView[0];var bottom=this._vf.fieldOfView[1];var right=this._vf.fieldOfView[2];var top=this._vf.fieldOfView[3];this._projMatrix=x3dom.fields.SFMatrix4f.ortho(left,right,bottom,top,near,far,aspect);} this._lastAspect=aspect;return this._projMatrix;}}));x3dom.registerNodeType("Viewfrustum","Navigation",defineClass(x3dom.nodeTypes.X3DViewpointNode,function(ctx){x3dom.nodeTypes.Viewfrustum.superClass.call(this,ctx);this.addField_SFMatrix4f(ctx,'modelview',1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);this.addField_SFMatrix4f(ctx,'projection',1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);this._viewMatrix=this._vf.modelview.transpose().inverse();this._projMatrix=this._vf.projection.transpose();this._centerOfRotation=new x3dom.fields.SFVec3f(0,0,0);},{fieldChanged:function(fieldName){if(fieldName=="modelview"){this.resetView();} else if(fieldName=="projection"){this._projMatrix=this._vf.projection.transpose();} else if(fieldName.indexOf("bind")>=0){this.bind(this._vf.bind);}},getCenterOfRotation:function(){return this._centerOfRotation;},setCenterOfRotation:function(cor){this._centerOfRotation.setValues(cor);},getViewMatrix:function(){return this._viewMatrix;},getFieldOfView:function(){return(2.0*Math.atan(1.0/this._projMatrix._11));},getImgPlaneHeightAtDistOne:function(){return 2.0/this._projMatrix._11;},resetView:function(){this._viewMatrix=this._vf.modelview.transpose().inverse();this._centerOfRotation=new x3dom.fields.SFVec3f(0,0,0);},getProjectionMatrix:function(aspect){return this._projMatrix;}}));x3dom.registerNodeType("X3DNavigationInfoNode","Navigation",defineClass(x3dom.nodeTypes.X3DBindableNode,function(ctx){x3dom.nodeTypes.X3DNavigationInfoNode.superClass.call(this,ctx);}));x3dom.registerNodeType("NavigationInfo","Navigation",defineClass(x3dom.nodeTypes.X3DNavigationInfoNode,function(ctx){x3dom.nodeTypes.NavigationInfo.superClass.call(this,ctx);this.addField_SFBool(ctx,'headlight',true);this.addField_MFString(ctx,'type',["EXAMINE","ANY"]);this.addField_MFFloat(ctx,'typeParams',[-0.4,60,0.05,2.8]);this.addField_SFString(ctx,'explorationMode','all');this.addField_MFFloat(ctx,'avatarSize',[0.25,1.6,0.75]);this.addField_SFFloat(ctx,'visibilityLimit',0.0);this.addField_SFFloat(ctx,'speed',1.0);this.addField_SFTime(ctx,'transitionTime',1.0);this.addField_MFString(ctx,'transitionType',["LINEAR"]);this._validTypes=["none","examine","turntable","fly","freefly","lookat","lookaround","walk","game","helicopter","any"];this._heliUpdated=false;var type=this.checkType(this.getType());x3dom.debug.logInfo("NavType: "+type);},{fieldChanged:function(fieldName){if(fieldName=="typeParams"){this._heliUpdated=false;} else if(fieldName=="type"){var type=this.checkType(this.getType());switch(type){case'game':this._nameSpace.doc._viewarea.initMouseState();break;case'helicopter':this._heliUpdated=false;break;case"turntable":this._nameSpace.doc._viewarea.initMouseState();this._nameSpace.doc._viewarea.initTurnTable(this);break;default:break;} this._vf.type[0]=type;x3dom.debug.logInfo("Switch to "+type+" mode.");}},setType:function(type,viewarea){var navType=this.checkType(type.toLowerCase());var oldType=this.checkType(this.getType());switch(navType){case'game':if(oldType!==navType){if(viewarea) viewarea.initMouseState();else this._nameSpace.doc._viewarea.initMouseState();} break;case'helicopter':if(oldType!==navType){this._heliUpdated=false;} break;case"turntable":if(oldType!==navType){if(viewarea){viewarea.initMouseState();viewarea.initTurnTable(this);} else{this._nameSpace.doc._viewarea.initMouseState();this._nameSpace.doc._viewarea.initTurnTable(this);}} break;default:break;} this._vf.type[0]=navType;x3dom.debug.logInfo("Switch to "+navType+" mode.");},getType:function(){var type=this._vf.type[0].toLowerCase();if(type.length<=1) type="none";else if(type=="any") type="examine";return type;},getTypeParams:function(){var length=this._vf.typeParams.length;var theta=(length>=1)?this._vf.typeParams[0]:-0.4;var height=(length>=2)?this._vf.typeParams[1]:60.0;var minAngle=(length>=3)?this._vf.typeParams[2]:x3dom.fields.Eps;var maxAngle=(length>=4)?this._vf.typeParams[3]:Math.PI-x3dom.fields.Eps;var params=[theta,height,minAngle,maxAngle];if(length>=5) {params.push(this._vf.typeParams[4]);} return params;},setTypeParams:function(params){for(var i=0;i-1){return type;} else{x3dom.debug.logWarning(type+" is no valid navigation type, use one of "+ this._validTypes.toString());return"examine";}},getExplorationMode:function(){switch(this._vf.explorationMode.toLowerCase()){case"all":return 7;case"rotate":return 1;case"zoom":return 2;case"pan":return 4;case"none":return 0;default:return 7;}}}));x3dom.registerNodeType("Billboard","Navigation",defineClass(x3dom.nodeTypes.X3DGroupingNode,function(ctx){x3dom.nodeTypes.Billboard.superClass.call(this,ctx);this.addField_SFVec3f(ctx,'axisOfRotation',0,1,0);this._eye=new x3dom.fields.SFVec3f(0,0,0);this._eyeViewUp=new x3dom.fields.SFVec3f(0,0,0);this._eyeLook=new x3dom.fields.SFVec3f(0,0,0);},{collectDrawableObjects:function(transform,drawableCollection,singlePath,invalidateCache,planeMask) {if(singlePath&&(this._parentNodes.length>1)) singlePath=false;if(singlePath&&(invalidateCache=invalidateCache||this.cacheInvalid())) this.invalidateCache();planeMask=drawableCollection.cull(transform,this.graphState(),singlePath,planeMask);if(planeMask<=0){return;} singlePath=false;var vol=this.getVolume();var min=x3dom.fields.SFVec3f.MAX();var max=x3dom.fields.SFVec3f.MIN();vol.getBounds(min,max);var mat_view=drawableCollection.viewMatrix;var center=new x3dom.fields.SFVec3f(0,0,0);center=mat_view.inverse().multMatrixPnt(center);var mat_view_model=mat_view.mult(transform);this._eye=transform.inverse().multMatrixPnt(center);this._eyeViewUp=new x3dom.fields.SFVec3f(mat_view_model._10,mat_view_model._11,mat_view_model._12);this._eyeLook=new x3dom.fields.SFVec3f(mat_view_model._20,mat_view_model._21,mat_view_model._22);var rotMat=x3dom.fields.SFMatrix4f.identity();var mid=max.add(min).multiply(0.5);var billboard_to_viewer=this._eye.subtract(mid);if(this._vf.axisOfRotation.equals(new x3dom.fields.SFVec3f(0,0,0),x3dom.fields.Eps)){var rot1=x3dom.fields.Quaternion.rotateFromTo(billboard_to_viewer,new x3dom.fields.SFVec3f(0,0,1));rotMat=rot1.toMatrix().transpose();var yAxis=rotMat.multMatrixPnt(new x3dom.fields.SFVec3f(0,1,0)).normalize();var zAxis=rotMat.multMatrixPnt(new x3dom.fields.SFVec3f(0,0,1)).normalize();if(!this._eyeViewUp.equals(new x3dom.fields.SFVec3f(0,0,0),x3dom.fields.Eps)){var rot2=x3dom.fields.Quaternion.rotateFromTo(this._eyeLook,zAxis);var rotatedyAxis=rot2.toMatrix().transpose().multMatrixVec(yAxis);var rot3=x3dom.fields.Quaternion.rotateFromTo(this._eyeViewUp,rotatedyAxis);rotMat=rot2.toMatrix().transpose().mult(rotMat);rotMat=rot3.toMatrix().transpose().mult(rotMat);}} else{var normalPlane=this._vf.axisOfRotation.cross(billboard_to_viewer).normalize();if(this._eye.z<0){normalPlane=normalPlane.multiply(-1);} var degreesToRotate=Math.asin(normalPlane.dot(new x3dom.fields.SFVec3f(0,0,1)));if(this._eye.z<0){degreesToRotate+=Math.PI;} rotMat=x3dom.fields.SFMatrix4f.parseRotation(this._vf.axisOfRotation.x+", "+this._vf.axisOfRotation.y+", "+ this._vf.axisOfRotation.z+", "+degreesToRotate*(-1));} var childTransform=this.transformMatrix(transform.mult(rotMat));for(var i=0,i_n=this._childNodes.length;i1)) singlePath=false;if(singlePath&&(invalidateCache=invalidateCache||this.cacheInvalid())) this.invalidateCache();planeMask=drawableCollection.cull(transform,this.graphState(),singlePath,planeMask);if(planeMask<=0){return;} var cnode,childTransform;if(singlePath){if(!this._graph.globalMatrix){this._graph.globalMatrix=this.transformMatrix(transform);} childTransform=this._graph.globalMatrix;} else{childTransform=this.transformMatrix(transform);} for(var i=0,n=this._childNodes.length;i1)) singlePath=false;if(singlePath&&(invalidateCache=invalidateCache||this.cacheInvalid())) this.invalidateCache();planeMask=drawableCollection.cull(transform,this.graphState(),singlePath,planeMask);if(planeMask<=0){return;} singlePath=false;this.visitChildren(transform,drawableCollection,singlePath,invalidateCache,planeMask);},visitChildren:function(transform,drawableCollection,singlePath,invalidateCache,planeMask){}}));x3dom.registerNodeType("LOD","Navigation",defineClass(x3dom.nodeTypes.X3DLODNode,function(ctx){x3dom.nodeTypes.LOD.superClass.call(this,ctx);this.addField_MFFloat(ctx,"range",[]);this._lastRangePos=-1;},{visitChildren:function(transform,drawableCollection,singlePath,invalidateCache,planeMask) {var i=0,n=this._childNodes.length;var vol=this.getVolume();var min=x3dom.fields.SFVec3f.MAX();var max=x3dom.fields.SFVec3f.MIN();vol.getBounds(min,max);var mat_view=drawableCollection.viewMatrix;var center=new x3dom.fields.SFVec3f(0,0,0);center=mat_view.inverse().multMatrixPnt(center);this._eye=transform.inverse().multMatrixPnt(center);var mid=max.add(min).multiply(0.5).add(this._vf.center);var len=mid.subtract(this._eye).length();while(ithis._vf.range[i]){i++;} if(i&&i>=n){i=n-1;} this._lastRangePos=i;var cnode=this._childNodes[i];if(n&&cnode) {var childTransform=this.transformMatrix(transform);cnode.collectDrawableObjects(childTransform,drawableCollection,singlePath,invalidateCache,planeMask);}},getVolume:function() {var vol=this._graph.volume;if(!this.volumeValid()&&this._vf.render) {var child,childVol;if(this._lastRangePos>=0){child=this._childNodes[this._lastRangePos];childVol=(child&&child._vf.render===true)?child.getVolume():null;if(childVol&&childVol.isValid()) vol.extendBounds(childVol.min,childVol.max);} else{for(var i=0,n=this._childNodes.length;ix3dom.fields.Eps&&len*this._vf.subScale<=this._vf.size.length()){if(this._childNodes.length<=1){var offset=new Array(new x3dom.fields.SFVec3f(-0.25*this._vf.size.x,0.25*this._vf.size.y,0),new x3dom.fields.SFVec3f(0.25*this._vf.size.x,0.25*this._vf.size.y,0),new x3dom.fields.SFVec3f(-0.25*this._vf.size.x,-0.25*this._vf.size.y,0),new x3dom.fields.SFVec3f(0.25*this._vf.size.x,-0.25*this._vf.size.y,0));for(l=0;l<4;l++){var node=new x3dom.nodeTypes.DynamicLOD();node._nameSpace=this._nameSpace;node._eye.setValues(this._eye);node.level=this.level+1;node.quadrant=l;node.cell=this.cell+l;node._vf.urlHead=this._vf.urlHead;node._vf.urlCenter=this._vf.urlCenter;node._vf.urlTail=this._vf.urlTail;node._vf.center=this._vf.center.add(offset[l]);node._vf.size=this._vf.size.multiply(0.5);node._vf.subdivision.setValues(this._vf.subdivision);var app=new x3dom.nodeTypes.Appearance();var tex=new x3dom.nodeTypes.ImageTexture();tex._nameSpace=this._nameSpace;tex._vf.url[0]=this._vf.urlHead+node.quadrant+this._vf.urlCenter+node.cell+this._vf.urlTail;app.addChild(tex);tex.nodeChanged();var shape=new x3dom.nodeTypes.Shape();shape._nameSpace=this._nameSpace;shape.addChild(app);app.nodeChanged();node.addChild(shape,"root");shape.nodeChanged();this.addChild(node);node.nodeChanged();}} else{for(l=1;l=0&&pos=3,"RenderedTexture.dimensions requires at least 3 entries.");this._clearParents=true;this._needRenderUpdate=true;},{nodeChanged:function() {this._clearParents=true;this._needRenderUpdate=true;},fieldChanged:function(fieldName) {switch(fieldName) {case"excludeNodes":this._clearParents=true;break;case"update":if(this._vf.update.toUpperCase()=="NEXT_FRAME_ONLY"||this._vf.update.toUpperCase()=="ALWAYS"){this._needRenderUpdate=true;} break;default:break;}},getViewMatrix:function() {if(this._clearParents&&this._cf.excludeNodes.nodes.length){var that=this;Array.forEach(this._cf.excludeNodes.nodes,function(node){for(var i=0,n=node._parentNodes.length;i11)?11:this._vf.iterations;this._vf.iterations=(this._vf.iterations<3)?3:this._vf.iterations;this._vf.maxLevel=(this._vf.maxLevel>11)?11:this._vf.maxLevel;this._vf.maxLevel=(this._vf.maxLevel<3)?3:this._vf.maxLevel;this._vf.maxLevel=(this._vf.maxLevel>this._vf.iterations)?this._vf.iterations:this._vf.maxLevel;var repeatConfig=[{x:4,y:8},{x:8,y:8},{x:8,y:16},{x:16,y:16},{x:16,y:32},{x:32,y:32},{x:32,y:64},{x:64,y:64},{x:64,y:128}];this._repeat=new x3dom.fields.SFVec2f(this._vf.dimensions[0]/repeatConfig[this._vf.iterations-3].x,this._vf.dimensions[1]/repeatConfig[this._vf.iterations-3].y);this._renderedImage=0;this._currLoadLevel=0;this._loadLevel=1;},{nextLevel:function(){if(this._loadLevel"+"http://x3dom.org/x3dom/doc/help/composedShader.html)\n"+" attribute vec3 position;\n"+" attribute vec3 normal;\n"+" attribute vec2 texcoord;\n"+" attribute vec3 color;\n"+" uniform mat4 modelViewProjectionMatrix;\n"+" uniform mat4 modelViewMatrix;\n"+" uniform mat4 normalMatrix;\n"+" uniform mat4 viewMatrix;\n"+" uniform sampler2D tex;\n");x3dom.nodeTypes.ComposedShader.ShaderInfoMsgShown=true;}},{nodeChanged:function() {var i,n=this._cf.parts.nodes.length;for(i=0;itwoPi) this._vf.angle=twoPi;this._origCCW=this._vf.ccw;var innerRadius=this._vf.innerRadius;var outerRadius=this._vf.outerRadius;if(this._vf.insideOutsideRadius==true) {if(innerRadius>outerRadius){var tmp=innerRadius;innerRadius=outerRadius;outerRadius=tmp;} var rad=(outerRadius-innerRadius)/2;outerRadius=innerRadius+rad;innerRadius=rad;this._vf.ccw=!this._origCCW;} var rings=this._vf.subdivision.x,sides=this._vf.subdivision.y;rings=Math.max(3,Math.round((this._vf.angle/twoPi)*rings));var geoCacheID='Torus_'+innerRadius+'_'+outerRadius+'_'+this._vf.angle+'_'+ this._vf.subdivision+'-'+this._vf.caps;if(this._vf.useGeoCache&&x3dom.geoCache[geoCacheID]!==undefined) {this._mesh=x3dom.geoCache[geoCacheID];} else {var ringDelta=this._vf.angle/rings;var sideDelta=twoPi/sides;var a,b,theta,phi;var cosTheta,sinTheta,cosPhi,sinPhi,dist;for(a=0,theta=0;a<=rings;a++,theta+=ringDelta) {cosTheta=Math.cos(theta);sinTheta=Math.sin(theta);for(b=0,phi=0;b<=sides;b++,phi+=sideDelta) {cosPhi=Math.cos(phi);sinPhi=Math.sin(phi);dist=outerRadius+innerRadius*cosPhi;if(this._vf.insideOutsideRadius){this._mesh._positions[0].push(cosTheta*dist,innerRadius*sinPhi,-sinTheta*dist);this._mesh._normals[0].push(cosTheta*cosPhi,sinPhi,-sinTheta*cosPhi);} else{this._mesh._positions[0].push(cosTheta*dist,-sinTheta*dist,innerRadius*sinPhi);this._mesh._normals[0].push(cosTheta*cosPhi,-sinTheta*cosPhi,sinPhi);} this._mesh._texCoords[0].push(-a/rings,b/sides);}} for(a=0;a0){this._mesh._indices[0].push(origPos);this._mesh._indices[0].push(origPos+b);this._mesh._indices[0].push(origPos+b-1);} if(b==sides){this._mesh._indices[0].push(origPos);this._mesh._indices[0].push(origPos+1);this._mesh._indices[0].push(origPos+b);}} cosTheta=Math.cos(this._vf.angle);sinTheta=Math.sin(this._vf.angle);origPos=this._mesh._positions[0].length/3;var nx=-sinTheta,ny=-cosTheta;if(this._vf.insideOutsideRadius){this._mesh._positions[0].push(cosTheta*outerRadius,0,-sinTheta*outerRadius);this._mesh._normals[0].push(nx,0,ny);} else{this._mesh._positions[0].push(cosTheta*outerRadius,-sinTheta*outerRadius,0);this._mesh._normals[0].push(nx,ny,0);} this._mesh._texCoords[0].push(0.5,0.5);for(b=0,phi=0;b<=sides;b++,phi+=sideDelta) {cosPhi=Math.cos(phi);sinPhi=Math.sin(phi);dist=outerRadius+innerRadius*cosPhi;if(this._vf.insideOutsideRadius){this._mesh._positions[0].push(cosTheta*dist,sinPhi*innerRadius,-sinTheta*dist);this._mesh._normals[0].push(nx,0,ny);} else{this._mesh._positions[0].push(cosTheta*dist,-sinTheta*dist,sinPhi*innerRadius);this._mesh._normals[0].push(nx,ny,0);} this._mesh._texCoords[0].push(1-(1+cosPhi)*0.5,(1-sinPhi)*0.5);if(b>0){this._mesh._indices[0].push(origPos);this._mesh._indices[0].push(origPos+b-1);this._mesh._indices[0].push(origPos+b);} if(b==sides){this._mesh._indices[0].push(origPos);this._mesh._indices[0].push(origPos+b);this._mesh._indices[0].push(origPos+1);}}} this._mesh._invalidate=true;this._mesh._numFaces=this._mesh._indices[0].length/3;this._mesh._numCoords=this._mesh._positions[0].length/3;x3dom.geoCache[geoCacheID]=this._mesh;}},{fieldChanged:function(fieldName) {if(fieldName=="innerRadius"||fieldName=="outerRadius"||fieldName=="subdivision"||fieldName=="angle"||fieldName=="insideOutsideRadius"||fieldName=="caps") {var twoPi=2.0*Math.PI;if(this._vf.angle<0) this._vf.angle=0;else if(this._vf.angle>twoPi) this._vf.angle=twoPi;var innerRadius=this._vf.innerRadius;var outerRadius=this._vf.outerRadius;if(this._vf.insideOutsideRadius==true) {if(innerRadius>outerRadius){var tmp=innerRadius;innerRadius=outerRadius;outerRadius=tmp;} var rad=(outerRadius-innerRadius)/2;outerRadius=innerRadius+rad;innerRadius=rad;this._vf.ccw=!this._origCCW;} else this._vf.ccw=this._origCCW;var rings=this._vf.subdivision.x,sides=this._vf.subdivision.y;rings=Math.max(3,Math.round((this._vf.angle/twoPi)*rings));var ringDelta=this._vf.angle/rings;var sideDelta=twoPi/sides;var a,b,theta,phi;var cosTheta,sinTheta,cosPhi,sinPhi,dist;this._mesh._positions[0]=[];this._mesh._normals[0]=[];this._mesh._texCoords[0]=[];this._mesh._indices[0]=[];for(a=0,theta=0;a<=rings;a++,theta+=ringDelta) {cosTheta=Math.cos(theta);sinTheta=Math.sin(theta);for(b=0,phi=0;b<=sides;b++,phi+=sideDelta) {cosPhi=Math.cos(phi);sinPhi=Math.sin(phi);dist=outerRadius+innerRadius*cosPhi;if(this._vf.insideOutsideRadius){this._mesh._positions[0].push(cosTheta*dist,innerRadius*sinPhi,-sinTheta*dist);this._mesh._normals[0].push(cosTheta*cosPhi,sinPhi,-sinTheta*cosPhi);} else{this._mesh._positions[0].push(cosTheta*dist,-sinTheta*dist,innerRadius*sinPhi);this._mesh._normals[0].push(cosTheta*cosPhi,-sinTheta*cosPhi,sinPhi);} this._mesh._texCoords[0].push(-a/rings,b/sides);}} for(a=0;a0){this._mesh._indices[0].push(origPos);this._mesh._indices[0].push(origPos+b);this._mesh._indices[0].push(origPos+b-1);} if(b==sides){this._mesh._indices[0].push(origPos);this._mesh._indices[0].push(origPos+1);this._mesh._indices[0].push(origPos+b);}} cosTheta=Math.cos(this._vf.angle);sinTheta=Math.sin(this._vf.angle);origPos=this._mesh._positions[0].length/3;var nx=-sinTheta,ny=-cosTheta;if(this._vf.insideOutsideRadius){this._mesh._positions[0].push(cosTheta*outerRadius,0,-sinTheta*outerRadius);this._mesh._normals[0].push(nx,0,ny);} else{this._mesh._positions[0].push(cosTheta*outerRadius,-sinTheta*outerRadius,0);this._mesh._normals[0].push(nx,ny,0);} this._mesh._texCoords[0].push(0.5,0.5);for(b=0,phi=0;b<=sides;b++,phi+=sideDelta) {cosPhi=Math.cos(phi);sinPhi=Math.sin(phi);dist=outerRadius+innerRadius*cosPhi;if(this._vf.insideOutsideRadius){this._mesh._positions[0].push(cosTheta*dist,sinPhi*innerRadius,-sinTheta*dist);this._mesh._normals[0].push(nx,0,ny);} else{this._mesh._positions[0].push(cosTheta*dist,-sinTheta*dist,sinPhi*innerRadius);this._mesh._normals[0].push(nx,ny,0);} this._mesh._texCoords[0].push(1-(1+cosPhi)*0.5,(1-sinPhi)*0.5);if(b>0){this._mesh._indices[0].push(origPos);this._mesh._indices[0].push(origPos+b-1);this._mesh._indices[0].push(origPos+b);} if(b==sides){this._mesh._indices[0].push(origPos);this._mesh._indices[0].push(origPos+b);this._mesh._indices[0].push(origPos+1);}}} this.invalidateVolume();this._mesh._numFaces=this._mesh._indices[0].length/3;this._mesh._numCoords=this._mesh._positions[0].length/3;Array.forEach(this._parentNodes,function(node){node.setAllDirty();node.invalidateVolume();});}}}));x3dom.registerNodeType("Cone","Geometry3D",defineClass(x3dom.nodeTypes.X3DSpatialGeometryNode,function(ctx){x3dom.nodeTypes.Cone.superClass.call(this,ctx);this.addField_SFFloat(ctx,'bottomRadius',1.0);this.addField_SFFloat(ctx,'topRadius',0);this.addField_SFFloat(ctx,'height',2.0);this.addField_SFBool(ctx,'bottom',true);this.addField_SFBool(ctx,'side',true);this.addField_SFBool(ctx,'top',true);this.addField_SFFloat(ctx,'subdivision',32);var geoCacheID='Cone_'+this._vf.bottomRadius+'_'+this._vf.height+'_'+this._vf.top+'_'+ this._vf.bottom+'_'+this._vf.side+'_'+this._vf.topRadius+'_'+this._vf.subdivision;if(this._vf.useGeoCache&&x3dom.geoCache[geoCacheID]!==undefined){this._mesh=x3dom.geoCache[geoCacheID];} else{var bottomRadius=this._vf.bottomRadius,height=this._vf.height;var topRadius=this._vf.topRadius,sides=this._vf.subdivision;var beta,x,z;var delta=2.0*Math.PI/sides;var incl=(bottomRadius-topRadius)/height;var nlen=1.0/Math.sqrt(1.0+incl*incl);var j=0,k=0;var h,base;if(this._vf.side&&height>0){var px=0,pz=0;for(j=0,k=0;j<=sides;j++){beta=j*delta;x=Math.sin(beta);z=-Math.cos(beta);if(topRadius>x3dom.fields.Eps){px=x*topRadius;pz=z*topRadius;} this._mesh._positions[0].push(px,height/2,pz);this._mesh._normals[0].push(x/nlen,incl/nlen,z/nlen);this._mesh._texCoords[0].push(1.0-j/sides,1);this._mesh._positions[0].push(x*bottomRadius,-height/2,z*bottomRadius);this._mesh._normals[0].push(x/nlen,incl/nlen,z/nlen);this._mesh._texCoords[0].push(1.0-j/sides,0);if(j>0){this._mesh._indices[0].push(k);this._mesh._indices[0].push(k+2);this._mesh._indices[0].push(k+1);this._mesh._indices[0].push(k+1);this._mesh._indices[0].push(k+2);this._mesh._indices[0].push(k+3);k+=2;}}} if(this._vf.bottom&&bottomRadius>0){base=this._mesh._positions[0].length/3;for(j=sides-1;j>=0;j--){beta=j*delta;x=bottomRadius*Math.sin(beta);z=-bottomRadius*Math.cos(beta);this._mesh._positions[0].push(x,-height/2,z);this._mesh._normals[0].push(0,-1,0);this._mesh._texCoords[0].push(x/bottomRadius/2+0.5,z/bottomRadius/2+0.5);} h=base+1;for(j=2;jx3dom.fields.Eps){base=this._mesh._positions[0].length/3;for(j=sides-1;j>=0;j--){beta=j*delta;x=topRadius*Math.sin(beta);z=-topRadius*Math.cos(beta);this._mesh._positions[0].push(x,height/2,z);this._mesh._normals[0].push(0,1,0);this._mesh._texCoords[0].push(x/topRadius/2+0.5,1.0-z/topRadius/2+0.5);} h=base+1;for(j=2;j0) {var px=0,pz=0;for(j=0,k=0;j<=sides;j++){beta=j*delta;x=Math.sin(beta);z=-Math.cos(beta);if(topRadius>x3dom.fields.Eps){px=x*topRadius;pz=z*topRadius;} this._mesh._positions[0].push(px,height/2,pz);this._mesh._normals[0].push(x/nlen,incl/nlen,z/nlen);this._mesh._texCoords[0].push(1.0-j/sides,1);this._mesh._positions[0].push(x*bottomRadius,-height/2,z*bottomRadius);this._mesh._normals[0].push(x/nlen,incl/nlen,z/nlen);this._mesh._texCoords[0].push(1.0-j/sides,0);if(j>0){this._mesh._indices[0].push(k);this._mesh._indices[0].push(k+2);this._mesh._indices[0].push(k+1);this._mesh._indices[0].push(k+1);this._mesh._indices[0].push(k+2);this._mesh._indices[0].push(k+3);k+=2;}}} if(this._vf.bottom&&bottomRadius>0) {base=this._mesh._positions[0].length/3;for(j=sides-1;j>=0;j--){beta=j*delta;x=bottomRadius*Math.sin(beta);z=-bottomRadius*Math.cos(beta);this._mesh._positions[0].push(x,-height/2,z);this._mesh._normals[0].push(0,-1,0);this._mesh._texCoords[0].push(x/bottomRadius/2+0.5,z/bottomRadius/2+0.5);} h=base+1;for(j=2;jx3dom.fields.Eps) {base=this._mesh._positions[0].length/3;for(j=sides-1;j>=0;j--){beta=j*delta;x=topRadius*Math.sin(beta);z=-topRadius*Math.cos(beta);this._mesh._positions[0].push(x,height/2,z);this._mesh._normals[0].push(0,1,0);this._mesh._texCoords[0].push(x/topRadius/2+0.5,1.0-z/topRadius/2+0.5);} h=base+1;for(j=2;j0) {this._mesh._indices[0].push(k);this._mesh._indices[0].push(k+1);this._mesh._indices[0].push(k+2);this._mesh._indices[0].push(k+2);this._mesh._indices[0].push(k+1);this._mesh._indices[0].push(k+3);k+=2;}}} if(radius>0) {var h,base=this._mesh._positions[0].length/3;if(this._vf.top) {for(j=sides-1;j>=0;j--) {beta=j*delta;x=radius*Math.sin(beta);z=-radius*Math.cos(beta);this._mesh._positions[0].push(x,height,z);this._mesh._normals[0].push(0,1,0);this._mesh._texCoords[0].push(x/radius/2+0.5,-z/radius/2+0.5);} h=base+1;for(j=2;j=0;j--) {beta=j*delta;x=radius*Math.sin(beta);z=-radius*Math.cos(beta);this._mesh._positions[0].push(x,-height,z);this._mesh._normals[0].push(0,-1,0);this._mesh._texCoords[0].push(x/radius/2+0.5,z/radius/2+0.5);} h=base+1;for(j=2;j0) {var h,base=this._mesh._positions[0].length/3;if(this._vf.top) {for(j=sides-1;j>=0;j--) {beta=j*delta;x=radius*Math.sin(beta);z=-radius*Math.cos(beta);this._mesh._positions[0].push(x,height,z);}}} if(this._vf.bottom) {for(j=sides-1;j>=0;j--) {beta=j*delta;x=radius*Math.sin(beta);z=-radius*Math.cos(beta);this._mesh._positions[0].push(x,-height,z);}} this.invalidateVolume();this._mesh._numCoords=this._mesh._positions[0].length/3;Array.forEach(this._parentNodes,function(node){node._dirty.positions=true;node.invalidateVolume();});} else if(fieldName==="subdivision"||fieldName==="bottom"||fieldName==="top"||fieldName==="side") {this._mesh._positions[0]=[];this._mesh._indices[0]=[];this._mesh._normals[0]=[];this._mesh._texCoords[0]=[];var radius=this._vf.radius,height=this._vf.height/2;var sides=this._vf.subdivision;var beta,x,z,j;var delta=2.0*Math.PI/sides;var k=0;if(this._vf.side) {for(j=0,k=0;j<=sides;j++) {beta=j*delta;x=Math.sin(beta);z=-Math.cos(beta);this._mesh._positions[0].push(x*radius,-height,z*radius);this._mesh._normals[0].push(x,0,z);this._mesh._texCoords[0].push(1.0-j/sides,0);this._mesh._positions[0].push(x*radius,height,z*radius);this._mesh._normals[0].push(x,0,z);this._mesh._texCoords[0].push(1.0-j/sides,1);if(j>0) {this._mesh._indices[0].push(k+0);this._mesh._indices[0].push(k+1);this._mesh._indices[0].push(k+2);this._mesh._indices[0].push(k+2);this._mesh._indices[0].push(k+1);this._mesh._indices[0].push(k+3);k+=2;}}} if(radius>0) {var h,base=this._mesh._positions[0].length/3;if(this._vf.top) {for(j=sides-1;j>=0;j--) {beta=j*delta;x=radius*Math.sin(beta);z=-radius*Math.cos(beta);this._mesh._positions[0].push(x,height,z);this._mesh._normals[0].push(0,1,0);this._mesh._texCoords[0].push(x/radius/2+0.5,-z/radius/2+0.5);} h=base+1;for(j=2;j=0;j--) {beta=j*delta;x=radius*Math.sin(beta);z=-radius*Math.cos(beta);this._mesh._positions[0].push(x,-height,z);this._mesh._normals[0].push(0,-1,0);this._mesh._texCoords[0].push(x/radius/2+0.5,z/radius/2+0.5);} h=base+1;for(j=2;j=3){srcHeaderSize=responseBeginUint32[2];srcBodyOffset=srcHeaderSize+12;srcBodySize=xhr.response.byteLength-srcBodyOffset;if(srcHeaderSize>0&&srcBodySize>=0) {srcHeaderView=new Uint8Array(xhr.response,12,srcHeaderSize);srcBodyView=new Uint8Array(xhr.response,srcBodyOffset,srcBodySize);try {srcHeaderObj=JSON.parse(String.fromCharCode.apply(null,srcHeaderView));} catch(exc) {x3dom.debug.logError("Unable to parse SRC header: "+exc);return;} that._updateRenderDataFromSRC(shape,shaderProgram,gl,srcHeaderObj,srcBodyView);} else {x3dom.debug.logError("Invalid SRC data, loaded from URL \""+ encodeURI(that._vf['url'])+"\"");return;}} else {x3dom.debug.logError("Unable to load SRC data from URL \""+encodeURI(that._vf['url'])+"\"");}};},_updateRenderDataFromSRC:function(shape,shaderProgram,gl,srcHeaderObj,srcBodyView) {var INDEX_BUFFER_IDX=0;var POSITION_BUFFER_IDX=1;var NORMAL_BUFFER_IDX=2;var TEXCOORD_BUFFER_IDX=3;var COLOR_BUFFER_IDX=4;var ID_BUFFER_IDX=5;var MAX_NUM_BUFFERS_PER_DRAW=6;var indexViews=srcHeaderObj["accessors"]["indexViews"];var indexViewID,indexView;var attributeViews=srcHeaderObj["accessors"]["attributeViews"];var attributes;var attributeID,attributeView;var x3domTypeID,x3domShortTypeID,numComponents;var meshes=srcHeaderObj["meshes"];var mesh,meshID;var meshIdx,bufferOffset;var viewIDsToGLBufferIDs={};var indexViewBufferIDs={};for(indexViewID in indexViews) {indexView=indexViews[indexViewID];indexViewBufferIDs[indexView["bufferView"]]=true;} this._createGLBuffersFromSRCChunks(gl,srcHeaderObj["bufferChunks"],srcHeaderObj["bufferViews"],srcBodyView,indexViewBufferIDs,viewIDsToGLBufferIDs);for(indexViewID in indexViews) {indexView=indexViews[indexViewID];if(indexView["componentType"]!=gl.UNSIGNED_SHORT) {x3dom.debug.logWarning("SRC index componentType "+indexView["componentType"]+" is not UNSIGNED_SHORT. "+"Ignoring given value and assuming UNSIGNED_SHORT indices.");} shape._webgl.indexType=gl.UNSIGNED_SHORT;} meshIdx=0;bufferOffset=0;shape._webgl.primType=[];shape._webgl.indexOffset=[];shape._webgl.drawCount=[];this._mesh._numCoords=0;this._mesh._numFaces=0;for(meshID in meshes) {mesh=meshes[meshID];indexViewID=mesh["indices"];if(indexViewID!="") {shape._webgl.externalGeometry=1;indexView=indexViews[indexViewID];shape._webgl.indexOffset[meshIdx]=indexView["byteOffset"];shape._webgl.drawCount[meshIdx]=indexView["count"];shape._webgl.buffers[INDEX_BUFFER_IDX+bufferOffset]=viewIDsToGLBufferIDs[indexView["bufferView"]];this._mesh._numFaces+=indexView["count"]/3;} else {shape._webgl.externalGeometry=-1;} shape._webgl.primType[meshIdx]=mesh["primitive"];attributes=mesh["attributes"];for(attributeID in attributes) {attributeView=attributeViews[attributes[attributeID]];switch(attributeID) {case"position":x3domTypeID="coord";x3domShortTypeID="Pos";shape._webgl.buffers[POSITION_BUFFER_IDX+bufferOffset]=viewIDsToGLBufferIDs[attributeView["bufferView"]];if(mesh["indices"]=="") {shape._webgl.drawCount=attributeView["count"];this._mesh._numFaces+=attributeView["count"]/3;} this._mesh._numCoords+=attributeView["count"];break;case"normal":x3domTypeID="normal";x3domShortTypeID="Norm";shape._webgl.buffers[NORMAL_BUFFER_IDX+bufferOffset]=viewIDsToGLBufferIDs[attributeView["bufferView"]];break;case"texcoord":x3domTypeID="texCoord";x3domShortTypeID="Tex";shape._webgl.buffers[TEXCOORD_BUFFER_IDX+bufferOffset]=viewIDsToGLBufferIDs[attributeView["bufferView"]];break;case"color":x3domTypeID="color";x3domShortTypeID="Col";shape._webgl.buffers[COLOR_BUFFER_IDX+bufferOffset]=viewIDsToGLBufferIDs[attributeView["bufferView"]];break;case"id":x3domTypeID="id";x3domShortTypeID="Id";shape._webgl.buffers[ID_BUFFER_IDX+bufferOffset]=viewIDsToGLBufferIDs[attributeView["bufferView"]];break;};shape["_"+x3domTypeID+"StrideOffset"][0]=attributeView["byteStride"];shape["_"+x3domTypeID+"StrideOffset"][1]=attributeView["byteOffset"];shape._webgl[x3domTypeID+"Type"]=attributeView["componentType"];numComponents=x3dom.nodeTypes.ExternalGeometry._findNumComponentsForSRCAccessorType(attributeView["type"]);this._mesh["_num"+x3domShortTypeID+"Components"]=numComponents;} ++meshIdx;bufferOffset+=MAX_NUM_BUFFERS_PER_DRAW;} shape._nameSpace.doc.needRender=true;x3dom.BinaryContainerLoader.checkError(gl);},_createGLBuffersFromSRCChunks:function(gl,bufferChunksObj,bufferViewsObj,srcBodyView,indexViewBufferIDs,viewIDsToGLBufferIDs) {var i;var bufferView;var chunkIDList;var bufferType;var chunk;var newBuffer;var chunkDataView;var currentChunkDataOffset;for(var bufferViewID in bufferViewsObj) {bufferType=(typeof indexViewBufferIDs[bufferViewID]!=='undefined')?gl.ELEMENT_ARRAY_BUFFER:gl.ARRAY_BUFFER;bufferView=bufferViewsObj[bufferViewID];chunkIDList=bufferView["chunks"];if(chunkIDList.length==1) {chunk=bufferChunksObj[chunkIDList[0]];chunkDataView=new Uint8Array(srcBodyView.buffer,srcBodyView.byteOffset+chunk["byteOffset"],chunk["byteLength"]);newBuffer=gl.createBuffer();gl.bindBuffer(bufferType,newBuffer);gl.bufferData(bufferType,chunkDataView,gl.STATIC_DRAW);viewIDsToGLBufferIDs[bufferViewID]=newBuffer;} else {newBuffer=gl.createBuffer();gl.bindBuffer(bufferType,newBuffer);gl.bufferData(bufferType,bufferView["byteLength"],gl.STATIC_DRAW);currentChunkDataOffset=0;for(i=0;i=0);return(this._vf.lit&&hasTris);}}));x3dom.registerNodeType("BinaryGeometry","Geometry3D",defineClass(x3dom.nodeTypes.X3DBinaryContainerGeometryNode,function(ctx){x3dom.nodeTypes.BinaryGeometry.superClass.call(this,ctx);this.addField_SFString(ctx,'index',"");this.addField_SFString(ctx,'coord',"");this.addField_SFString(ctx,'normal',"");this.addField_SFString(ctx,'texCoord',"");this.addField_SFString(ctx,'color',"");this.addField_SFString(ctx,'tangent',"");this.addField_SFString(ctx,'binormal',"");this.addField_SFString(ctx,'indexType',"Uint16");this.addField_SFString(ctx,'coordType',"Float32");this.addField_SFString(ctx,'normalType',"Float32");this.addField_SFString(ctx,'texCoordType',"Float32");this.addField_SFString(ctx,'colorType',"Float32");this.addField_SFString(ctx,'tangentType',"Float32");this.addField_SFString(ctx,'binormalType',"Float32");this.addField_SFBool(ctx,'normalAsSphericalCoordinates',false);this.addField_SFBool(ctx,'rgbaColors',false);this.addField_SFInt32(ctx,'numTexCoordComponents',2);this.addField_SFBool(ctx,'normalPerVertex',true);this.addField_SFBool(ctx,'idsPerVertex',false);this._hasStrideOffset=false;this._mesh._numPosComponents=this._vf.normalAsSphericalCoordinates?4:3;this._mesh._numTexComponents=this._vf.numTexCoordComponents;this._mesh._numColComponents=this._vf.rgbaColors?4:3;this._mesh._numNormComponents=this._vf.normalAsSphericalCoordinates?2:3;this._vertexCountSum=0;for(var i=0;i=0&&strideInd>=0){offset=+this._vf.coord.substring(++offsetInd,strideInd);stride=+this._vf.coord.substring(strideInd);parent._coordStrideOffset=[stride,offset];this._hasStrideOffset=true;if((offset/8)-Math.floor(offset/8)==0){this._mesh._numPosComponents=4;}} else if(strideInd>=0){stride=+this._vf.coord.substring(strideInd);parent._coordStrideOffset=[stride,0];if((stride/8)-Math.floor(stride/8)==0){this._mesh._numPosComponents=4;}} offsetInd=this._vf.normal.lastIndexOf('#');strideInd=this._vf.normal.lastIndexOf('+');if(offsetInd>=0&&strideInd>=0){offset=+this._vf.normal.substring(++offsetInd,strideInd);stride=+this._vf.normal.substring(strideInd);parent._normalStrideOffset=[stride,offset];} else if(strideInd>=0){stride=+this._vf.normal.substring(strideInd);parent._normalStrideOffset=[stride,0];} offsetInd=this._vf.texCoord.lastIndexOf('#');strideInd=this._vf.texCoord.lastIndexOf('+');if(offsetInd>=0&&strideInd>=0){offset=+this._vf.texCoord.substring(++offsetInd,strideInd);stride=+this._vf.texCoord.substring(strideInd);parent._texCoordStrideOffset=[stride,offset];} else if(strideInd>=0){stride=+this._vf.texCoord.substring(strideInd);parent._texCoordStrideOffset=[stride,0];} offsetInd=this._vf.color.lastIndexOf('#');strideInd=this._vf.color.lastIndexOf('+');if(offsetInd>=0&&strideInd>=0){offset=+this._vf.color.substring(++offsetInd,strideInd);stride=+this._vf.color.substring(strideInd);parent._colorStrideOffset=[stride,offset];} else if(strideInd>=0){stride=+this._vf.color.substring(strideInd);parent._colorStrideOffset=[stride,0];} if(this._vf.indexType!="Uint16"&&!x3dom.caps.INDEX_UINT) x3dom.debug.logWarning("Index type "+this._vf.indexType+" problematic");},doIntersect:function(line) {var min=this.getMin();var max=this.getMax();var isect=line.intersect(min,max);if(isect&&line.enterthis._vf.bbMaxModF.x) this._vf.bbShiftVec.x=1.0;if(this._vf.bbMinModF.y>this._vf.bbMaxModF.y) this._vf.bbShiftVec.y=1.0;if(this._vf.bbMinModF.z>this._vf.bbMaxModF.z) this._vf.bbShiftVec.z=1.0;this.addField_MFNode('levels',x3dom.nodeTypes.PopGeometryLevel);this.addField_SFInt32(ctx,'attributeStride',0);this.addField_SFInt32(ctx,'positionOffset',0);this.addField_SFInt32(ctx,'normalOffset',0);this.addField_SFInt32(ctx,'texcoordOffset',0);this.addField_SFInt32(ctx,'colorOffset',0);this.addField_SFInt32(ctx,'numAnchorVertices',0);this.addField_SFInt32(ctx,'positionPrecision',2);this.addField_SFInt32(ctx,'normalPrecision',1);this.addField_SFInt32(ctx,'texcoordPrecision',2);this.addField_SFInt32(ctx,'colorPrecision',1);this.addField_SFInt32(ctx,'minPrecisionLevel',-1);this.addField_SFInt32(ctx,'maxPrecisionLevel',-1);this.addField_SFFloat(ctx,'precisionFactor',1.0);this.addField_SFString(ctx,'coordType',"Uint16");this.addField_SFString(ctx,'normalType',"Uint8");this.addField_SFString(ctx,'texCoordType',"Uint16");this.addField_SFString(ctx,'colorType',"Uint8");this.addField_SFInt32(ctx,'vertexBufferSize',0);this.addField_SFBool(ctx,'indexedRendering',true);this.addField_SFBool(ctx,'sphericalNormals',false);this.addField_MFInt32(ctx,'originalVertexCount',[0]);for(var i=0;i0){var geoCacheID='ImageGeometry_'+this._vf.implicitMeshSize.x+'_'+this._vf.implicitMeshSize.y;if(this._vf.useGeoCache&&x3dom.geoCache[geoCacheID]!==undefined) {this._mesh=x3dom.geoCache[geoCacheID];} else {for(var y=0;y0) {hasNormalInd=true;} if(texCoordInd.length>0) {hasTexCoordInd=true;} if(colorInd.length>0) {hasColorInd=true;} var positions,normals,texCoords,colors;var coordNode=this._cf.coord.node;x3dom.debug.assert(coordNode);positions=coordNode.getPoints();var normalNode=this._cf.normal.node;if(normalNode) {hasNormal=true;normals=normalNode._vf.vector;} else{hasNormal=false;} var texMode="",numTexComponents=2;var texCoordNode=this._cf.texCoord.node;if(x3dom.isa(texCoordNode,x3dom.nodeTypes.MultiTextureCoordinate)){if(texCoordNode._cf.texCoord.nodes.length) texCoordNode=texCoordNode._cf.texCoord.nodes[0];} if(texCoordNode) {if(texCoordNode._vf.point){hasTexCoord=true;texCoords=texCoordNode._vf.point;if(x3dom.isa(texCoordNode,x3dom.nodeTypes.TextureCoordinate3D)){numTexComponents=3;}} else if(texCoordNode._vf.mode){texMode=texCoordNode._vf.mode;}} else{hasTexCoord=false;} this._mesh._numTexComponents=numTexComponents;var numColComponents=3;var colorNode=this._cf.color.node;if(colorNode) {hasColor=true;colors=colorNode._vf.color;if(x3dom.isa(colorNode,x3dom.nodeTypes.ColorRGBA)){numColComponents=4;}} else{hasColor=false;} this._mesh._numColComponents=numColComponents;this._mesh._indices[0]=[];this._mesh._positions[0]=[];this._mesh._normals[0]=[];this._mesh._texCoords[0]=[];this._mesh._colors[0]=[];var i,j,t,cnt,faceCnt;var p0,p1,p2,n0,n1,n2,t0,t1,t2,c0,c1,c2;if((this._vf.creaseAngle<=x3dom.fields.Eps)||(positions.length>x3dom.Utils.maxIndexableCoords)||(hasNormal&&hasNormalInd)||(hasTexCoord&&hasTexCoordInd)||(hasColor&&hasColorInd)) {if(this._vf.creaseAngle<=x3dom.fields.Eps) x3dom.debug.logWarning('Fallback to inefficient multi-index mode since creaseAngle=0.');if(this._vf.convex){t=0;cnt=0;faceCnt=0;this._mesh._multiIndIndices=[];this._mesh._posSize=positions.length;for(i=0;i0) this._mesh._numFaces+=indexLength/3;else this._mesh._numFaces+=numCoords/3;}},fieldChanged:function(fieldName) {if(fieldName!="coord"&&fieldName!="normal"&&fieldName!="texCoord"&&fieldName!="color"&&fieldName!="coordIndex") {x3dom.debug.logWarning("IndexedFaceSet: fieldChanged for "+ fieldName+" not yet implemented!");return;} var pnts=this._cf.coord.node._vf.point;var n=pnts.length;var texCoordNode=this._cf.texCoord.node;if(x3dom.isa(texCoordNode,x3dom.nodeTypes.MultiTextureCoordinate)){if(texCoordNode._cf.texCoord.nodes.length) texCoordNode=texCoordNode._cf.texCoord.nodes[0];} if(((this._vf.creaseAngle<=x3dom.fields.Eps)||(n>x3dom.Utils.maxIndexableCoords)||(this._vf.normalIndex.length>0&&this._cf.normal.node)||(this._vf.texCoordIndex.length>0&&texCoordNode)||(this._vf.colorIndex.length>0&&this._cf.color.node))&&this._mesh._multiIndIndices) {var needNormals=!this._cf.normal.node&&this._vf.normalUpdateMode.toLowerCase()!='none';n=this._mesh._multiIndIndices.length;this._mesh._positions[0]=[];this._mesh._indices[0]=[];if(fieldName=="coord"&&n) {if(needNormals){this._mesh._normals[0]=[];} for(i=0;i0) {hasNormalInd=true;} if(texCoordInd.length>0) {hasTexCoordInd=true;} if(colorInd.length>0) {hasColorInd=true;} var positions,normals,texCoords,colors;var coordNode=this._cf.coord.node;x3dom.debug.assert(coordNode);positions=coordNode.getPoints();var normalNode=this._cf.normal.node;if(normalNode) {hasNormal=true;normals=normalNode._vf.vector;} else{hasNormal=false;} var texMode="",numTexComponents=2;texCoordNode=this._cf.texCoord.node;if(x3dom.isa(texCoordNode,x3dom.nodeTypes.MultiTextureCoordinate)){if(texCoordNode._cf.texCoord.nodes.length) texCoordNode=texCoordNode._cf.texCoord.nodes[0];} if(texCoordNode) {if(texCoordNode._vf.point){hasTexCoord=true;texCoords=texCoordNode._vf.point;if(x3dom.isa(texCoordNode,x3dom.nodeTypes.TextureCoordinate3D)){numTexComponents=3;}} else if(texCoordNode._vf.mode){texMode=texCoordNode._vf.mode;}} else{hasTexCoord=false;} this._mesh._numTexComponents=numTexComponents;var numColComponents=3;var colorNode=this._cf.color.node;if(colorNode) {hasColor=true;colors=colorNode._vf.color;if(x3dom.isa(colorNode,x3dom.nodeTypes.ColorRGBA)){numColComponents=4;}} else{hasColor=false;} this._mesh._numColComponents=numColComponents;var i,j,t,cnt,faceCnt;var p0,p1,p2,n0,n1,n2,t0,t1,t2,c0,c1,c2;if(this._vf.convex){t=0;cnt=0;faceCnt=0;this._mesh._multiIndIndices=[];this._mesh._posSize=positions.length;for(i=0;i0) this._mesh._numFaces+=indexLength/3;else this._mesh._numFaces+=numCoords/3;} Array.forEach(this._parentNodes,function(node){node.setGeoDirty();});} else{if(fieldName=="coord") {var needNormals=!this._cf.normal.node&&this._vf.normalUpdateMode.toLowerCase()!='none';this._mesh._positions[0]=pnts.toGL();if(needNormals){this._mesh.calcNormals(this._vf.creaseAngle,this._vf.ccw);} this.invalidateVolume();Array.forEach(this._parentNodes,function(node){node._dirty.positions=true;if(needNormals) node._dirty.normals=true;node.invalidateVolume();});} else if(fieldName=="color") {pnts=this._cf.color.node._vf.color;this._mesh._colors[0]=pnts.toGL();Array.forEach(this._parentNodes,function(node){node._dirty.colors=true;});} else if(fieldName=="normal") {pnts=this._cf.normal.node._vf.vector;this._mesh._normals[0]=pnts.toGL();Array.forEach(this._parentNodes,function(node){node._dirty.normals=true;});} else if(fieldName=="texCoord") {texCoordNode=this._cf.texCoord.node;if(x3dom.isa(texCoordNode,x3dom.nodeTypes.MultiTextureCoordinate)){if(texCoordNode._cf.texCoord.nodes.length) texCoordNode=texCoordNode._cf.texCoord.nodes[0];} pnts=texCoordNode._vf.point;this._mesh._texCoords[0]=pnts.toGL();Array.forEach(this._parentNodes,function(node){node._dirty.texcoords=true;});} else if(fieldName=="coordIndex") {needNormals=!this._cf.normal.node&&this._vf.normalUpdateMode.toLowerCase()!='none';indexes=this._vf.coordIndex;t=0;n=indexes.length;this._mesh._indices[0]=[];for(i=0;i=0) {sqrt_part=Math.sqrt(sqrt_part);alpha_1=-p*0.5+sqrt_part;alpha_2=-p*0.5-sqrt_part;alpha_1=Math.min(alpha_1,alpha_2);if(alpha_1>0.0) {var hitPoint=viewRay.pos.add(viewRay.dir.multiply(alpha_1));var closestPointOnYAxis=this._yAxisLine.closestPoint(hitPoint);var vecToHitPoint=hitPoint.subtract(closestPointOnYAxis).normalize();this._currentRotation=x3dom.fields.Quaternion.rotateFromTo(this._initialCylinderIntersectionVector,vecToHitPoint);var offsetQuat=x3dom.fields.Quaternion.axisAngle(this._yAxisLine.dir,this._vf["offset"]);this._currentRotation=this._currentRotation.multiply(offsetQuat);this.postMessage('rotation_changed',this._currentRotation);}}} else {}},_stopDragging:function() {x3dom.nodeTypes.X3DDragSensorNode.prototype._stopDragging.call(this);if(this._vf["autoOffset"]) {this._vf["offset"]=this._currentRotation.angle();this.postMessage('offset_changed',this._vf["offset"]);}}}));x3dom.versionInfo={version:'1.6.0',revision:'5e8c0441fe2cbe9970ffd14f1546100672a95185',date:'Thu May 8 20:51:15 2014 +0200'};