Luces y sombras 3D

Introducción

Las luces emiten luz que se mezcla con los materiales produciendo un resultado visible. La luz puede proceder de varias fuentes en una escena:

  • Del propio material, en forma de color de emisión (aunque no afecta a los objetos cercanos a menos que se habilite la iluminación indirecta del espacio de la pantalla o horneada).

  • Nodos de luz: DirectionalLight3D, OmniLight3D y SpotLight3D.

  • Luz Ambiental en Environment o Reflection Probe.

  • Global illumination (LightmapGI, VoxelGI or SDFGI).

El color de emisión es una propiedad del material. Puedes leer más sobre ello en el tutorial Material estándar 3D y material ORM 3D.

Ver también

You can compare various types of lights in action using the 3D Lights and Shadows demo project.

Nodos de luz

Existen tres tipos de nodos de luz: DirectionalLight3D, OmniLight3D and SpotLight3D. Echemos un vistazo a los parámetros comunes para las luces:

../../_images/light_params.png

Cada propiedad tiene una función específica:

  • Color: Color base para la luz emitida.

  • Energía: Multiplicador de energía. Resulta útil para saturar luces o para trabajar con Iluminación de alto rango dinámico.

  • Energía indirecta: Multiplicador secundario utilizado con luz indirecta (rebote de luz). Funciona con Using Lightmap global illumination, VoxelGI o SDFGI.

  • Volumetric Fog Energy: Secondary multiplier used with volumetric fog. This only has an effect when volumetric fog is enabled.

  • Negativa: La luz se vuelve sustractiva en lugar de aditiva. A veces resulta útil compensar manualmente algunas esquinas oscuras.

  • Especular: Afecta la intensidad de la mancha especular en los objetos afectados por esta luz. En cero, esta luz se convierte en una luz difusa pura.

  • Bake Mode: Establece el modo de "bake" para la luz. Véase Using Lightmap global illumination.

  • Cull Mask: Objects that are in the selected layers below will be affected by this light. Note that objects disabled via this cull mask will still cast shadows. If you don't want disabled objects to cast shadows, adjust the Cast Shadow property on the GeometryInstance3D to the desired value.

Ver también

See Physical light and camera units if you wish to use real world units to configure your lights' intensity and color temperature.

Límites de número de luces

When using the Forward+ renderer, Godot uses a clustering approach for real-time lighting. As many lights as desired can be added (as long as performance allows). However, there's still a default limit of 512 clustered elements that can be present in the current camera view. A clustered element is an omni light, a spot light, a decal or a reflection probe. This limit can be increased by adjusting Max Clustered Elements in Project Settings > Rendering > Limits > Cluster Builder.

Al usar el renderizador Mobile, existe un límite de 8 OmniLights + 8 SpotLights por recurso de modelo. También existe un límite de 256 OmniLights + 256 SpotLights que se pueden renderizar en la vista de cámara actual. Estos límites no se pueden modificar actualmente.

When using the Compatibility renderer, up to 8 OmniLights + 8 SpotLights can be rendered per mesh resource. This limit can be increased in the advanced Project Settings by adjusting Max Renderable Elements and/or Max Lights per Object in Rendering > Limits > OpenGL, at the cost of performance and longer shader compilation times. The limit can also be decreased to reduce shader compilation times and improve performance slightly.

Con todos los métodos de renderizado, se pueden ver hasta 8 luces direccionales simultáneamente. Sin embargo, cada luz direccional adicional con sombras habilitadas reducirá la resolución efectiva de las sombras. Esto se debe a que el atlas de sombras direccionales se comparte entre todas las luces.

Si se supera el límite de renderizado, las luces empezarán a aparecer y desaparecer durante el movimiento de la cámara, lo que puede resultar molesto. Activar la función Desvanecimiento de Distancia en los nodos de luz puede ayudar a reducir este problema y, al mismo tiempo, mejorar el rendimiento. Dividir las mallas en porciones más pequeñas también puede ser útil, especialmente para la geometría de nivel (lo que también mejora la eficiencia de la selección).

If you need to render more lights than possible in a given renderer, consider using baked lightmaps with lights' bake mode set to Static. This allows lights to be fully baked, which also makes them much faster to render. You can also use emissive materials with any global illumination technique as a replacement for light nodes that emit light over a large area.

Mapeo de sombras

Las luces opcionalmente pueden proyectar sombras. Esto les da mayor realismo (la luz no llega a las zonas ocluidas), pero puede incurrir en un mayor coste de rendimiento. Hay una lista de parámetros de sombra genéricos, cada uno también tiene una función específica:

  • Enabled: Check to enable shadow mapping in this light.

  • Opacidad: Las áreas ocluidas se oscurecen con este factor de opacidad. Las sombras son completamente opacas por defecto, pero se puede modificar para que sean translúcidas para una luz determinada.

  • Bias: When this parameter is too low, self-shadowing occurs. When too high, shadows separate from the casters. Tweak to what works best for you.

  • Normal Bias: When this parameter is too low, self-shadowing occurs. When too high, shadows appear misaligned from the casters. Tweak to what works best for you.

  • Transmittance Bias: When this parameter is too low, self-shadowing occurs on materials that have transmittance enabled. When too high, shadows will not affect materials that have transmittance enabled consistently. Tweak to what works best for you.

  • Reverse Cull Face: Some scenes work better when shadow mapping is rendered with face-culling inverted.

  • Blur: Multiplies the shadow blur radius for this light. This works with both traditional shadow mapping and contact-hardening shadows (lights with Angular Distance or Size greater than 0.0). Higher values result in softer shadows, which will also appear to be more temporally stable for moving objects. The downside of increasing shadow blur is that it will make the grainy pattern used for filtering more noticeable. See also Modo del filtro de sombras.

  • Caster Mask: Shadows are only cast by objects in these layers. Note that this mask does not affect which objects shadows are cast onto.

../../_images/lights_and_shadows_blur.webp

Ajustar el sesgo de sombra

Below is an image of what tweaking bias looks like. Default values work for most cases, but in general, it depends on the size and complexity of geometry.

If the Shadow Bias or Shadow Normal Bias is set too low for a given light, the shadow will be "smeared" onto the objects. This will cause the light's intended appearance to darken, and is called shadow acne:

../../_images/lights_and_shadows_acne.webp

On the other hand, if the Shadow Bias or Shadow Normal Bias is set too high for a given light, the shadow may appear to be disconnected from the object. This is called peter-panning:

../../_images/lights_and_shadows_peter_panning.webp

In general, increasing Shadow Normal Bias is preferred over increasing Shadow Bias. Increasing Shadow Normal Bias does not cause as much peter-panning as increasing Shadow Bias, but it can still resolve most shadow acne issues efficiently. The downside of increasing Shadow Normal Bias is that it can make shadows appear thinner for certain objects.

Any sort of bias issues can be fixed by increasing the shadow map resolution, at the cost of decreased performance.

Nota

Tweaking shadow mapping settings is an art – there are no "one size fits all" settings. To achieve the best visuals, you may need to use different shadow bias values on a per-light basis.

Note on Appearance Changes: When enabling shadows on a light, be aware that the light's appearance might change compared to when it's rendered without shadows in the compatibility renderer. Due to limitations with older mobile devices, shadows are implemented using a multi-pass rendering approach so lights with shadows are rendered in sRGB space instead of linear space. This change in rendering space can sometimes drastically alter the light's appearance. To achieve a similar appearance to an unshadowed light, you may need to adjust the light's energy setting.

Directional light (Luz direccional)

Este es el tipo de luz más común y representa una fuente de luz muy lejana (como el sol). También es la luz menos costosa de calcular y debería utilizarse siempre que sea posible (aunque no es el mapa de sombras menos costoso de calcular, pero eso se explicará más adelante).

La luz direccional modela un número infinito de rayos de luz paralelos que cubren la escena completa. El nodo de luz direccional es representado por una gran flecha que indica la dirección de los rayos de luz. Sin embargo, la posición del nodo no afecta al comportamiento de luz y puede ser colocado en cualquier lugar de la escena.

../../_images/light_directional.png

Every face whose front-side is hit by the light rays is lit, while the others stay dark. Unlike most other light types, directional lights don't have specific parameters.

The directional light also offers an Angular Distance property, which determines the light's angular size in degrees. Increasing this above 0.0 will make shadows softer at greater distances from the caster, while also affecting the sun's appearance in procedural sky materials. This is called a contact-hardening shadow (also known as PCSS).

For reference, the angular distance of the Sun viewed from the Earth is approximately 0.5. This kind of shadow is expensive, so check the recommendations in PCSS recommendations if setting this value above 0.0 on lights with shadows enabled.

Mapeo de sombras direccional

To compute shadow maps, the scene is rendered (only depth) from an orthogonal point of view that covers the whole scene (or up to the max distance). There is, however, a problem with this approach because objects closer to the camera receive low-resolution shadows that may appear blocky.

Para solucionar esto, se utiliza una técnica llamada Mapas de Sombra Divididos Paralelos (Parallel Split Shadow Maps, o PSSM). Esto divide el frustum de visión en 2 o 4 áreas. Cada área obtiene su propio mapa de sombras. Esto permite que áreas pequeñas cercanas al espectador tengan la misma resolución de sombras que un área enorme y lejana. Cuando las sombras están habilitadas para DirectionalLight3D, el modo de sombra predeterminado es PSSM con 4 divisiones. En escenarios donde un objeto es lo suficientemente grande como para aparecer en las cuatro divisiones, resulta en un aumento de las llamadas de dibujado. Específicamente, dicho objeto se renderizará cinco veces en total: una vez por cada una de las cuatro divisiones de sombra y una vez para el renderizado final de la escena. Esto puede afectar el rendimiento, por lo que es importante comprender este comportamiento para optimizar su escena y gestionar las expectativas de rendimiento.

../../_images/lights_and_shadows_pssm_explained.webp

Con esto, las sombras se vuelven más detalladas:

../../_images/lights_and_shadows_directional_mode.webp

Para controlar PSSM, se exponen varios parámetros:

../../_images/lights_and_shadows_directional_shadow_params.webp

Each split distance is controlled relative to the camera far (or shadow Max Distance if greater than 0.0). 0.0 is the eye position and 1.0 is where the shadow ends at a distance. Splits are in-between. Default values generally work well, but tweaking the first split a bit is common to give more detail to close objects (like a character in a third-person game).

Asegúrate siempre de establecer una Distancia Máxima de sombra según las necesidades de la escena. Una distancia máxima menor dará como resultado sombras de mejor aspecto y un mejor rendimiento, ya que será necesario incluir menos objetos en la representación de sombras. También puedes ajustar Inicio de Desvanecimiento (Fade Start) para controlar qué tan agresivo debe ser el desvanecimiento de la sombra en la distancia. Para escenas en las que la Distancia Máxima cubre completamente la escena en cualquier posición de la cámara, puedes aumentar Inicio de Desvanecimiento a 1.0 para evitar que la sombra se desvanezca a distancia. Esto no debe hacerse en escenas en las que la Distancia Máxima no cubre completamente la escena, ya que la sombra parecerá cortarse de repente.

Sometimes, the transition between a split and the next can look bad. To fix this, the Blend Splits option can be turned on, which sacrifices detail and performance in exchange for smoother transitions:

../../_images/blend_splits.png

The Shadow > Normal Bias parameter can be used to fix special cases of self-shadowing when objects are perpendicular to the light. The only downside is that it makes the shadow a bit thinner. Consider increasing Shadow > Normal Bias before increasing Shadow > Bias in most situations.

Lastly, Pancake Size is a property that can be adjusted to fix missing shadows when using large objects with unsubdivided meshes. Only change this value if you notice missing shadows that are not related to shadow biasing issues.

Omni light (luz omnidireccional)

Omni light es un punto que emite luz esféricamente en todas las direcciones hasta un radio dado.

../../_images/light_omni.png

En la vida real, la atenuación de la luz es una función inversa, lo que significa que las luces omnidireccionales no tienen radio. Esto es un problema porque calcular un gran número de este tipo de luces se volvería costoso.

To solve this, a Range parameter is introduced together with an attenuation function.

../../_images/light_omni_params.png

Estos dos parámetros permiten ajustar cómo funciona esto visualmente para encontrar resultados estéticamente agradables.

../../_images/light_attenuation.png

A Size parameter is also available in OmniLight3D. Increasing this value will make the light fade out slower and shadows appear blurrier when far away from the caster. This can be used to simulate area lights to an extent. This is called a contact-hardening shadow (also known as PCSS). This kind of shadow is expensive, so check the recommendations in PCSS recommendations if setting this value above 0.0 on lights with shadows enabled.

../../_images/lights_and_shadows_pcss.webp

Mapeo de sombras omnidireccional

El mapeo de sombras para una Omni light es relativamente sencillo. Lo principal a considerar es el algoritmo que se utilizará para renderizarlo.

Omni Shadows can be rendered as either Dual Paraboloid or Cube mapped. Dual Paraboloid renders quickly, but can cause deformations, while Cube is more correct, but slower. The default is Cube, but consider changing it to Dual Paraboloid for lights where it doesn't make much of a visual difference.

../../_images/lights_and_shadows_dual_parabolid_vs_cubemap.webp

If the objects being rendered are mostly irregular and subdivided, Dual Paraboloid is usually enough. In any case, as these shadows are cached in a shadow atlas (more on that at the end), it may not make a difference in performance for most scenes.

Omni lights with shadows enabled can make use of projectors. The projector texture will multiply the light's color by the color at a given point on the texture. As a result, lights will usually appear to be darker once a projector texture is assigned; you can increase Energy to compensate for this.

Omni light projector textures require a special 360° panorama mapping, similar to PanoramaSkyMaterial textures.

Con la textura del proyector a continuación, se obtiene el siguiente resultado:

../../_images/lights_and_shadows_omni_projector_example.webp ../../_images/lights_and_shadows_omni_projector.webp

Truco

If you've acquired omni projectors in the form of cubemap images, you can use this web-based conversion tool to convert them to a single panorama image.

Spot light (luz focal)

Las luces focales (o puntuales) son similares a las omnidireccionales (omni lights), excepto porque emiten luz solamente en un cono (o "corte"). Son útiles para simular linternas, luces de coche, reflectores, focos, etc. Este tipo de luz además se atenúa en la dirección opuesta a la que apunta.

Spot lights share the same Range, Attenuation and Size as OmniLight3D, and add two extra parameters:

  • Angle: El ángulo de apertura de la luz.

  • Angle Attenuation: The cone attenuation, which helps soften the cone borders.

Mapeo de sombras focal

Spots feature the same parameters as omni lights for shadow mapping. Rendering spot shadow maps is significantly faster compared to omni lights, as only one shadow texture needs to be rendered (instead of rendering 6 faces, or 2 in dual paraboloid mode).

Spot lights with shadows enabled can make use of projectors. The projector texture will multiply the light's color by the color at a given point on the texture. As a result, lights will usually appear to be darker once a projector texture is assigned; you can increase Energy to compensate for this.

Unlike omni light projectors, a spot light projector texture doesn't need to follow a special format to look correct. It will be mapped in a way similar to a decal.

Con la textura del proyector a continuación, se obtiene el siguiente resultado:

../../_images/lights_and_shadows_spot_projector_example.webp ../../_images/lights_and_shadows_spot_projector.webp

Nota

Spot lights with wide angles will have lower-quality shadows than spot lights with narrow angles, as the shadow map is spread over a larger surface. At angles wider than 89 degrees, spot light shadows will stop working entirely. If you need shadows for wider lights, use an omni light instead.

Atlas de sombras

Unlike Directional lights, which have their own shadow texture, omni and spot lights are assigned to slots of a shadow atlas. This atlas can be configured in the advanced Project Settings (Rendering > Lights And Shadows > Positional Shadow).

The resolution applies to the whole shadow atlas. This atlas is divided into four quadrants:

../../_images/lights_and_shadows_shadow_quadrants.webp

Cada cuadrante se puede subdividir para asignar cualquier número de mapas de sombras; la siguiente es la subdivisión predeterminada:

../../_images/lights_and_shadows_shadow_quadrants2.webp

El atlas de sombras asigna el espacio de la siguiente manera:

  • The biggest shadow map size (when no subdivision is used) represents a light the size of the screen (or bigger).

  • Subdivisions (smaller maps) represent shadows for lights that are further away from view and proportionally smaller.

En Cada fotograma, se realiza el siguiente procedimiento para todas las luces:

  1. Se comprueba si la luz está en un espacio del tamaño correcto. Si no es así, se vuelve a renderizar y se mueve a un espacio más grande o más pequeño.

  2. Se comprueba si ha cambiado algún objeto que afecte al mapa de sombras. Si esto sucedió, se renderiza de nuevo la luz.

  3. Si no ha ocurrido nada de lo anterior, no se hace nada, y la sombra queda intacta.

If the slots in a quadrant are full, lights are pushed back to smaller slots, depending on size and distance. If all slots in all quadrants are full, some lights will not be able to render shadows even if shadows are enabled on them.

The default shadow allocation strategy allows rendering up to 88 lights with shadows enabled in the camera frustum (4 + 4 + 16 + 64):

  1. El primer y más detallado cuadrante puede almacenar 4 sombras.

  2. El segundo cuadrante puede almacenar otras 4 sombras.

  3. El tercer cuadrante puede almacenar 16 sombras, con menos detalles.

  4. El cuarto cuadrante, el menos detallado, puede almacenar 64 sombras, con aún menos detalles.

Using a higher number of shadows per quadrant allows supporting a greater amount of total lights with shadows enabled, while also improving performance (as shadows will be rendered at a lower resolution for each light). However, increasing the number of shadows per quadrant comes at the cost of lower shadow quality.

In some cases, you may want to use a different allocation strategy. For example, in a top-down game where all lights are around the same size, you may want to set all quadrants to have the same subdivision so that all lights have shadows of similar quality level.

Balancing performance and quality

La representación de sombras es un aspecto crucial del rendimiento del renderizado 3D. Es fundamental tomar las decisiones correctas para evitar cuellos de botella.

La configuración de la calidad de la sombra direccional se puede cambiar en tiempo de ejecución llamando a los métodos de RenderingServer apropiados.

Positional (omni/spot) shadow quality settings can be changed at runtime on the root Viewport.

Tamaño del mapa de sombras

High shadow resolutions result in sharper shadows, but at a significant performance cost. It should also be noted that sharper shadows are not always more realistic. In most cases, this should be kept at its default value of 4096 or decreased to 2048 for low-end GPUs.

Si las sombras posicionales se vuelven demasiado borrosas tras reducir el tamaño del mapa de sombras, puedes solucionarlo ajustando los cuadrantes del shadow atlas para que contengan menos sombras. Esto permitirá que cada sombra se renderice con mayor resolución.

Modo del filtro de sombras

Several shadow map quality settings can be chosen here. The default Soft Low is a good balance between performance and quality for scenes with detailed textures, as the texture detail will help make the dithering pattern less noticeable.

However, in projects with less detailed textures, the shadow dithering pattern may be more visible. To hide this pattern, you can either enable Antialiasing temporal (TAA), AMD FidelityFX Super Resolution 2.2 (FSR2), Antialiasing aproximado rápido (FXAA), or increase the shadow filter quality to Soft Medium or higher.

The Soft Very Low setting will automatically decrease shadow blur to make artifacts from the low sample count less visible. Conversely, the Soft High and Soft Ultra settings will automatically increase shadow blur to better make use of the increased sample count.

../../_images/lights_and_shadows_filter_quality.webp

16-bits versus 32-bits

De forma predeterminada, Godot utiliza texturas de profundidad de 16 bits para la representación de mapas de sombras. Esto se recomienda en la mayoría de los casos, ya que ofrece un mejor rendimiento sin una diferencia apreciable en la calidad.

Si se deshabilita la opción 16 Bits, se usarán texturas de profundidad de 32 bits. Esto puede resultar en menos artefactos en escenas grandes y luces grandes con sombras activadas. Sin embargo, la diferencia suele ser apenas perceptible, lo que puede afectar significativamente el rendimiento.

Light/shadow distance fade

OmniLight3D y SpotLight3D ofrecen varias propiedades para ocultar luces distantes. Esto puede mejorar significativamente el rendimiento en escenas grandes con docenas de luces o más.

  • Enabled: Controls whether distance fade (a form of LOD) is enabled. The light will fade out over Begin + Length, after which it will be culled and not sent to the shader at all. Use this to reduce the number of active lights in a scene and thus improve performance.

  • Begin: The distance from the camera at which the light begins to fade away (in 3D units).

  • Shadow: The distance from the camera at which the shadow begins to fade away (in 3D units). This can be used to fade out shadows sooner compared to the light, further improving performance. Only available if shadows are enabled for the light.

  • Length: The distance over which the light and shadow fades (in 3D units). The light becomes slowly more transparent over this distance and is completely invisible at the end. Higher values result in a smoother fade-out transition, which is more suited when the camera moves fast.

PCSS recommendations

Percentage-closer soft shadows (PCSS) provide a more realistic shadow mapping appearance, with the penumbra size varying depending on the distance between the caster and the surface receiving the shadow. This comes at a high performance cost, especially for directional lights.

Para evitar problemas de rendimiento, se recomienda:

  • Only use a handful of lights with PCSS shadows enabled at a given time. The effect is generally most visible on large, bright lights. Secondary light sources that are more faint usually don't benefit much from using PCSS shadows.

  • Provide a setting for users to disable PCSS shadows. On directional lights, this can be done by setting the DirectionalLight3D's light_angular_distance property to 0.0 in a script. On positional lights, this can be done by setting the OmniLight3D or SpotLight3D's light_size property to 0.0 in a script.

Modo de filtro del proyector

The way projectors are rendered also has an impact on performance. The Rendering > Textures > Light Projectors > Filter advanced project setting lets you control how projector textures should be filtered. Nearest/Linear do not use mipmaps, which makes them faster to render. However, projectors will look grainy at distance. Nearest/Linear Mipmaps will look smoother at a distance, but projectors will look blurry when viewed from oblique angles. This can be resolved by using Nearest/Linear Mipmaps Anisotropic, which is the highest-quality mode, but also the most expensive.

Si tu proyecto tiene un estilo pixel art, considera configurar el filtro con uno de los valores Más cercano para que los proyectores utilicen el filtro por vecino más cercano. De lo contrario, utiliza Lineal.