The problem of GLTFLoader with InstancedMesh

I want to use instancedMesh() to load a GLB model, but many meshes and materials are under the GLB model.
Each mesh and material must be loaded.
Want to ask if there is a way to turn each mesh into an instancedMesh object to efficiently manage the position of each count?

Have you had a look at the official example for this here I’ve not inspected the model to check if its multiple parts or multi material but essentially you can merge geometries on all parts that share the same matetial…

i don’t think there’s anything. models rarely share the same material, practically nothing on sketchfab does. it’s always a bunch of geometries and materials, no texture atlas is shared between them. you may be able to merge geometries, but it will limit what you can later do with the model.

the only place where it exists is the react + three eco system. see

there’s a tool called gltfjsx that uses gltf-transform to dedupe the geometries, all similar geometries now refer to a single geometry. it then traverses everything to find geometry+ material pairs and builds an index of instanceable meshes and drops it into drei/Merged.

here’s a live example GLTF auto instances - CodeSandbox

2 Likes

Would like to ask if gltf-transform has a similar sample code?

If you have a GLB model that contains many repetitions of the same mesh(es) then glTF Transform can detect that, consolidate any redundant data, and (optionally) add the EXT_mesh_gpu_instancing extension causing GLTFLoader to create THREE.InstancedMesh objects. Typical usage in the CLI would look something like this:

# install
npm install --global @gltf-transform/cli

# help
gltf-transform --help

# deduplicate and instance
gltf-transform dedup in.glb out.glb
gltf-transform instance out.glb out.glb

Or there’s a Node.js or Web-friendly scripting API for this too.

If you just have a GLB containing one example of the thing you want to repeat throughout the scene, though, that’s probably out of glTF-Transform’s wheelhouse. R3F is good for that, for vanilla three.js you’d have to deconstruct the scene a bit and I don’t know of general-purpose examples for that.

I put this example together, not sure if it helps but essentially it pushes all parts of the gltf to an array and creates an instance mesh for each part, setting the positions from a fixed array of vector3’s, not sure this is the most performant way but the only way I could see possible, updating the positions is also a bit tricky but works if the positions don’t need dynamically updating…

2 Likes