问题描述
如何为 Direct3D 中的简单顶点对象添加透明度?
我使用了这里的信息但没有结果: https://docs.microsoft.com/ru-ru/windows/win32/direct3d9/vertex-alpha
我这样初始化设备:
PresentParameters presentParams = new PresentParameters();
presentParams.SwapEffect = SwapEffect.Discard;
presentParams.DeviceWindowHandle = this.Handle;
presentParams.BackBufferFormat = Format.A8R8G8B8;
presentParams.PresentFlags = PresentFlags.LockableBackBuffer;
presentParams.BackBufferWidth = this.ClientSize.Width;
presentParams.BackBufferHeight = this.ClientSize.Height;
presentParams.Windowed = true;
var device = new Device(_direct3d,DeviceType.Hardware,this.Handle,_createFlags,presentParams);device.SetRenderState(RenderState.Lighting,false);
// ..tried different variations of flags here with no result..
device.SetRenderState(RenderState.DiffuseMaterialSource,ColorSource.Color1);
var surface = device.GetBackBuffer(0,0);
device.Clear(ClearFlags.Target | ClearFlags.ZBuffer,Color.Black,1.0f,0);
顶点类声明:
[StructLayout(LayoutKind.Sequential)]
public struct ColoredVertex : IEquatable<ColoredVertex>
{
public Vector3 Position { get; set; }
public int Color { get; set; }
public static VertexElement[] Format
{
get
{
return new VertexElement[] {
new VertexElement(0,DeclarationType.Float3,DeclarationMethod.Default,DeclarationUsage.PositionTransformed,0),new VertexElement(0,12,DeclarationType.Color,DeclarationUsage.Color,VertexElement.VertexDeclarationEnd
};
}
}
public ColoredVertex(Vector3 position,int color)
: this()
{
Position = position;
Color = color;
}
然后我画图元。 颜色包含第二个三角形的 alpha 值为 50,所以我希望三角形是透明的......但没有
_device.BeginScene();
var colorN1 = Color.FromArgb(255,100,100);
var triangleN1 = new ColoredVertex[] {
new ColoredVertex(new Vector3(10f,10f,0.0f),colorN1.ToArgb()),new ColoredVertex(new Vector3(1000.0f,10.0f,new ColoredVertex(new Vector3(1000f,800f,};
using (var decl = new VertexDeclaration(_device,ColoredVertex.Format))
{
_device.VertexFormat = VertexFormat.Diffuse;
_device.VertexDeclaration = decl;
_device.DrawUserPrimitives<ColoredVertex>(PrimitiveType.TriangleList,1,triangleN1);
}
var colorN2 = Color.FromArgb(50,0);
var triangleN2 = new ColoredVertex[] {
new ColoredVertex(new Vector3(100f,100f,1.0f),colorN2.ToArgb()),new ColoredVertex(new Vector3(800.0f,100.0f,new ColoredVertex(new Vector3(700f,900f,};
using (var decl = new VertexDeclaration(_device,ColoredVertex.Format))
{
_device.VertexFormat = VertexFormat.Diffuse;
_device.VertexDeclaration = decl;
_device.DrawUserPrimitives<ColoredVertex>(PrimitiveType.TriangleList,triangleN2);
}
_device.EndScene();
_device.Present();
解决方法
这些 RenderState 标志发挥了作用:
_device.SetRenderState(RenderState.SourceBlend,Blend.SourceAlpha);
_device.SetRenderState(RenderState.DestinationBlend,Blend.InverseSourceAlpha);
_device.SetRenderState(RenderState.AlphaBlendEnable,true);