refreshBoundingInfo called every time an InstancedMesh is created, even if not needed

We create and destroy instances all the time with high frequency (hundreds of avatars moving in and out of high fidelity ranges, and so on), and the InstancedMesh we use for this have mesh.doNotSyncBoundingInfo = true and mesh.alwaysSelectAsActiveMesh = true, since anything else is too costly.

Every time we create an InstancedMesh, in its constructor this.refreshBoundingInfo(true, true) is called ( Babylon.js/packages/dev/core/src/Meshes/instancedMesh.ts at aeec5b9613b6d15942860ae6aba11b6792900b97 · BabylonJS/Babylon.js · GitHub), which is very costly, especially since it can happen several times per frame. We never use this bounding info and it’s identical for all instances (bounding info of a proto mesh), since our displacement happens entirely in a vertex shader.

We’ve now approached this by mocking the InstancedMesh.prototype.refreshBoundingInfo while we create our instances, and then restoring the original function when done:

InstancedMesh.prototype.refreshBoundingInfo = function () {
  return this;
};

It works well, despite the prototype mangling. We do wrap the mocking in a try { } catch { } finally { }, so it’s not possible for the mocked function to stick, even if a runtime error occurs while it’s mocked. Does anyone see any additional side effects/issues with this approach? Thanks!

2 Likes

I faced a quite similar issue with Gaussian Splatting a while ago.
Costly Bounding infos I wanted to take care myself.
It ended up like this : Babylon.js/packages/dev/core/src/Meshes/GaussianSplatting/gaussianSplattingMesh.ts at aeec5b9613b6d15942860ae6aba11b6792900b97 · BabylonJS/Babylon.js · GitHub

and no need to override prototype functions

Unless I’m missing something I think the key difference here is that we’re using an InstancedMesh, which calls this.refreshBoundingInfo in its constructor, and if bounding info is missing (which it is when it’s a new instance), no amount of isLocked will help: Babylon.js/packages/dev/core/src/Meshes/instancedMesh.ts at aeec5b9613b6d15942860ae6aba11b6792900b97 · BabylonJS/Babylon.js · GitHub