blob: fbee8f46c77788d44dd1b8a9eff62b565a46473c [file] [log] [blame]
Kevin Lubick217056c2018-09-20 17:39:31 -04001// 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.
Kevin Lubickb5ae3b52018-11-03 07:51:19 -04004(function(CanvasKit) {
Kevin Lubick217056c2018-09-20 17:39:31 -04005 // CanvasKit.onRuntimeInitialized is called after the WASM library has loaded.
6 // Anything that modifies an exposed class (e.g. SkPath) should be set
7 // after onRuntimeInitialized, otherwise, it can happen outside of that scope.
8 CanvasKit.onRuntimeInitialized = function() {
9 // All calls to 'this' need to go in externs.js so closure doesn't minify them away.
Kevin Lubick1a05fce2018-11-20 12:51:16 -050010
11
12 // Add some helpers for matrices. This is ported from SkMatrix.cpp
13 // to save complexity and overhead of going back and forth between
14 // C++ and JS layers.
Kevin Lubickae9dfc02018-12-06 10:14:10 -050015 // I would have liked to use something like DOMMatrix, except it
16 // isn't widely supported (would need polyfills) and it doesn't
17 // have a mapPoints() function (which could maybe be tacked on here).
18 // If DOMMatrix catches on, it would be worth re-considering this usage.
Kevin Lubick1a05fce2018-11-20 12:51:16 -050019 CanvasKit.SkMatrix = {};
20 function sdot(a, b, c, d, e, f) {
21 e = e || 0;
22 f = f || 0;
23 return a * b + c * d + e * f;
24 }
25
Kevin Lubickb9db3902018-11-26 11:47:54 -050026 CanvasKit.SkMatrix.identity = function() {
27 return [
28 1, 0, 0,
29 0, 1, 0,
30 0, 0, 1,
31 ];
32 };
33
Kevin Lubickae9dfc02018-12-06 10:14:10 -050034 // Return the inverse (if it exists) of this matrix.
35 // Otherwise, return the identity.
36 CanvasKit.SkMatrix.invert = function(m) {
37 var det = m[0]*m[4]*m[8] + m[1]*m[5]*m[6] + m[2]*m[3]*m[7]
38 - m[2]*m[4]*m[6] - m[1]*m[3]*m[8] - m[0]*m[5]*m[7];
39 if (!det) {
40 SkDebug('Warning, uninvertible matrix');
41 return CanvasKit.SkMatrix.identity();
42 }
43 return [
44 (m[4]*m[8] - m[5]*m[7])/det, (m[2]*m[7] - m[1]*m[8])/det, (m[1]*m[5] - m[2]*m[4])/det,
45 (m[5]*m[6] - m[3]*m[8])/det, (m[0]*m[8] - m[2]*m[6])/det, (m[2]*m[3] - m[0]*m[5])/det,
46 (m[3]*m[7] - m[4]*m[6])/det, (m[1]*m[6] - m[0]*m[7])/det, (m[0]*m[4] - m[1]*m[3])/det,
47 ];
48 };
49
Kevin Lubickb9db3902018-11-26 11:47:54 -050050 // Maps the given points according to the passed in matrix.
51 // Results are done in place.
52 // See SkMatrix.h::mapPoints for the docs on the math.
53 CanvasKit.SkMatrix.mapPoints = function(matrix, ptArr) {
54 if (ptArr.length % 2) {
55 throw 'mapPoints requires an even length arr';
56 }
57 for (var i = 0; i < ptArr.length; i+=2) {
58 var x = ptArr[i], y = ptArr[i+1];
59 // Gx+Hy+I
60 var denom = matrix[6]*x + matrix[7]*y + matrix[8];
61 // Ax+By+C
62 var xTrans = matrix[0]*x + matrix[1]*y + matrix[2];
63 // Dx+Ey+F
64 var yTrans = matrix[3]*x + matrix[4]*y + matrix[5];
65 ptArr[i] = xTrans/denom;
66 ptArr[i+1] = yTrans/denom;
67 }
68 return ptArr;
69 };
70
71 CanvasKit.SkMatrix.multiply = function(m1, m2) {
72 var result = [0,0,0, 0,0,0, 0,0,0];
73 for (var r = 0; r < 3; r++) {
74 for (var c = 0; c < 3; c++) {
75 // m1 and m2 are 1D arrays pretending to be 2D arrays
76 result[3*r + c] = sdot(m1[3*r + 0], m2[3*0 + c],
77 m1[3*r + 1], m2[3*1 + c],
78 m1[3*r + 2], m2[3*2 + c]);
79 }
80 }
81 return result;
82 }
83
84 // Return a matrix representing a rotation by n radians.
Kevin Lubick1a05fce2018-11-20 12:51:16 -050085 // px, py optionally say which point the rotation should be around
86 // with the default being (0, 0);
Kevin Lubickb9db3902018-11-26 11:47:54 -050087 CanvasKit.SkMatrix.rotated = function(radians, px, py) {
Kevin Lubick1a05fce2018-11-20 12:51:16 -050088 px = px || 0;
89 py = py || 0;
Kevin Lubickb9db3902018-11-26 11:47:54 -050090 var sinV = Math.sin(radians);
91 var cosV = Math.cos(radians);
Kevin Lubick1a05fce2018-11-20 12:51:16 -050092 return [
93 cosV, -sinV, sdot( sinV, py, 1 - cosV, px),
94 sinV, cosV, sdot(-sinV, px, 1 - cosV, py),
95 0, 0, 1,
96 ];
97 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -050098
Kevin Lubickb9db3902018-11-26 11:47:54 -050099 CanvasKit.SkMatrix.scaled = function(sx, sy, px, py) {
100 px = px || 0;
101 py = py || 0;
102 return [
103 sx, 0, px - sx * px,
104 0, sy, py - sy * py,
105 0, 0, 1,
106 ];
107 };
108
109 CanvasKit.SkMatrix.skewed = function(kx, ky, px, py) {
110 px = px || 0;
111 py = py || 0;
112 return [
113 1, kx, -kx * px,
114 ky, 1, -ky * py,
115 0, 0, 1,
116 ];
117 };
118
119 CanvasKit.SkMatrix.translated = function(dx, dy) {
120 return [
121 1, 0, dx,
122 0, 1, dy,
123 0, 0, 1,
124 ];
125 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500126
127 CanvasKit.SkPath.prototype.addArc = function(oval, startAngle, sweepAngle) {
128 // see arc() for the HTMLCanvas version
129 // note input angles are degrees.
130 this._addArc(oval, startAngle, sweepAngle);
131 return this;
132 };
133
Kevin Lubick217056c2018-09-20 17:39:31 -0400134 CanvasKit.SkPath.prototype.addPath = function() {
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500135 // Takes 1, 2, 7, or 10 required args, where the first arg is always the path.
136 // The last arg is optional and chooses between add or extend mode.
Kevin Lubick217056c2018-09-20 17:39:31 -0400137 // The options for the remaining args are:
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500138 // - an array of 6 or 9 parameters (perspective is optional)
139 // - the 9 parameters of a full matrix or
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400140 // the 6 non-perspective params of a matrix.
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500141 var args = Array.prototype.slice.call(arguments);
142 var path = args[0];
143 var extend = false;
144 if (typeof args[args.length-1] === "boolean") {
145 extend = args.pop();
146 }
147 if (args.length === 1) {
148 // Add path, unchanged. Use identity matrix
149 this._addPath(path, 1, 0, 0,
150 0, 1, 0,
151 0, 0, 1,
152 extend);
153 } else if (args.length === 2) {
Kevin Lubick217056c2018-09-20 17:39:31 -0400154 // User provided the 9 params of a full matrix as an array.
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500155 var a = args[1];
156 this._addPath(path, a[0], a[1], a[2],
157 a[3], a[4], a[5],
158 a[6] || 0, a[7] || 0, a[8] || 1,
159 extend);
160 } else if (args.length === 7 || args.length === 10) {
Kevin Lubick217056c2018-09-20 17:39:31 -0400161 // User provided the 9 params of a (full) matrix directly.
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400162 // (or just the 6 non perspective ones)
Kevin Lubick217056c2018-09-20 17:39:31 -0400163 // These are in the same order as what Skia expects.
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500164 var a = args;
165 this._addPath(path, a[1], a[2], a[3],
166 a[4], a[5], a[6],
167 a[7] || 0, a[8] || 0, a[9] || 1,
168 extend);
Kevin Lubick217056c2018-09-20 17:39:31 -0400169 } else {
Kevin Lubick6fccc9d2018-11-20 15:55:10 -0500170 SkDebug('addPath expected to take 1, 2, 7, or 10 required args. Got ' + args.length);
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500171 return null;
172 }
173 return this;
174 };
175
176 CanvasKit.SkPath.prototype.addRect = function() {
177 // Takes 1, 2, 4 or 5 args
178 // - SkRect
179 // - SkRect, isCCW
180 // - left, top, right, bottom
181 // - left, top, right, bottom, isCCW
182 if (arguments.length === 1 || arguments.length === 2) {
183 var r = arguments[0];
184 var ccw = arguments[1] || false;
185 this._addRect(r.fLeft, r.fTop, r.fRight, r.fBottom, ccw);
186 } else if (arguments.length === 4 || arguments.length === 5) {
187 var a = arguments;
188 this._addRect(a[0], a[1], a[2], a[3], a[4] || false);
189 } else {
Kevin Lubick6fccc9d2018-11-20 15:55:10 -0500190 SkDebug('addRect expected to take 1, 2, 4, or 5 args. Got ' + arguments.length);
Kevin Lubick217056c2018-09-20 17:39:31 -0400191 return null;
192 }
193 return this;
194 };
195
Kevin Lubickda3d8ac2019-01-07 11:08:55 -0500196 CanvasKit.SkPath.prototype.addRoundRect = function() {
197 // Takes 3, 4, 6 or 7 args
198 // - SkRect, radii, ccw
199 // - SkRect, rx, ry, ccw
200 // - left, top, right, bottom, radii, ccw
201 // - left, top, right, bottom, rx, ry, ccw
202 var args = arguments;
203 if (args.length === 3 || args.length === 6) {
204 var radii = args[args.length-2];
205 } else if (args.length === 6 || args.length === 7){
206 // duplicate the given (rx, ry) pairs for each corner.
207 var rx = args[args.length-3];
208 var ry = args[args.length-2];
209 var radii = [rx, ry, rx, ry, rx, ry, rx, ry];
210 } else {
211 SkDebug('addRoundRect expected to take 3, 4, 6, or 7 args. Got ' + args.length);
212 return null;
213 }
214 if (radii.length !== 8) {
215 SkDebug('addRoundRect needs 8 radii provided. Got ' + radii.length);
216 return null;
217 }
218 var rptr = copy1dArray(radii, CanvasKit.HEAPF32);
219 if (args.length === 3 || args.length === 4) {
220 var r = args[0];
221 var ccw = args[args.length - 1];
222 this._addRoundRect(r.fLeft, r.fTop, r.fRight, r.fBottom, rptr, ccw);
223 } else if (args.length === 6 || args.length === 7) {
224 var a = args;
225 this._addRoundRect(a[0], a[1], a[2], a[3], rptr, ccw);
226 }
227 CanvasKit._free(rptr);
228 return this;
229 };
230
Alexander Khovansky3e119332018-11-15 02:01:19 +0300231 CanvasKit.SkPath.prototype.arc = function(x, y, radius, startAngle, endAngle, ccw) {
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500232 // emulates the HTMLCanvas behavior. See addArc() for the SkPath version.
233 // Note input angles are radians.
234 var bounds = CanvasKit.LTRBRect(x-radius, y-radius, x+radius, y+radius);
235 var sweep = radiansToDegrees(endAngle - startAngle) - (360 * !!ccw);
236 var temp = new CanvasKit.SkPath();
237 temp.addArc(bounds, radiansToDegrees(startAngle), sweep);
238 this.addPath(temp, true);
239 temp.delete();
Alexander Khovansky3e119332018-11-15 02:01:19 +0300240 return this;
241 };
242
Kevin Lubick1646e7d2018-12-07 13:03:08 -0500243 CanvasKit.SkPath.prototype.arcTo = function() {
244 // takes 4, 5 or 7 args
245 // - 5 x1, y1, x2, y2, radius
246 // - 4 oval (as Rect), startAngle, sweepAngle, forceMoveTo
247 // - 7 x1, y1, x2, y2, startAngle, sweepAngle, forceMoveTo
248 var args = arguments;
249 if (args.length === 5) {
250 this._arcTo(args[0], args[1], args[2], args[3], args[4]);
251 } else if (args.length === 4) {
252 this._arcTo(args[0], args[1], args[2], args[3]);
253 } else if (args.length === 7) {
254 this._arcTo(CanvasKit.LTRBRect(args[0], args[1], args[2], args[3]),
255 args[4], args[5], args[6]);
256 } else {
257 throw 'Invalid args for arcTo. Expected 4, 5, or 7, got '+ args.length;
258 }
259
Kevin Lubick217056c2018-09-20 17:39:31 -0400260 return this;
261 };
262
263 CanvasKit.SkPath.prototype.close = function() {
264 this._close();
265 return this;
266 };
267
268 CanvasKit.SkPath.prototype.conicTo = function(x1, y1, x2, y2, w) {
269 this._conicTo(x1, y1, x2, y2, w);
270 return this;
271 };
272
273 CanvasKit.SkPath.prototype.cubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
274 this._cubicTo(cp1x, cp1y, cp2x, cp2y, x, y);
275 return this;
276 };
277
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400278 CanvasKit.SkPath.prototype.dash = function(on, off, phase) {
279 if (this._dash(on, off, phase)) {
280 return this;
281 }
282 return null;
283 };
284
Kevin Lubick217056c2018-09-20 17:39:31 -0400285 CanvasKit.SkPath.prototype.lineTo = function(x, y) {
286 this._lineTo(x, y);
287 return this;
288 };
289
290 CanvasKit.SkPath.prototype.moveTo = function(x, y) {
291 this._moveTo(x, y);
292 return this;
293 };
294
295 CanvasKit.SkPath.prototype.op = function(otherPath, op) {
296 if (this._op(otherPath, op)) {
297 return this;
298 }
299 return null;
300 };
301
302 CanvasKit.SkPath.prototype.quadTo = function(cpx, cpy, x, y) {
303 this._quadTo(cpx, cpy, x, y);
304 return this;
305 };
306
307 CanvasKit.SkPath.prototype.simplify = function() {
308 if (this._simplify()) {
309 return this;
310 }
311 return null;
312 };
313
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400314 CanvasKit.SkPath.prototype.stroke = function(opts) {
315 // Fill out any missing values with the default values.
316 /**
317 * See externs.js for this definition
318 * @type {StrokeOpts}
319 */
320 opts = opts || {};
321 opts.width = opts.width || 1;
322 opts.miter_limit = opts.miter_limit || 4;
Kevin Lubickb9db3902018-11-26 11:47:54 -0500323 opts.cap = opts.cap || CanvasKit.StrokeCap.Butt;
324 opts.join = opts.join || CanvasKit.StrokeJoin.Miter;
Kevin Lubick1646e7d2018-12-07 13:03:08 -0500325 opts.precision = opts.precision || 1;
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400326 if (this._stroke(opts)) {
327 return this;
328 }
329 return null;
330 };
331
Kevin Lubick217056c2018-09-20 17:39:31 -0400332 CanvasKit.SkPath.prototype.transform = function() {
333 // Takes 1 or 9 args
334 if (arguments.length === 1) {
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400335 // argument 1 should be a 6 or 9 element array.
Kevin Lubick217056c2018-09-20 17:39:31 -0400336 var a = arguments[0];
337 this._transform(a[0], a[1], a[2],
338 a[3], a[4], a[5],
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400339 a[6] || 0, a[7] || 0, a[8] || 1);
340 } else if (arguments.length === 6 || arguments.length === 9) {
341 // these arguments are the 6 or 9 members of the matrix
Kevin Lubick217056c2018-09-20 17:39:31 -0400342 var a = arguments;
343 this._transform(a[0], a[1], a[2],
344 a[3], a[4], a[5],
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400345 a[6] || 0, a[7] || 0, a[8] || 1);
Kevin Lubick217056c2018-09-20 17:39:31 -0400346 } else {
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400347 throw 'transform expected to take 1 or 9 arguments. Got ' + arguments.length;
Kevin Lubick217056c2018-09-20 17:39:31 -0400348 }
349 return this;
350 };
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400351 // isComplement is optional, defaults to false
352 CanvasKit.SkPath.prototype.trim = function(startT, stopT, isComplement) {
353 if (this._trim(startT, stopT, !!isComplement)) {
354 return this;
355 }
356 return null;
357 };
358
359 // bones should be a 3d array.
360 // Each bone is a 3x2 transformation matrix in column major order:
361 // | scaleX skewX transX |
362 // | skewY scaleY transY |
363 // and bones is an array of those matrices.
364 // Returns a copy of this (SkVertices) with the bones applied.
365 CanvasKit.SkVertices.prototype.applyBones = function(bones) {
366 var bPtr = copy3dArray(bones, CanvasKit.HEAPF32);
367 var vert = this._applyBones(bPtr, bones.length);
368 CanvasKit._free(bPtr);
369 return vert;
370 }
Kevin Lubick53965c92018-10-11 08:51:55 -0400371
Alexander Khovansky3e119332018-11-15 02:01:19 +0300372 CanvasKit.SkImage.prototype.encodeToData = function() {
Kevin Lubick52b9f372018-12-04 13:57:36 -0500373 if (!arguments.length) {
Alexander Khovansky3e119332018-11-15 02:01:19 +0300374 return this._encodeToData();
375 }
376
377 if (arguments.length === 2) {
378 var a = arguments;
379 return this._encodeToDataWithFormat(a[0], a[1]);
380 }
381
382 throw 'encodeToData expected to take 0 or 2 arguments. Got ' + arguments.length;
383 }
384
Kevin Lubick52b9f372018-12-04 13:57:36 -0500385 // returns Uint8Array
386 CanvasKit.SkCanvas.prototype.readPixels = function(x, y, w, h, alphaType,
387 colorType, dstRowBytes) {
388 // supply defaults (which are compatible with HTMLCanvas's getImageData)
389 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
390 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
391 dstRowBytes = dstRowBytes || (4 * w);
392
393 var len = h * dstRowBytes
394 var pptr = CanvasKit._malloc(len);
395 var ok = this._readPixels({
396 'width': w,
397 'height': h,
398 'colorType': colorType,
399 'alphaType': alphaType,
400 }, pptr, dstRowBytes, x, y);
401 if (!ok) {
402 CanvasKit._free(pptr);
403 return null;
404 }
405
406 // The first typed array is just a view into memory. Because we will
407 // be free-ing that, we call slice to make a persistent copy.
408 var pixels = new Uint8Array(CanvasKit.HEAPU8.buffer, pptr, len).slice();
409 CanvasKit._free(pptr);
410 return pixels;
411 }
412
413 // pixels is a TypedArray. No matter the input size, it will be treated as
414 // a Uint8Array (essentially, a byte array).
415 CanvasKit.SkCanvas.prototype.writePixels = function(pixels, srcWidth, srcHeight,
416 destX, destY, alphaType, colorType) {
417 if (pixels.byteLength % (srcWidth * srcHeight)) {
418 throw 'pixels length must be a multiple of the srcWidth * srcHeight';
419 }
420 var bytesPerPixel = pixels.byteLength / (srcWidth * srcHeight);
421 // supply defaults (which are compatible with HTMLCanvas's putImageData)
422 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
423 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
424 var srcRowBytes = bytesPerPixel * srcWidth;
425
426 var pptr = CanvasKit._malloc(pixels.byteLength);
427 CanvasKit.HEAPU8.set(pixels, pptr);
428
429 var ok = this._writePixels({
430 'width': srcWidth,
431 'height': srcHeight,
432 'colorType': colorType,
433 'alphaType': alphaType,
434 }, pptr, srcRowBytes, destX, destY);
435
436 CanvasKit._free(pptr);
437 return ok;
438 }
439
Kevin Lubickddd0a332018-12-12 10:35:13 -0500440 // fontData should be an arrayBuffer
441 CanvasKit.SkFontMgr.prototype.MakeTypefaceFromData = function(fontData) {
442 var data = new Uint8Array(fontData);
443
444 var fptr = CanvasKit._malloc(data.byteLength);
445 CanvasKit.HEAPU8.set(data, fptr);
446 var font = this._makeTypefaceFromData(fptr, data.byteLength);
447 if (!font) {
448 SkDebug('Could not decode font data');
449 // We do not need to free the data since the C++ will do that for us
Kevin Lubick8e4a3312018-12-14 15:03:41 -0500450 // when the font is deleted (or fails to decode);
Kevin Lubickddd0a332018-12-12 10:35:13 -0500451 return null;
452 }
Kevin Lubickddd0a332018-12-12 10:35:13 -0500453 return font;
454 }
455
Kevin Lubick5b90b842018-10-17 07:57:18 -0400456 // Run through the JS files that are added at compile time.
457 if (CanvasKit._extraInitializations) {
458 CanvasKit._extraInitializations.forEach(function(init) {
459 init();
460 });
Kevin Lubick217056c2018-09-20 17:39:31 -0400461 }
Kevin Lubick3d99b1e2018-10-16 10:15:01 -0400462 } // end CanvasKit.onRuntimeInitialized, that is, anything changing prototypes or dynamic.
Kevin Lubick53965c92018-10-11 08:51:55 -0400463
Kevin Lubick217056c2018-09-20 17:39:31 -0400464 CanvasKit.LTRBRect = function(l, t, r, b) {
465 return {
466 fLeft: l,
467 fTop: t,
468 fRight: r,
469 fBottom: b,
470 };
471 }
472
Kevin Lubick0a1293c2018-12-03 12:31:04 -0500473 CanvasKit.XYWHRect = function(x, y, w, h) {
474 return {
475 fLeft: x,
476 fTop: y,
477 fRight: x+w,
478 fBottom: y+h,
479 };
480 }
481
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400482 var nullptr = 0; // emscripten doesn't like to take null as uintptr_t
483
484 // arr can be a normal JS array or a TypedArray
485 // dest is something like CanvasKit.HEAPF32
486 function copy1dArray(arr, dest) {
487 if (!arr || !arr.length) {
488 return nullptr;
489 }
490 var ptr = CanvasKit._malloc(arr.length * dest.BYTES_PER_ELEMENT);
491 // In c++ terms, the WASM heap is a uint8_t*, a long buffer/array of single
492 // byte elements. When we run _malloc, we always get an offset/pointer into
493 // that block of memory.
494 // CanvasKit exposes some different views to make it easier to work with
495 // different types. HEAPF32 for example, exposes it as a float*
496 // However, to make the ptr line up, we have to do some pointer arithmetic.
497 // Concretely, we need to convert ptr to go from an index into a 1-byte-wide
498 // buffer to an index into a 4-byte-wide buffer (in the case of HEAPF32)
499 // and thus we divide ptr by 4.
500 dest.set(arr, ptr / dest.BYTES_PER_ELEMENT);
501 return ptr;
502 }
503
504 // arr should be a non-jagged 2d JS array (TypeyArrays can't be nested
505 // inside themselves.)
506 // dest is something like CanvasKit.HEAPF32
507 function copy2dArray(arr, dest) {
508 if (!arr || !arr.length) {
509 return nullptr;
510 }
511 var ptr = CanvasKit._malloc(arr.length * arr[0].length * dest.BYTES_PER_ELEMENT);
512 var idx = 0;
513 var adjustedPtr = ptr / dest.BYTES_PER_ELEMENT;
514 for (var r = 0; r < arr.length; r++) {
515 for (var c = 0; c < arr[0].length; c++) {
516 dest[adjustedPtr + idx] = arr[r][c];
517 idx++;
518 }
519 }
520 return ptr;
521 }
522
523 // arr should be a non-jagged 3d JS array (TypeyArrays can't be nested
524 // inside themselves.)
525 // dest is something like CanvasKit.HEAPF32
526 function copy3dArray(arr, dest) {
527 if (!arr || !arr.length || !arr[0].length) {
528 return nullptr;
529 }
530 var ptr = CanvasKit._malloc(arr.length * arr[0].length * arr[0][0].length * dest.BYTES_PER_ELEMENT);
531 var idx = 0;
532 var adjustedPtr = ptr / dest.BYTES_PER_ELEMENT;
533 for (var x = 0; x < arr.length; x++) {
534 for (var y = 0; y < arr[0].length; y++) {
535 for (var z = 0; z < arr[0][0].length; z++) {
536 dest[adjustedPtr + idx] = arr[x][y][z];
537 idx++;
538 }
539 }
540 }
541 return ptr;
542 }
543
Kevin Lubickda3d8ac2019-01-07 11:08:55 -0500544 // Caching the Float32Arrays can save having to reallocate them
545 // over and over again.
546 var Float32ArrayCache = {};
547
548 // Takes a 2D array of commands and puts them into the WASM heap
549 // as a 1D array. This allows them to referenced from the C++ code.
550 // Returns a 2 element array, with the first item being essentially a
551 // pointer to the array and the second item being the length of
552 // the new 1D array.
553 //
554 // Example usage:
555 // let cmds = [
556 // [CanvasKit.MOVE_VERB, 0, 10],
557 // [CanvasKit.LINE_VERB, 30, 40],
558 // [CanvasKit.QUAD_VERB, 20, 50, 45, 60],
559 // ];
560 function loadCmdsTypedArray(arr) {
561 var len = 0;
562 for (var r = 0; r < arr.length; r++) {
563 len += arr[r].length;
564 }
565
566 var ta;
567 if (Float32ArrayCache[len]) {
568 ta = Float32ArrayCache[len];
569 } else {
570 ta = new Float32Array(len);
571 Float32ArrayCache[len] = ta;
572 }
573 // Flatten into a 1d array
574 var i = 0;
575 for (var r = 0; r < arr.length; r++) {
576 for (var c = 0; c < arr[r].length; c++) {
577 var item = arr[r][c];
578 ta[i] = item;
579 i++;
580 }
581 }
582
583 var ptr = copy1dArray(ta, CanvasKit.HEAPF32);
584 return [ptr, len];
585 }
586
587 CanvasKit.MakePathFromCmds = function(cmds) {
588 var ptrLen = loadCmdsTypedArray(cmds);
589 var path = CanvasKit._MakePathFromCmds(ptrLen[0], ptrLen[1]);
590 CanvasKit._free(ptrLen[0]);
591 return path;
592 }
593
Kevin Lubick217056c2018-09-20 17:39:31 -0400594 CanvasKit.MakeSkDashPathEffect = function(intervals, phase) {
595 if (!phase) {
596 phase = 0;
597 }
598 if (!intervals.length || intervals.length % 2 === 1) {
599 throw 'Intervals array must have even length';
600 }
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400601 var ptr = copy1dArray(intervals, CanvasKit.HEAPF32);
602 var dpe = CanvasKit._MakeSkDashPathEffect(ptr, intervals.length, phase);
603 CanvasKit._free(ptr);
604 return dpe;
605 }
606
Kevin Lubickd29edd72018-12-07 08:29:52 -0500607 // data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
Kevin Lubick0a1293c2018-12-03 12:31:04 -0500608 CanvasKit.MakeImageFromEncoded = function(data) {
609 data = new Uint8Array(data);
610
611 var iptr = CanvasKit._malloc(data.byteLength);
612 CanvasKit.HEAPU8.set(data, iptr);
613 var img = CanvasKit._decodeImage(iptr, data.byteLength);
614 if (!img) {
615 SkDebug('Could not decode image');
616 CanvasKit._free(iptr);
617 return null;
618 }
619 var realDelete = img.delete.bind(img);
620 img.delete = function() {
621 CanvasKit._free(iptr);
622 realDelete();
623 }
624 return img;
625 }
626
Kevin Lubickd29edd72018-12-07 08:29:52 -0500627 // imgData is an Encoded SkImage, e.g. from MakeImageFromEncoded
628 CanvasKit.MakeImageShader = function(img, xTileMode, yTileMode, clampUnpremul, localMatrix) {
629 if (!img) {
630 return null;
631 }
632 clampUnpremul = clampUnpremul || false;
633 if (localMatrix) {
634 // Add perspective args if not provided.
635 if (localMatrix.length === 6) {
636 localMatrix.push(0, 0, 1);
637 }
638 return CanvasKit._MakeImageShader(img, xTileMode, yTileMode, clampUnpremul, localMatrix);
639 } else {
640 return CanvasKit._MakeImageShader(img, xTileMode, yTileMode, clampUnpremul);
641 }
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400642 }
643
Kevin Lubick52b9f372018-12-04 13:57:36 -0500644 // pixels is a Uint8Array
645 CanvasKit.MakeImage = function(pixels, width, height, alphaType, colorType) {
646 var bytesPerPixel = pixels.byteLength / (width * height);
647 var info = {
648 'width': width,
649 'height': height,
650 'alphaType': alphaType,
651 'colorType': colorType,
652 };
653 var pptr = CanvasKit._malloc(pixels.byteLength);
654 CanvasKit.HEAPU8.set(pixels, pptr);
655 // No need to _free iptr, Image takes it with SkData::MakeFromMalloc
656
657 return CanvasKit._MakeImage(info, pptr, pixels.byteLength, width * bytesPerPixel);
658 }
659
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400660 CanvasKit.MakeLinearGradientShader = function(start, end, colors, pos, mode, localMatrix, flags) {
661 var colorPtr = copy1dArray(colors, CanvasKit.HEAP32);
662 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
663 flags = flags || 0;
664
665 if (localMatrix) {
666 // Add perspective args if not provided.
667 if (localMatrix.length === 6) {
668 localMatrix.push(0, 0, 1);
669 }
670 var lgs = CanvasKit._MakeLinearGradientShader(start, end, colorPtr, posPtr,
671 colors.length, mode, flags, localMatrix);
672 } else {
673 var lgs = CanvasKit._MakeLinearGradientShader(start, end, colorPtr, posPtr,
674 colors.length, mode, flags);
Kevin Lubick217056c2018-09-20 17:39:31 -0400675 }
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400676
677 CanvasKit._free(colorPtr);
678 CanvasKit._free(posPtr);
679 return lgs;
680 }
681
682 CanvasKit.MakeRadialGradientShader = function(center, radius, colors, pos, mode, localMatrix, flags) {
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400683 var colorPtr = copy1dArray(colors, CanvasKit.HEAP32);
684 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
685 flags = flags || 0;
686
687 if (localMatrix) {
688 // Add perspective args if not provided.
689 if (localMatrix.length === 6) {
690 localMatrix.push(0, 0, 1);
691 }
692 var rgs = CanvasKit._MakeRadialGradientShader(center, radius, colorPtr, posPtr,
693 colors.length, mode, flags, localMatrix);
694 } else {
695 var rgs = CanvasKit._MakeRadialGradientShader(center, radius, colorPtr, posPtr,
696 colors.length, mode, flags);
697 }
698
699 CanvasKit._free(colorPtr);
700 CanvasKit._free(posPtr);
701 return rgs;
702 }
703
Kevin Lubickeb2f6b02018-11-29 15:07:02 -0500704 CanvasKit.MakeTwoPointConicalGradientShader = function(start, startRadius, end, endRadius,
705 colors, pos, mode, localMatrix, flags) {
706 var colorPtr = copy1dArray(colors, CanvasKit.HEAP32);
707 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
708 flags = flags || 0;
709
710 if (localMatrix) {
711 // Add perspective args if not provided.
712 if (localMatrix.length === 6) {
713 localMatrix.push(0, 0, 1);
714 }
715 var rgs = CanvasKit._MakeTwoPointConicalGradientShader(
716 start, startRadius, end, endRadius,
717 colorPtr, posPtr, colors.length, mode, flags, localMatrix);
718 } else {
719 var rgs = CanvasKit._MakeTwoPointConicalGradientShader(
720 start, startRadius, end, endRadius,
721 colorPtr, posPtr, colors.length, mode, flags);
722 }
723
724 CanvasKit._free(colorPtr);
725 CanvasKit._free(posPtr);
726 return rgs;
727 }
728
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400729 CanvasKit.MakeSkVertices = function(mode, positions, textureCoordinates, colors,
730 boneIndices, boneWeights, indices) {
731 var positionPtr = copy2dArray(positions, CanvasKit.HEAPF32);
732 var texPtr = copy2dArray(textureCoordinates, CanvasKit.HEAPF32);
733 // Since we write the colors to memory as signed integers (JSColor), we can
734 // read them out on the other side as unsigned ints (SkColor) just fine
735 // - it's effectively casting.
736 var colorPtr = copy1dArray(colors, CanvasKit.HEAP32);
737
738 var boneIdxPtr = copy2dArray(boneIndices, CanvasKit.HEAP32);
739 var boneWtPtr = copy2dArray(boneWeights, CanvasKit.HEAPF32);
740 var idxPtr = copy1dArray(indices, CanvasKit.HEAPU16);
741
742 var idxCount = (indices && indices.length) || 0;
743 // _MakeVertices will copy all the values in, so we are free to release
744 // the memory after.
745 var vertices = CanvasKit._MakeSkVertices(mode, positions.length, positionPtr,
746 texPtr, colorPtr, boneIdxPtr, boneWtPtr,
747 idxCount, idxPtr);
748 positionPtr && CanvasKit._free(positionPtr);
749 texPtr && CanvasKit._free(texPtr);
750 colorPtr && CanvasKit._free(colorPtr);
751 idxPtr && CanvasKit._free(idxPtr);
752 boneIdxPtr && CanvasKit._free(boneIdxPtr);
753 boneWtPtr && CanvasKit._free(boneWtPtr);
754 return vertices;
Kevin Lubick217056c2018-09-20 17:39:31 -0400755 }
756
Kevin Lubick217056c2018-09-20 17:39:31 -0400757}(Module)); // When this file is loaded in, the high level object is "Module";
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500758
759// Intentionally added outside the scope to allow usage in canvas2d.js and other
760// pre-js files. These names are unlikely to cause emscripten collisions.
761function radiansToDegrees(rad) {
762 return (rad / Math.PI) * 180;
763}
764
765function degreesToRadians(deg) {
766 return (deg / 180) * Math.PI;
767}
768