blob: fe0d6be6ee58ea04ce9f576e14d74fd4017af4e5 [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 Lubickec4903d2019-01-14 08:36:08 -0500385 CanvasKit.SkCanvas.prototype.drawText = function(str, x, y, font, paint) {
386 // lengthBytesUTF8 and stringToUTF8Array are defined in the emscripten
387 // JS. See https://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html#stringToUTF8
388 // Add 1 for null terminator
389 var strLen = lengthBytesUTF8(str) + 1;
390 var strPtr = CanvasKit._malloc(strLen);
391 // Add 1 for the null terminator.
392 stringToUTF8(str, strPtr, strLen);
393 this._drawSimpleText(strPtr, strLen, x, y, font, paint);
394 }
395
Kevin Lubick52b9f372018-12-04 13:57:36 -0500396 // returns Uint8Array
397 CanvasKit.SkCanvas.prototype.readPixels = function(x, y, w, h, alphaType,
398 colorType, dstRowBytes) {
399 // supply defaults (which are compatible with HTMLCanvas's getImageData)
400 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
401 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
402 dstRowBytes = dstRowBytes || (4 * w);
403
404 var len = h * dstRowBytes
405 var pptr = CanvasKit._malloc(len);
406 var ok = this._readPixels({
407 'width': w,
408 'height': h,
409 'colorType': colorType,
410 'alphaType': alphaType,
411 }, pptr, dstRowBytes, x, y);
412 if (!ok) {
413 CanvasKit._free(pptr);
414 return null;
415 }
416
417 // The first typed array is just a view into memory. Because we will
418 // be free-ing that, we call slice to make a persistent copy.
419 var pixels = new Uint8Array(CanvasKit.HEAPU8.buffer, pptr, len).slice();
420 CanvasKit._free(pptr);
421 return pixels;
422 }
423
424 // pixels is a TypedArray. No matter the input size, it will be treated as
425 // a Uint8Array (essentially, a byte array).
426 CanvasKit.SkCanvas.prototype.writePixels = function(pixels, srcWidth, srcHeight,
427 destX, destY, alphaType, colorType) {
428 if (pixels.byteLength % (srcWidth * srcHeight)) {
429 throw 'pixels length must be a multiple of the srcWidth * srcHeight';
430 }
431 var bytesPerPixel = pixels.byteLength / (srcWidth * srcHeight);
432 // supply defaults (which are compatible with HTMLCanvas's putImageData)
433 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
434 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
435 var srcRowBytes = bytesPerPixel * srcWidth;
436
437 var pptr = CanvasKit._malloc(pixels.byteLength);
438 CanvasKit.HEAPU8.set(pixels, pptr);
439
440 var ok = this._writePixels({
441 'width': srcWidth,
442 'height': srcHeight,
443 'colorType': colorType,
444 'alphaType': alphaType,
445 }, pptr, srcRowBytes, destX, destY);
446
447 CanvasKit._free(pptr);
448 return ok;
449 }
450
Kevin Lubickddd0a332018-12-12 10:35:13 -0500451 // fontData should be an arrayBuffer
452 CanvasKit.SkFontMgr.prototype.MakeTypefaceFromData = function(fontData) {
453 var data = new Uint8Array(fontData);
454
455 var fptr = CanvasKit._malloc(data.byteLength);
456 CanvasKit.HEAPU8.set(data, fptr);
457 var font = this._makeTypefaceFromData(fptr, data.byteLength);
458 if (!font) {
459 SkDebug('Could not decode font data');
460 // We do not need to free the data since the C++ will do that for us
Kevin Lubick8e4a3312018-12-14 15:03:41 -0500461 // when the font is deleted (or fails to decode);
Kevin Lubickddd0a332018-12-12 10:35:13 -0500462 return null;
463 }
Kevin Lubickddd0a332018-12-12 10:35:13 -0500464 return font;
465 }
466
Kevin Lubickec4903d2019-01-14 08:36:08 -0500467 CanvasKit.SkTextBlob.MakeFromText = function(str, font) {
468 // lengthBytesUTF8 and stringToUTF8Array are defined in the emscripten
469 // JS. See https://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html#stringToUTF8
470 // Add 1 for null terminator
471 var strLen = lengthBytesUTF8(str) + 1;
472 var strPtr = CanvasKit._malloc(strLen);
473 // Add 1 for the null terminator.
474 stringToUTF8(str, strPtr, strLen);
475
476 var blob = CanvasKit.SkTextBlob._MakeFromText(strPtr, strLen - 1, font, CanvasKit.TextEncoding.UTF8);
477 if (!blob) {
478 SkDebug('Could not make textblob from string "' + str + '"');
479 return null;
480 }
481
482 var origDelete = blob.delete.bind(blob);
483 blob.delete = function() {
484 CanvasKit._free(strPtr);
485 origDelete();
486 }
487 return blob;
488 }
489
Kevin Lubick5b90b842018-10-17 07:57:18 -0400490 // Run through the JS files that are added at compile time.
491 if (CanvasKit._extraInitializations) {
492 CanvasKit._extraInitializations.forEach(function(init) {
493 init();
494 });
Kevin Lubick217056c2018-09-20 17:39:31 -0400495 }
Kevin Lubick3d99b1e2018-10-16 10:15:01 -0400496 } // end CanvasKit.onRuntimeInitialized, that is, anything changing prototypes or dynamic.
Kevin Lubick53965c92018-10-11 08:51:55 -0400497
Kevin Lubick217056c2018-09-20 17:39:31 -0400498 CanvasKit.LTRBRect = function(l, t, r, b) {
499 return {
500 fLeft: l,
501 fTop: t,
502 fRight: r,
503 fBottom: b,
504 };
505 }
506
Kevin Lubick0a1293c2018-12-03 12:31:04 -0500507 CanvasKit.XYWHRect = function(x, y, w, h) {
508 return {
509 fLeft: x,
510 fTop: y,
511 fRight: x+w,
512 fBottom: y+h,
513 };
514 }
515
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400516 var nullptr = 0; // emscripten doesn't like to take null as uintptr_t
517
518 // arr can be a normal JS array or a TypedArray
519 // dest is something like CanvasKit.HEAPF32
520 function copy1dArray(arr, dest) {
521 if (!arr || !arr.length) {
522 return nullptr;
523 }
524 var ptr = CanvasKit._malloc(arr.length * dest.BYTES_PER_ELEMENT);
525 // In c++ terms, the WASM heap is a uint8_t*, a long buffer/array of single
526 // byte elements. When we run _malloc, we always get an offset/pointer into
527 // that block of memory.
528 // CanvasKit exposes some different views to make it easier to work with
529 // different types. HEAPF32 for example, exposes it as a float*
530 // However, to make the ptr line up, we have to do some pointer arithmetic.
531 // Concretely, we need to convert ptr to go from an index into a 1-byte-wide
532 // buffer to an index into a 4-byte-wide buffer (in the case of HEAPF32)
533 // and thus we divide ptr by 4.
534 dest.set(arr, ptr / dest.BYTES_PER_ELEMENT);
535 return ptr;
536 }
537
538 // arr should be a non-jagged 2d JS array (TypeyArrays can't be nested
539 // inside themselves.)
540 // dest is something like CanvasKit.HEAPF32
541 function copy2dArray(arr, dest) {
542 if (!arr || !arr.length) {
543 return nullptr;
544 }
545 var ptr = CanvasKit._malloc(arr.length * arr[0].length * dest.BYTES_PER_ELEMENT);
546 var idx = 0;
547 var adjustedPtr = ptr / dest.BYTES_PER_ELEMENT;
548 for (var r = 0; r < arr.length; r++) {
549 for (var c = 0; c < arr[0].length; c++) {
550 dest[adjustedPtr + idx] = arr[r][c];
551 idx++;
552 }
553 }
554 return ptr;
555 }
556
557 // arr should be a non-jagged 3d JS array (TypeyArrays can't be nested
558 // inside themselves.)
559 // dest is something like CanvasKit.HEAPF32
560 function copy3dArray(arr, dest) {
561 if (!arr || !arr.length || !arr[0].length) {
562 return nullptr;
563 }
564 var ptr = CanvasKit._malloc(arr.length * arr[0].length * arr[0][0].length * dest.BYTES_PER_ELEMENT);
565 var idx = 0;
566 var adjustedPtr = ptr / dest.BYTES_PER_ELEMENT;
567 for (var x = 0; x < arr.length; x++) {
568 for (var y = 0; y < arr[0].length; y++) {
569 for (var z = 0; z < arr[0][0].length; z++) {
570 dest[adjustedPtr + idx] = arr[x][y][z];
571 idx++;
572 }
573 }
574 }
575 return ptr;
576 }
577
Kevin Lubickda3d8ac2019-01-07 11:08:55 -0500578 // Caching the Float32Arrays can save having to reallocate them
579 // over and over again.
580 var Float32ArrayCache = {};
581
582 // Takes a 2D array of commands and puts them into the WASM heap
583 // as a 1D array. This allows them to referenced from the C++ code.
584 // Returns a 2 element array, with the first item being essentially a
585 // pointer to the array and the second item being the length of
586 // the new 1D array.
587 //
588 // Example usage:
589 // let cmds = [
590 // [CanvasKit.MOVE_VERB, 0, 10],
591 // [CanvasKit.LINE_VERB, 30, 40],
592 // [CanvasKit.QUAD_VERB, 20, 50, 45, 60],
593 // ];
594 function loadCmdsTypedArray(arr) {
595 var len = 0;
596 for (var r = 0; r < arr.length; r++) {
597 len += arr[r].length;
598 }
599
600 var ta;
601 if (Float32ArrayCache[len]) {
602 ta = Float32ArrayCache[len];
603 } else {
604 ta = new Float32Array(len);
605 Float32ArrayCache[len] = ta;
606 }
607 // Flatten into a 1d array
608 var i = 0;
609 for (var r = 0; r < arr.length; r++) {
610 for (var c = 0; c < arr[r].length; c++) {
611 var item = arr[r][c];
612 ta[i] = item;
613 i++;
614 }
615 }
616
617 var ptr = copy1dArray(ta, CanvasKit.HEAPF32);
618 return [ptr, len];
619 }
620
621 CanvasKit.MakePathFromCmds = function(cmds) {
622 var ptrLen = loadCmdsTypedArray(cmds);
623 var path = CanvasKit._MakePathFromCmds(ptrLen[0], ptrLen[1]);
624 CanvasKit._free(ptrLen[0]);
625 return path;
626 }
627
Kevin Lubick217056c2018-09-20 17:39:31 -0400628 CanvasKit.MakeSkDashPathEffect = function(intervals, phase) {
629 if (!phase) {
630 phase = 0;
631 }
632 if (!intervals.length || intervals.length % 2 === 1) {
633 throw 'Intervals array must have even length';
634 }
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400635 var ptr = copy1dArray(intervals, CanvasKit.HEAPF32);
636 var dpe = CanvasKit._MakeSkDashPathEffect(ptr, intervals.length, phase);
637 CanvasKit._free(ptr);
638 return dpe;
639 }
640
Kevin Lubickd29edd72018-12-07 08:29:52 -0500641 // data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
Kevin Lubick0a1293c2018-12-03 12:31:04 -0500642 CanvasKit.MakeImageFromEncoded = function(data) {
643 data = new Uint8Array(data);
644
645 var iptr = CanvasKit._malloc(data.byteLength);
646 CanvasKit.HEAPU8.set(data, iptr);
647 var img = CanvasKit._decodeImage(iptr, data.byteLength);
648 if (!img) {
649 SkDebug('Could not decode image');
650 CanvasKit._free(iptr);
651 return null;
652 }
653 var realDelete = img.delete.bind(img);
654 img.delete = function() {
655 CanvasKit._free(iptr);
656 realDelete();
657 }
658 return img;
659 }
660
Kevin Lubickd29edd72018-12-07 08:29:52 -0500661 // imgData is an Encoded SkImage, e.g. from MakeImageFromEncoded
662 CanvasKit.MakeImageShader = function(img, xTileMode, yTileMode, clampUnpremul, localMatrix) {
663 if (!img) {
664 return null;
665 }
666 clampUnpremul = clampUnpremul || false;
667 if (localMatrix) {
668 // Add perspective args if not provided.
669 if (localMatrix.length === 6) {
670 localMatrix.push(0, 0, 1);
671 }
672 return CanvasKit._MakeImageShader(img, xTileMode, yTileMode, clampUnpremul, localMatrix);
673 } else {
674 return CanvasKit._MakeImageShader(img, xTileMode, yTileMode, clampUnpremul);
675 }
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400676 }
677
Kevin Lubick52b9f372018-12-04 13:57:36 -0500678 // pixels is a Uint8Array
679 CanvasKit.MakeImage = function(pixels, width, height, alphaType, colorType) {
680 var bytesPerPixel = pixels.byteLength / (width * height);
681 var info = {
682 'width': width,
683 'height': height,
684 'alphaType': alphaType,
685 'colorType': colorType,
686 };
687 var pptr = CanvasKit._malloc(pixels.byteLength);
688 CanvasKit.HEAPU8.set(pixels, pptr);
689 // No need to _free iptr, Image takes it with SkData::MakeFromMalloc
690
691 return CanvasKit._MakeImage(info, pptr, pixels.byteLength, width * bytesPerPixel);
692 }
693
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400694 CanvasKit.MakeLinearGradientShader = function(start, end, colors, pos, mode, localMatrix, flags) {
695 var colorPtr = copy1dArray(colors, CanvasKit.HEAP32);
696 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
697 flags = flags || 0;
698
699 if (localMatrix) {
700 // Add perspective args if not provided.
701 if (localMatrix.length === 6) {
702 localMatrix.push(0, 0, 1);
703 }
704 var lgs = CanvasKit._MakeLinearGradientShader(start, end, colorPtr, posPtr,
705 colors.length, mode, flags, localMatrix);
706 } else {
707 var lgs = CanvasKit._MakeLinearGradientShader(start, end, colorPtr, posPtr,
708 colors.length, mode, flags);
Kevin Lubick217056c2018-09-20 17:39:31 -0400709 }
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400710
711 CanvasKit._free(colorPtr);
712 CanvasKit._free(posPtr);
713 return lgs;
714 }
715
716 CanvasKit.MakeRadialGradientShader = function(center, radius, colors, pos, mode, localMatrix, flags) {
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400717 var colorPtr = copy1dArray(colors, CanvasKit.HEAP32);
718 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
719 flags = flags || 0;
720
721 if (localMatrix) {
722 // Add perspective args if not provided.
723 if (localMatrix.length === 6) {
724 localMatrix.push(0, 0, 1);
725 }
726 var rgs = CanvasKit._MakeRadialGradientShader(center, radius, colorPtr, posPtr,
727 colors.length, mode, flags, localMatrix);
728 } else {
729 var rgs = CanvasKit._MakeRadialGradientShader(center, radius, colorPtr, posPtr,
730 colors.length, mode, flags);
731 }
732
733 CanvasKit._free(colorPtr);
734 CanvasKit._free(posPtr);
735 return rgs;
736 }
737
Kevin Lubickeb2f6b02018-11-29 15:07:02 -0500738 CanvasKit.MakeTwoPointConicalGradientShader = function(start, startRadius, end, endRadius,
739 colors, pos, mode, localMatrix, flags) {
740 var colorPtr = copy1dArray(colors, CanvasKit.HEAP32);
741 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
742 flags = flags || 0;
743
744 if (localMatrix) {
745 // Add perspective args if not provided.
746 if (localMatrix.length === 6) {
747 localMatrix.push(0, 0, 1);
748 }
749 var rgs = CanvasKit._MakeTwoPointConicalGradientShader(
750 start, startRadius, end, endRadius,
751 colorPtr, posPtr, colors.length, mode, flags, localMatrix);
752 } else {
753 var rgs = CanvasKit._MakeTwoPointConicalGradientShader(
754 start, startRadius, end, endRadius,
755 colorPtr, posPtr, colors.length, mode, flags);
756 }
757
758 CanvasKit._free(colorPtr);
759 CanvasKit._free(posPtr);
760 return rgs;
761 }
762
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400763 CanvasKit.MakeSkVertices = function(mode, positions, textureCoordinates, colors,
764 boneIndices, boneWeights, indices) {
765 var positionPtr = copy2dArray(positions, CanvasKit.HEAPF32);
766 var texPtr = copy2dArray(textureCoordinates, CanvasKit.HEAPF32);
767 // Since we write the colors to memory as signed integers (JSColor), we can
768 // read them out on the other side as unsigned ints (SkColor) just fine
769 // - it's effectively casting.
770 var colorPtr = copy1dArray(colors, CanvasKit.HEAP32);
771
772 var boneIdxPtr = copy2dArray(boneIndices, CanvasKit.HEAP32);
773 var boneWtPtr = copy2dArray(boneWeights, CanvasKit.HEAPF32);
774 var idxPtr = copy1dArray(indices, CanvasKit.HEAPU16);
775
776 var idxCount = (indices && indices.length) || 0;
777 // _MakeVertices will copy all the values in, so we are free to release
778 // the memory after.
779 var vertices = CanvasKit._MakeSkVertices(mode, positions.length, positionPtr,
780 texPtr, colorPtr, boneIdxPtr, boneWtPtr,
781 idxCount, idxPtr);
782 positionPtr && CanvasKit._free(positionPtr);
783 texPtr && CanvasKit._free(texPtr);
784 colorPtr && CanvasKit._free(colorPtr);
785 idxPtr && CanvasKit._free(idxPtr);
786 boneIdxPtr && CanvasKit._free(boneIdxPtr);
787 boneWtPtr && CanvasKit._free(boneWtPtr);
788 return vertices;
Kevin Lubick217056c2018-09-20 17:39:31 -0400789 }
790
Kevin Lubick217056c2018-09-20 17:39:31 -0400791}(Module)); // When this file is loaded in, the high level object is "Module";
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500792
793// Intentionally added outside the scope to allow usage in canvas2d.js and other
794// pre-js files. These names are unlikely to cause emscripten collisions.
795function radiansToDegrees(rad) {
796 return (rad / Math.PI) * 180;
797}
798
799function degreesToRadians(deg) {
800 return (deg / 180) * Math.PI;
801}
802