_transforms.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. 'use strict';
  2. const regTransformTypes = /matrix|translate|scale|rotate|skewX|skewY/;
  3. const regTransformSplit =
  4. /\s*(matrix|translate|scale|rotate|skewX|skewY)\s*\(\s*(.+?)\s*\)[\s,]*/;
  5. const regNumericValues = /[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/g;
  6. /**
  7. * @typedef {{ name: string, data: Array<number> }} TransformItem
  8. */
  9. /**
  10. * Convert transform string to JS representation.
  11. *
  12. * @type {(transformString: string) => Array<TransformItem>}
  13. */
  14. exports.transform2js = (transformString) => {
  15. // JS representation of the transform data
  16. /**
  17. * @type {Array<TransformItem>}
  18. */
  19. const transforms = [];
  20. // current transform context
  21. /**
  22. * @type {null | TransformItem}
  23. */
  24. let current = null;
  25. // split value into ['', 'translate', '10 50', '', 'scale', '2', '', 'rotate', '-45', '']
  26. for (const item of transformString.split(regTransformSplit)) {
  27. var num;
  28. if (item) {
  29. // if item is a translate function
  30. if (regTransformTypes.test(item)) {
  31. // then collect it and change current context
  32. current = { name: item, data: [] };
  33. transforms.push(current);
  34. // else if item is data
  35. } else {
  36. // then split it into [10, 50] and collect as context.data
  37. // eslint-disable-next-line no-cond-assign
  38. while ((num = regNumericValues.exec(item))) {
  39. num = Number(num);
  40. if (current != null) {
  41. current.data.push(num);
  42. }
  43. }
  44. }
  45. }
  46. }
  47. // return empty array if broken transform (no data)
  48. return current == null || current.data.length == 0 ? [] : transforms;
  49. };
  50. /**
  51. * Multiply transforms into one.
  52. *
  53. * @type {(transforms: Array<TransformItem>) => TransformItem}
  54. */
  55. exports.transformsMultiply = (transforms) => {
  56. // convert transforms objects to the matrices
  57. const matrixData = transforms.map((transform) => {
  58. if (transform.name === 'matrix') {
  59. return transform.data;
  60. }
  61. return transformToMatrix(transform);
  62. });
  63. // multiply all matrices into one
  64. const matrixTransform = {
  65. name: 'matrix',
  66. data:
  67. matrixData.length > 0 ? matrixData.reduce(multiplyTransformMatrices) : [],
  68. };
  69. return matrixTransform;
  70. };
  71. /**
  72. * math utilities in radians.
  73. */
  74. const mth = {
  75. /**
  76. * @type {(deg: number) => number}
  77. */
  78. rad: (deg) => {
  79. return (deg * Math.PI) / 180;
  80. },
  81. /**
  82. * @type {(rad: number) => number}
  83. */
  84. deg: (rad) => {
  85. return (rad * 180) / Math.PI;
  86. },
  87. /**
  88. * @type {(deg: number) => number}
  89. */
  90. cos: (deg) => {
  91. return Math.cos(mth.rad(deg));
  92. },
  93. /**
  94. * @type {(val: number, floatPrecision: number) => number}
  95. */
  96. acos: (val, floatPrecision) => {
  97. return Number(mth.deg(Math.acos(val)).toFixed(floatPrecision));
  98. },
  99. /**
  100. * @type {(deg: number) => number}
  101. */
  102. sin: (deg) => {
  103. return Math.sin(mth.rad(deg));
  104. },
  105. /**
  106. * @type {(val: number, floatPrecision: number) => number}
  107. */
  108. asin: (val, floatPrecision) => {
  109. return Number(mth.deg(Math.asin(val)).toFixed(floatPrecision));
  110. },
  111. /**
  112. * @type {(deg: number) => number}
  113. */
  114. tan: (deg) => {
  115. return Math.tan(mth.rad(deg));
  116. },
  117. /**
  118. * @type {(val: number, floatPrecision: number) => number}
  119. */
  120. atan: (val, floatPrecision) => {
  121. return Number(mth.deg(Math.atan(val)).toFixed(floatPrecision));
  122. },
  123. };
  124. /**
  125. * @typedef {{
  126. * convertToShorts: boolean,
  127. * floatPrecision: number,
  128. * transformPrecision: number,
  129. * matrixToTransform: boolean,
  130. * shortTranslate: boolean,
  131. * shortScale: boolean,
  132. * shortRotate: boolean,
  133. * removeUseless: boolean,
  134. * collapseIntoOne: boolean,
  135. * leadingZero: boolean,
  136. * negativeExtraSpace: boolean,
  137. * }} TransformParams
  138. */
  139. /**
  140. * Decompose matrix into simple transforms. See
  141. * https://frederic-wang.fr/decomposition-of-2d-transform-matrices.html
  142. *
  143. * @type {(transform: TransformItem, params: TransformParams) => Array<TransformItem>}
  144. */
  145. exports.matrixToTransform = (transform, params) => {
  146. let floatPrecision = params.floatPrecision;
  147. let data = transform.data;
  148. let transforms = [];
  149. let sx = Number(
  150. Math.hypot(data[0], data[1]).toFixed(params.transformPrecision)
  151. );
  152. let sy = Number(
  153. ((data[0] * data[3] - data[1] * data[2]) / sx).toFixed(
  154. params.transformPrecision
  155. )
  156. );
  157. let colsSum = data[0] * data[2] + data[1] * data[3];
  158. let rowsSum = data[0] * data[1] + data[2] * data[3];
  159. let scaleBefore = rowsSum != 0 || sx == sy;
  160. // [..., ..., ..., ..., tx, ty] → translate(tx, ty)
  161. if (data[4] || data[5]) {
  162. transforms.push({
  163. name: 'translate',
  164. data: data.slice(4, data[5] ? 6 : 5),
  165. });
  166. }
  167. // [sx, 0, tan(a)·sy, sy, 0, 0] → skewX(a)·scale(sx, sy)
  168. if (!data[1] && data[2]) {
  169. transforms.push({
  170. name: 'skewX',
  171. data: [mth.atan(data[2] / sy, floatPrecision)],
  172. });
  173. // [sx, sx·tan(a), 0, sy, 0, 0] → skewY(a)·scale(sx, sy)
  174. } else if (data[1] && !data[2]) {
  175. transforms.push({
  176. name: 'skewY',
  177. data: [mth.atan(data[1] / data[0], floatPrecision)],
  178. });
  179. sx = data[0];
  180. sy = data[3];
  181. // [sx·cos(a), sx·sin(a), sy·-sin(a), sy·cos(a), x, y] → rotate(a[, cx, cy])·(scale or skewX) or
  182. // [sx·cos(a), sy·sin(a), sx·-sin(a), sy·cos(a), x, y] → scale(sx, sy)·rotate(a[, cx, cy]) (if !scaleBefore)
  183. } else if (!colsSum || (sx == 1 && sy == 1) || !scaleBefore) {
  184. if (!scaleBefore) {
  185. sx = (data[0] < 0 ? -1 : 1) * Math.hypot(data[0], data[2]);
  186. sy = (data[3] < 0 ? -1 : 1) * Math.hypot(data[1], data[3]);
  187. transforms.push({ name: 'scale', data: [sx, sy] });
  188. }
  189. var angle = Math.min(Math.max(-1, data[0] / sx), 1),
  190. rotate = [
  191. mth.acos(angle, floatPrecision) *
  192. ((scaleBefore ? 1 : sy) * data[1] < 0 ? -1 : 1),
  193. ];
  194. if (rotate[0]) transforms.push({ name: 'rotate', data: rotate });
  195. if (rowsSum && colsSum)
  196. transforms.push({
  197. name: 'skewX',
  198. data: [mth.atan(colsSum / (sx * sx), floatPrecision)],
  199. });
  200. // rotate(a, cx, cy) can consume translate() within optional arguments cx, cy (rotation point)
  201. if (rotate[0] && (data[4] || data[5])) {
  202. transforms.shift();
  203. var cos = data[0] / sx,
  204. sin = data[1] / (scaleBefore ? sx : sy),
  205. x = data[4] * (scaleBefore ? 1 : sy),
  206. y = data[5] * (scaleBefore ? 1 : sx),
  207. denom =
  208. (Math.pow(1 - cos, 2) + Math.pow(sin, 2)) *
  209. (scaleBefore ? 1 : sx * sy);
  210. rotate.push(((1 - cos) * x - sin * y) / denom);
  211. rotate.push(((1 - cos) * y + sin * x) / denom);
  212. }
  213. // Too many transformations, return original matrix if it isn't just a scale/translate
  214. } else if (data[1] || data[2]) {
  215. return [transform];
  216. }
  217. if ((scaleBefore && (sx != 1 || sy != 1)) || !transforms.length)
  218. transforms.push({
  219. name: 'scale',
  220. data: sx == sy ? [sx] : [sx, sy],
  221. });
  222. return transforms;
  223. };
  224. /**
  225. * Convert transform to the matrix data.
  226. *
  227. * @type {(transform: TransformItem) => Array<number> }
  228. */
  229. const transformToMatrix = (transform) => {
  230. if (transform.name === 'matrix') {
  231. return transform.data;
  232. }
  233. switch (transform.name) {
  234. case 'translate':
  235. // [1, 0, 0, 1, tx, ty]
  236. return [1, 0, 0, 1, transform.data[0], transform.data[1] || 0];
  237. case 'scale':
  238. // [sx, 0, 0, sy, 0, 0]
  239. return [
  240. transform.data[0],
  241. 0,
  242. 0,
  243. transform.data[1] || transform.data[0],
  244. 0,
  245. 0,
  246. ];
  247. case 'rotate':
  248. // [cos(a), sin(a), -sin(a), cos(a), x, y]
  249. var cos = mth.cos(transform.data[0]),
  250. sin = mth.sin(transform.data[0]),
  251. cx = transform.data[1] || 0,
  252. cy = transform.data[2] || 0;
  253. return [
  254. cos,
  255. sin,
  256. -sin,
  257. cos,
  258. (1 - cos) * cx + sin * cy,
  259. (1 - cos) * cy - sin * cx,
  260. ];
  261. case 'skewX':
  262. // [1, 0, tan(a), 1, 0, 0]
  263. return [1, 0, mth.tan(transform.data[0]), 1, 0, 0];
  264. case 'skewY':
  265. // [1, tan(a), 0, 1, 0, 0]
  266. return [1, mth.tan(transform.data[0]), 0, 1, 0, 0];
  267. default:
  268. throw Error(`Unknown transform ${transform.name}`);
  269. }
  270. };
  271. /**
  272. * Applies transformation to an arc. To do so, we represent ellipse as a matrix, multiply it
  273. * by the transformation matrix and use a singular value decomposition to represent in a form
  274. * rotate(θ)·scale(a b)·rotate(φ). This gives us new ellipse params a, b and θ.
  275. * SVD is being done with the formulae provided by Wolffram|Alpha (svd {{m0, m2}, {m1, m3}})
  276. *
  277. * @type {(
  278. * cursor: [x: number, y: number],
  279. * arc: Array<number>,
  280. * transform: Array<number>
  281. * ) => Array<number>}
  282. */
  283. exports.transformArc = (cursor, arc, transform) => {
  284. const x = arc[5] - cursor[0];
  285. const y = arc[6] - cursor[1];
  286. let a = arc[0];
  287. let b = arc[1];
  288. const rot = (arc[2] * Math.PI) / 180;
  289. const cos = Math.cos(rot);
  290. const sin = Math.sin(rot);
  291. // skip if radius is 0
  292. if (a > 0 && b > 0) {
  293. let h =
  294. Math.pow(x * cos + y * sin, 2) / (4 * a * a) +
  295. Math.pow(y * cos - x * sin, 2) / (4 * b * b);
  296. if (h > 1) {
  297. h = Math.sqrt(h);
  298. a *= h;
  299. b *= h;
  300. }
  301. }
  302. const ellipse = [a * cos, a * sin, -b * sin, b * cos, 0, 0];
  303. const m = multiplyTransformMatrices(transform, ellipse);
  304. // Decompose the new ellipse matrix
  305. const lastCol = m[2] * m[2] + m[3] * m[3];
  306. const squareSum = m[0] * m[0] + m[1] * m[1] + lastCol;
  307. const root =
  308. Math.hypot(m[0] - m[3], m[1] + m[2]) * Math.hypot(m[0] + m[3], m[1] - m[2]);
  309. if (!root) {
  310. // circle
  311. arc[0] = arc[1] = Math.sqrt(squareSum / 2);
  312. arc[2] = 0;
  313. } else {
  314. const majorAxisSqr = (squareSum + root) / 2;
  315. const minorAxisSqr = (squareSum - root) / 2;
  316. const major = Math.abs(majorAxisSqr - lastCol) > 1e-6;
  317. const sub = (major ? majorAxisSqr : minorAxisSqr) - lastCol;
  318. const rowsSum = m[0] * m[2] + m[1] * m[3];
  319. const term1 = m[0] * sub + m[2] * rowsSum;
  320. const term2 = m[1] * sub + m[3] * rowsSum;
  321. arc[0] = Math.sqrt(majorAxisSqr);
  322. arc[1] = Math.sqrt(minorAxisSqr);
  323. arc[2] =
  324. (((major ? term2 < 0 : term1 > 0) ? -1 : 1) *
  325. Math.acos((major ? term1 : term2) / Math.hypot(term1, term2)) *
  326. 180) /
  327. Math.PI;
  328. }
  329. if (transform[0] < 0 !== transform[3] < 0) {
  330. // Flip the sweep flag if coordinates are being flipped horizontally XOR vertically
  331. arc[4] = 1 - arc[4];
  332. }
  333. return arc;
  334. };
  335. /**
  336. * Multiply transformation matrices.
  337. *
  338. * @type {(a: Array<number>, b: Array<number>) => Array<number>}
  339. */
  340. const multiplyTransformMatrices = (a, b) => {
  341. return [
  342. a[0] * b[0] + a[2] * b[1],
  343. a[1] * b[0] + a[3] * b[1],
  344. a[0] * b[2] + a[2] * b[3],
  345. a[1] * b[2] + a[3] * b[3],
  346. a[0] * b[4] + a[2] * b[5] + a[4],
  347. a[1] * b[4] + a[3] * b[5] + a[5],
  348. ];
  349. };