-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathColorMath.cs
More file actions
59 lines (52 loc) · 1.85 KB
/
ColorMath.cs
File metadata and controls
59 lines (52 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System.Collections;
using System.Collections.Generic;
using Unity.Mathematics;
using static Unity.Mathematics.math;
// Thanks to Ian Taylor at https://www.chilliant.com/rgb2hsv.html
public static class ColorMath
{
public static float3 HueToRgb(in float h)
{
float r = abs(h * 6 - 3) - 1;
float g = 2 - abs(h * 6 - 2);
float b = 2 - abs(h * 6 - 4);
return saturate(float3(r,g,b));
}
public static float3 HsvToRgb(in float3 hsv)
{
float3 rgb = HueToRgb(hsv.x);
return ((rgb - 1) * hsv.y + 1) * hsv.z;
}
public static float3 HslToRgb(in float3 hsl)
{
float3 rgb = HueToRgb(hsl.x);
float c = (1 - abs(2 * hsl.z - 1)) * hsl.y;
return (rgb - 0.5f) * c + hsl.z;
}
const float Epsilon = 1e-10f;
public static float3 RgbToHcv(in float3 rgb)
{
// Based on work by Sam Hocevar and Emil Persson
float4 p = (rgb.y < rgb.z) ? float4(rgb.zy, -1.0f, 2.0f/3.0f) : float4(rgb.zy, 0.0f, -1.0f/3.0f);
float4 q = (rgb.x < p.x) ? float4(p.xyw, rgb.x) : float4(rgb.x, p.yzx);
float c = q.x - min(q.w, q.y);
float h = abs((q.w - q.y) / (6 * c + Epsilon) + q.z);
return float3(h, c, q.x);
}
public static float3 RgbToHsv(in float3 rgb)
{
float3 hcv = RgbToHcv(rgb);
float s = hcv.y / (hcv.z + Epsilon);
return float3(hcv.x, s, hcv.z);
}
public static float3 RgbToHsl(in float3 rgb)
{
float3 hcv = RgbToHcv(rgb);
float l = hcv.z - hcv.y * 0.5f;
float s = hcv.y / (1 - abs(l * 2 - 1) + Epsilon);
return float3(hcv.x, s, l);
}
}