Making masks with shading nodes that accounts camera ray
Solution

The mask effect can be achieved with rendering objects in different scenes and combining them in compositor after.

Compositing with Eevee:



Compositing with Cycles: