blob: 16878613cbd5ab33c66b6d3ef2ae9b78b2fea95c [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 Lubick1a05fce2018-11-20 12:51:16 -05004
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05005// 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.
8CanvasKit.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
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050011 // Add some helpers for matrices. This is ported from SkMatrix.cpp
12 // to save complexity and overhead of going back and forth between
13 // C++ and JS layers.
14 // I would have liked to use something like DOMMatrix, except it
15 // isn't widely supported (would need polyfills) and it doesn't
16 // have a mapPoints() function (which could maybe be tacked on here).
17 // If DOMMatrix catches on, it would be worth re-considering this usage.
18 CanvasKit.SkMatrix = {};
Nathaniel Nifong77798b42020-02-21 17:15:22 -050019 function sdot() { // to be called with an even number of scalar args
20 var acc = 0;
21 for (var i=0; i < arguments.length-1; i+=2) {
22 acc += arguments[i] * arguments[i+1];
23 }
24 return acc;
25 }
26
27
28 // Private general matrix functions used in both 3x3s and 4x4s.
29 // Return a square identity matrix of size n.
30 var identityN = function(n) {
31 var size = n*n;
32 var m = new Array(size);
33 while(size--) {
34 m[size] = size%(n+1) == 0 ? 1.0 : 0.0;
35 }
36 return m;
37 }
38
39 // Stride, a function for compactly representing several ways of copying an array into another.
40 // Write vector `v` into matrix `m`. `m` is a matrix encoded as an array in row-major
41 // order. Its width is passed as `width`. `v` is an array with length < (m.length/width).
42 // An element of `v` is copied into `m` starting at `offset` and moving `colStride` cols right
43 // each row.
44 //
45 // For example, a width of 4, offset of 3, and stride of -1 would put the vector here.
46 // _ _ 0 _
47 // _ 1 _ _
48 // 2 _ _ _
49 // _ _ _ 3
50 //
51 var stride = function(v, m, width, offset, colStride) {
52 for (var i=0; i<v.length; i++) {
53 m[i * width + // column
54 (i * colStride + offset + width) % width // row
55 ] = v[i];
56 }
57 return m;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050058 }
59
60 CanvasKit.SkMatrix.identity = function() {
Nathaniel Nifong77798b42020-02-21 17:15:22 -050061 return identityN(3);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050062 };
63
64 // Return the inverse (if it exists) of this matrix.
Kevin Lubick9b56cea2020-04-06 08:16:18 -040065 // Otherwise, return null.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050066 CanvasKit.SkMatrix.invert = function(m) {
Nathaniel Nifong77798b42020-02-21 17:15:22 -050067 // Find the determinant by the sarrus rule. https://en.wikipedia.org/wiki/Rule_of_Sarrus
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050068 var det = m[0]*m[4]*m[8] + m[1]*m[5]*m[6] + m[2]*m[3]*m[7]
69 - m[2]*m[4]*m[6] - m[1]*m[3]*m[8] - m[0]*m[5]*m[7];
70 if (!det) {
71 SkDebug('Warning, uninvertible matrix');
Nathaniel Nifong77798b42020-02-21 17:15:22 -050072 return null;
Kevin Lubick1a05fce2018-11-20 12:51:16 -050073 }
Nathaniel Nifong77798b42020-02-21 17:15:22 -050074 // Return the inverse by the formula adj(m)/det.
75 // adj (adjugate) of a 3x3 is the transpose of it's cofactor matrix.
76 // a cofactor matrix is a matrix where each term is +-det(N) where matrix N is the 2x2 formed
77 // by removing the row and column we're currently setting from the source.
78 // the sign alternates in a checkerboard pattern with a `+` at the top left.
79 // that's all been combined here into one expression.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050080 return [
81 (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,
82 (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,
83 (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,
84 ];
85 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -050086
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050087 // Maps the given points according to the passed in matrix.
88 // Results are done in place.
89 // See SkMatrix.h::mapPoints for the docs on the math.
90 CanvasKit.SkMatrix.mapPoints = function(matrix, ptArr) {
Nathaniel Nifong77798b42020-02-21 17:15:22 -050091 if (skIsDebug && (ptArr.length % 2)) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050092 throw 'mapPoints requires an even length arr';
Kevin Lubickb9db3902018-11-26 11:47:54 -050093 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050094 for (var i = 0; i < ptArr.length; i+=2) {
95 var x = ptArr[i], y = ptArr[i+1];
96 // Gx+Hy+I
97 var denom = matrix[6]*x + matrix[7]*y + matrix[8];
98 // Ax+By+C
99 var xTrans = matrix[0]*x + matrix[1]*y + matrix[2];
100 // Dx+Ey+F
101 var yTrans = matrix[3]*x + matrix[4]*y + matrix[5];
102 ptArr[i] = xTrans/denom;
103 ptArr[i+1] = yTrans/denom;
104 }
105 return ptArr;
106 };
Kevin Lubickb9db3902018-11-26 11:47:54 -0500107
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500108 function isnumber(val) { return val !== NaN; };
109
Kevin Lubickc89ca0b2020-04-02 14:30:00 -0400110 // generalized iterative algorithm for multiplying two matrices.
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500111 function multiply(m1, m2, size) {
112
113 if (skIsDebug && (!m1.every(isnumber) || !m2.every(isnumber))) {
114 throw 'Some members of matrices are NaN m1='+m1+', m2='+m2+'';
115 }
116 if (skIsDebug && (m1.length !== m2.length)) {
117 throw 'Undefined for matrices of different sizes. m1.length='+m1.length+', m2.length='+m2.length;
118 }
119 if (skIsDebug && (size*size !== m1.length)) {
120 throw 'Undefined for non-square matrices. array size was '+size;
121 }
122
123 var result = Array(m1.length);
124 for (var r = 0; r < size; r++) {
125 for (var c = 0; c < size; c++) {
126 // accumulate a sum of m1[r,k]*m2[k, c]
127 var acc = 0;
128 for (var k = 0; k < size; k++) {
129 acc += m1[size * r + k] * m2[size * k + c];
130 }
131 result[r * size + c] = acc;
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500132 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500133 }
134 return result;
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500135 };
136
137 // Accept an integer indicating the size of the matrices being multiplied (3 for 3x3), and any
138 // number of matrices following it.
139 function multiplyMany(size, listOfMatrices) {
140 if (skIsDebug && (listOfMatrices.length < 2)) {
141 throw 'multiplication expected two or more matrices';
142 }
143 var result = multiply(listOfMatrices[0], listOfMatrices[1], size);
144 var next = 2;
145 while (next < listOfMatrices.length) {
146 result = multiply(result, listOfMatrices[next], size);
147 next++;
148 }
149 return result;
150 };
151
152 // Accept any number 3x3 of matrices as arguments, multiply them together.
Kevin Lubick9e2d3842020-04-01 13:42:15 -0400153 // Matrix multiplication is associative but not commutative. the order of the arguments
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500154 // matters, but it does not matter that this implementation multiplies them left to right.
155 CanvasKit.SkMatrix.multiply = function() {
156 return multiplyMany(3, arguments);
157 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500158
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500159 // Return a matrix representing a rotation by n radians.
160 // px, py optionally say which point the rotation should be around
161 // with the default being (0, 0);
162 CanvasKit.SkMatrix.rotated = function(radians, px, py) {
163 px = px || 0;
164 py = py || 0;
165 var sinV = Math.sin(radians);
166 var cosV = Math.cos(radians);
167 return [
168 cosV, -sinV, sdot( sinV, py, 1 - cosV, px),
169 sinV, cosV, sdot(-sinV, px, 1 - cosV, py),
170 0, 0, 1,
171 ];
172 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400173
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500174 CanvasKit.SkMatrix.scaled = function(sx, sy, px, py) {
175 px = px || 0;
176 py = py || 0;
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500177 var m = stride([sx, sy], identityN(3), 3, 0, 1);
178 return stride([px-sx*px, py-sy*py], m, 3, 2, 0);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500179 };
Kevin Lubickda3d8ac2019-01-07 11:08:55 -0500180
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500181 CanvasKit.SkMatrix.skewed = function(kx, ky, px, py) {
182 px = px || 0;
183 py = py || 0;
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500184 var m = stride([kx, ky], identityN(3), 3, 1, -1);
185 return stride([-kx*px, -ky*py], m, 3, 2, 0);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500186 };
Alexander Khovansky3e119332018-11-15 02:01:19 +0300187
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500188 CanvasKit.SkMatrix.translated = function(dx, dy) {
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500189 return stride(arguments, identityN(3), 3, 2, 0);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500190 };
Kevin Lubick1646e7d2018-12-07 13:03:08 -0500191
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500192 // Functions for manipulating vectors.
193 // Loosely based off of SkV3 in SkM44.h but skia also has SkVec2 and Skv4. This combines them and
194 // works on vectors of any length.
195 CanvasKit.SkVector = {};
196 CanvasKit.SkVector.dot = function(a, b) {
197 if (skIsDebug && (a.length !== b.length)) {
198 throw 'Cannot perform dot product on arrays of different length ('+a.length+' vs '+b.length+')';
199 }
200 return a.map(function(v, i) { return v*b[i] }).reduce(function(acc, cur) { return acc + cur; });
201 }
202 CanvasKit.SkVector.lengthSquared = function(v) {
203 return CanvasKit.SkVector.dot(v, v);
204 }
205 CanvasKit.SkVector.length = function(v) {
206 return Math.sqrt(CanvasKit.SkVector.lengthSquared(v));
207 }
208 CanvasKit.SkVector.mulScalar = function(v, s) {
209 return v.map(function(i) { return i*s });
210 }
211 CanvasKit.SkVector.add = function(a, b) {
212 return a.map(function(v, i) { return v+b[i] });
213 }
214 CanvasKit.SkVector.sub = function(a, b) {
215 return a.map(function(v, i) { return v-b[i]; });
216 }
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500217 CanvasKit.SkVector.dist = function(a, b) {
218 return CanvasKit.SkVector.length(CanvasKit.SkVector.sub(a, b));
219 }
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500220 CanvasKit.SkVector.normalize = function(v) {
221 return CanvasKit.SkVector.mulScalar(v, 1/CanvasKit.SkVector.length(v));
222 }
223 CanvasKit.SkVector.cross = function(a, b) {
224 if (skIsDebug && (a.length !== 3 || a.length !== 3)) {
225 throw 'Cross product is only defined for 3-dimensional vectors (a.length='+a.length+', b.length='+b.length+')';
226 }
227 return [
228 a[1]*b[2] - a[2]*b[1],
229 a[2]*b[0] - a[0]*b[2],
230 a[0]*b[1] - a[1]*b[0],
231 ];
232 }
233
Kevin Lubickc1d08982020-04-06 13:52:15 -0400234 // Functions for creating and manipulating (row-major) 4x4 matrices. Accepted in place of
235 // SkM44 in canvas methods, for the same reasons as the 3x3 matrices above.
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500236 // ported from C++ code in SkM44.cpp
237 CanvasKit.SkM44 = {};
238 // Create a 4x4 identity matrix
239 CanvasKit.SkM44.identity = function() {
240 return identityN(4);
241 }
242
243 // Anything named vec below is an array of length 3 representing a vector/point in 3D space.
244 // Create a 4x4 matrix representing a translate by the provided 3-vec
245 CanvasKit.SkM44.translated = function(vec) {
246 return stride(vec, identityN(4), 4, 3, 0);
247 }
248 // Create a 4x4 matrix representing a scaling by the provided 3-vec
249 CanvasKit.SkM44.scaled = function(vec) {
250 return stride(vec, identityN(4), 4, 0, 1);
251 }
252 // Create a 4x4 matrix representing a rotation about the provided axis 3-vec.
253 // axis does not need to be normalized.
254 CanvasKit.SkM44.rotated = function(axisVec, radians) {
255 return CanvasKit.SkM44.rotatedUnitSinCos(
256 CanvasKit.SkVector.normalize(axisVec), Math.sin(radians), Math.cos(radians));
257 }
258 // Create a 4x4 matrix representing a rotation about the provided normalized axis 3-vec.
259 // Rotation is provided redundantly as both sin and cos values.
260 // This rotate can be used when you already have the cosAngle and sinAngle values
261 // so you don't have to atan(cos/sin) to call roatated() which expects an angle in radians.
262 // this does no checking! Behavior for invalid sin or cos values or non-normalized axis vectors
263 // is incorrect. Prefer rotate().
264 CanvasKit.SkM44.rotatedUnitSinCos = function(axisVec, sinAngle, cosAngle) {
265 var x = axisVec[0];
266 var y = axisVec[1];
267 var z = axisVec[2];
268 var c = cosAngle;
269 var s = sinAngle;
270 var t = 1 - c;
271 return [
272 t*x*x + c, t*x*y - s*z, t*x*z + s*y, 0,
273 t*x*y + s*z, t*y*y + c, t*y*z - s*x, 0,
274 t*x*z - s*y, t*y*z + s*x, t*z*z + c, 0,
275 0, 0, 0, 1
276 ];
277 }
278 // Create a 4x4 matrix representing a camera at eyeVec, pointed at centerVec.
279 CanvasKit.SkM44.lookat = function(eyeVec, centerVec, upVec) {
280 var f = CanvasKit.SkVector.normalize(CanvasKit.SkVector.sub(centerVec, eyeVec));
281 var u = CanvasKit.SkVector.normalize(upVec);
282 var s = CanvasKit.SkVector.normalize(CanvasKit.SkVector.cross(f, u));
283
284 var m = CanvasKit.SkM44.identity();
285 // set each column's top three numbers
Kevin Lubickc1d08982020-04-06 13:52:15 -0400286 stride(s, m, 4, 0, 0);
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500287 stride(CanvasKit.SkVector.cross(s, f), m, 4, 1, 0);
288 stride(CanvasKit.SkVector.mulScalar(f, -1), m, 4, 2, 0);
Kevin Lubickc1d08982020-04-06 13:52:15 -0400289 stride(eyeVec, m, 4, 3, 0);
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500290
291 var m2 = CanvasKit.SkM44.invert(m);
292 if (m2 === null) {
293 return CanvasKit.SkM44.identity();
294 }
295 return m2;
296 }
297 // Create a 4x4 matrix representing a perspective. All arguments are scalars.
298 // angle is in radians.
299 CanvasKit.SkM44.perspective = function(near, far, angle) {
300 if (skIsDebug && (far <= near)) {
301 throw "far must be greater than near when constructing SkM44 using perspective.";
302 }
303 var dInv = 1 / (far - near);
304 var halfAngle = angle / 2;
305 var cot = Math.cos(halfAngle) / Math.sin(halfAngle);
306 return [
307 cot, 0, 0, 0,
308 0, cot, 0, 0,
309 0, 0, (far+near)*dInv, 2*far*near*dInv,
310 0, 0, -1, 1,
311 ];
312 }
313 // Returns the number at the given row and column in matrix m.
314 CanvasKit.SkM44.rc = function(m, r, c) {
315 return m[r*4+c];
316 }
317 // Accepts any number of 4x4 matrix arguments, multiplies them left to right.
318 CanvasKit.SkM44.multiply = function() {
319 return multiplyMany(4, arguments);
320 }
321
322 // Invert the 4x4 matrix if it is invertible and return it. if not, return null.
323 // taken from SkM44.cpp (altered to use row-major order)
324 // m is not altered.
325 CanvasKit.SkM44.invert = function(m) {
326 if (skIsDebug && !m.every(isnumber)) {
327 throw 'some members of matrix are NaN m='+m;
328 }
329
330 var a00 = m[0];
331 var a01 = m[4];
332 var a02 = m[8];
333 var a03 = m[12];
334 var a10 = m[1];
335 var a11 = m[5];
336 var a12 = m[9];
337 var a13 = m[13];
338 var a20 = m[2];
339 var a21 = m[6];
340 var a22 = m[10];
341 var a23 = m[14];
342 var a30 = m[3];
343 var a31 = m[7];
344 var a32 = m[11];
345 var a33 = m[15];
346
347 var b00 = a00 * a11 - a01 * a10;
348 var b01 = a00 * a12 - a02 * a10;
349 var b02 = a00 * a13 - a03 * a10;
350 var b03 = a01 * a12 - a02 * a11;
351 var b04 = a01 * a13 - a03 * a11;
352 var b05 = a02 * a13 - a03 * a12;
353 var b06 = a20 * a31 - a21 * a30;
354 var b07 = a20 * a32 - a22 * a30;
355 var b08 = a20 * a33 - a23 * a30;
356 var b09 = a21 * a32 - a22 * a31;
357 var b10 = a21 * a33 - a23 * a31;
358 var b11 = a22 * a33 - a23 * a32;
359
360 // calculate determinate
361 var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
362 var invdet = 1.0 / det;
363
364 // bail out if the matrix is not invertible
365 if (det === 0 || invdet === Infinity) {
366 SkDebug('Warning, uninvertible matrix');
367 return null;
368 }
369
370 b00 *= invdet;
371 b01 *= invdet;
372 b02 *= invdet;
373 b03 *= invdet;
374 b04 *= invdet;
375 b05 *= invdet;
376 b06 *= invdet;
377 b07 *= invdet;
378 b08 *= invdet;
379 b09 *= invdet;
380 b10 *= invdet;
381 b11 *= invdet;
382
383 // store result in row major order
384 var tmp = [
385 a11 * b11 - a12 * b10 + a13 * b09,
386 a12 * b08 - a10 * b11 - a13 * b07,
387 a10 * b10 - a11 * b08 + a13 * b06,
388 a11 * b07 - a10 * b09 - a12 * b06,
389
390 a02 * b10 - a01 * b11 - a03 * b09,
391 a00 * b11 - a02 * b08 + a03 * b07,
392 a01 * b08 - a00 * b10 - a03 * b06,
393 a00 * b09 - a01 * b07 + a02 * b06,
394
395 a31 * b05 - a32 * b04 + a33 * b03,
396 a32 * b02 - a30 * b05 - a33 * b01,
397 a30 * b04 - a31 * b02 + a33 * b00,
398 a31 * b01 - a30 * b03 - a32 * b00,
399
400 a22 * b04 - a21 * b05 - a23 * b03,
401 a20 * b05 - a22 * b02 + a23 * b01,
402 a21 * b02 - a20 * b04 - a23 * b00,
403 a20 * b03 - a21 * b01 + a22 * b00,
404 ];
405
406
407 if (!tmp.every(function(val) { return val !== NaN && val !== Infinity && val !== -Infinity; })) {
408 SkDebug('inverted matrix contains infinities or NaN '+tmp);
409 return null;
410 }
411 return tmp;
412 }
413
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500414 CanvasKit.SkM44.transpose = function(m) {
415 return [
416 m[0], m[4], m[8], m[12],
417 m[1], m[5], m[9], m[13],
418 m[2], m[6], m[10], m[14],
419 m[3], m[7], m[11], m[15],
420 ];
421 }
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500422
Kevin Lubickd3729342019-09-12 11:11:25 -0400423 // An SkColorMatrix is a 4x4 color matrix that transforms the 4 color channels
424 // with a 1x4 matrix that post-translates those 4 channels.
425 // For example, the following is the layout with the scale (S) and post-transform
426 // (PT) items indicated.
427 // RS, 0, 0, 0 | RPT
428 // 0, GS, 0, 0 | GPT
429 // 0, 0, BS, 0 | BPT
430 // 0, 0, 0, AS | APT
431 //
432 // Much of this was hand-transcribed from SkColorMatrix.cpp, because it's easier to
433 // deal with a Float32Array of length 20 than to try to expose the SkColorMatrix object.
434
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500435 var rScale = 0;
436 var gScale = 6;
437 var bScale = 12;
438 var aScale = 18;
439
Kevin Lubickd3729342019-09-12 11:11:25 -0400440 var rPostTrans = 4;
441 var gPostTrans = 9;
442 var bPostTrans = 14;
443 var aPostTrans = 19;
444
445 CanvasKit.SkColorMatrix = {};
446 CanvasKit.SkColorMatrix.identity = function() {
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500447 var m = new Float32Array(20);
448 m[rScale] = 1;
449 m[gScale] = 1;
450 m[bScale] = 1;
451 m[aScale] = 1;
452 return m;
Kevin Lubickd3729342019-09-12 11:11:25 -0400453 }
454
455 CanvasKit.SkColorMatrix.scaled = function(rs, gs, bs, as) {
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500456 var m = new Float32Array(20);
457 m[rScale] = rs;
458 m[gScale] = gs;
459 m[bScale] = bs;
460 m[aScale] = as;
461 return m;
Kevin Lubickd3729342019-09-12 11:11:25 -0400462 }
463
464 var rotateIndices = [
465 [6, 7, 11, 12],
466 [0, 10, 2, 12],
467 [0, 1, 5, 6],
468 ];
469 // axis should be 0, 1, 2 for r, g, b
470 CanvasKit.SkColorMatrix.rotated = function(axis, sine, cosine) {
471 var m = CanvasKit.SkColorMatrix.identity();
472 var indices = rotateIndices[axis];
473 m[indices[0]] = cosine;
474 m[indices[1]] = sine;
475 m[indices[2]] = -sine;
476 m[indices[3]] = cosine;
477 return m;
478 }
479
480 // m is a SkColorMatrix (i.e. a Float32Array), and this sets the 4 "special"
481 // params that will translate the colors after they are multiplied by the 4x4 matrix.
482 CanvasKit.SkColorMatrix.postTranslate = function(m, dr, dg, db, da) {
483 m[rPostTrans] += dr;
484 m[gPostTrans] += dg;
485 m[bPostTrans] += db;
486 m[aPostTrans] += da;
487 return m;
488 }
489
490 // concat returns a new SkColorMatrix that is the result of multiplying outer*inner;
491 CanvasKit.SkColorMatrix.concat = function(outer, inner) {
492 var m = new Float32Array(20);
493 var index = 0;
494 for (var j = 0; j < 20; j += 5) {
495 for (var i = 0; i < 4; i++) {
496 m[index++] = outer[j + 0] * inner[i + 0] +
497 outer[j + 1] * inner[i + 5] +
498 outer[j + 2] * inner[i + 10] +
499 outer[j + 3] * inner[i + 15];
500 }
501 m[index++] = outer[j + 0] * inner[4] +
502 outer[j + 1] * inner[9] +
503 outer[j + 2] * inner[14] +
504 outer[j + 3] * inner[19] +
505 outer[j + 4];
506 }
507
508 return m;
509 }
510
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500511 CanvasKit.SkPath.prototype.addArc = function(oval, startAngle, sweepAngle) {
512 // see arc() for the HTMLCanvas version
513 // note input angles are degrees.
514 this._addArc(oval, startAngle, sweepAngle);
515 return this;
516 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400517
Kevin Lubicke384df42019-08-26 15:48:09 -0400518 CanvasKit.SkPath.prototype.addOval = function(oval, isCCW, startIndex) {
519 if (startIndex === undefined) {
520 startIndex = 1;
521 }
522 this._addOval(oval, !!isCCW, startIndex);
523 return this;
524 };
525
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500526 CanvasKit.SkPath.prototype.addPath = function() {
527 // Takes 1, 2, 7, or 10 required args, where the first arg is always the path.
528 // The last arg is optional and chooses between add or extend mode.
529 // The options for the remaining args are:
530 // - an array of 6 or 9 parameters (perspective is optional)
531 // - the 9 parameters of a full matrix or
532 // the 6 non-perspective params of a matrix.
533 var args = Array.prototype.slice.call(arguments);
534 var path = args[0];
535 var extend = false;
536 if (typeof args[args.length-1] === "boolean") {
537 extend = args.pop();
538 }
539 if (args.length === 1) {
540 // Add path, unchanged. Use identity matrix
541 this._addPath(path, 1, 0, 0,
542 0, 1, 0,
543 0, 0, 1,
544 extend);
545 } else if (args.length === 2) {
546 // User provided the 9 params of a full matrix as an array.
547 var a = args[1];
548 this._addPath(path, a[0], a[1], a[2],
549 a[3], a[4], a[5],
550 a[6] || 0, a[7] || 0, a[8] || 1,
551 extend);
552 } else if (args.length === 7 || args.length === 10) {
553 // User provided the 9 params of a (full) matrix directly.
554 // (or just the 6 non perspective ones)
555 // These are in the same order as what Skia expects.
556 var a = args;
557 this._addPath(path, a[1], a[2], a[3],
558 a[4], a[5], a[6],
559 a[7] || 0, a[8] || 0, a[9] || 1,
560 extend);
561 } else {
562 SkDebug('addPath expected to take 1, 2, 7, or 10 required args. Got ' + args.length);
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400563 return null;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500564 }
565 return this;
566 };
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400567
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500568 // points is either an array of [x, y] where x and y are numbers or
569 // a typed array from Malloc where the even indices will be treated
570 // as x coordinates and the odd indices will be treated as y coordinates.
571 CanvasKit.SkPath.prototype.addPoly = function(points, close) {
572 var ptr;
573 var n;
574 // This was created with CanvasKit.Malloc, so assume the user has
575 // already been filled with data.
576 if (points['_ck']) {
577 ptr = points.byteOffset;
578 n = points.length/2;
579 } else {
580 ptr = copy2dArray(points, CanvasKit.HEAPF32);
581 n = points.length;
582 }
583 this._addPoly(ptr, n, close);
584 CanvasKit._free(ptr);
585 return this;
586 };
587
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500588 CanvasKit.SkPath.prototype.addRect = function() {
589 // Takes 1, 2, 4 or 5 args
590 // - SkRect
591 // - SkRect, isCCW
592 // - left, top, right, bottom
593 // - left, top, right, bottom, isCCW
594 if (arguments.length === 1 || arguments.length === 2) {
595 var r = arguments[0];
596 var ccw = arguments[1] || false;
597 this._addRect(r.fLeft, r.fTop, r.fRight, r.fBottom, ccw);
598 } else if (arguments.length === 4 || arguments.length === 5) {
599 var a = arguments;
600 this._addRect(a[0], a[1], a[2], a[3], a[4] || false);
601 } else {
602 SkDebug('addRect expected to take 1, 2, 4, or 5 args. Got ' + arguments.length);
Kevin Lubick217056c2018-09-20 17:39:31 -0400603 return null;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500604 }
605 return this;
606 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400607
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500608 CanvasKit.SkPath.prototype.addRoundRect = function() {
609 // Takes 3, 4, 6 or 7 args
610 // - SkRect, radii, ccw
611 // - SkRect, rx, ry, ccw
612 // - left, top, right, bottom, radii, ccw
613 // - left, top, right, bottom, rx, ry, ccw
614 var args = arguments;
615 if (args.length === 3 || args.length === 6) {
616 var radii = args[args.length-2];
617 } else if (args.length === 6 || args.length === 7){
618 // duplicate the given (rx, ry) pairs for each corner.
619 var rx = args[args.length-3];
620 var ry = args[args.length-2];
621 var radii = [rx, ry, rx, ry, rx, ry, rx, ry];
622 } else {
623 SkDebug('addRoundRect expected to take 3, 4, 6, or 7 args. Got ' + args.length);
624 return null;
625 }
626 if (radii.length !== 8) {
627 SkDebug('addRoundRect needs 8 radii provided. Got ' + radii.length);
628 return null;
629 }
630 var rptr = copy1dArray(radii, CanvasKit.HEAPF32);
631 if (args.length === 3 || args.length === 4) {
632 var r = args[0];
633 var ccw = args[args.length - 1];
634 this._addRoundRect(r.fLeft, r.fTop, r.fRight, r.fBottom, rptr, ccw);
635 } else if (args.length === 6 || args.length === 7) {
636 var a = args;
637 this._addRoundRect(a[0], a[1], a[2], a[3], rptr, ccw);
638 }
639 CanvasKit._free(rptr);
640 return this;
641 };
642
643 CanvasKit.SkPath.prototype.arc = function(x, y, radius, startAngle, endAngle, ccw) {
644 // emulates the HTMLCanvas behavior. See addArc() for the SkPath version.
645 // Note input angles are radians.
646 var bounds = CanvasKit.LTRBRect(x-radius, y-radius, x+radius, y+radius);
647 var sweep = radiansToDegrees(endAngle - startAngle) - (360 * !!ccw);
648 var temp = new CanvasKit.SkPath();
649 temp.addArc(bounds, radiansToDegrees(startAngle), sweep);
650 this.addPath(temp, true);
651 temp.delete();
652 return this;
653 };
654
655 CanvasKit.SkPath.prototype.arcTo = function() {
656 // takes 4, 5 or 7 args
657 // - 5 x1, y1, x2, y2, radius
658 // - 4 oval (as Rect), startAngle, sweepAngle, forceMoveTo
Kevin Lubicke384df42019-08-26 15:48:09 -0400659 // - 7 rx, ry, xAxisRotate, useSmallArc, isCCW, x, y
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500660 var args = arguments;
661 if (args.length === 5) {
662 this._arcTo(args[0], args[1], args[2], args[3], args[4]);
663 } else if (args.length === 4) {
664 this._arcTo(args[0], args[1], args[2], args[3]);
665 } else if (args.length === 7) {
Kevin Lubicke384df42019-08-26 15:48:09 -0400666 this._arcTo(args[0], args[1], args[2], !!args[3], !!args[4], args[5], args[6]);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500667 } else {
668 throw 'Invalid args for arcTo. Expected 4, 5, or 7, got '+ args.length;
669 }
670
671 return this;
672 };
673
674 CanvasKit.SkPath.prototype.close = function() {
675 this._close();
676 return this;
677 };
678
679 CanvasKit.SkPath.prototype.conicTo = function(x1, y1, x2, y2, w) {
680 this._conicTo(x1, y1, x2, y2, w);
681 return this;
682 };
683
684 CanvasKit.SkPath.prototype.cubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
685 this._cubicTo(cp1x, cp1y, cp2x, cp2y, x, y);
686 return this;
687 };
688
689 CanvasKit.SkPath.prototype.dash = function(on, off, phase) {
690 if (this._dash(on, off, phase)) {
Kevin Lubick217056c2018-09-20 17:39:31 -0400691 return this;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500692 }
693 return null;
694 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400695
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500696 CanvasKit.SkPath.prototype.lineTo = function(x, y) {
697 this._lineTo(x, y);
698 return this;
699 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400700
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500701 CanvasKit.SkPath.prototype.moveTo = function(x, y) {
702 this._moveTo(x, y);
703 return this;
704 };
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400705
Kevin Lubicke384df42019-08-26 15:48:09 -0400706 CanvasKit.SkPath.prototype.offset = function(dx, dy) {
707 this._transform(1, 0, dx,
708 0, 1, dy,
709 0, 0, 1);
710 return this;
711 };
712
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500713 CanvasKit.SkPath.prototype.quadTo = function(cpx, cpy, x, y) {
714 this._quadTo(cpx, cpy, x, y);
715 return this;
716 };
717
Kevin Lubick79b71342019-11-01 14:36:52 -0400718 CanvasKit.SkPath.prototype.rArcTo = function(rx, ry, xAxisRotate, useSmallArc, isCCW, dx, dy) {
719 this._rArcTo(rx, ry, xAxisRotate, useSmallArc, isCCW, dx, dy);
720 return this;
721 };
722
723 CanvasKit.SkPath.prototype.rConicTo = function(dx1, dy1, dx2, dy2, w) {
724 this._rConicTo(dx1, dy1, dx2, dy2, w);
725 return this;
726 };
727
728 // These params are all relative
729 CanvasKit.SkPath.prototype.rCubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
730 this._rCubicTo(cp1x, cp1y, cp2x, cp2y, x, y);
731 return this;
732 };
733
734 CanvasKit.SkPath.prototype.rLineTo = function(dx, dy) {
735 this._rLineTo(dx, dy);
736 return this;
737 };
738
739 CanvasKit.SkPath.prototype.rMoveTo = function(dx, dy) {
740 this._rMoveTo(dx, dy);
741 return this;
742 };
743
744 // These params are all relative
745 CanvasKit.SkPath.prototype.rQuadTo = function(cpx, cpy, x, y) {
746 this._rQuadTo(cpx, cpy, x, y);
747 return this;
748 };
749
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500750 CanvasKit.SkPath.prototype.stroke = function(opts) {
751 // Fill out any missing values with the default values.
752 /**
753 * See externs.js for this definition
754 * @type {StrokeOpts}
755 */
756 opts = opts || {};
757 opts.width = opts.width || 1;
758 opts.miter_limit = opts.miter_limit || 4;
759 opts.cap = opts.cap || CanvasKit.StrokeCap.Butt;
760 opts.join = opts.join || CanvasKit.StrokeJoin.Miter;
761 opts.precision = opts.precision || 1;
762 if (this._stroke(opts)) {
763 return this;
764 }
765 return null;
766 };
767
768 CanvasKit.SkPath.prototype.transform = function() {
769 // Takes 1 or 9 args
770 if (arguments.length === 1) {
771 // argument 1 should be a 6 or 9 element array.
772 var a = arguments[0];
773 this._transform(a[0], a[1], a[2],
774 a[3], a[4], a[5],
775 a[6] || 0, a[7] || 0, a[8] || 1);
776 } else if (arguments.length === 6 || arguments.length === 9) {
777 // these arguments are the 6 or 9 members of the matrix
778 var a = arguments;
779 this._transform(a[0], a[1], a[2],
780 a[3], a[4], a[5],
781 a[6] || 0, a[7] || 0, a[8] || 1);
782 } else {
783 throw 'transform expected to take 1 or 9 arguments. Got ' + arguments.length;
784 }
785 return this;
786 };
787 // isComplement is optional, defaults to false
788 CanvasKit.SkPath.prototype.trim = function(startT, stopT, isComplement) {
789 if (this._trim(startT, stopT, !!isComplement)) {
790 return this;
791 }
792 return null;
793 };
794
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500795 CanvasKit.SkImage.prototype.encodeToData = function() {
796 if (!arguments.length) {
797 return this._encodeToData();
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400798 }
Kevin Lubick53965c92018-10-11 08:51:55 -0400799
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500800 if (arguments.length === 2) {
801 var a = arguments;
802 return this._encodeToDataWithFormat(a[0], a[1]);
Alexander Khovansky3e119332018-11-15 02:01:19 +0300803 }
804
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500805 throw 'encodeToData expected to take 0 or 2 arguments. Got ' + arguments.length;
806 }
Kevin Lubick1ba9c4d2019-02-22 10:04:06 -0500807
Kevin Lubicka064c282019-04-04 09:28:53 -0400808 CanvasKit.SkImage.prototype.makeShader = function(xTileMode, yTileMode, localMatrix) {
Kevin Lubick6bffe392020-04-02 15:24:15 -0400809 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
810 var shader = this._makeShader(xTileMode, yTileMode, localMatrixPtr);
Kevin Lubickc1d08982020-04-06 13:52:15 -0400811 CanvasKit._free(localMatrixPtr);
Kevin Lubick6bffe392020-04-02 15:24:15 -0400812 return shader;
Kevin Lubicka064c282019-04-04 09:28:53 -0400813 }
814
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400815 CanvasKit.SkImage.prototype.readPixels = function(imageInfo, srcX, srcY) {
816 var rowBytes;
Kevin Lubick319524b2020-01-22 15:29:14 -0500817 // Important to use ["string"] notation here, otherwise the closure compiler will
818 // minify away the colorType.
819 switch (imageInfo["colorType"]) {
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400820 case CanvasKit.ColorType.RGBA_8888:
821 rowBytes = imageInfo.width * 4; // 1 byte per channel == 4 bytes per pixel in 8888
822 break;
823 case CanvasKit.ColorType.RGBA_F32:
824 rowBytes = imageInfo.width * 16; // 4 bytes per channel == 16 bytes per pixel in F32
825 break;
826 default:
827 SkDebug("Colortype not yet supported");
828 return;
829 }
830 var pBytes = rowBytes * imageInfo.height;
831 var pPtr = CanvasKit._malloc(pBytes);
832
833 if (!this._readPixels(imageInfo, pPtr, rowBytes, srcX, srcY)) {
834 SkDebug("Could not read pixels with the given inputs");
835 return null;
836 }
837
838 // Put those pixels into a typed array of the right format and then
839 // make a copy with slice() that we can return.
840 var retVal = null;
Kevin Lubick319524b2020-01-22 15:29:14 -0500841 switch (imageInfo["colorType"]) {
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400842 case CanvasKit.ColorType.RGBA_8888:
Bryce Thomas1fa54042020-01-14 13:46:30 -0800843 retVal = new Uint8Array(CanvasKit.HEAPU8.buffer, pPtr, pBytes).slice();
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400844 break;
845 case CanvasKit.ColorType.RGBA_F32:
Bryce Thomas1fa54042020-01-14 13:46:30 -0800846 retVal = new Float32Array(CanvasKit.HEAPU8.buffer, pPtr, pBytes).slice();
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400847 break;
848 }
849
850 // Free the allocated pixels in the WASM memory
851 CanvasKit._free(pPtr);
852 return retVal;
Kevin Lubick6bffe392020-04-02 15:24:15 -0400853 }
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400854
Kevin Lubickc1d08982020-04-06 13:52:15 -0400855 // concat takes a 3x2, a 3x3, or a 4x4 matrix and upscales it (if needed) to 4x4. This is because
856 // under the hood, SkCanvas uses a 4x4 matrix.
Kevin Lubick6bffe392020-04-02 15:24:15 -0400857 CanvasKit.SkCanvas.prototype.concat = function(matr) {
Kevin Lubickc1d08982020-04-06 13:52:15 -0400858 var matrPtr = copy4x4MatrixToWasm(matr);
Kevin Lubick6bffe392020-04-02 15:24:15 -0400859 this._concat(matrPtr);
Kevin Lubickc1d08982020-04-06 13:52:15 -0400860 CanvasKit._free(matrPtr);
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400861 }
862
Kevin Lubickc1d08982020-04-06 13:52:15 -0400863 // Deprecated - just use concat
864 CanvasKit.SkCanvas.prototype.concat44 = CanvasKit.SkCanvas.prototype.concat;
865
Kevin Lubickee91c072019-03-29 10:39:52 -0400866 // atlas is an SkImage, e.g. from CanvasKit.MakeImageFromEncoded
867 // srcRects and dstXforms should be CanvasKit.SkRectBuilder and CanvasKit.RSXFormBuilder
868 // or just arrays of floats in groups of 4.
Kevin Lubick6bffe392020-04-02 15:24:15 -0400869 // colors, if provided, should be a CanvasKit.SkColorBuilder or array of CanvasKit.SimpleColor4f
Kevin Lubickee91c072019-03-29 10:39:52 -0400870 CanvasKit.SkCanvas.prototype.drawAtlas = function(atlas, srcRects, dstXforms, paint,
871 /*optional*/ blendMode, colors) {
872 if (!atlas || !paint || !srcRects || !dstXforms) {
873 SkDebug('Doing nothing since missing a required input');
874 return;
875 }
876 if (srcRects.length !== dstXforms.length || (colors && colors.length !== dstXforms.length)) {
877 SkDebug('Doing nothing since input arrays length mismatches');
Nathaniel Nifonge5d32542020-03-26 09:27:48 -0400878 return;
Kevin Lubickee91c072019-03-29 10:39:52 -0400879 }
880 if (!blendMode) {
881 blendMode = CanvasKit.BlendMode.SrcOver;
882 }
883
884 var srcRectPtr;
885 if (srcRects.build) {
886 srcRectPtr = srcRects.build();
887 } else {
888 srcRectPtr = copy1dArray(srcRects, CanvasKit.HEAPF32);
889 }
890
891 var dstXformPtr;
892 if (dstXforms.build) {
893 dstXformPtr = dstXforms.build();
894 } else {
895 dstXformPtr = copy1dArray(dstXforms, CanvasKit.HEAPF32);
896 }
897
Kevin Lubick6bffe392020-04-02 15:24:15 -0400898 var colorPtr = nullptr;
Kevin Lubickee91c072019-03-29 10:39:52 -0400899 if (colors) {
900 if (colors.build) {
901 colorPtr = colors.build();
902 } else {
Nathaniel Nifonge5d32542020-03-26 09:27:48 -0400903 if (!isCanvasKitColor(colors[0])) {
904 SkDebug('DrawAtlas color argument expected to be CanvasKit.SkRectBuilder or array of ' +
Kevin Lubick6bffe392020-04-02 15:24:15 -0400905 'CanvasKit.SimpleColor4f, but got '+colors);
Nathaniel Nifonge5d32542020-03-26 09:27:48 -0400906 return;
907 }
908 // convert here
909 colors = colors.map(toUint32Color);
Kevin Lubickee91c072019-03-29 10:39:52 -0400910 colorPtr = copy1dArray(colors, CanvasKit.HEAPU32);
911 }
912 }
913
914 this._drawAtlas(atlas, dstXformPtr, srcRectPtr, colorPtr, dstXforms.length,
915 blendMode, paint);
916
917 if (srcRectPtr && !srcRects.build) {
918 CanvasKit._free(srcRectPtr);
919 }
920 if (dstXformPtr && !dstXforms.build) {
921 CanvasKit._free(dstXformPtr);
922 }
923 if (colorPtr && !colors.build) {
924 CanvasKit._free(colorPtr);
925 }
926
927 }
928
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500929 // points is either an array of [x, y] where x and y are numbers or
930 // a typed array from Malloc where the even indices will be treated
931 // as x coordinates and the odd indices will be treated as y coordinates.
932 CanvasKit.SkCanvas.prototype.drawPoints = function(mode, points, paint) {
933 var ptr;
934 var n;
935 // This was created with CanvasKit.Malloc, so assume the user has
936 // already been filled with data.
937 if (points['_ck']) {
938 ptr = points.byteOffset;
939 n = points.length/2;
940 } else {
941 ptr = copy2dArray(points, CanvasKit.HEAPF32);
942 n = points.length;
943 }
944 this._drawPoints(mode, ptr, n, paint);
945 CanvasKit._free(ptr);
946 }
947
Kevin Lubickc1d08982020-04-06 13:52:15 -0400948 // getLocalToCamera returns a 4x4 matrix.
949 CanvasKit.SkCanvas.prototype.getLocalToCamera = function() {
950 var matrPtr = CanvasKit._malloc(16 * 4); // allocate space for the matrix
951 // _getLocalToCamera will copy the values into the pointer.
952 this._getLocalToCamera(matrPtr);
953 return copy4x4MatrixFromWasm(matrPtr);
954 }
955
956 // getLocalToDevice returns a 4x4 matrix.
957 CanvasKit.SkCanvas.prototype.getLocalToDevice = function() {
958 var matrPtr = CanvasKit._malloc(16 * 4); // allocate space for the matrix
959 // _getLocalToDevice will copy the values into the pointer.
960 this._getLocalToDevice(matrPtr);
961 return copy4x4MatrixFromWasm(matrPtr);
962 }
963
964 // getLocalToWorld returns a 4x4 matrix.
965 CanvasKit.SkCanvas.prototype.getLocalToWorld = function() {
966 var matrPtr = CanvasKit._malloc(16 * 4); // allocate space for the matrix
967 // _getLocalToWorld will copy the values into the pointer.
968 this._getLocalToWorld(matrPtr);
969 return copy4x4MatrixFromWasm(matrPtr);
970 }
971
972 // getTotalMatrix returns the current matrix as a 3x3 matrix.
Kevin Lubick6bffe392020-04-02 15:24:15 -0400973 CanvasKit.SkCanvas.prototype.getTotalMatrix = function() {
974 var matrPtr = CanvasKit._malloc(9 * 4); // allocate space for the matrix
975 // _getTotalMatrix will copy the values into the pointer.
976 this._getTotalMatrix(matrPtr);
977 // read them out into an array. TODO(kjlubick): If we change SkMatrix to be
978 // typedArrays, then we should return a typed array here too.
979 var rv = new Array(9);
980 for (var i = 0; i < 9; i++) {
981 rv[i] = CanvasKit.HEAPF32[matrPtr/4 + i]; // divide by 4 to "cast" to float.
982 }
983 CanvasKit._free(matrPtr);
984 return rv;
985 }
986
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500987 // returns Uint8Array
988 CanvasKit.SkCanvas.prototype.readPixels = function(x, y, w, h, alphaType,
989 colorType, dstRowBytes) {
990 // supply defaults (which are compatible with HTMLCanvas's getImageData)
991 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
992 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
993 dstRowBytes = dstRowBytes || (4 * w);
994
995 var len = h * dstRowBytes
996 var pptr = CanvasKit._malloc(len);
997 var ok = this._readPixels({
998 'width': w,
999 'height': h,
Kevin Lubick52b9f372018-12-04 13:57:36 -05001000 'colorType': colorType,
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001001 'alphaType': alphaType,
1002 }, pptr, dstRowBytes, x, y);
1003 if (!ok) {
1004 CanvasKit._free(pptr);
1005 return null;
1006 }
1007
1008 // The first typed array is just a view into memory. Because we will
1009 // be free-ing that, we call slice to make a persistent copy.
Bryce Thomas1fa54042020-01-14 13:46:30 -08001010 var pixels = new Uint8Array(CanvasKit.HEAPU8.buffer, pptr, len).slice();
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001011 CanvasKit._free(pptr);
1012 return pixels;
1013 }
1014
Kevin Lubickc1d08982020-04-06 13:52:15 -04001015 CanvasKit.SkCanvas.prototype.saveCamera = function(projection, camera) {
1016 var pPtr = copy4x4MatrixToWasm(projection);
1017 var cPtr = copy4x4MatrixToWasm(camera);
1018 this._saveCamera(pPtr, cPtr);
1019 CanvasKit._free(pPtr)
1020 CanvasKit._free(cPtr);
1021 }
1022
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001023 // pixels is a TypedArray. No matter the input size, it will be treated as
1024 // a Uint8Array (essentially, a byte array).
1025 CanvasKit.SkCanvas.prototype.writePixels = function(pixels, srcWidth, srcHeight,
1026 destX, destY, alphaType, colorType) {
1027 if (pixels.byteLength % (srcWidth * srcHeight)) {
1028 throw 'pixels length must be a multiple of the srcWidth * srcHeight';
1029 }
1030 var bytesPerPixel = pixels.byteLength / (srcWidth * srcHeight);
1031 // supply defaults (which are compatible with HTMLCanvas's putImageData)
1032 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
1033 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
1034 var srcRowBytes = bytesPerPixel * srcWidth;
1035
Kevin Lubick52b9f372018-12-04 13:57:36 -05001036 var pptr = CanvasKit._malloc(pixels.byteLength);
1037 CanvasKit.HEAPU8.set(pixels, pptr);
Kevin Lubick52b9f372018-12-04 13:57:36 -05001038
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001039 var ok = this._writePixels({
1040 'width': srcWidth,
1041 'height': srcHeight,
1042 'colorType': colorType,
1043 'alphaType': alphaType,
1044 }, pptr, srcRowBytes, destX, destY);
1045
1046 CanvasKit._free(pptr);
1047 return ok;
Kevin Lubick52b9f372018-12-04 13:57:36 -05001048 }
1049
Kevin Lubickd3729342019-09-12 11:11:25 -04001050 // colorMatrix is an SkColorMatrix (e.g. Float32Array of length 20)
1051 CanvasKit.SkColorFilter.MakeMatrix = function(colorMatrix) {
1052 if (!colorMatrix || colorMatrix.length !== 20) {
Kevin Lubick6bffe392020-04-02 15:24:15 -04001053 throw 'invalid color matrix';
Kevin Lubickd3729342019-09-12 11:11:25 -04001054 }
1055 var fptr = copy1dArray(colorMatrix, CanvasKit.HEAPF32);
1056 // We know skia memcopies the floats, so we can free our memory after the call returns.
1057 var m = CanvasKit.SkColorFilter._makeMatrix(fptr);
1058 CanvasKit._free(fptr);
1059 return m;
1060 }
1061
Kevin Lubick6bffe392020-04-02 15:24:15 -04001062 CanvasKit.SkImageFilter.MakeMatrixTransform = function(matr, filterQuality, input) {
1063 var matrPtr = copy3x3MatrixToWasm(matr);
1064 var imgF = CanvasKit.SkImageFilter._MakeMatrixTransform(matrPtr, filterQuality, input);
1065
Kevin Lubickc1d08982020-04-06 13:52:15 -04001066 CanvasKit._free(matrPtr);
Kevin Lubick6bffe392020-04-02 15:24:15 -04001067 return imgF;
1068 }
1069
Kevin Lubickcc13fd32019-04-05 13:00:01 -04001070 CanvasKit.SkSurface.prototype.captureFrameAsSkPicture = function(drawFrame) {
1071 // Set up SkPictureRecorder
1072 var spr = new CanvasKit.SkPictureRecorder();
1073 var canvas = spr.beginRecording(
1074 CanvasKit.LTRBRect(0, 0, this.width(), this.height()));
1075 drawFrame(canvas);
1076 var pic = spr.finishRecordingAsPicture();
1077 spr.delete();
1078 // TODO: do we need to clean up the memory for canvas?
1079 // If we delete it here, saveAsFile doesn't work correctly.
1080 return pic;
1081 }
1082
Kevin Lubick359a7e32019-03-19 09:34:37 -04001083 CanvasKit.SkSurface.prototype.requestAnimationFrame = function(callback, dirtyRect) {
1084 if (!this._cached_canvas) {
1085 this._cached_canvas = this.getCanvas();
1086 }
1087 window.requestAnimationFrame(function() {
Kevin Lubick39026282019-03-28 12:46:40 -04001088 if (this._context !== undefined) {
1089 CanvasKit.setCurrentContext(this._context);
1090 }
Kevin Lubick359a7e32019-03-19 09:34:37 -04001091
1092 callback(this._cached_canvas);
1093
Bryce Thomas2c5b8562020-01-22 13:49:41 -08001094 // We do not dispose() of the SkSurface here, as the client will typically
1095 // call requestAnimationFrame again from within the supplied callback.
1096 // For drawing a single frame, prefer drawOnce().
Kevin Lubick359a7e32019-03-19 09:34:37 -04001097 this.flush();
1098 }.bind(this));
1099 }
1100
Kevin Lubick52379332020-01-27 10:01:25 -05001101 // drawOnce will dispose of the surface after drawing the frame using the provided
1102 // callback.
Bryce Thomas2c5b8562020-01-22 13:49:41 -08001103 CanvasKit.SkSurface.prototype.drawOnce = function(callback, dirtyRect) {
1104 if (!this._cached_canvas) {
1105 this._cached_canvas = this.getCanvas();
1106 }
1107 window.requestAnimationFrame(function() {
1108 if (this._context !== undefined) {
1109 CanvasKit.setCurrentContext(this._context);
1110 }
1111 callback(this._cached_canvas);
1112
1113 this.flush();
1114 this.dispose();
1115 }.bind(this));
1116 }
1117
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001118 CanvasKit.SkPathEffect.MakeDash = function(intervals, phase) {
1119 if (!phase) {
1120 phase = 0;
1121 }
1122 if (!intervals.length || intervals.length % 2 === 1) {
1123 throw 'Intervals array must have even length';
1124 }
1125 var ptr = copy1dArray(intervals, CanvasKit.HEAPF32);
Kevin Lubickf279c632020-03-18 09:53:55 -04001126 var dpe = CanvasKit.SkPathEffect._MakeDash(ptr, intervals.length, phase);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001127 CanvasKit._free(ptr);
1128 return dpe;
1129 }
1130
1131 CanvasKit.SkShader.MakeLinearGradient = function(start, end, colors, pos, mode, localMatrix, flags) {
Nathaniel Nifonge5d32542020-03-26 09:27:48 -04001132 var colorPtr = copy2dArray(colors, CanvasKit.HEAPF32);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001133 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
1134 flags = flags || 0;
Kevin Lubick6bffe392020-04-02 15:24:15 -04001135 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001136
Kevin Lubick6bffe392020-04-02 15:24:15 -04001137 var lgs = CanvasKit._MakeLinearGradientShader(start, end, colorPtr, posPtr,
1138 colors.length, mode, flags, localMatrixPtr);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001139
Kevin Lubickc1d08982020-04-06 13:52:15 -04001140 CanvasKit._free(localMatrixPtr);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001141 CanvasKit._free(colorPtr);
1142 CanvasKit._free(posPtr);
1143 return lgs;
1144 }
1145
1146 CanvasKit.SkShader.MakeRadialGradient = function(center, radius, colors, pos, mode, localMatrix, flags) {
Nathaniel Nifonge5d32542020-03-26 09:27:48 -04001147 var colorPtr = copy2dArray(colors, CanvasKit.HEAPF32);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001148 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
1149 flags = flags || 0;
Kevin Lubick6bffe392020-04-02 15:24:15 -04001150 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001151
Kevin Lubick6bffe392020-04-02 15:24:15 -04001152 var rgs = CanvasKit._MakeRadialGradientShader(center, radius, colorPtr, posPtr,
1153 colors.length, mode, flags, localMatrixPtr);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001154
Kevin Lubickc1d08982020-04-06 13:52:15 -04001155 CanvasKit._free(localMatrixPtr);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001156 CanvasKit._free(colorPtr);
1157 CanvasKit._free(posPtr);
1158 return rgs;
1159 }
1160
Dan Field3d44f732020-03-16 09:17:30 -07001161 CanvasKit.SkShader.MakeSweepGradient = function(cx, cy, colors, pos, mode, localMatrix, flags, startAngle, endAngle) {
Nathaniel Nifonge5d32542020-03-26 09:27:48 -04001162 var colorPtr = copy2dArray(colors, CanvasKit.HEAPF32);
Dan Field3d44f732020-03-16 09:17:30 -07001163 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
1164 flags = flags || 0;
1165 startAngle = startAngle || 0;
1166 endAngle = endAngle || 360;
Kevin Lubick6bffe392020-04-02 15:24:15 -04001167 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Dan Field3d44f732020-03-16 09:17:30 -07001168
1169 var sgs = CanvasKit._MakeSweepGradientShader(cx, cy, colorPtr, posPtr,
Kevin Lubick6bffe392020-04-02 15:24:15 -04001170 colors.length, mode,
1171 startAngle, endAngle, flags,
1172 localMatrixPtr);
Dan Field3d44f732020-03-16 09:17:30 -07001173
Kevin Lubickc1d08982020-04-06 13:52:15 -04001174 CanvasKit._free(localMatrixPtr);
Dan Field3d44f732020-03-16 09:17:30 -07001175 CanvasKit._free(colorPtr);
1176 CanvasKit._free(posPtr);
1177 return sgs;
1178 }
1179
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001180 CanvasKit.SkShader.MakeTwoPointConicalGradient = function(start, startRadius, end, endRadius,
Kevin Lubick6bffe392020-04-02 15:24:15 -04001181 colors, pos, mode, localMatrix, flags) {
Nathaniel Nifonge5d32542020-03-26 09:27:48 -04001182 var colorPtr = copy2dArray(colors, CanvasKit.HEAPF32);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001183 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
1184 flags = flags || 0;
Kevin Lubick6bffe392020-04-02 15:24:15 -04001185 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001186
Kevin Lubick6bffe392020-04-02 15:24:15 -04001187 var rgs = CanvasKit._MakeTwoPointConicalGradientShader(
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001188 start, startRadius, end, endRadius,
Kevin Lubick6bffe392020-04-02 15:24:15 -04001189 colorPtr, posPtr, colors.length, mode, flags, localMatrixPtr);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001190
Kevin Lubickc1d08982020-04-06 13:52:15 -04001191 CanvasKit._free(localMatrixPtr);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001192 CanvasKit._free(colorPtr);
1193 CanvasKit._free(posPtr);
1194 return rgs;
1195 }
1196
1197 // temporary support for deprecated names.
Nathaniel Nifongc8f95e22020-03-09 11:52:51 -04001198 CanvasKit.MakeSkDashPathEffect = CanvasKit.SkPathEffect.MakeDash;
1199 CanvasKit.MakeLinearGradientShader = CanvasKit.SkShader.MakeLinearGradient;
1200 CanvasKit.MakeRadialGradientShader = CanvasKit.SkShader.MakeRadialGradient;
1201 CanvasKit.MakeTwoPointConicalGradientShader = CanvasKit.SkShader.MakeTwoPointConicalGradient;
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001202
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001203 // Run through the JS files that are added at compile time.
1204 if (CanvasKit._extraInitializations) {
1205 CanvasKit._extraInitializations.forEach(function(init) {
1206 init();
1207 });
Kevin Lubickeb2f6b02018-11-29 15:07:02 -05001208 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001209}; // end CanvasKit.onRuntimeInitialized, that is, anything changing prototypes or dynamic.
Kevin Lubickeb2f6b02018-11-29 15:07:02 -05001210
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001211CanvasKit.LTRBRect = function(l, t, r, b) {
1212 return {
1213 fLeft: l,
1214 fTop: t,
1215 fRight: r,
1216 fBottom: b,
1217 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -05001218}
1219
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001220CanvasKit.XYWHRect = function(x, y, w, h) {
1221 return {
1222 fLeft: x,
1223 fTop: y,
1224 fRight: x+w,
1225 fBottom: y+h,
1226 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -05001227}
1228
Kevin Lubick7d644e12019-09-11 14:22:22 -04001229// RRectXY returns an RRect with the given rect and a radiusX and radiusY for
1230// all 4 corners.
1231CanvasKit.RRectXY = function(rect, rx, ry) {
1232 return {
1233 rect: rect,
1234 rx1: rx,
1235 ry1: ry,
1236 rx2: rx,
1237 ry2: ry,
1238 rx3: rx,
1239 ry3: ry,
1240 rx4: rx,
1241 ry4: ry,
1242 };
1243}
1244
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001245CanvasKit.MakePathFromCmds = function(cmds) {
1246 var ptrLen = loadCmdsTypedArray(cmds);
1247 var path = CanvasKit._MakePathFromCmds(ptrLen[0], ptrLen[1]);
1248 CanvasKit._free(ptrLen[0]);
1249 return path;
1250}
1251
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001252// data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
Kevin Lubick6b921b72019-09-18 16:18:17 -04001253CanvasKit.MakeAnimatedImageFromEncoded = function(data) {
1254 data = new Uint8Array(data);
1255
1256 var iptr = CanvasKit._malloc(data.byteLength);
1257 CanvasKit.HEAPU8.set(data, iptr);
1258 var img = CanvasKit._decodeAnimatedImage(iptr, data.byteLength);
1259 if (!img) {
1260 SkDebug('Could not decode animated image');
1261 return null;
1262 }
1263 return img;
1264}
1265
1266// data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001267CanvasKit.MakeImageFromEncoded = function(data) {
1268 data = new Uint8Array(data);
1269
1270 var iptr = CanvasKit._malloc(data.byteLength);
1271 CanvasKit.HEAPU8.set(data, iptr);
1272 var img = CanvasKit._decodeImage(iptr, data.byteLength);
1273 if (!img) {
1274 SkDebug('Could not decode image');
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001275 return null;
1276 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001277 return img;
1278}
1279
Kevin Lubickeda0b432019-12-02 08:26:48 -05001280// pixels must be a Uint8Array with bytes representing the pixel values
1281// (e.g. each set of 4 bytes could represent RGBA values for a single pixel).
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001282CanvasKit.MakeImage = function(pixels, width, height, alphaType, colorType) {
Kevin Lubickeda0b432019-12-02 08:26:48 -05001283 var bytesPerPixel = pixels.length / (width * height);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001284 var info = {
1285 'width': width,
1286 'height': height,
1287 'alphaType': alphaType,
1288 'colorType': colorType,
1289 };
Kevin Lubickeda0b432019-12-02 08:26:48 -05001290 var pptr = copy1dArray(pixels, CanvasKit.HEAPU8);
1291 // No need to _free pptr, Image takes it with SkData::MakeFromMalloc
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001292
Kevin Lubickeda0b432019-12-02 08:26:48 -05001293 return CanvasKit._MakeImage(info, pptr, pixels.length, width * bytesPerPixel);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001294}
1295
Nathaniel Nifonge5d32542020-03-26 09:27:48 -04001296// colors is an array of SimpleColor4f
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001297CanvasKit.MakeSkVertices = function(mode, positions, textureCoordinates, colors,
Mike Reed5caf9352020-03-02 14:57:09 -05001298 indices, isVolatile) {
Kevin Lubickb3574c92019-03-06 08:25:36 -05001299 // Default isVolitile to true if not set
1300 isVolatile = isVolatile === undefined ? true : isVolatile;
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001301 var idxCount = (indices && indices.length) || 0;
1302
1303 var flags = 0;
1304 // These flags are from SkVertices.h and should be kept in sync with those.
1305 if (textureCoordinates && textureCoordinates.length) {
1306 flags |= (1 << 0);
1307 }
1308 if (colors && colors.length) {
1309 flags |= (1 << 1);
1310 }
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001311 if (!isVolatile) {
Mike Reed5caf9352020-03-02 14:57:09 -05001312 flags |= (1 << 2);
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001313 }
1314
1315 var builder = new CanvasKit._SkVerticesBuilder(mode, positions.length, idxCount, flags);
1316
1317 copy2dArray(positions, CanvasKit.HEAPF32, builder.positions());
1318 if (builder.texCoords()) {
1319 copy2dArray(textureCoordinates, CanvasKit.HEAPF32, builder.texCoords());
1320 }
1321 if (builder.colors()) {
Nathaniel Nifonge5d32542020-03-26 09:27:48 -04001322 // Convert from canvaskit 4f colors to 32 bit uint colors which builder supports.
1323 copy1dArray(colors.map(toUint32Color), CanvasKit.HEAPU32, builder.colors());
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001324 }
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001325 if (builder.indices()) {
1326 copy1dArray(indices, CanvasKit.HEAPU16, builder.indices());
1327 }
Kevin Lubickb3574c92019-03-06 08:25:36 -05001328
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001329 var idxCount = (indices && indices.length) || 0;
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001330 // Create the vertices, which owns the memory that the builder had allocated.
1331 return builder.detach();
Kevin Lubicka4f218d2020-01-14 08:39:09 -05001332};