             segmentStartPos_eye, endPosCut_eye, fragmentColor);
         finalColor = finalColor + fragmentColor * (1.0f - finalColor.a);
       }
-      position = fromEyeToNdcSpace(endPos_eye);
-      outputColor = clamp(finalColor, vec4(0.0), vec4(1.0));
+      setPositionAndDepthFor(layerIndex, endPos_eye);
+      setColorForLayer(layerIndex, clamp(finalColor, vec4(0.0), vec4(1.0)));
       finalColor = vec4(0);
       fragmentColor = vec4(0);
       segmentStartPos_eye = endPosCut_eye;
+
+      ++layerIndex;
     }
 
     if (activeObjectCount > 0)

  return ndcPos / ndcPos.w;
}

void setPositionAndDepth(in vec4 positionInEyeSpace)
{
  if (position.w == POSITION_NOT_SET)
  {
    vec4 ndcPos = fromEyeToNdcSpace(positionInEyeSpace);
    gl_FragDepth = ndcPos.z;
    position = ndcPos;
  }
  else if (position2.w == POSITION_NOT_SET)
  {
    vec4 ndcPos = fromEyeToNdcSpace(positionInEyeSpace);
    position2 = ndcPos;
  }
}

void setColorForLayer(int layerIndex, vec4 color)

    finalColor = blend(finalColor, nextFragment.color);
    if (nextFragment.color.w > alphaThresholdForDepth)
    {
      setPositionAndDepthFor(layerIndex, nextFragment.eyePos);
    }
  }

  finalColor = clampColor(finalColor);

  if (layerIndex != layerCount - 1)
  {
    setColorForLayer(layerIndex++, finalColor);
  }
  else
  {
    setColorForLayer(layerIndex++, blend(finalColor, vec4(backgroundColor, 1.0)));
  }

  for (; layerIndex < layerCount; ++layerIndex)
    setColorForLayer(layerIndex, vec4(backgroundColor, 1));
}

