How can I draw a texture using a black/white image as a mask?

Started by
2 comments, last by Jerax 16 years, 10 months ago
I'm trying to create terrain like in Worms or Scorched Earth and I've found this excellent tutorial: http://www.indierover.com/ktb-tutorial-1-2d-randomly-generated-terrain-for-worms-style-game/ The author is creating a black/white image and then replacing the black spots with textures. How can I do this with DirectX? Thanks!
Advertisement
There are various ways to do it.

First of all, if you're creating the "black/white image" in Direct3D, then you don't really need to create it, but can draw it so that results can be used for the texture. Let's assume this for now, i.e., that you're drawing the "black" areas, and the white is clear background.

Option 1: Draw your image with the stencil buffer enabled (there were various posts about stencil recently, which would give you more details), setting the stencil where you draw. Then draw the texture only where the stencil is set. (In this option you're not actually creating an image).

Option 2: Clear your image to alpha=0 (transparent), draw on it with alpha=1. Use the resulting alpha to blend the texture.

I'm sure there are more ways to do it.

If you already have a B/W image, pre-created, load it and specify the white colour as a colour key (D3DXCreateTextureFromFileEx has that option), then use what's described above in option 2.

There are various other ways, using blending, but they'd work more easily if your image has white where you want to draw, and black where you don't.

[Edited by - ET3D on June 14, 2007 12:54:20 AM]
Yes, there are many ways to do this.
Most popular, the next: you create texture with alpha channel(one texture vs. two). In alpha channel you can write not only black\white colors and middle - gray values. With this, you can crate different transparent regions. But return to your task.
1. Create texture as I wrote.
2. Enable alphablending.
3. Set SRCBLEND to SRCALPHA and DESTBLEND to INVSRCALPHA.
4. Draw your image.
You could use alpha test rather than alpha blending if it's just black and white.

This topic is closed to new replies.

Advertisement