number-packing.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /**
  2. * Copyright (c) 2019-2021 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. import { Vec3, Vec4 } from '../mol-math/linear-algebra';
  8. import { NumberArray } from './type-helpers';
  9. /** encode positive integer as rgb byte triplet into array at offset */
  10. export function packIntToRGBArray(value: number, array: NumberArray, offset: number) {
  11. value = clamp(Math.round(value), 0, 16777216 - 1) + 1;
  12. array[offset + 2] = value % 256;
  13. value = Math.floor(value / 256);
  14. array[offset + 1] = value % 256;
  15. value = Math.floor(value / 256);
  16. array[offset] = value % 256;
  17. return array;
  18. }
  19. /** decode positive integer encoded as rgb byte triplet */
  20. export function unpackRGBToInt(r: number, g: number, b: number) {
  21. return (Math.floor(r) * 256 * 256 + Math.floor(g) * 256 + Math.floor(b)) - 1;
  22. }
  23. const UnpackDownscale = 255 / 256; // 0..1 -> fraction (excluding 1)
  24. const PackFactors = Vec3.create(256 * 256 * 256, 256 * 256, 256);
  25. const UnpackFactors = Vec4.create(
  26. UnpackDownscale / PackFactors[0],
  27. UnpackDownscale / PackFactors[1],
  28. UnpackDownscale / PackFactors[2],
  29. UnpackDownscale / 1
  30. );
  31. const tmpDepthRGBA = Vec4();
  32. export function unpackRGBAToDepth(r: number, g: number, b: number, a: number) {
  33. Vec4.set(tmpDepthRGBA, r / 255, g / 255, b / 255, a / 255);
  34. return Vec4.dot(tmpDepthRGBA, UnpackFactors);
  35. }