blob: 7248606597c755d648d498972052a98c161a4d63 [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
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -040011 // Create single copies of all three supported color spaces
12 // These are sk_sp<SkColorSpace>
13 CanvasKit.SkColorSpace.SRGB = CanvasKit.SkColorSpace._MakeSRGB();
14 CanvasKit.SkColorSpace.DISPLAY_P3 = CanvasKit.SkColorSpace._MakeDisplayP3();
15 CanvasKit.SkColorSpace.ADOBE_RGB = CanvasKit.SkColorSpace._MakeAdobeRGB();
16
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050017 // Add some helpers for matrices. This is ported from SkMatrix.cpp
18 // to save complexity and overhead of going back and forth between
19 // C++ and JS layers.
20 // I would have liked to use something like DOMMatrix, except it
21 // isn't widely supported (would need polyfills) and it doesn't
22 // have a mapPoints() function (which could maybe be tacked on here).
23 // If DOMMatrix catches on, it would be worth re-considering this usage.
24 CanvasKit.SkMatrix = {};
Nathaniel Nifong77798b42020-02-21 17:15:22 -050025 function sdot() { // to be called with an even number of scalar args
26 var acc = 0;
27 for (var i=0; i < arguments.length-1; i+=2) {
28 acc += arguments[i] * arguments[i+1];
29 }
30 return acc;
31 }
32
33
34 // Private general matrix functions used in both 3x3s and 4x4s.
35 // Return a square identity matrix of size n.
36 var identityN = function(n) {
37 var size = n*n;
38 var m = new Array(size);
39 while(size--) {
40 m[size] = size%(n+1) == 0 ? 1.0 : 0.0;
41 }
42 return m;
43 }
44
45 // Stride, a function for compactly representing several ways of copying an array into another.
46 // Write vector `v` into matrix `m`. `m` is a matrix encoded as an array in row-major
47 // order. Its width is passed as `width`. `v` is an array with length < (m.length/width).
48 // An element of `v` is copied into `m` starting at `offset` and moving `colStride` cols right
49 // each row.
50 //
51 // For example, a width of 4, offset of 3, and stride of -1 would put the vector here.
52 // _ _ 0 _
53 // _ 1 _ _
54 // 2 _ _ _
55 // _ _ _ 3
56 //
57 var stride = function(v, m, width, offset, colStride) {
58 for (var i=0; i<v.length; i++) {
59 m[i * width + // column
60 (i * colStride + offset + width) % width // row
61 ] = v[i];
62 }
63 return m;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050064 }
65
66 CanvasKit.SkMatrix.identity = function() {
Nathaniel Nifong77798b42020-02-21 17:15:22 -050067 return identityN(3);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050068 };
69
70 // Return the inverse (if it exists) of this matrix.
Kevin Lubick9b56cea2020-04-06 08:16:18 -040071 // Otherwise, return null.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050072 CanvasKit.SkMatrix.invert = function(m) {
Nathaniel Nifong77798b42020-02-21 17:15:22 -050073 // Find the determinant by the sarrus rule. https://en.wikipedia.org/wiki/Rule_of_Sarrus
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050074 var det = m[0]*m[4]*m[8] + m[1]*m[5]*m[6] + m[2]*m[3]*m[7]
75 - m[2]*m[4]*m[6] - m[1]*m[3]*m[8] - m[0]*m[5]*m[7];
76 if (!det) {
77 SkDebug('Warning, uninvertible matrix');
Nathaniel Nifong77798b42020-02-21 17:15:22 -050078 return null;
Kevin Lubick1a05fce2018-11-20 12:51:16 -050079 }
Nathaniel Nifong77798b42020-02-21 17:15:22 -050080 // Return the inverse by the formula adj(m)/det.
81 // adj (adjugate) of a 3x3 is the transpose of it's cofactor matrix.
82 // a cofactor matrix is a matrix where each term is +-det(N) where matrix N is the 2x2 formed
83 // by removing the row and column we're currently setting from the source.
84 // the sign alternates in a checkerboard pattern with a `+` at the top left.
85 // that's all been combined here into one expression.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050086 return [
87 (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,
88 (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,
89 (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,
90 ];
91 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -050092
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050093 // Maps the given points according to the passed in matrix.
94 // Results are done in place.
95 // See SkMatrix.h::mapPoints for the docs on the math.
96 CanvasKit.SkMatrix.mapPoints = function(matrix, ptArr) {
Nathaniel Nifong77798b42020-02-21 17:15:22 -050097 if (skIsDebug && (ptArr.length % 2)) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050098 throw 'mapPoints requires an even length arr';
Kevin Lubickb9db3902018-11-26 11:47:54 -050099 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500100 for (var i = 0; i < ptArr.length; i+=2) {
101 var x = ptArr[i], y = ptArr[i+1];
102 // Gx+Hy+I
103 var denom = matrix[6]*x + matrix[7]*y + matrix[8];
104 // Ax+By+C
105 var xTrans = matrix[0]*x + matrix[1]*y + matrix[2];
106 // Dx+Ey+F
107 var yTrans = matrix[3]*x + matrix[4]*y + matrix[5];
108 ptArr[i] = xTrans/denom;
109 ptArr[i+1] = yTrans/denom;
110 }
111 return ptArr;
112 };
Kevin Lubickb9db3902018-11-26 11:47:54 -0500113
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500114 function isnumber(val) { return val !== NaN; };
115
Kevin Lubickc89ca0b2020-04-02 14:30:00 -0400116 // generalized iterative algorithm for multiplying two matrices.
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500117 function multiply(m1, m2, size) {
118
119 if (skIsDebug && (!m1.every(isnumber) || !m2.every(isnumber))) {
120 throw 'Some members of matrices are NaN m1='+m1+', m2='+m2+'';
121 }
122 if (skIsDebug && (m1.length !== m2.length)) {
123 throw 'Undefined for matrices of different sizes. m1.length='+m1.length+', m2.length='+m2.length;
124 }
125 if (skIsDebug && (size*size !== m1.length)) {
126 throw 'Undefined for non-square matrices. array size was '+size;
127 }
128
129 var result = Array(m1.length);
130 for (var r = 0; r < size; r++) {
131 for (var c = 0; c < size; c++) {
132 // accumulate a sum of m1[r,k]*m2[k, c]
133 var acc = 0;
134 for (var k = 0; k < size; k++) {
135 acc += m1[size * r + k] * m2[size * k + c];
136 }
137 result[r * size + c] = acc;
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500138 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500139 }
140 return result;
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500141 };
142
143 // Accept an integer indicating the size of the matrices being multiplied (3 for 3x3), and any
144 // number of matrices following it.
145 function multiplyMany(size, listOfMatrices) {
146 if (skIsDebug && (listOfMatrices.length < 2)) {
147 throw 'multiplication expected two or more matrices';
148 }
149 var result = multiply(listOfMatrices[0], listOfMatrices[1], size);
150 var next = 2;
151 while (next < listOfMatrices.length) {
152 result = multiply(result, listOfMatrices[next], size);
153 next++;
154 }
155 return result;
156 };
157
158 // Accept any number 3x3 of matrices as arguments, multiply them together.
Kevin Lubick9e2d3842020-04-01 13:42:15 -0400159 // Matrix multiplication is associative but not commutative. the order of the arguments
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500160 // matters, but it does not matter that this implementation multiplies them left to right.
161 CanvasKit.SkMatrix.multiply = function() {
162 return multiplyMany(3, arguments);
163 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500164
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500165 // Return a matrix representing a rotation by n radians.
166 // px, py optionally say which point the rotation should be around
167 // with the default being (0, 0);
168 CanvasKit.SkMatrix.rotated = function(radians, px, py) {
169 px = px || 0;
170 py = py || 0;
171 var sinV = Math.sin(radians);
172 var cosV = Math.cos(radians);
173 return [
174 cosV, -sinV, sdot( sinV, py, 1 - cosV, px),
175 sinV, cosV, sdot(-sinV, px, 1 - cosV, py),
176 0, 0, 1,
177 ];
178 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400179
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500180 CanvasKit.SkMatrix.scaled = function(sx, sy, px, py) {
181 px = px || 0;
182 py = py || 0;
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500183 var m = stride([sx, sy], identityN(3), 3, 0, 1);
184 return stride([px-sx*px, py-sy*py], m, 3, 2, 0);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500185 };
Kevin Lubickda3d8ac2019-01-07 11:08:55 -0500186
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500187 CanvasKit.SkMatrix.skewed = function(kx, ky, px, py) {
188 px = px || 0;
189 py = py || 0;
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500190 var m = stride([kx, ky], identityN(3), 3, 1, -1);
191 return stride([-kx*px, -ky*py], m, 3, 2, 0);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500192 };
Alexander Khovansky3e119332018-11-15 02:01:19 +0300193
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500194 CanvasKit.SkMatrix.translated = function(dx, dy) {
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500195 return stride(arguments, identityN(3), 3, 2, 0);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500196 };
Kevin Lubick1646e7d2018-12-07 13:03:08 -0500197
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500198 // Functions for manipulating vectors.
199 // Loosely based off of SkV3 in SkM44.h but skia also has SkVec2 and Skv4. This combines them and
200 // works on vectors of any length.
201 CanvasKit.SkVector = {};
202 CanvasKit.SkVector.dot = function(a, b) {
203 if (skIsDebug && (a.length !== b.length)) {
204 throw 'Cannot perform dot product on arrays of different length ('+a.length+' vs '+b.length+')';
205 }
206 return a.map(function(v, i) { return v*b[i] }).reduce(function(acc, cur) { return acc + cur; });
207 }
208 CanvasKit.SkVector.lengthSquared = function(v) {
209 return CanvasKit.SkVector.dot(v, v);
210 }
211 CanvasKit.SkVector.length = function(v) {
212 return Math.sqrt(CanvasKit.SkVector.lengthSquared(v));
213 }
214 CanvasKit.SkVector.mulScalar = function(v, s) {
215 return v.map(function(i) { return i*s });
216 }
217 CanvasKit.SkVector.add = function(a, b) {
218 return a.map(function(v, i) { return v+b[i] });
219 }
220 CanvasKit.SkVector.sub = function(a, b) {
221 return a.map(function(v, i) { return v-b[i]; });
222 }
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500223 CanvasKit.SkVector.dist = function(a, b) {
224 return CanvasKit.SkVector.length(CanvasKit.SkVector.sub(a, b));
225 }
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500226 CanvasKit.SkVector.normalize = function(v) {
227 return CanvasKit.SkVector.mulScalar(v, 1/CanvasKit.SkVector.length(v));
228 }
229 CanvasKit.SkVector.cross = function(a, b) {
230 if (skIsDebug && (a.length !== 3 || a.length !== 3)) {
231 throw 'Cross product is only defined for 3-dimensional vectors (a.length='+a.length+', b.length='+b.length+')';
232 }
233 return [
234 a[1]*b[2] - a[2]*b[1],
235 a[2]*b[0] - a[0]*b[2],
236 a[0]*b[1] - a[1]*b[0],
237 ];
238 }
239
Kevin Lubickc1d08982020-04-06 13:52:15 -0400240 // Functions for creating and manipulating (row-major) 4x4 matrices. Accepted in place of
241 // SkM44 in canvas methods, for the same reasons as the 3x3 matrices above.
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500242 // ported from C++ code in SkM44.cpp
243 CanvasKit.SkM44 = {};
244 // Create a 4x4 identity matrix
245 CanvasKit.SkM44.identity = function() {
246 return identityN(4);
247 }
248
249 // Anything named vec below is an array of length 3 representing a vector/point in 3D space.
250 // Create a 4x4 matrix representing a translate by the provided 3-vec
251 CanvasKit.SkM44.translated = function(vec) {
252 return stride(vec, identityN(4), 4, 3, 0);
253 }
254 // Create a 4x4 matrix representing a scaling by the provided 3-vec
255 CanvasKit.SkM44.scaled = function(vec) {
256 return stride(vec, identityN(4), 4, 0, 1);
257 }
258 // Create a 4x4 matrix representing a rotation about the provided axis 3-vec.
259 // axis does not need to be normalized.
260 CanvasKit.SkM44.rotated = function(axisVec, radians) {
261 return CanvasKit.SkM44.rotatedUnitSinCos(
262 CanvasKit.SkVector.normalize(axisVec), Math.sin(radians), Math.cos(radians));
263 }
264 // Create a 4x4 matrix representing a rotation about the provided normalized axis 3-vec.
265 // Rotation is provided redundantly as both sin and cos values.
266 // This rotate can be used when you already have the cosAngle and sinAngle values
267 // so you don't have to atan(cos/sin) to call roatated() which expects an angle in radians.
268 // this does no checking! Behavior for invalid sin or cos values or non-normalized axis vectors
269 // is incorrect. Prefer rotate().
270 CanvasKit.SkM44.rotatedUnitSinCos = function(axisVec, sinAngle, cosAngle) {
271 var x = axisVec[0];
272 var y = axisVec[1];
273 var z = axisVec[2];
274 var c = cosAngle;
275 var s = sinAngle;
276 var t = 1 - c;
277 return [
278 t*x*x + c, t*x*y - s*z, t*x*z + s*y, 0,
279 t*x*y + s*z, t*y*y + c, t*y*z - s*x, 0,
280 t*x*z - s*y, t*y*z + s*x, t*z*z + c, 0,
281 0, 0, 0, 1
282 ];
283 }
284 // Create a 4x4 matrix representing a camera at eyeVec, pointed at centerVec.
285 CanvasKit.SkM44.lookat = function(eyeVec, centerVec, upVec) {
286 var f = CanvasKit.SkVector.normalize(CanvasKit.SkVector.sub(centerVec, eyeVec));
287 var u = CanvasKit.SkVector.normalize(upVec);
288 var s = CanvasKit.SkVector.normalize(CanvasKit.SkVector.cross(f, u));
289
290 var m = CanvasKit.SkM44.identity();
291 // set each column's top three numbers
Kevin Lubickc1d08982020-04-06 13:52:15 -0400292 stride(s, m, 4, 0, 0);
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500293 stride(CanvasKit.SkVector.cross(s, f), m, 4, 1, 0);
294 stride(CanvasKit.SkVector.mulScalar(f, -1), m, 4, 2, 0);
Kevin Lubickc1d08982020-04-06 13:52:15 -0400295 stride(eyeVec, m, 4, 3, 0);
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500296
297 var m2 = CanvasKit.SkM44.invert(m);
298 if (m2 === null) {
299 return CanvasKit.SkM44.identity();
300 }
301 return m2;
302 }
303 // Create a 4x4 matrix representing a perspective. All arguments are scalars.
304 // angle is in radians.
305 CanvasKit.SkM44.perspective = function(near, far, angle) {
306 if (skIsDebug && (far <= near)) {
307 throw "far must be greater than near when constructing SkM44 using perspective.";
308 }
309 var dInv = 1 / (far - near);
310 var halfAngle = angle / 2;
311 var cot = Math.cos(halfAngle) / Math.sin(halfAngle);
312 return [
313 cot, 0, 0, 0,
314 0, cot, 0, 0,
315 0, 0, (far+near)*dInv, 2*far*near*dInv,
316 0, 0, -1, 1,
317 ];
318 }
319 // Returns the number at the given row and column in matrix m.
320 CanvasKit.SkM44.rc = function(m, r, c) {
321 return m[r*4+c];
322 }
323 // Accepts any number of 4x4 matrix arguments, multiplies them left to right.
324 CanvasKit.SkM44.multiply = function() {
325 return multiplyMany(4, arguments);
326 }
327
328 // Invert the 4x4 matrix if it is invertible and return it. if not, return null.
329 // taken from SkM44.cpp (altered to use row-major order)
330 // m is not altered.
331 CanvasKit.SkM44.invert = function(m) {
332 if (skIsDebug && !m.every(isnumber)) {
333 throw 'some members of matrix are NaN m='+m;
334 }
335
336 var a00 = m[0];
337 var a01 = m[4];
338 var a02 = m[8];
339 var a03 = m[12];
340 var a10 = m[1];
341 var a11 = m[5];
342 var a12 = m[9];
343 var a13 = m[13];
344 var a20 = m[2];
345 var a21 = m[6];
346 var a22 = m[10];
347 var a23 = m[14];
348 var a30 = m[3];
349 var a31 = m[7];
350 var a32 = m[11];
351 var a33 = m[15];
352
353 var b00 = a00 * a11 - a01 * a10;
354 var b01 = a00 * a12 - a02 * a10;
355 var b02 = a00 * a13 - a03 * a10;
356 var b03 = a01 * a12 - a02 * a11;
357 var b04 = a01 * a13 - a03 * a11;
358 var b05 = a02 * a13 - a03 * a12;
359 var b06 = a20 * a31 - a21 * a30;
360 var b07 = a20 * a32 - a22 * a30;
361 var b08 = a20 * a33 - a23 * a30;
362 var b09 = a21 * a32 - a22 * a31;
363 var b10 = a21 * a33 - a23 * a31;
364 var b11 = a22 * a33 - a23 * a32;
365
366 // calculate determinate
367 var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
368 var invdet = 1.0 / det;
369
370 // bail out if the matrix is not invertible
371 if (det === 0 || invdet === Infinity) {
372 SkDebug('Warning, uninvertible matrix');
373 return null;
374 }
375
376 b00 *= invdet;
377 b01 *= invdet;
378 b02 *= invdet;
379 b03 *= invdet;
380 b04 *= invdet;
381 b05 *= invdet;
382 b06 *= invdet;
383 b07 *= invdet;
384 b08 *= invdet;
385 b09 *= invdet;
386 b10 *= invdet;
387 b11 *= invdet;
388
389 // store result in row major order
390 var tmp = [
391 a11 * b11 - a12 * b10 + a13 * b09,
392 a12 * b08 - a10 * b11 - a13 * b07,
393 a10 * b10 - a11 * b08 + a13 * b06,
394 a11 * b07 - a10 * b09 - a12 * b06,
395
396 a02 * b10 - a01 * b11 - a03 * b09,
397 a00 * b11 - a02 * b08 + a03 * b07,
398 a01 * b08 - a00 * b10 - a03 * b06,
399 a00 * b09 - a01 * b07 + a02 * b06,
400
401 a31 * b05 - a32 * b04 + a33 * b03,
402 a32 * b02 - a30 * b05 - a33 * b01,
403 a30 * b04 - a31 * b02 + a33 * b00,
404 a31 * b01 - a30 * b03 - a32 * b00,
405
406 a22 * b04 - a21 * b05 - a23 * b03,
407 a20 * b05 - a22 * b02 + a23 * b01,
408 a21 * b02 - a20 * b04 - a23 * b00,
409 a20 * b03 - a21 * b01 + a22 * b00,
410 ];
411
412
413 if (!tmp.every(function(val) { return val !== NaN && val !== Infinity && val !== -Infinity; })) {
414 SkDebug('inverted matrix contains infinities or NaN '+tmp);
415 return null;
416 }
417 return tmp;
418 }
419
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500420 CanvasKit.SkM44.transpose = function(m) {
421 return [
422 m[0], m[4], m[8], m[12],
423 m[1], m[5], m[9], m[13],
424 m[2], m[6], m[10], m[14],
425 m[3], m[7], m[11], m[15],
426 ];
427 }
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500428
Kevin Lubickd3729342019-09-12 11:11:25 -0400429 // An SkColorMatrix is a 4x4 color matrix that transforms the 4 color channels
430 // with a 1x4 matrix that post-translates those 4 channels.
431 // For example, the following is the layout with the scale (S) and post-transform
432 // (PT) items indicated.
433 // RS, 0, 0, 0 | RPT
434 // 0, GS, 0, 0 | GPT
435 // 0, 0, BS, 0 | BPT
436 // 0, 0, 0, AS | APT
437 //
438 // Much of this was hand-transcribed from SkColorMatrix.cpp, because it's easier to
439 // deal with a Float32Array of length 20 than to try to expose the SkColorMatrix object.
440
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500441 var rScale = 0;
442 var gScale = 6;
443 var bScale = 12;
444 var aScale = 18;
445
Kevin Lubickd3729342019-09-12 11:11:25 -0400446 var rPostTrans = 4;
447 var gPostTrans = 9;
448 var bPostTrans = 14;
449 var aPostTrans = 19;
450
451 CanvasKit.SkColorMatrix = {};
452 CanvasKit.SkColorMatrix.identity = function() {
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500453 var m = new Float32Array(20);
454 m[rScale] = 1;
455 m[gScale] = 1;
456 m[bScale] = 1;
457 m[aScale] = 1;
458 return m;
Kevin Lubickd3729342019-09-12 11:11:25 -0400459 }
460
461 CanvasKit.SkColorMatrix.scaled = function(rs, gs, bs, as) {
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500462 var m = new Float32Array(20);
463 m[rScale] = rs;
464 m[gScale] = gs;
465 m[bScale] = bs;
466 m[aScale] = as;
467 return m;
Kevin Lubickd3729342019-09-12 11:11:25 -0400468 }
469
470 var rotateIndices = [
471 [6, 7, 11, 12],
472 [0, 10, 2, 12],
473 [0, 1, 5, 6],
474 ];
475 // axis should be 0, 1, 2 for r, g, b
476 CanvasKit.SkColorMatrix.rotated = function(axis, sine, cosine) {
477 var m = CanvasKit.SkColorMatrix.identity();
478 var indices = rotateIndices[axis];
479 m[indices[0]] = cosine;
480 m[indices[1]] = sine;
481 m[indices[2]] = -sine;
482 m[indices[3]] = cosine;
483 return m;
484 }
485
486 // m is a SkColorMatrix (i.e. a Float32Array), and this sets the 4 "special"
487 // params that will translate the colors after they are multiplied by the 4x4 matrix.
488 CanvasKit.SkColorMatrix.postTranslate = function(m, dr, dg, db, da) {
489 m[rPostTrans] += dr;
490 m[gPostTrans] += dg;
491 m[bPostTrans] += db;
492 m[aPostTrans] += da;
493 return m;
494 }
495
496 // concat returns a new SkColorMatrix that is the result of multiplying outer*inner;
497 CanvasKit.SkColorMatrix.concat = function(outer, inner) {
498 var m = new Float32Array(20);
499 var index = 0;
500 for (var j = 0; j < 20; j += 5) {
501 for (var i = 0; i < 4; i++) {
502 m[index++] = outer[j + 0] * inner[i + 0] +
503 outer[j + 1] * inner[i + 5] +
504 outer[j + 2] * inner[i + 10] +
505 outer[j + 3] * inner[i + 15];
506 }
507 m[index++] = outer[j + 0] * inner[4] +
508 outer[j + 1] * inner[9] +
509 outer[j + 2] * inner[14] +
510 outer[j + 3] * inner[19] +
511 outer[j + 4];
512 }
513
514 return m;
515 }
516
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500517 CanvasKit.SkPath.prototype.addArc = function(oval, startAngle, sweepAngle) {
518 // see arc() for the HTMLCanvas version
519 // note input angles are degrees.
520 this._addArc(oval, startAngle, sweepAngle);
521 return this;
522 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400523
Kevin Lubicke384df42019-08-26 15:48:09 -0400524 CanvasKit.SkPath.prototype.addOval = function(oval, isCCW, startIndex) {
525 if (startIndex === undefined) {
526 startIndex = 1;
527 }
528 this._addOval(oval, !!isCCW, startIndex);
529 return this;
530 };
531
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500532 CanvasKit.SkPath.prototype.addPath = function() {
533 // Takes 1, 2, 7, or 10 required args, where the first arg is always the path.
534 // The last arg is optional and chooses between add or extend mode.
535 // The options for the remaining args are:
536 // - an array of 6 or 9 parameters (perspective is optional)
537 // - the 9 parameters of a full matrix or
538 // the 6 non-perspective params of a matrix.
539 var args = Array.prototype.slice.call(arguments);
540 var path = args[0];
541 var extend = false;
542 if (typeof args[args.length-1] === "boolean") {
543 extend = args.pop();
544 }
545 if (args.length === 1) {
546 // Add path, unchanged. Use identity matrix
547 this._addPath(path, 1, 0, 0,
548 0, 1, 0,
549 0, 0, 1,
550 extend);
551 } else if (args.length === 2) {
552 // User provided the 9 params of a full matrix as an array.
553 var a = args[1];
554 this._addPath(path, a[0], a[1], a[2],
555 a[3], a[4], a[5],
556 a[6] || 0, a[7] || 0, a[8] || 1,
557 extend);
558 } else if (args.length === 7 || args.length === 10) {
559 // User provided the 9 params of a (full) matrix directly.
560 // (or just the 6 non perspective ones)
561 // These are in the same order as what Skia expects.
562 var a = args;
563 this._addPath(path, a[1], a[2], a[3],
564 a[4], a[5], a[6],
565 a[7] || 0, a[8] || 0, a[9] || 1,
566 extend);
567 } else {
568 SkDebug('addPath expected to take 1, 2, 7, or 10 required args. Got ' + args.length);
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400569 return null;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500570 }
571 return this;
572 };
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400573
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500574 // points is either an array of [x, y] where x and y are numbers or
575 // a typed array from Malloc where the even indices will be treated
576 // as x coordinates and the odd indices will be treated as y coordinates.
577 CanvasKit.SkPath.prototype.addPoly = function(points, close) {
578 var ptr;
579 var n;
580 // This was created with CanvasKit.Malloc, so assume the user has
581 // already been filled with data.
582 if (points['_ck']) {
583 ptr = points.byteOffset;
584 n = points.length/2;
585 } else {
586 ptr = copy2dArray(points, CanvasKit.HEAPF32);
587 n = points.length;
588 }
589 this._addPoly(ptr, n, close);
Kevin Lubickcf118922020-05-28 14:43:38 -0400590 freeArraysThatAreNotMallocedByUsers(ptr, points);
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500591 return this;
592 };
593
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500594 CanvasKit.SkPath.prototype.addRect = function() {
595 // Takes 1, 2, 4 or 5 args
596 // - SkRect
597 // - SkRect, isCCW
598 // - left, top, right, bottom
599 // - left, top, right, bottom, isCCW
600 if (arguments.length === 1 || arguments.length === 2) {
601 var r = arguments[0];
602 var ccw = arguments[1] || false;
603 this._addRect(r.fLeft, r.fTop, r.fRight, r.fBottom, ccw);
604 } else if (arguments.length === 4 || arguments.length === 5) {
605 var a = arguments;
606 this._addRect(a[0], a[1], a[2], a[3], a[4] || false);
607 } else {
608 SkDebug('addRect expected to take 1, 2, 4, or 5 args. Got ' + arguments.length);
Kevin Lubick217056c2018-09-20 17:39:31 -0400609 return null;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500610 }
611 return this;
612 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400613
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500614 CanvasKit.SkPath.prototype.addRoundRect = function() {
615 // Takes 3, 4, 6 or 7 args
616 // - SkRect, radii, ccw
617 // - SkRect, rx, ry, ccw
618 // - left, top, right, bottom, radii, ccw
619 // - left, top, right, bottom, rx, ry, ccw
620 var args = arguments;
621 if (args.length === 3 || args.length === 6) {
622 var radii = args[args.length-2];
Kevin Lubickcf118922020-05-28 14:43:38 -0400623 } else if (args.length === 4 || args.length === 7){
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500624 // duplicate the given (rx, ry) pairs for each corner.
625 var rx = args[args.length-3];
626 var ry = args[args.length-2];
627 var radii = [rx, ry, rx, ry, rx, ry, rx, ry];
628 } else {
629 SkDebug('addRoundRect expected to take 3, 4, 6, or 7 args. Got ' + args.length);
630 return null;
631 }
632 if (radii.length !== 8) {
633 SkDebug('addRoundRect needs 8 radii provided. Got ' + radii.length);
634 return null;
635 }
636 var rptr = copy1dArray(radii, CanvasKit.HEAPF32);
637 if (args.length === 3 || args.length === 4) {
638 var r = args[0];
639 var ccw = args[args.length - 1];
640 this._addRoundRect(r.fLeft, r.fTop, r.fRight, r.fBottom, rptr, ccw);
641 } else if (args.length === 6 || args.length === 7) {
642 var a = args;
643 this._addRoundRect(a[0], a[1], a[2], a[3], rptr, ccw);
644 }
Kevin Lubickcf118922020-05-28 14:43:38 -0400645 freeArraysThatAreNotMallocedByUsers(rptr, radii);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500646 return this;
647 };
648
649 CanvasKit.SkPath.prototype.arc = function(x, y, radius, startAngle, endAngle, ccw) {
650 // emulates the HTMLCanvas behavior. See addArc() for the SkPath version.
651 // Note input angles are radians.
652 var bounds = CanvasKit.LTRBRect(x-radius, y-radius, x+radius, y+radius);
653 var sweep = radiansToDegrees(endAngle - startAngle) - (360 * !!ccw);
654 var temp = new CanvasKit.SkPath();
655 temp.addArc(bounds, radiansToDegrees(startAngle), sweep);
656 this.addPath(temp, true);
657 temp.delete();
658 return this;
659 };
660
661 CanvasKit.SkPath.prototype.arcTo = function() {
662 // takes 4, 5 or 7 args
663 // - 5 x1, y1, x2, y2, radius
664 // - 4 oval (as Rect), startAngle, sweepAngle, forceMoveTo
Kevin Lubicke384df42019-08-26 15:48:09 -0400665 // - 7 rx, ry, xAxisRotate, useSmallArc, isCCW, x, y
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500666 var args = arguments;
667 if (args.length === 5) {
668 this._arcTo(args[0], args[1], args[2], args[3], args[4]);
669 } else if (args.length === 4) {
670 this._arcTo(args[0], args[1], args[2], args[3]);
671 } else if (args.length === 7) {
Kevin Lubicke384df42019-08-26 15:48:09 -0400672 this._arcTo(args[0], args[1], args[2], !!args[3], !!args[4], args[5], args[6]);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500673 } else {
674 throw 'Invalid args for arcTo. Expected 4, 5, or 7, got '+ args.length;
675 }
676
677 return this;
678 };
679
680 CanvasKit.SkPath.prototype.close = function() {
681 this._close();
682 return this;
683 };
684
685 CanvasKit.SkPath.prototype.conicTo = function(x1, y1, x2, y2, w) {
686 this._conicTo(x1, y1, x2, y2, w);
687 return this;
688 };
689
690 CanvasKit.SkPath.prototype.cubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
691 this._cubicTo(cp1x, cp1y, cp2x, cp2y, x, y);
692 return this;
693 };
694
695 CanvasKit.SkPath.prototype.dash = function(on, off, phase) {
696 if (this._dash(on, off, phase)) {
Kevin Lubick217056c2018-09-20 17:39:31 -0400697 return this;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500698 }
699 return null;
700 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400701
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500702 CanvasKit.SkPath.prototype.lineTo = function(x, y) {
703 this._lineTo(x, y);
704 return this;
705 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400706
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500707 CanvasKit.SkPath.prototype.moveTo = function(x, y) {
708 this._moveTo(x, y);
709 return this;
710 };
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400711
Kevin Lubicke384df42019-08-26 15:48:09 -0400712 CanvasKit.SkPath.prototype.offset = function(dx, dy) {
713 this._transform(1, 0, dx,
714 0, 1, dy,
715 0, 0, 1);
716 return this;
717 };
718
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500719 CanvasKit.SkPath.prototype.quadTo = function(cpx, cpy, x, y) {
720 this._quadTo(cpx, cpy, x, y);
721 return this;
722 };
723
Kevin Lubick79b71342019-11-01 14:36:52 -0400724 CanvasKit.SkPath.prototype.rArcTo = function(rx, ry, xAxisRotate, useSmallArc, isCCW, dx, dy) {
725 this._rArcTo(rx, ry, xAxisRotate, useSmallArc, isCCW, dx, dy);
726 return this;
727 };
728
729 CanvasKit.SkPath.prototype.rConicTo = function(dx1, dy1, dx2, dy2, w) {
730 this._rConicTo(dx1, dy1, dx2, dy2, w);
731 return this;
732 };
733
734 // These params are all relative
735 CanvasKit.SkPath.prototype.rCubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
736 this._rCubicTo(cp1x, cp1y, cp2x, cp2y, x, y);
737 return this;
738 };
739
740 CanvasKit.SkPath.prototype.rLineTo = function(dx, dy) {
741 this._rLineTo(dx, dy);
742 return this;
743 };
744
745 CanvasKit.SkPath.prototype.rMoveTo = function(dx, dy) {
746 this._rMoveTo(dx, dy);
747 return this;
748 };
749
750 // These params are all relative
751 CanvasKit.SkPath.prototype.rQuadTo = function(cpx, cpy, x, y) {
752 this._rQuadTo(cpx, cpy, x, y);
753 return this;
754 };
755
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500756 CanvasKit.SkPath.prototype.stroke = function(opts) {
757 // Fill out any missing values with the default values.
758 /**
759 * See externs.js for this definition
760 * @type {StrokeOpts}
761 */
762 opts = opts || {};
763 opts.width = opts.width || 1;
764 opts.miter_limit = opts.miter_limit || 4;
765 opts.cap = opts.cap || CanvasKit.StrokeCap.Butt;
766 opts.join = opts.join || CanvasKit.StrokeJoin.Miter;
767 opts.precision = opts.precision || 1;
768 if (this._stroke(opts)) {
769 return this;
770 }
771 return null;
772 };
773
774 CanvasKit.SkPath.prototype.transform = function() {
775 // Takes 1 or 9 args
776 if (arguments.length === 1) {
777 // argument 1 should be a 6 or 9 element array.
778 var a = arguments[0];
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 if (arguments.length === 6 || arguments.length === 9) {
783 // these arguments are the 6 or 9 members of the matrix
784 var a = arguments;
785 this._transform(a[0], a[1], a[2],
786 a[3], a[4], a[5],
787 a[6] || 0, a[7] || 0, a[8] || 1);
788 } else {
789 throw 'transform expected to take 1 or 9 arguments. Got ' + arguments.length;
790 }
791 return this;
792 };
793 // isComplement is optional, defaults to false
794 CanvasKit.SkPath.prototype.trim = function(startT, stopT, isComplement) {
795 if (this._trim(startT, stopT, !!isComplement)) {
796 return this;
797 }
798 return null;
799 };
800
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500801 CanvasKit.SkImage.prototype.encodeToData = function() {
802 if (!arguments.length) {
803 return this._encodeToData();
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400804 }
Kevin Lubick53965c92018-10-11 08:51:55 -0400805
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500806 if (arguments.length === 2) {
807 var a = arguments;
808 return this._encodeToDataWithFormat(a[0], a[1]);
Alexander Khovansky3e119332018-11-15 02:01:19 +0300809 }
810
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500811 throw 'encodeToData expected to take 0 or 2 arguments. Got ' + arguments.length;
812 }
Kevin Lubick1ba9c4d2019-02-22 10:04:06 -0500813
Kevin Lubicka064c282019-04-04 09:28:53 -0400814 CanvasKit.SkImage.prototype.makeShader = function(xTileMode, yTileMode, localMatrix) {
Kevin Lubick6bffe392020-04-02 15:24:15 -0400815 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
816 var shader = this._makeShader(xTileMode, yTileMode, localMatrixPtr);
Kevin Lubickcf118922020-05-28 14:43:38 -0400817 freeArraysThatAreNotMallocedByUsers(localMatrixPtr, localMatrix);
Kevin Lubick6bffe392020-04-02 15:24:15 -0400818 return shader;
Kevin Lubicka064c282019-04-04 09:28:53 -0400819 }
820
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400821 CanvasKit.SkImage.prototype.readPixels = function(imageInfo, srcX, srcY) {
822 var rowBytes;
Kevin Lubick319524b2020-01-22 15:29:14 -0500823 // Important to use ["string"] notation here, otherwise the closure compiler will
824 // minify away the colorType.
825 switch (imageInfo["colorType"]) {
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400826 case CanvasKit.ColorType.RGBA_8888:
827 rowBytes = imageInfo.width * 4; // 1 byte per channel == 4 bytes per pixel in 8888
828 break;
829 case CanvasKit.ColorType.RGBA_F32:
830 rowBytes = imageInfo.width * 16; // 4 bytes per channel == 16 bytes per pixel in F32
831 break;
832 default:
833 SkDebug("Colortype not yet supported");
834 return;
835 }
836 var pBytes = rowBytes * imageInfo.height;
837 var pPtr = CanvasKit._malloc(pBytes);
838
839 if (!this._readPixels(imageInfo, pPtr, rowBytes, srcX, srcY)) {
840 SkDebug("Could not read pixels with the given inputs");
841 return null;
842 }
843
844 // Put those pixels into a typed array of the right format and then
845 // make a copy with slice() that we can return.
846 var retVal = null;
Kevin Lubick319524b2020-01-22 15:29:14 -0500847 switch (imageInfo["colorType"]) {
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400848 case CanvasKit.ColorType.RGBA_8888:
Bryce Thomas1fa54042020-01-14 13:46:30 -0800849 retVal = new Uint8Array(CanvasKit.HEAPU8.buffer, pPtr, pBytes).slice();
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400850 break;
851 case CanvasKit.ColorType.RGBA_F32:
Bryce Thomas1fa54042020-01-14 13:46:30 -0800852 retVal = new Float32Array(CanvasKit.HEAPU8.buffer, pPtr, pBytes).slice();
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400853 break;
854 }
855
856 // Free the allocated pixels in the WASM memory
857 CanvasKit._free(pPtr);
858 return retVal;
Kevin Lubick6bffe392020-04-02 15:24:15 -0400859 }
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400860
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400861 // Accepts an array of four numbers in the range of 0-1 representing a 4f color
862 CanvasKit.SkCanvas.prototype.clear = function (color4f) {
863 var cPtr = copy1dArray(color4f, CanvasKit.HEAPF32);
864 this._clear(cPtr);
Kevin Lubickcf118922020-05-28 14:43:38 -0400865 freeArraysThatAreNotMallocedByUsers(cPtr, color4f);
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 Lubickcf118922020-05-28 14:43:38 -0400873 freeArraysThatAreNotMallocedByUsers(matrPtr, matr);
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400874 }
875
Kevin Lubickc1d08982020-04-06 13:52:15 -0400876 // Deprecated - just use concat
877 CanvasKit.SkCanvas.prototype.concat44 = CanvasKit.SkCanvas.prototype.concat;
878
Kevin Lubickee91c072019-03-29 10:39:52 -0400879 // atlas is an SkImage, e.g. from CanvasKit.MakeImageFromEncoded
880 // srcRects and dstXforms should be CanvasKit.SkRectBuilder and CanvasKit.RSXFormBuilder
881 // or just arrays of floats in groups of 4.
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400882 // colors, if provided, should be a CanvasKit.SkColorBuilder or array of float colors (arrays of 4 floats)
Kevin Lubickee91c072019-03-29 10:39:52 -0400883 CanvasKit.SkCanvas.prototype.drawAtlas = function(atlas, srcRects, dstXforms, paint,
884 /*optional*/ blendMode, colors) {
885 if (!atlas || !paint || !srcRects || !dstXforms) {
886 SkDebug('Doing nothing since missing a required input');
887 return;
888 }
889 if (srcRects.length !== dstXforms.length || (colors && colors.length !== dstXforms.length)) {
890 SkDebug('Doing nothing since input arrays length mismatches');
Nathaniel Nifonge5d32542020-03-26 09:27:48 -0400891 return;
Kevin Lubickee91c072019-03-29 10:39:52 -0400892 }
893 if (!blendMode) {
894 blendMode = CanvasKit.BlendMode.SrcOver;
895 }
896
897 var srcRectPtr;
898 if (srcRects.build) {
899 srcRectPtr = srcRects.build();
900 } else {
901 srcRectPtr = copy1dArray(srcRects, CanvasKit.HEAPF32);
902 }
903
904 var dstXformPtr;
905 if (dstXforms.build) {
906 dstXformPtr = dstXforms.build();
907 } else {
908 dstXformPtr = copy1dArray(dstXforms, CanvasKit.HEAPF32);
909 }
910
Kevin Lubick6bffe392020-04-02 15:24:15 -0400911 var colorPtr = nullptr;
Kevin Lubickee91c072019-03-29 10:39:52 -0400912 if (colors) {
913 if (colors.build) {
914 colorPtr = colors.build();
915 } else {
Nathaniel Nifonge5d32542020-03-26 09:27:48 -0400916 if (!isCanvasKitColor(colors[0])) {
917 SkDebug('DrawAtlas color argument expected to be CanvasKit.SkRectBuilder or array of ' +
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400918 'float arrays, but got '+colors);
Nathaniel Nifonge5d32542020-03-26 09:27:48 -0400919 return;
920 }
921 // convert here
922 colors = colors.map(toUint32Color);
Kevin Lubickee91c072019-03-29 10:39:52 -0400923 colorPtr = copy1dArray(colors, CanvasKit.HEAPU32);
924 }
925 }
926
927 this._drawAtlas(atlas, dstXformPtr, srcRectPtr, colorPtr, dstXforms.length,
928 blendMode, paint);
929
930 if (srcRectPtr && !srcRects.build) {
Kevin Lubickcf118922020-05-28 14:43:38 -0400931 freeArraysThatAreNotMallocedByUsers(srcRectPtr, srcRects);
Kevin Lubickee91c072019-03-29 10:39:52 -0400932 }
933 if (dstXformPtr && !dstXforms.build) {
Kevin Lubickcf118922020-05-28 14:43:38 -0400934 freeArraysThatAreNotMallocedByUsers(dstXformPtr, dstXforms);
Kevin Lubickee91c072019-03-29 10:39:52 -0400935 }
936 if (colorPtr && !colors.build) {
Kevin Lubickcf118922020-05-28 14:43:38 -0400937 freeArraysThatAreNotMallocedByUsers(colorPtr, colors);
Kevin Lubickee91c072019-03-29 10:39:52 -0400938 }
939
940 }
941
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400942 CanvasKit.SkCanvas.prototype.drawColor = function (color4f, mode) {
943 var cPtr = copy1dArray(color4f, CanvasKit.HEAPF32);
944 if (mode !== undefined) {
945 this._drawColor(cPtr, mode);
946 } else {
947 this._drawColor(cPtr);
948 }
Kevin Lubickcf118922020-05-28 14:43:38 -0400949 freeArraysThatAreNotMallocedByUsers(cPtr, color4f);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400950 }
951
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500952 // points is either an array of [x, y] where x and y are numbers or
953 // a typed array from Malloc where the even indices will be treated
954 // as x coordinates and the odd indices will be treated as y coordinates.
955 CanvasKit.SkCanvas.prototype.drawPoints = function(mode, points, paint) {
956 var ptr;
957 var n;
958 // This was created with CanvasKit.Malloc, so assume the user has
959 // already been filled with data.
960 if (points['_ck']) {
961 ptr = points.byteOffset;
962 n = points.length/2;
963 } else {
964 ptr = copy2dArray(points, CanvasKit.HEAPF32);
965 n = points.length;
966 }
967 this._drawPoints(mode, ptr, n, paint);
Kevin Lubickcf118922020-05-28 14:43:38 -0400968 freeArraysThatAreNotMallocedByUsers(ptr, points);
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500969 }
970
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400971 CanvasKit.SkCanvas.prototype.drawShadow = function(path, zPlaneParams, lightPos, lightRadius, ambientColor, spotColor, flags) {
972 var ambiPtr = copy1dArray(ambientColor, CanvasKit.HEAPF32);
973 var spotPtr = copy1dArray(spotColor, CanvasKit.HEAPF32);
974 this._drawShadow(path, zPlaneParams, lightPos, lightRadius, ambiPtr, spotPtr, flags);
Kevin Lubickcf118922020-05-28 14:43:38 -0400975 freeArraysThatAreNotMallocedByUsers(ambiPtr, ambientColor);
976 freeArraysThatAreNotMallocedByUsers(spotPtr, spotColor);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400977 }
978
Kevin Lubickc1d08982020-04-06 13:52:15 -0400979 // getLocalToDevice returns a 4x4 matrix.
980 CanvasKit.SkCanvas.prototype.getLocalToDevice = function() {
981 var matrPtr = CanvasKit._malloc(16 * 4); // allocate space for the matrix
982 // _getLocalToDevice will copy the values into the pointer.
983 this._getLocalToDevice(matrPtr);
984 return copy4x4MatrixFromWasm(matrPtr);
985 }
986
Nathaniel Nifong00de91c2020-05-06 16:22:33 -0400987 // findMarkedCTM returns a 4x4 matrix, or null if a matrix was not found at
988 // the provided marker.
989 CanvasKit.SkCanvas.prototype.findMarkedCTM = function(marker) {
990 var matrPtr = CanvasKit._malloc(16 * 4); // allocate space for the matrix
991 // _getLocalToDevice will copy the values into the pointer.
992 var found = this._findMarkedCTM(marker, matrPtr);
993 if (!found) {
994 return null;
995 }
996 return copy4x4MatrixFromWasm(matrPtr);
997 }
998
Kevin Lubickc1d08982020-04-06 13:52:15 -0400999 // getTotalMatrix returns the current matrix as a 3x3 matrix.
Kevin Lubick6bffe392020-04-02 15:24:15 -04001000 CanvasKit.SkCanvas.prototype.getTotalMatrix = function() {
1001 var matrPtr = CanvasKit._malloc(9 * 4); // allocate space for the matrix
1002 // _getTotalMatrix will copy the values into the pointer.
1003 this._getTotalMatrix(matrPtr);
1004 // read them out into an array. TODO(kjlubick): If we change SkMatrix to be
1005 // typedArrays, then we should return a typed array here too.
1006 var rv = new Array(9);
1007 for (var i = 0; i < 9; i++) {
1008 rv[i] = CanvasKit.HEAPF32[matrPtr/4 + i]; // divide by 4 to "cast" to float.
1009 }
1010 CanvasKit._free(matrPtr);
1011 return rv;
1012 }
1013
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001014 // returns Uint8Array
1015 CanvasKit.SkCanvas.prototype.readPixels = function(x, y, w, h, alphaType,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001016 colorType, colorSpace, dstRowBytes) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001017 // supply defaults (which are compatible with HTMLCanvas's getImageData)
1018 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
1019 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001020 colorSpace = colorSpace || CanvasKit.SkColorSpace.SRGB;
1021 var pixBytes = 4;
1022 if (colorType === CanvasKit.ColorType.RGBA_F16) {
1023 pixBytes = 8;
1024 }
1025 dstRowBytes = dstRowBytes || (pixBytes * w);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001026
1027 var len = h * dstRowBytes
1028 var pptr = CanvasKit._malloc(len);
1029 var ok = this._readPixels({
1030 'width': w,
1031 'height': h,
Kevin Lubick52b9f372018-12-04 13:57:36 -05001032 'colorType': colorType,
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001033 'alphaType': alphaType,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001034 'colorSpace': colorSpace,
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001035 }, pptr, dstRowBytes, x, y);
1036 if (!ok) {
1037 CanvasKit._free(pptr);
1038 return null;
1039 }
1040
1041 // The first typed array is just a view into memory. Because we will
1042 // be free-ing that, we call slice to make a persistent copy.
Bryce Thomas1fa54042020-01-14 13:46:30 -08001043 var pixels = new Uint8Array(CanvasKit.HEAPU8.buffer, pptr, len).slice();
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001044 CanvasKit._free(pptr);
1045 return pixels;
1046 }
1047
Kevin Lubickcf118922020-05-28 14:43:38 -04001048 // pixels should be a Uint8Array or a plain JS array.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001049 CanvasKit.SkCanvas.prototype.writePixels = function(pixels, srcWidth, srcHeight,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001050 destX, destY, alphaType, colorType, colorSpace) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001051 if (pixels.byteLength % (srcWidth * srcHeight)) {
1052 throw 'pixels length must be a multiple of the srcWidth * srcHeight';
1053 }
1054 var bytesPerPixel = pixels.byteLength / (srcWidth * srcHeight);
1055 // supply defaults (which are compatible with HTMLCanvas's putImageData)
1056 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
1057 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001058 colorSpace = colorSpace || CanvasKit.SkColorSpace.SRGB;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001059 var srcRowBytes = bytesPerPixel * srcWidth;
1060
Kevin Lubickcf118922020-05-28 14:43:38 -04001061 var pptr = copy1dArray(pixels, CanvasKit.HEAPU8);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001062 var ok = this._writePixels({
1063 'width': srcWidth,
1064 'height': srcHeight,
1065 'colorType': colorType,
1066 'alphaType': alphaType,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001067 'colorSpace': colorSpace,
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001068 }, pptr, srcRowBytes, destX, destY);
1069
Kevin Lubickcf118922020-05-28 14:43:38 -04001070 freeArraysThatAreNotMallocedByUsers(pptr, pixels);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001071 return ok;
Kevin Lubick52b9f372018-12-04 13:57:36 -05001072 }
1073
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001074 CanvasKit.SkColorFilter.MakeBlend = function(color4f, mode) {
1075 var cPtr = copy1dArray(color4f, CanvasKit.HEAPF32);
1076 var result = CanvasKit.SkColorFilter._MakeBlend(cPtr, mode);
Kevin Lubickcf118922020-05-28 14:43:38 -04001077 freeArraysThatAreNotMallocedByUsers(cPtr, color4f);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001078 return result;
1079 }
1080
Kevin Lubickd3729342019-09-12 11:11:25 -04001081 // colorMatrix is an SkColorMatrix (e.g. Float32Array of length 20)
1082 CanvasKit.SkColorFilter.MakeMatrix = function(colorMatrix) {
1083 if (!colorMatrix || colorMatrix.length !== 20) {
Kevin Lubick6bffe392020-04-02 15:24:15 -04001084 throw 'invalid color matrix';
Kevin Lubickd3729342019-09-12 11:11:25 -04001085 }
1086 var fptr = copy1dArray(colorMatrix, CanvasKit.HEAPF32);
1087 // We know skia memcopies the floats, so we can free our memory after the call returns.
1088 var m = CanvasKit.SkColorFilter._makeMatrix(fptr);
Kevin Lubickcf118922020-05-28 14:43:38 -04001089 freeArraysThatAreNotMallocedByUsers(fptr, colorMatrix);
Kevin Lubickd3729342019-09-12 11:11:25 -04001090 return m;
1091 }
1092
Kevin Lubick6bffe392020-04-02 15:24:15 -04001093 CanvasKit.SkImageFilter.MakeMatrixTransform = function(matr, filterQuality, input) {
1094 var matrPtr = copy3x3MatrixToWasm(matr);
1095 var imgF = CanvasKit.SkImageFilter._MakeMatrixTransform(matrPtr, filterQuality, input);
1096
Kevin Lubickcf118922020-05-28 14:43:38 -04001097 freeArraysThatAreNotMallocedByUsers(matrPtr, matr);
Kevin Lubick6bffe392020-04-02 15:24:15 -04001098 return imgF;
1099 }
1100
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001101 CanvasKit.SkPaint.prototype.getColor = function() {
1102 var cPtr = CanvasKit._malloc(16); // 4 floats, 4 bytes each
1103 this._getColor(cPtr);
1104 return copyColorFromWasm(cPtr);
1105 }
1106
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001107 CanvasKit.SkPaint.prototype.setColor = function(color4f, colorSpace) {
1108 colorSpace = colorSpace || null; // null will be replaced with sRGB in the C++ method.
1109 // emscripten wouldn't bind undefined to the sk_sp<SkColorSpace> expected here.
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001110 var cPtr = copy1dArray(color4f, CanvasKit.HEAPF32);
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001111 this._setColor(cPtr, colorSpace);
Kevin Lubickcf118922020-05-28 14:43:38 -04001112 freeArraysThatAreNotMallocedByUsers(cPtr, color4f);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001113 }
1114
Kevin Lubickcc13fd32019-04-05 13:00:01 -04001115 CanvasKit.SkSurface.prototype.captureFrameAsSkPicture = function(drawFrame) {
1116 // Set up SkPictureRecorder
1117 var spr = new CanvasKit.SkPictureRecorder();
1118 var canvas = spr.beginRecording(
1119 CanvasKit.LTRBRect(0, 0, this.width(), this.height()));
1120 drawFrame(canvas);
1121 var pic = spr.finishRecordingAsPicture();
1122 spr.delete();
1123 // TODO: do we need to clean up the memory for canvas?
1124 // If we delete it here, saveAsFile doesn't work correctly.
1125 return pic;
1126 }
1127
Kevin Lubick359a7e32019-03-19 09:34:37 -04001128 CanvasKit.SkSurface.prototype.requestAnimationFrame = function(callback, dirtyRect) {
1129 if (!this._cached_canvas) {
1130 this._cached_canvas = this.getCanvas();
1131 }
1132 window.requestAnimationFrame(function() {
Kevin Lubick39026282019-03-28 12:46:40 -04001133 if (this._context !== undefined) {
1134 CanvasKit.setCurrentContext(this._context);
1135 }
Kevin Lubick359a7e32019-03-19 09:34:37 -04001136
1137 callback(this._cached_canvas);
1138
Bryce Thomas2c5b8562020-01-22 13:49:41 -08001139 // We do not dispose() of the SkSurface here, as the client will typically
1140 // call requestAnimationFrame again from within the supplied callback.
1141 // For drawing a single frame, prefer drawOnce().
Kevin Lubick359a7e32019-03-19 09:34:37 -04001142 this.flush();
1143 }.bind(this));
1144 }
1145
Kevin Lubick52379332020-01-27 10:01:25 -05001146 // drawOnce will dispose of the surface after drawing the frame using the provided
1147 // callback.
Bryce Thomas2c5b8562020-01-22 13:49:41 -08001148 CanvasKit.SkSurface.prototype.drawOnce = function(callback, dirtyRect) {
1149 if (!this._cached_canvas) {
1150 this._cached_canvas = this.getCanvas();
1151 }
1152 window.requestAnimationFrame(function() {
1153 if (this._context !== undefined) {
1154 CanvasKit.setCurrentContext(this._context);
1155 }
1156 callback(this._cached_canvas);
1157
1158 this.flush();
1159 this.dispose();
1160 }.bind(this));
1161 }
1162
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001163 CanvasKit.SkPathEffect.MakeDash = function(intervals, phase) {
1164 if (!phase) {
1165 phase = 0;
1166 }
1167 if (!intervals.length || intervals.length % 2 === 1) {
1168 throw 'Intervals array must have even length';
1169 }
1170 var ptr = copy1dArray(intervals, CanvasKit.HEAPF32);
Kevin Lubickf279c632020-03-18 09:53:55 -04001171 var dpe = CanvasKit.SkPathEffect._MakeDash(ptr, intervals.length, phase);
Kevin Lubickcf118922020-05-28 14:43:38 -04001172 freeArraysThatAreNotMallocedByUsers(ptr, intervals);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001173 return dpe;
1174 }
1175
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001176 CanvasKit.SkShader.Color = function(color4f, colorSpace) {
1177 colorSpace = colorSpace || null
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001178 var cPtr = copy1dArray(color4f, CanvasKit.HEAPF32);
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001179 var result = CanvasKit.SkShader._Color(cPtr, colorSpace);
Kevin Lubickcf118922020-05-28 14:43:38 -04001180 freeArraysThatAreNotMallocedByUsers(cPtr, color4f);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001181 return result;
1182 }
1183
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001184 CanvasKit.SkShader.MakeLinearGradient = function(start, end, colors, pos, mode, localMatrix, flags, colorSpace) {
1185 colorSpace = colorSpace || null
Nathaniel Nifonge5d32542020-03-26 09:27:48 -04001186 var colorPtr = copy2dArray(colors, CanvasKit.HEAPF32);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001187 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
1188 flags = flags || 0;
Kevin Lubick6bffe392020-04-02 15:24:15 -04001189 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001190
Kevin Lubick6bffe392020-04-02 15:24:15 -04001191 var lgs = CanvasKit._MakeLinearGradientShader(start, end, colorPtr, posPtr,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001192 colors.length, mode, flags, localMatrixPtr, colorSpace);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001193
Kevin Lubickcf118922020-05-28 14:43:38 -04001194 freeArraysThatAreNotMallocedByUsers(localMatrixPtr, localMatrix);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001195 CanvasKit._free(colorPtr);
Kevin Lubickcf118922020-05-28 14:43:38 -04001196 freeArraysThatAreNotMallocedByUsers(posPtr, pos);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001197 return lgs;
1198 }
1199
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001200 CanvasKit.SkShader.MakeRadialGradient = function(center, radius, colors, pos, mode, localMatrix, flags, colorSpace) {
1201 colorSpace = colorSpace || null
Nathaniel Nifonge5d32542020-03-26 09:27:48 -04001202 var colorPtr = copy2dArray(colors, CanvasKit.HEAPF32);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001203 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
1204 flags = flags || 0;
Kevin Lubick6bffe392020-04-02 15:24:15 -04001205 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001206
Kevin Lubick6bffe392020-04-02 15:24:15 -04001207 var rgs = CanvasKit._MakeRadialGradientShader(center, radius, colorPtr, posPtr,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001208 colors.length, mode, flags, localMatrixPtr, colorSpace);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001209
Kevin Lubickcf118922020-05-28 14:43:38 -04001210 freeArraysThatAreNotMallocedByUsers(localMatrixPtr, localMatrix);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001211 CanvasKit._free(colorPtr);
Kevin Lubickcf118922020-05-28 14:43:38 -04001212 freeArraysThatAreNotMallocedByUsers(posPtr, pos);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001213 return rgs;
1214 }
1215
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001216 CanvasKit.SkShader.MakeSweepGradient = function(cx, cy, colors, pos, mode, localMatrix, flags, startAngle, endAngle, colorSpace) {
1217 colorSpace = colorSpace || null
Nathaniel Nifonge5d32542020-03-26 09:27:48 -04001218 var colorPtr = copy2dArray(colors, CanvasKit.HEAPF32);
Dan Field3d44f732020-03-16 09:17:30 -07001219 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
1220 flags = flags || 0;
1221 startAngle = startAngle || 0;
1222 endAngle = endAngle || 360;
Kevin Lubick6bffe392020-04-02 15:24:15 -04001223 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Dan Field3d44f732020-03-16 09:17:30 -07001224
1225 var sgs = CanvasKit._MakeSweepGradientShader(cx, cy, colorPtr, posPtr,
Kevin Lubick6bffe392020-04-02 15:24:15 -04001226 colors.length, mode,
1227 startAngle, endAngle, flags,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001228 localMatrixPtr, colorSpace);
Dan Field3d44f732020-03-16 09:17:30 -07001229
Kevin Lubickcf118922020-05-28 14:43:38 -04001230 freeArraysThatAreNotMallocedByUsers(localMatrixPtr, localMatrix);
Dan Field3d44f732020-03-16 09:17:30 -07001231 CanvasKit._free(colorPtr);
Kevin Lubickcf118922020-05-28 14:43:38 -04001232 freeArraysThatAreNotMallocedByUsers(posPtr, pos);
Dan Field3d44f732020-03-16 09:17:30 -07001233 return sgs;
1234 }
1235
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001236 CanvasKit.SkShader.MakeTwoPointConicalGradient = function(start, startRadius, end, endRadius,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001237 colors, pos, mode, localMatrix, flags, colorSpace) {
1238 colorSpace = colorSpace || null
Nathaniel Nifonge5d32542020-03-26 09:27:48 -04001239 var colorPtr = copy2dArray(colors, CanvasKit.HEAPF32);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001240 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
1241 flags = flags || 0;
Kevin Lubick6bffe392020-04-02 15:24:15 -04001242 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001243
Kevin Lubick6bffe392020-04-02 15:24:15 -04001244 var rgs = CanvasKit._MakeTwoPointConicalGradientShader(
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001245 start, startRadius, end, endRadius,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001246 colorPtr, posPtr, colors.length, mode, flags, localMatrixPtr, colorSpace);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001247
Kevin Lubickcf118922020-05-28 14:43:38 -04001248 freeArraysThatAreNotMallocedByUsers(localMatrixPtr, localMatrix);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001249 CanvasKit._free(colorPtr);
Kevin Lubickcf118922020-05-28 14:43:38 -04001250 freeArraysThatAreNotMallocedByUsers(posPtr, pos);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001251 return rgs;
1252 }
1253
1254 // temporary support for deprecated names.
Nathaniel Nifongc8f95e22020-03-09 11:52:51 -04001255 CanvasKit.MakeSkDashPathEffect = CanvasKit.SkPathEffect.MakeDash;
1256 CanvasKit.MakeLinearGradientShader = CanvasKit.SkShader.MakeLinearGradient;
1257 CanvasKit.MakeRadialGradientShader = CanvasKit.SkShader.MakeRadialGradient;
1258 CanvasKit.MakeTwoPointConicalGradientShader = CanvasKit.SkShader.MakeTwoPointConicalGradient;
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001259
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001260 // Run through the JS files that are added at compile time.
1261 if (CanvasKit._extraInitializations) {
1262 CanvasKit._extraInitializations.forEach(function(init) {
1263 init();
1264 });
Kevin Lubickeb2f6b02018-11-29 15:07:02 -05001265 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001266}; // end CanvasKit.onRuntimeInitialized, that is, anything changing prototypes or dynamic.
Kevin Lubickeb2f6b02018-11-29 15:07:02 -05001267
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001268// Accepts an object holding two canvaskit colors.
1269// {
1270// ambient: {r, g, b, a},
1271// spot: {r, g, b, a},
1272// }
1273// Returns the same format
1274CanvasKit.computeTonalColors = function(tonalColors) {
1275 var cPtrAmbi = copy1dArray(tonalColors['ambient'], CanvasKit.HEAPF32);
1276 var cPtrSpot = copy1dArray(tonalColors['spot'], CanvasKit.HEAPF32);
1277 this._computeTonalColors(cPtrAmbi, cPtrSpot);
1278 var result = {
1279 'ambient': copyColorFromWasm(cPtrAmbi),
1280 'spot': copyColorFromWasm(cPtrSpot),
1281 }
1282 return result;
1283}
1284
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001285CanvasKit.LTRBRect = function(l, t, r, b) {
1286 return {
1287 fLeft: l,
1288 fTop: t,
1289 fRight: r,
1290 fBottom: b,
1291 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -05001292}
1293
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001294CanvasKit.XYWHRect = function(x, y, w, h) {
1295 return {
1296 fLeft: x,
1297 fTop: y,
1298 fRight: x+w,
1299 fBottom: y+h,
1300 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -05001301}
1302
Kevin Lubick7d644e12019-09-11 14:22:22 -04001303// RRectXY returns an RRect with the given rect and a radiusX and radiusY for
1304// all 4 corners.
1305CanvasKit.RRectXY = function(rect, rx, ry) {
1306 return {
1307 rect: rect,
1308 rx1: rx,
1309 ry1: ry,
1310 rx2: rx,
1311 ry2: ry,
1312 rx3: rx,
1313 ry3: ry,
1314 rx4: rx,
1315 ry4: ry,
1316 };
1317}
1318
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001319CanvasKit.MakePathFromCmds = function(cmds) {
1320 var ptrLen = loadCmdsTypedArray(cmds);
1321 var path = CanvasKit._MakePathFromCmds(ptrLen[0], ptrLen[1]);
1322 CanvasKit._free(ptrLen[0]);
1323 return path;
1324}
1325
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001326// data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
Kevin Lubick6b921b72019-09-18 16:18:17 -04001327CanvasKit.MakeAnimatedImageFromEncoded = function(data) {
1328 data = new Uint8Array(data);
1329
1330 var iptr = CanvasKit._malloc(data.byteLength);
1331 CanvasKit.HEAPU8.set(data, iptr);
1332 var img = CanvasKit._decodeAnimatedImage(iptr, data.byteLength);
1333 if (!img) {
1334 SkDebug('Could not decode animated image');
1335 return null;
1336 }
1337 return img;
1338}
1339
1340// data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001341CanvasKit.MakeImageFromEncoded = function(data) {
1342 data = new Uint8Array(data);
1343
1344 var iptr = CanvasKit._malloc(data.byteLength);
1345 CanvasKit.HEAPU8.set(data, iptr);
1346 var img = CanvasKit._decodeImage(iptr, data.byteLength);
1347 if (!img) {
1348 SkDebug('Could not decode image');
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001349 return null;
1350 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001351 return img;
1352}
1353
Kevin Lubickeda0b432019-12-02 08:26:48 -05001354// pixels must be a Uint8Array with bytes representing the pixel values
1355// (e.g. each set of 4 bytes could represent RGBA values for a single pixel).
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001356CanvasKit.MakeImage = function(pixels, width, height, alphaType, colorType, colorSpace) {
Kevin Lubickeda0b432019-12-02 08:26:48 -05001357 var bytesPerPixel = pixels.length / (width * height);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001358 var info = {
1359 'width': width,
1360 'height': height,
1361 'alphaType': alphaType,
1362 'colorType': colorType,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001363 'colorSpace': colorSpace,
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001364 };
Kevin Lubickeda0b432019-12-02 08:26:48 -05001365 var pptr = copy1dArray(pixels, CanvasKit.HEAPU8);
1366 // No need to _free pptr, Image takes it with SkData::MakeFromMalloc
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001367
Kevin Lubickeda0b432019-12-02 08:26:48 -05001368 return CanvasKit._MakeImage(info, pptr, pixels.length, width * bytesPerPixel);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001369}
1370
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001371// colors is an array of float color arrays
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001372CanvasKit.MakeSkVertices = function(mode, positions, textureCoordinates, colors,
Mike Reed5caf9352020-03-02 14:57:09 -05001373 indices, isVolatile) {
Kevin Lubickb3574c92019-03-06 08:25:36 -05001374 // Default isVolitile to true if not set
1375 isVolatile = isVolatile === undefined ? true : isVolatile;
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001376 var idxCount = (indices && indices.length) || 0;
1377
1378 var flags = 0;
1379 // These flags are from SkVertices.h and should be kept in sync with those.
1380 if (textureCoordinates && textureCoordinates.length) {
1381 flags |= (1 << 0);
1382 }
1383 if (colors && colors.length) {
1384 flags |= (1 << 1);
1385 }
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001386 if (!isVolatile) {
Mike Reed5caf9352020-03-02 14:57:09 -05001387 flags |= (1 << 2);
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001388 }
1389
1390 var builder = new CanvasKit._SkVerticesBuilder(mode, positions.length, idxCount, flags);
1391
1392 copy2dArray(positions, CanvasKit.HEAPF32, builder.positions());
1393 if (builder.texCoords()) {
1394 copy2dArray(textureCoordinates, CanvasKit.HEAPF32, builder.texCoords());
1395 }
1396 if (builder.colors()) {
Nathaniel Nifonge5d32542020-03-26 09:27:48 -04001397 // Convert from canvaskit 4f colors to 32 bit uint colors which builder supports.
1398 copy1dArray(colors.map(toUint32Color), CanvasKit.HEAPU32, builder.colors());
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001399 }
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001400 if (builder.indices()) {
1401 copy1dArray(indices, CanvasKit.HEAPU16, builder.indices());
1402 }
Kevin Lubickb3574c92019-03-06 08:25:36 -05001403
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001404 var idxCount = (indices && indices.length) || 0;
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001405 // Create the vertices, which owns the memory that the builder had allocated.
1406 return builder.detach();
Kevin Lubicka4f218d2020-01-14 08:39:09 -05001407};