Add new math utilities to shaders library

This commit is contained in:
2022-05-16 10:06:12 +02:00
parent c74b66f728
commit 8125e406bb
3 changed files with 80 additions and 0 deletions
+15
View File
@@ -54,6 +54,21 @@ float4 Square(float4 x)
return x * x;
}
float Max2(float2 x)
{
return max(x.x, x.y);
}
float Max3(float3 x)
{
return max(x.x, max(x.y, x.z));
}
float Max4(float4 x)
{
return max(x.x, max(x.y, max(x.z, x.w)));
}
float Pow2(float x)
{
return x * x;
+47
View File
@@ -0,0 +1,47 @@
// Copyright (c) 2012-2022 Wojciech Figat. All rights reserved.
#ifndef __OCTAHEDRAL__
#define __OCTAHEDRAL__
// Implementation based on:
// "A Survey of Efficient Representations for Independent Unit Vectors", Journal of Computer Graphics Tools (JCGT), vol. 3, no. 2, 1-30, 2014
// Zina H. Cigolle, Sam Donow, Daniel Evangelakos, Michael Mara, Morgan McGuire, and Quirin Meyer
// http://jcgt.org/published/0003/02/01/
float GetSignNotZero(float v)
{
return v >= 0.0f ? 1.0f : -1.0f;
}
float2 GetSignNotZero(float2 v)
{
return float2(GetSignNotZero(v.x), GetSignNotZero(v.y));
}
// Calculates octahedral coordinates (in range [-1; 1]) for direction vector
float2 GetOctahedralCoords(float3 direction)
{
float2 uv = direction.xy * (1.0f / (abs(direction.x) + abs(direction.y) + abs(direction.z)));
if (direction.z < 0.0f)
uv = (1.0f - abs(uv.yx)) * GetSignNotZero(uv.xy);
return uv;
}
// Calculates octahedral coordinates (in range [-1; 1]) for 2D texture (assuming 1 pixel border around)
float2 GetOctahedralCoords(uint2 texCoords, uint resolution)
{
float2 uv = float2(texCoords.x % resolution, texCoords.y % resolution) + 0.5f;
uv.xy /= float(resolution);
return uv * 2.0f - 1.0f;
}
// Gets the direction vector from octahedral coordinates
float3 GetOctahedralDirection(float2 coords)
{
float3 direction = float3(coords.x, coords.y, 1.0f - abs(coords.x) - abs(coords.y));
if (direction.z < 0.0f)
direction.xy = (1.0f - abs(direction.yx)) * GetSignNotZero(direction.xy);
return normalize(direction);
}
#endif
+18
View File
@@ -0,0 +1,18 @@
// Copyright (c) 2012-2022 Wojciech Figat. All rights reserved.
#ifndef __QUATERNION__
#define __QUATERNION__
float4 QuaternionMultiply(float4 q1, float4 q2)
{
return float4(q2.xyz * q1.w + q1.xyz * q2.w + cross(q1.xyz, q2.xyz), q1.w * q2.w - dot(q1.xyz, q2.xyz));
}
float3 QuaternionRotate(float4 q, float3 v)
{
float3 b = q.xyz;
float b2 = dot(b, b);
return (v * (q.w * q.w - b2) + b * (dot(v, b) * 2.f) + cross(b, v) * (q.w * 2.f));
}
#endif