srgb_lut.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #!/usr/bin/env python
  2. # vim:fileencoding=utf-8
  3. import os
  4. import sys
  5. from functools import lru_cache
  6. from typing import List
  7. if __name__ == '__main__' and not __package__:
  8. import __main__
  9. __main__.__package__ = 'gen'
  10. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  11. def to_linear(a: float) -> float:
  12. if a <= 0.04045:
  13. return a / 12.92
  14. else:
  15. return float(pow((a + 0.055) / 1.055, 2.4))
  16. @lru_cache
  17. def generate_srgb_lut(line_prefix: str = ' ') -> List[str]:
  18. values: List[str] = []
  19. lines: List[str] = []
  20. for i in range(256):
  21. values.append('{:1.5f}f'.format(to_linear(i / 255.0)))
  22. for i in range(16):
  23. lines.append(line_prefix + ', '.join(values[i * 16:(i + 1) * 16]) + ',')
  24. lines[-1] = lines[-1].rstrip(',')
  25. return lines
  26. def generate_srgb_gamma(declaration: str = 'static const GLfloat srgb_lut[256] = {', close: str = '};') -> str:
  27. lines: List[str] = []
  28. a = lines.append
  29. a('// Generated by gen-srgb-lut.py DO NOT edit')
  30. a('')
  31. a(declaration)
  32. lines += generate_srgb_lut()
  33. a(close)
  34. return "\n".join(lines)
  35. def main(args: List[str]=sys.argv) -> None:
  36. c = generate_srgb_gamma()
  37. with open(os.path.join('kitty', 'srgb_gamma.h'), 'w') as f:
  38. f.write(f'{c}\n')
  39. if __name__ == '__main__':
  40. import runpy
  41. m = runpy.run_path(os.path.dirname(os.path.abspath(__file__)))
  42. m['main']([sys.executable, 'srgb-lut'])