Texture Alpha

Alpha data also can be supplied by textures. The texture must first be created, and then the alpha values added to it. To render with the texture, set it to a texture stage and select the appropriate texture stage operation and operands. When draw is called, the primitive is rendered with transparency.

These steps are illustrated in the following C# code example.


          [C#]
          
// Declare a Device.
Device device = null

// Declare a global texture variable.
Texture texture = null;

// Initialize the device.
.
.
.

// Create an alpha texture.
texture = new Texture(device, 128, 128, 0, 0, Format.A8R8G8B8, Pool.Managed);

LoadGradient();

The Texture class sets up everything by creating an empty texture. After the texture resource is created, LoadGradient is called to load the alpha channel.


          [C#]
          
protected void LoadGradient()
{
    uint yGrad, xGrad;
    uint dx = 128;      // width
    uint dy = 128;      // height

    uint[] buffer = new uint[dy * dx];

    GraphicsStream gs = null;

    try
    {
        gs = texture.LockRectangle(0, LockFlags.Discard);

        for (uint y = 0; y < dy; y++)
        {
            uint offset = y * dx;
            yGrad = (uint)(((float)y / (float)dx) * 255.0f);

            for (uint x = 0; x < dx;)
            {
                xGrad = (uint)(((float)x / (float)dx) * 255.0f);

                uint b = (uint)(xGrad + (255 - yGrad)) / 2 & 0xFF;
                uint g = (uint)((255 - xGrad) + yGrad) / 2 & 0xFF;
                uint r = (uint)(xGrad + yGrad) / 2 & 0xFF;
                uint a = (uint)(xGrad + yGrad) / 2 & 0xFF;

                buffer[offset + x] = ((a << 24) + (r << 16) + (g << 8) + (b));
                x++;
            }
        }
    
        gs.Write(buffer);
        texture.UnlockRectangle(0);
    }
    catch(InvalidCallException)
    {
        return;
    }
}

The alpha value is calculated based on the current pixel's relative x/y position within the texture size.

Next, assign the texture to a texture stage and set up the texture stage.


          [C#]
          
 // Assign texture.
device.SetTexture(0, texture)

// Texture stage states.
device.TextureState[0].ColorOperation = TextureOperation.Modulate;
device.TextureState[0].ColorArgument1 = TextureArgument.TextureColor;
device.TextureState[0].ColorArgument2 = TextureArgument.Diffuse;

device.TextureState[0].AlphaOperation = TextureOperation.Modulate;
device.TextureState[0].AlphaArgument1 = TextureArgument.TextureColor;
device.TextureState[0].AlphaArgument2 = TextureArgument.Diffuse;

This code results in a primitive with a transparency gradient. The gradient is transparent where x = 0, and opaque where x is its maximum value.

Show: