Guest User

Raycaster

a guest
Nov 14th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. My WebGL App
  3. */
  4.  
  5. // Global variables
  6. let mainContainer = null;
  7. let fpsContainer
  8. let stats = null;
  9. let camera = null;
  10. let renderer = null;
  11. let scene = null;
  12. let camControls = null;
  13. // Global Meshes
  14. let plane = null;
  15. let box, bucket, vase, ellipse = null;
  16.  
  17. let gui, ctrl = null;
  18.  
  19. var gele = new THREE.Group();
  20.  
  21. // 3d models
  22. const table = new THREE.Group();
  23. const santa = new THREE.Group();
  24. const gifts = new THREE.Group();
  25. const gifts2 = new THREE.Group();
  26. const tree = new THREE.Group();
  27.  
  28. const raycaster = new THREE.Raycaster();
  29. const mouse = new THREE.Vector2();
  30. let intersects;
  31.  
  32. function init(){
  33.     if ( THREE.WEBGL.isWebGLAvailable() === false ) container.appendChild( WEBGL.getWebGLErrorMessage() );
  34.     fpsContainer = document.querySelector( '#fps' );
  35.     mainContainer = document.querySelector( '#webgl-secne' );
  36.     scene = new THREE.Scene();
  37.  
  38.     //fonas su paveiksliuku
  39.  
  40.     let loader = new THREE.CubeTextureLoader();
  41.     loader.setPath( 'img/fonas/' );
  42.     const background = loader.load( [
  43.         'frozenft.png', 'frozenbk.png',
  44.         'frozenup.png', 'frozendn.png',
  45.         'frozenrt.png', 'frozenlf.png'
  46.     ]);
  47.     background.format = THREE.RGBFormat;
  48.     scene.background = background;
  49.  
  50.     createStats();
  51.     createCamera();
  52.     createControls();
  53.     createMeshes();
  54.     createLights();
  55.     createRenderer();
  56.     renderer.setAnimationLoop( () => {
  57.     update();
  58.     render();
  59.   } );
  60. }
  61.  
  62. // Animations
  63. function update(){
  64. // scene.traverse(function(e) {
  65. //         if (e instanceof THREE.Group && e != plane ) {
  66. //             e.rotation.x += ctrl.rotationSpeed;
  67. //             e.rotation.y += ctrl.rotationSpeed;
  68. //             e.rotation.z += ctrl.rotationSpeed;
  69. //         }
  70. //     });
  71.  
  72. box10 = scene.getObjectByName("box-10");
  73. if (box10 != null){
  74.     box10.rotation.x += ctrl.rotationSpeed;
  75.     box10.rotation.y += ctrl.rotationSpeed;
  76.     box10.rotation.z += ctrl.rotationSpeed;
  77. }
  78. }
  79.  
  80. // Statically rendered content
  81. function render(){
  82.     stats.begin();
  83.     renderer.render( scene, camera );
  84.     stats.end();
  85. }
  86.  
  87. // FPS counter
  88. function createStats(){
  89.     stats = new Stats();
  90.     stats.showPanel( 0 );   // 0: fps, 1: ms, 2: mb, 3+: custom
  91.     fpsContainer.appendChild( stats.dom );
  92. }
  93.  
  94. // Camera object
  95. function createCamera(){
  96.     const fov = 45;
  97.     const aspect =  mainContainer.clientWidth / mainContainer.clientHeight;
  98.     const near = 0.1;
  99.     const far = 500;    // meters
  100.     camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  101.    
  102.     // camera = new THREE.OrthographicCamera(
  103.     //  window.innerWidth / -32,
  104.     //  window.innerWidth / 32,
  105.     //  window.innerHeight / 32,
  106.     //  window.innerHeight / -32, -500, 500 );
  107.    
  108.     camera.position.x = 10;
  109.     camera.position.y = 20;
  110.     camera.position.z = 50;
  111.     camera.lookAt(scene.position);
  112. }
  113.  
  114. // Interactive controls
  115. function createControls(){
  116.     camControls = new THREE.OrbitControls(camera, mainContainer);
  117.     camControls.autoRotate = false;
  118. }
  119.  
  120. // Light objects
  121. function createLights(){
  122.     const spotLight = new THREE.SpotLight( 0xffffff );
  123.     spotLight.position.set( -10, 18, 10 );
  124.     spotLight.shadow.mapSize.width = 2048; // default 512
  125.     spotLight.shadow.mapSize.height = 2048; //default 512
  126.     spotLight.intensity = 1.5;
  127.     spotLight.distance = 200;
  128.     spotLight.angle = Math.PI/3;
  129.     spotLight.penumbra = 0.4; // 0 - 1
  130.     spotLight.decay = 0.2;
  131.     spotLight.castShadow = true;
  132.     scene.add( spotLight );
  133.  
  134.     const ambientLight = new THREE.AmbientLight( 0xffffff, 0.2 ); // 0x111111 - 0xaaaaaa, 1 ; 0xffffff, 0.1 - 0.3;
  135.     scene.add( ambientLight );
  136. }
  137.  
  138. function createPlane(){
  139.  
  140.     const planeGeometry = new THREE.PlaneBufferGeometry(30,30);
  141.  
  142.     // medzio tekstura
  143.     const texture = new THREE.TextureLoader().load( "img/wood.jpg" );
  144.     texture.encoding = THREE.sRGBEncoding;
  145.     texture.anisotropy = 16;
  146.  
  147.     texture.wrapS = THREE.RepeatWrapping;
  148.     texture.wrapT = THREE.RepeatWrapping;
  149.     texture.repeat.set(5,5);
  150.  
  151.     // filtrai
  152.     texture.magFilter = THREE.LinearFilter;
  153.     texture.minFilter = THREE.LinearMipMapLinearFilter;
  154.    
  155.     const planeMaterial =  new THREE.MeshStandardMaterial({ map: texture});
  156.    
  157.     plane = new THREE.Mesh(planeGeometry,planeMaterial);
  158.     plane.rotation.x = -0.5*Math.PI;
  159.     plane.position.x = 0;
  160.     plane.position.y = 0;
  161.     plane.position.z = 0;
  162.     plane.receiveShadow = true;
  163.     scene.add(plane);
  164. }
  165.  
  166. function createCustomBox(length, width, height) {
  167.     l = length/2;
  168.     w = width/2;
  169.     h = height/2;
  170.     const vertices = [
  171.         new THREE.Vector3( l,  h,  w),
  172.         new THREE.Vector3( l,  h, -w),
  173.         new THREE.Vector3( l, -h,  w),
  174.         new THREE.Vector3( l, -h, -w),
  175.         new THREE.Vector3(-l,  h, -w),
  176.         new THREE.Vector3(-l,  h,  w),
  177.         new THREE.Vector3(-l, -h, -w),
  178.         new THREE.Vector3(-l, -h,  w)
  179.     ];
  180.     const faces = [
  181.         new THREE.Face3(0,2,1),
  182.         new THREE.Face3(2,3,1),
  183.         new THREE.Face3(4,6,5),
  184.         new THREE.Face3(6,7,5),
  185.         new THREE.Face3(4,5,1),
  186.         new THREE.Face3(5,0,1),
  187.         new THREE.Face3(7,6,2),
  188.         new THREE.Face3(6,3,2),
  189.         new THREE.Face3(5,7,0),
  190.         new THREE.Face3(7,2,0),
  191.         new THREE.Face3(1,3,4),
  192.         new THREE.Face3(3,6,4)
  193.     ];
  194.  
  195.     let geom = new THREE.Geometry();
  196.     geom.vertices = vertices;
  197.     geom.faces = faces;
  198.  
  199.     const materials = [
  200.         new THREE.MeshLambertMaterial( { opacity:0.6, color: Math.random() * 0xffffff, transparent:true} ),
  201.         new THREE.MeshBasicMaterial( { color: 0x000000, wireframe: true } )
  202.     ];
  203.  
  204.     let mesh = THREE.SceneUtils.createMultiMaterialObject(geom,materials);
  205.  
  206.     mesh.children.forEach(function(e) {
  207.         e.castShadow=true;
  208.     });
  209.    
  210.     return mesh;
  211. }
  212.  
  213. // geles kotas
  214. function createStem(width){
  215.     let points = [];
  216.  
  217.     for ( let i = 0; i < 20; i ++ ) {
  218.         points.push( new THREE.Vector2( width,  i ) );
  219.     }
  220.    
  221.     const latheGeom = new THREE.LatheGeometry( points );
  222.  
  223.     const materials = [
  224.         new THREE.MeshLambertMaterial( {color: 0x013220, transparent:false, side:THREE.DoubleSide } )
  225.     ];
  226.  
  227.     const mesh = THREE.SceneUtils.createMultiMaterialObject(latheGeom,materials);
  228.  
  229.     mesh.children.forEach(function(e) {
  230.         e.castShadow=true;
  231.         e.geometry.computeFaceNormals(); //skaiciuoja normales vektorius geram apsvietimui
  232.         });
  233.        
  234.     return mesh;
  235. }
  236.  
  237.  
  238. // geles ziedas
  239. function createBlossom(rotatePrec, heightPrec){
  240.     const pts = [
  241.         new THREE.Vector2( 6, 0),
  242.         new THREE.Vector2( 3, 1),
  243.         new THREE.Vector2( 4, 2),
  244.         new THREE.Vector2( 5, 3),
  245.         new THREE.Vector2( 6, 4),
  246.         new THREE.Vector2( 5, 5),
  247.         new THREE.Vector2( 0, 8)
  248.         ];
  249.    
  250.     const spline = new THREE.SplineCurve(pts);
  251.     let splineGeometry = new THREE.Geometry();
  252.  
  253.     splineGeometry.vertices = spline.getPoints(heightPrec);
  254.    
  255.     const latheGeom = new THREE.LatheGeometry(splineGeometry.vertices, rotatePrec);
  256.  
  257.     const materials = [
  258.         //vidine puse
  259.         new THREE.MeshLambertMaterial( { opacity:0.6, color: 0xef4e4e, transparent:false, side:THREE.DoubleSide} ),
  260.         //isore
  261.         new THREE.MeshLambertMaterial( { opacity:0.6, color: 0xf50404, transparent:false} ),
  262.     ];
  263.    
  264.     let mesh = THREE.SceneUtils.createMultiMaterialObject(latheGeom,materials);
  265.    
  266.     mesh.children.forEach(function(e) {
  267.         e.castShadow=true;
  268.         e.geometry.computeFaceNormals();
  269.         });
  270.  
  271.     return mesh;
  272. }
  273.  
  274. // geles lapelis
  275. function createLeaf(){
  276.     var path = new THREE.Shape();
  277.     path.absellipse(0,0,4,8,0, Math.PI*2, false,0);
  278.     var geometry = new THREE.ShapeBufferGeometry( path );
  279.     var material = new THREE.MeshBasicMaterial( { color: 0x197440} );
  280.     ellipse = new THREE.Mesh( geometry, material );
  281.     ellipse.material.side = THREE.DoubleSide;
  282.     return ellipse;
  283. }
  284.  
  285. // geles vazonas
  286. function createVase(rotatePrec, heightPrec){
  287.  
  288.     const pts = [
  289.         new THREE.Vector2( 2, 0),
  290.         new THREE.Vector2( 3, 1),
  291.         new THREE.Vector2( 4, 2),
  292.         new THREE.Vector2( 3, 3),
  293.         new THREE.Vector2( 4, 4),
  294.         new THREE.Vector2( 1.5, 5),
  295.         new THREE.Vector2( 2, 6)
  296.         ];
  297.    
  298.     const spline = new THREE.SplineCurve(pts);
  299.     let splineGeometry = new THREE.Geometry();
  300.  
  301.     splineGeometry.vertices = spline.getPoints(heightPrec);
  302.    
  303.     const latheGeom = new THREE.LatheGeometry(splineGeometry.vertices, rotatePrec);
  304.  
  305.     const texture = new THREE.TextureLoader().load( "img/marble.jpg" );
  306.     texture.encoding = THREE.sRGBEncoding;
  307.     texture.anisotropy = 16;
  308.  
  309.     const materials = [
  310.         // vidus
  311.         new THREE.MeshLambertMaterial( { opacity:0.6, color: 0x0c7078, transparent:false, side:THREE.DoubleSide} ),
  312.         // isore
  313.         new THREE.MeshStandardMaterial({ map: texture}),
  314.     ];
  315.    
  316.     let mesh = THREE.SceneUtils.createMultiMaterialObject(latheGeom,materials);
  317.    
  318.     mesh.children.forEach(function(e) {
  319.         e.castShadow=true;
  320.         e.geometry.computeFaceNormals();
  321.         });
  322.  
  323.     return mesh;
  324. }
  325.  
  326. function createTable() {
  327.     const mtlLoader = new THREE.MTLLoader();
  328.     mtlLoader.load( 'models/table_and_chairs2.mtl', function( materials ) {
  329.         materials.preload();
  330.         const objloader = new THREE.OBJLoader();
  331.         objloader.setMaterials( materials );
  332.          objloader.load( 'models/table_and_chairs2.obj', function( object ){
  333.             object.traverse( function ( child ){
  334.                 if ( child instanceof THREE.Mesh ){
  335.                     child.castShadow = true;
  336.                     child.receiveShadow = true;
  337.                 }
  338.             });
  339.             object.scale.set(6, 6, 6);
  340.             object.castShadow = true;
  341.            
  342.             table.add(object);
  343.         });
  344.     });
  345.    
  346.     table.name = "table";
  347.     scene.add(table);
  348. }
  349.  
  350. function createTree() {
  351.     const mtlLoader = new THREE.MTLLoader();
  352.     mtlLoader.load( 'models/12150_Christmas_Tree_V2_L2.mtl', function( materials ) {
  353.         materials.preload();
  354.         const objloader = new THREE.OBJLoader();
  355.         objloader.setMaterials( materials );
  356.          objloader.load( 'models/12150_Christmas_Tree_V2_L2.obj', function( object ){
  357.             object.traverse( function ( child ){
  358.                 if ( child instanceof THREE.Mesh ){
  359.                     child.castShadow = true;
  360.                     child.receiveShadow = true;
  361.                 }
  362.             });
  363.             object.scale.set(0.07, 0.07, 0.07);
  364.             object.castShadow = true;
  365.            
  366.             tree.add(object);
  367.         });
  368.     });
  369.     scene.add(tree);
  370. }
  371.  
  372. function createGifts() {
  373.     const mtlLoader = new THREE.MTLLoader();
  374.     mtlLoader.load( 'models/13495_Stack_of_Gifts_v2_L2.mtl', function( materials ) {
  375.         materials.preload();
  376.         const objloader = new THREE.OBJLoader();
  377.         objloader.setMaterials( materials );
  378.          objloader.load( 'models/13495_Stack_of_Gifts_v2_L2.obj', function( object ){
  379.             object.traverse( function ( child ){
  380.                 if ( child instanceof THREE.Mesh ){
  381.                     child.castShadow = true;
  382.                     child.receiveShadow = true;
  383.                 }
  384.             });
  385.             object.scale.set(0.07, 0.07, 0.07);
  386.             object.castShadow = true;
  387.            
  388.             gifts.add(object);
  389.         });
  390.     });
  391.     scene.add(gifts);
  392. }
  393.  
  394. function createGifts2() {
  395.     const mtlLoader = new THREE.MTLLoader();
  396.     mtlLoader.load( 'models/13495_Stack_of_Gifts_v2_L2.mtl', function( materials ) {
  397.         materials.preload();
  398.         const objloader = new THREE.OBJLoader();
  399.         objloader.setMaterials( materials );
  400.          objloader.load( 'models/13495_Stack_of_Gifts_v2_L2.obj', function( object ){
  401.             object.traverse( function ( child ){
  402.                 if ( child instanceof THREE.Mesh ){
  403.                     child.castShadow = true;
  404.                     child.receiveShadow = true;
  405.                 }
  406.             });
  407.             object.scale.set(0.07, 0.07, 0.07);
  408.             object.castShadow = true;
  409.            
  410.             gifts2.add(object);
  411.         });
  412.     });
  413.     scene.add(gifts2);
  414. }
  415.  
  416. function createSanta() {
  417.     const mtlLoader = new THREE.MTLLoader();
  418.     mtlLoader.load( 'models/12165_Santa_Claus_v1_l2.mtl', function( materials ) {
  419.         materials.preload();
  420.         const objloader = new THREE.OBJLoader();
  421.         objloader.setMaterials( materials );
  422.          objloader.load( 'models/12165_Santa_Claus_v1_l2.obj', function( object ){
  423.             object.traverse( function ( child ){
  424.                 if ( child instanceof THREE.Mesh ){
  425.                     child.castShadow = true;
  426.                     child.receiveShadow = true;
  427.                 }
  428.             });
  429.             object.scale.set(0.07, 0.07, 0.07);
  430.             object.castShadow = true;
  431.            
  432.             santa.add(object);
  433.         });
  434.     });
  435.     scene.add(santa);
  436. }
  437.  
  438. function getRandomInt(min, max) {
  439.     return Math.floor(Math.random() * (max - min + 1) + min);
  440. }
  441.  
  442. class ObjectGenerator{
  443.     numOfObjects = scene.children.length;
  444.     rotationSpeed = 0.02;
  445.  
  446.     constructor(){}
  447.  
  448.     showObjectsInfo(){
  449.         this.numOfObjects = scene.children.length;
  450.         console.log(scene.children);
  451.     }
  452.  
  453.     cloneFlower(){
  454.         let flowerClone= gele.clone();
  455.         flowerClone.position.set(getRandomInt(-2,2),4.5,getRandomInt(-3,3));
  456.         scene.add(flowerClone);
  457.     }
  458.  
  459.     removeLastObject() {
  460.         const allChildren = scene.children;
  461.         const lastObject = allChildren[allChildren.length-1];
  462.         if (lastObject instanceof THREE.Group) {
  463.             scene.remove(lastObject);
  464.         }
  465.         this.numOfObjects = scene.children.length;
  466.     }
  467. }
  468.  
  469. // Meshes and other visible objects
  470. function createMeshes(){
  471.  
  472.     createPlane(plane);
  473.  
  474.     // geles kotas
  475.     var stem = createStem(0.5);
  476.    
  477.     stem.scale.set(0.3,0.3,0.3);
  478.     gele.add(stem);
  479.    
  480.     // geles ziedas
  481.     blossom = createBlossom(5, 10);
  482.     blossom.rotation.x = Math.PI;
  483.     blossom.scale.set(0.2,0.2,0.2);
  484.     blossom.position.y = 7;
  485.     gele.add(blossom);
  486.  
  487.     // geles vazonas
  488.     vase = createVase(10, 10);
  489.     vase.rotation.x = Math.PI;
  490.     vase.scale.set(0.5,0.5,0.5);
  491.     vase.rotation.z = Math.PI ;
  492.     gele.add(vase);
  493.  
  494.     // geles lapas
  495.     leaf = createLeaf();
  496.     leaf.scale.set(0.1,0.1,0.1);
  497.     leaf.position.y = 4;
  498.     leaf.position.x = 0.5;
  499.     leaf.rotation.z = Math.PI/4;
  500.     leaf.rotation.y = Math.PI;
  501.     gele.add(leaf);
  502.  
  503.    
  504.     gele.scale.set(0.4,0.4,0.4);
  505.     gele.position.y = 4.5;
  506.     gele.position.z = -1;
  507.  
  508.     gele.name = "flower";
  509.     scene.add(gele);
  510.  
  511.     createTable();
  512.  
  513.     createTree();
  514.     tree.rotation.y = Math.PI;
  515.     tree.rotation.x = Math.PI/2;
  516.     tree.position.set(10,0,10);
  517.  
  518.     createGifts(gifts);
  519.     gifts.rotation.y = Math.PI;
  520.     gifts.rotation.x = Math.PI/2;
  521.     gifts.scale.set(0.5,0.5,0.5);
  522.     gifts.position.set(12,0,2);
  523.  
  524.     createGifts2(gifts2);
  525.     gifts2.rotation.y = Math.PI;
  526.     gifts2.rotation.x = Math.PI/2;
  527.     gifts2.scale.set(0.5,0.5,0.5);
  528.     gifts2.position.set(5,0,10);
  529.  
  530.     createSanta();
  531.     santa.rotation.y = Math.PI;
  532.     santa.rotation.x = Math.PI/2;
  533.     santa.scale.set(0.8,0.8,0.8);
  534.     santa.position.set(-8,0,5);
  535.     santa.rotation.z = - (Math.PI / 4);
  536.    
  537.     // let smallBucket= gele.clone();
  538.     // smallBucket.translateZ(10.0);
  539.     // smallBucket.scale.set(0.5,0.5,0.5);
  540.     // scene.add(smallBucket);
  541.  
  542.     gui = new dat.GUI();
  543.     ctrl = new ObjectGenerator({ autoplace: false, width: 500 });
  544.     gui.add(ctrl, 'numOfObjects').name("Number of objects").listen();
  545.     gui.add(ctrl, 'showObjectsInfo').name("Show info");
  546.     gui.add(ctrl, 'cloneFlower').name("Clone flower");
  547.     gui.add(ctrl, 'removeLastObject').name("Remove flower");
  548. }
  549.  
  550. // Renderer object and features
  551. function createRenderer(){
  552.     renderer = new THREE.WebGLRenderer( { antialias: true } );
  553.     renderer.setSize(mainContainer.clientWidth, mainContainer.clientHeight);
  554.     renderer.setPixelRatio( window.devicePixelRatio );
  555.     renderer.shadowMap.enabled = true;
  556.     renderer.shadowMap.type = THREE.PCFSoftShadowMap; //THREE.BasicShadowMap | THREE.PCFShadowMap | THREE.PCFSoftShadowMap
  557.     // set the gamma correction so that output colors look correct on our screens
  558.   renderer.gammaFactor = 2.2;
  559.   renderer.gammaOutput = true;
  560.     mainContainer.appendChild( renderer.domElement );
  561. }
  562.  
  563. function onWindowResize() {
  564.   camera.aspect = window.innerWidth / window.innerHeight;
  565.   camera.updateProjectionMatrix();
  566.   renderer.setSize( window.innerWidth, window.innerHeight );
  567. }
  568.  
  569. function onMouseMove( event ) {
  570.     mouse.x = 2 * ( event.clientX / window.innerWidth ) - 1;
  571.     mouse.y = 1 - 2 * ( event.clientY / window.innerHeight );
  572. }
  573.  
  574. function onMouseDown( event ) {
  575.     raycaster.setFromCamera( mouse, camera );
  576.     intersects = raycaster.intersectObjects( scene.children, true );
  577.     for ( var i = 0; i < intersects.length; i++ ) {
  578.         if(intersects[ i ].object != plane){
  579.         //intersects[ i ].object.material.color.set( Math.random() * 0xffffff );
  580.         }
  581.         if(intersects[ i ].object.parent.name == "flower"){
  582.             window.location.href ='https://www.google.com/';
  583.             console.log("Paspausta");
  584.         }
  585.     }
  586. }
  587.  
  588. //mouse clicko listneriai
  589. window.addEventListener( 'mousemove', onMouseMove, false );
  590. window.addEventListener( 'mousedown', onMouseDown, false );
  591. //---------
  592.  
  593. window.addEventListener( 'resize', onWindowResize, false );
  594. init();
Add Comment
Please, Sign In to add comment