/// <summary> /// Function called to initialize the application. /// </summary> private void Initialize() { GorgonExample.ResourceBaseDirectory = new DirectoryInfo(Settings.Default.ResourceLocation); // Resize and center the screen. var screen = Screen.FromHandle(Handle); ClientSize = Settings.Default.Resolution; Location = new Point(screen.Bounds.Left + (screen.WorkingArea.Width / 2) - (ClientSize.Width / 2), screen.Bounds.Top + (screen.WorkingArea.Height / 2) - (ClientSize.Height / 2)); // Initialize our graphics. IReadOnlyList <IGorgonVideoAdapterInfo> videoAdapters = GorgonGraphics.EnumerateAdapters(log: GorgonApplication.Log); if (videoAdapters.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(videoAdapters.OrderByDescending(item => item.FeatureSet).First()); // Build our "screen". _screen = new GorgonSwapChain(_graphics, this, new GorgonSwapChainInfo { Width = ClientSize.Width, Height = ClientSize.Height, Format = BufferFormat.R8G8B8A8_UNorm }); if (!Settings.Default.IsWindowed) { // Go full screen by using borderless windowed mode. _screen.EnterFullScreen(); } // Build up our 2D renderer. _renderer = new Gorgon2D(_graphics); // Load in the logo texture from our resources. GorgonExample.LoadResources(_graphics); // Create fonts. _textFont = GorgonExample.Fonts.GetFont(new GorgonFontInfo("GiGi", 24.0f, FontHeightMode.Points, "GiGi_24pt") { AntiAliasingMode = FontAntiAliasMode.AntiAlias, TextureWidth = 512, TextureHeight = 256 }); // Use the form font for this one. _helpFont = GorgonExample.Fonts.GetFont(new GorgonFontInfo(Font.FontFamily.Name, Font.Size, Font.Unit == GraphicsUnit.Pixel ? FontHeightMode.Pixels : FontHeightMode.Points, "Form Font") { AntiAliasingMode = FontAntiAliasMode.AntiAlias, FontStyle = FontStyle.Bold }); // Create our file system and mount the resources. _fileSystem = new GorgonFileSystem(GorgonApplication.Log); _fileSystem.Mount(GorgonExample.GetResourcePath(@"FileSystems\FolderSystem").FullName); // In the previous versions of Gorgon, we used to load the image first, and then the sprites. // But in this version, we have an extension that will load the sprite textures for us. _sprites = new GorgonSprite[3]; // The sprites are in the v2 format. IEnumerable <IGorgonSpriteCodec> v2Codec = new[] { new GorgonV2SpriteCodec(_renderer) }; IEnumerable <IGorgonImageCodec> pngCodec = new[] { new GorgonCodecPng() }; _sprites[0] = _fileSystem.LoadSpriteFromFileSystem(_renderer, "/Sprites/base.gorSprite", spriteCodecs: v2Codec, imageCodecs: pngCodec); _sprites[1] = _fileSystem.LoadSpriteFromFileSystem(_renderer, "/Sprites/Mother.gorSprite", spriteCodecs: v2Codec, imageCodecs: pngCodec); _sprites[2] = _fileSystem.LoadSpriteFromFileSystem(_renderer, "/Sprites/Mother2c.gorSprite", spriteCodecs: v2Codec, imageCodecs: pngCodec); // This is how you would get the sprites in v2 of Gorgon: /*_spriteImage = _graphics.Textures.FromMemory<GorgonTexture2D>("0_HardVacuum", LoadFile("/Images/0_HardVacuum.png"), new GorgonCodecPNG()); * * // Get the sprites. * // The sprites in the file system are from version 1.0 of Gorgon. * // This version is backwards compatible and can load any version * // of the sprites produced by older versions of Gorgon. * _sprites = new GorgonSprite[3]; * _sprites[0] = _renderer.Renderables.FromMemory<GorgonSprite>("Base", LoadFile("/Sprites/base.gorSprite")); * _sprites[1] = _renderer.Renderables.FromMemory<GorgonSprite>("Mother", LoadFile("/Sprites/Mother.gorSprite")); * _sprites[2] = _renderer.Renderables.FromMemory<GorgonSprite>("Mother2c", LoadFile("/Sprites/Mother2c.gorSprite")); */ // Get poetry. _textPosition = new DX.Vector2(0, ClientSize.Height + _textFont.LineHeight); _poetry = new GorgonTextSprite(_textFont, Encoding.UTF8.GetString(LoadFile("/SomeText.txt"))) { Position = _textPosition, Color = Color.Black }; // Set up help text. _helpText = new GorgonTextSprite(_helpFont, "F1 - Show/hide this help text.\nS - Show frame statistics.\nESC - Exit.") { Color = Color.Blue, Position = new DX.Vector2(3, 3) }; // Unlike the old example, we'll blend to render targets, ping-ponging back and forth, for a much better quality image and smoother transition. _blurEffect = new Gorgon2DGaussBlurEffect(_renderer, 3) { BlurRenderTargetsSize = new DX.Size2((int)_sprites[2].Size.Width * 2, (int)_sprites[2].Size.Height * 2), PreserveAlpha = false }; _blurEffect.Precache(); _blurredTarget[0] = GorgonRenderTarget2DView.CreateRenderTarget(_graphics, new GorgonTexture2DInfo("Blurred RTV") { Width = _blurEffect.BlurRenderTargetsSize.Width, Height = _blurEffect.BlurRenderTargetsSize.Height, Binding = TextureBinding.ShaderResource, Format = BufferFormat.R8G8B8A8_UNorm, Usage = ResourceUsage.Default }); _blurredTarget[1] = GorgonRenderTarget2DView.CreateRenderTarget(_graphics, _blurredTarget[0]); _blurredImage[0] = _blurredTarget[0].GetShaderResourceView(); _blurredImage[1] = _blurredTarget[1].GetShaderResourceView(); GorgonApplication.IdleMethod = Idle; }
/// <summary> /// Handles the <see cref="E:KeyDown" /> event. /// </summary> /// <param name="e">The <see cref="KeyEventArgs" /> instance containing the event data.</param> protected override void OnKeyUp(KeyEventArgs e) { switch (e.KeyCode) { case Keys.Escape: Close(); // Close break; case Keys.F: if (_screen.IsWindowed) { _screen.EnterFullScreen(); } else { _screen.ExitFullScreen(); } break; case Keys.Down: _radius -= 1.0f; if (_radius < 2.0f) { _radius = 2.0f; } break; case Keys.Up: _radius += 1.0f; if (_radius > 50.0f) { _radius = 50.0f; } break; case Keys.F1: _currentBlend = _drawModulatedBlend; break; case Keys.F2: _currentBlend = _drawAdditiveBlend; break; case Keys.F3: _currentBlend = _drawNoBlend; break; case Keys.C: // Fill the back up image with white _backBuffer.Clear(GorgonColor.White); _backBuffer.Texture.CopyTo(_backupImage); break; case Keys.J: // Disable if we go beyond the end of the list. _counter++; if (_counter == -1) { // Clip the mouse cursor to our client area. Cursor.Clip = _mouse.PositionConstraint = RectangleToScreen(ClientRectangle); // Set the position to the current mouse position. _mouse.Position = Cursor.Position; _input.RegisterDevice(_mouse); _useWinFormsInput = false; _messageSprite.Text = "Using mouse and keyboard (Raw Input)"; break; } if ((_joystickList.Count == 0) || ((_counter >= _joystickList.Count) && (_joystick != null))) { if (!_useWinFormsInput) { Cursor.Clip = Rectangle.Empty; _input.UnregisterDevice(_mouse); } _useWinFormsInput = true; _joystick = null; _counter = -2; _messageSprite.Text = "Using mouse and keyboard (Windows Forms)."; break; } // If we previously had raw input on, turn it off. if (!_useWinFormsInput) { Cursor.Clip = Rectangle.Empty; _input.UnregisterDevice(_mouse); _useWinFormsInput = true; } // Move to the next joystick. _joystick = _joystickList[_counter]; _messageSprite.Text = "Using joystick " + _joystick.Info.Description; break; } }
/// <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(); } }
/// <summary> /// Handles the KeyDown event of the _form control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="KeyEventArgs"/> instance containing the event data.</param> private static void Form_KeyDown(object sender, KeyEventArgs e) { int ballIncrement = 1; switch (e.KeyCode) { case Keys.Pause: _paused = !_paused; break; case Keys.F1: _showHelp = !_showHelp; break; case Keys.Up: if ((e.Control) && (e.Shift)) { ballIncrement = 1000; } else { if (e.Control) { ballIncrement = 100; } if (e.Shift) { ballIncrement = 10; } } GenerateBalls(ballIncrement); break; case Keys.Down: if ((e.Control) && (e.Shift)) { ballIncrement = 1000; } else { if (e.Control) { ballIncrement = 100; } if (e.Shift) { ballIncrement = 10; } } GenerateBalls(-ballIncrement); break; case Keys.Enter: if (e.Alt) { if (_mainScreen.IsWindowed) { IGorgonVideoOutputInfo output = _graphics.VideoAdapter.Outputs[_window.Handle]; if (output == null) { _mainScreen.EnterFullScreen(); } else { var mode = new GorgonVideoMode(_window.ClientSize.Width, _window.ClientSize.Height, BufferFormat.R8G8B8A8_UNorm); _mainScreen.EnterFullScreen(in mode, output); } } else { _mainScreen.ExitFullScreen(); } } break; case Keys.OemMinus: _blur.BlurRadius--; if (_blur.BlurRadius < 0) { _blur.BlurRadius = 0; } break; case Keys.Oemplus: _blur.BlurRadius++; if (_blur.BlurRadius > _blur.MaximumBlurRadius) { _blur.BlurRadius = _blur.MaximumBlurRadius; } break; } }