// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
/// <summary>
/// Various helper functions.
/// </summary>
shader Utilities
{
    // -------------------------------------
    // type definition
    // -------------------------------------
    typedef uint Half2;
    typedef uint2 Half4;
    
    // Converts a Half2 to a float2
    float2 Half2ToFloat2(Half2 value) 
    {
        return float2(f16tof32(value), f16tof32(value >> 16));
    }

    // Converts a float2 to a Half2
    Half2 Float2ToHalf2(float2 value) 
    {
        return f32tof16(value.x) | (f32tof16(value.y) << 16);
    }

    // Converts a Half4 to a float4
    float4 Half4ToFloat4(Half4 value) {
        return float4(f16tof32(value.x), f16tof32(value.x>>16), f16tof32(value.y), f16tof32(value.y>>16));
    }

    // Converts a float4 to a Half4
    Half4 Float4ToHalf4(float4 value) {
        return uint2(f32tof16(value.x) | (f32tof16(value.y) << 16), f32tof16(value.z) | (f32tof16(value.w) << 16));
    }

    // Commpute Schlick's approximation of Fresnel
    float3 FresnelSchlick(float3 specularColor, float3 eye, float3 h, float factor)
    {
        return specularColor + (1.0f - specularColor) * pow(1.0f - saturate(dot(eye, h)), 5.0f) * factor;
    }

    // Commpute Schlick's approximation of Fresnel
    float3 FresnelSchlickWithGloss(float3 specularColor, float3 eye, float3 h, float factor, float gloss)
    {
        return specularColor + (max(specularColor, gloss) - specularColor) * pow(1.0f - saturate(dot(eye, h)), 5.0f) * factor;
    }

    // flip the texture coordinate if on an opengl device.
    static float2 ConvertTexCoord(float2 texcoord) {
#ifdef STRIDE_GRAPHICS_API_OPENGL
        return float2(texcoord.x, 1.0f - texcoord.y);
#else
        return texcoord;
#endif
    }
};
