forked from AcademySoftwareFoundation/MaterialX
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hsv.mdl
80 lines (70 loc) · 2.79 KB
/
hsv.mdl
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Support functions for HSV <--> RGB color conversions
mdl 1.0;
import ::math::*;
import ::limits::*;
// Convert from the HSV color model to the RGB color model
export float3 mx_hsvtorgb(float3 hsv) {
// from "Color Imaging, Fundamentals and Applications", Reinhard et al., p. 442
// A hue of 1.0 is questionably valid, and needs to be interpreted as 0.0f
float h_prime = (hsv.x < 1.0f) ? hsv.x * 6.0f : 0.0f; // H * 360.0/60.0
float h_floor = math::floor(h_prime);
float f = h_prime - h_floor;
float zy = hsv.z*hsv.y;
float a = hsv.z - zy;
float b = hsv.z - zy*f;
float c = a + zy*f;
switch(int(h_floor)) {
default:
// hue out of [0,1] range...
// fall through...
case 0:
return float3(hsv.z, c, a);
case 1:
return float3(b, hsv.z, a);
case 2:
return float3(a, hsv.z, c);
case 3:
return float3(a, b, hsv.z);
case 4:
return float3(c, a, hsv.z);
case 5:
return float3(hsv.z, a, b);
}
}
// Convert from the RGB color model to the HSV color model
export float3 mx_rgbtohsv(float3 rgb) {
// from "Color Imaging, Fundamentals and Applications", Reinhard et al., p. 442
// H =
// 60*(G-B)/(max-min) if R is max
// 60*(2+((B-R)/(max-min))) if G is max
// 60*(4+((R-G)/(max-min))) if B if max
// and normalize the result by dividing by 360deg
// S = (max-min)/max
// V = max
float max = math::max(rgb.x, math::max(rgb.y, rgb.z));
float min = math::min(rgb.x, math::min(rgb.y, rgb.z));
float range = max - min;
float inv_range = (1.0f/6.0f)/range;
float saturation = (max > limits::FLOAT_MIN) ? (range / max) : 0.0f;
float hue = (saturation != 0.0f) ?
((max == rgb.x) ? ((rgb.y-rgb.z)*inv_range) // R is max
: (max == rgb.y) ? ((2.0f/6.0f) + (rgb.z-rgb.x)*inv_range) // G is max
: ((4.0f/6.0f) + (rgb.x-rgb.y)*inv_range)) // B is max
: 0.0f; // hue is undefined (assume 0)
return float3((hue >= 0.0f) ? hue : (hue + 1.0f), saturation, max);
}