public void InitializeDeviceResources() { ModeDescription backBufferDesc = new ModeDescription(1600, 900, new Rational(60, 1), Format.B8G8R8A8_UNorm); SwapChainDescription swapChainDesc = new SwapChainDescription() { ModeDescription = backBufferDesc, SampleDescription = new SampleDescription(1, 0), Usage = Usage.RenderTargetOutput, BufferCount = 1, OutputHandle = this.Handle, IsWindowed = true }; var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.VideoSupport | SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug; //SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain); SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, creationFlags, swapChainDesc, out d3dDevice, out swapChain); d3dDeviceContext = d3dDevice.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>(); using (SharpDX.Direct3D11.Texture2D backBuffer = swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0)) { renderTargetView = new SharpDX.Direct3D11.RenderTargetView(d3dDevice, backBuffer); } System.Drawing.Graphics g = this.CreateGraphics(); SharpDX.Direct2D1.Factory d2dFactory = new SharpDX.Direct2D1.Factory(SharpDX.Direct2D1.FactoryType.SingleThreaded, SharpDX.Direct2D1.DebugLevel.None); // Create Direct2D device var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device>(); //d2dDevice = new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice); d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice); d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None); //d2dContext.PrimitiveBlend = PrimitiveBlend.SourceOver; BitmapProperties1 properties = new BitmapProperties1(new SharpDX.Direct2D1.PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore), g.DpiX, g.DpiY, BitmapOptions.Target | BitmapOptions.CannotDraw); Surface backBuffer2D = swapChain.GetBackBuffer <Surface>(0); //new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied) SharpDX.Direct2D1.RenderTargetProperties rtp = new SharpDX.Direct2D1.RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore)); d2dRenderTarget = new SharpDX.Direct2D1.RenderTarget(d2dFactory, backBuffer2D, rtp); d2dTarget = new Bitmap1(d2dContext, backBuffer2D, properties); d3dDeviceContext.OutputMerger.SetRenderTargets(renderTargetView); }
public void BeginFrame() { Debug.Assert(curView == null); Debug.Assert(curTarget == null); curTarget = chain.GetBackBuffer <Texture2D>(0); curView = new RenderTargetView(ImageFramework.DirectX.Device.Get().Handle, curTarget); }
public void Resize(int width, int height) { ResolutionX = width; ResolutionY = height; MainCamera.renderTargetView?.Dispose(); MainCamera.depthStencilView?.Dispose(); D2DTarget?.Dispose(); D2DContext?.Dispose(); MainCamera.AspectRatio = width / (float)height; swapChain.ResizeBuffers(swapChain.Description.BufferCount, width, height, DXGI.Format.Unknown, DXGI.SwapChainFlags.None); D2DContext = new D2D1.DeviceContext(D2DDevice, D2D1.DeviceContextOptions.None); using (DXGI.Surface surface = swapChain.GetBackBuffer <DXGI.Surface>(0)) D2DTarget = new D2D1.Bitmap1(D2DContext, surface, new D2D1.BitmapProperties1(new D2D1.PixelFormat(DXGI.Format.R8G8B8A8_UNorm, D2D1.AlphaMode.Premultiplied), D2DFactory.DesktopDpi.Height, D2DFactory.DesktopDpi.Width, D2D1.BitmapOptions.CannotDraw | D2D1.BitmapOptions.Target) ); D2DContext.Target = D2DTarget; // render target using (D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0)) MainCamera.renderTargetView = new D3D11.RenderTargetView(Device, backBuffer); // depth buffer D3D11.Texture2DDescription depthDescription = new D3D11.Texture2DDescription() { Format = DXGI.Format.D32_Float, ArraySize = 1, MipLevels = 1, Width = width, Height = height, SampleDescription = new DXGI.SampleDescription(SampleCount, SampleQuality), Usage = D3D11.ResourceUsage.Default, BindFlags = D3D11.BindFlags.DepthStencil, CpuAccessFlags = D3D11.CpuAccessFlags.None, OptionFlags = D3D11.ResourceOptionFlags.None }; using (D3D11.Texture2D depthTexture = new D3D11.Texture2D(Device, depthDescription)) MainCamera.depthStencilView = new D3D11.DepthStencilView(Device, depthTexture); // viewport Viewport = new Viewport(0, 0, width, height); Context.Rasterizer.SetViewport(Viewport); }
public void BeginFrame() { Debug.Assert(curView == null); using (var backBuffer = chain.GetBackBuffer <Texture2D>(0)) { curView = new RenderTargetView(Device.Get().Handle, backBuffer); } }
/// <summary> /// Creates the render target. /// </summary> /// <returns>D3D11.RenderTargetView.</returns> /// <exception cref="System.Exception"></exception> private D3D11.RenderTargetView CreateRenderTarget() { if (d3dDevice == null || swapChain == null) { throw new Exception(MethodBase.GetCurrentMethod().Name + "Device or SwapChain is null"); } using (D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0)) { return(new D3D11.RenderTargetView(d3dDevice, backBuffer)); } }
public DeviceResources(IntPtr windowHandle, int renderResWidth, int renderResHeight, int targetFPS) { Device = new D3D11.Device(DriverType.Hardware, D3D11.DeviceCreationFlags.Debug | D3D11.DeviceCreationFlags.DisableGpuTimeout); DeviceContext = Device.ImmediateContext; var backBufferDesc = new DXGI.ModeDescription( renderResWidth, renderResHeight, new DXGI.Rational(targetFPS, 1), DXGI.Format.R8G8B8A8_UNorm ); //var backBufferDesc = new DXGI.ModeDescription() //{ // Width = renderResWidth, // Height = renderResHeight, // RefreshRate = new DXGI.Rational(targetFPS, 1), // Format = DXGI.Format.R8G8B8A8_UNorm //}; var swapChainDesc = new DXGI.SwapChainDescription() { ModeDescription = backBufferDesc, SampleDescription = sampleDescription, Usage = DXGI.Usage.RenderTargetOutput, BufferCount = 1, OutputHandle = windowHandle, IsWindowed = true }; // Create SwapChain DXGI.Factory factory = new DXGI.Factory1(); SwapChain = new DXGI.SwapChain(factory, Device, swapChainDesc); // Create BackBuffer RTV BackBuffer = SwapChain.GetBackBuffer <D3D11.Texture2D>(0); BackBufferRTV = new D3D11.RenderTargetView(Device, BackBuffer); }
private void CreateDeviceIndependentResources() { _dxgiDevice = _d3dDevice.QueryInterface <SharpDX.DXGI.Device>(); _d2dDevice = new SharpDX.Direct2D1.Device(_dxgiDevice); _d2dFactory = _d2dDevice.Factory; var dpiX = _d2dFactory.DesktopDpi.Width; var dpiY = _d2dFactory.DesktopDpi.Height; _dc = new SharpDX.Direct2D1.DeviceContext(_d2dDevice, DeviceContextOptions.None); _dc.PrimitiveBlend = PrimitiveBlend.SourceOver; var format = new SharpDX.Direct2D1.PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied); var properties = new BitmapProperties1(format, dpiX, dpiY, BitmapOptions.Target | BitmapOptions.CannotDraw); _surface = _swapChain.GetBackBuffer <Surface>(0); _renderTarget = new Bitmap1(_dc, _surface, properties); _dc.Target = _renderTarget; _dc.AntialiasMode = AntialiasMode.PerPrimitive; OnCreateDeviceIndependentResources(); this._deviceIndependedResourcesCreated = true; }
void InitializeDeviceResources() { DXGI.ModeDescription backBufferDesc = new DXGI.ModeDescription(m_width, m_height, new DXGI.Rational(60, 1), DXGI.Format.R8G8B8A8_UNorm); DXGI.SwapChainDescription swapChainDesc = new DXGI.SwapChainDescription() { ModeDescription = backBufferDesc, SampleDescription = new DXGI.SampleDescription(1, 0), Usage = DXGI.Usage.RenderTargetOutput, BufferCount = 1, OutputHandle = m_renderForm.Handle, IsWindowed = true, }; D3D11.Device.CreateWithSwapChain(SharpDX.Direct3D.DriverType.Hardware, D3D11.DeviceCreationFlags.None, swapChainDesc, out m_d3d11Device, out m_swapChain); m_d3d11DeviceContext = m_d3d11Device.ImmediateContext; using (D3D11.Texture2D backBufer = m_swapChain.GetBackBuffer <D3D11.Texture2D>(0)) { m_renderTargetView = new D3D11.RenderTargetView(m_d3d11Device, backBufer); } m_viewPort = new SharpDX.Viewport(0, 0, m_width, m_height); m_d3d11DeviceContext.Rasterizer.SetViewport(m_viewPort); }
public void Init(Form form) { ViewportSize = new Size2F(form.Width, form.Height); hViewportSize = new Size2F(form.Width / 2f, form.Height / 2f); ModeDescription backBufferDesc = new ModeDescription(form.Width, form.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm); SwapChainDescription swapChainDesc = new SwapChainDescription() { ModeDescription = backBufferDesc, SampleDescription = new SampleDescription(1, 0), Usage = Usage.RenderTargetOutput, BufferCount = 1, OutputHandle = form.Handle, IsWindowed = true, }; D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain); d3dDeviceContext = d3dDevice.ImmediateContext; d3dDeviceContext.Rasterizer.SetViewport(0, 0, form.Width, form.Height); using (D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0)) { renderTargetView = new D3D11.RenderTargetView(d3dDevice, backBuffer); } D3D11.BlendStateDescription blendStateDesc = D3D11.BlendStateDescription.Default(); blendStateDesc.AlphaToCoverageEnable = false; blendStateDesc.RenderTarget[0].IsBlendEnabled = true; blendStateDesc.RenderTarget[0].SourceBlend = D3D11.BlendOption.SourceAlpha; blendStateDesc.RenderTarget[0].DestinationBlend = D3D11.BlendOption.One; // blendStateDesc.RenderTarget[0].BlendOperation = D3D11.BlendOperation.Maximum; blendStateDesc.RenderTarget[0].SourceAlphaBlend = D3D11.BlendOption.SourceAlpha; //Zero blendStateDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.DestinationAlpha; blendStateDesc.RenderTarget[0].AlphaBlendOperation = D3D11.BlendOperation.Maximum; blendStateDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All; blendState = new D3D11.BlendState(d3dDevice, blendStateDesc); Fonts = new Detail.FontCache(this); var layout2d = new D3D11.InputElement[] { new D3D11.InputElement("POSITION", 0, Format.R32G32_Float, 0, 0), new D3D11.InputElement("COLOR", 0, Format.R32G32B32A32_Float, 8, 0), new D3D11.InputElement("TEXCOORDS", 0, Format.R32G32_Float, 24, 0), }; var layout3d = new D3D11.InputElement[] { new D3D11.InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new D3D11.InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0), }; var vertexShaderOutput2d = ShaderBytecode.Compile(Detail.Shaders.vertexShaderCode2d, "main", "vs_4_0", ShaderFlags.Debug); var vertexShaderOutput3d = ShaderBytecode.Compile(Detail.Shaders.vertexShaderCode3d, "main", "vs_4_0", ShaderFlags.Debug); var pixelShaderOutput = ShaderBytecode.Compile(Detail.Shaders.pixelShaderCode, "main", "ps_4_0", ShaderFlags.Debug); Detail.Shaders.VertexShader2D = new D3D11.VertexShader(Device, vertexShaderOutput2d); Detail.Shaders.VertexShader3D = new D3D11.VertexShader(Device, vertexShaderOutput3d); Detail.Shaders.PixelShader = new D3D11.PixelShader(Device, pixelShaderOutput); Detail.Shaders.InputLayout2D = new D3D11.InputLayout(Device, ShaderSignature.GetInputSignature(vertexShaderOutput2d), layout2d); Detail.Shaders.InputLayout3D = new D3D11.InputLayout(Device, ShaderSignature.GetInputSignature(vertexShaderOutput3d), layout3d); IntPtr data = System.Runtime.InteropServices.Marshal.AllocHGlobal(4 * 4 * 4); var white = BitConverter.GetBytes(1f); for (int i = 0; i < 4 * 4; i++) { for (int j = 0; j < white.Length; j++) { System.Runtime.InteropServices.Marshal.WriteByte(data, i * sizeof(float) + j, white[j]); } } White = new D3D11.Texture2D(Device, new D3D11.Texture2DDescription { Width = 4, Height = 4, ArraySize = 1, BindFlags = D3D11.BindFlags.ShaderResource, Usage = D3D11.ResourceUsage.Dynamic, CpuAccessFlags = D3D11.CpuAccessFlags.Write, Format = Format.R32G32B32A32_Float, MipLevels = 1, OptionFlags = D3D11.ResourceOptionFlags.None, SampleDescription = new DXGI.SampleDescription(1, 0), }, new DataBox[] { new DataBox(data, 4 * 2, 4) }); System.Runtime.InteropServices.Marshal.FreeHGlobal(data); WhiteView = new D3D11.ShaderResourceView(Device, White); samplerState = new D3D11.SamplerState(Device, new D3D11.SamplerStateDescription() { Filter = D3D11.Filter.MinMagMipLinear, AddressU = D3D11.TextureAddressMode.Clamp, AddressV = D3D11.TextureAddressMode.Clamp, AddressW = D3D11.TextureAddressMode.Clamp, BorderColor = new RawColor4(1f, 0f, 1f, 1f), ComparisonFunction = D3D11.Comparison.Never, MaximumAnisotropy = 16, MipLodBias = 0, MinimumLod = 0, MaximumLod = 16 }); transfBuffer = new SharpDX.Direct3D11.Buffer(Device, new D3D11.BufferDescription(sizeof(float) * 4, D3D11.ResourceUsage.Dynamic, D3D11.BindFlags.ConstantBuffer, D3D11.CpuAccessFlags.Write, D3D11.ResourceOptionFlags.None, sizeof(float))); DataStream stream; DeviceContext.MapSubresource(transfBuffer, D3D11.MapMode.WriteDiscard, D3D11.MapFlags.None, out stream); stream.Write(hViewportSize.Width); stream.Write(hViewportSize.Height); DeviceContext.UnmapSubresource(transfBuffer, 0); DeviceContext.VertexShader.SetShader(vertexShader, null, 0); DeviceContext.VertexShader.SetConstantBuffer(0, transfBuffer); DeviceContext.PixelShader.SetShader(pixelShader, null, 0); DeviceContext.PixelShader.SetSampler(0, samplerState); DeviceContext.InputAssembler.InputLayout = inputLayout; DeviceContext.OutputMerger.BlendState = blendState; cam = new Camera(this); }
private void InitializeDeviceResources(DXGI.SwapChain swapChain) { backbufferTexture = swapChain.GetBackBuffer <D3D11.Texture2D>(0); backbufferRTV = new D3D11.RenderTargetView(device, backbufferTexture); width = backbufferTexture.Description.Width; height = backbufferTexture.Description.Height; D3D11.Texture2DDescription sceneTextureDesc = new D3D11.Texture2DDescription { CpuAccessFlags = D3D11.CpuAccessFlags.None, BindFlags = D3D11.BindFlags.RenderTarget | D3D11.BindFlags.ShaderResource, Format = DXGI.Format.R8G8B8A8_UNorm, Width = width, Height = height, OptionFlags = D3D11.ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = D3D11.ResourceUsage.Default }; sceneTexture = new D3D11.Texture2D(device, sceneTextureDesc); sceneRTV = new D3D11.RenderTargetView(device, sceneTexture); sceneSRV = new D3D11.ShaderResourceView(device, sceneTexture); var depthBufferDesc = new D3D11.Texture2DDescription() { Width = width, Height = height, MipLevels = 1, ArraySize = 1, Format = DXGI.Format.R32_Typeless, SampleDescription = { Count = 1, Quality = 0 }, Usage = D3D11.ResourceUsage.Default, BindFlags = D3D11.BindFlags.DepthStencil | D3D11.BindFlags.ShaderResource, CpuAccessFlags = D3D11.CpuAccessFlags.None, OptionFlags = D3D11.ResourceOptionFlags.None }; using (var depthStencilBufferTexture = new D3D11.Texture2D(device, depthBufferDesc)) { var depthStencilViewDesc = new D3D11.DepthStencilViewDescription() { Format = DXGI.Format.D32_Float, Dimension = D3D11.DepthStencilViewDimension.Texture2D, Texture2D = { MipSlice = 0 } }; depthDSV = new D3D11.DepthStencilView(device, depthStencilBufferTexture, depthStencilViewDesc); var shaderResourceViewDesc = new D3D11.ShaderResourceViewDescription() { Format = DXGI.Format.R32_Float, Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D, Texture2D = { MipLevels = 1, MostDetailedMip = 0 } }; depthSRV = new D3D11.ShaderResourceView(device, depthStencilBufferTexture, shaderResourceViewDesc); } var depthStencilDesc = new D3D11.DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = D3D11.DepthWriteMask.All, DepthComparison = D3D11.Comparison.Less, IsStencilEnabled = false, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = new D3D11.DepthStencilOperationDescription() { FailOperation = D3D11.StencilOperation.Keep, DepthFailOperation = D3D11.StencilOperation.Keep, PassOperation = D3D11.StencilOperation.Keep, Comparison = D3D11.Comparison.Always }, BackFace = new D3D11.DepthStencilOperationDescription() { FailOperation = D3D11.StencilOperation.Keep, DepthFailOperation = D3D11.StencilOperation.Keep, PassOperation = D3D11.StencilOperation.Keep, Comparison = D3D11.Comparison.Always } }; depthStencilState = new D3D11.DepthStencilState(device, depthStencilDesc); var rasterDesc = new D3D11.RasterizerStateDescription() { IsAntialiasedLineEnabled = false, CullMode = D3D11.CullMode.Back, DepthBias = 0, DepthBiasClamp = 0.0f, IsDepthClipEnabled = true, FillMode = D3D11.FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = 0.0f }; rasterizerState = new D3D11.RasterizerState(device, rasterDesc); }
public SharpRender(RenderForm form) { this.form = form; var adapters = new DXGI.Factory1().Adapters; DXGI.Adapter myadapter = null; for (int i = 0; i < adapters.Length; ++i) { Logger.Log(string.Format("Adapter Found: [{0}] " + "{1}\tDeviceId={5}" + "{1}\tLuid={6}" + "{1}\tVendorId={10}" + "{1}\tSubsystemId={9}" + "{1}\tDescription={4}" + "{1}\tRevision={7}" + "{1}\tDedicatedSystemMemory={2}" + "{1}\tDedicatedVideoMemory={3}" + "{1}\tSharedSystemMemory={8}" + "", i, Environment.NewLine, adapters[i].Description.DedicatedSystemMemory, adapters[i].Description.DedicatedVideoMemory, adapters[i].Description.Description, adapters[i].Description.DeviceId, adapters[i].Description.Luid, adapters[i].Description.Revision, adapters[i].Description.SharedSystemMemory, adapters[i].Description.SubsystemId, adapters[i].Description.VendorId)); var outputs = adapters[i].Outputs; for (int j = 0; j < outputs.Length; ++j) { Logger.Log(string.Format("Output Found: [{0},{1}]" + "{2}\tDeviceName={4}" + "{2}\tIsAttachedToDesktop={5}" + "{2}\tMonitorHandle={6}" + "{2}\tDesktopBounds={3}" + "{2}\tRotation={7}" + "", i, j, Environment.NewLine, (Rectangle)outputs[j].Description.DesktopBounds, outputs[j].Description.DeviceName, outputs[j].Description.IsAttachedToDesktop, outputs[j].Description.MonitorHandle, outputs[j].Description.Rotation)); } if (outputs.Length > 0 && myadapter == null) { myadapter = adapters[i]; } } d3device = new Direct3D11.Device( myadapter, Direct3D11.DeviceCreationFlags.BgraSupport); //SharpDX.Direct3D.DriverType.Hardware, //Direct3D11.DeviceCreationFlags.BgraSupport | //Direct3D11.DeviceCreationFlags.Debug); defDevice = d3device.QueryInterface <Direct3D11.Device1>(); dxgiDevice2 = defDevice.QueryInterface <DXGI.Device2>(); dxgiAdapter = dxgiDevice2.Adapter; dxgiFactory2 = dxgiAdapter.GetParent <DXGI.Factory2>(); var scDescription = new DXGI.SwapChainDescription1() { Width = 0, Height = 0, Format = DXGI.Format.B8G8R8A8_UNorm, Stereo = false, SampleDescription = new DXGI.SampleDescription(1, 0), Usage = DXGI.Usage.RenderTargetOutput, BufferCount = 2, Scaling = DXGI.Scaling.None, SwapEffect = DXGI.SwapEffect.FlipSequential }; swapChain = new DXGI.SwapChain1(dxgiFactory2, defDevice, form.Handle, ref scDescription, null, null); d2dDevice = new Direct2D1.Device(dxgiDevice2); d2dContext = new Direct2D1.DeviceContext(d2dDevice, Direct2D1.DeviceContextOptions.None); fac = new Direct2D1.Factory(Direct2D1.FactoryType.SingleThreaded); var dpi = fac.DesktopDpi; var bMProperties = new Direct2D1.BitmapProperties1( new Direct2D1.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, Direct2D1.AlphaMode.Premultiplied), dpi.Width, dpi.Height, Direct2D1.BitmapOptions.CannotDraw | Direct2D1.BitmapOptions.Target); bb = swapChain.GetBackBuffer <DXGI.Surface>(0); target = new Direct2D1.Bitmap1(d2dContext, bb, bMProperties); d2dContext.Target = target; wrFactory = new DirectWrite.Factory(); brush = new Direct2D1.SolidColorBrush(d2dContext, c(Color.White)); }
public RLocalRenderer(int width, int height) { RenderWidth = width; RenderHeight = height; renderForm = new RenderForm("RLocal Renderer"); renderForm.ClientSize = new Size(RenderWidth, RenderHeight); renderForm.AllowUserResizing = false; //renderForm.IsFullscreen = true; ModeDescription backBufferDesc = new ModeDescription(RenderWidth, RenderHeight, new Rational(60, 1), Format.B8G8R8A8_UNorm); SwapChainDescription swapChainDesc = new SwapChainDescription() { ModeDescription = backBufferDesc, SampleDescription = new SampleDescription(1, 0), Usage = Usage.RenderTargetOutput, BufferCount = 1, OutputHandle = renderForm.Handle, IsWindowed = true }; var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.VideoSupport | SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport; // | DeviceCreationFlags.Debug; //SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain); SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, creationFlags, swapChainDesc, out d3dDevice, out swapChain); d3dDeviceContext = d3dDevice.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>(); ConfigureAltEnter(); using (SharpDX.Direct3D11.Texture2D backBuffer = swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0)) { renderTargetView = new SharpDX.Direct3D11.RenderTargetView(d3dDevice, backBuffer); } System.Drawing.Graphics graphics = renderForm.CreateGraphics(); SharpDX.Direct2D1.Factory d2dFactory = new SharpDX.Direct2D1.Factory(SharpDX.Direct2D1.FactoryType.SingleThreaded, SharpDX.Direct2D1.DebugLevel.None); // Create Direct2D device var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device>(); //d2dDevice = new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice); d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice); d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None); //d2dContext.PrimitiveBlend = PrimitiveBlend.SourceOver; BitmapProperties1 properties = new BitmapProperties1(new SharpDX.Direct2D1.PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore), graphics.DpiX, graphics.DpiY, BitmapOptions.Target | BitmapOptions.CannotDraw); Surface backBuffer2D = swapChain.GetBackBuffer <Surface>(0); //new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied) SharpDX.Direct2D1.RenderTargetProperties rtp = new SharpDX.Direct2D1.RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore)); d2dRenderTarget = new SharpDX.Direct2D1.RenderTarget(d2dFactory, backBuffer2D, rtp); d2dTarget = new Bitmap1(d2dContext, backBuffer2D, properties); d3dDeviceContext.OutputMerger.SetRenderTargets(renderTargetView); RenderBuffer = new byte[RLocalUtils.GetSizeBGRA(RenderWidth, RenderHeight)]; }
/// <summary> /// deviceを作成します。 /// </summary> /// <param name="control">レンダリング先となるcontrol</param> /// <param name="ocu_config">設定</param> /// <returns>deviceの作成に成功したか</returns> public bool InitializeApplication(Control control, OcuConfig ocu_config) { this.ocu_config = ocu_config; oculus = new OculusWrap.Wrap(); // Initialize the Oculus runtime. bool success = oculus.Initialize(); if (!success) { MessageBox.Show("Failed to initialize the Oculus runtime library.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } // Use the head mounted display, if it's available, otherwise use the debug HMD. int numberOfHeadMountedDisplays = oculus.Hmd_Detect(); if (numberOfHeadMountedDisplays > 0) hmd = oculus.Hmd_Create(0); else hmd = oculus.Hmd_CreateDebug(OculusWrap.OVR.HmdType.DK2); if (hmd == null) { MessageBox.Show("Oculus Rift not detected.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (hmd.ProductName == string.Empty) MessageBox.Show("The HMD is not enabled.", "There's a tear in the Rift", MessageBoxButtons.OK, MessageBoxIcon.Error); // Specify which head tracking capabilities to enable. hmd.SetEnabledCaps(OculusWrap.OVR.HmdCaps.LowPersistence | OculusWrap.OVR.HmdCaps.DynamicPrediction); // Start the sensor which informs of the Rift's pose and motion hmd.ConfigureTracking(OculusWrap.OVR.TrackingCaps.ovrTrackingCap_Orientation | OculusWrap.OVR.TrackingCaps.ovrTrackingCap_MagYawCorrection | OculusWrap.OVR.TrackingCaps.ovrTrackingCap_Position, OculusWrap.OVR.TrackingCaps.None); // Create DirectX drawing device. device = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.None); ctx = device.ImmediateContext; Stopwatch sw = new Stopwatch(); sw.Start(); string effect_file = Path.Combine(Application.StartupPath, @"toonshader.fx.bin"); if (! File.Exists(effect_file)) { Console.WriteLine("File not found: " + effect_file); return false; } try { var shader_bytecode = ShaderBytecode.FromFile(effect_file); effect = new Effect(device, shader_bytecode); } catch (SharpDX.CompilationException e) { Console.WriteLine(e.Message + ": " + effect_file); return false; } sw.Stop(); Console.WriteLine("toonshader.fx.bin read time: " + sw.Elapsed); string techmap_file = Path.Combine(Application.StartupPath, @"techmap.txt"); if (!File.Exists(techmap_file)) { Console.WriteLine("File not found: " + techmap_file); return false; } techmap.Load(techmap_file); control.MouseDown += new MouseEventHandler(form_OnMouseDown); // Define the properties of the swap chain. SwapChainDescription swapChainDescription = DefineSwapChainDescription(control); // Create DirectX Graphics Interface factory, used to create the swap chain. dxgi_factory = new SharpDX.DXGI.Factory(); // Create the swap chain. swap_chain = new SwapChain(dxgi_factory, device, swapChainDescription); // Retrieve the back buffer of the swap chain. buf0 = swap_chain.GetBackBuffer<Texture2D>(0); buf0_view = new RenderTargetView(device, buf0); // Create a depth buffer, using the same width and height as the back buffer. Texture2DDescription depthBufferDescription = DefineDepthBufferDescription(control); // Create the depth buffer. ztex = new Texture2D(device, depthBufferDescription); ztex_view = new DepthStencilView(device, ztex); ctx.OutputMerger.SetRenderTargets(ztex_view, buf0_view); viewport = new Viewport(0, 0, hmd.Resolution.Width, hmd.Resolution.Height, 0.0f, 1.0f); ctx.Rasterizer.SetViewport(viewport); // Retrieve the DXGI device, in order to set the maximum frame latency. using (SharpDX.DXGI.Device1 dxgiDevice = device.QueryInterface<SharpDX.DXGI.Device1>()) { dxgiDevice.MaximumFrameLatency = 1; } layers = new OculusWrap.Layers(); layer_eye_fov = layers.AddLayerEyeFov(); CreateEyeTextures(); CreateMirrorTexture(control); World_variable = effect.GetVariableBySemantic("World").AsMatrix(); WorldView_variable = effect.GetVariableBySemantic("WorldView").AsMatrix(); WorldViewProjection_variable = effect.GetVariableBySemantic("WorldViewProjection").AsMatrix(); /* for HUD */ Projection_variable = effect.GetVariableBySemantic("Projection").AsMatrix(); LocalBoneMats_variable = effect.GetVariableByName("LocalBoneMats").AsMatrix(); LightDirForced_variable = effect.GetVariableByName("LightDirForced").AsVector(); UVSCR_variable = effect.GetVariableByName("UVSCR").AsVector(); cb_variable = effect.GetConstantBufferByName("cb"); ShadeTex_texture_variable = effect.GetVariableByName("ShadeTex_texture").AsShaderResource(); ColorTex_texture_variable = effect.GetVariableByName("ColorTex_texture").AsShaderResource(); //figures.Camera = camera; figures.TSOFileOpen += delegate(TSOFile tso) { tso.Open(device, effect); techmap.AssignTechniqueIndices(tso); }; // Define an input layout to be passed to the vertex shader. var technique = effect.GetTechniqueByIndex(0); il = new InputLayout(device, technique.GetPassByIndex(0).Description.Signature, TSOSubMesh.ie); // Setup the immediate context to use the shaders and model we defined. ctx.InputAssembler.InputLayout = il; DefineBlendState(); DefineDepthStencilState(); DefineRasterizerState(); main_camera = new Camera() { Position = ocu_config.Position, Rotation = Quaternion.Identity, }; directInput = new DirectInput(); keyboard = new Keyboard(directInput); keyboard.Acquire(); keyboardState = keyboard.GetCurrentState(); return true; }
/// <summary> /// deviceを作成します。 /// </summary> /// <param name="control">レンダリング先となるcontrol</param> /// <param name="ocu_config">設定</param> /// <returns>deviceの作成に成功したか</returns> public bool InitializeApplication(Control control, OcuConfig ocu_config) { this.ocu_config = ocu_config; oculus = new OculusWrap.Wrap(); // Initialize the Oculus runtime. bool success = oculus.Initialize(); if (!success) { MessageBox.Show("Failed to initialize the Oculus runtime library.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } // Use the head mounted display, if it's available, otherwise use the debug HMD. int numberOfHeadMountedDisplays = oculus.Hmd_Detect(); if (numberOfHeadMountedDisplays > 0) { hmd = oculus.Hmd_Create(0); } else { hmd = oculus.Hmd_CreateDebug(OculusWrap.OVR.HmdType.DK2); } if (hmd == null) { MessageBox.Show("Oculus Rift not detected.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } if (hmd.ProductName == string.Empty) { MessageBox.Show("The HMD is not enabled.", "There's a tear in the Rift", MessageBoxButtons.OK, MessageBoxIcon.Error); } // Specify which head tracking capabilities to enable. hmd.SetEnabledCaps(OculusWrap.OVR.HmdCaps.LowPersistence | OculusWrap.OVR.HmdCaps.DynamicPrediction); // Start the sensor which informs of the Rift's pose and motion hmd.ConfigureTracking(OculusWrap.OVR.TrackingCaps.ovrTrackingCap_Orientation | OculusWrap.OVR.TrackingCaps.ovrTrackingCap_MagYawCorrection | OculusWrap.OVR.TrackingCaps.ovrTrackingCap_Position, OculusWrap.OVR.TrackingCaps.None); // Create DirectX drawing device. device = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.None); ctx = device.ImmediateContext; Stopwatch sw = new Stopwatch(); sw.Start(); string effect_file = Path.Combine(Application.StartupPath, @"toonshader.fx.bin"); if (!File.Exists(effect_file)) { Console.WriteLine("File not found: " + effect_file); return(false); } try { var shader_bytecode = ShaderBytecode.FromFile(effect_file); effect = new Effect(device, shader_bytecode); } catch (SharpDX.CompilationException e) { Console.WriteLine(e.Message + ": " + effect_file); return(false); } sw.Stop(); Console.WriteLine("toonshader.fx.bin read time: " + sw.Elapsed); string techmap_file = Path.Combine(Application.StartupPath, @"techmap.txt"); if (!File.Exists(techmap_file)) { Console.WriteLine("File not found: " + techmap_file); return(false); } techmap.Load(techmap_file); control.MouseDown += new MouseEventHandler(form_OnMouseDown); // Define the properties of the swap chain. SwapChainDescription swapChainDescription = DefineSwapChainDescription(control); // Create DirectX Graphics Interface factory, used to create the swap chain. dxgi_factory = new SharpDX.DXGI.Factory(); // Create the swap chain. swap_chain = new SwapChain(dxgi_factory, device, swapChainDescription); // Retrieve the back buffer of the swap chain. buf0 = swap_chain.GetBackBuffer <Texture2D>(0); buf0_view = new RenderTargetView(device, buf0); // Create a depth buffer, using the same width and height as the back buffer. Texture2DDescription depthBufferDescription = DefineDepthBufferDescription(control); // Create the depth buffer. ztex = new Texture2D(device, depthBufferDescription); ztex_view = new DepthStencilView(device, ztex); ctx.OutputMerger.SetRenderTargets(ztex_view, buf0_view); viewport = new Viewport(0, 0, hmd.Resolution.Width, hmd.Resolution.Height, 0.0f, 1.0f); ctx.Rasterizer.SetViewport(viewport); // Retrieve the DXGI device, in order to set the maximum frame latency. using (SharpDX.DXGI.Device1 dxgiDevice = device.QueryInterface <SharpDX.DXGI.Device1>()) { dxgiDevice.MaximumFrameLatency = 1; } layers = new OculusWrap.Layers(); layer_eye_fov = layers.AddLayerEyeFov(); CreateEyeTextures(); CreateMirrorTexture(control); World_variable = effect.GetVariableBySemantic("World").AsMatrix(); WorldView_variable = effect.GetVariableBySemantic("WorldView").AsMatrix(); WorldViewProjection_variable = effect.GetVariableBySemantic("WorldViewProjection").AsMatrix(); /* for HUD */ Projection_variable = effect.GetVariableBySemantic("Projection").AsMatrix(); LocalBoneMats_variable = effect.GetVariableByName("LocalBoneMats").AsMatrix(); LightDirForced_variable = effect.GetVariableByName("LightDirForced").AsVector(); UVSCR_variable = effect.GetVariableByName("UVSCR").AsVector(); cb_variable = effect.GetConstantBufferByName("cb"); ShadeTex_texture_variable = effect.GetVariableByName("ShadeTex_texture").AsShaderResource(); ColorTex_texture_variable = effect.GetVariableByName("ColorTex_texture").AsShaderResource(); //figures.Camera = camera; figures.TSOFileOpen += delegate(TSOFile tso) { tso.Open(device, effect); techmap.AssignTechniqueIndices(tso); }; // Define an input layout to be passed to the vertex shader. var technique = effect.GetTechniqueByIndex(0); il = new InputLayout(device, technique.GetPassByIndex(0).Description.Signature, TSOSubMesh.ie); // Setup the immediate context to use the shaders and model we defined. ctx.InputAssembler.InputLayout = il; DefineBlendState(); DefineDepthStencilState(); DefineRasterizerState(); main_camera = new Camera() { Position = ocu_config.Position, Rotation = Quaternion.Identity, }; directInput = new DirectInput(); keyboard = new Keyboard(directInput); keyboard.Acquire(); keyboardState = keyboard.GetCurrentState(); return(true); }
private void InitializeDeviceResources(DXGI.SwapChain swapChain) { backbufferTexture = swapChain.GetBackBuffer <D3D11.Texture2D>(0); backbufferRTV = new D3D11.RenderTargetView(device, backbufferTexture); width = backbufferTexture.Description.Width; height = backbufferTexture.Description.Height; var depthBufferDesc = new D3D11.Texture2DDescription() { Width = width, Height = height, MipLevels = 1, ArraySize = 1, Format = DXGI.Format.D24_UNorm_S8_UInt, SampleDescription = new DXGI.SampleDescription(1, 0), Usage = D3D11.ResourceUsage.Default, BindFlags = D3D11.BindFlags.DepthStencil, CpuAccessFlags = D3D11.CpuAccessFlags.None, OptionFlags = D3D11.ResourceOptionFlags.None }; using (var depthStencilBufferTexture = new D3D11.Texture2D(device, depthBufferDesc)) { var depthStencilViewDesc = new D3D11.DepthStencilViewDescription() { Format = DXGI.Format.D24_UNorm_S8_UInt, Dimension = D3D11.DepthStencilViewDimension.Texture2D, Texture2D = new D3D11.DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }; depthDSV = new D3D11.DepthStencilView(device, depthStencilBufferTexture, depthStencilViewDesc); } var depthStencilDesc = new D3D11.DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = D3D11.DepthWriteMask.All, DepthComparison = D3D11.Comparison.Less, IsStencilEnabled = false, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = new D3D11.DepthStencilOperationDescription() { FailOperation = D3D11.StencilOperation.Keep, DepthFailOperation = D3D11.StencilOperation.Keep, PassOperation = D3D11.StencilOperation.Keep, Comparison = D3D11.Comparison.Always }, BackFace = new D3D11.DepthStencilOperationDescription() { FailOperation = D3D11.StencilOperation.Keep, DepthFailOperation = D3D11.StencilOperation.Keep, PassOperation = D3D11.StencilOperation.Keep, Comparison = D3D11.Comparison.Always } }; depthStencilState = new D3D11.DepthStencilState(device, depthStencilDesc); var rasterDesc = new D3D11.RasterizerStateDescription() { IsAntialiasedLineEnabled = false, CullMode = D3D11.CullMode.Back, DepthBias = 0, DepthBiasClamp = 0.0f, IsDepthClipEnabled = false, FillMode = D3D11.FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = 0.0f }; /*var blendDesc = new D3D11.BlendStateDescription(); * blendDesc.RenderTarget[0].IsBlendEnabled = true; * blendDesc.RenderTarget[0].SourceBlend = D3D11.BlendOption.SourceAlpha; * blendDesc.RenderTarget[0].DestinationBlend = D3D11.BlendOption.InverseSourceAlpha; * blendDesc.RenderTarget[0].BlendOperation = D3D11.BlendOperation.Add; * blendDesc.RenderTarget[0].SourceAlphaBlend = D3D11.BlendOption.Zero; * blendDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.Zero; * blendDesc.RenderTarget[0].AlphaBlendOperation = D3D11.BlendOperation.Add; * blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;*/ #if ALPHABLENDING var blendDesc = new D3D11.BlendStateDescription(); blendDesc.RenderTarget[0].IsBlendEnabled = true; blendDesc.RenderTarget[0].SourceBlend = D3D11.BlendOption.SourceAlpha; blendDesc.RenderTarget[0].DestinationBlend = D3D11.BlendOption.InverseSourceAlpha; blendDesc.RenderTarget[0].BlendOperation = D3D11.BlendOperation.Add; blendDesc.RenderTarget[0].SourceAlphaBlend = D3D11.BlendOption.Zero; blendDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.One; blendDesc.RenderTarget[0].AlphaBlendOperation = D3D11.BlendOperation.Add; blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All; #endif #if ADDITIVEBLENDING var blendDesc = new D3D11.BlendStateDescription(); blendDesc.RenderTarget[0].IsBlendEnabled = true; blendDesc.RenderTarget[0].SourceBlend = D3D11.BlendOption.SourceAlpha; blendDesc.RenderTarget[0].DestinationBlend = D3D11.BlendOption.DestinationAlpha; blendDesc.RenderTarget[0].BlendOperation = D3D11.BlendOperation.Add; blendDesc.RenderTarget[0].SourceAlphaBlend = D3D11.BlendOption.One; blendDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.One; blendDesc.RenderTarget[0].AlphaBlendOperation = D3D11.BlendOperation.Add; blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All; #endif // RenderTarget[0].BlendOpSharpDX.Direct3D11.BlendOperation.Add RenderTarget[0].SrcBlendAlphaSharpDX.Direct3D11.BlendOption.One // RenderTarget[0].DestBlendAlphaSharpDX.Direct3D11.BlendOption.Zero RenderTarget[0].BlendOpAlphaSharpDX.Direct3D11.BlendOperation.Add // RenderTarget[0].RenderTargetWriteMaskSharpDX.Direct3D11.ColorWriteMaskFlags.All blendState = new D3D11.BlendState(device, blendDesc); rasterizerState = new D3D11.RasterizerState(device, rasterDesc); }