| 1 | // Copyright 2025 The TCell Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package color |
| 16 | |
| 17 | import ( |
| 18 | "github.com/lucasb-eyer/go-colorful" |
| 19 | ) |
| 20 | |
| 21 | // Find attempts to find a given color, or the best match possible for it, |
| 22 | // from the palette given. This is an expensive operation, so results should |
| 23 | // be cached by the caller. |
| 24 | func Find(c Color, palette []Color) Color { |
| 25 | match := Default |
| 26 | dist := float64(0) |
| 27 | r, g, b := c.RGB() |
| 28 | c1 := colorful.Color{ |
| 29 | R: float64(r) / 255.0, |
| 30 | G: float64(g) / 255.0, |
| 31 | B: float64(b) / 255.0, |
| 32 | } |
| 33 | for _, d := range palette { |
| 34 | r, g, b = d.RGB() |
| 35 | c2 := colorful.Color{ |
| 36 | R: float64(r) / 255.0, |
| 37 | G: float64(g) / 255.0, |
| 38 | B: float64(b) / 255.0, |
| 39 | } |
| 40 | // CIE94 is more accurate, but really really expensive. |
| 41 | nd := c1.DistanceCIE76(c2) |
| 42 | // NB: nd < dist is false if is NaN. |
| 43 | // We have never seen a case where the CIE76 algorithm returns NaN. |
| 44 | if match == Default || nd < dist { |
| 45 | match = d |
| 46 | dist = nd |
| 47 | } |
| 48 | } |
| 49 | return match |
| 50 | } |