Search code examples
c#openglglslfragment-shaderopentk

Crop the top and bottom part of texture using opentk


I have a slider which have value ranges from zero to one. Now using the value of this slider , I want to crop the image from bottom to half of image And from top to half of image. I have done the first one (bottom crop) by resizing the height of GLControl. Not sure that this is the proper way to achieve this. But it is working fine. I have no idea for second option (cropping from top to half of image). Please help to get it. Attached is the outputs that I got when performing bottom crop with values 0,0.4,1.0 respectively.

 int FramereHeight = (glControl2.Height / 2) / 10; // crop the middle camera upto half of it's height                     
 if (NumericUpdownMiddleBottomCropVal != 0.0)//value ranges from zero to one
                        {
 glControl2.Height = glControl2.Height - Convert.ToInt32(NumericUpdownMiddleBottomCropVal * 10 * FramereHeight);
                        }
      public void CreateShaders()
    {
        /***********Vert Shader********************/
        vertShader = GL.CreateShader(ShaderType.VertexShader);
        GL.ShaderSource(vertShader, @"attribute vec3 a_position;
                                varying vec2 vTexCoord;
                                void main() {
                                vTexCoord = (a_position.xy+1)/2 ;  
                                gl_Position =vec4(a_position, 1);
                                }");
        GL.CompileShader(vertShader);

        /***********Frag Shader ****************/
        fragShader = GL.CreateShader(ShaderType.FragmentShader);
        GL.ShaderSource(fragShader, @"precision highp float;
  uniform sampler2D sTexture_2;varying vec2 vTexCoord; 
  uniform float sSelectedCropVal;
  uniform float sSelectedTopCropVal;uniform float sSelectedBottomCropVal;
          void main ()
         {
    if (abs(vTexCoord.y-0.5) * 2.0 > 1.0 - 0.5*sSelectedCropVal)
    discard;
     vec4 color = texture2D (sTexture_2, vec2(vTexCoord.x, vTexCoord.y));
     gl_FragColor =color;
   }"); GL.CompileShader(fragShader);
    }

Original Image When sSelectedCropVal=1.0


Solution

  • I assume that sSelectedCropVal is in range [0.0, 1.0].

    You can discard the fragments depending on the v corodiante:

    if ((0.5 - vTexCoord.y) * 2.0 > 1.0-sSelectedCropVal)
        discard;
    if ((vTexCoord.y - 0.5) * 2.0 > 1.0-sSelectedBottomCropVal)
        discard;
    

    Complete shader:

    precision highp float;
    uniform sampler2D sTexture_2;varying vec2 vTexCoord; 
    uniform float sSelectedCropVal;
    uniform float sSelectedTopCropVal;uniform float sSelectedBottomCropVal;
    
    void main ()
    {
        if ((0.5 - vTexCoord.y) * 2.0 > 1.0-sSelectedCropVal)
            discard;
        if ((vTexCoord.y - 0.5) * 2.0 > 1.0-sSelectedBottomCropVal)
            discard;
    
         vec4 color = texture2D(sTexture_2, vTexCoord.xy);
         gl_FragColor = color;
    }