keycolors.lua 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. local write_new_color_file = false
  2. local last_assigned_hue = math.random()
  3. local last_assigned_saturation = math.random()
  4. local golden_ratio_conjugate = 0.618033988749895 -- for spreading out the random colours more evenly, reducing clustering
  5. local key_color_map
  6. local path = minetest.get_worldpath()
  7. local color_filename = path .. "/simplecrafting_key_colors.lua"
  8. local color_file = loadfile(color_filename)
  9. if color_file ~= nil then
  10. key_color_map = color_file()
  11. else
  12. key_color_map = {}
  13. end
  14. -- HSV values in [0..1[
  15. -- returns {r, g, b} values from 0 to 255
  16. local hsv_to_rgb = function(h, s, v)
  17. local h_i = math.floor(h*6)
  18. local f = h*6 - h_i
  19. local p = v * (1 - s)
  20. local q = v * (1 - f*s)
  21. local t = v * (1 - (1 - f) * s)
  22. local r, g, b
  23. if h_i==0 then r, g, b = v, t, p
  24. elseif h_i==1 then r, g, b = q, v, p
  25. elseif h_i==2 then r, g, b = p, v, t
  26. elseif h_i==3 then r, g, b = p, q, v
  27. elseif h_i==4 then r, g, b = t, p, v
  28. elseif h_i==5 then r, g, b = v, p, q
  29. end
  30. return {math.floor(r*255), math.floor(g*255), math.floor(b*255)}
  31. end
  32. simplecrafting_lib.get_key_color = function(key)
  33. if not key_color_map[key] then
  34. last_assigned_hue = last_assigned_hue + golden_ratio_conjugate
  35. last_assigned_hue = last_assigned_hue % 1
  36. last_assigned_saturation = last_assigned_saturation + golden_ratio_conjugate
  37. last_assigned_saturation = last_assigned_saturation % 1
  38. local color_vec = hsv_to_rgb(last_assigned_hue, last_assigned_saturation/2 + 0.5, 1)
  39. color = "#"..string.format('%02X', color_vec[1])..string.format('%02X', color_vec[2])..string.format('%02X', color_vec[3])
  40. key_color_map[key] = color
  41. write_new_color_file = true
  42. return color
  43. else
  44. return key_color_map[key]
  45. end
  46. end
  47. simplecrafting_lib.save_key_colors = function()
  48. if write_new_color_file then
  49. local color_file, err = io.open(color_filename, "w")
  50. if err == nil then
  51. color_file:write("return "..dump(key_color_map))
  52. color_file:flush()
  53. color_file:close()
  54. write_new_color_file = false
  55. end
  56. end
  57. end