$$ In the first chapter, you learned about the basics of Three.js, and in the previouschapter, we looked a bit deeper at the most important parts of the scene: thegeometries, meshes, and cameras. You might have noticed that we skipped lights inthat chapter even though they make up an important part of every Three.js scene.Without lights, we won’t see anything rendered. Since Three.js contains a large numberof lights, each of which has a specific use, we’ll use this whole chapter to explain thevarious details of the lights and prepare you for the next chapter on material usage.

En el primer capítulo, aprendiste los conceptos básicos de Three.js, y en el capítulo anterior, analizamos un poco más en profundidad las partes más importantes de la escena: las geometrías, las mallas y las cámaras. Es posible que hayas notado que omitimos las luces en ese capítulo a pesar de que constituyen una parte importante de cada escena de Three.js. Sin luces, no veremos nada renderizado. Dado que Three.js contiene una gran cantidad de luces, cada una de las cuales tiene un uso específico, usaremos todo este capítulo para explicar los diversos detalles de las luces y prepararlo para el próximo capítulo sobre el uso de materiales.

$$ In this chapter, you’ll learn about the following subjects:

En este capítulo, aprenderá sobre los siguientes temas:

$$ As with all the chapters, we have a lot of examples that you can use to experimentwith the lights’ behavior. The examples shown in this chapter can be found in thechapter-03 folder of the supplied sources.

Como en todos los capítulos, tenemos muchos ejemplos que puedes usar para experimentar con el comportamiento de las luces. Los ejemplos que se muestran en este capítulo se pueden encontrar en la carpeta del capítulo 03 de las fuentes proporcionadas.

$$ There are a number of different lights available in Three.js that all have specificbehavior and usages. In this chapter, we’ll discuss the following set of lights:

Hay varias luces diferentes disponibles en Three.js y todas tienen comportamientos y usos específicos. En este capítulo, analizaremos el siguiente conjunto de luces:

$$ This chapter is divided into two main parts. First, we’ll look at the basic lights:THREE.AmbientLight, THREE.PointLight, THREE.SpotLight, and THREE.DirectionalLight. All these lights extend the base THREE.Light object, whichprovides shared functionality. The lights mentioned here are simple lights thatrequire little setting up and can be used to recreate most of the required lightingscenarios. In the second part, we will look at a couple of special-purpose lights andeffects: THREE.HemisphereLight, THREE.AreaLight, and THREE.LensFlare. You’llprobably only need these lights in very specific cases.

Este capítulo se divide en dos partes principales. Primero, veremos las luces básicas: TRES.AmbientLight, TRES.PointLight, TRES.SpotLight y TRES.DirectionalLight. Todas estas luces amplían la base TRES. Objeto de luz, que proporciona una funcionalidad compartida. Las luces mencionadas aquí son luces simples que requieren poca configuración y pueden usarse para recrear la mayoría de los escenarios de iluminación requeridos. En la segunda parte, veremos un par de luces y efectos de propósito especial: THREE.HemisphereLight, THREE.AreaLight y THREE.LensFlare. Probablemente sólo necesitarás estas luces en casos muy concretos.

$$ When you create THREE.AmbientLight, the color is applied globally. There isn’t aspecific direction this light comes from, and THREE.AmbientLight doesn’t contributeto any shadows. You would normally not use THREE.AmbientLight as the singlesource of light in a scene since it colors all the objects in the same color, regardless ofshape. You use it together with other lighting sources, such as THREE.SpotLight orTHREE.DirectionalLight to soften the shadows or add some additional color to thescene. The easiest way to understand this is by looking at the 01-ambient-light.html example in the chapter-03 folder. With this example, you get a simple userinterface that can be used to modify THREE.AmbientLight that is available in thisscene. Note that in this scene, we also have THREE.SpotLight, which adds additionallighting and provides shadows.

Cuando creas THREE.AmbientLight, el color se aplica globalmente. No hay una dirección específica de la que provenga esta luz, y TRES. La Luz Ambiental no contribuye a ninguna sombra. Normalmente no utilizarías THREE.AmbientLight como única fuente de luz en una escena, ya que colorea todos los objetos del mismo color, independientemente de su forma. Se utiliza junto con otras fuentes de iluminación, como THREE.SpotLight o THREE.DirectionalLight para suavizar las sombras o agregar algo de color adicional a la escena. La forma más sencilla de entender esto es mirando el ejemplo 01-ambient-light.html en la carpeta capítulo-03. Con este ejemplo, obtienes una interfaz de usuario simple que se puede usar para modificar TRES.AmbientLight que está disponible en esta escena. Tenga en cuenta que en esta escena también tenemos THREE.SpotLight, que agrega iluminación adicional y proporciona sombras.

$$ The standard color we use in this scene is #0c0c0c. This is a hexadecimalrepresentation of a color. The first two values specify the red part of the color, thenext two values specify the green part, and the last two values specify the blue part.

El color estándar que utilizamos en esta escena es #0c0c0c. Ésta es una representación hexadecimal de un color. Los dos primeros valores especifican la parte roja del color, los dos valores siguientes especifican la parte verde y los dos últimos valores especifican la parte azul.

$$ As the preceding image shows, the yellow/orange color is applied to all the objectsand casts a green glow over the complete scene. What you should remember whenworking with this light is that you should be very conservative with the coloryou specify. If the color you specify is too bright, you’ll quickly get a completelyoversaturated image.

Como muestra la imagen anterior, el color amarillo/naranja se aplica a todos los objetos y proyecta un brillo verde sobre toda la escena. Lo que debes recordar cuando trabajes con esta luz es que debes ser muy conservador con el color que especifiques. Si el color que especifica es demasiado brillante, rápidamente obtendrá una imagen completamente sobresaturada.

$$ Creating THREE.AmbientLight is very simple and only takes a couple of steps. THREE.AmbientLight doesn’t have a position and is applied globally, so we only need tospecify the color (in hex), new THREE.AmbientLight(ambiColor), and add thislight to the scene, scene.add(ambientLight). In the example, we bind the color ofTHREE.AmbientLight to the control menu. To do this, you can use the same kind ofconfiguration we used in the previous two chapters. The only change is that insteadof using the gui.add(…) function, we use the gui.addColor(…) function. Thiscreates an option in the control menu, with which we can directly change the color ofthe passed-in variable. In the code, you can see that we use the onChange feature ofdat.GUI: gui.addColor(…).onChange(function(e){…}). With this function, wetell dat.GUI to call the passed-in function each time the color changes. In this specificcase, we set the color of THREE.AmbientLight to a new value.

Crear THREE.AmbientLight es muy sencillo y sólo requiere un par de pasos. THREE.AmbientLight no tiene una posición y se aplica globalmente, por lo que solo necesitamos especificar el color (en hexadecimal), nuevo THREE.AmbientLight (ambiColor) y agregar esta luz a la escena, scene.add(ambientLight). En el ejemplo, vinculamos el color de THREE.AmbientLight al menú de control. Para hacer esto, puede usar el mismo tipo de configuración que usamos en los dos capítulos anteriores. El único cambio es que en lugar de usar la función gui.add(…), usamos la función gui.addColor(…). Esto crea una opción en el menú de control, con la que podemos cambiar directamente el color de la variable pasada. En el código, puede ver que usamos la función onChange de dat.GUI: gui.addColor(…).onChange(function(e){…}). Con esta función, le decimos a dat.GUI que llame a la función pasada cada vez que cambie el color. En este caso específico, configuramos el color de THREE.AmbientLight a un nuevo valor.

$$ Before we move on to the next light, here’s a quick note on using the THREE.Colorobject. In Three.js, when you construct an object, you can (usually) specify the coloras either a hex string (“#0c0c0c”) or a hex value (0x0c0c0c), which is the preferredway of doing it, or by specifying the individual RGB values (0.3, 0.5, 0.6) on a scaleof 0 to 1. If you want to change the color after construction, you’ll have to create anew THREE.Color object or modify the internal properties of the current THREE.Color object. The THREE.Color object comes with the following functions to set andget information about the current object:

Antes de pasar a la siguiente luz, aquí hay una nota rápida sobre el uso del objeto THREE.Color. En Three.js, cuando construyes un objeto, puedes (normalmente) especificar el color como una cadena hexadecimal (“#0c0c0c”) o un valor hexadecimal (0x0c0c0c), que es la forma preferida de hacerlo, o especificando los valores RGB individuales (0,3, 0,5, 0,6) en una escala de 0 a 1. Si deseas cambiar el color después de la construcción, tendrás que crear un nuevo objeto THREE.Color o modificarlo. las propiedades internas del objeto THREE.Color actual. El objeto THREE.Color viene con las siguientes funciones para configurar y obtener información sobre el objeto actual:

$$ In this table, you can see that there are many ways in which you can change thecurrent color. A lot of these functions are used internally by Three.js, but they alsoprovide a good way to easily change the color of lights and materials.

En esta tabla, puede ver que hay muchas formas de cambiar el color actual. Three.js utiliza muchas de estas funciones internamente, pero también proporcionan una buena manera de cambiar fácilmente el color de las luces y los materiales.

$$ THREE.PointLight in Three.js is a light source that shines light in all directionsemanating from a single point. A good example of a point light is a signal flare firedin the night sky. Just as with all the lights, we have a specific example you can useto play around with THREE.PointLight. If you look at 02-point-light.html inthe chapter-03 folder, you can find an example where a THREE.PointLight light ismoving around a simple Three.js scene. The following screenshot shows an exampleof this:

THREE.PointLight en Three.js es una fuente de luz que irradia luz en todas las direcciones desde un solo punto. Un buen ejemplo de luz puntual es una bengala de señal disparada en el cielo nocturno. Al igual que con todas las luces, tenemos un ejemplo específico que puedes usar para jugar con THREE.PointLight. Si observa 02-point-light.html en la carpeta del capítulo 03, puede encontrar un ejemplo en el que una luz THREE.PointLight se mueve por una escena simple de Three.js. La siguiente captura de pantalla muestra un ejemplo de esto:

$$ You might notice that we don’t see any shadows in this example. InThree.js, THREE.PointLight doesn’t cast shadows. Since THREE.PointLight emits light in all directions, calculating shadows is avery heavy process for the GPU.

Quizás notes que no vemos ninguna sombra en este ejemplo. En Three.js, THREE.PointLight no proyecta sombras. Dado que THREE.PointLight emite luz en todas direcciones, calcular sombras es un proceso muy pesado para la GPU.

$$ In the next couple of examples and screenshots, we’ll explain these properties. First,let’s look at how you can create THREE.PointLight:

En los siguientes ejemplos y capturas de pantalla, explicaremos estas propiedades. Primero, veamos cómo puedes crear THREE.PointLight:

$$ We create a light with a specific color property (here we use a string value; wecould have also used a number or THREE.Color), set its position property, and addit to the scene.

Creamos una luz con una propiedad de color específica (aquí usamos un valor de cadena; también podríamos haber usado un número o TRES.Color), establecemos su propiedad de posición y la agregamos a la escena.

$$ All you have to do to change the intensity of the light is use the intensity property ofTHREE.PointLight, as follows:

Todo lo que tienes que hacer para cambiar la intensidad de la luz es usar la propiedad de intensidad de THREE.PointLight, de la siguiente manera:

$$ The distance property of PointLight is a very interesting one and is best explainedwith an example. In the following screenshot, you see the same scene again, but thistime with a very high intensity property (we have a very bright light), but with asmall distance:

La propiedad de distancia de PointLight es muy interesante y se explica mejor con un ejemplo. En la siguiente captura de pantalla, vuelves a ver la misma escena, pero esta vez con una propiedad de intensidad muy alta (tenemos una luz muy brillante), pero con una distancia pequeña:

$$ THREE.SpotLight is one of the lights you’ll use most often (especially if you wantto use shadows). THREE.SpotLight is a light source that has a cone-like effect. Youcan compare this with a flashlight or a lantern. This light has a direction and an angleat which it produces light. The following table lists all the properties that apply toTHREE.SpotLight:

TRES. SpotLight es una de las luces que usarás con más frecuencia (especialmente si quieres usar sombras). THREE.SpotLight es una fuente de luz que tiene un efecto de cono. Puedes comparar esto con una linterna o una linterna. Esta luz tiene una dirección y un ángulo en el que produce luz. La siguiente tabla enumera todas las propiedades que se aplican a THREE.SpotLight:

$$ THREE.SpotLight is not very different from THREE.PointLight. The onlydifference is that we set the castShadow property to true because we wantshadows, and we need to set the target property for this SpotLight. The targetproperty determines where the light is aimed at. In this case, we point it at theobject named plane. When you run the example (03-spot-light.html), you’ll seea scene like the following screenshot:

THREE.SpotLight no es muy diferente de THREE.PointLight. La única diferencia es que configuramos la propiedad castShadow en verdadero porque queremos sombras y necesitamos establecer la propiedad de destino para este SpotLight. La propiedad objetivo determina hacia dónde apunta la luz. En este caso, apuntamos al objeto llamado plano. Cuando ejecute el ejemplo (03-spot-light.html), verá una escena como la siguiente captura de pantalla:

$$ In the table at the beginning of this section, we showed a couple of propertiesthat can be used to control how the light emanates from THREE.SpotLight. Thedistance and angle properties define the shape of the cone of light. The angleproperty defines the width of the cone, and with the distance property, we set thelength of the cone. The following figure explains how these two values togetherdefine the area that will receive light from THREE.SpotLight:

En la tabla al comienzo de esta sección, mostramos un par de propiedades que se pueden usar para controlar cómo emana la luz de THREE.SpotLight. Las propiedades de distancia y ángulo definen la forma del cono de luz. La propiedad de ángulo define el ancho del cono y con la propiedad de distancia establecemos la longitud del cono. La siguiente figura explica cómo estos dos valores juntos definen el área que recibirá luz de THREE.SpotLight:

$$ You could use this to highlight a specific object or simulate a small flashlight. Wecould also have created the same focused beam effect using a small exponent valueand angle. On a cautionary note on this second approach, remember that a very smallangle can quickly lead to all kinds of rendering artifacts (an artifact is a term used ingraphics for unwanted distortions and strangely rendered parts of the screen).

Puedes usar esto para resaltar un objeto específico o simular una pequeña linterna. También podríamos haber creado el mismo efecto de haz enfocado usando un valor de exponente y un ángulo pequeños. Como nota de precaución sobre este segundo enfoque, recuerde que un ángulo muy pequeño puede conducir rápidamente a todo tipo de artefactos de renderizado (un artefacto es un término usado en gráficos para distorsiones no deseadas y partes de la pantalla renderizadas de manera extraña).

$$ I’ll end this section with a couple of pointers, just in case you run into issueswith shadows:

Terminaré esta sección con un par de consejos, en caso de que tengas problemas con las sombras:

$$ The last of the basic lights we will look at is THREE.DirectionalLight. This type oflight can be considered as a light that is very far away. All the light rays it sends outare parallel to each other. A good example of this is the sun. The sun is so far awaythat the light rays we receive on earth are (almost) parallel to each other. The maindifference between THREE.DirectionalLight and THREE.SpotLight (which wesaw in the previous section) is that this light won’t diminish the farther it gets fromthe target of THREE.DirectionalLight as it does with THREE.SpotLight (you canfine-tune this with the distance and exponent parameters). The complete area thatis lit by THREE.DirectionalLight receives the same intensity of light.

La última de las luces básicas que veremos es TRES.DirectionalLight. Este tipo de luz se puede considerar como una luz que está muy lejana. Todos los rayos de luz que envía son paralelos entre sí. Un buen ejemplo de esto es el sol. El sol está tan lejos que los rayos de luz que recibimos en la Tierra son (casi) paralelos entre sí. La principal diferencia entre THREE.DirectionalLight y THREE.SpotLight (que vimos en la sección anterior) es que esta luz no disminuirá cuanto más se aleje del objetivo de THREE.DirectionalLight como lo hace con THREE.SpotLight (puede ajustar esto con los parámetros de distancia y exponente). Toda el área iluminada por TRES Luces Direccionales recibe la misma intensidad de luz.

$$ As you can see in the preceding image, there isn’t a cone of light that is applied to thescene. Everything receives the same amount of light. Only the direction, the color,and the intensity of the light is used to calculate the colors and shadows.

Como puede ver en la imagen anterior, no hay un cono de luz aplicado a la escena. Todo recibe la misma cantidad de luz. Sólo se utiliza la dirección, el color y la intensidad de la luz para calcular los colores y las sombras.

$$ If you look back at the THREE.SpotLight examples, you can see that we hadto define the cone of light where shadows were applied. Since, for THREE.DirectionalLight, all the rays are parallel to each other, we don’t have a cone oflight, instead, we have a cuboid area, as you can see in the following screenshot (ifyou want to see this for yourself, move the camera further away from the scene):

Si vuelves a mirar los ejemplos de THREE.SpotLight, podrás ver que tuvimos que definir el cono de luz donde se aplicaron las sombras. Dado que, para THREE.DirectionalLight, todos los rayos son paralelos entre sí, no tenemos un cono de luz, sino un área cuboide, como puedes ver en la siguiente captura de pantalla (si quieres verlo por ti mismo, aleja la cámara de la escena):