Exemplo n.º 1
0
        static void Main()
        {
            var renderForm = new RenderForm("");

            SharpDX.DXGI.Factory f = new SharpDX.DXGI.Factory();
            SharpDX.DXGI.Adapter a = f.GetAdapter(1);


            SharpDX.Direct3D11.Device  d  = new Device(a, DeviceCreationFlags.VideoSupport | DeviceCreationFlags.BgraSupport);
            SharpDX.Direct3D11.Device2 d2 = d.QueryInterface <SharpDX.Direct3D11.Device2>();
            //d.Dispose();*/

            /* var device = new RenderDevice(, 1);
             * RenderContext context = new RenderContext(device);
             *
             * var d = device.Device;*/
            var multithread = d.QueryInterface <SharpDX.Direct3D.DeviceMultithread>();

            multithread.SetMultithreadProtected(true);

            // Create a DXGI Device Manager
            var dxgiDeviceManager = new SharpDX.MediaFoundation.DXGIDeviceManager();

            dxgiDeviceManager.ResetDevice(d);

            VideoDevice vd = d.QueryInterface <VideoDevice>();

            //vd.VideoDecoderProfileCount

            /*VideoDecoderDescription desc = new VideoDecoderDescription()
             * {
             *
             * }*/

            VideoContext ctx = d.ImmediateContext.QueryInterface <VideoContext>();

            /*var swapChain = new DX11SwapChain(device, renderForm.Handle);
             *
             * /*var dx = new VideoDecoderDescription()
             * {
             *
             * }*/
            /*int i = vd.VideoDecoderProfileCount;
             *
             * renderForm.ResizeEnd += (s, e) => swapChain.Resize();
             *
             * RenderLoop.Run(renderForm, () =>
             * {
             *  context.Context.ClearRenderTargetView(swapChain.RenderView, new SharpDX.Color4(1, 1, 1, 1));
             *
             *  swapChain.Present(1, SharpDX.DXGI.PresentFlags.None);
             * });*/
        }
Exemplo n.º 2
0
        private Device()
        {
            DeviceCreationFlags flags = DeviceCreationFlags.None;

#if DEBUG
            flags |= DeviceCreationFlags.Debug;
#endif
            Handle = new SharpDX.Direct3D11.Device(DriverType.Hardware, flags, new FeatureLevel[] { FeatureLevel.Level_11_0 });

            // obtain the factory that created the device
            var obj     = Handle.QueryInterface <SharpDX.DXGI.Device>();
            var adapter = obj.Adapter;
            FactoryHandle = adapter.GetParent <SharpDX.DXGI.Factory>();
            context       = Handle.ImmediateContext;
        }
Exemplo n.º 3
0
        /// <summary>
        /// deviceを作成します。
        /// </summary>
        /// <param name="control">レンダリング先となるcontrol</param>
        /// <param name="tso_config">設定</param>
        /// <returns>deviceの作成に成功したか</returns>
        public bool InitializeApplication(Control control, TSOConfig tso_config)
        {
            this.tso_config = tso_config;
            SetControl(control);

            control.MouseDown += new MouseEventHandler(form_OnMouseDown);
            control.MouseMove += new MouseEventHandler(form_OnMouseMove);

            {
            device = new Device(DriverType.Hardware, DeviceCreationFlags.None);

            var desc = new SharpDX.DXGI.SwapChainDescription()
            {
                BufferCount = 1,
                Usage = SharpDX.DXGI.Usage.RenderTargetOutput,
                OutputHandle = control.Handle,
                IsWindowed = true,
                ModeDescription = new SharpDX.DXGI.ModeDescription(0, 0, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm),
                SampleDescription = DetectSampleDescription(device, SharpDX.DXGI.Format.D32_Float),
                Flags = SharpDX.DXGI.SwapChainFlags.AllowModeSwitch,
                SwapEffect = SharpDX.DXGI.SwapEffect.Discard
            };
            dxgi_factory = new SharpDX.DXGI.Factory();
            swap_chain = new SharpDX.DXGI.SwapChain(dxgi_factory, device, desc);
            }

            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);

            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;

            camera.Update();

            DefineBlendState();
            DefineDepthStencilState();
            DefineRasterizerState();

            return true;
        }
Exemplo n.º 4
0
        public Dx11RenderingDevice()
        {
            logger.Info("Dx11 rendering device creating.");
#if DEBUG
            const DeviceCreationFlags DebugFlags = DeviceCreationFlags.Debug;
#else
            const DeviceCreationFlags DebugFlags = DeviceCreationFlags.None;
#endif
            try
            {
                Factory = new Factory();
                if (Factory.Adapters.Count() == 0)
                {
                    MessageBox.Show("Your system have no video adapters. Try to install video adapter.", "DirectX error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    throw new Exception("There are no valid video adapters in system.");
                }

                var adapter = Factory.GetAdapter(0);
                if (adapter == null)
                {
                    MessageBox.Show("DirectX wasn't able to acquire video adapter. Try to restart your system.", "DirectX error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    throw new Exception("DirectX wasn't able to acquire video adapter.");
                }

                if (adapter.Outputs == null || adapter.Outputs.Count() == 0)
                {
                    MessageBox.Show("There are no video displays connected to your system. Try to connect a display.", "DirectX error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    throw new Exception("No connected displays found.");
                }

                Device = new Device(adapter, DebugFlags | DeviceCreationFlags.SingleThreaded, FeatureLevel.Level_10_0);
            }
            catch (Exception exc)
            {
                switch ((uint)exc.HResult)
                {
                case 0x887A0004:
                    MessageBox.Show("Your DirectX version, videocard or drivers are out of date.\nDirectX 11 installation and videocard with DirectX 10 support is required.", "DirectX error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;

                case 0x887A002D:
                    MessageBox.Show("Warning: provided build is a debug build.\nPlease install DirectX SDK or request release build from QA team.", "DirectX error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;

                case 0x887A0005:
                case 0x887A0020:
                    MessageBox.Show("There was a serious video system error while initializing Direct3D device.\nTry to restart your system.", "DirectX error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;

                default:
                    MessageBox.Show("Unknown error while creating Direct3D device!\nShutting down now.", "DirectX error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
                }

                throw new Exception("Can't create Direct3D 11 device! Exception: " + exc);
            }

#if DEBUG
            using (InfoQueue DeviceInfoQueue = Device.QueryInterface <InfoQueue>())
            {
                DeviceInfoQueue.SetBreakOnSeverity(MessageSeverity.Warning, true);
            }
#endif

            try
            {
                Context = Device.ImmediateContext;

                /*TestShader = new Dx11PipelineState(this, "TestShader", new InputElement[]
                 * {
                 * new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                 * new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 0, 1, InputClassification.PerVertexData, 0)
                 * });*/
                TextShader = new Dx11PipelineState(this, "TextShader", new InputElement[]
                {
                    new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0, InputClassification.PerVertexData, 0),
                    new InputElement("UVW", 0, Format.R32G32_UInt, 0, 1, InputClassification.PerVertexData, 0)
                });
                SpriteShader = new Dx11PipelineState(this, "SpriteShader", new InputElement[]
                {
                    new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0, InputClassification.PerVertexData, 0),
                    new InputElement("UVW", 0, Format.R32G32_UInt, 0, 1, InputClassification.PerVertexData, 0)
                });
                RoomShader = new Dx11PipelineState(this, "RoomShader", new InputElement[]
                {
                    new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                    new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 0, 1, InputClassification.PerVertexData, 0),
                    new InputElement("OVERLAY", 0, Format.R8G8B8A8_UNorm, 0, 2, InputClassification.PerVertexData, 0),
                    new InputElement("UVWANDBLENDMODE", 0, Format.R32G32_UInt, 0, 3, InputClassification.PerVertexData, 0),
                    new InputElement("EDITORUVANDSECTORTEXTURE", 0, Format.R32_UInt, 0, 4, InputClassification.PerVertexData, 0)
                });
                RasterizerBackCulling = new RasterizerState(Device, new RasterizerStateDescription
                {
                    CullMode = CullMode.Back,
                    FillMode = FillMode.Solid,
                });
                SamplerDefault = new SamplerState(Device, new SamplerStateDescription
                {
                    AddressU          = TextureAddressMode.Mirror,
                    AddressV          = TextureAddressMode.Mirror,
                    AddressW          = TextureAddressMode.Wrap,
                    Filter            = Filter.Anisotropic,
                    MaximumAnisotropy = 4,
                });
                SamplerRoundToNearest = new SamplerState(Device, new SamplerStateDescription
                {
                    AddressU          = TextureAddressMode.Wrap,
                    AddressV          = TextureAddressMode.Wrap,
                    AddressW          = TextureAddressMode.Wrap,
                    Filter            = Filter.MinMagMipPoint,
                    MaximumAnisotropy = 4,
                });
                {
                    DepthStencilStateDescription desc = DepthStencilStateDescription.Default();
                    desc.DepthComparison  = Comparison.LessEqual;
                    desc.DepthWriteMask   = DepthWriteMask.All;
                    desc.IsDepthEnabled   = true;
                    desc.IsStencilEnabled = false;
                    DepthStencilDefault   = new DepthStencilState(Device, desc);
                }
                {
                    DepthStencilStateDescription desc = DepthStencilStateDescription.Default();
                    desc.DepthComparison  = Comparison.Always;
                    desc.DepthWriteMask   = DepthWriteMask.Zero;
                    desc.IsDepthEnabled   = false;
                    desc.IsStencilEnabled = false;
                    DepthStencilNoZBuffer = new DepthStencilState(Device, desc);
                }
                BlendingDisabled = new BlendState(Device, BlendStateDescription.Default());
                {
                    BlendStateDescription desc = BlendStateDescription.Default();
                    desc.RenderTarget[0].IsBlendEnabled        = true;
                    desc.RenderTarget[0].SourceBlend           = desc.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
                    desc.RenderTarget[0].DestinationBlend      = desc.RenderTarget[0].DestinationAlphaBlend = BlendOption.InverseSourceAlpha;
                    desc.RenderTarget[0].BlendOperation        = desc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
                    desc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
                    BlendingPremultipliedAlpha = new BlendState(Device, desc);
                }
            }
            catch (Exception exc)
            {
                throw new Exception("Can't assign needed Direct3D parameters! Exception: " + exc);
            }

            // Sector textures
            bool       support16BitTexture = Device.CheckFormatSupport(Format.B5G5R5A1_UNorm).HasFlag(FormatSupport.Texture2D); // For some reason not all DirectX devices support 16 bit textures.
            string[]   sectorTextureNames  = Enum.GetNames(typeof(SectorTexture)).Skip(1).ToArray();
            GCHandle[] handles             = new GCHandle[sectorTextureNames.Length];
            try
            {
                DataBox[] dataBoxes = new DataBox[sectorTextureNames.Length];
                for (int i = 0; i < sectorTextureNames.Length; ++i)
                {
                    string name = nameof(TombLib) + "." + nameof(Rendering) + ".SectorTextures." + sectorTextureNames[i] + ".png";
                    using (Stream stream = ThisAssembly.GetManifestResourceStream(name))
                    {
                        ImageC image = ImageC.FromStream(stream);
                        if ((image.Width != SectorTextureSize) || (image.Height != SectorTextureSize))
                        {
                            throw new ArgumentOutOfRangeException("The embedded resource '" + name + "' is not of a valid size.");
                        }

                        if (support16BitTexture)
                        { // Compress image data into B5G5R5A1 format to save a bit of GPU memory. (3 MB saved with currently 23 images)
                            ushort[] sectorTextureData = new ushort[SectorTextureSize * SectorTextureSize];
                            for (int j = 0; j < (SectorTextureSize * SectorTextureSize); ++j)
                            {
                                ColorC Color = image.Get(j);
                                sectorTextureData[j] = (ushort)(
                                    ((Color.B >> 3) << 0) |
                                    ((Color.G >> 3) << 5) |
                                    ((Color.R >> 3) << 10) |
                                    ((Color.A >> 7) << 15));
                            }
                            handles[i]   = GCHandle.Alloc(sectorTextureData, GCHandleType.Pinned);
                            dataBoxes[i] = new DataBox(handles[i].AddrOfPinnedObject(), sizeof(ushort) * SectorTextureSize, 0);
                        }
                        else
                        {
                            handles[i]   = GCHandle.Alloc(image.ToByteArray(), GCHandleType.Pinned);
                            dataBoxes[i] = new DataBox(handles[i].AddrOfPinnedObject(), sizeof(uint) * SectorTextureSize, 0);
                        }
                    }
                }

                SectorTextureArray = new Texture2D(Device, new Texture2DDescription
                {
                    Width             = SectorTextureSize,
                    Height            = SectorTextureSize,
                    MipLevels         = 1,
                    ArraySize         = sectorTextureNames.Length,
                    Format            = support16BitTexture ? Format.B5G5R5A1_UNorm : Format.B8G8R8A8_UNorm,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage             = ResourceUsage.Immutable,
                    BindFlags         = BindFlags.ShaderResource,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    OptionFlags       = ResourceOptionFlags.None
                }, dataBoxes);
            }
            finally
            {
                foreach (GCHandle handle in handles)
                {
                    handle.Free();
                }
            }
            SectorTextureArrayView = new ShaderResourceView(Device, SectorTextureArray);

            // Set omni present state
            ResetState();

            logger.Info("Dx11 rendering device created.");
        }