C++Builder Easily Cutout An Image With A Pixel Shader On Windows

FireWind

Свой
Регистрация
2 Дек 2005
Сообщения
1,957
Реакции
1,199
Credits
4,009
Easily Cutout An Image With A Pixel Shader On Windows
February 28, 2021 By Muminjon

In the previous example on Shader programming with Delphi FireMonkey, we created a texture feature to show images. So the material source manages the image bitmap.

In this sample, you will create this:
1614582849893.png
We can do this by adjusting the texture itself and set all pixels outside of the circle to transparent. This needs a change to the texture. By utilizing a transformed pixel shader, you could make the cutout for any image.

Pixel Shaders​

We can keep the same vertex shaders as the previous example. The pixel shaders have to be updated through:
C++:
// HLSL
 
Texture2D Texture;
SamplerState Sampler;
 
float4 main(float4 position: SV_POSITION,
  float2 texCoord: TEXCOORD0): SV_Target0
{
  // texCoord ranges from 0.0 to 1.0
  // For calculating a unit circle, remap to -1.0 to 1.0
  float2 locationFromCenter = (2.0 * texCoord) - float2(1.0, 1.0);
  
  // Calculate distance from center
  float distanceFromCenter = length(locationFromCenter);
  
  // A distance greater than 1 means we are outside the circle.
  // Return a transparent color in that case
  if (distanceFromCenter > 1.0)
    return float4(0.0, 0.0, 0.0, 0.0);
    
  return Texture.Sample(Sampler, texCoord);
}
1614582878180.png
In this part no need to update the materials at the Delphi side since all changes are controlled by the shader.