Skip to content

Instantly share code, notes, and snippets.

@cdata
Created November 8, 2017 23:26
Show Gist options
  • Save cdata/f2d7a6ccdec071839bc1954c32595e87 to your computer and use it in GitHub Desktop.
Save cdata/f2d7a6ccdec071839bc1954c32595e87 to your computer and use it in GitHub Desktop.
A quick hack to clone a Three.js GLTF scene without re-loading or re-parsing the source.
const cloneGltf = (gltf) => {
const clone = {
animations: gltf.animations,
scene: gltf.scene.clone(true)
};
const skinnedMeshes = {};
gltf.scene.traverse(node => {
if (node.isSkinnedMesh) {
skinnedMeshes[node.name] = node;
}
});
const cloneBones = {};
const cloneSkinnedMeshes = {};
clone.scene.traverse(node => {
if (node.isBone) {
cloneBones[node.name] = node;
}
if (node.isSkinnedMesh) {
cloneSkinnedMeshes[node.name] = node;
}
});
for (let name in skinnedMeshes) {
const skinnedMesh = skinnedMeshes[name];
const skeleton = skinnedMesh.skeleton;
const cloneSkinnedMesh = cloneSkinnedMeshes[name];
const orderedCloneBones = [];
for (let i = 0; i < skeleton.bones.length; ++i) {
const cloneBone = cloneBones[skeleton.bones[i].name];
orderedCloneBones.push(cloneBone);
}
cloneSkinnedMesh.bind(
new Skeleton(orderedCloneBones, skeleton.boneInverses),
cloneSkinnedMesh.matrixWorld);
}
return clone;
}
@dahngeek
Copy link

For anyone that found this, you might need to add THREE. before the Skeleton part
like this:

new THREE.Skeleton(orderedCloneBones, skeleton.boneInverses),

@Forgere
Copy link

Forgere commented Mar 30, 2021

awesome

@ben-xD
Copy link

ben-xD commented Jan 1, 2023

I didn't need this, and used gltf.scene.scale.set instead which is much simpler:

const loader = new GLTFLoader();
        const tree = await loader.loadAsync("objects/Tree_1.gltf");
        const treeScale = 0.2;
        tree.scene.scale.set(treeScale, treeScale, treeScale);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment