Use material from GLB in custom shader

I’m loading a GLB mesh with GLTF loader and I’m processing the call back with the following function:

function processgltf(gltf) {
    gltf.scene.traverse(function (child) {
        if (child.isMesh) {
            var geometry = child.geometry;
            var material = child.material;

I would like to use a custom fragment shader (with ShaderMaterial). I would therefore need to use a 2DSampler. My question is the following:

Is there a way to instanciate a 2DSampler referencing the texture embbeded in the GLB ?

The loader does not return the textures separately so there is no easy way to access them. One approach is to traverse through gltf.scene, filter out all meshes and then access the respective materials. The code you have posted does already show how this is done. You just have to select the correct textures form the materials and then assign them to the corresponding uniforms of your shader material.

1 Like

You could also do this:

new GLTFLoader()
  .load( 'model.glb', async ( gltf ) => {
    const textures = await gltf.parser.getDependencies( 'texture' );
  } );

That will provide every texture the original glTF file contains, but note that the various meshes in the three.js scene might have clones of these textures (if, for example, a texture needed to be cloned to apply a UV transform).

If your model contains different meshes with different textures, traversing the scene and modifying one object at a time would be better than the approach I suggest above.

1 Like

Thanks, but I didn’t get how how to retrieve the texture from child.material . I’m following the example I found here, but with this mesh, the field is null. Which field in the material structure should I use ?

Well, that depends. Usually you want to go for which represents the diffuse map of the material.