How do I add multiple shaders to a Mesh Object

Hi, I’m new to three.js and am developing a 3D model display project where I have to add multiple effects (like adding a picture watermark, or a random polygon mark) using shader materials. I can easily replace the mesh’s original material with a ShaderMaterial if I only have to apply one shader. But since whether an effect is applied or how many effects are to apply is decided by the user, I can’t write all them in one shader.
I’ve considered using string concat to add additional code to one shader program, but that may cause problems if some part of the code is complex.
Is there a better way to do this? Thank you.

You can add multiple materials to a single geometry by adding BufferGeometry.groups. Normally groups are used to render different parts of a geometry with different materials. However, group definitions can overlap so it is possible to add multiple materials on top of each other. Check out the following demo which adds two diffuse textures on a plane geometry.

However, if you need more control over how different effects are combined or composed, consider to use a single shader material and use GLSL defines in order to control whether a certain shader code block is executed or not.

1 Like

Thanks for the reply. That looks good. I just wonder if there would be performance issues since it looks like you “copied” the geometry and applied a single material to each of them?

The groups approach definitely affects performance since you draw the plane twice (with separate draw calls). The combined shader approach is faster.