Skip to content

Instantly share code, notes, and snippets.

@codemasher
Last active December 18, 2015 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codemasher/b869faa7603e1934c28d to your computer and use it in GitHub Desktop.
Save codemasher/b869faa7603e1934c28d to your computer and use it in GitHub Desktop.
Another approach to get the correct RGB values from the GW2 color API as Cliff Spradlin described over here: https://forum-en.guildwars2.com/forum/community/api/How-To-Colors-API/2148826
<?php
// note: the array Syntax $foo = [...] is available since PHP 5.4, you may need to change to $foo = array(...)
// http://php.net/manual/en/language.types.array.php
function matrix_multiply($m1, $m2){
$r = count($m1);
$c = count($m2[0]);
$p = count($m2);
if(count($m1[0]) != $p){
return false; //incompatible matrix
}
$m3 = [];
for($i = 0; $i < $r; $i++){
for($j = 0; $j < $c; $j++){
$m3[$i][$j] = 0;
for($k = 0; $k < $p; $k++){
$m3[$i][$j] += $m1[$i][$k]*$m2[$k][$j];
}
}
}
return ($m3);
}
function compositeColorShiftRgb($hslbc, $base){
// colors from the response .json -> material
$h = ($hslbc['hue']*pi())/180;
$s = $hslbc['saturation'];
$l = $hslbc['lightness'];
$b = $hslbc['brightness']/128;
$c = $hslbc['contrast'];
// 4x4 identity matrix
$matrix = [
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]
];
if($b != 0 || $c != 1){
// process brightness and contrast
$t = 128*(2*$b+1-$c);
$mult = [
[$c, 0, 0, $t],
[ 0, $c, 0, $t],
[ 0, 0, $c, $t],
[ 0, 0, 0, 1]
];
$matrix = matrix_multiply($mult, $matrix);
}
if($h != 0 || $s != 1 || $l != 1){
// transform to HSL
$multRgbToHsl = [
[ 0.707107, 0, -0.707107, 0],
[-0.408248, 0.816497, -0.408248, 0],
[ 0.577350, 0.577350, 0.577350, 0],
[ 0, 0, 0, 1]
];
$matrix = matrix_multiply($multRgbToHsl, $matrix);
// process adjustments
$cosHue = cos($h);
$sinHue = sin($h);
$mult = [
[ $cosHue * $s, $sinHue * $s, 0, 0],
[-$sinHue * $s, $cosHue * $s, 0, 0],
[ 0, 0, $l, 0],
[ 0, 0, 0, 1]
];
$matrix = matrix_multiply($mult, $matrix);
// transform back to RGB
$multHslToRgb = [
[ 0.707107, -0.408248, 0.577350, 0],
[ 0, 0.816497, 0.577350, 0],
[-0.707107, -0.408248, 0.577350, 0],
[ 0, 0, 0, 1]
];
$matrix = matrix_multiply($multHslToRgb, $matrix);
}
// apply the color transformation
$bgrVector = [
[$base[2]],
[$base[1]],
[$base[0]],
[1]
];
$bgrVector = matrix_multiply($matrix,$bgrVector);
// clamp the values
$rgb = [
floor(max(0, min(255, $bgrVector[2][0]))),
floor(max(0, min(255, $bgrVector[1][0]))),
floor(max(0, min(255, $bgrVector[0][0])))
];
return $rgb;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment