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); }
// Initialize hardware-dependent resources. // Device-independent resources, such as ID2D1Geometry, are kept on the CPU. // Device-dependent resources, such as ID2D1RenderTarget and ID2D1LinearGradientBrush, directly map to resources on the GPU // (when hardware acceleration is available). // Rendering calls are performed by combining vertex and coverage information from a geometry with texturing information produced by the device-dependent resources. private void CreateDeviceResources() { // http://msdn.microsoft.com/zh-tw/library/windows/apps/dn481540.aspx // Unlike the original C++ sample, we don't have smart pointers so we need to // dispose Direct3D objects explicitly Utilities.Dispose(ref d3dDevice); Utilities.Dispose(ref d2dDevice); Utilities.Dispose(ref d2dContext); Utilities.Dispose(ref d2dFactory); #if DEBUG var debugLevel = SharpDX.Direct2D1.DebugLevel.Information; #else var debugLevel = SharpDX.Direct2D1.DebugLevel.None; #endif d2dFactory = new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded); // This flag adds support for surfaces with a different color channel ordering // than the API default. It is required for compatibility with Direct2D. var creationFlags = DeviceCreationFlags.BgraSupport; #if DEBUG // If the project is in a debug build, enable debugging via SDK Layers. creationFlags |= DeviceCreationFlags.Debug; #endif // This array defines the set of DirectX hardware feature levels this app will support. // Note the ordering should be preserved. // Don't forget to declare your application's minimum required feature level in its // description. All applications are assumed to support 9.1 unless otherwise stated. FeatureLevel[] featureLevels = { FeatureLevel.Level_11_1, FeatureLevel.Level_11_0, FeatureLevel.Level_10_1, FeatureLevel.Level_10_0, FeatureLevel.Level_9_3, FeatureLevel.Level_9_2, FeatureLevel.Level_9_1, }; // Create the Direct3D 11 API device object. d3dDevice = new Device(DriverType.Hardware, creationFlags, featureLevels); // Get the Direct3D 11.1 API device. // DXGI : DirectX Graphics Infrastructure // DXGI 是一組用來設定和管理低階圖形與圖形卡資源的 API // 為了直接存取 GPU 並管理其資源,必須有一個對應用程式描述它的方式。 // 您所需最重要的 GPU 資訊就是繪製像素的位置,這樣它才能夠將這些像素傳送到螢幕上。 // 這通常稱為「背景緩衝區」—GPU 記憶體中的一個位置,您可以在該處繪製像素, // 然後「翻轉」或「交換」,並在收到重新整理訊號時傳送到螢幕上。 // DXGI 可讓您取得該位置以及使用該緩衝區 (稱為「交換鏈結」, // 因為這是可交換的緩衝區鏈結,允許多個緩衝處理策略) 的方法。 using (var dxgiDevice = d3dDevice.QueryInterface<SharpDX.DXGI.Device>()) { // Create the Direct2D device object and a corresponding context. // 是 GPU 資源的虛擬表示法 // ID3D11Device 包含您不常呼叫的圖形方法,通常是在任何轉譯發生之前呼叫這些方法,用來取得和設定開始繪製像素時所需的一組資源。 d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice); // 是轉譯管線與處理程序的跨裝置抽象概念 // ID3D11DeviceContext 則包含您在每個框架呼叫的方法: // 在緩衝區與檢視及其他資源中載入、變更輸出合併與轉譯器狀態、管理著色器, // 以及繪製將這些資源在狀態與著色器之間傳遞的結果。 d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, DeviceContextOptions.EnableMultithreadedOptimizations); // Query for ISurfaceImageSourceNative interface. using (var sisNative = ComObject.QueryInterface<ISurfaceImageSourceNative>(this)) sisNative.Device = dxgiDevice; } setPrimitiveBlend(); }
/// <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; }
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); }