blob: 0135dbbbaff1cfcc0bc3332851f40eaf2e8b1ce7 [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 Lubick93f1a382020-06-02 16:15:23 -040011 _scratchColor = CanvasKit.Malloc(Float32Array, 4); // 4 color scalars.
Kevin Lubickb42660f2020-06-03 09:58:27 -040012 _scratchColorPtr = _scratchColor['byteOffset'];
Kevin Lubick6aa38692020-06-01 11:25:47 -040013
14 _scratch4x4Matrix = CanvasKit.Malloc(Float32Array, 16); // 16 matrix scalars.
Kevin Lubickb42660f2020-06-03 09:58:27 -040015 _scratch4x4MatrixPtr = _scratch4x4Matrix['byteOffset'];
Kevin Lubick6aa38692020-06-01 11:25:47 -040016
17 _scratch3x3Matrix = CanvasKit.Malloc(Float32Array, 9); // 9 matrix scalars.
Kevin Lubickb42660f2020-06-03 09:58:27 -040018 _scratch3x3MatrixPtr = _scratch3x3Matrix['byteOffset'];
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -040019 // Create single copies of all three supported color spaces
20 // These are sk_sp<SkColorSpace>
21 CanvasKit.SkColorSpace.SRGB = CanvasKit.SkColorSpace._MakeSRGB();
22 CanvasKit.SkColorSpace.DISPLAY_P3 = CanvasKit.SkColorSpace._MakeDisplayP3();
23 CanvasKit.SkColorSpace.ADOBE_RGB = CanvasKit.SkColorSpace._MakeAdobeRGB();
24
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050025 // Add some helpers for matrices. This is ported from SkMatrix.cpp
26 // to save complexity and overhead of going back and forth between
27 // C++ and JS layers.
28 // I would have liked to use something like DOMMatrix, except it
29 // isn't widely supported (would need polyfills) and it doesn't
30 // have a mapPoints() function (which could maybe be tacked on here).
31 // If DOMMatrix catches on, it would be worth re-considering this usage.
32 CanvasKit.SkMatrix = {};
Nathaniel Nifong77798b42020-02-21 17:15:22 -050033 function sdot() { // to be called with an even number of scalar args
34 var acc = 0;
35 for (var i=0; i < arguments.length-1; i+=2) {
36 acc += arguments[i] * arguments[i+1];
37 }
38 return acc;
39 }
40
41
42 // Private general matrix functions used in both 3x3s and 4x4s.
43 // Return a square identity matrix of size n.
44 var identityN = function(n) {
45 var size = n*n;
46 var m = new Array(size);
47 while(size--) {
48 m[size] = size%(n+1) == 0 ? 1.0 : 0.0;
49 }
50 return m;
51 }
52
53 // Stride, a function for compactly representing several ways of copying an array into another.
54 // Write vector `v` into matrix `m`. `m` is a matrix encoded as an array in row-major
55 // order. Its width is passed as `width`. `v` is an array with length < (m.length/width).
56 // An element of `v` is copied into `m` starting at `offset` and moving `colStride` cols right
57 // each row.
58 //
59 // For example, a width of 4, offset of 3, and stride of -1 would put the vector here.
60 // _ _ 0 _
61 // _ 1 _ _
62 // 2 _ _ _
63 // _ _ _ 3
64 //
65 var stride = function(v, m, width, offset, colStride) {
66 for (var i=0; i<v.length; i++) {
67 m[i * width + // column
68 (i * colStride + offset + width) % width // row
69 ] = v[i];
70 }
71 return m;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050072 }
73
74 CanvasKit.SkMatrix.identity = function() {
Nathaniel Nifong77798b42020-02-21 17:15:22 -050075 return identityN(3);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050076 };
77
78 // Return the inverse (if it exists) of this matrix.
Kevin Lubick9b56cea2020-04-06 08:16:18 -040079 // Otherwise, return null.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050080 CanvasKit.SkMatrix.invert = function(m) {
Nathaniel Nifong77798b42020-02-21 17:15:22 -050081 // Find the determinant by the sarrus rule. https://en.wikipedia.org/wiki/Rule_of_Sarrus
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050082 var det = m[0]*m[4]*m[8] + m[1]*m[5]*m[6] + m[2]*m[3]*m[7]
83 - m[2]*m[4]*m[6] - m[1]*m[3]*m[8] - m[0]*m[5]*m[7];
84 if (!det) {
85 SkDebug('Warning, uninvertible matrix');
Nathaniel Nifong77798b42020-02-21 17:15:22 -050086 return null;
Kevin Lubick1a05fce2018-11-20 12:51:16 -050087 }
Nathaniel Nifong77798b42020-02-21 17:15:22 -050088 // Return the inverse by the formula adj(m)/det.
89 // adj (adjugate) of a 3x3 is the transpose of it's cofactor matrix.
90 // a cofactor matrix is a matrix where each term is +-det(N) where matrix N is the 2x2 formed
91 // by removing the row and column we're currently setting from the source.
92 // the sign alternates in a checkerboard pattern with a `+` at the top left.
93 // that's all been combined here into one expression.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050094 return [
95 (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,
96 (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,
97 (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,
98 ];
99 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500100
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500101 // Maps the given points according to the passed in matrix.
102 // Results are done in place.
103 // See SkMatrix.h::mapPoints for the docs on the math.
104 CanvasKit.SkMatrix.mapPoints = function(matrix, ptArr) {
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500105 if (skIsDebug && (ptArr.length % 2)) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500106 throw 'mapPoints requires an even length arr';
Kevin Lubickb9db3902018-11-26 11:47:54 -0500107 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500108 for (var i = 0; i < ptArr.length; i+=2) {
109 var x = ptArr[i], y = ptArr[i+1];
110 // Gx+Hy+I
111 var denom = matrix[6]*x + matrix[7]*y + matrix[8];
112 // Ax+By+C
113 var xTrans = matrix[0]*x + matrix[1]*y + matrix[2];
114 // Dx+Ey+F
115 var yTrans = matrix[3]*x + matrix[4]*y + matrix[5];
116 ptArr[i] = xTrans/denom;
117 ptArr[i+1] = yTrans/denom;
118 }
119 return ptArr;
120 };
Kevin Lubickb9db3902018-11-26 11:47:54 -0500121
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500122 function isnumber(val) { return val !== NaN; };
123
Kevin Lubickc89ca0b2020-04-02 14:30:00 -0400124 // generalized iterative algorithm for multiplying two matrices.
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500125 function multiply(m1, m2, size) {
126
127 if (skIsDebug && (!m1.every(isnumber) || !m2.every(isnumber))) {
128 throw 'Some members of matrices are NaN m1='+m1+', m2='+m2+'';
129 }
130 if (skIsDebug && (m1.length !== m2.length)) {
131 throw 'Undefined for matrices of different sizes. m1.length='+m1.length+', m2.length='+m2.length;
132 }
133 if (skIsDebug && (size*size !== m1.length)) {
134 throw 'Undefined for non-square matrices. array size was '+size;
135 }
136
137 var result = Array(m1.length);
138 for (var r = 0; r < size; r++) {
139 for (var c = 0; c < size; c++) {
140 // accumulate a sum of m1[r,k]*m2[k, c]
141 var acc = 0;
142 for (var k = 0; k < size; k++) {
143 acc += m1[size * r + k] * m2[size * k + c];
144 }
145 result[r * size + c] = acc;
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500146 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500147 }
148 return result;
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500149 };
150
151 // Accept an integer indicating the size of the matrices being multiplied (3 for 3x3), and any
152 // number of matrices following it.
153 function multiplyMany(size, listOfMatrices) {
154 if (skIsDebug && (listOfMatrices.length < 2)) {
155 throw 'multiplication expected two or more matrices';
156 }
157 var result = multiply(listOfMatrices[0], listOfMatrices[1], size);
158 var next = 2;
159 while (next < listOfMatrices.length) {
160 result = multiply(result, listOfMatrices[next], size);
161 next++;
162 }
163 return result;
164 };
165
166 // Accept any number 3x3 of matrices as arguments, multiply them together.
Kevin Lubick9e2d3842020-04-01 13:42:15 -0400167 // Matrix multiplication is associative but not commutative. the order of the arguments
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500168 // matters, but it does not matter that this implementation multiplies them left to right.
169 CanvasKit.SkMatrix.multiply = function() {
170 return multiplyMany(3, arguments);
171 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500172
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500173 // Return a matrix representing a rotation by n radians.
174 // px, py optionally say which point the rotation should be around
175 // with the default being (0, 0);
176 CanvasKit.SkMatrix.rotated = function(radians, px, py) {
177 px = px || 0;
178 py = py || 0;
179 var sinV = Math.sin(radians);
180 var cosV = Math.cos(radians);
181 return [
182 cosV, -sinV, sdot( sinV, py, 1 - cosV, px),
183 sinV, cosV, sdot(-sinV, px, 1 - cosV, py),
184 0, 0, 1,
185 ];
186 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400187
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500188 CanvasKit.SkMatrix.scaled = function(sx, sy, px, py) {
189 px = px || 0;
190 py = py || 0;
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500191 var m = stride([sx, sy], identityN(3), 3, 0, 1);
192 return stride([px-sx*px, py-sy*py], m, 3, 2, 0);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500193 };
Kevin Lubickda3d8ac2019-01-07 11:08:55 -0500194
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500195 CanvasKit.SkMatrix.skewed = function(kx, ky, px, py) {
196 px = px || 0;
197 py = py || 0;
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500198 var m = stride([kx, ky], identityN(3), 3, 1, -1);
199 return stride([-kx*px, -ky*py], m, 3, 2, 0);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500200 };
Alexander Khovansky3e119332018-11-15 02:01:19 +0300201
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500202 CanvasKit.SkMatrix.translated = function(dx, dy) {
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500203 return stride(arguments, identityN(3), 3, 2, 0);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500204 };
Kevin Lubick1646e7d2018-12-07 13:03:08 -0500205
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500206 // Functions for manipulating vectors.
207 // Loosely based off of SkV3 in SkM44.h but skia also has SkVec2 and Skv4. This combines them and
208 // works on vectors of any length.
209 CanvasKit.SkVector = {};
210 CanvasKit.SkVector.dot = function(a, b) {
211 if (skIsDebug && (a.length !== b.length)) {
212 throw 'Cannot perform dot product on arrays of different length ('+a.length+' vs '+b.length+')';
213 }
214 return a.map(function(v, i) { return v*b[i] }).reduce(function(acc, cur) { return acc + cur; });
215 }
216 CanvasKit.SkVector.lengthSquared = function(v) {
217 return CanvasKit.SkVector.dot(v, v);
218 }
219 CanvasKit.SkVector.length = function(v) {
220 return Math.sqrt(CanvasKit.SkVector.lengthSquared(v));
221 }
222 CanvasKit.SkVector.mulScalar = function(v, s) {
223 return v.map(function(i) { return i*s });
224 }
225 CanvasKit.SkVector.add = function(a, b) {
226 return a.map(function(v, i) { return v+b[i] });
227 }
228 CanvasKit.SkVector.sub = function(a, b) {
229 return a.map(function(v, i) { return v-b[i]; });
230 }
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500231 CanvasKit.SkVector.dist = function(a, b) {
232 return CanvasKit.SkVector.length(CanvasKit.SkVector.sub(a, b));
233 }
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500234 CanvasKit.SkVector.normalize = function(v) {
235 return CanvasKit.SkVector.mulScalar(v, 1/CanvasKit.SkVector.length(v));
236 }
237 CanvasKit.SkVector.cross = function(a, b) {
238 if (skIsDebug && (a.length !== 3 || a.length !== 3)) {
239 throw 'Cross product is only defined for 3-dimensional vectors (a.length='+a.length+', b.length='+b.length+')';
240 }
241 return [
242 a[1]*b[2] - a[2]*b[1],
243 a[2]*b[0] - a[0]*b[2],
244 a[0]*b[1] - a[1]*b[0],
245 ];
246 }
247
Kevin Lubickc1d08982020-04-06 13:52:15 -0400248 // Functions for creating and manipulating (row-major) 4x4 matrices. Accepted in place of
249 // SkM44 in canvas methods, for the same reasons as the 3x3 matrices above.
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500250 // ported from C++ code in SkM44.cpp
251 CanvasKit.SkM44 = {};
252 // Create a 4x4 identity matrix
253 CanvasKit.SkM44.identity = function() {
254 return identityN(4);
255 }
256
257 // Anything named vec below is an array of length 3 representing a vector/point in 3D space.
258 // Create a 4x4 matrix representing a translate by the provided 3-vec
259 CanvasKit.SkM44.translated = function(vec) {
260 return stride(vec, identityN(4), 4, 3, 0);
261 }
262 // Create a 4x4 matrix representing a scaling by the provided 3-vec
263 CanvasKit.SkM44.scaled = function(vec) {
264 return stride(vec, identityN(4), 4, 0, 1);
265 }
266 // Create a 4x4 matrix representing a rotation about the provided axis 3-vec.
267 // axis does not need to be normalized.
268 CanvasKit.SkM44.rotated = function(axisVec, radians) {
269 return CanvasKit.SkM44.rotatedUnitSinCos(
270 CanvasKit.SkVector.normalize(axisVec), Math.sin(radians), Math.cos(radians));
271 }
272 // Create a 4x4 matrix representing a rotation about the provided normalized axis 3-vec.
273 // Rotation is provided redundantly as both sin and cos values.
274 // This rotate can be used when you already have the cosAngle and sinAngle values
275 // so you don't have to atan(cos/sin) to call roatated() which expects an angle in radians.
276 // this does no checking! Behavior for invalid sin or cos values or non-normalized axis vectors
Nathaniel Nifong3392ebe2020-06-01 09:21:36 -0400277 // is incorrect. Prefer rotated().
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500278 CanvasKit.SkM44.rotatedUnitSinCos = function(axisVec, sinAngle, cosAngle) {
279 var x = axisVec[0];
280 var y = axisVec[1];
281 var z = axisVec[2];
282 var c = cosAngle;
283 var s = sinAngle;
284 var t = 1 - c;
285 return [
286 t*x*x + c, t*x*y - s*z, t*x*z + s*y, 0,
287 t*x*y + s*z, t*y*y + c, t*y*z - s*x, 0,
288 t*x*z - s*y, t*y*z + s*x, t*z*z + c, 0,
289 0, 0, 0, 1
290 ];
291 }
292 // Create a 4x4 matrix representing a camera at eyeVec, pointed at centerVec.
293 CanvasKit.SkM44.lookat = function(eyeVec, centerVec, upVec) {
294 var f = CanvasKit.SkVector.normalize(CanvasKit.SkVector.sub(centerVec, eyeVec));
295 var u = CanvasKit.SkVector.normalize(upVec);
296 var s = CanvasKit.SkVector.normalize(CanvasKit.SkVector.cross(f, u));
297
298 var m = CanvasKit.SkM44.identity();
299 // set each column's top three numbers
Kevin Lubickc1d08982020-04-06 13:52:15 -0400300 stride(s, m, 4, 0, 0);
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500301 stride(CanvasKit.SkVector.cross(s, f), m, 4, 1, 0);
302 stride(CanvasKit.SkVector.mulScalar(f, -1), m, 4, 2, 0);
Kevin Lubickc1d08982020-04-06 13:52:15 -0400303 stride(eyeVec, m, 4, 3, 0);
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500304
305 var m2 = CanvasKit.SkM44.invert(m);
306 if (m2 === null) {
307 return CanvasKit.SkM44.identity();
308 }
309 return m2;
310 }
311 // Create a 4x4 matrix representing a perspective. All arguments are scalars.
312 // angle is in radians.
313 CanvasKit.SkM44.perspective = function(near, far, angle) {
314 if (skIsDebug && (far <= near)) {
315 throw "far must be greater than near when constructing SkM44 using perspective.";
316 }
317 var dInv = 1 / (far - near);
318 var halfAngle = angle / 2;
319 var cot = Math.cos(halfAngle) / Math.sin(halfAngle);
320 return [
321 cot, 0, 0, 0,
322 0, cot, 0, 0,
323 0, 0, (far+near)*dInv, 2*far*near*dInv,
324 0, 0, -1, 1,
325 ];
326 }
327 // Returns the number at the given row and column in matrix m.
328 CanvasKit.SkM44.rc = function(m, r, c) {
329 return m[r*4+c];
330 }
331 // Accepts any number of 4x4 matrix arguments, multiplies them left to right.
332 CanvasKit.SkM44.multiply = function() {
333 return multiplyMany(4, arguments);
334 }
335
336 // Invert the 4x4 matrix if it is invertible and return it. if not, return null.
337 // taken from SkM44.cpp (altered to use row-major order)
338 // m is not altered.
339 CanvasKit.SkM44.invert = function(m) {
340 if (skIsDebug && !m.every(isnumber)) {
341 throw 'some members of matrix are NaN m='+m;
342 }
343
344 var a00 = m[0];
345 var a01 = m[4];
346 var a02 = m[8];
347 var a03 = m[12];
348 var a10 = m[1];
349 var a11 = m[5];
350 var a12 = m[9];
351 var a13 = m[13];
352 var a20 = m[2];
353 var a21 = m[6];
354 var a22 = m[10];
355 var a23 = m[14];
356 var a30 = m[3];
357 var a31 = m[7];
358 var a32 = m[11];
359 var a33 = m[15];
360
361 var b00 = a00 * a11 - a01 * a10;
362 var b01 = a00 * a12 - a02 * a10;
363 var b02 = a00 * a13 - a03 * a10;
364 var b03 = a01 * a12 - a02 * a11;
365 var b04 = a01 * a13 - a03 * a11;
366 var b05 = a02 * a13 - a03 * a12;
367 var b06 = a20 * a31 - a21 * a30;
368 var b07 = a20 * a32 - a22 * a30;
369 var b08 = a20 * a33 - a23 * a30;
370 var b09 = a21 * a32 - a22 * a31;
371 var b10 = a21 * a33 - a23 * a31;
372 var b11 = a22 * a33 - a23 * a32;
373
374 // calculate determinate
375 var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
376 var invdet = 1.0 / det;
377
378 // bail out if the matrix is not invertible
379 if (det === 0 || invdet === Infinity) {
380 SkDebug('Warning, uninvertible matrix');
381 return null;
382 }
383
384 b00 *= invdet;
385 b01 *= invdet;
386 b02 *= invdet;
387 b03 *= invdet;
388 b04 *= invdet;
389 b05 *= invdet;
390 b06 *= invdet;
391 b07 *= invdet;
392 b08 *= invdet;
393 b09 *= invdet;
394 b10 *= invdet;
395 b11 *= invdet;
396
397 // store result in row major order
398 var tmp = [
399 a11 * b11 - a12 * b10 + a13 * b09,
400 a12 * b08 - a10 * b11 - a13 * b07,
401 a10 * b10 - a11 * b08 + a13 * b06,
402 a11 * b07 - a10 * b09 - a12 * b06,
403
404 a02 * b10 - a01 * b11 - a03 * b09,
405 a00 * b11 - a02 * b08 + a03 * b07,
406 a01 * b08 - a00 * b10 - a03 * b06,
407 a00 * b09 - a01 * b07 + a02 * b06,
408
409 a31 * b05 - a32 * b04 + a33 * b03,
410 a32 * b02 - a30 * b05 - a33 * b01,
411 a30 * b04 - a31 * b02 + a33 * b00,
412 a31 * b01 - a30 * b03 - a32 * b00,
413
414 a22 * b04 - a21 * b05 - a23 * b03,
415 a20 * b05 - a22 * b02 + a23 * b01,
416 a21 * b02 - a20 * b04 - a23 * b00,
417 a20 * b03 - a21 * b01 + a22 * b00,
418 ];
419
420
421 if (!tmp.every(function(val) { return val !== NaN && val !== Infinity && val !== -Infinity; })) {
422 SkDebug('inverted matrix contains infinities or NaN '+tmp);
423 return null;
424 }
425 return tmp;
426 }
427
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500428 CanvasKit.SkM44.transpose = function(m) {
429 return [
430 m[0], m[4], m[8], m[12],
431 m[1], m[5], m[9], m[13],
432 m[2], m[6], m[10], m[14],
433 m[3], m[7], m[11], m[15],
434 ];
435 }
Nathaniel Nifong77798b42020-02-21 17:15:22 -0500436
Kevin Lubickd3729342019-09-12 11:11:25 -0400437 // An SkColorMatrix is a 4x4 color matrix that transforms the 4 color channels
438 // with a 1x4 matrix that post-translates those 4 channels.
439 // For example, the following is the layout with the scale (S) and post-transform
440 // (PT) items indicated.
441 // RS, 0, 0, 0 | RPT
442 // 0, GS, 0, 0 | GPT
443 // 0, 0, BS, 0 | BPT
444 // 0, 0, 0, AS | APT
445 //
446 // Much of this was hand-transcribed from SkColorMatrix.cpp, because it's easier to
447 // deal with a Float32Array of length 20 than to try to expose the SkColorMatrix object.
448
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500449 var rScale = 0;
450 var gScale = 6;
451 var bScale = 12;
452 var aScale = 18;
453
Kevin Lubickd3729342019-09-12 11:11:25 -0400454 var rPostTrans = 4;
455 var gPostTrans = 9;
456 var bPostTrans = 14;
457 var aPostTrans = 19;
458
459 CanvasKit.SkColorMatrix = {};
460 CanvasKit.SkColorMatrix.identity = function() {
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500461 var m = new Float32Array(20);
462 m[rScale] = 1;
463 m[gScale] = 1;
464 m[bScale] = 1;
465 m[aScale] = 1;
466 return m;
Kevin Lubickd3729342019-09-12 11:11:25 -0400467 }
468
469 CanvasKit.SkColorMatrix.scaled = function(rs, gs, bs, as) {
Nathaniel Nifongcc5415a2020-02-23 14:26:33 -0500470 var m = new Float32Array(20);
471 m[rScale] = rs;
472 m[gScale] = gs;
473 m[bScale] = bs;
474 m[aScale] = as;
475 return m;
Kevin Lubickd3729342019-09-12 11:11:25 -0400476 }
477
478 var rotateIndices = [
479 [6, 7, 11, 12],
480 [0, 10, 2, 12],
481 [0, 1, 5, 6],
482 ];
483 // axis should be 0, 1, 2 for r, g, b
484 CanvasKit.SkColorMatrix.rotated = function(axis, sine, cosine) {
485 var m = CanvasKit.SkColorMatrix.identity();
486 var indices = rotateIndices[axis];
487 m[indices[0]] = cosine;
488 m[indices[1]] = sine;
489 m[indices[2]] = -sine;
490 m[indices[3]] = cosine;
491 return m;
492 }
493
494 // m is a SkColorMatrix (i.e. a Float32Array), and this sets the 4 "special"
495 // params that will translate the colors after they are multiplied by the 4x4 matrix.
496 CanvasKit.SkColorMatrix.postTranslate = function(m, dr, dg, db, da) {
497 m[rPostTrans] += dr;
498 m[gPostTrans] += dg;
499 m[bPostTrans] += db;
500 m[aPostTrans] += da;
501 return m;
502 }
503
504 // concat returns a new SkColorMatrix that is the result of multiplying outer*inner;
505 CanvasKit.SkColorMatrix.concat = function(outer, inner) {
506 var m = new Float32Array(20);
507 var index = 0;
508 for (var j = 0; j < 20; j += 5) {
509 for (var i = 0; i < 4; i++) {
510 m[index++] = outer[j + 0] * inner[i + 0] +
511 outer[j + 1] * inner[i + 5] +
512 outer[j + 2] * inner[i + 10] +
513 outer[j + 3] * inner[i + 15];
514 }
515 m[index++] = outer[j + 0] * inner[4] +
516 outer[j + 1] * inner[9] +
517 outer[j + 2] * inner[14] +
518 outer[j + 3] * inner[19] +
519 outer[j + 4];
520 }
521
522 return m;
Kevin Lubickd9b9e5e2020-06-23 16:58:10 -0400523 };
524
525 CanvasKit.SkPath.MakeFromCmds = function(cmds) {
526 var ptrLen = loadCmdsTypedArray(cmds);
527 var path = CanvasKit.SkPath._MakeFromCmds(ptrLen[0], ptrLen[1]);
528 CanvasKit._free(ptrLen[0]);
529 return path;
530 };
531
532 // Deprecated
533 CanvasKit.MakePathFromCmds = CanvasKit.SkPath.MakeFromCmds;
534
535 // The weights array is optional (only used for conics).
536 CanvasKit.SkPath.MakeFromVerbsPointsWeights = function(verbs, pts, weights) {
537 var verbsPtr = copy1dArray(verbs, "HEAPU8");
538 var pointsPtr = copy1dArray(pts, "HEAPF32");
539 var weightsPtr = copy1dArray(weights, "HEAPF32");
540 var numWeights = (weights && weights.length) || 0;
541 var path = CanvasKit.SkPath._MakeFromVerbsPointsWeights(
542 verbsPtr, verbs.length, pointsPtr, pts.length, weightsPtr, numWeights);
543 freeArraysThatAreNotMallocedByUsers(verbsPtr, verbs);
544 freeArraysThatAreNotMallocedByUsers(pointsPtr, pts);
545 freeArraysThatAreNotMallocedByUsers(weightsPtr, weights);
546 return path;
547 };
Kevin Lubickd3729342019-09-12 11:11:25 -0400548
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500549 CanvasKit.SkPath.prototype.addArc = function(oval, startAngle, sweepAngle) {
550 // see arc() for the HTMLCanvas version
551 // note input angles are degrees.
552 this._addArc(oval, startAngle, sweepAngle);
553 return this;
554 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400555
Kevin Lubicke384df42019-08-26 15:48:09 -0400556 CanvasKit.SkPath.prototype.addOval = function(oval, isCCW, startIndex) {
557 if (startIndex === undefined) {
558 startIndex = 1;
559 }
560 this._addOval(oval, !!isCCW, startIndex);
561 return this;
562 };
563
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500564 CanvasKit.SkPath.prototype.addPath = function() {
565 // Takes 1, 2, 7, or 10 required args, where the first arg is always the path.
566 // The last arg is optional and chooses between add or extend mode.
567 // The options for the remaining args are:
568 // - an array of 6 or 9 parameters (perspective is optional)
569 // - the 9 parameters of a full matrix or
570 // the 6 non-perspective params of a matrix.
571 var args = Array.prototype.slice.call(arguments);
572 var path = args[0];
573 var extend = false;
574 if (typeof args[args.length-1] === "boolean") {
575 extend = args.pop();
576 }
577 if (args.length === 1) {
578 // Add path, unchanged. Use identity matrix
579 this._addPath(path, 1, 0, 0,
580 0, 1, 0,
581 0, 0, 1,
582 extend);
583 } else if (args.length === 2) {
584 // User provided the 9 params of a full matrix as an array.
585 var a = args[1];
586 this._addPath(path, a[0], a[1], a[2],
587 a[3], a[4], a[5],
588 a[6] || 0, a[7] || 0, a[8] || 1,
589 extend);
590 } else if (args.length === 7 || args.length === 10) {
591 // User provided the 9 params of a (full) matrix directly.
592 // (or just the 6 non perspective ones)
593 // These are in the same order as what Skia expects.
594 var a = args;
595 this._addPath(path, a[1], a[2], a[3],
596 a[4], a[5], a[6],
597 a[7] || 0, a[8] || 0, a[9] || 1,
598 extend);
599 } else {
600 SkDebug('addPath expected to take 1, 2, 7, or 10 required args. Got ' + args.length);
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400601 return null;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500602 }
603 return this;
604 };
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400605
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500606 // points is either an array of [x, y] where x and y are numbers or
607 // a typed array from Malloc where the even indices will be treated
608 // as x coordinates and the odd indices will be treated as y coordinates.
609 CanvasKit.SkPath.prototype.addPoly = function(points, close) {
610 var ptr;
611 var n;
612 // This was created with CanvasKit.Malloc, so assume the user has
613 // already been filled with data.
614 if (points['_ck']) {
615 ptr = points.byteOffset;
616 n = points.length/2;
617 } else {
Kevin Lubick69e46da2020-06-05 07:13:48 -0400618 ptr = copy2dArray(points, "HEAPF32");
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500619 n = points.length;
620 }
621 this._addPoly(ptr, n, close);
Kevin Lubickcf118922020-05-28 14:43:38 -0400622 freeArraysThatAreNotMallocedByUsers(ptr, points);
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500623 return this;
624 };
625
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500626 CanvasKit.SkPath.prototype.addRect = function() {
627 // Takes 1, 2, 4 or 5 args
628 // - SkRect
629 // - SkRect, isCCW
630 // - left, top, right, bottom
631 // - left, top, right, bottom, isCCW
632 if (arguments.length === 1 || arguments.length === 2) {
633 var r = arguments[0];
634 var ccw = arguments[1] || false;
635 this._addRect(r.fLeft, r.fTop, r.fRight, r.fBottom, ccw);
636 } else if (arguments.length === 4 || arguments.length === 5) {
637 var a = arguments;
638 this._addRect(a[0], a[1], a[2], a[3], a[4] || false);
639 } else {
640 SkDebug('addRect expected to take 1, 2, 4, or 5 args. Got ' + arguments.length);
Kevin Lubick217056c2018-09-20 17:39:31 -0400641 return null;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500642 }
643 return this;
644 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400645
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500646 CanvasKit.SkPath.prototype.addRoundRect = function() {
647 // Takes 3, 4, 6 or 7 args
Nathaniel Nifong3392ebe2020-06-01 09:21:36 -0400648 // - SkRect, radii (an array of 8 numbers), ccw
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500649 // - SkRect, rx, ry, ccw
650 // - left, top, right, bottom, radii, ccw
651 // - left, top, right, bottom, rx, ry, ccw
652 var args = arguments;
653 if (args.length === 3 || args.length === 6) {
654 var radii = args[args.length-2];
Kevin Lubickcf118922020-05-28 14:43:38 -0400655 } else if (args.length === 4 || args.length === 7){
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500656 // duplicate the given (rx, ry) pairs for each corner.
657 var rx = args[args.length-3];
658 var ry = args[args.length-2];
659 var radii = [rx, ry, rx, ry, rx, ry, rx, ry];
660 } else {
661 SkDebug('addRoundRect expected to take 3, 4, 6, or 7 args. Got ' + args.length);
662 return null;
663 }
664 if (radii.length !== 8) {
665 SkDebug('addRoundRect needs 8 radii provided. Got ' + radii.length);
666 return null;
667 }
Kevin Lubick69e46da2020-06-05 07:13:48 -0400668 var rptr = copy1dArray(radii, "HEAPF32");
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500669 if (args.length === 3 || args.length === 4) {
670 var r = args[0];
671 var ccw = args[args.length - 1];
672 this._addRoundRect(r.fLeft, r.fTop, r.fRight, r.fBottom, rptr, ccw);
673 } else if (args.length === 6 || args.length === 7) {
674 var a = args;
675 this._addRoundRect(a[0], a[1], a[2], a[3], rptr, ccw);
676 }
Kevin Lubickcf118922020-05-28 14:43:38 -0400677 freeArraysThatAreNotMallocedByUsers(rptr, radii);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500678 return this;
679 };
680
Kevin Lubickd9b9e5e2020-06-23 16:58:10 -0400681 // The weights array is optional (only used for conics).
682 CanvasKit.SkPath.prototype.addVerbsPointsWeights = function(verbs, points, weights) {
683 var verbsPtr = copy1dArray(verbs, "HEAPU8");
684 var pointsPtr = copy1dArray(points, "HEAPF32");
685 var weightsPtr = copy1dArray(weights, "HEAPF32");
686 var numWeights = (weights && weights.length) || 0;
687 this._addVerbsPointsWeights(verbsPtr, verbs.length, pointsPtr, points.length,
688 weightsPtr, numWeights);
689 freeArraysThatAreNotMallocedByUsers(verbsPtr, verbs);
690 freeArraysThatAreNotMallocedByUsers(pointsPtr, points);
691 freeArraysThatAreNotMallocedByUsers(weightsPtr, weights);
692 };
693
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500694 CanvasKit.SkPath.prototype.arc = function(x, y, radius, startAngle, endAngle, ccw) {
695 // emulates the HTMLCanvas behavior. See addArc() for the SkPath version.
696 // Note input angles are radians.
697 var bounds = CanvasKit.LTRBRect(x-radius, y-radius, x+radius, y+radius);
698 var sweep = radiansToDegrees(endAngle - startAngle) - (360 * !!ccw);
699 var temp = new CanvasKit.SkPath();
700 temp.addArc(bounds, radiansToDegrees(startAngle), sweep);
701 this.addPath(temp, true);
702 temp.delete();
703 return this;
704 };
705
706 CanvasKit.SkPath.prototype.arcTo = function() {
707 // takes 4, 5 or 7 args
708 // - 5 x1, y1, x2, y2, radius
709 // - 4 oval (as Rect), startAngle, sweepAngle, forceMoveTo
Kevin Lubicke384df42019-08-26 15:48:09 -0400710 // - 7 rx, ry, xAxisRotate, useSmallArc, isCCW, x, y
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500711 var args = arguments;
712 if (args.length === 5) {
713 this._arcTo(args[0], args[1], args[2], args[3], args[4]);
714 } else if (args.length === 4) {
715 this._arcTo(args[0], args[1], args[2], args[3]);
716 } else if (args.length === 7) {
Kevin Lubicke384df42019-08-26 15:48:09 -0400717 this._arcTo(args[0], args[1], args[2], !!args[3], !!args[4], args[5], args[6]);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500718 } else {
719 throw 'Invalid args for arcTo. Expected 4, 5, or 7, got '+ args.length;
720 }
721
722 return this;
723 };
724
725 CanvasKit.SkPath.prototype.close = function() {
726 this._close();
727 return this;
728 };
729
730 CanvasKit.SkPath.prototype.conicTo = function(x1, y1, x2, y2, w) {
731 this._conicTo(x1, y1, x2, y2, w);
732 return this;
733 };
734
735 CanvasKit.SkPath.prototype.cubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
736 this._cubicTo(cp1x, cp1y, cp2x, cp2y, x, y);
737 return this;
738 };
739
740 CanvasKit.SkPath.prototype.dash = function(on, off, phase) {
741 if (this._dash(on, off, phase)) {
Kevin Lubick217056c2018-09-20 17:39:31 -0400742 return this;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500743 }
744 return null;
745 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400746
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500747 CanvasKit.SkPath.prototype.lineTo = function(x, y) {
748 this._lineTo(x, y);
749 return this;
750 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400751
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500752 CanvasKit.SkPath.prototype.moveTo = function(x, y) {
753 this._moveTo(x, y);
754 return this;
755 };
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400756
Kevin Lubicke384df42019-08-26 15:48:09 -0400757 CanvasKit.SkPath.prototype.offset = function(dx, dy) {
758 this._transform(1, 0, dx,
759 0, 1, dy,
760 0, 0, 1);
761 return this;
762 };
763
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500764 CanvasKit.SkPath.prototype.quadTo = function(cpx, cpy, x, y) {
765 this._quadTo(cpx, cpy, x, y);
766 return this;
767 };
768
Kevin Lubick79b71342019-11-01 14:36:52 -0400769 CanvasKit.SkPath.prototype.rArcTo = function(rx, ry, xAxisRotate, useSmallArc, isCCW, dx, dy) {
770 this._rArcTo(rx, ry, xAxisRotate, useSmallArc, isCCW, dx, dy);
771 return this;
772 };
773
774 CanvasKit.SkPath.prototype.rConicTo = function(dx1, dy1, dx2, dy2, w) {
775 this._rConicTo(dx1, dy1, dx2, dy2, w);
776 return this;
777 };
778
779 // These params are all relative
780 CanvasKit.SkPath.prototype.rCubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
781 this._rCubicTo(cp1x, cp1y, cp2x, cp2y, x, y);
782 return this;
783 };
784
785 CanvasKit.SkPath.prototype.rLineTo = function(dx, dy) {
786 this._rLineTo(dx, dy);
787 return this;
788 };
789
790 CanvasKit.SkPath.prototype.rMoveTo = function(dx, dy) {
791 this._rMoveTo(dx, dy);
792 return this;
793 };
794
795 // These params are all relative
796 CanvasKit.SkPath.prototype.rQuadTo = function(cpx, cpy, x, y) {
797 this._rQuadTo(cpx, cpy, x, y);
798 return this;
799 };
800
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500801 CanvasKit.SkPath.prototype.stroke = function(opts) {
802 // Fill out any missing values with the default values.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500803 opts = opts || {};
Kevin Lubick6aa38692020-06-01 11:25:47 -0400804 opts['width'] = opts['width'] || 1;
805 opts['miter_limit'] = opts['miter_limit'] || 4;
806 opts['cap'] = opts['cap'] || CanvasKit.StrokeCap.Butt;
807 opts['join'] = opts['join'] || CanvasKit.StrokeJoin.Miter;
808 opts['precision'] = opts['precision'] || 1;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500809 if (this._stroke(opts)) {
810 return this;
811 }
812 return null;
813 };
814
815 CanvasKit.SkPath.prototype.transform = function() {
816 // Takes 1 or 9 args
817 if (arguments.length === 1) {
818 // argument 1 should be a 6 or 9 element array.
819 var a = arguments[0];
820 this._transform(a[0], a[1], a[2],
821 a[3], a[4], a[5],
822 a[6] || 0, a[7] || 0, a[8] || 1);
823 } else if (arguments.length === 6 || arguments.length === 9) {
824 // these arguments are the 6 or 9 members of the matrix
825 var a = arguments;
826 this._transform(a[0], a[1], a[2],
827 a[3], a[4], a[5],
828 a[6] || 0, a[7] || 0, a[8] || 1);
829 } else {
830 throw 'transform expected to take 1 or 9 arguments. Got ' + arguments.length;
831 }
832 return this;
833 };
834 // isComplement is optional, defaults to false
835 CanvasKit.SkPath.prototype.trim = function(startT, stopT, isComplement) {
836 if (this._trim(startT, stopT, !!isComplement)) {
837 return this;
838 }
839 return null;
840 };
841
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500842 CanvasKit.SkImage.prototype.encodeToData = function() {
843 if (!arguments.length) {
844 return this._encodeToData();
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400845 }
Kevin Lubick53965c92018-10-11 08:51:55 -0400846
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500847 if (arguments.length === 2) {
848 var a = arguments;
849 return this._encodeToDataWithFormat(a[0], a[1]);
Alexander Khovansky3e119332018-11-15 02:01:19 +0300850 }
851
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500852 throw 'encodeToData expected to take 0 or 2 arguments. Got ' + arguments.length;
853 }
Kevin Lubick1ba9c4d2019-02-22 10:04:06 -0500854
Kevin Lubicka064c282019-04-04 09:28:53 -0400855 CanvasKit.SkImage.prototype.makeShader = function(xTileMode, yTileMode, localMatrix) {
Kevin Lubick6bffe392020-04-02 15:24:15 -0400856 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Kevin Lubick6aa38692020-06-01 11:25:47 -0400857 return this._makeShader(xTileMode, yTileMode, localMatrixPtr);
Kevin Lubicka064c282019-04-04 09:28:53 -0400858 }
859
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400860 CanvasKit.SkImage.prototype.readPixels = function(imageInfo, srcX, srcY) {
861 var rowBytes;
Kevin Lubick319524b2020-01-22 15:29:14 -0500862 // Important to use ["string"] notation here, otherwise the closure compiler will
863 // minify away the colorType.
864 switch (imageInfo["colorType"]) {
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400865 case CanvasKit.ColorType.RGBA_8888:
866 rowBytes = imageInfo.width * 4; // 1 byte per channel == 4 bytes per pixel in 8888
867 break;
868 case CanvasKit.ColorType.RGBA_F32:
869 rowBytes = imageInfo.width * 16; // 4 bytes per channel == 16 bytes per pixel in F32
870 break;
871 default:
872 SkDebug("Colortype not yet supported");
873 return;
874 }
875 var pBytes = rowBytes * imageInfo.height;
876 var pPtr = CanvasKit._malloc(pBytes);
877
878 if (!this._readPixels(imageInfo, pPtr, rowBytes, srcX, srcY)) {
879 SkDebug("Could not read pixels with the given inputs");
880 return null;
881 }
882
883 // Put those pixels into a typed array of the right format and then
884 // make a copy with slice() that we can return.
885 var retVal = null;
Kevin Lubick319524b2020-01-22 15:29:14 -0500886 switch (imageInfo["colorType"]) {
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400887 case CanvasKit.ColorType.RGBA_8888:
Bryce Thomas1fa54042020-01-14 13:46:30 -0800888 retVal = new Uint8Array(CanvasKit.HEAPU8.buffer, pPtr, pBytes).slice();
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400889 break;
890 case CanvasKit.ColorType.RGBA_F32:
Bryce Thomas1fa54042020-01-14 13:46:30 -0800891 retVal = new Float32Array(CanvasKit.HEAPU8.buffer, pPtr, pBytes).slice();
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400892 break;
893 }
894
895 // Free the allocated pixels in the WASM memory
896 CanvasKit._free(pPtr);
897 return retVal;
Kevin Lubick6bffe392020-04-02 15:24:15 -0400898 }
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400899
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400900 // Accepts an array of four numbers in the range of 0-1 representing a 4f color
901 CanvasKit.SkCanvas.prototype.clear = function (color4f) {
Kevin Lubick6aa38692020-06-01 11:25:47 -0400902 var cPtr = copyColorToWasm(color4f);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400903 this._clear(cPtr);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400904 }
905
Kevin Lubickc1d08982020-04-06 13:52:15 -0400906 // concat takes a 3x2, a 3x3, or a 4x4 matrix and upscales it (if needed) to 4x4. This is because
907 // under the hood, SkCanvas uses a 4x4 matrix.
Kevin Lubick6bffe392020-04-02 15:24:15 -0400908 CanvasKit.SkCanvas.prototype.concat = function(matr) {
Kevin Lubickc1d08982020-04-06 13:52:15 -0400909 var matrPtr = copy4x4MatrixToWasm(matr);
Kevin Lubick6bffe392020-04-02 15:24:15 -0400910 this._concat(matrPtr);
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400911 }
912
Kevin Lubickc1d08982020-04-06 13:52:15 -0400913 // Deprecated - just use concat
914 CanvasKit.SkCanvas.prototype.concat44 = CanvasKit.SkCanvas.prototype.concat;
915
Kevin Lubickee91c072019-03-29 10:39:52 -0400916 // atlas is an SkImage, e.g. from CanvasKit.MakeImageFromEncoded
Nathaniel Nifongcd75b172020-06-05 11:17:43 -0400917 // srcRects, dstXforms, and colors should be CanvasKit.SkRectBuilder, CanvasKit.RSXFormBuilder,
918 // and CanvasKit.SkColorBuilder (fastest)
919 // Or they can be an array of floats of length 4*number of destinations.
920 // colors are optional and used to tint the drawn images using the optional blend mode
Nathaniel Nifongd05fd0c2020-06-11 08:44:20 -0400921 // Colors may be an SkColorBuilder, a Uint32Array of int colors,
922 // a Flat Float32Array of float colors or a 2d Array of Float32Array(4) (deprecated)
Kevin Lubickee91c072019-03-29 10:39:52 -0400923 CanvasKit.SkCanvas.prototype.drawAtlas = function(atlas, srcRects, dstXforms, paint,
924 /*optional*/ blendMode, colors) {
925 if (!atlas || !paint || !srcRects || !dstXforms) {
926 SkDebug('Doing nothing since missing a required input');
927 return;
928 }
Nathaniel Nifongcd75b172020-06-05 11:17:43 -0400929
930 // builder arguments report the length as the number of rects, but when passed as arrays
931 // their.length attribute is 4x higher because it's the number of total components of all rects.
932 // colors is always going to report the same length, at least until floats colors are supported
933 // by this function.
934 if (srcRects.length !== dstXforms.length) {
Kevin Lubickee91c072019-03-29 10:39:52 -0400935 SkDebug('Doing nothing since input arrays length mismatches');
Nathaniel Nifonge5d32542020-03-26 09:27:48 -0400936 return;
Kevin Lubickee91c072019-03-29 10:39:52 -0400937 }
938 if (!blendMode) {
939 blendMode = CanvasKit.BlendMode.SrcOver;
940 }
941
942 var srcRectPtr;
943 if (srcRects.build) {
944 srcRectPtr = srcRects.build();
945 } else {
Kevin Lubick69e46da2020-06-05 07:13:48 -0400946 srcRectPtr = copy1dArray(srcRects, "HEAPF32");
Kevin Lubickee91c072019-03-29 10:39:52 -0400947 }
948
Nathaniel Nifongcd75b172020-06-05 11:17:43 -0400949 var count = 1;
Kevin Lubickee91c072019-03-29 10:39:52 -0400950 var dstXformPtr;
951 if (dstXforms.build) {
952 dstXformPtr = dstXforms.build();
Nathaniel Nifongcd75b172020-06-05 11:17:43 -0400953 count = dstXforms.length;
Kevin Lubickee91c072019-03-29 10:39:52 -0400954 } else {
Kevin Lubick69e46da2020-06-05 07:13:48 -0400955 dstXformPtr = copy1dArray(dstXforms, "HEAPF32");
Nathaniel Nifongcd75b172020-06-05 11:17:43 -0400956 count = dstXforms.length / 4;
Kevin Lubickee91c072019-03-29 10:39:52 -0400957 }
958
Kevin Lubick6bffe392020-04-02 15:24:15 -0400959 var colorPtr = nullptr;
Kevin Lubickee91c072019-03-29 10:39:52 -0400960 if (colors) {
961 if (colors.build) {
962 colorPtr = colors.build();
963 } else {
Nathaniel Nifongd05fd0c2020-06-11 08:44:20 -0400964 colorPtr = copy1dArray(assureIntColors(colors), "HEAPU32");
Kevin Lubickee91c072019-03-29 10:39:52 -0400965 }
966 }
967
Nathaniel Nifongcd75b172020-06-05 11:17:43 -0400968 this._drawAtlas(atlas, dstXformPtr, srcRectPtr, colorPtr, count, blendMode, paint);
Kevin Lubickee91c072019-03-29 10:39:52 -0400969
970 if (srcRectPtr && !srcRects.build) {
Kevin Lubickcf118922020-05-28 14:43:38 -0400971 freeArraysThatAreNotMallocedByUsers(srcRectPtr, srcRects);
Kevin Lubickee91c072019-03-29 10:39:52 -0400972 }
973 if (dstXformPtr && !dstXforms.build) {
Kevin Lubickcf118922020-05-28 14:43:38 -0400974 freeArraysThatAreNotMallocedByUsers(dstXformPtr, dstXforms);
Kevin Lubickee91c072019-03-29 10:39:52 -0400975 }
976 if (colorPtr && !colors.build) {
Kevin Lubickcf118922020-05-28 14:43:38 -0400977 freeArraysThatAreNotMallocedByUsers(colorPtr, colors);
Kevin Lubickee91c072019-03-29 10:39:52 -0400978 }
Kevin Lubickee91c072019-03-29 10:39:52 -0400979 }
980
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400981 CanvasKit.SkCanvas.prototype.drawColor = function (color4f, mode) {
Kevin Lubick6aa38692020-06-01 11:25:47 -0400982 var cPtr = copyColorToWasm(color4f);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400983 if (mode !== undefined) {
984 this._drawColor(cPtr, mode);
985 } else {
986 this._drawColor(cPtr);
987 }
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400988 }
989
Kevin Lubick93f1a382020-06-02 16:15:23 -0400990 CanvasKit.SkCanvas.prototype.drawColorComponents = function (r, g, b, a, mode) {
991 var cPtr = copyColorComponentsToWasm(r, g, b, a);
992 if (mode !== undefined) {
993 this._drawColor(cPtr, mode);
994 } else {
995 this._drawColor(cPtr);
996 }
997 }
998
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500999 // points is either an array of [x, y] where x and y are numbers or
1000 // a typed array from Malloc where the even indices will be treated
1001 // as x coordinates and the odd indices will be treated as y coordinates.
1002 CanvasKit.SkCanvas.prototype.drawPoints = function(mode, points, paint) {
1003 var ptr;
1004 var n;
1005 // This was created with CanvasKit.Malloc, so assume the user has
1006 // already been filled with data.
1007 if (points['_ck']) {
1008 ptr = points.byteOffset;
1009 n = points.length/2;
1010 } else {
Kevin Lubick69e46da2020-06-05 07:13:48 -04001011 ptr = copy2dArray(points, "HEAPF32");
Kevin Lubick37ab53e2019-11-11 10:06:08 -05001012 n = points.length;
1013 }
1014 this._drawPoints(mode, ptr, n, paint);
Kevin Lubickcf118922020-05-28 14:43:38 -04001015 freeArraysThatAreNotMallocedByUsers(ptr, points);
Kevin Lubick37ab53e2019-11-11 10:06:08 -05001016 }
1017
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001018 CanvasKit.SkCanvas.prototype.drawShadow = function(path, zPlaneParams, lightPos, lightRadius, ambientColor, spotColor, flags) {
Kevin Lubick6aa38692020-06-01 11:25:47 -04001019 var ambiPtr = copyColorToWasmNoScratch(ambientColor);
1020 var spotPtr = copyColorToWasmNoScratch(spotColor);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001021 this._drawShadow(path, zPlaneParams, lightPos, lightRadius, ambiPtr, spotPtr, flags);
Kevin Lubickcf118922020-05-28 14:43:38 -04001022 freeArraysThatAreNotMallocedByUsers(ambiPtr, ambientColor);
1023 freeArraysThatAreNotMallocedByUsers(spotPtr, spotColor);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001024 }
1025
Kevin Lubickc1d08982020-04-06 13:52:15 -04001026 // getLocalToDevice returns a 4x4 matrix.
1027 CanvasKit.SkCanvas.prototype.getLocalToDevice = function() {
Kevin Lubickc1d08982020-04-06 13:52:15 -04001028 // _getLocalToDevice will copy the values into the pointer.
Kevin Lubick6aa38692020-06-01 11:25:47 -04001029 this._getLocalToDevice(_scratch4x4MatrixPtr);
1030 return copy4x4MatrixFromWasm(_scratch4x4MatrixPtr);
Kevin Lubickc1d08982020-04-06 13:52:15 -04001031 }
1032
Nathaniel Nifong00de91c2020-05-06 16:22:33 -04001033 // findMarkedCTM returns a 4x4 matrix, or null if a matrix was not found at
1034 // the provided marker.
1035 CanvasKit.SkCanvas.prototype.findMarkedCTM = function(marker) {
Nathaniel Nifong00de91c2020-05-06 16:22:33 -04001036 // _getLocalToDevice will copy the values into the pointer.
Kevin Lubick6aa38692020-06-01 11:25:47 -04001037 var found = this._findMarkedCTM(marker, _scratch4x4MatrixPtr);
Nathaniel Nifong00de91c2020-05-06 16:22:33 -04001038 if (!found) {
1039 return null;
1040 }
Kevin Lubick6aa38692020-06-01 11:25:47 -04001041 return copy4x4MatrixFromWasm(_scratch4x4MatrixPtr);
Nathaniel Nifong00de91c2020-05-06 16:22:33 -04001042 }
1043
Kevin Lubickc1d08982020-04-06 13:52:15 -04001044 // getTotalMatrix returns the current matrix as a 3x3 matrix.
Kevin Lubick6bffe392020-04-02 15:24:15 -04001045 CanvasKit.SkCanvas.prototype.getTotalMatrix = function() {
Kevin Lubick6bffe392020-04-02 15:24:15 -04001046 // _getTotalMatrix will copy the values into the pointer.
Kevin Lubick6aa38692020-06-01 11:25:47 -04001047 this._getTotalMatrix(_scratch3x3MatrixPtr);
Kevin Lubick6bffe392020-04-02 15:24:15 -04001048 // read them out into an array. TODO(kjlubick): If we change SkMatrix to be
1049 // typedArrays, then we should return a typed array here too.
1050 var rv = new Array(9);
1051 for (var i = 0; i < 9; i++) {
Kevin Lubick6aa38692020-06-01 11:25:47 -04001052 rv[i] = CanvasKit.HEAPF32[_scratch3x3MatrixPtr/4 + i]; // divide by 4 to "cast" to float.
Kevin Lubick6bffe392020-04-02 15:24:15 -04001053 }
Kevin Lubick6bffe392020-04-02 15:24:15 -04001054 return rv;
1055 }
1056
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001057 // returns Uint8Array
1058 CanvasKit.SkCanvas.prototype.readPixels = function(x, y, w, h, alphaType,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001059 colorType, colorSpace, dstRowBytes) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001060 // supply defaults (which are compatible with HTMLCanvas's getImageData)
1061 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
1062 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001063 colorSpace = colorSpace || CanvasKit.SkColorSpace.SRGB;
1064 var pixBytes = 4;
1065 if (colorType === CanvasKit.ColorType.RGBA_F16) {
1066 pixBytes = 8;
1067 }
1068 dstRowBytes = dstRowBytes || (pixBytes * w);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001069
1070 var len = h * dstRowBytes
1071 var pptr = CanvasKit._malloc(len);
1072 var ok = this._readPixels({
1073 'width': w,
1074 'height': h,
Kevin Lubick52b9f372018-12-04 13:57:36 -05001075 'colorType': colorType,
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001076 'alphaType': alphaType,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001077 'colorSpace': colorSpace,
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001078 }, pptr, dstRowBytes, x, y);
1079 if (!ok) {
1080 CanvasKit._free(pptr);
1081 return null;
1082 }
1083
1084 // The first typed array is just a view into memory. Because we will
1085 // be free-ing that, we call slice to make a persistent copy.
Bryce Thomas1fa54042020-01-14 13:46:30 -08001086 var pixels = new Uint8Array(CanvasKit.HEAPU8.buffer, pptr, len).slice();
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001087 CanvasKit._free(pptr);
1088 return pixels;
1089 }
1090
Kevin Lubickcf118922020-05-28 14:43:38 -04001091 // pixels should be a Uint8Array or a plain JS array.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001092 CanvasKit.SkCanvas.prototype.writePixels = function(pixels, srcWidth, srcHeight,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001093 destX, destY, alphaType, colorType, colorSpace) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001094 if (pixels.byteLength % (srcWidth * srcHeight)) {
1095 throw 'pixels length must be a multiple of the srcWidth * srcHeight';
1096 }
1097 var bytesPerPixel = pixels.byteLength / (srcWidth * srcHeight);
1098 // supply defaults (which are compatible with HTMLCanvas's putImageData)
1099 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
1100 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001101 colorSpace = colorSpace || CanvasKit.SkColorSpace.SRGB;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001102 var srcRowBytes = bytesPerPixel * srcWidth;
1103
Kevin Lubick69e46da2020-06-05 07:13:48 -04001104 var pptr = copy1dArray(pixels, "HEAPU8");
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001105 var ok = this._writePixels({
1106 'width': srcWidth,
1107 'height': srcHeight,
1108 'colorType': colorType,
1109 'alphaType': alphaType,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001110 'colorSpace': colorSpace,
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001111 }, pptr, srcRowBytes, destX, destY);
1112
Kevin Lubickcf118922020-05-28 14:43:38 -04001113 freeArraysThatAreNotMallocedByUsers(pptr, pixels);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001114 return ok;
Kevin Lubick52b9f372018-12-04 13:57:36 -05001115 }
1116
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001117 CanvasKit.SkColorFilter.MakeBlend = function(color4f, mode) {
Kevin Lubick6aa38692020-06-01 11:25:47 -04001118 var cPtr = copyColorToWasm(color4f);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001119 var result = CanvasKit.SkColorFilter._MakeBlend(cPtr, mode);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001120 return result;
1121 }
1122
Kevin Lubickd3729342019-09-12 11:11:25 -04001123 // colorMatrix is an SkColorMatrix (e.g. Float32Array of length 20)
1124 CanvasKit.SkColorFilter.MakeMatrix = function(colorMatrix) {
1125 if (!colorMatrix || colorMatrix.length !== 20) {
Kevin Lubick6bffe392020-04-02 15:24:15 -04001126 throw 'invalid color matrix';
Kevin Lubickd3729342019-09-12 11:11:25 -04001127 }
Kevin Lubick69e46da2020-06-05 07:13:48 -04001128 var fptr = copy1dArray(colorMatrix, "HEAPF32");
Kevin Lubickd3729342019-09-12 11:11:25 -04001129 // We know skia memcopies the floats, so we can free our memory after the call returns.
1130 var m = CanvasKit.SkColorFilter._makeMatrix(fptr);
Kevin Lubickcf118922020-05-28 14:43:38 -04001131 freeArraysThatAreNotMallocedByUsers(fptr, colorMatrix);
Kevin Lubickd3729342019-09-12 11:11:25 -04001132 return m;
1133 }
1134
Kevin Lubick6bffe392020-04-02 15:24:15 -04001135 CanvasKit.SkImageFilter.MakeMatrixTransform = function(matr, filterQuality, input) {
1136 var matrPtr = copy3x3MatrixToWasm(matr);
Kevin Lubick6aa38692020-06-01 11:25:47 -04001137 return CanvasKit.SkImageFilter._MakeMatrixTransform(matrPtr, filterQuality, input);
Kevin Lubick6bffe392020-04-02 15:24:15 -04001138 }
1139
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001140 CanvasKit.SkPaint.prototype.getColor = function() {
Kevin Lubick6aa38692020-06-01 11:25:47 -04001141 this._getColor(_scratchColorPtr);
1142 return copyColorFromWasm(_scratchColorPtr);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001143 }
1144
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001145 CanvasKit.SkPaint.prototype.setColor = function(color4f, colorSpace) {
1146 colorSpace = colorSpace || null; // null will be replaced with sRGB in the C++ method.
1147 // emscripten wouldn't bind undefined to the sk_sp<SkColorSpace> expected here.
Kevin Lubick6aa38692020-06-01 11:25:47 -04001148 var cPtr = copyColorToWasm(color4f);
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001149 this._setColor(cPtr, colorSpace);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001150 }
1151
Kevin Lubick93f1a382020-06-02 16:15:23 -04001152 // The color components here are expected to be floating point values (nominally between
1153 // 0.0 and 1.0, but with wider color gamuts, the values could exceed this range). To convert
1154 // between standard 8 bit colors and floats, just divide by 255 before passing them in.
1155 CanvasKit.SkPaint.prototype.setColorComponents = function(r, g, b, a, colorSpace) {
1156 colorSpace = colorSpace || null; // null will be replaced with sRGB in the C++ method.
1157 // emscripten wouldn't bind undefined to the sk_sp<SkColorSpace> expected here.
1158 var cPtr = copyColorComponentsToWasm(r, g, b, a);
1159 this._setColor(cPtr, colorSpace);
1160 }
1161
Kevin Lubickcc13fd32019-04-05 13:00:01 -04001162 CanvasKit.SkSurface.prototype.captureFrameAsSkPicture = function(drawFrame) {
1163 // Set up SkPictureRecorder
1164 var spr = new CanvasKit.SkPictureRecorder();
1165 var canvas = spr.beginRecording(
1166 CanvasKit.LTRBRect(0, 0, this.width(), this.height()));
1167 drawFrame(canvas);
1168 var pic = spr.finishRecordingAsPicture();
1169 spr.delete();
1170 // TODO: do we need to clean up the memory for canvas?
1171 // If we delete it here, saveAsFile doesn't work correctly.
1172 return pic;
1173 }
1174
Kevin Lubick359a7e32019-03-19 09:34:37 -04001175 CanvasKit.SkSurface.prototype.requestAnimationFrame = function(callback, dirtyRect) {
1176 if (!this._cached_canvas) {
1177 this._cached_canvas = this.getCanvas();
1178 }
1179 window.requestAnimationFrame(function() {
Kevin Lubick39026282019-03-28 12:46:40 -04001180 if (this._context !== undefined) {
1181 CanvasKit.setCurrentContext(this._context);
1182 }
Kevin Lubick359a7e32019-03-19 09:34:37 -04001183
1184 callback(this._cached_canvas);
1185
Bryce Thomas2c5b8562020-01-22 13:49:41 -08001186 // We do not dispose() of the SkSurface here, as the client will typically
1187 // call requestAnimationFrame again from within the supplied callback.
1188 // For drawing a single frame, prefer drawOnce().
Bryce Thomas9331ca02020-05-29 16:51:21 -07001189 this.flush(dirtyRect);
Kevin Lubick359a7e32019-03-19 09:34:37 -04001190 }.bind(this));
1191 }
1192
Kevin Lubick52379332020-01-27 10:01:25 -05001193 // drawOnce will dispose of the surface after drawing the frame using the provided
1194 // callback.
Bryce Thomas2c5b8562020-01-22 13:49:41 -08001195 CanvasKit.SkSurface.prototype.drawOnce = function(callback, dirtyRect) {
1196 if (!this._cached_canvas) {
1197 this._cached_canvas = this.getCanvas();
1198 }
1199 window.requestAnimationFrame(function() {
1200 if (this._context !== undefined) {
1201 CanvasKit.setCurrentContext(this._context);
1202 }
1203 callback(this._cached_canvas);
1204
Bryce Thomas9331ca02020-05-29 16:51:21 -07001205 this.flush(dirtyRect);
Bryce Thomas2c5b8562020-01-22 13:49:41 -08001206 this.dispose();
1207 }.bind(this));
1208 }
1209
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001210 CanvasKit.SkPathEffect.MakeDash = function(intervals, phase) {
1211 if (!phase) {
1212 phase = 0;
1213 }
1214 if (!intervals.length || intervals.length % 2 === 1) {
1215 throw 'Intervals array must have even length';
1216 }
Kevin Lubick69e46da2020-06-05 07:13:48 -04001217 var ptr = copy1dArray(intervals, "HEAPF32");
Kevin Lubickf279c632020-03-18 09:53:55 -04001218 var dpe = CanvasKit.SkPathEffect._MakeDash(ptr, intervals.length, phase);
Kevin Lubickcf118922020-05-28 14:43:38 -04001219 freeArraysThatAreNotMallocedByUsers(ptr, intervals);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001220 return dpe;
1221 }
1222
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001223 CanvasKit.SkShader.Color = function(color4f, colorSpace) {
1224 colorSpace = colorSpace || null
Kevin Lubick6aa38692020-06-01 11:25:47 -04001225 var cPtr = copyColorToWasm(color4f);
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001226 var result = CanvasKit.SkShader._Color(cPtr, colorSpace);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001227 return result;
1228 }
1229
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001230 CanvasKit.SkShader.MakeLinearGradient = function(start, end, colors, pos, mode, localMatrix, flags, colorSpace) {
1231 colorSpace = colorSpace || null
Nathaniel Nifongd05fd0c2020-06-11 08:44:20 -04001232 var cPtrInfo = copyFlexibleColorArray(colors);
1233 var posPtr = copy1dArray(pos, "HEAPF32");
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001234 flags = flags || 0;
Kevin Lubick6bffe392020-04-02 15:24:15 -04001235 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001236
Nathaniel Nifongd05fd0c2020-06-11 08:44:20 -04001237 var lgs = CanvasKit._MakeLinearGradientShader(start, end, cPtrInfo.colorPtr, cPtrInfo.colorType, posPtr,
1238 cPtrInfo.count, mode, flags, localMatrixPtr, colorSpace);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001239
Nathaniel Nifongd05fd0c2020-06-11 08:44:20 -04001240 freeArraysThatAreNotMallocedByUsers(cPtrInfo.colorPtr, colors);
Kevin Lubicke7b329e2020-06-05 15:58:01 -04001241 pos && freeArraysThatAreNotMallocedByUsers(posPtr, pos);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001242 return lgs;
1243 }
1244
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001245 CanvasKit.SkShader.MakeRadialGradient = function(center, radius, colors, pos, mode, localMatrix, flags, colorSpace) {
1246 colorSpace = colorSpace || null
Nathaniel Nifongd05fd0c2020-06-11 08:44:20 -04001247 var cPtrInfo = copyFlexibleColorArray(colors);
Kevin Lubick69e46da2020-06-05 07:13:48 -04001248 var posPtr = copy1dArray(pos, "HEAPF32");
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001249 flags = flags || 0;
Kevin Lubick6bffe392020-04-02 15:24:15 -04001250 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001251
Nathaniel Nifongd05fd0c2020-06-11 08:44:20 -04001252 var rgs = CanvasKit._MakeRadialGradientShader(center, radius, cPtrInfo.colorPtr, cPtrInfo.colorType, posPtr,
1253 cPtrInfo.count, mode, flags, localMatrixPtr, colorSpace);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001254
Nathaniel Nifongd05fd0c2020-06-11 08:44:20 -04001255 freeArraysThatAreNotMallocedByUsers(cPtrInfo.colorPtr, colors);
Kevin Lubicke7b329e2020-06-05 15:58:01 -04001256 pos && freeArraysThatAreNotMallocedByUsers(posPtr, pos);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001257 return rgs;
1258 }
1259
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001260 CanvasKit.SkShader.MakeSweepGradient = function(cx, cy, colors, pos, mode, localMatrix, flags, startAngle, endAngle, colorSpace) {
1261 colorSpace = colorSpace || null
Nathaniel Nifongd05fd0c2020-06-11 08:44:20 -04001262 var cPtrInfo = copyFlexibleColorArray(colors);
Kevin Lubick69e46da2020-06-05 07:13:48 -04001263 var posPtr = copy1dArray(pos, "HEAPF32");
Dan Field3d44f732020-03-16 09:17:30 -07001264 flags = flags || 0;
1265 startAngle = startAngle || 0;
1266 endAngle = endAngle || 360;
Kevin Lubick6bffe392020-04-02 15:24:15 -04001267 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Dan Field3d44f732020-03-16 09:17:30 -07001268
Nathaniel Nifongd05fd0c2020-06-11 08:44:20 -04001269 var sgs = CanvasKit._MakeSweepGradientShader(cx, cy, cPtrInfo.colorPtr, cPtrInfo.colorType, posPtr,
1270 cPtrInfo.count, mode,
Kevin Lubick6bffe392020-04-02 15:24:15 -04001271 startAngle, endAngle, flags,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001272 localMatrixPtr, colorSpace);
Dan Field3d44f732020-03-16 09:17:30 -07001273
Nathaniel Nifongd05fd0c2020-06-11 08:44:20 -04001274 freeArraysThatAreNotMallocedByUsers(cPtrInfo.colorPtr, colors);
Kevin Lubicke7b329e2020-06-05 15:58:01 -04001275 pos && freeArraysThatAreNotMallocedByUsers(posPtr, pos);
Dan Field3d44f732020-03-16 09:17:30 -07001276 return sgs;
1277 }
1278
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001279 CanvasKit.SkShader.MakeTwoPointConicalGradient = function(start, startRadius, end, endRadius,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001280 colors, pos, mode, localMatrix, flags, colorSpace) {
1281 colorSpace = colorSpace || null
Nathaniel Nifongd05fd0c2020-06-11 08:44:20 -04001282 var cPtrInfo = copyFlexibleColorArray(colors);
Kevin Lubick69e46da2020-06-05 07:13:48 -04001283 var posPtr = copy1dArray(pos, "HEAPF32");
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001284 flags = flags || 0;
Kevin Lubick6bffe392020-04-02 15:24:15 -04001285 var localMatrixPtr = copy3x3MatrixToWasm(localMatrix);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001286
Kevin Lubick6bffe392020-04-02 15:24:15 -04001287 var rgs = CanvasKit._MakeTwoPointConicalGradientShader(
Nathaniel Nifongd05fd0c2020-06-11 08:44:20 -04001288 start, startRadius, end, endRadius, cPtrInfo.colorPtr, cPtrInfo.colorType,
1289 posPtr, cPtrInfo.count, mode, flags, localMatrixPtr, colorSpace);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001290
Nathaniel Nifongd05fd0c2020-06-11 08:44:20 -04001291 freeArraysThatAreNotMallocedByUsers(cPtrInfo.colorPtr, colors);
Kevin Lubicke7b329e2020-06-05 15:58:01 -04001292 pos && freeArraysThatAreNotMallocedByUsers(posPtr, pos);
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001293 return rgs;
1294 }
1295
1296 // temporary support for deprecated names.
Nathaniel Nifongc8f95e22020-03-09 11:52:51 -04001297 CanvasKit.MakeSkDashPathEffect = CanvasKit.SkPathEffect.MakeDash;
1298 CanvasKit.MakeLinearGradientShader = CanvasKit.SkShader.MakeLinearGradient;
1299 CanvasKit.MakeRadialGradientShader = CanvasKit.SkShader.MakeRadialGradient;
1300 CanvasKit.MakeTwoPointConicalGradientShader = CanvasKit.SkShader.MakeTwoPointConicalGradient;
Nathaniel Nifong23b0ed92020-03-04 15:43:50 -05001301
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001302 // Run through the JS files that are added at compile time.
1303 if (CanvasKit._extraInitializations) {
1304 CanvasKit._extraInitializations.forEach(function(init) {
1305 init();
1306 });
Kevin Lubickeb2f6b02018-11-29 15:07:02 -05001307 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001308}; // end CanvasKit.onRuntimeInitialized, that is, anything changing prototypes or dynamic.
Kevin Lubickeb2f6b02018-11-29 15:07:02 -05001309
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001310// Accepts an object holding two canvaskit colors.
1311// {
1312// ambient: {r, g, b, a},
1313// spot: {r, g, b, a},
1314// }
Kevin Lubicke7b329e2020-06-05 15:58:01 -04001315// Returns the same format. Note, if malloced colors are passed in, the memory
1316// housing the passed in colors passed in will be overwritten with the computed
1317// tonal colors.
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001318CanvasKit.computeTonalColors = function(tonalColors) {
Kevin Lubicke7b329e2020-06-05 15:58:01 -04001319 // copy the colors into WASM
Kevin Lubick6aa38692020-06-01 11:25:47 -04001320 var cPtrAmbi = copyColorToWasmNoScratch(tonalColors['ambient']);
1321 var cPtrSpot = copyColorToWasmNoScratch(tonalColors['spot']);
Kevin Lubicke7b329e2020-06-05 15:58:01 -04001322 // The output of this function will be the same pointers we passed in.
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001323 this._computeTonalColors(cPtrAmbi, cPtrSpot);
Kevin Lubicke7b329e2020-06-05 15:58:01 -04001324 // Read the results out.
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001325 var result = {
1326 'ambient': copyColorFromWasm(cPtrAmbi),
1327 'spot': copyColorFromWasm(cPtrSpot),
Kevin Lubickd9b9e5e2020-06-23 16:58:10 -04001328 };
Kevin Lubicke7b329e2020-06-05 15:58:01 -04001329 // If the user passed us malloced colors in here, we don't want to clean them up.
1330 freeArraysThatAreNotMallocedByUsers(cPtrAmbi, tonalColors['ambient']);
1331 freeArraysThatAreNotMallocedByUsers(cPtrSpot, tonalColors['spot']);
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001332 return result;
Kevin Lubickd9b9e5e2020-06-23 16:58:10 -04001333};
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -04001334
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001335CanvasKit.LTRBRect = function(l, t, r, b) {
1336 return {
1337 fLeft: l,
1338 fTop: t,
1339 fRight: r,
1340 fBottom: b,
1341 };
Kevin Lubickd9b9e5e2020-06-23 16:58:10 -04001342};
Kevin Lubick1a05fce2018-11-20 12:51:16 -05001343
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001344CanvasKit.XYWHRect = function(x, y, w, h) {
1345 return {
1346 fLeft: x,
1347 fTop: y,
1348 fRight: x+w,
1349 fBottom: y+h,
1350 };
Kevin Lubickd9b9e5e2020-06-23 16:58:10 -04001351};
Kevin Lubick1a05fce2018-11-20 12:51:16 -05001352
Kevin Lubick7d644e12019-09-11 14:22:22 -04001353// RRectXY returns an RRect with the given rect and a radiusX and radiusY for
1354// all 4 corners.
1355CanvasKit.RRectXY = function(rect, rx, ry) {
1356 return {
1357 rect: rect,
1358 rx1: rx,
1359 ry1: ry,
1360 rx2: rx,
1361 ry2: ry,
1362 rx3: rx,
1363 ry3: ry,
1364 rx4: rx,
1365 ry4: ry,
1366 };
Kevin Lubickd9b9e5e2020-06-23 16:58:10 -04001367};
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001368
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001369// data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
Kevin Lubick6b921b72019-09-18 16:18:17 -04001370CanvasKit.MakeAnimatedImageFromEncoded = function(data) {
1371 data = new Uint8Array(data);
1372
1373 var iptr = CanvasKit._malloc(data.byteLength);
1374 CanvasKit.HEAPU8.set(data, iptr);
1375 var img = CanvasKit._decodeAnimatedImage(iptr, data.byteLength);
1376 if (!img) {
1377 SkDebug('Could not decode animated image');
1378 return null;
1379 }
1380 return img;
1381}
1382
1383// data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001384CanvasKit.MakeImageFromEncoded = function(data) {
1385 data = new Uint8Array(data);
1386
1387 var iptr = CanvasKit._malloc(data.byteLength);
1388 CanvasKit.HEAPU8.set(data, iptr);
1389 var img = CanvasKit._decodeImage(iptr, data.byteLength);
1390 if (!img) {
1391 SkDebug('Could not decode image');
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001392 return null;
1393 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001394 return img;
1395}
1396
Elliot Evans28796192020-06-15 12:53:27 -06001397// A variable to hold a canvasElement which can be reused once created the first time.
1398var memoizedCanvas2dElement = null;
1399
1400// Alternative to CanvasKit.MakeImageFromEncoded. Allows for CanvasKit users to take advantage of
1401// browser APIs to decode images instead of using codecs included in the CanvasKit wasm binary.
1402// Expects that the canvasImageSource has already loaded/decoded.
1403// CanvasImageSource reference: https://developer.mozilla.org/en-US/docs/Web/API/CanvasImageSource
1404CanvasKit.MakeImageFromCanvasImageSource = function(canvasImageSource) {
1405 var width = canvasImageSource.width;
1406 var height = canvasImageSource.height;
1407
1408 if (!memoizedCanvas2dElement) {
1409 memoizedCanvas2dElement = document.createElement('canvas');
1410 }
1411 memoizedCanvas2dElement.width = width;
1412 memoizedCanvas2dElement.height = height;
1413
1414 var ctx2d = memoizedCanvas2dElement.getContext('2d');
1415 ctx2d.drawImage(canvasImageSource, 0, 0);
1416
1417 var imageData = ctx2d.getImageData(0, 0, width, height);
1418
1419 return CanvasKit.MakeImage(
1420 imageData.data,
1421 width,
1422 height,
1423 CanvasKit.AlphaType.Unpremul,
1424 CanvasKit.ColorType.RGBA_8888,
1425 CanvasKit.SkColorSpace.SRGB
1426 );
1427}
1428
1429// pixels may be any Typed Array, but Uint8Array or Uint8ClampedArray is recommended,
1430// with bytes representing the pixel values.
Kevin Lubickeda0b432019-12-02 08:26:48 -05001431// (e.g. each set of 4 bytes could represent RGBA values for a single pixel).
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001432CanvasKit.MakeImage = function(pixels, width, height, alphaType, colorType, colorSpace) {
Kevin Lubickeda0b432019-12-02 08:26:48 -05001433 var bytesPerPixel = pixels.length / (width * height);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001434 var info = {
1435 'width': width,
1436 'height': height,
1437 'alphaType': alphaType,
1438 'colorType': colorType,
Nathaniel Nifongb1ebbb12020-05-26 13:10:20 -04001439 'colorSpace': colorSpace,
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001440 };
Kevin Lubick69e46da2020-06-05 07:13:48 -04001441 var pptr = copy1dArray(pixels, "HEAPU8");
Kevin Lubickeda0b432019-12-02 08:26:48 -05001442 // No need to _free pptr, Image takes it with SkData::MakeFromMalloc
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001443
Kevin Lubickeda0b432019-12-02 08:26:48 -05001444 return CanvasKit._MakeImage(info, pptr, pixels.length, width * bytesPerPixel);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001445}
1446
Nathaniel Nifongd05fd0c2020-06-11 08:44:20 -04001447// Colors may be a Uint32Array of int colors, a Flat Float32Array of float colors
1448// or a 2d Array of Float32Array(4) (deprecated)
1449// the underlying skia function accepts only int colors so it is recommended
1450// to pass an array of int colors to avoid an extra conversion.
1451// SkColorBuilder is not accepted.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001452CanvasKit.MakeSkVertices = function(mode, positions, textureCoordinates, colors,
Mike Reed5caf9352020-03-02 14:57:09 -05001453 indices, isVolatile) {
Kevin Lubickb3574c92019-03-06 08:25:36 -05001454 // Default isVolitile to true if not set
1455 isVolatile = isVolatile === undefined ? true : isVolatile;
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001456 var idxCount = (indices && indices.length) || 0;
1457
1458 var flags = 0;
1459 // These flags are from SkVertices.h and should be kept in sync with those.
1460 if (textureCoordinates && textureCoordinates.length) {
1461 flags |= (1 << 0);
1462 }
1463 if (colors && colors.length) {
1464 flags |= (1 << 1);
1465 }
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001466 if (!isVolatile) {
Mike Reed5caf9352020-03-02 14:57:09 -05001467 flags |= (1 << 2);
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001468 }
1469
Nathaniel Nifongd05fd0c2020-06-11 08:44:20 -04001470 var builder = new CanvasKit._SkVerticesBuilder(mode, positions.length, idxCount, flags);
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001471
Kevin Lubick69e46da2020-06-05 07:13:48 -04001472 copy2dArray(positions, "HEAPF32", builder.positions());
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001473 if (builder.texCoords()) {
Kevin Lubick69e46da2020-06-05 07:13:48 -04001474 copy2dArray(textureCoordinates, "HEAPF32", builder.texCoords());
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001475 }
1476 if (builder.colors()) {
Nathaniel Nifongd05fd0c2020-06-11 08:44:20 -04001477 if (colors.build) {
1478 throw('Color builder not accepted by MakeSkVertices, use array of ints');
1479 } else {
1480 copy1dArray(assureIntColors(colors), "HEAPU32", builder.colors());
1481 }
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001482 }
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001483 if (builder.indices()) {
Kevin Lubick69e46da2020-06-05 07:13:48 -04001484 copy1dArray(indices, "HEAPU16", builder.indices());
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001485 }
Kevin Lubickb3574c92019-03-06 08:25:36 -05001486
Kevin Lubickd6ba7252019-06-03 14:38:05 -04001487 // Create the vertices, which owns the memory that the builder had allocated.
1488 return builder.detach();
Kevin Lubicka4f218d2020-01-14 08:39:09 -05001489};