示例#1
0
文件: DXMain.cs 项目: vtastek/MGE-XE
        public static void GetDeviceCaps()
        {
            // Device.IsUsingEventHandlers = false;

            object value = Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Bethesda Softworks\Morrowind", "Adapter", 0);

            adapter = (value != null) ? (int)value : 0;
            if (d3d.AdapterCount <= adapter)
            {
                throw new ApplicationException("Morrowind is set up to use a graphics card which could not be found on your system.");
            }

            for (int i = 2; i <= 16; i++)
            {
                if (d3d.CheckDeviceMultisampleType(adapter, DeviceType.Hardware, Format.X8R8G8B8, false, (MultisampleType)i))
                {
                    mCaps.MaxFullscreenAA = i;
                }
                if (d3d.CheckDeviceMultisampleType(adapter, DeviceType.Hardware, Format.X8R8G8B8, true, (MultisampleType)i))
                {
                    mCaps.MaxWindowedAA = i;
                }
            }

            caps = d3d.GetDeviceCaps(adapter, DeviceType.Hardware);

            mCaps.MaxAF         = caps.MaxAnisotropy;
            mCaps.SupportsSM1   = (caps.VertexShaderVersion >= new Version(1, 1)) && (caps.PixelShaderVersion >= new Version(1, 4));
            mCaps.SupportsSM2   = (caps.VertexShaderVersion.Major >= 2) && (caps.PixelShaderVersion.Major >= 2);
            mCaps.SupportsSM3   = (caps.VertexShaderVersion.Major >= 3) && (caps.PixelShaderVersion.Major >= 3);
            mCaps.MaxTexSize    = Math.Min(caps.MaxTextureHeight, caps.MaxTextureWidth);
            mCaps.MaxPrimitives = caps.MaxPrimitiveCount;
            mCaps.MaxIndicies   = caps.MaxVertexIndex;
        }
示例#2
0
 private void buttonTS1_Click(object sender, EventArgs e)
 {
     try
     {
         Direct3D     w = new Direct3D();
         Capabilities q = w.GetDeviceCaps(0, DeviceType.Hardware);
         rtbDebugMsg.AppendText("Vertex Shader ver: \n" + q.VertexShaderVersion.ToString() + "\n");
         rtbDebugMsg.AppendText("Device Type: \n" + q.DeviceType.ToString() + "\n");
         rtbDebugMsg.AppendText("Device Caps: \n" + q.DeviceCaps.ToString() + "\n");
         rtbDebugMsg.AppendText("Device Caps2: \n" + q.DeviceCaps2.ToString() + "\n");
         rtbDebugMsg.AppendText("Pixel Shader: \n" + q.PixelShaderVersion.ToString() + "\n");
         rtbDebugMsg.AppendText("Texture Caps: \n" + q.TextureCaps.ToString() + "\n");
         rtbDebugMsg.AppendText("FVF Caps: \n" + q.FVFCaps.ToString() + "\n");
         rtbDebugMsg.AppendText("Line Caps: \n" + q.LineCaps.ToString() + "\n");
         rtbDebugMsg.AppendText("MaxVertexIndex Caps: \n" + q.MaxVertexIndex.ToString() + "\n");
         rtbDebugMsg.AppendText("PrimitiveMiscCaps: \n" + q.PrimitiveMiscCaps.ToString() + "\n");
         rtbDebugMsg.AppendText("RatserCaps: \n" + q.RasterCaps.ToString() + "\n");
         rtbDebugMsg.AppendText("VertexProcessingCaps: \n" + q.VertexProcessingCaps.ToString() + "\n");
         rtbDebugMsg.AppendText("VS20Caps: \n" + q.VS20Caps.ToString() + "\n");
     }
     catch (Exception ex)
     {
         Debug.Write(ex.ToString());
     }
 }
示例#3
0
        public static void Hook06000092(Direct3D d3d, TrackBar trackbar, int quality, bool windowed)
        {
            int adapter = d3d.Adapters.DefaultAdapter.Adapter;
            int val;
            int val2;
            int maxquality;

            if (d3d.CheckDeviceMultisampleType(adapter, DeviceType.Hardware, d3d.Adapters[adapter].CurrentDisplayMode.Format, windowed, MultisampleType.NonMaskable, out val) &&
                d3d.CheckDeviceMultisampleType(adapter, DeviceType.Hardware, Format.D24S8, windowed, MultisampleType.NonMaskable, out val2))
            {
                maxquality = Math.Min(val, val2);
            }
            else
            {
                maxquality = 0;
            }
            Capabilities deviceCaps = d3d.GetDeviceCaps(0, DeviceType.Hardware);

            trackbar.Enabled = (maxquality > 0);
            if (trackbar.Enabled)
            {
                trackbar.Maximum = maxquality;
                try
                {
                    trackbar.Value = (int)Math.Log(quality, 2);
                }
                catch
                {
                }
            }
        }
示例#4
0
        private void Form_Load(object sender, EventArgs e)
        {
            Form form = (Form)sender;

            System.Diagnostics.Debug.Assert(Direct3D == null);
            Direct3D = new Direct3D();

            int          nAdapter = Direct3D.Adapters[0].Adapter;
            Capabilities devCaps  = Direct3D.GetDeviceCaps(nAdapter,
                                                           DeviceType.Hardware);

            // the flags for our Direct3D device. Use software rendering by
            // default
            CreateFlags devFlags = CreateFlags.SoftwareVertexProcessing;

            // use hardware vertex processing if supported
            if ((devCaps.DeviceCaps & DeviceCaps.HWTransformAndLight)
                == DeviceCaps.HWTransformAndLight)
            {
                devFlags = CreateFlags.HardwareVertexProcessing;
            }

            // use pure device (whatever that is) if supported
            if ((devCaps.DeviceCaps & DeviceCaps.PureDevice)
                == DeviceCaps.PureDevice)
            {
                devFlags |= CreateFlags.PureDevice;
            }

            DisplayMode displayMode = Direct3D.GetAdapterDisplayMode(nAdapter);

            System.Diagnostics.Debug.Assert(PresentParams == null);
            PresentParams = new PresentParameters();
            PresentParams.BackBufferWidth        = form.ClientSize.Width;
            PresentParams.BackBufferHeight       = form.ClientSize.Height;
            PresentParams.BackBufferFormat       = displayMode.Format;
            PresentParams.BackBufferCount        = 1;
            PresentParams.Windowed               = true;
            PresentParams.SwapEffect             = SwapEffect.Discard;
            PresentParams.AutoDepthStencilFormat = Format.D16;
            PresentParams.EnableAutoDepthStencil = true;
            PresentParams.DeviceWindowHandle     = form.Handle;

            System.Diagnostics.Debug.Assert(Device == null);
            // create the Direct3D device
            Device = new SDXDevice(new Device(Direct3D, nAdapter, DeviceType.Hardware, form.Handle,
                                              devFlags, PresentParams),
                                   Form.ClientSize.Width / 640.0f, Form.ClientSize.Height / 480.0f);

            ResetDevice();

            using (System.Drawing.Font baseFont = new System.Drawing.Font("Arial Black", 18, FontStyle.Bold))
            {
                System.Diagnostics.Debug.Assert(d3dFont == null);
                d3dFont = new Font(Device, baseFont);
            }

            Application.Idle += OnApplicationIdle;
        }
示例#5
0
        private static void TryCreateDeviceInternal(IntPtr windowHandle, DeviceType deviceType, MyRenderDeviceSettings settingsToTry, out Device device, out PresentParameters parameters)
        {
            device     = null;
            parameters = CreatePresentParameters(settingsToTry, windowHandle);
            while (device == null)
            {
                try
                {
                    // These calls are here to ensure that none of these calls throw exceptions (even if their results are not used).
                    m_d3d.Dispose();
                    m_d3d = new Direct3D();

                    var d3dCaps = m_d3d.GetDeviceCaps(settingsToTry.AdapterOrdinal, DeviceType.Hardware);

                    device = new Device(m_d3d, settingsToTry.AdapterOrdinal, deviceType, Parameters.DeviceWindowHandle,
                                        CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve,
                                        Parameters);
                    device.Clear(ClearFlags.Target, new SharpDX.ColorBGRA(0, 0, 0, 1), 1.0f, 0);

                    var caps = Device.Capabilities;
                }
                catch (SharpDX.SharpDXException e)
                {
                    if (e.ResultCode == ResultCode.NotAvailable ||
                        (e.ResultCode == ResultCode.InvalidCall && GetForegroundWindow() != Parameters.DeviceWindowHandle))
                    {
                        // User has probably Alt+Tabbed or locked his computer before the game has started.
                        // To counter this, we try creating device again a bit later.
                        Thread.Sleep(2000);
                        MyLog.Default.WriteLine("Device creation failed with " + e.Message);
                    }
                    else
                    {
                        // Either settings or graphics card are not supported.
                        MyLog.Default.WriteLine(e);
                        throw;
                    }
                }

                try
                {
                    MyLog.Default.WriteLine("Loading adapters");
                    m_adaptersList = GetAdaptersList(m_d3d);
                    MyLog.Default.WriteLine("Found adapters");
                    foreach (var adapter in m_adaptersList)
                    {
                        adapter.LogInfo(MyLog.Default.WriteLine);
                    }
                }
                catch (Exception e)
                {
                    MyLog.Default.WriteLine(e);
                    throw;
                }
            }
        }
示例#6
0
 public bool Direct3DInit()
 {
     try
     {
         Direct3D           direct3D       = new Direct3D();
         AdapterInformation defaultAdapter = direct3D.Adapters.DefaultAdapter;
         CreateFlags        createFlags    = (direct3D.GetDeviceCaps(defaultAdapter.Adapter, SlimDX.Direct3D9.DeviceType.Hardware).DeviceCaps & DeviceCaps.HWTransformAndLight) != DeviceCaps.HWTransformAndLight ? CreateFlags.SoftwareVertexProcessing : CreateFlags.HardwareVertexProcessing;
         this.GlobalData.presentParams = new PresentParameters()
         {
             BackBufferWidth    = 640,
             BackBufferHeight   = 480,
             BackBufferFormat   = defaultAdapter.CurrentDisplayMode.Format,
             DeviceWindowHandle = this.Form_Main.Handle,
             Windowed           = !this.fullWindow,
             PresentFlags       = PresentFlags.DiscardDepthStencil,
             SwapEffect         = SwapEffect.Discard
         };
         if (this.presentInterval == 1)
         {
             this.GlobalData.presentParams.PresentationInterval = !this.verticalSync ? PresentInterval.Immediate : PresentInterval.Default;
         }
         else if (this.fullWindow && this.verticalSync)
         {
             if (this.presentInterval == 2)
             {
                 this.GlobalData.presentParams.PresentationInterval = PresentInterval.Two;
             }
             else if (this.presentInterval == 3)
             {
                 this.GlobalData.presentParams.PresentationInterval = PresentInterval.Three;
             }
         }
         else
         {
             this.GlobalData.presentParams.PresentationInterval = PresentInterval.Immediate;
         }
         this.DeviceMain = new SlimDX.Direct3D9.Device(direct3D, defaultAdapter.Adapter, SlimDX.Direct3D9.DeviceType.Hardware, this.Form_Main.Handle, createFlags, new PresentParameters[1]
         {
             this.GlobalData.presentParams
         });
         this.GlobalData.SpriteMain = new MySprite(this.DeviceMain);
         return(true);
     }
     catch
     {
         int num = (int)MessageBox.Show("DirectX初始化失败", "DirectX Initial Error");
         return(false);
     }
 }
示例#7
0
        /* Hook DirectX Device Creation */
        private IntPtr CreateDeviceImpl(IntPtr direct3DPointer, uint adapter, DeviceType deviceType, IntPtr hFocusWindow, CreateFlags behaviorFlags, ref PresentParameters pPresentationParameters, int **ppReturnedDeviceInterface)
        {
            // Get D3D Interface (IDirect3D9)
            Direct3D d3d = new Direct3D(direct3DPointer);

            // Enable Hardware Vertex Processing..
            if (_dx9Settings.HardwareVertexProcessing)
            {
                behaviorFlags = behaviorFlags & ~CreateFlags.SoftwareVertexProcessing;
                behaviorFlags = behaviorFlags | CreateFlags.HardwareVertexProcessing;
            }

            // Get and Set max MSAA Quality
            if (_dx9Settings.EnableMSAA)
            {
                bool msaaAvailable = d3d.CheckDeviceMultisampleType(0, DeviceType.Hardware, pPresentationParameters.BackBufferFormat,
                                                                    pPresentationParameters.Windowed, (MultisampleType)_dx9Settings.MSAALevel, out maxMSAAQuality);

                if (!msaaAvailable)
                {
                    Bindings.PrintError($"The user set MSAA Setting ({_dx9Settings.MSAALevel} Samples) is not supported on this hardware configuration.");
                    Bindings.PrintError($"MSAA will be disabled.");
                    _dx9Settings.EnableMSAA = false;
                }

                if (maxMSAAQuality > 0)
                {
                    maxMSAAQuality -= 1;
                }
            }

            // Check for AF Compatibility
            if (_dx9Settings.EnableAF)
            {
                var capabilities = d3d.GetDeviceCaps(0, DeviceType.Hardware);
                if (_dx9Settings.AFLevel > capabilities.MaxAnisotropy)
                {
                    Bindings.PrintError($"The user set Anisotropic Filtering Setting ({_dx9Settings.AFLevel} Samples) is not supported on this hardware configuration.");
                    Bindings.PrintError($"AF will be disabled.");
                    _dx9Settings.EnableAF = false;
                }
            }

            // Set present parameters.
            pPresentationParameters = SetPresentParameters(ref pPresentationParameters);

            return(_createDeviceHook.OriginalFunction(direct3DPointer, adapter, deviceType, hFocusWindow, behaviorFlags, ref pPresentationParameters, ppReturnedDeviceInterface));
        }
示例#8
0
        public void CreateDevice()
        {
            DestroyDevice();

            var pp = MakePresentParameters();

            var flags = CreateFlags.SoftwareVertexProcessing;

            if ((_d3d.GetDeviceCaps(0, DeviceType.Hardware).DeviceCaps & DeviceCaps.HWTransformAndLight) != 0)
            {
                flags = CreateFlags.HardwareVertexProcessing;
            }

            flags |= CreateFlags.FpuPreserve;
            Dev    = new Device(_d3d, 0, DeviceType.Hardware, pp.DeviceWindowHandle, flags, pp);
        }
示例#9
0
        /// <summary>
        /// Creates a new engine capabilities object.
        /// </summary>
        /// <param name="direct3D">Provides access to the Direct3D subsystem.</param>
        /// <param name="config">The settings used to initialize the <see cref="Engine"/>.</param>
        internal EngineCapabilities(Direct3D direct3D, EngineConfig config)
        {
            #region Sanity checks
            if (direct3D == null)
            {
                throw new ArgumentNullException(nameof(direct3D));
            }
            #endregion

            _direct3D     = direct3D;
            _capabilities = _direct3D.GetDeviceCaps(0, DeviceType.Hardware);
            _engineConfig = config;

            DetermineHardwareInformation();
            DetermineDeviceCapabilities();
        }
示例#10
0
        public static void Create()
        {
            Parameters = new PresentParameters
            {
                BackBufferFormat     = Format.X8R8G8B8,
                PresentFlags         = PresentFlags.LockableBackBuffer,
                BackBufferWidth      = Settings.ScreenWidth,
                BackBufferHeight     = Settings.ScreenHeight,
                SwapEffect           = SwapEffect.Discard,
                PresentationInterval = Settings.FPSCap ? PresentInterval.One : PresentInterval.Immediate,
                Windowed             = !Settings.FullScreen,
            };


            Direct3D d3d = new Direct3D();

            Capabilities devCaps  = d3d.GetDeviceCaps(0, DeviceType.Hardware);
            DeviceType   devType  = DeviceType.Reference;
            CreateFlags  devFlags = CreateFlags.HardwareVertexProcessing;

            if (devCaps.VertexShaderVersion.Major >= 2 && devCaps.PixelShaderVersion.Major >= 2)
            {
                devType = DeviceType.Hardware;
            }

            if ((devCaps.DeviceCaps & DeviceCaps.HWTransformAndLight) != 0)
            {
                devFlags = CreateFlags.HardwareVertexProcessing;
            }


            if ((devCaps.DeviceCaps & DeviceCaps.PureDevice) != 0)
            {
                devFlags |= CreateFlags.PureDevice;
            }


            Device = new Device(d3d, d3d.Adapters.DefaultAdapter.Adapter, devType, Program.Form.Handle, devFlags, Parameters);

            Device.SetDialogBoxMode(true);

            LoadTextures();
            LoadPixelsShaders();
        }
示例#11
0
        public void CreateDevice()
        {
            DestroyDevice();

            //just create some present params so we can get the device created
            var pp = new PresentParameters
            {
                BackBufferWidth      = 8,
                BackBufferHeight     = 8,
                DeviceWindowHandle   = OffscreenNativeWindow.WindowInfo.Handle,
                PresentationInterval = PresentInterval.Immediate
            };

            var flags = CreateFlags.SoftwareVertexProcessing;

            if ((d3d.GetDeviceCaps(0, DeviceType.Hardware).DeviceCaps & DeviceCaps.HWTransformAndLight) != 0)
            {
                flags = CreateFlags.HardwareVertexProcessing;
            }
            dev = new Device(d3d, 0, DeviceType.Hardware, pp.DeviceWindowHandle, flags, pp);
        }
示例#12
0
        /// <summary>
        /// Creates a new Instance of the CDirect3D Class
        /// </summary>
        public CDirect3D()
        {
            this.Icon = new System.Drawing.Icon(Path.Combine(System.Environment.CurrentDirectory, CSettings.sIcon));
            _Textures = new Dictionary<int, STexture>();
            _D3DTextures = new Dictionary<int, Texture>();
            _Queque = new List<STextureQueque>();
            _IDs = new Queue<int>();

            //Fill Queue with 100000 IDs
            for (int i = 0; i < 100000; i++)
                _IDs.Enqueue(i);

            _Vertices = new Queue<TexturedColoredVertex>();
            _VerticesTextures = new Queue<Texture>();
            _VerticesRotationMatrices = new Queue<Matrix>();

            _Keys = new CKeys();
            try
            {
                _D3D = new Direct3D();
            }
            catch (Direct3D9NotFoundException e)
            {
                MessageBox.Show("No DirectX runtimes were found, please download and install them " +
                    "from http://www.microsoft.com/download/en/details.aspx?id=8109",
                    CSettings.sProgramName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                CLog.LogError(e.Message + " - No DirectX runtimes were found, please download and install them from http://www.microsoft.com/download/en/details.aspx?id=8109");
                Environment.Exit(Environment.ExitCode);
            }

            this.Paint += new PaintEventHandler(this.OnPaintEvent);
            this.Closing += new CancelEventHandler(this.OnClosingEvent);
            this.Resize += new EventHandler(this.OnResizeEvent);

            this.KeyDown += new KeyEventHandler(this.OnKeyDown);
            this.PreviewKeyDown += new PreviewKeyDownEventHandler(this.OnPreviewKeyDown);
            this.KeyPress += new KeyPressEventHandler(this.OnKeyPress);
            this.KeyUp += new KeyEventHandler(this.OnKeyUp);

            _Mouse = new CMouse();
            this.MouseMove += new MouseEventHandler(this.OnMouseMove);
            this.MouseWheel += new MouseEventHandler(this.OnMouseWheel);
            this.MouseDown += new MouseEventHandler(this.OnMouseDown);
            this.MouseUp += new MouseEventHandler(this.OnMouseUp);
            this.MouseLeave += new EventHandler(this.OnMouseLeave);
            this.MouseEnter += new EventHandler(this.OnMouseEnter);

            this.ClientSize = new Size(CConfig.ScreenW, CConfig.ScreenH);
            _SizeBeforeMinimize = ClientSize;

            _PresentParameters = new PresentParameters();
            _PresentParameters.Windowed = true;
            _PresentParameters.SwapEffect = SwapEffect.Discard;
            _PresentParameters.BackBufferHeight = CConfig.ScreenH;
            _PresentParameters.BackBufferWidth = CConfig.ScreenW;
            _PresentParameters.BackBufferFormat = _D3D.Adapters.DefaultAdapter.CurrentDisplayMode.Format;
            _PresentParameters.Multisample = MultisampleType.None;
            _PresentParameters.MultisampleQuality = 0;

            //Apply antialiasing and check if antialiasing mode is supported
            #region Antialiasing
            int quality = 0;
            if (CConfig.AAMode == EAntiAliasingModes.x0)
            {
                _PresentParameters.Multisample = MultisampleType.None;
                _PresentParameters.MultisampleQuality = quality;
            }
            else if (CConfig.AAMode == EAntiAliasingModes.x2)
            {
                if (_D3D.CheckDeviceMultisampleType(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware, _D3D.Adapters.DefaultAdapter.CurrentDisplayMode.Format, false, MultisampleType.TwoSamples, out quality))
                {
                    _PresentParameters.Multisample = MultisampleType.TwoSamples;
                    _PresentParameters.MultisampleQuality = quality - 1;
                }
                else
                    CLog.LogError("[Direct3D] This AAMode is not supported by this device or driver, fallback to no AA");
            }
            else if (CConfig.AAMode == EAntiAliasingModes.x4)
            {
                if (_D3D.CheckDeviceMultisampleType(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware, _D3D.Adapters.DefaultAdapter.CurrentDisplayMode.Format, false, MultisampleType.FourSamples, out quality))
                {
                    _PresentParameters.Multisample = MultisampleType.FourSamples;
                    _PresentParameters.MultisampleQuality = quality - 1;
                }
                else
                    CLog.LogError("[Direct3D] This AAMode is not supported by this device or driver, fallback to no AA");
            }
            else if (CConfig.AAMode == EAntiAliasingModes.x8)
            {
                if (_D3D.CheckDeviceMultisampleType(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware, _D3D.Adapters.DefaultAdapter.CurrentDisplayMode.Format, false, MultisampleType.EightSamples, out quality))
                {
                    _PresentParameters.Multisample = MultisampleType.EightSamples;
                    _PresentParameters.MultisampleQuality = quality - 1;
                }
                else
                    CLog.LogError("[Direct3D] This AAMode is not supported by this device or driver, fallback to no AA");
            }
            else if (CConfig.AAMode == EAntiAliasingModes.x16 || CConfig.AAMode == EAntiAliasingModes.x32) //x32 is not supported, fallback to x16
            {
                if (_D3D.CheckDeviceMultisampleType(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware, _D3D.Adapters.DefaultAdapter.CurrentDisplayMode.Format, false, MultisampleType.SixteenSamples, out quality))
                {
                    _PresentParameters.Multisample = MultisampleType.SixteenSamples;
                    _PresentParameters.MultisampleQuality = quality - 1;
                }
                else
                    CLog.LogError("[Direct3D] This AAMode is not supported by this device or driver, fallback to no AA");
            }
            #endregion Antialiasing

            //Apply the VSync configuration
            if (CConfig.VSync == EOffOn.TR_CONFIG_ON)
                _PresentParameters.PresentationInterval = PresentInterval.Default;
            else
                _PresentParameters.PresentationInterval = PresentInterval.Immediate;

            //GMA 950 graphics devices can only process vertices in software mode
            Capabilities caps = _D3D.GetDeviceCaps(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware);
            CreateFlags flags = CreateFlags.None;
            if ((caps.DeviceCaps & DeviceCaps.HWTransformAndLight) != 0)
                flags = CreateFlags.HardwareVertexProcessing;
            else
                flags = CreateFlags.SoftwareVertexProcessing;
            try
            {
                _Device = new Device(_D3D, _D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware, Handle, flags, _PresentParameters);
            }
            catch (Exception e)
            {
                MessageBox.Show("Something went wrong during device creating, please check if your DirectX redistributables " +
                    "and graphic card drivers are up to date. You can download the DirectX runtimes at http://www.microsoft.com/download/en/details.aspx?id=8109",
                    CSettings.sProgramName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                CLog.LogError(e.Message + " - Something went wrong during device creating, please check if your DirectX redistributables and grafic card drivers are up to date. You can download the DirectX runtimes at http://www.microsoft.com/download/en/details.aspx?id=8109");
                Environment.Exit(Environment.ExitCode);
            }
            finally
            {
                if (_Device == null || _Device.Disposed)
                {
                    MessageBox.Show("Something went wrong during device creating, please check if your DirectX redistributables " +
                        "and graphic card drivers are up to date. You can download the DirectX runtimes at http://www.microsoft.com/download/en/details.aspx?id=8109",
                        CSettings.sProgramName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    CLog.LogError("Something went wrong during device creating, please check if your DirectX redistributables and grafic card drivers are up to date. You can download the DirectX runtimes at http://www.microsoft.com/download/en/details.aspx?id=8109");
                    Environment.Exit(Environment.ExitCode);
                }
            }

            this.CenterToScreen();
        }
示例#13
0
        static public void Hook06000005(ref Direct3D d3d, ref Device device, ref PresentParameters param, Control control, bool windowed, Size size, int quality)
        {
            fullscreen |= !windowed;
            d3d         = new Direct3D();
            int          adapter     = d3d.Adapters.DefaultAdapter.Adapter;
            Capabilities deviceCaps  = d3d.GetDeviceCaps(adapter, DeviceType.Hardware);
            DeviceType   deviceType  = deviceCaps.DeviceType;
            CreateFlags  createFlags = (deviceCaps.VertexShaderVersion >= new Version(2, 0)) ? CreateFlags.HardwareVertexProcessing : CreateFlags.SoftwareVertexProcessing;

            param            = new PresentParameters();
            param.SwapEffect = SwapEffect.Discard;
            DisplayMode currentDisplayMode = d3d.Adapters[adapter].CurrentDisplayMode;

            param.Windowed = (windowed || !d3d.CheckDeviceType(adapter, DeviceType.Hardware, currentDisplayMode.Format, currentDisplayMode.Format, false));
            if (param.Windowed)
            {
                param.DeviceWindowHandle = control.Handle;
                if (!fullscreen)
                {
                    param.BackBufferWidth  = 0;
                    param.BackBufferHeight = 0;
                }
                else
                {
                    param.BackBufferWidth  = size.Width;
                    param.BackBufferHeight = size.Height;
                    control.ClientSize     = new Size(currentDisplayMode.Width, currentDisplayMode.Height);
                    control.Location       = new Point(0, 0);
                }
            }
            else
            {
                param.BackBufferFormat = currentDisplayMode.Format;
                param.BackBufferCount  = 1;
                if (size.Width == 0 || size.Height == 0)
                {
                    size = new Size(currentDisplayMode.Width, currentDisplayMode.Height);
                }
                param.BackBufferWidth  = size.Width;
                param.BackBufferHeight = size.Height;
                param.PresentFlags     = PresentFlags.LockableBackBuffer;
                control.ClientSize     = new Size(currentDisplayMode.Width, currentDisplayMode.Height);
                control.Location       = new Point(0, 0);
            }
            if (d3d.CheckDeviceFormat(adapter, DeviceType.Hardware, currentDisplayMode.Format, Usage.DepthStencil, ResourceType.Surface, Format.D24S8))
            {
                param.EnableAutoDepthStencil = true;
                param.AutoDepthStencilFormat = Format.D24S8;
            }
            MultisampleType multisampleType = quality <= 1 ? MultisampleType.None : MultisampleType.NonMaskable;

            while (multisampleType > MultisampleType.None)
            {
                int val;
                int val2;
                if (d3d.CheckDeviceMultisampleType(adapter, deviceType, param.BackBufferFormat, param.Windowed, multisampleType, out val) && d3d.CheckDeviceMultisampleType(adapter, deviceType, Format.D24S8, param.Windowed, multisampleType, out val2))
                {
                    param.Multisample = multisampleType;
                    if (multisampleType == MultisampleType.NonMaskable)
                    {
                        param.MultisampleQuality = Math.Min(Math.Min(val, val2) - 1, (int)Math.Log(quality, 2) - 1);
                        break;
                    }
                    break;
                }
                else
                {
                    multisampleType--;
                }
            }
            param.PresentationInterval = PresentInterval.One;
            device = new Device(d3d, adapter, deviceType, control.Handle, createFlags, new PresentParameters[] { param });
        }
示例#14
0
 private void buttonTS1_Click(object sender, EventArgs e)
 {
     try
     {
         Direct3D w = new Direct3D();
         Capabilities q = w.GetDeviceCaps(0, DeviceType.Hardware);
         rtbDebugMsg.AppendText("Vertex Shader ver: \n" + q.VertexShaderVersion.ToString() + "\n");
         rtbDebugMsg.AppendText("Device Type: \n" + q.DeviceType.ToString() + "\n");
         rtbDebugMsg.AppendText("Device Caps: \n" + q.DeviceCaps.ToString() + "\n");
         rtbDebugMsg.AppendText("Device Caps2: \n" + q.DeviceCaps2.ToString() + "\n");
         rtbDebugMsg.AppendText("Pixel Shader: \n" + q.PixelShaderVersion.ToString() + "\n");
         rtbDebugMsg.AppendText("Texture Caps: \n" + q.TextureCaps.ToString() + "\n");
         rtbDebugMsg.AppendText("FVF Caps: \n" + q.FVFCaps.ToString() + "\n");
         rtbDebugMsg.AppendText("Line Caps: \n" + q.LineCaps.ToString() + "\n");
         rtbDebugMsg.AppendText("MaxVertexIndex Caps: \n" + q.MaxVertexIndex.ToString() + "\n");
         rtbDebugMsg.AppendText("PrimitiveMiscCaps: \n" + q.PrimitiveMiscCaps.ToString() + "\n");
         rtbDebugMsg.AppendText("RatserCaps: \n" + q.RasterCaps.ToString() + "\n");
         rtbDebugMsg.AppendText("VertexProcessingCaps: \n" + q.VertexProcessingCaps.ToString() + "\n");
         rtbDebugMsg.AppendText("VS20Caps: \n" + q.VS20Caps.ToString() + "\n");
     }
     catch (Exception ex)
     {
         Debug.Write(ex.ToString());
     }
 }
        /// <summary>
        /// Initializes the Direct3D objects and sets the Available flag
        /// </summary>
        private void InitializeDirect3D()
        {
            DirectXStatus = DirectXStatus.Unavailable_Unknown;

            ReleaseDevice();
            ReleaseDirect3D();

            // assume that we can't run at all under terminal services
            //if (GetSystemMetrics(SM_REMOTESESSION) != 0)
            //{
            //    DirectXStatus = DirectXStatus.Unavailable_RemoteSession;
            //    return;
            //}

            //int renderingTier = (RenderCapability.Tier >> 16);
            //if (renderingTier < 2)
            //{
            //DirectXStatus = DirectXStatus.Unavailable_LowTier;
            //return;
            //}

#if USE_XP_MODE
            _direct3D   = new Direct3D();
            UseDeviceEx = false;
#else
            try
            {
                direct3DEx  = new Direct3DEx();
                UseDeviceEx = true;
            }
            catch
            {
                try
                {
                    direct3D    = new Direct3D();
                    UseDeviceEx = false;
                }
                catch (Direct3DX9NotFoundException)
                {
                    DirectXStatus = DirectXStatus.Unavailable_MissingDirectX;
                    return;
                }
                catch
                {
                    DirectXStatus = DirectXStatus.Unavailable_Unknown;
                    return;
                }
            }
#endif

            bool   ok;
            Result result;

            ok = Direct3D.CheckDeviceType(0, DeviceType.Hardware, adapterFormat, backbufferFormat, true, out result);
            if (!ok)
            {
                //const int D3DERR_NOTAVAILABLE = -2005530518;
                //if (result.Code == D3DERR_NOTAVAILABLE)
                //{
                //   ReleaseDirect3D();
                //   Available = Status.Unavailable_NotReady;
                //   return;
                //}
                ReleaseDirect3D();
                return;
            }

            ok = Direct3D.CheckDepthStencilMatch(0, DeviceType.Hardware, adapterFormat, backbufferFormat, depthStencilFormat, out result);
            if (!ok)
            {
                ReleaseDirect3D();
                return;
            }

            Capabilities deviceCaps = Direct3D.GetDeviceCaps(0, DeviceType.Hardware);
            if ((deviceCaps.DeviceCaps & DeviceCaps.HWTransformAndLight) != 0)
            {
                createFlags |= CreateFlags.HardwareVertexProcessing;
            }
            else
            {
                createFlags |= CreateFlags.SoftwareVertexProcessing;
            }

            DirectXStatus = DirectXStatus.Available;

            return;
        }
示例#16
0
        /// <summary>
        /// Creates a new Instance of the CDirect3D Class
        /// </summary>
        public CDirect3D()
        {
            this.Icon = new System.Drawing.Icon(Path.Combine(System.Environment.CurrentDirectory, CSettings.sIcon));
            _Textures = new List<STexture>();
            _D3DTextures = new List<Texture>();
            _Queque = new List<STextureQueque>();

            _Keys = new CKeys();
            _D3D = new Direct3D();

            this.Paint += new PaintEventHandler(this.OnPaintEvent);
            this.Closing += new CancelEventHandler(this.OnClosingEvent);
            this.Resize += new EventHandler(this.OnResizeEvent);

            this.KeyDown += new KeyEventHandler(this.OnKeyDown);
            this.PreviewKeyDown += new PreviewKeyDownEventHandler(this.OnPreviewKeyDown);
            this.KeyPress += new KeyPressEventHandler(this.OnKeyPress);
            this.KeyUp += new KeyEventHandler(this.OnKeyUp);

            _Mouse = new CMouse();
            this.MouseMove += new MouseEventHandler(this.OnMouseMove);
            this.MouseWheel += new MouseEventHandler(this.OnMouseWheel);
            this.MouseDown += new MouseEventHandler(this.OnMouseDown);
            this.MouseUp += new MouseEventHandler(this.OnMouseUp);
            this.MouseLeave += new EventHandler(this.OnMouseLeave);
            this.MouseEnter += new EventHandler(this.OnMouseEnter);

            this.ClientSize = new Size(CConfig.ScreenW, CConfig.ScreenH);
            _SizeBeforeMinimize = ClientSize;

            _PresentParameters = new PresentParameters();
            _PresentParameters.Windowed = true;
            _PresentParameters.SwapEffect = SwapEffect.Discard;
            _PresentParameters.BackBufferHeight = CConfig.ScreenH;
            _PresentParameters.BackBufferWidth = CConfig.ScreenW;
            _PresentParameters.BackBufferFormat = _D3D.Adapters.DefaultAdapter.CurrentDisplayMode.Format;
            _PresentParameters.Multisample = MultisampleType.None;
            _PresentParameters.MultisampleQuality = 0;

            //Apply antialiasing and check if antialiasing mode is supported
            #region Antialiasing
            int quality = 0;
            if (CConfig.AAMode == EAntiAliasingModes.x0)
            {
                _PresentParameters.Multisample = MultisampleType.None;
                _PresentParameters.MultisampleQuality = quality;
            }
            else if (CConfig.AAMode == EAntiAliasingModes.x2)
            {
                if (_D3D.CheckDeviceMultisampleType(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware, _D3D.Adapters.DefaultAdapter.CurrentDisplayMode.Format, false, MultisampleType.TwoSamples, out quality))
                {
                    _PresentParameters.Multisample = MultisampleType.TwoSamples;
                    _PresentParameters.MultisampleQuality = quality - 1;
                }
                else
                    CLog.LogError("[Direct3D] This AAMode is not supported by this device or driver, fallback to no AA");
            }
            else if (CConfig.AAMode == EAntiAliasingModes.x4)
            {
                if (_D3D.CheckDeviceMultisampleType(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware, _D3D.Adapters.DefaultAdapter.CurrentDisplayMode.Format, false, MultisampleType.FourSamples, out quality))
                {
                    _PresentParameters.Multisample = MultisampleType.FourSamples;
                    _PresentParameters.MultisampleQuality = quality - 1;
                }
                else
                    CLog.LogError("[Direct3D] This AAMode is not supported by this device or driver, fallback to no AA");
            }
            else if (CConfig.AAMode == EAntiAliasingModes.x8)
            {
                if (_D3D.CheckDeviceMultisampleType(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware, _D3D.Adapters.DefaultAdapter.CurrentDisplayMode.Format, false, MultisampleType.EightSamples, out quality))
                {
                    _PresentParameters.Multisample = MultisampleType.EightSamples;
                    _PresentParameters.MultisampleQuality = quality - 1;
                }
                else
                    CLog.LogError("[Direct3D] This AAMode is not supported by this device or driver, fallback to no AA");
            }
            else if (CConfig.AAMode == EAntiAliasingModes.x16 || CConfig.AAMode == EAntiAliasingModes.x32) //x32 is not supported, fallback to x16
            {
                if (_D3D.CheckDeviceMultisampleType(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware, _D3D.Adapters.DefaultAdapter.CurrentDisplayMode.Format, false, MultisampleType.SixteenSamples, out quality))
                {
                    _PresentParameters.Multisample = MultisampleType.SixteenSamples;
                    _PresentParameters.MultisampleQuality = quality - 1;
                }
                else
                    CLog.LogError("[Direct3D] This AAMode is not supported by this device or driver, fallback to no AA");
            }
            #endregion Antialiasing

            //Apply the VSync configuration
            if (CConfig.VSync == EOffOn.TR_CONFIG_ON)
                _PresentParameters.PresentationInterval = PresentInterval.Default;
            else
                _PresentParameters.PresentationInterval = PresentInterval.Immediate;

            //GMA 950 graphics devices can only process vertices in software mode
            Capabilities caps = _D3D.GetDeviceCaps(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware);
            CreateFlags flags = CreateFlags.None;
            if ((caps.DeviceCaps & DeviceCaps.HWTransformAndLight) != 0)
                flags = CreateFlags.HardwareVertexProcessing;
            else
                flags = CreateFlags.SoftwareVertexProcessing;
            _Device = new Device(_D3D, _D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware, Handle, flags, _PresentParameters);

            this.CenterToScreen();

            //This creates a new white texture and adds it to the texture pool
            //This texture is used for the DrawRect method
            blankMap = new Bitmap(1, 1);
            Graphics g = Graphics.FromImage(blankMap);
            g.Clear(Color.White);
            g.Dispose();
            blankTexture = AddTexture(blankMap);

            transparentTexture = new Texture(_Device, 1, 1, 0, Usage.None, Format.A8R8G8B8, Pool.Managed);
            blankMap.Dispose();
        }
示例#17
0
        private void Initialize(SDL_RendererFlags flags)
        {
            _info       = new RendererInfo();
            _info.Flags = SDL_RendererFlags.SDL_RENDERER_ACCELERATED;

            _d3d = new Direct3D();

            _pparams = new PresentParameters();
            _pparams.DeviceWindowHandle = _hwnd;
            _pparams.BackBufferWidth    = _window.ClientSize.Width;
            _pparams.BackBufferHeight   = _window.ClientSize.Height;
            if (Config.Fullscreen)
            {
            }
            else
            {
                _pparams.BackBufferFormat = Format.Unknown;
            }
            _pparams.BackBufferCount = 1;// 后备缓冲区的数量。通常设为“1”,即只有一个后备表面。

            /*
             * 指定系统如何将后台缓冲区的内容复制到前台缓冲区,从而在屏幕上显示。它的值有:
             * D3DSWAPEFFECT_DISCARD: 清除后台缓存的内容。
             * D3DSWAPEEFECT_FLIP: 保留后台缓存的内容,当缓存区>1时。
             * D3DSWAPEFFECT_COPY: 保留后台缓存的内容,缓冲区=1时。
             * 一般情况下使用D3DSWAPEFFECT_DISCARD
             */
            _pparams.SwapEffect = SwapEffect.Discard;

            if (Config.Fullscreen)
            {
                if (Config.Borderless)
                {
                    _pparams.Windowed = true;
                    _pparams.FullScreenRefreshRateInHz = 0;
                }
                else
                {
                    _pparams.Windowed = false;
                    _pparams.FullScreenRefreshRateInHz = 0;
                }
            }
            else
            {
                _pparams.Windowed = true;// 指定窗口模式。True = 窗口模式;False = 全屏模式

                /*
                 * 显示适配器刷新屏幕的速率。该值取决于应用程序运行的模式:
                 * 对于窗口模式,刷新率必须为0。
                 * 对于全屏模式,刷新率是EnumAdapterModes返回的刷新率之一。
                 */
                _pparams.FullScreenRefreshRateInHz = 0;
            }
            if ((flags & SDL_RendererFlags.SDL_RENDERER_PRESENTVSYNC) != 0)
            {
                /*
                 * 交换链的后缓冲区可以提供给前缓冲区的最大速率。可以用以下方式:
                 * D3DPRESENT_INTERVAL_DEFAULT: 这几乎等同于D3DPRESENT_INTERVAL_ONE。
                 * D3DPRESENT_INTERVAL_ONE: 垂直同步。当前的操作不会比刷新屏幕更频繁地受到影响。
                 * D3DPRESENT_INTERVAL_IMMEDIATE: 以实时的方式来显示渲染画面。
                 */
                _pparams.PresentationInterval = PresentInterval.One;
            }
            else
            {
                _pparams.PresentationInterval = PresentInterval.Immediate;
            }

            CreateFlags device_flags = CreateFlags.FpuPreserve;// 将Direct3D浮点计算的精度设置为调用线程使用的精度
            //device_flags |= CreateFlags.Multithreaded;// 瓶颈主要在IO上面,且SDL中尚未设置,此处预留以备不时之需
            Capabilities caps = _d3d.GetDeviceCaps(D3DADAPTER_DEFAULT, DeviceType.Hardware);

            if ((caps.DeviceCaps & DeviceCaps.HWTransformAndLight) != 0)
            {
                device_flags |= CreateFlags.HardwareVertexProcessing;
            }
            else
            {
                device_flags |= CreateFlags.SoftwareVertexProcessing;
            }

            /*
             * @param adapter       表示显示适配器的序号。D3DADAPTER_DEFAULT(0)始终是主要的显示适配器。
             * @param renderWindow  窗体或任何其他Control派生类的句柄。此参数指示要绑定到设备的表面。
             *                      指定的窗口必须是顶级窗口。不支持空值。
             * @param deviceType    定义设备类型。
             *                      D3DDEVTYPE_HAL 硬件栅格化。可以使用软件,硬件或混合的变换和照明进行着色。
             *                      详见:https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3ddevtype
             * @param behaviorFlags 控制设备创建行为的一个或多个标志的组合。
             *                      D3DCREATE_HARDWARE_VERTEXPROCESSING 指定硬件顶点处理。
             *                      D3DCREATE_SOFTWARE_VERTEXPROCESSING 指定软件顶点处理。
             *                      对于Windows 10版本1607及更高版本,不建议使用此设置。
             *                      使用D3DCREATE_HARDWARE_VERTEXPROCESSING。
             *                      [!Note] 除非没有可用的硬件顶点处理,
             *                      否则在Windows 10版本1607(及更高版本)中不建议使用软件顶点处理,
             *                      因为在提高实现安全性的同时,软件顶点处理的效率已大大降低。
             *                      详见:https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3dcreate
             *
             * @see https://docs.microsoft.com/en-us/windows/win32/api/d3d9/nf-d3d9-idirect3d9-createdevice
             */
            _d3dDevice = new Device(_d3d
                                    , D3DADAPTER_DEFAULT
                                    , DeviceType.Hardware
                                    , _hwnd
                                    , device_flags
                                    , _pparams);
            _beginScene = true;
            _scaleMode  = (TextureFilter)D3DTEXF_FORCE_DWORD;

            // Get presentation parameters to fill info
            SwapChain chain = _d3dDevice.GetSwapChain(0);

            _pparams = chain.PresentParameters;
            chain.Dispose();// FIXME: IDirect3DSwapChain9::Release?
            if (_pparams.PresentationInterval == PresentInterval.One)
            {
                _info.Flags |= SDL_RendererFlags.SDL_RENDERER_PRESENTVSYNC;
            }

            caps = _d3dDevice.Capabilities;
            _info.MaxTextureWidth  = caps.MaxTextureWidth;
            _info.MaxTextureHeight = caps.MaxTextureHeight;
            if (caps.SimultaneousRTCount >= 2)
            {
                _info.Flags |= SDL_RendererFlags.SDL_RENDERER_TARGETTEXTURE;
            }

            // Set up parameters for rendering
            _d3dDevice.VertexShader = null;
            // IDirect3DDevice9::SetFVF(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1)
            _d3dDevice.VertexFormat = VertexFormat.Position | VertexFormat.Diffuse | VertexFormat.Texture1;
            // IDirect3DDevice9::SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE)
            _d3dDevice.SetRenderState(RenderState.ZEnable, ZBufferType.DontUseZBuffer);
            _d3dDevice.SetRenderState(RenderState.CullMode, Cull.None);
            _d3dDevice.SetRenderState(RenderState.Lighting, false);
            // Enable color modulation by diffuse color
            _d3dDevice.SetTextureStageState(0, TextureStage.ColorOperation, TextureOperation.Modulate);
            _d3dDevice.SetTextureStageState(0, TextureStage.ColorArg1, TextureArgument.Texture);
            _d3dDevice.SetTextureStageState(0, TextureStage.ColorArg2, TextureArgument.Diffuse);
            // Enable alpha modulation by diffuse alpha
            _d3dDevice.SetTextureStageState(0, TextureStage.AlphaOperation, TextureOperation.Modulate);
            _d3dDevice.SetTextureStageState(0, TextureStage.AlphaArg1, TextureArgument.Texture);
            _d3dDevice.SetTextureStageState(0, TextureStage.AlphaArg2, TextureArgument.Diffuse);
            // Disable second texture stage, since we're done
            _d3dDevice.SetTextureStageState(1, TextureStage.ColorOperation, TextureOperation.Disable);
            _d3dDevice.SetTextureStageState(1, TextureStage.AlphaOperation, TextureOperation.Disable);

            // Store the default render target
            _defaultRenderTarget = _d3dDevice.GetRenderTarget(0);
            _currentRenderTarget = null;

            // Set an identity world and view matrix
            RawMatrix matrix;

            matrix.M11 = 1.0f;
            matrix.M12 = 0.0f;
            matrix.M13 = 0.0f;
            matrix.M14 = 0.0f;
            matrix.M21 = 0.0f;
            matrix.M22 = 1.0f;
            matrix.M23 = 0.0f;
            matrix.M24 = 0.0f;
            matrix.M31 = 0.0f;
            matrix.M32 = 0.0f;
            matrix.M33 = 1.0f;
            matrix.M34 = 0.0f;
            matrix.M41 = 0.0f;
            matrix.M42 = 0.0f;
            matrix.M43 = 0.0f;
            matrix.M44 = 1.0f;
            _d3dDevice.SetTransform(TransformState.World, matrix);
            _d3dDevice.SetTransform(TransformState.View, matrix);

            _scale.x = 1.0f;
            _scale.y = 1.0f;

            if (!_window.Visible || _window.WindowState == FormWindowState.Minimized)
            {
                _hidden = true;
            }
            else
            {
                _hidden = false;
            }
        }
示例#18
0
        // This initializes the graphics
        public bool Initialize()
        {
            PresentParameters displaypp;
            DeviceType        devtype;

            // Use default adapter
            this.adapter = 0;             // Manager.Adapters.Default.Adapter;

            try
            {
                // Make present parameters
                displaypp = CreatePresentParameters(adapter);

                // Determine device type for compatability with NVPerfHUD
                if (d3d.Adapters[adapter].Details.Description.EndsWith(NVPERFHUD_ADAPTER))
                {
                    devtype = DeviceType.Reference;
                }
                else
                {
                    devtype = DeviceType.Hardware;
                }

                // Get the device capabilities
                devicecaps = d3d.GetDeviceCaps(adapter, devtype);

                // Check if this adapter supports TnL
                if ((devicecaps.DeviceCaps & DeviceCaps.HWTransformAndLight) != 0)
                {
                    // Initialize with hardware TnL
                    device = new Device(d3d, adapter, devtype, rendertarget.Handle,
                                        CreateFlags.HardwareVertexProcessing, displaypp);
                }
                else
                {
                    // Initialize with software TnL
                    device = new Device(d3d, adapter, devtype, rendertarget.Handle,
                                        CreateFlags.SoftwareVertexProcessing, displaypp);
                }
            }
            catch (Exception)
            {
                // Failed
                MessageBox.Show(General.MainWindow, "Unable to initialize the Direct3D video device. Another application may have taken exclusive mode on this video device or the device does not support Direct3D at all.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            // Add event to cancel resize event
            //device.DeviceResizing += new CancelEventHandler(CancelResize);

            // Keep a reference to the original buffers
            backbuffer  = device.GetBackBuffer(0, 0);
            depthbuffer = device.DepthStencilSurface;

            // Get the viewport
            viewport = device.Viewport;

            // Create shader manager
            shaders = new ShaderManager(this);

            // Font
            postfilter  = Filter.Box;
            font        = new TextFont();
            fonttexture = new ResourceImage("CodeImp.DoomBuilder.Resources.Font.png");
            fonttexture.LoadImage();
            fonttexture.MipMapLevels = 2;
            fonttexture.CreateTexture();

            // Initialize settings
            SetupSettings();

            // Done
            return(true);
        }
示例#19
0
        // This initializes the graphics
        public bool Initialize()
        {
            // Use default adapter
            this.adapter = 0;             // Manager.Adapters.Default.Adapter;

            try
            {
                // Make present parameters
                PresentParameters displaypp = CreatePresentParameters(adapter);

                // Determine device type for compatability with NVPerfHUD
                DeviceType devtype;
                if (d3d.Adapters[adapter].Details.Description.EndsWith(NVPERFHUD_ADAPTER))
                {
                    devtype = DeviceType.Reference;
                }
                else
                {
                    devtype = DeviceType.Hardware;
                }

                //mxd. Check maximum supported AA level...
                for (int i = AA_STEPS.Count - 1; i > 0; i--)
                {
                    if (General.Settings.AntiAliasingSamples < AA_STEPS[i])
                    {
                        continue;
                    }
                    if (d3d.CheckDeviceMultisampleType(this.adapter, devtype, d3d.Adapters[adapter].CurrentDisplayMode.Format, displaypp.Windowed, (MultisampleType)AA_STEPS[i]))
                    {
                        break;
                    }

                    if (General.Settings.AntiAliasingSamples > AA_STEPS[i - 1])
                    {
                        General.Settings.AntiAliasingSamples = AA_STEPS[i - 1];

                        // TODO: looks like setting Multisample here just resets it to MultisampleType.None,
                        // regardless of value in displaypp.Multisample. Why?..
                        displaypp.Multisample = (MultisampleType)General.Settings.AntiAliasingSamples;
                    }
                }

                // Get the device capabilities
                devicecaps = d3d.GetDeviceCaps(adapter, devtype);

                // Check if this adapter supports TnL
                if ((devicecaps.DeviceCaps & DeviceCaps.HWTransformAndLight) != 0)
                {
                    // Initialize with hardware TnL
                    device = new Device(d3d, adapter, devtype, rendertarget.Handle,
                                        CreateFlags.HardwareVertexProcessing, displaypp);
                }
                else
                {
                    // Initialize with software TnL
                    device = new Device(d3d, adapter, devtype, rendertarget.Handle,
                                        CreateFlags.SoftwareVertexProcessing, displaypp);
                }
            }
            catch (Exception)
            {
                // Failed
                MessageBox.Show(General.MainWindow, "Unable to initialize the Direct3D video device. Another application may have taken exclusive mode on this video device or the device does not support Direct3D at all.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            //mxd. Check if we can use shaders
            if (device.Capabilities.PixelShaderVersion.Major < 2)
            {
                // Failed
                MessageBox.Show(General.MainWindow, "Unable to initialize the Direct3D video device. Video device with Shader Model 2.0 support is required.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            // Add event to cancel resize event
            //device.DeviceResizing += new CancelEventHandler(CancelResize);

            // Keep a reference to the original buffers
            backbuffer  = device.GetBackBuffer(0, 0);
            depthbuffer = device.DepthStencilSurface;

            // Get the viewport
            viewport = device.Viewport;

            // Create shader manager
            shaders = new ShaderManager(this);

            // Initialize settings
            SetupSettings();

            // Done
            return(true);
        }
示例#20
0
        public bool InitializeDirect3D()
        {
            //try
            //{
            PresentParameters presentParams = new PresentParameters();

            presentParams.Windowed               = true;               // We don't want to run fullscreen
            presentParams.SwapEffect             = SwapEffect.Discard; // Discard the frames
            presentParams.AutoDepthStencilFormat = Format.D16;         //24 bits for the depth and 8 bits for the stencil
            presentParams.EnableAutoDepthStencil = true;               //Let direct3d handle the depth buffers for the application
            presentParams.PresentationInterval   = PresentInterval.One;

            Direct3D    d3d = new Direct3D();
            IEnumerator i   = d3d.Adapters.GetEnumerator();

            while (i.MoveNext())
            {
                AdapterInformation ai       = i.Current as AdapterInformation;
                int          adapterOrdinal = ai.Adapter;
                Capabilities hardware       = d3d.GetDeviceCaps(adapterOrdinal, DeviceType.Hardware);
                CreateFlags  flags          = CreateFlags.SoftwareVertexProcessing;
                if (hardware.DeviceCaps == DeviceCaps.HWTransformAndLight)
                {
                    flags = CreateFlags.HardwareVertexProcessing;
                }

                Device = new Device(d3d, adapterOrdinal, hardware.DeviceType, this.Handle, flags, presentParams);     //Create a device
                if (Device != null)
                {
                    break;
                }
            }

            // Camera
            this.Focus();
            cam       = new Camera(this);
            cam.speed = 0.02f;

            cam.Position.X = 0.5741551f;
            cam.Position.Y = 0.01331316f;
            cam.Position.Z = 0.4271703f;

            cam.radianv = 6.161014f;
            cam.radianh = 3.14159f;

            cam.x = 0.5741551f;
            cam.y = 0.01331316f;
            cam.z = 0.4271703f;

            cam.ComputePosition();

            //Device.DeviceReset += new EventHandler(Device_DeviceReset);
            Device_DeviceReset(Device, null);

            // Load Model
            model.Initialize(Device);
            //Button.Position = new Microsoft.DirectX.Vector2(10f, 10f);
            //Panel.Controls.Add(Button);
            //Panel.Initialize(Device);
            //Panel.Opacity = 100;
            //Panel.Size = new Size(500, 100);
            return(true);
            //}
            //catch (Exception e)
            //{
            //    MessageBox.Show(e.ToString(), "Error"); // Handle all the exceptions
            //    return false;
            //}
        }
示例#21
0
        /// <summary>
        ///     Creates a new Instance of the CDirect3D Class
        /// </summary>
        public CDirect3D()
        {
            _Form = new CRenderFormHook {
                ClientSize = new Size(CConfig.Config.Graphics.ScreenW, CConfig.Config.Graphics.ScreenH)
            };

            try
            {
                _D3D = new Direct3D();
            }
            catch (Direct3DX9NotFoundException e)
            {
                CLog.LogError("No DirectX runtimes were found, please download and install them from http://www.microsoft.com/download/en/details.aspx?id=8109", true, true, e);
            }

            _Form.KeyDown        += _OnKeyDown;
            _Form.PreviewKeyDown += _OnPreviewKeyDown;
            _Form.KeyPress       += _OnKeyPress;
            _Form.KeyUp          += _OnKeyUp;

            _Form.MouseMove  += _OnMouseMove;
            _Form.MouseWheel += _OnMouseWheel;
            _Form.MouseDown  += _OnMouseDown;
            _Form.MouseUp    += _OnMouseUp;
            _Form.MouseLeave += _OnMouseLeave;
            _Form.MouseEnter += _OnMouseEnter;

            _PresentParameters = new PresentParameters
            {
                Windowed           = true,
                SwapEffect         = SwapEffect.Discard,
                BackBufferHeight   = CConfig.Config.Graphics.ScreenH,
                BackBufferWidth    = CConfig.Config.Graphics.ScreenW,
                BackBufferFormat   = _D3D.Adapters.DefaultAdapter.CurrentDisplayMode.Format,
                Multisample        = MultisampleType.None,
                MultisampleQuality = 0
            };

            //Apply antialiasing and check if antialiasing mode is supported

            #region Antialiasing
            int             quality;
            MultisampleType msType;
            switch (CConfig.Config.Graphics.AAMode)
            {
            case EAntiAliasingModes.X2:
                msType = MultisampleType.TwoSamples;
                break;

            case EAntiAliasingModes.X4:
                msType = MultisampleType.FourSamples;
                break;

            case EAntiAliasingModes.X8:
                msType = MultisampleType.EightSamples;
                break;

            case EAntiAliasingModes.X16:
            case EAntiAliasingModes.X32:     //x32 is not supported, fallback to x16
                msType = MultisampleType.SixteenSamples;
                break;

            default:
                msType = MultisampleType.None;
                break;
            }

            if (
                !_D3D.CheckDeviceMultisampleType(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware, _D3D.Adapters.DefaultAdapter.CurrentDisplayMode.Format, false, msType,
                                                 out quality))
            {
                CLog.LogError("[Direct3D] This AAMode is not supported by this device or driver, fallback to no AA");
                msType  = MultisampleType.None;
                quality = 1;
            }

            _PresentParameters.Multisample        = msType;
            _PresentParameters.MultisampleQuality = quality - 1;
            #endregion Antialiasing

            //Apply the VSync configuration
            _PresentParameters.PresentationInterval = CConfig.Config.Graphics.VSync == EOffOn.TR_CONFIG_ON ? PresentInterval.Default : PresentInterval.Immediate;

            //GMA 950 graphics devices can only process vertices in software mode
            Capabilities caps  = _D3D.GetDeviceCaps(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware);
            CreateFlags  flags = (caps.DeviceCaps & DeviceCaps.HWTransformAndLight) != 0 ? CreateFlags.HardwareVertexProcessing : CreateFlags.SoftwareVertexProcessing;

            //Check if Pow2 textures are needed
            _NonPowerOf2TextureSupported  = true;
            _NonPowerOf2TextureSupported &= (caps.TextureCaps & TextureCaps.Pow2) == 0;
            _NonPowerOf2TextureSupported &= (caps.TextureCaps & TextureCaps.NonPow2Conditional) == 0;
            _NonPowerOf2TextureSupported &= (caps.TextureCaps & TextureCaps.SquareOnly) == 0;

            try
            {
                _Device = new Device(_D3D, _D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware, _Form.Handle, flags, _PresentParameters);
            }
            catch (Exception e)
            {
                CLog.LogError("Error during D3D device creation.", false, false, e);
            }
            finally
            {
                if (_Device == null || _Device.Disposed)
                {
                    CLog.LogError(
                        "Something went wrong during device creating, please check if your DirectX redistributables and grafic card drivers are up to date. You can download the DirectX runtimes at http://www.microsoft.com/download/en/details.aspx?id=8109",
                        true, true);
                }
            }
        }