Search code examples
autodesk-forgeautodesk-viewer

Changing the property and opacity of elements in Forge viewer


I know that, there are examples about this topic but I couldn't reach to any result. I have tried to change the material attributes with this:

  var instanceTree = viewer.model.getInstanceTree();
  var fragList = viewer.model.getFragmentList();
  instanceTree.enumNodeFragments( selectedDBID, (fragId) => {
    var material = fragList.getMaterial(fragId)

     if(material){
       material.opacity = 0.5
       material.transparent = true
       material.needsUpdate = true
     }
  });

  viewer.impl.invalidate(true,true,true)

and than I have tried this :

 var customMaterial = new THREE.MeshPhongMaterial
  ({
       opacity:    0.2,
       transparent: true
   });       
   this.viewer.impl.matman().addMaterial('myCustomMaterial', customMaterial, true);
   fragList.setMaterial(fragId, customMaterial);
   viewer.impl.invalidate(true,true,true)

or this :

  fragmentList.setMaterial(fragId, new THREE.MeshPhongMaterial( { opacity: 0.5 } ));

These are all changing the opacity when I check the material properties on Console. However nothing changes on the viewer and the component looks same.

Material type of selected elements is MeshPhongMaterial, viewer is latest version.

Does anyone have any idea ?


Solution

  • Not seeing any changes after you modify materials of objects in Forge Viewer is often caused by mesh consolidation - a performance optimization that combines multiple geometries into one to reduce the number of GPU draw calls. Try "unconsolidating" your model using viewer.model.unconsolidate(); and see if that helps.

    As far as customizing opacity of materials, note that this may yield unexpected results. When loading a model, Forge Viewer precomputes a special data structure for efficient traversal and rendering of all its elements, based on whether their material is fully opaque or semi-transparent. Changing the material later on does not update the data structure, and for example, rendering an object with semi-transparent material together with opaque objects can cause visual artifacts.