GLTF loader to JSON loader

Hello.

I’m trying to update an old script (rev. 69) which uses the JSON loader. I’ve been able to implement LegacyJSONLoader and it works fine (although the rest of the script has many issues).

But I’d rather implement the GLTF loader. The first difference I notice is that, while the JSON loader returns one geometry and an array of materials, the GLTF loader doesn’t. And the script requires that single geometry.

So, I’m trying this:

new THREE.GLTFLoader().load(url, function(data) {
    var json=data.scene.toJSON(),
        geo=new THREE.Geometry();
    for(var i=0;i<json.geometries.length;i++) geo.merge(json.geometries[i]);
    //...continue with the old method using geo and json.materials
});

But, although it doesn’t fail, the model isn’t loaded or it’s created empty.

I could traverse data.scene to extract the mesh and then use its geometry, but a GLTF file can contain multiple meshes. That’s why I tried to merge them all.

Is there any simple way to make the two loaders compatible? Without rewriting the whole script.

Thank you.

You probably do not want to be calling scene.toJSON(). That converts native threejs objects (like THREE.Geometry) into plain JSON objects, which are meant for saving to storage and not for use at runtime. For more information on what the method is returning, see the GLTFLoader docs. The data.scene object is a THREE.Scene instance, and you can traverse it to find its geometries:

var geometries = [];
data.scene.traverse((o) => {
  if (o.isMesh) geometries.push(o.geometry);
});

However, if the glTF model contains multiple meshes, there might be a good reason for that. Are you sure you need to merge them into a single geometry? If so, you will want to use BufferGeometryUtils.mergeBufferGeometries(). The old Geometry class is no longer supported in many situations, and all the new loaders return BufferGeometry instead.