Gltf / useGLTF

Summary

A convenience hook that uses useLoader and GLTFLoader.

useGLTF hook

useGLTF<T extends string | string[]>(
  path: T,
  useDraco?: boolean | string = true,
  useMeshOpt: boolean = true,
  extendLoader?: (loader: GLTFLoader) => void
): T extends any[] ? (GLTF & ObjectMap)[] : GLTF & ObjectMap
GLTF, ObjectMap and GLTFLoader being defined as follows:
  • GLTF:

    export interface GLTF {
      animations: AnimationClip[]
      scene: Group
      scenes: Group[]
      cameras: Camera[]
      asset: {
        copyright?: string
        generator?: string
        version?: string
        minVersion?: string
        extensions?: any
        extras?: any
      }
      parser: GLTFParser
      userData: any
    }
    
  • ObjectMap being:

    type ObjectMap = {
      nodes: {
        [name: string]: THREE.Object3D
      }
      materials: {
        [name: string]: THREE.Material
      }
    }
    
  • GLTFLoader defined here

Basic

const gltf = useGLTF(url)

You can also preload a model:

useGLTF.preload(url)

draco (decompression)

It defaults to CDN loaded draco binaries (https://www.gstatic.com/draco/v1/decoders/) which are only loaded for compressed models.

But you can also use your own draco binaries by passing a path:

useGLTF(url, '/draco-gltf')

If you want to use your own draco decoder globally, you can pass it through:

useGLTF.setDecoderPath(path)
Note

If you are using the CDN loaded draco binaries, you can get a small speedup in loading time by prefetching them.

You can accomplish this by adding two <link> tags to your <head> tag, as below. The version in those URLs must exactly match what useGLTF uses for this to work. If you're using create-react-app, public/index.html file contains the <head> tag.

<link
  rel="prefetch"
  crossorigin="anonymous"
  href="https://www.gstatic.com/draco/versioned/decoders/1.5.5/draco_wasm_wrapper.js"
/>
<link
  rel="prefetch"
  crossorigin="anonymous"
  href="https://www.gstatic.com/draco/versioned/decoders/1.5.5/draco_decoder.wasm"
/>

It is recommended that you check your browser's network tab to confirm that the correct URLs are being used, and that the files do get loaded from the prefetch cache on subsequent requests.

extendLoader

If for example your model facecap.glb needs KTX2 textures, you can extendLoader:

import { KTX2Loader } from 'three-stdlib'
const ktx2Loader = new KTX2Loader()
ktx2Loader.setTranscoderPath('https://unpkg.com/three@0.168.0/examples/jsm/libs/basis/')

// ...

const { gl } = useThree()
useGLTF('facecap.glb', true, true, (loader) => {
  loader.setKTX2Loader(ktx2Loader.detectSupport(gl))
})

Gltf component

A Gltf component is also provided.

It takes the same props as useGLTF (except src which cannot be an array):

<Gltf src={url} />
<Gltf src={url} useDraco='/draco-gltf' ... />