How to combine lights in a GLSL shader

Oscar de la Hera Gomez
Two flowers that represent ReactJS and ThreeJS with the text "Combining Lights in a GLSL Shader" beneath them.

Create a shader that takes in multiple lights as uniforms. Then, add up their properties to determine the combined final result.

In order to combine, or mix lights, in GLSL you must write a shader that takes in the lights as uniforms and determines the visual outcome by adding up the properties of the lights in the fragment shader.

An example solution of a shader that renders a point light and a spotlight can be found can be found on the tutorial/three-js/light-shaders branch of our Open Source React, Typescript & ViteJS Starter Project.

To clone this project, paste the code found below in Terminal.

git clone git@github.com:delasign/reactjs-3js-vitejs-starter-project.git

Step One: Create shaders for individual lights

A screenshot of Chrome showing the Spot Light in action.

Use our guide below to create the necessary functionality for ambient lights, directional lights, point lights and spotlights.

Step Two: Write the Shader

A screenshot of VSCode showing the shader that we wrote that combines a point light and a spotlight. The code is available in the repository linked above.

Create a vertex.glsl and fragment.glsl file for your shader.

This shader should make use of the functionality created in Step One and add up the properties of the lights that are passed in as uniforms.

If you wish to have multiple lights of the same type, we recommend that you pass them in as an array and add them up using a for loop.

We recommend that you place these files under a folder within a shaders folder.

Step Three: Create a Scene

A screenshot of VSCode showing a scene that uses a point light, a spot light. These properties are passed into the shader as uniforms.

Create a scene that makes use of the vertex and fragment shader that you created in Step Two.

Step Four: Test

A screenshot of Chrome that shows a plane which has a point light and a spot light. On the top right there are dat.gui elements that allow you to alter the lights in real-time.

Run the code and make sure that everything works as expected.

If you wish to include dat.gui sliders like we have, consult the tutorials below.

Looking to learn more about ReactJS and ThreeJS ?

Search our blog to find educational content on learning how to use ReactJS and ThreeJS.

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details