/// <summary> /// Function to initialize the background texture offset. /// </summary> private static void InitializeBackgroundTexturePositioning() { if (_randomOffset == null) { _randomOffset = new DX.Vector2(GorgonRandom.RandomSingle(_background.Width - _postTarget1.Width), GorgonRandom.RandomSingle(_background.Height - _postTarget1.Height)); } // If we're previously out of frame, then push back until we're in frame. if (_randomOffset.Value.X + _postTarget1.Width > _background.Width) { _randomOffset = new DX.Vector2(_randomOffset.Value.X - _postTarget1.Width, _randomOffset.Value.Y); } if (_randomOffset.Value.Y + _postTarget1.Height > _background.Height) { _randomOffset = new DX.Vector2(_randomOffset.Value.X, _randomOffset.Value.Y - _postTarget1.Height); } if (_randomOffset.Value.X < 0) { _randomOffset = new DX.Vector2(0, _randomOffset.Value.Y); } if (_randomOffset.Value.Y < 0) { _randomOffset = new DX.Vector2(_randomOffset.Value.X, 0); } // Convert to texels. _backgroundOffset = _background.Texture.ToTexel(_randomOffset.Value); }
/// <summary> /// Function to animate the anchor color. /// </summary> public void Animate() { if (!_isStarted) { _lastTime = GorgonTiming.SecondsSinceStart; _isStarted = true; return; } float time = (GorgonTiming.SecondsSinceStart - _lastTime) * 4.0f; Vector3 result; Vector3.Lerp(ref _lastColor, ref _nextColor, time, out result); Color = new GorgonColor(result); if (time <= 1) { return; } _lastTime = GorgonTiming.SecondsSinceStart; _lastColor = _nextColor; _nextColor = new Vector3(GorgonRandom.RandomSingle(), GorgonRandom.RandomSingle(), GorgonRandom.RandomSingle()); }
/// <summary> /// Function to enumerate and update the active controllers list. /// </summary> private void UpdateActiveControllers() { IReadOnlyList <IGorgonGamingDeviceInfo> controllers = _driver.EnumerateGamingDevices(true); // Enumerate the active controllers. We'll only take 3 of the 4 available xbox controllers, and only if they have the correct capabilities. _controllers = controllers.Where(item => (item.Capabilities & GamingDeviceCapabilityFlags.SupportsThrottle) == GamingDeviceCapabilityFlags.SupportsThrottle && (item.Capabilities & GamingDeviceCapabilityFlags.SupportsSecondaryXAxis) == GamingDeviceCapabilityFlags.SupportsSecondaryXAxis && (item.Capabilities & GamingDeviceCapabilityFlags.SupportsSecondaryYAxis) == GamingDeviceCapabilityFlags.SupportsSecondaryYAxis && (item.Capabilities & GamingDeviceCapabilityFlags.SupportsVibration) == GamingDeviceCapabilityFlags.SupportsVibration && (item.Capabilities & GamingDeviceCapabilityFlags.SupportsRudder) == GamingDeviceCapabilityFlags.SupportsRudder) .Take(3) .Select(item => _driver.CreateGamingDevice(item)).ToArray(); for (int i = 0; i < _controllers.Count; i++) { if (!_controllers[i].IsConnected) { continue; } // Start at a random spot. _stickPosition[i] = new Point(GorgonRandom.RandomInt32(64, panelDisplay.ClientSize.Width - 64), GorgonRandom.RandomInt32(64, panelDisplay.ClientSize.Height - 64)); // Turn off spray for all controllers. _sprayStates[i] = new SprayCan(_controllers[i], i); } }
/// <summary> /// Function called during CPU idle time. /// </summary> /// <returns><b>true</b> to continue executing, <b>false</b> to stop.</returns> private static bool Idle() { _renderer .Update(_ => { _background.Position = new DX.Vector2(_background.Position.X, _background.Position.Y + (0.3f * GorgonTiming.Delta)); // Just wrap around if we hit the top of the background. if (_background.Position.Y > _background.Bounds.Height) { _background.Position = new DX.Vector2(_background.Position.X, _screen.Height); } if (_floatLeft) { _floatOffset -= GorgonTiming.Delta * (_screen.Width / 16.0f); } else { _floatOffset += GorgonTiming.Delta * (_screen.Width / 16.0f); } float floatBounds = _screen.Width / 4.0f; if (_floatOffset < -floatBounds) { _floatOffset = -floatBounds; _floatLeft = !_floatLeft; } else if (_floatOffset > floatBounds) { _floatOffset = floatBounds; _floatLeft = !_floatLeft; } _ship.Position = new DX.Vector2((_screen.Width / 2) + _floatOffset, _screen.Height - 120); }) .Begin() .DrawSprite(_background) .DrawLoop(_stars.Length, (i, r) => { // Our renderer interface is passed to this method so that we can call back into it for things like loops and such. // Draw our "stars". ref DX.Vector2 star = ref _stars[i]; star = new DX.Vector2(star.X, star.Y + (((i % 2) == 0 ? 0.3f : 0.4f) * GorgonTiming.Delta)); if (star.Y > 1.0f) { star = new DX.Vector2(GorgonRandom.RandomSingle(), GorgonRandom.RandomSingle() * -1.0f); return(true); } var position = new DX.Vector2(star.X * _screen.Width, star.Y * _screen.Height); float starColorValue = GorgonRandom.RandomSingle(0.35f, 1.0f); var starColor = new GorgonColor(starColorValue, starColorValue, starColorValue, 1.0f); r.DrawFilledRectangle(new DX.RectangleF(position.X, position.Y, 1, 1), starColor); return(true); })
/// <summary> /// Funciton to generate random noise for the effect. /// </summary> private void GenerateRandomNoise() { int textureSize = 128; object parameter; if ((Parameters.TryGetValue("TextureSize", out parameter)) && (parameter != null)) { var size = (int)parameter; if (size > 16) { textureSize = size; } } using (var image = new GorgonImageData(new GorgonTexture2DSettings { Width = textureSize, Height = textureSize, Format = BufferFormat.R8_UIntNormal, Usage = BufferUsage.Default })) { unsafe { var dataPtr = (byte *)image.Buffers[0].Data.UnsafePointer; // Write perlin noise to the texture. for (int y = 0; y < textureSize; ++y) { for (int x = 0; x < textureSize; ++x) { float simplexNoise = GorgonRandom.SimplexNoise(new Vector2(x * (1.0f / _noiseFrequency), y * (1.0f / _noiseFrequency))); if (simplexNoise < -0.75f) { simplexNoise *= -1; } else { simplexNoise *= 0.95f; } if (simplexNoise < 0.125f) { simplexNoise = 0.0f; } *(dataPtr++) = (byte)(simplexNoise * 255.0f); } } } _randomTexture = Graphics.Textures.CreateTexture <GorgonTexture2D>("Effect.OldFilm.RandomTexture", image); } }
/// <summary> /// Function called during CPU idle time. /// </summary> /// <returns><b>true</b> to continue executing, <b>false</b> to stop.</returns> private static bool Idle() { _background.Position = new DX.Vector2(_background.Position.X, _background.Position.Y + (0.3f * GorgonTiming.Delta)); // Just wrap around if we hit the top of the background. if (_background.Position.Y > _background.Bounds.Height) { _background.Position = new DX.Vector2(_background.Position.X, _screen.Height); } if (_floatLeft) { _floatOffset -= GorgonTiming.Delta * (_screen.Width / 16.0f); } else { _floatOffset += GorgonTiming.Delta * (_screen.Width / 16.0f); } float floatBounds = _screen.Width / 4.0f; if (_floatOffset < -floatBounds) { _floatOffset = -floatBounds; _floatLeft = !_floatLeft; } else if (_floatOffset > floatBounds) { _floatOffset = floatBounds; _floatLeft = !_floatLeft; } _ship.Position = new DX.Vector2((_screen.Width / 2) + _floatOffset, _screen.Height - 120); _renderer.Begin(); _renderer.DrawSprite(_background); // Draw our "stars". for (int i = 0; i < _stars.Length; ++i) { ref DX.Vector2 star = ref _stars[i]; star = new DX.Vector2(star.X, star.Y + (((i % 2) == 0 ? 0.3f : 0.4f) * GorgonTiming.Delta)); if (star.Y > 1.0f) { star = new DX.Vector2(GorgonRandom.RandomSingle(), GorgonRandom.RandomSingle() * -1.0f); continue; } var position = new DX.Vector2(star.X * _screen.Width, star.Y * _screen.Height); float starColorValue = GorgonRandom.RandomSingle(0.35f, 1.0f); var starColor = new GorgonColor(starColorValue, starColorValue, starColorValue, 1.0f); _renderer.DrawFilledRectangle(new DX.RectangleF(position.X, position.Y, 1, 1), starColor); }
/// <summary> /// Function to handle idle time for the application. /// </summary> /// <returns><b>true</b> to continue processing, <b>false</b> to stop.</returns> private bool Idle() { // Do nothing here. When we need to update, we will. _swap.RenderTargetView.Clear(GorgonColor.White); // Use a fixed step timing to animate the cube. _accumulator += GorgonTiming.Delta; while (_accumulator >= TargetDelta) { // Spin the cube. _rotation.X += GorgonRandom.RandomSingle(45, 90) * TargetDelta * (_rotationSpeed.X.FastSin()); _rotation.Y += GorgonRandom.RandomSingle(45, 90) * TargetDelta * (_rotationSpeed.Y.FastSin()); _rotation.Z += GorgonRandom.RandomSingle(45, 90) * TargetDelta * (_rotationSpeed.Z.FastSin()); if (_rotation.X >= 360.0f) { _rotation.X -= 360.0f; } if (_rotation.Y >= 360.0f) { _rotation.Y -= 360.0f; } if (_rotation.Z >= 360.0f) { _rotation.Z -= 360.0f; } _rotationSpeed.X += TargetDelta / 6f; _rotationSpeed.Y += TargetDelta / 6f; _rotationSpeed.Z += TargetDelta / 6f; if (_rotationSpeed.X > 6.28319f) { _rotationSpeed.X = 0; } if (_rotationSpeed.Y > 6.28319f) { _rotationSpeed.Y = 0; } if (_rotationSpeed.Z > 6.28319f) { _rotationSpeed.Z = 0; } _cube.RotateXYZ(_rotation.X, _rotation.Y, _rotation.Z); _accumulator -= TargetDelta; } ref DX.Matrix matrix = ref _cube.WorldMatrix;
/// <summary> /// Initializes a new instance of the <see cref="Spray" /> class. /// </summary> /// <param name="size">Size of the drawing surface.</param> public Spray(Size size) { Surface = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppArgb); _graphics = DrawingGraphics.FromImage(Surface); _brushes = new SolidBrush[64]; for (int i = 0; i < _brushes.Length; ++i) { _brushes[i] = new SolidBrush(Color.FromArgb(GorgonRandom.RandomInt32(0, 255), GorgonRandom.RandomInt32(0, 255), GorgonRandom.RandomInt32(0, 255))); } }
/// <summary> /// Function to randomly "spray" a point on the surface. /// </summary> /// <param name="point">Origin point for the spray.</param> public void SprayPoint(Point point) { var randomArea = new Point(GorgonRandom.RandomInt32(-10, 10), GorgonRandom.RandomInt32(-10, 10)); Color randomColor = Color.FromArgb(GorgonRandom.RandomInt32(0, 255), GorgonRandom.RandomInt32(0, 255), GorgonRandom.RandomInt32(0, 255)); using (var brush = new SolidBrush(randomColor)) { _graphics.FillEllipse(brush, new Rectangle(point.X + randomArea.X , point.Y + randomArea.Y , 10 , 10)); } }
public void Test2ViewsSameShaderStage() { GorgonTexture2D texture = null; _framework.CreateTestScene(Shaders, Shaders, true); try { using (var data = new GorgonImageData(new GorgonTexture2DSettings { Width = 256, Height = 256, ArrayCount = 1, Format = BufferFormat.R8G8B8A8, MipCount = 1, ShaderViewFormat = BufferFormat.R8G8B8A8_Int, AllowUnorderedAccessViews = false, Usage = BufferUsage.Default })) { for (int i = 0; i < 5000; i++) { data.Buffers[0].Data.Position = ((GorgonRandom.RandomInt32(0, 256) * data.Buffers[0].PitchInformation.RowPitch) + GorgonRandom.RandomInt32(0, 256) * 4); data.Buffers[0].Data.Write((int)((GorgonRandom.RandomSingle() * 2.0f - 1.0f) * (Int32.MaxValue - 2))); } texture = _framework.Graphics.Textures.CreateTexture <GorgonTexture2D>("Test2D", data); } GorgonTextureShaderView view = texture.GetShaderView(BufferFormat.R8G8B8A8_UIntNormal); _framework.Graphics.Shaders.PixelShader.Resources[0] = texture; _framework.Graphics.Shaders.PixelShader.Resources[1] = view; Assert.IsTrue(_framework.Run() == DialogResult.Yes); } finally { if (texture != null) { texture.Dispose(); } } }
/// <summary> /// Function to generate the balls. /// </summary> /// <param name="ballCount">Ball count to add to the total ball count.</param> private static void GenerateBalls(int ballCount) { float halfWidth = _mainScreen.Width / 2.0f; float halfHeight = _mainScreen.Height / 2.0f; int start = _ballCount; _ballCount += ballCount; if (_ballCount < 1) { _ballCount = 1; } if (_ballCount > 1048576) { _ballCount = 1048576; } // Create ball array. if (_ballList == null) { _ballList = new Ball[1048576]; } // Generate balls. for (int i = start; i < _ballCount; i++) { var ball = new Ball { Position = new DX.Vector2(halfWidth - (_ball.Size.Width / 2.0f), halfHeight - (_ball.Size.Height / 2.0f)), PositionDelta = new DX.Vector2((GorgonRandom.RandomSingle() * _mainScreen.Width) - (halfWidth), (GorgonRandom.RandomSingle() * _mainScreen.Height) - (halfHeight)), Scale = 1.0f, ScaleDelta = (GorgonRandom.RandomSingle() * 2.0f) - 1.0f, Rotation = 0, RotationDelta = (GorgonRandom.RandomSingle() * 360.0f) - 180.0f, Color = Color.White, Opacity = 1.0f, OpacityDelta = GorgonRandom.RandomSingle() - 0.5f, Checkered = true }; _ballList[i] = ball; } }
public void BindStructBuffer() { _framework.CreateTestScene(_sbShaders, _sbShaders, false); using (var buffer = _framework.Graphics.Buffers.CreateStructuredBuffer("SB", new GorgonStructuredBufferSettings { SizeInBytes = 48, StructureSize = 12 })) { _bufferStream = new GorgonDataStream(48); _framework.Graphics.Shaders.VertexShader.Resources[0] = buffer; _framework.MaxTimeout = 10000; _framework.IdleFunc = () => { for (int i = 0; i < 4; i++) { var rnd = new Vector3(GorgonRandom.RandomSingle() * GorgonTiming.Delta, GorgonRandom.RandomSingle() * GorgonTiming.Delta, GorgonRandom.RandomSingle() * GorgonTiming.Delta); _bufferStream.Write(rnd); } _bufferStream.Position = 0; // ReSharper disable AccessToDisposedClosure buffer.Update(_bufferStream); // ReSharper restore AccessToDisposedClosure return(false); }; _framework.Run(); } }
/// <summary> /// Function to draw the pretty picture. /// </summary> private void DrawAPrettyPicture() { // Paint color. Color paintColor; // Clear the back buffer. _screen.RenderTargetView.Clear(Color.FromArgb(0, 0, 64)); // First, we need to inform the renderer that we're about draw some stuff. _renderer.Begin(); // Draw some points as stars. for (int x = 0; x < 1000; x++) { // Color. int colorSwitch = GorgonRandom.RandomInt32(160) + 95; // Color component for the points. // Get the star color. paintColor = Color.FromArgb(colorSwitch, colorSwitch, colorSwitch); _renderer.DrawFilledRectangle(new DX.RectangleF(GorgonRandom.RandomSingle(_screen.Width), GorgonRandom.RandomSingle(_screen.Height), 1, 1), paintColor); } // Draw lines. for (int x = 0; x < 360; x++) { float cos = (x + (x / 2.0f)).FastCos(); // Cosine. float sin = (x + (x / 3.0f)).FastSin(); // Sin. // Set up a random color. paintColor = Color.FromArgb((byte)GorgonRandom.RandomInt32(128, 255), GorgonRandom.RandomInt32(64, 255), GorgonRandom.RandomInt32(64, 255), 0); var startPosition = new DX.Vector2(sin + _halfSize.Width, cos + _halfSize.Height); var endPosition = new DX.Vector2((cos * (GorgonRandom.RandomSingle(_halfSize.Width * 0.82f))) + startPosition.X, (sin * (GorgonRandom.RandomSingle(_halfSize.Height * 0.82f))) + startPosition.Y); _renderer.DrawLine(startPosition.X, startPosition.Y, endPosition.X, endPosition.Y, paintColor); //Gorgon.Screen.Line(sin + _halfWidth, cos + _halfHeight, cos * (RandomValue * _halfWidth), sin * (RandomValue * _halfHeight), paintColor); } // Draw a filled circle. float size = (_halfSize.Width / 2.0f) + (GorgonRandom.RandomInt32(10) - 8); float half = size / 2.0f; _renderer.DrawFilledEllipse(new DX.RectangleF(_halfSize.Width - half, _halfSize.Height - half, size, size), Color.Yellow); // Draw some circles in the filled circle (sunspots). for (int x = 0; x < 25; x++) { float radius = GorgonRandom.RandomSingle(5.0f); var spotPosition = new DX.Vector2((GorgonRandom.RandomSingle((_halfSize.Height / 2.0f)) + _halfSize.Width - (_halfSize.Height / 4.0f)), (GorgonRandom.RandomSingle((_halfSize.Height / 2.0f)) + _halfSize.Height - (_halfSize.Height / 4.0f))); _renderer.DrawEllipse(new DX.RectangleF(spotPosition.X - (radius * 0.5f), spotPosition.Y - (radius * 0.5f), radius, radius), Color.Black); } // Draw some black bars. _renderer.DrawFilledRectangle(new DX.RectangleF(0, 0, _screen.Width, _screen.Height / 6.0f), Color.Black); _renderer.DrawFilledRectangle(new DX.RectangleF(0, _screen.Height - (_screen.Height / 6.0f), _screen.Width, _screen.Height / 6.0f), Color.Black); // Tell the renderer that we're done drawing so we can actually render the shapes. _renderer.End(); GorgonExample.DrawStatsAndLogo(_renderer); // Always call this when done or you won't see anything. _screen.Present(1); }
/// <summary> /// Function to randomly "spray" a point on the surface. /// </summary> /// <param name="point">Origin point for the spray.</param> public void SprayPoint(Point point) { var randomArea = new Point(GorgonRandom.RandomInt32(-10, 10), GorgonRandom.RandomInt32(-10, 10)); _graphics.FillEllipse(_brushes[GorgonRandom.RandomInt32(0, _brushes.Length - 1)], new Rectangle(point.X + randomArea.X, point.Y + randomArea.Y, 10, 10)); }
/// <summary> /// Function called after a pass has been rendered. /// </summary> /// <param name="pass">Pass that was rendered.</param> protected override void OnAfterPassRender(GorgonEffectPass pass) { // We must set the pixel shader back to the default here. // Otherwise our current shader may not like that we're trying to // render lines and points with no textures attached. // If this shader is nested with another (e.g. gauss blur), then // this situation can throw warnings up in the debug spew. // Setting the pixel shader to the proper shader when rendering // primitives with no textures is the best way to correct this. Gorgon2D.PixelShader.Current = null; var blend = Gorgon2D.Drawing.Blending; // Render dust and dirt. for (int i = 0; i < DirtAmount; ++i) { float grayDust = GorgonRandom.RandomSingle(0.1f, 0.25f); var dustColor = new GorgonColor(grayDust, grayDust, grayDust, GorgonRandom.RandomSingle(0.25f, 0.95f)); // Render dust points. _point.Color = dustColor; _point.PointThickness = new Vector2(1); _point.Position = new Vector2(GorgonRandom.RandomSingle(0, _currentTargetSize.X - 1), GorgonRandom.RandomSingle(0, _currentTargetSize.Y - 1)); _point.Draw(); if (GorgonRandom.RandomInt32(100) >= DirtPercent) { continue; } // Render dirt/hair lines. var dirtStart = new Vector2(GorgonRandom.RandomSingle(0, _currentTargetSize.X - 1), GorgonRandom.RandomSingle(0, _currentTargetSize.Y - 1)); float dirtWidth = GorgonRandom.RandomSingle(1.0f, 3.0f); bool isHair = GorgonRandom.RandomInt32(100) > 50; bool isHairVertical = isHair && GorgonRandom.RandomInt32(100) > 50; grayDust = GorgonRandom.RandomSingle(0.1f, 0.15f); dustColor = new GorgonColor(grayDust, grayDust, grayDust, GorgonRandom.RandomSingle(0.25f, 0.95f)); for (int j = 0; j < GorgonRandom.RandomInt32(4, (int)_currentTargetSize.X / 4); j++) { _point.Color = dustColor; _point.Position = new Vector2(dirtStart.X, dirtStart.Y); _point.PointThickness = isHair ? new Vector2(1) : new Vector2(dirtWidth, dirtWidth); _point.Draw(); if ((!isHair) || (isHairVertical)) { if (GorgonRandom.RandomInt32(100) > 50) { dirtStart.X++; } else { dirtStart.X--; } } else { if (grayDust < 0.25f) { dirtStart.X++; } else { dirtStart.X--; } } if ((!isHair) || (!isHairVertical)) { if (GorgonRandom.RandomInt32(100) > 50) { dirtStart.Y++; } else { dirtStart.Y--; } } else { if (dirtWidth < 1.5f) { dirtStart.Y++; } else { dirtStart.Y--; } } } } // Restore the previous blend state. Gorgon2D.Drawing.Blending = blend; base.OnAfterPassRender(pass); }
/// <summary> /// Initializes a new instance of the <see cref="AnchorColorAnim"/> class. /// </summary> public AnchorColorAnim() { _nextColor = new Vector3(GorgonRandom.RandomSingle(), GorgonRandom.RandomSingle(), GorgonRandom.RandomSingle()); }
/// <summary> /// Function to generate the Gorgon bitmap fonts. /// </summary> /// <param name="fontFamilies">The list of TrueType font families to use.</param> /// <param name="window">The window that contains the loading message.</param> private static void GenerateGorgonFonts(IReadOnlyList <Drawing.FontFamily> fontFamilies, FormMain window) { // Pick a font to use with outlines. int fontWithOutlineIndex = GorgonRandom.RandomInt32(1, 5); _glowIndex = GorgonRandom.RandomInt32(fontWithOutlineIndex + 1, fontWithOutlineIndex + 5); int fontWithGradient = GorgonRandom.RandomInt32(_glowIndex + 1, _glowIndex + 5); int fontWithTexture = GorgonRandom.RandomInt32(fontWithGradient + 1, fontWithGradient + 5).Min(_fontFamilies.Count - 1); var pngCodec = new GorgonCodecPng(); using (IGorgonImage texture = pngCodec.LoadFromFile(Path.Combine(GorgonExample.GetResourcePath(@"Textures\Fonts\").FullName, "Gradient.png"))) { for (int i = 0; i < _fontFamilies.Count; ++i) { string fontFamily = _fontFamilies[i]; // Use this to determine if the font is avaiable. if (fontFamilies.All(item => !string.Equals(item.Name, fontFamily, StringComparison.InvariantCultureIgnoreCase))) { // Can't locate this one, move on... continue; } bool isExternal = Drawing.FontFamily.Families.All(item => !string.Equals(item.Name, fontFamily, StringComparison.InvariantCultureIgnoreCase)); string fontName; int outlineSize = 0; GorgonColor outlineColor1 = GorgonColor.BlackTransparent; GorgonColor outlineColor2 = GorgonColor.BlackTransparent; GorgonGlyphBrush brush = null; if (i == fontWithOutlineIndex) { fontName = $"{fontFamily} 32px Outlined{(isExternal ? " External TTF" : string.Empty)}"; outlineColor1 = GorgonColor.Black; outlineColor2 = GorgonColor.Black; outlineSize = 3; } else if (i == _glowIndex) { fontName = $"{fontFamily} 32px Outline as Glow{(isExternal ? " External TTF" : string.Empty)}"; outlineColor1 = new GorgonColor(GorgonColor.YellowPure, 1.0f); outlineColor2 = new GorgonColor(GorgonColor.DarkRed, 0.0f); outlineSize = 16; } else if (i == fontWithGradient) { fontName = $"{fontFamily} 32px Gradient{(isExternal ? " External TTF" : string.Empty)}"; brush = new GorgonGlyphLinearGradientBrush { StartColor = GorgonColor.White, EndColor = GorgonColor.Black, Angle = 45.0f }; } else if (i == fontWithTexture) { fontName = $"{fontFamily} 32px Textured{(isExternal ? " External TTF" : string.Empty)}"; brush = new GorgonGlyphTextureBrush(texture); } else { fontName = $"{fontFamily} 32px{(isExternal ? " External TTF" : string.Empty)}"; } window.UpdateStatus($"Generating Font: {fontFamily}".Ellipses(50)); var fontInfo = new GorgonFontInfo(fontFamily, 30.25f, name: fontName) { AntiAliasingMode = FontAntiAliasMode.AntiAlias, OutlineSize = outlineSize, OutlineColor1 = outlineColor1, OutlineColor2 = outlineColor2, UsePremultipliedTextures = false, Brush = brush }; _font.Add(_fontFactory.GetFont(fontInfo)); // Texture brushes have to be disposed when we're done with them. var disposableBrush = brush as IDisposable; disposableBrush?.Dispose(); } } }
/// <summary> /// Function to perform the transformation of the balls. /// </summary> /// <param name="frameTime">Frame delta time.</param> private static void Transform(float frameTime) { // Transform balls. for (int i = 0; i < _ballCount; i++) { Ball currentBall = _ballList[i]; currentBall.Position = Vector2.Add(currentBall.Position, Vector2.Multiply(currentBall.PositionDelta, frameTime)); currentBall.Scale += currentBall.ScaleDelta * frameTime; currentBall.Rotation += currentBall.RotationDelta * frameTime; currentBall.Opacity += currentBall.OpacityDelta * frameTime; if (currentBall.Rotation > 360.0f) { currentBall.Rotation = currentBall.Rotation - 360.0f; } if (currentBall.Rotation < 0.0f) { currentBall.Rotation = currentBall.Rotation + 360.0f; } // Adjust position. if ((currentBall.Position.X > _mainScreen.Settings.Width) || (currentBall.Position.X < 0)) { currentBall.PositionDelta.X = -currentBall.PositionDelta.X; currentBall.RotationDelta = -currentBall.RotationDelta; } if ((currentBall.Position.Y > _mainScreen.Settings.Height) || (currentBall.Position.Y < 0)) { currentBall.PositionDelta.Y = -currentBall.PositionDelta.Y; currentBall.RotationDelta = -currentBall.RotationDelta; } // Adjust scale. if ((currentBall.Scale > 2.0f) || (currentBall.Scale < 0.5f)) { currentBall.ScaleDelta = -currentBall.ScaleDelta; if (currentBall.Scale < 0.5f) { currentBall.OpacityDelta = GorgonRandom.RandomSingle() * 0.5f * (currentBall.OpacityDelta / currentBall.OpacityDelta.Abs()); } } // Adjust opacity. if ((currentBall.Opacity <= 1.0f) && (currentBall.Opacity >= 0.0f)) { continue; } if (currentBall.Opacity > 1.0f) { currentBall.Opacity = 1.0f; currentBall.OpacityDelta = -currentBall.OpacityDelta; continue; } currentBall.Opacity = 0.0f; currentBall.Checkered = !currentBall.Checkered; currentBall.Color = Color.FromArgb(255, GorgonRandom.RandomInt32(0, 255), GorgonRandom.RandomInt32(0, 255), GorgonRandom.RandomInt32(0, 255)); currentBall.OpacityDelta = GorgonRandom.RandomSingle() * 0.5f; } }
public void Init() { _form = new TestForm { ShowTestPanel = true, ClientSize = new Size(1280, 800) }; _form.WindowState = FormWindowState.Minimized; _form.Show(); _form.WindowState = FormWindowState.Normal; _graphics = new GorgonGraphics(); _swap = _graphics.Output.CreateSwapChain("Screen", new GorgonSwapChainSettings() { Window = _form.panelDisplay, DepthStencilFormat = BufferFormat.D24_UIntNormal_S8_UInt }); _swap.AfterSwapChainResized += (sender, args) => { var currentMatrix = new MatrixBuffer(); _graphics.Rasterizer.SetViewport(_swap.Viewport); _aspect = (_swap.Settings.VideoMode.Width) / (float)(_swap.Settings.VideoMode.Height); currentMatrix.Projection = Matrix.PerspectiveFovLH(100.39f.Radians(), _aspect, 0.1f, 1000.0f); currentMatrix.View = Matrix.LookAtLH(new Vector3(0, 0, -0.75f), new Vector3(0, 0, 1.0f), Vector3.UnitY); _graphics.Output.SetRenderTarget(_swap, _swap.DepthStencilBuffer); pvw = currentMatrix.View * currentMatrix.Projection; }; _swap.AfterStateTransition += (sender, args) => { var currentMatrix = new MatrixBuffer(); _graphics.Rasterizer.SetViewport(_swap.Viewport); _aspect = (_swap.Settings.VideoMode.Width) / (float)(_swap.Settings.VideoMode.Height); currentMatrix.Projection = Matrix.PerspectiveFovLH(100.39f.Radians(), _aspect, 0.1f, 1000.0f); currentMatrix.View = Matrix.LookAtLH(new Vector3(0, 0, -0.75f), new Vector3(0, 0, 1.0f), Vector3.UnitY); _graphics.Output.SetRenderTarget(_swap, _swap.DepthStencilBuffer); pvw = currentMatrix.View * currentMatrix.Projection; }; var button = new Button() { Text = "3D", Location = new Point(90, 3) }; button.Click += (sender, args) => { _3d = !_3d; Matrix currentMatrix = Matrix.LookAtLH(new Vector3(0, 0, _camPos), new Vector3(0, 0, 1.0f), Vector3.UnitY); Matrix projection = Matrix.PerspectiveFovLH(100.39f.Radians(), _aspect, 0.1f, 1000.0f); pvw = currentMatrix * projection; }; _form.panelInput.Controls.Add(button); _sprite = new vertex[Count * 4]; for (int i = 0; i < Count; i++) { _balls[i].Scale = 1.0f; _balls[i].ScaleDelta = (GorgonRandom.RandomSingle() * 1.5f) + 0.25f; _balls[i].AlphaBounce = _balls[i].ScaleBouce = false; _balls[i].XBounce = GorgonRandom.RandomInt32(0, 100) > 50; _balls[i].YBounce = GorgonRandom.RandomInt32(0, 100) > 50; _balls[i].ZBounce = GorgonRandom.RandomInt32(0, 100) > 50; _balls[i].Velocity = new Vector3((GorgonRandom.RandomSingle() * 0.5f), (GorgonRandom.RandomSingle() * 0.5f), (GorgonRandom.RandomSingle() * 0.5f)); _balls[i].Angle = 0.0f; _balls[i].AngleDelta = 1.0f; _balls[i].Color = new Vector4(1.0f); _balls[i].AlphaDelta = GorgonRandom.RandomSingle() * 0.5f; _balls[i].Checkered = true; // GorgonRandom.RandomInt32(0, 100) > 50; _balls[i].Position = new Vector3((GorgonRandom.RandomSingle() * 2.0f) - 1.0f, (GorgonRandom.RandomSingle() * 2.0f) - 1.0f, GorgonRandom.RandomSingle()); } _vs = _graphics.Shaders.CreateShader <GorgonVertexShader>("TestVShader", "VS", _shader, null, true); _ps = _graphics.Shaders.CreateShader <GorgonPixelShader>("TestPShader", "PS", _shader, null, true); _layout = _graphics.Input.CreateInputLayout("Input", typeof(vertex), _vs); int vertexSize = _layout.Size; int index = 0; var indices = new int[Count * 6 * sizeof(int)]; for (int i = 0; i < indices.Length; i += 6) { indices[i] = index; indices[i + 1] = index + 1; indices[i + 2] = index + 2; indices[i + 3] = index + 1; indices[i + 4] = index + 3; indices[i + 5] = index + 2; index += 4; } _vertices = _graphics.Buffers.CreateVertexBuffer("Vertex", new GorgonBufferSettings() { SizeInBytes = 4 * vertexSize * Count, Usage = BufferUsage.Dynamic }); _index = _graphics.Buffers.CreateIndexBuffer("Index", indices, BufferUsage.Immutable); _texture = _graphics.Textures.FromFile <GorgonTexture2D>("Balls", @"..\..\..\..\Resources\BallDemo\BallDemo.png", new GorgonCodecPNG()); _texture2 = _graphics.Textures.FromFile <GorgonTexture2D>("VBBack", @"..\..\..\..\Resources\Images\VBback.jpg", new GorgonCodecJPEG()); var matrix = new MatrixBuffer(); _aspect = _swap.Settings.VideoMode.Width / (float)(_swap.Settings.VideoMode.Height); matrix.Projection = Matrix.PerspectiveFovLH(100.39f.Radians(), _aspect, 0.1f, 1000.0f); matrix.View = Matrix.LookAtLH(new Vector3(0, 0, _camPos), new Vector3(0, 0, 1.0f), Vector3.UnitY); matrix.Array = new Vector4[3]; matrix.Array[0] = new Vector4(1.0f, 1.0f, 1.0f, 1.0f); matrix.Array[1] = new Vector4(1.0f, 1.0f, 1.0f, 1.0f); matrix.Array[2] = new Vector4(1.0f, 1.0f, 1.0f, 1.0f); matrix.valueType = new TEMPGUY { value2 = matrix.View, tempArray = new Vector4[3] }; _depthStateAlpha.IsDepthEnabled = false; _depthStateAlpha.IsDepthWriteEnabled = false; _graphics.Input.Layout = _layout; _graphics.Shaders.VertexShader.Current = _vs; _graphics.Shaders.PixelShader.Current = _ps; _graphics.Shaders.PixelShader.TextureSamplers.SetRange(0, new[] { GorgonTextureSamplerStates.LinearFilter, GorgonTextureSamplerStates.LinearFilter }); _graphics.Rasterizer.SetViewport(_swap.Viewport); _graphics.Output.DepthStencilState.States = _depthStateAlpha; _graphics.Output.SetRenderTarget(_swap, _swap.DepthStencilBuffer); _graphics.Input.VertexBuffers[0] = new GorgonVertexBufferBinding(_vertices, vertexSize); _graphics.Input.IndexBuffer = _index; _graphics.Shaders.PixelShader.Resources.SetRange(0, new GorgonShaderView[] { _texture, _texture2 }); _graphics.Output.BlendingState.States = GorgonBlendStates.ModulatedBlending; pvw = matrix.valueType.value2 * matrix.Projection; _tempStream = new GorgonDataStream(_sprite.Length * vertexSize); }
public void BouncyBalls3D() { Gorgon.Run(_form, () => { _swap.Clear(Color.Black); for (int i = 0; i < Count; i++) { _balls[i].Angle += _balls[i].AngleDelta * GorgonTiming.Delta; if (_balls[i].Angle > 360.0f) { _balls[i].Angle = _balls[i].Angle - 360.0f; _balls[i].AngleDelta = GorgonRandom.RandomSingle() * 90.0f; } if ((_balls[i].ScaleBouce) || (!_balls[i].ZBounce)) { _balls[i].Color.W -= _balls[i].Velocity.Z * GorgonTiming.Delta; } else { _balls[i].Color.W += _balls[i].Velocity.Z * GorgonTiming.Delta; } if (_balls[i].Color.W > 1.0f) { _balls[i].Color.W = 1.0f; } if (_balls[i].Color.W < 0.0f) { _balls[i].Color.W = 0.0f; _balls[i].Color = new Vector4((GorgonRandom.RandomSingle() * 0.961f) + 0.039f, (GorgonRandom.RandomSingle() * 0.961f) + 0.039f, (GorgonRandom.RandomSingle() * 0.961f) + 0.039f, 0.0f); } if (_balls[i].YBounce) { _balls[i].Position.Y -= (_balls[i].Velocity.Y * GorgonTiming.Delta); } else { _balls[i].Position.Y += (_balls[i].Velocity.Y * GorgonTiming.Delta); } if (_balls[i].XBounce) { _balls[i].Position.X -= (_balls[i].Velocity.X * GorgonTiming.Delta); } else { _balls[i].Position.X += (_balls[i].Velocity.X * GorgonTiming.Delta); } if (_balls[i].ZBounce) { _balls[i].Position.Z -= (_balls[i].Velocity.Z * GorgonTiming.Delta); } else { _balls[i].Position.Z += (_balls[i].Velocity.Z * GorgonTiming.Delta); } if (_balls[i].Position.X > (1.0f * _aspect)) { _balls[i].Position.X = (1.0f * _aspect); _balls[i].Velocity.X = (GorgonRandom.RandomSingle() * 0.5f); _balls[i].XBounce = !_balls[i].XBounce; } if (_balls[i].Position.Y > (1.0f * _aspect)) { _balls[i].Position.Y = (1.0f * _aspect); _balls[i].Velocity.Y = (GorgonRandom.RandomSingle() * 0.5f); _balls[i].YBounce = !_balls[i].YBounce; } if (_balls[i].Position.X < (-1.0f * _aspect)) { _balls[i].Position.X = (-1.0f * _aspect); _balls[i].Velocity.X = GorgonRandom.RandomSingle() * 0.5f; _balls[i].XBounce = !_balls[i].XBounce; } if (_balls[i].Position.Y < (-1.0f * _aspect)) { _balls[i].Position.Y = (-1.0f * _aspect); _balls[i].Velocity.Y = GorgonRandom.RandomSingle() * 0.5f; _balls[i].YBounce = !_balls[i].YBounce; } if (_balls[i].Position.Z < -1.0f) { _balls[i].Position.Z = -1.0f; _balls[i].Velocity.Z = GorgonRandom.RandomSingle() * 0.5f; _balls[i].ZBounce = !_balls[i].ZBounce; } if (!(_balls[i].Position.Z > 1.0f)) { continue; } _balls[i].Position.Z = 1.0f; _balls[i].Velocity.Z = GorgonRandom.RandomSingle() * 0.5f; _balls[i].ZBounce = !_balls[i].ZBounce; } var sortPos = _balls.OrderByDescending(item => item.Position.Z).ToArray(); for (int i = 0; i < Count * 4; i += 4) { int arrayindex = i / 4; Matrix world; if (_3d) { Quaternion rot = Quaternion.RotationYawPitchRoll(sortPos[arrayindex].Angle.Cos(), -sortPos[arrayindex].Angle.Sin() * 2.0f, -sortPos[arrayindex].Angle); Matrix.RotationQuaternion(ref rot, out world); } else { world = Matrix.RotationZ(-sortPos[arrayindex].Angle); } world = world * (Matrix.Scaling(sortPos[arrayindex].Scale, sortPos[arrayindex].Scale, 1.0f)) * Matrix.Translation(sortPos[arrayindex].Position.X, sortPos[arrayindex].Position.Y, sortPos[arrayindex].Position.Z); Matrix trans; Matrix.Multiply(ref world, ref pvw, out trans); _sprite[i].Color = new GorgonColor(sortPos[arrayindex].Color); _sprite[i + 1].Color = _sprite[i].Color; _sprite[i + 2].Color = _sprite[i].Color; _sprite[i + 3].Color = _sprite[i].Color; _sprite[i].Position = Vector3.Transform(new Vector3(-0.1401f, 0.1401f, 0.0f), trans); _sprite[i + 1].Position = Vector3.Transform(new Vector3(0.1401f, 0.1401f, 0.0f), trans); _sprite[i + 2].Position = Vector3.Transform(new Vector3(-0.1401f, -0.1401f, 0.0f), trans); _sprite[i + 3].Position = Vector3.Transform(new Vector3(0.1401f, -0.1401f, 0.0f), trans); if (sortPos[arrayindex].Checkered) { _sprite[i].UV = new Vector2(0.503f, 0.0f); _sprite[i + 1].UV = new Vector2(1.0f, 0.0f); _sprite[i + 2].UV = new Vector2(0.503f, 0.5f); _sprite[i + 3].UV = new Vector2(1.0f, 0.5f); } else { _sprite[i].UV = new Vector2(0.0f, 0.503f); _sprite[i + 1].UV = new Vector2(0.5f, 0.503f); _sprite[i + 2].UV = new Vector2(0.0f, 1.0f); _sprite[i + 3].UV = new Vector2(0.5f, 1.0f); } } using (GorgonDataStream vstream = _vertices.Lock(BufferLockFlags.Write | BufferLockFlags.Discard)) { vstream.WriteRange(_sprite); _vertices.Unlock(); } _graphics.Output.DrawIndexed(0, 0, 6 * Count); _swap.Flip(); _form.Text = string.Format("FPS: {0:0.0} DT: {1:0.000}ms", GorgonTiming.FPS, GorgonTiming.Delta * 1000); return(true); }); Assert.IsTrue(_form.TestResult == DialogResult.Yes); }
/// <summary> /// Function to perform operations while the CPU is idle. /// </summary> /// <returns><b>true</b> to continue processing, <b>false</b> to stop.</returns> private static bool Idle() { _postTarget1.Clear(GorgonColor.Black); DX.Vector2 textureSize = _background.Texture.ToTexel(new DX.Vector2(_postTarget1.Width, _postTarget1.Height)); // Blit the background texture. _graphics.SetRenderTarget(_postTarget1); _renderer.Begin(); _renderer.DrawFilledRectangle(new DX.RectangleF(0, 0, _postTarget1.Width, _postTarget1.Height), GorgonColor.White, _background, new DX.RectangleF(_backgroundOffset.X, _backgroundOffset.Y, textureSize.X, textureSize.Y)); _shipSprite.Color = new GorgonColor(GorgonColor.White, _cloakController.Opacity); _renderer.DrawSprite(_shipSprite); _renderer.End(); // No sense in rendering the effect if it's not present. float strength = _cloakController.CloakAmount; if (strength > 0.0f) { // Don't bother recording the current state, we're going to be updating it shortly, so it'd be redundant. _displacement.Strength = strength; _displacement.Render((passIndex, _, __) => DrawDisplacement(passIndex), _postTarget2); } else { // Send the undisplaced image to the 2nd post process target. _graphics.SetRenderTarget(_postTarget2); _renderer.Begin(); _renderer.DrawFilledRectangle(new DX.RectangleF(0, 0, _postTarget1.Width, _postTarget1.Height), GorgonColor.White, _postView1, new DX.RectangleF(0, 0, 1, 1)); _renderer.End(); } // Smooth our results. int blurRadiusUpdate = GorgonRandom.RandomInt32(0, 1000000); if (blurRadiusUpdate > 997000) { _gaussBlur.BlurRadius = (_gaussBlur.BlurRadius + 1).Min(_gaussBlur.MaximumBlurRadius / 2); } else if (blurRadiusUpdate < 3000) { _gaussBlur.BlurRadius = (_gaussBlur.BlurRadius - 1).Max(1); } // If we didn't blur (radius = 0), then just use the original view. if (_gaussBlur.BlurRadius > 0) { _gaussBlur.Render((_, __, outputSize) => { _renderer.DrawFilledRectangle(new DX.RectangleF(0, 0, outputSize.Width, outputSize.Height), GorgonColor.White, _postView2, new DX.RectangleF(0, 0, 1, 1)); }, _postTarget2); } // Render as an old film effect. _oldFilm.Time = GorgonTiming.SecondsSinceStart * 2; DX.Vector2 offset = DX.Vector2.Zero; if (GorgonRandom.RandomInt32(0, 100) > 95) { offset = new DX.Vector2(GorgonRandom.RandomSingle(-2.0f, 2.0f), GorgonRandom.RandomSingle(-1.5f, 1.5f)); } _oldFilm.Render((_, __, size) => _renderer.DrawFilledRectangle(new DX.RectangleF(offset.X, offset.Y, size.Width, size.Height), GorgonColor.White, _postView2, new DX.RectangleF(0, 0, 1, 1)), _postTarget1); // Send to our screen. _screen.RenderTargetView.Clear(GorgonColor.Black); _graphics.SetRenderTarget(_screen.RenderTargetView); _renderer.Begin(Gorgon2DBatchState.NoBlend); if (GorgonRandom.RandomInt32(0, 100) < 2) { _finalBrightness = GorgonRandom.RandomSingle(0.65f, 1.0f); } _renderer.DrawFilledRectangle(new DX.RectangleF(0, 0, _finalView.Width, _finalView.Height), new GorgonColor(_finalBrightness, _finalBrightness, _finalBrightness, 1.0f), _postView1, new DX.RectangleF(0, 0, 1, 1)); _renderer.End(); _renderer.Begin(); if (_showHelp) { _renderer.DrawString(HelpText, new DX.Vector2(0, 64), color: new GorgonColor(1.0f, 1.0f, 0)); } _renderer.End(); GorgonExample.DrawStatsAndLogo(_renderer); // Flip our back buffers over. _screen.Present(1); _cloakController.Update(); return(true); }
public void TestComputeShader() { _framework.CreateTestScene(BaseShaders, BaseShaders, true, true); using (var compShader = _framework.Graphics.Shaders.CreateShader <GorgonComputeShader>("CompShader", "TestCS", BaseShaders)) { var cbuffer = _framework.Graphics.Buffers.CreateConstantBuffer("CBuffer", new GorgonConstantBufferSettings { SizeInBytes = 16 }); var cbuffer2 = _framework.Graphics.Buffers.CreateConstantBuffer("CBuffer2", new GorgonConstantBufferSettings { SizeInBytes = 16 }); var view = ((GorgonTexture2D)_framework.Screen).GetUnorderedAccessView(BufferFormat.R8G8B8A8_UIntNormal); _framework.Screen.AfterSwapChainResized += (sender, e) => { view = ((GorgonTexture2D)_framework.Screen).GetUnorderedAccessView(BufferFormat.R8G8B8A8_UIntNormal); using (var data = new GorgonDataStream(16)) { data.Write(new Vector2(e.Width, e.Height)); data.Position = 0; cbuffer.Update(data); } }; var texture = _framework.Graphics.Textures.CreateTexture <GorgonTexture2D>("Test", Resources.Glass, new GorgonGDIOptions { AllowUnorderedAccess = true, Format = BufferFormat.R8G8B8A8_UIntNormal }); var test = new Vector3(GorgonRandom.RandomSingle(0, 180.0f), GorgonRandom.RandomSingle(0, 180.0f), GorgonRandom.RandomSingle(0, 180.0f)); var speed = new Vector3(GorgonRandom.RandomSingle(5, 45), GorgonRandom.RandomSingle(5, 45), GorgonRandom.RandomSingle(5, 45)); var testDir = new Vector3(1); _framework.IdleFunc = () => { //_framework.Screen.Clear(GorgonColor.White); _framework.Graphics.Output.SetRenderTarget(null); _framework.Graphics.Shaders.PixelShader.Resources[0] = null; _framework.Graphics.Shaders.ComputeShader.Current = compShader; _framework.Graphics.Shaders.ComputeShader.ConstantBuffers[0] = cbuffer; _framework.Graphics.Shaders.ComputeShader.ConstantBuffers[1] = cbuffer2; _framework.Graphics.Shaders.ComputeShader.UnorderedAccessViews[0] = view; _framework.Graphics.Shaders.ComputeShader.Dispatch((_framework.Screen.Settings.Width + 10) / 10, (_framework.Screen.Settings.Height + 10) / 10, 1); _framework.Graphics.Shaders.ComputeShader.UnorderedAccessViews[0] = null; _framework.Graphics.Output.SetRenderTarget(_framework.Screen); _framework.Graphics.Shaders.PixelShader.Resources[0] = texture; test += Vector3.Modulate(testDir * GorgonTiming.Delta, speed); /*if ((test >= 1.0f) || (test <= 0.0f)) * { * testDir *= -1.0f; * }*/ if ((test.X > 359.9f) || (test.X <= 0.0f)) { test.X = test.X - 359.9f * -testDir.X; speed.X = GorgonRandom.RandomSingle(5, 180.0f); testDir.X *= -1.0f; } if ((test.Y > 359.9f) || (test.Y <= 0.0f)) { test.Y = test.Y - 359.9f * -testDir.X; speed.Y = GorgonRandom.RandomSingle(5, 180); testDir.Y *= -1.0f; } if ((test.Z > 359.9f) || (test.Z <= 0.0f)) { test.Z = test.Z - 359.9f * -testDir.Y; speed.Z = GorgonRandom.RandomSingle(5, 180); testDir.Z *= -1.0f; } var animVal = new Vector3(test.X.Radians().Cos(), test.Y.Radians().Sin(), test.Z.Radians().Cos() * test.Z.Radians().Cos()); cbuffer2.Update(ref animVal); return(false); }; Assert.IsTrue(_framework.Run() == DialogResult.Yes); } }
/// <summary> /// Function to initialize the effects and the effect compositor. /// </summary> private static void InitializeEffects() { // The blur effect. _blurEffect = new Gorgon2DGaussBlurEffect(_renderer) { PreserveAlpha = true }; _blurEffect.Precache(); // The grayscale effect. _grayScaleEffect = new Gorgon2DGrayScaleEffect(_renderer); // The posterize effect. _posterizeEffect = new Gorgon2DPosterizedEffect(_renderer) { Bits = 10 }; // The 1 bit effect. _1BitEffect = new Gorgon2D1BitEffect(_renderer) { Threshold = new GorgonRangeF(0.5f, 1.0f), ConvertAlphaChannel = false }; // The burn effect. _burnEffect = new Gorgon2DBurnDodgeEffect(_renderer) { UseDodge = false }; // The dodge effect. _dodgeEffect = new Gorgon2DBurnDodgeEffect(_renderer) { UseDodge = true }; // The invert effect. _invertEffect = new Gorgon2DInvertEffect(_renderer); // The sharpen effect. _sharpenEffect = new Gorgon2DSharpenEmbossEffect(_renderer) { UseEmbossing = false, Amount = 1.0f }; // The emboss effect. _embossEffect = new Gorgon2DSharpenEmbossEffect(_renderer) { UseEmbossing = true, Amount = 1.0f }; // The sobel edge detection effect. _sobelEffect = new Gorgon2DSobelEdgeDetectEffect(_renderer) { LineThickness = 2.5f, EdgeThreshold = 0.80f }; // An old film effect. _oldFilmEffect = new Gorgon2DOldFilmEffect(_renderer) { ScrollSpeed = 0.05f }; // A HDR bloom effect. _bloomEffect = new Gorgon2DBloomEffect(_renderer) { Threshold = 1.11f, BloomIntensity = 35.0f, BlurAmount = 6.0f, ColorIntensity = 1.15f }; // A chromatic aberration effect. _chromatic = new Gorgon2DChromaticAberrationEffect(_renderer) { Intensity = 0.25f }; _compositor = new Gorgon2DCompositor(_renderer); // Set up each pass for the compositor. // As you can see, we're not strictly limited to using our 2D effect objects, we can define custom passes as well. // And, we can also define how existing effects are rendered for things like animation and such. _compositor.EffectPass("Chromatic Aberration", _chromatic) .EffectPass("1-Bit Color", _1BitEffect) .EffectPass("Blur", _blurEffect) .EffectPass("Grayscale", _grayScaleEffect) .EffectPass("Posterize", _posterizeEffect) .EffectPass("Burn", _burnEffect) .EffectPass("Dodge", _dodgeEffect) .EffectPass("Invert", _invertEffect) .EffectPass("Sharpen", _sharpenEffect) .EffectPass("Emboss", _embossEffect) .EffectPass("Bloom", _bloomEffect) .Pass(new Gorgon2DCompositionPass("Sobel Edge Detection", _sobelEffect) { BlendOverride = GorgonBlendState.Default, ClearColor = GorgonColor.White }) .RenderPass("Sobel Blend Pass", (sobelTexture, pass, passCount, size) => { // This is a custom pass that does nothing but rendering. No effect is applied here, just straight rendering to // the currently active render target. var rectPosition = new DX.RectangleF(0, 0, size.Width, size.Height); var texCoords = new DX.RectangleF(0, 0, 1, 1); _renderer.DrawFilledRectangle(rectPosition, GorgonColor.White, _images[_currentImage], texCoords); _renderer.DrawFilledRectangle(rectPosition, GorgonColor.White, sobelTexture, texCoords); }) .Pass(new Gorgon2DCompositionPass("Olde Film", _oldFilmEffect) { BlendOverride = GorgonBlendState.Additive, RenderMethod = (prevEffect, passIndex, passCount, size) => { // Here we can override the method used to render to the effect. // In this case, we're animating our old film content to shake and darken at defined intervals. // If we do not override this, the compositor would just blit the previous texture to the // current render target. var rectPosition = new DX.RectangleF(0, 0, size.Width, size.Height); var texCoords = new DX.RectangleF(0, 0, 1, 1); GorgonColor color = GorgonColor.White; if ((GorgonTiming.SecondsSinceStart % 10) >= 4) { rectPosition.Inflate(GorgonRandom.RandomSingle(1, 5), GorgonRandom.RandomSingle(1, 5)); float value = GorgonRandom.RandomSingle(0.5f, 0.89f); color = new GorgonColor(value, value, value, 1.0f); } _renderer.DrawFilledRectangle(rectPosition, color, prevEffect, texCoords); } }) .InitialClearColor(GorgonColor.White) .FinalClearColor(GorgonColor.White); _compositor.Passes["Chromatic Aberration"].Enabled = false; _compositor.Passes["Bloom"].Enabled = false; _compositor.Passes["Posterize"].Enabled = false; _compositor.Passes["Grayscale"].Enabled = false; _compositor.Passes["1-Bit Color"].Enabled = false; _compositor.Passes["Emboss"].Enabled = false; _compositor.Passes["Dodge"].Enabled = false; _compositor.Passes["Olde Film"].Enabled = false; }
public void BindRawBuffer() { _framework.CreateTestScene(_rbShaders, _rbShaders, false); var values = new byte[256 * 256 * 4]; float angle = 0.0f; using (var buffer = _framework.Graphics.Buffers.CreateBuffer("RB", new GorgonBufferSettings { AllowRawViews = true, AllowShaderViews = true, DefaultShaderViewFormat = BufferFormat.R32_UInt, SizeInBytes = values.Length })) { _framework.Graphics.Shaders.PixelShader.Resources[0] = buffer; _framework.IdleFunc = () => { using (var stream = new GorgonDataStream(values)) { float rads = (angle * GorgonRandom.RandomSingle(8.0f, 32.0f) + 16.0f).Radians(); float x = 128 + GorgonRandom.RandomInt32(0, 5) + (rads * rads.Cos()); float y = 128 + GorgonRandom.RandomInt32(0, 5) + (rads * rads.Sin()); if (x > 255) { x = 255; } if (y > 255) { y = 255; } if (x < 0) { x = 0; } if (y < 0) { y = 0; } int pos = (((int)y * 1024) + ((int)x * 4)); for (int i = 0; i < pos - 50; i++) { values[i] = (byte)(values[i] * 0.95f); } values[pos] = 255; values[pos + 3] = values[pos + 2] = values[pos + 1] = (byte)GorgonRandom.RandomInt32(64, 128); angle += GorgonRandom.RandomSingle(1, 180) * GorgonTiming.Delta; if (angle > 360.0f) { angle = 0.0f; } buffer.Update(stream); return(false); } }; _framework.MaxTimeout = 15000; _framework.Run(); } }
/// <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 { // Load the XInput plug-in assembly. Gorgon.PlugIns.LoadPlugInAssembly(Program.PlugInPath + "Gorgon.Input.XInput.dll"); // Create our factory. _factory = GorgonInputFactory.CreateInputFactory("GorgonLibrary.Input.GorgonXInputPlugIn"); // Ensure that we have and XBox controller to work with. if (_factory.JoystickDevices.Count == 0) { GorgonDialogs.ErrorBox(this, "No XBox controllers were found on this system.\nThis example requires an XBox controller."); Gorgon.Quit(); return; } // Enumerate the active joysticks. We'll only take 3 of the 4 available xbox controllers. _joystick = new GorgonJoystick[3]; _stickPosition = new PointF[_joystick.Count]; _sprayStates = new SprayCan[_joystick.Count]; for (int i = 0; i < _joystick.Count; i++) { var joystick = _factory.CreateJoystick(this, _factory.JoystickDevices[i].Name); // Set a dead zone on the joystick. // A dead zone will stop input from the joystick until it reaches the outside // of the specified coordinates. joystick.DeadZone.X = new GorgonRange(joystick.Capabilities.XAxisRange.Minimum / 4, joystick.Capabilities.XAxisRange.Maximum / 4); joystick.DeadZone.Y = new GorgonRange(joystick.Capabilities.YAxisRange.Minimum / 4, joystick.Capabilities.YAxisRange.Maximum / 4); joystick.DeadZone.SecondaryX = new GorgonRange(joystick.Capabilities.XAxisRange.Minimum / 128, joystick.Capabilities.XAxisRange.Maximum / 128); joystick.DeadZone.SecondaryY = new GorgonRange(joystick.Capabilities.YAxisRange.Minimum / 128, joystick.Capabilities.YAxisRange.Maximum / 128); _joystick[i] = joystick; // Start at a random spot. _stickPosition[i] = new Point(GorgonRandom.RandomInt32(64, panelDisplay.ClientSize.Width - 64), GorgonRandom.RandomInt32(64, panelDisplay.ClientSize.Height - 64)); // Turn off spray for all controllers. _sprayStates[i] = new SprayCan(joystick, i); } // Check for connected controllers. while (!_joystick.Any(item => item.IsConnected)) { if (MessageBox.Show(this, "There are no XBox controllers connected.\nPlease plug in an XBox controller and click OK.", "No Controllers", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.Cancel) { continue; } Gorgon.Quit(); return; } // Get the graphics interface for our panel. _surface = new DrawingSurface(panelDisplay); // Set up our idle loop. Gorgon.ApplicationIdleLoopMethod += 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. GorgonException.Catch(ex, () => GorgonDialogs.ErrorBox(this, ex)); Gorgon.Quit(); } }
/// <summary> /// Function to perform the updates to the cloak animation. /// </summary> public void Update() { switch (Direction) { case CloakDirection.Cloak: Opacity -= 0.8f * GorgonTiming.Delta; _cloakAmount += 0.12f * GorgonTiming.Delta; _cloakAmount = _cloakAmount.Min(0.25f).Max(0); Opacity = Opacity.Min(1.0f).Max(0); if ((_cloakAmount >= 0.25f) && (Opacity <= 0.0f)) { Direction = CloakDirection.CloakPulse; _cloakPulseAngle = 180.0f; _cloakAngleRads = _cloakPulseAngle.ToRadians(); } break; case CloakDirection.Uncloak: if (_cloakAmount < 0.12f) { Opacity += 0.8f * GorgonTiming.Delta; } _cloakAmount -= 0.12f * GorgonTiming.Delta; _cloakAmount = _cloakAmount.Min(0.25f).Max(0); Opacity = Opacity.Min(1.0f).Max(0); if ((_cloakAmount <= 0.0f) && (Opacity >= 1.0f)) { Direction = CloakDirection.None; } break; case CloakDirection.UncloakStopPulse: _cloakPulseAngle += (90.0f * GorgonTiming.Delta) * _stopPulseDirection; if (((_cloakPulseAngle > 180.0f) && (_stopPulseDirection == 1)) || (_cloakPulseAngle < 180.0f) && (_stopPulseDirection == -1)) { _cloakPulseAngle = 180.0f; Direction = CloakDirection.Uncloak; } _cloakAngleRads = _cloakPulseAngle.ToRadians(); break; case CloakDirection.CloakPulse: _cloakAngleRads = _cloakPulseAngle.ToRadians(); _cloakPulseAngle += GorgonRandom.RandomSingle(0.0f, 120.0f) * GorgonTiming.Delta; if (_cloakPulseAngle > 360.0f) { _cloakPulseAngle -= 360.0f; } break; } }
public void TestTextureUpdate() { float diver = 1.0f; var shader = _framework.Graphics.Shaders.FromMemory <GorgonPixelShader>("PS", "TestPSUpdateSub", Resources.TextureShaders); var texture = _framework.Graphics.Textures.CreateTexture("Texture", new GorgonTexture2DSettings { ArrayCount = 1, Format = BufferFormat.R8G8B8A8_UIntNormal, MipCount = 4, Height = 256, Width = 256, Usage = BufferUsage.Default }); var dynTexture = _framework.Graphics.Textures.CreateTexture("DynTexture", new GorgonTexture2DSettings { ArrayCount = 1, Format = BufferFormat.R8G8B8A8_UIntNormal, MipCount = 1, Height = 256, Width = 256, Usage = BufferUsage.Dynamic }); var imageData = GorgonImageData.CreateFromGDIImage(Resources.Glass, ImageType.Image2D, new GorgonGDIOptions { MipCount = 4 }); _framework.CreateTestScene(Shaders, Shaders, true); _framework.Graphics.Shaders.PixelShader.Current = shader; _framework.Graphics.Shaders.PixelShader.Resources[1] = texture; texture.UpdateSubResource(imageData.Buffers[0], new Rectangle { Width = 128, Height = 128, X = 0, Y = 0 }); texture.UpdateSubResource(imageData.Buffers[1], new Rectangle { Width = 64, Height = 64, X = 128, Y = 0 }); GorgonTexture2D testIntFormat = _framework.Graphics.Textures.CreateTexture("asas", new GorgonTexture2DSettings { Format = BufferFormat.R8G8B8A8_Int, Usage = BufferUsage.Dynamic, Width = 64, Height = 64 }); _framework.IdleFunc = () => { _framework.Graphics.Shaders.PixelShader.Resources[2] = null; using (var lockData = dynTexture.Lock(BufferLockFlags.Write | BufferLockFlags.Discard)) { for (int i = 0; i < 4096; ++i) { int y = GorgonRandom.RandomInt32(0, imageData.Buffers[0].Height); int x = GorgonRandom.RandomInt32(0, imageData.Buffers[0].Width); // 95417E imageData.Buffers[0].Data.Position = (y * imageData.Buffers[0].PitchInformation.RowPitch) + (x * 4); lockData.Data.Position = (y * lockData.PitchInformation.RowPitch) + (x * dynTexture.FormatInformation.SizeInBytes); var color = new GorgonColor(imageData.Buffers[0].Data.ReadInt32()); color = new GorgonColor(color.Red / diver, color.Green / diver, color.Blue / diver); lockData.Data.Write(color.ToARGB()); //lockData.Data.Write(0xFF00FF00); /*lockData.Data.Write(Color.FromArgb(color.ToARGB()).R); * lockData.Data.Write(Color.FromArgb(color.ToARGB()).G); * lockData.Data.Write(Color.FromArgb(color.ToARGB()).B); * lockData.Data.Write(Color.FromArgb(color.ToARGB()).A);*/ } } diver += 0.5f * GorgonTiming.Delta; if (diver > 32.0f) { diver = 1.0f; } _framework.Graphics.Shaders.PixelShader.Resources[2] = dynTexture; return(false); }; Assert.IsTrue(_framework.Run() == DialogResult.Yes); }
/// <summary> /// Function to initialize the application. /// </summary> /// <returns>The main window for the application.</returns> private static FormMain Initialize() { GorgonExample.ResourceBaseDirectory = new DirectoryInfo(Settings.Default.ResourceLocation); FormMain window = GorgonExample.Initialize(new DX.Size2(Settings.Default.Resolution.Width, Settings.Default.Resolution.Height), "Post Processing"); try { IReadOnlyList <IGorgonVideoAdapterInfo> videoDevices = 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 Effects Example Swap Chain") { Width = Settings.Default.Resolution.Width, Height = Settings.Default.Resolution.Height, Format = BufferFormat.R8G8B8A8_UNorm }); // Tell the graphics API that we want to render to the "screen" swap chain. _graphics.SetRenderTarget(_screen.RenderTargetView); // Initialize the renderer so that we are able to draw stuff. _renderer = new Gorgon2D(_graphics); GorgonExample.LoadResources(_graphics); // Load the Gorgon logo to show in the lower right corner. var ddsCodec = new GorgonCodecDds(); // Import the images we'll use in our post process chain. if (!LoadImageFiles(ddsCodec)) { return(window); } // Initialize the effects that we'll use for compositing, and the compositor itself. InitializeEffects(); // Set up our quick and dirty GUI. _buttons = new Button[_compositor.Passes.Count]; LayoutGUI(); // Select a random image to start _currentImage = GorgonRandom.RandomInt32(0, _images.Length - 1); window.KeyUp += Window_KeyUp; window.MouseUp += Window_MouseUp; window.MouseMove += Window_MouseMove; window.MouseDown += Window_MouseDown; window.IsLoaded = true; return(window); } finally { GorgonExample.EndInit(); } }
/// <summary> /// Function to update the sprayer. /// </summary> public void Update() { float throttleValue = Joystick.Throttle; float appTime = GorgonTiming.SecondsSinceStart - _activeStartTime; // Get unit time. float unitTime = appTime / _maxTime; // Vibrate our controller. Joystick.Vibrate(1, (int)_vibAmount); // Get the spray vector in a -1 .. 1 range. var sprayVector = new PointF(Joystick.SecondaryX - Joystick.Capabilities.SecondaryXAxisRange.Minimum, Joystick.SecondaryY - Joystick.Capabilities.SecondaryYAxisRange.Minimum); sprayVector = new PointF((sprayVector.X / (Joystick.Capabilities.SecondaryXAxisRange.Range + 1)) * 2.0f - 1.0f, -((sprayVector.Y / (Joystick.Capabilities.SecondaryYAxisRange.Range + 1)) * 2.0f - 1.0f)); // Calculate angle without magnitude. var sprayVectorDelta = new PointF(sprayVector.X, sprayVector.Y); float sprayAngle = 0.0f; // Ensure that we get the correct angle. if (sprayVectorDelta.Y.EqualsEpsilon(0.0f)) { if (sprayVectorDelta.X < 0.0f) { sprayAngle = (-90.0f).Radians(); } else if (sprayVectorDelta.X > 0.0f) { sprayAngle = (90.0f).Radians(); } } else { sprayAngle = (sprayVectorDelta.Y).ATan(sprayVectorDelta.X) + (-45.0f).Radians(); } // Get sine and cosine for the angle. float sin = sprayAngle.Sin(); float cos = sprayAngle.Cos(); // Decrease spray time. _time = _maxTime - appTime; // If we're out of time, then leave. if (_time <= 0.0f) { IsActive = false; NeedReset = true; return; } // Decrease alpha over time. _alpha = _maxAlpha - (_maxAlpha * unitTime); if (_alpha < 0.0f) { _alpha = 0.0f; } // Decrease vibration over time. _vibAmount = _vibMax - (_vibMax * unitTime); if (_vibAmount < 0.0f) { _vibAmount = 0.0f; } // Decrease the amount over time and by throttle pressure. _sprayAmount = _sprayMax * unitTime; SprayPointSize = (unitTime * 30.0f) + 10.0f; // Scale the vector. sprayVector = new PointF(_sprayAmount * (cos - sin), _sprayAmount * (sin + cos)); // Update the spray position. var jitter = new PointF(GorgonRandom.RandomSingle(-_sprayAmount / _sprayMax * throttleValue / 10.0f, _sprayAmount / _sprayMax * throttleValue / 10.0f), GorgonRandom.RandomSingle(-_sprayAmount / _sprayMax * throttleValue / 10.0f, _sprayAmount / _sprayMax * throttleValue / 10.0f)); Position = new PointF(Origin.X + sprayVector.X + jitter.X, Origin.Y + sprayVector.Y + jitter.Y); }