var cds=cds||{};THREE.Object3D.prototype.getBoundingBox=function(){return new THREE.Box3().setFromObject(this)}
THREE.Box3.prototype.getLength=function(){var v1=this.max;var v2=this.min;var dx=v1.x-v2.x;var dy=v1.y-v2.y;var dz=v1.z-v2.z;var len=Math.sqrt(dx*dx+dy*dy+dz*dz);return len;}
cds.cadViewer={MODE_SHADED:0,MODE_WIREFRAME:1,MODE_TRANSPARENT:2,VIEW_ISOMETRIC:0,VIEW_TOP:1,VIEW_LEFT:2,VIEW_BOTTOM:3,VIEW_RIGHT:4,ZOOM_MULTIPLIER:5.0,AMBIENT_COLOR:0x303030,SPOTLIGHT_COLOR:0xFFFFFF,SPOTLIGHT_INTENSITY:0.5,LOADING_ICON_URL:"https://dpk3n3gg92jwt.cloudfront.net/cadviewer/images/loading_gears.gif",CANVAS_WIDTH:200,CANVAS_HEIGHT:200,CAM_DISTANCE:50,facing:null,ENVIRONMENT_MAP_URLS:["https://dpk3n3gg92jwt.cloudfront.net/cadviewer/images/0004.png","https://dpk3n3gg92jwt.cloudfront.net/cadviewer/images/0002.png","https://dpk3n3gg92jwt.cloudfront.net/cadviewer/images/0006.png","https://dpk3n3gg92jwt.cloudfront.net/cadviewer/images/0005.png","https://dpk3n3gg92jwt.cloudfront.net/cadviewer/images/0001.png","https://dpk3n3gg92jwt.cloudfront.net/cadviewer/images/0003.png"],targetList:[],parentElement:null,container:null,viewerHeight:0,viewerWidth:0,spotLight:null,ambientLight:null,camera:null,camera2:null,scene:null,scene2:null,overlayScene:null,renderer:null,renderer2:null,composer:null,controls:null,sceneObject:null,sceneBoundingBox:null,cameraPosX:0,cameraPosY:0,cameraPosZ:0,cameraRotX:0,cameraRotY:0,cameraRotZ:0,loadingIcon:null,isLoading:false,currentFileName:null,showBoundingBox:false,sceneBoundingBoxIndicator:null,INTERSECTED:null,raycaster:null,mouse:null,showSpinCenters:false,spinCenters:null,edgesHelpers:[],edgeOccluder:null,edgeEffect:null,currentRenderMode:this.MODE_SHADED,originalSceneObjectMatertials:[],projector:null,isMouseDown:false,isRotated:false,translationSum:0,textureCube:null,previousPartAdded:null,bbs:[],clock:null,frameId:null,isMobile:false,prevViewerWidth:0,prevViewerHeight:0,isRenderingAllowed:true,cacheWebGLAvailability:null,cnt:1,hlColor:null,useCustomToolTipText:false,mouseSubscribed:false,openAssemblyInNewTab:false,annotationSubscribed:null,explosionSubscribed:null,firstWireframe:1,isMouseUp:false,originalVectors:undefined,explodedVectors:undefined,explodeEffect:null,raycaster:new THREE.Raycaster(),mouse:new THREE.Vector2(),INTERSECTED:undefined,intersectedPart:undefined,annoTemp:new THREE.Object3D(),texturemap:"/texture/bricks.jpg",pivot:null,rotateSpeed:null,tempcolor:null,rendertemp:1,explode:false,tooltip_span:null,subAssemblyLoaded:false,viewerVersion:"QA 205.1",environment:{type:'Relfection',map:'cloud'},skyBox:"cloud",ENVIRONMENT_MAP:{CLOUD:"cloud",CASTLE:"castle",BRIDGE:"bridge",CLOUDYDAY:"cloudyday",DESERTHIGHWAY:"deserthighway",AUTOSHOP:"autoshop",STUDIO6:"studio6",STUDIO2:"studio2",ROOM:"room",ROCKY:"rocky",FIELD:"field",CITY:"city"},ENVIRONMENT_TYPE:{REFLECTION:"Reflection",REFRACTION:"Refraction",},environmentMapEnabled:false,reflectiveMaterials:[],cadFilePath:null,isAssembly:false,showPercentLoader:false,urlToSceneObjectMap:[],studio:null,partNameToObject3d:[],instancingEnabled:false,partFileSize:undefined,studioMaterials:[],studioEnvironmentMaps:[],zoomPercentage:0,replacedAssemblyToPartName:[],recursiveExplosion:false,init:function(parentElementId){"use strict";if(!this.isWebGLAvailable()){console.log("Error in CDS CAD viewer: webGL not available");return;}
THREE.ShaderChunk.map_fragment=THREE.ShaderChunk.map_fragment.replace("diffuseColor *= texelColor;","diffuseColor = vec4( mix( diffuse, texelColor.rgb, texelColor.a ), opacity );");this.parentElement=document.getElementById(parentElementId);if(!this.parentElement){console.log("Could not initialize CDS CAD viewer: invalid container element id "+parentElementId);return;}
this.mouse=new THREE.Vector2();this.container=document.createElement("div");this.container.setAttribute("class","cds-cad-viewer-container");this.parentElement.appendChild(this.container);if(!cds.cadViewer.showPercentLoader){this.loadingIcon=document.createElement("div");this.loadingIcon.setAttribute("class","cds-cad-viewer-loading-icon");this.container.appendChild(this.loadingIcon);var img=document.createElement("img");img.setAttribute("src",this.LOADING_ICON_URL);img.setAttribute("class","cds-cad-viewer-loading-icon-image");this.loadingIcon.appendChild(img);}
this.renderer=new THREE.WebGLRenderer({antialias:true,preserveDrawingBuffer:true,clearColor:0xFFFFFF,clearAlpha:1,alpha:true,stencil:false,logarithmicDepthBuffer:true});this.renderer.autoClear=false;var self=this;this.renderer.domElement.addEventListener("webglcontextlost",function(e){console.log("Error in CDS CAD viewer: context is lost, cancelling animation frame "+self.frameId);e.preventDefault();cancelAnimationFrame(self.frameId);window.location.reload();},false);this.renderer.domElement.addEventListener("webglcontextrestored",function(e){console.log("Warning in CDS CAD viewer: context is restored "+e);e.preventDefault();},false);THREEx.FullScreen.init(this.renderer.domElement);this.getViewerSize();this.renderer.setSize(this.viewerWidth,this.viewerHeight);this.renderer.setClearColor(0x000000,0);this.container.appendChild(this.renderer.domElement);this.renderer.domElement.setAttribute("id","cds-cad-viewer-renderer");this.renderer.gammaInput=true;this.renderer.gammaOutput=true;this.scene=new THREE.Scene();this.overlayScene=new THREE.Scene();this.camera=new THREE.PerspectiveCamera(45,this.viewerWidth/this.viewerHeight,0.1,200000);this.camera.position.z=60;this.camera.position.y=60;this.camera.position.x=60;this.scene.add(this.camera);this.mouse.x=0;this.mouse.y=0;this.ambientLight=new THREE.AmbientLight(this.AMBIENT_COLOR);this.scene.add(this.ambientLight);this.spotLight=new THREE.SpotLight(this.SPOTLIGHT_COLOR,this.SPOTLIGHT_INTENSITY);this.scene.add(this.spotLight);this.camera.add(this.spotLight);this.spotLight.position.set(190,190,165);this.spotLight.target.position.set(0,0,-1);this.controls=new THREE.TrackballControls(this.camera,this.renderer.domElement);this.controls.target.set(0,0,0);this.clock=new THREE.Clock();this.composer=new THREE.EffectComposer(this.renderer);this.composer.addPass(new THREE.RenderPass(this.scene,this.camera));this.edgeEffect=new THREE.ShaderPass(THREE.EdgeShader);this.edgeEffect.uniforms.aspect.value.x=this.viewerWidth;this.edgeEffect.uniforms.aspect.value.y=this.viewerHeight;this.edgeEffect.renderToScreen=true;this.edgeEffect.enabled=false;this.composer.addPass(this.edgeEffect);this.renderer2=new THREE.WebGLRenderer({antialias:true,alpha:true,});this.renderer2.autoClear=false;THREEx.FullScreen.init(this.renderer2.domElement);this.getViewerSize();this.renderer2.setSize(this.viewerWidth/10,this.viewerHeight/10);this.renderer2.setClearColor(0x000000,0);this.renderer2.setPixelRatio(window.devicePixelRatio)
this.container.appendChild(this.renderer2.domElement);this.renderer2.domElement.setAttribute("id","inset");this.scene2=new THREE.Scene();this.camera2=new THREE.PerspectiveCamera(50,this.viewerWidth/this.viewerHeight,1,1000);this.camera2.up=this.camera.up;this.scene2.add(this.camera2);var axes=new THREE.AxesHelper(25);this.scene2.add(axes);if(this.renderer&&this.renderer.context){this.renderer.context.getProgramInfoLog=function(){return"";};}
this.projector=new THREE.Projector();this.animate();this.isMobile="onorientationchange"in window;window.addEventListener("resize",this.onWindowResize,false);if(this.isMobile){window.addEventListener("orientationchange",function(){setTimeout(self.onWindowResize,100);});}
document.addEventListener("mousemove",this.onMouseMove,false);this.renderer.domElement.addEventListener("mousedown",this.onMouseDown,false);this.renderer.domElement.addEventListener("mouseup",this.onMouseUp,false);this.renderer.domElement.addEventListener('dblclick',cds.cadViewer.onMouseDoubleClick,false);},traverse:function(sceneObject,onObjectFound,onComplete){var childCount=sceneObject.children.length;for(var i=0;i<sceneObject.children.length;i++){if(sceneObject.children[i].children[0]!=undefined){if(sceneObject.children[i].children[0].type=='Group'){onObjectFound(sceneObject.children[i])
cds.cadViewer.traverse(sceneObject.children[i],onObjectFound,function(){if(--childCount==0){onComplete()}})}else if(sceneObject.children[i].children[0].type=='Object3D'){onObjectFound(sceneObject.children[i])
cds.cadViewer.traverse(sceneObject.children[i],onObjectFound,function(){if(--childCount==0){onComplete()}})}else{onObjectFound(sceneObject.children[i])
onObjectFound(sceneObject.children[i].children[0])
if(--childCount==0){onComplete()}}}else{onObjectFound(sceneObject.children[i])
if(--childCount==0){onComplete()}}}},getAssemblyId:function(){var asmUrl=/[\\&&]asm=([^&#]*)/.exec(window.location.search);if(asmUrl==null){return undefined;}else{return asmUrl[1];}},showProgressBar:function(isAssembly){cds.cadViewer.showPercentLoader=true;document.getElementById("circularProgress").style.display='inline'
cds.cadViewer.isAssembly=isAssembly},toggleInstancing:function(){cds.cadViewer.instancingEnabled=!cds.cadViewer.instancingEnabled;},setPartFileSize:function(partFileSize){cds.cadViewer.partFileSize=partFileSize;},loadScene:function(path){var assemblyId=cds.cadViewer.getAssemblyId();if(assemblyId!=undefined){cds.cadViewer.subAssemblyLoaded=true;}"use strict";if(!path){console.log("Could not initialize CDS CAD viewer: no CAD model to loadScene");return;}else{cds.cadViewer.cadFilePath=path}
if(path.indexOf("//")===0){path="https:"+path;}
if(document.getElementById("explodeViewCheckbox")!=null)
if(document.getElementById("explodeViewCheckbox").checked==true)
document.getElementById("explodeViewCheckbox").checked=false;if(cds.cadViewer.facing==null)
cds.cadViewer.facing=THREE.DoubleSide;if(document.getElementById("explosionSubscription")!=null){document.getElementById("explosionSubscription").checked=false;cds.cadViewer.explosionSubscribed=undefined;document.getElementById("explosionEverything").style.visibility="hidden";document.getElementById("explodeViewCheckbox").style.visibility="hidden";}
if(document.getElementById("mouseSubscription")!=null){document.getElementById("mouseSubscription").checked=false;cds.cadViewer.mouseSubscribed=undefined;}
if(document.getElementById("annotSubscription")!=null)
document.getElementById("annotSubscription").checked=false;if(document.getElementById("highlight")!=null)
document.getElementById("highlight").style.visibility="visible";if(document.getElementById("gridRadio")!=null)
document.getElementById("gridRadio").checked=true;if(document.getElementById("logoRadio")!=null)
document.getElementById("logoRadio").checked=true;this.textureCube=new THREE.TextureLoader();var texture0=this.textureCube.load(this.ENVIRONMENT_MAP_URLS[0]);var texture1=this.textureCube.load(this.ENVIRONMENT_MAP_URLS[1]);var texture2=this.textureCube.load(this.ENVIRONMENT_MAP_URLS[2]);var texture3=this.textureCube.load(this.ENVIRONMENT_MAP_URLS[3]);var texture4=this.textureCube.load(this.ENVIRONMENT_MAP_URLS[4]);var texture5=this.textureCube.load(this.ENVIRONMENT_MAP_URLS[5]);var vector=new THREE.Vector3(0,0,0);vector.unproject(this.camera);var raycaster=new THREE.Raycaster(this.camera.position,vector.sub(this.camera.position).normalize());var intersections=raycaster.intersectObjects(this.scene.children,true);if(this.isLoading===true){console.log("Warning in CDS CAD viewer: Cannot load new model while loading still in progress");return;}
this.controls.enabled=false;this.isLoading=true;this.closeScene();if(!cds.cadViewer.hasOwnProperty('CADURL')){cds.cadViewer.cadDirectory=path.substr(0,path.lastIndexOf('/')+1);}
switch(path.split('.').pop().toLowerCase()){case"js":this.loadRemoteScript(path,this.onSceneLoad);break;case"json":this.readJSON(path,assemblyId);break;default:console.log('Invalid file type found...');}},loadJSON:function(filePath,json){var loader=new THREE.ObjectLoader();loader.texturePath=cds.cadViewer.RemoveLastDirectoryPartOf(filePath)+'/'
loader.setCrossOrigin('Anonymous');loader.parse(json,function(loadedScene){cds.cadViewer.onSceneLoad(filePath,loadedScene);});},RemoveLastDirectoryPartOf:function(the_url){var the_arr=the_url.split('/');the_arr.pop();return(the_arr.join('/'));},dispose:function(){"use strict";this.closeScene();this.composer=null;this.scene=null;this.overlayScene=null;this.controls=null;this.renderer=null;},closeScene:function(){"use strict";if(this.scene!==null){if(this.sceneBoundingBoxIndicator!==null){this.overlayScene.remove(this.sceneBoundingBoxIndicator);this.sceneBoundingBoxIndicator=null;}
if(this.spinCenters!==null){if(this.spinCenters instanceof THREE.Object3D){this.spinCenters.traverse(function(mesh){if(mesh instanceof THREE.Mesh){mesh.geometry.dispose();if(mesh.material.length!=undefined){if(mesh.material.length>0){for(var i=0;i<mesh.material.length;i++){if(mesh.material[i].map){mesh.material[i].map.dispose();}
mesh.material[i].dispose();}}}else{if(mesh.material.map){mesh.material.map.dispose();}
mesh.material.dispose();}}});}
this.overlayScene.remove(this.spinCenters);this.spinCenters=null;}
if(this.sceneObject!==null){var object=this.sceneObject;if(object instanceof THREE.Object3D){object.traverse(function(mesh){if(mesh instanceof THREE.Mesh){mesh.geometry.dispose();if(mesh.material.length!=undefined){if(mesh.material.length>0){for(var i=0;i<mesh.material.length;i++){if(mesh.material[i].map){mesh.material[i].map.dispose();}
mesh.material[i].dispose();}}}else{if(mesh.material.map){mesh.material.map.dispose();}
mesh.material.dispose();}}});}
this.scene.remove(this.sceneObject);this.sceneObject=null;}
this.sceneBoundingBox=null;this.clearBaseGridFromScene();if(cds.cadViewer.hasOwnProperty('toggleShadow')&&cds.cadViewer.hasOwnProperty('shadows')){cds.cadViewer.shadows.removeShadows();}}},isWebGLAvailable:function(){"use strict";var i,e,canvas,context,names;if(this.cacheWebGLAvailability){return this.cacheWebGLAvailability;}
if(!window.WebGLRenderingContext){this.cacheWebGLAvailability=false;return false;}
canvas=document.createElement("canvas");if(!canvas){this.cacheWebGLAvailability=false;return false;}
names=["webgl","experimental-webgl","webkit-3d","moz-webgl"];for(i=0;i<names.length;++i){try{context=canvas.getContext(names[i]);}catch(e){}
if(context){this.cacheWebGLAvailability=true;return true;}}
this.cacheWebGLAvailability=false;return false;},setupGui:function(){effectController={shininess:40.0,ka:0.17,kd:0.51,ks:0.2,metallic:true,hue:0.121,saturation:0.73,lightness:0.66,lhue:0.04,lsaturation:0.01,llightness:1.0,lx:0.32,ly:0.39,lz:0.7,newTess:15,bottom:true,lid:true,body:true,fitLid:false,nonblinn:false,newShading:"glossy"};var h;var gui=new dat.GUI();h=gui.addFolder("Material control");h.add(effectController,"shininess",1.0,400.0,1.0).name("shininess").onChange(render);h.add(effectController,"kd",0.0,1.0,0.025).name("diffuse strength").onChange(render);h.add(effectController,"ks",0.0,1.0,0.025).name("specular strength").onChange(render);h.add(effectController,"metallic").onChange(render);h=gui.addFolder("Material color");h.add(effectController,"hue",0.0,1.0,0.025).name("hue").onChange(render);h.add(effectController,"saturation",0.0,1.0,0.025).name("saturation").onChange(render);h.add(effectController,"lightness",0.0,1.0,0.025).name("lightness").onChange(render);h=gui.addFolder("Lighting");h.add(effectController,"lhue",0.0,1.0,0.025).name("hue").onChange(render);h.add(effectController,"lsaturation",0.0,1.0,0.025).name("saturation").onChange(render);h.add(effectController,"llightness",0.0,1.0,0.025).name("lightness").onChange(render);h.add(effectController,"ka",0.0,1.0,0.025).name("ambient").onChange(render);h=gui.addFolder("Light direction");h.add(effectController,"lx",-1.0,1.0,0.025).name("x").onChange(render);h.add(effectController,"ly",-1.0,1.0,0.025).name("y").onChange(render);h.add(effectController,"lz",-1.0,1.0,0.025).name("z").onChange(render);h=gui.addFolder("Tessellation control");h.add(effectController,"newTess",[2,3,4,5,6,8,10,15,20,30,40,50]).name("Tessellation Level").onChange(render);h.add(effectController,"lid").name("display lid").onChange(render);h.add(effectController,"body").name("display body").onChange(render);h.add(effectController,"bottom").name("display bottom").onChange(render);h.add(effectController,"fitLid").name("snug lid").onChange(render);h.add(effectController,"nonblinn").name("original scale").onChange(render);h=gui.add(effectController,"newShading",["wireframe","flat","smooth","glossy","textured","reflective"]).name("Shading").onChange(render);},setRenderMode:function(mode){"use strict";if(mode===this.currentRenderMode){return;}
switch(mode){case this.MODE_SHADED:this.currentRenderMode=mode;this.setObjectMaterialDepthAndSide(this.sceneObject,true,true,THREE.FrontSide);this.setObjectOpacity(this.sceneObject,1.0,false);this.removeWireframe();break;case this.MODE_TRANSPARENT:this.currentRenderMode=mode;this.setObjectMaterialDepthAndSide(this.sceneObject,false,false,THREE.FrontSide);this.setObjectOpacity(this.sceneObject,0.5,true);this.removeWireframe();break;case this.MODE_WIREFRAME:this.currentRenderMode=mode;this.setObjectMaterialDepthAndSide(this.sceneObject,true,true,THREE.FrontSide);this.setObjectOpacity(this.sceneObject,1.0,false);this.renderWireframe();break;default:console.log("Error in CDS CAD viewer: invalid render mode "+mode);break;}},setObjectMaterialDepthAndSide:function(object,depthTest,depthWrite,side){"use strict";if(object instanceof THREE.Object3D){object.traverse(function(mesh){if(mesh instanceof THREE.Mesh){if(mesh.material.length!=undefined){for(var i=0;i<mesh.material.length;i++){if(mesh.material[i]){if(mesh.parent.type!="Group"){mesh.material[i].side=THREE.FrontSide;}
mesh.material[i].depthTest=depthTest;mesh.material[i].depthWrite=depthWrite;}}}else{if(mesh.material){if(mesh.parent.type!="Group"){mesh.material.side=THREE.FrontSide;}
mesh.material.depthTest=depthTest;mesh.material.depthWrite=depthWrite;}}}});}},setObjectOpacity:function(object,opacity,isTransparent){"use strict";if(object instanceof THREE.Object3D){object.traverse(function(mesh){if(mesh instanceof THREE.Mesh){for(var i=0;i<mesh.material.length;i++){if(mesh.material[i]){mesh.material[i].transparent=isTransparent;mesh.material[i].opacity=opacity;}}}else{if(mesh.material){mesh.material.transparent=isTransparent;mesh.material.opacity=opacity;}}});}},renderWireframe:function(){"use strict";this.removeEdgesHelpers();var self=this;var geo,mat,wireframe;if(this.sceneObject instanceof THREE.Object3D){this.sceneObject.traverse(function(mesh){if(mesh instanceof THREE.Mesh){if(mesh.material.length!=undefined){for(var i=0;i<mesh.material.length;i++){if(mesh.material[i]){mesh.material[i].side=THREE.DoubleSide;}}}else{if(mesh.material){mesh.material.side=THREE.DoubleSide;}}
geo=new THREE.EdgesGeometry(mesh.geometry);mat=new THREE.LineBasicMaterial({color:0x3D3D3D,linewidth:1});wireframe=new THREE.LineSegments(geo,mat);if(cds.cadViewer.firstWireframe==1)
mesh.add(wireframe);for(var i=0;i<mesh.children.length;i++){mesh.children[i].visible=true;}
mesh.visible=false;self.edgesHelpers.push(mesh.children[0]);}});this.edgeEffect.enabled=true;this.createEdgeOccluder();}},removeWireframe:function(){"use strict";this.removeEdgesHelpers();var i;if(this.sceneObject instanceof THREE.Object3D){this.edgeEffect.enabled=false;this.sceneObject.traverse(function(mesh){if(mesh instanceof THREE.Mesh){mesh.visible=true;cds.cadViewer.firstWireframe=2;for(i=0;i<mesh.children.length;i++){mesh.children[i].visible=false;}}});}
if(this.showBoundingBox){this.sceneBoundingBoxIndicator.traverse(function(obj){if(obj instanceof THREE.Object3D){obj.traverse(function(mesh){if(mesh instanceof THREE.Mesh||mesh instanceof THREE.Line){if(mesh.material.length!=undefined){for(var i=0;i<mesh.material.length;i++){if(mesh.material[i]){mesh.material[i].depthTest=true;mesh.material[i].depthWrite=true;mesh.material[i].transparent=false;mesh.material[i].side=THREE.FrontSide;mesh.material[i].polygonOffset=true;mesh.material[i].polygonOffsetFactor=0.2;mesh.material[i].polygonOffsetUnits=1.0;}}}else{if(mesh.material){mesh.material.depthTest=true;mesh.material.depthWrite=true;mesh.material.transparent=false;mesh.material.side=THREE.FrontSide;mesh.material.polygonOffset=true;mesh.material.polygonOffsetFactor=0.2;mesh.material.polygonOffsetUnits=1.0;}}}});}});}},createEdgeOccluder:function(){"use strict";if(this.edgeOccluder){this.scene.remove(this.edgeOccluder);}
this.edgeOccluder=this.sceneObject.clone();this.edgeOccluder.traverse(function(mesh){if(mesh instanceof THREE.Mesh){mesh.visible=true;if(mesh.material){mesh.material=new THREE.MeshBasicMaterial({"color":0xffffff});mesh.material.opacity=0.05;mesh.material.polygonOffset=true;mesh.material.polygonOffsetFactor=0.2;mesh.material.polygonOffsetUnits=1.0;}}});this.edgeOccluder.scale.set(this.edgeOccluder.scale.x*0.994,this.edgeOccluder.scale.y*0.994,this.edgeOccluder.scale.z*0.994);this.scene.add(this.edgeOccluder);if(this.showBoundingBox){this.sceneBoundingBoxIndicator.traverse(function(obj){if(obj instanceof THREE.Object3D){obj.traverse(function(mesh){if(mesh instanceof THREE.Mesh||mesh instanceof THREE.Line){if(mesh.material.length!=undefined){for(var i=0;i<mesh.material.length;i++){if(mesh.material[i]){mesh.material[i].depthTest=false;mesh.material[i].depthWrite=false;mesh.material[i].transparent=true;mesh.material[i].side=THREE.FrontSide;mesh.material[i].polygonOffset=true;mesh.material[i].polygonOffsetFactor=0.2;mesh.material[i].polygonOffsetUnits=1.0;}}}else{if(mesh.material){mesh.material.depthTest=false;mesh.material.depthWrite=false;mesh.material.transparent=true;mesh.material.side=THREE.FrontSide;mesh.material.polygonOffset=true;mesh.material.polygonOffsetFactor=0.2;mesh.material.polygonOffsetUnits=1.0;}}}});}});}},removeEdgesHelpers:function(){"use strict";if(this.edgeOccluder!==null){this.scene.remove(this.edgeOccluder);this.edgeOccluder=null;}
var self=this;this.edgesHelpers.forEach(function(eh){if(eh instanceof THREE.Object3D){eh.traverse(function(mesh){if(mesh instanceof THREE.Mesh){mesh.geometry.dispose();if(mesh.material.length!=undefined){for(var i=0;i<mesh.material.length;i++){if(mesh.material[i]){if(mesh.material[i].map){mesh.material[i].map.dispose();}
mesh.material[i].dispose();}}}else{if(mesh.material){if(mesh.material.map){mesh.material.map.dispose();}
mesh.material.dispose();}}}});self.scene.remove(eh);}});this.edgesHelpers.length=0;},setOrientation:function(view){"use strict";var val=cds.cadViewer.getCameraPositionValueForView();this.resetCamera()
switch(view){case this.VIEW_ISOMETRIC:break;case this.VIEW_TOP:cds.cadViewer.studioUtils.animateParam(this.controls.target,this.sceneObject.getBoundingBox().getCenter(),function(){})
cds.cadViewer.studioUtils.animateParam(this.camera.position,new THREE.Vector3(0,val,0),function(){})
cds.cadViewer.studioUtils.animateParam(this.camera.up,new THREE.Vector3(1,0,0),function(){})
break;case this.VIEW_LEFT:cds.cadViewer.studioUtils.animateParam(this.controls.target,this.sceneObject.getBoundingBox().getCenter(),function(){})
cds.cadViewer.studioUtils.animateParam(this.camera.position,new THREE.Vector3(-val,0,0),function(){})
cds.cadViewer.studioUtils.animateParam(this.camera.up,new THREE.Vector3(0,1,0),function(){})
break;case this.VIEW_BOTTOM:cds.cadViewer.studioUtils.animateParam(this.controls.target,this.sceneObject.getBoundingBox().getCenter(),function(){})
cds.cadViewer.studioUtils.animateParam(this.camera.position,new THREE.Vector3(0,-val,0),function(){})
cds.cadViewer.studioUtils.animateParam(this.camera.up,new THREE.Vector3(-1,0,0),function(){})
break;case this.VIEW_RIGHT:cds.cadViewer.studioUtils.animateParam(this.controls.target,this.sceneObject.getBoundingBox().getCenter(),function(){})
cds.cadViewer.studioUtils.animateParam(this.camera.position,new THREE.Vector3(val,0,0),function(){})
cds.cadViewer.studioUtils.animateParam(this.camera.up,new THREE.Vector3(0,1,0),function(){})
break;default:console.log("Error in CDS CAD viewer: invalid view orientation "+view);break;}
this.render();cds.cadViewer.controls.noZoom=false
cds.cadViewer.controls.noPan=false},resetCamera:function(){"use strict";if(!cds.cadViewer.scene.children[2].userData.hasOwnProperty("boundingBox")){cds.cadViewer.studioUtils.animateParam(this.camera.position,new THREE.Vector3(this.cameraPosX,this.cameraPosY,this.cameraPosZ),function(){})
cds.cadViewer.studioUtils.animateParam(this.camera.rotation,new THREE.Vector3(this.cameraRotX,this.cameraRotY,this.cameraRotZ),function(){})
cds.cadViewer.studioUtils.animateParam(this.camera.up,new THREE.Vector3(0,1,0),function(){})
this.camera.updateProjectionMatrix();}
if(cds.cadViewer.scene.children[2].userData.hasOwnProperty("boundingBox")){var bbox=cds.cadViewer.sceneObject.getBoundingBox();var center=bbox.getCenter();this.controls.update();cds.cadViewer.studioUtils.animateParam(this.controls.target,new THREE.Vector3(center.x,center.y,center.z),function(){})
cds.cadViewer.studioUtils.animateParam(this.camera.position,new THREE.Vector3(this.cameraPosX,this.cameraPosY,this.cameraPosZ),function(){})
cds.cadViewer.studioUtils.animateParam(this.camera.up,new THREE.Vector3(0,1,0),function(){})
this.camera.updateProjectionMatrix();}},getCameraPositionValueForView:function(){var dist;if(cds.cadViewer.scene.children[2].userData.hasOwnProperty("boundingBox")){dist=cds.cadViewer.camera.position.distanceTo(cds.cadViewer.sceneObject.position);}else if(!cds.cadViewer.scene.children[2].userData.hasOwnProperty("boundingBox")){dist=100;}
return dist;return dist;},setFullScreen:function(){"use strict";THREEx.FullScreen.init(this.renderer.domElement);THREEx.FullScreen.init(this.renderer2.domElement);if(!THREEx.FullScreen.available()){console.log("FullScreen mode not available");}else{if(!THREEx.FullScreen.activated()){this.prevViewerWidth=this.viewerWidth;this.prevViewerHeight=this.viewerHeight;}
this.renderer.setClearColor(0x000000,0);this.renderer2.setClearColor(0x000000,0);THREEx.FullScreen.request(this.container);}},toggleBoundingBoxDisplay:function(){"use strict";this.showBoundingBox=!this.showBoundingBox;if(this.showBoundingBox){if(this.sceneBoundingBoxIndicator===null){this.sceneBoundingBoxIndicator=new THREE.BoxHelper(this.sceneObject,0x00ff00);this.overlayScene.add(this.sceneBoundingBoxIndicator);}}else{if(this.sceneBoundingBoxIndicator!==null){this.overlayScene.remove(this.sceneBoundingBoxIndicator);this.sceneBoundingBoxIndicator=null;}}},toggleSpinCenterDisplay:function(){"use strict";this.showSpinCenters=!this.showSpinCenters;if(this.showSpinCenters){if(this.spinCenters===null){this.spinCenters=new THREE.Object3D();var dir=new THREE.Vector3(1,0,0);var origin=this.sceneObject.position;var length=30;this.spinCenters.add(new THREE.ArrowHelper(dir,origin,length,0xff0000));this.spinCenters.add(new THREE.ArrowHelper(new THREE.Vector3(0,1,0),origin,length,0x00ff00));this.spinCenters.add(new THREE.ArrowHelper(new THREE.Vector3(0,0,1),origin,length,0x0000ff));this.spinCenters.add(new THREE.AxisHelper(22));this.spinCenters.traverse(function(obj){if(obj instanceof THREE.Object3D){obj.traverse(function(mesh){if(mesh instanceof THREE.Mesh||mesh instanceof THREE.Line){if(mesh.material){mesh.material.depthTest=false;mesh.material.depthWrite=false;mesh.material.transparent=true;mesh.material.side=THREE.FrontSide;mesh.material.polygonOffset=true;mesh.material.polygonOffsetFactor=0.2;mesh.material.polygonOffsetUnits=1.0;}}});}});this.overlayScene.add(this.spinCenters);}}else{if(this.spinCenters!==null){if(this.spinCenters instanceof THREE.Object3D){this.spinCenters.traverse(function(mesh){if(mesh instanceof THREE.Mesh){mesh.geometry.dispose();if(mesh.material){if(mesh.material.map){mesh.material.map.dispose();}
mesh.material.dispose();}}});}
this.overlayScene.remove(this.spinCenters);this.spinCenters=null;}}},render:function(){"use strict";var l;if(cds.cadViewer.scene){l=cds.cadViewer.scene.children.length;for(var i=0;i<l;i++){if(cds.cadViewer.scene.children[i].type=="Object3D"){var object=cds.cadViewer.scene.children[i];if(this.rotateSpeed==undefined)
this.rotateSpeed=0.0;object.rotation.y+=this.rotateSpeed;}}}
if(cds.cadViewer.hasOwnProperty('studioUtils')){if(cds.cadViewer.studioUtils.mixer)
cds.cadViewer.studioUtils.mixer.update(this.clock.getDelta());if(cds.cadViewer.studioUtils.annotationFactory.length>0)
cds.cadViewer.studioUtils.updateAnnotation();}
if(this.controls&&this.renderer&&this.camera2&&this.camera2.position&&this.scene2){this.controls.update();this.renderer.clear(true,true,true);this.camera2.position.copy(this.camera.position);this.camera2.position.sub(this.controls.target);this.camera2.position.setLength(this.CAM_DISTANCE);this.camera2.lookAt(this.scene2.position);}
if(this.composer&&this.renderer2&&this.render){if(this.edgeEffect.enabled){this.composer.render();this.renderer2.render(this.scene2,this.camera2);}else{this.renderer.render(this.scene,this.camera);this.renderer2.render(this.scene2,this.camera2);}
if(this.showBoundingBox||this.showSpinCenters){this.renderer.render(this.overlayScene,this.camera);this.renderer2.render(this.scene2,this.camera2);}}},setLightAttributes:function(ambientLightColor,spotLightColor,spotLightIntensity){"use strict";this.ambientLight.color.setHex(ambientLightColor);this.spotLight.color.setHex(spotLightColor);this.spotLight.intensity=spotLightIntensity;},getViewerSize:function(){"use strict";if(THREEx.FullScreen.available()&&THREEx.FullScreen.activated()){this.viewerWidth=window.innerWidth;this.viewerHeight=window.innerHeight;}else{if(document.defaultView&&document.defaultView.getComputedStyle){this.viewerWidth=parseFloat(document.defaultView.getComputedStyle(this.parentElement,null).getPropertyValue("width"));this.viewerHeight=parseFloat(document.defaultView.getComputedStyle(this.parentElement,null).getPropertyValue("height"));}else{this.viewerWidth=parseFloat(this.parentElement.currentStyle.width);this.viewerHeight=parseFloat(this.parentElement.currentStyle.height);}}},getPosition:function(el){var xPos=0;var yPos=0;var Position=new THREE.Vector2();while(el){if(el.tagName=="BODY"){var xScroll=el.scrollLeft||document.documentElement.scrollLeft;var yScroll=el.scrollTop||document.documentElement.scrollTop;xPos+=(el.offsetLeft-xScroll+el.clientLeft);yPos+=(el.offsetTop-yScroll+el.clientTop);}else{xPos+=(el.offsetLeft-el.scrollLeft+el.clientLeft);yPos+=(el.offsetTop-el.scrollTop+el.clientTop);}
el=el.offsetParent;}
Position.x=xPos;Position.y=yPos;return Position;},getViewerCoordinateForMouseMove:function(event){"use strict";var canvasPosition=new THREE.Vector2();if(THREEx.FullScreen.available()&&THREEx.FullScreen.activated()){this.viewerWidth=window.innerWidth;this.viewerHeight=window.innerHeight;this.mouse.x=(event.clientX/this.viewerWidth)*2-1;this.mouse.y=-(event.clientY/this.viewerHeight)*2+1;}else{if(document.defaultView&&document.defaultView.getComputedStyle){this.viewerWidth=parseFloat(document.defaultView.getComputedStyle(this.parentElement,null).getPropertyValue("width"));this.viewerHeight=parseFloat(document.defaultView.getComputedStyle(this.parentElement,null).getPropertyValue("height"));var myElement=document.querySelector("#cds-cad-viewer-renderer");canvasPosition=this.getPosition(myElement);this.mouse.x=((event.clientX-canvasPosition.x)/this.viewerWidth)*2-1;this.mouse.y=-((event.clientY-canvasPosition.y)/this.viewerHeight)*2+1;}else{this.viewerWidth=parseFloat(this.parentElement.currentStyle.width);this.viewerHeight=parseFloat(this.parentElement.currentStyle.height);}}},animate:function(){"use strict";cds.cadViewer.frameId=requestAnimationFrame(cds.cadViewer.animate);TWEEN.update();if(cds.cadViewer.isRenderingAllowed){cds.cadViewer.render();}},onMouseMove:function(event){"use strict";cds.cadViewer.getViewerCoordinateForMouseMove(event);if(cds.cadViewer.mouseSubscribed!=undefined){if(cds.cadViewer.mouseSubscribed==true){cds.cadViewer.modelSelection(event);}}
var tooltipDiv=document.getElementById('tooltip');if(tooltipDiv!=null){var mousePos=cds.cadViewer.getMousePos(cds.cadViewer.renderer.domElement,event);tooltipDiv.style.left=mousePos.x+'px';tooltipDiv.style.top=(mousePos.y+20)+'px';}
if(cds.cadViewer.hasOwnProperty('tooltip')){cds.cadViewer.tooltip.showTooltip(cds.cadViewer.tooltip.tooltipEnabled);}
var bool=this.isMouseDown
if(cds.cadViewer.isMouseDown){cds.cadViewer.isRotated=true;}
cds.cadViewer.mouseHoverCallback();},onMouseDown:function(event){"use strict";if(event.button==1){cds.cadViewer.onMiddleMouseDown();}
cds.cadViewer.isMouseDown=true;if(!cds.cadViewer.hasOwnProperty('dragCheckLocation')){cds.cadViewer.dragCheckLocation=[];}
cds.cadViewer.dragCheckLocation=[event.clientX,event.clientY];},onMiddleMouseDown:function(event){if(cds.cadViewer.openAssemblyInNewTab){var intersects=cds.cadViewer.getIntersects(cds.cadViewer.sceneObject.children);if(intersects.length>0){var intersectedObject=intersects[0].object;var objectNode=cds.cadViewer.getImmediateAssemblyNode(intersectedObject);if(objectNode!=undefined){if(objectNode.children[0].type!="Mesh"&&objectNode.children[0].type!="Group"){if(window.location.href.indexOf("asm")!==-1){window.open(cds.cadViewer.updateQueryStringParameter(window.location.href,"asm",objectNode.userData.compId),'_blank');}else{window.open(window.location.href+"&asm="+objectNode.userData.compId,'_blank');}}}}}},updateQueryStringParameter:function(uri,key,value){var re=new RegExp("([?&])"+key+"=.*?(&|$)","i");var separator=uri.indexOf('?')!==-1?"&":"?";if(uri.match(re)){return uri.replace(re,'$1'+key+"="+value+'$2');}else{return uri+separator+key+"="+value;}},onMouseUp:function(event){"use strict";cds.cadViewer.isMouseDown=false;cds.cadViewer.isMouseUp=true;cds.cadViewer.isRotated=false;var performActionsOnClickEvent=true;if(event.button!=1){if(cds.cadViewer.hasOwnProperty('dragCheckLocation')){if(cds.cadViewer.dragCheckLocation.length>0)
if(!(event.pageX===cds.cadViewer.dragCheckLocation[0]&&event.pageY===cds.cadViewer.dragCheckLocation[1])){performActionsOnClickEvent=false;}}
if(performActionsOnClickEvent){if(THREEx.FullScreen.available()&&THREEx.FullScreen.activated()){var elem=cds.cadViewer.renderer.domElement;var boundingRect=elem.getBoundingClientRect(),x=(event.clientX-boundingRect.left)*(elem.width/boundingRect.width),y=(event.clientY-boundingRect.top)*(elem.height/boundingRect.height);var vector=new THREE.Vector3((x/window.innerWidth)*2-1,-(y/window.innerHeight)*2+1,0.5);cds.cadViewer.mouse.x=vector.x;cds.cadViewer.mouse.y=vector.y;}
if(!cds.cadViewer.hasOwnProperty('getFullPathOfPart')){cds.cadViewer.getFullPathOfPart=new cds.cadViewer.GetFullPathOfPart();}
var path=cds.cadViewer.getFullPathOfPart.getPathofPart();var immediateNodeName=cds.cadViewer.getFullPathOfPart.getPathOfTheImmediateChildNode();cds.cadViewer.getPartUnderMouseForAnimation();cds.cadViewer.mouseClickCallback(path);cds.cadViewer.nodeSelectCallback(immediateNodeName);}
delete cds.cadViewer.dragCheckLocation;}},onMouseClick:function(event){if(THREEx.FullScreen.available()&&THREEx.FullScreen.activated()){var elem=cds.cadViewer.renderer.domElement;var boundingRect=elem.getBoundingClientRect(),x=(event.clientX-boundingRect.left)*(elem.width/boundingRect.width),y=(event.clientY-boundingRect.top)*(elem.height/boundingRect.height);var vector=new THREE.Vector3((x/window.innerWidth)*2-1,-(y/window.innerHeight)*2+1,0.5);cds.cadViewer.mouse.x=vector.x;cds.cadViewer.mouse.y=vector.y;}
if(!cds.cadViewer.hasOwnProperty('getFullPathOfPart')){cds.cadViewer.getFullPathOfPart=new cds.cadViewer.GetFullPathOfPart();}
var path=cds.cadViewer.getFullPathOfPart.getPathofPart();cds.cadViewer.getPartUnderMouseForAnimation();cds.cadViewer.mouseClickCallback(path);},onMouseDoubleClick:function(event){cds.cadViewer.mouseDoubleClickCallback();cds.cadViewer.zoomOnSpecificPart(event);},onProgress:function(p){},onSceneError:function(event){"use strict";console.log("Error loading model in CDS CAD viewer: "+event);cds.cadViewer.loadingIcon.style.display="none";cds.cadViewer.isLoading=false;},onWindowResize:function(){"use strict";var prevWidth=cds.cadViewer.viewerWidth;var prevHeight=cds.cadViewer.viewerHeight;cds.cadViewer.getViewerSize();if(!THREEx.FullScreen.activated()){var temp1=document.getElementById("parentfieldset");if(temp1)
temp1.style="width: 450px; left: 511px; /* right: 58px; */ top: 64px; position: absolute; z-index: 2147483647;";cds.cadViewer.renderer.setClearColor(0x000000,0);cds.cadViewer.renderer.domElement.setAttribute("style","");cds.cadViewer.renderer2.setClearColor(0x000000,0);cds.cadViewer.renderer2.setSize(this.viewerWidth/10,this.viewerHeight/10);cds.cadViewer.renderer2.domElement.setAttribute("style","");}
cds.cadViewer.camera.aspect=cds.cadViewer.viewerWidth/cds.cadViewer.viewerHeight;cds.cadViewer.camera.updateProjectionMatrix();cds.cadViewer.camera2.aspect=cds.cadViewer.viewerWidth/cds.cadViewer.viewerHeight;cds.cadViewer.camera2.updateProjectionMatrix();var logoradiotemp=document.getElementById("logoRadio");if(logoradiotemp)
if(document.getElementById("logoRadio").checked==true){var canvas=document.getElementById("cds-cad-viewer-renderer");if(!THREEx.FullScreen.activated())
canvas.style="background:white; background-image: url('/images/icons/logo-header.png');background-repeat: no-repeat;background-position: 296px 417px;";else
canvas.style="background:white; background-image: url('/images/icons/logo-header.png');background-repeat: no-repeat;";}else{var canvas=document.getElementById("cds-cad-viewer-renderer");canvas.style=' background: white;'}
cds.cadViewer.renderer.setSize(cds.cadViewer.viewerWidth,cds.cadViewer.viewerHeight);cds.cadViewer.renderer2.setSize(cds.cadViewer.viewerWidth/10,cds.cadViewer.viewerHeight/10);cds.cadViewer.edgeEffect.uniforms.aspect.value.x=cds.cadViewer.viewerWidth;cds.cadViewer.edgeEffect.uniforms.aspect.value.y=cds.cadViewer.viewerHeight;cds.cadViewer.composer.setSize(cds.cadViewer.viewerWidth,cds.cadViewer.viewerHeight);cds.cadViewer.controls.handleResize();if(cds.cadViewer.isRenderingAllowed){cds.cadViewer.render();}},onSceneLoad:function(fileName,tempScene){try{"use strict";this.isLoading=false;var object=new THREE.Object3D();if(tempScene==undefined)
tempScene=this.loadSceneData();while(tempScene.children.length>0){object.add(tempScene.children[0]);}
if(tempScene instanceof THREE.Mesh){object.add(tempScene);}
this.controls.handleResize();this.controls.reset();this.currentFileName=fileName;this.sceneObject=object;this.sceneObject.userData=tempScene.userData;tempScene=null;if(this.sceneObject.userData.DLL_Version!=undefined){console.log("DLL Version: "+this.sceneObject.userData.DLL_Version);console.log("Viewer version: "+cds.cadViewer.viewerVersion);}
this.scene.add(this.sceneObject);this.setCameraParams();this.originalSceneObjectMatertials.length=0;this.edgeEffect.enabled=false;this.setRenderMode(this.currentRenderMode);this.animate();this.render();cds.cadViewer.applyStudioProperties();cds.cadViewer.loadStudioAnimations();}catch(e){console.log("Error loading model in CDS CAD viewer: "+e);}finally{this.isLoading=false;if(!cds.cadViewer.showPercentLoader)
this.loadingIcon.style.display="none";this.controls.enabled=true;this.bbs.forEach(function(b){this.scene.remove(b);});this.bbs.length=0;this.originalWidth=Number.MAX_VALUE;this.originalHeight=Number.MAX_VALUE;this.alreadyBinned=false;if(this.alreadyBinned===false){this.alreadyBinned=true;this.originalWidth=this.renderer.domElement.offsetWidth;this.originalHeight=this.renderer.domElement.offsetHeight;}
this.partNameToObject3d=[]
this.postLoadSceneCallback();}},setCameraParams:function(){var _this=cds.cadViewer;var box=this.sceneObject.userData.boundingBox;var cameraControls=new this.CameraControls();var isNotValidForCameraZoom=false;if(this.sceneObject.hasOwnProperty('userData')){if(this.sceneObject.userData.DLL_Version!=undefined){if(cds.cadViewer.ifDllHasBumpScaled(this.sceneObject.userData.DLL_Version)){if(box!=undefined){this.changeCameraTransform(this.sceneObject.getBoundingBox());this.sceneBoundingBox=this.sceneObject.getBoundingBox();this.centerCamera();isNotValidForCameraZoom=true;}}}}
if(!isNotValidForCameraZoom){this.sceneBoundingBox=this.sceneObject.getBoundingBox();var scale=cds.cadViewer.scaleObject(this.sceneBoundingBox);cds.cadViewer.sceneObject.scale.set(scale,scale,scale);cds.cadViewer.centerObject(cds.cadViewer.sceneObject);}
cameraControls.storeCameraPosition();},convertBoundingBox:function(boundingBox){var bbox=new THREE.Box3()
bbox.min=new THREE.Vector3(boundingBox.min[0],boundingBox.min[1],boundingBox.min[2])
bbox.max=new THREE.Vector3(boundingBox.max[0],boundingBox.max[1],boundingBox.max[2])
return bbox;},changeCameraTransform:function(jsonBoundingBox){var boundingBox=null;var oldBoundingBox=null;if(jsonBoundingBox.min instanceof THREE.Vector3){boundingBox=jsonBoundingBox;oldBoundingBox=jsonBoundingBox;}else{boundingBox=cds.cadViewer.convertBoundingBox(jsonBoundingBox);oldBoundingBox=cds.cadViewer.convertBoundingBox(jsonBoundingBox);}
var scaleFactor=cds.cadViewer.scaleObject(boundingBox);var scaledBoundingBox=cds.cadViewer.createScaledBoundingBox(scaleFactor,boundingBox);var adjacent=scaledBoundingBox.max.x-scaledBoundingBox.getCenter().x;var opposite=cds.cadViewer.camera.position.z;var angle=Math.atan(opposite/adjacent);var adjacent=oldBoundingBox.max.x-oldBoundingBox.getCenter().x;var cameraDistance=Math.tan(angle)*adjacent;cds.cadViewer.camera.position.set(cameraDistance,cameraDistance,cameraDistance);},createScaledBoundingBox:function(scaleFactor,boundingBox){var newBox=new THREE.Box3();newBox.min.x=scaleFactor*boundingBox.min.x;newBox.min.y=scaleFactor*boundingBox.min.y;newBox.min.z=scaleFactor*boundingBox.min.z;newBox.max.x=scaleFactor*boundingBox.max.x;newBox.max.y=scaleFactor*boundingBox.max.y;newBox.max.z=scaleFactor*boundingBox.max.z;return newBox;},postLoadSceneCallback:function(){},postModelTreeLoadCallback:function(){},onPartHover:function(partName){},onAnimationLoad:function(partName){},postLoadMaterialCallback:function(partName){},onAssemblyProgress:function(progress){},toolTipTextCallback:function(name){},mouseHoverCallback:function(){},mouseClickCallback:function(path){},nodeSelectCallback:function(name){},mouseDoubleClickCallback:function(){},loadScript:function(url,callback){var script=document.createElement("script")
script.type="text/javascript";if(script.readyState){script.onreadystatechange=function(){if(script.readyState=="loaded"||script.readyState=="complete"){script.onreadystatechange=null;callback();}};}else{script.onload=function(){callback();};}
script.src=url;document.getElementsByTagName("head")[0].appendChild(script);},loadRemoteScript:function(source,callback){"use strict";var script=document.createElement("script"),parent=document.getElementsByTagName("script")[0];script.src=source;script.type="application/javascript";if(this.isIE()){script.type="text/javascript";}
script.async=true;script.onerror=function(){script.onload=script.onreadystatechange=null;script=undefined;};parent.parentNode.insertBefore(script,parent);script.onload=script.onreadystatechange=function(_,isAbort){if(isAbort||!script.readyState||/loaded|complete/.test(script.readyState)){script.onload=script.onreadystatechange=null;script=undefined;if(!isAbort){if(callback){if(cds.cadViewer.isIE()&&cds.cadViewer.isIE()<9){setTimeout(function(){callback();},100);}else{callback();this.parentElement.removeChild(this);}}}}};},isIE:function(){var myNav=navigator.userAgent.toLowerCase();return(myNav.indexOf('msie')!=-1)?parseInt(myNav.split('msie')[1]):false;},computeBoundingBox:function(obj){"use strict";if(obj instanceof THREE.Mesh){var geometry=obj.geometry;geometry.computeBoundingBox();return geometry.boundingBox;}
if(obj instanceof THREE.Object3D){var bb=new THREE.Box3();for(var i=0;i<obj.children.length;i++){bb.union(cds.cadViewer.computeBoundingBox(obj.children[i]));}
return bb;}},setPercentZoom:function(percentage){cds.cadViewer.zoomPercentage=percentage},scaleObject:function(boundingBox){"use strict";var xDimension=boundingBox.max.x-boundingBox.min.x;var yDimension=boundingBox.max.y-boundingBox.min.y;var zDimension=boundingBox.max.z-boundingBox.min.z;var maxOfXY=Math.max(xDimension,yDimension);var lengthOfLargestDimension=Math.max(maxOfXY,zDimension);var scaleFactor=1/lengthOfLargestDimension*(60+((cds.cadViewer.zoomPercentage/100)*60));return scaleFactor;},centerCamera:function(){var boxCenter=cds.cadViewer.sceneBoundingBox.getCenter();var centerX=boxCenter.x;var centerY=boxCenter.y;var centerZ=boxCenter.z;var matrix=new THREE.Matrix4();cds.cadViewer.camera.updateMatrix();matrix.makeTranslation(-centerX,-centerY,-centerZ);matrix.getInverse(matrix);cds.cadViewer.controls.target.copy(cds.cadViewer.sceneBoundingBox.getCenter())
cds.cadViewer.camera.applyMatrix(matrix);},centerObject:function(object){"use strict";var box=cds.cadViewer.sceneBoundingBox;var centerX=(box.max.x+box.min.x)/2.0*object.scale.x;var centerY=(box.max.y+box.min.y)/2.0*object.scale.y;var centerZ=(box.max.z+box.min.z)/2.0*object.scale.z;var to=new THREE.Vector3(-centerX,-centerY,-centerZ);new TWEEN.Tween(object.position).to({x:to.x,y:to.y,z:to.z},500).easing(TWEEN.Easing.Linear.None).start();object.position.set(-centerX,-centerY,-centerZ);},explodeDropdownChange:function(){var explodeEffect=[TWEEN.Easing.Linear.None,TWEEN.Easing.Quadratic.In,TWEEN.Easing.Quadratic.Out,TWEEN.Easing.Quadratic.InOut,TWEEN.Easing.Cubic.In,TWEEN.Easing.Cubic.Out,TWEEN.Easing.Cubic.InOut,TWEEN.Easing.Quartic.In,TWEEN.Easing.Quartic.Out,TWEEN.Easing.Quartic.InOut,TWEEN.Easing.Quintic.In,TWEEN.Easing.Quintic.Out,TWEEN.Easing.Quintic.InOut,TWEEN.Easing.Sinusoidal.In,TWEEN.Easing.Sinusoidal.Out,TWEEN.Easing.Sinusoidal.InOut,TWEEN.Easing.Exponential.In,TWEEN.Easing.Exponential.Out,TWEEN.Easing.Exponential.InOut,TWEEN.Easing.Circular.In,TWEEN.Easing.Circular.Out,TWEEN.Easing.Circular.InOut,TWEEN.Easing.Elastic.In,TWEEN.Easing.Elastic.Out,TWEEN.Easing.Elastic.InOut,TWEEN.Easing.Back.In,TWEEN.Easing.Back.Out,TWEEN.Easing.Back.InOut,TWEEN.Easing.Bounce.In,TWEEN.Easing.Bounce.Out,TWEEN.Easing.Bounce.InOut];this.explodeEffect=explodeEffect[document.getElementById("explodeDropdown").value];document.getElementById("explodeViewCheckbox").checked=!document.getElementById("explodeViewCheckbox").checked;this.toggleViews(document.getElementById("explodeViewCheckbox").checked);},applyScaleHeight:function(){cds.cadViewer.bumpScale=document.getElementById('sclaleHeight').value;cds.cadViewer.loadScene(cadURL);},setHighlightColor:function(color){if(color==undefined)
color='#00ff00';cds.cadViewer.hlColor=color;},swapColor:function(color){if(color==undefined)
color='#00ff00';cds.cadViewer.color=color;cds.cadViewer.loadScene(cadURL);},updateSliderOpacityValue:function(value){cds.cadViewer.opacity=value.value;var label=document.getElementById("range1");label.textContent=value.value*100+"%";cds.cadViewer.loadScene(cadURL);},updateSliderRotateSpeed:function(value){cds.cadViewer.rotateSpeed=Number(value.value);var label=document.getElementById("spinLabel");label.textContent=Number(value.value);},explosionSubscribe:function(){var checkbox=document.getElementById("explosionSubscription");if(checkbox.checked==true){cds.cadViewer.explosionSubscribed=1;document.getElementById("explosionEverything").style.visibility="visible";document.getElementById("explodeViewCheckbox").style.visibility="visible";}else{cds.cadViewer.explosionSubscribed=undefined;document.getElementById("explosionEverything").style.visibility="hidden";document.getElementById("explodeViewCheckbox").style.visibility="hidden";}},mouseSubscribe:function(){var checkbox=document.getElementById("mouseSubscription");if(checkbox.checked==true){cds.cadViewer.mouseSubscribed=1;document.getElementById("highlight").style.visibility="visible";}else{cds.cadViewer.mouseSubscribed=undefined;document.getElementById("highlight").style.visibility="hidden";}},annotSubscribe:function(){var checkbox=document.getElementById("annotSubscription");var v1=cds.cadViewer.scene.children[2],l=v1.children.length;if(checkbox.checked==true){if(this.annoTemp)
if(this.annoTemp.userData.annotation==1)
v1.add(this.annoTemp);}else{this.annoTemp=v1.children[l-1];if(this.annoTemp)
if(this.annoTemp.userData.annotation==1)
v1.remove(v1.children[l-1]);}},loadgun:function(){var checkbox=document.getElementById("multiSubassembly");if(checkbox.checked==true)
checkbox.checked=false;else
checkbox.checked=true;var checkbox=document.getElementById("loadGun");if(checkbox.checked==true){cadURL="/samples/PROBA52.js";cds.cadViewer.loadScene(cadURL);}else{cadURL="/samples/cube.js";cds.cadViewer.loadScene(cadURL);}},multiSubassembly:function(){var checkbox=document.getElementById("loadGun");if(checkbox.checked==true)
checkbox.checked=false;else
checkbox.checked=true;var checkbox=document.getElementById("multiSubassembly");if(checkbox.checked==true){cadURL="/samples/ZAMEK_2.js";cds.cadViewer.loadScene(cadURL);}else{cadURL="/samples/cube.js";cds.cadViewer.loadScene(cadURL);}},modelChange:function(){var value=document.getElementById("modelDropdown").value;if(value==0){cadURL="/samples/cube.js";cds.cadViewer.loadScene(cadURL);}else if(value==1){cadURL="/samples/PROBA52.js";cds.cadViewer.loadScene(cadURL);}else if(value==2){cadURL="/samples/ASSEMBLY1.js";cds.cadViewer.loadScene(cadURL);}else if(value==3){cadURL="/samples/ZAMEK_2.js";cds.cadViewer.loadScene(cadURL);}},gridToggle:function(obj){var length=cds.cadViewer.scene.children.length;for(var i=0;i<length;i++){if(cds.cadViewer.scene.children[i].type=="LineSegments"){if(document.getElementById("gridRadio").checked==true)
cds.cadViewer.scene.children[i].visible=true;else
cds.cadViewer.scene.children[i].visible=false;}}},logoToggle:function(obj){if(document.getElementById("logoRadio").checked==true){var canvas=document.getElementById("cds-cad-viewer-renderer");canvas.style="background-image: url('/images/icons/logo-header.png'); background-repeat: no-repeat; background-position: 296px 417px;"}else{var canvas=document.getElementById("cds-cad-viewer-renderer");canvas.style=' background:white;'}},colorSwapCheck:function(){var textureDropdown=document.getElementById("swapColor");var opacitySlider=document.getElementById("opacitySlider");var opacityValue=document.getElementById("range1")
var modeldropdown=document.getElementById("modelDropdown");if(document.getElementById("colorSwapCheck").checked==true){textureDropdown.style.display="";textureDropdown.disable=false;opacitySlider.style.display="";opacitySlider.disable=false;opacityValue.style.display="";opacityValue.disable=false;modeldropdown.disabled=true;cadURL="/samples/CubeColor.js";cds.cadViewer.loadScene(cadURL);}else{textureDropdown.disabled=true;opacitySlider.disabled=true;opacityValue.disabled=true;modeldropdown.disabled=false;}},textureSwapCheck:function(){var textureDropdown=document.getElementById("leave");var modeldropdown=document.getElementById("modelDropdown");if(document.getElementById("textureSwapCheck").checked==true){textureDropdown.style.display="";textureDropdown.disable=false;modeldropdown.disabled=true;cadURL="/samples/CubeTexture.js";cds.cadViewer.loadScene(cadURL);}else{textureDropdown.disabled=true;modeldropdown.disabled=false;}},textureSwap:function(){cds.cadViewer.loadScene(cadURL);if(document.getElementById("leave").value=="1"){cds.cadViewer.texturemap="/texture/bricks.jpg";cds.cadViewer.loadScene(cadURL);}
if(document.getElementById("leave").value=="2"){cds.cadViewer.texturemap="/texture/Galvanized.jpg";cds.cadViewer.loadScene(cadURL);}
if(document.getElementById("leave").value=="3"){cds.cadViewer.texturemap="/texture/Finger.jpg";cds.cadViewer.loadScene(cadURL);}
if(document.getElementById("leave").value=="4"){cds.cadViewer.texturemap="/texture/wall2.jpg";cds.cadViewer.loadScene(cadURL);}
if(document.getElementById("leave").value=="5"){cds.cadViewer.texturemap="/texture/gun.jpg";cds.cadViewer.loadScene(cadURL);}},downloadImage:function(canvas,filename){var lnk=document.createElement('a'),e;lnk.download=filename;lnk.href=canvas.toDataURL();if(document.createEvent){e=document.createEvent("MouseEvents");e.initMouseEvent("click",true,true,window,0,0,0,0,0,false,false,false,false,0,null);lnk.dispatchEvent(e);}else if(lnk.fireEvent){lnk.fireEvent("onclick");}},exportImage:function(filename){var f=filename,canvas=document.getElementById("cds-cad-viewer-renderer");if(!f){f='3dcapture';}
if(f.indexOf(".png")!==-1){f=f.substring(0,f.indexOf(".png"));}
cds.cadViewer.downloadImage(canvas,f+".png");},exportImageWithSize:function(filename,width,height){var f=filename,canvas=document.getElementById("cds-cad-viewer-renderer");if(!f){f='3dcapture';}
if(f.indexOf(".png")!==-1){f=f.substring(0,f.indexOf(".png"));}
cds.cadViewer.downloadImageWithSize(canvas,f+".png",width,height);},downloadImageWithSize:function(canvas,filename,width,height){var lnk=document.createElement('a'),e;lnk.download=filename;var resizedCanvas=document.createElement("canvas");var resizedContext=resizedCanvas.getContext("2d");resizedCanvas.height=height==undefined?"850":height;resizedCanvas.width=width==undefined?"1150":width;var context=canvas.getContext("2d");resizedContext.drawImage(canvas,-((canvas.width/2)-(resizedCanvas.width/2)),-((canvas.height/2)-(resizedCanvas.height/2)),canvas.width,canvas.height);var myResizedData=resizedCanvas.toDataURL();lnk.href=myResizedData
if(document.createEvent){e=document.createEvent("MouseEvents");e.initMouseEvent("click",true,true,window,0,0,0,0,0,false,false,false,false,0,null);lnk.dispatchEvent(e);}else if(lnk.fireEvent){lnk.fireEvent("onclick");}},solidOutline:function(object){"use strict";if(object instanceof THREE.Object3D){object.traverse(function(mesh){if(mesh instanceof THREE.Mesh){if(mesh.material.length!=undefined){for(var i=0;i<mesh.material.length;i++){if(mesh.material[i]){var geo=new THREE.EdgesGeometry(mesh.geometry);var mat=new THREE.LineBasicMaterial({color:0x000000,linewidth:2});var wireframe=new THREE.LineSegments(geo,mat);mesh.add(wireframe);}}}else{if(mesh.material){var geo=new THREE.EdgesGeometry(mesh.geometry);var mat=new THREE.LineBasicMaterial({color:0x000000,linewidth:2});var wireframe=new THREE.LineSegments(geo,mat);mesh.add(wireframe);}}}});}},zoomfit:function(box){var v1=box.max;var v2=box.min;var dx=v1.x-v2.x;var dy=v1.y-v2.y;var dz=v1.z-v2.z;var len=Math.sqrt(dx*dx+dy*dy+dz*dz);cds.cadViewer.camera.position.set(len,len,len);},changefacing:function(object){if(object=="1"){cds.cadViewer.facing=THREE.FrontSide;cds.cadViewer.loadScene(cadURL);}else if(object=="2"){cds.cadViewer.facing=THREE.BackSide;cds.cadViewer.loadScene(cadURL);}else if(object=="3"){cds.cadViewer.facing=THREE.DoubleSide;cds.cadViewer.loadScene(cadURL);}else
console.log("unknown Input");},replceSubscribe:function(object){var cylinder=cds.cadViewer.scene.children[2].children[0].children[2];for(var i=0;i<cylinder.children.length;i++){cylinder.children[i].layers.set(1);}
cds.cadViewer.camera.layers.disable(1);var cube=cds.cadViewer.scene.children[2].children[0].children[1];for(var i=0;i<cube.children.length;i++){cube.children[i].layers.set(2);}
cds.cadViewer.camera.layers.disable(2);},replaceDemo:function(object){if(object=="1"){cds.cadViewer.camera.layers.disable(1);cds.cadViewer.camera.layers.enable(2);}else if(object=="2"){cds.cadViewer.camera.layers.enable(1);cds.cadViewer.camera.layers.disable(2);}else
console.log("unknown Input");},zoomOnSpecificPart:function(event){var camera=cds.cadViewer.camera;var controls=cds.cadViewer.controls;var mouse=cds.cadViewer.mouse;var middle=new THREE.Vector3();var bound=new THREE.Vector3();var dir=new THREE.Vector3();var raycaster=cds.cadViewer.raycaster;var scene=cds.cadViewer.scene;controls.update();event.preventDefault();var intersects=cds.cadViewer.getIntersects(cds.cadViewer.sceneObject.children);if(intersects.length>0){if(intersects[0].object.type=="Sprite"&&intersects.length>1){var intersectedObject=intersects[1].object;}else if(intersects[0].object.type!="Sprite"){var intersectedObject=intersects[0].object;}
if(intersectedObject!=undefined){var bbox=new THREE.Box3();var boxHelper1=new THREE.BoxHelper(intersectedObject.parent,0xff0000);bbox.setFromObject(boxHelper1);middle.x=(bbox.max.x+bbox.min.x)/2;middle.y=(bbox.max.y+bbox.min.y)/2;middle.z=(bbox.max.z+bbox.min.z)/2;var dx=bbox.max.x-bbox.min.x;var dy=bbox.max.y-bbox.min.y;var dz=bbox.max.z-bbox.min.z;var dist=Math.sqrt(dx*dx+dy*dy+dz*dz);new TWEEN.Tween(controls.target).to({x:middle.x,y:middle.y,z:middle.z},2000).easing(TWEEN.Easing.Linear.None).start()
new TWEEN.Tween(camera.position).to({x:middle.x+(dist*1),y:middle.y+(dist*1),z:middle.z+(dist*1)},2000).easing(TWEEN.Easing.Linear.None).start()
camera.lookAt(middle);}}else{var bbox=new THREE.Box3();var boxHelper1=new THREE.BoxHelper(cds.cadViewer.scene,0xff0000);bbox.setFromObject(boxHelper1);middle.x=(bbox.max.x+bbox.min.x)/2;middle.y=(bbox.max.y+bbox.min.y)/2;middle.z=(bbox.max.z+bbox.min.z)/2;var dx=bbox.max.x-bbox.min.x;var dy=bbox.max.y-bbox.min.y;var dz=bbox.max.z-bbox.min.z;var dist=Math.sqrt(dx*dx+dy*dy+dz*dz);new TWEEN.Tween(controls.target).to({x:middle.x,y:middle.y,z:middle.z},2000).easing(TWEEN.Easing.Linear.None).start()
new TWEEN.Tween(camera.position).to({x:middle.x+(dist*1),y:middle.y+(dist*1),z:middle.z+(dist*1)},2000).easing(TWEEN.Easing.Linear.None).start()
camera.lookAt(middle);}
controls.update();},toggleTooltip:function(){if(!cds.cadViewer.hasOwnProperty('tooltip')){cds.cadViewer.tooltip=new cds.cadViewer.Tooltip();}
cds.cadViewer.tooltip.tooltipEnabled=!cds.cadViewer.tooltip.tooltipEnabled;},modelSelection:function(event){var intersects=cds.cadViewer.getIntersects(cds.cadViewer.sceneObject.children);if(intersects.length>0){var intersectedObject=intersects[0].object;var intersectionPt=intersects[0].point;if(intersectedObject!=undefined){cds.cadViewer.removeNameSelectionMaterial();cds.cadViewer.removeSelectionMaterial();cds.cadViewer.INTERSECTED=intersectedObject;cds.cadViewer.applySelectionMaterial();if(cds.cadViewer.INTERSECTED.parent.parent!=null){if(cds.cadViewer.INTERSECTED.parent.type=="Group"){if(cds.cadViewer.INTERSECTED.parent.parent.parent.name==cds.cadViewer.sceneObject.children[0].name){cds.cadViewer.onPartHover(cds.cadViewer.INTERSECTED.parent.parent.name);}}else{if(cds.cadViewer.INTERSECTED.parent.parent.name==cds.cadViewer.sceneObject.children[0].name){cds.cadViewer.onPartHover(cds.cadViewer.INTERSECTED.parent.name);}}}}}else{var x=event.clientX,y=event.clientY,elementMouseIsOver=document.elementFromPoint(x,y);if(elementMouseIsOver!=null){if(elementMouseIsOver.id=="cds-cad-viewer-renderer"){cds.cadViewer.removeNameSelectionMaterial();cds.cadViewer.removeSelectionMaterial();cds.cadViewer.INTERSECTED=null;cds.cadViewer.onPartHover();}}}},Tooltip:function(){this.tooltipEnabled=false;this.showTooltip=function(event){if(this.tooltipEnabled){var tooltipDiv=document.getElementById('tooltip');if(tooltipDiv==null){this.addCSSForTooltip();this.addTooltipDiv();tooltipDiv=document.getElementById('tooltip');}
tooltipDiv.style.display='none';var intersects=cds.cadViewer.getIntersects(cds.cadViewer.sceneObject.children);if(intersects.length>0){var intersectedObject=intersects[0].object;var parent=cds.cadViewer.getImmediateAssemblyNode(intersectedObject);if(parent.name){var message="";if(cds.cadViewer.useCustomToolTipText==true){message=cds.cadViewer.toolTipTextCallback(parent.name);}else{message=parent.name;}
tooltipDiv=document.getElementById('tooltip');tooltipDiv.style.display='block';cds.cadViewer.tooltip_span.setAttribute('data-tooltip',message);}}}}
this.addTooltipDiv=function(){tooltipDiv=document.createElement('div');tooltipDiv.id='tooltip';tooltipDiv.style.position='absolute';tooltipDiv.style.display='none';tooltipDiv.style.zIndex='1';cds.cadViewer.tooltip_span=document.createElement('span');cds.cadViewer.tooltip_span.setAttribute('data-tooltip','TEST');tooltipDiv.appendChild(cds.cadViewer.tooltip_span);document.body.appendChild(tooltipDiv);}
this.addCSSForTooltip=function(){var csstag=document.createElement('style');csstag.append("[data-tooltip]{position:relative;z-index:2;cursor:pointer}[data-tooltip]:before{position:absolute;top:150%;left:50%;margin-bottom:5px;margin-left:-80px;padding:7px;max-width:500px;min-width:160px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;background-color:#000;background-color:hsla(0,0%,20%,.9);color:#fff;content:attr(data-tooltip);text-align:center;font-size:14px;line-height:1.2}[data-tooltip]:after{position:absolute;top:50%;left:50%;margin-left:-5px;margin-top:-5px;width:0;border-bottom:5px solid #000;border-bottom:5px solid hsla(0,0%,20%,.9);border-right:5px solid transparent;border-left:5px solid transparent;content:'';font-size:0;line-height:0}");var head=document.getElementsByTagName('head')[0];head.appendChild(csstag);}},removeNameSelectionMaterial:function(){if(cds.cadViewer.INTERSECTED==null){if(cds.cadViewer.intersectedPart!=undefined){var objectName=cds.cadViewer.intersectedPart;var rootAssembly=cds.cadViewer.scene.children[2].children[0];cds.cadViewer.getObjectsByName(objectName,rootAssembly,function(object){cds.cadViewer.getMeshFor(object,function(selectedMesh){cds.cadViewer.removeSelectionMaterialOnMesh(selectedMesh);});});cds.cadViewer.intersectedPart=undefined;}}},applySelectionMaterial:function(){cds.cadViewer.getSelectedMesh(function(selectedMesh){cds.cadViewer.applySelectionMaterialOnMesh(selectedMesh);});},applySelectionMaterialOnMesh:function(mesh){if(mesh.material.length!=undefined){for(var i=0;i<mesh.material.length;i++){if(mesh.userData.currentMat==undefined){mesh.userData.currentMat=[];}
mesh.userData.currentMat.push(mesh.material[i]);var tempMaterial=new THREE.MeshPhongMaterial();tempMaterial.emissive.setHex('0x999');mesh.material[i]=tempMaterial;}}else{if(cds.cadViewer.currenMaterial==undefined||cds.cadViewer.currenMaterial==null){cds.cadViewer.currenMaterial=[];}
if(mesh!=null){mesh.parent.traverse(function(mesh){if(mesh instanceof THREE.Mesh){cds.cadViewer.currenMaterial.push(mesh.material);var tempMaterial=new THREE.MeshPhongMaterial().copy(mesh.material.clone());tempMaterial.emissive.setHex('0x999');mesh.material=tempMaterial;}});}}},getSelectedMesh:function(selection){if(cds.cadViewer.INTERSECTED!=null){var selectedMesh=cds.cadViewer.INTERSECTED.parent;var objectNode=cds.cadViewer.getImmediateAssemblyNode(selectedMesh);if(objectNode!=undefined){objectNode.traverse(function(child){if(child instanceof THREE.Mesh){selection(child);}});}}},getImmediateAssemblyNode:function(selectedMesh){if(selectedMesh!=null){if(selectedMesh.parent!=null){if(selectedMesh.parent.name==cds.cadViewer.sceneObject.children[0].name){return selectedMesh;}else{return cds.cadViewer.getImmediateAssemblyNode(selectedMesh.parent);}}else{return undefined;}}else{return undefined;}},getMeshFor:function(object,selected){object.traverse(function(child){if(child instanceof THREE.Mesh){selected(child);}});},getObjectsByName:function(name,jsonObject,selectedObject){for(var i=0;i<jsonObject.children.length;i++){var children=jsonObject.children;if(children[i].name==name){selectedObject(children[i]);}
if(children[i].children.length>0){cds.cadViewer.getObjectsByName(name,children[i],function(object){selectedObject(object);});}}},highlightObject:function(object){if(object.userData.childType=="Part"){object.children.forEach(function(element){if(element.type=="Group"){cds.cadViewer.applySelectionMaterialOnMesh(element.children[0]);}else{cds.cadViewer.applySelectionMaterialOnMesh(element);}})}else{for(var i=0;i<object.children.length;i++){cds.cadViewer.highlightObject(object.children[i]);}}},highlightPartByName:function(partName){if(cds.cadViewer.mouseSubscribed==true){cds.cadViewer.removeNameSelectionMaterial();cds.cadViewer.removeSelectionMaterial();cds.cadViewer.INTERSECTED=null;cds.cadViewer.intersectedPart=partName;cds.cadViewer.getObjectsByName(partName,cds.cadViewer.scene.children[2].children[0],function(object){cds.cadViewer.highlightObject(object);});}},removeSelectionMaterial:function(){cds.cadViewer.getSelectedMesh(function(selectedMesh){cds.cadViewer.removeSelectionMaterialOnMesh(selectedMesh);});},removeSelectionMaterialOnMesh:function(mesh){if(mesh.material.length!=undefined&&mesh.userData.currentMat!=undefined){if(mesh.userData.currentMat.length>0){for(var i=0;i<mesh.material.length;i++){mesh.material[i]=mesh.userData.currentMat[i];}}
mesh.userData.currentMat=[];}else{if(cds.cadViewer.INTERSECTED!=null){if(mesh.parent.name!=cds.cadViewer.INTERSECTED.parent.name){if(cds.cadViewer.currenMaterial!=undefined){mesh.parent.traverse(function(mesh){if(mesh instanceof THREE.Mesh){mesh.material=cds.cadViewer.currenMaterial[0];cds.cadViewer.currenMaterial.splice(0,1);}});mesh.parent.userData.intersected=undefined;cds.cadViewer.currenMaterial=[];}}}}},getMousePos:function(canvas,evt){var rect=canvas.getBoundingClientRect();return{x:evt.clientX-rect.left,y:evt.clientY-rect.top};},getIntersects:function(objects){var mouse_vector=new THREE.Vector3(cds.cadViewer.mouse.x,cds.cadViewer.mouse.y,1);cds.cadViewer.raycaster.setFromCamera(mouse_vector,cds.cadViewer.camera);return cds.cadViewer.raycaster.intersectObjects(objects,true);},toggleGetFullPath:function(){if(!cds.cadViewer.hasOwnProperty('getFullPathOfPart')){cds.cadViewer.getFullPathOfPart=new cds.cadViewer.GetFullPathOfPart();}
cds.cadViewer.getFullPathOfPart.isGetFullPathOfPartEnabled=!cds.cadViewer.getFullPathOfPart.isGetFullPathOfPartEnabled;},GetFullPathOfPart:function(){this.isGetFullPathOfPartEnabled=true;this.fullPath='';this.path=[];this.getPathofPart=function(){if(this.isGetFullPathOfPartEnabled){var intersects=cds.cadViewer.getIntersects(cds.cadViewer.sceneObject.children);if(intersects.length>0){var intersectedObject=intersects[0].object;if(intersectedObject!=undefined&&intersectedObject!=null){this.getRootLevelPathOfPart(intersectedObject);return this.fullPath;}}}}
this.getPathOfTheImmediateChildNode=function(){var intersects=cds.cadViewer.getIntersects(cds.cadViewer.sceneObject.children);if(intersects.length>0){var intersectedObject=intersects[0].object;var immediateNode=cds.cadViewer.getImmediateAssemblyNode(intersectedObject)
return immediateNode.name;}},this.getRootLevelPathOfPart=function(object){var parent=object.parent;if(parent.parent.type!="Scene"){if(parent.type=="Object3D"){this.path.push(parent.name);if(parent.parent!=undefined&&parent.parent!=null)
this.getRootLevelPathOfPart(parent,this.path);}else if(parent.type=="Group"){this.path.push(parent.parent.name);if(parent.parent!=undefined&&parent.parent!=null)
this.getRootLevelPathOfPart(parent.parent,this.path);}}else{this.fullPath="";for(var i=this.path.length-1;i>=0;i--){this.fullPath+='/'+this.path[i];}
this.path=[];return this.fullPath;}}},changePartDecal:function(partName,imageUrl){cds.cadViewer.scene.getObjectByName(partName).traverse(function(mesh){if(mesh instanceof THREE.Mesh){if(mesh.material.length!=undefined){for(var i=0;i<mesh.material.length;i++){mesh.material[i].map=new THREE.TextureLoader().load(imageUrl);mesh.material[i].needsUpdate=true;}}else{mesh.material.map=new THREE.TextureLoader().load(imageUrl);mesh.material.needsUpdate=true;}}});},changePartColor:function(partName,color){var c=color;if(c.indexOf("#")===0){c=c.substring(1);}
cds.cadViewer.scene.getObjectByName(partName).traverse(function(mesh){if(mesh instanceof THREE.Mesh){if(mesh.material.length!=undefined){for(var i=0;i<mesh.material.length;i++){mesh.material[i].color.setHex('0x'+c.toString());mesh.material[i].needsUpdate=true;}}else{mesh.material.color.setHex('0x'+c.toString());mesh.material.needsUpdate=true;}}});},swapTexture:function(partName,textureFilePath,bumpEnabled){cds.cadViewer.scene.getObjectByName(partName).traverse(function(mesh){if(mesh instanceof THREE.Mesh){if(mesh.material.length!=undefined){for(var i=0;i<mesh.material.length;i++){if(bumpEnabled){mesh.material[i].bumpMap=new THREE.TextureLoader().load(textureFilePath);}else{mesh.material[i].bumpMap=undefined;}
mesh.material[i].needsUpdate=true;}}else{if(bumpEnabled){mesh.material.bumpMap=new THREE.TextureLoader().load(textureFilePath);}else{mesh.material.bumpMap=undefined;}
mesh.material.needsUpdate=true;}}});},setBumpTexture:function(partName,textureFilePath){cds.cadViewer.swapTexture(partName,textureFilePath,true);},hasExplosion:function(){if(cds.cadViewer.scene.children[2].userData.hasExplosion!=undefined){if(cds.cadViewer.scene.children[2].userData.hasExplosion){return true;}}
return false;},explodeAssembly:function(){cds.cadViewer.explode=!cds.cadViewer.explode;var explode=cds.cadViewer.explode;if(cds.cadViewer.hasExplosion()){cds.cadViewer.traverseAssembly(cds.cadViewer.scene.children[2].children[0]);if(cds.cadViewer.hasOwnProperty("offsetLines")){for(var k=0;k<cds.cadViewer.offsetLines.length;k++){var line=cds.cadViewer.offsetLines[k];if(cds.cadViewer.explode){line.material.opacity=0
line.material.transparent=true
line.visible=true
var tweenon=new TWEEN.Tween(line.material).to({opacity:1},1500).onComplete(function(){line.material.transparent=false;});tweenon.start();}else{line.material.transparent=true
line.material.opacity=1
var tweenoff=new TWEEN.Tween(line.material).to({opacity:0},1500).onComplete(function(){line.visible=false});tweenoff.start();}}}}else{console.log("Scene does not contain explosion data");}},traverseAssembly:function(node){for(var i=0;i<node.children.length;i++){var childNode=node.children[i];if(childNode.children.length>0){if(childNode.children[0].type=="Group"||childNode.children[0].type=="Mesh"){cds.cadViewer.applyTweenExplosion(childNode);}else{cds.cadViewer.applyTweenExplosion(childNode);if(cds.cadViewer.recursiveExplosion){cds.cadViewer.traverseAssembly(childNode)}}}}},applyTweenExplosion:function(node){var explode=cds.cadViewer.explode;if(node.userData.ExplodedMatrix!=undefined){var from=node.position;var to=new THREE.Matrix4();var nodeExplosionMatrix=new THREE.Matrix4();if(node.userData.initialPos==undefined){node.userData.initialPos=new THREE.Vector3(node.position.x,node.position.y,node.position.z);}
if(explode&&node.userData.ExplodedMatrix!=undefined){nodeExplosionMatrix.fromArray(node.userData.ExplodedMatrix);var explodedPosition=new THREE.Vector3();var quaternion=new THREE.Quaternion();var scale=new THREE.Vector3();nodeExplosionMatrix.decompose(explodedPosition,quaternion,scale);to=explodedPosition;}else{to=node.userData.initialPos;}
from=node.position;var twn=new TWEEN.Tween(from).to({x:to.x,y:to.y,z:to.z},1500).easing(TWEEN.Easing.Linear.None).start();}},getReplaceablePartInModel:function(){var replaceablePartKeyValuePair={};cds.cadViewer.scene.children[2].traverse(function(child){if(child.userData.Replaceable_count!=undefined){var partName=child.name;var Replaceable_count=child.userData.Replaceable_count;replaceablePartKeyValuePair[partName]=new Array();for(var i=1;i<=Replaceable_count;i++){var replaceablePartName=partName+"_"+i;replaceablePartKeyValuePair[partName].push(replaceablePartName);}}});return replaceablePartKeyValuePair;},replacePart:function(key,value,callback){if(!cds.cadViewer.hasOwnProperty('partReplacement')||cds.cadViewer.partReplacement===null){cds.cadViewer.partReplacement=new cds.cadViewer.PartReplacement();}
cds.cadViewer.partReplacement.replacePart(key,value,callback);},PartReplacement:function(){this.obj=function(){obj=new Object();this.add=function(key,value){obj[""+key+""]=value;},this.isEmpty=function(obj){for(var key in obj){if(obj.hasOwnProperty(key))
return false;}
return true;},this.obj=obj;}
this.previousPartAdded=new this.obj();cds.cadViewer.previousPartAdded=this.previousPartAdded;this.previouslyAddedSubAsm=[];this.addPartIntoParent=null;this.defaultSubAssemblies={};this.replaceablesObjects=[];this.getDefaultPartAddedInModel=function(){cds.cadViewer.scene.children[2].traverse(function(child){if(child.userData.Replaceable_count!=undefined){if(child.children.length>0){if(child.children[0].type==="Object3D"){cds.cadViewer.partReplacement.isSubassembly=true;cds.cadViewer.partReplacement.defaultSubAssemblies[child.name]=child.clone();cds.cadViewer.partReplacement.addPartIntoParent=child.parent;}}
var partName=child.name;cds.cadViewer.partReplacement.previousPartAdded.add(partName,partName);}});},this.addPart=function(partName,parent,prevPartMatrix,prevPartExplodedMatrix,callback){var partFilePath=cds.cadViewer.cadDirectory+partName;if(!(partFilePath.substr(partFilePath.lastIndexOf('.'),partFilePath.length)==".json")){partFilePath+=".json"}
var loader=new THREE.ObjectLoader();loader.setCrossOrigin('Anonymous');loader.load(partFilePath,function(loadedScene){if(partName.split('.').pop().toLowerCase()=="json"){partName=partName.substr(0,partName.lastIndexOf('.'));}
loadedScene.children[0].name=partName;if(loadedScene instanceof THREE.Scene){if(cds.cadViewer.partReplacement.replaceablesObjects.length>1){loadedScene.children[0].applyMatrix(prevPartMatrix);loadedScene.children[0].updateMatrix();}
loadedScene.children[0].userData.ExplodedMatrix=prevPartExplodedMatrix
parent.add(loadedScene.children[0]);}else{loadedScene.applyMatrix(prevPartMatrix);loadedScene.userData.ExplodedMatrix=prevPartExplodedMatrix
parent.add(loadedScene);}
parent=null;prevPartMatrix=null;this.addPartIntoParent=null;if(callback!=undefined){callback();}});},this.addSubAssembly=function(partName,callback){var replaceableSuassembly;var loadDefaultSubassembly=this.defaultSubAssemblies[partName];if(loadDefaultSubassembly){replaceableSuassembly=this.defaultSubAssemblies[partName];if(replaceableSuassembly.parent==null){replaceableSuassembly.parent=this.addPartIntoParent;}
this.addPartIntoParent.add(replaceableSuassembly);}else{if(cds.cadViewer.hasOwnProperty("replaceableSubAssemblyMap")){replaceableSuassembly=cds.cadViewer.replaceableSubAssemblyMap[partName];if(replaceableSuassembly.parent==null){replaceableSuassembly.parent=this.addPartIntoParent;}
this.addPartIntoParent.add(replaceableSuassembly);}}
this.traverseObjectToSetPreviouslySelectedReplaceables(replaceableSuassembly);console.log(cds.cadViewer.partReplacement.previousPartAdded.obj);this.addPartIntoParent=null;if(callback!=undefined){callback();}},this.traverseObjectToSetPreviouslySelectedReplaceables=function(asm){if(asm){var keys=Object.keys(cds.cadViewer.partReplacement.previousPartAdded.obj);for(var i=0;i<keys.length;i++){var key=keys[i];var partKey=asm.name;if(asm.name.lastIndexOf('_')>-1){partKey=asm.name.slice(0,asm.name.lastIndexOf('_'));}
if(partKey!=key){asm.traverse(function(child){if(child.type==="Object3D"){var partKey=child.name;if(child.name.lastIndexOf('_')>-1){partKey=child.name.slice(0,child.name.lastIndexOf('_'));}
if(child.name!=cds.cadViewer.partReplacement.previousPartAdded.obj[key]||partKey!=cds.cadViewer.partReplacement.previousPartAdded.obj[key]){if(partKey===key&&asm.name!=key){var childSubasm=cds.cadViewer.replaceableSubAssemblyMap[cds.cadViewer.partReplacement.previousPartAdded.obj[key]];if(childSubasm){var parent=child.parent;parent.remove(child);parent.add(childSubasm);}}}}});}}}else{console.log("Object is null : inside traverseObjectToSetPreviouslySelectedReplaceables()");}},this.getAllReplaceableObjects=function(partKey){var replaceablesObjects=[];cds.cadViewer.getObjectsByName(partKey,cds.cadViewer.sceneObject,function(child){console.log(child.parent.name);replaceablesObjects.push(child);});return replaceablesObjects;},this.replacePart=function(PartKey,partNameToBeAdded,callback){this.replaceablesObjects=[];if(this.previousPartAdded.isEmpty(this.previousPartAdded.obj)){this.getDefaultPartAddedInModel();}
cds.cadViewer.getObjectsByName(this.previousPartAdded.obj[PartKey],cds.cadViewer.scene.children[2],function(child){cds.cadViewer.partReplacement.replaceablesObjects.push(child);});if(PartKey.split('.').pop().toLowerCase()=="json"){PartKey=PartKey.substr(0,PartKey.lastIndexOf('.'));}
if(this.replaceablesObjects.length>0){for(var i=0;i<this.replaceablesObjects.length;i++){var rObject=this.replaceablesObjects[i];if(rObject.name==this.previousPartAdded.obj[PartKey]){var prevPartMatrix=rObject.matrix;var prevPartExplodedMatrix=rObject.userData.ExplodedMatrix
var addPartIntoParent=rObject.parent;if(addPartIntoParent!=null){console.log("Removing from parent");addPartIntoParent.remove(rObject);}else{console.log("parent NULL");addPartIntoParent=cds.cadViewer.scene.children[2];addPartIntoParent.remove(rObject);}
if(rObject.children.length>0){if(rObject.children[0].type==="Object3D"){this.addPartIntoParent=addPartIntoParent;var partName=cds.cadViewer.replacedAssemblyToPartName[PartKey]
if(partName){cds.cadViewer.partReplacement.replaceablesObjects.delete(partName)}
this.addSubAssembly(partNameToBeAdded,callback);}else{this.addPart(partNameToBeAdded,addPartIntoParent,prevPartMatrix,prevPartExplodedMatrix,callback);}}else{this.addPart(partNameToBeAdded,addPartIntoParent,prevPartMatrix,prevPartExplodedMatrix,callback);}}}}else{console.log("Unable to find replaceable part for : "+this.previousPartAdded.obj[PartKey]);}
delete this.previousPartAdded.obj[PartKey];if(partNameToBeAdded.substr(partNameToBeAdded.lastIndexOf('.'),partNameToBeAdded.length)==".json"){this.previousPartAdded.add(PartKey,partNameToBeAdded.substr(0,partNameToBeAdded.lastIndexOf('.')));}else{this.previousPartAdded.add(PartKey,partNameToBeAdded);}}},OnCreatePartSwitchingPanel:function(){var parts=cds.cadViewer.getReplaceablePartInModel();if(parts!=undefined){var body=document.getElementsByTagName('body')[0];cds.cadViewer.addCSSPartReplace();var divReplacePart=document.createElement("div");divReplacePart.style="z-index: 9999;position: absolute;max-width: 200px;";divReplacePart.id="ReplaceParts";for(var key in parts){var selectTag=document.createElement("select");selectTag.id=key;selectTag.className="soflow";selectTag.addEventListener("change",cds.cadViewer.getSelectedValue,false);selectTag.add(new Option(key,true,true),null);for(var i=0;i<parts[key].length;i++){selectTag.add(new Option(parts[key][i],false,false),null);}
divReplacePart.appendChild(selectTag);}
body.insertBefore(divReplacePart,body.children[0]);}},getSelectedValue:function(e){var id=e.target.id;var selectedPartName=e.target.selectedOptions[0].innerText;cds.cadViewer.replacePart(id,selectedPartName);},addCSSPartReplace:function(){var csstag=document.createElement('style');csstag.append("select.soflow,select.soflow-color{-webkit-appearance:button;-webkit-border-radius:2px;-webkit-box-shadow:0 1px 3px rgba(0,0,0,.1);-webkit-padding-end:20px;-webkit-padding-start:2px;-webkit-user-select:none;background-image:url(http://i62.tinypic.com/15xvbd5.png),-webkit-linear-gradient(#FAFAFA,#F4F4F4 40%,#E5E5E5);background-position:97% center;background-repeat:no-repeat;border:1px solid #AAA;color:#555;font-size:inherit;margin:5px;overflow:hidden;padding:5px 10px;text-overflow:ellipsis;white-space:nowrap;width:300px}select.soflow-color{color:#fff;background-image:url(http://i62.tinypic.com/15xvbd5.png),-webkit-linear-gradient(#779126,#779126 40%,#779126);background-color:#779126;-webkit-border-radius:20px;-moz-border-radius:20px;border-radius:20px;padding-left:15px}")
var head=document.getElementsByTagName('head')[0];head.appendChild(csstag);},readJSON:function(filePath,assemblyId){if(!cds.cadViewer.hasOwnProperty('readJSONFile')||cds.cadViewer.readJSONFile===null){cds.cadViewer.readJSONFile=new cds.cadViewer.ReadJSONFile(assemblyId);}
cds.cadViewer.readJSONFile.readJSON(filePath,assemblyId);},ReadJSONFile:function(assemblyId){var ispartLoading=false;var JSONFileObject=new THREE.Object3D();var rootobj=new THREE.Object3D();var partDir=null;var bounding;var superRoot=new THREE.Object3D();var partCount=0;var countPart=0;this.readJSON=function(filePath,assemblyId){var cameraControls=new cds.cadViewer.CameraControls();if(cds.cadViewer.urlToSceneObjectMap[cds.cadViewer.cadFilePath]!=undefined){cds.cadViewer.scene.remove(cds.cadViewer.sceneObject)
cds.cadViewer.sceneObject=cds.cadViewer.urlToSceneObjectMap[cds.cadViewer.cadFilePath]
if(cds.cadViewer.sceneObject.userData.boundingBox!=undefined||cds.cadViewer.sceneObject.userData.boundingBox!=null){cds.cadViewer.sceneBoundingBox=cds.cadViewer.convertBoundingBox(cds.cadViewer.sceneObject.userData.boundingBox);}
cds.cadViewer.changeCameraTransform(cds.cadViewer.sceneBoundingBox);cds.cadViewer.centerCamera();cds.cadViewer.scene.add(cds.cadViewer.sceneObject)
cds.cadViewer.resetCamera()
cds.cadViewer.readJSONFile.onCompleteSceneLoad()
return}
partDir=filePath.substr(0,filePath.lastIndexOf('/')+1);var request=new XMLHttpRequest();request.open('GET',filePath,true);request.send(null);if(!cds.cadViewer.isAssembly){if(cds.cadViewer.partFileSize){request.onprogress=function(evt){var progress=(evt.loaded/cds.cadViewer.partFileSize)*100
cds.cadViewer.onAssemblyProgress(progress)}}}
request.onreadystatechange=function(){if(request.readyState==4){if(request.status==200){if(request.response!==""){JSONFileObject=JSON.parse(request.response);}
cameraControls.setCameraWith(JSONFileObject);if(!JSONFileObject.hasOwnProperty('filename')){cds.cadViewer.loadJSON(filePath,JSONFileObject);}else{if(JSONFileObject.userData.hasOwnProperty('DLL_Version')){console.log("DLL Version: "+JSONFileObject.userData.DLL_Version);console.log("Viewer version: "+cds.cadViewer.viewerVersion);}
cds.cadViewer.readJSONFile.readMainJSON(JSONFileObject,assemblyId);}}else{console.log("Failed to load, status code: "+request.status);}}}}
this.readMainJSON=function(JSONFileObject,assemblyId){if(assemblyId==undefined){rootobj.name=JSONFileObject.children[0].title;rootobj.type="Object3D";rootobj.parent=superRoot;cds.cadViewer.scene.add(superRoot);cds.cadViewer.sceneObject=superRoot;cds.cadViewer.urlToSceneObjectMap[cds.cadViewer.cadFilePath.toString()]=cds.cadViewer.sceneObject
cds.cadViewer.controls.reset();this.decideRootObject(JSONFileObject.children[0],rootobj);superRoot.children.push(rootobj);if(JSONFileObject.userData){superRoot.userData=JSONFileObject.userData;}}else{rootobj.name=assemblyId;var assembly=this.getAssemblyByName(JSONFileObject,assemblyId);rootobj.type="Object3D";rootobj.parent=superRoot;rootobj.userData.ExplodedMatrix=assembly.userData.ExplodedMatrix;this.decideRootObject(assembly,rootobj);superRoot.children.push(rootobj);if(JSONFileObject.userData){superRoot.userData=JSONFileObject.userData;}
cds.cadViewer.sceneObject=superRoot;cds.cadViewer.scene.add(cds.cadViewer.sceneObject);}
if(cds.cadViewer.sceneBoundingBox!=undefined||cds.cadViewer.sceneBoundingBox!=null){cds.cadViewer.changeCameraTransform(cds.cadViewer.sceneBoundingBox);cds.cadViewer.centerCamera();}
if(JSONFileObject.hasOwnProperty('OffsetLines')){this.loadOffsetLines(JSONFileObject.OffsetLines)}}
this.loadOffsetLines=function(jOffsetLines){var material=new THREE.LineDashedMaterial({color:0x0000ff,linewidth:1,scale:1,dashSize:4,gapSize:6,});for(var j=0;j<jOffsetLines[0].geometries.length;j++){var geom=jOffsetLines[0].geometries[j]
var geometry=new THREE.Geometry();if(geom.data.vertices.length%3==0){for(var i=0;i<=geom.data.vertices.length-3;i+=3){var vec=new THREE.Vector3(geom.data.vertices[i],geom.data.vertices[i+1],geom.data.vertices[i+2])
geometry.vertices.push(vec)}}
geometry.computeLineDistances();var line=new THREE.Line(geometry,material);if(!cds.cadViewer.hasOwnProperty('offsetLines')){cds.cadViewer.offsetLines=[]}
line.visible=false
cds.cadViewer.offsetLines.push(line)
cds.cadViewer.sceneObject.add(line);}}
this.getAssemblyByName=function(json,assemblyId){var assembly=this.getAssemblyJson(json.children[0],assemblyId);return assembly;}
this.getAssemblyJson=function(jsonObject,assemblyId){for(var i=0;i<jsonObject.children.length;i++){var children=jsonObject.children;if(children[i].children.length>0){if(children[i].userData.compId==assemblyId){return children[i];}
var assembly=this.getAssemblyJson(children[i],assemblyId);if(assembly!==undefined){return assembly;}}}},this.decideRootObject=function(JSONRootObject,rootobject){var childCount=JSONRootObject.children.length;switch(JSONRootObject.type){case"Assembly":this.traverseMainJSON(JSONRootObject,rootobj,null,function(progress){cds.cadViewer.onAssemblyProgress(progress)});break;case"Part":this.loadPartFile(JSONRootObject,rootobject,this.onPartLoad);partCount+=1;}}
this.traverseMainJSON=function(JSONobj,rootobject,parentExplosionMatrix,onProgress){var totalChildCount=JSONobj.children.length
var childrenLoaded=0
for(var x=0;x<JSONobj.children.length;x++){var scopedMatrix=JSON.parse(JSON.stringify(parentExplosionMatrix));if(JSONobj.children[x].type=="Assembly"){var isReplaceableSubAsm=false;var _subasm=new THREE.Object3D();_subasm.name=JSONobj.children[x].title;var _smatrix=new THREE.Matrix4();_smatrix.fromArray(JSONobj.children[x].matrix);_subasm.applyMatrix(_smatrix);_subasm.updateMatrix();_subasm.parent=rootobject;_subasm.userData=JSON.parse(JSON.stringify(JSONobj.children[x].userData));var childExploMatrix=new THREE.Matrix4()
if(scopedMatrix){var exploMatrix=new THREE.Matrix4();exploMatrix.fromArray(scopedMatrix);if(_subasm.userData.ExplodedMatrix){var newExplosionMatrix=exploMatrix.clone()
childExploMatrix.fromArray(_subasm.userData.ExplodedMatrix);var newMatrix=new THREE.Matrix4();newMatrix.multiplyMatrices(newExplosionMatrix,childExploMatrix);var invertedMatrix=exploMatrix.getInverse(exploMatrix);var matrix=new THREE.Matrix4()
matrix.multiplyMatrices(invertedMatrix,childExploMatrix);_subasm.userData.ExplodedMatrix=matrix.toArray();scopedMatrix=newMatrix.toArray()}else{var matrix=new THREE.Matrix4()
matrix.multiplyMatrices(exploMatrix,_subasm.matrix);scopedMatrix=matrix.toArray()}}else{if(_subasm.userData.ExplodedMatrix){var exploMatrix=rootobject.matrix.clone();childExploMatrix.fromArray(_subasm.userData.ExplodedMatrix);var invertedMatrix=exploMatrix.getInverse(exploMatrix);var matrix=invertedMatrix.multiply(childExploMatrix);_subasm.userData.ExplodedMatrix=matrix.toArray();scopedMatrix=matrix.toArray()}else{scopedMatrix=_subasm.matrix.toArray();}}
this.checkReplaceableSubassemblies(_subasm);if(cds.cadViewer.hasOwnProperty('replaceableSubAsmNameList')){var replaceableValuesArray=Object.values(cds.cadViewer.replaceableSubAsmNameList);for(var i=0;i<replaceableValuesArray.length;i++){var values=replaceableValuesArray[i];if(values.indexOf(_subasm.name)>-1){isReplaceableSubAsm=true;if(!cds.cadViewer.hasOwnProperty('replaceableSubAssemblyMap')){cds.cadViewer.replaceableSubAssemblyMap={};}
cds.cadViewer.replaceableSubAssemblyMap[_subasm.name]=_subasm;}}}
if(!isReplaceableSubAsm){rootobject.children.push(_subasm);}
this.traverseMainJSON(JSONobj.children[x],_subasm,JSON.parse(JSON.stringify(scopedMatrix)),function(progress){if(progress==100){childrenLoaded+=1
var progress=(childrenLoaded/totalChildCount)*100
onProgress(progress)}});}else if(JSONobj.children[x].type=="Part"){this.loadPartFile(JSONobj,JSONobj.children[x],rootobject,JSON.parse(JSON.stringify(scopedMatrix)),this.onPartLoad,function(){childrenLoaded+=1
var progress=(childrenLoaded/totalChildCount)*100
onProgress(progress)});partCount+=1;}}}
this.loadPartFile=function(subAsmJsonObj,JSONobj,rootobject,scopedMatrix,callback,partLoaded){var cadURL="";if(cds.cadViewer.previousPartAdded!=null){if(cds.cadViewer.previousPartAdded.obj!=undefined){if(JSONobj.title in cds.cadViewer.previousPartAdded.obj){cadURL=partDir+cds.cadViewer.previousPartAdded.obj[JSONobj.title]+".json"}else{cadURL=partDir+JSONobj.filename;}}}else{cadURL=partDir+JSONobj.filename;}
var loader=new THREE.ObjectLoader();loader.setCrossOrigin('Anonymous');loader.load(cadURL,function(loadedScene){loadedScene.name=JSONobj.filename;if(JSONobj.hasOwnProperty('userData')){if(JSONobj.userData.hasOwnProperty('compId')){loadedScene.userData.compId=JSONobj.userData.compId;}}
callback(loadedScene,subAsmJsonObj,JSONobj,rootobject,scopedMatrix,function(){partLoaded()},cds.cadViewer.readJSONFile.onCompleteSceneLoad);});}
this.onPartLoad=function(loadedScene,subAsmJsonObj,JSONobj,subAsmNode,parentExplosionMatrix,partLoaded,callback){var partNode=loadedScene.children[0];if(cds.cadViewer.instancingEnabled){if(cds.cadViewer.partNameToObject3d[JSONobj.filename]!=undefined){var partNode=cds.cadViewer.partNameToObject3d[JSONobj.filename].clone();}else{cds.cadViewer.partNameToObject3d[JSONobj.filename]=partNode.clone();}}
partNode.uuid=THREE.Math.generateUUID();partNode.parent=subAsmNode;var matrix=new THREE.Matrix4();matrix.fromArray(JSONobj.matrix);partNode.applyMatrix(matrix);partNode.updateMatrix();if(JSONobj.userData){partNode.userData.ExplodedMatrix=JSONobj.userData.ExplodedMatrix;partNode.userData.compId=JSONobj.userData.compId;if(JSONobj.userData.ExplodedMatrix){var exploMatrix=new THREE.Matrix4();if(parentExplosionMatrix!=undefined){exploMatrix.fromArray(parentExplosionMatrix);var childExploMatrix=new THREE.Matrix4();childExploMatrix.fromArray(partNode.userData.ExplodedMatrix);var invertedMatrix=exploMatrix.getInverse(exploMatrix);var matrix=invertedMatrix.multiply(childExploMatrix);partNode.userData.ExplodedMatrix=matrix.toArray();}}}
subAsmNode.children.push(partNode);cds.cadViewer.storeOriginalMatrixOfPartInUserData(partNode);countPart+=1;if(countPart==partCount){callback(cds.cadViewer.scene);}
partLoaded()}
this.onCompleteSceneLoad=function(){var _this=cds.cadViewer;try{var cameraControls=new _this.CameraControls();if(cds.cadViewer.sceneBoundingBox==undefined||cds.cadViewer.sceneBoundingBox==null){cds.cadViewer.sceneBoundingBox=cds.cadViewer.sceneObject.getBoundingBox();var scale=cds.cadViewer.scaleObject(cds.cadViewer.sceneObject.getBoundingBox());cds.cadViewer.sceneObject.scale.set(scale,scale,scale)
cds.cadViewer.centerObject(cds.cadViewer.sceneObject);}
cameraControls.setCameraPosition(cds.cadViewer.sceneObject.userData.cameraPosition);cameraControls.storeCameraPosition();_this.originalSceneObjectMatertials.length=0;_this.edgeEffect.enabled=false;_this.setRenderMode(cds.cadViewer.currentRenderMode);_this.animate();_this.render();cds.cadViewer.applyStudioProperties();}catch(e){console.log("Error loading model in CDS CAD viewer: "+e);}finally{_this.isLoading=false;if(!cds.cadViewer.showPercentLoader)
_this.loadingIcon.style.display="none";delete _this.readJSONFile;_this.controls.handleResize();_this.controls.enabled=true;_this.bbs.forEach(function(b){_this.scene.remove(b);});_this.bbs.length=0;_this.originalWidth=Number.MAX_VALUE;_this.originalHeight=Number.MAX_VALUE;_this.alreadyBinned=false;if(_this.alreadyBinned===false){_this.alreadyBinned=true;_this.originalWidth=_this.renderer.domElement.offsetWidth;_this.originalHeight=_this.renderer.domElement.offsetHeight;}
_this.partNameToObject3d=[]
_this.postLoadSceneCallback();}}
this.checkReplaceableSubassemblies=function(subassembly){if(subassembly.userData.hasOwnProperty('Replaceable_count')){if(!cds.cadViewer.hasOwnProperty('replaceableSubAsmNameList')){cds.cadViewer.replaceableSubAsmNameList={};}
for(var i=1;i<=subassembly.userData.Replaceable_count;i++){if(!cds.cadViewer.replaceableSubAsmNameList[subassembly.name]){cds.cadViewer.replaceableSubAsmNameList[subassembly.name]=new Array();}
cds.cadViewer.replaceableSubAsmNameList[subassembly.name].push(subassembly.name+"_"+i);}}}},getMonthOrdinal:function(month){switch(month){case"Jan":return 1;break;case"Feb":return 2;break;case"Mar":return 3;break;case"April":return 4;break;case"May":return 5;break;case"June":return 6;break;case"July":return 7;break;case"Aug":return 8;break;case"Sept":return 9;break;case"Oct":return 10;break;case"Nov":return 11;break;default:return 12;}},ifDllHasBumpScaled:function(dllVersion){var lstString=dllVersion.split('.');var date=new Date(lstString[0],cds.cadViewer.getMonthOrdinal(lstString[1]),lstString[2]);var dateForDllWithBumpScale=new Date(2018,8,21);return date>=dateForDllWithBumpScale||(dllVersion.indexOf("1.0.0")!==-1);},CameraControls:function(){this.setCameraFrom=function(userData){if(userData.DLL_Version!=undefined){if(cds.cadViewer.ifDllHasBumpScaled(userData.DLL_Version)){if(userData.hasOwnProperty('boundingBox'))
cds.cadViewer.sceneBoundingBox=cds.cadViewer.convertBoundingBox(userData.boundingBox);}}}
this.setCameraWith=function(jsonFileObject){if(jsonFileObject.hasOwnProperty('userData')){this.setCameraFrom(jsonFileObject.userData)}else if(jsonFileObject.hasOwnProperty('object')){if(jsonFileObject.object.hasOwnProperty('userData')){this.setCameraFrom(jsonFileObject.object.userData)}}}
this.storeCameraPosition=function(){cds.cadViewer.cameraPosX=cds.cadViewer.camera.position.x;cds.cadViewer.cameraPosY=cds.cadViewer.camera.position.y;cds.cadViewer.cameraPosZ=cds.cadViewer.camera.position.z;cds.cadViewer.cameraRotX=cds.cadViewer.camera.rotation.x;cds.cadViewer.cameraRotY=cds.cadViewer.camera.rotation.y;cds.cadViewer.cameraRotZ=cds.cadViewer.camera.rotation.z;}
this.setCameraPosition=function(cameraPosition){if(cameraPosition!=undefined){var identity=new THREE.Matrix4().identity();var matrix=new THREE.Matrix4().fromArray(cameraPosition)
if(!matrix.equals(identity)){cds.cadViewer.camera.updateMatrix();var mat=new THREE.Matrix4().fromArray(cameraPosition);var inverse=new THREE.Matrix4();inverse.getInverse(mat);var quaternion=new THREE.Quaternion();var position=new THREE.Vector3();var scale=new THREE.Vector3();inverse.decompose(position,quaternion,scale);cds.cadViewer.camera.position.set(position.x,position.y,position.z);cds.cadViewer.camera.up.set(cameraPosition[1],cameraPosition[5],cameraPosition[9]);cds.cadViewer.camera.updateProjectionMatrix();}}}
this.setZoomLimits=function(minDistanceMultiplier){var __this=cds.cadViewer;if(!cds.cadViewer.scene.children[2].userData.hasOwnProperty("boundingBox")){var radius=Math.max(__this.sceneBoundingBox.max.x-__this.sceneBoundingBox.min.x,__this.sceneBoundingBox.max.y-__this.sceneBoundingBox.min.y,__this.sceneBoundingBox.max.z-__this.sceneBoundingBox.min.z);var maxScale=Math.max(__this.sceneObject.scale.x,__this.sceneObject.scale.y,__this.sceneObject.scale.z);__this.controls.minDistance=radius*maxScale;__this.controls.maxDistance=__this.controls.minDistance*__this.ZOOM_MULTIPLIER;if(typeof minDistanceMultiplier!=="undefined"&&minDistanceMultiplier!==null){__this.controls.minDistance*=minDistanceMultiplier;}}else{var dist=cds.cadViewer.camera.position.distanceTo(cds.cadViewer.sceneObject.position)
var scalefactor=dist/2;__this.controls.minDistance=scalefactor;__this.controls.maxDistance=__this.controls.minDistance*__this.ZOOM_MULTIPLIER;if(typeof minDistanceMultiplier!=="undefined"&&minDistanceMultiplier!==null){__this.controls.minDistance*=minDistanceMultiplier;}}}},fetchMaterial:function(materialId){var material=undefined;cds.cadViewer.scene.traverse(function(mesh){if(mesh instanceof THREE.Mesh){for(var i=0;i<mesh.material.length;i++){if(mesh.material[i]){if(mesh.material[i].uuid==materialId){material=mesh.material[i];break;}}else{console.log("Material undefined");}}}});return material;},getConfigurableMaterials:function(){var configurableMaterials=new Object();cds.cadViewer.scene.traverse(function(object){if(object instanceof THREE.Object3D||object instanceof THREE.Group){var confMap=object.userData.configurableMaterials;if(confMap!=undefined){for(var i=0;i<Object.keys(confMap).length;i++){configurableMaterials[Object.keys(confMap)[i]]=confMap[Object.keys(confMap)[i]];}}}});return configurableMaterials;},getSurfaceMaterial:function(surfaceType){var matId="";var materialMap=cds.cadViewer.getConfigurableMaterials();for(var i=0;i<Object.keys(materialMap).length;i++){if(Object.keys(materialMap)[i]==surfaceType){matId=materialMap[surfaceType];}}
if(matId!=""){var material=cds.cadViewer.fetchMaterial(matId);return material;}else{console.log("Unable to find material for surface : "+surfaceType);return undefined;}},setSurfaceColor:function(surfaceType,color){if(color.indexOf("#")===0){color=color.substring(1);}
var material=cds.cadViewer.getSurfaceMaterial(surfaceType);if(material!=undefined){if(material.map){material.map=null;}
material.color.setHex('0x'+color.toString());material.needsUpdate=true;}},setSurfaceTexture:function(surfaceType,textureImageUrl,isBumpEnabled){var material=cds.cadViewer.getSurfaceMaterial(surfaceType);if(material!=undefined){if(isBumpEnabled){material.bumpMap=new THREE.TextureLoader().load(textureImageUrl);material.bumpScale=1;}else{material.bumpMap=undefined;material.map=new THREE.TextureLoader().load(textureImageUrl);}
material.needsUpdate=true;}},setSurfaceBumpTexture:function(surfaceType,textureImageUrl){cds.cadViewer.swapSurfaceTexture(surfaceType,textureImageUrl,true);},storeOriginalMatrixOfPartInUserData:function(part){if(!part.userData.hasOwnProperty('OriginalMatrix')){part.userData.OriginalMatrix=null;}
part.userData.OriginalMatrix=part.matrix.clone();},toggleAnimation:function(){if(!cds.cadViewer.hasOwnProperty('animation')){cds.cadViewer.animation=new cds.cadViewer.Animation();}
cds.cadViewer.animation.isAnimationEnabled=!cds.cadViewer.animation.isAnimationEnabled;},hasKinematics:function(partName){var part=cds.cadViewer.scene.getObjectByName(partName);if(part!=undefined){if(part.userData.hasOwnProperty('Kinematics')){if(part.userData.Kinematics.length>0){return true;}}}else{console.log("Unable to get part with name "+partName);}
return false;},getPartUnderMouseForAnimation:function(){var intersects=cds.cadViewer.getIntersects(cds.cadViewer.sceneObject.children);if(intersects.length>0){var part=intersects[0].object;if(part instanceof THREE.Mesh){part=intersects[0].object.parent;}
if(part instanceof THREE.Object3D&&part.name!="")
cds.cadViewer.runAnimation(part.name);}},runAnimation:function(partName){if(!cds.cadViewer.hasOwnProperty('animation')){cds.cadViewer.animation=new cds.cadViewer.Animation();}
cds.cadViewer.animation.SetKinematicsToPart(partName);},Animation:function(){var index=0;this.obj=function(){obj=new Object();this.add=function(key,value){obj[""+key+""]=value;},this.isEmpty=function(obj){if(obj==undefined){obj=this.obj;}
for(var key in obj){if(obj.hasOwnProperty(key))
return false;}
return true;},this.obj=obj;}
this.isAnimationEnabled=false;this.lastAnimationAddedForPart=new Object();this.isTweening=false;this.isLastAnimation=false;this.partInQueue=[];var part;this.endTransformation;this.endTransformation;this.reset=new Object();this.SetKinematicsToPart=function(partName){var part=cds.cadViewer.scene.getObjectByName(partName);if(part.userData.hasOwnProperty('Kinematics')){if(part!=undefined){this.isTweening=true;if(index>0){index=0;}
this.pauseAnimationOnClick(partName);this.applyAnimation(part,index);}}}
this.pauseAnimationOnClick=function(partName){var part=cds.cadViewer.scene.getObjectByName(partName);if(this.reset[""+partName+""]){index=part.userData.Kinematics.length;this.reset[""+partName+""]=false;}else if(this.lastAnimationAddedForPart){if(this.lastAnimationAddedForPart[partName]){index=this.lastAnimationAddedForPart[partName];this.reset[""+partName+""]=true;if(index===part.userData.Kinematics.length-1){delete this.lastAnimationAddedForPart[partName];}else if(index===part.userData.Kinematics.length){index=0;}}else{if(index===0){this.lastAnimationAddedForPart[""+partName+""]=index+1;this.reset[""+partName+""]=true;}}}else{if(index===0){this.lastAnimationAddedForPart[""+partName+""]=index+1;this.reset[""+partName+""]=true;}}}
this.addPartInQueueForAnimation=function(partName){this.partInQueue.push(partName);}
this.applyAnimation=function(part,index){if(part.userData.hasOwnProperty('Kinematics')){if(this.isTweening){console.log("inside applyAnimation()");if(index<part.userData.Kinematics.length){var MATRIX_ARRAY=part.userData.Kinematics[index];var matrix=new THREE.Matrix4();matrix.fromArray(MATRIX_ARRAY);if(!part.userData.hasOwnProperty('OriginalMatrix')&&index===0){part.userData.OriginalMatrix=part.matrix.clone();}
var dummyObj=new THREE.Object3D();dummyObj.applyMatrix(matrix);dummyObj.updateMatrix();var endR=dummyObj.rotation;var startR=part.rotation;var startDegX=parseFloat(THREE.Math.radToDeg(startR.x).toFixed(3));var startDegY=parseFloat(THREE.Math.radToDeg(startR.y).toFixed(3));var startDegZ=parseFloat(THREE.Math.radToDeg(startR.z).toFixed(3));var endDegX=parseFloat(THREE.Math.radToDeg(endR.x).toFixed(3));var endDegY=parseFloat(THREE.Math.radToDeg(endR.y).toFixed(3));var endDegZ=parseFloat(THREE.Math.radToDeg(endR.z).toFixed(3));var endTransformation={x:dummyObj.position.x,y:dummyObj.position.y,z:dummyObj.position.z,rx:dummyObj.quaternion.x,ry:dummyObj.quaternion.y,rz:dummyObj.quaternion.z,rw:dummyObj.quaternion.w,};}else if(index===part.userData.Kinematics.length){if(part.userData.hasOwnProperty('OriginalMatrix')){var position=part.position;var quaternion=part.quaternion;var dummyObj=new THREE.Object3D();dummyObj.applyMatrix(part.userData.OriginalMatrix);dummyObj.updateMatrix();var endTransformation={x:dummyObj.position.x,y:dummyObj.position.y,z:dummyObj.position.z,rx:dummyObj.quaternion.x,ry:dummyObj.quaternion.y,rz:dummyObj.quaternion.z,rw:dummyObj.quaternion.w,};}
this.isLastAnimation=true;}
this.addAnimation(endTransformation,part);}}else{console.log(part.name+" does not contains kinematics data");}}
this.addAnimation=function(endTransformation,part){var position=part.position;var quaternion=part.quaternion;var startTransformation={x:position.x,y:position.y,z:position.z,rx:quaternion.x,ry:quaternion.y,rz:quaternion.z,rw:quaternion.w,};if(startTransformation!=undefined&&endTransformation!=undefined){var twn=new TWEEN.Tween(startTransformation).to(endTransformation,1500).easing(TWEEN.Easing.Linear.None).onUpdate(function(){part.position.set(startTransformation.x,startTransformation.y,startTransformation.z);part.quaternion.set(startTransformation.rx,startTransformation.ry,startTransformation.rz,startTransformation.rw);}).onComplete(function(){twn.stop();cds.cadViewer.animation.isTweening=false;}).start();}}},addBaseGridInViewer:function(){if(!cds.cadViewer.hasOwnProperty('gridHelper')){var bb=new THREE.Box3().setFromObject(cds.cadViewer.sceneObject);cds.cadViewer.gridHelper=new THREE.GridHelper(100,100);cds.cadViewer.gridHelper.position.set(bb.getCenter().x,bb.min.y,bb.getCenter().z);var scaleFactor=cds.cadViewer.getScaleFactor(cds.cadViewer.sceneObject,cds.cadViewer.gridHelper);scaleFactor*=3;cds.cadViewer.gridHelper.scale.set(scaleFactor,scaleFactor,scaleFactor);cds.cadViewer.gridHelper.name="baseGrid";cds.cadViewer.scene.add(cds.cadViewer.gridHelper);if(!cds.cadViewer.hasOwnProperty('isBaseGridEnabled')){cds.cadViewer.isBaseGridEnabled=false;}
cds.cadViewer.isBaseGridEnabled=true;}},createMutableGrid:function(){if(!cds.cadViewer.hasOwnProperty('mutableGrid')){var size=100;var dimension=100;var bb=cds.cadViewer.sceneObject.getBoundingBox();cds.cadViewer.mutableGrid=new THREE.GridHelper(size,dimension);cds.cadViewer.mutableGrid.position.set(bb.getCenter().x,bb.min.y,bb.getCenter().z);cds.cadViewer.mutableGrid.name="mutableGrid";cds.cadViewer.scene.add(cds.cadViewer.mutableGrid);}
if(!cds.cadViewer.hasOwnProperty('isMutableGridEnabled')){cds.cadViewer.isMutableGridEnabled=false;}
cds.cadViewer.isMutableGridEnabled=true;},updateMutableGrid:function(size,divisions){if(cds.cadViewer.hasOwnProperty('mutableGrid')){cds.cadViewer.scene.remove(cds.cadViewer.mutableGrid);var bb=new THREE.Box3().setFromObject(cds.cadViewer.sceneObject);cds.cadViewer.mutableGrid=new THREE.GridHelper(size,divisions);cds.cadViewer.mutableGrid.position.set(bb.getCenter().x,bb.min.y,bb.getCenter().z);cds.cadViewer.mutableGrid.name="mutableGrid";cds.cadViewer.scene.add(cds.cadViewer.mutableGrid);}},getScaleFactor:function(object1,object2){var length1=cds.cadViewer.getBoundingBoxLength(object1.getBoundingBox());var length2=cds.cadViewer.getBoundingBoxLength(object2.getBoundingBox());return length1/length2;},getBoundingBoxLength:function(boundingBox){var v1=boundingBox.max;var v2=boundingBox.min;var dx=v1.x-v2.x;var dy=v1.y-v2.y;var dz=v1.z-v2.z;var length=Math.sqrt(dx*dx+dy*dy+dz*dz);return length;},toggleBaseGrid:function(){cds.cadViewer.setBaseGrid(!cds.cadViewer.isBaseGridEnabled);},setBaseGrid:function(state){if(cds.cadViewer.hasOwnProperty("gridHelper")){cds.cadViewer.gridHelper.visible=state;cds.cadViewer.isBaseGridEnabled=cds.cadViewer.gridHelper.visible;}else if(state){console.log("Grid is not added in scene");cds.cadViewer.addBaseGridInViewer();}},toggleMutableGrid:function(){cds.cadViewer.setMutableGrid(!cds.cadViewer.isMutableGridEnabled);},setMutableGrid:function(state){if(cds.cadViewer.hasOwnProperty("mutableGrid")){cds.cadViewer.mutableGrid.visible=state;cds.cadViewer.isMutableGridEnabled=cds.cadViewer.mutableGrid.visible;}else if(state){cds.cadViewer.createMutableGrid();}},clearBaseGridFromScene:function(){if(cds.cadViewer.hasOwnProperty('gridHelper')&&cds.cadViewer.hasOwnProperty('isBaseGridEnabled')){if(cds.cadViewer.isBaseGridEnabled){cds.cadViewer.scene.remove(cds.cadViewer.gridHelper);delete cds.cadViewer.gridHelper;delete cds.cadViewer.isBaseGridEnabled;}}},toggleShadowinViewer:function(){if(!cds.cadViewer.hasOwnProperty('toggleShadow')){cds.cadViewer.toggleShadow=false;}
cds.cadViewer.toggleShadow=!cds.cadViewer.toggleShadow;if(!cds.cadViewer.hasOwnProperty('shadows')){cds.cadViewer.shadows=new cds.cadViewer.Shadows();}
cds.cadViewer.shadows.setShadowInViewer(cds.cadViewer.toggleShadow);},Shadows:function(){this.shadowLight=null;this.shadowPlane=null;this.lightTobeRestore=null;this.setShadowInViewer=function(isShadowEnabled){if(!cds.cadViewer.isLoading){if(isShadowEnabled){this.addShadows();this.enableObjectsToCastShadows();}else{this.disableObjectsToCastShadow();this.removeShadows();}}}
this.addShadows=function(){if(this.shadowLight==null||this.shadowPlane==null){this.createShadowLightAndPlane();}else{cds.cadViewer.camera.children[0].intensity=0;}
cds.cadViewer.scene.add(this.shadowPlane);cds.cadViewer.scene.add(this.shadowLight);}
this.createShadowLightAndPlane=function(){var bb=new THREE.Box3().setFromObject(cds.cadViewer.sceneObject);var geometry=new THREE.PlaneBufferGeometry(100,100);var planeMaterial=new THREE.ShadowMaterial();planeMaterial.opacity=0.5;this.shadowPlane=new THREE.Mesh(geometry,planeMaterial);this.shadowPlane.name="ShadowPlane";if(cds.cadViewer.sceneObject.userData.boundingBox!=undefined){this.shadowPlane.position.set(bb.getCenter().x,bb.min.y,bb.getCenter().z);}else{this.shadowPlane.position.set(0,bb.min.y,0);}
var scaleFactor=cds.cadViewer.getScaleFactor(cds.cadViewer.sceneObject,this.shadowPlane);scaleFactor*=5;this.shadowPlane.scale.set(scaleFactor,scaleFactor,scaleFactor);this.shadowPlane.rotation.x=-Math.PI/2;this.shadowPlane.castShadow=false;this.shadowPlane.receiveShadow=true;this.shadowLight=cds.cadViewer.scene.children[0].children[0].clone();this.lightTobeRestore=cds.cadViewer.scene.children[0].children[0];var tempCam=cds.cadViewer.camera.clone();tempCam.remove(tempCam.children[0])
this.shadowLight.shadow.camera=tempCam;this.shadowLight.lookAt(bb.getCenter());if(cds.cadViewer.sceneObject.userData.boundingBox!=undefined){var scaleFactor=cds.cadViewer.scaleObject(cds.cadViewer.sceneObject.getBoundingBox());var distance=(cds.cadViewer.sceneBoundingBox.max.y-cds.cadViewer.sceneBoundingBox.min.y)*20;var lightPositionAlongYAxis=distance;this.shadowLight.position.set(0,lightPositionAlongYAxis,0);}else{this.shadowLight.position.set(0,1000,0);}
this.shadowLight.castShadow=true;this.shadowLight.shadow.mapSize.width=cds.cadViewer.renderer.domElement.width;this.shadowLight.shadow.mapSize.height=cds.cadViewer.renderer.domElement.height;this.shadowLight.shadow.bias=0.0001;this.shadowLight.shadow.radius=1;this.shadowLight.shadow.camera.near=10;this.shadowLight.shadow.camera.updateProjectionMatrix();this.shadowLight.intensity=0.1;var renderer=cds.cadViewer.renderer;renderer.shadowMap.enabled=true;renderer.shadowMap.type=THREE.PCFSoftShadowMap;}
this.enableObjectsToCastShadows=function(){var objects=[];cds.cadViewer.sceneObject.traverse(function(mesh){if(mesh instanceof THREE.Mesh){mesh.castShadow=true;mesh.receiveShadow=false;}});}
this.disableObjectsToCastShadow=function(){var objects=[];cds.cadViewer.sceneObject.traverse(function(mesh){if(mesh instanceof THREE.Mesh){mesh.castShadow=false;mesh.receiveShadow=false;}});}
this.removeShadows=function(){if(this.lightTobeRestore!==null){if(this.lightTobeRestore.intensity==0){this.lightTobeRestore.intensity=0.5;}
cds.cadViewer.scene.children[0].children[0]=this.lightTobeRestore;cds.cadViewer.scene.remove(this.shadowPlane);cds.cadViewer.scene.remove(this.shadowLight);delete cds.cadViewer.shadows;}else{console.log("Shadow is not added in scene");}}},setBrassMaterial:function(partName){if(!cds.cadViewer.hasOwnProperty('envMap')){cds.cadViewer.envMap=new cds.cadViewer.EnvironmentMap();}
var part=cds.cadViewer.scene.getObjectByName(partName);part.traverse(function(mesh){if(mesh instanceof THREE.Mesh){for(var i=0;i<mesh.material.length;i++){mesh.material[i].color.setHex('0xf2bd2b');}}});if(cds.cadViewer.hasOwnProperty('envMap')){if(cds.cadViewer.envMap.enabled){cds.cadViewer.envMap.setEnvironmentMap();}}},setMetalTextureForPart:function(partName,metalTextureType,envImageDirectory){if(!cds.cadViewer.hasOwnProperty('textureMap')){cds.cadViewer.textureMap=new cds.cadViewer.ChromeBrassTexture();}
if(cds.cadViewer.textureMap.envTextureCube==null&&envImageDirectory==undefined){console.log("Need to specify third input parameter i.e. environment mapping images directory");}
if(partName!=undefined&&metalTextureType!=undefined){cds.cadViewer.textureMap.setTexture(partName,metalTextureType,envImageDirectory);}},ChromeBrassTexture:function(){this.enabled=false;this.envTextureCube=null;this.metalType="";this.setTexture=function(partName,metalTextureType,envImageDirectory){"use strict";this.metalType=metalTextureType.toLowerCase();if(this.envTextureCube==null){this.createReflectionCube(envImageDirectory);}
if(this.metalType=="chrome"){this.setChromeTextureToPart(partName);}else if(this.metalType=="brass"){this.setBrassMaterial(partName);}}
this.setBrassMaterial=function(partName){var part=cds.cadViewer.scene.getObjectByName(partName);if(part!=undefined){part.traverse(function(mesh){if(mesh instanceof THREE.Mesh){if(mesh.material.length!=undefined){for(var i=0;i<mesh.material.length;i++){mesh.material[i].color.setHex('0xf2bd2b');mesh.material[i].envMap=cds.cadViewer.textureMap.envTextureCube;mesh.material[i].combine=THREE.MixOperation;mesh.material[i].reflectivity=0.5;if(mesh.material[i].map){mesh.material[i].map=null;}
mesh.material[i].needsUpdate=true;}}else{mesh.material.color.setHex('0xf2bd2b');mesh.material.envMap=cds.cadViewer.textureMap.envTextureCube;mesh.material.combine=THREE.MixOperation;mesh.material.reflectivity=0.5;if(mesh.material.map){mesh.material.map=null;}
mesh.material.needsUpdate=true;}}});}else{console.log("Unable to find part : "+partName)}}
this.setChromeTextureToPart=function(partName){var part=cds.cadViewer.scene.getObjectByName(partName);if(part!=undefined){part.traverse(function(mesh){if(mesh instanceof THREE.Mesh){if(mesh.material.length>0){if(mesh.material.length!=undefined){for(var i=0;i<mesh.material.length;i++){if(mesh.material[i].color.getHexString()=="f2bd2b"){mesh.material[i].color.setHex('0x96a0ab');}
mesh.material[i].envMap=cds.cadViewer.textureMap.envTextureCube;mesh.material[i].combine=THREE.MixOperation;mesh.material[i].shininess=30;mesh.material[i].reflectivity=0.5;mesh.material[i].needsUpdate=true;}}else{mesh.material.envMap=cds.cadViewer.textureMap.envTextureCube;mesh.material.combine=THREE.MixOperation;mesh.material.shininess=30;mesh.material.reflectivity=0.5;mesh.material.needsUpdate=true;}}}});}else{console.log("Unable to find part : "+partName)}}
this.createReflectionCube=function(envImageDirectory){var path=envImageDirectory;var format='.jpg';var urls=[path+'top'+format,path+'ny'+format,path+'top'+format,path+'t1'+format,path+'ny'+format,path+'top'+format];var reflectionCube=new THREE.CubeTextureLoader().load(urls);this.envTextureCube=reflectionCube;}},applyStudioProperties:function(){cds.cadViewer.studioUtils=new cds.cadViewer.StudioUtils();let studioFeatures=cds.cadViewer.sceneObject.userData.studioFeatures
if(studioFeatures){if(studioFeatures.material)
cds.cadViewer.studioUtils.applyStudioProperties();if(studioFeatures.animation)
cds.cadViewer.studioUtils.loadStudioAnimations();if(studioFeatures.explosion)
cds.cadViewer.studioUtils.loadStudioExplosions();if(studioFeatures.annotation)
cds.cadViewer.studioUtils.loadStudioAnnotations();if(studioFeatures.camera)
cds.cadViewer.studioUtils.loadCameraViewPoints();}else{cds.cadViewer.studioUtils.applyStudioProperties();cds.cadViewer.studioUtils.loadStudioAnimations();cds.cadViewer.studioUtils.loadStudioExplosions();cds.cadViewer.studioUtils.loadStudioAnnotations();cds.cadViewer.studioUtils.loadCameraViewPoints();}},setSkyBox:function(box){cds.cadViewer.skyBox=box
cds.cadViewer.scene.background=cds.cadViewer.envMaterialMap(undefined,box);},toggleSkyBox:function(){cds.cadViewer.scene.background=cds.cadViewer.scene.background==null?cds.cadViewer.envMaterialMap(undefined,cds.cadViewer.skyBox):null},setEnvMap:function(mode,env){cds.cadViewer.environment.type=mode
cds.cadViewer.environment.map=env
cds.cadViewer.reflectiveMaterials.forEach(function(material){material.envMap=cds.cadViewer.envMaterialMap(mode,env);material.needsUpdate=true;})
cds.cadViewer.environmentMapEnabled=true},toggleEnvMap:function(){if(cds.cadViewer.environmentMapEnabled){cds.cadViewer.reflectiveMaterials.forEach(function(material){material.envMap=null;material.needsUpdate=true;})}else{cds.cadViewer.reflectiveMaterials.forEach(function(material){material.envMap=cds.cadViewer.envMaterialMap(cds.cadViewer.environment.type,cds.cadViewer.environment.map);material.needsUpdate=true;})}
cds.cadViewer.environmentMapEnabled=!cds.cadViewer.environmentMapEnabled},getAllMaterials:function(material){cds.cadViewer.sceneObject.traverse(function(child){if(child instanceof THREE.Mesh){for(var i=0;i<child.material.length;i++){material(child.material[i]);}}});},envMaterialMap:function(mode,env){var envCube=cds.cadViewer.studioEnvironmentMaps[env];if(mode==="Refraction"){envCube.mapping=THREE.CubeRefractionMapping;}
envCube.format=THREE.RGBFormat;return envCube;},StudioUtils:function(){this.mixer=null;this.animationActionsByPart={};this.lastAnimationAction=null;this.play=false;this.pause=false;this.inifinityAnimationExist=false;this.infinityAnimationDelay={};this.materialsMapByName={};this.annotation=false;this.annotationFactory=[];this.viewpoints=[];this.currentViewPoint=null;this.highlightedPartName=undefined;this.highlightedAnnotation=null;this.applyAnimations=function(animations){var scope=this;var maxTime=0;this.mixer=new THREE.AnimationMixer();cds.cadViewer.traverse(cds.cadViewer.sceneObject,function(child){if(child.children.length>0){if(child.children[0].type==="Group"||child.children[0].type==="Mesh"){let cId=child.userData.compId;let newAnimations=animations.animations[cId]
if(newAnimations!=undefined){let time=0;for(var i=0;i<newAnimations.length;i++){var animation=newAnimations[i];let animationAction=scope.mixer.clipAction(THREE.AnimationClip.parse(animation.clip),child);animationAction.repetitions=animation.infinity===false?0:Infinity;animationAction.clampWhenFinished=true;if(!scope.animationActionsByPart[cId])scope.animationActionsByPart[cId]=[];scope.animationActionsByPart[cId].push(animationAction);time+=animation.clip.duration;if(maxTime<time&&animationAction.repetitions!==Infinity){maxTime=time;scope.lastAnimationAction=animationAction;}
if(animationAction.repetitions===Infinity)
scope.inifinityAnimationExist=true;if(animation.delay>0){scope.infinityAnimationDelay[animation.clip.name]=animation.delay;}}
child.userData.initialQuat=child.quaternion.clone();}}}},function(){cds.cadViewer.onAnimationLoad()});this.mixer.addEventListener('finished',this.onFinishAnimation);cds.cadViewer.sceneObject.userData.hasAnimation=true;}
this.playAnimation=function(){for(let cId in this.animationActionsByPart){this.animationActionsByPart[cId][0].play();if(this.infinityAnimationDelay[this.animationActionsByPart[cId][0]._clip.name]){this.animationActionsByPart[cId][0].startAt(this.mixer.time+this.infinityAnimationDelay[this.animationActionsByPart[cId][0]._clip.name]);}}
this.play=true;}
this.stopAnimation=function(){for(let cId in this.animationActionsByPart){this.animationActionsByPart[cId].forEach(function(animation){animation.stop();});}
for(let cId in this.animationClipsByPart){this.animationClipsByPart[cId].part.quaternion.copy(this.animationClipsByPart[cId].part.userData.initialQuat);}
this.play=false;}
this.togglePauseState=function(){for(let cId in this.animationActionsByPart){this.animationActionsByPart[cId].forEach(function(animation){animation.paused=!animation.paused;});}}
this.onFinishAnimation=function(event){var scope=cds.cadViewer.studioUtils;var names=event.action._clip.name.split(".");var animationAction=scope.animationActionsByPart[names[0]]
if(animationAction){if(animationAction[Number(names[1])+1]){let pAnimation=animationAction[Number(names[1])];animationAction[Number(names[1])+1].play();pAnimation.stop();let qtrack=pAnimation._clip.tracks[1];if(qtrack&&qtrack.name===".quaternion"){let len=qtrack.values.length;pAnimation._localRoot.quaternion.set(qtrack.values[len-4],qtrack.values[len-3],qtrack.values[len-2],qtrack.values[len-1]);}}}
if(event.action===scope.lastAnimationAction&&scope.inifinityAnimationExist===false){scope.play=false;}}
this.lightsObject;this.saveMaterial;this.applyStudioMaterialByObjectName=function(name){var sceneNode=cds.cadViewer.sceneObject.getObjectByName(name)
this.applyMaterial(sceneNode);}
this.applyMaterial=function(sceneNode){var materialStorage={};cds.cadViewer.traverse(sceneNode,function(child){if(child.type=='Mesh'){for(let i=0;i<child.material.length;i++){if(!materialStorage[child.material[i].uuid]){if(cds.cadViewer.studioMaterialContainer.materials[child.material[i].name]){let property=Object.assign({},cds.cadViewer.studioMaterialContainer.materials[child.material[i].name]);let sMap=property.map;let sBump=property.bumpMap;property.name=child.material[i].name;property.uuid=child.material[i].uuid;delete property.map;delete property.bumpMap;child.material[i]=new THREE.MeshPhysicalMaterial(property);if(property.reflectivity>0.0){cds.cadViewer.reflectiveMaterials.push(child.material[i]);}
if(sMap){var uuid=sMap;if(cds.cadViewer.studioMaterialContainer.textures[uuid]){let textureProperty=cds.cadViewer.studioMaterialContainer.textures[uuid];new THREE.TextureLoader().load(textureProperty.name,function(texture){child.material[i].map=texture;child.material[i].map.name=textureProperty.name;child.material[i].map.wrapS=THREE.RepeatWrapping;child.material[i].map.wrapT=THREE.RepeatWrapping;child.material[i].map.offset.fromArray(textureProperty.offset);child.material[i].map.repeat.fromArray(textureProperty.repeat);child.material[i].map.center.fromArray(textureProperty.center);child.material[i].map.rotation=textureProperty.rotation;child.material[i].needsUpdate=true;},undefined,function(event){alert("Failed to load texture from URL "+event.target.src);});}}
if(sBump){var uuid=sBump;if(cds.cadViewer.studioMaterialContainer.textures[uuid]){let bumpTextureProperty=cds.cadViewer.studioMaterialContainer.textures[uuid];new THREE.TextureLoader().load(bumpTextureProperty.name,function(texture){child.material[i].bumpMap=texture;child.material[i].bumpMap.name=bumpTextureProperty.name;child.material[i].bumpMap.wrapS=THREE.RepeatWrapping;child.material[i].bumpMap.wrapT=THREE.RepeatWrapping;child.material[i].bumpMap.offset.fromArray(bumpTextureProperty.offset);child.material[i].bumpMap.repeat.fromArray(bumpTextureProperty.repeat);child.material[i].bumpMap.center.fromArray(bumpTextureProperty.center);child.material[i].bumpMap.rotation=bumpTextureProperty.rotation;child.material[i].needsUpdate=true;},undefined,function(event){alert("Failed to load texture from URL "+event.target.src);});}}
materialStorage[child.material[i].uuid]=child.material[i];if(cds.cadViewer.studioUtils.materialsMapByName[child.material[i].name]!==undefined){cds.cadViewer.studioUtils.materialsMapByName[child.material[i].name].push(child.material[i])}else{cds.cadViewer.studioUtils.materialsMapByName[child.material[i].name]=[]
cds.cadViewer.studioUtils.materialsMapByName[child.material[i].name].push(child.material[i])}}else{child.material[i]=new THREE.MeshPhysicalMaterial({name:child.material[i].name,uuid:child.material[i].uuid,color:child.material[i].color,emissive:child.material[i].emissive,map:child.material[i].map,bumpMap:child.material[i].bumpMap,bumpScale:child.material[i].bumpScale,envMap:child.material[i].envMap,reflectivity:child.material[i].reflectivity,transparent:child.material[i].transparent,opacity:child.material[i].opacity,side:child.material[i].side});materialStorage[child.material[i].uuid]=child.material[i];}}else{child.material[i]=materialStorage[child.material[i].uuid];if(materialStorage[child.material[i].uuid].reflectivity>0.0){cds.cadViewer.reflectiveMaterials.push(child.material[i]);}}}}},function(){cds.cadViewer.postLoadMaterialCallback();})}
this.applyExplosions=function(jsonFile){cds.cadViewer.sceneObject.traverse(function(child){if(jsonFile.explosions.hasOwnProperty(child.userData.compId)){child.userData.ExplodedMatrix=jsonFile.explosions[child.userData.compId];}else if(child.type==="Object3D"){child.userData.ExplodedMatrix=undefined;}});cds.cadViewer.sceneObject.userData.hasExplosion=true;}
this.initEnvironmentMaps=function(onComplete){var dirPaths=["cloud","castle","bridge"]
for(var i=0;i<dirPaths.length;i++){var path='images/envMap/'+dirPaths[i]+'/';var format='.jpg';var urls=[path+'right'+format,path+'left'+format,path+'top'+format,path+'bottom'+format,path+'front'+format,path+'back'+format];cds.cadViewer.studioEnvironmentMaps[dirPaths[i]]=urls}
var loader=new THREE.CubeTextureLoader()
loader.load(cds.cadViewer.studioEnvironmentMaps[dirPaths[0]],function(texture1){cds.cadViewer.studioEnvironmentMaps[dirPaths[0]]=texture1
loader.load(cds.cadViewer.studioEnvironmentMaps[dirPaths[1]],function(texture2){cds.cadViewer.studioEnvironmentMaps[dirPaths[1]]=texture2
loader.load(cds.cadViewer.studioEnvironmentMaps[dirPaths[2]],function(texture3){cds.cadViewer.studioEnvironmentMaps[dirPaths[2]]=texture3
onComplete()},function(xhr){},function(){console.log("Failed to load environment maps, reflections won't work");onComplete();})},function(xhr){},function(){console.log("Failed to load environment maps, reflections won't work");onComplete();})},function(xhr){},function(){console.log("Failed to load environment maps, reflections won't work");onComplete();})}
this.applyStudioProperties=function(){var arr=cds.cadViewer.cadFilePath.split('.');arr.pop();arr.push("cdsm");var link=decodeURIComponent(arr.join('.'));this.readTextFile(link,function(text){var jsonFile=JSON.parse(text);cds.cadViewer.studioUtils.initEnvironmentMaps(function(){cds.cadViewer.studioMaterialContainer=jsonFile
cds.cadViewer.studioUtils.applyMaterial(cds.cadViewer.sceneObject);})});}
this.getMaterialsByName=function(name){if(this.materialsMapByName[name])
return this.materialsMapByName[name]
else
console.log("materials by name \""+name+"\" not found")}
this.applyAnnotations=function(jsonFile){if(jsonFile.hasOwnProperty("annotations")){var scope=this;for(let i=0;i<cds.cadViewer.sceneObject.children[0].children.length;i++){if(jsonFile.annotations.hasOwnProperty(cds.cadViewer.sceneObject.children[0].children[i].userData.compId)){scope.createAnnotation(cds.cadViewer.sceneObject.children[0].children[i],jsonFile.annotations[cds.cadViewer.sceneObject.children[0].children[i].userData.compId]);}}
cds.cadViewer.sceneObject.userData.hasAnnotation=true;this.showAnnotations(true);cds.cadViewer.renderer.domElement.addEventListener("mousemove",this.highlightAnnotationDiv,false);cds.cadViewer.postModelTreeLoadCallback();this.addCart()}
if(jsonFile.hasOwnProperty("cameraMatrix")&&jsonFile.cameraMatrix){this.setCamera(jsonFile.cameraMatrix);}
if(typeof jsonFile["cameraRotation"]==="boolean"){cds.cadViewer.controls.noRotate=!jsonFile.cameraRotation;}}
this.setCamera=function(cameraMatrix){cds.cadViewer.camera.position.set(cameraMatrix.elements[12],cameraMatrix.elements[13],cameraMatrix.elements[14]);cds.cadViewer.camera.up.set(cameraMatrix.elements[4],cameraMatrix.elements[5],cameraMatrix.elements[6]);}
this.addCart=function(){var cartButton=document.createElement("input");cartButton.type="button";cartButton.value="ADD TO CART";cartButton.style="position: absolute; right: 25px; top: 20px";document.body.appendChild(cartButton);}
this.createAnnotation=function(part,annotations){for(let i=0;i<annotations.length;i++){if(!part.userData.hasOwnProperty('annotationNo')){part.userData.annotationNo=1;}else{part.userData.annotationNo++;}
var annotation=document.createElement("div");annotation.id=part.userData.compId+"."+(part.userData.annotationNo-1);var hyperlink=annotations[i].url;var imgURL=annotations[i].imageUrl;var aText=annotations[i].text;if(hyperlink!==''){var anchor=document.createElement("a");anchor.href=hyperlink;anchor.target="_blank";anchor.style.color="rgb(255, 255, 255)";}
if(imgURL!==''){var imgDiv=document.createElement("div");var img=document.createElement("img");img.src=imgURL;img.style.width=annotations[i].imageWidth+"px";img.style.height=annotations[i].imageHeight+"px";imgDiv.appendChild(img);}
if(aText!==''){var span=document.createElement("span");span.style="-moz-user-select: none; -webkit-user-select: none; -ms-user-select:none; user-select:none;-o-user-select:none;"
span.innerText=aText;}
if(aText!==''&&imgURL===''&&hyperlink===''){annotation.appendChild(span);}else if(aText!==''&&imgURL===''&&hyperlink!==''){anchor.appendChild(span);annotation.appendChild(anchor);}else if(aText===''&&imgURL!==''&&hyperlink===''){annotation.appendChild(imgDiv);}else if(aText===''&&imgURL!==''&&hyperlink!==''){anchor.appendChild(imgDiv);annotation.appendChild(anchor);}else if(aText!==''&&imgURL!==''&&hyperlink===''){annotation.appendChild(imgDiv);annotation.appendChild(span);}else if(aText!==''&&imgURL!==''&&hyperlink!==''){anchor.appendChild(span);annotation.appendChild(imgDiv);annotation.appendChild(anchor);}
annotation.onmouseover=function(){if(cds.cadViewer.hasOwnProperty('materialProperties'))
cds.cadViewer.materialProperties.highlightPartUsingCompId(part.userData.compId);annotation.style.backgroundColor="rgb(0, 102, 255)"
var tr=document.getElementById(part.name)
if(tr){tr.style.background="#000"
tr.cells[0].style.color='white'
tr.cells[1].style.color='white'
tr.cells[2].style.color='white'}};annotation.ondblclick=function(){cds.cadViewer.setCameraZoomOn(part)}
annotation.onmouseout=function(){if(cds.cadViewer.hasOwnProperty('materialProperties'))
cds.cadViewer.materialProperties.removeHighlights();annotation.style.backgroundColor="rgb(255, 255, 255)";var tr=document.getElementById(part.name)
if(tr){tr.style.background="#fff"
tr.cells[0].style.color="#000"
tr.cells[1].style.color="#000"
tr.cells[2].style.color="#000"}};annotation.style="text-align: center; position: absolute; background-color: rgb(255, 255, 255); padding: 7px; border: 1px solid rgb(212, 212, 212); overflow: hidden;  border-radius: 20px; color: rgb(0, 0, 0); box-shadow: 0px 0px 5px 1px white; min-width: 10px; min-height: 10px; display: none";var cdscadviewercontainer=document.getElementsByClassName("cds-cad-viewer-container")[0];cdscadviewercontainer.appendChild(annotation);var material=new THREE.LineBasicMaterial({color:"#000000"});var geometry=new THREE.Geometry();var vertex0=new THREE.Vector3(annotations[i].lineVertices[0].x,annotations[i].lineVertices[0].y,annotations[i].lineVertices[0].z);var vertex1=new THREE.Vector3(annotations[i].lineVertices[1].x,annotations[i].lineVertices[1].y,annotations[i].lineVertices[1].z);geometry.vertices.push(vertex0);geometry.vertices.push(vertex1);var annotationLine=new THREE.Line(geometry,material);annotationLine.geometry.verticesNeedUpdate=true;annotationLine.visible=false;part.add(annotationLine);if(annotations[i].animationData.length>0){for(let j=0;j<annotations[i].animationData.length;j++){if(annotations[i].animationData[j].endTime===null){annotations[i].animationData[j].endTime=Infinity;}}}
this.annotationFactory.push({part:part,line:annotationLine,domElement:annotation,vertex:[vertex0,vertex1],explosionEnd:annotations[i].explosionEndOnly,animationTimeFrames:annotations[i].animationData});}}
this.getIntersectedPart=function(event,object){var mouseX=(event.clientX/window.innerWidth)*2-1;var mouseY=-(event.clientY/window.innerHeight)*2+1;var vector=new THREE.Vector3(mouseX,mouseY,1);var _this=this;vector.unproject(cds.cadViewer.camera);cds.cadViewer.raycaster.set(cds.cadViewer.camera.position,vector.sub(cds.cadViewer.camera.position).normalize());var intersectObj=cds.cadViewer.raycaster.intersectObjects(object,true);if(intersectObj.length>0){if(intersectObj[0].object instanceof THREE.Mesh){if(intersectObj[0].object.parent.type==="Group"){var part=intersectObj[0].object.parent.parent;}else{var part=intersectObj[0].object.parent;}
if(part.userData.childType==="Part"){return part}}}}
this.highlightAnnotationDiv=function(){var _this=cds.cadViewer.studioUtils
var intersectedPart=_this.getIntersectedPart(event,cds.cadViewer.sceneObject.children)
if(intersectedPart){var id=intersectedPart.userData.compId+"."+(intersectedPart.userData.annotationNo-1)
if(_this.highlightedPartName&&intersectedPart.name!==_this.highlightedPartName){if(_this.highlightedAnnotation)
_this.highlightedAnnotation.style.backgroundColor="rgb(255, 255, 255)";_this.highlightedAnnotation=null;if(cds.cadViewer.hasOwnProperty('materialProperties'))
cds.cadViewer.materialProperties.removeHighlights();_this.HighlightModetreeRow(_this.highlightedPartName,"#fff","#000");_this.highlightedPartName=undefined;}
if(!_this.highlightedPartName){var annotationDOMElement=document.getElementById(id)
if(annotationDOMElement){annotationDOMElement.style.backgroundColor="rgb(0, 102, 255)";_this.highlightedAnnotation=annotationDOMElement;_this.HighlightModetreeRow(intersectedPart.name,"#000","#fff");}
_this.highlightedPartName=intersectedPart.name;if(cds.cadViewer.hasOwnProperty('materialProperties'))
cds.cadViewer.materialProperties.highlightPartUsingCompId(intersectedPart.userData.compId);}}else{if(_this.highlightedPartName){if(_this.highlightedAnnotation)
_this.highlightedAnnotation.style.backgroundColor="rgb(255, 255, 255)";_this.highlightedAnnotation=null;_this.HighlightModetreeRow(_this.highlightedPartName,"#fff","#000");if(cds.cadViewer.hasOwnProperty('materialProperties'))
cds.cadViewer.materialProperties.removeHighlights();_this.highlightedPartName=undefined;}}}
this.HighlightModetreeRow=function(id,backgroundColor,color){var row=document.getElementById(id);if(row){row.style.background=backgroundColor;row.cells[0].style.color=color;row.cells[1].style.color=color;row.cells[2].style.color=color;row.cells[3].style.color=color;row.cells[3].style.color=color;}}
this.updateAnnotation=function(){for(var i=0;i<this.annotationFactory.length;i++){let vertex0=this.annotationFactory[i].vertex[0].clone();let vertex1=this.annotationFactory[i].vertex[1].clone();this.annotationFactory[i].part.localToWorld(vertex0);this.annotationFactory[i].part.localToWorld(vertex1);const vector=new THREE.Vector3(vertex1.x,vertex1.y,vertex1.z);const vector0=new THREE.Vector3(vertex0.x,vertex0.y,vertex0.z);const canvas=cds.cadViewer.renderer.domElement;vector0.project(cds.cadViewer.camera);vector.project(cds.cadViewer.camera);let rightSide=false;if(vector0.x<vector.x){rightSide=true;}
vector.x=Math.round((0.5+vector.x/2)*(canvas.width));vector.y=Math.round((0.5-vector.y/2)*(canvas.height));let annotation=this.annotationFactory[i].domElement;annotation.style.top=vector.y-14+'px';if(rightSide){annotation.style.right="";annotation.style.left=vector.x+'px';}else{annotation.style.left="";annotation.style.right="calc(100% - "+vector.x+"px)";}}}
this.toggleAnnotation=function(){this.showAnnotations(!this.annotation)}
this.showAnnotations=function(state){for(let i=0;i<this.annotationFactory.length;i++){this.annotationFactory[i].line.visible=state;this.annotationFactory[i].domElement.style.display=state===true?"block":"none";}
this.annotation=state}
this.getViewPointNames=function(){return cds.cadViewer.studioUtils.viewpoints.map(function(element,index,array){return element.name})},this.setCameraWithName=function(name){let _this=this
var viewPoint=cds.cadViewer.studioUtils.viewpoints.find(function(element,index,array){return element.name===name})
let cameraViewPoint=_this.getVectorMap(viewPoint)
let matrix=cameraViewPoint["matrix"].elements;_this.animateCameraPosition(cds.cadViewer.camera,{x:matrix[12],y:matrix[13],z:matrix[14]},function(){})
_this.animateCameraParam(cds.cadViewer.camera.up,{x:matrix[4],y:matrix[5],z:matrix[6]},function(){})
_this.animateCameraParam(cds.cadViewer.controls.target,{x:cameraViewPoint["target"].x,y:cameraViewPoint["target"].y,z:cameraViewPoint["target"].z},function(){})}
this.setCameraViewPoints=function(json){this.viewpoints=json["viewpoints"]}
this.getVectorMap=function(viewpoint){let cameraViewPoint=[]
let target=viewpoint["target"]
cameraViewPoint["target"]=new THREE.Vector3(target.x,target.y,target.z)
let matrixArray=viewpoint["matrix"].elements
cameraViewPoint["matrix"]=new THREE.Matrix4().fromArray(matrixArray)
return cameraViewPoint}
this.getViewPointsDiv=function(cameraViewPoint){var _this=this
var pointerDivCircle=document.createElement('div')
pointerDivCircle.classList.add('pointer-circle')
pointerDiv=document.createElement('div')
pointerDiv.classList.add('pointer-background')
pointerDiv.appendChild(pointerDivCircle)
pointerDiv.onmouseenter=function(){pointerDivCircle.classList.add('pointer-circle-hover')}
pointerDiv.onmouseleave=function(){pointerDivCircle.classList.remove('pointer-circle-hover')}
pointerDiv.onclick=function(){_this.animateCameraPosition(cds.cadViewer.camera,cameraViewPoint["position"],function(){cds.cadViewer.controls.target.copy(cameraViewPoint["target"])})}
document.body.appendChild(pointerDiv)
return pointerDiv}
this.updateAllViewPoints=function(){for(let index=0;index<this.viewpoints.length;index++){const element=this.viewpoints[index];this.updateViewPoint(element["position"],element["domElement"])}}
this.updateViewPoint=function(pointerPosition,pointerDiv){let camera=cds.cadViewer.camera
let renderer=cds.cadViewer.renderer
if(pointerPosition!=null&pointerDiv!=null){var position=pointerPosition.clone()
position.project(camera)
var canvas=renderer.domElement
position.x=Math.round((0.5+position.x/2)*(canvas.width));position.y=Math.round((0.5-position.y/2)*(canvas.height));pointerDiv.style.top=position.y+'px'
pointerDiv.style.left=position.x+'px'}}
this.animateCameraPosition=function(camera,to,onFinish){new TWEEN.Tween(camera.position).to({x:to.x,y:to.y,z:to.z},2000).easing(TWEEN.Easing.Linear.None).onComplete(function(){camera.updateProjectionMatrix();onFinish()}).start()}
this.animateParam=function(param,to,onFinish){new TWEEN.Tween(param).to({x:to.x,y:to.y,z:to.z},2000).easing(TWEEN.Easing.Linear.None).onComplete(function(){cds.cadViewer.camera.updateProjectionMatrix();onFinish()}).start()}
this.loadStudioAnimations=function(){var arr=cds.cadViewer.cadFilePath.split('.');arr.pop();arr.push("anim");var link=decodeURIComponent(arr.join('.'));this.readTextFile(link,function(response){var jsonFile=JSON.parse(response);cds.cadViewer.studioUtils.applyAnimations(jsonFile);});}
this.loadStudioExplosions=function(){var arr=cds.cadViewer.cadFilePath.split('.');arr.pop();arr.push("expl");var link=decodeURIComponent(arr.join('.'));this.readTextFile(link,function(response){var jsonFile=JSON.parse(response);cds.cadViewer.studioUtils.applyExplosions(jsonFile);});}
this.loadStudioAnnotations=function(){var arr=cds.cadViewer.cadFilePath.split('.');arr.pop();arr.push("anot");var link=decodeURIComponent(arr.join('.'));this.readTextFile(link,function(response){var jsonFile=JSON.parse(response);cds.cadViewer.studioUtils.applyAnnotations(jsonFile);});}
this.loadCameraViewPoints=function(){var arr=cds.cadViewer.cadFilePath.split('.');arr.pop();arr.push("cam");var link=decodeURIComponent(arr.join('.'));this.readTextFile(link,function(response){var jsonFile=JSON.parse(response);cds.cadViewer.studioUtils.setCameraViewPoints(jsonFile);});}
this.readTextFile=function(link,callback){var rawFile=new XMLHttpRequest();rawFile.open("GET",link,true);rawFile.onreadystatechange=function(){if(rawFile.readyState===4&&rawFile.status=="200"){callback(rawFile.responseText);}else if(rawFile.readyState===4&&rawFile.status!=="200"){console.log("File doesn't exist on link: "+link);}}
rawFile.send();}}};function MouseHoverUpdate(){var vector=new THREE.Vector3(cds.cadViewer.mouse.x,cds.cadViewer.mouse.y,0.5);}
function SetSpriteTextOnZoom(){var spritetext=[];var timestamp=new Date()*0.0001;cds.cadViewer.scene.traverse(function(text){if(text instanceof THREE.Sprite){text.children[0].geometry.computeBoundingBox();var scaleVector=new THREE.Vector3();var scaleFactor=4;var vec=new THREE.Vector3(text.children[0].geometry.boundingBox.centerX,text.children[0].geometry.boundingBox.centerY,text.children[0].geometry.boundingBox.centerZ);var scaleby=scaleVector.subVectors(vec,cds.cadViewer.camera.position).length()/scaleFactor;text.children[0].scale.set(scaleby,scaleby,1);}});}
var sprites=[];function ToggleDiamensionVisibility(){"use strict";cds.cadViewer.showDiamension=!cds.cadViewer.showDiamension;var dim;if(cds.cadViewer.showDiamension){GetDiamensions(sprites);sprites.forEach(function(text){text.visible=false;});}else{sprites.forEach(function(text){text.visible=true;});}}
function GetDiamensions(modeldiamension){if(cds.cadViewer.sceneObject instanceof THREE.Object3D){for(var i=0;i<cds.cadViewer.sceneObject.children.length;i++){if(cds.cadViewer.sceneObject.children[i]instanceof THREE.Object3D){var text1=cds.cadViewer.sceneObject.children[i];if(text1 instanceof THREE.Line&&text1.userData.drawType==="Dimension"){sprites.push(text1);}
if(text1.children!=0){if(text1.children[0].material instanceof THREE.SpriteMaterial){sprites.push(text1.children[0]);}}}}}}
function setupTween(lastPos,CurrentPos,isAngular){if(isAngular==undefined){var tween=new TWEEN.Tween(lastPos).to(CurrentPos,900);tween.easing(TWEEN.Easing.Cubic.In);tween.start();}else{var tween=new TWEEN.Tween(lastPos).to({x:CurrentPos.x/Math.PI,y:CurrentPos.y/Math.PI,z:CurrentPos.z/Math.PI,},600);tween.easing(TWEEN.Easing.Cubic.In);tween.start();}}
function rotate(){for(var i=0,l=cds.cadViewer.scene.children.length;i<l;i++){var object=cds.cadViewer.scene.children[i];object.rotation.y+=0.01;}}
var THREEx=THREEx||{};THREEx.FullScreen=THREEx.FullScreen||{};THREEx.FullScreen._hasWebkitFullScreen=false;THREEx.FullScreen._hasMozFullScreen=false;THREEx.FullScreen._hasMsFullScreen=false;THREEx.FullScreen.init=function(element){element=element||document.body;this._hasWebkitFullScreen=element.webkitRequestFullScreen?true:false;this._hasMozFullScreen=element.mozRequestFullScreen?true:false;this._hasMsFullScreen=element.msRequestFullscreen?true:false;}
THREEx.FullScreen.available=function(){return this._hasWebkitFullScreen||this._hasMozFullScreen||this._hasMsFullScreen;}
THREEx.FullScreen.activated=function(){if(this._hasWebkitFullScreen){return document.webkitIsFullScreen;}else if(this._hasMozFullScreen){return document.mozFullScreen;}else if(this._hasMsFullScreen){return document.msFullscreenElement!==undefined&&document.msFullscreenElement!==null;}else{console.assert(false);}}
THREEx.FullScreen.request=function(element){element=element||document.body;if(this._hasWebkitFullScreen){element.webkitRequestFullScreen(element.ALLOW_KEYBOARD_INPUT);}else if(this._hasMozFullScreen){element.mozRequestFullScreen();}else if(this._hasMsFullScreen){element.msRequestFullscreen();}else{console.assert(false);}}
THREEx.FullScreen.cancel=function(){if(this._hasWebkitFullScreen){document.webkitCancelFullScreen();}else if(this._hasMozFullScreen){document.mozCancelFullScreen();}else if(this._hasMsFullScreen){document.msExitFullscreen();}else{console.assert(false);}}
if(Date.now===undefined){Date.now=function(){return new Date().valueOf();};}
THREE.TrackballControls=function(object,domElement){var _this=this;var STATE={NONE:-1,ROTATE:0,ZOOM:1,PAN:2,TOUCH_ROTATE:3,TOUCH_ZOOM_PAN:4};this.object=object;this.domElement=(domElement!==undefined)?domElement:document;this.enabled=true;this.screen={left:0,top:0,width:0,height:0};this.rotateSpeed=1.0;this.zoomSpeed=1.2;this.panSpeed=0.3;this.noRotate=false;this.noZoom=false;this.noPan=false;this.staticMoving=false;this.dynamicDampingFactor=0.2;this.minDistance=0;this.maxDistance=Infinity;this.keys=[65,83,68];this.target=new THREE.Vector3();var EPS=0.000001;var lastPosition=new THREE.Vector3();var _state=STATE.NONE,_prevState=STATE.NONE,_eye=new THREE.Vector3(),_movePrev=new THREE.Vector2(),_moveCurr=new THREE.Vector2(),_lastAxis=new THREE.Vector3(),_lastAngle=0,_zoomStart=new THREE.Vector2(),_zoomEnd=new THREE.Vector2(),_touchZoomDistanceStart=0,_touchZoomDistanceEnd=0,_panStart=new THREE.Vector2(),_panEnd=new THREE.Vector2();this.target0=this.target.clone();this.position0=this.object.position.clone();this.up0=this.object.up.clone();var changeEvent={type:'change'};var startEvent={type:'start'};var endEvent={type:'end'};this.handleResize=function(){if(this.domElement===document){this.screen.left=0;this.screen.top=0;this.screen.width=window.innerWidth;this.screen.height=window.innerHeight;}else{var box=this.domElement.getBoundingClientRect();var d=this.domElement.ownerDocument.documentElement;this.screen.left=box.left+window.pageXOffset-d.clientLeft;this.screen.top=box.top+window.pageYOffset-d.clientTop;this.screen.width=box.width;this.screen.height=box.height;}};this.handleEvent=function(event){if(typeof this[event.type]=='function'){this[event.type](event);}};var getMouseOnScreen=(function(){var vector=new THREE.Vector2();return function getMouseOnScreen(pageX,pageY){vector.set((pageX-_this.screen.left)/_this.screen.width,(pageY-_this.screen.top)/_this.screen.height);return vector;};}());var getMouseOnCircle=(function(){var vector=new THREE.Vector2();return function getMouseOnCircle(pageX,pageY){vector.set(((pageX-_this.screen.width*0.5-_this.screen.left)/(_this.screen.width*0.5)),((_this.screen.height+2*(_this.screen.top-pageY))/_this.screen.width));return vector;};}());this.rotateCamera=(function(){var axis=new THREE.Vector3(),quaternion=new THREE.Quaternion(),eyeDirection=new THREE.Vector3(),objectUpDirection=new THREE.Vector3(),objectSidewaysDirection=new THREE.Vector3(),moveDirection=new THREE.Vector3(),angle;return function rotateCamera(){moveDirection.set(_moveCurr.x-_movePrev.x,_moveCurr.y-_movePrev.y,0);angle=moveDirection.length();if(angle){_eye.copy(_this.object.position).sub(_this.target);eyeDirection.copy(_eye).normalize();objectUpDirection.copy(_this.object.up).normalize();objectSidewaysDirection.crossVectors(objectUpDirection,eyeDirection).normalize();objectUpDirection.setLength(_moveCurr.y-_movePrev.y);objectSidewaysDirection.setLength(_moveCurr.x-_movePrev.x);moveDirection.copy(objectUpDirection.add(objectSidewaysDirection));axis.crossVectors(moveDirection,_eye).normalize();angle*=_this.rotateSpeed;quaternion.setFromAxisAngle(axis,angle);_eye.applyQuaternion(quaternion);_this.object.up.applyQuaternion(quaternion);_lastAxis.copy(axis);_lastAngle=angle;}else if(!_this.staticMoving&&_lastAngle){_lastAngle*=Math.sqrt(1.0-_this.dynamicDampingFactor);_eye.copy(_this.object.position).sub(_this.target);quaternion.setFromAxisAngle(_lastAxis,_lastAngle);_eye.applyQuaternion(quaternion);_this.object.up.applyQuaternion(quaternion);}
_movePrev.copy(_moveCurr);};}());this.zoomCamera=function(){var factor;if(_state===STATE.TOUCH_ZOOM_PAN){factor=_touchZoomDistanceStart/_touchZoomDistanceEnd;_touchZoomDistanceStart=_touchZoomDistanceEnd;_eye.multiplyScalar(factor);}else{factor=1.0+(_zoomEnd.y-_zoomStart.y)*_this.zoomSpeed;if(factor!==1.0&&factor>0.0){_eye.multiplyScalar(factor);}
if(_this.staticMoving){_zoomStart.copy(_zoomEnd);}else{_zoomStart.y+=(_zoomEnd.y-_zoomStart.y)*this.dynamicDampingFactor;}}};this.panCamera=(function(){var mouseChange=new THREE.Vector2(),objectUp=new THREE.Vector3(),pan=new THREE.Vector3();return function panCamera(){mouseChange.copy(_panEnd).sub(_panStart);if(mouseChange.lengthSq()){mouseChange.multiplyScalar(_eye.length()*_this.panSpeed);pan.copy(_eye).cross(_this.object.up).setLength(mouseChange.x);pan.add(objectUp.copy(_this.object.up).setLength(mouseChange.y));_this.object.position.add(pan);_this.target.add(pan);if(_this.staticMoving){_panStart.copy(_panEnd);}else{_panStart.add(mouseChange.subVectors(_panEnd,_panStart).multiplyScalar(_this.dynamicDampingFactor));}}};}());this.checkDistances=function(){if(!_this.noZoom||!_this.noPan){if(_eye.lengthSq()>_this.maxDistance*_this.maxDistance){_this.object.position.addVectors(_this.target,_eye.setLength(_this.maxDistance));_zoomStart.copy(_zoomEnd);}
if(_eye.lengthSq()<_this.minDistance*_this.minDistance){_this.object.position.addVectors(_this.target,_eye.setLength(_this.minDistance));_zoomStart.copy(_zoomEnd);}}};this.update=function(){_eye.subVectors(_this.object.position,_this.target);if(!_this.noRotate){_this.rotateCamera();}
if(!_this.noZoom){_this.zoomCamera();}
if(!_this.noPan){_this.panCamera();}
_this.object.position.addVectors(_this.target,_eye);_this.checkDistances();_this.object.lookAt(_this.target);if(lastPosition.distanceToSquared(_this.object.position)>EPS){_this.dispatchEvent(changeEvent);lastPosition.copy(_this.object.position);}};this.reset=function(){_state=STATE.NONE;_prevState=STATE.NONE;_this.target.copy(_this.target0);_this.object.position.copy(_this.position0);_this.object.up.copy(_this.up0);_eye.subVectors(_this.object.position,_this.target);_this.object.lookAt(_this.target);_this.dispatchEvent(changeEvent);lastPosition.copy(_this.object.position);};function keydown(event){if(_this.enabled===false)return;window.removeEventListener('keydown',keydown);_prevState=_state;if(_state!==STATE.NONE){return;}else if(event.keyCode===_this.keys[STATE.ROTATE]&&!_this.noRotate){_state=STATE.ROTATE;}else if(event.keyCode===_this.keys[STATE.ZOOM]&&!_this.noZoom){_state=STATE.ZOOM;}else if(event.keyCode===_this.keys[STATE.PAN]&&!_this.noPan){_state=STATE.PAN;}}
function keyup(event){if(_this.enabled===false)return;_state=_prevState;window.addEventListener('keydown',keydown,false);}
function mousedown(event){if(_this.enabled===false)return;event.preventDefault();event.stopPropagation();if(_state===STATE.NONE){_state=event.button;}
if(_state===STATE.ROTATE&&!_this.noRotate){_moveCurr.copy(getMouseOnCircle(event.pageX,event.pageY));_movePrev.copy(_moveCurr);}else if(_state===STATE.ZOOM&&!_this.noZoom){_zoomStart.copy(getMouseOnScreen(event.pageX,event.pageY));_zoomEnd.copy(_zoomStart);}else if(_state===STATE.PAN&&!_this.noPan){_panStart.copy(getMouseOnScreen(event.pageX,event.pageY));_panEnd.copy(_panStart);}
document.addEventListener('mousemove',mousemove,false);document.addEventListener('mouseup',mouseup,false);_this.dispatchEvent(startEvent);}
function mousemove(event){if(_this.enabled===false)return;event.preventDefault();event.stopPropagation();if(_state===STATE.ROTATE&&!_this.noRotate){_movePrev.copy(_moveCurr);_moveCurr.copy(getMouseOnCircle(event.pageX,event.pageY));}else if(_state===STATE.ZOOM&&!_this.noZoom){_zoomEnd.copy(getMouseOnScreen(event.pageX,event.pageY));}else if(_state===STATE.PAN&&!_this.noPan){_panEnd.copy(getMouseOnScreen(event.pageX,event.pageY));}}
function mouseup(event){if(_this.enabled===false)return;event.preventDefault();event.stopPropagation();_state=STATE.NONE;document.removeEventListener('mousemove',mousemove);document.removeEventListener('mouseup',mouseup);_this.dispatchEvent(endEvent);}
function mousewheel(event){if(_this.enabled===false)return;if(_this.noZoom===true)return;event.preventDefault();event.stopPropagation();switch(event.deltaMode){case 2:_zoomStart.y-=event.deltaY*0.025;break;case 1:_zoomStart.y-=event.deltaY*0.01;break;default:_zoomStart.y-=event.deltaY*0.00025;break;}
_this.dispatchEvent(startEvent);_this.dispatchEvent(endEvent);}
function touchstart(event){if(_this.enabled===false)return;switch(event.touches.length){case 1:_state=STATE.TOUCH_ROTATE;_moveCurr.copy(getMouseOnCircle(event.touches[0].pageX,event.touches[0].pageY));_movePrev.copy(_moveCurr);break;default:_state=STATE.TOUCH_ZOOM_PAN;var dx=event.touches[0].pageX-event.touches[1].pageX;var dy=event.touches[0].pageY-event.touches[1].pageY;_touchZoomDistanceEnd=_touchZoomDistanceStart=Math.sqrt(dx*dx+dy*dy);var x=(event.touches[0].pageX+event.touches[1].pageX)/2;var y=(event.touches[0].pageY+event.touches[1].pageY)/2;_panStart.copy(getMouseOnScreen(x,y));_panEnd.copy(_panStart);break;}
_this.dispatchEvent(startEvent);}
function touchmove(event){if(_this.enabled===false)return;event.preventDefault();event.stopPropagation();switch(event.touches.length){case 1:_movePrev.copy(_moveCurr);_moveCurr.copy(getMouseOnCircle(event.touches[0].pageX,event.touches[0].pageY));break;default:var dx=event.touches[0].pageX-event.touches[1].pageX;var dy=event.touches[0].pageY-event.touches[1].pageY;_touchZoomDistanceEnd=Math.sqrt(dx*dx+dy*dy);var x=(event.touches[0].pageX+event.touches[1].pageX)/2;var y=(event.touches[0].pageY+event.touches[1].pageY)/2;_panEnd.copy(getMouseOnScreen(x,y));break;}}
function touchend(event){if(_this.enabled===false)return;switch(event.touches.length){case 0:_state=STATE.NONE;break;case 1:_state=STATE.TOUCH_ROTATE;_moveCurr.copy(getMouseOnCircle(event.touches[0].pageX,event.touches[0].pageY));_movePrev.copy(_moveCurr);break;}
_this.dispatchEvent(endEvent);}
function contextmenu(event){if(_this.enabled===false)return;event.preventDefault();}
this.dispose=function(){this.domElement.removeEventListener('contextmenu',contextmenu,false);this.domElement.removeEventListener('mousedown',mousedown,false);this.domElement.removeEventListener('wheel',mousewheel,false);this.domElement.removeEventListener('touchstart',touchstart,false);this.domElement.removeEventListener('touchend',touchend,false);this.domElement.removeEventListener('touchmove',touchmove,false);document.removeEventListener('mousemove',mousemove,false);document.removeEventListener('mouseup',mouseup,false);window.removeEventListener('keydown',keydown,false);window.removeEventListener('keyup',keyup,false);};this.domElement.addEventListener('contextmenu',contextmenu,false);this.domElement.addEventListener('mousedown',mousedown,false);this.domElement.addEventListener('wheel',mousewheel,false);this.domElement.addEventListener('touchstart',touchstart,false);this.domElement.addEventListener('touchend',touchend,false);this.domElement.addEventListener('touchmove',touchmove,false);window.addEventListener('keydown',keydown,false);window.addEventListener('keyup',keyup,false);this.handleResize();this.update();};THREE.TrackballControls.prototype=Object.create(THREE.EventDispatcher.prototype);THREE.TrackballControls.prototype.constructor=THREE.TrackballControls;THREE.RenderPass=function(scene,camera,overrideMaterial,clearColor,clearAlpha){this.scene=scene;this.camera=camera;this.overrideMaterial=overrideMaterial;this.clearColor=clearColor;this.clearAlpha=(clearAlpha!==undefined)?clearAlpha:1;this.oldClearColor=new THREE.Color();this.oldClearAlpha=1;this.enabled=true;this.clear=true;this.needsSwap=false;};THREE.RenderPass.prototype={render:function(renderer,writeBuffer,readBuffer,delta){this.scene.overrideMaterial=this.overrideMaterial;if(this.clearColor){this.oldClearColor.copy(renderer.getClearColor());this.oldClearAlpha=renderer.getClearAlpha();renderer.setClearColor(this.clearColor,this.clearAlpha);}
renderer.render(this.scene,this.camera,readBuffer,this.clear);if(this.clearColor){renderer.setClearColor(this.oldClearColor,this.oldClearAlpha);}
this.scene.overrideMaterial=null;}};THREE.ShaderPass=function(shader,textureID){this.textureID=(textureID!==undefined)?textureID:"tDiffuse";this.uniforms=THREE.UniformsUtils.clone(shader.uniforms);this.material=new THREE.ShaderMaterial({uniforms:this.uniforms,vertexShader:shader.vertexShader,fragmentShader:shader.fragmentShader});this.renderToScreen=false;this.enabled=true;this.needsSwap=true;this.clear=false;this.camera=new THREE.OrthographicCamera(-1,1,1,-1,0,1);this.scene=new THREE.Scene();this.quad=new THREE.Mesh(new THREE.PlaneGeometry(2,2),null);this.scene.add(this.quad);};THREE.ShaderPass.prototype={render:function(renderer,writeBuffer,readBuffer,delta){if(this.uniforms[this.textureID]){this.uniforms[this.textureID].value=readBuffer;}
this.quad.material=this.material;if(this.renderToScreen){renderer.render(this.scene,this.camera);}else{renderer.render(this.scene,this.camera,writeBuffer,this.clear);}}};THREE.MaskPass=function(scene,camera){this.scene=scene;this.camera=camera;this.enabled=true;this.clear=true;this.needsSwap=false;this.inverse=false;};THREE.MaskPass.prototype={render:function(renderer,writeBuffer,readBuffer,delta){var context=renderer.context;context.colorMask(false,false,false,false);context.depthMask(false);var writeValue,clearValue;if(this.inverse){writeValue=0;clearValue=1;}else{writeValue=1;clearValue=0;}
context.enable(context.STENCIL_TEST);context.stencilOp(context.REPLACE,context.REPLACE,context.REPLACE);context.stencilFunc(context.ALWAYS,writeValue,0xffffffff);context.clearStencil(clearValue);renderer.render(this.scene,this.camera,readBuffer,this.clear);renderer.render(this.scene,this.camera,writeBuffer,this.clear);context.colorMask(true,true,true,true);context.depthMask(true);context.stencilFunc(context.EQUAL,1,0xffffffff);context.stencilOp(context.KEEP,context.KEEP,context.KEEP);}};THREE.ClearMaskPass=function(){this.enabled=true;};THREE.ClearMaskPass.prototype={render:function(renderer,writeBuffer,readBuffer,delta){var context=renderer.context;context.disable(context.STENCIL_TEST);}};THREE.EffectComposer=function(renderer,renderTarget){this.renderer=renderer;if(renderTarget===undefined){var width=window.innerWidth||1;var height=window.innerHeight||1;var parameters={minFilter:THREE.LinearFilter,magFilter:THREE.LinearFilter,format:THREE.RGBFormat,stencilBuffer:false};renderTarget=new THREE.WebGLRenderTarget(width,height,parameters);}
this.renderTarget1=renderTarget;this.renderTarget2=renderTarget.clone();this.writeBuffer=this.renderTarget1;this.readBuffer=this.renderTarget2;this.passes=[];if(THREE.CopyShader===undefined)
console.error("THREE.EffectComposer relies on THREE.CopyShader");this.copyPass=new THREE.ShaderPass(THREE.CopyShader);};THREE.EffectComposer.prototype={swapBuffers:function(){var tmp=this.readBuffer;this.readBuffer=this.writeBuffer;this.writeBuffer=tmp;},addPass:function(pass){this.passes.push(pass);},insertPass:function(pass,index){this.passes.splice(index,0,pass);},render:function(delta){this.writeBuffer=this.renderTarget1;this.readBuffer=this.renderTarget2;var maskActive=false;var pass,i,il=this.passes.length;for(i=0;i<il;i++){pass=this.passes[i];if(!pass.enabled)continue;pass.render(this.renderer,this.writeBuffer,this.readBuffer,delta,maskActive);if(pass.needsSwap){if(maskActive){var context=this.renderer.context;context.stencilFunc(context.NOTEQUAL,1,0xffffffff);this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,delta);context.stencilFunc(context.EQUAL,1,0xffffffff);}
this.swapBuffers();}
if(pass instanceof THREE.MaskPass){maskActive=true;}else if(pass instanceof THREE.ClearMaskPass){maskActive=false;}}},reset:function(renderTarget){if(renderTarget===undefined){renderTarget=this.renderTarget1.clone();renderTarget.width=window.innerWidth;renderTarget.height=window.innerHeight;}
this.renderTarget1=renderTarget;this.renderTarget2=renderTarget.clone();this.writeBuffer=this.renderTarget1;this.readBuffer=this.renderTarget2;},setSize:function(width,height){var renderTarget=this.renderTarget1.clone();renderTarget.width=width;renderTarget.height=height;this.reset(renderTarget);}};THREE.CopyShader={uniforms:{"tDiffuse":{type:"t",value:null},"opacity":{type:"f",value:1.0}},vertexShader:["varying vec2 vUv;","void main() {","vUv = uv;","gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );","}"].join("\n"),fragmentShader:["uniform float opacity;","uniform sampler2D tDiffuse;","varying vec2 vUv;","void main() {","vec4 texel = texture2D( tDiffuse, vUv );","gl_FragColor = opacity * texel;","}"].join("\n")};THREE.EdgeShader={uniforms:{"tDiffuse":{type:"t",value:null},"aspect":{type:"v2",value:new THREE.Vector2(512,512)},},vertexShader:["varying vec2 vUv;","void main() {","vUv = uv;","gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );","}"].join("\n"),fragmentShader:["uniform sampler2D tDiffuse;","varying vec2 vUv;","uniform vec2 aspect;","vec2 texel = vec2(1.0 / aspect.x, 1.0 / aspect.y);","mat3 G[2];","const mat3 g0 = mat3( 1.0, 2.0, 1.0, 0.0, 0.0, 0.0, -1.0, -2.0, -1.0 );","const mat3 g1 = mat3( 1.0, 0.0, -1.0, 2.0, 0.0, -2.0, 1.0, 0.0, -1.0 );","void main(void)","{","mat3 I;","float cnv[2];","G[0] = g0;","G[1] = g1;","I[0][0] = length(texture2D(tDiffuse, vUv + texel * vec2(-1.0,-1.0) ).rgb);","I[0][1] = length(texture2D(tDiffuse, vUv + texel * vec2(-1.0,0.0) ).rgb);","I[0][2] = length(texture2D(tDiffuse, vUv + texel * vec2(-1.0,1.0) ).rgb);","I[1][0] = length(texture2D(tDiffuse, vUv + texel * vec2(0.0,-1.0) ).rgb);","I[1][1] = length(texture2D(tDiffuse, vUv + texel * vec2(0.0,0.0) ).rgb);","I[1][2] = length(texture2D(tDiffuse, vUv + texel * vec2(0.0,1.0) ).rgb);","I[2][0] = length(texture2D(tDiffuse, vUv + texel * vec2(1.0,-1.0) ).rgb);","I[2][1] = length(texture2D(tDiffuse, vUv + texel * vec2(1.0,0.0) ).rgb);","I[2][2] = length(texture2D(tDiffuse, vUv + texel * vec2(1.0,1.0) ).rgb);","for (int i=0; i<2; i++) {","float dp3 = dot(G[i][0], I[0]) + dot(G[i][1], I[1]) + dot(G[i][2], I[2]);","cnv[i] = dp3 * dp3; ","}","float val = sqrt(cnv[0]*cnv[0]+cnv[1]*cnv[1]);","if (val < 0.1)","{","vec3 sample = texture2D(tDiffuse, vUv + vec2(0.0,0.0)).rgb;","if (sample.r > 0.1 && sample.g < 1.0)","{","gl_FragColor = vec4(0.24, 0.24, 0.24, 1.0);","}","else","{","discard;","}","}","else","{","gl_FragColor = vec4(0.24, 0.24, 0.24, 1.0);","}","} ",].join("\n")};THREE.RenderableObject=function(){this.id=0;this.object=null;this.z=0;this.renderOrder=0;};THREE.RenderableFace=function(){this.id=0;this.v1=new THREE.RenderableVertex();this.v2=new THREE.RenderableVertex();this.v3=new THREE.RenderableVertex();this.normalModel=new THREE.Vector3();this.vertexNormalsModel=[new THREE.Vector3(),new THREE.Vector3(),new THREE.Vector3()];this.vertexNormalsLength=0;this.color=new THREE.Color();this.material=null;this.uvs=[new THREE.Vector2(),new THREE.Vector2(),new THREE.Vector2()];this.z=0;this.renderOrder=0;};THREE.RenderableVertex=function(){this.position=new THREE.Vector3();this.positionWorld=new THREE.Vector3();this.positionScreen=new THREE.Vector4();this.visible=true;};THREE.RenderableVertex.prototype.copy=function(vertex){this.positionWorld.copy(vertex.positionWorld);this.positionScreen.copy(vertex.positionScreen);};THREE.RenderableLine=function(){this.id=0;this.v1=new THREE.RenderableVertex();this.v2=new THREE.RenderableVertex();this.vertexColors=[new THREE.Color(),new THREE.Color()];this.material=null;this.z=0;this.renderOrder=0;};THREE.RenderableSprite=function(){this.id=0;this.object=null;this.x=0;this.y=0;this.z=0;this.rotation=0;this.scale=new THREE.Vector2();this.material=null;this.renderOrder=0;};THREE.Projector=function(){var _object,_objectCount,_objectPool=[],_objectPoolLength=0,_vertex,_vertexCount,_vertexPool=[],_vertexPoolLength=0,_face,_faceCount,_facePool=[],_facePoolLength=0,_line,_lineCount,_linePool=[],_linePoolLength=0,_sprite,_spriteCount,_spritePool=[],_spritePoolLength=0,_renderData={objects:[],lights:[],elements:[]},_vector3=new THREE.Vector3(),_vector4=new THREE.Vector4(),_clipBox=new THREE.Box3(new THREE.Vector3(-1,-1,-1),new THREE.Vector3(1,1,1)),_boundingBox=new THREE.Box3(),_points3=new Array(3),_points4=new Array(4),_viewMatrix=new THREE.Matrix4(),_viewProjectionMatrix=new THREE.Matrix4(),_modelMatrix,_modelViewProjectionMatrix=new THREE.Matrix4(),_normalMatrix=new THREE.Matrix3(),_frustum=new THREE.Frustum(),_clippedVertex1PositionScreen=new THREE.Vector4(),_clippedVertex2PositionScreen=new THREE.Vector4();this.projectVector=function(vector,camera){console.warn('THREE.Projector: .projectVector() is now vector.project().');vector.project(camera);};this.unprojectVector=function(vector,camera){console.warn('THREE.Projector: .unprojectVector() is now vector.unproject().');vector.unproject(camera);};this.pickingRay=function(vector,camera){console.error('THREE.Projector: .pickingRay() is now raycaster.setFromCamera().');};var RenderList=function(){var normals=[];var uvs=[];var object=null;var material=null;var normalMatrix=new THREE.Matrix3();function setObject(value){object=value;material=object.material;normalMatrix.getNormalMatrix(object.matrixWorld);normals.length=0;uvs.length=0;}
function projectVertex(vertex){var position=vertex.position;var positionWorld=vertex.positionWorld;var positionScreen=vertex.positionScreen;positionWorld.copy(position).applyMatrix4(_modelMatrix);positionScreen.copy(positionWorld).applyMatrix4(_viewProjectionMatrix);var invW=1/positionScreen.w;positionScreen.x*=invW;positionScreen.y*=invW;positionScreen.z*=invW;vertex.visible=positionScreen.x>=-1&&positionScreen.x<=1&&positionScreen.y>=-1&&positionScreen.y<=1&&positionScreen.z>=-1&&positionScreen.z<=1;}
function pushVertex(x,y,z){_vertex=getNextVertexInPool();_vertex.position.set(x,y,z);projectVertex(_vertex);}
function pushNormal(x,y,z){normals.push(x,y,z);}
function pushUv(x,y){uvs.push(x,y);}
function checkTriangleVisibility(v1,v2,v3){if(v1.visible===true||v2.visible===true||v3.visible===true)return true;_points3[0]=v1.positionScreen;_points3[1]=v2.positionScreen;_points3[2]=v3.positionScreen;return _clipBox.intersectsBox(_boundingBox.setFromPoints(_points3));}
function checkBackfaceCulling(v1,v2,v3){return((v3.positionScreen.x-v1.positionScreen.x)*(v2.positionScreen.y-v1.positionScreen.y)-
(v3.positionScreen.y-v1.positionScreen.y)*(v2.positionScreen.x-v1.positionScreen.x))<0;}
function pushLine(a,b){var v1=_vertexPool[a];var v2=_vertexPool[b];_line=getNextLineInPool();_line.id=object.id;_line.v1.copy(v1);_line.v2.copy(v2);_line.z=(v1.positionScreen.z+v2.positionScreen.z)/2;_line.renderOrder=object.renderOrder;_line.material=object.material;_renderData.elements.push(_line);}
function pushTriangle(a,b,c){var v1=_vertexPool[a];var v2=_vertexPool[b];var v3=_vertexPool[c];if(checkTriangleVisibility(v1,v2,v3)===false)return;if(material.side===THREE.DoubleSide||checkBackfaceCulling(v1,v2,v3)===true){_face=getNextFaceInPool();_face.id=object.id;_face.v1.copy(v1);_face.v2.copy(v2);_face.v3.copy(v3);_face.z=(v1.positionScreen.z+v2.positionScreen.z+v3.positionScreen.z)/3;_face.renderOrder=object.renderOrder;_face.normalModel.fromArray(normals,a*3);_face.normalModel.applyMatrix3(normalMatrix).normalize();for(var i=0;i<3;i++){var normal=_face.vertexNormalsModel[i];normal.fromArray(normals,arguments[i]*3);normal.applyMatrix3(normalMatrix).normalize();var uv=_face.uvs[i];uv.fromArray(uvs,arguments[i]*2);}
_face.vertexNormalsLength=3;_face.material=object.material;_renderData.elements.push(_face);}}
return{setObject:setObject,projectVertex:projectVertex,checkTriangleVisibility:checkTriangleVisibility,checkBackfaceCulling:checkBackfaceCulling,pushVertex:pushVertex,pushNormal:pushNormal,pushUv:pushUv,pushLine:pushLine,pushTriangle:pushTriangle}};var renderList=new RenderList();this.projectScene=function(scene,camera,sortObjects,sortElements){_faceCount=0;_lineCount=0;_spriteCount=0;_renderData.elements.length=0;if(scene.autoUpdate===true)scene.updateMatrixWorld();if(camera.parent===null)camera.updateMatrixWorld();_viewMatrix.copy(camera.matrixWorldInverse.getInverse(camera.matrixWorld));_viewProjectionMatrix.multiplyMatrices(camera.projectionMatrix,_viewMatrix);_frustum.setFromMatrix(_viewProjectionMatrix);_objectCount=0;_renderData.objects.length=0;_renderData.lights.length=0;function addObject(object){_object=getNextObjectInPool();_object.id=object.id;_object.object=object;_vector3.setFromMatrixPosition(object.matrixWorld);_vector3.applyProjection(_viewProjectionMatrix);_object.z=_vector3.z;_object.renderOrder=object.renderOrder;_renderData.objects.push(_object);}
scene.traverseVisible(function(object){if(object instanceof THREE.Light){_renderData.lights.push(object);}else if(object instanceof THREE.Mesh||object instanceof THREE.Line){if(object.material.visible===false)return;if(object.frustumCulled===true&&_frustum.intersectsObject(object)===false)return;addObject(object);}else if(object instanceof THREE.Sprite){if(object.material.visible===false)return;if(object.frustumCulled===true&&_frustum.intersectsSprite(object)===false)return;addObject(object);}});if(sortObjects===true){_renderData.objects.sort(painterSort);}
for(var o=0,ol=_renderData.objects.length;o<ol;o++){var object=_renderData.objects[o].object;var geometry=object.geometry;renderList.setObject(object);_modelMatrix=object.matrixWorld;_vertexCount=0;if(object instanceof THREE.Mesh){if(geometry instanceof THREE.BufferGeometry){var attributes=geometry.attributes;var groups=geometry.groups;if(attributes.position===undefined)continue;var positions=attributes.position.array;for(var i=0,l=positions.length;i<l;i+=3){renderList.pushVertex(positions[i],positions[i+1],positions[i+2]);}
if(attributes.normal!==undefined){var normals=attributes.normal.array;for(var i=0,l=normals.length;i<l;i+=3){renderList.pushNormal(normals[i],normals[i+1],normals[i+2]);}}
if(attributes.uv!==undefined){var uvs=attributes.uv.array;for(var i=0,l=uvs.length;i<l;i+=2){renderList.pushUv(uvs[i],uvs[i+1]);}}
if(geometry.index!==null){var indices=geometry.index.array;if(groups.length>0){for(var o=0;o<groups.length;o++){var group=groups[o];for(var i=group.start,l=group.start+group.count;i<l;i+=3){renderList.pushTriangle(indices[i],indices[i+1],indices[i+2]);}}}else{for(var i=0,l=indices.length;i<l;i+=3){renderList.pushTriangle(indices[i],indices[i+1],indices[i+2]);}}}else{for(var i=0,l=positions.length/3;i<l;i+=3){renderList.pushTriangle(i,i+1,i+2);}}}else if(geometry instanceof THREE.Geometry){var vertices=geometry.vertices;var faces=geometry.faces;var faceVertexUvs=geometry.faceVertexUvs[0];_normalMatrix.getNormalMatrix(_modelMatrix);var material=object.material;var isFaceMaterial=material instanceof THREE.MultiMaterial;var objectMaterials=isFaceMaterial===true?object.material:null;for(var v=0,vl=vertices.length;v<vl;v++){var vertex=vertices[v];_vector3.copy(vertex);if(material.morphTargets===true){var morphTargets=geometry.morphTargets;var morphInfluences=object.morphTargetInfluences;for(var t=0,tl=morphTargets.length;t<tl;t++){var influence=morphInfluences[t];if(influence===0)continue;var target=morphTargets[t];var targetVertex=target.vertices[v];_vector3.x+=(targetVertex.x-vertex.x)*influence;_vector3.y+=(targetVertex.y-vertex.y)*influence;_vector3.z+=(targetVertex.z-vertex.z)*influence;}}
renderList.pushVertex(_vector3.x,_vector3.y,_vector3.z);}
for(var f=0,fl=faces.length;f<fl;f++){var face=faces[f];material=isFaceMaterial===true?objectMaterials.materials[face.materialIndex]:object.material;if(material===undefined)continue;var side=material.side;var v1=_vertexPool[face.a];var v2=_vertexPool[face.b];var v3=_vertexPool[face.c];if(renderList.checkTriangleVisibility(v1,v2,v3)===false)continue;var visible=renderList.checkBackfaceCulling(v1,v2,v3);if(side!==THREE.DoubleSide){if(side===THREE.FrontSide&&visible===false)continue;if(side===THREE.BackSide&&visible===true)continue;}
_face=getNextFaceInPool();_face.id=object.id;_face.v1.copy(v1);_face.v2.copy(v2);_face.v3.copy(v3);_face.normalModel.copy(face.normal);if(visible===false&&(side===THREE.BackSide||side===THREE.DoubleSide)){_face.normalModel.negate();}
_face.normalModel.applyMatrix3(_normalMatrix).normalize();var faceVertexNormals=face.vertexNormals;for(var n=0,nl=Math.min(faceVertexNormals.length,3);n<nl;n++){var normalModel=_face.vertexNormalsModel[n];normalModel.copy(faceVertexNormals[n]);if(visible===false&&(side===THREE.BackSide||side===THREE.DoubleSide)){normalModel.negate();}
normalModel.applyMatrix3(_normalMatrix).normalize();}
_face.vertexNormalsLength=faceVertexNormals.length;var vertexUvs=faceVertexUvs[f];if(vertexUvs!==undefined){for(var u=0;u<3;u++){_face.uvs[u].copy(vertexUvs[u]);}}
_face.color=face.color;_face.material=material;_face.z=(v1.positionScreen.z+v2.positionScreen.z+v3.positionScreen.z)/3;_face.renderOrder=object.renderOrder;_renderData.elements.push(_face);}}}else if(object instanceof THREE.Line){if(geometry instanceof THREE.BufferGeometry){var attributes=geometry.attributes;if(attributes.position!==undefined){var positions=attributes.position.array;for(var i=0,l=positions.length;i<l;i+=3){renderList.pushVertex(positions[i],positions[i+1],positions[i+2]);}
if(geometry.index!==null){var indices=geometry.index.array;for(var i=0,l=indices.length;i<l;i+=2){renderList.pushLine(indices[i],indices[i+1]);}}else{var step=object instanceof THREE.LineSegments?2:1;for(var i=0,l=(positions.length/3)-1;i<l;i+=step){renderList.pushLine(i,i+1);}}}}else if(geometry instanceof THREE.Geometry){_modelViewProjectionMatrix.multiplyMatrices(_viewProjectionMatrix,_modelMatrix);var vertices=object.geometry.vertices;if(vertices.length===0)continue;v1=getNextVertexInPool();v1.positionScreen.copy(vertices[0]).applyMatrix4(_modelViewProjectionMatrix);var step=object instanceof THREE.LineSegments?2:1;for(var v=1,vl=vertices.length;v<vl;v++){v1=getNextVertexInPool();v1.positionScreen.copy(vertices[v]).applyMatrix4(_modelViewProjectionMatrix);if((v+1)%step>0)continue;v2=_vertexPool[_vertexCount-2];_clippedVertex1PositionScreen.copy(v1.positionScreen);_clippedVertex2PositionScreen.copy(v2.positionScreen);if(clipLine(_clippedVertex1PositionScreen,_clippedVertex2PositionScreen)===true){_clippedVertex1PositionScreen.multiplyScalar(1/_clippedVertex1PositionScreen.w);_clippedVertex2PositionScreen.multiplyScalar(1/_clippedVertex2PositionScreen.w);_line=getNextLineInPool();_line.id=object.id;_line.v1.positionScreen.copy(_clippedVertex1PositionScreen);_line.v2.positionScreen.copy(_clippedVertex2PositionScreen);_line.z=Math.max(_clippedVertex1PositionScreen.z,_clippedVertex2PositionScreen.z);_line.renderOrder=object.renderOrder;_line.material=object.material;if(object.material.vertexColors===THREE.VertexColors){_line.vertexColors[0].copy(object.geometry.colors[v]);_line.vertexColors[1].copy(object.geometry.colors[v-1]);}
_renderData.elements.push(_line);}}}}else if(object instanceof THREE.Sprite){_vector4.set(_modelMatrix.elements[12],_modelMatrix.elements[13],_modelMatrix.elements[14],1);_vector4.applyMatrix4(_viewProjectionMatrix);var invW=1/_vector4.w;_vector4.z*=invW;if(_vector4.z>=-1&&_vector4.z<=1){_sprite=getNextSpriteInPool();_sprite.id=object.id;_sprite.x=_vector4.x*invW;_sprite.y=_vector4.y*invW;_sprite.z=_vector4.z;_sprite.renderOrder=object.renderOrder;_sprite.object=object;_sprite.rotation=object.rotation;_sprite.scale.x=object.scale.x*Math.abs(_sprite.x-(_vector4.x+camera.projectionMatrix.elements[0])/(_vector4.w+camera.projectionMatrix.elements[12]));_sprite.scale.y=object.scale.y*Math.abs(_sprite.y-(_vector4.y+camera.projectionMatrix.elements[5])/(_vector4.w+camera.projectionMatrix.elements[13]));_sprite.material=object.material;_renderData.elements.push(_sprite);}}}
if(sortElements===true){_renderData.elements.sort(painterSort);}
return _renderData;};function getNextObjectInPool(){if(_objectCount===_objectPoolLength){var object=new THREE.RenderableObject();_objectPool.push(object);_objectPoolLength++;_objectCount++;return object;}
return _objectPool[_objectCount++];}
function getNextVertexInPool(){if(_vertexCount===_vertexPoolLength){var vertex=new THREE.RenderableVertex();_vertexPool.push(vertex);_vertexPoolLength++;_vertexCount++;return vertex;}
return _vertexPool[_vertexCount++];}
function getNextFaceInPool(){if(_faceCount===_facePoolLength){var face=new THREE.RenderableFace();_facePool.push(face);_facePoolLength++;_faceCount++;return face;}
return _facePool[_faceCount++];}
function getNextLineInPool(){if(_lineCount===_linePoolLength){var line=new THREE.RenderableLine();_linePool.push(line);_linePoolLength++;_lineCount++;return line;}
return _linePool[_lineCount++];}
function getNextSpriteInPool(){if(_spriteCount===_spritePoolLength){var sprite=new THREE.RenderableSprite();_spritePool.push(sprite);_spritePoolLength++;_spriteCount++;return sprite;}
return _spritePool[_spriteCount++];}
function painterSort(a,b){if(a.renderOrder!==b.renderOrder){return a.renderOrder-b.renderOrder;}else if(a.z!==b.z){return b.z-a.z;}else if(a.id!==b.id){return a.id-b.id;}else{return 0;}}
function clipLine(s1,s2){var alpha1=0,alpha2=1,bc1near=s1.z+s1.w,bc2near=s2.z+s2.w,bc1far=-s1.z+s1.w,bc2far=-s2.z+s2.w;if(bc1near>=0&&bc2near>=0&&bc1far>=0&&bc2far>=0){return true;}else if((bc1near<0&&bc2near<0)||(bc1far<0&&bc2far<0)){return false;}else{if(bc1near<0){alpha1=Math.max(alpha1,bc1near/(bc1near-bc2near));}else if(bc2near<0){alpha2=Math.min(alpha2,bc1near/(bc1near-bc2near));}
if(bc1far<0){alpha1=Math.max(alpha1,bc1far/(bc1far-bc2far));}else if(bc2far<0){alpha2=Math.min(alpha2,bc1far/(bc1far-bc2far));}
if(alpha2<alpha1){return false;}else{s1.lerp(s2,alpha1);s2.lerp(s1,1-alpha2);return true;}}}};