raytracing.github.io icon indicating copy to clipboard operation
raytracing.github.io copied to clipboard

Optimize unit_vector() function?

Open hollasch opened this issue 3 years ago • 1 comments

Currently defined as

inline vec3 unit_vector(vec3 v) {
    return v / v.length();
}

However, in situations where the vector is already unit length, this can be expensive. We could optimize this with something like

inline vec3 unit_vector(vec3 v) {
    const static auto epsilon = 1e-10;
    const static auto low = 1.0 - epsilon;
    const static auto high = 1.0 + epsilon;

    const auto len_squared = v.length_squared();

    if (low < len_squared || len_squared < high)
        v /= sqrt(len_squared);
}

Try it out to see if there's any significant speedup. Likely there's not, and in this case we should definitely favor simplicity over this fussiness.

hollasch avatar Aug 22 '22 21:08 hollasch

image

I think it's better to leave it as-is.

Zor-X-L avatar Aug 26 '22 06:08 Zor-X-L