blob: e0206c7f8b41dc97a9bcdacd7144f01ebd69e696 [file] [log] [blame]
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05001// helper JS that could be used anywhere in the glue code
Kevin Lubick217056c2018-09-20 17:39:31 -04002
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05003function clamp(c) {
4 return Math.round(Math.max(0, Math.min(c || 0, 255)));
5}
Kevin Lubick217056c2018-09-20 17:39:31 -04006
Nathaniel Nifonge5d32542020-03-26 09:27:48 -04007// Constructs a Color with the same API as CSS's rgba(), that is
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05008// r,g,b are 0-255, and a is 0.0 to 1.0.
9// if a is omitted, it will be assumed to be 1.0
Nathaniel Nifonge5d32542020-03-26 09:27:48 -040010// Internally, Colors are a TypedArray of four unpremultiplied 32-bit floats: a, r, g, b
11// In order to construct one with more precision or in a wider gamut, use
12// CanvasKit.Color4f
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050013CanvasKit.Color = function(r, g, b, a) {
14 if (a === undefined) {
15 a = 1;
Kevin Lubick217056c2018-09-20 17:39:31 -040016 }
Nathaniel Nifonge5d32542020-03-26 09:27:48 -040017 return CanvasKit.Color4f(clamp(r)/255, clamp(g)/255, clamp(b)/255, a);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050018}
Kevin Lubick217056c2018-09-20 17:39:31 -040019
Nathaniel Nifonge5d32542020-03-26 09:27:48 -040020// Construct a 4-float color.
21// Opaque if opacity is omitted.
22CanvasKit.Color4f = function(r, g, b, a) {
23 if (a === undefined) {
24 a = 1;
25 }
26 return Float32Array.of(r, g, b, a);
27}
28
29// Color constants use property getters to prevent other code from accidentally
30// changing them.
31Object.defineProperty(CanvasKit, "TRANSPARENT", {
32 get: function() { return CanvasKit.Color4f(0, 0, 0, 0); }
33});
34Object.defineProperty(CanvasKit, "BLACK", {
35 get: function() { return CanvasKit.Color4f(0, 0, 0, 1); }
36});
37Object.defineProperty(CanvasKit, "WHITE", {
38 get: function() { return CanvasKit.Color4f(1, 1, 1, 1); }
39});
40Object.defineProperty(CanvasKit, "RED", {
41 get: function() { return CanvasKit.Color4f(1, 0, 0, 1); }
42});
43Object.defineProperty(CanvasKit, "GREEN", {
44 get: function() { return CanvasKit.Color4f(0, 1, 0, 1); }
45});
46Object.defineProperty(CanvasKit, "BLUE", {
47 get: function() { return CanvasKit.Color4f(0, 0, 1, 1); }
48});
49Object.defineProperty(CanvasKit, "YELLOW", {
50 get: function() { return CanvasKit.Color4f(1, 1, 0, 1); }
51});
52Object.defineProperty(CanvasKit, "CYAN", {
53 get: function() { return CanvasKit.Color4f(0, 1, 1, 1); }
54});
55Object.defineProperty(CanvasKit, "MAGENTA", {
56 get: function() { return CanvasKit.Color4f(1, 0, 1, 1); }
57});
58
59// returns a css style [r, g, b, a] from a CanvasKit.Color
60// where r, g, b are returned as ints in the range [0, 255]
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050061// where a is scaled between 0 and 1.0
62CanvasKit.getColorComponents = function(color) {
63 return [
Nathaniel Nifonge5d32542020-03-26 09:27:48 -040064 Math.floor(color[0]*255),
65 Math.floor(color[1]*255),
66 Math.floor(color[2]*255),
67 color[3]
68 ];
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050069}
70
Kevin Lubick39284662020-02-20 10:29:55 -050071// parseColorString takes in a CSS color value and returns a CanvasKit.Color
Nathaniel Nifonge5d32542020-03-26 09:27:48 -040072// (which is an array of 4 floats in RGBA order). An optional colorMap
73// may be provided which maps custom strings to values.
Kevin Lubick39284662020-02-20 10:29:55 -050074// In the CanvasKit canvas2d shim layer, we provide this map for processing
75// canvas2d calls, but not here for code size reasons.
76CanvasKit.parseColorString = function(colorStr, colorMap) {
77 colorStr = colorStr.toLowerCase();
78 // See https://drafts.csswg.org/css-color/#typedef-hex-color
79 if (colorStr.startsWith('#')) {
80 var r, g, b, a = 255;
81 switch (colorStr.length) {
82 case 9: // 8 hex chars #RRGGBBAA
83 a = parseInt(colorStr.slice(7, 9), 16);
84 case 7: // 6 hex chars #RRGGBB
85 r = parseInt(colorStr.slice(1, 3), 16);
86 g = parseInt(colorStr.slice(3, 5), 16);
87 b = parseInt(colorStr.slice(5, 7), 16);
88 break;
89 case 5: // 4 hex chars #RGBA
90 // multiplying by 17 is the same effect as
91 // appending another character of the same value
92 // e.g. e => ee == 14 => 238
93 a = parseInt(colorStr.slice(4, 5), 16) * 17;
94 case 4: // 6 hex chars #RGB
95 r = parseInt(colorStr.slice(1, 2), 16) * 17;
96 g = parseInt(colorStr.slice(2, 3), 16) * 17;
97 b = parseInt(colorStr.slice(3, 4), 16) * 17;
98 break;
99 }
100 return CanvasKit.Color(r, g, b, a/255);
101
102 } else if (colorStr.startsWith('rgba')) {
103 // Trim off rgba( and the closing )
104 colorStr = colorStr.slice(5, -1);
105 var nums = colorStr.split(',');
106 return CanvasKit.Color(+nums[0], +nums[1], +nums[2],
107 valueOrPercent(nums[3]));
108 } else if (colorStr.startsWith('rgb')) {
109 // Trim off rgba( and the closing )
110 colorStr = colorStr.slice(4, -1);
111 var nums = colorStr.split(',');
112 // rgb can take 3 or 4 arguments
113 return CanvasKit.Color(+nums[0], +nums[1], +nums[2],
114 valueOrPercent(nums[3]));
115 } else if (colorStr.startsWith('gray(')) {
116 // TODO
117 } else if (colorStr.startsWith('hsl')) {
118 // TODO
119 } else if (colorMap) {
120 // Try for named color
121 var nc = colorMap[colorStr];
122 if (nc !== undefined) {
123 return nc;
124 }
125 }
126 SkDebug('unrecognized color ' + colorStr);
127 return CanvasKit.BLACK;
128}
129
Nathaniel Nifonge5d32542020-03-26 09:27:48 -0400130function isCanvasKitColor(ob) {
131 if (!ob) {
132 return false;
133 }
134 return (ob.constructor === Float32Array && ob.length === 4);
135}
136
137// Warning information is lost by this conversion
138function toUint32Color(c) {
139 return ((clamp(c[3]*255) << 24) | (clamp(c[0]*255) << 16) | (clamp(c[1]*255) << 8) | (clamp(c[2]*255) << 0)) >>> 0;
140}
141function uIntColorToCanvasKitColor(c) {
142 return CanvasKit.Color(
143 (c >> 16) & 0xFF,
144 (c >> 8) & 0xFF,
145 (c >> 0) & 0xFF,
146 ((c >> 24) & 0xFF) / 255
147 );
148}
149
Kevin Lubick39284662020-02-20 10:29:55 -0500150function valueOrPercent(aStr) {
151 if (aStr === undefined) {
152 return 1; // default to opaque.
153 }
154 var a = parseFloat(aStr);
155 if (aStr && aStr.indexOf('%') !== -1) {
156 return a / 100;
157 }
158 return a;
159}
160
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500161CanvasKit.multiplyByAlpha = function(color, alpha) {
Nathaniel Nifonge5d32542020-03-26 09:27:48 -0400162 // make a copy of the color so the function remains pure.
163 var result = color.slice();
164 result[3] = Math.max(0, Math.min(result[3] * alpha, 1));
165 return result;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500166}
Kevin Lubick61ef7b22018-11-27 13:26:59 -0500167
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500168function radiansToDegrees(rad) {
169 return (rad / Math.PI) * 180;
170}
Kevin Lubick12c0e502018-11-28 12:51:56 -0500171
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500172function degreesToRadians(deg) {
173 return (deg / 180) * Math.PI;
174}
Kevin Lubick12c0e502018-11-28 12:51:56 -0500175
176// See https://stackoverflow.com/a/31090240
177// This contraption keeps closure from minifying away the check
178// if btoa is defined *and* prevents runtime "btoa" or "window" is not defined.
179// Defined outside any scopes to make it available in all files.
180var isNode = !(new Function("try {return this===window;}catch(e){ return false;}")());
Kevin Lubick1646e7d2018-12-07 13:03:08 -0500181
182function almostEqual(floata, floatb) {
183 return Math.abs(floata - floatb) < 0.00001;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500184}
185
186
187var nullptr = 0; // emscripten doesn't like to take null as uintptr_t
188
189// arr can be a normal JS array or a TypedArray
190// dest is something like CanvasKit.HEAPF32
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400191// ptr can be optionally provided if the memory was already allocated.
192function copy1dArray(arr, dest, ptr) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500193 if (!arr || !arr.length) {
194 return nullptr;
195 }
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400196 // This was created with CanvasKit.Malloc, so it's already been copied.
197 if (arr['_ck']) {
198 return arr.byteOffset;
199 }
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400200 if (!ptr) {
201 ptr = CanvasKit._malloc(arr.length * dest.BYTES_PER_ELEMENT);
202 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500203 // In c++ terms, the WASM heap is a uint8_t*, a long buffer/array of single
204 // byte elements. When we run _malloc, we always get an offset/pointer into
205 // that block of memory.
206 // CanvasKit exposes some different views to make it easier to work with
207 // different types. HEAPF32 for example, exposes it as a float*
208 // However, to make the ptr line up, we have to do some pointer arithmetic.
209 // Concretely, we need to convert ptr to go from an index into a 1-byte-wide
210 // buffer to an index into a 4-byte-wide buffer (in the case of HEAPF32)
211 // and thus we divide ptr by 4.
212 dest.set(arr, ptr / dest.BYTES_PER_ELEMENT);
213 return ptr;
214}
215
216// arr should be a non-jagged 2d JS array (TypedArrays can't be nested
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500217// inside themselves). A common use case is points.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500218// dest is something like CanvasKit.HEAPF32
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400219// ptr can be optionally provided if the memory was already allocated.
220function copy2dArray(arr, dest, ptr) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500221 if (!arr || !arr.length) {
222 return nullptr;
223 }
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400224 if (!ptr) {
225 ptr = CanvasKit._malloc(arr.length * arr[0].length * dest.BYTES_PER_ELEMENT);
226 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500227 var idx = 0;
228 var adjustedPtr = ptr / dest.BYTES_PER_ELEMENT;
229 for (var r = 0; r < arr.length; r++) {
230 for (var c = 0; c < arr[0].length; c++) {
231 dest[adjustedPtr + idx] = arr[r][c];
232 idx++;
233 }
234 }
235 return ptr;
236}
237
Kevin Lubick6bffe392020-04-02 15:24:15 -0400238var defaultPerspective = Float32Array.of(0, 0, 1);
239
Kevin Lubick6aa38692020-06-01 11:25:47 -0400240var _scratch3x3MatrixPtr = nullptr;
Kevin Lubick462a8602020-06-01 15:43:03 -0400241var _scratch3x3Matrix; // the result from CanvasKit.Malloc
Kevin Lubick6aa38692020-06-01 11:25:47 -0400242
Kevin Lubick6bffe392020-04-02 15:24:15 -0400243// Copies the given DOMMatrix/Array/TypedArray to the CanvasKit heap and
244// returns a pointer to the memory. This memory is a float* of length 9.
245// If the passed in matrix is null/undefined, we return 0 (nullptr). All calls
246// on the C++ side should check for nullptr where appropriate. It is generally
247// the responsibility of the JS side code to call CanvasKit._free on the
248// allocated memory before returning to the user code.
249function copy3x3MatrixToWasm(matr) {
250 if (!matr) {
251 return nullptr;
252 }
Kevin Lubick6aa38692020-06-01 11:25:47 -0400253
Kevin Lubick6bffe392020-04-02 15:24:15 -0400254 if (matr.length) {
255 // TODO(kjlubick): Downsample a 16 length (4x4 matrix)
256 if (matr.length !== 6 && matr.length !== 9) {
257 throw 'invalid matrix size';
258 }
259 // This should be an array or typed array.
260 // have to divide the pointer by 4 to "cast" it from bytes to float.
Kevin Lubick6aa38692020-06-01 11:25:47 -0400261 var mPtr = copy1dArray(matr, CanvasKit.HEAPF32, _scratch3x3MatrixPtr);
Kevin Lubick6bffe392020-04-02 15:24:15 -0400262 if (matr.length === 6) {
Kevin Lubick6aa38692020-06-01 11:25:47 -0400263 // Overwrite the last 3 floats with the default perspective. The divide
264 // by 4 casts the pointer into a float pointer.
265 CanvasKit.HEAPF32.set(defaultPerspective, 6 + mPtr / 4);
Kevin Lubick6bffe392020-04-02 15:24:15 -0400266 }
Kevin Lubick6aa38692020-06-01 11:25:47 -0400267 return mPtr;
Kevin Lubick6bffe392020-04-02 15:24:15 -0400268 }
Kevin Lubick462a8602020-06-01 15:43:03 -0400269 var wasm3x3Matrix = _scratch3x3Matrix['toTypedArray']();
Kevin Lubick6aa38692020-06-01 11:25:47 -0400270 // Try as if it's a DOMMatrix. Reminder that DOMMatrix is column-major.
Kevin Lubick462a8602020-06-01 15:43:03 -0400271 wasm3x3Matrix[0] = matr.m11;
272 wasm3x3Matrix[1] = matr.m21;
273 wasm3x3Matrix[2] = matr.m41;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400274
Kevin Lubick462a8602020-06-01 15:43:03 -0400275 wasm3x3Matrix[3] = matr.m12;
276 wasm3x3Matrix[4] = matr.m22;
277 wasm3x3Matrix[5] = matr.m42;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400278
Kevin Lubick462a8602020-06-01 15:43:03 -0400279 wasm3x3Matrix[6] = matr.m14;
280 wasm3x3Matrix[7] = matr.m24;
281 wasm3x3Matrix[8] = matr.m44;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400282 return _scratch3x3MatrixPtr;
Kevin Lubick6bffe392020-04-02 15:24:15 -0400283}
284
Kevin Lubick6aa38692020-06-01 11:25:47 -0400285var _scratch4x4MatrixPtr = nullptr;
Kevin Lubick462a8602020-06-01 15:43:03 -0400286var _scratch4x4Matrix; // the result from CanvasKit.Malloc
Kevin Lubick6aa38692020-06-01 11:25:47 -0400287
Kevin Lubickc1d08982020-04-06 13:52:15 -0400288function copy4x4MatrixToWasm(matr) {
289 if (!matr) {
290 return nullptr;
291 }
Kevin Lubick462a8602020-06-01 15:43:03 -0400292 var wasm4x4Matrix = _scratch4x4Matrix['toTypedArray']();
Kevin Lubickc1d08982020-04-06 13:52:15 -0400293 if (matr.length) {
294 if (matr.length !== 16 && matr.length !== 6 && matr.length !== 9) {
295 throw 'invalid matrix size';
296 }
297 if (matr.length === 16) {
298 // This should be an array or typed array.
299 // have to divide the pointer by 4 to "cast" it from bytes to float.
Kevin Lubick6aa38692020-06-01 11:25:47 -0400300 return copy1dArray(matr, CanvasKit.HEAPF32, _scratch4x4MatrixPtr);
Kevin Lubickc1d08982020-04-06 13:52:15 -0400301 }
Kevin Lubick6aa38692020-06-01 11:25:47 -0400302 // Upscale the row-major 3x3 or 3x2 matrix into a 4x4 row-major matrix
303 // TODO(skbug.com/10108) This will need to change when we convert our
304 // JS 4x4 to be column-major.
305 // When upscaling, we need to overwrite the 3rd column and the 3rd row with
306 // 0s. It's easiest to just do that with a fill command.
Kevin Lubick462a8602020-06-01 15:43:03 -0400307 wasm4x4Matrix.fill(0);
308 wasm4x4Matrix[0] = matr[0];
309 wasm4x4Matrix[1] = matr[1];
Kevin Lubick6aa38692020-06-01 11:25:47 -0400310 // skip col 2
Kevin Lubick462a8602020-06-01 15:43:03 -0400311 wasm4x4Matrix[3] = matr[2];
Kevin Lubick6aa38692020-06-01 11:25:47 -0400312
Kevin Lubick462a8602020-06-01 15:43:03 -0400313 wasm4x4Matrix[4] = matr[3];
314 wasm4x4Matrix[5] = matr[4];
Kevin Lubick6aa38692020-06-01 11:25:47 -0400315 // skip col 2
Kevin Lubick462a8602020-06-01 15:43:03 -0400316 wasm4x4Matrix[7] = matr[5];
Kevin Lubick6aa38692020-06-01 11:25:47 -0400317
318 // skip row 2
319
Kevin Lubick462a8602020-06-01 15:43:03 -0400320 wasm4x4Matrix[12] = matr[6];
321 wasm4x4Matrix[13] = matr[7];
Kevin Lubick6aa38692020-06-01 11:25:47 -0400322 // skip col 2
Kevin Lubick462a8602020-06-01 15:43:03 -0400323 wasm4x4Matrix[15] = matr[8];
Kevin Lubick6aa38692020-06-01 11:25:47 -0400324
325 if (matr.length === 6) {
326 // fix perspective for the 3x2 case (from above, they will be undefined).
Kevin Lubick462a8602020-06-01 15:43:03 -0400327 wasm4x4Matrix[12]=0;
328 wasm4x4Matrix[13]=0;
329 wasm4x4Matrix[15]=1;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400330 }
331 return _scratch4x4MatrixPtr;
Kevin Lubickc1d08982020-04-06 13:52:15 -0400332 }
Kevin Lubick6aa38692020-06-01 11:25:47 -0400333 // Try as if it's a DOMMatrix. Reminder that DOMMatrix is column-major.
Kevin Lubick462a8602020-06-01 15:43:03 -0400334 wasm4x4Matrix[0] = matr.m11;
335 wasm4x4Matrix[1] = matr.m21;
336 wasm4x4Matrix[2] = matr.m31;
337 wasm4x4Matrix[3] = matr.m41;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400338
Kevin Lubick462a8602020-06-01 15:43:03 -0400339 wasm4x4Matrix[4] = matr.m12;
340 wasm4x4Matrix[5] = matr.m22;
341 wasm4x4Matrix[6] = matr.m32;
342 wasm4x4Matrix[7] = matr.m42;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400343
Kevin Lubick462a8602020-06-01 15:43:03 -0400344 wasm4x4Matrix[8] = matr.m13;
345 wasm4x4Matrix[9] = matr.m23;
346 wasm4x4Matrix[10] = matr.m33;
347 wasm4x4Matrix[11] = matr.m43;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400348
Kevin Lubick462a8602020-06-01 15:43:03 -0400349 wasm4x4Matrix[12] = matr.m14;
350 wasm4x4Matrix[13] = matr.m24;
351 wasm4x4Matrix[14] = matr.m34;
352 wasm4x4Matrix[15] = matr.m44;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400353 return _scratch4x4MatrixPtr;
Kevin Lubickc1d08982020-04-06 13:52:15 -0400354}
355
Kevin Lubick6aa38692020-06-01 11:25:47 -0400356// copies a 4x4 matrix at the given pointer into a JS array. It is the caller's
357// responsibility to free the matrPtr if needed.
Kevin Lubickc1d08982020-04-06 13:52:15 -0400358function copy4x4MatrixFromWasm(matrPtr) {
359 // read them out into an array. TODO(kjlubick): If we change SkMatrix to be
360 // typedArrays, then we should return a typed array here too.
361 var rv = new Array(16);
362 for (var i = 0; i < 16; i++) {
363 rv[i] = CanvasKit.HEAPF32[matrPtr/4 + i]; // divide by 4 to "cast" to float.
364 }
Kevin Lubickc1d08982020-04-06 13:52:15 -0400365 return rv;
366}
367
Kevin Lubick6aa38692020-06-01 11:25:47 -0400368var _scratchColorPtr = nullptr;
369
370function copyColorToWasm(color4f, ptr) {
371 // TODO(kjlubick): accept 4 floats or int color
372 return copy1dArray(color4f, CanvasKit.HEAPF32, ptr || _scratchColorPtr);
373}
374
375function copyColorToWasmNoScratch(color4f) {
376 // TODO(kjlubick): accept 4 floats or int color
377 return copy1dArray(color4f, CanvasKit.HEAPF32);
378}
379
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400380// copies the four floats at the given pointer in a js Float32Array
381function copyColorFromWasm(colorPtr) {
382 var rv = new Float32Array(4);
383 for (var i = 0; i < 4; i++) {
384 rv[i] = CanvasKit.HEAPF32[colorPtr/4 + i]; // divide by 4 to "cast" to float.
385 }
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400386 return rv;
Kevin Lubickcf118922020-05-28 14:43:38 -0400387}
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400388
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500389// Caching the Float32Arrays can save having to reallocate them
390// over and over again.
391var Float32ArrayCache = {};
392
393// Takes a 2D array of commands and puts them into the WASM heap
394// as a 1D array. This allows them to referenced from the C++ code.
395// Returns a 2 element array, with the first item being essentially a
396// pointer to the array and the second item being the length of
397// the new 1D array.
398//
399// Example usage:
400// let cmds = [
401// [CanvasKit.MOVE_VERB, 0, 10],
402// [CanvasKit.LINE_VERB, 30, 40],
403// [CanvasKit.QUAD_VERB, 20, 50, 45, 60],
404// ];
405function loadCmdsTypedArray(arr) {
406 var len = 0;
407 for (var r = 0; r < arr.length; r++) {
408 len += arr[r].length;
409 }
410
411 var ta;
412 if (Float32ArrayCache[len]) {
413 ta = Float32ArrayCache[len];
414 } else {
415 ta = new Float32Array(len);
416 Float32ArrayCache[len] = ta;
417 }
418 // Flatten into a 1d array
419 var i = 0;
420 for (var r = 0; r < arr.length; r++) {
421 for (var c = 0; c < arr[r].length; c++) {
422 var item = arr[r][c];
423 ta[i] = item;
424 i++;
425 }
426 }
427
428 var ptr = copy1dArray(ta, CanvasKit.HEAPF32);
429 return [ptr, len];
430}
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400431
Kevin Lubickcc13fd32019-04-05 13:00:01 -0400432function saveBytesToFile(bytes, fileName) {
433 if (!isNode) {
434 // https://stackoverflow.com/a/32094834
435 var blob = new Blob([bytes], {type: 'application/octet-stream'});
436 url = window.URL.createObjectURL(blob);
437 var a = document.createElement('a');
438 document.body.appendChild(a);
439 a.href = url;
440 a.download = fileName;
441 a.click();
442 // clean up after because FF might not download it synchronously
443 setTimeout(function() {
444 URL.revokeObjectURL(url);
445 a.remove();
446 }, 50);
447 } else {
448 var fs = require('fs');
449 // https://stackoverflow.com/a/42006750
450 // https://stackoverflow.com/a/47018122
451 fs.writeFile(fileName, new Buffer(bytes), function(err) {
452 if (err) throw err;
453 });
454 }
455}
Kevin Lubickee91c072019-03-29 10:39:52 -0400456/**
457 * Generic helper for dealing with an array of four floats.
458 */
459CanvasKit.FourFloatArrayHelper = function() {
460 this._floats = [];
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400461 this._ptr = null;
Kevin Lubickee91c072019-03-29 10:39:52 -0400462
463 Object.defineProperty(this, 'length', {
464 enumerable: true,
465 get: function() {
466 return this._floats.length / 4;
467 },
468 });
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400469}
470
471/**
Kevin Lubickee91c072019-03-29 10:39:52 -0400472 * push the four floats onto the end of the array - if build() has already
473 * been called, the call will return without modifying anything.
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400474 */
Kevin Lubickee91c072019-03-29 10:39:52 -0400475CanvasKit.FourFloatArrayHelper.prototype.push = function(f1, f2, f3, f4) {
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400476 if (this._ptr) {
477 SkDebug('Cannot push more points - already built');
478 return;
479 }
Kevin Lubickee91c072019-03-29 10:39:52 -0400480 this._floats.push(f1, f2, f3, f4);
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400481}
482
Kevin Lubickee91c072019-03-29 10:39:52 -0400483/**
484 * Set the four floats at a given index - if build() has already
485 * been called, the WASM memory will be written to directly.
486 */
487CanvasKit.FourFloatArrayHelper.prototype.set = function(idx, f1, f2, f3, f4) {
488 if (idx < 0 || idx >= this._floats.length/4) {
489 SkDebug('Cannot set index ' + idx + ', it is out of range', this._floats.length/4);
490 return;
491 }
492 idx *= 4;
493 var BYTES_PER_ELEMENT = 4;
494 if (this._ptr) {
495 // convert this._ptr from uint8_t* to SkScalar* by dividing by 4
496 var floatPtr = (this._ptr / BYTES_PER_ELEMENT) + idx;
497 CanvasKit.HEAPF32[floatPtr] = f1;
498 CanvasKit.HEAPF32[floatPtr + 1] = f2;
499 CanvasKit.HEAPF32[floatPtr + 2] = f3;
500 CanvasKit.HEAPF32[floatPtr + 3] = f4;
501 return;
502 }
503 this._floats[idx] = f1;
504 this._floats[idx + 1] = f2;
505 this._floats[idx + 2] = f3;
506 this._floats[idx + 3] = f4;
507}
508
509/**
510 * Copies the float data to the WASM memory and returns a pointer
511 * to that allocated memory. Once build has been called, this
512 * float array cannot be made bigger.
513 */
514CanvasKit.FourFloatArrayHelper.prototype.build = function() {
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400515 if (this._ptr) {
516 return this._ptr;
517 }
Kevin Lubickee91c072019-03-29 10:39:52 -0400518 this._ptr = copy1dArray(this._floats, CanvasKit.HEAPF32);
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400519 return this._ptr;
520}
521
Kevin Lubickee91c072019-03-29 10:39:52 -0400522/**
523 * Frees the wasm memory associated with this array. Of note,
524 * the points are not removed, so push/set/build can all
525 * be called to make a newly allocated (possibly bigger)
526 * float array.
527 */
528CanvasKit.FourFloatArrayHelper.prototype.delete = function() {
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400529 if (this._ptr) {
530 CanvasKit._free(this._ptr);
531 this._ptr = null;
532 }
533}
Kevin Lubickee91c072019-03-29 10:39:52 -0400534
535/**
536 * Generic helper for dealing with an array of unsigned ints.
537 */
538CanvasKit.OneUIntArrayHelper = function() {
539 this._uints = [];
540 this._ptr = null;
541
542 Object.defineProperty(this, 'length', {
543 enumerable: true,
544 get: function() {
545 return this._uints.length;
546 },
547 });
548}
549
550/**
551 * push the unsigned int onto the end of the array - if build() has already
552 * been called, the call will return without modifying anything.
553 */
554CanvasKit.OneUIntArrayHelper.prototype.push = function(u) {
555 if (this._ptr) {
556 SkDebug('Cannot push more points - already built');
557 return;
558 }
559 this._uints.push(u);
560}
561
562/**
563 * Set the uint at a given index - if build() has already
564 * been called, the WASM memory will be written to directly.
565 */
566CanvasKit.OneUIntArrayHelper.prototype.set = function(idx, u) {
567 if (idx < 0 || idx >= this._uints.length) {
568 SkDebug('Cannot set index ' + idx + ', it is out of range', this._uints.length);
569 return;
570 }
571 idx *= 4;
572 var BYTES_PER_ELEMENT = 4;
573 if (this._ptr) {
574 // convert this._ptr from uint8_t* to SkScalar* by dividing by 4
575 var uintPtr = (this._ptr / BYTES_PER_ELEMENT) + idx;
576 CanvasKit.HEAPU32[uintPtr] = u;
577 return;
578 }
579 this._uints[idx] = u;
580}
581
582/**
583 * Copies the uint data to the WASM memory and returns a pointer
584 * to that allocated memory. Once build has been called, this
585 * unit array cannot be made bigger.
586 */
587CanvasKit.OneUIntArrayHelper.prototype.build = function() {
588 if (this._ptr) {
589 return this._ptr;
590 }
591 this._ptr = copy1dArray(this._uints, CanvasKit.HEAPU32);
592 return this._ptr;
593}
594
595/**
596 * Frees the wasm memory associated with this array. Of note,
597 * the points are not removed, so push/set/build can all
598 * be called to make a newly allocated (possibly bigger)
599 * uint array.
600 */
601CanvasKit.OneUIntArrayHelper.prototype.delete = function() {
602 if (this._ptr) {
603 CanvasKit._free(this._ptr);
604 this._ptr = null;
605 }
606}
607
608/**
609 * Helper for building an array of SkRects (which are just structs
610 * of 4 floats).
611 *
612 * It can be more performant to use this helper, as
613 * the C++-side array is only allocated once (on the first call)
614 * to build. Subsequent set() operations operate directly on
615 * the C++-side array, avoiding having to re-allocate (and free)
616 * the array every time.
617 *
618 * Input points are taken as left, top, right, bottom
619 */
620CanvasKit.SkRectBuilder = CanvasKit.FourFloatArrayHelper;
621/**
622 * Helper for building an array of RSXForms (which are just structs
623 * of 4 floats).
624 *
625 * It can be more performant to use this helper, as
626 * the C++-side array is only allocated once (on the first call)
627 * to build. Subsequent set() operations operate directly on
628 * the C++-side array, avoiding having to re-allocate (and free)
629 * the array every time.
630 *
631 * An RSXForm is a compressed form of a rotation+scale matrix.
632 *
633 * [ scos -ssin tx ]
634 * [ ssin scos ty ]
635 * [ 0 0 1 ]
636 *
637 * Input points are taken as scos, ssin, tx, ty
638 */
639CanvasKit.RSXFormBuilder = CanvasKit.FourFloatArrayHelper;
640
641/**
642 * Helper for building an array of SkColor
643 *
644 * It can be more performant to use this helper, as
645 * the C++-side array is only allocated once (on the first call)
646 * to build. Subsequent set() operations operate directly on
647 * the C++-side array, avoiding having to re-allocate (and free)
648 * the array every time.
649 */
650CanvasKit.SkColorBuilder = CanvasKit.OneUIntArrayHelper;
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400651
652/**
653 * Malloc returns a TypedArray backed by the C++ memory of the
654 * given length. It should only be used by advanced users who
655 * can manage memory and initialize values properly. When used
656 * correctly, it can save copying of data between JS and C++.
657 * When used incorrectly, it can lead to memory leaks.
Kevin Lubickcf118922020-05-28 14:43:38 -0400658 * Any memory allocated by CanvasKit.Malloc needs to be released with CanvasKit.Free.
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400659 *
Kevin Lubick462a8602020-06-01 15:43:03 -0400660 * const mObj = CanvasKit.Malloc(Float32Array, 20);
661 * // Get a TypedArray view around the malloc'd memory (this does not copy anything).
662 * const ta = mObj.toTypedArray();
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400663 * // store data into ta
Kevin Lubick462a8602020-06-01 15:43:03 -0400664 * // ...
665 * const cf = CanvasKit.SkColorFilter.MakeMatrix(mObj); // ta could also be used.
666 *
667 * // eventually...
668 * CanvasKit.Free(mObj);
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400669 *
670 * @param {TypedArray} typedArray - constructor for the typedArray.
Kevin Lubick6aa38692020-06-01 11:25:47 -0400671 * @param {number} len - number of *elements* to store.
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400672 */
673CanvasKit.Malloc = function(typedArray, len) {
674 var byteLen = len * typedArray.BYTES_PER_ELEMENT;
675 var ptr = CanvasKit._malloc(byteLen);
Kevin Lubick462a8602020-06-01 15:43:03 -0400676 return {
677 '_ck': true,
678 'length': len,
679 'byteOffset': ptr,
680 typedArray: null,
681 'toTypedArray': function() {
682 // Check if the previously allocated array is still usable.
683 // If it's falsey, then we haven't created an array yet.
684 // If it's empty, then WASM resized memory and emptied the array.
685 if (this.typedArray && this.typedArray.length) {
686 return this.typedArray;
687 }
688 this.typedArray = new typedArray(CanvasKit.HEAPU8.buffer, ptr, len);
689 // add a marker that this was allocated in C++ land
690 this.typedArray['_ck'] = true;
691 return this.typedArray;
692 },
693 };
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400694}
Kevin Lubickcf118922020-05-28 14:43:38 -0400695
696/**
697 * Free frees the memory returned by Malloc.
698 * Any memory allocated by CanvasKit.Malloc needs to be released with CanvasKit.Free.
699 */
Kevin Lubick462a8602020-06-01 15:43:03 -0400700CanvasKit.Free = function(mallocObj) {
701 CanvasKit._free(mallocObj['byteOffset']);
702 mallocObj['byteOffset'] = nullptr;
703 // Set these to null to make sure the TypedArrays can be garbage collected.
704 mallocObj['toTypedArray'] = null;
705 mallocObj.typedArray = null;
Kevin Lubickcf118922020-05-28 14:43:38 -0400706}
707
708// This helper will free the given pointer unless the provided array is one
709// that was returned by CanvasKit.Malloc.
710function freeArraysThatAreNotMallocedByUsers(ptr, arr) {
711 if (!arr || !arr['_ck']) {
712 CanvasKit._free(ptr);
713 }
Kevin Lubick6aa38692020-06-01 11:25:47 -0400714}