units.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include "units.hpp"
  2. #define PI 3.14159265358979323846
  3. namespace Sass {
  4. double conversion_factors[10][10] = {
  5. /* in cm pc mm pt px deg grad rad turn */
  6. /* in */ { 1, 2.54, 6, 25.4, 72, 96, 1, 1, 1, 1 },
  7. /* cm */ { 1.0/2.54, 1, 6.0/2.54, 10, 72.0/2.54, 96.0/2.54, 1, 1, 1, 1 },
  8. /* pc */ { 1.0/6.0, 2.54/6.0, 1, 25.4/6.0, 72.0/6.0, 96.0/6.0, 1, 1, 1, 1 },
  9. /* mm */ { 1.0/25.4, 1.0/10.0, 6.0/25.4, 1, 72.0/25.4, 96.0/25.4, 1, 1, 1, 1 },
  10. /* pt */ { 1.0/72.0, 2.54/72.0, 6.0/72.0, 25.4/72.0, 1, 96.0/72.0, 1, 1, 1, 1 },
  11. /* px */ { 1.0/96.0, 2.54/96.0, 6.0/96.0, 25.4/96.0, 72.0/96.0, 1, 1, 1, 1, 1 },
  12. /* deg */ { 1 , 1 , 1 , 1 , 1 , 1, 1, 40.0/36.0, PI/180.0, 1.0/360.0 },
  13. /* grad */ { 1 , 1 , 1 , 1 , 1 , 1, 36.0/40.0, 1, PI/200.0, 1.0/400.0 },
  14. /* rad */ { 1 , 1 , 1 , 1 , 1 , 1, 180.0/PI, 200.0/PI, 1, PI/2.0 },
  15. /* turn */ { 1 , 1 , 1 , 1 , 1 , 1, 360.0/1.0, 400.0/1.0, 2.0*PI, 1 }
  16. };
  17. Unit string_to_unit(const string& s)
  18. {
  19. if (s == "in") return IN;
  20. else if (s == "cm") return CM;
  21. else if (s == "pc") return PC;
  22. else if (s == "mm") return MM;
  23. else if (s == "pt") return PT;
  24. else if (s == "px") return PX;
  25. else if (s == "deg") return DEG;
  26. else if (s == "grad") return GRAD;
  27. else if (s == "rad") return RAD;
  28. else if (s == "turn") return TURN;
  29. else return INCOMMENSURABLE;
  30. }
  31. double conversion_factor(const string& s1, const string& s2)
  32. {
  33. Unit u1 = string_to_unit(s1);
  34. Unit u2 = string_to_unit(s2);
  35. double factor;
  36. if (u1 == INCOMMENSURABLE || u2 == INCOMMENSURABLE)
  37. factor = 0;
  38. else
  39. factor = conversion_factors[u1][u2];
  40. return factor;
  41. }
  42. double convert(double n, const string& from, const string& to)
  43. {
  44. double factor = conversion_factor(from, to);
  45. return factor ? factor * n : n;
  46. }
  47. }