Search code examples
three.js3daframegltf

Can I put a THREE.js material on a gltf model?


Im currently working on my portfolio in A-frame. I'm trying to change the material of the objects to a wireframe material, i'm using the wireframe material (MeshBasicMaterial) of THREE.js to do that. If I put this material on objects like "a-box" or "a-sphere" it works, but i need to put this wireframe material on my 3D gltf model. Is this possible?

This is my script to call the material:

AFRAME.registerComponent('wireframe', {
             dependencies: ['material'],
             init: function () {
             this.el.components.material.material.wireframe = true;
                }
            });
<a-box position="-1 0.5 -3" rotation="0 45 0" material="color: blue" wireframe></a-box>

Solution

  • It is possible to modify the material on a gltf. One way to do it is to drill into the THREEjs level of the mesh inside the gltf, and create a new material and assign it a wireframe property.

     AFRAME.registerComponent('tree-manager', {         
              init: function () {
                let el = this.el;
                let comp = this;
                let data = this.data;
                comp.scene = el.sceneEl.object3D;  
                comp.counter = 0;   
                comp.treeModels = [];
                comp.modelLoaded = false;
    
                // After gltf model has loaded, modify it materials.
                el.addEventListener('model-loaded', function(ev){
                  let mesh = el.getObject3D('mesh'); 
                  if (!mesh){return;}
                  //console.log(mesh);
                  mesh.traverse(function(node){
                     if (node.isMesh){  
                       let mat = new THREE.MeshStandardMaterial;
                       let color = new THREE.Color(0xaa5511);
                       mat.color = color;
                       mat.wireframe = true;
                       node.material = mat;                  
                     }
                  });
                  comp.modelLoaded = true;
                });   
              }
            });
    
    <a-entity id="tree" gltf-model="#tree-gltf" scale="5 5 5"  tree-manager></a-entity>
    

    Here is a glitch that shows how.