float-packing.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. /**
  2. * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. import { clamp } from '../mol-math/interpolate';
  7. const maxFloat = 10000.0; // NOTE same constant is set in shaders
  8. const floatLogFactor = Math.log(maxFloat + 1.0);
  9. /** encode float logarithmically */
  10. export function encodeFloatLog(value: number) { return Math.log(value + 1.0) / floatLogFactor }
  11. /** decode logarithmically encoded float */
  12. export function decodeFloatLog(value: number) { return Math.exp(value * floatLogFactor) - 1.0 }
  13. /** encode float as normalized rgb triplet */
  14. export function encodeFloatRGB(value: number) {
  15. value = clamp(value, 0.0, 16777216.0 - 1.0) + 1.0
  16. const b = (value % 256) / 255.0
  17. value = Math.floor(value / 256.0)
  18. const g = (value % 256) / 255.0
  19. value = Math.floor(value / 256.0)
  20. const r = (value % 256) / 255.0
  21. return [r, g, b]
  22. }
  23. /** decode float encoded as rgb triplet */
  24. export function decodeFloatRGB(r: number, g: number, b: number) {
  25. return (Math.floor(r) * 256 * 256 + Math.floor(g) * 256 + Math.floor(b)) - 1
  26. }