Пример #1
0
        /// <summary>
        ///		Enumerates driver information and their supported display modes.
        /// </summary>
        public static Driver GetDriverInfo()
        {
            ArrayList driverList = new ArrayList();

            // get the information for the default adapter (not checking secondaries)
            AdapterInformation adapterInfo = D3D.Manager.Adapters[0];

            Driver driver = new Driver(adapterInfo);

            int lastWidth = 0, lastHeight = 0;

            D3D.Format lastFormat = 0;

            foreach (DisplayMode mode in adapterInfo.SupportedDisplayModes)
            {
                // filter out lower resolutions, and make sure this isnt a dupe (ignore variations on refresh rate)
                if ((mode.Width >= 640 && mode.Height >= 480) &&
                    ((mode.Width != lastWidth) || mode.Height != lastHeight || mode.Format != lastFormat))
                {
                    // add the video mode to the list
                    driver.VideoModes.Add(new VideoMode(mode));

                    // save current mode settings for comparison on the next iteraion
                    lastWidth  = mode.Width;
                    lastHeight = mode.Height;
                    lastFormat = mode.Format;
                }
            }

            return(driver);
        }
Пример #2
0
        /// <summary>
        /// Initializes the graphics.
        /// </summary>
        public void Initialize()
        {
            _direct3D = new Direct3D();
            AdapterInformation primaryAdaptor = _direct3D.Adapters.DefaultAdapter;

            var presentationParameters = new PresentParameters
            {
                BackBufferCount    = 1,
                BackBufferWidth    = _graphicsDevice.BackBuffer.Width,
                BackBufferHeight   = _graphicsDevice.BackBuffer.Height,
                DeviceWindowHandle = _graphicsDevice.RenderTarget.Handle,
                SwapEffect         = SwapEffect.Discard,
                Windowed           = true,
                BackBufferFormat   = Format.A8R8G8B8,
            };

            if (SmoothingMode == SmoothingMode.AntiAlias)
            {
                SetHighestMultisampleType(presentationParameters);
                _direct3D9Device.SetRenderState(RenderState.MultisampleAntialias, true);
            }

            presentationParameters.PresentationInterval = PresentInterval.Immediate;

            _direct3D9Device = new Device(_direct3D, primaryAdaptor.Adapter, DeviceType.Hardware,
                                          _graphicsDevice.RenderTarget.Handle,
                                          CreateFlags.HardwareVertexProcessing, presentationParameters);

            DirectXHelper.Direct3D9 = _direct3D9Device;

            _sprite = new Sprite(_direct3D9Device);
        }
Пример #3
0
        public Allocator(Device dev)
        {
            adapterInfo = Manager.Adapters.Default;

            device = dev;

            creationParameters = device.CreationParameters;
        }
Пример #4
0
        public Allocator(Device dev)
        {
            adapterInfo = Manager.Adapters.Default;

              device = dev;

              creationParameters = device.CreationParameters;
        }
Пример #5
0
        public override void Init(GDI.Rectangle srcRect, GDI.Size destSize)
        {
            logger.Debug("Direct3DCapture::Init(...)");

            base.Init(srcRect, destSize);

            //this.videoBuffer = new VideoBuffer(destSize.Width, destSize.Height, PixelFormat.Format32bppArgb);

            adapterInfo = direct3D9.Adapters.FirstOrDefault(); //  DefaultAdapter;//direct3D9.Adapters[1];

            var hMonitor = User32.GetMonitorFromRect(srcRect);

            if (hMonitor != IntPtr.Zero)
            {
                adapterInfo = direct3D9.Adapters.FirstOrDefault(a => a.Monitor == hMonitor);
            }

            if (hWnd == IntPtr.Zero)
            {// иначе не работает Device.Reset()
                hWnd = User32.GetDesktopWindow();
            }

            logger.Info("DefaultAdapter " + " " + adapterInfo.Details.DeviceName + " " + adapterInfo.Details.Description);

            var displayMode = adapterInfo.CurrentDisplayMode;

            logger.Info("CurrentDisplayMode " + " " + displayMode.Width + "x" + displayMode.Height + " " + displayMode.Format);

            //Rectangle clientRect = NativeMethods.GetAbsoluteClientRect(hWnd);

            presentParams = new PresentParameters
            {
                //BackBufferHeight = clientRect.Height,
                //BackBufferWidth = clientRect.Width,
                BackBufferHeight = adapterInfo.CurrentDisplayMode.Height,
                BackBufferWidth  = adapterInfo.CurrentDisplayMode.Width,
                BackBufferFormat = adapterInfo.CurrentDisplayMode.Format,
                BackBufferCount  = 1,

                Windowed = true,

                MultiSampleType = MultisampleType.None,
                SwapEffect      = SwapEffect.Discard,

                PresentFlags         = PresentFlags.None,
                PresentationInterval = PresentInterval.Default | PresentInterval.Immediate,
            };


            CreateFlags Flags = (CreateFlags.Multithreaded | CreateFlags.FpuPreserve | CreateFlags.HardwareVertexProcessing);

            //CreateFlags Flags = (CreateFlags.SoftwareVertexProcessing);

            device = new Device(direct3D9, adapterInfo.Adapter, DeviceType.Hardware, hWnd, Flags, presentParams);


            InitSurfaces();
        }
Пример #6
0
        public Allocator(Device dev, Direct3D D3D)
        {
            this.D3D    = D3D;
            adapterInfo = D3D.Adapters.DefaultAdapter;

            device = dev;

            creationParameters = device.CreationParameters;
        }
Пример #7
0
        public AdapterDisplay(AdapterInformation ai)
        {
            multistring.SetString(Language.ENGLISH, "Enabled", "Enabled");
            multistring.SetString(Language.ENGLISH, "Disabled", "Disabled");
            multistring.SetString(Language.ENGLISH, "Configure Device", "Configure Device");

            multistring.SetString(Language.DUTCH, "Enabled", "Ingeschakeld");
            multistring.SetString(Language.DUTCH, "Disabled", "Niet ingeschakeld");
            multistring.SetString(Language.DUTCH, "Configure Device", "Apparaat configureren");

            multistring.SetString(Language.HEBREW, "Enabled", "זמין");
            multistring.SetString(Language.HEBREW, "Disabled", "לא זמין");
            multistring.SetString(Language.HEBREW, "Configure Device", "קביעת תצורה של ההתקן");

            multistring.SetString(Language.PORTUGUESE, "Enabled", "Permitir");
            multistring.SetString(Language.PORTUGUESE, "Disabled", "Desativado");
            multistring.SetString(Language.PORTUGUESE, "Configure Device", "Configurar Dispositivo");

            multistring.SetString(Language.CHINESE, "Enabled", "启用");
            multistring.SetString(Language.CHINESE, "Disabled", "禁用");
            multistring.SetString(Language.CHINESE, "Configure Device", "配置设备");

            multistring.SetString(Language.GERMAN, "Enabled", "Ermöglichen");
            multistring.SetString(Language.GERMAN, "Disabled", "Deaktiviert");
            multistring.SetString(Language.GERMAN, "Configure Device", "Gerät konfigurieren");

            multistring.SetString(Language.RUSSIAN, "Enabled", "Включить");
            multistring.SetString(Language.RUSSIAN, "Disabled", "инвалид");
            multistring.SetString(Language.RUSSIAN, "Configure Device", "Настройка устройства");

            multistring.SetString(Language.SPANISH, "Enabled", "Permitir");
            multistring.SetString(Language.SPANISH, "Disabled", "Discapacitado");
            multistring.SetString(Language.SPANISH, "Configure Device", "Configurar Dispositivo");

            multistring.SetString(Language.JAPANESE, "Enabled", "有効");
            multistring.SetString(Language.JAPANESE, "Disabled", "有効ではないです。");
            multistring.SetString(Language.JAPANESE, "Configure Device", "デバイスを構成します。");

            multistring.SetString(Language.ITALIAN, "Enabled", "Abilitato");
            multistring.SetString(Language.ITALIAN, "Disabled", "Non abilitato");
            multistring.SetString(Language.ITALIAN, "Configure Device", "Configurare il dispositivo");

            multistring.SetString(Language.FRENCH, "Enabled", "Activé");
            multistring.SetString(Language.FRENCH, "Disabled", "Pas activé");
            multistring.SetString(Language.FRENCH, "Configure Device", "Configurer le périphérique");

            if (null != ai)
            {
                this.ai = ai;
                InitializeComponent();
                textBoxDetails.Text = ai.Summary;
                Program.trayIcon.adapters.MenuItems.Add(new MenuItem(ai.Name, this.buttonConfig_Click));
            }
            ThemeChanged();
        }
        //constructor
        public ControlSystem()
            : base()
        {
            string DeviceType = this.ControllerPrompt;

            if (DeviceType != "CP3" && DeviceType != "CP3N")
            {
                ErrorLog.Error("This program is for a CP3 or CP3N Control System");
                ErrorLog.Error("Terminating Execution");
                throw new NotSupportedException();
            }

            try
            {
                #region Onboard Devices
                //CP3 onboard devices
                //Slot-02.Slot2.1
                Ethernet_Information = AdapterInformation.GetAdapterInformation();
                //Slot-03.Slot-01
                Com01 = new TwoWaySerialDriver(this.ComPorts[1]);
                //Slot-03.Slot-02
                Com02 = new RS232OnlyTwoWaySerialDriver(this.ComPorts[2]);
                //Slot-03.Slot-03
                Com03 = new RS232OnlyTwoWaySerialDriver(this.ComPorts[3]);
                //Slot-04
                C2I_CP3_IO8 = IOs8AnalogInputCard.GetIO8AnalogInputCard(VersiPorts);
                //Slot-05
                C2I_CP3_RY8 = Relays8Card.GetRelay8Card(RelayPorts);
                //Slot-06 Port-01
                IR1 = this.IROutputPorts[1];
                //Slot-06 Port-02
                IR2 = this.IROutputPorts[2];
                //Slot-07
                C2I_CP3_SYSTEMMONITOR = System_Monitor.GetSystemMonitor();
                //Slot-07.Slot-01
                C2I_CP3_SYSTEMCONTROL = System_Control.GetSystemControl();
                //Slot-7.Slot-02
                C2I_CP3_SYSTEMINFORMATION = System_Information.GetSystemInformation();
                //Slot-10.Slot-01
                C2I_USB_HID = new USBPort(UsbHids[1]);
                #endregion

                //Single Port examples:
                //IOPort8 = new IOPort(VersiPorts[8]);
                //Relay8 = new SingleRelay(RelayPorts[8]);

                Thread.MaxNumberOfUserThreads = 20;
            }
            catch (Exception e)
            {
                ErrorLog.Error("Error in the constructor: {0}", e.Message);
            }
        }
Пример #9
0
        public DeviceContext(IntPtr handle, int backBufferWidth, int backBufferHeight, bool fullScreen, bool verticalSync)
        {
            PerformanceMonitor = new PerformanceMonitor();

            _formHandle            = handle;
            PresentationParameters = new PresentParameters()
            {
                BackBufferFormat       = Format.X8R8G8B8,
                BackBufferCount        = 1,
                BackBufferWidth        = backBufferWidth,
                BackBufferHeight       = backBufferHeight,
                MultiSampleType        = MultisampleType.None,
                SwapEffect             = SwapEffect.Discard,
                EnableAutoDepthStencil = true,
                AutoDepthStencilFormat = Format.D24S8,
                PresentFlags           = PresentFlags.DiscardDepthStencil,
                PresentationInterval   = PresentInterval.Immediate,
                Windowed           = !fullScreen,
                DeviceWindowHandle = _formHandle
            };

            try
            {
                Direct3D library = new Direct3D();

                if (library.AdapterCount == 0)
                {
                    throw new Exception("Unable to find an appropriate Direct3D adapter.");
                }

                AdapterDetails     adapterDetails     = library.GetAdapterIdentifier(0);
                AdapterInformation adapterInformation = library.Adapters[0];

                _device   = new Device(library, 0, DeviceType.Hardware, _formHandle, CreateFlags.HardwareVertexProcessing, PresentationParameters);
                _viewport = _device.Viewport;

                _capabilities = _device.Capabilities;

                Tracer.Info("Adapter: {0}", adapterDetails.DeviceName);
                Tracer.Info("Driver: {0}, v{1}", adapterDetails.Driver, adapterDetails.DriverVersion);
                Tracer.Info("Max Texture Size: {0}x{1}", _capabilities.MaxTextureWidth, _capabilities.MaxTextureHeight);
                Tracer.Info("Max Texture Repeat: {0}", _capabilities.MaxTextureRepeat);
                Tracer.Info("Max Texture Aspect Ratio: {0}", _capabilities.MaxTextureAspectRatio);
                Tracer.Info("Texture Size Options: {0}", _capabilities.TextureCaps);
            }
            catch (Exception e)
            {
                Tracer.Error(e);
                return;
            }

            _vertexDeclarationBuilder = new VertexDeclarationBuilder(this);
        }
Пример #10
0
        /// <summary>
        /// Creates or re-creates the DirectX device and the backbuffer. This is necessary in the initialization phase
        /// of the SkinEngine and after a parameter was changed which affects the DX device creation.
        /// </summary>
        internal static void DoReCreateDevice_MainThread()
        {
            try
            {
                // Note that only the thread which handles window messages is allowed to call CreateDevice and Reset
                // (see http://msdn.microsoft.com/en-us/library/windows/desktop/bb147224%28v=vs.85%29.aspx )
                ServiceRegistration.Get <ILogger>().Debug("GraphicsDevice: Initializing DirectX");
                MPDirect3D.Load();

                // Cleanup-part: Only necessary during re-initialization
                UIResourcesHelper.ReleaseUIResources();
                if (_backBuffer != null)
                {
                    _backBuffer.Dispose();
                }
                if (_device != null)
                {
                    _device.Dispose();
                }
                _device = _setup.SetupDirectX();
                // End cleanup part

                SetupRenderStrategies();
                SetupRenderPipelines();

                Capabilities deviceCapabilities = _device.Capabilities;
                _backBuffer = _device.GetRenderTarget(0);
                _device.MaximumFrameLatency = _setup.PresentParameters.BackBufferCount; // Enables the device to queue as many frames as we have backbuffers defined
                int ordinal = deviceCapabilities.AdapterOrdinal;
                AdapterInformation adapterInfo = MPDirect3D.Direct3D.Adapters[ordinal];
                DisplayMode        currentMode = adapterInfo.CurrentDisplayMode;
                AdaptTargetFrameRateToDisplayMode(currentMode);
                LogScreenMode(currentMode);
                bool firstTimeInitialization = _dxCapabilities == null;
                _dxCapabilities = DxCapabilities.RequestCapabilities(deviceCapabilities, currentMode);
                if (firstTimeInitialization)
                {
                    if (!_dxCapabilities.SupportsShaders)
                    {
                        string text = String.Format("MediaPortal 2 needs a graphics card wich supports shader model 2.0\nYour card does NOT support this.\nMediaportal 2 will continue but migh run slow");
                        MessageBox.Show(text, "GraphicAdapter", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
                SetRenderState();
                UIResourcesHelper.ReallocUIResources();
            }
            catch (Exception ex)
            {
                ServiceRegistration.Get <ILogger>().Critical("GraphicsDevice: Failed to setup DirectX", ex);
                Environment.Exit(0);
            }
        }
Пример #11
0
        /// <summary>
        /// The create device.
        /// </summary>
        /// <param name="renderpanel">The renderpanel.</param>
        /// <remarks></remarks>
        public void CreateDevice(Control renderpanel)
        {
            PresentParameters presentParams = new PresentParameters();

            presentParams.Windowed = true; // We don't want to run fullscreen

            /*
             * presentParams.BackBufferCount = 1; //Number of backbuffers to create
             * presentParams.BackBufferFormat = Manager.Adapters.Default.CurrentDisplayMode.Format; //The current format of the display device
             * presentParams.BackBufferWidth = renderpanel.Width;
             * presentParams.BackBufferHeight = renderpanel.Height;
             */
            presentParams.SwapEffect             = SwapEffect.Discard; // Discard the frames
            presentParams.AutoDepthStencilFormat = DepthFormat.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;

            IEnumerator i = Manager.Adapters.GetEnumerator();

            while (i.MoveNext())
            {
                AdapterInformation ai = i.Current as AdapterInformation;

                int adapterOrdinal = ai.Adapter;

                Caps hardware = Manager.GetDeviceCaps(adapterOrdinal, DeviceType.Hardware);

                CreateFlags flags = CreateFlags.SoftwareVertexProcessing;

                if (hardware.DeviceCaps.SupportsHardwareTransformAndLight)
                {
                    flags = CreateFlags.HardwareVertexProcessing;

                    // if (hardware.MaxActiveLights > 0)
                    // this.lighting = true;
                    // flags |= CreateFlags.PureDevice;
                    // if (hardware.DeviceCaps.m
                }

                device = new Device(adapterOrdinal, hardware.DeviceType, renderpanel, flags, presentParams);

                // Create a device
                if (device != null)
                {
                    break;
                }
            }

            device.DeviceReset += OnResetDevice;
            this.pause          = false;
            OnResetDevice(device, null);
        }
Пример #12
0
			///<summary>Inverse of ToString(). String to DirectXDeviceFormat.</summary>
			public DirectXDeviceFormat(string directXFormat){
				if(directXFormat.IndexOf(';')<0){
					//Invalid format.
					return;
				}
				string[] settings=directXFormat.Split(new char[] {';'});
				adapter=Manager.Adapters[PIn.Int(settings[0])];
				deviceType=(DeviceType)Enum.Parse(typeof(DeviceType),settings[1]);
				createFlags=(CreateFlags)PIn.Int(settings[2]);
				depthStencilFormat=(DepthFormat)Enum.Parse(typeof(DepthFormat),settings[3]);
				backBufferFormat=(Format)Enum.Parse(typeof(Format),settings[4]);
				maxMultiSampleType=(MultiSampleType)Enum.Parse(typeof(MultiSampleType),settings[5]);
			}
Пример #13
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);
     }
 }
Пример #14
0
        public void ManagerAdaptersCount()
        {
            AdapterListCollection list = Manager.Adapters;

            if (list != null)
            {
                Assert.AreNotEqual(list.Count, 0);

                for (int i = 0; i < list.Count; i++)
                {
                    AdapterInformation info = list [i];
                    Assert.IsNotNull(info);
                }
            }
        }
Пример #15
0
        /// <summary>
        /// Resets the DirectX device. This will release all screens, other UI resources and our back buffer, reset the DX device and realloc
        /// all resources.
        /// </summary>
        public static bool Reset()
        {
            ServiceRegistration.Get <ILogger>().Warn("GraphicsDevice: Resetting DX device...");
            _screenManager.ExecuteWithTempReleasedResources(() => ExecuteInMainThread(() =>
            {
                // Note that the thread which created the device must call this (see http://msdn.microsoft.com/en-us/library/windows/desktop/bb174344%28v=vs.85%29.aspx ).
                // Note also that only the thread which handles window messages is allowed to call CreateDevice and Reset
                // (see http://msdn.microsoft.com/en-us/library/windows/desktop/bb147224%28v=vs.85%29.aspx )
                ServiceRegistration.Get <ILogger>().Debug("GraphicsDevice: Reset DirectX");
                UIResourcesHelper.ReleaseUIResources();

                if (ContentManager.Instance.TotalAllocationSize != 0)
                {
                    ServiceRegistration.Get <ILogger>().Warn("GraphicsDevice: ContentManager.TotalAllocationSize = {0}, should be 0!", ContentManager.Instance.TotalAllocationSize / (1024 * 1024));
                }

                if (_backBuffer != null)
                {
                    _backBuffer.Dispose();
                }
                _backBuffer = null;

                _setup.BuildPresentParamsFromSettings();
                PresentParameters parameters = _setup.PresentParameters;
                _device.ResetEx(ref parameters);
                _setup.PresentParameters = parameters;

                SetupRenderStrategies();
                SetupRenderPipelines();

                Capabilities deviceCapabilities = _device.Capabilities;
                int ordinal = deviceCapabilities.AdapterOrdinal;
                AdapterInformation adapterInfo = MPDirect3D.Direct3D.Adapters[ordinal];
                DisplayMode currentMode        = adapterInfo.CurrentDisplayMode;
                AdaptTargetFrameRateToDisplayMode(currentMode);
                ServiceRegistration.Get <ILogger>().Debug("GraphicsDevice: DirectX reset {0}x{1} format: {2} {3} Hz", Width, Height,
                                                          currentMode.Format, TargetFrameRate);
                _backBuffer = _device.GetRenderTarget(0);
                _device.MaximumFrameLatency = _setup.PresentParameters.BackBufferCount; // Enables the device to queue as many frames as we have backbuffers defined
                _dxCapabilities             = DxCapabilities.RequestCapabilities(deviceCapabilities, currentMode);

                ScreenRefreshWorkaround();

                UIResourcesHelper.ReallocUIResources();
            }));
            ServiceRegistration.Get <ILogger>().Warn("GraphicsDevice: Device successfully reset");
            return(true);
        }
Пример #16
0
        /// <summary>
        /// Check if the Multisample Settings are Ok
        /// </summary>
        /// <param name="depthFmt"></param>
        /// <param name="backbufferFmt"></param>
        /// <param name="multisampleType"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public static bool IsDeviceMultiSampleOK(MultiSampleType multisampleType, DepthFormat depthFmt, Format backbufferFmt, out int result, out int qualityLevels)
        {
            AdapterInformation ai = Manager.Adapters.Default;

            // Verify that the render target surface supports the given multisample type
            if ((backbufferFmt == Format.Unknown) || (Manager.CheckDeviceMultiSampleType(ai.Adapter, DeviceType.Hardware, backbufferFmt, false, multisampleType, out result, out qualityLevels)))
            {
                // Verify that the depth stencil surface supports the given multisample type
                if (Manager.CheckDeviceMultiSampleType(ai.Adapter, DeviceType.Hardware, (Format)depthFmt, false, multisampleType, out result, out qualityLevels))
                {
                    return(true);                       // if both calls succeed
                }
            }

            return(false);              // if either call fails.  NOTE: HRESULT passed back in result
        }
        public void InitDevice()
        {
            AdapterInformation adapterInfo = Manager.Adapters[0];

            presentParams.BackBufferCount        = 1;
            presentParams.BackBufferFormat       = adapterInfo.CurrentDisplayMode.Format;
            presentParams.BackBufferWidth        = this.Width;
            presentParams.BackBufferHeight       = this.Height;
            presentParams.SwapEffect             = SwapEffect.Discard;
            presentParams.AutoDepthStencilFormat = DepthFormat.D24S8;
            presentParams.EnableAutoDepthStencil = true;
            presentParams.Windowed = true;

            device = new Device(0, DeviceType.Hardware, this.Handle, CreateFlags.SoftwareVertexProcessing, presentParams);
            device.DeviceResizing += new System.ComponentModel.CancelEventHandler(OnResize);
            initFailure            = false;
        }
Пример #18
0
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox2.SelectedItem == null)
            {
                return;
            }

            var newAdapter = Utils.Reflection.GetProperty <AdapterInformation>(comboBox2.SelectedItem, "Tag");

            if (SelectedAdapter.Adapter == newAdapter.Adapter)
            {
                return;
            }

            SelectedAdapter = newAdapter;
            AdapterChanged();
        }
Пример #19
0
        public static void Main(string[] args)
        {
            AdapterInformation info = new AdapterInformation("Aaron's DAAP Share", "");
            //service.RegType = "_hap._tcp";
            //service.ReplyDomain = "local.";
            //service.Port = 3689;

            ServiceAnnouncement service = new ServiceAnnouncement(info, null);

            // TxtRecords are optional
            //TxtRecord txt_record = new TxtRecord();
            //txt_record.Add("Password", "false");
            //service.TxtRecord = txt_record;

            //service.Register();

            BuildWebHost(args).Run();
        }
Пример #20
0
        public void ManagerAdapters()
        {
            AdapterListCollection list = Manager.Adapters;

            if (list != null)
            {
                IEnumerator e = list.GetEnumerator();
                Assert.IsNotNull(e);
                while (e.MoveNext())
                {
                    try {
                        AdapterInformation info = e.Current as AdapterInformation;
                        Assert.IsNotNull(info);
                    } catch {
                        //TODO: Implement e.Current
                    }
                }
            }
        }
Пример #21
0
        private void CreateDevice()
        {
            adapterInfo = Manager.Adapters.Default;

            presentParam                  = new PresentParameters();
            presentParam.Windowed         = true;
            presentParam.PresentFlag      = PresentFlag.Video;
            presentParam.SwapEffect       = SwapEffect.Copy;
            presentParam.BackBufferFormat = adapterInfo.CurrentDisplayMode.Format;

            device = new Device(
                0,
                DeviceType.Hardware,
                parentControl,
                CreateFlags.SoftwareVertexProcessing | CreateFlags.MultiThreaded,
                presentParam
                );

            renderTarget = device.GetRenderTarget(0);
        }
Пример #22
0
        } // mostrar().fim

        // verificarDispositivo() Verifica possibilidade de configuração
        // do dispositivo
        private static bool verificarDispositivo(Format video_formato,
                                                 Format backbuffer_formato, out int erro_info)
        {
            // Resultado
            bool res = false;

            // Aplicação vai rodar com o sem janela(false)
            bool app_janelada = false;

            // Coleta informações do adaptador default
            AdapterInformation info = Manager.Adapters.Default;

            // Verifica se o dispositivo pode ser usado no adaptador default
            // com a superfície dada
            res = Manager.CheckDeviceType(info.Adapter, DeviceType.Hardware,
                                          video_formato, backbuffer_formato,
                                          app_janelada, out erro_info);

            // Além de res, HRESULT é passado de volta em erro_info
            return(res);
        } // verificarDispositivo().fim
Пример #23
0
        } // config_janela() fim

        // adaptador_exibirInfoGeral()
        // Exibe informações gerais e modo de vídeo do adaptador
        private static void adaptador_exibirInfoGeral()
        {
            // Obtém informações gerais do adaptador
            AdapterInformation placaVideo = Manager.Adapters[0];

            mostrar("Adaptador: " + placaVideo.Adapter.ToString());
            mostrar(placaVideo.Information.Description);
            mostrar(placaVideo.Information.DriverName);
            mostrar(placaVideo.Information.DriverVersion.ToString());


            mostrar("\n Modo de video atual: ");
            string info_modo_atual;
            // Acessa informação do modo de video corrente
            DisplayMode modo_atual = placaVideo.CurrentDisplayMode;

            // Formata a informação do modo de video e mostra-a
            info_modo_atual = string.Format("{0} x {1} - Formato:{2}\n",
                                            modo_atual.Width.ToString(),
                                            modo_atual.Height.ToString(),
                                            modo_atual.Format.ToString());
            mostrar(info_modo_atual);

            mostrar("\n Modos de video suportados: ");
            mostrar("--------------------------------------------------------");
            // Obtém informação dos outros modos de vídeos suportadores, formata
            // e exibe-a.
            DisplayModeEnumerator modos_video = placaVideo.SupportedDisplayModes;

            foreach (DisplayMode mdvideo in modos_video)
            {
                string info;
                info = string.Format("{0} x {1} -{2}",
                                     mdvideo.Width.ToString(),
                                     mdvideo.Width.ToString(),
                                     mdvideo.Format.ToString());
                mostrar(info);
            } //endfor each
        }     // adaptador_exibirInfoGeral().fim
Пример #24
0
        public static Bitmap CaptureRegionDirect3D(IntPtr handle, Rectangle region)
        {
            Device             device;
            IntPtr             intPtr         = handle;
            Bitmap             bitmap         = null;
            AdapterInformation defaultAdapter = Direct3DCapture._direct3D9.Adapters.DefaultAdapter;

            if (!Direct3DCapture._direct3DDeviceCache.ContainsKey(intPtr))
            {
                PresentParameters presentParameter = new PresentParameters()
                {
                    BackBufferFormat = defaultAdapter.CurrentDisplayMode.Format
                };
                Rectangle absoluteClientRect = LineageMTool.Spazzarama.ScreenCapture.NativeMethods.GetAbsoluteClientRect(intPtr);
                presentParameter.BackBufferHeight             = absoluteClientRect.Height;
                presentParameter.BackBufferWidth              = absoluteClientRect.Width;
                presentParameter.Multisample                  = MultisampleType.None;
                presentParameter.SwapEffect                   = SwapEffect.Discard;
                presentParameter.DeviceWindowHandle           = intPtr;
                presentParameter.PresentationInterval         = PresentInterval.Default;
                presentParameter.FullScreenRefreshRateInHertz = 0;
                device = new Device(Direct3DCapture._direct3D9, defaultAdapter.Adapter, DeviceType.Hardware, intPtr, CreateFlags.SoftwareVertexProcessing, new PresentParameters[] { presentParameter });
                Direct3DCapture._direct3DDeviceCache.Add(intPtr, device);
            }
            else
            {
                device = Direct3DCapture._direct3DDeviceCache[intPtr];
            }
            int         width = defaultAdapter.CurrentDisplayMode.Width;
            DisplayMode currentDisplayMode = defaultAdapter.CurrentDisplayMode;

            using (Surface surface = Surface.CreateOffscreenPlain(device, width, currentDisplayMode.Height, Format.A8R8G8B8, Pool.SystemMemory))
            {
                device.GetFrontBufferData(0, surface);
                bitmap = new Bitmap(Surface.ToStream(surface, ImageFileFormat.Bmp, new Rectangle(region.Left, region.Top, region.Width, region.Height)));
            }
            return(bitmap);
        }
Пример #25
0
        public Renderer(Control RenderScene)
        {
            //Presentation Parameters
            PresentParameters presentParams = new PresentParameters();

            presentParams.Windowed               = true;
            presentParams.SwapEffect             = SwapEffect.Discard;
            presentParams.AutoDepthStencilFormat = DepthFormat.D16;
            presentParams.EnableAutoDepthStencil = true;
            presentParams.PresentationInterval   = PresentInterval.One;

            //Lets create the render device but we need to get their caps
            IEnumerator i = Manager.Adapters.GetEnumerator();

            while (i.MoveNext())
            {
                AdapterInformation ai      = i.Current as AdapterInformation;
                int         adapterOrdinal = ai.Adapter;
                Caps        hardware       = Manager.GetDeviceCaps(adapterOrdinal, DeviceType.Hardware);
                CreateFlags flags          = CreateFlags.SoftwareVertexProcessing;

                if (hardware.DeviceCaps.SupportsHardwareTransformAndLight)
                {
                    flags = CreateFlags.HardwareVertexProcessing;
                }

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

            //For device reset we have to set some settings
            device.DeviceReset += new System.EventHandler(OnResetDevice);
            OnResetDevice(device, null);
        }
Пример #26
0
        static public void Start(AdapterInformation AdapterInfo)
        {
            _AdapterInformation = AdapterInfo;


            _AdapterInformation.CIP_Port_F_Changed             += value => CrestronConsole.PrintLine("CIP_Port_F_Changed  :{0}", value);
            _AdapterInformation.CTP_Port_F_Changed             += value => CrestronConsole.PrintLine("CTP_Port_F_Changed  :{0}", value);
            _AdapterInformation.CurrentDefaultRouter_F_Changed += value => CrestronConsole.PrintLine("CurrentDefaultRouter_F_Changed  :{0}", value);
            _AdapterInformation.CurrentDHCP_State_F_Changed    += value => CrestronConsole.PrintLine("CurrentDHCP_State_F_Changed  :{0}", value);
            _AdapterInformation.CurrentIPAddress_F_Changed     += value => CrestronConsole.PrintLine("CurrentIPAddress_F_Changed  :{0}", value);
            _AdapterInformation.CurrentNetMask_F_Changed       += value => CrestronConsole.PrintLine("CurrentNetMask_F_Changed  :{0}", value);
            _AdapterInformation.DNS_Server_1_F_Changed         += value => CrestronConsole.PrintLine("DNS_Server_1_F_Changed  :{0}", value);
            _AdapterInformation.DNS_Server_2_F_Changed         += value => CrestronConsole.PrintLine("DNS_Server_2_F_Changed  :{0}", value);
            _AdapterInformation.DNS_Server_3_F_Changed         += value => CrestronConsole.PrintLine("DNS_Server_3_F_Changed  :{0}", value);
            _AdapterInformation.DomainName_F_Changed           += value => CrestronConsole.PrintLine("DomainName_F_Changed  :{0}", value);
            _AdapterInformation.EthernetStatus_F_Changed       += value => CrestronConsole.PrintLine("EthernetStatus_F_Changed  :{0}", value);
            _AdapterInformation.HostName_F_Changed             += value => CrestronConsole.PrintLine("HostName_F_Changed  :{0}", value);
            _AdapterInformation.LinkStatus_F_Changed           += value => CrestronConsole.PrintLine("LinkStatus_F_Changed  :{0}", value);
            _AdapterInformation.MAC_Address_F_Changed          += value => CrestronConsole.PrintLine("MAC_Address_F_Changed  :{0}", value);
            _AdapterInformation.SecureCIP_Port_Changed         += value => CrestronConsole.PrintLine("SecureCIP_Port_Changed  :{0}", value);
            _AdapterInformation.SecureCTP_Port_F_Changed       += value => CrestronConsole.PrintLine("SecureCTP_Port_F_Changed  :{0}", value);
            _AdapterInformation.SecureWebPort_F_Changed        += value => CrestronConsole.PrintLine("SecureWebPort_F_Changed  :{0}", value);
            _AdapterInformation.SSL_CA_On_F_Changed            += value => CrestronConsole.PrintLine("SSL_CA_On_F_Changed  :{0}", value);
            _AdapterInformation.SSL_CertificateType_F_Changed  += value => CrestronConsole.PrintLine("SSL_CertificateType_F_Changed  :{0}", value);
            _AdapterInformation.SSL_Off_F_Changed             += value => CrestronConsole.PrintLine("SSL_Off_F_Changed  :{0}", value);
            _AdapterInformation.SSL_SelfOn_F_Changed          += value => CrestronConsole.PrintLine("SSL_SelfOn_F_Changed  :{0}", value);
            _AdapterInformation.StartupDHCP_State_F_Changed   += value => CrestronConsole.PrintLine("StartupDHCP_State_F_Changed :{0}", value);
            _AdapterInformation.StaticDefaultRouter_F_Changed += value => CrestronConsole.PrintLine("StaticDefaultRouter_F_Changed  :{0}", value);
            _AdapterInformation.StaticIPAddress_F_Changed     += value => CrestronConsole.PrintLine("StaticIPAddress_F_Changed  :{0}", value);
            _AdapterInformation.StaticNetMask_F_Changed       += value => CrestronConsole.PrintLine("StaticNetMask_F_Changed  :{0}", value);
            _AdapterInformation.WebPort_F_Changed             += value => CrestronConsole.PrintLine("WebPort_F_Changed  :{0}", value);
            _AdapterInformation.Webserver_Status_F_Changed    += value => CrestronConsole.PrintLine("Webserver_Status_F_Changed  :{0}", value);


            CrestronConsole.AddNewConsoleCommand(EthernetInfo, "TEthernetInfo", "Show all Etherner Properties", ConsoleAccessLevelEnum.AccessOperator);
            CrestronConsole.AddNewConsoleCommand(Retrigger, "TEtherInfoRetrig", "Retrigger Ethernet Info", ConsoleAccessLevelEnum.AccessOperator);
        }
Пример #27
0
        public bool InitializeGraphics()
        {
            try
            {
                AdapterInformation ai = Manager.Adapters.Default;
                Caps caps             = Manager.GetDeviceCaps(ai.Adapter, DeviceType.Hardware);
                if (!caps.TextureCaps.SupportsProjected)
                {
                    MessageBox.Show("Erro: Graphics adaptor does not support projected textures!");
                }

                Cursor.Hide();
                presentParams.Windowed               = !doFullscreen;
                presentParams.SwapEffect             = SwapEffect.Discard;                                                           // Discard the frames
                presentParams.EnableAutoDepthStencil = true;                                                                         // Turn on a Depth stencil
                presentParams.AutoDepthStencilFormat = DepthFormat.D16;                                                              // And the stencil format

                presentParams.BackBufferWidth      = m_dwWidth;                                                                      //screen width
                presentParams.BackBufferHeight     = m_dwHeight;                                                                     //screen height
                presentParams.BackBufferFormat     = Format.R5G6B5;                                                                  //color depth
                presentParams.MultiSample          = MultiSampleType.None;                                                           //anti-aliasing
                presentParams.PresentationInterval = PresentInterval.Immediate;                                                      //don't wait... draw right away

                device              = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams); //Create a device
                device.DeviceReset += new System.EventHandler(this.OnResetDevice);
                this.OnCreateDevice(device, null);
                this.OnResetDevice(device, null);

                return(true);
            }
            catch (DirectXException)
            {
                // Catch any errors and return a failure
                return(false);
            }
        }
        public DirectShowAllocator(Device dev, int movieID, string tname)
        {
            ID = movieID;
            textureName = tname;
            adapterInfo = D3D.Manager.Adapters.Default;

            device = dev;

            creationParameters = device.CreationParameters;
        }
Пример #29
0
        public bool InitDirectX(int width, int height)
        {
            currentParams = new PresentParameters();
            AdapterInformation adapterInfo = direct3D9.Adapters.DefaultAdapter;

            currentParams.Windowed = true;//!fullScreenMode;// true;
            //currentParams.BackBufferFormat = Format.A4R4G4B4;
            currentParams.BackBufferFormat = adapterInfo.CurrentDisplayMode.Format;
            currentParams.BackBufferCount  = 1;
            if (fullScreenMode)
            {
                currentParams.BackBufferWidth  = displayWidth;
                currentParams.BackBufferHeight = displayHeight;
            }
            else
            {
                currentParams.BackBufferHeight = height;         // BackBufferHeight, set to  the Window's height.
                currentParams.BackBufferWidth  = width;          // BackBufferWidth, set to  the Window's width.
            }

            currentParams.Multisample          = MultisampleType.None;
            currentParams.SwapEffect           = SwapEffect.Discard;
            currentParams.PresentFlags         = PresentFlags.None;
            currentParams.PresentationInterval = PresentInterval.Immediate;

            try
            {
                dxDevice = new Device(direct3D9, adapterInfo.Adapter, DeviceType.Hardware, this.Handle, CreateFlags.HardwareVertexProcessing, currentParams);
            }
            catch (Direct3D9Exception)
            {
                try
                {
                    dxDevice = new Device(direct3D9, adapterInfo.Adapter, DeviceType.Hardware, this.Handle, CreateFlags.SoftwareVertexProcessing, currentParams);
                }
                catch
                {
                    directXAvailable = false;
                    return(false);
                }
            }

            sprite          = new Sprite(dxDevice);
            interlaceSprite = new Sprite(dxDevice);

            SetSpeccyScreenSize(ziggyWin.zx.GetTotalScreenWidth(), ziggyWin.zx.GetTotalScreenHeight());

            float scaleX = ((float)displayWidth / (float)(ScreenWidth));
            float scaleY = ((float)displayHeight / (float)(ScreenHeight));

            if (scaleX < 1.0f)
            {
                scaleX = 1.0f;
            }

            if (scaleY < 1.0f)
            {
                scaleY = 1.0f;
            }
            SlimDX.Matrix scaling = SlimDX.Matrix.Scaling(scaleX, scaleY, 0);
            sprite.Transform = scaling;

            directXAvailable = true;
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                ZeroWin.Properties.Resources.scanlines2.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                stream.Position   = 0;
                interlaceOverlay2 = SlimDX.Direct3D9.Texture.FromStream(dxDevice, stream);
            }
            //interlaceOverlay2 = SlimDX.Direct3D9.Texture.FromFile(dxDevice, Application.StartupPath + @"\images\scanlines2.png");
            return(true);
        }
Пример #30
0
        public bool InitDirectX(int width, int height, bool is16bit = false)
        {
            isSuspended = true;
            DestroyDX();

            displayRect   = new Rectangle(0, 0, width, height);
            displayWidth  = width;
            displayHeight = height;

            AdapterInformation adapterInfo = Manager.Adapters.Default;

            ziggyWin.logger.Log("Setting up render parameters...");
            currentParams = new PresentParameters();
            currentParams.BackBufferCount      = 2;
            currentParams.BackBufferWidth      = width;
            currentParams.BackBufferHeight     = height;
            currentParams.SwapEffect           = SwapEffect.Discard;
            currentParams.PresentFlag          = PresentFlag.None;
            currentParams.PresentationInterval = (enableVsync ? PresentInterval.One : PresentInterval.Immediate);
            currentParams.Windowed             = !fullScreenMode;// true;

            Format currentFormat = Manager.Adapters[0].CurrentDisplayMode.Format;
            bool   formatCheck   = Manager.CheckDeviceType(0,
                                                           DeviceType.Hardware,
                                                           currentFormat,
                                                           currentFormat,
                                                           false);

            if (!formatCheck)
            {
                MessageBox.Show("Invalid format", "dx error", MessageBoxButtons.OK);
            }

            if (fullScreenMode)
            {
                currentParams.DeviceWindow     = this.Parent;
                currentParams.BackBufferFormat = currentFormat;//(is16bit ? Format.R5G6B5 : Format.X8B8G8R8);
            }
            else
            {
                currentParams.DeviceWindow     = this;
                currentParams.BackBufferFormat = adapterInfo.CurrentDisplayMode.Format;
            }

            try {
                ziggyWin.logger.Log("Initializing directX device...");
                dxDevice = new Device(0, DeviceType.Hardware, this, CreateFlags.HardwareVertexProcessing, currentParams);
            } catch (Microsoft.DirectX.DirectXException dx) {
                MessageBox.Show(dx.ErrorString, "DX error", MessageBoxButtons.OK);
                try {
                    dxDevice = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, currentParams);
                } catch (Microsoft.DirectX.DirectXException dx2) {
                    MessageBox.Show(dx2.ErrorString, "DX error", MessageBoxButtons.OK);
                    directXAvailable = false;
                    return(false);
                }
            }

            //sprite = new Sprite(dxDevice);
            //interlaceSprite = new Sprite(dxDevice);
            SetSpeccyScreenSize(ziggyWin.zx.GetTotalScreenWidth(), ziggyWin.zx.GetTotalScreenHeight());

            float scaleX = ((float)displayWidth / (float)(ScreenWidth));
            float scaleY = ((float)displayHeight / (float)(ScreenHeight));

            //Maintain 4:3 aspect ration when full screen
            if (EnableFullScreen && ziggyWin.config.MaintainAspectRatioInFullScreen)
            {
                if (displayHeight < displayWidth)
                {
                    float aspectXScale = 0.75f; // (displayHeight * 4.0f) / (displayWidth * 3.0f);
                    scaleX = (scaleX * aspectXScale);
                    int newWidth = (int)(displayWidth * aspectXScale);
                    //displayRect = new Rectangle(0, 0, newWidth, displayHeight);
                    spritePos = new Vector3((((displayWidth - newWidth)) / (scaleX * 2.0f)), 0, 0);
                }
                else //Not tested!!!
                {
                    float aspectYScale = 1.33f;// (displayWidth * 3.0f) / (displayHeight * 4.0f);
                    scaleY = (scaleY * aspectYScale);
                    int newHeight = (int)(displayHeight * aspectYScale);
                    //displayRect = new Rectangle(0, 0, displayWidth, newHeight);
                }
            }
            else
            {
                spritePos = Vector3.Empty;
            }

            if (scaleX < 1.0f)
            {
                scaleX = 1.0f;
            }

            if (scaleY < 1.0f)
            {
                scaleY = 1.0f;
            }

            Matrix scaling = Matrix.Scaling(scaleX, scaleY, 1.0f);

            //sprite.Transform = scaling;
            System.Console.WriteLine("scaleX " + scaleX + "     scaleY " + scaleY);
            System.Console.WriteLine("pos " + spritePos);
            Texture displayTexture = new Texture(dxDevice, ScreenWidth, ScreenHeight, 1, Usage.None, currentParams.BackBufferFormat, Pool.Managed);

            displaySprite.Init(dxDevice, displayTexture, new Rectangle((int)spritePos.X, (int)spritePos.Y, ScreenWidth, ScreenHeight), scaling);

            using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) {
                ZeroWin.Properties.Resources.scanlines2.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                stream.Position = 0;
                Texture interlaceTexture = Texture.FromStream(dxDevice, stream, Usage.None, Pool.Managed);
                Surface interlaceSurface = interlaceTexture.GetSurfaceLevel(0);

                //Why 1.5f? Because it works very well.
                //Trying to use displayHeight/texture_width (which would seem logical) leads to strange banding on the screen.
                scanlineSprite.Init(dxDevice, interlaceTexture, new Rectangle((int)spritePos.X, (int)spritePos.Y, ScreenWidth, ScreenHeight), scaling, 1.0f, displayHeight / 1.5f);
            }

            System.Drawing.Font systemfont = new System.Drawing.Font(System.Drawing.SystemFonts.MessageBoxFont.FontFamily, 10f, FontStyle.Regular);
            isSuspended      = false;
            lastTime         = PrecisionTimer.TimeInMilliseconds();
            directXAvailable = true;
            return(true);
        }
Пример #31
0
        private void CreateDevice()
        {
            adapterInfo = Manager.Adapters.Default;

            presentParam = new PresentParameters();
            presentParam.Windowed = true;
            presentParam.PresentFlag = PresentFlag.Video;
            presentParam.SwapEffect = SwapEffect.Copy;
            presentParam.BackBufferFormat = adapterInfo.CurrentDisplayMode.Format;

            device = new Device(
                0,
                DeviceType.Hardware,
                parentControl,
                CreateFlags.SoftwareVertexProcessing | CreateFlags.MultiThreaded,
                presentParam
                );

            renderTarget = device.GetRenderTarget(0);
        }
Пример #32
0
        //public bool IsVMR9Connected

        #endregion

        #region public members

        /// <summary>
        /// Add VMR9 filter to graph and configure it
        /// </summary>
        /// <param name="graphBuilder"></param>
        public bool AddVMR9(IGraphBuilder graphBuilder)
        {
            if (!_useVmr9)
            {
                Log.Debug("VMR9: addvmr9 - vmr9 is deactivated");
                return(false);
            }
            if (_isVmr9Initialized)
            {
                Log.Debug("VMR9: addvmr9: vmr9 has already been initialized");
                return(false);
            }

            bool _useEvr = GUIGraphicsContext.IsEvr;

            if (_instanceCounter != 0)
            {
                Log.Error("VMR9: Multiple instances of VMR9 running!!!");
                throw new Exception("VMR9Helper: Multiple instances of VMR9 running!!!");
            }

            HResult            hr;
            IntPtr             hMonitor;
            AdapterInformation ai = GUIGraphicsContext.currentFullscreenAdapterInfo;

            hMonitor = Manager.GetAdapterMonitor(ai.Adapter);
            IntPtr upDevice = DirectShowUtil.GetUnmanagedDevice(GUIGraphicsContext.DX9Device);

            _scene = new PlaneScene(this);
            _scene.Init();

            if (_useEvr)
            {
                EvrInit(_scene, (uint)upDevice.ToInt32(), ref _vmr9Filter, (uint)hMonitor.ToInt32());
                hr = new HResult(graphBuilder.AddFilter(_vmr9Filter, "Enhanced Video Renderer"));
                Log.Info("VMR9: added EVR Renderer to graph");
            }
            else
            {
                _vmr9Filter = (IBaseFilter) new VideoMixingRenderer9();
                Log.Info("VMR9: added Video Mixing Renderer 9 to graph");

                Vmr9Init(_scene, (uint)upDevice.ToInt32(), _vmr9Filter, (uint)hMonitor.ToInt32());
                hr = new HResult(graphBuilder.AddFilter(_vmr9Filter, "Video Mixing Renderer 9"));
            }

            if (_vmr9Filter == null)
            {
                Error.SetError("Unable to play movie", "Renderer could not be added");
                Log.Error("VMR9: Renderer not installed / cannot be used!");
                return(false);
            }

            if (hr != 0)
            {
                if (_useEvr)
                {
                    EvrDeinit();
                }
                else
                {
                    Vmr9Deinit();
                }
                _scene.Stop();
                _scene.Deinit();
                _scene = null;

                DirectShowUtil.ReleaseComObject(_vmr9Filter);
                _vmr9Filter = null;
                Error.SetError("Unable to play movie", "Unable to initialize Renderer");
                Log.Error("VMR9: Failed to add Renderer to filter graph");
                return(false);
            }

            _qualityInterface         = _vmr9Filter as IQualProp;
            _vmr9MixerBitmapInterface = _vmr9Filter as IVMRMixerBitmap9;
            _graphBuilderInterface    = graphBuilder;
            _instanceCounter++;
            _isVmr9Initialized = true;
            if (!_useEvr)
            {
                SetDeinterlacePrefs();

                IVMRMixerControl9 mixer = _vmr9Filter as IVMRMixerControl9;
                if (mixer != null)
                {
                    VMR9MixerPrefs dwPrefs;
                    mixer.GetMixingPrefs(out dwPrefs);
                    dwPrefs &= ~VMR9MixerPrefs.RenderTargetMask;

                    dwPrefs |= VMR9MixerPrefs.RenderTargetYUV;
                    // YUV saves graphics bandwith  http://msdn2.microsoft.com/en-us/library/ms788177(VS.85).aspx
                    hr.Set(mixer.SetMixingPrefs(dwPrefs));
                    Log.Debug("VMR9: Enabled YUV mixing - " + hr.ToDXString());

                    using (Settings xmlreader = new MPSettings())
                    {
                        //Enable nonsquaremixing
                        if (xmlreader.GetValueAsBool("general", "nonsquare", true))
                        {
                            mixer.GetMixingPrefs(out dwPrefs);
                            dwPrefs |= VMR9MixerPrefs.NonSquareMixing;
                            hr.Set(mixer.SetMixingPrefs(dwPrefs));
                            Log.Debug("VRM9: Turning on nonsquare mixing - " + hr.ToDXString());
                            hr.Set(mixer.SetMixingPrefs(dwPrefs));
                        }

                        // Enable DecimateMask - this will effectively use only half of the input width & length
                        if (xmlreader.GetValueAsBool("general", "dx9decimatemask", false))
                        {
                            mixer.GetMixingPrefs(out dwPrefs);
                            dwPrefs &= ~VMR9MixerPrefs.DecimateMask;
                            dwPrefs |= VMR9MixerPrefs.DecimateOutput;
                            hr.Set(mixer.SetMixingPrefs(dwPrefs));
                            Log.Debug("VRM9: Enable decimatemask - " + hr.ToDXString());
                            hr.Set(mixer.SetMixingPrefs(dwPrefs));
                        }

                        // see  D3DTEXTUREFILTERTYPE Enumerated Type documents for further information
                        // MixerPref9_PointFiltering
                        // MixerPref9_BiLinearFiltering
                        // MixerPref9_AnisotropicFiltering
                        // MixerPref9_PyramidalQuadFiltering
                        // MixerPref9_GaussianQuadFiltering

                        mixer.SetMixingPrefs(dwPrefs);
                        mixer.GetMixingPrefs(out dwPrefs);
                        dwPrefs &= ~VMR9MixerPrefs.FilteringMask;
                        string filtermode9 = xmlreader.GetValueAsString("general", "dx9filteringmode", "Gaussian Quad Filtering");
                        if (filtermode9 == "Point Filtering")
                        {
                            dwPrefs |= VMR9MixerPrefs.PointFiltering;
                        }
                        else if (filtermode9 == "Bilinear Filtering")
                        {
                            dwPrefs |= VMR9MixerPrefs.BiLinearFiltering;
                        }
                        else if (filtermode9 == "Anisotropic Filtering")
                        {
                            dwPrefs |= VMR9MixerPrefs.AnisotropicFiltering;
                        }
                        else if (filtermode9 == "Pyrimidal Quad Filtering")
                        {
                            dwPrefs |= VMR9MixerPrefs.PyramidalQuadFiltering;
                        }
                        else
                        {
                            dwPrefs |= VMR9MixerPrefs.GaussianQuadFiltering;
                        }

                        hr.Set(mixer.SetMixingPrefs(dwPrefs));
                        Log.Debug("VRM9: Set filter mode - " + filtermode9 + " " + hr.ToDXString());
                    }
                }
            }
            _threadId = Thread.CurrentThread.ManagedThreadId;
            GUIGraphicsContext.Vmr9Active = true;
            g_vmr9 = this;
            Log.Debug("VMR9: Renderer successfully added");
            return(true);
        }
Пример #33
0
        private void CreateDevice()
        {
            if (this._device != null)
            {
                this._device.Dispose();
            }

            PresentParameters  presentParams = new PresentParameters();
            AdapterInformation adapter       = Manager.Adapters.Default;

            DisplayMode dm;

            if (m_bFullscreen)
            {
                //TODO: DK kolla caps upplösning/refreshrate
//				foreach (Microsoft.DirectX.Direct3D.DisplayMode dispMode in Manager.Adapters.Default.SupportedDisplayModes)
//					dispMode.
                dm        = new DisplayMode();
                dm.Width  = 1024;                //800;
                dm.Height = 768;                 //600;
                dm.Format = Format.X8R8G8B8;
            }
            else
            {
                dm = adapter.CurrentDisplayMode;
            }

            presentParams.SwapEffect       = SwapEffect.Discard; // Discard; Copy
            presentParams.BackBufferFormat = Format.Unknown;
            if (m_bFullscreen)
            {
                presentParams.BackBufferFormat          = dm.Format;
                presentParams.BackBufferWidth           = dm.Width;
                presentParams.BackBufferHeight          = dm.Height;
                presentParams.FullScreenRefreshRateInHz = 60;
                presentParams.PresentFlag          = PresentFlag.LockableBackBuffer;
                presentParams.BackBufferCount      = 1;
                presentParams.PresentationInterval = PresentInterval.One;                 //Immediate;
            }
            presentParams.AutoDepthStencilFormat = DepthFormat.D16;
            presentParams.EnableAutoDepthStencil = true;
            presentParams.Windowed = !m_bFullscreen;

            //http://www.dotnetforums.net/t73717.html
            //http://www.dotnetforums.net/showthread.php?t=92593

            // Store the default adapter
            int         adapterOrdinal = Manager.Adapters.Default.Adapter;
            CreateFlags flags;

            flags = CreateFlags.SoftwareVertexProcessing;
            // Check to see if we can use a pure hardware device
            Caps caps = Manager.GetDeviceCaps(adapterOrdinal, DeviceType.Hardware);

            if (caps.DeviceCaps.SupportsHardwareTransformAndLight)
            {
                flags = CreateFlags.HardwareVertexProcessing;
            }

            // Do we support a pure device?
            if (caps.DeviceCaps.SupportsPureDevice)
            {
                flags |= CreateFlags.PureDevice;
            }

            this._device = new Device(0, DeviceType.Hardware, this._renderControl, flags, presentParams);

            //TODO: for some unknown reason, this suddenly stopped working on my new Acer laptop... Something to do with switching to DirectX debug runtime? Worked a while after that though.
            try
            {
                this._device.SamplerState[0].MagFilter = TextureFilter.None; //Linear;
                this._device.SamplerState[0].MinFilter = TextureFilter.None; //.Linear;
                this._device.SamplerState[0].MipFilter = TextureFilter.None;
            }
            catch { }

            this._device.DeviceReset += new System.EventHandler(this.OnResetDevice);
            this.OnResetDevice(this._device, null);

            this.SetUpViews();

            this._defaultRenderTarget = this._device.GetRenderTarget(0);
        }
Пример #34
0
        /// <summary>
        /// Setup the Direct3D Device
        /// </summary>
        /// <param name="thisForm"></param>
        //public static void SetupD3D(OpenSebJ.frmVideoRender thisForm)
        public static void SetupD3D(System.Windows.Forms.Form thisForm)
        {
            // Set the clientForm to the form initating the D3D interface
            clientForm = thisForm;

            // Required so that we can get a pointer to the monitor that the DX graphics are being drawn to.
            adapterInfo = Manager.Adapters.Default;


            // From the Allocator code - not sure of the effect
            // TODO determine if required..
            //Device.IsUsingEventHandlers = false;

            // Setup DirectX device
            PresentParameters presentParams = new PresentParameters();

            // Always use windowed mode for debugging and fullscreen for the presentation.
            presentParams.Windowed = true;

            presentParams.PresentationInterval = PresentInterval.Default;
            presentParams.BackBufferFormat     = Format.X8R8G8B8;
            presentParams.BackBufferWidth      = clientForm.Width;
            presentParams.BackBufferHeight     = clientForm.Height;

            //Needs to specifically be set for full screen
            //presentParams.BackBufferWidth = 800;
            //presentParams.BackBufferHeight = 600;

            // Default to triple buffering for performance gain,
            // if we are low on video memory and use multisampling, 1 is ok too.
            presentParams.BackBufferCount = 2;

            // Discard back buffer when swapping, its faster
            presentParams.SwapEffect = SwapEffect.Discard;

            presentParams.MultiSample = MultiSampleType.None;

            presentParams.MultiSampleQuality = 0;


            // Picked off another example
            presentParams.PresentFlag = PresentFlag.Video;

            // Use a Z-Buffer with 32 bit if possible
            presentParams.EnableAutoDepthStencil = true;
            presentParams.AutoDepthStencilFormat = DepthFormat.D24X8;

            // For windowed, default to PresentInterval.Immediate which will
            // wait not for the vertical retrace period to prevent tearing,
            // but may introduce tearing. For full screen, default to
            // PresentInterval.Default which will wait for the vertical retrace
            // period to prevent tearing.
            presentParams.PresentationInterval = PresentInterval.Immediate;

            // Try setting up the device. There can be a few problems when going with full screen
            // using the event render - needs further investigation
            try
            {
                device = new Device(0, DeviceType.Hardware, clientForm, CreateFlags.HardwareVertexProcessing | CreateFlags.PureDevice, presentParams);
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.ToString());
            }


            //Setup the view matrix to look at the complete sceen
            device.Transform.View = Matrix.LookAtLH(
                new Vector3(0.0f, 0.0f, -4.0f),
                new Vector3(0.0f, 0.0f, 0.0f),
                new Vector3(0.0f, 1.0f, 0.0f));

            float aspectRatio = (float)clientForm.Width / (float)clientForm.Height;
            float fieldOfView = (float)Math.PI / 2.0f;
            float nearPlane   = 1.0f;
            float farPlane    = 100.0f;


            // Apply the view projection matrix to see everything
            device.Transform.Projection = Matrix.PerspectiveFovLH(fieldOfView, aspectRatio, nearPlane, farPlane);
        }
Пример #35
0
		private static bool IsDeviceMultiSampleOK(AdapterInformation adapter,DeviceType deviceType,DepthFormat depthFormat,
			Format backbufferFormat,MultiSampleType multisampleType,bool windowed) {
			int qualityLevels=0;
			int result=0;
			//Verify that the render target surface supports the given multisample type
			if(Manager.CheckDeviceMultiSampleType(adapter.Adapter,deviceType,backbufferFormat,windowed,multisampleType,out result,out qualityLevels)) {
				//Verify that the depth stencil surface supports the given multisample type
				if(Manager.CheckDeviceMultiSampleType(adapter.Adapter,deviceType,(Format)depthFormat,windowed,multisampleType,out result,out qualityLevels)) {
					return (result==((int)ResultCode.Success));
				}
			}
			return false;
		}