From aec3b9fd7f7decec49e53f28da1e2cef9ea08478 Mon Sep 17 00:00:00 2001 From: David Briscoe Date: Fri, 1 Apr 2022 21:27:56 -0700 Subject: [PATCH] Prevent nan when using color_to_hsv(white) When r,g,b are equal, delta will be zero and hue will be nan due to divide by zero. This is also an issue with the reference C++ code: https://tio.run/##Sy4o0E3OScxL//9fOTMvOac0JVXBJjO/uKQoNTHXjiszr0QhNzEzT0NToZqLs7gkxcoqOb@0RMHGRkHJIzUnJ19HITy/KCdFUQkkBJZPzUvJseaq/f8fAA An alternative approach is to always add epsilon or use a different hue calculation: http://web.archive.org/web/20210515082154/http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv --- modules/color.lua | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/modules/color.lua b/modules/color.lua index 148f5b3..e410e5f 100644 --- a/modules/color.lua +++ b/modules/color.lua @@ -2,6 +2,7 @@ -- @module color local modules = (...):gsub('%.[^%.]+$', '') .. "." +local constants = require(modules .. "constants") local utils = require(modules .. "utils") local precond = require(modules .. "_private_precond") local color = {} @@ -75,6 +76,11 @@ local function color_to_hsv(c) return { h, s, v, 1 } end + -- Prevent division by zero. + if delta == 0 then + delta = constants.DBL_EPSILON + end + if r == max then h = ( g - b ) / delta -- yellow/magenta elseif g == max then