Using NodeMaterial buildId to reduce shader compile times for identical node trees?

I’m programatically creating NodeMaterials with different node branches depending on desired material settings. This allows creating custom materials that can still integrate with Babylon.js core shader features (PBR, lights, shadows etc) without having to worry about conflicts in GLSL code / uniform names etc.

However, if a model has lots of materials (for example 100) then compiling shaders for that many NodeMaterials can be extremely slow (tens of seconds) especially on browsers that don’t support KHR_parallel_shader_compile extension.

However, there seems to be a buildId property, so lets say I do this:

nodeMaterial.buildId = *generate hash based on node tree structure*;
const updateBuildId = false;, updateBuildId);

Now the shader is only compiled for unique node tree configurations. So if out of 100 materials only 5 will have unique node tree then only 5 shaders need to be compiled. This seems to work.

Anyway. I’m asking here to get confirmation that this is what the buildId is intented for? Or am I abusing the system and there may be issues later down the line? Or are there any other things that I need to do to make this work reliably?

I am not sure if this is helpful as well: NodeMaterial | Babylon.js Documentation - there is a second argument to .clone for node materials only that shares the effect and skips the time generating it. I don’t think you can skip forceCompilation though, would love to know if you can !

This comes from a similar post to yours How to stop NodeMaterial from generating same effects when not needed and save compilation time from a while back where messing with buildId could also produce the same outcome as the new argument.

Thanks, that second link was very helpful. :+1:

Looks like the buildId setting was exposed specifically for a case similar to mine. So I’m hopeful that I can keep using it to solve the slow shader compile issue without too many issues in the future.

NodeMaterial could probably be made to automatically calculate buildId based on the generated shader code + uniform arrays. That way identical node setup shaders would get cached automatically without manual buildId tricks. But regardless, looks like I should be able to use manual buildId for now. :slightly_smiling_face:

Hi @MiikaH just checking in, was your question answered?

It was indeed.

1 Like