pattern_helper.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2022 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * JavaScript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.TilingPattern = exports.PathType = void 0;
  27. exports.getShadingPattern = getShadingPattern;
  28. var _util = require("../shared/util.js");
  29. var _is_node = require("../shared/is_node.js");
  30. const PathType = {
  31. FILL: "Fill",
  32. STROKE: "Stroke",
  33. SHADING: "Shading"
  34. };
  35. exports.PathType = PathType;
  36. function applyBoundingBox(ctx, bbox) {
  37. if (!bbox || _is_node.isNodeJS) {
  38. return;
  39. }
  40. const width = bbox[2] - bbox[0];
  41. const height = bbox[3] - bbox[1];
  42. const region = new Path2D();
  43. region.rect(bbox[0], bbox[1], width, height);
  44. ctx.clip(region);
  45. }
  46. class BaseShadingPattern {
  47. constructor() {
  48. if (this.constructor === BaseShadingPattern) {
  49. (0, _util.unreachable)("Cannot initialize BaseShadingPattern.");
  50. }
  51. }
  52. getPattern() {
  53. (0, _util.unreachable)("Abstract method `getPattern` called.");
  54. }
  55. }
  56. class RadialAxialShadingPattern extends BaseShadingPattern {
  57. constructor(IR) {
  58. super();
  59. this._type = IR[1];
  60. this._bbox = IR[2];
  61. this._colorStops = IR[3];
  62. this._p0 = IR[4];
  63. this._p1 = IR[5];
  64. this._r0 = IR[6];
  65. this._r1 = IR[7];
  66. this.matrix = null;
  67. }
  68. _createGradient(ctx) {
  69. let grad;
  70. if (this._type === "axial") {
  71. grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
  72. } else if (this._type === "radial") {
  73. grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
  74. }
  75. for (const colorStop of this._colorStops) {
  76. grad.addColorStop(colorStop[0], colorStop[1]);
  77. }
  78. return grad;
  79. }
  80. getPattern(ctx, owner, inverse, pathType) {
  81. let pattern;
  82. if (pathType === PathType.STROKE || pathType === PathType.FILL) {
  83. const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, ctx.mozCurrentTransform) || [0, 0, 0, 0];
  84. const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
  85. const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
  86. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height, true);
  87. const tmpCtx = tmpCanvas.context;
  88. tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  89. tmpCtx.beginPath();
  90. tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  91. tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
  92. inverse = _util.Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
  93. tmpCtx.transform.apply(tmpCtx, owner.baseTransform);
  94. if (this.matrix) {
  95. tmpCtx.transform.apply(tmpCtx, this.matrix);
  96. }
  97. applyBoundingBox(tmpCtx, this._bbox);
  98. tmpCtx.fillStyle = this._createGradient(tmpCtx);
  99. tmpCtx.fill();
  100. pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
  101. const domMatrix = new DOMMatrix(inverse);
  102. try {
  103. pattern.setTransform(domMatrix);
  104. } catch (ex) {
  105. (0, _util.warn)(`RadialAxialShadingPattern.getPattern: "${ex?.message}".`);
  106. }
  107. } else {
  108. applyBoundingBox(ctx, this._bbox);
  109. pattern = this._createGradient(ctx);
  110. }
  111. return pattern;
  112. }
  113. }
  114. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  115. const coords = context.coords,
  116. colors = context.colors;
  117. const bytes = data.data,
  118. rowSize = data.width * 4;
  119. let tmp;
  120. if (coords[p1 + 1] > coords[p2 + 1]) {
  121. tmp = p1;
  122. p1 = p2;
  123. p2 = tmp;
  124. tmp = c1;
  125. c1 = c2;
  126. c2 = tmp;
  127. }
  128. if (coords[p2 + 1] > coords[p3 + 1]) {
  129. tmp = p2;
  130. p2 = p3;
  131. p3 = tmp;
  132. tmp = c2;
  133. c2 = c3;
  134. c3 = tmp;
  135. }
  136. if (coords[p1 + 1] > coords[p2 + 1]) {
  137. tmp = p1;
  138. p1 = p2;
  139. p2 = tmp;
  140. tmp = c1;
  141. c1 = c2;
  142. c2 = tmp;
  143. }
  144. const x1 = (coords[p1] + context.offsetX) * context.scaleX;
  145. const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  146. const x2 = (coords[p2] + context.offsetX) * context.scaleX;
  147. const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  148. const x3 = (coords[p3] + context.offsetX) * context.scaleX;
  149. const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  150. if (y1 >= y3) {
  151. return;
  152. }
  153. const c1r = colors[c1],
  154. c1g = colors[c1 + 1],
  155. c1b = colors[c1 + 2];
  156. const c2r = colors[c2],
  157. c2g = colors[c2 + 1],
  158. c2b = colors[c2 + 2];
  159. const c3r = colors[c3],
  160. c3g = colors[c3 + 1],
  161. c3b = colors[c3 + 2];
  162. const minY = Math.round(y1),
  163. maxY = Math.round(y3);
  164. let xa, car, cag, cab;
  165. let xb, cbr, cbg, cbb;
  166. for (let y = minY; y <= maxY; y++) {
  167. if (y < y2) {
  168. let k;
  169. if (y < y1) {
  170. k = 0;
  171. } else {
  172. k = (y1 - y) / (y1 - y2);
  173. }
  174. xa = x1 - (x1 - x2) * k;
  175. car = c1r - (c1r - c2r) * k;
  176. cag = c1g - (c1g - c2g) * k;
  177. cab = c1b - (c1b - c2b) * k;
  178. } else {
  179. let k;
  180. if (y > y3) {
  181. k = 1;
  182. } else if (y2 === y3) {
  183. k = 0;
  184. } else {
  185. k = (y2 - y) / (y2 - y3);
  186. }
  187. xa = x2 - (x2 - x3) * k;
  188. car = c2r - (c2r - c3r) * k;
  189. cag = c2g - (c2g - c3g) * k;
  190. cab = c2b - (c2b - c3b) * k;
  191. }
  192. let k;
  193. if (y < y1) {
  194. k = 0;
  195. } else if (y > y3) {
  196. k = 1;
  197. } else {
  198. k = (y1 - y) / (y1 - y3);
  199. }
  200. xb = x1 - (x1 - x3) * k;
  201. cbr = c1r - (c1r - c3r) * k;
  202. cbg = c1g - (c1g - c3g) * k;
  203. cbb = c1b - (c1b - c3b) * k;
  204. const x1_ = Math.round(Math.min(xa, xb));
  205. const x2_ = Math.round(Math.max(xa, xb));
  206. let j = rowSize * y + x1_ * 4;
  207. for (let x = x1_; x <= x2_; x++) {
  208. k = (xa - x) / (xa - xb);
  209. if (k < 0) {
  210. k = 0;
  211. } else if (k > 1) {
  212. k = 1;
  213. }
  214. bytes[j++] = car - (car - cbr) * k | 0;
  215. bytes[j++] = cag - (cag - cbg) * k | 0;
  216. bytes[j++] = cab - (cab - cbb) * k | 0;
  217. bytes[j++] = 255;
  218. }
  219. }
  220. }
  221. function drawFigure(data, figure, context) {
  222. const ps = figure.coords;
  223. const cs = figure.colors;
  224. let i, ii;
  225. switch (figure.type) {
  226. case "lattice":
  227. const verticesPerRow = figure.verticesPerRow;
  228. const rows = Math.floor(ps.length / verticesPerRow) - 1;
  229. const cols = verticesPerRow - 1;
  230. for (i = 0; i < rows; i++) {
  231. let q = i * verticesPerRow;
  232. for (let j = 0; j < cols; j++, q++) {
  233. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  234. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  235. }
  236. }
  237. break;
  238. case "triangles":
  239. for (i = 0, ii = ps.length; i < ii; i += 3) {
  240. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  241. }
  242. break;
  243. default:
  244. throw new Error("illegal figure");
  245. }
  246. }
  247. class MeshShadingPattern extends BaseShadingPattern {
  248. constructor(IR) {
  249. super();
  250. this._coords = IR[2];
  251. this._colors = IR[3];
  252. this._figures = IR[4];
  253. this._bounds = IR[5];
  254. this._bbox = IR[7];
  255. this._background = IR[8];
  256. this.matrix = null;
  257. }
  258. _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
  259. const EXPECTED_SCALE = 1.1;
  260. const MAX_PATTERN_SIZE = 3000;
  261. const BORDER_SIZE = 2;
  262. const offsetX = Math.floor(this._bounds[0]);
  263. const offsetY = Math.floor(this._bounds[1]);
  264. const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
  265. const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
  266. const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  267. const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  268. const scaleX = boundsWidth / width;
  269. const scaleY = boundsHeight / height;
  270. const context = {
  271. coords: this._coords,
  272. colors: this._colors,
  273. offsetX: -offsetX,
  274. offsetY: -offsetY,
  275. scaleX: 1 / scaleX,
  276. scaleY: 1 / scaleY
  277. };
  278. const paddedWidth = width + BORDER_SIZE * 2;
  279. const paddedHeight = height + BORDER_SIZE * 2;
  280. const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight, false);
  281. const tmpCtx = tmpCanvas.context;
  282. const data = tmpCtx.createImageData(width, height);
  283. if (backgroundColor) {
  284. const bytes = data.data;
  285. for (let i = 0, ii = bytes.length; i < ii; i += 4) {
  286. bytes[i] = backgroundColor[0];
  287. bytes[i + 1] = backgroundColor[1];
  288. bytes[i + 2] = backgroundColor[2];
  289. bytes[i + 3] = 255;
  290. }
  291. }
  292. for (const figure of this._figures) {
  293. drawFigure(data, figure, context);
  294. }
  295. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  296. const canvas = tmpCanvas.canvas;
  297. return {
  298. canvas,
  299. offsetX: offsetX - BORDER_SIZE * scaleX,
  300. offsetY: offsetY - BORDER_SIZE * scaleY,
  301. scaleX,
  302. scaleY
  303. };
  304. }
  305. getPattern(ctx, owner, inverse, pathType) {
  306. applyBoundingBox(ctx, this._bbox);
  307. let scale;
  308. if (pathType === PathType.SHADING) {
  309. scale = _util.Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  310. } else {
  311. scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform);
  312. if (this.matrix) {
  313. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  314. scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
  315. }
  316. }
  317. const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
  318. if (pathType !== PathType.SHADING) {
  319. ctx.setTransform.apply(ctx, owner.baseTransform);
  320. if (this.matrix) {
  321. ctx.transform.apply(ctx, this.matrix);
  322. }
  323. }
  324. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  325. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  326. return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
  327. }
  328. }
  329. class DummyShadingPattern extends BaseShadingPattern {
  330. getPattern() {
  331. return "hotpink";
  332. }
  333. }
  334. function getShadingPattern(IR) {
  335. switch (IR[0]) {
  336. case "RadialAxial":
  337. return new RadialAxialShadingPattern(IR);
  338. case "Mesh":
  339. return new MeshShadingPattern(IR);
  340. case "Dummy":
  341. return new DummyShadingPattern();
  342. }
  343. throw new Error(`Unknown IR type: ${IR[0]}`);
  344. }
  345. const PaintType = {
  346. COLORED: 1,
  347. UNCOLORED: 2
  348. };
  349. class TilingPattern {
  350. static get MAX_PATTERN_SIZE() {
  351. return (0, _util.shadow)(this, "MAX_PATTERN_SIZE", 3000);
  352. }
  353. constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  354. this.operatorList = IR[2];
  355. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  356. this.bbox = IR[4];
  357. this.xstep = IR[5];
  358. this.ystep = IR[6];
  359. this.paintType = IR[7];
  360. this.tilingType = IR[8];
  361. this.color = color;
  362. this.ctx = ctx;
  363. this.canvasGraphicsFactory = canvasGraphicsFactory;
  364. this.baseTransform = baseTransform;
  365. }
  366. createPatternCanvas(owner) {
  367. const operatorList = this.operatorList;
  368. const bbox = this.bbox;
  369. const xstep = this.xstep;
  370. const ystep = this.ystep;
  371. const paintType = this.paintType;
  372. const tilingType = this.tilingType;
  373. const color = this.color;
  374. const canvasGraphicsFactory = this.canvasGraphicsFactory;
  375. (0, _util.info)("TilingType: " + tilingType);
  376. const x0 = bbox[0],
  377. y0 = bbox[1],
  378. x1 = bbox[2],
  379. y1 = bbox[3];
  380. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  381. const curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform);
  382. const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
  383. const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
  384. const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
  385. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size, true);
  386. const tmpCtx = tmpCanvas.context;
  387. const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  388. graphics.groupLevel = owner.groupLevel;
  389. this.setFillAndStrokeStyleToContext(graphics, paintType, color);
  390. let adjustedX0 = x0;
  391. let adjustedY0 = y0;
  392. let adjustedX1 = x1;
  393. let adjustedY1 = y1;
  394. if (x0 < 0) {
  395. adjustedX0 = 0;
  396. adjustedX1 += Math.abs(x0);
  397. }
  398. if (y0 < 0) {
  399. adjustedY0 = 0;
  400. adjustedY1 += Math.abs(y0);
  401. }
  402. tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0));
  403. graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
  404. tmpCtx.save();
  405. this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1);
  406. graphics.baseTransform = graphics.ctx.mozCurrentTransform.slice();
  407. graphics.executeOperatorList(operatorList);
  408. graphics.endDrawing();
  409. return {
  410. canvas: tmpCanvas.canvas,
  411. scaleX: dimx.scale,
  412. scaleY: dimy.scale,
  413. offsetX: adjustedX0,
  414. offsetY: adjustedY0
  415. };
  416. }
  417. getSizeAndScale(step, realOutputSize, scale) {
  418. step = Math.abs(step);
  419. const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
  420. let size = Math.ceil(step * scale);
  421. if (size >= maxSize) {
  422. size = maxSize;
  423. } else {
  424. scale = size / step;
  425. }
  426. return {
  427. scale,
  428. size
  429. };
  430. }
  431. clipBbox(graphics, x0, y0, x1, y1) {
  432. const bboxWidth = x1 - x0;
  433. const bboxHeight = y1 - y0;
  434. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  435. graphics.current.updateRectMinMax(graphics.ctx.mozCurrentTransform, [x0, y0, x1, y1]);
  436. graphics.clip();
  437. graphics.endPath();
  438. }
  439. setFillAndStrokeStyleToContext(graphics, paintType, color) {
  440. const context = graphics.ctx,
  441. current = graphics.current;
  442. switch (paintType) {
  443. case PaintType.COLORED:
  444. const ctx = this.ctx;
  445. context.fillStyle = ctx.fillStyle;
  446. context.strokeStyle = ctx.strokeStyle;
  447. current.fillColor = ctx.fillStyle;
  448. current.strokeColor = ctx.strokeStyle;
  449. break;
  450. case PaintType.UNCOLORED:
  451. const cssColor = _util.Util.makeHexColor(color[0], color[1], color[2]);
  452. context.fillStyle = cssColor;
  453. context.strokeStyle = cssColor;
  454. current.fillColor = cssColor;
  455. current.strokeColor = cssColor;
  456. break;
  457. default:
  458. throw new _util.FormatError(`Unsupported paint type: ${paintType}`);
  459. }
  460. }
  461. getPattern(ctx, owner, inverse, pathType) {
  462. let matrix = inverse;
  463. if (pathType !== PathType.SHADING) {
  464. matrix = _util.Util.transform(matrix, owner.baseTransform);
  465. if (this.matrix) {
  466. matrix = _util.Util.transform(matrix, this.matrix);
  467. }
  468. }
  469. const temporaryPatternCanvas = this.createPatternCanvas(owner);
  470. let domMatrix = new DOMMatrix(matrix);
  471. domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  472. domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
  473. const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
  474. try {
  475. pattern.setTransform(domMatrix);
  476. } catch (ex) {
  477. (0, _util.warn)(`TilingPattern.getPattern: "${ex?.message}".`);
  478. }
  479. return pattern;
  480. }
  481. }
  482. exports.TilingPattern = TilingPattern;