blob: 9e6fe9b7b7ccf7aa4ec519e7865676abf89bcdb4 [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 Lubick6aa38692020-06-01 11:25:47 -040011 _scratchColorPtr = CanvasKit._malloc(4 * 4); // 4 32bit floats
12
13 _scratch4x4Matrix = CanvasKit.Malloc(Float32Array, 16); // 16 matrix scalars.
14 _scratch4x4MatrixPtr = _scratch4x4Matrix.byteOffset;
15
16 _scratch3x3Matrix = CanvasKit.Malloc(Float32Array, 9); // 9 matrix scalars.
17 _scratch3x3MatrixPtr = _scratch3x3Matrix.byteOffset;
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -040018 // Create single copies of all three supported color spaces
19 // These are sk_sp<SkColorSpace>
20 CanvasKit.SkColorSpace.SRGB = CanvasKit.SkColorSpace._MakeSRGB();
21 CanvasKit.SkColorSpace.DISPLAY_P3 = CanvasKit.SkColorSpace._MakeDisplayP3();
22 CanvasKit.SkColorSpace.ADOBE_RGB = CanvasKit.SkColorSpace._MakeAdobeRGB();
23
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050024 // Add some helpers for matrices. This is ported from SkMatrix.cpp
25 // to save complexity and overhead of going back and forth between
26 // C++ and JS layers.
27 // I would have liked to use something like DOMMatrix, except it
28 // isn't widely supported (would need polyfills) and it doesn't
29 // have a mapPoints() function (which could maybe be tacked on here).
30 // If DOMMatrix catches on, it would be worth re-considering this usage.
31 CanvasKit.SkMatrix = {};
Nathaniel Nifong77798b42020-02-21 17:15:22 -050032 function sdot() { // to be called with an even number of scalar args
33 var acc = 0;
34 for (var i=0; i < arguments.length-1; i+=2) {
35 acc += arguments[i] * arguments[i+1];
36 }
37 return acc;
38 }
39
40
41 // Private general matrix functions used in both 3x3s and 4x4s.
42 // Return a square identity matrix of size n.
43 var identityN = function(n) {
44 var size = n*n;
45 var m = new Array(size);
46 while(size--) {
47 m[size] = size%(n+1) == 0 ? 1.0 : 0.0;
48 }
49 return m;
50 }
51
52 // Stride, a function for compactly representing several ways of copying an array into another.
53 // Write vector `v` into matrix `m`. `m` is a matrix encoded as an array in row-major
54 // order. Its width is passed as `width`. `v` is an array with length < (m.length/width).
55 // An element of `v` is copied into `m` starting at `offset` and moving `colStride` cols right
56 // each row.
57 //
58 // For example, a width of 4, offset of 3, and stride of -1 would put the vector here.
59 // _ _ 0 _
60 // _ 1 _ _
61 // 2 _ _ _
62 // _ _ _ 3
63 //
64 var stride = function(v, m, width, offset, colStride) {
65 for (var i=0; i<v.length; i++) {
66 m[i * width + // column
67 (i * colStride + offset + width) % width // row
68 ] = v[i];
69 }
70 return m;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050071 }
72
73 CanvasKit.SkMatrix.identity = function() {
Nathaniel Nifong77798b42020-02-21 17:15:22 -050074 return identityN(3);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050075 };
76
77 // Return the inverse (if it exists) of this matrix.
Kevin Lubick9b56cea2020-04-06 08:16:18 -040078 // Otherwise, return null.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050079 CanvasKit.SkMatrix.invert = function(m) {
Nathaniel Nifong77798b42020-02-21 17:15:22 -050080 // Find the determinant by the sarrus rule. https://en.wikipedia.org/wiki/Rule_of_Sarrus
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050081 var det = m[0]*m[4]*m[8] + m[1]*m[5]*m[6] + m[2]*m[3]*m[7]
82 - m[2]*m[4]*m[6] - m[1]*m[3]*m[8] - m[0]*m[5]*m[7];
83 if (!det) {
84 SkDebug('Warning, uninvertible matrix');
Nathaniel Nifong77798b42020-02-21 17:15:22 -050085 return null;
Kevin Lubick1a05fce2018-11-20 12:51:16 -050086 }
Nathaniel Nifong77798b42020-02-21 17:15:22 -050087 // Return the inverse by the formula adj(m)/det.
88 // adj (adjugate) of a 3x3 is the transpose of it's cofactor matrix.
89 // a cofactor matrix is a matrix where each term is +-det(N) where matrix N is the 2x2 formed
90 // by removing the row and column we're currently setting from the source.
91 // the sign alternates in a checkerboard pattern with a `+` at the top left.
92 // that's all been combined here into one expression.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050093 return [
94 (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,
95 (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,
96 (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,
97 ];
98 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -050099
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500100 // Maps the given points according to the passed in matrix.
101 // Results are done in place.
102 // See SkMatrix.h::mapPoints for the docs on the math.
103 CanvasKit.SkMatrix.mapPoints = function(matrix, ptArr) {
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500104 if (skIsDebug && (ptArr.length % 2)) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500105 throw 'mapPoints requires an even length arr';
Kevin Lubickb9db3902018-11-26 11:47:54 -0500106 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500107 for (var i = 0; i < ptArr.length; i+=2) {
108 var x = ptArr[i], y = ptArr[i+1];
109 // Gx+Hy+I
110 var denom = matrix[6]*x + matrix[7]*y + matrix[8];
111 // Ax+By+C
112 var xTrans = matrix[0]*x + matrix[1]*y + matrix[2];
113 // Dx+Ey+F
114 var yTrans = matrix[3]*x + matrix[4]*y + matrix[5];
115 ptArr[i] = xTrans/denom;
116 ptArr[i+1] = yTrans/denom;
117 }
118 return ptArr;
119 };
Kevin Lubickb9db3902018-11-26 11:47:54 -0500120
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500121 function isnumber(val) { return val !== NaN; };
122
Kevin Lubickc89ca0b2020-04-02 14:30:00 -0400123 // generalized iterative algorithm for multiplying two matrices.
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500124 function multiply(m1, m2, size) {
125
126 if (skIsDebug && (!m1.every(isnumber) || !m2.every(isnumber))) {
127 throw 'Some members of matrices are NaN m1='+m1+', m2='+m2+'';
128 }
129 if (skIsDebug && (m1.length !== m2.length)) {
130 throw 'Undefined for matrices of different sizes. m1.length='+m1.length+', m2.length='+m2.length;
131 }
132 if (skIsDebug && (size*size !== m1.length)) {
133 throw 'Undefined for non-square matrices. array size was '+size;
134 }
135
136 var result = Array(m1.length);
137 for (var r = 0; r < size; r++) {
138 for (var c = 0; c < size; c++) {
139 // accumulate a sum of m1[r,k]*m2[k, c]
140 var acc = 0;
141 for (var k = 0; k < size; k++) {
142 acc += m1[size * r + k] * m2[size * k + c];
143 }
144 result[r * size + c] = acc;
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500145 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500146 }
147 return result;
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500148 };
149
150 // Accept an integer indicating the size of the matrices being multiplied (3 for 3x3), and any
151 // number of matrices following it.
152 function multiplyMany(size, listOfMatrices) {
153 if (skIsDebug && (listOfMatrices.length < 2)) {
154 throw 'multiplication expected two or more matrices';
155 }
156 var result = multiply(listOfMatrices[0], listOfMatrices[1], size);
157 var next = 2;
158 while (next < listOfMatrices.length) {
159 result = multiply(result, listOfMatrices[next], size);
160 next++;
161 }
162 return result;
163 };
164
165 // Accept any number 3x3 of matrices as arguments, multiply them together.
Kevin Lubick9e2d3842020-04-01 13:42:15 -0400166 // Matrix multiplication is associative but not commutative. the order of the arguments
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500167 // matters, but it does not matter that this implementation multiplies them left to right.
168 CanvasKit.SkMatrix.multiply = function() {
169 return multiplyMany(3, arguments);
170 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500171
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500172 // Return a matrix representing a rotation by n radians.
173 // px, py optionally say which point the rotation should be around
174 // with the default being (0, 0);
175 CanvasKit.SkMatrix.rotated = function(radians, px, py) {
176 px = px || 0;
177 py = py || 0;
178 var sinV = Math.sin(radians);
179 var cosV = Math.cos(radians);
180 return [
181 cosV, -sinV, sdot( sinV, py, 1 - cosV, px),
182 sinV, cosV, sdot(-sinV, px, 1 - cosV, py),
183 0, 0, 1,
184 ];
185 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400186
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500187 CanvasKit.SkMatrix.scaled = function(sx, sy, px, py) {
188 px = px || 0;
189 py = py || 0;
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500190 var m = stride([sx, sy], identityN(3), 3, 0, 1);
191 return stride([px-sx*px, py-sy*py], m, 3, 2, 0);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500192 };
Kevin Lubickda3d8ac2019-01-07 11:08:55 -0500193
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500194 CanvasKit.SkMatrix.skewed = function(kx, ky, px, py) {
195 px = px || 0;
196 py = py || 0;
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500197 var m = stride([kx, ky], identityN(3), 3, 1, -1);
198 return stride([-kx*px, -ky*py], m, 3, 2, 0);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500199 };
Alexander Khovansky3e119332018-11-15 02:01:19 +0300200
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500201 CanvasKit.SkMatrix.translated = function(dx, dy) {
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500202 return stride(arguments, identityN(3), 3, 2, 0);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500203 };
Kevin Lubick1646e7d2018-12-07 13:03:08 -0500204
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500205 // Functions for manipulating vectors.
206 // Loosely based off of SkV3 in SkM44.h but skia also has SkVec2 and Skv4. This combines them and
207 // works on vectors of any length.
208 CanvasKit.SkVector = {};
209 CanvasKit.SkVector.dot = function(a, b) {
210 if (skIsDebug && (a.length !== b.length)) {
211 throw 'Cannot perform dot product on arrays of different length ('+a.length+' vs '+b.length+')';
212 }
213 return a.map(function(v, i) { return v*b[i] }).reduce(function(acc, cur) { return acc + cur; });
214 }
215 CanvasKit.SkVector.lengthSquared = function(v) {
216 return CanvasKit.SkVector.dot(v, v);
217 }
218 CanvasKit.SkVector.length = function(v) {
219 return Math.sqrt(CanvasKit.SkVector.lengthSquared(v));
220 }
221 CanvasKit.SkVector.mulScalar = function(v, s) {
222 return v.map(function(i) { return i*s });
223 }
224 CanvasKit.SkVector.add = function(a, b) {
225 return a.map(function(v, i) { return v+b[i] });
226 }
227 CanvasKit.SkVector.sub = function(a, b) {
228 return a.map(function(v, i) { return v-b[i]; });
229 }
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500230 CanvasKit.SkVector.dist = function(a, b) {
231 return CanvasKit.SkVector.length(CanvasKit.SkVector.sub(a, b));
232 }
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500233 CanvasKit.SkVector.normalize = function(v) {
234 return CanvasKit.SkVector.mulScalar(v, 1/CanvasKit.SkVector.length(v));
235 }
236 CanvasKit.SkVector.cross = function(a, b) {
237 if (skIsDebug && (a.length !== 3 || a.length !== 3)) {
238 throw 'Cross product is only defined for 3-dimensional vectors (a.length='+a.length+', b.length='+b.length+')';
239 }
240 return [
241 a[1]*b[2] - a[2]*b[1],
242 a[2]*b[0] - a[0]*b[2],
243 a[0]*b[1] - a[1]*b[0],
244 ];
245 }
246
Kevin Lubickc1d08982020-04-06 13:52:15 -0400247 // Functions for creating and manipulating (row-major) 4x4 matrices. Accepted in place of
248 // SkM44 in canvas methods, for the same reasons as the 3x3 matrices above.
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500249 // ported from C++ code in SkM44.cpp
250 CanvasKit.SkM44 = {};
251 // Create a 4x4 identity matrix
252 CanvasKit.SkM44.identity = function() {
253 return identityN(4);
254 }
255
256 // Anything named vec below is an array of length 3 representing a vector/point in 3D space.
257 // Create a 4x4 matrix representing a translate by the provided 3-vec
258 CanvasKit.SkM44.translated = function(vec) {
259 return stride(vec, identityN(4), 4, 3, 0);
260 }
261 // Create a 4x4 matrix representing a scaling by the provided 3-vec
262 CanvasKit.SkM44.scaled = function(vec) {
263 return stride(vec, identityN(4), 4, 0, 1);
264 }
265 // Create a 4x4 matrix representing a rotation about the provided axis 3-vec.
266 // axis does not need to be normalized.
267 CanvasKit.SkM44.rotated = function(axisVec, radians) {
268 return CanvasKit.SkM44.rotatedUnitSinCos(
269 CanvasKit.SkVector.normalize(axisVec), Math.sin(radians), Math.cos(radians));
270 }
271 // Create a 4x4 matrix representing a rotation about the provided normalized axis 3-vec.
272 // Rotation is provided redundantly as both sin and cos values.
273 // This rotate can be used when you already have the cosAngle and sinAngle values
274 // so you don't have to atan(cos/sin) to call roatated() which expects an angle in radians.
275 // this does no checking! Behavior for invalid sin or cos values or non-normalized axis vectors
Nathaniel Nifong3392ebe2020-06-01 09:21:36 -0400276 // is incorrect. Prefer rotated().
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500277 CanvasKit.SkM44.rotatedUnitSinCos = function(axisVec, sinAngle, cosAngle) {
278 var x = axisVec[0];
279 var y = axisVec[1];
280 var z = axisVec[2];
281 var c = cosAngle;
282 var s = sinAngle;
283 var t = 1 - c;
284 return [
285 t*x*x + c, t*x*y - s*z, t*x*z + s*y, 0,
286 t*x*y + s*z, t*y*y + c, t*y*z - s*x, 0,
287 t*x*z - s*y, t*y*z + s*x, t*z*z + c, 0,
288 0, 0, 0, 1
289 ];
290 }
291 // Create a 4x4 matrix representing a camera at eyeVec, pointed at centerVec.
292 CanvasKit.SkM44.lookat = function(eyeVec, centerVec, upVec) {
293 var f = CanvasKit.SkVector.normalize(CanvasKit.SkVector.sub(centerVec, eyeVec));
294 var u = CanvasKit.SkVector.normalize(upVec);
295 var s = CanvasKit.SkVector.normalize(CanvasKit.SkVector.cross(f, u));
296
297 var m = CanvasKit.SkM44.identity();
298 // set each column's top three numbers
Kevin Lubickc1d08982020-04-06 13:52:15 -0400299 stride(s, m, 4, 0, 0);
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500300 stride(CanvasKit.SkVector.cross(s, f), m, 4, 1, 0);
301 stride(CanvasKit.SkVector.mulScalar(f, -1), m, 4, 2, 0);
Kevin Lubickc1d08982020-04-06 13:52:15 -0400302 stride(eyeVec, m, 4, 3, 0);
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500303
304 var m2 = CanvasKit.SkM44.invert(m);
305 if (m2 === null) {
306 return CanvasKit.SkM44.identity();
307 }
308 return m2;
309 }
310 // Create a 4x4 matrix representing a perspective. All arguments are scalars.
311 // angle is in radians.
312 CanvasKit.SkM44.perspective = function(near, far, angle) {
313 if (skIsDebug && (far <= near)) {
314 throw "far must be greater than near when constructing SkM44 using perspective.";
315 }
316 var dInv = 1 / (far - near);
317 var halfAngle = angle / 2;
318 var cot = Math.cos(halfAngle) / Math.sin(halfAngle);
319 return [
320 cot, 0, 0, 0,
321 0, cot, 0, 0,
322 0, 0, (far+near)*dInv, 2*far*near*dInv,
323 0, 0, -1, 1,
324 ];
325 }
326 // Returns the number at the given row and column in matrix m.
327 CanvasKit.SkM44.rc = function(m, r, c) {
328 return m[r*4+c];
329 }
330 // Accepts any number of 4x4 matrix arguments, multiplies them left to right.
331 CanvasKit.SkM44.multiply = function() {
332 return multiplyMany(4, arguments);
333 }
334
335 // Invert the 4x4 matrix if it is invertible and return it. if not, return null.
336 // taken from SkM44.cpp (altered to use row-major order)
337 // m is not altered.
338 CanvasKit.SkM44.invert = function(m) {
339 if (skIsDebug && !m.every(isnumber)) {
340 throw 'some members of matrix are NaN m='+m;
341 }
342
343 var a00 = m[0];
344 var a01 = m[4];
345 var a02 = m[8];
346 var a03 = m[12];
347 var a10 = m[1];
348 var a11 = m[5];
349 var a12 = m[9];
350 var a13 = m[13];
351 var a20 = m[2];
352 var a21 = m[6];
353 var a22 = m[10];
354 var a23 = m[14];
355 var a30 = m[3];
356 var a31 = m[7];
357 var a32 = m[11];
358 var a33 = m[15];
359
360 var b00 = a00 * a11 - a01 * a10;
361 var b01 = a00 * a12 - a02 * a10;
362 var b02 = a00 * a13 - a03 * a10;
363 var b03 = a01 * a12 - a02 * a11;
364 var b04 = a01 * a13 - a03 * a11;
365 var b05 = a02 * a13 - a03 * a12;
366 var b06 = a20 * a31 - a21 * a30;
367 var b07 = a20 * a32 - a22 * a30;
368 var b08 = a20 * a33 - a23 * a30;
369 var b09 = a21 * a32 - a22 * a31;
370 var b10 = a21 * a33 - a23 * a31;
371 var b11 = a22 * a33 - a23 * a32;
372
373 // calculate determinate
374 var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
375 var invdet = 1.0 / det;
376
377 // bail out if the matrix is not invertible
378 if (det === 0 || invdet === Infinity) {
379 SkDebug('Warning, uninvertible matrix');
380 return null;
381 }
382
383 b00 *= invdet;
384 b01 *= invdet;
385 b02 *= invdet;
386 b03 *= invdet;
387 b04 *= invdet;
388 b05 *= invdet;
389 b06 *= invdet;
390 b07 *= invdet;
391 b08 *= invdet;
392 b09 *= invdet;
393 b10 *= invdet;
394 b11 *= invdet;
395
396 // store result in row major order
397 var tmp = [
398 a11 * b11 - a12 * b10 + a13 * b09,
399 a12 * b08 - a10 * b11 - a13 * b07,
400 a10 * b10 - a11 * b08 + a13 * b06,
401 a11 * b07 - a10 * b09 - a12 * b06,
402
403 a02 * b10 - a01 * b11 - a03 * b09,
404 a00 * b11 - a02 * b08 + a03 * b07,
405 a01 * b08 - a00 * b10 - a03 * b06,
406 a00 * b09 - a01 * b07 + a02 * b06,
407
408 a31 * b05 - a32 * b04 + a33 * b03,
409 a32 * b02 - a30 * b05 - a33 * b01,
410 a30 * b04 - a31 * b02 + a33 * b00,
411 a31 * b01 - a30 * b03 - a32 * b00,
412
413 a22 * b04 - a21 * b05 - a23 * b03,
414 a20 * b05 - a22 * b02 + a23 * b01,
415 a21 * b02 - a20 * b04 - a23 * b00,
416 a20 * b03 - a21 * b01 + a22 * b00,
417 ];
418
419
420 if (!tmp.every(function(val) { return val !== NaN && val !== Infinity && val !== -Infinity; })) {
421 SkDebug('inverted matrix contains infinities or NaN '+tmp);
422 return null;
423 }
424 return tmp;
425 }
426
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500427 CanvasKit.SkM44.transpose = function(m) {
428 return [
429 m[0], m[4], m[8], m[12],
430 m[1], m[5], m[9], m[13],
431 m[2], m[6], m[10], m[14],
432 m[3], m[7], m[11], m[15],
433 ];
434 }
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500435
Kevin Lubickd3729342019-09-12 11:11:25 -0400436 // An SkColorMatrix is a 4x4 color matrix that transforms the 4 color channels
437 // with a 1x4 matrix that post-translates those 4 channels.
438 // For example, the following is the layout with the scale (S) and post-transform
439 // (PT) items indicated.
440 // RS, 0, 0, 0 | RPT
441 // 0, GS, 0, 0 | GPT
442 // 0, 0, BS, 0 | BPT
443 // 0, 0, 0, AS | APT
444 //
445 // Much of this was hand-transcribed from SkColorMatrix.cpp, because it's easier to
446 // deal with a Float32Array of length 20 than to try to expose the SkColorMatrix object.
447
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500448 var rScale = 0;
449 var gScale = 6;
450 var bScale = 12;
451 var aScale = 18;
452
Kevin Lubickd3729342019-09-12 11:11:25 -0400453 var rPostTrans = 4;
454 var gPostTrans = 9;
455 var bPostTrans = 14;
456 var aPostTrans = 19;
457
458 CanvasKit.SkColorMatrix = {};
459 CanvasKit.SkColorMatrix.identity = function() {
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500460 var m = new Float32Array(20);
461 m[rScale] = 1;
462 m[gScale] = 1;
463 m[bScale] = 1;
464 m[aScale] = 1;
465 return m;
Kevin Lubickd3729342019-09-12 11:11:25 -0400466 }
467
468 CanvasKit.SkColorMatrix.scaled = function(rs, gs, bs, as) {
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500469 var m = new Float32Array(20);
470 m[rScale] = rs;
471 m[gScale] = gs;
472 m[bScale] = bs;
473 m[aScale] = as;
474 return m;
Kevin Lubickd3729342019-09-12 11:11:25 -0400475 }
476
477 var rotateIndices = [
478 [6, 7, 11, 12],
479 [0, 10, 2, 12],
480 [0, 1, 5, 6],
481 ];
482 // axis should be 0, 1, 2 for r, g, b
483 CanvasKit.SkColorMatrix.rotated = function(axis, sine, cosine) {
484 var m = CanvasKit.SkColorMatrix.identity();
485 var indices = rotateIndices[axis];
486 m[indices[0]] = cosine;
487 m[indices[1]] = sine;
488 m[indices[2]] = -sine;
489 m[indices[3]] = cosine;
490 return m;
491 }
492
493 // m is a SkColorMatrix (i.e. a Float32Array), and this sets the 4 "special"
494 // params that will translate the colors after they are multiplied by the 4x4 matrix.
495 CanvasKit.SkColorMatrix.postTranslate = function(m, dr, dg, db, da) {
496 m[rPostTrans] += dr;
497 m[gPostTrans] += dg;
498 m[bPostTrans] += db;
499 m[aPostTrans] += da;
500 return m;
501 }
502
503 // concat returns a new SkColorMatrix that is the result of multiplying outer*inner;
504 CanvasKit.SkColorMatrix.concat = function(outer, inner) {
505 var m = new Float32Array(20);
506 var index = 0;
507 for (var j = 0; j < 20; j += 5) {
508 for (var i = 0; i < 4; i++) {
509 m[index++] = outer[j + 0] * inner[i + 0] +
510 outer[j + 1] * inner[i + 5] +
511 outer[j + 2] * inner[i + 10] +
512 outer[j + 3] * inner[i + 15];
513 }
514 m[index++] = outer[j + 0] * inner[4] +
515 outer[j + 1] * inner[9] +
516 outer[j + 2] * inner[14] +
517 outer[j + 3] * inner[19] +
518 outer[j + 4];
519 }
520
521 return m;
522 }
523
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500524 CanvasKit.SkPath.prototype.addArc = function(oval, startAngle, sweepAngle) {
525 // see arc() for the HTMLCanvas version
526 // note input angles are degrees.
527 this._addArc(oval, startAngle, sweepAngle);
528 return this;
529 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400530
Kevin Lubicke384df42019-08-26 15:48:09 -0400531 CanvasKit.SkPath.prototype.addOval = function(oval, isCCW, startIndex) {
532 if (startIndex === undefined) {
533 startIndex = 1;
534 }
535 this._addOval(oval, !!isCCW, startIndex);
536 return this;
537 };
538
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500539 CanvasKit.SkPath.prototype.addPath = function() {
540 // Takes 1, 2, 7, or 10 required args, where the first arg is always the path.
541 // The last arg is optional and chooses between add or extend mode.
542 // The options for the remaining args are:
543 // - an array of 6 or 9 parameters (perspective is optional)
544 // - the 9 parameters of a full matrix or
545 // the 6 non-perspective params of a matrix.
546 var args = Array.prototype.slice.call(arguments);
547 var path = args[0];
548 var extend = false;
549 if (typeof args[args.length-1] === "boolean") {
550 extend = args.pop();
551 }
552 if (args.length === 1) {
553 // Add path, unchanged. Use identity matrix
554 this._addPath(path, 1, 0, 0,
555 0, 1, 0,
556 0, 0, 1,
557 extend);
558 } else if (args.length === 2) {
559 // User provided the 9 params of a full matrix as an array.
560 var a = args[1];
561 this._addPath(path, a[0], a[1], a[2],
562 a[3], a[4], a[5],
563 a[6] || 0, a[7] || 0, a[8] || 1,
564 extend);
565 } else if (args.length === 7 || args.length === 10) {
566 // User provided the 9 params of a (full) matrix directly.
567 // (or just the 6 non perspective ones)
568 // These are in the same order as what Skia expects.
569 var a = args;
570 this._addPath(path, a[1], a[2], a[3],
571 a[4], a[5], a[6],
572 a[7] || 0, a[8] || 0, a[9] || 1,
573 extend);
574 } else {
575 SkDebug('addPath expected to take 1, 2, 7, or 10 required args. Got ' + args.length);
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400576 return null;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500577 }
578 return this;
579 };
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400580
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500581 // points is either an array of [x, y] where x and y are numbers or
582 // a typed array from Malloc where the even indices will be treated
583 // as x coordinates and the odd indices will be treated as y coordinates.
584 CanvasKit.SkPath.prototype.addPoly = function(points, close) {
585 var ptr;
586 var n;
587 // This was created with CanvasKit.Malloc, so assume the user has
588 // already been filled with data.
589 if (points['_ck']) {
590 ptr = points.byteOffset;
591 n = points.length/2;
592 } else {
593 ptr = copy2dArray(points, CanvasKit.HEAPF32);
594 n = points.length;
595 }
596 this._addPoly(ptr, n, close);
Kevin Lubickcf118922020-05-28 14:43:38 -0400597 freeArraysThatAreNotMallocedByUsers(ptr, points);
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500598 return this;
599 };
600
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500601 CanvasKit.SkPath.prototype.addRect = function() {
602 // Takes 1, 2, 4 or 5 args
603 // - SkRect
604 // - SkRect, isCCW
605 // - left, top, right, bottom
606 // - left, top, right, bottom, isCCW
607 if (arguments.length === 1 || arguments.length === 2) {
608 var r = arguments[0];
609 var ccw = arguments[1] || false;
610 this._addRect(r.fLeft, r.fTop, r.fRight, r.fBottom, ccw);
611 } else if (arguments.length === 4 || arguments.length === 5) {
612 var a = arguments;
613 this._addRect(a[0], a[1], a[2], a[3], a[4] || false);
614 } else {
615 SkDebug('addRect expected to take 1, 2, 4, or 5 args. Got ' + arguments.length);
Kevin Lubick217056c2018-09-20 17:39:31 -0400616 return null;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500617 }
618 return this;
619 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400620
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500621 CanvasKit.SkPath.prototype.addRoundRect = function() {
622 // Takes 3, 4, 6 or 7 args
Nathaniel Nifong3392ebe2020-06-01 09:21:36 -0400623 // - SkRect, radii (an array of 8 numbers), ccw
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500624 // - SkRect, rx, ry, ccw
625 // - left, top, right, bottom, radii, ccw
626 // - left, top, right, bottom, rx, ry, ccw
627 var args = arguments;
628 if (args.length === 3 || args.length === 6) {
629 var radii = args[args.length-2];
Kevin Lubickcf118922020-05-28 14:43:38 -0400630 } else if (args.length === 4 || args.length === 7){
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500631 // duplicate the given (rx, ry) pairs for each corner.
632 var rx = args[args.length-3];
633 var ry = args[args.length-2];
634 var radii = [rx, ry, rx, ry, rx, ry, rx, ry];
635 } else {
636 SkDebug('addRoundRect expected to take 3, 4, 6, or 7 args. Got ' + args.length);
637 return null;
638 }
639 if (radii.length !== 8) {
640 SkDebug('addRoundRect needs 8 radii provided. Got ' + radii.length);
641 return null;
642 }
643 var rptr = copy1dArray(radii, CanvasKit.HEAPF32);
644 if (args.length === 3 || args.length === 4) {
645 var r = args[0];
646 var ccw = args[args.length - 1];
647 this._addRoundRect(r.fLeft, r.fTop, r.fRight, r.fBottom, rptr, ccw);
648 } else if (args.length === 6 || args.length === 7) {
649 var a = args;
650 this._addRoundRect(a[0], a[1], a[2], a[3], rptr, ccw);
651 }
Kevin Lubickcf118922020-05-28 14:43:38 -0400652 freeArraysThatAreNotMallocedByUsers(rptr, radii);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500653 return this;
654 };
655
656 CanvasKit.SkPath.prototype.arc = function(x, y, radius, startAngle, endAngle, ccw) {
657 // emulates the HTMLCanvas behavior. See addArc() for the SkPath version.
658 // Note input angles are radians.
659 var bounds = CanvasKit.LTRBRect(x-radius, y-radius, x+radius, y+radius);
660 var sweep = radiansToDegrees(endAngle - startAngle) - (360 * !!ccw);
661 var temp = new CanvasKit.SkPath();
662 temp.addArc(bounds, radiansToDegrees(startAngle), sweep);
663 this.addPath(temp, true);
664 temp.delete();
665 return this;
666 };
667
668 CanvasKit.SkPath.prototype.arcTo = function() {
669 // takes 4, 5 or 7 args
670 // - 5 x1, y1, x2, y2, radius
671 // - 4 oval (as Rect), startAngle, sweepAngle, forceMoveTo
Kevin Lubicke384df42019-08-26 15:48:09 -0400672 // - 7 rx, ry, xAxisRotate, useSmallArc, isCCW, x, y
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500673 var args = arguments;
674 if (args.length === 5) {
675 this._arcTo(args[0], args[1], args[2], args[3], args[4]);
676 } else if (args.length === 4) {
677 this._arcTo(args[0], args[1], args[2], args[3]);
678 } else if (args.length === 7) {
Kevin Lubicke384df42019-08-26 15:48:09 -0400679 this._arcTo(args[0], args[1], args[2], !!args[3], !!args[4], args[5], args[6]);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500680 } else {
681 throw 'Invalid args for arcTo. Expected 4, 5, or 7, got '+ args.length;
682 }
683
684 return this;
685 };
686
687 CanvasKit.SkPath.prototype.close = function() {
688 this._close();
689 return this;
690 };
691
692 CanvasKit.SkPath.prototype.conicTo = function(x1, y1, x2, y2, w) {
693 this._conicTo(x1, y1, x2, y2, w);
694 return this;
695 };
696
697 CanvasKit.SkPath.prototype.cubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
698 this._cubicTo(cp1x, cp1y, cp2x, cp2y, x, y);
699 return this;
700 };
701
702 CanvasKit.SkPath.prototype.dash = function(on, off, phase) {
703 if (this._dash(on, off, phase)) {
Kevin Lubick217056c2018-09-20 17:39:31 -0400704 return this;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500705 }
706 return null;
707 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400708
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500709 CanvasKit.SkPath.prototype.lineTo = function(x, y) {
710 this._lineTo(x, y);
711 return this;
712 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400713
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500714 CanvasKit.SkPath.prototype.moveTo = function(x, y) {
715 this._moveTo(x, y);
716 return this;
717 };
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400718
Kevin Lubicke384df42019-08-26 15:48:09 -0400719 CanvasKit.SkPath.prototype.offset = function(dx, dy) {
720 this._transform(1, 0, dx,
721 0, 1, dy,
722 0, 0, 1);
723 return this;
724 };
725
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500726 CanvasKit.SkPath.prototype.quadTo = function(cpx, cpy, x, y) {
727 this._quadTo(cpx, cpy, x, y);
728 return this;
729 };
730
Kevin Lubick79b71342019-11-01 14:36:52 -0400731 CanvasKit.SkPath.prototype.rArcTo = function(rx, ry, xAxisRotate, useSmallArc, isCCW, dx, dy) {
732 this._rArcTo(rx, ry, xAxisRotate, useSmallArc, isCCW, dx, dy);
733 return this;
734 };
735
736 CanvasKit.SkPath.prototype.rConicTo = function(dx1, dy1, dx2, dy2, w) {
737 this._rConicTo(dx1, dy1, dx2, dy2, w);
738 return this;
739 };
740
741 // These params are all relative
742 CanvasKit.SkPath.prototype.rCubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
743 this._rCubicTo(cp1x, cp1y, cp2x, cp2y, x, y);
744 return this;
745 };
746
747 CanvasKit.SkPath.prototype.rLineTo = function(dx, dy) {
748 this._rLineTo(dx, dy);
749 return this;
750 };
751
752 CanvasKit.SkPath.prototype.rMoveTo = function(dx, dy) {
753 this._rMoveTo(dx, dy);
754 return this;
755 };
756
757 // These params are all relative
758 CanvasKit.SkPath.prototype.rQuadTo = function(cpx, cpy, x, y) {
759 this._rQuadTo(cpx, cpy, x, y);
760 return this;
761 };
762
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500763 CanvasKit.SkPath.prototype.stroke = function(opts) {
764 // Fill out any missing values with the default values.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500765 opts = opts || {};
Kevin Lubick6aa38692020-06-01 11:25:47 -0400766 opts['width'] = opts['width'] || 1;
767 opts['miter_limit'] = opts['miter_limit'] || 4;
768 opts['cap'] = opts['cap'] || CanvasKit.StrokeCap.Butt;
769 opts['join'] = opts['join'] || CanvasKit.StrokeJoin.Miter;
770 opts['precision'] = opts['precision'] || 1;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500771 if (this._stroke(opts)) {
772 return this;
773 }
774 return null;
775 };
776
777 CanvasKit.SkPath.prototype.transform = function() {
778 // Takes 1 or 9 args
779 if (arguments.length === 1) {
780 // argument 1 should be a 6 or 9 element array.
781 var a = arguments[0];
782 this._transform(a[0], a[1], a[2],
783 a[3], a[4], a[5],
784 a[6] || 0, a[7] || 0, a[8] || 1);
785 } else if (arguments.length === 6 || arguments.length === 9) {
786 // these arguments are the 6 or 9 members of the matrix
787 var a = arguments;
788 this._transform(a[0], a[1], a[2],
789 a[3], a[4], a[5],
790 a[6] || 0, a[7] || 0, a[8] || 1);
791 } else {
792 throw 'transform expected to take 1 or 9 arguments. Got ' + arguments.length;
793 }
794 return this;
795 };
796 // isComplement is optional, defaults to false
797 CanvasKit.SkPath.prototype.trim = function(startT, stopT, isComplement) {
798 if (this._trim(startT, stopT, !!isComplement)) {
799 return this;
800 }
801 return null;
802 };
803
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500804 CanvasKit.SkImage.prototype.encodeToData = function() {
805 if (!arguments.length) {
806 return this._encodeToData();
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400807 }
Kevin Lubick53965c92018-10-11 08:51:55 -0400808
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500809 if (arguments.length === 2) {
810 var a = arguments;
811 return this._encodeToDataWithFormat(a[0], a[1]);
Alexander Khovansky3e119332018-11-15 02:01:19 +0300812 }
813
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500814 throw 'encodeToData expected to take 0 or 2 arguments. Got ' + arguments.length;
815 }
Kevin Lubick1ba9c4d2019-02-22 10:04:06 -0500816
Kevin Lubicka064c282019-04-04 09:28:53 -0400817 CanvasKit.SkImage.prototype.makeShader = function(xTileMode, yTileMode, localMatrix) {
Kevin Lubick6bffe392020-04-02 15:24:15 -0400818 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Kevin Lubick6aa38692020-06-01 11:25:47 -0400819 return this._makeShader(xTileMode, yTileMode, localMatrixPtr);
Kevin Lubicka064c282019-04-04 09:28:53 -0400820 }
821
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400822 CanvasKit.SkImage.prototype.readPixels = function(imageInfo, srcX, srcY) {
823 var rowBytes;
Kevin Lubick319524b2020-01-22 15:29:14 -0500824 // Important to use ["string"] notation here, otherwise the closure compiler will
825 // minify away the colorType.
826 switch (imageInfo["colorType"]) {
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400827 case CanvasKit.ColorType.RGBA_8888:
828 rowBytes = imageInfo.width * 4; // 1 byte per channel == 4 bytes per pixel in 8888
829 break;
830 case CanvasKit.ColorType.RGBA_F32:
831 rowBytes = imageInfo.width * 16; // 4 bytes per channel == 16 bytes per pixel in F32
832 break;
833 default:
834 SkDebug("Colortype not yet supported");
835 return;
836 }
837 var pBytes = rowBytes * imageInfo.height;
838 var pPtr = CanvasKit._malloc(pBytes);
839
840 if (!this._readPixels(imageInfo, pPtr, rowBytes, srcX, srcY)) {
841 SkDebug("Could not read pixels with the given inputs");
842 return null;
843 }
844
845 // Put those pixels into a typed array of the right format and then
846 // make a copy with slice() that we can return.
847 var retVal = null;
Kevin Lubick319524b2020-01-22 15:29:14 -0500848 switch (imageInfo["colorType"]) {
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400849 case CanvasKit.ColorType.RGBA_8888:
Bryce Thomas1fa54042020-01-14 13:46:30 -0800850 retVal = new Uint8Array(CanvasKit.HEAPU8.buffer, pPtr, pBytes).slice();
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400851 break;
852 case CanvasKit.ColorType.RGBA_F32:
Bryce Thomas1fa54042020-01-14 13:46:30 -0800853 retVal = new Float32Array(CanvasKit.HEAPU8.buffer, pPtr, pBytes).slice();
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400854 break;
855 }
856
857 // Free the allocated pixels in the WASM memory
858 CanvasKit._free(pPtr);
859 return retVal;
Kevin Lubick6bffe392020-04-02 15:24:15 -0400860 }
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400861
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400862 // Accepts an array of four numbers in the range of 0-1 representing a 4f color
863 CanvasKit.SkCanvas.prototype.clear = function (color4f) {
Kevin Lubick6aa38692020-06-01 11:25:47 -0400864 var cPtr = copyColorToWasm(color4f);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400865 this._clear(cPtr);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400866 }
867
Kevin Lubickc1d08982020-04-06 13:52:15 -0400868 // concat takes a 3x2, a 3x3, or a 4x4 matrix and upscales it (if needed) to 4x4. This is because
869 // under the hood, SkCanvas uses a 4x4 matrix.
Kevin Lubick6bffe392020-04-02 15:24:15 -0400870 CanvasKit.SkCanvas.prototype.concat = function(matr) {
Kevin Lubickc1d08982020-04-06 13:52:15 -0400871 var matrPtr = copy4x4MatrixToWasm(matr);
Kevin Lubick6bffe392020-04-02 15:24:15 -0400872 this._concat(matrPtr);
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400873 }
874
Kevin Lubickc1d08982020-04-06 13:52:15 -0400875 // Deprecated - just use concat
876 CanvasKit.SkCanvas.prototype.concat44 = CanvasKit.SkCanvas.prototype.concat;
877
Kevin Lubickee91c072019-03-29 10:39:52 -0400878 // atlas is an SkImage, e.g. from CanvasKit.MakeImageFromEncoded
879 // srcRects and dstXforms should be CanvasKit.SkRectBuilder and CanvasKit.RSXFormBuilder
880 // or just arrays of floats in groups of 4.
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400881 // colors, if provided, should be a CanvasKit.SkColorBuilder or array of float colors (arrays of 4 floats)
Kevin Lubickee91c072019-03-29 10:39:52 -0400882 CanvasKit.SkCanvas.prototype.drawAtlas = function(atlas, srcRects, dstXforms, paint,
883 /*optional*/ blendMode, colors) {
884 if (!atlas || !paint || !srcRects || !dstXforms) {
885 SkDebug('Doing nothing since missing a required input');
886 return;
887 }
888 if (srcRects.length !== dstXforms.length || (colors && colors.length !== dstXforms.length)) {
889 SkDebug('Doing nothing since input arrays length mismatches');
Nathaniel Nifonge5d32542020-03-26 09:27:48 -0400890 return;
Kevin Lubickee91c072019-03-29 10:39:52 -0400891 }
892 if (!blendMode) {
893 blendMode = CanvasKit.BlendMode.SrcOver;
894 }
895
896 var srcRectPtr;
897 if (srcRects.build) {
898 srcRectPtr = srcRects.build();
899 } else {
900 srcRectPtr = copy1dArray(srcRects, CanvasKit.HEAPF32);
901 }
902
903 var dstXformPtr;
904 if (dstXforms.build) {
905 dstXformPtr = dstXforms.build();
906 } else {
907 dstXformPtr = copy1dArray(dstXforms, CanvasKit.HEAPF32);
908 }
909
Kevin Lubick6bffe392020-04-02 15:24:15 -0400910 var colorPtr = nullptr;
Kevin Lubickee91c072019-03-29 10:39:52 -0400911 if (colors) {
912 if (colors.build) {
913 colorPtr = colors.build();
914 } else {
Nathaniel Nifonge5d32542020-03-26 09:27:48 -0400915 if (!isCanvasKitColor(colors[0])) {
916 SkDebug('DrawAtlas color argument expected to be CanvasKit.SkRectBuilder or array of ' +
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400917 'float arrays, but got '+colors);
Nathaniel Nifonge5d32542020-03-26 09:27:48 -0400918 return;
919 }
920 // convert here
921 colors = colors.map(toUint32Color);
Kevin Lubickee91c072019-03-29 10:39:52 -0400922 colorPtr = copy1dArray(colors, CanvasKit.HEAPU32);
923 }
924 }
925
926 this._drawAtlas(atlas, dstXformPtr, srcRectPtr, colorPtr, dstXforms.length,
927 blendMode, paint);
928
929 if (srcRectPtr && !srcRects.build) {
Kevin Lubickcf118922020-05-28 14:43:38 -0400930 freeArraysThatAreNotMallocedByUsers(srcRectPtr, srcRects);
Kevin Lubickee91c072019-03-29 10:39:52 -0400931 }
932 if (dstXformPtr && !dstXforms.build) {
Kevin Lubickcf118922020-05-28 14:43:38 -0400933 freeArraysThatAreNotMallocedByUsers(dstXformPtr, dstXforms);
Kevin Lubickee91c072019-03-29 10:39:52 -0400934 }
935 if (colorPtr && !colors.build) {
Kevin Lubickcf118922020-05-28 14:43:38 -0400936 freeArraysThatAreNotMallocedByUsers(colorPtr, colors);
Kevin Lubickee91c072019-03-29 10:39:52 -0400937 }
938
939 }
940
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400941 CanvasKit.SkCanvas.prototype.drawColor = function (color4f, mode) {
Kevin Lubick6aa38692020-06-01 11:25:47 -0400942 var cPtr = copyColorToWasm(color4f);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400943 if (mode !== undefined) {
944 this._drawColor(cPtr, mode);
945 } else {
946 this._drawColor(cPtr);
947 }
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400948 }
949
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500950 // points is either an array of [x, y] where x and y are numbers or
951 // a typed array from Malloc where the even indices will be treated
952 // as x coordinates and the odd indices will be treated as y coordinates.
953 CanvasKit.SkCanvas.prototype.drawPoints = function(mode, points, paint) {
954 var ptr;
955 var n;
956 // This was created with CanvasKit.Malloc, so assume the user has
957 // already been filled with data.
958 if (points['_ck']) {
959 ptr = points.byteOffset;
960 n = points.length/2;
961 } else {
962 ptr = copy2dArray(points, CanvasKit.HEAPF32);
963 n = points.length;
964 }
965 this._drawPoints(mode, ptr, n, paint);
Kevin Lubickcf118922020-05-28 14:43:38 -0400966 freeArraysThatAreNotMallocedByUsers(ptr, points);
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500967 }
968
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400969 CanvasKit.SkCanvas.prototype.drawShadow = function(path, zPlaneParams, lightPos, lightRadius, ambientColor, spotColor, flags) {
Kevin Lubick6aa38692020-06-01 11:25:47 -0400970 var ambiPtr = copyColorToWasmNoScratch(ambientColor);
971 var spotPtr = copyColorToWasmNoScratch(spotColor);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400972 this._drawShadow(path, zPlaneParams, lightPos, lightRadius, ambiPtr, spotPtr, flags);
Kevin Lubickcf118922020-05-28 14:43:38 -0400973 freeArraysThatAreNotMallocedByUsers(ambiPtr, ambientColor);
974 freeArraysThatAreNotMallocedByUsers(spotPtr, spotColor);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400975 }
976
Kevin Lubickc1d08982020-04-06 13:52:15 -0400977 // getLocalToDevice returns a 4x4 matrix.
978 CanvasKit.SkCanvas.prototype.getLocalToDevice = function() {
Kevin Lubickc1d08982020-04-06 13:52:15 -0400979 // _getLocalToDevice will copy the values into the pointer.
Kevin Lubick6aa38692020-06-01 11:25:47 -0400980 this._getLocalToDevice(_scratch4x4MatrixPtr);
981 return copy4x4MatrixFromWasm(_scratch4x4MatrixPtr);
Kevin Lubickc1d08982020-04-06 13:52:15 -0400982 }
983
Nathaniel Nifong00de91c2020-05-06 16:22:33 -0400984 // findMarkedCTM returns a 4x4 matrix, or null if a matrix was not found at
985 // the provided marker.
986 CanvasKit.SkCanvas.prototype.findMarkedCTM = function(marker) {
Nathaniel Nifong00de91c2020-05-06 16:22:33 -0400987 // _getLocalToDevice will copy the values into the pointer.
Kevin Lubick6aa38692020-06-01 11:25:47 -0400988 var found = this._findMarkedCTM(marker, _scratch4x4MatrixPtr);
Nathaniel Nifong00de91c2020-05-06 16:22:33 -0400989 if (!found) {
990 return null;
991 }
Kevin Lubick6aa38692020-06-01 11:25:47 -0400992 return copy4x4MatrixFromWasm(_scratch4x4MatrixPtr);
Nathaniel Nifong00de91c2020-05-06 16:22:33 -0400993 }
994
Kevin Lubickc1d08982020-04-06 13:52:15 -0400995 // getTotalMatrix returns the current matrix as a 3x3 matrix.
Kevin Lubick6bffe392020-04-02 15:24:15 -0400996 CanvasKit.SkCanvas.prototype.getTotalMatrix = function() {
Kevin Lubick6bffe392020-04-02 15:24:15 -0400997 // _getTotalMatrix will copy the values into the pointer.
Kevin Lubick6aa38692020-06-01 11:25:47 -0400998 this._getTotalMatrix(_scratch3x3MatrixPtr);
Kevin Lubick6bffe392020-04-02 15:24:15 -0400999 // read them out into an array. TODO(kjlubick): If we change SkMatrix to be
1000 // typedArrays, then we should return a typed array here too.
1001 var rv = new Array(9);
1002 for (var i = 0; i < 9; i++) {
Kevin Lubick6aa38692020-06-01 11:25:47 -04001003 rv[i] = CanvasKit.HEAPF32[_scratch3x3MatrixPtr/4 + i]; // divide by 4 to "cast" to float.
Kevin Lubick6bffe392020-04-02 15:24:15 -04001004 }
Kevin Lubick6bffe392020-04-02 15:24:15 -04001005 return rv;
1006 }
1007
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001008 // returns Uint8Array
1009 CanvasKit.SkCanvas.prototype.readPixels = function(x, y, w, h, alphaType,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001010 colorType, colorSpace, dstRowBytes) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001011 // supply defaults (which are compatible with HTMLCanvas's getImageData)
1012 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
1013 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001014 colorSpace = colorSpace || CanvasKit.SkColorSpace.SRGB;
1015 var pixBytes = 4;
1016 if (colorType === CanvasKit.ColorType.RGBA_F16) {
1017 pixBytes = 8;
1018 }
1019 dstRowBytes = dstRowBytes || (pixBytes * w);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001020
1021 var len = h * dstRowBytes
1022 var pptr = CanvasKit._malloc(len);
1023 var ok = this._readPixels({
1024 'width': w,
1025 'height': h,
Kevin Lubick52b9f372018-12-04 13:57:36 -05001026 'colorType': colorType,
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001027 'alphaType': alphaType,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001028 'colorSpace': colorSpace,
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001029 }, pptr, dstRowBytes, x, y);
1030 if (!ok) {
1031 CanvasKit._free(pptr);
1032 return null;
1033 }
1034
1035 // The first typed array is just a view into memory. Because we will
1036 // be free-ing that, we call slice to make a persistent copy.
Bryce Thomas1fa54042020-01-14 13:46:30 -08001037 var pixels = new Uint8Array(CanvasKit.HEAPU8.buffer, pptr, len).slice();
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001038 CanvasKit._free(pptr);
1039 return pixels;
1040 }
1041
Kevin Lubickcf118922020-05-28 14:43:38 -04001042 // pixels should be a Uint8Array or a plain JS array.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001043 CanvasKit.SkCanvas.prototype.writePixels = function(pixels, srcWidth, srcHeight,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001044 destX, destY, alphaType, colorType, colorSpace) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001045 if (pixels.byteLength % (srcWidth * srcHeight)) {
1046 throw 'pixels length must be a multiple of the srcWidth * srcHeight';
1047 }
1048 var bytesPerPixel = pixels.byteLength / (srcWidth * srcHeight);
1049 // supply defaults (which are compatible with HTMLCanvas's putImageData)
1050 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
1051 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001052 colorSpace = colorSpace || CanvasKit.SkColorSpace.SRGB;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001053 var srcRowBytes = bytesPerPixel * srcWidth;
1054
Kevin Lubickcf118922020-05-28 14:43:38 -04001055 var pptr = copy1dArray(pixels, CanvasKit.HEAPU8);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001056 var ok = this._writePixels({
1057 'width': srcWidth,
1058 'height': srcHeight,
1059 'colorType': colorType,
1060 'alphaType': alphaType,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001061 'colorSpace': colorSpace,
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001062 }, pptr, srcRowBytes, destX, destY);
1063
Kevin Lubickcf118922020-05-28 14:43:38 -04001064 freeArraysThatAreNotMallocedByUsers(pptr, pixels);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001065 return ok;
Kevin Lubick52b9f372018-12-04 13:57:36 -05001066 }
1067
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001068 CanvasKit.SkColorFilter.MakeBlend = function(color4f, mode) {
Kevin Lubick6aa38692020-06-01 11:25:47 -04001069 var cPtr = copyColorToWasm(color4f);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001070 var result = CanvasKit.SkColorFilter._MakeBlend(cPtr, mode);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001071 return result;
1072 }
1073
Kevin Lubickd3729342019-09-12 11:11:25 -04001074 // colorMatrix is an SkColorMatrix (e.g. Float32Array of length 20)
1075 CanvasKit.SkColorFilter.MakeMatrix = function(colorMatrix) {
1076 if (!colorMatrix || colorMatrix.length !== 20) {
Kevin Lubick6bffe392020-04-02 15:24:15 -04001077 throw 'invalid color matrix';
Kevin Lubickd3729342019-09-12 11:11:25 -04001078 }
1079 var fptr = copy1dArray(colorMatrix, CanvasKit.HEAPF32);
1080 // We know skia memcopies the floats, so we can free our memory after the call returns.
1081 var m = CanvasKit.SkColorFilter._makeMatrix(fptr);
Kevin Lubickcf118922020-05-28 14:43:38 -04001082 freeArraysThatAreNotMallocedByUsers(fptr, colorMatrix);
Kevin Lubickd3729342019-09-12 11:11:25 -04001083 return m;
1084 }
1085
Kevin Lubick6bffe392020-04-02 15:24:15 -04001086 CanvasKit.SkImageFilter.MakeMatrixTransform = function(matr, filterQuality, input) {
1087 var matrPtr = copy3x3MatrixToWasm(matr);
Kevin Lubick6aa38692020-06-01 11:25:47 -04001088 return CanvasKit.SkImageFilter._MakeMatrixTransform(matrPtr, filterQuality, input);
Kevin Lubick6bffe392020-04-02 15:24:15 -04001089 }
1090
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001091 CanvasKit.SkPaint.prototype.getColor = function() {
Kevin Lubick6aa38692020-06-01 11:25:47 -04001092 this._getColor(_scratchColorPtr);
1093 return copyColorFromWasm(_scratchColorPtr);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001094 }
1095
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001096 CanvasKit.SkPaint.prototype.setColor = function(color4f, colorSpace) {
1097 colorSpace = colorSpace || null; // null will be replaced with sRGB in the C++ method.
1098 // emscripten wouldn't bind undefined to the sk_sp<SkColorSpace> expected here.
Kevin Lubick6aa38692020-06-01 11:25:47 -04001099 var cPtr = copyColorToWasm(color4f);
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001100 this._setColor(cPtr, colorSpace);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001101 }
1102
Kevin Lubickcc13fd32019-04-05 13:00:01 -04001103 CanvasKit.SkSurface.prototype.captureFrameAsSkPicture = function(drawFrame) {
1104 // Set up SkPictureRecorder
1105 var spr = new CanvasKit.SkPictureRecorder();
1106 var canvas = spr.beginRecording(
1107 CanvasKit.LTRBRect(0, 0, this.width(), this.height()));
1108 drawFrame(canvas);
1109 var pic = spr.finishRecordingAsPicture();
1110 spr.delete();
1111 // TODO: do we need to clean up the memory for canvas?
1112 // If we delete it here, saveAsFile doesn't work correctly.
1113 return pic;
1114 }
1115
Kevin Lubick359a7e32019-03-19 09:34:37 -04001116 CanvasKit.SkSurface.prototype.requestAnimationFrame = function(callback, dirtyRect) {
1117 if (!this._cached_canvas) {
1118 this._cached_canvas = this.getCanvas();
1119 }
1120 window.requestAnimationFrame(function() {
Kevin Lubick39026282019-03-28 12:46:40 -04001121 if (this._context !== undefined) {
1122 CanvasKit.setCurrentContext(this._context);
1123 }
Kevin Lubick359a7e32019-03-19 09:34:37 -04001124
1125 callback(this._cached_canvas);
1126
Bryce Thomas2c5b8562020-01-22 13:49:41 -08001127 // We do not dispose() of the SkSurface here, as the client will typically
1128 // call requestAnimationFrame again from within the supplied callback.
1129 // For drawing a single frame, prefer drawOnce().
Bryce Thomas9331ca02020-05-29 16:51:21 -07001130 this.flush(dirtyRect);
Kevin Lubick359a7e32019-03-19 09:34:37 -04001131 }.bind(this));
1132 }
1133
Kevin Lubick52379332020-01-27 10:01:25 -05001134 // drawOnce will dispose of the surface after drawing the frame using the provided
1135 // callback.
Bryce Thomas2c5b8562020-01-22 13:49:41 -08001136 CanvasKit.SkSurface.prototype.drawOnce = function(callback, dirtyRect) {
1137 if (!this._cached_canvas) {
1138 this._cached_canvas = this.getCanvas();
1139 }
1140 window.requestAnimationFrame(function() {
1141 if (this._context !== undefined) {
1142 CanvasKit.setCurrentContext(this._context);
1143 }
1144 callback(this._cached_canvas);
1145
Bryce Thomas9331ca02020-05-29 16:51:21 -07001146 this.flush(dirtyRect);
Bryce Thomas2c5b8562020-01-22 13:49:41 -08001147 this.dispose();
1148 }.bind(this));
1149 }
1150
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001151 CanvasKit.SkPathEffect.MakeDash = function(intervals, phase) {
1152 if (!phase) {
1153 phase = 0;
1154 }
1155 if (!intervals.length || intervals.length % 2 === 1) {
1156 throw 'Intervals array must have even length';
1157 }
1158 var ptr = copy1dArray(intervals, CanvasKit.HEAPF32);
Kevin Lubickf279c632020-03-18 09:53:55 -04001159 var dpe = CanvasKit.SkPathEffect._MakeDash(ptr, intervals.length, phase);
Kevin Lubickcf118922020-05-28 14:43:38 -04001160 freeArraysThatAreNotMallocedByUsers(ptr, intervals);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001161 return dpe;
1162 }
1163
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001164 CanvasKit.SkShader.Color = function(color4f, colorSpace) {
1165 colorSpace = colorSpace || null
Kevin Lubick6aa38692020-06-01 11:25:47 -04001166 var cPtr = copyColorToWasm(color4f);
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001167 var result = CanvasKit.SkShader._Color(cPtr, colorSpace);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001168 return result;
1169 }
1170
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001171 CanvasKit.SkShader.MakeLinearGradient = function(start, end, colors, pos, mode, localMatrix, flags, colorSpace) {
1172 colorSpace = colorSpace || null
Nathaniel Nifonge5d32542020-03-26 09:27:48 -04001173 var colorPtr = copy2dArray(colors, CanvasKit.HEAPF32);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001174 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
1175 flags = flags || 0;
Kevin Lubick6bffe392020-04-02 15:24:15 -04001176 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001177
Kevin Lubick6bffe392020-04-02 15:24:15 -04001178 var lgs = CanvasKit._MakeLinearGradientShader(start, end, colorPtr, posPtr,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001179 colors.length, mode, flags, localMatrixPtr, colorSpace);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001180
1181 CanvasKit._free(colorPtr);
Kevin Lubickcf118922020-05-28 14:43:38 -04001182 freeArraysThatAreNotMallocedByUsers(posPtr, pos);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001183 return lgs;
1184 }
1185
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001186 CanvasKit.SkShader.MakeRadialGradient = function(center, radius, colors, pos, mode, localMatrix, flags, colorSpace) {
1187 colorSpace = colorSpace || null
Nathaniel Nifonge5d32542020-03-26 09:27:48 -04001188 var colorPtr = copy2dArray(colors, CanvasKit.HEAPF32);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001189 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
1190 flags = flags || 0;
Kevin Lubick6bffe392020-04-02 15:24:15 -04001191 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001192
Kevin Lubick6bffe392020-04-02 15:24:15 -04001193 var rgs = CanvasKit._MakeRadialGradientShader(center, radius, colorPtr, posPtr,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001194 colors.length, mode, flags, localMatrixPtr, colorSpace);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001195
1196 CanvasKit._free(colorPtr);
Kevin Lubickcf118922020-05-28 14:43:38 -04001197 freeArraysThatAreNotMallocedByUsers(posPtr, pos);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001198 return rgs;
1199 }
1200
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001201 CanvasKit.SkShader.MakeSweepGradient = function(cx, cy, colors, pos, mode, localMatrix, flags, startAngle, endAngle, colorSpace) {
1202 colorSpace = colorSpace || null
Nathaniel Nifonge5d32542020-03-26 09:27:48 -04001203 var colorPtr = copy2dArray(colors, CanvasKit.HEAPF32);
Dan Field3d44f732020-03-16 09:17:30 -07001204 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
1205 flags = flags || 0;
1206 startAngle = startAngle || 0;
1207 endAngle = endAngle || 360;
Kevin Lubick6bffe392020-04-02 15:24:15 -04001208 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Dan Field3d44f732020-03-16 09:17:30 -07001209
1210 var sgs = CanvasKit._MakeSweepGradientShader(cx, cy, colorPtr, posPtr,
Kevin Lubick6bffe392020-04-02 15:24:15 -04001211 colors.length, mode,
1212 startAngle, endAngle, flags,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001213 localMatrixPtr, colorSpace);
Dan Field3d44f732020-03-16 09:17:30 -07001214
1215 CanvasKit._free(colorPtr);
Kevin Lubickcf118922020-05-28 14:43:38 -04001216 freeArraysThatAreNotMallocedByUsers(posPtr, pos);
Dan Field3d44f732020-03-16 09:17:30 -07001217 return sgs;
1218 }
1219
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001220 CanvasKit.SkShader.MakeTwoPointConicalGradient = function(start, startRadius, end, endRadius,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001221 colors, pos, mode, localMatrix, flags, colorSpace) {
1222 colorSpace = colorSpace || null
Nathaniel Nifonge5d32542020-03-26 09:27:48 -04001223 var colorPtr = copy2dArray(colors, CanvasKit.HEAPF32);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001224 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
1225 flags = flags || 0;
Kevin Lubick6bffe392020-04-02 15:24:15 -04001226 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001227
Kevin Lubick6bffe392020-04-02 15:24:15 -04001228 var rgs = CanvasKit._MakeTwoPointConicalGradientShader(
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001229 start, startRadius, end, endRadius,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001230 colorPtr, posPtr, colors.length, mode, flags, localMatrixPtr, colorSpace);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001231
1232 CanvasKit._free(colorPtr);
Kevin Lubickcf118922020-05-28 14:43:38 -04001233 freeArraysThatAreNotMallocedByUsers(posPtr, pos);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001234 return rgs;
1235 }
1236
1237 // temporary support for deprecated names.
Nathaniel Nifongc8f95e22020-03-09 11:52:51 -04001238 CanvasKit.MakeSkDashPathEffect = CanvasKit.SkPathEffect.MakeDash;
1239 CanvasKit.MakeLinearGradientShader = CanvasKit.SkShader.MakeLinearGradient;
1240 CanvasKit.MakeRadialGradientShader = CanvasKit.SkShader.MakeRadialGradient;
1241 CanvasKit.MakeTwoPointConicalGradientShader = CanvasKit.SkShader.MakeTwoPointConicalGradient;
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001242
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001243 // Run through the JS files that are added at compile time.
1244 if (CanvasKit._extraInitializations) {
1245 CanvasKit._extraInitializations.forEach(function(init) {
1246 init();
1247 });
Kevin Lubickeb2f6b02018-11-29 15:07:02 -05001248 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001249}; // end CanvasKit.onRuntimeInitialized, that is, anything changing prototypes or dynamic.
Kevin Lubickeb2f6b02018-11-29 15:07:02 -05001250
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001251// Accepts an object holding two canvaskit colors.
1252// {
1253// ambient: {r, g, b, a},
1254// spot: {r, g, b, a},
1255// }
1256// Returns the same format
1257CanvasKit.computeTonalColors = function(tonalColors) {
Kevin Lubick6aa38692020-06-01 11:25:47 -04001258 var cPtrAmbi = copyColorToWasmNoScratch(tonalColors['ambient']);
1259 var cPtrSpot = copyColorToWasmNoScratch(tonalColors['spot']);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001260 this._computeTonalColors(cPtrAmbi, cPtrSpot);
1261 var result = {
1262 'ambient': copyColorFromWasm(cPtrAmbi),
1263 'spot': copyColorFromWasm(cPtrSpot),
1264 }
Kevin Lubick6aa38692020-06-01 11:25:47 -04001265 freeArraysThatAreNotMallocedByUsers(cPtrAmbi);
1266 freeArraysThatAreNotMallocedByUsers(cPtrSpot);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001267 return result;
1268}
1269
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001270CanvasKit.LTRBRect = function(l, t, r, b) {
1271 return {
1272 fLeft: l,
1273 fTop: t,
1274 fRight: r,
1275 fBottom: b,
1276 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -05001277}
1278
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001279CanvasKit.XYWHRect = function(x, y, w, h) {
1280 return {
1281 fLeft: x,
1282 fTop: y,
1283 fRight: x+w,
1284 fBottom: y+h,
1285 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -05001286}
1287
Kevin Lubick7d644e12019-09-11 14:22:22 -04001288// RRectXY returns an RRect with the given rect and a radiusX and radiusY for
1289// all 4 corners.
1290CanvasKit.RRectXY = function(rect, rx, ry) {
1291 return {
1292 rect: rect,
1293 rx1: rx,
1294 ry1: ry,
1295 rx2: rx,
1296 ry2: ry,
1297 rx3: rx,
1298 ry3: ry,
1299 rx4: rx,
1300 ry4: ry,
1301 };
1302}
1303
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001304CanvasKit.MakePathFromCmds = function(cmds) {
1305 var ptrLen = loadCmdsTypedArray(cmds);
1306 var path = CanvasKit._MakePathFromCmds(ptrLen[0], ptrLen[1]);
1307 CanvasKit._free(ptrLen[0]);
1308 return path;
1309}
1310
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001311// data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
Kevin Lubick6b921b72019-09-18 16:18:17 -04001312CanvasKit.MakeAnimatedImageFromEncoded = function(data) {
1313 data = new Uint8Array(data);
1314
1315 var iptr = CanvasKit._malloc(data.byteLength);
1316 CanvasKit.HEAPU8.set(data, iptr);
1317 var img = CanvasKit._decodeAnimatedImage(iptr, data.byteLength);
1318 if (!img) {
1319 SkDebug('Could not decode animated image');
1320 return null;
1321 }
1322 return img;
1323}
1324
1325// data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001326CanvasKit.MakeImageFromEncoded = function(data) {
1327 data = new Uint8Array(data);
1328
1329 var iptr = CanvasKit._malloc(data.byteLength);
1330 CanvasKit.HEAPU8.set(data, iptr);
1331 var img = CanvasKit._decodeImage(iptr, data.byteLength);
1332 if (!img) {
1333 SkDebug('Could not decode image');
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001334 return null;
1335 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001336 return img;
1337}
1338
Kevin Lubickeda0b432019-12-02 08:26:48 -05001339// pixels must be a Uint8Array with bytes representing the pixel values
1340// (e.g. each set of 4 bytes could represent RGBA values for a single pixel).
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001341CanvasKit.MakeImage = function(pixels, width, height, alphaType, colorType, colorSpace) {
Kevin Lubickeda0b432019-12-02 08:26:48 -05001342 var bytesPerPixel = pixels.length / (width * height);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001343 var info = {
1344 'width': width,
1345 'height': height,
1346 'alphaType': alphaType,
1347 'colorType': colorType,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001348 'colorSpace': colorSpace,
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001349 };
Kevin Lubickeda0b432019-12-02 08:26:48 -05001350 var pptr = copy1dArray(pixels, CanvasKit.HEAPU8);
1351 // No need to _free pptr, Image takes it with SkData::MakeFromMalloc
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001352
Kevin Lubickeda0b432019-12-02 08:26:48 -05001353 return CanvasKit._MakeImage(info, pptr, pixels.length, width * bytesPerPixel);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001354}
1355
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001356// colors is an array of float color arrays
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001357CanvasKit.MakeSkVertices = function(mode, positions, textureCoordinates, colors,
Mike Reed5caf9352020-03-02 14:57:09 -05001358 indices, isVolatile) {
Kevin Lubickb3574c92019-03-06 08:25:36 -05001359 // Default isVolitile to true if not set
1360 isVolatile = isVolatile === undefined ? true : isVolatile;
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001361 var idxCount = (indices && indices.length) || 0;
1362
1363 var flags = 0;
1364 // These flags are from SkVertices.h and should be kept in sync with those.
1365 if (textureCoordinates && textureCoordinates.length) {
1366 flags |= (1 << 0);
1367 }
1368 if (colors && colors.length) {
1369 flags |= (1 << 1);
1370 }
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001371 if (!isVolatile) {
Mike Reed5caf9352020-03-02 14:57:09 -05001372 flags |= (1 << 2);
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001373 }
1374
1375 var builder = new CanvasKit._SkVerticesBuilder(mode, positions.length, idxCount, flags);
1376
1377 copy2dArray(positions, CanvasKit.HEAPF32, builder.positions());
1378 if (builder.texCoords()) {
1379 copy2dArray(textureCoordinates, CanvasKit.HEAPF32, builder.texCoords());
1380 }
1381 if (builder.colors()) {
Nathaniel Nifonge5d32542020-03-26 09:27:48 -04001382 // Convert from canvaskit 4f colors to 32 bit uint colors which builder supports.
1383 copy1dArray(colors.map(toUint32Color), CanvasKit.HEAPU32, builder.colors());
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001384 }
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001385 if (builder.indices()) {
1386 copy1dArray(indices, CanvasKit.HEAPU16, builder.indices());
1387 }
Kevin Lubickb3574c92019-03-06 08:25:36 -05001388
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001389 var idxCount = (indices && indices.length) || 0;
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001390 // Create the vertices, which owns the memory that the builder had allocated.
1391 return builder.detach();
Kevin Lubicka4f218d2020-01-14 08:39:09 -05001392};