Tips to pre-compile shaders before they're needed?

I’m currently working on a project that displays two objects, one at a time. When all assets load, Object1 is rendered, and Object2 has visibility set to false. Upon user interaction, their visibility is swapped, so Object1 is not visible, and Object2 is visible, and so on.

My problem is that the shaders for Object2 don’t compile and don’t get passed to the GPU until JUST BEFORE being rendered for the first time, causing a visible “hiccup” in performance. I would much rather this to happen only once, at the beginning of the whole experience, and not in the middle while swapping objects.

Before Object2 is first rendered:
Ojbect1

After Object2 is first rendered, takes a second to create the new shaders in the GPU:
Object2

Is there a way to get all shaders, textures, buffers to the GPU before they’re first rendered? I’ve found a trick is to render objects at a small scale for one frame, or at very low opacity, but it’s a pain to do this for all objects that will be visible in the future. Is there a way to pre-compile, or to tell the engine to prepare the shaders to be ready for action in the future?

Ah, I believe I found the solution right after posting this question!

https://threejs.org/docs/#api/en/renderers/WebGLRenderer.compile
“Compiles all materials in the scene with the camera. This is useful to precompile shaders before the first rendering.”

1 Like

That’s the way to do it. I think it’s similar to calling render() on everything (both your objects visible) but with a color mask set to false (dont write anything). I’m not sure, but i think compile() addresses only the shaders, you might also have an issue with bufferData().

2 Likes

This is also a good approach.