LYGIA Shader Library

normalFromHeightMap (lygia/sample/normalFromHeightMap)

Given a height map texture, calculate normal at point (s, t)

Dependencies:

Use:

normalFromHeightMap(<SAMPLER_TYPE> heightMap, <vec2> st, <float> strength, <float> offset)

Check it on Github



#ifndef SAMPLE_CHANNEL
#define SAMPLE_CHANNEL 0
#endif

vec3 normalFromHeightMap(SAMPLER_TYPE heightMap, vec2 st, float strength, float offset)
{
    offset = pow3(offset) * 0.1;

    float p = SAMPLER_FNC(heightMap, st)[SAMPLE_CHANNEL];
    float h = SAMPLER_FNC(heightMap, st + vec2(offset, 0.0))[SAMPLE_CHANNEL];
    float v = SAMPLER_FNC(heightMap, st + vec2(0.0, offset))[SAMPLE_CHANNEL];

    vec3 a = vec3(1, 0, (h - p) * strength);
    vec3 b = vec3(0, 1, (v - p) * strength);

    return normalize(cross(a, b));
}

vec3 normalFromHeightMap(SAMPLER_TYPE heightMap, vec2 st, float strength)
{
    return normalFromHeightMap(heightMap, st, strength, 0.5);

}

Dependencies:

Use:

normalFromHeightMap(<SAMPLER_TYPE> heightMap, <float2> st, <float> strength, <float> offset)

Check it on Github



#ifndef SAMPLE_CHANNEL
#define SAMPLE_CHANNEL 0
#endif

float3 normalFromHeightMap(SAMPLER_TYPE heightMap, float2 st, float strength, float offset)
{
    offset = pow3(offset) * 0.1;

    float p = SAMPLER_FNC(heightMap, st)[SAMPLE_CHANNEL];
    float h = SAMPLER_FNC(heightMap, st + float2(offset, 0.0))[SAMPLE_CHANNEL];
    float v = SAMPLER_FNC(heightMap, st + float2(0.0, offset))[SAMPLE_CHANNEL];

    float3 a = float3(1, 0, (h - p) * strength);
    float3 b = float3(0, 1, (v - p) * strength);

    return normalize(cross(a, b));
}

float3 normalFromHeightMap(SAMPLER_TYPE heightMap, float2 st, float strength)
{
    return normalFromHeightMap(heightMap, st, strength, 0.5);

}

License

MIT License (MIT) Copyright (c) 2024 Shadi EL Hajj

LYGIA is dual-licensed under the Prosperity License and the Patron License for sponsors and contributors.

Sponsors and contributors are automatically added to the Patron License and they can ignore the any non-commercial rule of the Prosperity Licensed software (please take a look to the exception).

It's also possible to get a permanent comercial license hook to a single and specific version of LYGIA.

Get the latest news and releases

Sign up for the news letter bellow, joing the LYGIA's channel on Discord or follow the Github repository