Skip to content

Commit

Permalink
cleans up project
Browse files Browse the repository at this point in the history
  • Loading branch information
BoyBaykiller committed Oct 24, 2021
1 parent daba231 commit 401c04c
Show file tree
Hide file tree
Showing 16 changed files with 298 additions and 236 deletions.
2 changes: 2 additions & 0 deletions OpenTK-PathTracer/OpenTK-PathTracer.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
<Platforms>AnyCPU;x64</Platforms>
<RunPostBuildEvent>Always</RunPostBuildEvent>
<AssemblyName>OpenTK-PathTracer</AssemblyName>
<ApplicationIcon />
<StartupObject />
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
using System;
using OpenTK;
using OpenTK;
using OpenTK_PathTracer.Render.Objects;

namespace OpenTK_PathTracer
{
abstract class BaseUBOCompatible
abstract class BaseSTD140Compatible
{
public abstract int BufferOffset { get; }

public abstract Vector4[] GetGPUFriendlyData();

public void Upload(BufferObject uniformBuffer)
public void Upload(BufferObject buffer)
{
Vector4[] data = GetGPUFriendlyData();
uniformBuffer.SubData(BufferOffset, Vector4.SizeInBytes * data.Length, data);
buffer.SubData(BufferOffset, Vector4.SizeInBytes * data.Length, data);
}
}
}
5 changes: 4 additions & 1 deletion OpenTK-PathTracer/Src/CSharp/Camera.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ public void ProcessInputs(float dT, out bool frameChanged)
View = GenerateMatrix(Position, ViewDir, Up);
}

public static Matrix4 GenerateMatrix(Vector3 position, Vector3 viewDir, Vector3 up) => Matrix4.LookAt(position, position + viewDir, up);
public static Matrix4 GenerateMatrix(Vector3 position, Vector3 viewDir, Vector3 up)
{
return Matrix4.LookAt(position, position + viewDir, up);
}
}
}
2 changes: 1 addition & 1 deletion OpenTK-PathTracer/Src/CSharp/GameObjects/BaseGameObject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace OpenTK_PathTracer.GameObjects
{
abstract class BaseGameObject : BaseUBOCompatible
abstract class BaseGameObject : BaseSTD140Compatible
{
public Material Material;
public Vector3 Position;
Expand Down
2 changes: 1 addition & 1 deletion OpenTK-PathTracer/Src/CSharp/Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public static void ParallelLoadCubemapImages(Texture texture, string[] paths, Si
if (!bitmaps.All(i => i.Width == i.Height && i.Width == bitmaps[0].Width))
throw new ArgumentException($"Individual cubemap textures must be squares and every texture must be of the same size");
int size = bitmaps[0].Width;
texture.ImmutableAllocate(size, size, 1, sizedInternalFormat);
texture.ImmutableAllocate(size, size, 1, sizedInternalFormat, 6);
for (int i = 0; i < 6; i++)
{
System.Drawing.Imaging.BitmapData bitmapData = bitmaps[i].LockBits(new Rectangle(0, 0, size, size), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Expand Down
27 changes: 16 additions & 11 deletions OpenTK-PathTracer/Src/CSharp/MainWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class MainWindow : GameWindow


public Matrix4 projection, inverseProjection;
Vector2 nearFarPlane = new Vector2(EPSILON, 2000f);
Vector2 nearFarPlane = new Vector2(EPSILON, 200f);
public int FPS, UPS;
private int fps, ups;

Expand Down Expand Up @@ -75,15 +75,15 @@ protected override void OnUpdateFrame(FrameEventArgs args)
ThreadManager.InvokeQueuedActions();
KeyboardManager.Update();
MouseManager.Update();

if (Focused)
{
if (Render.GUI.Final.ImGuiIOPtr.WantCaptureMouse && !CursorVisible)
{
Point _point = PointToScreen(new Point(Width / 2, Height / 2));
Mouse.SetPosition(_point.X, _point.Y);
}

Render.GUI.Final.Update(this);

if (KeyboardManager.IsKeyDown(Key.Escape))
Expand All @@ -99,7 +99,7 @@ protected override void OnUpdateFrame(FrameEventArgs args)
{
CursorVisible = !CursorVisible;
CursorGrabbed = !CursorGrabbed;

if (!CursorVisible)
{
MouseManager.Update();
Expand Down Expand Up @@ -137,10 +137,12 @@ protected override void OnLoad(EventArgs e)
Console.WriteLine($"OpenGL: {Helper.APIMajor}.{Helper.APIMinor}");
Console.WriteLine($"GLSL: {GL.GetString(StringName.ShadingLanguageVersion)}");
Console.WriteLine($"GPU: {GL.GetString(StringName.Renderer)}");

if (!Helper.IsCoreExtensionAvailable("GL_ARB_direct_state_access", 4, 5))
throw new NotSupportedException("Your system does not support GL_ARB_direct_state_access");

if (!Helper.IsCoreExtensionAvailable("GL_ARB_texture_storage", 4, 2))
throw new NotSupportedException("Your system does not support GL_ARB_texture_storage");

GL.DepthMask(false);
GL.Disable(EnableCap.DepthTest);
GL.Disable(EnableCap.CullFace);
Expand All @@ -161,8 +163,8 @@ protected override void OnLoad(EventArgs e)
"Res/Textures/EnvironmentMap/posz.png",
"Res/Textures/EnvironmentMap/negz.png"
}, (SizedInternalFormat)PixelInternalFormat.Srgb8Alpha8);
AtmosphericScatterer = new AtmosphericScattering(128, 100, 10, 2.1f, 35.0f, 0.01f, new Vector3(680, 550, 440), new Vector3(0, 500, 0), new Vector3(20.43f, -201.99f, -20.67f));

AtmosphericScatterer = new AtmosphericScattering(128, 100, 10, 2.1f, 35.0f, 0.01f, new Vector3(680, 550, 440), new Vector3(0, 500 + 800.0f, 0), new Vector3(20.43f, -201.99f + 800.0f, -20.67f));
PathTracer = new PathTracer(SkyBox, Width, Height, 13, 1, 20f, 0.14f);
Rasterizer = new Rasterizer(Width, Height);
PostProcesser = new ScreenEffect(new Shader(ShaderType.FragmentShader, "Res/Shaders/PostProcessing/fragment.glsl".GetPathContent()), Width, Height);
Expand All @@ -182,7 +184,7 @@ protected override void OnLoad(EventArgs e)
for (float x = 0; x < balls; x++)
for (float y = 0; y < balls; y++)
GameObjects.Add(new Sphere(new Vector3(dimensions.X / balls * x * 1.1f - dimensions.X / 2, (dimensions.Y / balls) * y - dimensions.Y / 2 + radius, -5), radius, PathTracer.NumSpheres++, new Material(albedo: new Vector3(0.59f, 0.59f, 0.99f), emissiv: new Vector3(0), refractionColor: Vector3.Zero, specularChance: x / (balls - 1), specularRoughness: y / (balls - 1), indexOfRefraction: 1f, refractionChance: 0.0f, refractionRoughnes: 0.1f)));

Vector3 delta = dimensions / balls;
for (float x = 0; x < balls; x++)
{
Expand All @@ -207,7 +209,7 @@ protected override void OnLoad(EventArgs e)
GameObjects.Add(new Sphere(position, radius, PathTracer.NumSpheres++, material1));
}
#endregion

#region SetupCuboids

Cuboid down = new Cuboid(new Vector3(0, -height / 2, -10), new Vector3(width, EPSILON, depth), PathTracer.NumCuboids++, new Material(albedo: new Vector3(0.2f, 0.04f, 0.04f), emissiv: new Vector3(0.0f), refractionColor: Vector3.Zero, specularChance: 0.0f, specularRoughness: 0.051f, indexOfRefraction: 1.0f, refractionChance: 0.0f, refractionRoughnes: 0.0f));
Expand All @@ -225,7 +227,7 @@ protected override void OnLoad(EventArgs e)

GameObjects.AddRange(new Cuboid[] { down, upLight, back, front, right, left, middle });
#endregion

for (int i = 0; i < GameObjects.Count; i++)
GameObjects[i].Upload(GameObjectsUBO);

Expand Down Expand Up @@ -286,7 +288,10 @@ public bool RayTrace(Ray ray, out BaseGameObject gameObject, out float t1, out f

return tMin != float.MaxValue;
}
public static float GetSmallestPositive(float t1, float t2) => t1 < 0 ? t2 : t1;
public static float GetSmallestPositive(float t1, float t2)
{
return t1 < 0 ? t2 : t1;
}

public void SetGameObjectsRandomMaterial<T>(int maxNum) where T : BaseGameObject
{
Expand Down
2 changes: 1 addition & 1 deletion OpenTK-PathTracer/Src/CSharp/Material.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

namespace OpenTK_PathTracer
{
class Material : BaseUBOCompatible
class Material : BaseSTD140Compatible
{
public static Material Zero => new Material(albedo: Vector3.One, emissiv: Vector3.Zero, refractionColor: Vector3.Zero, specularChance: 0.0f, specularRoughness: 0.0f, indexOfRefraction: 1.0f, refractionChance: 0.0f, refractionRoughnes: 0.0f);
public const int GPU_INSTANCE_SIZE = 16 * 4;
Expand Down
4 changes: 2 additions & 2 deletions OpenTK-PathTracer/Src/CSharp/Render/AtmosphericScatterer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,13 +110,13 @@ public Vector3 ViewPos
}
}

public readonly Query Query;
public readonly TimerQuery Query;
public readonly Texture Result;
private readonly ShaderProgram shaderProgram;
private readonly BufferObject bufferObject;
public AtmosphericScattering(int size, int inScatteringSamples, int densitySamples, float scatteringStrength, float densityFallOff, float atmosphereRadius, Vector3 waveLengths, Vector3 lightPos, Vector3 viewPos)
{
Query = new Query(600);
Query = new TimerQuery(600);

Result = new Texture(TextureTarget2d.TextureCubeMap);
Result.MutableAllocate(size, size, 1, PixelInternalFormat.Rgba32f);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public void Bind(BufferTarget bufferTarget)
}

/// <summary>
/// Sets <seealso cref="BufferOffset"/> to 0 and overrides the content with 0
/// Sets <see cref="BufferOffset"/> to 0 and overrides the content with 0
/// </summary>
public void Reset()
{
Expand Down
31 changes: 12 additions & 19 deletions OpenTK-PathTracer/Src/CSharp/Render/Objects/Texture.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenTK;
using OpenTK.Graphics.OpenGL4;
using PixelFormat = OpenTK.Graphics.OpenGL4.PixelFormat;
Expand Down Expand Up @@ -91,7 +88,7 @@ public void SetWrapMode(TextureWrapMode wrapS, TextureWrapMode wrapT)
GL.TextureParameter(ID, TextureParameterName.TextureWrapT, (int)wrapT);
}

public void SetTextureWrap(TextureWrapMode wrapS, TextureWrapMode wrapT, TextureWrapMode wrapR)
public void SetWrapMode(TextureWrapMode wrapS, TextureWrapMode wrapT, TextureWrapMode wrapR)
{
GL.TextureParameter(ID, TextureParameterName.TextureWrapS, (int)wrapS);
GL.TextureParameter(ID, TextureParameterName.TextureWrapT, (int)wrapT);
Expand Down Expand Up @@ -137,6 +134,11 @@ public void SubTexture1D(int width, PixelFormat pixelFormat, PixelType pixelType
GL.TextureSubImage1D(ID, level, xOffset, width, pixelFormat, pixelType, pixels);
}


/// <summary>
/// To properly generate mipmaps <see cref="TextureMinFilter"/> must be set to one of the mipmap options
/// and if immutable storage is used the level parameter should match the number of desired mipmap levels to generate (default: 1).
/// </summary>
public void GenerateMipmap()
{
GL.GenerateTextureMipmap(ID);
Expand All @@ -155,10 +157,13 @@ public void SetSeamlessCubeMapPerTexture(bool param)
GL.TextureParameter(ID, (TextureParameterName)All.TextureCubeMapSeamless, param ? 1 : 0);
}

public unsafe void SetBorderColor(Vector4 color)
public void SetBorderColor(Vector4 color)
{
float* colors = stackalloc[] { color.X, color.Y, color.Z, color.W };
GL.TextureParameter(ID, TextureParameterName.TextureBorderColor, colors);
unsafe
{
float* colors = stackalloc[] { color.X, color.Y, color.Z, color.W };
GL.TextureParameter(ID, TextureParameterName.TextureBorderColor, colors);
}
}

public void SetMipmapLodBias(float bias)
Expand Down Expand Up @@ -253,18 +258,12 @@ public void ImmutableAllocate(int width, int height, int depth, SizedInternalFor

public long GetTextureBindlessHandle()
{
if (Helper.IsExtensionsAvailable("GL_ARB_bindless_texture"))
throw new NotSupportedException("Your system does not support GL_ARB_bindless_texture");

long textureHandle = GL.Arb.GetTextureHandle(ID);
GL.Arb.MakeTextureHandleResident(textureHandle);
return textureHandle;
}
public static bool UnmakeTextureBindless(long textureHandle)
{
if (Helper.IsExtensionsAvailable("GL_ARB_bindless_texture"))
throw new NotSupportedException("Your system does not support GL_ARB_bindless_texture");

if (GL.Arb.IsTextureHandleResident(textureHandle))
{
GL.Arb.MakeTextureHandleNonResident(textureHandle);
Expand All @@ -275,18 +274,12 @@ public static bool UnmakeTextureBindless(long textureHandle)

public long GetImageBindlessHandle(int level, bool layered, int layer, PixelFormat pixelFormat, TextureAccess textureAccess)
{
if (Helper.IsExtensionsAvailable("GL_ARB_bindless_texture"))
throw new NotSupportedException("Your system does not support GL_ARB_bindless_texture");

long imageHandle = GL.Arb.GetImageHandle(ID, level, layered, layer, pixelFormat);
GL.Arb.MakeImageHandleResident(imageHandle, (All)textureAccess);
return imageHandle;
}
public static bool UnmakeImageBindless(long imageHandle)
{
if (Helper.IsExtensionsAvailable("GL_ARB_bindless_texture"))
throw new NotSupportedException("Your system does not support GL_ARB_bindless_texture");

if (GL.Arb.IsImageHandleResident(imageHandle))
{
GL.Arb.MakeImageHandleNonResident(imageHandle);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,24 @@

namespace OpenTK_PathTracer.Render.Objects
{
/// <summary>
/// This measures the timings of GPU commands
/// </summary>
class Query : IDisposable
class TimerQuery : IDisposable
{
public readonly int ID;
public float ElapsedMilliseconds { get; private set; }

private readonly Stopwatch timer = new Stopwatch();
private bool doStopAndReset = false;


public readonly int ID;
public int UpdateRate;
public Query(int updatePeriodInMs)
public TimerQuery(int updatePeriodInMs)
{
GL.CreateQueries(QueryTarget.TimeElapsed, 1, out ID);
UpdateRate = updatePeriodInMs;
}


/// <summary>
/// If <seealso cref="UpdateRate"/> milliseconds are elapsed since the last Query, a new Query on the GPU, which captures all render commands from now until StopAndReset, is started.
/// If <see cref="UpdateRate"/> milliseconds are elapsed since the last <see cref="TimerQuery"/>, a new one on will be issued, which measures all render commands from now until <see cref="StopAndReset"/>.
/// </summary>
public void Start()
{
Expand All @@ -38,7 +34,7 @@ public void Start()
}

/// <summary>
/// Resets the Query on the GPU and stores the result in <seealso cref="ElapsedMilliseconds"/>
/// Resets the <see cref="TimerQuery"/> and stores the result in <see cref="ElapsedMilliseconds"/>
/// </summary>
public void StopAndReset()
{
Expand Down
7 changes: 4 additions & 3 deletions OpenTK-PathTracer/Src/CSharp/Render/PathTracer.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#define USE_COMPUTE
using System;
using OpenTK;
using OpenTK.Graphics.OpenGL4;
using OpenTK_PathTracer.Render.Objects;
Expand Down Expand Up @@ -84,7 +83,9 @@ public float ApertureDiameter

public Texture EnvironmentMap;
public readonly Texture Result;
#if !USE_COMPUTE
private readonly Framebuffer framebuffer;
#endif
private readonly ShaderProgram shaderProgram;
public PathTracer(Texture environmentMap, int width, int height, int rayDepth, int spp, float focalLength, float apertureDiamater)
{
Expand Down Expand Up @@ -116,10 +117,10 @@ public void Run()
#if USE_COMPUTE
Result.AttachImage(0, 0, false, 0, TextureAccess.ReadWrite, SizedInternalFormat.Rgba32f);
GL.DispatchCompute((Result.Width * Result.Height + 32 - 1) / 32, 1, 1);
GL.MemoryBarrier(MemoryBarrierFlags.TextureFetchBarrierBit);
GL.MemoryBarrier(MemoryBarrierFlags.TextureFetchBarrierBit | MemoryBarrierFlags.ShaderImageAccessBarrierBit);
#else
framebuffer.Bind();
Result.AttachSampler(0);
Result.AttachImage(0, 0, false, 0, TextureAccess.ReadOnly, SizedInternalFormat.Rgba32f);
GL.DrawArrays(PrimitiveType.Quads, 0, 4);
#endif
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ Ray GetWorldSpaceRay(mat4 inverseProj, mat4 inverseView, vec3 viewPos, vec2 norm
bool IsInside(vec2 pos, vec2 size);


const vec3 PlanetPos = vec3(0, -800, 0);
const vec3 PlanetPos = vec3(0, 0, 0);
const float PlanetRad = 600;
uniform float atmosphereRad;

Expand Down Expand Up @@ -126,7 +126,7 @@ float DensityAtPoint(vec3 point)
bool RaySphereIntersect(Ray ray, vec3 position, float radius, out float t1, out float t2)
{
// Source: https://antongerdelan.net/opengl/raycasting.html
t1 = FLOAT_MAX; t2 = FLOAT_MAX;
t1 = t2 = FLOAT_MAX;

vec3 sphereToRay = ray.Origin - position;
float b = dot(ray.Direction, sphereToRay);
Expand Down
Loading

0 comments on commit 401c04c

Please sign in to comment.