three.js 03-03 之 SpotLight 光源
生活随笔
收集整理的這篇文章主要介紹了
three.js 03-03 之 SpotLight 光源
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
? ? 這一篇我們來簡單介紹一下 SpotLight 光源。如果你已經(jīng)看過我前幾篇關(guān)于燈光方面的介紹,相信你對燈光應(yīng)該有了一定的認(rèn)識了。在 three.js 中,SpotLight(聚光燈光源)大概會(huì)是最常用的一種光源,尤其是當(dāng)想要生成陰影時(shí)。SpotLight 光源有一種雛形效果,類似我們生活中的手電筒或者燈籠。下面我先來看看聚光燈不同于點(diǎn)光源的幾個(gè)額外屬性,如下表所示:
| castShadow (投影) | 如果此屬性為 true,這個(gè)光源就會(huì)生成陰影;否則就不會(huì)生成陰影 |
| shadow.camera.near (投影相機(jī)近面) | 此屬性表明,從距離光源的哪一個(gè)地方開始可以生成陰影 |
| shadow.camera.far (投影相機(jī)遠(yuǎn)面) | 此屬性表明,到距離光源的哪一個(gè)地方為止可以生成陰影 |
| shadow.camera.fov (投影相機(jī)視野) | 此屬性表明,用于生成陰影的視野有多大 |
| target (目標(biāo)) | 此屬性決定光源照射的方向 |
| shadow.bias (陰影偏移) | 用來偏置陰影的位置。當(dāng)決定一個(gè)表面是否在陰影里時(shí),在標(biāo)準(zhǔn)深度上增加或減去多少。更多概念可參考?Shadow Map?相關(guān)知識 |
| angel (角度) | 此屬性表明光源射出的光柱有多寬。單位是弧度,默認(rèn)值 Math.PI/3。 |
| shadow.camera.visible (投影相機(jī)可見性) | 此屬性如果設(shè)置為 true,你就可以看到光源在哪里以及如何生成陰影。 |
| shadow.mapSize.width (陰影映射寬度) | 此屬性決定在陰影寬度方向上用多少像素來生成陰影。這個(gè)數(shù)必須是 2的冪。默認(rèn)為 512。此值越大越平滑。 |
| shadow.mapSize.height (陰影映射高度) | 此屬性決定在陰影高度方向上用多少像素來生成陰影。這個(gè)數(shù)必須是 2的冪。默認(rèn)為 512。此值越大越平滑。 |
下面我們先給出一個(gè)完整的示例代碼:
<!DOCTYPE html> <html> <head><title>示例 03.03 - 聚光燈光源</title><script src="../build/three.js"></script><script src="../build/js/controls/OrbitControls.js"></script><script src="../build/js/libs/stats.min.js"></script><script src="../build/js/libs/dat.gui.min.js"></script><script src="../jquery/jquery-3.2.1.min.js"></script><style>body {/* 設(shè)置 margin 為 0,并且 overflow 為 hidden,來完成頁面樣式 */margin: 0;overflow: hidden;}/* 統(tǒng)計(jì)對象的樣式 */#Stats-output {position: absolute;left: 0px;top: 0px;}</style> </head> <body><!-- 用于 WebGL 輸出的 Div --> <div id="WebGL-output"></div> <!-- 用于統(tǒng)計(jì) FPS 輸出的 Div --> <div id="Stats-output"></div><!-- 運(yùn)行 Three.js 示例的 Javascript 代碼 --> <script type="text/javascript">var scene;var camera;var render;var controls;var stats;var guiControls;var cube;var sphere;var spotLight;var lightHelper;var shadowCameraHelper;$(function() {stats = initStats();scene = new THREE.Scene();camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000); // 2147483647camera.position.set(-30, 40, 30);render = new THREE.WebGLRenderer( {antialias: true} ); // antialias 抗鋸齒render.setSize(window.innerWidth, window.innerHeight);render.setClearColor(0xEEEEEE);render.shadowMap.enabled = true; // 允許陰影投射$('#WebGL-output')[0].appendChild(render.domElement);window.addEventListener('resize', onWindowResize, false);var target = new THREE.Vector3(scene.position.x, scene.position.y ,scene.position.z);controls = new THREE.OrbitControls(camera, render.domElement);controls.target = target;camera.lookAt(target);scene.add(new THREE.AxesHelper(20));// 加入坐標(biāo)軸// 加入一個(gè)平面(帶線框效果)var planeGeometry = new THREE.PlaneGeometry(60, 20, 1, 1);var planeMaterials = [new THREE.MeshLambertMaterial( {color: 0xFFFFFF} ),new THREE.MeshBasicMaterial( {color: 0xFFFFFF, wireframe: true, transparent: true, opacity: 0.5} )];var plane = THREE.SceneUtils.createMultiMaterialObject(planeGeometry, planeMaterials);plane.rotation.x = -0.5 * Math.PI; // 沿著 X軸旋轉(zhuǎn)-90°plane.position.x = 15; // 沿著 x軸右移 15個(gè)單位plane.position.y = 0; // y軸為 0plane.position.z = 0; // z軸為 0plane.children[0].receiveShadow = true; // 非線框幾何平面接收陰影scene.add(plane);// 加入一個(gè)立方體var cubeGeometry = new THREE.BoxGeometry(4, 4, 4);var cubeMaterial = new THREE.MeshLambertMaterial( {color: 0xFF7777} );cube = new THREE.Mesh(cubeGeometry, cubeMaterial);cube.position.x = -4;cube.position.y = 3;cube.position.z = 0;cube.castShadow = true; // 立方體投射陰影scene.add(cube);// 加入一個(gè)球體var sphereGeometry = new THREE.SphereGeometry(4, 20, 20);var sphereMaterial = new THREE.MeshLambertMaterial( {color: 0x7777FF} );sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);sphere.position.x = 20;sphere.position.y = 4;sphere.position.z = 2;sphere.castShadow = true; // 球體投射陰影scene.add(sphere);// 加入一個(gè)環(huán)境光源var ambientLight = new THREE.AmbientLight(0x0c0c0c);scene.add(ambientLight);// 加入一個(gè)小球體來表示聚光燈位置sphereGeometry = new THREE.SphereGeometry(0.2, 20, 20);sphereMaterial = new THREE.MeshBasicMaterial( {color: 0xac6c25} );var lightMesh = new THREE.Mesh(sphereGeometry, sphereMaterial);// 加入一個(gè)點(diǎn)光源:color 顏色, intensity 強(qiáng)度, distance 距離, angle 散射角, penumbra 衰減百分比, decay 衰減spotLight = new THREE.SpotLight( 0xffffff, 1, 200, 1.2, 0.05, 2);spotLight.position.set(3, 20, 3);spotLight.castShadow = true; // 光源產(chǎn)生陰影spotLight.shadow.mapSize.set(2048, 2048); // 必須是 2的冪,默認(rèn)值為 512spotLight.shadow.camera.near = 2;spotLight.shadow.camera.far = 200;spotLight.shadow.camera.fov = spotLight.angle * 180 / Math.PI; //spotLight.target = plane;spotLight.add(lightMesh);scene.add(spotLight);// 用來表示聚光燈屬性的幾何線框lightHelper = new THREE.SpotLightHelper(spotLight);lightHelper.name = "lightHelper";// 用來表示聚光燈相機(jī)的幾何線框shadowCameraHelper = new THREE.CameraHelper(spotLight.shadow.camera);shadowCameraHelper.name = "shadowCameraHelper";/** 用來保存那些需要修改的變量 */guiControls = new function() {this.rotationSpeed = 0.02;this.bouncingSpeed = 0.04;this.ambientColor = '#1c1c1c';this.pointColor = '#ffffff';this.intensity = 1;this.distance = 200;this.angle = 1.2;this.penumbra = 0.05;this.decay = 2;this.near = 2;this.far = 200;this.fov = 30;this.debug = true;this.castShadow = true;this.disableSpotLight = false;this.target = 'Plane';this.stopMoveLight = false;}updateShadowCamera();/** 定義 dat.GUI 對象,并綁定 guiControls 的兩個(gè)屬性 */var gui = new dat.GUI();gui.addColor(guiControls, 'ambientColor').onChange( function(e) {ambientLight.color = new THREE.Color(e);});gui.addColor(guiControls, 'pointColor').onChange( function(e) {spotLight.color = new THREE.Color(e);});gui.add(guiControls, 'intensity', 0, 3).onChange( function(e) {spotLight.intensity = e;});gui.add(guiControls, 'distance', 0, 200).onChange( function(e) {spotLight.distance = e;});gui.add(guiControls, 'angle', 0, 2 * Math.PI).onChange( function(e) {spotLight.angle = e;});gui.add(guiControls, 'penumbra', 0.0, 1.0).onChange( function(e) {spotLight.penumbra = e;});gui.add(guiControls, 'decay', 0, 30).onChange( function(e) {spotLight.decay = e;});gui.add(guiControls, 'near', 2, 20).onChange( function(e) {updateShadowCamera();});gui.add(guiControls, 'far', 20, 200).onChange( function(e) {updateShadowCamera();});gui.add(guiControls, 'fov', 0, 180).onChange( function(e) {updateShadowCamera();});gui.add(guiControls, 'debug').onChange(function(e) {updateShadowCamera();});gui.add(guiControls, 'castShadow').onChange(function(e) {spotLight.castShadow = e;});gui.add(guiControls, 'disableSpotLight').onChange(function(e) {spotLight.visible = !e;});gui.add(guiControls, 'target', ['Plane', 'Cube', 'Sphere']).onChange(function(e) {switch (e) {case 'Plane':spotLight.target = plane;break;case 'Cube':spotLight.target = cube;break;case 'Sphere':spotLight.target = sphere;break;}});gui.add(guiControls, 'stopMoveLight').onChange(function(e){this.stopMoveLight = e;});function updateShadowCamera() {spotLight.shadow.camera.near = guiControls.near;spotLight.shadow.camera.far = guiControls.far;spotLight.shadow.camera.fov = guiControls.fov;if (guiControls.debug) {scene.remove(scene.getObjectByName('shadowCameraHelper'));shadowCameraHelper = new THREE.CameraHelper(spotLight.shadow.camera);shadowCameraHelper.name = "shadowCameraHelper";scene.add(shadowCameraHelper);scene.remove(scene.getObjectByName('lightHelper'));lightHelper = new THREE.SpotLightHelper(spotLight);lightHelper.name = "lightHelper";scene.add(lightHelper);} else {scene.remove(scene.getObjectByName('shadowCameraHelper'));scene.remove(scene.getObjectByName('lightHelper'));}}renderScene();});/** 渲染場景 */function renderScene() {stats.update();rotateCube(); // 旋轉(zhuǎn)立方體bounceSphere(); // 彈跳球體moveLight(); // 移動(dòng)點(diǎn)光源及其小球lightHelper.update();requestAnimationFrame(renderScene);render.render(scene, camera);}/** 初始化 stats 統(tǒng)計(jì)對象 */function initStats() {stats = new Stats();stats.setMode(0); // 0 為監(jiān)測 FPS;1 為監(jiān)測渲染時(shí)間$('#Stats-output').append(stats.domElement);return stats;}/** 當(dāng)瀏覽器窗口大小變化時(shí)觸發(fā) */function onWindowResize() {camera.aspect = window.innerWidth / window.innerHeight;camera.updateProjectionMatrix();render.setSize(window.innerWidth, window.innerHeight);}/** 轉(zhuǎn)動(dòng)立方體 */function rotateCube() {cube.rotation.x += guiControls.rotationSpeed;cube.rotation.y += guiControls.rotationSpeed;cube.rotation.z += guiControls.rotationSpeed;}/** 彈跳球體 */var step = 0;function bounceSphere() {step += guiControls.bouncingSpeed;sphere.position.x = 20 + (10 * Math.cos(step));sphere.position.y = 2 + (10 * Math.abs(Math.sin(step)));}/** 移動(dòng)點(diǎn)光源及其小球 */var invert = 1;var phase = 0;function moveLight() {if (guiControls.stopMoveLight)return;if (phase > 2 * Math.PI) {//debugger;invert = invert * -1;phase -= 2 * Math.PI;} else {phase += guiControls.rotationSpeed;}spotLight.position.x = 14 * (Math.cos(phase));spotLight.position.z = 7 * (Math.sin(phase));//spotLight.position.y = 10;//console.log('x:%f, z:%f, phase', spotLight.position.x, spotLight.position.z, phase);if (invert < 0) {var pivot = 14;spotLight.position.x = (invert * (spotLight.position.x - pivot)) + pivot;}}</script> </body> </html>大家可以通過這個(gè)相對完整的示例,親手試驗(yàn)并觀察各種屬性的效果。實(shí)際上 SpotLight 跟 PointLight 差別不大,唯一的不同在于聚光燈需要設(shè)置 target (目標(biāo))屬性,此屬性決定光源照射的地方。在本例中,默認(rèn)是 plane 的中心,你可以通過右上角的下拉菜單來動(dòng)態(tài)地修改該屬性,以便觀察對應(yīng)的效果。但是,需要指出的是,在我們的例子中,這個(gè) target 始終都是指向某個(gè)特定的對象。如果我們不想讓它瞄準(zhǔn)某個(gè)特定的對象,而是指向空間中的任意一點(diǎn)那該怎么辦?其實(shí)答案很簡單,我們可以創(chuàng)建一個(gè) THREE.Object3D() 示例,然后讓聚光燈的 target 屬性指向它即可,如下所示: var target = new THREE.Object3D(); target.position.set(0, 5, 0); spotLight.target = target;另外比較特殊的幾個(gè)屬性就是 shadow.camera.near、shadow.camera.far 及?shadow.camera.fov 屬性,它們控制光線如何投影、以及在哪里投影等。為了看到相機(jī)是如何工作的,在本示例中,我們增加了與之相應(yīng)的?THREE.CameraHelper() 對象,它完美的展示了相機(jī)是如何工作的。可以通過右上角的 debug 開關(guān)來開啟和禁止這個(gè)對象來觀察效果。? ? 最后需要提醒的是,對于陰影的生成,你不僅要告訴光源需要生成陰影,而且還要通過 castShadow 和 receiveShadow 屬性告訴每一個(gè)幾何體,是否接收和(或)投射陰影。
未完待續(xù)···
總結(jié)
以上是生活随笔為你收集整理的three.js 03-03 之 SpotLight 光源的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: windows server 2008小
- 下一篇: OV7670 STM32驱动 YUYV格