UI Element stencil

Well I managed to do it using stencil buffer and custom shader chunk that discards the invisible background around the text mesh.

Text:

mat = this.entity.element._text._material.clone();
this.entity.element._text._setMaterial(mat);
mat.chunks.endPS = `gl_FragColor.a = dAlpha;
                    gl_FragColor = applyMsdf(gl_FragColor);
                    if(gl_FragColor.a < 0.1)
                        discard;`;
mat.depthWrite = false;
mat.redWrite = mat.greenWrite = mat.blueWrite = mat.alphaWrite = false;
mat.stencilBack = mat.stencilFront = new pc.StencilParameters({
     zpass: pc.STENCILOP_INCREMENT
});

Background:

    mat = this.entity.element._image._material.clone();
    this.entity.element._image._material = mat;
    this.entity.element._image._updateMaterial(true);
    mat.stencilBack = mat.stencilFront = new pc.StencilParameters({
        func: pc.FUNC_EQUAL,
        ref: 0
    });
    mat.update();

Thanks for the help everyone, and I hope this helps someone in the future.

4 Likes