Advertisement
CrazedProgrammer

RGB API

Apr 25th, 2015
1,519
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.32 KB | None | 0 0
  1. -- RGB API version 1.0 by CrazedProgrammer
  2. -- You can find info and documentation on these pages:
  3. --
  4. -- You may use this in your ComputerCraft programs and modify it without asking.
  5. -- However, you may not publish this API under your name without asking me.
  6. -- If you have any suggestions, bug reports or questions then please send an email to:
  7. -- crazedprogrammer@gmail.com
  8. local hex = {"F0F0F0", "F2B233", "E57FD8", "99B2F2", "DEDE6C", "7FCC19", "F2B2CC", "4C4C4C", "999999", "4C99B2", "B266E5", "3366CC", "7F664C", "57A64E", "CC4C4C", "191919"}
  9. local rgb = {}
  10. for i=1,16,1 do
  11.   rgb[i] = {tonumber(hex[i]:sub(1, 2), 16), tonumber(hex[i]:sub(3, 4), 16), tonumber(hex[i]:sub(5, 6), 16)}
  12. end
  13. local rgb2 = {}
  14. for i=1,16,1 do
  15.   rgb2[i] = {}
  16.   for j=1,16,1 do
  17.     rgb2[i][j] = {(rgb[i][1] * 34 + rgb[j][1] * 20) / 54, (rgb[i][2] * 34 + rgb[j][2] * 20) / 54, (rgb[i][3] * 34 + rgb[j][3] * 20) / 54}
  18.   end
  19. end
  20.  
  21. colors.fromRGB = function (r, g, b)
  22.   local dist = 1e100
  23.   local d = 1e100
  24.   local color = -1
  25.   for i=1,16,1 do
  26.     d = math.sqrt((math.max(rgb[i][1], r) - math.min(rgb[i][1], r)) ^ 2 + (math.max(rgb[i][2], g) - math.min(rgb[i][2], g)) ^ 2 + (math.max(rgb[i][3], b) - math.min(rgb[i][3], b)) ^ 2)
  27.     if d < dist then
  28.       dist = d
  29.       color = i - 1
  30.     end
  31.   end
  32.   return 2 ^ color
  33. end
  34.  
  35. colors.toRGB = function(color)
  36.   return unpack(rgb[math.floor(math.log(color) / math.log(2) + 1)])
  37. end
  38.  
  39. colors.fromRGB2 = function (r, g, b)
  40.   local dist = 1e100
  41.   local d = 1e100
  42.   local color1 = -1
  43.   local color2 = -1
  44.   for i=1,16,1 do
  45.     for j=1,16,1 do
  46.       d = math.sqrt((math.max(rgb2[i][j][1], r) - math.min(rgb2[i][j][1], r)) ^ 2 + (math.max(rgb2[i][j][2], g) - math.min(rgb2[i][j][2], g)) ^ 2 + (math.max(rgb2[i][j][3], b) - math.min(rgb2[i][j][3], b)) ^ 2)
  47.       if d < dist then
  48.         dist = d
  49.         color1 = i - 1
  50.         color2 = j - 1
  51.       end
  52.     end
  53.   end
  54.   return 2 ^ color1, 2 ^ color2
  55. end
  56.  
  57. colors.toRGB2 = function(color1, color2, str)
  58.   local c1 = math.floor(math.log(color1) / math.log(2) + 1)
  59.   local c2 = math.floor(math.log(color2) / math.log(2) + 1)
  60.   return math.floor(rgb2[c1][c2][1]), math.floor(rgb2[c1][c2][2]), math.floor(rgb2[c1][c2][3])
  61. end
  62.  
  63. colours.fromRGB = colors.fromRGB
  64. colours.toRGB = colors.toRGB
  65. colours.fromRGB2 = colors.fromRGB2
  66. colours.toRGB2 = colors.toRGB2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement