Search code examples
autodesk-forgeautodesk-viewer

Set transparent for specific element


I want set transparent for specific element, i follow this code:


        var instanceTree = this.viewer.model.getInstanceTree();
        var fragList = this.viewer.model.getFragmentList();
        this.listElement.forEach(element => {
            instanceTree.enumNodeFragments(element, (fragId) => {
                console.log(element.material)
                var material = fragList.getMaterial(fragId)
                if (material) {
                    material.opacity = value;
                    material.transparent = true;
                    material.needsUpdate = true;
                }
            });
        });
        this.viewer.impl.invalidate(true, true, true);

but it overide for all elements have that material. How can i set for selected element? Appreciate any comments.

UPDATE 1: i found go around way is clone main material than register it with different name:

                    var newMaterial = material.clone();
                    const materials = this.viewer.impl.matman();
                    materials.addMaterial('mymaterial',newMaterial,true);
                    fragList.setMaterial(fragId,newMaterial);
                    newMaterial.opacity = value;
                    newMaterial.transparent = true;
                    newMaterial.needsUpdate = true;

but effect is not what i want, it has different color and when set transparent i can only see a couple object behind it enter image description here

enter image description here

enter image description here


Solution

  • You can create your own, custom THREE.js material and assign it to the fragment using fragList.setMaterial(fragId, material).

    For more information on using custom materials or shaders, see https://forge.autodesk.com/blog/custom-shader-materials-forge-viewer.

    EDIT:

    Regarding the visual anomalies (for example, when you only see some of the objects behind something semi-transparent), this is a known problem, unfortunately with no clear solution. When the Forge Model Derivative service creates an SVF file to be viewed in Forge Viewer, the individual scene elements are stored in a data structure optimized for fast traversal, depending on whether they are semi-transparent or fully opaque. This data structure is fixed, and so unfortunately, when you take an object that was originally fully opaque, and you make it semi-transparent, it will most likely be rendered in a wrong order...