internal void ReleaseDevices()
 {
     IsRendererSuppressed = true;
     RenderTarget.Dispose();
     Backbuffer.Dispose();
     RenderTargetSurface.Dispose();
     RenderTargetView.Dispose();
     D2DDeviceContext.Dispose();
     D2DDevice.Dispose();
     D2DFactory.Dispose();
     DXGIDevice.Dispose();
     D3DDevice.Dispose();
     D3DDefaultDevice.Dispose();
     SwapChain.Dispose();
     SwapChain           = null;
     RenderTarget        = null;
     RenderTargetSurface = null;
     Backbuffer          = null;
     RenderTargetView    = null;
     D2DDeviceContext    = null;
     D2DFactory          = null;
     D2DDevice           = null;
     DXGIDevice          = null;
     D3DDevice           = null;
     D3DDefaultDevice    = null;
 }
Пример #2
0
        protected override void CreateImpl()
        {
            var swapChainDesc = new SwapChainDescription()
            {
                BufferCount = (int)Desc.BufferCount,
                ModeDescription = new ModeDescription((int) Desc.Width, (int)Desc.Height, new Rational(0,0), Memory.Enums.ToDXGIFormat[(int)Desc.Format]),
                Usage = Usage.RenderTargetOutput,
                SwapEffect = SwapEffect.FlipDiscard,
                OutputHandle = Desc.WindowHandle,
                SampleDescription = new SampleDescription
                {
                    Count = (int) Desc.SampleCount,
                    Quality = (int) Desc.SampleQuality
                },
                IsWindowed = !Desc.Fullscreen
            };
            using (var factory = new Factory4())
            {
                var tempSwapChain = new SharpDX.DXGI.SwapChain(factory, ((CommandQueue)Desc.AssociatedGraphicsQueue).CommandQueueD3D12, swapChainDesc);
                SwapChainDXGI = tempSwapChain.QueryInterface<SwapChain3>();
                tempSwapChain.Dispose();
                CurrentBackBufferIndex = (uint)SwapChainDXGI.CurrentBackBufferIndex;
            }

            SwapChainDXGI.DebugName = Label;

            Log.Info("Created SwapChain");
        }
Пример #3
0
        /// <summary>
        /// Disposes of object resources.
        /// </summary>
        /// <param name="disposeManagedResources">If true, managed resources should be
        /// disposed of in addition to unmanaged resources.</param>
        protected virtual void Dispose(bool disposeManagedResources)
        {
            if (disposeManagedResources)
            {
                _d3d11Device.Dispose();
                _dxgiDevice.Dispose();
                _backBuffer.Dispose();
                _targetBitmap.Dispose();
                _backBuffer2.Dispose();
                _targetBitmap2.Dispose();
                _d2dDevice.Dispose();
                swapChain.Dispose();
                swapChain2.Dispose();
                d2dContext.Dispose();
                d2dContext2.Dispose();
                dw_Factory.Dispose();
            }

            _d3d11Device   = null;
            _dxgiDevice    = null;
            _backBuffer    = null;
            _targetBitmap  = null;
            _backBuffer2   = null;
            _targetBitmap2 = null;
            _d2dDevice     = null;
            swapChain      = null;
            swapChain2     = null;
            d2dContext     = null;
            d2dContext2    = null;
            dw_Factory     = null;
        }
Пример #4
0
        protected override void CreateImpl()
        {
            var swapChainDesc = new SwapChainDescription()
            {
                BufferCount       = (int)Desc.BufferCount,
                ModeDescription   = new ModeDescription((int)Desc.Width, (int)Desc.Height, new Rational(0, 0), Memory.Enums.ToDXGIFormat[(int)Desc.Format]),
                Usage             = Usage.RenderTargetOutput,
                SwapEffect        = SwapEffect.FlipDiscard,
                OutputHandle      = Desc.WindowHandle,
                SampleDescription = new SampleDescription
                {
                    Count   = (int)Desc.SampleCount,
                    Quality = (int)Desc.SampleQuality
                },
                IsWindowed = !Desc.Fullscreen
            };

            using (var factory = new Factory4())
            {
                var tempSwapChain = new SharpDX.DXGI.SwapChain(factory, ((CommandQueue)Desc.AssociatedGraphicsQueue).CommandQueueD3D12, swapChainDesc);
                SwapChainDXGI = tempSwapChain.QueryInterface <SwapChain3>();
                tempSwapChain.Dispose();
                CurrentBackBufferIndex = (uint)SwapChainDXGI.CurrentBackBufferIndex;
            }

            SwapChainDXGI.DebugName = Label;

            Log.Info("Created SwapChain");
        }
        public void ConstructRenderAndResource(double width, double height)
        {
            float dpiX, dpiY;

            this.GetDpi(out dpiX, out dpiY);

            var desc = new DXGI.SwapChainDescription()
            {
                BufferCount     = 1,
                ModeDescription = new DXGI.ModeDescription((int)width, (int)height,
                                                           new DXGI.Rational(60, 1), DXGI.Format.B8G8R8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = TextBox.Handle,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                SwapEffect        = DXGI.SwapEffect.Discard,
                Usage             = DXGI.Usage.RenderTargetOutput
            };

            this.swapchain = new DXGI.SwapChain(factory_dxgi, device, desc);

            this.device2d = new D2D.Device1(this._factory.D2DFactory, device_dxgi);

            this.render = new D2D.DeviceContext1(this.device2d, D2D.DeviceContextOptions.None);

            D2D.BitmapProperties bmpProp = new D2D.BitmapProperties();
            bmpProp.DpiX        = dpiX;
            bmpProp.DpiY        = dpiY;
            bmpProp.PixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied);
            this.bmp_d2d        = new D2D.Bitmap(this.render, DXGI.Surface.FromSwapChain(swapchain, 0), bmpProp);
            this.cachedBitMap   = new D2D.Bitmap(this.render, new SharpDX.Size2((int)width, (int)height), bmpProp);
            this.hasCache       = false;

            this.render.Target = this.bmp_d2d;

            this.textRender = new CustomTextRenderer(this._factory, this.Foreground);

            this.renderSize = new Size(width, height);

            //デフォルト値を反映させる
            this.Foreground        = ToColor4(this.TextBox.Foreground);
            this.Background        = ToColor4(this.TextBox.Background);
            this.ControlChar       = ToColor4(this.TextBox.ControlChar);
            this.Url               = ToColor4(this.TextBox.Url);
            this.Keyword1          = ToColor4(this.TextBox.Keyword1);
            this.Keyword2          = ToColor4(this.TextBox.Keyword2);
            this.Literal           = ToColor4(this.TextBox.Literal);
            this.Comment           = ToColor4(this.TextBox.Comment);
            this.Hilight           = ToColor4(this.TextBox.Hilight);
            this.LineMarker        = ToColor4(this.TextBox.LineMarker);
            this.InsertCaret       = ToColor4(this.TextBox.InsertCaret);
            this.OverwriteCaret    = ToColor4(this.TextBox.OverwriteCaret);
            this.UpdateArea        = ToColor4(this.TextBox.UpdateArea);
            this.HilightForeground = ToColor4(this.TextBox.HilightForeground);
        }
Пример #6
0
        public override void Hook()
        {
            this.DebugMessage("Hook: Begin");

            // Determine method addresses in Direct3D10.Device, and DXGI.SwapChain
            if (_d3d10VTblAddresses == null)
            {
                _d3d10VTblAddresses         = new List <IntPtr>();
                _dxgiSwapChainVTblAddresses = new List <IntPtr>();
                this.DebugMessage("Hook: Before device creation");
                using (var factory = new Factory(IntPtr.Zero)) //???????????????????????????
                {
                    using (var device = new Device(factory.GetAdapter(0), DeviceCreationFlags.None))
                    {
                        this.DebugMessage("Hook: Device created");
                        _d3d10VTblAddresses.AddRange(GetVTblAddresses(device.NativePointer, D3D10_DEVICE_METHOD_COUNT));

                        using (var renderForm = new System.Windows.Forms.Form())
                        {
                            using (SharpDX.DXGI.SwapChain sc = new SharpDX.DXGI.SwapChain(factory, device, DXGI.CreateSwapChainDescription(renderForm.Handle)))
                            {
                                _dxgiSwapChainVTblAddresses.AddRange(GetVTblAddresses(sc.NativePointer, DXGI.DXGI_SWAPCHAIN_METHOD_COUNT));
                            }
                        }
                    }
                }
            }

            // We will capture the backbuffer here
            DXGISwapChain_PresentHook = LocalHook.Create(
                _dxgiSwapChainVTblAddresses[(int)DXGI.DXGISwapChainVTbl.Present],
                new DXGISwapChain_PresentDelegate(PresentHook),
                this);

            // We will capture target/window resizes here
            DXGISwapChain_ResizeTargetHook = LocalHook.Create(
                _dxgiSwapChainVTblAddresses[(int)DXGI.DXGISwapChainVTbl.ResizeTarget],
                new DXGISwapChain_ResizeTargetDelegate(ResizeTargetHook),
                this);

            /*
             * Don't forget that all hooks will start deactivated...
             * The following ensures that all threads are intercepted:
             * Note: you must do this for each hook.
             */
            DXGISwapChain_PresentHook.ThreadACL.SetExclusiveACL(new Int32[1]);

            DXGISwapChain_ResizeTargetHook.ThreadACL.SetExclusiveACL(new Int32[1]);

            Hooks.Add(DXGISwapChain_PresentHook);
            Hooks.Add(DXGISwapChain_ResizeTargetHook);
        }
Пример #7
0
        public SwapChain(Form form, Renderer renderer, int fullScreenWidth, int fullScreenHeight)
        {
            if (fullScreenWidth == 0 || fullScreenHeight == 0)
            {
                fullScreenWidth  = SystemInformation.VirtualScreen.Width;
                fullScreenHeight = SystemInformation.VirtualScreen.Height;
            }
            this.fullScreenWidth  = fullScreenWidth;
            this.fullScreenHeight = fullScreenHeight;

            formWidth  = form.ClientSize.Width;
            formHeight = form.ClientSize.Height;

            var swapChainDescriptor = new SwapChainDescription()
            {
                BufferCount       = 1,
                Usage             = Usage.RenderTargetOutput,
                Flags             = SwapChainFlags.AllowModeSwitch,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(0, 1), Format.R8G8B8A8_UNorm),
                OutputHandle      = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard
            };

            using (var factory = new Factory1()) {
                swapChain = new DXSwapChain(factory, renderer.Device, swapChainDescriptor);
            }
            using (var resource = Resource.FromSwapChain <Texture2D>(swapChain, 0)) {
                RenderTarget = new RenderTargetGroup(resource);
            }

            using (var fac = swapChain.GetParent <Factory>()) {
                fac.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAltEnter);
            }

            form.ResizeBegin += (o, e) => {
                formHeight = ((Form)o).Height;
                formWidth  = ((Form)o).Width;
            };
            form.ResizeBegin += (o, e) => {
                isResizing = true;
            };
            form.ResizeEnd += (o, e) => {
                isResizing = false;
                HandleResize(o, e);
            };
            form.KeyDown += HandleKeyDown;

            form.SizeChanged += HandleResize;
        }
Пример #8
0
        public Renderer(D3D11.Device device, DXGI.SwapChain swapChain)
        {
            this.device = device;

            deviceContext = device.ImmediateContext;

            InitializeDeviceResources(swapChain);
            InitializeShaders();
            InitializeTriangle();

            postEffect = new PostEffect(device);

            stopWatch = Stopwatch.StartNew();
        }
Пример #9
0
        public void Dispose()
        {
            localHook.ThreadACL.SetInclusiveACL(new int[] { 0 });
            localHook.Dispose();
            localHook = null;

            swapChain.Dispose();
            swapChain = null;

            device.Dispose();
            device = null;

            DestroyWindow(hwnd);
            hwnd = IntPtr.Zero;
        }
Пример #10
0
        public Renderer(D3D11.Device device, DXGI.SwapChain swapChain)
        {
            this.device = device;

            deviceContext = device.ImmediateContext;

            InitializeDeviceResources(swapChain);
            InitializeShaders();
            InitializeTriangle();

            softwareRasterizer = new SoftwareRasterizer(this);

            mode = RenderMode.RenderModeHardware;

            stopWatch = Stopwatch.StartNew();
        }
Пример #11
0
        public void Initialize()
        {
            // Lets create a present command queue
            var queueDesc = new CommandQueueDescription(CommandListType.Direct);

            NativeCommandQueue = Device.NativeDevice.CreateCommandQueue(queueDesc);

            // Descirbe and create the swap chain
            using (var factory = new Factory4())
            {
                var width  = Description.Width;
                var height = Description.Height;
                var swapChainDescription = new SwapChainDescription
                {
                    BufferCount       = BackBufferCount,
                    ModeDescription   = new ModeDescription(width, height, new Rational(60, 1), Format.B8G8R8A8_UNorm),
                    Usage             = Usage.RenderTargetOutput,
                    SwapEffect        = SwapEffect.FlipDiscard,
                    OutputHandle      = Description.WindowHandle,
                    Flags             = SwapChainFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed        = true
                };
                using (var tempSwapChain = new SharpDX.DXGI.SwapChain(factory, NativeCommandQueue, swapChainDescription))
                {
                    NativeSwapChain = tempSwapChain.QueryInterface <SwapChain3>();
                    BackBufferIndex = NativeSwapChain.CurrentBackBufferIndex;
                }
            }
            // We need now to retrieve the back buffers:
            // 1) We need a heap to store the views
            BackBuffers = new Texture[BackBufferCount];
            for (int i = 0; i < BackBufferCount; i++)
            {
                BackBuffers[i] = new Texture(Device);
                BackBuffers[i].Initialize(NativeSwapChain.GetBackBuffer <Resource>(i));
            }

            BackBuffer = new Texture(Device);
            BackBuffer.Initialize(NativeSwapChain.GetBackBuffer <Resource>(BackBufferIndex));

            CreateDepthStencilBuffer();

            Device.PrintLiveObjects();
        }
Пример #12
0
        private void createSwapChain()
        {
            lock (deviceManager.DeviceLock)
            {
                var factory = new DXGI.Factory();

                var description = new DXGI.SwapChainDescription()
                {
                    BufferCount     = 1,
                    ModeDescription =
                        new DXGI.ModeDescription(
                            control.ClientSize.Width,
                            control.ClientSize.Height,
                            new DXGI.Rational(60, 1),
                            DXGI.Format.R8G8B8A8_UNorm),
                    IsWindowed        = true,
                    SampleDescription = new DXGI.SampleDescription(1, 0),
                    SwapEffect        = DXGI.SwapEffect.Discard,
                    Usage             = DXGI.Usage.RenderTargetOutput,
                    OutputHandle      = control.Handle
                };

                swapChain = new DXGI.SwapChain(factory, deviceContext.Device, description);

                backbuffer     = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(swapChain, 0);
                backbufferView = new D3D11.RenderTargetView(deviceContext.Device, backbuffer);
            }

            var d2dFactory = deviceManager.Direct2dFactory;
            var surface    = backbuffer.QueryInterface <DXGI.Surface>();

            renderTarget = new D2D.RenderTarget(
                d2dFactory,
                surface,
                new D2D.RenderTargetProperties(
                    new D2D.PixelFormat(
                        DXGI.Format.Unknown,
                        D2D.AlphaMode.Premultiplied)));

            renderTarget.AntialiasMode = D2D.AntialiasMode.Aliased;

            createViewport();
        }
Пример #13
0
        public override void Cleanup()
        {
            DeviceDebug device3DDebug = null;

            if (IsDebugMode)
            {
                device3DDebug = new DeviceDebug(DeviceRef);
            }

            SwapChainRef?.Dispose();
            SwapChainRef = null;
            base.Cleanup();

            if (IsDebugMode && device3DDebug != null)
            {
                device3DDebug.ReportLiveDeviceObjects(ReportingLevel.Detail);
                System.Diagnostics.Debug.Write(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects());
            }
        }
Пример #14
0
        protected override void OnHandleDestroyed(EventArgs e)
        {
            if (_swapChain != null)
            {
                _swapChain.Dispose();
                _swapChain = null;
            }

            if (_d3dDevice != null)
            {
                if (_d3dDevice.ImmediateContext.Rasterizer.State != null)
                {
                    _d3dDevice.ImmediateContext.Rasterizer.State.Dispose();
                }
                _d3dDevice.Dispose();
                _d3dDevice = null;
            }

            base.OnHandleDestroyed(e);
        }
Пример #15
0
        public SwapChain(
            GraphicsDevice graphicsDevice,
            IntPtr windowHandle,
            int backBufferCount,
            int width,
            int height)
        {
            _graphicsDevice  = graphicsDevice;
            _backBufferCount = backBufferCount;

            DeviceSwapChain = AddDisposable(CreateSwapChain(
                                                windowHandle,
                                                _graphicsDevice.Device,
                                                _graphicsDevice.BackBufferFormat,
                                                backBufferCount,
                                                width,
                                                height));

            Resize(width, height);
        }
Пример #16
0
        public SwapChain(IntPtr hwnd, int width, int height)
        {
            Width  = width;
            Height = height;

            var desc = new SwapChainDescription
            {
                BufferCount       = bufferCount,
                Flags             = flags,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(width, height, new Rational(0, 1), Format.R8G8B8A8_UNorm),
                OutputHandle      = hwnd,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.FlipSequential,
                Usage             = Usage.RenderTargetOutput
            };

            var device = Device.Get();

            chain = new SharpDX.DXGI.SwapChain(device.FactoryHandle, device.Handle, desc);
        }
Пример #17
0
        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);
        }
Пример #18
0
 public void InitScreen1(IntPtr handle)
 {
     d2dContext        = new D2D1.DeviceContext(_d2dDevice, D2D1.DeviceContextOptions.None);
     d2dContextCdgText = new D2D1.DeviceContext(_d2dDevice, D2D1.DeviceContextOptions.None);
     // DXGI SwapChain
     DXGI.SwapChainDescription swapChainDesc = new DXGI.SwapChainDescription()
     {
         BufferCount       = 1,
         Usage             = DXGI.Usage.RenderTargetOutput,
         OutputHandle      = handle,
         IsWindowed        = true,
         ModeDescription   = new DXGI.ModeDescription(0, 0, new DXGI.Rational(60, 1), DXGI.Format.B8G8R8A8_UNorm),
         SampleDescription = new DXGI.SampleDescription(1, 0),
         SwapEffect        = DXGI.SwapEffect.Discard
     };
     swapChain = new DXGI.SwapChain(_dxgiDevice.GetParent <DXGI.Adapter>().GetParent <DXGI.Factory>(), _d3d11Device, swapChainDesc);
     // BackBuffer
     _backBuffer = DXGI.Surface.FromSwapChain(swapChain, 0);
     //BackBuffer DeviceContext
     _targetBitmap     = new D2D1.Bitmap1(d2dContext, _backBuffer);
     d2dContext.Target = _targetBitmap;
     // _dcBrush = new D2D1.SolidColorBrush(d2dContext, Color.Black);
 }
Пример #19
0
        private List<IntPtr> GetProcAddress()
        {
            var address = new List<IntPtr>();

            _device12 = new SharpDX.Direct3D12.Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0);
            using (var renderForm = new Form())
            {
                using (var factory = new SharpDX.DXGI.Factory4())
                {
                    _commandQueue
                        = _device12.CreateCommandQueue(new SharpDX.Direct3D12.CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Direct));

                    _commandAllocator
                        = _device12.CreateCommandAllocator(CommandListType.Direct);

                    _commandList
                        = _device12.CreateCommandList(CommandListType.Direct, _commandAllocator, null);

                    var swapChainDesc = new SharpDX.DXGI.SwapChainDescription()
                    {
                        BufferCount = 2,
                        ModeDescription = new SharpDX.DXGI.ModeDescription(100, 100, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm),
                        Usage = SharpDX.DXGI.Usage.RenderTargetOutput,
                        SwapEffect = SharpDX.DXGI.SwapEffect.FlipDiscard,
                        OutputHandle = renderForm.Handle,
                        Flags = SwapChainFlags.AllowModeSwitch,
                        SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                        IsWindowed = true
                    };

                    var tempSwapChain = new SharpDX.DXGI.SwapChain(factory, _commandQueue, swapChainDesc);
                    _swapChain = tempSwapChain.QueryInterface<SharpDX.DXGI.SwapChain3>();
                    tempSwapChain.Dispose();
                }

                if (_device12 != null && _swapChain != null)
                {
                    address.AddRange(GetVTblAddresses(_device12.NativePointer, 44));
                    address.AddRange(GetVTblAddresses(_commandQueue.NativePointer, 19));
                    address.AddRange(GetVTblAddresses(_commandAllocator.NativePointer, 9));
                    address.AddRange(GetVTblAddresses(_commandList.NativePointer, 60));
                    address.AddRange(GetVTblAddresses(_swapChain.NativePointer, 18));

                    _device12.Dispose();
                    _device12 = null;

                    _commandQueue.Dispose();
                    _commandQueue = null;

                    _commandAllocator.Dispose();
                    _commandAllocator = null;

                    _commandList.Dispose();
                    _commandList = null;

                    _swapChain.Dispose();
                    _swapChain = null;
                }
            }

            return address;
        }
Пример #20
0
        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));
        }
Пример #21
0
        private void createSwapChain()
        {
            lock (deviceManager.DeviceLock)
            {
                var factory = new DXGI.Factory();

                var description = new DXGI.SwapChainDescription()
                {
                    BufferCount = 1,
                    ModeDescription =
                        new DXGI.ModeDescription(
                            control.ClientSize.Width,
                            control.ClientSize.Height,
                            new DXGI.Rational(60, 1),
                            DXGI.Format.R8G8B8A8_UNorm),
                    IsWindowed = true,
                    SampleDescription = new DXGI.SampleDescription(1, 0),
                    SwapEffect = DXGI.SwapEffect.Discard,
                    Usage = DXGI.Usage.RenderTargetOutput,
                    OutputHandle = control.Handle
                };

                swapChain = new DXGI.SwapChain(factory, deviceContext.Device, description);

                backbuffer = D3D11.Texture2D.FromSwapChain<D3D11.Texture2D>(swapChain, 0);
                backbufferView = new D3D11.RenderTargetView(deviceContext.Device, backbuffer);
            }

            var d2dFactory = deviceManager.Direct2dFactory;
            var surface = backbuffer.QueryInterface<DXGI.Surface>();
            renderTarget = new D2D.RenderTarget(
                d2dFactory,
                surface,
                new D2D.RenderTargetProperties(
                    new D2D.PixelFormat(
                        DXGI.Format.Unknown,
                        D2D.AlphaMode.Premultiplied)));

            renderTarget.AntialiasMode = D2D.AntialiasMode.Aliased;

            createViewport();
        }
Пример #22
0
        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);
        }
Пример #23
0
        /// <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;
        }
Пример #24
0
        public override void Hook()
        {
            this.DebugMessage("Hook: Begin");

            // Determine method addresses in Direct3D10.Device, and DXGI.SwapChain
            if (_d3d10VTblAddresses == null)
            {
                _d3d10VTblAddresses = new List<IntPtr>();
                _dxgiSwapChainVTblAddresses = new List<IntPtr>();
                this.DebugMessage("Hook: Before device creation");
                using (var factory = new Factory())
                {
                    using (var device = new Device(factory.GetAdapter(0), DeviceCreationFlags.None))
                    {
                        this.DebugMessage("Hook: Device created");
                        _d3d10VTblAddresses.AddRange(GetVTblAddresses(device.NativePointer, D3D10_DEVICE_METHOD_COUNT));

                        using (var renderForm = new System.Windows.Forms.Form())
                        {
                            using (SharpDX.DXGI.SwapChain sc = new SharpDX.DXGI.SwapChain(factory, device, DXGI.CreateSwapChainDescription(renderForm.Handle)))
                            {
                                _dxgiSwapChainVTblAddresses.AddRange(GetVTblAddresses(sc.NativePointer, DXGI.DXGI_SWAPCHAIN_METHOD_COUNT));
                            }
                        }
                    }
                }
            }

            // We will capture the backbuffer here
            DXGISwapChain_PresentHook = new Hook<DXGISwapChain_PresentDelegate>(
                _dxgiSwapChainVTblAddresses[(int)DXGI.DXGISwapChainVTbl.Present],
                new DXGISwapChain_PresentDelegate(PresentHook),
                this);

            // We will capture target/window resizes here
            DXGISwapChain_ResizeTargetHook = new Hook<DXGISwapChain_ResizeTargetDelegate>(
                _dxgiSwapChainVTblAddresses[(int)DXGI.DXGISwapChainVTbl.ResizeTarget],
                new DXGISwapChain_ResizeTargetDelegate(ResizeTargetHook),
                this);

            /*
             * Don't forget that all hooks will start deactivated...
             * The following ensures that all threads are intercepted:
             * Note: you must do this for each hook.
             */
            DXGISwapChain_PresentHook.Activate();

            DXGISwapChain_ResizeTargetHook.Activate();

            Hooks.Add(DXGISwapChain_PresentHook);
            Hooks.Add(DXGISwapChain_ResizeTargetHook);
        }
Пример #25
0
        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);
        }
Пример #26
0
        /// <summary>
        /// Function to intialize the swap chain.
        /// </summary>
        internal void Initialize()
        {
            var D3DSettings = new GI.SwapChainDescription();

            // Resize the window to match requested mode size.
            if ((_parentForm == Settings.Window) && (Settings.IsWindowed) && (!Settings.NoClientResize))
            {
                _parentForm.ClientSize = new Size(Settings.VideoMode.Width, Settings.VideoMode.Height);
            }

            AutoResize = !Settings.NoClientResize;
            Graphics.GetFullScreenSwapChains();
            D3DSettings.BufferCount = Settings.BufferCount;
            D3DSettings.Flags       = GI.SwapChainFlags.AllowModeSwitch;

            D3DSettings.IsWindowed        = true;
            D3DSettings.ModeDescription   = GorgonVideoMode.Convert(Settings.VideoMode);
            D3DSettings.OutputHandle      = Settings.Window.Handle;
            D3DSettings.SampleDescription = GorgonMultisampling.Convert(Settings.Multisampling);
            D3DSettings.SwapEffect        = GorgonSwapChainSettings.Convert(Settings.SwapEffect);

            if ((Settings.Flags & SwapChainUsageFlags.RenderTarget) == SwapChainUsageFlags.RenderTarget)
            {
                D3DSettings.Usage = GI.Usage.RenderTargetOutput;
            }

            if ((Settings.Flags & SwapChainUsageFlags.AllowShaderView) == SwapChainUsageFlags.AllowShaderView)
            {
                D3DSettings.Usage |= GI.Usage.ShaderInput;
            }

            if ((Settings.Flags & SwapChainUsageFlags.AllowUnorderedAccessView) == SwapChainUsageFlags.AllowUnorderedAccessView)
            {
                D3DSettings.Usage |= GI.Usage.UnorderedAccess;
            }

            Gorgon.Log.Print("GorgonSwapChain '{0}': Creating D3D11 swap chain...", LoggingLevel.Simple, Name);
            GISwapChain = new GI.SwapChain(Graphics.GIFactory, Graphics.D3DDevice, D3DSettings)
            {
                DebugName = Name + " DXGISwapChain"
            };

            // Due to an issue with winforms and DXGI, we have to manually handle transitions ourselves.
            Graphics.GIFactory.MakeWindowAssociation(Settings.Window.Handle, GI.WindowAssociationFlags.IgnoreAll);

            CreateResources();

            if (!Settings.IsWindowed)
            {
                ModeStateUpdate();
            }

            Settings.Window.Resize += Window_Resize;

            if (_parentForm == null)
            {
                return;
            }

            _parentForm.ResizeBegin += _parentForm_ResizeBegin;
            _parentForm.ResizeEnd   += _parentForm_ResizeEnd;
        }
Пример #27
0
        void CreateDevice(System.Drawing.Size size, IntPtr hwnd)
        {
            RenderViewSize = size;
            ControlHandle = hwnd;

            //create device and swapchain
            DriverType driverType = DriverType.Hardware;
            DeviceCreationFlags flags = DeviceCreationFlags.None;
            if (Config.DebugMode) flags |= DeviceCreationFlags.Debug;

            FeatureLevel[] levels = new FeatureLevel[] { FeatureLevel.Level_11_0, FeatureLevel.Level_10_1, FeatureLevel.Level_10_0 };

            SwapChainDescription desc = new SwapChainDescription();
            desc.BufferCount = 1;
            desc.Flags = SharpDX.DXGI.SwapChainFlags.None;
            desc.IsWindowed = true;
            desc.ModeDescription = new ModeDescription(RenderViewSize.Width, RenderViewSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm);
            desc.OutputHandle = ControlHandle;
            desc.SampleDescription = new SampleDescription(Config.MSAASampleCount, Config.MSAAQuality);
            desc.SwapEffect = SwapEffect.Discard;
            desc.Usage = Usage.RenderTargetOutput;

            SharpDX.Direct3D11.Device createdDevice;
            SharpDX.DXGI.SwapChain createdSwapChain;
            SharpDX.Direct3D11.Device.CreateWithSwapChain(driverType, flags, levels, desc, out createdDevice, out createdSwapChain);

            // Store references
            this.SwapChain = createdSwapChain;
            this.Device = createdDevice;
            this.DeviceContext = createdDevice.ImmediateContext;

            this.SwapChain.DebugName = "Lilium";
            this.Device.DebugName = "Lilium";
            this.DeviceContext.DebugName = "Lilium";

            // Ignore all windows events
            var factory = SwapChain.GetParent<Factory>();
            factory.MakeWindowAssociation(ControlHandle, WindowAssociationFlags.IgnoreAll);

            ResizeBuffers();

            renderTimer = new Timer();
            renderTimer.Tick += renderTimer_TickUpdate;
            renderTimer.Interval = 1;
            renderTimer.Start();
        }
Пример #28
0
        private static void Main()
        {
            RenderForm form = new RenderForm("OculusWrap SharpDX demo");

            IntPtr          sessionPtr;
            InputLayout     inputLayout          = null;
            Buffer          contantBuffer        = null;
            Buffer          vertexBuffer         = null;
            ShaderSignature shaderSignature      = null;
            PixelShader     pixelShader          = null;
            ShaderBytecode  pixelShaderByteCode  = null;
            VertexShader    vertexShader         = null;
            ShaderBytecode  vertexShaderByteCode = null;
            Texture2D       mirrorTextureD3D     = null;

            EyeTexture[]      eyeTextures                = null;
            DeviceContext     immediateContext           = null;
            DepthStencilState depthStencilState          = null;
            DepthStencilView  depthStencilView           = null;
            Texture2D         depthBuffer                = null;
            RenderTargetView  backBufferRenderTargetView = null;
            Texture2D         backBuffer = null;

            SharpDX.DXGI.SwapChain swapChain = null;
            Factory       factory            = null;
            MirrorTexture mirrorTexture      = null;
            Guid          textureInterfaceId = new Guid("6f15aaf2-d208-4e89-9ab4-489535d34f9c");                                                            // Interface ID of the Direct3D Texture2D interface.

            Result result;

            OvrWrap OVR = OvrWrap.Create();

            // Define initialization parameters with debug flag.
            InitParams initializationParameters = new InitParams();

            initializationParameters.Flags = InitFlags.Debug | InitFlags.RequestVersion;
            initializationParameters.RequestedMinorVersion = 17;

            // Initialize the Oculus runtime.
            string errorReason = null;

            try
            {
                result = OVR.Initialize(initializationParameters);

                if (result < Result.Success)
                {
                    errorReason = result.ToString();
                }
            }
            catch (Exception ex)
            {
                errorReason = ex.Message;
            }

            if (errorReason != null)
            {
                MessageBox.Show("Failed to initialize the Oculus runtime library:\r\n" + errorReason, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Use the head mounted display.
            sessionPtr = IntPtr.Zero;
            var graphicsLuid = new GraphicsLuid();

            result = OVR.Create(ref sessionPtr, ref graphicsLuid);
            if (result < Result.Success)
            {
                MessageBox.Show("The HMD is not enabled: " + result.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var hmdDesc = OVR.GetHmdDesc(sessionPtr);


            try
            {
                // Create a set of layers to submit.
                eyeTextures = new EyeTexture[2];

                // Create DirectX drawing device.
                SharpDX.Direct3D11.Device device = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.Debug);

                // Create DirectX Graphics Interface factory, used to create the swap chain.
                factory = new SharpDX.DXGI.Factory4();

                immediateContext = device.ImmediateContext;

                // Define the properties of the swap chain.
                SwapChainDescription swapChainDescription = new SwapChainDescription();
                swapChainDescription.BufferCount            = 1;
                swapChainDescription.IsWindowed             = true;
                swapChainDescription.OutputHandle           = form.Handle;
                swapChainDescription.SampleDescription      = new SampleDescription(1, 0);
                swapChainDescription.Usage                  = Usage.RenderTargetOutput | Usage.ShaderInput;
                swapChainDescription.SwapEffect             = SwapEffect.Sequential;
                swapChainDescription.Flags                  = SwapChainFlags.AllowModeSwitch;
                swapChainDescription.ModeDescription.Width  = form.Width;
                swapChainDescription.ModeDescription.Height = form.Height;
                swapChainDescription.ModeDescription.Format = Format.R8G8B8A8_UNorm;
                swapChainDescription.ModeDescription.RefreshRate.Numerator   = 0;
                swapChainDescription.ModeDescription.RefreshRate.Denominator = 1;

                // Create the swap chain.
                swapChain = new SwapChain(factory, device, swapChainDescription);

                // Retrieve the back buffer of the swap chain.
                backBuffer = swapChain.GetBackBuffer <Texture2D>(0);
                backBufferRenderTargetView = new RenderTargetView(device, backBuffer);

                // Create a depth buffer, using the same width and height as the back buffer.
                Texture2DDescription depthBufferDescription = new Texture2DDescription();
                depthBufferDescription.Format            = Format.D32_Float;
                depthBufferDescription.ArraySize         = 1;
                depthBufferDescription.MipLevels         = 1;
                depthBufferDescription.Width             = form.Width;
                depthBufferDescription.Height            = form.Height;
                depthBufferDescription.SampleDescription = new SampleDescription(1, 0);
                depthBufferDescription.Usage             = ResourceUsage.Default;
                depthBufferDescription.BindFlags         = BindFlags.DepthStencil;
                depthBufferDescription.CpuAccessFlags    = CpuAccessFlags.None;
                depthBufferDescription.OptionFlags       = ResourceOptionFlags.None;

                // Define how the depth buffer will be used to filter out objects, based on their distance from the viewer.
                DepthStencilStateDescription depthStencilStateDescription = new DepthStencilStateDescription();
                depthStencilStateDescription.IsDepthEnabled  = true;
                depthStencilStateDescription.DepthComparison = Comparison.Less;
                depthStencilStateDescription.DepthWriteMask  = DepthWriteMask.Zero;

                // Create the depth buffer.
                depthBuffer       = new Texture2D(device, depthBufferDescription);
                depthStencilView  = new DepthStencilView(device, depthBuffer);
                depthStencilState = new DepthStencilState(device, depthStencilStateDescription);

                var viewport = new Viewport(0, 0, hmdDesc.Resolution.Width, hmdDesc.Resolution.Height, 0.0f, 1.0f);

                immediateContext.OutputMerger.SetDepthStencilState(depthStencilState);
                immediateContext.OutputMerger.SetRenderTargets(depthStencilView, backBufferRenderTargetView);
                immediateContext.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;
                }

                var layerEyeFov = new LayerEyeFov();
                layerEyeFov.Header.Type  = LayerType.EyeFov;
                layerEyeFov.Header.Flags = LayerFlags.None;

                for (int eyeIndex = 0; eyeIndex < 2; eyeIndex++)
                {
                    EyeType eye        = (EyeType)eyeIndex;
                    var     eyeTexture = new EyeTexture();
                    eyeTextures[eyeIndex] = eyeTexture;

                    // Retrieve size and position of the texture for the current eye.
                    eyeTexture.FieldOfView           = hmdDesc.DefaultEyeFov[eyeIndex];
                    eyeTexture.TextureSize           = OVR.GetFovTextureSize(sessionPtr, eye, hmdDesc.DefaultEyeFov[eyeIndex], 1.0f);
                    eyeTexture.RenderDescription     = OVR.GetRenderDesc(sessionPtr, eye, hmdDesc.DefaultEyeFov[eyeIndex]);
                    eyeTexture.HmdToEyeViewOffset    = eyeTexture.RenderDescription.HmdToEyePose.Position;
                    eyeTexture.ViewportSize.Position = new Vector2i(0, 0);
                    eyeTexture.ViewportSize.Size     = eyeTexture.TextureSize;
                    eyeTexture.Viewport = new Viewport(0, 0, eyeTexture.TextureSize.Width, eyeTexture.TextureSize.Height, 0.0f, 1.0f);

                    // Define a texture at the size recommended for the eye texture.
                    eyeTexture.Texture2DDescription                   = new Texture2DDescription();
                    eyeTexture.Texture2DDescription.Width             = eyeTexture.TextureSize.Width;
                    eyeTexture.Texture2DDescription.Height            = eyeTexture.TextureSize.Height;
                    eyeTexture.Texture2DDescription.ArraySize         = 1;
                    eyeTexture.Texture2DDescription.MipLevels         = 1;
                    eyeTexture.Texture2DDescription.Format            = Format.R8G8B8A8_UNorm;
                    eyeTexture.Texture2DDescription.SampleDescription = new SampleDescription(1, 0);
                    eyeTexture.Texture2DDescription.Usage             = ResourceUsage.Default;
                    eyeTexture.Texture2DDescription.CpuAccessFlags    = CpuAccessFlags.None;
                    eyeTexture.Texture2DDescription.BindFlags         = BindFlags.ShaderResource | BindFlags.RenderTarget;

                    // Convert the SharpDX texture description to the Oculus texture swap chain description.
                    TextureSwapChainDesc textureSwapChainDesc = SharpDXHelpers.CreateTextureSwapChainDescription(eyeTexture.Texture2DDescription);

                    // Create a texture swap chain, which will contain the textures to render to, for the current eye.
                    IntPtr textureSwapChainPtr;

                    result = OVR.CreateTextureSwapChainDX(sessionPtr, device.NativePointer, ref textureSwapChainDesc, out textureSwapChainPtr);
                    WriteErrorDetails(OVR, result, "Failed to create swap chain.");

                    eyeTexture.SwapTextureSet = new TextureSwapChain(OVR, sessionPtr, textureSwapChainPtr);


                    // Retrieve the number of buffers of the created swap chain.
                    int textureSwapChainBufferCount;
                    result = eyeTexture.SwapTextureSet.GetLength(out textureSwapChainBufferCount);
                    WriteErrorDetails(OVR, result, "Failed to retrieve the number of buffers of the created swap chain.");

                    // Create room for each DirectX texture in the SwapTextureSet.
                    eyeTexture.Textures          = new Texture2D[textureSwapChainBufferCount];
                    eyeTexture.RenderTargetViews = new RenderTargetView[textureSwapChainBufferCount];

                    // Create a texture 2D and a render target view, for each unmanaged texture contained in the SwapTextureSet.
                    for (int textureIndex = 0; textureIndex < textureSwapChainBufferCount; textureIndex++)
                    {
                        // Retrieve the Direct3D texture contained in the Oculus TextureSwapChainBuffer.
                        IntPtr swapChainTextureComPtr = IntPtr.Zero;
                        result = eyeTexture.SwapTextureSet.GetBufferDX(textureIndex, textureInterfaceId, out swapChainTextureComPtr);
                        WriteErrorDetails(OVR, result, "Failed to retrieve a texture from the created swap chain.");

                        // Create a managed Texture2D, based on the unmanaged texture pointer.
                        eyeTexture.Textures[textureIndex] = new Texture2D(swapChainTextureComPtr);

                        // Create a render target view for the current Texture2D.
                        eyeTexture.RenderTargetViews[textureIndex] = new RenderTargetView(device, eyeTexture.Textures[textureIndex]);
                    }

                    // Define the depth buffer, at the size recommended for the eye texture.
                    eyeTexture.DepthBufferDescription                   = new Texture2DDescription();
                    eyeTexture.DepthBufferDescription.Format            = Format.D32_Float;
                    eyeTexture.DepthBufferDescription.Width             = eyeTexture.TextureSize.Width;
                    eyeTexture.DepthBufferDescription.Height            = eyeTexture.TextureSize.Height;
                    eyeTexture.DepthBufferDescription.ArraySize         = 1;
                    eyeTexture.DepthBufferDescription.MipLevels         = 1;
                    eyeTexture.DepthBufferDescription.SampleDescription = new SampleDescription(1, 0);
                    eyeTexture.DepthBufferDescription.Usage             = ResourceUsage.Default;
                    eyeTexture.DepthBufferDescription.BindFlags         = BindFlags.DepthStencil;
                    eyeTexture.DepthBufferDescription.CpuAccessFlags    = CpuAccessFlags.None;
                    eyeTexture.DepthBufferDescription.OptionFlags       = ResourceOptionFlags.None;

                    // Create the depth buffer.
                    eyeTexture.DepthBuffer      = new Texture2D(device, eyeTexture.DepthBufferDescription);
                    eyeTexture.DepthStencilView = new DepthStencilView(device, eyeTexture.DepthBuffer);

                    // Specify the texture to show on the HMD.
                    if (eyeIndex == 0)
                    {
                        layerEyeFov.ColorTextureLeft      = eyeTexture.SwapTextureSet.TextureSwapChainPtr;
                        layerEyeFov.ViewportLeft.Position = new Vector2i(0, 0);
                        layerEyeFov.ViewportLeft.Size     = eyeTexture.TextureSize;
                        layerEyeFov.FovLeft = eyeTexture.FieldOfView;
                    }
                    else
                    {
                        layerEyeFov.ColorTextureRight      = eyeTexture.SwapTextureSet.TextureSwapChainPtr;
                        layerEyeFov.ViewportRight.Position = new Vector2i(0, 0);
                        layerEyeFov.ViewportRight.Size     = eyeTexture.TextureSize;
                        layerEyeFov.FovRight = eyeTexture.FieldOfView;
                    }
                }

                MirrorTextureDesc mirrorTextureDescription = new MirrorTextureDesc();
                mirrorTextureDescription.Format    = TextureFormat.R8G8B8A8_UNorm_SRgb;
                mirrorTextureDescription.Width     = form.Width;
                mirrorTextureDescription.Height    = form.Height;
                mirrorTextureDescription.MiscFlags = TextureMiscFlags.None;

                // Create the texture used to display the rendered result on the computer monitor.
                IntPtr mirrorTexturePtr;
                result = OVR.CreateMirrorTextureDX(sessionPtr, device.NativePointer, ref mirrorTextureDescription, out mirrorTexturePtr);
                WriteErrorDetails(OVR, result, "Failed to create mirror texture.");

                mirrorTexture = new MirrorTexture(OVR, sessionPtr, mirrorTexturePtr);


                // Retrieve the Direct3D texture contained in the Oculus MirrorTexture.
                IntPtr mirrorTextureComPtr = IntPtr.Zero;
                result = mirrorTexture.GetBufferDX(textureInterfaceId, out mirrorTextureComPtr);
                WriteErrorDetails(OVR, result, "Failed to retrieve the texture from the created mirror texture buffer.");

                // Create a managed Texture2D, based on the unmanaged texture pointer.
                mirrorTextureD3D = new Texture2D(mirrorTextureComPtr);

                #region Vertex and pixel shader
                // Create vertex shader.
                vertexShaderByteCode = ShaderBytecode.CompileFromFile("Shaders.fx", "VertexShaderPositionColor", "vs_4_0");
                vertexShader         = new VertexShader(device, vertexShaderByteCode);

                // Create pixel shader.
                pixelShaderByteCode = ShaderBytecode.CompileFromFile("Shaders.fx", "PixelShaderPositionColor", "ps_4_0");
                pixelShader         = new PixelShader(device, pixelShaderByteCode);

                shaderSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode);

                // Specify that each vertex consists of a single vertex position and color.
                InputElement[] inputElements = new InputElement[]
                {
                    new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                    new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
                };

                // Define an input layout to be passed to the vertex shader.
                inputLayout = new InputLayout(device, shaderSignature, inputElements);

                // Create a vertex buffer, containing our 3D model.
                vertexBuffer = Buffer.Create(device, BindFlags.VertexBuffer, m_vertices);

                // Create a constant buffer, to contain our WorldViewProjection matrix, that will be passed to the vertex shader.
                contantBuffer = new Buffer(device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

                // Setup the immediate context to use the shaders and model we defined.
                immediateContext.InputAssembler.InputLayout       = inputLayout;
                immediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
                immediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, sizeof(float) * 4 * 2, 0));
                immediateContext.VertexShader.SetConstantBuffer(0, contantBuffer);
                immediateContext.VertexShader.Set(vertexShader);
                immediateContext.PixelShader.Set(pixelShader);
                #endregion

                DateTime startTime = DateTime.Now;
                Vector3  position  = new Vector3(0, 0, -1);

                #region Render loop
                RenderLoop.Run(form, () =>
                {
                    Vector3f[] hmdToEyeViewOffsets = { eyeTextures[0].HmdToEyeViewOffset, eyeTextures[1].HmdToEyeViewOffset };
                    double displayMidpoint         = OVR.GetPredictedDisplayTime(sessionPtr, 0);
                    TrackingState trackingState    = OVR.GetTrackingState(sessionPtr, displayMidpoint, true);
                    Posef[] eyePoses = new Posef[2];

                    // Calculate the position and orientation of each eye.
                    OVR.CalcEyePoses(trackingState.HeadPose.ThePose, hmdToEyeViewOffsets, ref eyePoses);

                    float timeSinceStart = (float)(DateTime.Now - startTime).TotalSeconds;

                    for (int eyeIndex = 0; eyeIndex < 2; eyeIndex++)
                    {
                        EyeType eye           = (EyeType)eyeIndex;
                        EyeTexture eyeTexture = eyeTextures[eyeIndex];

                        if (eyeIndex == 0)
                        {
                            layerEyeFov.RenderPoseLeft = eyePoses[0];
                        }
                        else
                        {
                            layerEyeFov.RenderPoseRight = eyePoses[1];
                        }

                        // Update the render description at each frame, as the HmdToEyeOffset can change at runtime.
                        eyeTexture.RenderDescription = OVR.GetRenderDesc(sessionPtr, eye, hmdDesc.DefaultEyeFov[eyeIndex]);

                        // Retrieve the index of the active texture
                        int textureIndex;
                        result = eyeTexture.SwapTextureSet.GetCurrentIndex(out textureIndex);
                        WriteErrorDetails(OVR, result, "Failed to retrieve texture swap chain current index.");

                        immediateContext.OutputMerger.SetRenderTargets(eyeTexture.DepthStencilView, eyeTexture.RenderTargetViews[textureIndex]);
                        immediateContext.ClearRenderTargetView(eyeTexture.RenderTargetViews[textureIndex], Color.Black);
                        immediateContext.ClearDepthStencilView(eyeTexture.DepthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);
                        immediateContext.Rasterizer.SetViewport(eyeTexture.Viewport);

                        // Retrieve the eye rotation quaternion and use it to calculate the LookAt direction and the LookUp direction.
                        Quaternion rotationQuaternion = SharpDXHelpers.ToQuaternion(eyePoses[eyeIndex].Orientation);
                        Matrix rotationMatrix         = Matrix.RotationQuaternion(rotationQuaternion);
                        Vector3 lookUp = Vector3.Transform(new Vector3(0, -1, 0), rotationMatrix).ToVector3();
                        Vector3 lookAt = Vector3.Transform(new Vector3(0, 0, 1), rotationMatrix).ToVector3();

                        Vector3 viewPosition = position - eyePoses[eyeIndex].Position.ToVector3();

                        Matrix world      = Matrix.Scaling(0.1f) * Matrix.RotationX(timeSinceStart / 10f) * Matrix.RotationY(timeSinceStart * 2 / 10f) * Matrix.RotationZ(timeSinceStart * 3 / 10f);
                        Matrix viewMatrix = Matrix.LookAtLH(viewPosition, viewPosition + lookAt, lookUp);

                        Matrix projectionMatrix = OVR.Matrix4f_Projection(eyeTexture.FieldOfView, 0.1f, 100.0f, ProjectionModifier.LeftHanded).ToMatrix();
                        projectionMatrix.Transpose();

                        Matrix worldViewProjection = world * viewMatrix * projectionMatrix;
                        worldViewProjection.Transpose();

                        // Update the transformation matrix.
                        immediateContext.UpdateSubresource(ref worldViewProjection, contantBuffer);

                        // Draw the cube
                        immediateContext.Draw(m_vertices.Length / 2, 0);

                        // Commits any pending changes to the TextureSwapChain, and advances its current index
                        result = eyeTexture.SwapTextureSet.Commit();
                        WriteErrorDetails(OVR, result, "Failed to commit the swap chain texture.");
                    }


                    result = OVR.SubmitFrame(sessionPtr, 0L, IntPtr.Zero, ref layerEyeFov);
                    WriteErrorDetails(OVR, result, "Failed to submit the frame of the current layers.");

                    immediateContext.CopyResource(mirrorTextureD3D, backBuffer);
                    swapChain.Present(0, PresentFlags.None);
                });
                #endregion
            }
            finally
            {
                if (immediateContext != null)
                {
                    immediateContext.ClearState();
                    immediateContext.Flush();
                }

                // Release all resources
                Dispose(inputLayout);
                Dispose(contantBuffer);
                Dispose(vertexBuffer);
                Dispose(shaderSignature);
                Dispose(pixelShader);
                Dispose(pixelShaderByteCode);
                Dispose(vertexShader);
                Dispose(vertexShaderByteCode);
                Dispose(mirrorTextureD3D);
                Dispose(mirrorTexture);
                Dispose(eyeTextures[0]);
                Dispose(eyeTextures[1]);
                Dispose(immediateContext);
                Dispose(depthStencilState);
                Dispose(depthStencilView);
                Dispose(depthBuffer);
                Dispose(backBufferRenderTargetView);
                Dispose(backBuffer);
                Dispose(swapChain);
                Dispose(factory);

                // Disposing the device, before the hmd, will cause the hmd to fail when disposing.
                // Disposing the device, after the hmd, will cause the dispose of the device to fail.
                // It looks as if the hmd steals ownership of the device and destroys it, when it's shutting down.
                // device.Dispose();
                OVR.Destroy(sessionPtr);
            }
        }
Пример #29
0
        /// <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);
        }
Пример #30
0
        /// <summary>
        /// Creates Direct3D11 Device, RenderTargetView, DepthStencilView, Viewport
        /// </summary>
        /// <param name="deviceDescription">The device description.</param>
        /// <exception cref="System.Exception"></exception>
        /// <exception cref="System.ComponentModel.InvalidEnumArgumentException">deviceDescription.MultiSampleCount</exception>
        private void Initialize(DeviceDescription deviceDescription)
        {
            FeatureLevel[] levels = new FeatureLevel[] {
                FeatureLevel.Level_10_0,
                FeatureLevel.Level_10_1,
                FeatureLevel.Level_11_0,
                FeatureLevel.Level_11_1,
            };

            d3dDevice = new D3D11.Device(DriverType.Hardware, D3D11.DeviceCreationFlags.Debug, levels);

            DXGI.ModeDescription backBufferDesc = new DXGI.ModeDescription()
            {
                Width            = width,
                Height           = height,
                Format           = BackBufferFormat,
                RefreshRate      = new DXGI.Rational(60, 1),
                Scaling          = DXGI.DisplayModeScaling.Unspecified,
                ScanlineOrdering = DXGI.DisplayModeScanlineOrder.Progressive,
            };

            DXGI.SwapChainDescription swapChainDesc = new DXGI.SwapChainDescription()
            {
                BufferCount     = 1,
                Flags           = DXGI.SwapChainFlags.None,
                IsWindowed      = !deviceDescription.Fullcreen,
                ModeDescription = backBufferDesc,
                OutputHandle    = renderControl.Handle,
                SwapEffect      = deviceDescription.SwapEffect,
                Usage           = DXGI.Usage.RenderTargetOutput,
            };

            switch (deviceDescription.MultiSampleCount)
            {
            case MultiSampleType.MSAA1:
                swapChainDesc.SampleDescription = new DXGI.SampleDescription(1, deviceDescription.MultiSampleQuality);
                break;

            case MultiSampleType.MSAA2:
                swapChainDesc.SampleDescription = new DXGI.SampleDescription(2, deviceDescription.MultiSampleQuality);
                break;

            case MultiSampleType.MSAA4:
                swapChainDesc.SampleDescription = new DXGI.SampleDescription(4, deviceDescription.MultiSampleQuality);
                break;

            case MultiSampleType.MSAA8:
                swapChainDesc.SampleDescription = new DXGI.SampleDescription(8, deviceDescription.MultiSampleQuality);
                break;

            case MultiSampleType.MSAA16:
                swapChainDesc.SampleDescription = new DXGI.SampleDescription(16, deviceDescription.MultiSampleQuality);
                break;

            case MultiSampleType.Unknown:
                var samples = SharpDXDevice.CheckMultiSample();
                if (samples == null)
                {
                    throw new Exception(MethodBase.GetCurrentMethod().Name +
                                        " Because the MultiSampleCount parameter is [Unknown], the device could not determine the parameter automatically");
                }
                swapChainDesc.SampleDescription = samples.Last();
                break;

            default:
                throw new System.ComponentModel.InvalidEnumArgumentException("deviceDescription.MultiSampleCount",
                                                                             (int)deviceDescription.MultiSampleCount, typeof(MultiSampleType));
            }

            DXGI.Device  device  = d3dDevice.QueryInterface <DXGI.Device>();
            DXGI.Adapter adapter = device.GetParent <DXGI.Adapter>();
            DXGI.Factory factory = adapter.GetParent <DXGI.Factory>();

            swapChain = new DXGI.SwapChain(factory, d3dDevice, swapChainDesc);

            d3dContext = d3dDevice.ImmediateContext;

            D3D11.RasterizerStateDescription rasterDesc = new D3D11.RasterizerStateDescription()
            {
                CullMode = D3D11.CullMode.Back,
                FillMode = D3D11.FillMode.Solid,
                IsAntialiasedLineEnabled = true,
                IsMultisampleEnabled     = true,
                IsDepthClipEnabled       = true,
            };

            viewport = new Viewport(0, 0, width, height);

            this.SetRasterizerState(rasterDesc);
            d3dRenderTarget = CreateRenderTarget();
            d3dDepthStencil = CreateDepthStencil();
        }
Пример #31
0
        public override void InitDevice()
        {
            Width  = Surface.ClientSize.Width;
            Height = Surface.ClientSize.Height;

            SwapChainDescription SwapDesc = new SwapChainDescription()
            {
                BufferCount     = 1,
                ModeDescription = new ModeDescription(
                    Width, Height,
                    new Rational(60, 1),
                    Format.R8G8B8A8_UNorm//R8G8B8A8_UNorm
                    ),
                IsWindowed        = true,
                OutputHandle      = Surface.Handle,
                SampleDescription = new SampleDescription(MSamplesCount, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput,
            };

            Device    device;
            SwapChain swapChain;

            DeviceCreationFlags deviceCreationFlags = DeviceCreationFlags.BgraSupport;

            if (IsDebugMode)
            {
                deviceCreationFlags |= DeviceCreationFlags.Debug;
            }

            Device.CreateWithSwapChain(
                DriverType.Hardware,
                deviceCreationFlags,
                //DeviceCreationFlags.None,
                SwapDesc,
                out device,
                out swapChain
                );
            DeviceRef           = device;
            DeviceRef.DebugName = "The Device";
            DeviceRef.ImmediateContext.DebugName = "The Context";

            CheckFeatures();

            SwapChainRef           = swapChain;
            SwapChainRef.DebugName = "The SwapChain";

            // Ignore all windows events
            FactoryDXGI factory = swapChain.GetParent <FactoryDXGI>();

            factory.MakeWindowAssociation(Surface.Handle, WindowAssociationFlags.IgnoreAll);

            ZBufferTextureDescription = new Texture2DDescription {
                Format            = Format.R32_Typeless,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = Width,
                Height            = Height,
                SampleDescription = new SampleDescription(MSamplesCount, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil | BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None,
            };

            Factory2D                = new Factory(FactoryType.SingleThreaded, DebugLevel.Information);
            FactoryDWrite            = new SharpDX.DirectWrite.Factory();
            RenderTarget2DProperites = new RenderTargetProperties(new PixelFormat(
                                                                      Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied));
        }