drei
drei copied to clipboard
useVariants hook to use KHR Material Variants
Why
The KHR Material Variants GLTF Extension allows you to set multiple materials on multiple meshes within a single GLTF instance. This allows you to create many different versions of objects inside a single gltf file and set a global state object to switch between them.
This is supported within threeJS core: Here
What
This hook takes the returned GLTF object from the standard loader or loaders like useGLTF
const gltf = useGLTF('model.glb');
const { activeVariant, setVariant, variants, materials } = useVariants(gltf);
activeVariant
is the string name of the current variant
setVariant
takes the string name input of the variant object
variants
is an array of of variants that look like { name: 'variantName' }
( NOTE: I was originally going to simplify this to just be the variant names, but talking with Don it would be possible to add data to variant objects that could be useful. Leaving it this way makes that data accessible)
materials
This is less commonly used but is the actual materials array from the GLTF. apps like GLTFJSX actually struggle with gltf material lists and can accidentally merge them or mess them up. Because we are already deep into the GLTF I added this to help me pull them out and read them if needed. It will probably be ignored by most.
You can set the variant using the setVariant
method or as an input to the hook itself.
This makes things convienent when the switching logic happens outside the component.
Using setVariant()
const gltf = useGLTF('model.glb')
const { setVariant } = useVariants(gltf)
useEffect(() => {
setVariant(props.variant)
}, [props.variant])
Using direct hook input:
const gltf = useGLTF('model.glb')
useVariants(gltf, props.variant)