Implemented logic with masks and stencil buffer