26 Sep 2021

General:
+ Added Summaries

Renderer
-------
SM.Base:
+ SM.Base.Controls.Mouse now has a feature to disable tracking.
+ Replaced Bloom Effect with the similar system how blender use it.
+ You can now disable ANY post processing effects.
+ Interpolation for CVectors.
+ MathUtils
+ RenderPipelines now have a central list for post processing effects.

~ Log-System is now ignored if a debugger is attached.
~ Post Processing Shader does now send the texel size as the "renderedTextureTexelSize"-uniform.
~ Improved Text Rendering

SM.OGL:
+ ColorAttachments now contain a reference to the framebuffer its connected.
+ ColorAttachments can now have a own size.
+ Framebuffer.Append(string key, Vector2 size, int pos)
+Framebuffers now have a method to completely reset itself.
+ Framebuffers now have a Blit-method called "CopyTo".

~ Framebuffer.GetCurrentlyActive() will now return an actual SM.OGL.Framebuffer-object.
~ Renderbuffers now are a class and contain the ID by itself.
~ Renamed Uniform-function to its class-name: f.E. SetBool, SetFloat instead of SetUniform1

Optionals:
Controls:
+ Framecache for the GameController.GetState()
This commit is contained in:
Nineto Nine 2021-09-26 21:27:14 +02:00
parent dffa581596
commit 9b52d401e7
61 changed files with 1529 additions and 818 deletions

View file

@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SM.Intergrations</RootNamespace>
<AssemblyName>SM.Intergrations</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />

View file

@ -23,30 +23,30 @@ namespace SM.Intergrations.ShaderTool
STPCompositeNode composeNode = drawNode.OGLEffect;
ShaderFileFiles.Vertex = new[] { new ShaderFile(composeNode.Vertex.ShaderCode) };
ShaderFileFiles.Fragment = new [] {new ShaderFile(composeNode.Fragment.ShaderCode)};
ShaderFiles.Vertex = new[] { new ShaderFile(composeNode.Vertex.ShaderCode) };
ShaderFiles.Fragment = new [] {new ShaderFile(composeNode.Fragment.ShaderCode)};
if (composeNode.Geometry != null)
ShaderFileFiles.Geometry = new[] {new ShaderFile(composeNode.Geometry.ShaderCode)};
ShaderFiles.Geometry = new[] {new ShaderFile(composeNode.Geometry.ShaderCode)};
foreach (KeyValuePair<string, STPVariable> pair in drawNode.Variables)
{
switch (pair.Value.Type)
{
case STPBasisType.Bool:
_uniforms += context => Uniforms[pair.Key].SetUniform1(context.Material.ShaderArguments.Get(pair.Key, false));
_uniforms += context => Uniforms[pair.Key].SetBool(context.Material.ShaderArguments.Get(pair.Key, false));
break;
case STPBasisType.Float:
_uniforms += context => Uniforms[pair.Key].SetUniform1(context.Material.ShaderArguments.Get(pair.Key, 0.0f));
_uniforms += context => Uniforms[pair.Key].SetFloat(context.Material.ShaderArguments.Get(pair.Key, 0.0f));
break;
case STPBasisType.Vector2:
_uniforms += context => Uniforms[pair.Key].SetUniform2(context.Material.ShaderArguments.Get(pair.Key, Vector2.Zero));
_uniforms += context => Uniforms[pair.Key].SetVector2(context.Material.ShaderArguments.Get(pair.Key, Vector2.Zero));
break;
case STPBasisType.Vector3:
_uniforms += context => Uniforms[pair.Key].SetUniform3(context.Material.ShaderArguments.Get(pair.Key, Vector3.Zero));
_uniforms += context => Uniforms[pair.Key].SetVector3(context.Material.ShaderArguments.Get(pair.Key, Vector3.Zero));
break;
case STPBasisType.Vector4:
_uniforms += context =>
Uniforms[pair.Key].SetUniform4(context.Material.ShaderArguments.Get(pair.Key, Vector4.Zero));
Uniforms[pair.Key].SetVector4(context.Material.ShaderArguments.Get(pair.Key, Vector4.Zero));
break;
case STPBasisType.Matrix:
_uniforms += context => Uniforms[pair.Key].SetMatrix4(context.Material.ShaderArguments.Get(pair.Key, Matrix4.Identity));

View file

@ -39,7 +39,7 @@ namespace SM.Intergrations.ShaderTool
}
}
public override void Draw(ColorAttachment source, DrawContext context)
protected override void Drawing(ColorAttachment source, DrawContext context)
{
Arguments["_Scene"] = (TextureBase)source;
Arguments["_MVP"] = Mvp;

View file

@ -23,30 +23,30 @@ namespace SM.Intergrations.ShaderTool
STPCompositeNode composeNode = postProcessNode.OGLEffect;
ShaderFileFiles.Vertex = new[] { new ShaderFile(composeNode.Vertex.ShaderCode) };
ShaderFileFiles.Fragment = new[] { new ShaderFile(composeNode.Fragment.ShaderCode) };
ShaderFiles.Vertex = new[] { new ShaderFile(composeNode.Vertex.ShaderCode) };
ShaderFiles.Fragment = new[] { new ShaderFile(composeNode.Fragment.ShaderCode) };
if (composeNode.Geometry != null)
ShaderFileFiles.Geometry = new[] { new ShaderFile(composeNode.Geometry.ShaderCode) };
ShaderFiles.Geometry = new[] { new ShaderFile(composeNode.Geometry.ShaderCode) };
foreach (KeyValuePair<string, STPVariable> pair in postProcessNode.Variables)
{
switch (pair.Value.Type)
{
case STPBasisType.Bool:
_uniforms += context => Uniforms[pair.Key].SetUniform1(context.Get(pair.Key, false));
_uniforms += context => Uniforms[pair.Key].SetBool(context.Get(pair.Key, false));
break;
case STPBasisType.Float:
_uniforms += context => Uniforms[pair.Key].SetUniform1(context.Get(pair.Key, 0.0f));
_uniforms += context => Uniforms[pair.Key].SetFloat(context.Get(pair.Key, 0.0f));
break;
case STPBasisType.Vector2:
_uniforms += context => Uniforms[pair.Key].SetUniform2(context.Get(pair.Key, Vector2.Zero));
_uniforms += context => Uniforms[pair.Key].SetVector2(context.Get(pair.Key, Vector2.Zero));
break;
case STPBasisType.Vector3:
_uniforms += context => Uniforms[pair.Key].SetUniform3(context.Get(pair.Key, Vector3.Zero));
_uniforms += context => Uniforms[pair.Key].SetVector3(context.Get(pair.Key, Vector3.Zero));
break;
case STPBasisType.Vector4:
_uniforms += context =>
Uniforms[pair.Key].SetUniform4(context.Get(pair.Key, Vector4.Zero));
Uniforms[pair.Key].SetVector4(context.Get(pair.Key, Vector4.Zero));
break;
case STPBasisType.Matrix:
_uniforms += context => Uniforms[pair.Key].SetMatrix4(context.Get(pair.Key, Matrix4.Identity));

View file

@ -1,16 +1,22 @@
using SharpDX.XInput;
using SM.Base;
namespace SM.Utils.Controls
{
public struct GameController
public class GameController
{
public static float GlobalDeadband = 2500;
public static float GlobalDeadband = .1F;
private Controller _controller;
private ulong _lastFrame;
internal GamepadButtonFlags _lastPressedButtons;
public float Deadband { get; set; }
public bool IsConnected => _controller.IsConnected;
public GameControllerState LastState { get; private set; }
public UserIndex Index { get; private set; }
public GameController(int id) : this((UserIndex)id)
@ -18,21 +24,32 @@ namespace SM.Utils.Controls
public GameController(UserIndex index = UserIndex.Any)
{
_lastPressedButtons = GamepadButtonFlags.None;
_controller = new Controller(index);
Index = index;
Deadband = GlobalDeadband;
}
public GameControllerState GetState()
public GameControllerState GetState(bool force = false)
{
if (!IsConnected)
if (!force && _lastFrame == SMRenderer.CurrentFrame)
{
return new GameControllerState(true);
return LastState;
}
Gamepad state = _controller.GetState().Gamepad;
GameControllerState st = new GameControllerState(true);
if (IsConnected)
{
Gamepad state = _controller.GetState().Gamepad;
st = new GameControllerState(state, this);
_lastPressedButtons = state.Buttons;
}
return new GameControllerState(state, ref this);
LastState = st;
_lastFrame = SMRenderer.CurrentFrame;
return st;
}
}

View file

@ -22,22 +22,11 @@ namespace SM.Utils.Controls
DPad = GameControllerStateDPad.Default;
Buttons = GameControllerStateButtons.Default;
}
internal GameControllerState(Gamepad state, ref GameController controller)
internal GameControllerState(Gamepad state, GameController controller)
{
FromConnected = true;
Thumbs = new GameControllerStateThumbs
{
Left = new Vector2(
Math.Abs((float)state.LeftThumbX) < controller.Deadband ? 0 : (float)state.LeftThumbX / short.MaxValue,
Math.Abs((float)state.LeftThumbY) < controller.Deadband ? 0 : (float)state.LeftThumbY / short.MaxValue),
Right = new Vector2(
Math.Abs((float)state.RightThumbX) < controller.Deadband ? 0 : (float)state.RightThumbX / short.MaxValue,
Math.Abs((float)state.RightThumbY) < controller.Deadband ? 0 : (float)state.RightThumbY / short.MaxValue),
PressedLeft = state.Buttons.HasFlag(GamepadButtonFlags.LeftThumb),
PressedRight = state.Buttons.HasFlag(GamepadButtonFlags.RightThumb)
};
Thumbs = new GameControllerStateThumbs(controller, state);
Triggers = new GameControllerStateTriggers()
{
@ -46,7 +35,7 @@ namespace SM.Utils.Controls
};
DPad = new GameControllerStateDPad(state.Buttons);
Buttons = new GameControllerStateButtons(state.Buttons);
Buttons = new GameControllerStateButtons(state.Buttons, controller);
}
public override string ToString()

View file

@ -4,9 +4,14 @@ namespace SM.Utils.Controls
{
public struct GameControllerStateButtons
{
public static GameControllerStateButtons Default = new GameControllerStateButtons(GamepadButtonFlags.None);
public static GameControllerStateButtons Default = new GameControllerStateButtons()
{
_buttonFlags = GamepadButtonFlags.None,
_lastButtonFlags = GamepadButtonFlags.None
};
private GamepadButtonFlags _buttonFlags;
private GamepadButtonFlags _lastButtonFlags;
public bool X;
public bool Y;
@ -22,13 +27,14 @@ namespace SM.Utils.Controls
public bool Start;
public bool Back;
public bool this[GamepadButtonFlags flags] => _buttonFlags.HasFlag(flags);
public bool this[GamepadButtonFlags flags, bool once = false] => _buttonFlags.HasFlag(flags) && !(once && _lastButtonFlags.HasFlag(flags));
public bool AnyInteraction { get; }
internal GameControllerStateButtons(GamepadButtonFlags flags)
internal GameControllerStateButtons(GamepadButtonFlags flags, GameController controller)
{
_buttonFlags = flags;
_lastButtonFlags = controller._lastPressedButtons;
X = flags.HasFlag(GamepadButtonFlags.X);
Y = flags.HasFlag(GamepadButtonFlags.Y);

View file

@ -1,4 +1,6 @@
using OpenTK;
using System;
using OpenTK;
using SharpDX.XInput;
namespace SM.Utils.Controls
{
@ -15,6 +17,18 @@ namespace SM.Utils.Controls
public bool AnyInteraction => Left != Vector2.Zero || Right != Vector2.Zero || PressedLeft || PressedRight;
public GameControllerStateThumbs(GameController controller, Gamepad state)
{
Vector2 left = new Vector2(state.LeftThumbX, state.LeftThumbY) / short.MaxValue;
Vector2 right = new Vector2(state.RightThumbX, state.RightThumbY) / short.MaxValue;
Left = new Vector2(Math.Abs(left.X) < controller.Deadband ? 0 : left.X, Math.Abs(left.Y) < controller.Deadband ? 0 : left.Y);
Right = new Vector2(Math.Abs(right.X) < controller.Deadband ? 0 : right.X, Math.Abs(right.Y) < controller.Deadband ? 0 : right.Y);
PressedLeft = state.Buttons.HasFlag(GamepadButtonFlags.LeftThumb);
PressedRight = state.Buttons.HasFlag(GamepadButtonFlags.RightThumb);
}
public override string ToString()
{
return $"Left: ({Left.X}; {Left.Y}){(PressedLeft ? " Pressed" : "")}; Right: ({Right.X}; {Right.Y}){(PressedRight ? " Pressed" : "")}";

View file

@ -12,16 +12,25 @@ namespace SM.Utils.Controls
public struct GameKeybindActor
{
private GameKeybindActorType _type;
private GameController? _controller;
private GameController _controller;
private GameKeybindHost _keybindHost;
public GameKeybindActorType Type => _type;
public GameController? Controller => _controller;
public GameController Controller => _controller;
public object[] Parameter;
private GameKeybindActor(GameKeybindActorType type, GameController? controller)
private GameKeybindActor(GameKeybindActorType type, GameController controller)
{
_type = type;
_controller = controller;
_keybindHost = null;
Parameter = new object[0];
}
private GameKeybindActor(GameKeybindActorType type, ref GameController controller)
{
_type = type;
_controller = controller;
@ -58,7 +67,7 @@ namespace SM.Utils.Controls
KeyboardState = Keyboard.GetState(),
MouseState = Mouse.GetState(),
ControllerState = Controller?.GetState(),
ControllerState = Controller?.GetState() ?? new GameControllerState(true),
};
return keybind[Type].Invoke(context);

View file

@ -6,7 +6,7 @@ namespace SM.Utils.Controls
{
public KeyboardState KeyboardState;
public MouseState MouseState;
public GameControllerState? ControllerState;
public GameControllerState ControllerState;
public GameKeybindActor Actor;
public GameKeybindHost Host;

View file

@ -9,9 +9,10 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SM.Utils</RootNamespace>
<AssemblyName>SM.Utils</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@ -61,5 +62,11 @@
<None Include="OpenTK.dll.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\renderer\SM.Base\SM.Base.csproj">
<Project>{8e733844-4204-43e7-b3dc-3913cddabb0d}</Project>
<Name>SM.Base</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View file

@ -18,10 +18,20 @@ namespace SM.Base.Controls
private static MouseState? _mouseState;
private static List<MouseButton> _lastButtonsPressed = new List<MouseButton>();
private static Vector2 _inScreen;
/// <summary>
/// The current position of the mouse in the screen.
/// Gets or sets the current position of the mouse in the screen.
/// </summary>
public static Vector2 InScreen { get; private set; }
public static Vector2 InScreen
{
get => _inScreen;
set
{
_inScreen = value;
UpdateNormalized(SMRenderer.CurrentWindow);
}
}
/// <summary>
/// The current position of the mouse in the screen from 0..1.
@ -40,6 +50,16 @@ namespace SM.Base.Controls
/// </summary>
public static bool RightClick => IsDown(MouseButton.Right, true);
/// <summary>
/// If true, it disables the tracking of the mouse, allowing you to change the <see cref="InScreen"/> value, without the system replacing it again.
/// </summary>
public static bool StopTracking { get; set; }
private static void UpdateNormalized(IGenericWindow window)
{
InScreenNormalized = new Vector2(_inScreen.X / (float)window.Width, _inScreen.Y / (float)window.Height);
}
/// <summary>
/// The event to update the values.
/// </summary>
@ -47,8 +67,10 @@ namespace SM.Base.Controls
/// <param name="window">The window where the mouse is checked</param>
internal static void MouseMoveEvent(MouseMoveEventArgs mmea, IGenericWindow window)
{
if (StopTracking) return;
InScreen = new Vector2(mmea.X, mmea.Y);
InScreenNormalized = new Vector2(mmea.X / (float) window.Width, mmea.Y / (float) window.Height);
UpdateNormalized(window);
}
internal static void SetState()

View file

@ -39,6 +39,10 @@ namespace SM.Base.Drawing
/// </summary>
public ShaderArguments ShaderArguments { get; internal set; } = new ShaderArguments();
/// <summary>
/// Draws the material with the provided context.
/// </summary>
/// <param name="context"></param>
public virtual void Draw(DrawContext context)
{
context.Shader.Draw(context);

View file

@ -1,6 +1,8 @@
#region usings
using System;
using System.Collections.Generic;
using System.Linq;
using OpenTK;
using OpenTK.Graphics;
using SM.Base.Objects.Static;
@ -130,9 +132,13 @@ namespace SM.Base.Drawing.Text
{
if (!Font.WasCompiled) Font.RegenerateTexture();
if (string.IsNullOrEmpty(_text)) return;
_text = _text.Replace("\r\n", "\n").Replace("\t", " ");
_instances = new Instance[_text.Length];
List<Tuple<Vector2, Instance[]>> lines = new List<Tuple<Vector2, Instance[]>>();
List<Instance> currentLineInstances = new List<Instance>();
float x = 0;
float y = 0;
@ -146,8 +152,13 @@ namespace SM.Base.Drawing.Text
if (_text[i] == '\n')
{
if (currentLineInstances.Count > 0)
{
lines.Add(new Tuple<Vector2, Instance[]>(new Vector2(x, y), currentLineInstances.ToArray()));
currentLineInstances.Clear();
}
y += Font.Height;
Width = Math.Max(Width, x);
x = 0;
continue;
}
@ -170,32 +181,41 @@ namespace SM.Base.Drawing.Text
var matrix = Matrix4.CreateScale(parameter.Width, Font.Height, 1) *
Matrix4.CreateTranslation(x + parameter.Width / 2, -y, 0);
_instances[i] = new Instance
currentLineInstances.Add(_instances[i] = new Instance
{
ModelMatrix = matrix,
TextureMatrix = parameter.TextureMatrix
};
});
x += parameter.Advance;
}
if (currentLineInstances.Count > 0)
lines.Add(new Tuple<Vector2, Instance[]>(new Vector2(x, y), currentLineInstances.ToArray()));
Height = y + Font.Height;
Width = x;
Width = lines.Max(a => a.Item1.X);
if (Origin != TextOrigin.Left)
{
foreach (Instance i in _instances)
foreach (Tuple<Vector2, Instance[]> line in lines)
{
if (i == null) continue;
switch (Origin)
foreach (Instance i in line.Item2)
{
case TextOrigin.Center:
i.ModelMatrix *= Matrix4.CreateTranslation(-Width / 2, 0, 0);
break;
case TextOrigin.Right:
i.ModelMatrix *= Matrix4.CreateTranslation(-Width, 0, 0);
break;
if (i == null) continue;
switch (Origin)
{
case TextOrigin.Center:
i.ModelMatrix *= Matrix4.CreateTranslation(-line.Item1.X / 2, 0, 0);
break;
case TextOrigin.Right:
i.ModelMatrix *= Matrix4.CreateTranslation(-line.Item1.X, 0, 0);
break;
}
}
}
}
}
}

View file

@ -1,144 +0,0 @@
#region usings
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Text;
using OpenTK.Graphics.OpenGL4;
using SM.Base.Textures;
#endregion
namespace SM.Base.Drawing.Text
{
/// <summary>
/// Represents a font.
/// </summary>
public class Font : Texture
{
/// <summary>
/// The char set for the font.
/// <para>Default: <see cref="FontCharStorage.SimpleUTF8" /></para>
/// </summary>
public ICollection<char> CharSet = FontCharStorage.SimpleUTF8;
/// <summary>
/// The font family, that is used to find the right font.
/// </summary>
public FontFamily FontFamily;
/// <summary>
/// The font size.
/// <para>Default: 12</para>
/// </summary>
public float FontSize = 12;
public float SpaceWidth { get; private set; }
public float Spacing = 1;
/// <summary>
/// The font style.
/// <para>Default: <see cref="System.Drawing.FontStyle.Regular" /></para>
/// </summary>
public FontStyle FontStyle = FontStyle.Regular;
/// <summary>
/// This contains all information for the different font character.
/// </summary>
public Dictionary<char, CharParameter> Positions = new Dictionary<char, CharParameter>();
/// <summary>
/// Generates a font from a font family from the specified path.
/// </summary>
/// <param name="path">The specified path</param>
public Font(string path)
{
var pfc = new PrivateFontCollection();
pfc.AddFontFile(path);
FontFamily = pfc.Families[0];
}
/// <summary>
/// Generates a font from a specified font family.
/// </summary>
/// <param name="font">Font-Family</param>
public Font(FontFamily font)
{
FontFamily = font;
}
/// <inheritdoc />
public override TextureWrapMode WrapMode { get; set; } = TextureWrapMode.ClampToEdge;
/// <summary>
/// Regenerates the texture.
/// </summary>
public void RegenerateTexture()
{
Width = 0;
Height = 0;
Positions = new Dictionary<char, CharParameter>();
var map = new Bitmap(1000, 20);
var charParams = new Dictionary<char, float[]>();
using (var f = new System.Drawing.Font(FontFamily, FontSize, FontStyle))
{
using (var g = Graphics.FromImage(map))
{
g.Clear(Color.Transparent);
foreach (var c in CharSet)
{
var s = c.ToString();
var size = g.MeasureString(s, f, 0, StringFormat.GenericTypographic);
try
{
charParams.Add(c, new[] {size.Width, Width});
}
catch
{
// ignored
}
if (Height < size.Height) Height = (int) size.Height;
Width += (int) size.Width + 1;
}
SpaceWidth = g.MeasureString("_", f, 0, StringFormat.GenericTypographic).Width;
}
map = new Bitmap(Width, Height);
using (var g = Graphics.FromImage(map))
{
foreach (var keyValuePair in charParams)
{
var normalizedX = (keyValuePair.Value[1]+ 0.00001f) / Width;
var normalizedWidth = keyValuePair.Value[0] / Width;
CharParameter parameter;
Positions.Add(keyValuePair.Key, parameter = new CharParameter
{
NormalizedWidth = normalizedWidth,
NormalizedX = normalizedX,
Width = keyValuePair.Value[0],
X = (int) keyValuePair.Value[1]
});
g.DrawString(keyValuePair.Key.ToString(), f, Brushes.White, parameter.X, 0, StringFormat.GenericTypographic);
}
}
}
Map = map;
Recompile();
}
/// <inheritdoc />
public override void Compile()
{
RegenerateTexture();
base.Compile();
}
}
}

View file

@ -0,0 +1,216 @@
#region usings
using System;
using System.Drawing;
using OpenTK;
using OpenTK.Graphics.OpenGL4;
using SM.Base.Drawing;
using SM.Base.PostProcess;
using SM.Base.Utility;
using SM.Base.Window;
using SM.OGL.Framebuffer;
using SM.OGL.Shaders;
using SM.OGL.Texture;
#endregion
namespace SM.Base.Legacy.PostProcessing
{
/// <summary>
/// A bloom post process effect.
/// </summary>
[Obsolete("This bloom effect isn't good. Please use SM.Base.PostEffects.BloomEffect, if you want a good bloom effect.")]
public class BloomEffectOld : PostProcessEffect
{
private static BezierCurve _defaultCurve = new BezierCurve(Vector2.UnitY, Vector2.Zero, new Vector2(0.4f, 0), new Vector2(.5f,0));
private static readonly PostProcessShader _mergeShader = new PostProcessShader(
new ShaderFile(AssemblyUtility.ReadAssemblyFile("SM.Base.Legacy.PostProcessing.bloom_merge.vert")),
AssemblyUtility.ReadAssemblyFile("SM.Base.Legacy.PostProcessing.bloom_merge.glsl"));
private static readonly PostProcessShader _shader =
new PostProcessShader(AssemblyUtility.ReadAssemblyFile("SM.Base.Legacy.PostProcessing.bloom_blur.glsl"));
private const float _defaultTextureScale = .75f;
private Framebuffer _source;
private Framebuffer _tempColorBuffer;
private Framebuffer _bloomBuffer1;
private Framebuffer _bloomBuffer2;
private readonly bool _hdr;
private readonly float _textureScale = .75f;
private BezierCurve _weightCurve;
private float[] _weights;
private ColorAttachment _xBuffer;
private ColorAttachment _yBuffer;
/// <summary>
/// A texture where you can define the amount of the bloom effect at each pixel.
/// </summary>
public TextureBase AmountMap;
/// <summary>
/// The transformation for the amount map.
/// </summary>
public TextureTransformation AmountTransform = new TextureTransformation();
/// <summary>
/// The maximal amount the amount map is clamped to.
/// <para>Default: 1</para>
/// </summary>
public float MaxAmount = 1;
/// <summary>
/// The minimal amount the amount map is clamped to.
/// <para>Default: 0</para>
/// </summary>
public float MinAmount = 0;
/// <summary>
/// The defines how often the x-y-flipflop happens.
/// <para>Default: 8</para>
/// </summary>
public int Iterations = 8;
/// <summary>
/// The Threshold for the bloom effect.
/// <para>Default: .8f</para>
/// </summary>
public float Threshold = .8f;
/// <summary>
/// Increases the brightness of the resulting effect.
/// <para>Default: 1</para>
/// </summary>
public float Power = 1;
/// <summary>
/// Radius of the effect
/// <para>Default: 2</para>
/// </summary>
public float Radius = 1;
/// <summary>
/// This defines the weight curve.
/// </summary>
public BezierCurve WeightCurve
{
get => _weightCurve;
set
{
_weightCurve = value;
UpdateWeights();
}
}
/// <summary>
/// This defines how many picks the effect should pick from the weight curve.
/// </summary>
public int WeightCurvePickAmount = 4;
/// <summary>
/// This creates a bloom effect.
/// </summary>
/// <param name="source">This can specify a own source framebuffer. If not set, it will take the Pipeline MainFramebuffer.</param>
/// <param name="hdr">This allows to enable hdr returns.</param>
/// <param name="textureScale">This allows for a increase in performance, by lowering the calculating texture scale.</param>
public BloomEffectOld(Framebuffer source = null, bool hdr = false, float? textureScale = null)
{
_source = source;
_hdr = hdr;
_textureScale = textureScale.GetValueOrDefault(_defaultTextureScale);
WeightCurve = _defaultCurve;
}
private void UpdateWeights()
{
_weights = new float[WeightCurvePickAmount];
for (int i = 0; i < WeightCurvePickAmount; i++)
_weights[i] = _weightCurve.CalculatePoint((float) (i + 1) / (WeightCurvePickAmount + 1)).Y;
}
/// <inheritdoc/>
protected override void InitProcess()
{
_source ??= Pipeline.MainFramebuffer;
_source.ColorAttachments["color"].PixelInformation = PixelInformation.RGBA_HDR;
_tempColorBuffer = new Framebuffer(Pipeline.ConnectedWindow, 1);
_tempColorBuffer.Append("color", new ColorAttachment(0, PixelInformation.RGBA_HDR));
_tempColorBuffer.Compile();
_bloomBuffer1 = new Framebuffer(Pipeline.ConnectedWindow, _textureScale)
{
Name = "BloomX"
};
_bloomBuffer1.Append("xBuffer", _xBuffer = new ColorAttachment(0, PixelInformation.RGBA_HDR));
_bloomBuffer1.Compile();
_bloomBuffer2 = new Framebuffer(Pipeline.ConnectedWindow, _textureScale)
{
Name = "BloomY"
};
_bloomBuffer2.Append("yBuffer", _yBuffer = new ColorAttachment(0, PixelInformation.RGBA_HDR));
_bloomBuffer2.Compile();
Pipeline.Framebuffers.Add(_tempColorBuffer);
Pipeline.Framebuffers.Add(_bloomBuffer1);
Pipeline.Framebuffers.Add(_bloomBuffer2);
}
/// <inheritdoc/>
protected override void Drawing(ColorAttachment source, DrawContext context)
{
GL.Viewport(0, 0, (int) (Pipeline.ConnectedWindow.Width * _textureScale),
(int) (Pipeline.ConnectedWindow.Height * _textureScale));
Framebuffer target = Framebuffer.GetCurrentlyActive();
source.ConnectedFramebuffer.CopyTo(_tempColorBuffer);
bool first = true, hoz = true;
int iter = Iterations * 2;
for (int i = 0; i < iter; i++)
{
(hoz ? _bloomBuffer1 : _bloomBuffer2).Activate(false);
_shader.Draw(collection =>
{
collection["renderedTexture"].SetTexture(first ? source : (hoz ? _yBuffer : _xBuffer));
collection["First"].SetBool(first);
collection["Threshold"].SetFloat(Threshold);
collection["Horizontal"].SetBool(hoz);
collection["Weights"].SetFloat(_weights);
collection["WeightCount"].SetFloat(WeightCurvePickAmount);
collection["Power"].SetFloat(Power);
collection["Radius"].SetFloat(_textureScale * Radius);
});
hoz = !hoz;
if (first) first = false;
}
GL.Viewport(Pipeline.ConnectedWindow.ClientRectangle);
target.Activate();
_mergeShader.Draw(collection =>
{
collection["Scene"].SetTexture(_tempColorBuffer["color"]);
collection["Bloom"].SetTexture(_yBuffer);
collection["MinAmount"].SetFloat(MinAmount);
collection["MaxAmount"].SetFloat(MaxAmount);
collection["AmountMap"].SetTexture(AmountMap, collection["HasAmountMap"]);
collection["TextureTransform"].SetMatrix3(AmountTransform.GetMatrix());
collection["Exposure"].SetFloat(context.UseCamera.Exposure);
collection["HDR"].SetBool(_hdr);
});
}
}
}

View file

@ -1,5 +1,4 @@
#version 330
#define PI 3.14159265359
uniform sampler2D renderedTexture;
uniform float RenderScale;
@ -16,6 +15,7 @@ uniform float Power;
uniform float Radius;
layout(location = 0) out vec4 color;
layout(location = 1) out vec4 scene;
vec4 GetRenderColorOffset(vec2 offset);
@ -31,6 +31,8 @@ float GetWeight(int dif) {
}
void main() {
if (First) scene = GetRenderColorOffset(vec2(0));
vec3 thres = vec3(First ? Threshold : 0);
vec2 tex_offset = 1.0 / textureSize(renderedTexture, 0) * vec2(Horizontal ? 1 : 0, Horizontal ? 0 : 1);

View file

@ -18,7 +18,7 @@ layout(location = 0) out vec4 color;
void main() {
vec3 result = texture(Bloom, vTexture).rgb;
if (HasAmountMap) result *= clamp(length(texture(AmountMap, TransformedTexture).rgb) * (MaxAmount - MinAmount) + MinAmount, 0, 1);
//if (HasAmountMap) result *= clamp(length(texture(AmountMap, TransformedTexture).rgb) * (MaxAmount - MinAmount) + MinAmount, 0, 1);
if (!HDR) {
result = vec3(1.0) - exp(-result * Exposure);
}

View file

@ -0,0 +1,18 @@
#version 330
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec2 aTex;
uniform mat4 MVP;
uniform mat3 TextureTransform;
out vec2 vTexture;
out vec2 TransformedTexture;
void main() {
vTexture = aTex;
//TransformedTexture = vec2(TextureTransform * vec3(aTex, 1));
gl_Position = MVP * vec4(aPos, 1);
}

View file

@ -5,6 +5,7 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Windows.Forms;
using OpenTK.Graphics.OpenGL4;
using SM.OGL;
@ -82,14 +83,14 @@ namespace SM.Base
/// <summary>
/// Presets for the log targets.
/// </summary>
public static Dictionary<LogTarget, string> Preset = new()
public static Dictionary<LogTarget, string> Preset = new Dictionary<LogTarget, string>()
{
{LogTarget.Console, "[%type%] %msg%"},
{LogTarget.Debugger, "[%type%] %msg%"},
{LogTarget.File, "<%date%, %time%> [%type%] %msg%"}
};
private static readonly Dictionary<LogType, ConsoleColor> Colors = new()
private static readonly Dictionary<LogType, ConsoleColor> Colors = new Dictionary<LogType, ConsoleColor>()
{
{LogType.Info, ConsoleColor.Green},
{LogType.Warning, ConsoleColor.Yellow},
@ -145,7 +146,10 @@ namespace SM.Base
{
if (_init) return;
AppDomain.CurrentDomain.UnhandledException += ExceptionHandler;
if (!Debugger.IsAttached)
{
AppDomain.CurrentDomain.UnhandledException += ExceptionHandler;
}
AppDomain.CurrentDomain.DomainUnload += (sender, args) =>
{
_logStream.WriteLine("Unload application");
@ -172,9 +176,12 @@ namespace SM.Base
Write(e.IsTerminating ? "Terminating Error" : LogType.Error.ToString(),
e.IsTerminating ? ConsoleColor.DarkRed : ConsoleColor.Red, e.ExceptionObject);
MethodBase info = (e.ExceptionObject as Exception).TargetSite;
string name = $"{info.ReflectedType.Namespace}.{info.ReflectedType.Name}.{info.Name}".Replace(".", "::");
if (e.IsTerminating)
{
MessageBox.Show($"Critical error occured.\n\n{e.ExceptionObject}",
MessageBox.Show($"Critical error occured at {name}.\n\n{e.ExceptionObject}",
$"Terminating Error: {e.ExceptionObject.GetType().Name}");
_logStream?.Close();
}

View file

@ -1,211 +1,199 @@
#region usings
using System.Drawing;
using OpenTK;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL4;
using SM.Base.Drawing;
using SM.Base.PostProcess;
using SM.Base.Utility;
using SM.Base.Window;
using SM.OGL.Framebuffer;
using SM.OGL.Shaders;
using SM.OGL.Texture;
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SM.Base.PostEffects
{
/// <summary>
/// A bloom post process effect.
/// The recommended bloom effect, that looks way better than the old one.
/// <para>Based on Blender's implermentation, which is based on COD: Infinite Warfare.</para>
/// </summary>
public class BloomEffect : PostProcessEffect
public class BloomEffect : PostProcess.PostProcessEffect
{
private static BezierCurve _defaultCurve = new BezierCurve(Vector2.UnitY, Vector2.Zero, new Vector2(0.4f, 0), new Vector2(.5f,0));
private static readonly PostProcessShader _mergeShader = new PostProcessShader(
AssemblyUtility.ReadAssemblyFile(SMRenderer.PostProcessPath + ".bloom_merge_vert.glsl"),
AssemblyUtility.ReadAssemblyFile(SMRenderer.PostProcessPath + ".bloom_merge.glsl"));
private static readonly ShaderFile samplingFile = new ShaderFile(AssemblyUtility.ReadAssemblyFile(SMRenderer.PostProcessPath + ".bloom.sampling.frag"));
private static readonly PostProcessShader _shader =
new PostProcessShader(AssemblyUtility.ReadAssemblyFile(SMRenderer.PostProcessPath + ".bloom_blur.glsl"));
private const float _defaultTextureScale = .75f;
private static readonly PostProcessShader _filterShader = new PostProcessShader(
AssemblyUtility.ReadAssemblyFile(SMRenderer.PostProcessPath + ".bloom.filter.frag")
);
private static readonly PostProcessShader _downsampleShader = new PostProcessShader(
AssemblyUtility.ReadAssemblyFile(SMRenderer.PostProcessPath + ".bloom.downsample.frag")
);
private static readonly PostProcessShader _upsampleShader = new PostProcessShader(
AssemblyUtility.ReadAssemblyFile(SMRenderer.PostProcessPath + ".bloom.upsample.frag")
);
private static readonly PostProcessShader _combineShader = new PostProcessShader(
AssemblyUtility.ReadAssemblyFile(SMRenderer.PostProcessPath + ".bloom.combine.frag")
);
private Framebuffer _source;
static BloomEffect()
{
_upsampleShader.ShaderFiles.Fragment[0].GLSLExtensions.Add(samplingFile);
_combineShader.ShaderFiles.Fragment[0].GLSLExtensions.Add(samplingFile);
}
private Framebuffer _bloomBuffer1;
private Framebuffer _bloomBuffer2;
const int MAXBLOOMSTEPS = 8;
const float INTENSITY = .1f;
private readonly bool _hdr;
private readonly float _textureScale = .75f;
private List<Framebuffer> _downsampler;
private List<Framebuffer> _upsample;
private BezierCurve _weightCurve;
private float[] _weights;
private ColorAttachment _xBuffer;
private ColorAttachment _yBuffer;
private int _iterations;
private float _sampleSize;
private Vector4 _thresholdCurve;
private Color4 _bloomColor;
/// <summary>
/// A texture where you can define the amount of the bloom effect at each pixel.
/// </summary>
public TextureBase AmountMap;
/// <summary>
/// The transformation for the amount map.
/// </summary>
public TextureTransformation AmountTransform = new TextureTransformation();
/// <summary>
/// The maximal amount the amount map is clamped to.
/// <para>Default: 1</para>
/// </summary>
public float MaxAmount = 1;
/// <summary>
/// The minimal amount the amount map is clamped to.
/// <para>Default: 0</para>
/// </summary>
public float MinAmount = 0;
/// <summary>
/// The defines how often the x-y-flipflop happens.
/// <para>Default: 8</para>
/// </summary>
public int Iterations = 8;
/// <summary>
/// The Threshold for the bloom effect.
/// <para>Default: .8f</para>
/// The threshold, where the effect decided what is bright.
/// </summary>
public float Threshold = .8f;
/// <summary>
/// Increases the brightness of the resulting effect.
/// <para>Default: 1</para>
/// The radius of the effect.
/// </summary>
public float Power = 1;
public float Radius = 6.5f;
/// <summary>
/// Makes transition between under/over-threshold gradual.
/// </summary>
public float Knee = .5f;
/// <summary>
/// The intensity of the effect.
/// </summary>
public float Intensity = .5f;
/// <summary>
/// The tint of the effect.
/// </summary>
public Color4 Color = Color4.White;
/// <summary>
/// Radius of the effect
/// <para>Default: 2</para>
/// This creates a more prettier bloom effect.
/// </summary>
public float Radius = 1;
/// <summary>
/// This can disable the bloom calculation.
/// <para>Default: true</para>
/// </summary>
public bool Enable = true;
/// <summary>
/// This defines the weight curve.
/// </summary>
public BezierCurve WeightCurve
{
get => _weightCurve;
set
{
_weightCurve = value;
UpdateWeights();
}
}
/// <summary>
/// This defines how many picks the effect should pick from the weight curve.
/// </summary>
public int WeightCurvePickAmount = 4;
/// <summary>
/// This creates a bloom effect.
/// </summary>
/// <param name="source">This can specify a own source framebuffer. If not set, it will take the Pipeline MainFramebuffer.</param>
/// <param name="hdr">This allows to enable hdr returns.</param>
/// <param name="textureScale">This allows for a increase in performance, by lowering the calculating texture scale.</param>
public BloomEffect(Framebuffer source = null, bool hdr = false, float? textureScale = null)
public BloomEffect(bool hdr = false)
{
_source = source;
_hdr = hdr;
_textureScale = textureScale.GetValueOrDefault(_defaultTextureScale);
WeightCurve = _defaultCurve;
}
/// <inheritdoc/>
protected override void InitProcess() => CreateFramebuffers();
private void UpdateWeights()
private void CreateFramebuffers()
{
_weights = new float[WeightCurvePickAmount];
if (_downsampler != null) _downsampler.ForEach(a => a.Reset());
if (_upsample != null) _upsample.ForEach(a => a.Reset());
for (int i = 0; i < WeightCurvePickAmount; i++)
_weights[i] = _weightCurve.CalculatePoint((float) (i + 1) / (WeightCurvePickAmount + 1)).Y;
_downsampler = new List<Framebuffer>();
_upsample = new List<Framebuffer>();
Vector2 windowSize = Pipeline.ConnectedWindow.WindowSize;
float minDim = (float)Math.Min(windowSize.X, windowSize.Y);
float maxIter = (Radius - 8.0f) + (float)(Math.Log(minDim) / Math.Log(2));
int maxIterInt = (int)maxIter;
_iterations = Math.Max(Math.Min(MAXBLOOMSTEPS, maxIterInt), 1);
_sampleSize = .5f + maxIter - maxIterInt;
_thresholdCurve = new Vector4(
Threshold - Knee,
Knee * 2,
0.25f / Math.Max(1e-5f, Knee),
Threshold);
float intens = (Intensity * INTENSITY);
_bloomColor = new Color4(Color.R * intens, Color.G * intens, Color.B * intens, 1f);
PixelInformation pixel = new PixelInformation(PixelInternalFormat.R11fG11fB10f, PixelFormat.Rgb, PixelType.Float);
Vector2 texSize = windowSize;
Framebuffer f = new Framebuffer(texSize);
f.Append("0", new ColorAttachment(0, pixel));
f.Append("1", new ColorAttachment(1, pixel));
_downsampler.Add(f);
for (int i = 0; i < _iterations; i++)
{
texSize /= 2;
f = new Framebuffer(texSize);
f.Append("0", new ColorAttachment(0, pixel));
_downsampler.Add(f);
if (i == _iterations - 1) break;
f = new Framebuffer(texSize);
f.Append("0", new ColorAttachment(0, pixel));
_upsample.Add(f);
}
}
/// <inheritdoc/>
protected override void InitProcess()
public override void ScreenSizeChanged(IGenericWindow window)
{
_source ??= Pipeline.MainFramebuffer;
_source.ColorAttachments["color"].PixelInformation = PixelInformation.RGBA_HDR;
_bloomBuffer1 = new Framebuffer(Pipeline.ConnectedWindow, _textureScale)
{
Name = "BloomX"
};
_bloomBuffer1.Append("xBuffer", _xBuffer = new ColorAttachment(0, PixelInformation.RGBA_HDR));
_bloomBuffer1.Compile();
_bloomBuffer2 = new Framebuffer(Pipeline.ConnectedWindow, _textureScale)
{
Name = "BloomY"
};
_bloomBuffer2.Append("yBuffer", _yBuffer = new ColorAttachment(0, PixelInformation.RGBA_HDR));
_bloomBuffer2.Compile();
Pipeline.Framebuffers.Add(_bloomBuffer1);
Pipeline.Framebuffers.Add(_bloomBuffer2);
CreateFramebuffers();
}
/// <inheritdoc/>
public override void Draw(ColorAttachment source, DrawContext context)
protected override void Drawing(ColorAttachment source, DrawContext context)
{
if (Enable)
Framebuffer target = Framebuffer.GetCurrentlyActive();
// Filtering
_downsampler[0].Activate(true);
_filterShader.Draw(source, col =>
{
GL.Viewport(0, 0, (int) (Pipeline.ConnectedWindow.Width * _textureScale),
(int) (Pipeline.ConnectedWindow.Height * _textureScale));
col["ThresholdCurve"].SetVector4(_thresholdCurve);
});
Framebuffer target = Framebuffer.GetCurrentlyActive();
bool first = true, hoz = true;
int iter = Iterations * 2;
for (int i = 0; i < iter; i++)
{
(hoz ? _bloomBuffer1 : _bloomBuffer2).Activate(false);
// Downsampling
ColorAttachment last = _downsampler[0]["0"];
for(int i = 1; i < _iterations; i++)
{
ColorAttachment downsampleSource = last;
Framebuffer downsampleTarget = _downsampler[i];
downsampleTarget.Activate(true);
_downsampleShader.Draw(downsampleSource);
_shader.Draw(collection =>
{
collection["renderedTexture"].SetTexture(first ? source : (hoz ? _yBuffer : _xBuffer));
collection["First"].SetUniform1(first);
collection["Threshold"].SetUniform1(Threshold);
collection["Horizontal"].SetUniform1(hoz);
collection["Weights"].SetUniform1(_weights);
collection["WeightCount"].SetUniform1(WeightCurvePickAmount);
collection["Power"].SetUniform1(Power);
collection["Radius"].SetUniform1(_textureScale * Radius);
});
hoz = !hoz;
if (first) first = false;
}
GL.Viewport(Pipeline.ConnectedWindow.ClientRectangle);
target.Activate();
last = downsampleTarget["0"];
}
_mergeShader.Draw(collection =>
// Upsampling
for (int i = _iterations - 2; i >= 0; i--)
{
collection["Scene"].SetTexture(source);
collection["Bloom"].SetTexture(_yBuffer);
ColorAttachment downsampleSource = _downsampler[i]["0"];
Framebuffer upsampleTarget = _upsample[i];
collection["MinAmount"].SetUniform1(MinAmount);
collection["MaxAmount"].SetUniform1(MaxAmount);
collection["AmountMap"].SetTexture(AmountMap, collection["HasAmountMap"]);
collection["TextureTransform"].SetMatrix3(AmountTransform.GetMatrix());
upsampleTarget.Activate(true);
collection["Exposure"].SetUniform1(context.UseCamera.Exposure);
collection["HDR"].SetUniform1(_hdr);
_upsampleShader.Draw(last, (a) =>
{
if (last != null) a["baseBuffer"].SetTexture(downsampleSource);
a["sampleSize"].SetFloat(_sampleSize);
});
last = upsampleTarget["0"];
}
// combine
target.Activate(true);
_combineShader.Draw(last, (a) =>
{
a["sampleSize"].SetFloat(_sampleSize);
a["scene"].SetTexture(_downsampler[0]["1"]);
a["bloomColor"].SetColor(_bloomColor);
a["HDR"].SetBool(_hdr);
});
}
}

View file

@ -52,8 +52,8 @@ namespace SM.Base.PostEffects
{
_hdrExposureShader.Draw(u =>
{
u["Gamma"].SetUniform1(Gamma);
u["Exposure"].SetUniform1(exposure);
u["Gamma"].SetFloat(Gamma);
u["Exposure"].SetFloat(exposure);
u["Scene"].SetTexture(attachment);
});
}
@ -66,7 +66,7 @@ namespace SM.Base.PostEffects
{
_gammaShader.Draw(u =>
{
u["Gamma"].SetUniform1(Gamma);
u["Gamma"].SetFloat(Gamma);
u["Scene"].SetTexture(attachment);
});
}

View file

@ -0,0 +1,32 @@
#version 330 core
in vec2 vTexture;
uniform sampler2D scene;
uniform vec4 bloomColor;
uniform bool HDR;
vec3 safe_color(vec3 c) {
return clamp(c, vec3(0.0), vec3(1e20));
}
vec3 upsample_filter_high();
layout(location = 0) out vec4 color;
vec3 reinhardTone(vec3 col) {
return col / (col + vec3(1.0));
}
void main() {
vec3 scene = safe_color(texture2D(scene, vTexture).rgb);
vec3 blur = upsample_filter_high() * bloomColor.rgb;
if (HDR) {
color = vec4(scene + blur, 1);
return;
}
color = vec4(scene + reinhardTone(blur), 1);
}

View file

@ -0,0 +1,41 @@
#version 330 core
uniform vec2 renderedTextureTexelSize;
vec4 GetRenderColor();
vec4 GetRenderColorOffset(vec2);
float getBrightness(vec3 col) {
return max(col.r, max(col.g, col.b));
return (col.r + col.r + col.b + col.g + col.g + col.g) / 6.0;
}
layout(location = 0) out vec4 color;
vec3 downsample_high() {
vec4 d = renderedTextureTexelSize.xyxy * vec4(-1,-1, +1, +1);
vec3 s1 = GetRenderColorOffset(d.xy).rgb; // - -
// X -
vec3 s2 = GetRenderColorOffset(d.zy).rgb; // - -
// - X
vec3 s3 = GetRenderColorOffset(d.xw).rgb; // X -
// - -
vec3 s4 = GetRenderColorOffset(d.zw).rgb; // X -
// - -
float s1w = 1.0 / (getBrightness(s1) + 1.0);
float s2w = 1.0 / (getBrightness(s2) + 1.0);
float s3w = 1.0 / (getBrightness(s3) + 1.0);
float s4w = 1.0 / (getBrightness(s4) + 1.0);
float one_div = 1.0 / (s1w + s2w + s3w + s4w);
return (s1 * s1w + s2 * s2w + s3 * s3w + s4 * s4w) * one_div;
}
void main() {
color = vec4(downsample_high(),1);
}

View file

@ -0,0 +1,48 @@
#version 330 core
uniform vec4 ThresholdCurve;
uniform vec2 renderedTextureTexelSize;
vec4 GetRenderColorOffset(vec2);
layout(location = 0) out vec4 color;
layout(location = 1) out vec4 scene;
vec3 safe_color(vec3 c) {
return clamp(c, vec3(0.0), vec3(1e20));
}
vec3 median(vec3 a, vec3 b, vec3 c)
{
return a + b + c - min(min(a, b), c) - max(max(a, b), c);
}
float getBrightness(vec3 col) {
return max(col.r, max(col.g, col.b));
return (col.r + col.r + col.b + col.g + col.g + col.g) / 6.0;
}
void main() {
scene = vec4(safe_color(GetRenderColorOffset(vec2(0)).rgb), 1);
vec3 d = renderedTextureTexelSize.xyx * vec3(1,1,0);
vec3 s0 = scene.rgb + vec3(.1);
vec3 s1 = safe_color(GetRenderColorOffset(-d.xz).rgb) + vec3(.1);
vec3 s2 = safe_color(GetRenderColorOffset(+d.xz).rgb) + vec3(.1);
vec3 s3 = safe_color(GetRenderColorOffset(-d.zy).rgb) + vec3(.1);
vec3 s4 = safe_color(GetRenderColorOffset(+d.zy).rgb) + vec3(.1);
vec3 col = median(median(s0, s1, s2), s3, s4);
float br = getBrightness(col);
/*vec3 col = safe_color(GetRenderColor().rgb);
float br = getBrightness(col);*/
float rq = clamp(br - ThresholdCurve.x, 0, ThresholdCurve.y);
rq = ThresholdCurve.z * rq * rq;
float resultBr = max(rq, br - ThresholdCurve.w) / max(1e-5, br);
col *= resultBr;
color = vec4(col, 1);
}

View file

@ -0,0 +1,30 @@
#version 330 core
uniform vec2 renderedTextureTexelSize;
uniform float sampleSize;
vec4 GetRenderColorOffset(vec2);
vec3 upsample_filter_high() {
vec4 d = renderedTextureTexelSize.xyxy * vec4(1, 1,-1,0);
vec3 s;
// Line + 1
s = GetRenderColorOffset(d.zy).rgb; // x - -
s += GetRenderColorOffset(d.wy).rgb * 2; // - X -
s += GetRenderColorOffset(d.xy).rgb; // - - X
// Line 0
s += GetRenderColorOffset(d.zw).rgb * 2; // X - -
s += GetRenderColorOffset(vec2(0)).rgb * 4; // - X -
s += GetRenderColorOffset(d.xw).rgb * 2; // - - X
// Line - 1
s += GetRenderColorOffset(d.zz).rgb; // X - -
s += GetRenderColorOffset(d.wz).rgb * 2; // - X -
s += GetRenderColorOffset(d.xz).rgb; // - - X
return s * 0.0625; // 1 / 16 = 0.0625
}

View file

@ -0,0 +1,13 @@
#version 330 core
in vec2 vTexture;
uniform sampler2D baseBuffer;
layout(location = 0) out vec4 color;
vec3 upsample_filter_high();
void main() {
color = vec4(texture2D(baseBuffer, vTexture).rgb + upsample_filter_high(),1);
}

View file

@ -1,11 +0,0 @@
#version 330
layout(location = 1) in vec2 aTex;
uniform mat3 TextureTransform;
out vec2 TransformedTexture;
void vertex() {
TransformedTexture = vec2(TextureTransform * vec3(aTex, 1));
}

View file

@ -8,8 +8,28 @@ uniform float Gamma;
layout(location = 0) out vec4 color;
vec3 ACES(vec3 x) {
const float a = 2.51;
const float b = 0.03;
const float c = 2.43;
const float d = 0.59;
const float e = 0.14;
return clamp((x * (a * x + b)) / (x * (c * x + d) + e), 0,1.0);
}
vec3 reinhardTone(vec3 col) {
return col / (col + vec3(1.0));
}
vec3 exposure(vec3 scene) {
return vec3(1) - exp(-texture(Scene, vTexture).rgb * Exposure);
}
void main() {
vec3 result = vec3(1) - exp(-texture(Scene, vTexture).rgb * Exposure);
vec3 scene = texture2D(Scene, vTexture).rgb;
vec3 result = reinhardTone(scene);
color = vec4(pow(result, vec3(1 / Gamma)), 1);
}

View file

@ -24,6 +24,12 @@ namespace SM.Base.PostProcess
/// </summary>
protected RenderPipeline Pipeline;
/// <summary>
/// Enables the effect.
/// <para>Default: true</para>
/// </summary>
public bool Enable = true;
/// <summary>
/// Initialize the effect.
/// </summary>
@ -41,11 +47,20 @@ namespace SM.Base.PostProcess
{
}
/// <summary>
/// This executes
/// </summary>
/// <param name="source"></param>
/// <param name="context"></param>
public void Draw(ColorAttachment source, DrawContext context)
{
if (Enable) Drawing(source, context);
}
/// <summary>
/// Method to draw the actual effect.
/// </summary>
public abstract void Draw(ColorAttachment source, DrawContext context);
protected abstract void Drawing(ColorAttachment source, DrawContext context);
/// <summary>
/// Event, when the scene changed.
@ -53,5 +68,14 @@ namespace SM.Base.PostProcess
public virtual void SceneChanged(GenericScene scene)
{
}
/// <summary>
/// Event, when the screen size changed.
/// </summary>
/// <param name="window">Window that changed</param>
public virtual void ScreenSizeChanged(IGenericWindow window)
{
}
}
}

View file

@ -5,6 +5,7 @@ using System.Collections.Generic;
using OpenTK.Graphics.OpenGL4;
using SM.Base.Objects.Static;
using SM.Base.Utility;
using SM.OGL.Framebuffer;
using SM.OGL.Shaders;
#endregion
@ -25,6 +26,20 @@ namespace SM.Base.PostProcess
private static readonly string _normalVertexWithExt =
AssemblyUtility.ReadAssemblyFile("SM.Base.PostProcess.DefaultFiles.vertexWithExt.vert");
/// <summary>
/// Generates an action for the texture handling.
/// </summary>
/// <param name="renderedTexture"></param>
/// <returns></returns>
public static Action<UniformCollection> DefaultTextureAction(ColorAttachment renderedTexture)
{
return (col) =>
{
col["renderedTexture"].SetTexture(renderedTexture);
col["renderedTextureTexelSize"].SetVector2(renderedTexture.TexelSize);
};
}
/// <summary>
/// Creates the shader with the default vertex shader and custom fragment.
/// </summary>
@ -44,6 +59,14 @@ namespace SM.Base.PostProcess
}, new ShaderFile(fragment))
{
}
/// <summary>
/// Creates the shader with an vertex extension and custom fragment.
/// </summary>
/// <param name="vertex"></param>
/// <param name="fragment"></param>
public PostProcessShader(ShaderFile vertex, string fragment) : this(vertex, new ShaderFile(fragment))
{
}
private PostProcessShader(ShaderFile vertex, ShaderFile fragment) : base(
new ShaderFileCollection(vertex, fragment))
@ -51,6 +74,29 @@ namespace SM.Base.PostProcess
fragment.GLSLExtensions.Add(_fragExtensions);
}
/// <summary>
/// Draws the shader with the color attachment as texture.
/// </summary>
/// <param name="renderedTexture"></param>
public void Draw(ColorAttachment renderedTexture)
{
Draw(DefaultTextureAction(renderedTexture));
}
/// <summary>
/// Draws the shader with the color attachment as texture and provides access to the uniforms.
/// </summary>
/// <param name="renderedTexture"></param>
/// <param name="setUniformAction"></param>
public void Draw(ColorAttachment renderedTexture, Action<UniformCollection> setUniformAction)
{
var texAction = DefaultTextureAction(renderedTexture);
Draw((a) => {
texAction(a);
setUniformAction(a);
});
}
/// <summary>
/// Draws the shader with special uniforms.
/// </summary>

View file

@ -13,11 +13,12 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SM.Base</RootNamespace>
<AssemblyName>SM.Base</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@ -51,6 +52,7 @@
<Compile Include="Drawing\ShaderArguments.cs" />
<Compile Include="Drawing\TextureTransformation.cs" />
<Compile Include="Drawing\Text\Font.cs" />
<Compile Include="PostEffects\BloomEffect.cs" />
<Compile Include="PostEffects\PostProcessUtility.cs" />
<Compile Include="Scene\ICollectionItem.cs" />
<Compile Include="Scene\IFixedScriptable.cs" />
@ -61,6 +63,7 @@
<Compile Include="Types\CVector4.cs" />
<Compile Include="Types\CVectorBase.cs" />
<Compile Include="Utility\IInitializable.cs" />
<Compile Include="Utility\MathUtils.cs" />
<Compile Include="Utility\Ray.cs" />
<Compile Include="Utility\Util.cs" />
<Compile Include="Window\Contexts\DrawContext.cs" />
@ -71,7 +74,7 @@
<Compile Include="Objects\InstancedMesh.cs" />
<Compile Include="Objects\Mesh.cs" />
<Compile Include="Objects\Static\AxisHelper.cs" />
<Compile Include="PostEffects\BloomEffect.cs" />
<Compile Include="Legacy\PostProcessing\BloomEffectOld.cs" />
<Compile Include="PostProcess\PostProcessEffect.cs" />
<Compile Include="PostProcess\PostProcessShader.cs" />
<Compile Include="Scene\IScriptable.cs" />
@ -115,13 +118,12 @@
<EmbeddedResource Include="PostProcess\DefaultFiles\vertexWithExt.vert" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="PostEffects\Shaders\bloom_blur.glsl" />
<EmbeddedResource Include="PostEffects\Shaders\bloom_merge.glsl" />
<EmbeddedResource Include="Legacy\PostProcessing\bloom_blur.glsl" />
<EmbeddedResource Include="Legacy\PostProcessing\bloom_merge.glsl" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Shaders\SimpleShaderPresets\basic_vertex.glsl" />
<EmbeddedResource Include="Shaders\SimpleShaderPresets\instanced_vertex.glsl" />
<EmbeddedResource Include="PostEffects\Shaders\bloom_merge_vert.glsl" />
<EmbeddedResource Include="PostEffects\Shaders\finalize_hdr.glsl" />
<EmbeddedResource Include="PostEffects\Shaders\finalize_gamma.glsl" />
<EmbeddedResource Include="Shaders\Extensions\fragment\textureGamma.glsl" />
@ -139,7 +141,6 @@
<ItemGroup>
<Reference Include="OpenTK, Version=3.3.1.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL">
<HintPath>..\..\..\packages\OpenTK.3.3.1\lib\net20\OpenTK.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="SharpFont, Version=4.0.1.200, Culture=neutral, PublicKeyToken=48add4c483071cdf, processorArchitecture=MSIL">
<HintPath>..\..\..\packages\SharpFont.4.0.1\lib\net45\SharpFont.dll</HintPath>
@ -159,8 +160,14 @@
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Legacy\PostProcessing\bloom_merge.vert" />
<None Include="OpenTK.dll.config" />
<None Include="packages.config" />
<EmbeddedResource Include="PostEffects\Shaders\bloom\filter.frag" />
<EmbeddedResource Include="PostEffects\Shaders\bloom\downsample.frag" />
<EmbeddedResource Include="PostEffects\Shaders\bloom\upsample.frag" />
<EmbeddedResource Include="PostEffects\Shaders\bloom\combine.frag" />
<EmbeddedResource Include="PostEffects\Shaders\bloom\sampling.frag" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">

View file

@ -101,17 +101,19 @@ namespace SM.Base.Shaders
.SetMatrix4(context.Instances[0].ModelMatrix * context.ModelMatrix * context.View * context.World);
uniforms["MasterTextureMatrix"].SetMatrix3(context.Instances[0].TextureMatrix * context.TextureMatrix);
uniforms["HasVColor"]
.SetUniform1(context.Mesh.Attributes.Has("color"));
.SetBool(context.Mesh.Attributes.Has("color"));
DrawObject(context.ForcedType.GetValueOrDefault(context.Mesh.PrimitiveType), context.Mesh);
}
private static void InstancedSetUniforms(UniformCollection uniforms, DrawContext context)
{
if (context.Instances == null || context.Instances.Count < 1) return;
uniforms["MVP"].SetMatrix4(context.ModelMatrix * context.View * context.World);
uniforms["MasterTextureMatrix"].SetMatrix3(context.TextureMatrix);
uniforms["HasVColor"]
.SetUniform1(context.Mesh.Attributes.Has("color"));
.SetBool(context.Mesh.Attributes.Has("color"));
UniformArray instances = uniforms.GetArray("Instances");

View file

@ -1,5 +1,4 @@
#version 330
#define SM_SIMPLE_EXTENSION //!extension
layout(location = 0) in vec3 a_Position;
layout(location = 1) in vec2 a_Texture;
@ -13,10 +12,6 @@ out vec3 v_VertexPosition;
out vec2 v_TexCoords;
out vec4 v_Color;
#if (SM_SIMPLE_EXTENSION == 1)
void v_Extension();
#endif
void main() {
v_Color = vec4(1);
if (HasVColor) v_Color = a_Color;
@ -26,7 +21,5 @@ void main() {
v_VertexPosition = a_Position;
gl_Position = MVP * vec4(a_Position, 1);
#if (SM_SIMPLE_EXTENSION == 1)
v_Extension();
#endif
}

View file

@ -1,6 +1,5 @@
#version 330
#define maxInstances //!instanceMax
#define SM_SIMPLE_EXTENSION //!extension
struct Instance {
mat4 ModelMatrix;
@ -20,10 +19,6 @@ out vec3 v_VertexPosition;
out vec2 v_TexCoords;
out vec4 v_Color;
#if (SM_SIMPLE_EXTENSION == 1)
void v_Extension();
#endif
void main() {
v_Color = vec4(1);
if (HasVColor) v_Color = a_Color;
@ -33,7 +28,4 @@ void main() {
v_VertexPosition = a_Position;
gl_Position = MVP * Instances[gl_InstanceID].ModelMatrix * vec4(a_Position, 1);
#if (SM_SIMPLE_EXTENSION == 1)
v_Extension();
#endif
}

View file

@ -28,21 +28,6 @@ namespace SM.Base.Types
/// </summary>
public float X { get; set; }
/// <summary>
/// Interpolates the motion to the target.
/// </summary>
/// <param name="duration">How long the interpolation should take.</param>
/// <param name="to">The value it should interpolate.</param>
/// <param name="interpolationCurve">The curve how he interpolates. Preset values can be found under <see cref="AnimationCurves"/>. Default: <see cref="AnimationCurves.Linear"/></param>
/// <returns>A handle to control the interpolation process.</returns>
public InterpolationProcess Interpolate(TimeSpan duration, float to, BezierCurve? interpolationCurve = null)
{
InterpolationProcess process = new InterpolationProcess(this, duration, ConvertToVector4(), new Vector4(to, 0, 0, 0), interpolationCurve.GetValueOrDefault(AnimationCurves.Linear));
process.Start();
return process;
}
/// <summary>
/// Sets the X-Component.
/// </summary>

View file

@ -35,25 +35,6 @@ namespace SM.Base.Types
/// </summary>
public float Y { get; set; }
/// <summary>
/// Interpolates the motion to the target.
/// </summary>
/// <param name="duration">How long the interpolation should take.</param>
/// <param name="to">The value it should interpolate.</param>
/// <param name="interpolationCurve">The curve how he interpolates.
/// <para>When creating a curve, its recommended the Y-component is always between 0 -> 1. But it could make cool effects if not...</para>
/// <para>Preset curves can be found under <see cref="AnimationCurves"/>.</para>
/// <para>Default: <see cref="AnimationCurves.Linear"/></para>
/// </param>
/// <returns>A handle to control the interpolation process.</returns>
public InterpolationProcess Interpolate(TimeSpan duration, Vector2 to, BezierCurve? interpolationCurve = null)
{
InterpolationProcess process = new InterpolationProcess(this, duration, ConvertToVector4(), new Vector4(to), interpolationCurve.GetValueOrDefault(AnimationCurves.Linear));
process.Start();
return process;
}
/// <inheritdoc />
public override string ToString()
{

View file

@ -35,21 +35,6 @@ namespace SM.Base.Types
/// </summary>
public float Z { get; set; }
/// <summary>
/// Interpolates the motion to the target.
/// </summary>
/// <param name="duration">How long the interpolation should take.</param>
/// <param name="to">The value it should interpolate.</param>
/// <param name="interpolationCurve">The curve how he interpolates. Preset values can be found under <see cref="AnimationCurves"/>. Default: <see cref="AnimationCurves.Linear"/></param>
/// <returns>A handle to control the interpolation process.</returns>
public InterpolationProcess Interpolate(TimeSpan duration, Vector3 to, BezierCurve? interpolationCurve = null)
{
InterpolationProcess process = new InterpolationProcess(this, duration, ConvertToVector4(), new Vector4(to, 0), interpolationCurve.GetValueOrDefault(AnimationCurves.Linear));
process.Start();
return process;
}
/// <inheritdoc />
public override string ToString()

View file

@ -24,21 +24,6 @@ namespace SM.Base.Types
W = w;
}
/// <summary>
/// Interpolates the motion to the target.
/// </summary>
/// <param name="duration">How long the interpolation should take.</param>
/// <param name="to">The value it should interpolate.</param>
/// <param name="interpolationCurve">The curve how he interpolates. Preset values can be found under <see cref="AnimationCurves"/>. Default: <see cref="AnimationCurves.Linear"/></param>
/// <returns>A handle to control the interpolation process.</returns>
public InterpolationProcess Interpolate(TimeSpan duration, Vector4 to, BezierCurve? interpolationCurve = null)
{
InterpolationProcess process = new InterpolationProcess(this, duration, ConvertToVector4(), to, interpolationCurve.GetValueOrDefault(AnimationCurves.Linear));
process.Start();
return process;
}
/// <inheritdoc />
public override void Set(float uniform, bool triggerChanged = true)
{

View file

@ -1,5 +1,8 @@
using System;
using OpenTK;
using OpenTK.Audio.OpenAL;
using OpenTK.Graphics.OpenGL;
using SM.Base.Animation;
namespace SM.Base.Types
{
@ -48,6 +51,62 @@ namespace SM.Base.Types
NormalizationProcess(length);
}
/// <summary>
/// Interpolates the motion to the target.
/// </summary>
/// <param name="duration">How long the interpolation should take.</param>
/// <param name="to">The value it should interpolate.</param>
/// <param name="interpolationCurve">The curve how he interpolates. Preset values can be found under <see cref="AnimationCurves"/>. Default: <see cref="AnimationCurves.Linear"/></param>
/// <param name="autoStart">Auto-starts the interpolation process.</param>
/// <returns>A handle to control the interpolation process.</returns>
public InterpolationProcess Interpolate<TInterpolateType>(TimeSpan duration, TInterpolateType to, BezierCurve? interpolationCurve = null, bool autoStart = true)
where TInterpolateType : struct
{
return Interpolate<TInterpolateType>(duration, ConvertToVector4(), to, interpolationCurve, autoStart);
}
/// <summary>
/// Interpolates the motion to the target.
/// </summary>
/// <param name="duration">How long the interpolation should take.</param>
/// <param name="from">The value it should start with.</param>
/// <param name="to">The value it should interpolate.</param>
/// <param name="interpolationCurve">The curve how he interpolates. Preset values can be found under <see cref="AnimationCurves"/>. Default: <see cref="AnimationCurves.Linear"/></param>
/// <param name="autoStart">Auto-starts the interpolation process.</param>
/// <returns>A handle to control the interpolation process.</returns>
public InterpolationProcess Interpolate<TInterpolateType>(TimeSpan duration, TInterpolateType from, TInterpolateType to, BezierCurve? interpolationCurve = null, bool autoStart = true)
where TInterpolateType : struct
{
Vector4 start = from switch
{
float f => new Vector4(f, 0, 0, 0),
Vector2 v2 => new Vector4(v2.X, v2.Y, 0, 0),
Vector3 v3 => new Vector4(v3.X, v3.Y, v3.Z, 0),
Vector4 v4 => v4,
_ => throw new Exception("[INTERPOLATION] Only float, OpenTK.Vector2, OpenTK.Vector3, OpenTK.Vector4 are allowed as types.")
};
return Interpolate(duration, start, to, interpolationCurve, autoStart);
}
internal InterpolationProcess Interpolate<TInterpolateType>(TimeSpan duration, Vector4 from, TInterpolateType to, BezierCurve? interpolationCurve = null, bool autoStart = true)
where TInterpolateType : struct
{
Vector4 target = to switch
{
float f => new Vector4(f, 0, 0, 0),
Vector2 v2 => new Vector4(v2.X, v2.Y, 0, 0),
Vector3 v3 => new Vector4(v3.X, v3.Y, v3.Z, 0),
Vector4 v4 => v4,
_ => throw new Exception("[INTERPOLATION] Only float, OpenTK.Vector2, OpenTK.Vector3, OpenTK.Vector4 are allowed as types.")
};
InterpolationProcess process = new InterpolationProcess(this, duration, from, target, interpolationCurve.GetValueOrDefault(AnimationCurves.Linear));
if (autoStart) process.Start();
return process;
}
/// <summary>
/// Sets the values of the vector, by providing the values over an array.
/// </summary>

View file

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SM.Base.Utility
{
class MathUtils
{
public static float Lerp(float start, float end, float t)
{
return start + t * (end - start);
}
}
}

View file

@ -3,6 +3,7 @@
using System.Collections.Generic;
using System.Threading;
using SM.Base.Drawing;
using SM.Base.PostProcess;
using SM.Base.Shaders;
using SM.Base.Utility;
using SM.OGL.Framebuffer;
@ -17,6 +18,11 @@ namespace SM.Base.Window
/// </summary>
public abstract class RenderPipeline : IInitializable
{
/// <summary>
/// All post processing effects should go here, that should be automaticly managed.
/// </summary>
protected List<PostProcessEffect> PostProcessEffects = new List<PostProcessEffect>();
/// <summary>
/// This contains the windows its connected to.
/// </summary>
@ -47,9 +53,7 @@ namespace SM.Base.Window
/// <inheritdoc/>
public virtual void Activate()
{
}
{ }
/// <inheritdoc/>
public virtual void Initialization()
{
@ -73,11 +77,26 @@ namespace SM.Base.Window
/// <summary>
/// The event when resizing.
/// </summary>
public virtual void Resize()
public virtual void Resize(IGenericWindow window)
{
Recompile();
foreach (PostProcessEffect effect in PostProcessEffects)
{
effect.ScreenSizeChanged(window);
}
}
/// <summary>
/// Initilizes the collected post processing effects.
/// </summary>
protected void InitizePostProcessing()
{
foreach (PostProcessEffect effect in PostProcessEffects)
{
effect.Initilize(this);
}
}
/// <summary>
/// Compiles the framebuffers.
@ -116,11 +135,11 @@ namespace SM.Base.Window
public Framebuffer CreateWindowFramebuffer(int multisamples = 0, PixelInformation? pixelInformation = null, bool depth = true)
{
Framebuffer framebuffer = new(ConnectedWindow);
framebuffer.Append("color", new ColorAttachment(0, pixelInformation.GetValueOrDefault(PixelInformation.RGBA_LDR), multisamples));
framebuffer.Append("color", new ColorAttachment(0, pixelInformation.GetValueOrDefault(PixelInformation.RGBA_LDR), multisamples:multisamples));
if (depth)
{
RenderbufferAttachment depthAttach = RenderbufferAttachment.Depth;
RenderbufferAttachment depthAttach = RenderbufferAttachment.GenerateDepth();
depthAttach.Multisample = multisamples;
framebuffer.AppendRenderbuffer(depthAttach);
}

View file

@ -60,14 +60,17 @@ namespace SM.Base.Window
{
window.WindowSize = new Vector2(window.Width, window.Height);
window.AspectRatio = (float) window.Width / window.Height;
GL.Viewport(window.ClientRectangle);
window.CurrentRenderPipeline?.Resize();
if (window.WindowSize.LengthSquared == 0) return;
GL.Viewport(window.ClientRectangle);
PostProcessEffect.Mvp = Matrix4.CreateScale(window.Width, -window.Height, 1) *
Matrix4.LookAt(Vector3.UnitZ, Vector3.Zero, Vector3.UnitY) *
Matrix4.CreateOrthographic(window.Width, window.Height, .1f, 100f);
window.CurrentRenderPipeline?.Resize(window);
window.AppliedSetup?.Resize(window);
}

View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="OpenTK" version="3.3.1" targetFramework="net452" />
<package id="OpenTK" version="3.3.1" targetFramework="net471" />
<package id="SharpFont" version="4.0.1" targetFramework="net452" />
<package id="SharpFont.Dependencies" version="2.6" targetFramework="net452" />
</packages>

View file

@ -1,6 +1,7 @@
#region usings
using System;
using OpenTK;
using OpenTK.Graphics.OpenGL4;
using SM.OGL.Texture;
@ -21,6 +22,14 @@ namespace SM.OGL.Framebuffer
/// </summary>
public int AttachmentID { get; }
/// <summary>
/// Contains the framebuffer its connected.
/// <para>Usually the last framebuffer, that called the Compile-method.</para>
/// </summary>
public Framebuffer ConnectedFramebuffer { get; private set; }
public Vector2? AttachmentSize = null;
/// <summary>
/// Returns the <see cref="OpenTK.Graphics.OpenGL4.FramebufferAttachment"/> of this ColorAttachment.
/// </summary>
@ -47,7 +56,7 @@ namespace SM.OGL.Framebuffer
/// Creates a attachment with a specific id.
/// </summary>
/// <param name="attachmentId"></param>
public ColorAttachment(int attachmentId) : this(attachmentId, PixelInformation.RGBA_LDR)
public ColorAttachment(int attachmentId, Vector2? size = null) : this(attachmentId, PixelInformation.RGBA_LDR, size)
{ }
/// <summary>
@ -56,12 +65,16 @@ namespace SM.OGL.Framebuffer
/// <param name="attachmentID"></param>
/// <param name="pixelInformation"></param>
/// <param name="multisamples"></param>
public ColorAttachment(int attachmentID, PixelInformation pixelInformation, int multisamples = 0)
public ColorAttachment(int attachmentID, PixelInformation pixelInformation, Vector2? size = null, int multisamples = 0)
{
AttachmentID = attachmentID;
PixelInformation = pixelInformation;
AttachmentSize = size;
_multisamples = multisamples;
Target = IsMultisampled ? TextureTarget.Texture2DMultisample : TextureTarget.Texture2D;
WrapMode = TextureWrapMode.ClampToEdge;
}
/// <summary>
/// Generates the attachment.
@ -70,6 +83,7 @@ namespace SM.OGL.Framebuffer
public void Generate(Framebuffer f)
{
_id = GL.GenTexture();
ConnectedFramebuffer = f;
if (IsMultisampled) GenerateMultisampledTexture(f);
else GenerateTexture(f);
@ -77,29 +91,33 @@ namespace SM.OGL.Framebuffer
private void GenerateTexture(Framebuffer f)
{
GL.BindTexture(TextureTarget.Texture2D, _id);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInformation.InternalFormat,
(int)f.Size.X, (int)f.Size.Y,
0, PixelInformation.Format, PixelInformation.DataType, IntPtr.Zero);
Vector2 size = AttachmentSize.GetValueOrDefault(f.Size);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter,
(int)TextureMinFilter.Linear);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter,
(int)TextureMinFilter.Linear);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS,
(int)TextureParameterName.ClampToEdge);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT,
(int)TextureParameterName.ClampToEdge);
GL.BindTexture(TextureTarget.Texture2D, 0);
GenerateBaseTexture(size);
}
private void GenerateMultisampledTexture(Framebuffer f)
{
GL.BindTexture(TextureTarget.Texture2DMultisample, _id);
GL.TexImage2DMultisample(TextureTargetMultisample.Texture2DMultisample, _multisamples, PixelInformation.InternalFormat, (int)f.Size.X, (int)f.Size.Y, true);
GL.BindTexture(TextureTarget.Texture2DMultisample, 0);
Vector2 size = AttachmentSize.GetValueOrDefault(f.Size);
Width = (int)size.X;
Height = (int)size.Y;
const TextureTarget target = TextureTarget.Texture2DMultisample;
GL.BindTexture(target, _id);
GL.TexImage2DMultisample((TextureTargetMultisample)target, _multisamples, PixelInformation.InternalFormat,
Width, Height, true);
/*
GL.TexParameter(target, TextureParameterName.TextureMinFilter, (int)Filter);
GL.TexParameter(target, TextureParameterName.TextureMagFilter, (int)Filter);
GL.TexParameter(target, TextureParameterName.TextureWrapS,
(int)WrapMode);
GL.TexParameter(target, TextureParameterName.TextureWrapT,
(int)WrapMode);*/
GL.BindTexture(target, 0);
}
}
}

View file

@ -15,6 +15,10 @@ namespace SM.OGL.Framebuffer
/// </summary>
public class Framebuffer : GLObject
{
static Framebuffer CurrentlyActiveFramebuffer;
static Framebuffer CurrentlyActiveDrawFramebuffer;
static Framebuffer CurrentlyActiveReadFramebuffer;
/// <inheritdoc />
protected override bool AutoCompile { get; set; } = true;
@ -48,6 +52,8 @@ namespace SM.OGL.Framebuffer
public bool DefaultApplyViewport { get; set; } = true;
public ColorAttachment FirstColorAttachment { get; private set; }
/// <summary>
/// Contains all color attachments.
/// </summary>
@ -56,7 +62,7 @@ namespace SM.OGL.Framebuffer
/// <summary>
/// Contains the current renderbuffer attachments of the framebuffer.
/// </summary>
public Dictionary<RenderbufferAttachment, int> RenderbufferAttachments { get; } = new Dictionary<RenderbufferAttachment, int>();
public List<RenderbufferAttachment> RenderbufferAttachments { get; } = new List<RenderbufferAttachment>();
/// <summary>
/// Gets the color attachment with the specified color name.
@ -116,15 +122,19 @@ namespace SM.OGL.Framebuffer
foreach (var pair in ColorAttachments)
GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, pair.Value.FramebufferAttachment, pair.Value.Target, pair.Value.ID,
0);
FramebufferErrorCode err;
foreach (RenderbufferAttachment attachment in RenderbufferAttachments.Keys.ToArray())
err = GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer);
if (err != FramebufferErrorCode.FramebufferComplete)
throw new Exception("Failed loading framebuffer.\nProblem: " + err);
foreach (RenderbufferAttachment attachment in RenderbufferAttachments)
{
int att = attachment.Generate(this);
GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, attachment.FramebufferAttachment, RenderbufferTarget.Renderbuffer, att);
RenderbufferAttachments[attachment] = att;
attachment.Generate(this);
GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, attachment.FramebufferAttachment, RenderbufferTarget.Renderbuffer, attachment.ID);
}
var err = GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer);
err = GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer);
if (err != FramebufferErrorCode.FramebufferComplete)
throw new Exception("Failed loading framebuffer.\nProblem: " + err);
@ -132,15 +142,25 @@ namespace SM.OGL.Framebuffer
GL.BindTexture(TextureTarget.Texture2D, 0);
}
/// <summary>
/// Disposes and clears the attachment
/// </summary>
public void Reset()
{
Dispose();
ColorAttachments.Clear();
RenderbufferAttachments.Clear();
}
/// <inheritdoc />
public override void Dispose()
{
foreach (var attachment in ColorAttachments.Values) attachment.Dispose();
foreach (KeyValuePair<RenderbufferAttachment, int> pair in RenderbufferAttachments.ToArray())
FirstColorAttachment = null;
foreach (RenderbufferAttachment pair in RenderbufferAttachments.ToArray())
{
GL.DeleteRenderbuffer(pair.Value);
RenderbufferAttachments[pair.Key] = -1;
GL.DeleteRenderbuffer(pair.ID);
}
GL.DeleteFramebuffer(this);
base.Dispose();
@ -150,12 +170,14 @@ namespace SM.OGL.Framebuffer
/// <summary>
/// Appends a color attachment.
/// </summary>
public void Append(string key, int pos) => Append(key, new ColorAttachment(pos));
public void Append(string key, int pos) => Append(key, new ColorAttachment(pos, null));
public void Append(string key, Vector2 size, int pos) => Append(key, new ColorAttachment(pos, size));
/// <summary>
/// Appends a color attachment.
/// </summary>
public void Append(string key, ColorAttachment value)
{
if (ColorAttachments.Count == 0) FirstColorAttachment = value;
ColorAttachments.Add(key, value);
}
@ -165,7 +187,8 @@ namespace SM.OGL.Framebuffer
/// <param name="attachment"></param>
public void AppendRenderbuffer(RenderbufferAttachment attachment)
{
RenderbufferAttachments.Add(attachment, -1);
if (RenderbufferAttachments.Contains(attachment)) return;
RenderbufferAttachments.Add(attachment);
}
/// <summary>
@ -201,17 +224,55 @@ namespace SM.OGL.Framebuffer
/// <param name="clear"></param>
public void Activate(FramebufferTarget target, ClearBufferMask clear, bool? applyViewport = null)
{
switch (target)
{
case FramebufferTarget.ReadFramebuffer:
CurrentlyActiveReadFramebuffer = this;
break;
case FramebufferTarget.DrawFramebuffer:
CurrentlyActiveDrawFramebuffer = this;
break;
case FramebufferTarget.Framebuffer:
CurrentlyActiveFramebuffer = this;
break;
}
GL.BindFramebuffer(target, this);
if (applyViewport.GetValueOrDefault(DefaultApplyViewport)) GL.Viewport(0, 0, (int)Size.X, (int)Size.Y);
if (applyViewport.GetValueOrDefault(DefaultApplyViewport))
GL.Viewport(0, 0, (int)Size.X, (int)Size.Y);
GL.Clear(clear);
}
/// <summary>
/// Copies content to the specified Framebuffer.
/// </summary>
public void CopyTo(Framebuffer target, ClearBufferMask clear = ClearBufferMask.ColorBufferBit, BlitFramebufferFilter filter = BlitFramebufferFilter.Linear)
{
Activate(FramebufferTarget.ReadFramebuffer, false);
target.Activate(FramebufferTarget.DrawFramebuffer, false);
GL.BlitFramebuffer(0, 0, (int)Size.X, (int)Size.Y, 0, 0, (int)Size.X, (int)Size.Y, clear, filter);
}
/// <summary>
/// Returns a <see cref="Framebuffer"/> handle of the current framebuffer.
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
public static Framebuffer GetCurrentlyActive(FramebufferTarget target = FramebufferTarget.Framebuffer)
{
switch (target)
{
case FramebufferTarget.ReadFramebuffer:
return CurrentlyActiveReadFramebuffer ??= getCurrentlyActive(target);
case FramebufferTarget.DrawFramebuffer:
return CurrentlyActiveDrawFramebuffer ??= getCurrentlyActive(target);
case FramebufferTarget.Framebuffer:
return CurrentlyActiveFramebuffer ??= getCurrentlyActive(target);
}
return null;
}
static Framebuffer getCurrentlyActive(FramebufferTarget target = FramebufferTarget.Framebuffer)
{
Framebuffer buffer = new Framebuffer()
{
@ -232,6 +293,8 @@ namespace SM.OGL.Framebuffer
break;
}
return buffer;
}
}

View file

@ -5,12 +5,12 @@ namespace SM.OGL.Framebuffer
/// <summary>
/// Describes a renderbuffer attachment.
/// </summary>
public struct RenderbufferAttachment
public class RenderbufferAttachment
{
/// <summary>
/// Preset for the depthbuffer attachment.
/// </summary>
public static readonly RenderbufferAttachment Depth = new RenderbufferAttachment(RenderbufferStorage.Depth24Stencil8, FramebufferAttachment.DepthStencilAttachment);
public static RenderbufferAttachment GenerateDepth() => new RenderbufferAttachment(RenderbufferStorage.Depth24Stencil8, FramebufferAttachment.DepthStencilAttachment);
/// <summary>
/// Storage describes the internal format for the renderbuffer.
@ -26,6 +26,11 @@ namespace SM.OGL.Framebuffer
/// </summary>
public int Multisample;
/// <summary>
/// The id that was given to the renderbuffer.
/// </summary>
public int ID;
/// <summary>
/// Constructor
/// </summary>
@ -34,6 +39,8 @@ namespace SM.OGL.Framebuffer
Storage = storage;
FramebufferAttachment = framebufferAttachment;
Multisample = multisample;
ID = -1;
}
/// <summary>
@ -41,18 +48,38 @@ namespace SM.OGL.Framebuffer
/// </summary>
/// <param name="f">The framebuffer</param>
/// <returns>The ID of the renderbuffer.</returns>
public int Generate(Framebuffer f)
public void Generate(Framebuffer f)
{
int rb = GL.GenRenderbuffer();
ID = GL.GenRenderbuffer();
GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, rb);
GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, ID);
if (Multisample != 0)
GL.RenderbufferStorageMultisample(RenderbufferTarget.Renderbuffer, Multisample, Storage, (int)f.Size.X, (int)f.Size.Y);
else
GL.RenderbufferStorage(RenderbufferTarget.Renderbuffer, Storage, (int)f.Size.X, (int)f.Size.Y);
GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, 0);
}
/// <summary>
/// Disposes the renderbuffer.
/// </summary>
public void Dispose()
{
return rb;
GL.DeleteRenderbuffer(ID);
ID = -1;
}
/// <inheritdoc/>
public override bool Equals(object obj)
{
if (obj is RenderbufferAttachment ra)
{
if (ra.FramebufferAttachment == FramebufferAttachment) return true;
return false;
}
return false;
}
}
}

View file

@ -136,7 +136,7 @@ namespace SM.OGL
/// </summary>
public static void DisposeMarkedObjects()
{
foreach (GLObject o in _disposableObjects)
foreach (GLObject o in _disposableObjects.ToArray())
{
o.Dispose();
}

View file

@ -9,9 +9,10 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SM.OGL</RootNamespace>
<AssemblyName>SM.OGL</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>

View file

@ -19,7 +19,7 @@ namespace SM.OGL.Shaders
/// <summary>
/// Contains the different files for the shader.
/// </summary>
protected ShaderFileCollection ShaderFileFiles;
public ShaderFileCollection ShaderFiles;
/// <summary>
/// Contains and manage the uniforms from the shader.
@ -67,7 +67,7 @@ namespace SM.OGL.Shaders
Console.WriteLine();
ShaderFileFiles = new ShaderFileCollection(vertex,fragment, geometry);
ShaderFiles = new ShaderFileCollection(vertex,fragment, geometry);
}
/// <summary>
@ -80,7 +80,7 @@ namespace SM.OGL.Shaders
/// <inheritdoc />
protected GenericShader(ShaderFileCollection shaderFileFiles)
{
ShaderFileFiles = shaderFileFiles;
ShaderFiles = shaderFileFiles;
}
/// <inheritdoc />
@ -92,7 +92,7 @@ namespace SM.OGL.Shaders
/// <param name="newShaderFiles"></param>
public void Update(ShaderFileCollection newShaderFiles)
{
ShaderFileFiles = newShaderFiles;
ShaderFiles = newShaderFiles;
Recompile();
}
@ -103,9 +103,9 @@ namespace SM.OGL.Shaders
{
_id = GL.CreateProgram();
ShaderFileFiles.Append(this);
ShaderFiles.Append(this);
GL.LinkProgram(_id);
ShaderFileFiles.Detach(this);
ShaderFiles.Detach(this);
Uniforms = new UniformCollection {ParentShader = this};
Uniforms.Import(this);

View file

@ -24,6 +24,7 @@ namespace SM.OGL.Shaders
/// </summary>
public UniformCollection Parent { get; }
#region Constructors
/// <summary>
/// This creates a new uniform manager, that has a null parent.
/// </summary>
@ -63,289 +64,372 @@ namespace SM.OGL.Shaders
Parent = parent;
}
#endregion
#region Uniform1
public void SetUniform1(bool value)
/// <summary>
/// Set a boolean as value.
/// </summary>
/// <param name="value"></param>
public void SetBool(bool value)
{
GL.Uniform1(Location, value ? 1 : 0);
}
public void SetUniform1(int value)
/// <summary>
/// Sets a integer.
/// </summary>
/// <param name="value"></param>
public void SetInt(int value)
{
GL.Uniform1(Location, value);
}
public void SetUniform1(params int[] values)
/// <summary>
/// Sets an array of integers.
/// </summary>
/// <param name="values"></param>
public void SetInt(params int[] values)
{
GL.Uniform1(Location, values.Length, values);
}
public void SetUniform1(int count, ref int values)
{
GL.Uniform1(Location, count, ref values);
}
public void SetUniform1(uint value)
/// <summary>
/// Set a unsigned integer.
/// </summary>
/// <param name="value"></param>
public void SetUInt(uint value)
{
GL.Uniform1(Location, value);
}
public void SetUniform1(params uint[] values)
/// <summary>
/// Set an array of unsigned integers.
/// </summary>
/// <param name="values"></param>
public void SetUInt(params uint[] values)
{
GL.Uniform1(Location, values.Length, values);
}
public void SetUniform1(int count, ref uint values)
{
GL.Uniform1(Location, count, ref values);
}
public void SetUniform1(float value)
/// <summary>
/// Sets a float.
/// </summary>
/// <param name="value"></param>
public void SetFloat(float value)
{
GL.Uniform1(Location, value);
}
public void SetUniform1(params float[] values)
/// <summary>
/// Sets an array of floats.
/// </summary>
/// <param name="values"></param>
public void SetFloat(params float[] values)
{
GL.Uniform1(Location, values.Length, values);
}
public void SetUniform1(int count, ref float value)
{
GL.Uniform1(Location, count, ref value);
}
public void SetUniform1(double value)
{
GL.Uniform1(Location, value);
}
public void SetUniform1(params double[] values)
{
GL.Uniform1(Location, values.Length, values);
}
public void SetUniform1(int count, ref double value)
{
GL.Uniform1(Location, count, ref value);
}
#endregion
#region Uniform2
public void SetUniform2(float x, float y)
/// <summary>
/// Sets a float vector2 by providing the values.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
public void SetVector2(float x, float y)
{
GL.Uniform2(Location, x, y);
}
public void SetUniform2(double x, double y)
/// <summary>
/// Sets a unsigned integer vector2 by providing the values.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
public void SetVector2(uint x, uint y)
{
GL.Uniform2(Location, x, y);
}
public void SetUniform2(uint x, uint y)
/// <summary>
/// Sets a integer vector2 by providing the values.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
public void SetVector2(int x, int y)
{
GL.Uniform2(Location, x, y);
}
public void SetUniform2(int x, int y)
{
GL.Uniform2(Location, x, y);
}
public void SetUniform2(params float[] values)
{
GL.Uniform2(Location, values.Length / 2, values);
}
public void SetUniform2(params double[] values)
{
GL.Uniform2(Location, values.Length / 2, values);
}
public void SetUniform2(params int[] values)
{
GL.Uniform2(Location, values.Length / 2, values);
}
public void SetUniform2(params uint[] values)
{
GL.Uniform2(Location, values.Length / 2, values);
}
public void SetUniform2(int count, ref float values)
{
GL.Uniform2(Location, count, ref values);
}
public void SetUniform2(int count, ref double values)
{
GL.Uniform2(Location, count, ref values);
}
public void SetUniform2(int count, ref uint values)
{
GL.Uniform2(Location, count, ref values);
}
public void SetUniform2(Vector2 vector2)
/// <summary>
/// Sets a float vector2.
/// </summary>
/// <param name="vector2"></param>
public void SetVector2(Vector2 vector2)
{
GL.Uniform2(Location, vector2);
}
public void SetUniform2(ref Vector2 vector2)
/// <summary>
/// Sets a float vector2 by refencing.
/// </summary>
/// <param name="vector2"></param>
public void SetVector2(ref Vector2 vector2)
{
GL.Uniform2(Location, ref vector2);
}
/// <summary>
/// Sets a array of vector2.
/// </summary>
/// <param name="values"></param>
public void SetVector2(params Vector2[] values)
{
float[] newValues = new float[values.Length * 2];
for(int i = 0; i < values.Length; i++)
{
Vector2 val = values[i];
int newi = i * 2;
newValues[newi] = val.X;
newValues[newi + 1] = val.Y;
}
GL.Uniform2(Location, values.Length, newValues);
}
/// <summary>
/// Sets a float array that get converted to a vector2 array.
/// </summary>
/// <param name="values"></param>
public void SetVector2(params float[] values)
{
GL.Uniform2(Location, values.Length / 2, values);
}
/// <summary>
/// Sets a integer array that get converted to a ivector2 array.
/// </summary>
/// <param name="values"></param>
public void SetVector2(params int[] values)
{
GL.Uniform2(Location, values.Length / 2, values);
}
/// <summary>
/// Sets a unsigned integer array that get converted to a unsigned integer vector2 array.
/// </summary>
/// <param name="values"></param>
public void SetVector2(params uint[] values)
{
GL.Uniform2(Location, values.Length / 2, values);
}
#endregion
#region Uniform3
public void SetUniform3(float x, float y, float z)
/// <summary>
/// Sets a float vector3 by providing the values.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="z"></param>
public void SetVector3(float x, float y, float z)
{
GL.Uniform3(Location, x, y, z);
}
public void SetUniform3(double x, double y, double z)
/// <summary>
/// Sets a unsigned integer vector3 by providing the values.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="z"></param>
public void SetVector3(uint x, uint y, uint z)
{
GL.Uniform3(Location, x, y, z);
}
public void SetUniform3(uint x, uint y, uint z)
/// <summary>
/// Sets a integer vector3 by providing the values.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="z"></param>
public void SetVector3(int x, int y, int z)
{
GL.Uniform3(Location, x, y, z);
}
public void SetUniform3(int x, int y, int z)
{
GL.Uniform3(Location, x, y, z);
}
public void SetUniform3(params float[] values)
{
GL.Uniform3(Location, values.Length / 3, values);
}
public void SetUniform3(params double[] values)
{
GL.Uniform3(Location, values.Length / 3, values);
}
public void SetUniform3(params int[] values)
{
GL.Uniform3(Location, values.Length / 3, values);
}
public void SetUniform3(params uint[] values)
{
GL.Uniform3(Location, values.Length / 3, values);
}
public void SetUniform3(int count, ref float values)
{
GL.Uniform3(Location, count, ref values);
}
public void SetUniform3(int count, ref double values)
{
GL.Uniform3(Location, count, ref values);
}
public void SetUniform3(int count, ref uint values)
{
GL.Uniform3(Location, count, ref values);
}
public void SetUniform3(Vector3 vector)
/// <summary>
/// Sets a vector3.
/// </summary>
/// <param name="vector"></param>
public void SetVector3(Vector3 vector)
{
GL.Uniform3(Location, vector);
}
public void SetUniform3(ref Vector3 vector)
/// <summary>
/// Sets a vector3 by reference.
/// </summary>
/// <param name="vector"></param>
public void SetVector3(ref Vector3 vector)
{
GL.Uniform3(Location, ref vector);
}
/// <summary>
/// Sets a array of vector3.
/// </summary>
/// <param name="values"></param>
public void SetVector3(params Vector3[] values)
{
float[] newValues = new float[values.Length * 3];
for (int i = 0; i < values.Length; i++)
{
Vector3 val = values[i];
int newi = i * 3;
newValues[newi] = val.X;
newValues[newi + 1] = val.Y;
newValues[newi + 2] = val.Z;
}
GL.Uniform3(Location, values.Length, newValues);
}
/// <summary>
/// Sets a array by providing the components.
/// </summary>
/// <param name="values"></param>
public void SetVector3(params float[] values)
{
GL.Uniform3(Location, values.Length / 3, values);
}
/// <summary>
/// Sets a array by providing the components.
/// </summary>
/// <param name="values"></param>
public void SetVector3(params int[] values)
{
GL.Uniform3(Location, values.Length / 3, values);
}
/// <summary>
/// Sets a array by providing the components.
/// </summary>
/// <param name="values"></param>
public void SetVector3(params uint[] values)
{
GL.Uniform3(Location, values.Length / 3, values);
}
#endregion
#region Uniform4
public void SetUniform4(float x, float y, float z, float w)
/// <summary>
/// Sets a vector4 by providing the values.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="z"></param>
/// <param name="w"></param>
public void SetVector4(float x, float y, float z, float w)
{
GL.Uniform4(Location, x, y, z, w);
}
/// <summary>
/// Sets a vector4 by providing the values.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="z"></param>
/// <param name="w"></param>
public void SetVector4(uint x, uint y, uint z, uint w)
{
GL.Uniform4(Location, x, y, z, w);
}
/// <summary>
/// Sets a vector4 by providing the values.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="z"></param>
/// <param name="w"></param>
public void SetVector4(int x, int y, int z, int w)
{
GL.Uniform4(Location, x, y, z, w);
}
public void SetUniform4(double x, double y, double z, double w)
{
GL.Uniform4(Location, x, y, z, w);
}
public void SetUniform4(uint x, uint y, uint z, uint w)
{
GL.Uniform4(Location, x, y, z, w);
}
public void SetUniform4(int x, int y, int z, int w)
{
GL.Uniform4(Location, x, y, z, w);
}
public void SetUniform4(params float[] values)
{
GL.Uniform4(Location, values.Length / 4, values);
}
public void SetUniform4(params double[] values)
{
GL.Uniform4(Location, values.Length / 4, values);
}
public void SetUniform4(params int[] values)
{
GL.Uniform4(Location, values.Length / 4, values);
}
public void SetUniform4(params uint[] values)
{
GL.Uniform4(Location, values.Length / 4, values);
}
public void SetUniform4(int count, ref float values)
{
GL.Uniform4(Location, count, ref values);
}
public void SetUniform4(int count, ref double values)
{
GL.Uniform4(Location, count, ref values);
}
public void SetUniform4(int count, ref uint values)
{
GL.Uniform4(Location, count, ref values);
}
public void SetUniform4(Vector4 vector)
/// <summary>
/// Sets a vector4.
/// </summary>
/// <param name="vector"></param>
public void SetVector4(Vector4 vector)
{
GL.Uniform4(Location, vector);
}
public void SetUniform4(ref Vector4 vector)
/// <summary>
/// Sets a vector4.
/// </summary>
/// <param name="vector"></param>
public void SetVector4(ref Vector4 vector)
{
GL.Uniform4(Location, ref vector);
}
public void SetUniform4(Color4 color)
/// <summary>
/// Sets a array of Vector4.
/// </summary>
/// <param name="values"></param>
public void SetVector4(params Vector4[] values)
{
GL.Uniform4(Location, color);
float[] newValues = new float[values.Length * 4];
for (int i = 0; i < values.Length; i++)
{
Vector4 val = values[i];
int newi = i * 3;
newValues[newi] = val.X;
newValues[newi + 1] = val.Y;
newValues[newi + 2] = val.Z;
newValues[newi + 3] = val.W;
}
GL.Uniform3(Location, values.Length, newValues);
}
public void SetUniform4(Quaternion quaternion)
/// <summary>
/// Sets a array by providing the components.
/// </summary>
/// <param name="values"></param>
public void SetVector4(params float[] values)
{
GL.Uniform4(Location, values.Length / 4, values);
}
/// <summary>
/// Sets a array by providing the components.
/// </summary>
/// <param name="values"></param>
public void SetVector4(params int[] values)
{
GL.Uniform4(Location, values.Length / 4, values);
}
/// <summary>
/// Sets a array by providing the components.
/// </summary>
/// <param name="values"></param>
public void SetVector4(params uint[] values)
{
GL.Uniform4(Location, values.Length / 4, values);
}
/// <summary>
/// Sets a quaternion.
/// </summary>
/// <param name="quaternion"></param>
public void SetQuaternion(Quaternion quaternion)
{
GL.Uniform4(Location, quaternion);
}
@ -354,26 +438,22 @@ namespace SM.OGL.Shaders
#region Matrix2
/// <summary>
/// Sets a matrix2.
/// </summary>
/// <param name="matrix"></param>
/// <param name="transpose">If true, the matrix will be transposed.</param>
public void SetMatrix2(Matrix2 matrix, bool transpose = false)
{
GL.UniformMatrix2(Location, transpose, ref matrix);
}
public void SetMatrix2(int count, ref double value, bool transpose = false)
{
GL.UniformMatrix2(Location, count, transpose, ref value);
}
public void SetMatrix2(int count, ref float value, bool transpose = false)
{
GL.UniformMatrix2(Location, count, transpose, ref value);
}
public void SetMatrix2(int count, double[] value, bool transpose = false)
{
GL.UniformMatrix2(Location, count, transpose, value);
}
/// <summary>
/// Sets a matrix2 array.
/// </summary>
/// <param name="count"></param>
/// <param name="value"></param>
/// <param name="transpose">If true, the matrix will be transposed.</param>
public void SetMatrix2(int count, float[] value, bool transpose = false)
{
GL.UniformMatrix2(Location, count, transpose, value);
@ -382,27 +462,22 @@ namespace SM.OGL.Shaders
#endregion
#region Matrix3
/// <summary>
/// Sets a matrix3.
/// </summary>
/// <param name="matrix"></param>
/// <param name="transpose">If true, the matrix will be transposed.</param>
public void SetMatrix3(Matrix3 matrix, bool transpose = false)
{
GL.UniformMatrix3(Location, transpose, ref matrix);
}
public void SetMatrix3(int count, ref double value, bool transpose = false)
{
GL.UniformMatrix3(Location, count, transpose, ref value);
}
public void SetMatrix3(int count, ref float value, bool transpose = false)
{
GL.UniformMatrix3(Location, count, transpose, ref value);
}
public void SetMatrix3(int count, double[] value, bool transpose = false)
{
GL.UniformMatrix3(Location, count, transpose, value);
}
/// <summary>
/// Sets a matrix3 array.
/// </summary>
/// <param name="count"></param>
/// <param name="value"></param>
/// <param name="transpose">If true, the matrix will be transposed.</param>
public void SetMatrix3(int count, float[] value, bool transpose = false)
{
GL.UniformMatrix3(Location, count, transpose, value);
@ -412,31 +487,31 @@ namespace SM.OGL.Shaders
#region Matrix4
/// <summary>
/// Sets a matrix4.
/// </summary>
/// <param name="matrix"></param>
/// <param name="transpose">If true, the matrix will be transposed.</param>
public void SetMatrix4(Matrix4 matrix, bool transpose = false)
{
GL.UniformMatrix4(Location, transpose, ref matrix);
}
/// <summary>
/// Sets a matrix4 by reference.
/// </summary>
/// <param name="matrix"></param>
/// <param name="transpose">If true, the matrix will be transposed.</param>
public void SetMatrix4(ref Matrix4 matrix, bool transpose = false)
{
GL.UniformMatrix4(Location, transpose, ref matrix);
}
public void SetMatrix4(int count, ref double value, bool transpose = false)
{
GL.UniformMatrix4(Location, count, transpose, ref value);
}
public void SetMatrix4(int count, ref float value, bool transpose = false)
{
GL.UniformMatrix4(Location, count, transpose, ref value);
}
public void SetMatrix4(int count, double[] value, bool transpose = false)
{
GL.UniformMatrix4(Location, count, transpose, value);
}
/// <summary>
/// Sets a matrix4 array.
/// </summary>
/// <param name="count"></param>
/// <param name="value"></param>
/// <param name="transpose">If true, the matrix will be transposed.</param>
public void SetMatrix4(int count, float[] value, bool transpose = false)
{
GL.UniformMatrix4(Location, count, transpose, value);
@ -444,6 +519,15 @@ namespace SM.OGL.Shaders
#endregion
/// <summary>
/// Sets the color.
/// </summary>
/// <param name="color"></param>
public void SetColor(Color4 color)
{
GL.Uniform4(Location, color);
}
/// <summary>
/// Try to sets the texture at the next possible position and tells the checkUniform, if worked or not.
/// </summary>
@ -451,7 +535,7 @@ namespace SM.OGL.Shaders
/// <param name="checkUniform">The check uniform.</param>
public void SetTexture(TextureBase texture, Uniform checkUniform)
{
checkUniform.SetUniform1(texture != null);
checkUniform.SetBool(texture != null);
if (texture != null) SetTexture(texture);
}
@ -463,7 +547,7 @@ namespace SM.OGL.Shaders
/// <param name="checkUniform">The check uniform.</param>
public void SetTexture(TextureBase texture, int pos, Uniform checkUniform)
{
checkUniform.SetUniform1(texture != null);
checkUniform.SetBool(texture != null);
if (texture != null) SetTexture(texture);
}
@ -486,7 +570,7 @@ namespace SM.OGL.Shaders
Parent.NextTexture = texturePos + 1;
GL.ActiveTexture(TextureUnit.Texture0 + texturePos);
GL.BindTexture(texture.Target, texture);
SetUniform1(texturePos);
SetInt(texturePos);
}
/// <summary>

View file

@ -1,6 +1,8 @@
#region usings
using OpenTK;
using OpenTK.Graphics.OpenGL4;
using System;
#endregion
@ -10,6 +12,7 @@ namespace SM.OGL.Texture
/// Works as a basis for textures.
/// </summary>
public abstract class TextureBase : GLObject
{
/// <inheritdoc />
protected override bool AutoCompile { get; set; } = true;
@ -50,11 +53,35 @@ namespace SM.OGL.Texture
/// </summary>
public virtual int Height { get; protected set; }
public Vector2 Size => new Vector2(Width, Height);
public Vector2 TexelSize => new Vector2(1f / Width, 1f / Height);
/// <inheritdoc />
public override void Dispose()
{
GL.DeleteTexture(_id);
base.Dispose();
}
protected void GenerateBaseTexture(Vector2 size)
{
Width = (int)size.X;
Height = (int)size.Y;
GL.BindTexture(TextureTarget.Texture2D, _id);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInformation.InternalFormat,
Width, Height, 0,
PixelInformation.Format, PixelInformation.DataType, IntPtr.Zero);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)Filter);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)Filter);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS,
(int)WrapMode);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT,
(int)WrapMode);
GL.BindTexture(TextureTarget.Texture2D, 0);
}
}
}

View file

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="OpenTK" version="3.3.1" targetFramework="net452" />
<package id="OpenTK" version="3.3.1" targetFramework="net471" />
</packages>

View file

@ -8,9 +8,10 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SM2D</RootNamespace>
<AssemblyName>SMRenderer2D</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@ -30,9 +31,13 @@
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<AutoGenerateBindingRedirects>false</AutoGenerateBindingRedirects>
</PropertyGroup>
<ItemGroup>
<Reference Include="OpenTK, Version=3.3.1.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL">
<HintPath>..\..\..\packages\OpenTK.3.3.1\lib\net20\OpenTK.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />

View file

@ -18,7 +18,7 @@ namespace SM2D.Shader
static void SetUniforms(UniformCollection uniforms, DrawContext context)
{
uniforms["Tint"].SetUniform4(context.Material.Tint);
uniforms["Tint"].SetColor(context.Material.Tint);
uniforms["Texture"].SetTexture(context.Material.Texture, uniforms["UseTexture"]);
}
}

View file

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="OpenTK" version="3.3.1" targetFramework="net452" />
<package id="OpenTK" version="3.3.1" targetFramework="net471" />
</packages>

View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/>
</startup>
</configuration>

View file

@ -0,0 +1,10 @@
#version 330 core
uniform vec4 Color;
uniform float Scale;
layout(location = 0) out vec4 color;
void main() {
color = Color * Scale;
}

View file

@ -3,15 +3,20 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using ShaderToolParser;
using SharpDX.XInput;
using SM.Base;
using SM.Base.Animation;
using SM.Base.Controls;
using SM.Base.Drawing;
using SM.Base.Drawing.Text;
using SM.Base.Shaders;
using SM.Base.Time;
using SM.Base.Utility;
using SM.Base.Window;
using SM.Intergrations.ShaderTool;
using SM.Utils.Controls;
@ -28,25 +33,25 @@ namespace SM_TEST
{
static Scene scene;
private static GLWindow window;
private static PolyLine line;
private static GameController controller;
private static ItemCollection test;
private static DrawParticles particles;
private static InterpolationProcess interpolation;
private static GameKeybindActor actor;
public static STPProject portal;
static void Main(string[] args)
{
static void Main(string[] args){
Font font = new Font(@".\GapSansBold.ttf")
{
FontSize = 51,
CharSet = new char[]
{
'I', 'A','M','T','W','O'
}
};
font.RegenerateTexture();
controller = new GameController(0);
GameKeybindHost host = new GameKeybindHost(new GameKeybindList()
{
{"g_test", context => Keyboard.IsAnyKeyPressed, context => context.ControllerState.Buttons[GamepadButtonFlags.A, true]}
});
actor = GameKeybindActor.CreateControllerActor(controller);
actor.ConnectHost(host);
portal = STPProject.CreateFromZIP("portal.zip");
@ -58,18 +63,45 @@ namespace SM_TEST
{
ShowAxisHelper = true
});
scene.Background.Color = Color4.Red;
//scene.Background.Color = Color4.Red;
scene.Camera = new Camera()
{
};
DrawText obj = new DrawText(font, "I AM\n\tTWO")
{};
SimpleShader shader = new SimpleShader("basic", AssemblyUtility.ReadAssemblyFile("SM_TEST.Default Fragment Shader1.frag"), (a, b) => {
a["Color"].SetColor(b.Material.Tint);
a["Scale"].SetFloat(b.Material.ShaderArguments.Get("Scale", 1f));
});
DrawObject2D obj = new DrawObject2D()
{
Material =
{
CustomShader = shader,
Tint = new Color4(1f, 0.151217f, 0.050313f, 1),
ShaderArguments =
{
["Scale"] = 50f
}
}
};/*
DrawObject2D obj2 = new DrawObject2D()
{
Material =
{
Tint = Color4.Aqua,
CustomShader = shader,
ShaderArguments =
{
["Scale"] = 1000f
}
}
};
obj2.Transform.Position.Set(300);*/
scene.Objects.Add(obj);
window.UpdateFrame += WindowOnUpdateFrame;
window.RenderFrame += Window_RenderFrame;
window.Run();
@ -80,11 +112,5 @@ namespace SM_TEST
{
window.Title = Math.Floor(e.Time * 1000) + "ms";
}
private static void WindowOnUpdateFrame(object sender, FrameEventArgs e)
{
bool interactions = new GameController(0).GetState().AnyInteraction;
Console.WriteLine();
}
}
}

View file

@ -10,12 +10,13 @@
<OutputType>WinExe</OutputType>
<RootNamespace>SM_TEST</RootNamespace>
<AssemblyName>SM_TEST</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
@ -66,6 +67,7 @@
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<EmbeddedResource Include="Default Fragment Shader1.frag" />
<None Include="OpenTK.dll.config" />
<None Include="packages.config" />
</ItemGroup>

View file

@ -1,4 +1,5 @@
using OpenTK.Graphics.OpenGL4;
using SM.Base.Legacy.PostProcessing;
using SM.Base.PostEffects;
using SM.Base.Window;
using SM.Intergrations.ShaderTool;
@ -9,6 +10,7 @@ namespace SM_TEST
{
public class TestRenderPipeline : RenderPipeline
{
private BloomEffectOld _bloomObsolete;
private BloomEffect _bloom;
private STPostProcessEffect _vittage;
@ -17,16 +19,15 @@ namespace SM_TEST
public override void Initialization()
{
MainFramebuffer = CreateWindowFramebuffer(16, PixelInformation.RGBA_HDR);
MainFramebuffer = CreateWindowFramebuffer(0, PixelInformation.RGBA_HDR, true);
_postBuffer = CreateWindowFramebuffer(0, PixelInformation.RGBA_HDR, depth: true);
Framebuffers.Add(_postBuffer);
_bloom = new BloomEffect(_postBuffer, hdr: true, .75f)
_bloom = new BloomEffect(true)
{
Radius = 20,
};
_bloom.Initilize(this);
PostProcessEffects.Add(_bloom);
_vittage = new STPostProcessEffect(Program.portal.DrawNodes.Find(a => a.Variables.ContainsKey("_ViewportSize")))
/*_vittage = new STPostProcessEffect(Program.portal.DrawNodes.Find(a => a.Variables.ContainsKey("_ViewportSize")))
{
Arguments =
{
@ -36,7 +37,8 @@ namespace SM_TEST
{"Move", 3.33f}
}
};
_vittage.Initilize(this);
_vittage.Initilize(this);*/
InitizePostProcessing();
base.Initialization();
}
@ -50,16 +52,17 @@ namespace SM_TEST
context.Scene.DrawHUD(context);
GL.Disable(EnableCap.DepthTest);
_postBuffer.Activate(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
PostProcessUtility.ResolveMultisampledBuffers(MainFramebuffer, _postBuffer);
//_postBuffer.Activate(ClearBufferMask.ColorBufferBit);
//PostProcessUtility.ResolveMultisampledBuffers(MainFramebuffer, _postBuffer);
_vittage.Draw(_postBuffer["color"], context);
_bloom.Draw(_postBuffer["color"], context);
//_vittage.Draw(MainFramebuffer["color"], context);
//_bloom.Draw(MainFramebuffer["color"], context);
_bloomObsolete.Draw(MainFramebuffer["color"], context);
Framebuffer.Screen.Activate(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
PostProcessUtility.FinalizeHDR(_postBuffer["color"], .1f);
PostProcessUtility.FinalizeHDR(MainFramebuffer["color"], 1f);
context.Scene.DrawDebug(context);
//context.Scene.DrawDebug(context);
}
}
}