SlimDX和WPF的合作应用
1.首先定义一个DX操作类
using System;
using SlimDX;
using SlimDX.Direct3D9;
using System.Windows.Interop;
using System.Windows.Media; public class DX
{
private enum DirectXStatus
{
Available,
Unavailable_RemoteSession,
Unavailable_LowTier,
Unavailable_MissingDirectX,
Unavailable_Unknown
}; public static Device Device { get; private set; }
public static bool Available { get { return DX.Device != null; } }// = false; private static DX _dx;
private static DirectXStatus _status = DirectXStatus.Unavailable_Unknown;
private static string _statusMessage = ""; [System.Runtime.InteropServices.DllImport("user32")]
private static extern int GetSystemMetrics(int smIndex);
private const int SM_REMOTESESSION = 0x1000; // device settings
private const Format _adapterFormat = Format.X8R8G8B8;
private const Format _backbufferFormat = Format.A8R8G8B8;
private const Format _depthStencilFormat = Format.D16;
private static CreateFlags _createFlags = CreateFlags.Multithreaded | CreateFlags.FpuPreserve; private Direct3D _d3d; private DX()
{
initD3D();
if (_d3d != null)
initDevice();
//if (!DX.Available)
// MessageBox.Show("DirectX硬件加速不可用!\n\n" + _statusMessage, "", MessageBoxButton.OK, MessageBoxImage.Warning);
} ~DX()
{
if (DX.Device != null)
if (!DX.Device.Disposed)
DX.Device.Dispose();
if (_d3d != null)
if (!_d3d.Disposed)
_d3d.Dispose();
} public static void Init()
{
if (_dx == null)
_dx = new DX();
} private void initD3D()
{
if (_d3d != null)
return; _status = DirectXStatus.Unavailable_Unknown; //// assume that we can't run at all under terminal services
if (GetSystemMetrics(SM_REMOTESESSION) != )
{
_status = DirectXStatus.Unavailable_RemoteSession;
return;
} int renderingTier = (RenderCapability.Tier >> );
if (renderingTier < )
{
_status = DirectXStatus.Unavailable_LowTier;
_statusMessage = "low tier";
return;//注意:发现某些集成显卡,在这里出去!!
} try
{
_d3d = new Direct3DEx();
}
catch
{
try
{
_d3d = new Direct3D();
}
catch (Direct3DX9NotFoundException dfe)
{
_status = DirectXStatus.Unavailable_MissingDirectX;
_statusMessage = "Direct3DX9 Not Found\n" + dfe.Message;
return;
}
catch (Exception e)
{
_status = DirectXStatus.Unavailable_Unknown;
_statusMessage = e.Message;
return;
}
} bool ok;
Result result; ok = _d3d.CheckDeviceType(, DeviceType.Hardware, _adapterFormat, _backbufferFormat, true, out result);
if (!ok)
{
//Debug.WriteLine("*** failed to CheckDeviceType");
//MessageBox.Show("Failed to CheckDeviceType");
return;
} ok = _d3d.CheckDepthStencilMatch(, DeviceType.Hardware, _adapterFormat, _backbufferFormat, _depthStencilFormat, out result);
if (!ok)
{
//Debug.WriteLine("*** failed to CheckDepthStencilMatch");
_statusMessage = "Failed to CheckDepthStencilMatch";
return;
} Capabilities deviceCaps = _d3d.GetDeviceCaps(, DeviceType.Hardware);
if ((deviceCaps.DeviceCaps & DeviceCaps.HWTransformAndLight) != )
_createFlags |= CreateFlags.HardwareVertexProcessing;
else
_createFlags |= CreateFlags.SoftwareVertexProcessing; _status = DirectXStatus.Available;
} private void initDevice()
{
if (_status != DirectXStatus.Available)
return; HwndSource hwnd = new HwndSource(, , , , , , , "SlimDX_Wnd", IntPtr.Zero);
PresentParameters pp = new PresentParameters();
//pp.SwapEffect = SwapEffect.Copy;
//pp.DeviceWindowHandle = hwnd.Handle;
pp.Windowed = true;
pp.PresentFlags = PresentFlags.Video;
pp.SwapEffect = SwapEffect.Discard;
//pp.BackBufferCount = 1;
//pp.BackBufferWidth = 320;
//pp.BackBufferHeight = 240;
//pp.BackBufferFormat = _backbufferFormat;
//pp.AutoDepthStencilFormat = _depthStencilFormat;
try
{
DeviceType deviceType = DeviceType.Hardware;
if (_d3d is Direct3DEx)
DX.Device = new DeviceEx((Direct3DEx)_d3d, , deviceType, hwnd.Handle, _createFlags, pp);
else
DX.Device = new Device(_d3d, , deviceType, hwnd.Handle, _createFlags, pp);
}
catch (Exception ex)
{
//Debug.WriteLine("Exception in Direct3DReset " + ex.StackTrace);
//Debug.WriteLine("Exception in Direct3DReset " + ex.Message);
}
}
}
2.定义准备显卡硬件,和释放显卡硬件方法
定义一些变量
/// <summary>
/// 离屏表面
/// </summary>
private Surface _offscrn;
/// <summary>
/// 交换链
/// </summary>
private SwapChain _swapChain;
private D3DImage _d3dImage = null;
/// <summary>
/// 准备DirectX显卡硬件
/// </summary>
private bool prepareHardware(VideoFormat videoFormat, int videoWidth, int videoHeight)//, VideoFormat videoFormat)
{
if (!DX.Available)
return true; try
{
SlimDX.Direct3D9.Format format = SlimDX.Direct3D9.Format.A8R8G8B8;
if (videoFormat == VideoFormat.Yuv420)
format = (SlimDX.Direct3D9.Format)0x32315659;
if (_offscrn != null)
if (videoWidth == _offscrn.Description.Width && videoHeight == _offscrn.Description.Height && _offscrn.Description.Format == format)
return true; releaseHardware();
_offscrn = Surface.CreateOffscreenPlain(DX.Device, videoWidth, videoHeight, format, Pool.Default);
PresentParameters pp = new PresentParameters();
pp.Windowed = true;
pp.PresentFlags = PresentFlags.Video;
pp.SwapEffect = SwapEffect.Discard;
pp.BackBufferCount = ;
pp.BackBufferWidth = videoWidth;
pp.BackBufferHeight = videoHeight;
_swapChain = new SwapChain(DX.Device, pp);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 释放DirectX显卡硬件
/// </summary>
private void releaseHardware()
{
if (!DX.Available)
return;
if (_offscrn != null)
if (!_offscrn.Disposed)
_offscrn.Dispose();
_offscrn = null;
if (_swapChain != null)
if (!_swapChain.Disposed)
_swapChain.Dispose();
_swapChain = null;
}
3.
private void drawFrame(VideoFormat videoFormat, int width, int height, IntPtr Y, IntPtr U, IntPtr V)
{
if (!prepareHardware(videoFormat, width, height))
return;
if (_swapChain == null)
return; DataRectangle dr = _offscrn.LockRectangle(LockFlags.None);//在离屏表面上锁定一个矩形
drawYuv420(width, height, Y, U, V, dr.Data.DataPointer, dr.Pitch);//DataPointer 内部指针指向当前流的存储备份; Pitch 两个连续的行之间的数据的字节数
_offscrn.UnlockRectangle();//解锁矩形
using (Surface bb = _swapChain.GetBackBuffer())//从交换链中检索一个后台缓冲区
{
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(, , bb.Description.Width, bb.Description.Height);
_swapChain.Device.StretchRectangle(_offscrn, rect, bb, rect, TextureFilter.None);//将后台缓冲区的内容交换到前台缓冲区
_swapChain.Device.Present();//呈现后台缓冲区序列中下一个后台缓冲区的内容 _d3dImage.Lock();
_d3dImage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, bb.ComPointer);
_d3dImage.AddDirtyRect(new Int32Rect(, , _d3dImage.PixelWidth, _d3dImage.PixelHeight));
_d3dImage.Unlock();
}
} private void drawYuv420(int width, int height, IntPtr Y, IntPtr U, IntPtr V, IntPtr dest, int pitch)
{
IntPtr py = dest;
IntPtr pv = py + (pitch * height);
IntPtr pu = pv + ((pitch * height) / );
int w2 = width / , pitch2 = pitch / ;
for (int y = ; y < height; y++)
{
CopyMemory(py, Y + y * width, (uint)width);
py += pitch;
if ((y & ) != )
continue;
int offset = y / * w2;
CopyMemory(pu, U + offset, (uint)w2);
CopyMemory(pv, V + offset, (uint)w2);
pu += pitch2;
pv += pitch2;
}
}
[DllImport("kernel32.dll", EntryPoint = "RtlMoveMemory")]
private static extern void CopyMemory(IntPtr Destination, IntPtr Source, uint Length);
SlimDX和WPF的合作应用的更多相关文章
- WPF特点
前言:为什么要学习WPF呢?因为随着现阶段硬件技术的升级以及客户对体验的要求越来越高,传统的GDI和USERS(或者是GDI+.USERS)已经不能满足这个需求,因此,WPF技术应运而生. WPF的特 ...
- WPF开发中Designer和码农之间的合作
想要用WPF做出一流的软件界面, 必须要Designer和码农通力合作.理想的情况是平时并行开发,Designer用Expression套件(包括Design和Blend)来设计界面,码农开发Mode ...
- 年度巨献-WPF项目开发过程中WPF小知识点汇总(原创+摘抄)
WPF中Style的使用 Styel在英文中解释为”样式“,在Web开发中,css为层叠样式表,自从.net3.0推出WPF以来,WPF也有样式一说,通过设置样式,使其WPF控件外观更加美化同时减少了 ...
- WPF 3D 知识点大全以及实例
引言 现在物联网概念这么火,如果监控的信息能够实时在手机的客服端中以3D形式展示给我们,那种体验大家可以发挥自己的想象. 那生活中我们还有很多地方用到这些,如上图所示的Kinect 在医疗上的应用,当 ...
- 第一个WPF应用程序
WPF 全称为 Windows Presentation Foundation. 核心特性: WPF使用一种新的XAML(Extensible Application Markup Language) ...
- 2012开源项目计划-WPF企业级应用整合平台
2012开源项目计划-WPF企业级应用整合平台 开篇 2012年,提前祝大家新年快乐,为了加快2012年的开发计划,特打算年前和大家分享一下2012年的开发计划和年后具体的实施计划,希望有兴趣或者有志 ...
- 一、什么是WPF?
一.什么是WPF? Windows Presentation Foundation(以前的代号为“Avalon”)是 Microsoft 用于 Windows 的统一显示子系统,它通过 WinFX 公 ...
- wpf做的可扩展记事本
记得有个winform利用反射做的可扩展笔记本,闲来无事,便用wpf也搞了个可扩展记事本,可用接口动态扩展功能,较简单,以便参考: 目录结构如下: MainWindow.xaml为主功能界面,Func ...
- vs2012用wpf制作透明窗口中报错的解决方案
在开发wpf项目时,需要调用外部com组件,同时需要制作透明窗口,于是问题出现了,当我们在设置 AllowsTransparency="True"后,com组件显示不出来了,只有透 ...
随机推荐
- .net mvc结合微软提供的FormsAuthenticationTicket登陆
一.Web.config <system.web> <compilation debug="true" targetFramework="4.5&quo ...
- 学习ReactNative笔记整理一___JavaScript基础
学习ReactNative笔记整理一___JavaScript基础 ★★★笔记时间- 2017-1-9 ★★★ 前言: 现在跨平台是一个趋势,这样可以减少开发和维护的成本.第一次看是看的ReactNa ...
- 谁在唱衰PC?说出你的理由
在平板电脑的冲击下,PC真的衰落了吗?戴尔消费产品市场副总裁Raymond Wah给出了坚定的回答:“平板电脑没有办法代替PC”. 让他有如此底气做出这一判断的取决于两方面:一方面,PC(了解PC市场 ...
- 转载收藏之用 - 微信公众平台开发教程(四):Hello World
这一篇文章其实可以写在很前面,不过我还是希望开发者们尽多地了解清楚原理之后再下手. 通过上一篇Senparc.Weixin.MP SDK 微信公众平台开发教程(三):微信公众平台开发验证,我们已经使微 ...
- java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils
java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils Caused by: java.lang.ClassNotFou ...
- JS 浮点计算BUG
最近做项目的时候遇到一个比较纠结的js浮点计算问题. 当时是做利率计算,因为利率大多数涉及到小数点,精度要求也很高. 0.6+0.1+0.1=? 结果出现:0.7999999999999 网上查找了一 ...
- 10个工具让你的 shell 脚本更强大
10个工具让你的 shell 脚本更强大 很多人误以为shell脚本只能在命令行下使用.其实shell也可以调用一些GUI组件,例如菜单,警告框,进度条等等.你可以控制最终的输出,光标位 置还有各种输 ...
- HTML5 CSS3 诱人的实例 :模仿优酷视频截图功能
一般的视频网站对于用户上传的视频,在用户上传完成后,可以对播放的视频进行截图,然后作为视频的展示图.项目中也可以引入这样的功能给用户一种不错的体验,而不是让用户额外上传一张展示图. 效果图: 看起来还 ...
- 北京Uber优步司机奖励政策(12月3日)
用户组:人民优步(适用于12月3日) 滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://w ...
- hadoop深入研究:(十六)——Avro序列化与反序列化
转载请写明来源地址:http://blog.csdn.net/lastsweetop/article/details/9773233 所有源码在github上,https://github.com/l ...