three.js 03-03 之 SpotLight 光源

来源:互联网 发布:淘宝购物车改数量 编辑:程序博客网 时间:2024/06/05 18:28

    这一篇我们来简单介绍一下 SpotLight 光源。如果你已经看过我前几篇关于灯光方面的介绍,相信你对灯光应该有了一定的认识了。在 three.js 中,SpotLight(聚光灯光源)大概会是最常用的一种光源,尤其是当想要生成阴影时。SpotLight 光源有一种雏形效果,类似我们生活中的手电筒或者灯笼。下面我先来看看聚光灯不同于点光源的几个额外属性,如下表所示:

属性描述castShadow (投影)如果此属性为 true,这个光源就会生成阴影;否则就不会生成阴影shadow.camera.near (投影相机近面)此属性表明,从距离光源的哪一个地方开始可以生成阴影shadow.camera.far (投影相机远面)此属性表明,到距离光源的哪一个地方为止可以生成阴影shadow.camera.fov (投影相机视野)此属性表明,用于生成阴影的视野有多大target (目标)此属性决定光源照射的方向shadow.bias (阴影偏移)用来偏置阴影的位置。当决定一个表面是否在阴影里时,在标准深度上增加或减去多少。更多概念可参考 Shadow Map 相关知识angel (角度)此属性表明光源射出的光柱有多宽。单位是弧度,默认值 Math.PI/3。shadow.camera.visible (投影相机可见性)此属性如果设置为 true,你就可以看到光源在哪里以及如何生成阴影。shadow.mapSize.width (阴影映射宽度)此属性决定在阴影宽度方向上用多少像素来生成阴影。这个数必须是 2的幂。默认为 512。此值越大越平滑。shadow.mapSize.height (阴影映射高度)此属性决定在阴影高度方向上用多少像素来生成阴影。这个数必须是 2的幂。默认为 512。此值越大越平滑。

下面我们先给出一个完整的示例代码:

<!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 {            /* 设置 margin 为 0,并且 overflow 为 hidden,来完成页面样式 */            margin: 0;            overflow: hidden;        }/* 统计对象的样式 */#Stats-output {position: absolute;left: 0px;top: 0px;}    </style></head><body><!-- 用于 WebGL 输出的 Div --><div id="WebGL-output"></div><!-- 用于统计 FPS 输出的 Div --><div id="Stats-output"></div><!-- 运行 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));// 加入坐标轴// 加入一个平面(带线框效果)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轴旋转-90°plane.position.x = 15; // 沿着 x轴右移 15个单位plane.position.y = 0; // y轴为 0plane.position.z = 0; // z轴为 0plane.children[0].receiveShadow = true; // 非线框几何平面接收阴影scene.add(plane);// 加入一个立方体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);// 加入一个球体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);// 加入一个环境光源var ambientLight = new THREE.AmbientLight(0x0c0c0c);scene.add(ambientLight);// 加入一个小球体来表示聚光灯位置sphereGeometry = new THREE.SphereGeometry(0.2, 20, 20);sphereMaterial = new THREE.MeshBasicMaterial( {color: 0xac6c25} );var lightMesh = new THREE.Mesh(sphereGeometry, sphereMaterial);// 加入一个点光源:color 颜色, intensity 强度, 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; // 光源产生阴影spotLight.shadow.mapSize.set(2048, 2048); // 必须是 2的幂,默认值为 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";// 用来表示聚光灯相机的几何线框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 的两个属性 */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(); // 旋转立方体bounceSphere(); // 弹跳球体moveLight(); // 移动点光源及其小球lightHelper.update();requestAnimationFrame(renderScene);render.render(scene, camera);}/** 初始化 stats 统计对象 */function initStats() {stats = new Stats();stats.setMode(0); // 0 为监测 FPS;1 为监测渲染时间$('#Stats-output').append(stats.domElement);return stats;}/** 当浏览器窗口大小变化时触发 */function onWindowResize() {camera.aspect = window.innerWidth / window.innerHeight;camera.updateProjectionMatrix();render.setSize(window.innerWidth, window.innerHeight);}/** 转动立方体 */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)));}/** 移动点光源及其小球 */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>
大家可以通过这个相对完整的示例,亲手试验并观察各种属性的效果。实际上 SpotLight 跟 PointLight 差别不大,唯一的不同在于聚光灯需要设置 target (目标)属性,此属性决定光源照射的地方。在本例中,默认是 plane 的中心,你可以通过右上角的下拉菜单来动态地修改该属性,以便观察对应的效果。但是,需要指出的是,在我们的例子中,这个 target 始终都是指向某个特定的对象。如果我们不想让它瞄准某个特定的对象,而是指向空间中的任意一点那该怎么办?其实答案很简单,我们可以创建一个 THREE.Object3D() 示例,然后让聚光灯的 target 属性指向它即可,如下所示:

var target = new THREE.Object3D();target.position.set(0, 5, 0);spotLight.target = target;
另外比较特殊的几个属性就是 shadow.camera.near、shadow.camera.far 及 shadow.camera.fov 属性,它们控制光线如何投影、以及在哪里投影等。为了看到相机是如何工作的,在本示例中,我们增加了与之相应的 THREE.CameraHelper() 对象,它完美的展示了相机是如何工作的。可以通过右上角的 debug 开关来开启和禁止这个对象来观察效果。

    最后需要提醒的是,对于阴影的生成,你不仅要告诉光源需要生成阴影,而且还要通过 castShadow 和 receiveShadow 属性告诉每一个几何体,是否接收和(或)投射阴影。

未完待续···

原创粉丝点击