• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Adds JS functions to augment the CanvasKit interface.
2// For example, if there is a wrapper around the C++ call or logic to allow
3// chaining, it should go here.
4
5// CanvasKit.onRuntimeInitialized is called after the WASM library has loaded.
6// Anything that modifies an exposed class (e.g. Path) should be set
7// after onRuntimeInitialized, otherwise, it can happen outside of that scope.
8CanvasKit.onRuntimeInitialized = function() {
9  // All calls to 'this' need to go in externs.js so closure doesn't minify them away.
10
11  _scratchColor = CanvasKit.Malloc(Float32Array, 4); // 4 color scalars.
12  _scratchColorPtr = _scratchColor['byteOffset'];
13
14  _scratch4x4Matrix = CanvasKit.Malloc(Float32Array, 16); // 16 matrix scalars.
15  _scratch4x4MatrixPtr = _scratch4x4Matrix['byteOffset'];
16
17  _scratch3x3Matrix = CanvasKit.Malloc(Float32Array, 9); // 9 matrix scalars.
18  _scratch3x3MatrixPtr = _scratch3x3Matrix['byteOffset'];
19
20  _scratchRRect = CanvasKit.Malloc(Float32Array, 12); // 4 scalars for rrect, 8 for radii.
21  _scratchRRectPtr = _scratchRRect['byteOffset'];
22
23  _scratchRRect2 = CanvasKit.Malloc(Float32Array, 12); // 4 scalars for rrect, 8 for radii.
24  _scratchRRect2Ptr = _scratchRRect2['byteOffset'];
25
26  _scratchFourFloatsA = CanvasKit.Malloc(Float32Array, 4);
27  _scratchFourFloatsAPtr = _scratchFourFloatsA['byteOffset'];
28
29  _scratchFourFloatsB = CanvasKit.Malloc(Float32Array, 4);
30  _scratchFourFloatsBPtr = _scratchFourFloatsB['byteOffset'];
31
32  _scratchThreeFloatsA = CanvasKit.Malloc(Float32Array, 3); // 3 floats to represent SkVector3
33  _scratchThreeFloatsAPtr = _scratchThreeFloatsA['byteOffset'];
34
35  _scratchThreeFloatsB = CanvasKit.Malloc(Float32Array, 3); // 3 floats to represent SkVector3
36  _scratchThreeFloatsBPtr = _scratchThreeFloatsB['byteOffset'];
37
38  _scratchIRect = CanvasKit.Malloc(Int32Array, 4);
39  _scratchIRectPtr = _scratchIRect['byteOffset'];
40
41  // Create single copies of all three supported color spaces
42  // These are sk_sp<ColorSpace>
43  CanvasKit.ColorSpace.SRGB = CanvasKit.ColorSpace._MakeSRGB();
44  CanvasKit.ColorSpace.DISPLAY_P3 = CanvasKit.ColorSpace._MakeDisplayP3();
45  CanvasKit.ColorSpace.ADOBE_RGB = CanvasKit.ColorSpace._MakeAdobeRGB();
46
47  // Use quotes to tell closure compiler not to minify the names
48  CanvasKit['GlyphRunFlags'] = {
49    'IsWhiteSpace': CanvasKit['_GlyphRunFlags_isWhiteSpace'],
50  };
51
52  CanvasKit.Path.MakeFromCmds = function(cmds) {
53    var cmdPtr = copy1dArray(cmds, 'HEAPF32');
54    var path = CanvasKit.Path._MakeFromCmds(cmdPtr, cmds.length);
55    freeArraysThatAreNotMallocedByUsers(cmdPtr, cmds);
56    return path;
57  };
58
59  // The weights array is optional (only used for conics).
60  CanvasKit.Path.MakeFromVerbsPointsWeights = function(verbs, pts, weights) {
61    var verbsPtr = copy1dArray(verbs, 'HEAPU8');
62    var pointsPtr = copy1dArray(pts, 'HEAPF32');
63    var weightsPtr = copy1dArray(weights, 'HEAPF32');
64    var numWeights = (weights && weights.length) || 0;
65    var path = CanvasKit.Path._MakeFromVerbsPointsWeights(
66        verbsPtr, verbs.length, pointsPtr, pts.length, weightsPtr, numWeights);
67    freeArraysThatAreNotMallocedByUsers(verbsPtr, verbs);
68    freeArraysThatAreNotMallocedByUsers(pointsPtr, pts);
69    freeArraysThatAreNotMallocedByUsers(weightsPtr, weights);
70    return path;
71  };
72
73  CanvasKit.Path.prototype.addArc = function(oval, startAngle, sweepAngle) {
74    // see arc() for the HTMLCanvas version
75    // note input angles are degrees.
76    var oPtr = copyRectToWasm(oval);
77    this._addArc(oPtr, startAngle, sweepAngle);
78    return this;
79  };
80
81  CanvasKit.Path.prototype.addCircle = function(x, y, r, isCCW) {
82    this._addCircle(x, y, r, !!isCCW);
83    return this;
84  };
85
86  CanvasKit.Path.prototype.addOval = function(oval, isCCW, startIndex) {
87    if (startIndex === undefined) {
88      startIndex = 1;
89    }
90    var oPtr = copyRectToWasm(oval);
91    this._addOval(oPtr, !!isCCW, startIndex);
92    return this;
93  };
94
95  // TODO(kjlubick) clean up this API - split it apart if necessary
96  CanvasKit.Path.prototype.addPath = function() {
97    // Takes 1, 2, 7, or 10 required args, where the first arg is always the path.
98    // The last arg is optional and chooses between add or extend mode.
99    // The options for the remaining args are:
100    //   - an array of 6 or 9 parameters (perspective is optional)
101    //   - the 9 parameters of a full matrix or
102    //     the 6 non-perspective params of a matrix.
103    var args = Array.prototype.slice.call(arguments);
104    var path = args[0];
105    var extend = false;
106    if (typeof args[args.length-1] === 'boolean') {
107      extend = args.pop();
108    }
109    if (args.length === 1) {
110      // Add path, unchanged.  Use identity matrix
111      this._addPath(path, 1, 0, 0,
112                          0, 1, 0,
113                          0, 0, 1,
114                          extend);
115    } else if (args.length === 2) {
116      // User provided the 9 params of a full matrix as an array.
117      var a = args[1];
118      this._addPath(path, a[0],      a[1],      a[2],
119                          a[3],      a[4],      a[5],
120                          a[6] || 0, a[7] || 0, a[8] || 1,
121                          extend);
122    } else if (args.length === 7 || args.length === 10) {
123      // User provided the 9 params of a (full) matrix directly.
124      // (or just the 6 non perspective ones)
125      // These are in the same order as what Skia expects.
126      var a = args;
127      this._addPath(path, a[1],      a[2],      a[3],
128                          a[4],      a[5],      a[6],
129                          a[7] || 0, a[8] || 0, a[9] || 1,
130                          extend);
131    } else {
132      Debug('addPath expected to take 1, 2, 7, or 10 required args. Got ' + args.length);
133      return null;
134    }
135    return this;
136  };
137
138  // points is a 1d array of length 2n representing n points where the even indices
139  // will be treated as x coordinates and the odd indices will be treated as y coordinates.
140  // Like other APIs, this accepts a malloced type array or malloc obj.
141  CanvasKit.Path.prototype.addPoly = function(points, close) {
142    var ptr = copy1dArray(points, 'HEAPF32');
143    this._addPoly(ptr, points.length / 2, close);
144    freeArraysThatAreNotMallocedByUsers(ptr, points);
145    return this;
146  };
147
148  CanvasKit.Path.prototype.addRect = function(rect, isCCW) {
149    var rPtr = copyRectToWasm(rect);
150    this._addRect(rPtr, !!isCCW);
151    return this;
152  };
153
154  CanvasKit.Path.prototype.addRRect = function(rrect, isCCW) {
155    var rPtr = copyRRectToWasm(rrect);
156    this._addRRect(rPtr, !!isCCW);
157    return this;
158  };
159
160  // The weights array is optional (only used for conics).
161  CanvasKit.Path.prototype.addVerbsPointsWeights = function(verbs, points, weights) {
162    var verbsPtr = copy1dArray(verbs, 'HEAPU8');
163    var pointsPtr = copy1dArray(points, 'HEAPF32');
164    var weightsPtr = copy1dArray(weights, 'HEAPF32');
165    var numWeights = (weights && weights.length) || 0;
166    this._addVerbsPointsWeights(verbsPtr, verbs.length, pointsPtr, points.length,
167                                weightsPtr, numWeights);
168    freeArraysThatAreNotMallocedByUsers(verbsPtr, verbs);
169    freeArraysThatAreNotMallocedByUsers(pointsPtr, points);
170    freeArraysThatAreNotMallocedByUsers(weightsPtr, weights);
171  };
172
173  CanvasKit.Path.prototype.arc = function(x, y, radius, startAngle, endAngle, ccw) {
174    // emulates the HTMLCanvas behavior.  See addArc() for the Path version.
175    // Note input angles are radians.
176    var bounds = CanvasKit.LTRBRect(x-radius, y-radius, x+radius, y+radius);
177    var sweep = radiansToDegrees(endAngle - startAngle) - (360 * !!ccw);
178    var temp = new CanvasKit.Path();
179    temp.addArc(bounds, radiansToDegrees(startAngle), sweep);
180    this.addPath(temp, true);
181    temp.delete();
182    return this;
183  };
184
185  // Appends arc to Path. Arc added is part of ellipse
186  // bounded by oval, from startAngle through sweepAngle. Both startAngle and
187  // sweepAngle are measured in degrees, where zero degrees is aligned with the
188  // positive x-axis, and positive sweeps extends arc clockwise.
189  CanvasKit.Path.prototype.arcToOval = function(oval, startAngle, sweepAngle, forceMoveTo) {
190    var oPtr = copyRectToWasm(oval);
191    this._arcToOval(oPtr, startAngle, sweepAngle, forceMoveTo);
192    return this;
193  };
194
195  // Appends arc to Path. Arc is implemented by one or more conics weighted to
196  // describe part of oval with radii (rx, ry) rotated by xAxisRotate degrees. Arc
197  // curves from last point to (x, y), choosing one of four possible routes:
198  // clockwise or counterclockwise, and smaller or larger.
199
200  // Arc sweep is always less than 360 degrees. arcTo() appends line to (x, y) if
201  // either radii are zero, or if last point equals (x, y). arcTo() scales radii
202  // (rx, ry) to fit last point and (x, y) if both are greater than zero but
203  // too small.
204
205  // arcToRotated() appends up to four conic curves.
206  // arcToRotated() implements the functionality of SVG arc, although SVG sweep-flag value
207  // is opposite the integer value of sweep; SVG sweep-flag uses 1 for clockwise,
208  // while kCW_Direction cast to int is zero.
209  CanvasKit.Path.prototype.arcToRotated = function(rx, ry, xAxisRotate, useSmallArc, isCCW, x, y) {
210    this._arcToRotated(rx, ry, xAxisRotate, !!useSmallArc, !!isCCW, x, y);
211    return this;
212  };
213
214  // Appends arc to Path, after appending line if needed. Arc is implemented by conic
215  // weighted to describe part of circle. Arc is contained by tangent from
216  // last Path point to (x1, y1), and tangent from (x1, y1) to (x2, y2). Arc
217  // is part of circle sized to radius, positioned so it touches both tangent lines.
218
219  // If last Path Point does not start Arc, arcTo appends connecting Line to Path.
220  // The length of Vector from (x1, y1) to (x2, y2) does not affect Arc.
221
222  // Arc sweep is always less than 180 degrees. If radius is zero, or if
223  // tangents are nearly parallel, arcTo appends Line from last Path Point to (x1, y1).
224
225  // arcToTangent appends at most one Line and one conic.
226  // arcToTangent implements the functionality of PostScript arct and HTML Canvas arcTo.
227  CanvasKit.Path.prototype.arcToTangent = function(x1, y1, x2, y2, radius) {
228    this._arcToTangent(x1, y1, x2, y2, radius);
229    return this;
230  };
231
232  CanvasKit.Path.prototype.close = function() {
233    this._close();
234    return this;
235  };
236
237  CanvasKit.Path.prototype.conicTo = function(x1, y1, x2, y2, w) {
238    this._conicTo(x1, y1, x2, y2, w);
239    return this;
240  };
241
242  // Clients can pass in a Float32Array with length 4 to this and the results
243  // will be copied into that array. Otherwise, a new TypedArray will be allocated
244  // and returned.
245  CanvasKit.Path.prototype.computeTightBounds = function(optionalOutputArray) {
246    this._computeTightBounds(_scratchFourFloatsAPtr);
247    var ta = _scratchFourFloatsA['toTypedArray']();
248    if (optionalOutputArray) {
249      optionalOutputArray.set(ta);
250      return optionalOutputArray;
251    }
252    return ta.slice();
253  };
254
255  CanvasKit.Path.prototype.cubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
256    this._cubicTo(cp1x, cp1y, cp2x, cp2y, x, y);
257    return this;
258  };
259
260  CanvasKit.Path.prototype.dash = function(on, off, phase) {
261    if (this._dash(on, off, phase)) {
262      return this;
263    }
264    return null;
265  };
266
267  // Clients can pass in a Float32Array with length 4 to this and the results
268  // will be copied into that array. Otherwise, a new TypedArray will be allocated
269  // and returned.
270  CanvasKit.Path.prototype.getBounds = function(optionalOutputArray) {
271    this._getBounds(_scratchFourFloatsAPtr);
272    var ta = _scratchFourFloatsA['toTypedArray']();
273    if (optionalOutputArray) {
274      optionalOutputArray.set(ta);
275      return optionalOutputArray;
276    }
277    return ta.slice();
278  };
279
280  CanvasKit.Path.prototype.lineTo = function(x, y) {
281    this._lineTo(x, y);
282    return this;
283  };
284
285  CanvasKit.Path.prototype.moveTo = function(x, y) {
286    this._moveTo(x, y);
287    return this;
288  };
289
290  CanvasKit.Path.prototype.offset = function(dx, dy) {
291    this._transform(1, 0, dx,
292                    0, 1, dy,
293                    0, 0, 1);
294    return this;
295  };
296
297  CanvasKit.Path.prototype.quadTo = function(cpx, cpy, x, y) {
298    this._quadTo(cpx, cpy, x, y);
299    return this;
300  };
301
302 CanvasKit.Path.prototype.rArcTo = function(rx, ry, xAxisRotate, useSmallArc, isCCW, dx, dy) {
303    this._rArcTo(rx, ry, xAxisRotate, useSmallArc, isCCW, dx, dy);
304    return this;
305  };
306
307  CanvasKit.Path.prototype.rConicTo = function(dx1, dy1, dx2, dy2, w) {
308    this._rConicTo(dx1, dy1, dx2, dy2, w);
309    return this;
310  };
311
312  // These params are all relative
313  CanvasKit.Path.prototype.rCubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
314    this._rCubicTo(cp1x, cp1y, cp2x, cp2y, x, y);
315    return this;
316  };
317
318  CanvasKit.Path.prototype.rLineTo = function(dx, dy) {
319    this._rLineTo(dx, dy);
320    return this;
321  };
322
323  CanvasKit.Path.prototype.rMoveTo = function(dx, dy) {
324    this._rMoveTo(dx, dy);
325    return this;
326  };
327
328  // These params are all relative
329  CanvasKit.Path.prototype.rQuadTo = function(cpx, cpy, x, y) {
330    this._rQuadTo(cpx, cpy, x, y);
331    return this;
332  };
333
334  CanvasKit.Path.prototype.stroke = function(opts) {
335    // Fill out any missing values with the default values.
336    opts = opts || {};
337    opts['width'] = opts['width'] || 1;
338    opts['miter_limit'] = opts['miter_limit'] || 4;
339    opts['cap'] = opts['cap'] || CanvasKit.StrokeCap.Butt;
340    opts['join'] = opts['join'] || CanvasKit.StrokeJoin.Miter;
341    opts['precision'] = opts['precision'] || 1;
342    if (this._stroke(opts)) {
343      return this;
344    }
345    return null;
346  };
347
348  // TODO(kjlubick) Change this to take a 3x3 or 4x4 matrix (optionally malloc'd)
349  CanvasKit.Path.prototype.transform = function() {
350    // Takes 1 or 9 args
351    if (arguments.length === 1) {
352      // argument 1 should be a 6 or 9 element array.
353      var a = arguments[0];
354      this._transform(a[0], a[1], a[2],
355                      a[3], a[4], a[5],
356                      a[6] || 0, a[7] || 0, a[8] || 1);
357    } else if (arguments.length === 6 || arguments.length === 9) {
358      // these arguments are the 6 or 9 members of the matrix
359      var a = arguments;
360      this._transform(a[0], a[1], a[2],
361                      a[3], a[4], a[5],
362                      a[6] || 0, a[7] || 0, a[8] || 1);
363    } else {
364      throw 'transform expected to take 1 or 9 arguments. Got ' + arguments.length;
365    }
366    return this;
367  };
368
369  // isComplement is optional, defaults to false
370  CanvasKit.Path.prototype.trim = function(startT, stopT, isComplement) {
371    if (this._trim(startT, stopT, !!isComplement)) {
372      return this;
373    }
374    return null;
375  };
376
377  CanvasKit.Image.prototype.encodeToBytes = function(fmt, quality) {
378    var grCtx = CanvasKit.getCurrentGrDirectContext();
379    fmt = fmt || CanvasKit.ImageFormat.PNG;
380    quality = quality || 100;
381    if (grCtx) {
382      return this._encodeToBytes(fmt, quality, grCtx);
383    } else {
384      return this._encodeToBytes(fmt, quality);
385    }
386  };
387
388  // makeShaderCubic returns a shader for a given image, allowing it to be used on
389  // a paint as well as other purposes. This shader will be higher quality than
390  // other shader functions. See CubicResampler in SkSamplingOptions.h for more information
391  // on the cubicResampler params.
392  CanvasKit.Image.prototype.makeShaderCubic = function(xTileMode, yTileMode,
393                                                       cubicResamplerB, cubicResamplerC,
394                                                       localMatrix) {
395    var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
396    return this._makeShaderCubic(xTileMode, yTileMode, cubicResamplerB,
397                                 cubicResamplerC, localMatrixPtr);
398  };
399
400  // makeShaderCubic returns a shader for a given image, allowing it to be used on
401  // a paint as well as other purposes. This shader will draw more quickly than
402  // other shader functions, but at a lower quality.
403  CanvasKit.Image.prototype.makeShaderOptions = function(xTileMode, yTileMode,
404                                                         filterMode, mipmapMode,
405                                                         localMatrix) {
406    var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
407    return this._makeShaderOptions(xTileMode, yTileMode, filterMode, mipmapMode, localMatrixPtr);
408  };
409
410  function readPixels(source, srcX, srcY, imageInfo, destMallocObj, bytesPerRow, grCtx) {
411    if (!bytesPerRow) {
412      bytesPerRow = 4 * imageInfo['width'];
413      if (imageInfo['colorType'] === CanvasKit.ColorType.RGBA_F16) {
414        bytesPerRow *= 2;
415      }
416      else if (imageInfo['colorType'] === CanvasKit.ColorType.RGBA_F32) {
417        bytesPerRow *= 4;
418      }
419    }
420    var pBytes = bytesPerRow * imageInfo.height;
421    var pPtr;
422    if (destMallocObj) {
423      pPtr = destMallocObj['byteOffset'];
424    } else {
425      pPtr = CanvasKit._malloc(pBytes);
426    }
427
428    var rv;
429    if (grCtx) {
430      rv = source._readPixels(imageInfo, pPtr, bytesPerRow, srcX, srcY, grCtx);
431    } else {
432      rv = source._readPixels(imageInfo, pPtr, bytesPerRow, srcX, srcY);
433    }
434    if (!rv) {
435      Debug('Could not read pixels with the given inputs');
436      if (!destMallocObj) {
437        CanvasKit._free(pPtr);
438      }
439      return null;
440    }
441
442    // If the user provided us a buffer to copy into, we don't need to allocate a new TypedArray.
443    if (destMallocObj) {
444      return destMallocObj['toTypedArray'](); // Return the typed array wrapper w/o allocating.
445    }
446
447    // Put those pixels into a typed array of the right format and then
448    // make a copy with slice() that we can return.
449    var retVal = null;
450    switch (imageInfo['colorType']) {
451      case CanvasKit.ColorType.RGBA_8888:
452      case CanvasKit.ColorType.RGBA_F16: // there is no half-float JS type, so we return raw bytes.
453        retVal = new Uint8Array(CanvasKit.HEAPU8.buffer, pPtr, pBytes).slice();
454        break;
455      case CanvasKit.ColorType.RGBA_F32:
456        retVal = new Float32Array(CanvasKit.HEAPU8.buffer, pPtr, pBytes).slice();
457        break;
458      default:
459        Debug('ColorType not yet supported');
460        return null;
461    }
462
463    // Free the allocated pixels in the WASM memory
464    CanvasKit._free(pPtr);
465    return retVal;
466  }
467
468  CanvasKit.Image.prototype.readPixels = function(srcX, srcY, imageInfo, destMallocObj,
469                                                  bytesPerRow) {
470    var grCtx = CanvasKit.getCurrentGrDirectContext();
471    return readPixels(this, srcX, srcY, imageInfo, destMallocObj, bytesPerRow, grCtx);
472  };
473
474  // Accepts an array of four numbers in the range of 0-1 representing a 4f color
475  CanvasKit.Canvas.prototype.clear = function(color4f) {
476    CanvasKit.setCurrentContext(this._context);
477    var cPtr = copyColorToWasm(color4f);
478    this._clear(cPtr);
479  };
480
481  CanvasKit.Canvas.prototype.clipRRect = function(rrect, op, antialias) {
482    CanvasKit.setCurrentContext(this._context);
483    var rPtr = copyRRectToWasm(rrect);
484    this._clipRRect(rPtr, op, antialias);
485  };
486
487  CanvasKit.Canvas.prototype.clipRect = function(rect, op, antialias) {
488    CanvasKit.setCurrentContext(this._context);
489    var rPtr = copyRectToWasm(rect);
490    this._clipRect(rPtr, op, antialias);
491  };
492
493  // concat takes a 3x2, a 3x3, or a 4x4 matrix and upscales it (if needed) to 4x4. This is because
494  // under the hood, SkCanvas uses a 4x4 matrix.
495  CanvasKit.Canvas.prototype.concat = function(matr) {
496    CanvasKit.setCurrentContext(this._context);
497    var matrPtr = copy4x4MatrixToWasm(matr);
498    this._concat(matrPtr);
499  };
500
501  CanvasKit.Canvas.prototype.drawArc = function(oval, startAngle, sweepAngle, useCenter, paint) {
502    CanvasKit.setCurrentContext(this._context);
503    var oPtr = copyRectToWasm(oval);
504    this._drawArc(oPtr, startAngle, sweepAngle, useCenter, paint);
505  };
506
507  // atlas is an Image, e.g. from CanvasKit.MakeImageFromEncoded
508  // srcRects, dstXformsshould be arrays of floats of length 4*number of destinations.
509  // The colors param is optional and is used to tint the drawn images using the optional blend
510  // mode. Colors can be a Uint32Array of int colors or a flat Float32Array of float colors.
511  CanvasKit.Canvas.prototype.drawAtlas = function(atlas, srcRects, dstXforms, paint,
512                                       /* optional */ blendMode, /* optional */ colors,
513                                       /* optional */ sampling) {
514    if (!atlas || !paint || !srcRects || !dstXforms) {
515      Debug('Doing nothing since missing a required input');
516      return;
517    }
518
519    // builder arguments report the length as the number of rects, but when passed as arrays
520    // their.length attribute is 4x higher because it's the number of total components of all rects.
521    // colors is always going to report the same length, at least until floats colors are supported
522    // by this function.
523    if (srcRects.length !== dstXforms.length) {
524      Debug('Doing nothing since input arrays length mismatches');
525      return;
526    }
527    CanvasKit.setCurrentContext(this._context);
528    if (!blendMode) {
529      blendMode = CanvasKit.BlendMode.SrcOver;
530    }
531
532    var srcRectPtr = copy1dArray(srcRects, 'HEAPF32');
533
534    var dstXformPtr = copy1dArray(dstXforms, 'HEAPF32');
535    var count = dstXforms.length / 4;
536
537    var colorPtr = copy1dArray(assureIntColors(colors), 'HEAPU32');
538
539    // We require one of these:
540    // 1. sampling is null (we default to linear/none)
541    // 2. sampling.B and sampling.C --> CubicResampler
542    // 3. sampling.filter [and sampling.mipmap] --> FilterOptions
543    //
544    // Thus if all fields are available, we will choose cubic (since we search for B,C first)
545
546    if (sampling && ('B' in sampling) && ('C' in sampling)) {
547        this._drawAtlasCubic(atlas, dstXformPtr, srcRectPtr, colorPtr, count, blendMode,
548                             sampling['B'], sampling['C'], paint);
549    } else {
550        let filter = CanvasKit.FilterMode.Linear;
551        let mipmap = CanvasKit.MipmapMode.None;
552        if (sampling) {
553            filter = sampling['filter'];    // 'filter' is a required field
554            if ('mipmap' in sampling) {     // 'mipmap' is optional
555                mipmap = sampling['mipmap'];
556            }
557        }
558        this._drawAtlasOptions(atlas, dstXformPtr, srcRectPtr, colorPtr, count, blendMode,
559                               filter, mipmap, paint);
560    }
561
562    freeArraysThatAreNotMallocedByUsers(srcRectPtr, srcRects);
563    freeArraysThatAreNotMallocedByUsers(dstXformPtr, dstXforms);
564    freeArraysThatAreNotMallocedByUsers(colorPtr, colors);
565  };
566
567  CanvasKit.Canvas.prototype.drawCircle = function(cx, cy, r, paint) {
568    CanvasKit.setCurrentContext(this._context);
569    this._drawCircle(cx, cy, r, paint);
570  }
571
572  CanvasKit.Canvas.prototype.drawColor = function(color4f, mode) {
573    CanvasKit.setCurrentContext(this._context);
574    var cPtr = copyColorToWasm(color4f);
575    if (mode !== undefined) {
576      this._drawColor(cPtr, mode);
577    } else {
578      this._drawColor(cPtr);
579    }
580  };
581
582  CanvasKit.Canvas.prototype.drawColorInt = function(color, mode) {
583    CanvasKit.setCurrentContext(this._context);
584    this._drawColorInt(color, mode || CanvasKit.BlendMode.SrcOver);
585  }
586
587  CanvasKit.Canvas.prototype.drawColorComponents = function(r, g, b, a, mode) {
588    CanvasKit.setCurrentContext(this._context);
589    var cPtr = copyColorComponentsToWasm(r, g, b, a);
590    if (mode !== undefined) {
591      this._drawColor(cPtr, mode);
592    } else {
593      this._drawColor(cPtr);
594    }
595  };
596
597  CanvasKit.Canvas.prototype.drawDRRect = function(outer, inner, paint) {
598    CanvasKit.setCurrentContext(this._context);
599    var oPtr = copyRRectToWasm(outer, _scratchRRectPtr);
600    var iPtr = copyRRectToWasm(inner, _scratchRRect2Ptr);
601    this._drawDRRect(oPtr, iPtr, paint);
602  };
603
604  CanvasKit.Canvas.prototype.drawImage = function(img, x, y, paint) {
605    CanvasKit.setCurrentContext(this._context);
606    this._drawImage(img, x, y, paint || null);
607  };
608
609  CanvasKit.Canvas.prototype.drawImageCubic = function(img, x, y, b, c, paint) {
610    CanvasKit.setCurrentContext(this._context);
611    this._drawImageCubic(img, x, y, b, c, paint || null);
612  };
613
614  CanvasKit.Canvas.prototype.drawImageOptions = function(img, x, y, filter, mipmap, paint) {
615    CanvasKit.setCurrentContext(this._context);
616    this._drawImageOptions(img, x, y, filter, mipmap, paint || null);
617  };
618
619  CanvasKit.Canvas.prototype.drawImageNine = function(img, center, dest, filter, paint) {
620    CanvasKit.setCurrentContext(this._context);
621    var cPtr = copyIRectToWasm(center);
622    var dPtr = copyRectToWasm(dest);
623    this._drawImageNine(img, cPtr, dPtr, filter, paint || null);
624  };
625
626  CanvasKit.Canvas.prototype.drawImageRect = function(img, src, dest, paint, fastSample) {
627    CanvasKit.setCurrentContext(this._context);
628    copyRectToWasm(src,  _scratchFourFloatsAPtr);
629    copyRectToWasm(dest, _scratchFourFloatsBPtr);
630    this._drawImageRect(img, _scratchFourFloatsAPtr, _scratchFourFloatsBPtr, paint, !!fastSample);
631  };
632
633  CanvasKit.Canvas.prototype.drawImageRectCubic = function(img, src, dest, B, C, paint) {
634    CanvasKit.setCurrentContext(this._context);
635    copyRectToWasm(src,  _scratchFourFloatsAPtr);
636    copyRectToWasm(dest, _scratchFourFloatsBPtr);
637    this._drawImageRectCubic(img, _scratchFourFloatsAPtr, _scratchFourFloatsBPtr, B, C,
638      paint || null);
639  };
640
641  CanvasKit.Canvas.prototype.drawImageRectOptions = function(img, src, dest, filter, mipmap, paint) {
642    CanvasKit.setCurrentContext(this._context);
643    copyRectToWasm(src,  _scratchFourFloatsAPtr);
644    copyRectToWasm(dest, _scratchFourFloatsBPtr);
645    this._drawImageRectOptions(img, _scratchFourFloatsAPtr, _scratchFourFloatsBPtr, filter, mipmap,
646      paint || null);
647  };
648
649  CanvasKit.Canvas.prototype.drawLine = function(x1, y1, x2, y2, paint) {
650    CanvasKit.setCurrentContext(this._context);
651    this._drawLine(x1, y1, x2, y2, paint);
652  }
653
654  CanvasKit.Canvas.prototype.drawOval = function(oval, paint) {
655    CanvasKit.setCurrentContext(this._context);
656    var oPtr = copyRectToWasm(oval);
657    this._drawOval(oPtr, paint);
658  };
659
660  CanvasKit.Canvas.prototype.drawPaint = function(paint) {
661    CanvasKit.setCurrentContext(this._context);
662    this._drawPaint(paint);
663  }
664
665  CanvasKit.Canvas.prototype.drawParagraph = function(p, x, y) {
666    CanvasKit.setCurrentContext(this._context);
667    this._drawParagraph(p, x, y);
668  }
669
670  CanvasKit.Canvas.prototype.drawPatch = function(cubics, colors, texs, mode, paint) {
671    if (cubics.length < 24) {
672        throw 'Need 12 cubic points';
673    }
674    if (colors && colors.length < 4) {
675        throw 'Need 4 colors';
676    }
677    if (texs && texs.length < 8) {
678        throw 'Need 4 shader coordinates';
679    }
680    CanvasKit.setCurrentContext(this._context);
681
682    const cubics_ptr =          copy1dArray(cubics, 'HEAPF32');
683    const colors_ptr = colors ? copy1dArray(assureIntColors(colors), 'HEAPU32') : nullptr;
684    const texs_ptr   = texs   ? copy1dArray(texs,   'HEAPF32') : nullptr;
685    if (!mode) {
686        mode = CanvasKit.BlendMode.Modulate;
687    }
688
689    this._drawPatch(cubics_ptr, colors_ptr, texs_ptr, mode, paint);
690
691    freeArraysThatAreNotMallocedByUsers(texs_ptr,   texs);
692    freeArraysThatAreNotMallocedByUsers(colors_ptr, colors);
693    freeArraysThatAreNotMallocedByUsers(cubics_ptr, cubics);
694  };
695
696  CanvasKit.Canvas.prototype.drawPath = function(path, paint) {
697    CanvasKit.setCurrentContext(this._context);
698    this._drawPath(path, paint);
699  }
700
701  CanvasKit.Canvas.prototype.drawPicture = function(pic) {
702    CanvasKit.setCurrentContext(this._context);
703    this._drawPicture(pic);
704  }
705
706  // points is a 1d array of length 2n representing n points where the even indices
707  // will be treated as x coordinates and the odd indices will be treated as y coordinates.
708  // Like other APIs, this accepts a malloced type array or malloc obj.
709  CanvasKit.Canvas.prototype.drawPoints = function(mode, points, paint) {
710    CanvasKit.setCurrentContext(this._context);
711    var ptr = copy1dArray(points, 'HEAPF32');
712    this._drawPoints(mode, ptr, points.length / 2, paint);
713    freeArraysThatAreNotMallocedByUsers(ptr, points);
714  };
715
716  CanvasKit.Canvas.prototype.drawRRect = function(rrect, paint) {
717    CanvasKit.setCurrentContext(this._context);
718    var rPtr = copyRRectToWasm(rrect);
719    this._drawRRect(rPtr, paint);
720  };
721
722  CanvasKit.Canvas.prototype.drawRect = function(rect, paint) {
723    CanvasKit.setCurrentContext(this._context);
724    var rPtr = copyRectToWasm(rect);
725    this._drawRect(rPtr, paint);
726  };
727
728  CanvasKit.Canvas.prototype.drawRect4f = function(l, t, r, b, paint) {
729    CanvasKit.setCurrentContext(this._context);
730    this._drawRect4f(l, t, r, b, paint);
731  }
732
733  CanvasKit.Canvas.prototype.drawShadow = function(path, zPlaneParams, lightPos, lightRadius,
734                                                   ambientColor, spotColor, flags) {
735    CanvasKit.setCurrentContext(this._context);
736    var ambiPtr = copyColorToWasmNoScratch(ambientColor);
737    var spotPtr = copyColorToWasmNoScratch(spotColor);
738    // We use the return value from copy1dArray in case the passed in arrays are malloc'd.
739    var zPlanePtr = copy1dArray(zPlaneParams, 'HEAPF32', _scratchThreeFloatsAPtr);
740    var lightPosPtr = copy1dArray(lightPos, 'HEAPF32', _scratchThreeFloatsBPtr);
741    this._drawShadow(path, zPlanePtr, lightPosPtr, lightRadius, ambiPtr, spotPtr, flags);
742    freeArraysThatAreNotMallocedByUsers(ambiPtr, ambientColor);
743    freeArraysThatAreNotMallocedByUsers(spotPtr, spotColor);
744  };
745
746  CanvasKit.getShadowLocalBounds = function(ctm, path, zPlaneParams, lightPos, lightRadius,
747                                            flags, optOutputRect) {
748    var ctmPtr = copy3x3MatrixToWasm(ctm);
749    // We use the return value from copy1dArray in case the passed in arrays are malloc'd.
750    var zPlanePtr = copy1dArray(zPlaneParams, 'HEAPF32', _scratchThreeFloatsAPtr);
751    var lightPosPtr = copy1dArray(lightPos, 'HEAPF32', _scratchThreeFloatsBPtr);
752    var ok = this._getShadowLocalBounds(ctmPtr, path, zPlanePtr, lightPosPtr, lightRadius,
753                                        flags, _scratchFourFloatsAPtr);
754    if (!ok) {
755      return null;
756    }
757    var ta = _scratchFourFloatsA['toTypedArray']();
758    if (optOutputRect) {
759      optOutputRect.set(ta);
760      return optOutputRect;
761    }
762    return ta.slice();
763  };
764
765  CanvasKit.Canvas.prototype.drawTextBlob = function(blob, x, y, paint) {
766    CanvasKit.setCurrentContext(this._context);
767    this._drawTextBlob(blob, x, y, paint);
768  }
769
770  CanvasKit.Canvas.prototype.drawVertices = function(verts, mode, paint) {
771    CanvasKit.setCurrentContext(this._context);
772    this._drawVertices(verts, mode, paint);
773  }
774
775  // getDeviceClipBounds returns an SkIRect
776  CanvasKit.Canvas.prototype.getDeviceClipBounds = function(outputRect) {
777    // _getDeviceClipBounds will copy the values into the pointer.
778    this._getDeviceClipBounds(_scratchIRectPtr);
779    return copyIRectFromWasm(_scratchIRect, outputRect);
780  };
781
782  // getLocalToDevice returns a 4x4 matrix.
783  CanvasKit.Canvas.prototype.getLocalToDevice = function() {
784    // _getLocalToDevice will copy the values into the pointer.
785    this._getLocalToDevice(_scratch4x4MatrixPtr);
786    return copy4x4MatrixFromWasm(_scratch4x4MatrixPtr);
787  };
788
789  // getTotalMatrix returns the current matrix as a 3x3 matrix.
790  CanvasKit.Canvas.prototype.getTotalMatrix = function() {
791    // _getTotalMatrix will copy the values into the pointer.
792    this._getTotalMatrix(_scratch3x3MatrixPtr);
793    // read them out into an array. TODO(kjlubick): If we change Matrix to be
794    // typedArrays, then we should return a typed array here too.
795    var rv = new Array(9);
796    for (var i = 0; i < 9; i++) {
797      rv[i] = CanvasKit.HEAPF32[_scratch3x3MatrixPtr/4 + i]; // divide by 4 to "cast" to float.
798    }
799    return rv;
800  };
801
802  CanvasKit.Canvas.prototype.makeSurface = function(imageInfo) {
803    var s = this._makeSurface(imageInfo);
804    s._context = this._context;
805    return s;
806  };
807
808  CanvasKit.Canvas.prototype.readPixels = function(srcX, srcY, imageInfo, destMallocObj,
809                                                   bytesPerRow) {
810    CanvasKit.setCurrentContext(this._context);
811    return readPixels(this, srcX, srcY, imageInfo, destMallocObj, bytesPerRow);
812  };
813
814  CanvasKit.Canvas.prototype.saveLayer = function(paint, boundsRect, backdrop, flags) {
815    // bPtr will be 0 (nullptr) if boundsRect is undefined/null.
816    var bPtr = copyRectToWasm(boundsRect);
817    // These or clauses help emscripten, which does not deal with undefined well.
818    return this._saveLayer(paint || null, bPtr, backdrop || null, flags || 0);
819  };
820
821  // pixels should be a Uint8Array or a plain JS array.
822  CanvasKit.Canvas.prototype.writePixels = function(pixels, srcWidth, srcHeight,
823                                                      destX, destY, alphaType, colorType, colorSpace) {
824    if (pixels.byteLength % (srcWidth * srcHeight)) {
825      throw 'pixels length must be a multiple of the srcWidth * srcHeight';
826    }
827    CanvasKit.setCurrentContext(this._context);
828    var bytesPerPixel = pixels.byteLength / (srcWidth * srcHeight);
829    // supply defaults (which are compatible with HTMLCanvas's putImageData)
830    alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
831    colorType = colorType || CanvasKit.ColorType.RGBA_8888;
832    colorSpace = colorSpace || CanvasKit.ColorSpace.SRGB;
833    var srcRowBytes = bytesPerPixel * srcWidth;
834
835    var pptr = copy1dArray(pixels, 'HEAPU8');
836    var ok = this._writePixels({
837      'width': srcWidth,
838      'height': srcHeight,
839      'colorType': colorType,
840      'alphaType': alphaType,
841      'colorSpace': colorSpace,
842    }, pptr, srcRowBytes, destX, destY);
843
844    freeArraysThatAreNotMallocedByUsers(pptr, pixels);
845    return ok;
846  };
847
848  CanvasKit.ColorFilter.MakeBlend = function(color4f, mode, colorSpace) {
849    var cPtr = copyColorToWasm(color4f);
850    colorSpace = colorSpace || CanvasKit.ColorSpace.SRGB;
851    return CanvasKit.ColorFilter._MakeBlend(cPtr, mode, colorSpace);
852  };
853
854  // colorMatrix is an ColorMatrix (e.g. Float32Array of length 20)
855  CanvasKit.ColorFilter.MakeMatrix = function(colorMatrix) {
856    if (!colorMatrix || colorMatrix.length !== 20) {
857      throw 'invalid color matrix';
858    }
859    var fptr = copy1dArray(colorMatrix, 'HEAPF32');
860    // We know skia memcopies the floats, so we can free our memory after the call returns.
861    var m = CanvasKit.ColorFilter._makeMatrix(fptr);
862    freeArraysThatAreNotMallocedByUsers(fptr, colorMatrix);
863    return m;
864  };
865
866  CanvasKit.ContourMeasure.prototype.getPosTan = function(distance, optionalOutput) {
867    this._getPosTan(distance, _scratchFourFloatsAPtr);
868    var ta = _scratchFourFloatsA['toTypedArray']();
869    if (optionalOutput) {
870      optionalOutput.set(ta);
871      return optionalOutput;
872    }
873    return ta.slice();
874  };
875
876  CanvasKit.ImageFilter.prototype.getOutputBounds = function (drawBounds, ctm, optionalOutputArray) {
877    var bPtr = copyRectToWasm(drawBounds, _scratchFourFloatsAPtr);
878    var mPtr = copy3x3MatrixToWasm(ctm);
879    this._getOutputBounds(bPtr, mPtr, _scratchIRectPtr);
880    var ta = _scratchIRect['toTypedArray']();
881    if (optionalOutputArray) {
882      optionalOutputArray.set(ta);
883      return optionalOutputArray;
884    }
885    return ta.slice();
886  };
887
888  CanvasKit.ImageFilter.MakeDropShadow = function(dx, dy, sx, sy, color, input) {
889    var cPtr = copyColorToWasm(color, _scratchColorPtr);
890    return CanvasKit.ImageFilter._MakeDropShadow(dx, dy, sx, sy, cPtr, input);
891  };
892
893  CanvasKit.ImageFilter.MakeDropShadowOnly = function(dx, dy, sx, sy, color, input) {
894    var cPtr = copyColorToWasm(color, _scratchColorPtr);
895    return CanvasKit.ImageFilter._MakeDropShadowOnly(dx, dy, sx, sy, cPtr, input);
896  };
897
898  CanvasKit.ImageFilter.MakeImage = function(img, sampling, srcRect, dstRect) {
899    var srcPtr = copyRectToWasm(srcRect, _scratchFourFloatsAPtr);
900    var dstPtr = copyRectToWasm(dstRect, _scratchFourFloatsBPtr);
901
902    if ('B' in sampling && 'C' in sampling) {
903        return CanvasKit.ImageFilter._MakeImageCubic(img, sampling['B'], sampling['C'], srcPtr, dstPtr);
904    } else {
905        const filter = sampling['filter'];  // 'filter' is a required field
906        let mipmap = CanvasKit.MipmapMode.None;
907        if ('mipmap' in sampling) {         // 'mipmap' is optional
908            mipmap = sampling['mipmap'];
909        }
910        return CanvasKit.ImageFilter._MakeImageOptions(img, filter, mipmap, srcPtr, dstPtr);
911    }
912  };
913
914  CanvasKit.ImageFilter.MakeMatrixTransform = function(matrix, sampling, input) {
915    var matrPtr = copy3x3MatrixToWasm(matrix);
916
917    if ('B' in sampling && 'C' in sampling) {
918        return CanvasKit.ImageFilter._MakeMatrixTransformCubic(matrPtr,
919                                                               sampling['B'], sampling['C'],
920                                                               input);
921    } else {
922        const filter = sampling['filter'];  // 'filter' is a required field
923        let mipmap = CanvasKit.MipmapMode.None;
924        if ('mipmap' in sampling) {         // 'mipmap' is optional
925            mipmap = sampling['mipmap'];
926        }
927        return CanvasKit.ImageFilter._MakeMatrixTransformOptions(matrPtr,
928                                                                 filter, mipmap,
929                                                                 input);
930    }
931  };
932
933  CanvasKit.Paint.prototype.getColor = function() {
934    this._getColor(_scratchColorPtr);
935    return copyColorFromWasm(_scratchColorPtr);
936  };
937
938  CanvasKit.Paint.prototype.setColor = function(color4f, colorSpace) {
939    colorSpace = colorSpace || null; // null will be replaced with sRGB in the C++ method.
940    // emscripten wouldn't bind undefined to the sk_sp<ColorSpace> expected here.
941    var cPtr = copyColorToWasm(color4f);
942    this._setColor(cPtr, colorSpace);
943  };
944
945  // The color components here are expected to be floating point values (nominally between
946  // 0.0 and 1.0, but with wider color gamuts, the values could exceed this range). To convert
947  // between standard 8 bit colors and floats, just divide by 255 before passing them in.
948  CanvasKit.Paint.prototype.setColorComponents = function(r, g, b, a, colorSpace) {
949    colorSpace = colorSpace || null; // null will be replaced with sRGB in the C++ method.
950    // emscripten wouldn't bind undefined to the sk_sp<ColorSpace> expected here.
951    var cPtr = copyColorComponentsToWasm(r, g, b, a);
952    this._setColor(cPtr, colorSpace);
953  };
954
955  CanvasKit.Path.prototype.getPoint = function(idx, optionalOutput) {
956    // This will copy 2 floats into a space for 4 floats
957    this._getPoint(idx, _scratchFourFloatsAPtr);
958    var ta = _scratchFourFloatsA['toTypedArray']();
959    if (optionalOutput) {
960      // We cannot call optionalOutput.set() because it is an error to call .set() with
961      // a source bigger than the destination.
962      optionalOutput[0] = ta[0];
963      optionalOutput[1] = ta[1];
964      return optionalOutput;
965    }
966    // Be sure to return a copy of just the first 2 values.
967    return ta.slice(0, 2);
968  };
969
970  CanvasKit.Picture.prototype.makeShader = function(tmx, tmy, mode, matr, rect) {
971    var mPtr = copy3x3MatrixToWasm(matr);
972    var rPtr = copyRectToWasm(rect);
973    return this._makeShader(tmx, tmy, mode, mPtr, rPtr);
974  };
975
976  // Clients can pass in a Float32Array with length 4 to this and the results
977  // will be copied into that array. Otherwise, a new TypedArray will be allocated
978  // and returned.
979  CanvasKit.Picture.prototype.cullRect = function (optionalOutputArray) {
980    this._cullRect(_scratchFourFloatsAPtr);
981    var ta = _scratchFourFloatsA['toTypedArray']();
982    if (optionalOutputArray) {
983      optionalOutputArray.set(ta);
984      return optionalOutputArray;
985    }
986    return ta.slice();
987  };
988
989  // `bounds` is a required argument and is the initial cullRect for the picture.
990  // `computeBounds` is an optional boolean argument (default false) which, if
991  // true, will cause the recorded picture to compute a more accurate cullRect
992  // when it is created.
993  CanvasKit.PictureRecorder.prototype.beginRecording = function (bounds, computeBounds) {
994    var bPtr = copyRectToWasm(bounds);
995    return this._beginRecording(bPtr, !!computeBounds);
996  };
997
998  CanvasKit.Surface.prototype.getCanvas = function() {
999    var c = this._getCanvas();
1000    c._context = this._context;
1001    return c;
1002  };
1003
1004  CanvasKit.Surface.prototype.makeImageSnapshot = function(optionalBoundsRect) {
1005    CanvasKit.setCurrentContext(this._context);
1006    var bPtr = copyIRectToWasm(optionalBoundsRect);
1007    return this._makeImageSnapshot(bPtr);
1008  };
1009
1010  CanvasKit.Surface.prototype.makeSurface = function(imageInfo) {
1011    CanvasKit.setCurrentContext(this._context);
1012    var s = this._makeSurface(imageInfo);
1013    s._context = this._context;
1014    return s;
1015  };
1016
1017  CanvasKit.Surface.prototype._requestAnimationFrameInternal = function(callback, dirtyRect) {
1018    if (!this._cached_canvas) {
1019      this._cached_canvas = this.getCanvas();
1020    }
1021    return requestAnimationFrame(function() {
1022      CanvasKit.setCurrentContext(this._context);
1023
1024      callback(this._cached_canvas);
1025
1026      // We do not dispose() of the Surface here, as the client will typically
1027      // call requestAnimationFrame again from within the supplied callback.
1028      // For drawing a single frame, prefer drawOnce().
1029      this.flush(dirtyRect);
1030    }.bind(this));
1031  };
1032  if (!CanvasKit.Surface.prototype.requestAnimationFrame) {
1033    CanvasKit.Surface.prototype.requestAnimationFrame =
1034          CanvasKit.Surface.prototype._requestAnimationFrameInternal;
1035  }
1036
1037  // drawOnce will dispose of the surface after drawing the frame using the provided
1038  // callback.
1039  CanvasKit.Surface.prototype._drawOnceInternal = function(callback, dirtyRect) {
1040    if (!this._cached_canvas) {
1041      this._cached_canvas = this.getCanvas();
1042    }
1043    requestAnimationFrame(function() {
1044      CanvasKit.setCurrentContext(this._context);
1045      callback(this._cached_canvas);
1046
1047      this.flush(dirtyRect);
1048      this.dispose();
1049    }.bind(this));
1050  };
1051  if (!CanvasKit.Surface.prototype.drawOnce) {
1052    CanvasKit.Surface.prototype.drawOnce = CanvasKit.Surface.prototype._drawOnceInternal;
1053  }
1054
1055  CanvasKit.PathEffect.MakeDash = function(intervals, phase) {
1056    if (!phase) {
1057      phase = 0;
1058    }
1059    if (!intervals.length || intervals.length % 2 === 1) {
1060      throw 'Intervals array must have even length';
1061    }
1062    var ptr = copy1dArray(intervals, 'HEAPF32');
1063    var dpe = CanvasKit.PathEffect._MakeDash(ptr, intervals.length, phase);
1064    freeArraysThatAreNotMallocedByUsers(ptr, intervals);
1065    return dpe;
1066  };
1067
1068  CanvasKit.PathEffect.MakeLine2D = function(width, matrix) {
1069    var matrixPtr = copy3x3MatrixToWasm(matrix);
1070    return CanvasKit.PathEffect._MakeLine2D(width, matrixPtr);
1071  };
1072
1073  CanvasKit.PathEffect.MakePath2D = function(matrix, path) {
1074    var matrixPtr = copy3x3MatrixToWasm(matrix);
1075    return CanvasKit.PathEffect._MakePath2D(matrixPtr, path);
1076  };
1077
1078  CanvasKit.Shader.MakeColor = function(color4f, colorSpace) {
1079    colorSpace = colorSpace || null;
1080    var cPtr = copyColorToWasm(color4f);
1081    return CanvasKit.Shader._MakeColor(cPtr, colorSpace);
1082  };
1083
1084  // TODO(kjlubick) remove deprecated names.
1085  CanvasKit.Shader.Blend = CanvasKit.Shader.MakeBlend;
1086  CanvasKit.Shader.Color = CanvasKit.Shader.MakeColor;
1087
1088  CanvasKit.Shader.MakeLinearGradient = function(start, end, colors, pos, mode, localMatrix, flags, colorSpace) {
1089    colorSpace = colorSpace || null;
1090    var cPtrInfo = copyFlexibleColorArray(colors);
1091    var posPtr = copy1dArray(pos, 'HEAPF32');
1092    flags = flags || 0;
1093    var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
1094
1095    // Copy start and end to _scratchFourFloatsAPtr.
1096    var startEndPts = _scratchFourFloatsA['toTypedArray']();
1097    startEndPts.set(start);
1098    startEndPts.set(end, 2);
1099
1100    var lgs = CanvasKit.Shader._MakeLinearGradient(_scratchFourFloatsAPtr, cPtrInfo.colorPtr, cPtrInfo.colorType, posPtr,
1101                                                   cPtrInfo.count, mode, flags, localMatrixPtr, colorSpace);
1102
1103    freeArraysThatAreNotMallocedByUsers(cPtrInfo.colorPtr, colors);
1104    pos && freeArraysThatAreNotMallocedByUsers(posPtr, pos);
1105    return lgs;
1106  };
1107
1108  CanvasKit.Shader.MakeRadialGradient = function(center, radius, colors, pos, mode, localMatrix, flags, colorSpace) {
1109    colorSpace = colorSpace || null;
1110    var cPtrInfo = copyFlexibleColorArray(colors);
1111    var posPtr = copy1dArray(pos, 'HEAPF32');
1112    flags = flags || 0;
1113    var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
1114
1115    var rgs = CanvasKit.Shader._MakeRadialGradient(center[0], center[1], radius, cPtrInfo.colorPtr,
1116                                                   cPtrInfo.colorType, posPtr, cPtrInfo.count, mode,
1117                                                   flags, localMatrixPtr, colorSpace);
1118
1119    freeArraysThatAreNotMallocedByUsers(cPtrInfo.colorPtr, colors);
1120    pos && freeArraysThatAreNotMallocedByUsers(posPtr, pos);
1121    return rgs;
1122  };
1123
1124  CanvasKit.Shader.MakeSweepGradient = function(cx, cy, colors, pos, mode, localMatrix, flags, startAngle, endAngle, colorSpace) {
1125    colorSpace = colorSpace || null;
1126    var cPtrInfo = copyFlexibleColorArray(colors);
1127    var posPtr = copy1dArray(pos, 'HEAPF32');
1128    flags = flags || 0;
1129    startAngle = startAngle || 0;
1130    endAngle = endAngle || 360;
1131    var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
1132
1133    var sgs = CanvasKit.Shader._MakeSweepGradient(cx, cy, cPtrInfo.colorPtr, cPtrInfo.colorType, posPtr,
1134                                                  cPtrInfo.count, mode,
1135                                                  startAngle, endAngle, flags,
1136                                                  localMatrixPtr, colorSpace);
1137
1138    freeArraysThatAreNotMallocedByUsers(cPtrInfo.colorPtr, colors);
1139    pos && freeArraysThatAreNotMallocedByUsers(posPtr, pos);
1140    return sgs;
1141  };
1142
1143  CanvasKit.Shader.MakeTwoPointConicalGradient = function(start, startRadius, end, endRadius,
1144                                                          colors, pos, mode, localMatrix, flags, colorSpace) {
1145    colorSpace = colorSpace || null;
1146    var cPtrInfo = copyFlexibleColorArray(colors);
1147    var posPtr =   copy1dArray(pos, 'HEAPF32');
1148    flags = flags || 0;
1149    var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
1150
1151    // Copy start and end to _scratchFourFloatsAPtr.
1152    var startEndPts = _scratchFourFloatsA['toTypedArray']();
1153    startEndPts.set(start);
1154    startEndPts.set(end, 2);
1155
1156    var rgs = CanvasKit.Shader._MakeTwoPointConicalGradient(_scratchFourFloatsAPtr,
1157                          startRadius, endRadius, cPtrInfo.colorPtr, cPtrInfo.colorType,
1158                          posPtr, cPtrInfo.count, mode, flags, localMatrixPtr, colorSpace);
1159
1160    freeArraysThatAreNotMallocedByUsers(cPtrInfo.colorPtr, colors);
1161    pos && freeArraysThatAreNotMallocedByUsers(posPtr, pos);
1162    return rgs;
1163  };
1164
1165  // Clients can pass in a Float32Array with length 4 to this and the results
1166  // will be copied into that array. Otherwise, a new TypedArray will be allocated
1167  // and returned.
1168  CanvasKit.Vertices.prototype.bounds = function(optionalOutputArray) {
1169    this._bounds(_scratchFourFloatsAPtr);
1170    var ta = _scratchFourFloatsA['toTypedArray']();
1171    if (optionalOutputArray) {
1172      optionalOutputArray.set(ta);
1173      return optionalOutputArray;
1174    }
1175    return ta.slice();
1176  };
1177
1178  // Run through the JS files that are added at compile time.
1179  if (CanvasKit._extraInitializations) {
1180    CanvasKit._extraInitializations.forEach(function(init) {
1181      init();
1182    });
1183  }
1184}; // end CanvasKit.onRuntimeInitialized, that is, anything changing prototypes or dynamic.
1185
1186// Accepts an object holding two canvaskit colors.
1187// {
1188//    ambient: [r, g, b, a],
1189//    spot: [r, g, b, a],
1190// }
1191// Returns the same format. Note, if malloced colors are passed in, the memory
1192// housing the passed in colors passed in will be overwritten with the computed
1193// tonal colors.
1194CanvasKit.computeTonalColors = function(tonalColors) {
1195    // copy the colors into WASM
1196    var cPtrAmbi = copyColorToWasmNoScratch(tonalColors['ambient']);
1197    var cPtrSpot = copyColorToWasmNoScratch(tonalColors['spot']);
1198    // The output of this function will be the same pointers we passed in.
1199    this._computeTonalColors(cPtrAmbi, cPtrSpot);
1200    // Read the results out.
1201    var result =  {
1202      'ambient': copyColorFromWasm(cPtrAmbi),
1203      'spot': copyColorFromWasm(cPtrSpot),
1204    };
1205    // If the user passed us malloced colors in here, we don't want to clean them up.
1206    freeArraysThatAreNotMallocedByUsers(cPtrAmbi, tonalColors['ambient']);
1207    freeArraysThatAreNotMallocedByUsers(cPtrSpot, tonalColors['spot']);
1208    return result;
1209};
1210
1211CanvasKit.LTRBRect = function(l, t, r, b) {
1212  return Float32Array.of(l, t, r, b);
1213};
1214
1215CanvasKit.XYWHRect = function(x, y, w, h) {
1216  return Float32Array.of(x, y, x+w, y+h);
1217};
1218
1219CanvasKit.LTRBiRect = function(l, t, r, b) {
1220  return Int32Array.of(l, t, r, b);
1221};
1222
1223CanvasKit.XYWHiRect = function(x, y, w, h) {
1224  return Int32Array.of(x, y, x+w, y+h);
1225};
1226
1227// RRectXY returns a TypedArray representing an RRect with the given rect and a radiusX and
1228// radiusY for all 4 corners.
1229CanvasKit.RRectXY = function(rect, rx, ry) {
1230  return Float32Array.of(
1231    rect[0], rect[1], rect[2], rect[3],
1232    rx, ry,
1233    rx, ry,
1234    rx, ry,
1235    rx, ry,
1236  );
1237};
1238
1239// data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
1240CanvasKit.MakeAnimatedImageFromEncoded = function(data) {
1241  data = new Uint8Array(data);
1242
1243  var iptr = CanvasKit._malloc(data.byteLength);
1244  CanvasKit.HEAPU8.set(data, iptr);
1245  var img = CanvasKit._decodeAnimatedImage(iptr, data.byteLength);
1246  if (!img) {
1247    Debug('Could not decode animated image');
1248    return null;
1249  }
1250  return img;
1251};
1252
1253// data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
1254CanvasKit.MakeImageFromEncoded = function(data) {
1255  data = new Uint8Array(data);
1256
1257  var iptr = CanvasKit._malloc(data.byteLength);
1258  CanvasKit.HEAPU8.set(data, iptr);
1259  var img = CanvasKit._decodeImage(iptr, data.byteLength);
1260  if (!img) {
1261    Debug('Could not decode image');
1262    return null;
1263  }
1264  return img;
1265};
1266
1267// A variable to hold a canvasElement which can be reused once created the first time.
1268var memoizedCanvas2dElement = null;
1269
1270// Alternative to CanvasKit.MakeImageFromEncoded. Allows for CanvasKit users to take advantage of
1271// browser APIs to decode images instead of using codecs included in the CanvasKit wasm binary.
1272// Expects that the canvasImageSource has already loaded/decoded.
1273// CanvasImageSource reference: https://developer.mozilla.org/en-US/docs/Web/API/CanvasImageSource
1274CanvasKit.MakeImageFromCanvasImageSource = function(canvasImageSource) {
1275  var width = canvasImageSource.width;
1276  var height = canvasImageSource.height;
1277
1278  if (!memoizedCanvas2dElement) {
1279    memoizedCanvas2dElement = document.createElement('canvas');
1280  }
1281  memoizedCanvas2dElement.width = width;
1282  memoizedCanvas2dElement.height = height;
1283
1284  var ctx2d = memoizedCanvas2dElement.getContext('2d', {willReadFrequently: true});
1285  ctx2d.drawImage(canvasImageSource, 0, 0);
1286
1287  var imageData = ctx2d.getImageData(0, 0, width, height);
1288
1289  return CanvasKit.MakeImage({
1290      'width': width,
1291      'height': height,
1292      'alphaType': CanvasKit.AlphaType.Unpremul,
1293      'colorType': CanvasKit.ColorType.RGBA_8888,
1294      'colorSpace': CanvasKit.ColorSpace.SRGB
1295    }, imageData.data, 4 * width);
1296};
1297
1298// pixels may be an array but Uint8Array or Uint8ClampedArray is recommended,
1299// with the bytes representing the pixel values.
1300// (e.g. each set of 4 bytes could represent RGBA values for a single pixel).
1301CanvasKit.MakeImage = function(info, pixels, bytesPerRow) {
1302  var pptr = CanvasKit._malloc(pixels.length);
1303  CanvasKit.HEAPU8.set(pixels, pptr); // We always want to copy the bytes into the WASM heap.
1304  // No need to _free pptr, Image takes it with SkData::MakeFromMalloc
1305  return CanvasKit._MakeImage(info, pptr, pixels.length, bytesPerRow);
1306};
1307
1308// Colors may be a Uint32Array of int colors, a Flat Float32Array of float colors
1309// or a 2d Array of Float32Array(4) (deprecated)
1310// the underlying Skia function accepts only int colors so it is recommended
1311// to pass an array of int colors to avoid an extra conversion.
1312CanvasKit.MakeVertices = function(mode, positions, textureCoordinates, colors,
1313                                  indices, isVolatile) {
1314  // Default isVolatile to true if not set
1315  isVolatile = isVolatile === undefined ? true : isVolatile;
1316  var idxCount = (indices && indices.length) || 0;
1317
1318  var flags = 0;
1319  // These flags are from SkVertices.h and should be kept in sync with those.
1320  if (textureCoordinates && textureCoordinates.length) {
1321    flags |= (1 << 0);
1322  }
1323  if (colors && colors.length) {
1324    flags |= (1 << 1);
1325  }
1326  if (!isVolatile) {
1327    flags |= (1 << 2);
1328  }
1329
1330  var builder = new CanvasKit._VerticesBuilder(mode, positions.length / 2, idxCount, flags);
1331
1332  copy1dArray(positions, 'HEAPF32', builder.positions());
1333  if (builder.texCoords()) {
1334    copy1dArray(textureCoordinates, 'HEAPF32', builder.texCoords());
1335  }
1336  if (builder.colors()) {
1337      copy1dArray(assureIntColors(colors), 'HEAPU32', builder.colors());
1338  }
1339  if (builder.indices()) {
1340    copy1dArray(indices, 'HEAPU16', builder.indices());
1341  }
1342
1343  // Create the vertices, which owns the memory that the builder had allocated.
1344  return builder.detach();
1345};
1346