Lighting Up Compose: Inside Modifier.illuminate and the New Lights API

skydovesJaewoong Eum (skydoves)||21 min read

Lighting Up Compose: Inside Modifier.illuminate and the New Lights API

If you have ever faked lighting in Compose, you know the recipe: a Brush.radialGradient for the highlight, a darker gradient along one edge for depth, maybe a shadow underneath. It looks fine until something moves. Drag the card, change its corner radius, or move the "light" to the other side of the screen, and every gradient has to be recomputed by hand, because none of them know where the light is or what shape they sit on. Compose UI 1.14.0-alpha01 adds a lighting API that does this properly: you describe the lights, the material, and the shape, and Compose shades every pixel. So what actually happens when you add Modifier.illuminate to a composable?

In this article, you'll dive deep into the new Lights API, starting from a lit card you could drop into an app today and tracing inward: the three ingredients the API asks for, the draw pass that applies them, the AGSL shader that evaluates up to four lights per pixel, the signed distance function that invents a surface normal for every pixel, how a light finds its position relative to another composable, and why one of the two illuminate overloads moves a light without recomposing. The source quotes come from androidx.compose.ui:ui 1.14.0-alpha01, and the screenshots and counts come from a sample app run on Android emulators.

The fundamental problem: Gradients do not know about light

Here is the kind of code the new API replaces, a card with a hand placed highlight:

Box(
  Modifier
    .size(160.dp)
    .clip(RoundedCornerShape(24.dp))
    .background(Color(0xFF1E1E2E))
    .drawWithContent {
      drawContent()
      drawRect(
        Brush.radialGradient(
          colors = listOf(Color.White.copy(alpha = 0.35f), Color.Transparent),
          center = Offset(size.width * 0.25f, size.height * 0.2f),
          radius = size.minDimension * 0.6f,
        ),
      )
    },
)

The gradient is a picture of a highlight, not the result of a light. Its center, radius, and falloff are numbers you tuned for one size and one position. It has no idea that the card has rounded corners, so the "bevel" a designer asks for needs another gradient per edge. If two cards sit under the same light, you compute two different gradients that only look consistent because you did the trigonometry yourself.

A lighting model turns this around: you state where the light is and how the surface is shaped, and the shading follows, so moving the light moves every highlight at once.

A first lit card

A sample adapted from the official IlluminateSample is a good place to start. It lights a black 160 dp box, treated as a rounded rectangle for lighting, with one white point light above its top left corner:

Box(
  Modifier
    .size(160.dp)
    .background(Color.Black)
    .illuminate(
      lights = listOf(
        PointLight(
          color = Color.White,
          position = LightPosition.Local(DpOffset(x = 0.dp, y = 0.dp)),
          elevation = 48.dp,
          falloffRadius = 320.dp,
          intensity = 1f,
        ),
      ),
      surfaceMaterial = SurfaceMaterial.diffuse(Color.White).specular(Color.White, shininess = 32f),
      surfaceGeometrySpec = SurfaceGeometrySpec.convex(RoundedCornerShape(24.dp), thickness = 1.dp, bevelWidth = 12.dp),
    ),
)

To try it, note one build requirement first: the 1.14.0-alpha01 ui and foundation artifacts declare minCompileSdk=37 and minCompileMinorSdk=2 in their AAR metadata, so the app needs compileSdk 37.2, and the same metadata asks for AGP 9.4.0 or newer. Here is a variation of that card on an Android 17 (API 37) emulator, with a 22 dp bevel, the light 64 dp up, and the light placed over the card's upper left area on the left and exactly over its corner on the right:

image

On the left, the light sits over the card, so the specular term draws a round highlight under it and the bevel darkens on every side, because the curved band tilts away from a light that sits above the flat interior. On the right, the light sits over the corner, so the near bevel catches a glint and the far bevel falls into shadow. Nothing in the code describes those effects; they follow from the position of the light and the shape of the surface.

Three inputs go into that call:

  1. The lights: where light comes from, its color, and its strength.
  2. The surface material: how the surface reflects the light that reaches it.
  3. The surface geometry: what three dimensional shape the flat composable should pretend to have.

The three ingredients

Lights

Light has three concrete types, and the KDoc describes them by analogy: DirectionalLight for light "arriving from infinitely far away", PointLight for "a bulb at a fixed spot", and SpotLight for "a bulb that only lights a cone". Every light has a color and an intensity, and the two multiply: color.alpha * intensity scales the light's contribution, so a transparent color or an intensity of 0 contributes nothing, and values above 1 overdrive the light towards white.

  • DirectionalLight takes a direction vector that points from the surface towards the light. Only the ratio of the components matters. DirectionalLight.fromAngles(color, planeAngleDegrees, elevationDegrees, intensity) builds the same vector from two angles, where an elevation of 90 shines head on and 0 is level with the surface, which leaves it unlit.
  • PointLight sits at a position in the plane, elevation in front of it, and fades to zero at falloffRadius. A radius of 0 or less turns the falloff off.
  • SpotLight adds a targetOffset that aims the cone and a coneAngleDegrees half angle. Pixels outside the cone are not lit.

The constructors check little at runtime, mostly that their Dp and DpOffset values are specified: a PointLight or SpotLight with an unspecified elevation or falloffRadius throws an IllegalArgumentException, as does a SpotLight with an unspecified targetOffset.

Surface material

SurfaceMaterial describes three independent reflection components, and the KDoc names the models behind them: diffuse and specular "are calculated as per the Blinn-Phong reflection model", and fresnel "is calculated using Schlick's approximation".

  • diffuse\(color\) scatters light evenly and gives the surface its overall shading. It depends only on the angle between the surface and the light, not on where you look from.
  • specular\(color, shininess\) adds the tight highlight of a glossy surface. A larger shininess concentrates it into a smaller, sharper spot, and it must be positive.
  • fresnel\(reflectivity, intensity\) brightens the surface where it is seen at a grazing angle.

A component that is not set is disabled, so SurfaceMaterial.None "renders no lighting at all".

Surface geometry

The composable is flat, so SurfaceGeometrySpec tells the shader what shape to pretend it has:

  • flat\(shape, thickness\): a flat slab.
  • convex\(shape, thickness, bevelWidth\): a slab whose edges curve away from you across a band bevelWidth wide, like a pillow or a button.
  • concave\(shape, thickness, bevelWidth\): the same band curving the other way, like a dish.

thickness raises the surface towards the light. The KDoc for PointLight spells out the consequence: the light's height above the surface is elevation - thickness, so keep elevation larger than the thickness or the light ends up behind the surface.

The shape has a hard limit in this release. The SurfaceGeometrySpec KDoc says lighting "is currently implemented only for rectangles, and for rounded rectangles whose corners each have a circular radius", and anything else, including CutCornerShape, GenericShape, and elliptical corner radii, throws an IllegalArgumentException when the spec is resolved.

In the sample app, a CutCornerShape(16.dp) failed with this message: "SurfaceGeometrySpec does not support CutCornerShape(...), which produces a path based outline. Lighting is only implemented for rectangles and for rounded rectangles whose corners have circular radii." The message goes on to say that "custom Shape implementations are not supported", which is broader than the check itself: a custom Shape returning a rounded rectangle with circular corners lit without complaint, and the check rejects only path outlines and elliptical corners. Note when the exception arrives, too. It is thrown at draw time, when the spec is resolved against a real size, not when the modifier is created.

Inside the draw pass

Modifier.illuminate with a list of lights creates an IlluminationModifierNode, a DrawModifierNode that is also a GlobalPositionAwareModifierNode. Its draw function is short. Looking at the core of it in 1.14.0-alpha01:

override fun ContentDrawScope.draw() {
    drawContent()

    if (!LightShader.isSupported() || lights.isEmpty() || size.isEmpty()) return

    val coordinates = requireLayoutCoordinates()
    localLights.clear()

    lights.fastForEach { light -> localLights += with(light) { inLocalSpace(coordinates) } }

    var shader = lightShader
    if (shader == null) {
        shader =
            LightShader(
                lights = localLights,
                surfaceMaterial = surfaceMaterial,
                surfaceGeometrySpec = surfaceGeometrySpec,
                density = this,
                layoutDirection = layoutDirection,
                size = size,
            )
        lightShader = shader
    } else {
        shader.update(
            lights = localLights,
            surfaceMaterial = surfaceMaterial,
            surfaceGeometrySpec = surfaceGeometrySpec,
            density = this,
            layoutDirection = layoutDirection,
            size = size,
        )
    }
    paint.blendMode = blendMode
    shader.applyTo(paint)
    this.drawContext.canvas.drawRect(0f, 0f, size.width, size.height, paint)
}

The order of operations explains most of the API's behavior:

  1. Content first: drawContent() runs before anything else, so the lighting is a pass drawn on top of whatever the composable already draws. The blendMode parameter, SrcOver by default, decides how that pass is composited, and the KDoc warns that SrcOver "can occlude the underlying content", so text on a lit surface may need a different mode to stay legible.
  2. A silent fallback: if LightShader.isSupported() is false, the function returns after drawing the content. On Android that check is Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU, because the shader is a RuntimeShader, which needs API 33. Below that, the composable looks exactly as it would without the modifier.
  3. Positions resolved per draw: every light is converted into the lit composable's local coordinates on every draw, which is how a light can be defined relative to something else and still land in the right place.
  4. One shader per node, reused: the shader is created once and then updated, and the whole lighting pass is a single drawRect over the node's bounds.

On an API 31 emulator, the sample app's lit card was pixel identical to the plain card (0 of 538,204 pixels differed), and IlluminationScope.isSupported() returned false. The early return has a less obvious side effect: because it comes before the shader is built, the light count check and the shape check never run below API 33. The cases that throw on API 37, five lights or a CutCornerShape, GenericShape, or elliptical corner outline, all drew without a crash on API 31. If your test devices or emulators are all below API 33, a mistake that crashes on newer devices will pass every test.

The shader: Blinn-Phong for up to four lights

The Android LightShader is an AGSL program. The light uniforms are arrays sized by MAX_LIGHTS, which is LightShader.MaxLightsAllowed, exposed as IlluminationScope.MaxLightsAllowed, and the commit that added the shader describes it as evaluating "a Blinn-Phong and Schlick Fresnel lighting model for up to 4 lights". For each pixel, the shader first asks the geometry for a normal, then loops over the lights. The shader source is a Kotlin string template, so the excerpts below show it with the uniform names filled in. The part of the loop that runs once the light direction and attenuation are known, without the fresnel block, looks like this:

float nDotL = dot(normal, lightDir);
if (nDotL > 0.0 && attenuation > 0.0) {
    float3 lightRgb = uLightColors[i].rgb;
    float lightA = uLightColors[i].a * attenuation;

    if (uDiffuseEnabled == 1) {
        float w = uDiffuseColor.a * lightA * nDotL;
        rgb += uDiffuseColor.rgb * lightRgb * w;
        a += w;
    }

    if (uSpecularEnabled == 1) {
        float3 halfDir = safeNormalize(lightDir + viewDir);
        float specularFactor = pow(max(dot(normal, halfDir), 0.0), uSpecularShininess);
        float w = uSpecularColor.a * lightA * specularFactor;
        rgb += uSpecularColor.rgb * lightRgb * w;
        a += w;
    }
}

Reading it as a recipe:

  1. Diffuse is a dot product: nDotL is the cosine of the angle between the surface normal and the direction to the light. A surface facing the light gets the full contribution, a surface turned away gets none, and the if skips the light entirely when the surface faces away from it, which is what the KDoc means when it says the part of the surface where the normals face away from the light will not be lit by that light.
  2. Specular uses the half vector: Blinn-Phong compares the normal with the vector halfway between the light and the viewer, and raises the result to shininess. A higher exponent makes the cosine drop faster, which is why a larger shininess gives a smaller highlight.
  3. Fresnel uses Schlick's approximation: the next block computes pow(1.0 - saturate(dot(normal, viewDir)), 5.0) and blends it with the reflectivity. The brightening grows where the normal turns away from the viewer, but the term is also multiplied by nDotL and sits inside the same if, so it only shows up where the surface faces the light.
  4. Distance and cones are attenuation: for point and spot lights, attenuation starts from the intensity and is multiplied by a squared falloff, saturate(1.0 - length(toLight) / radius) squared, so brightness reaches zero at falloffRadius. A spot light then multiplies by step(uLightCutoffCosines[i], cosToFragment). A step is either 0 or 1, so the cone has a hard edge in this release, with no soft penumbra.

Two details make the result look right on screen. The light and material colors are converted to linear extended sRGB before upload, the math runs in linear space, and the final color goes back through fromLinearSrgb. And the shader returns premultiplied color with alpha equal to the summed contribution, clamped to 1, so a pixel that receives no light is fully transparent and leaves the content underneath untouched.

The fresnel detail is easy to miss in code and obvious on screen. With only fresnel(reflectivity = 0.04f) enabled and a directional light, the rim appears on the edges that face the light, and the opposite edges get nothing:

image

A convex card lit from the upper left lights its upper left edges, while a concave card, whose bevel tilts the other way, lights its lower right edges instead. With a head on light, the rim goes all the way around, faintly, and convex and concave render identically, since with the light head on, both nDotL and the fresnel factor depend only on the normal's z component, which both bevels share. The flat card gets no rim in any row, only an even brightening of a few levels, from the bare (30, 41, 66) to an average of (34.5, 45.0, 69.8) under the upper left light and (39.0, 49.6, 73.6) under the head on light, with each channel dithered by one level. The hard spot cone from the step is just as visible: a SpotLight aimed at the surface draws an elliptical pool with a sharp edge.

image

Inventing a normal for every pixel

The lighting math needs a surface normal per pixel, but a composable has no geometry. The answer is a second shader. Each SurfaceGeometrySpec resolves into a SurfaceGeometry that exposes a normal shader: a RuntimeShader whose output, for every pixel, is the normal in xyz and a coverage mask in a. The lighting shader receives it as a child shader, uniform shader uGeometryNormalShader, and calls eval on it per pixel. No normal map texture is ever allocated.

The normal shader starts from a signed distance function for a rounded rectangle, roundedRectSdf, which returns how far a pixel is from the outline: negative inside, positive outside. Pixels outside return an alpha of 0, and the lighting shader returns transparent for them, which is how the light stays inside the shape. For a convex or concave surface, the interesting part is the band along the edge. Looking at the beveled shader, with its uniform name filled in the same way:

float t = saturate((sdf + uBevel) / uBevel);
float angle = t * HALF_PI;
float3 normal =
    float3(tiltSign * outwardNormal\(edgeDelta, local\) * sin(angle),
           cos(angle) * nzSign);
return half4(float4(normalize(normal), 1.0));

t goes from 0 at the inner edge of the band to 1 at the outline, and the angle sweeps a quarter circle across it. At the inner edge the normal points straight at the viewer, (0, 0, 1), and at the outline it lies flat, pointing outwards for convex or inwards for concave. tiltSign is not a shader variable: the Kotlin template writes the literal 1.0 into the convex shader and -1.0 into the concave one. On the interior inside the band's inner edge, and everywhere on a flat surface, the normal is (0, 0, 1).

That has a practical consequence worth knowing before you tune anything. The shader's view direction is also (0, 0, 1). On the flat interior, every pixel has the same normal, so a DirectionalLight, which has the same direction everywhere, produces one uniform tint, and the fresnel term is at its minimum. On the emulator, a flat card under a directional diffuse light came out as one even tint averaging (125, 131.8, 146), with green dithered between 131 and 132, and working the shader's formula by hand for that card's colors gives (125.5, 131.8, 146.2):

image

So the shape of the lighting comes from two places only: the bevel band, where the normal changes, and position based lights, where the direction to the light changes from pixel to pixel. If a lit card looks flat, give it a bevel or move to a PointLight.

The normal shader is built once per resolved geometry and cached. BaseLightShader resolves a new geometry only when the spec, size, layout direction, or density changes, and it uploads lights and material again only when they differ from the last values it uploaded.

Where a light sits

Every light except DirectionalLight has a LightPosition, and there are three kinds:

  • Local\(offset\): measured from the top left of the composable being lit. The KDoc calls it "the cheapest option, as no coordinate conversion is required".
  • Global\(offset\): measured from the root of the composition, the same space as positionInRoot. Use it for one light that several composables should agree on.
  • Anchored\(state, offset\): measured from whichever composable state is attached to with Modifier.lightAnchor(state).

The conversion happens in Light.inLocalSpace, called from the draw pass you saw earlier. For an anchored light, the core of it is:

is LightPosition.Anchored -> {

    val anchor = position.state.coordinates
    if (
        anchor == null ||
            !anchor.isAttached ||
            !layoutCoordinates.isAttached ||
            !position.offset.isSpecified ||
            anchor.findRootCoordinates() !==
                layoutCoordinates.findRootCoordinates() // Not in the same hierarchy
    ) {
        unresolved()
    } else {
        localCopy(layoutCoordinates.localPositionOf(anchor, toPx(position.offset)))
    }
}

Modifier.lightAnchor is the publishing side. Its node implements onGloballyPositioned and writes the latest LayoutCoordinates into the LightAnchorState, and clears them on onUnplaced and onDetach. The lit composable reads those coordinates at draw time and converts the offset with localPositionOf. Three consequences follow from the code:

  1. Unplaced means dark: until the anchor has been placed, the light is unresolved and contributes nothing. The same happens when the anchor lives in another root, such as a Popup, a Dialog, or a separate ComposeView, because the root check fails.
  2. One anchor per state: a LightAnchorState tracks one composable. Attach the same state to two composables and it reports whichever was placed most recently, which the KDoc calls "rarely what was intended".
  3. Movement triggers a redraw, by two routes: LightAnchorState holds the anchor's coordinates in a snapshot state created with neverEqualPolicy(), and the anchor node writes it every time it is placed. The lit node reads that state inside draw(), so moving the anchor invalidates the draw of every composable lit by it. Moving the lit composable itself is covered by its own onGloballyPositioned, which calls invalidateDraw() whenever any of its lights is not Local. Local lights skip both, which is part of why they are cheaper.

In the sample app, one LightPosition.Anchored point light follows a "sun" composable, and six cards in a grid use the same anchored light. The cards never learn where the sun is; each one resolves the anchor in its own draw pass:

image

In its resting position, with the sun between cards 3 and 4, the two cards beside it get the brightest diffuse light and a glint on the bevel edge that faces it. The cards further away receive only a thin highlight on the bevel nearest the sun: the light reaches them at a shallow angle, so the flat interior, which faces the viewer, catches little of it, while the bevel band that tilts towards the sun catches much more. Falloff then dims the whole card with distance.

Two overloads, and why one redraws without recomposing

illuminate has a second overload that takes a block instead of a list. Its receiver, IlluminationScope, has three properties, lights, surfaceMaterial, and surfaceGeometrySpec, and every run of the block starts with all of them at their defaults. A light that follows an animated value looks like this:

val lightX by animateDpAsState(targetValue = if (expanded) 140.dp else 20.dp, label = "lightX")

Box(
  Modifier
    .size(160.dp)
    .background(Color.Black)
    .illuminate {
      lights = listOf(
        PointLight(Color.White, LightPosition.Local(DpOffset(lightX, 24.dp)), elevation = 48.dp, falloffRadius = 320.dp, intensity = 1f),
      )
      surfaceMaterial = SurfaceMaterial.diffuse(Color.White)
      surfaceGeometrySpec = SurfaceGeometrySpec.convex(RoundedCornerShape(24.dp), thickness = 1.dp, bevelWidth = 12.dp)
    },
)

lightX is a delegated state, so it is read where it is used: inside the block.

Looking at BlockIlluminationModifierNode, the block runs as the first thing in draw():

override fun ContentDrawScope.draw() {
    localIlluminationScope.reset()
    localIlluminationScope.block()

    drawContent()
    // ...same lighting pass as the list overload...
}

That placement matters in the same way it does for drawBehind { } or drawWithContent { }. State read inside the block is read during the draw phase, so a change invalidates only the draw phase of this layout node, with no recomposition or relayout. With the list overload, the lights are built in composition, so an animated light position recomposes the composable on every frame before the draw even starts.

The sample app animated a light's position for 120 frames both ways on the API 37 emulator, counting composable body executions with a plain counter in the body and draw passes with a counter in a draw modifier:

  • Block overload, state read inside the block: 0 body executions and 120 draws.
  • List overload, light built from the state in composition: 120 body executions and 120 draws.

Three runs of each gave the same counts, and neither overload measured or placed anything during the animation, so the difference is purely recomposition.

For anything that moves, such as a light following a finger, a scroll offset, or an animation, build the lights inside the block and read the animated values there.

Limits worth knowing before you ship

The API is alpha, and the current limits are explicit in the source:

  • API 33 and higher only: below that, IlluminationScope.isSupported() returns false and the content is drawn unchanged. The block still runs on every draw and the list overload still recomposes when its lights change, so the unlit path is not free. Treat lighting as an enhancement, never as the only signal of state.
  • At most four lights: a fifth light fails with "At most 4 lights are supported, but 5 were provided", again at draw time and only on API 33 and higher.
  • Rectangles and circular rounded rectangles only: other outlines throw at draw time, on API 33 and higher.
  • SurfaceMaterial.None still costs a pass: the sample's None card was pixel identical to the plain card, but the shader still runs and draws its transparent rectangle.
  • Hard spot cones: the cone edge is a step, with no soft falloff at the edge.
  • Local illumination only: the IlluminationScope KDoc is explicit that "other composables neither cast shadows onto the surface nor reflect light onto it". Each lit composable is shaded on its own.
  • Legibility: the default SrcOver blend can wash out text drawn underneath, so pick the blend mode with the content in mind.
  • Churn: a fourth change that adds a playground demo (c/4322707) is still in review, and names and parameters can change before beta. Pin the version and expect to revisit the code.

Conclusion

In practice, reach for Modifier.illuminate where a surface should respond to something: a card that brightens as a draggable light passes over it, a button whose bevel catches a light anchored to the user's finger, or a grid where every item agrees on one light. Drive anything that moves from the block overload, give the surface a bevel or a positioned light when you want visible shape, and test on API 33 or higher, since that is the only place the light count and the shape are validated. Then design the unlit version first, because every device below API 33 will see exactly that.

The interesting part of this API is how little it needed to add to Compose. There is no new rendering engine, only a draw modifier, two RuntimeShaders, and a few LayoutCoordinates conversions, all built from pieces you can already use. A light is just another input to the draw phase, and once you see it that way, lighting becomes a property you declare, like a shape or a color, instead of a picture you paint by hand.

As always, happy coding!

— Jaewoong (skydoves)