Exemplo n.º 1
0
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.Form.Load" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                // Set our default cursor.
                _currentCursor = Resources.hand_icon;

                // Create our input factory.
                _rawInput = new GorgonRawInput(this);

                // Ensure that we have the necessary input devices.
                // This enumeration method could be used to retrieve only a single specific mouse out of many.
                if (_rawInput.EnumerateMice().Count == 0)
                {
                    GorgonDialogs.ErrorBox(this, "There were no mice detected on this computer.  The application requires a mouse.");
                    GorgonApplication.Quit();
                }

                // This enumeration method could be used to retrieve only a single specific keyboard out of many.
                if (_rawInput.EnumerateKeyboards().Count == 0)
                {
                    GorgonDialogs.ErrorBox(this, "There were no keyboards detected on this computer.  The application requires a keyboard.");
                    GorgonApplication.Quit();
                }

                // Get our input devices.
                CreateMouse();
                CreateKeyboard();

                // When the display area changes size, update the spray effect
                // and limit the mouse.
                panelDisplay.Resize += PanelDisplay_Resize;

                // Set up our spray object.
                _spray  = new Spray(panelDisplay.ClientSize);
                _cursor = new MouseCursor(panelDisplay)
                {
                    Hotspot = new Point(-16, -3)
                };

                // Set up our idle method.
                GorgonApplication.IdleMethod = Idle;
            }
            catch (Exception ex)
            {
                // We do this here instead of just calling the dialog because this
                // function will send the exception to the Gorgon log file.
                ex.Catch(_ => GorgonDialogs.ErrorBox(this, _), GorgonApplication.Log);
                GorgonApplication.Quit();
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Function to initialize the application.
        /// </summary>
        private static async Task InitializeAsync(FormMain window)
        {
            try
            {
                GorgonExample.ResourceBaseDirectory   = new DirectoryInfo(Settings.Default.ResourceLocation);
                GorgonExample.PlugInLocationDirectory = new DirectoryInfo(Settings.Default.PlugInLocation);

                // Load our packed file system plug in.
                window.UpdateStatus("Loading plugins...");

                IGorgonPlugInService plugIns = await Task.Run(() =>
                {
                    _assemblyCache = new GorgonMefPlugInCache(GorgonApplication.Log);
                    _assemblyCache.LoadPlugInAssemblies(GorgonExample.GetPlugInPath().FullName, "Gorgon.FileSystem.GorPack.dll");
                    return(new GorgonMefPlugInService(_assemblyCache));
                });

                window.UpdateStatus("Initializing graphics...");

                // Retrieve the list of video adapters. We can do this on a background thread because there's no interaction between other threads and the
                // underlying D3D backend yet.
                IReadOnlyList <IGorgonVideoAdapterInfo> videoDevices = await Task.Run(() => GorgonGraphics.EnumerateAdapters(log: GorgonApplication.Log));

                if (videoDevices.Count == 0)
                {
                    throw new GorgonException(GorgonResult.CannotCreate,
                                              "Gorgon requires at least a Direct3D 11.4 capable video device.\nThere is no suitable device installed on the system.");
                }

                // Find the best video device.
                _graphics = new GorgonGraphics(videoDevices.OrderByDescending(item => item.FeatureSet).First());

                _screen = new GorgonSwapChain(_graphics,
                                              window,
                                              new GorgonSwapChainInfo("Gorgon2D Space Scene Example")
                {
                    Width  = Settings.Default.Resolution.Width,
                    Height = Settings.Default.Resolution.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });

                // Create a secondary render target for our scene. We use 16 bit floating point for the effect fidelity.
                // We'll lock our resolution to 1920x1080 (pretty common resolution for most people).
                _mainRtv = GorgonRenderTarget2DView.CreateRenderTarget(_graphics, new GorgonTexture2DInfo("Main RTV")
                {
                    Width   = (int)_baseResolution.X,
                    Height  = (int)_baseResolution.Y,
                    Format  = BufferFormat.R16G16B16A16_Float,
                    Binding = TextureBinding.ShaderResource
                });
                _mainSrv       = _mainRtv.GetShaderResourceView();
                _mainRtvAspect = _mainRtv.Width < _mainRtv.Height ? new DX.Vector2(1, (float)_mainRtv.Height / _mainRtv.Width) : new DX.Vector2((float)_mainRtv.Width / _mainRtv.Height, 1);

                // Initialize the renderer so that we are able to draw stuff.
                _renderer = new Gorgon2D(_graphics);

                // Set up our raw input.
                _input           = new GorgonRawInput(window, GorgonApplication.Log);
                _keyboard        = new GorgonRawKeyboard();
                _keyboard.KeyUp += Keyboard_KeyUp;
                _input.RegisterDevice(_keyboard);

                GorgonExample.LoadResources(_graphics);

                // Now for the fun stuff, load our asset resources. We can load this data by mounting a directory (which I did while developing), or use a packed file.
                //
                // The resource manager will hold all the data we need for the scene. Including 3D meshes, post processing effects, etc...
                _resources = new ResourceManagement(_renderer, plugIns);
                _resources.Load(Path.Combine(GorgonExample.GetResourcePath(@"FileSystems").FullName, "SpaceScene.gorPack"));

                window.UpdateStatus("Loading resources...");
                await _resources.LoadResourcesAsync();

                SetupScene();

                // Build up a font to use for rendering any GUI text.
                _helpFont = GorgonExample.Fonts.GetFont(new GorgonFontInfo("Segoe UI", 10.0f, FontHeightMode.Points, "Segoe UI 10pt")
                {
                    OutlineSize      = 2,
                    Characters       = (Resources.Instructions + "S:1234567890x").Distinct().ToArray(),
                    FontStyle        = FontStyle.Bold,
                    AntiAliasingMode = FontAntiAliasMode.AntiAlias,
                    OutlineColor1    = GorgonColor.Black,
                    OutlineColor2    = GorgonColor.Black
                });

                _textSprite = new GorgonTextSprite(_helpFont)
                {
                    Position = new DX.Vector2(0, 64),
                    DrawMode = TextDrawMode.OutlinedGlyphs,
                    Color    = GorgonColor.YellowPure
                };

                GorgonExample.ShowStatistics = true;

                // Set the idle here. We don't want to try and render until we're done loading.
                GorgonApplication.IdleMethod = Idle;
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.Form.Load"></see> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                GorgonExample.PlugInLocationDirectory = new DirectoryInfo(Settings.Default.PlugInLocation);

                // Load the assembly.
                _assemblyCache = new GorgonMefPlugInCache(GorgonApplication.Log);

                // Create the plugin service.
                IGorgonPlugInService plugInService = new GorgonMefPlugInService(_assemblyCache);

                // Create the factory to retrieve gaming device drivers.
                var factory = new GorgonGamingDeviceDriverFactory(plugInService);

                // Create the raw input interface.
                _input = new GorgonRawInput(this, GorgonApplication.Log);

                // Get available gaming device driver plug ins.
                _assemblyCache.LoadPlugInAssemblies(GorgonExample.GetPlugInPath().FullName, "Gorgon.Input.DirectInput.dll");
                _assemblyCache.LoadPlugInAssemblies(GorgonExample.GetPlugInPath().FullName, "Gorgon.Input.XInput.dll");

                _drivers = factory.LoadAllDrivers();

                _joystickList = new List <IGorgonGamingDevice>();

                // Get all gaming devices from the drivers.
                foreach (IGorgonGamingDeviceDriver driver in _drivers)
                {
                    IReadOnlyList <IGorgonGamingDeviceInfo> infoList = driver.EnumerateGamingDevices(true);

                    foreach (IGorgonGamingDeviceInfo info in infoList)
                    {
                        IGorgonGamingDevice device = driver.CreateGamingDevice(info);

                        // Turn off dead zones for this example.
                        foreach (GorgonGamingDeviceAxis axis in device.Axis)
                        {
                            axis.DeadZone = GorgonRange.Empty;
                        }

                        _joystickList.Add(device);
                    }
                }

                // Create mouse.
                _mouse = new GorgonRawMouse();

                // Create the graphics interface.
                ClientSize = Settings.Default.Resolution;

                IReadOnlyList <IGorgonVideoAdapterInfo> adapters = GorgonGraphics.EnumerateAdapters();
                _graphics = new GorgonGraphics(adapters[0], log: GorgonApplication.Log);
                _screen   = new GorgonSwapChain(_graphics, this, new GorgonSwapChainInfo("INeedYourInput Swapchain")
                {
                    Width  = Settings.Default.Resolution.Width,
                    Height = Settings.Default.Resolution.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });
                _graphics.SetRenderTarget(_screen.RenderTargetView);

                if (!Settings.Default.IsWindowed)
                {
                    _screen.EnterFullScreen();
                }

                // For the backup image. Used to make it as large as the monitor that we're on.
                var currentScreen = Screen.FromHandle(Handle);

                // Relocate the window to the center of the screen.
                Location = new Point(currentScreen.Bounds.Left + (currentScreen.WorkingArea.Width / 2) - (ClientSize.Width / 2),
                                     currentScreen.Bounds.Top + (currentScreen.WorkingArea.Height / 2) - (ClientSize.Height / 2));


                // Create the 2D renderer.
                _2D = new Gorgon2D(_graphics);

                // Create the text font.
                var fontFactory = new GorgonFontFactory(_graphics);
                _font = fontFactory.GetFont(new GorgonFontInfo("Arial", 9.0f, FontHeightMode.Points, "Arial 9pt")
                {
                    FontStyle        = FontStyle.Bold,
                    AntiAliasingMode = FontAntiAliasMode.AntiAlias
                });

                // Create text sprite.
                _messageSprite = new GorgonTextSprite(_font, "Using mouse and keyboard (Windows Forms).")
                {
                    Color = Color.Black
                };

                // Create a back buffer.
                _backBuffer = GorgonRenderTarget2DView.CreateRenderTarget(_graphics, new GorgonTexture2DInfo("Backbuffer storage")
                {
                    Width  = _screen.Width,
                    Height = _screen.Height,
                    Format = _screen.Format
                });
                _backBuffer.Clear(Color.White);
                _backBufferView = _backBuffer.GetShaderResourceView();

                // Clear our backup image to white to match our primary screen.
                using (IGorgonImage image = new GorgonImage(new GorgonImageInfo(ImageType.Image2D, _screen.Format)
                {
                    Width = _screen.Width,
                    Height = _screen.Height,
                    Format = _screen.Format
                }))
                {
                    image.Buffers[0].Fill(0xff);
                    _backupImage = image.ToTexture2D(_graphics,
                                                     new GorgonTexture2DLoadOptions
                    {
                        Binding = TextureBinding.None,
                        Usage   = ResourceUsage.Staging
                    });
                }

                // Set gorgon events.
                _screen.BeforeSwapChainResized += BeforeSwapChainResized;
                _screen.AfterSwapChainResized  += AfterSwapChainResized;

                // Enable the mouse.
                Cursor = Cursors.Cross;
                _mouse.MouseButtonDown += MouseInput;
                _mouse.MouseMove       += MouseInput;
                _mouse.MouseWheelMove  += (sender, args) =>
                {
                    _radius += args.WheelDelta.Sign();

                    if (_radius < 2.0f)
                    {
                        _radius = 2.0f;
                    }
                    if (_radius > 10.0f)
                    {
                        _radius = 10.0f;
                    }
                };

                // Set the mouse position.
                _mouse.Position = new Point(ClientSize.Width / 2, ClientSize.Height / 2);

                _noBlending = _blendBuilder.BlendState(GorgonBlendState.NoBlending)
                              .Build();
                _inverted = _blendBuilder.BlendState(GorgonBlendState.Inverted)
                            .Build();

                // Set up blending states for our pen.
                var blendStateBuilder = new GorgonBlendStateBuilder();
                _currentBlend = _drawModulatedBlend = _blendBuilder.BlendState(blendStateBuilder
                                                                               .ResetTo(GorgonBlendState.Default)
                                                                               .DestinationBlend(alpha: Blend.One)
                                                                               .Build())
                                                      .Build();

                _drawAdditiveBlend = _blendBuilder.BlendState(blendStateBuilder
                                                              .ResetTo(GorgonBlendState.Additive)
                                                              .DestinationBlend(alpha: Blend.One)
                                                              .Build())
                                     .Build();

                _drawNoBlend = _blendBuilder.BlendState(blendStateBuilder
                                                        .ResetTo(GorgonBlendState.NoBlending)
                                                        .DestinationBlend(alpha: Blend.One)
                                                        .Build())
                               .Build();

                GorgonApplication.IdleMethod = Gorgon_Idle;
            }
            catch (ReflectionTypeLoadException refEx)
            {
                string refErr = string.Join("\n", refEx.LoaderExceptions.Select(item => item.Message));
                GorgonDialogs.ErrorBox(this, refErr);
            }
            catch (Exception ex)
            {
                GorgonExample.HandleException(ex);
                GorgonApplication.Quit();
            }
        }