Search code examples
c#xnatextures

Issue with transparent texture on 3D primitive, XNA 4.0


I need to draw a large set of cubes, all with (possibly) unique textures on each side. Some of the textures also have parts of transparency. The cubes that are behind ones with transparent textures should show through the transparent texture. However, it seems that the order in which I draw the cubes decides if the transparency works or not, which is something I want to avoid. Look here:

cubeEffect.CurrentTechnique = cubeEffect.Techniques["Textured"];

Block[] cubes = new Block[4];
cubes[0] = new Block(BlockType.leaves, new Vector3(0, 0, 3));
cubes[1] = new Block(BlockType.dirt, new Vector3(0, 1, 3));
cubes[2] = new Block(BlockType.log, new Vector3(0, 0, 4));
cubes[3] = new Block(BlockType.gold, new Vector3(0, 1, 4));


foreach(Block b in cubes) {
    b.shape.RenderShape(GraphicsDevice, cubeEffect);
}

This is the code in the Draw method. It produces this result: the first image

As you can see, the textures behind the leaf cube are not visible on the other side. When i reverse index 3 and 0 on in the array, I get this: correct image

It is clear that the order of drawing is affecting the cubes. I suspect it may have to do with the blend mode, but I have no idea where to start with that.


Solution

  • You are relying on depth buffering to achieve occlusion. This technique only works for opaque objects.

    To achieve correct occlusion for a scene containing transparent objects:

    1. Set DepthBufferEnable and DepthBufferWriteEnable to true

    2. Draw all opaque geometry

    3. Leave DepthBufferEnable set to true, but change DepthBufferWriteEnable to false

    4. Sort alpha blended objects by distance from the camera, then draw them in order from back to front

    Extract from Depth sorting alpha blended objects by Shawn Hargreaves