Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

18.8 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    Light.hpp
 * @brief   2D light source component for the Lit material domain.
 * @details A scene's Light components are gathered by the render collect path into the
 *          per-frame LightConstants UBO (binding 2); Lit-domain material shaders read them
 *          via the injected applyLighting2D() helper. Point/Directional/Spot lights occupy a
 *          light slot; Ambient lights sum into the ambient term. This component carries only
 *          the light's intrinsic parameters. Where a light sits and where it aims are the
 *          entity's Transform: Point/Spot read their world position from it (and are skipped
 *          without one), and Directional/Spot aim along the entity's forward — its rotation
 *          applied to -Z, which is what an unrotated light has always shone along.
 *
 * @author  ESEngine Team
 * @date    2026
 *
 * @copyright Copyright (c) 2026 ESEngine Team
 *            Licensed under the Apache License, Version 2.0.
 */
#pragma once

#include "../../core/Types.hpp"
#include "../../core/Reflection.hpp"
#include "../../math/Math.hpp"
#include "../../resource/Handle.hpp"

namespace esengine::ecs {

/**
 * @brief 2D light kind. Point uses the Transform position + radius falloff; Directional uses
 *        the Transform's forward with no attenuation; Ambient adds a flat term independent of
 *        normal/position.
 */
ES_ENUM()
enum class LightType : i32 {
    Point = 0,
    Directional = 1,
    Ambient = 2,
    Spot = 3,
};

/**
 * @brief A 2D light contributing to Lit-shaded materials.
 *
 * @code
 * auto& light = registry.emplace<Light>(e);
 * light.type = static_cast<i32>(LightType::Directional);
 * light.color = {0, 1, 0};   // green
 * light.intensity = 1.0f;
 * @endcode
 */
ES_COMPONENT(renderable=enabled)
struct Light {
    /** @brief Light kind: 0 = Point, 1 = Directional, 2 = Ambient (see LightType). */
    ES_PROPERTY(enum=LightType, tooltip="Point, Directional, Ambient, or Spot.")
    i32 type{0};

    /** @brief Light color, multiplied by intensity. RGBA for editor color-picker consistency
     *         with every other engine color (Sprite/Shape/Text); the alpha is unused (a light's
     *         strength is `intensity`, which can exceed 1 for HDR). */
    ES_PROPERTY(animatable)
    glm::vec4 color{1.0f, 1.0f, 1.0f, 1.0f};

    /** @brief Light strength multiplier. */
    ES_PROPERTY(animatable, min=0, tooltip="Brightness multiplier of the light.")
    f32 intensity{1.0f};

    /** @brief Point/Spot falloff radius in world units (ignored by Directional/Ambient). */
    ES_PROPERTY(animatable, min=0, shown_when=type:Point|Spot,
                tooltip="Falloff reach in world units (Point / Spot).")
    f32 radius{200.0f};

    /** @brief How far the light stays at full strength before it starts falling off,
     *         in world units. 0 (the default) falls off from the light itself; a
     *         value at or past @ref radius is a hard-edged disc. Ignored by
     *         Directional/Ambient, which have no distance to fall off over. */
    ES_PROPERTY(animatable, min=0, shown_when=type:Point|Spot,
                tooltip="Radius held at full strength before the falloff starts.")
    f32 innerRadius{0.0f};

    /** @brief The shape of the falloff between @ref innerRadius and @ref radius, as the
     *         power the linear ramp is raised to. 1 (the default) IS linear; above it
     *         the light pools near its centre, below it it reaches further and ends
     *         abruptly. Ignored by Directional/Ambient. */
    ES_PROPERTY(animatable, min=0, max=8, shown_when=type:Point|Spot,
                tooltip="Falloff shape: 1 = linear, higher pools near the light, lower reaches further.")
    f32 falloff{1.0f};

    /** @brief Falls off as the inverse square of the distance, in metres, as a real light does (Unreal's Use Inverse
     *         Squared Falloff, glTF's and three.js's point lights): `intensity` is then what reaches a surface one metre
     *         away, and @ref radius is only where it is let go — the last of it eased to nothing over the far end — so
     *         a lamp pools under itself rather than washing a room evenly. Off, the light ramps from @ref innerRadius to
     *         @ref radius by @ref falloff. Point and Spot only. */
    ES_PROPERTY(shown_when=type:Point|Spot,
                tooltip="Fall off as 1/distance² in metres (a real lamp): intensity is the light 1 m away, radius only where it ends.")
    bool inverseSquare{false};

    /** @brief How much of this light a shadow takes away, 0..1. 1 (the default) is the
     *         whole of it; 0.7 leaves a shadow that is dark rather than black, which is
     *         what a 2D scene with bounce light in it looks like. Applies to both kinds
     *         of shadow this light casts. */
    ES_PROPERTY(animatable, min=0, max=1, slider,
                shown_when=type:Point|Directional|Spot,
                tooltip="How much of this light its shadows remove (1 = all of it).")
    f32 shadowStrength{1.0f};

    /** @brief The lowest sprite layer this light reaches. A sprite on a layer below it is not lit by this light,
     *         which is what keeps a lamp inside a room from lighting the roof drawn over it (a layer above the
     *         lamp's @ref layerMax). The default, with @ref layerMax, is every layer. Ambient lights reach every
     *         layer whatever these say: they are the scene's own sky, not a lamp somebody stands beside. Only
     *         sprites carry a layer to test; a mesh, a tilemap, a particle or a skeleton is lit as it always was. */
    ES_PROPERTY(min=-128, max=127, step=1, optional, shown_when=type:Point|Directional|Spot,
                tooltip="The lowest sprite layer this light reaches (default: every layer).")
    i32 layerMin{-128};

    /** @brief The highest sprite layer this light reaches. See @ref layerMin. */
    ES_PROPERTY(min=-128, max=127, step=1, optional, shown_when=type:Point|Directional|Spot,
                tooltip="The highest sprite layer this light reaches (default: every layer).")
    i32 layerMax{127};

    /** @brief A texture whose ALPHA is this light's shape — a lantern's glow, a window's
     *         shaft. Drawn at the light's own place, turned by its Transform, and
     *         multiplied into what the light gives a pixel; the colour is not read,
     *         because a light's colour is the light's. Four shaped lights fit a frame,
     *         and past that a light lights without a shape. */
    ES_PROPERTY(asset = texture, shown_when=type:Point|Spot,
                tooltip="A texture whose alpha shapes this light (a cookie).")
    resource::TextureHandle cookie;

    /** @brief How big @ref cookie is drawn, in world units. 0 on an axis covers the
     *         light's own reach on it — a square of 2 × @ref radius — which is what a
     *         cookie drawn for this light almost always wants: a shape smaller than the
     *         reach cuts the light off, and one larger is trimmed by the falloff. */
    ES_PROPERTY(animatable, min=0, shown_when=type:Point|Spot,
                tooltip="Cookie size in world units; 0 = the light's own reach.")
    glm::vec2 cookieSize{0.0f, 0.0f};

    /** @brief Spot inner cone angle in degrees (full angle; fully lit inside). */
    ES_PROPERTY(animatable, min=0, max=180, unit="°", advanced, shown_when=type:Spot)
    f32 innerAngle{30.0f};

    /** @brief Spot outer cone angle in degrees (full angle; fades to dark by here). */
    ES_PROPERTY(animatable, min=0, max=180, unit="°", advanced, shown_when=type:Spot)
    f32 outerAngle{45.0f};

    /** @brief Shadow penumbra softness = the light source's half-extent in world units; 0 is a
     *         hard edge (default). It widens a penumbra the way a bigger source does, and the edge
     *         sharpens as a caster nears what it falls on. Read by the 2D shadow pass, which
     *         draws the shadow once per sample across a source that has width, and by a mesh
     *         shadow map only where the light HAS a position (Point/Spot). */
    ES_PROPERTY(animatable, min=0, shown_when=type:Point|Directional|Spot,
                tooltip="Shadow softness (light-source size); 0 = hard edge.")
    f32 shadowSoftness{0.0f};

    /** @brief How wide a Directional light's source is, as the angle it subtends — the full
     *         angular diameter in degrees. A length cannot say it: the source is infinitely far
     *         away, so only an angle carries a penumbra. The default is the real sun's 0.53;
     *         0 is a hard edge. Ignored by the types that have a position and a size. */
    ES_PROPERTY(animatable, min=0, max=90, unit="°", advanced, shown_when=type:Directional,
                tooltip="Angular size of a Directional light's source (the sun is 0.53); 0 = hard edge.")
    f32 sourceAngle{0.53f};

    /** @brief Directional-light shadow reach in world units: how far its shadows are carried
     *         from whatever cast them. 0 = a Directional light casts no 2D shadow (default).
     *         Ignored by Point/Spot, whose shadows reach as far as their own radius. */
    ES_PROPERTY(animatable, min=0, advanced, shown_when=type:Directional,
                tooltip="Directional shadow distance; 0 = no directional shadow.")
    f32 shadowDistance{0.0f};

    /** @brief Casts a shadow map over 3D meshes. Every type but Ambient can: a sun's map
     *         is cascades over the view, a Spot's its cone, a Point's a cube. Separate from
     *         @ref shadowDistance, which shadows ShadowCaster2D edges in the plane — one
     *         light can do both. Lights that stand somewhere claim tiles first. */
    ES_PROPERTY(shown_when=type:Point|Directional|Spot,
                tooltip="Cast a shadow map over 3D meshes (Directional, Spot, Point).")
    bool meshShadows{false};

    /** @brief Half-extent of the shadow map's world coverage: one map of this radius, centred
     *         on the middle of the meshes that cast shadows, and not moving with the camera.
     *         0 = cascades fitted to what the camera can see. Larger trades sharpness for reach. */
    ES_PROPERTY(min=0, advanced, shown_when=type:Directional,
                tooltip="Shadow map coverage radius; 0 = fit the view.")
    f32 shadowExtent{0.0f};

    /** @brief Be the sun of the frame's environment. The direction and strength come
     *         from the panorama, turned with it; @ref color and @ref intensity scale
     *         what it gives and the Transform's aim is not read. The environment then
     *         lights with its sky alone, since the sun is this light's to cast. A
     *         panorama without a sun leaves the light out of the frame, and says so. */
    ES_PROPERTY(shown_when=type:Directional,
                tooltip="Take direction and strength from the environment's sun, and light the sky without it.")
    bool followEnvironmentSun{false};

    /** @brief With @ref followEnvironmentSun, aim this light by its own Transform instead of
     *         by where the panorama's sun is. The panorama still gives the light its colour
     *         and strength and still loses its sun in the lighting; only the direction is
     *         the scene's. What a time of day needs: a sun that crosses the sky over a
     *         panorama that was photographed with it in one place. */
    ES_PROPERTY(shown_when=type:Directional, advanced,
                tooltip="With Follow Environment Sun: aim by this light's Transform, not by the panorama.")
    bool aimFollowedSun{false};

    /** @brief What this Ambient light IS, when it is more than one colour: a baked
     *         panorama's irradiance and reflection. Without one the light stays the
     *         flat term it has always been — the same lighting, at order zero.
     *         @ref color and @ref intensity scale it. Ignored by the other types;
     *         the first Ambient light that carries one is the frame's environment. */
    ES_PROPERTY(asset = environment, shown_when=type:Ambient,
                tooltip="Baked environment (.esenv) this Ambient light casts.")
    resource::EnvironmentHandle environment;

    /** @brief Turn the environment about +Y, in degrees. One number turns all three
     *         of it — sky, diffuse irradiance and specular reflection — because
     *         moving a reflection to the other side of a model means all three or
     *         none. Here rather than in the `.esenv` so one bake is reusable. */
    ES_PROPERTY(unit=deg, shown_when=type:Ambient,
                tooltip="Turn the environment about the up axis, in degrees.")
    f32 environmentRotation{0.0f};

    /** @brief Draw @ref environment as the background as well as reflecting it. Off by
     *         default, so a scene that adopts an environment for its lighting does not
     *         also acquire a sky it did not ask for. Ignored without one — and the
     *         camera still decides whether the background is drawn at all. */
    ES_PROPERTY(shown_when=type:Ambient,
                tooltip="Draw this environment as the sky behind the scene.")
    bool drawEnvironment{false};

    /** @brief What baked reflection probes show, scaled. A probe was baked under one
     *         sky, so it goes on showing that sky: a weather that darkens the scene
     *         turns this down so a rainy street does not mirror a sunny one.
     *         1 = as baked. Read from the frame's Ambient light. */
    ES_PROPERTY(min=0, shown_when=type:Ambient, advanced,
                tooltip="Scale what baked reflection probes show (1 = as baked).")
    f32 reflectionScale{1.0f};

    /** @brief What the light this Ambient light's environment gives a surface (its diffuse half, the sky's
     *         irradiance) is multiplied by, apart from what a surface reflects of it: a scene can be lit warmer
     *         or brighter than its sky looks, as Unreal's sky light is through its own colour. 1 = as the sky gives
     *         it. A flat or Hemisphere ambient light has nothing to reflect apart from its Color, so this is its
     *         environment's alone. */
    ES_PROPERTY(min=0, animatable, shown_when=type:Ambient,
                tooltip="Scale the light the environment gives surfaces, not what they reflect of it (1 = as the sky gives it).")
    f32 diffuseScale{1.0f};

    /** @brief The colour @ref diffuseScale's light is tinted by, authored as @ref color is. White = as the sky gives it. */
    ES_PROPERTY(animatable, shown_when=type:Ambient,
                tooltip="Tint the light the environment gives surfaces, not what they reflect of it (white = as the sky gives it).")
    glm::vec4 diffuseTint{1.0f, 1.0f, 1.0f, 1.0f};

    /** @brief How much colour baked reflections keep: 1 as baked, 0 grey. An overcast
     *         sky drains colour from what it lights, and from what a probe mirrors. */
    ES_PROPERTY(min=0, max=1, shown_when=type:Ambient, advanced,
                tooltip="How much colour baked reflection probes keep (0 = grey).")
    f32 reflectionSaturation{1.0f};

    /** @brief What baked INDIRECT light (a lightmap, a probe volume) is multiplied by. A bake
     *         holds the light of one moment, and a lightmapped surface takes all of its
     *         indirect light from it, so a scene that moves through a day or a weather scales
     *         and tints the bake here — the way it scales this light. 1 = as baked. Read from
     *         the frame's Ambient light. */
    ES_PROPERTY(shown_when=type:Ambient, advanced,
                tooltip="Multiply baked indirect light (lightmaps, probe volumes) by this colour (1 = as baked).")
    glm::vec4 bakedTint{1.0f, 1.0f, 1.0f, 1.0f};

    /** @brief Make this Ambient light two colours: @ref color from above, @ref groundColor
     *         from below, blended by which way a surface faces. Off is the flat term it has
     *         always been. A sky and the ground it bounces off, without baking a panorama;
     *         ignored where @ref environment is set, whose irradiance already says that. */
    ES_PROPERTY(shown_when=type:Ambient,
                tooltip="Light from above in Color, from below in Ground Color, blended by which way a surface faces.")
    bool hemisphere{false};

    /** @brief What a surface facing straight down receives with @ref hemisphere on. Scaled by
     *         @ref intensity, and authored the way @ref color is. */
    ES_PROPERTY(animatable, shown_when=type:Ambient,
                tooltip="The ambient colour a surface facing straight down receives (Hemisphere).")
    glm::vec4 groundColor{0.35f, 0.3f, 0.25f, 1.0f};

    /** @brief Disabled lights are skipped during collection. */
    ES_PROPERTY()
    bool enabled{true};
};

/**
 * @brief A box of baked irradiance: the light for what a bake cannot hold still.
 *
 * @details A draw standing inside takes its indirect light from the eight probes
 *          around it rather than from the frame's one environment. The box is
 *          AXIS-ALIGNED on the entity's world position; rotation and scale are not
 *          read, because a grid solved on world axes cannot be sampled on others.
 */
ES_COMPONENT()
struct LightProbeVolume {
    /** @brief The grid this box is read through. Invalid = nothing baked yet, which
     *         leaves everything inside lit exactly as it was. */
    ES_PROPERTY(asset = probeVolume, tooltip="Baked probe grid (.esprobes) filling this box.")
    resource::ProbeVolumeHandle probes;

    /** @brief Fill the box at run time from what a camera at its centre sees, all round: the walls as the lights light
     *         them now, the sky through the openings — Unreal's real-time Sky Light / Reflection Capture, and the interior
     *         capture a hand-built renderer takes. One grid point for the whole box, read in place of @ref probes. */
    ES_PROPERTY(tooltip="Fill this box at run time from a capture at its centre (the room as lit now), not from a bake.")
    bool capture{false};

    /** @brief Seconds between captures; 0 captures once. Each lit view of the room includes the last capture's fill, so a
     *         few captures are a few bounces. */
    ES_PROPERTY(min=0, shown_when=capture:true, tooltip="Seconds between captures (0 = once). Each one adds a bounce.")
    f32 captureInterval{0.0f};

    /** @brief Half the box's size, in world units, from the entity's position. */
    ES_PROPERTY(min=0, tooltip="Half the box this volume covers, from the entity's position.")
    glm::vec3 halfExtents{100.0f, 100.0f, 100.0f};

    /** @brief World units a bake puts between probes. What the BAKE reads — the
     *         grid it produced carries its own resolution, so changing this
     *         changes nothing until the next one. */
    ES_PROPERTY(min=1, tooltip="World units between probes the next bake lays down.")
    f32 spacing{100.0f};

    /** @brief Disabled volumes are skipped during collection. */
    ES_PROPERTY()
    bool enabled{true};
};

}  // namespace esengine::ecs