blob: 912307306fef32f83f407ab2264bd731f4b573d7 [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
Kevin Lubick93f1a382020-06-02 16:15:23 -040020// Constructs a Color as a 32 bit integer, with 8 bits assigned to each channel.
21// Channels are expected to be between 0 and 255 and will be clamped as such.
22CanvasKit.ColorAsInt = function(r, g, b, a) {
23 // default to opaque
24 if (a === undefined) {
25 a = 255;
26 }
27 // This is consistent with how Skia represents colors in C++
28 return (clamp(a) << 24) | (clamp(r) << 16) | (clamp(g) << 8) | (clamp(b) << 0);
29}
Nathaniel Nifonge5d32542020-03-26 09:27:48 -040030// Construct a 4-float color.
31// Opaque if opacity is omitted.
32CanvasKit.Color4f = function(r, g, b, a) {
33 if (a === undefined) {
34 a = 1;
35 }
36 return Float32Array.of(r, g, b, a);
37}
38
39// Color constants use property getters to prevent other code from accidentally
40// changing them.
41Object.defineProperty(CanvasKit, "TRANSPARENT", {
42 get: function() { return CanvasKit.Color4f(0, 0, 0, 0); }
43});
44Object.defineProperty(CanvasKit, "BLACK", {
45 get: function() { return CanvasKit.Color4f(0, 0, 0, 1); }
46});
47Object.defineProperty(CanvasKit, "WHITE", {
48 get: function() { return CanvasKit.Color4f(1, 1, 1, 1); }
49});
50Object.defineProperty(CanvasKit, "RED", {
51 get: function() { return CanvasKit.Color4f(1, 0, 0, 1); }
52});
53Object.defineProperty(CanvasKit, "GREEN", {
54 get: function() { return CanvasKit.Color4f(0, 1, 0, 1); }
55});
56Object.defineProperty(CanvasKit, "BLUE", {
57 get: function() { return CanvasKit.Color4f(0, 0, 1, 1); }
58});
59Object.defineProperty(CanvasKit, "YELLOW", {
60 get: function() { return CanvasKit.Color4f(1, 1, 0, 1); }
61});
62Object.defineProperty(CanvasKit, "CYAN", {
63 get: function() { return CanvasKit.Color4f(0, 1, 1, 1); }
64});
65Object.defineProperty(CanvasKit, "MAGENTA", {
66 get: function() { return CanvasKit.Color4f(1, 0, 1, 1); }
67});
68
69// returns a css style [r, g, b, a] from a CanvasKit.Color
70// where r, g, b are returned as ints in the range [0, 255]
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050071// where a is scaled between 0 and 1.0
72CanvasKit.getColorComponents = function(color) {
73 return [
Nathaniel Nifonge5d32542020-03-26 09:27:48 -040074 Math.floor(color[0]*255),
75 Math.floor(color[1]*255),
76 Math.floor(color[2]*255),
77 color[3]
78 ];
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050079}
80
Kevin Lubick39284662020-02-20 10:29:55 -050081// parseColorString takes in a CSS color value and returns a CanvasKit.Color
Nathaniel Nifonge5d32542020-03-26 09:27:48 -040082// (which is an array of 4 floats in RGBA order). An optional colorMap
83// may be provided which maps custom strings to values.
Kevin Lubick39284662020-02-20 10:29:55 -050084// In the CanvasKit canvas2d shim layer, we provide this map for processing
85// canvas2d calls, but not here for code size reasons.
86CanvasKit.parseColorString = function(colorStr, colorMap) {
87 colorStr = colorStr.toLowerCase();
88 // See https://drafts.csswg.org/css-color/#typedef-hex-color
89 if (colorStr.startsWith('#')) {
90 var r, g, b, a = 255;
91 switch (colorStr.length) {
92 case 9: // 8 hex chars #RRGGBBAA
93 a = parseInt(colorStr.slice(7, 9), 16);
94 case 7: // 6 hex chars #RRGGBB
95 r = parseInt(colorStr.slice(1, 3), 16);
96 g = parseInt(colorStr.slice(3, 5), 16);
97 b = parseInt(colorStr.slice(5, 7), 16);
98 break;
99 case 5: // 4 hex chars #RGBA
100 // multiplying by 17 is the same effect as
101 // appending another character of the same value
102 // e.g. e => ee == 14 => 238
103 a = parseInt(colorStr.slice(4, 5), 16) * 17;
104 case 4: // 6 hex chars #RGB
105 r = parseInt(colorStr.slice(1, 2), 16) * 17;
106 g = parseInt(colorStr.slice(2, 3), 16) * 17;
107 b = parseInt(colorStr.slice(3, 4), 16) * 17;
108 break;
109 }
110 return CanvasKit.Color(r, g, b, a/255);
111
112 } else if (colorStr.startsWith('rgba')) {
113 // Trim off rgba( and the closing )
114 colorStr = colorStr.slice(5, -1);
115 var nums = colorStr.split(',');
116 return CanvasKit.Color(+nums[0], +nums[1], +nums[2],
117 valueOrPercent(nums[3]));
118 } else if (colorStr.startsWith('rgb')) {
119 // Trim off rgba( and the closing )
120 colorStr = colorStr.slice(4, -1);
121 var nums = colorStr.split(',');
122 // rgb can take 3 or 4 arguments
123 return CanvasKit.Color(+nums[0], +nums[1], +nums[2],
124 valueOrPercent(nums[3]));
125 } else if (colorStr.startsWith('gray(')) {
126 // TODO
127 } else if (colorStr.startsWith('hsl')) {
128 // TODO
129 } else if (colorMap) {
130 // Try for named color
131 var nc = colorMap[colorStr];
132 if (nc !== undefined) {
133 return nc;
134 }
135 }
136 SkDebug('unrecognized color ' + colorStr);
137 return CanvasKit.BLACK;
138}
139
Nathaniel Nifonge5d32542020-03-26 09:27:48 -0400140function isCanvasKitColor(ob) {
141 if (!ob) {
142 return false;
143 }
144 return (ob.constructor === Float32Array && ob.length === 4);
145}
146
147// Warning information is lost by this conversion
148function toUint32Color(c) {
149 return ((clamp(c[3]*255) << 24) | (clamp(c[0]*255) << 16) | (clamp(c[1]*255) << 8) | (clamp(c[2]*255) << 0)) >>> 0;
150}
151function uIntColorToCanvasKitColor(c) {
152 return CanvasKit.Color(
153 (c >> 16) & 0xFF,
154 (c >> 8) & 0xFF,
155 (c >> 0) & 0xFF,
156 ((c >> 24) & 0xFF) / 255
157 );
158}
159
Kevin Lubick39284662020-02-20 10:29:55 -0500160function valueOrPercent(aStr) {
161 if (aStr === undefined) {
162 return 1; // default to opaque.
163 }
164 var a = parseFloat(aStr);
165 if (aStr && aStr.indexOf('%') !== -1) {
166 return a / 100;
167 }
168 return a;
169}
170
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500171CanvasKit.multiplyByAlpha = function(color, alpha) {
Nathaniel Nifonge5d32542020-03-26 09:27:48 -0400172 // make a copy of the color so the function remains pure.
173 var result = color.slice();
174 result[3] = Math.max(0, Math.min(result[3] * alpha, 1));
175 return result;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500176}
Kevin Lubick61ef7b22018-11-27 13:26:59 -0500177
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500178function radiansToDegrees(rad) {
179 return (rad / Math.PI) * 180;
180}
Kevin Lubick12c0e502018-11-28 12:51:56 -0500181
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500182function degreesToRadians(deg) {
183 return (deg / 180) * Math.PI;
184}
Kevin Lubick12c0e502018-11-28 12:51:56 -0500185
186// See https://stackoverflow.com/a/31090240
187// This contraption keeps closure from minifying away the check
188// if btoa is defined *and* prevents runtime "btoa" or "window" is not defined.
189// Defined outside any scopes to make it available in all files.
190var isNode = !(new Function("try {return this===window;}catch(e){ return false;}")());
Kevin Lubick1646e7d2018-12-07 13:03:08 -0500191
192function almostEqual(floata, floatb) {
193 return Math.abs(floata - floatb) < 0.00001;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500194}
195
196
197var nullptr = 0; // emscripten doesn't like to take null as uintptr_t
198
199// arr can be a normal JS array or a TypedArray
200// dest is something like CanvasKit.HEAPF32
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400201// ptr can be optionally provided if the memory was already allocated.
202function copy1dArray(arr, dest, ptr) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500203 if (!arr || !arr.length) {
204 return nullptr;
205 }
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400206 // This was created with CanvasKit.Malloc, so it's already been copied.
207 if (arr['_ck']) {
208 return arr.byteOffset;
209 }
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400210 if (!ptr) {
211 ptr = CanvasKit._malloc(arr.length * dest.BYTES_PER_ELEMENT);
212 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500213 // In c++ terms, the WASM heap is a uint8_t*, a long buffer/array of single
214 // byte elements. When we run _malloc, we always get an offset/pointer into
215 // that block of memory.
216 // CanvasKit exposes some different views to make it easier to work with
217 // different types. HEAPF32 for example, exposes it as a float*
218 // However, to make the ptr line up, we have to do some pointer arithmetic.
219 // Concretely, we need to convert ptr to go from an index into a 1-byte-wide
220 // buffer to an index into a 4-byte-wide buffer (in the case of HEAPF32)
221 // and thus we divide ptr by 4.
222 dest.set(arr, ptr / dest.BYTES_PER_ELEMENT);
223 return ptr;
224}
225
226// arr should be a non-jagged 2d JS array (TypedArrays can't be nested
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500227// inside themselves). A common use case is points.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500228// dest is something like CanvasKit.HEAPF32
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400229// ptr can be optionally provided if the memory was already allocated.
230function copy2dArray(arr, dest, ptr) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500231 if (!arr || !arr.length) {
232 return nullptr;
233 }
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400234 if (!ptr) {
235 ptr = CanvasKit._malloc(arr.length * arr[0].length * dest.BYTES_PER_ELEMENT);
236 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500237 var idx = 0;
238 var adjustedPtr = ptr / dest.BYTES_PER_ELEMENT;
239 for (var r = 0; r < arr.length; r++) {
240 for (var c = 0; c < arr[0].length; c++) {
241 dest[adjustedPtr + idx] = arr[r][c];
242 idx++;
243 }
244 }
245 return ptr;
246}
247
Kevin Lubick6bffe392020-04-02 15:24:15 -0400248var defaultPerspective = Float32Array.of(0, 0, 1);
249
Kevin Lubick6aa38692020-06-01 11:25:47 -0400250var _scratch3x3MatrixPtr = nullptr;
Kevin Lubick462a8602020-06-01 15:43:03 -0400251var _scratch3x3Matrix; // the result from CanvasKit.Malloc
Kevin Lubick6aa38692020-06-01 11:25:47 -0400252
Kevin Lubick6bffe392020-04-02 15:24:15 -0400253// Copies the given DOMMatrix/Array/TypedArray to the CanvasKit heap and
254// returns a pointer to the memory. This memory is a float* of length 9.
255// If the passed in matrix is null/undefined, we return 0 (nullptr). All calls
256// on the C++ side should check for nullptr where appropriate. It is generally
257// the responsibility of the JS side code to call CanvasKit._free on the
258// allocated memory before returning to the user code.
259function copy3x3MatrixToWasm(matr) {
260 if (!matr) {
261 return nullptr;
262 }
Kevin Lubick6aa38692020-06-01 11:25:47 -0400263
Kevin Lubick6bffe392020-04-02 15:24:15 -0400264 if (matr.length) {
265 // TODO(kjlubick): Downsample a 16 length (4x4 matrix)
266 if (matr.length !== 6 && matr.length !== 9) {
267 throw 'invalid matrix size';
268 }
269 // This should be an array or typed array.
270 // have to divide the pointer by 4 to "cast" it from bytes to float.
Kevin Lubick6aa38692020-06-01 11:25:47 -0400271 var mPtr = copy1dArray(matr, CanvasKit.HEAPF32, _scratch3x3MatrixPtr);
Kevin Lubick6bffe392020-04-02 15:24:15 -0400272 if (matr.length === 6) {
Kevin Lubick6aa38692020-06-01 11:25:47 -0400273 // Overwrite the last 3 floats with the default perspective. The divide
274 // by 4 casts the pointer into a float pointer.
275 CanvasKit.HEAPF32.set(defaultPerspective, 6 + mPtr / 4);
Kevin Lubick6bffe392020-04-02 15:24:15 -0400276 }
Kevin Lubick6aa38692020-06-01 11:25:47 -0400277 return mPtr;
Kevin Lubick6bffe392020-04-02 15:24:15 -0400278 }
Kevin Lubick462a8602020-06-01 15:43:03 -0400279 var wasm3x3Matrix = _scratch3x3Matrix['toTypedArray']();
Kevin Lubick6aa38692020-06-01 11:25:47 -0400280 // Try as if it's a DOMMatrix. Reminder that DOMMatrix is column-major.
Kevin Lubick462a8602020-06-01 15:43:03 -0400281 wasm3x3Matrix[0] = matr.m11;
282 wasm3x3Matrix[1] = matr.m21;
283 wasm3x3Matrix[2] = matr.m41;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400284
Kevin Lubick462a8602020-06-01 15:43:03 -0400285 wasm3x3Matrix[3] = matr.m12;
286 wasm3x3Matrix[4] = matr.m22;
287 wasm3x3Matrix[5] = matr.m42;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400288
Kevin Lubick462a8602020-06-01 15:43:03 -0400289 wasm3x3Matrix[6] = matr.m14;
290 wasm3x3Matrix[7] = matr.m24;
291 wasm3x3Matrix[8] = matr.m44;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400292 return _scratch3x3MatrixPtr;
Kevin Lubick6bffe392020-04-02 15:24:15 -0400293}
294
Kevin Lubick6aa38692020-06-01 11:25:47 -0400295var _scratch4x4MatrixPtr = nullptr;
Kevin Lubick462a8602020-06-01 15:43:03 -0400296var _scratch4x4Matrix; // the result from CanvasKit.Malloc
Kevin Lubick6aa38692020-06-01 11:25:47 -0400297
Kevin Lubickc1d08982020-04-06 13:52:15 -0400298function copy4x4MatrixToWasm(matr) {
299 if (!matr) {
300 return nullptr;
301 }
Kevin Lubick462a8602020-06-01 15:43:03 -0400302 var wasm4x4Matrix = _scratch4x4Matrix['toTypedArray']();
Kevin Lubickc1d08982020-04-06 13:52:15 -0400303 if (matr.length) {
304 if (matr.length !== 16 && matr.length !== 6 && matr.length !== 9) {
305 throw 'invalid matrix size';
306 }
307 if (matr.length === 16) {
308 // This should be an array or typed array.
309 // have to divide the pointer by 4 to "cast" it from bytes to float.
Kevin Lubick6aa38692020-06-01 11:25:47 -0400310 return copy1dArray(matr, CanvasKit.HEAPF32, _scratch4x4MatrixPtr);
Kevin Lubickc1d08982020-04-06 13:52:15 -0400311 }
Kevin Lubick6aa38692020-06-01 11:25:47 -0400312 // Upscale the row-major 3x3 or 3x2 matrix into a 4x4 row-major matrix
313 // TODO(skbug.com/10108) This will need to change when we convert our
314 // JS 4x4 to be column-major.
315 // When upscaling, we need to overwrite the 3rd column and the 3rd row with
316 // 0s. It's easiest to just do that with a fill command.
Kevin Lubick462a8602020-06-01 15:43:03 -0400317 wasm4x4Matrix.fill(0);
318 wasm4x4Matrix[0] = matr[0];
319 wasm4x4Matrix[1] = matr[1];
Kevin Lubick6aa38692020-06-01 11:25:47 -0400320 // skip col 2
Kevin Lubick462a8602020-06-01 15:43:03 -0400321 wasm4x4Matrix[3] = matr[2];
Kevin Lubick6aa38692020-06-01 11:25:47 -0400322
Kevin Lubick462a8602020-06-01 15:43:03 -0400323 wasm4x4Matrix[4] = matr[3];
324 wasm4x4Matrix[5] = matr[4];
Kevin Lubick6aa38692020-06-01 11:25:47 -0400325 // skip col 2
Kevin Lubick462a8602020-06-01 15:43:03 -0400326 wasm4x4Matrix[7] = matr[5];
Kevin Lubick6aa38692020-06-01 11:25:47 -0400327
328 // skip row 2
329
Kevin Lubick462a8602020-06-01 15:43:03 -0400330 wasm4x4Matrix[12] = matr[6];
331 wasm4x4Matrix[13] = matr[7];
Kevin Lubick6aa38692020-06-01 11:25:47 -0400332 // skip col 2
Kevin Lubick462a8602020-06-01 15:43:03 -0400333 wasm4x4Matrix[15] = matr[8];
Kevin Lubick6aa38692020-06-01 11:25:47 -0400334
335 if (matr.length === 6) {
336 // fix perspective for the 3x2 case (from above, they will be undefined).
Kevin Lubick462a8602020-06-01 15:43:03 -0400337 wasm4x4Matrix[12]=0;
338 wasm4x4Matrix[13]=0;
339 wasm4x4Matrix[15]=1;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400340 }
341 return _scratch4x4MatrixPtr;
Kevin Lubickc1d08982020-04-06 13:52:15 -0400342 }
Kevin Lubick6aa38692020-06-01 11:25:47 -0400343 // Try as if it's a DOMMatrix. Reminder that DOMMatrix is column-major.
Kevin Lubick462a8602020-06-01 15:43:03 -0400344 wasm4x4Matrix[0] = matr.m11;
345 wasm4x4Matrix[1] = matr.m21;
346 wasm4x4Matrix[2] = matr.m31;
347 wasm4x4Matrix[3] = matr.m41;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400348
Kevin Lubick462a8602020-06-01 15:43:03 -0400349 wasm4x4Matrix[4] = matr.m12;
350 wasm4x4Matrix[5] = matr.m22;
351 wasm4x4Matrix[6] = matr.m32;
352 wasm4x4Matrix[7] = matr.m42;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400353
Kevin Lubick462a8602020-06-01 15:43:03 -0400354 wasm4x4Matrix[8] = matr.m13;
355 wasm4x4Matrix[9] = matr.m23;
356 wasm4x4Matrix[10] = matr.m33;
357 wasm4x4Matrix[11] = matr.m43;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400358
Kevin Lubick462a8602020-06-01 15:43:03 -0400359 wasm4x4Matrix[12] = matr.m14;
360 wasm4x4Matrix[13] = matr.m24;
361 wasm4x4Matrix[14] = matr.m34;
362 wasm4x4Matrix[15] = matr.m44;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400363 return _scratch4x4MatrixPtr;
Kevin Lubickc1d08982020-04-06 13:52:15 -0400364}
365
Kevin Lubick6aa38692020-06-01 11:25:47 -0400366// copies a 4x4 matrix at the given pointer into a JS array. It is the caller's
367// responsibility to free the matrPtr if needed.
Kevin Lubickc1d08982020-04-06 13:52:15 -0400368function copy4x4MatrixFromWasm(matrPtr) {
369 // read them out into an array. TODO(kjlubick): If we change SkMatrix to be
370 // typedArrays, then we should return a typed array here too.
371 var rv = new Array(16);
372 for (var i = 0; i < 16; i++) {
373 rv[i] = CanvasKit.HEAPF32[matrPtr/4 + i]; // divide by 4 to "cast" to float.
374 }
Kevin Lubickc1d08982020-04-06 13:52:15 -0400375 return rv;
376}
377
Kevin Lubick6aa38692020-06-01 11:25:47 -0400378var _scratchColorPtr = nullptr;
Kevin Lubick93f1a382020-06-02 16:15:23 -0400379var _scratchColor; // the result from CanvasKit.Malloc
Kevin Lubick6aa38692020-06-01 11:25:47 -0400380
381function copyColorToWasm(color4f, ptr) {
Kevin Lubick6aa38692020-06-01 11:25:47 -0400382 return copy1dArray(color4f, CanvasKit.HEAPF32, ptr || _scratchColorPtr);
383}
384
Kevin Lubick93f1a382020-06-02 16:15:23 -0400385function copyColorComponentsToWasm(r, g, b, a) {
386 var colors = _scratchColor['toTypedArray']();
387 colors[0] = r;
388 colors[1] = g;
389 colors[2] = b;
390 colors[3] = a;
391 return _scratchColorPtr;
392}
393
Kevin Lubick6aa38692020-06-01 11:25:47 -0400394function copyColorToWasmNoScratch(color4f) {
395 // TODO(kjlubick): accept 4 floats or int color
396 return copy1dArray(color4f, CanvasKit.HEAPF32);
397}
398
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400399// copies the four floats at the given pointer in a js Float32Array
400function copyColorFromWasm(colorPtr) {
401 var rv = new Float32Array(4);
402 for (var i = 0; i < 4; i++) {
403 rv[i] = CanvasKit.HEAPF32[colorPtr/4 + i]; // divide by 4 to "cast" to float.
404 }
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400405 return rv;
Kevin Lubickcf118922020-05-28 14:43:38 -0400406}
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400407
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500408// Caching the Float32Arrays can save having to reallocate them
409// over and over again.
410var Float32ArrayCache = {};
411
412// Takes a 2D array of commands and puts them into the WASM heap
413// as a 1D array. This allows them to referenced from the C++ code.
414// Returns a 2 element array, with the first item being essentially a
415// pointer to the array and the second item being the length of
416// the new 1D array.
417//
418// Example usage:
419// let cmds = [
420// [CanvasKit.MOVE_VERB, 0, 10],
421// [CanvasKit.LINE_VERB, 30, 40],
422// [CanvasKit.QUAD_VERB, 20, 50, 45, 60],
423// ];
424function loadCmdsTypedArray(arr) {
425 var len = 0;
426 for (var r = 0; r < arr.length; r++) {
427 len += arr[r].length;
428 }
429
430 var ta;
431 if (Float32ArrayCache[len]) {
432 ta = Float32ArrayCache[len];
433 } else {
434 ta = new Float32Array(len);
435 Float32ArrayCache[len] = ta;
436 }
437 // Flatten into a 1d array
438 var i = 0;
439 for (var r = 0; r < arr.length; r++) {
440 for (var c = 0; c < arr[r].length; c++) {
441 var item = arr[r][c];
442 ta[i] = item;
443 i++;
444 }
445 }
446
447 var ptr = copy1dArray(ta, CanvasKit.HEAPF32);
448 return [ptr, len];
449}
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400450
Kevin Lubickcc13fd32019-04-05 13:00:01 -0400451function saveBytesToFile(bytes, fileName) {
452 if (!isNode) {
453 // https://stackoverflow.com/a/32094834
454 var blob = new Blob([bytes], {type: 'application/octet-stream'});
455 url = window.URL.createObjectURL(blob);
456 var a = document.createElement('a');
457 document.body.appendChild(a);
458 a.href = url;
459 a.download = fileName;
460 a.click();
461 // clean up after because FF might not download it synchronously
462 setTimeout(function() {
463 URL.revokeObjectURL(url);
464 a.remove();
465 }, 50);
466 } else {
467 var fs = require('fs');
468 // https://stackoverflow.com/a/42006750
469 // https://stackoverflow.com/a/47018122
470 fs.writeFile(fileName, new Buffer(bytes), function(err) {
471 if (err) throw err;
472 });
473 }
474}
Kevin Lubickee91c072019-03-29 10:39:52 -0400475/**
476 * Generic helper for dealing with an array of four floats.
477 */
478CanvasKit.FourFloatArrayHelper = function() {
479 this._floats = [];
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400480 this._ptr = null;
Kevin Lubickee91c072019-03-29 10:39:52 -0400481
482 Object.defineProperty(this, 'length', {
483 enumerable: true,
484 get: function() {
485 return this._floats.length / 4;
486 },
487 });
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400488}
489
490/**
Kevin Lubickee91c072019-03-29 10:39:52 -0400491 * push the four floats onto the end of the array - if build() has already
492 * been called, the call will return without modifying anything.
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400493 */
Kevin Lubickee91c072019-03-29 10:39:52 -0400494CanvasKit.FourFloatArrayHelper.prototype.push = function(f1, f2, f3, f4) {
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400495 if (this._ptr) {
496 SkDebug('Cannot push more points - already built');
497 return;
498 }
Kevin Lubickee91c072019-03-29 10:39:52 -0400499 this._floats.push(f1, f2, f3, f4);
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400500}
501
Kevin Lubickee91c072019-03-29 10:39:52 -0400502/**
503 * Set the four floats at a given index - if build() has already
504 * been called, the WASM memory will be written to directly.
505 */
506CanvasKit.FourFloatArrayHelper.prototype.set = function(idx, f1, f2, f3, f4) {
507 if (idx < 0 || idx >= this._floats.length/4) {
508 SkDebug('Cannot set index ' + idx + ', it is out of range', this._floats.length/4);
509 return;
510 }
511 idx *= 4;
512 var BYTES_PER_ELEMENT = 4;
513 if (this._ptr) {
514 // convert this._ptr from uint8_t* to SkScalar* by dividing by 4
515 var floatPtr = (this._ptr / BYTES_PER_ELEMENT) + idx;
516 CanvasKit.HEAPF32[floatPtr] = f1;
517 CanvasKit.HEAPF32[floatPtr + 1] = f2;
518 CanvasKit.HEAPF32[floatPtr + 2] = f3;
519 CanvasKit.HEAPF32[floatPtr + 3] = f4;
520 return;
521 }
522 this._floats[idx] = f1;
523 this._floats[idx + 1] = f2;
524 this._floats[idx + 2] = f3;
525 this._floats[idx + 3] = f4;
526}
527
528/**
529 * Copies the float data to the WASM memory and returns a pointer
530 * to that allocated memory. Once build has been called, this
531 * float array cannot be made bigger.
532 */
533CanvasKit.FourFloatArrayHelper.prototype.build = function() {
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400534 if (this._ptr) {
535 return this._ptr;
536 }
Kevin Lubickee91c072019-03-29 10:39:52 -0400537 this._ptr = copy1dArray(this._floats, CanvasKit.HEAPF32);
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400538 return this._ptr;
539}
540
Kevin Lubickee91c072019-03-29 10:39:52 -0400541/**
542 * Frees the wasm memory associated with this array. Of note,
543 * the points are not removed, so push/set/build can all
544 * be called to make a newly allocated (possibly bigger)
545 * float array.
546 */
547CanvasKit.FourFloatArrayHelper.prototype.delete = function() {
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400548 if (this._ptr) {
549 CanvasKit._free(this._ptr);
550 this._ptr = null;
551 }
552}
Kevin Lubickee91c072019-03-29 10:39:52 -0400553
554/**
555 * Generic helper for dealing with an array of unsigned ints.
556 */
557CanvasKit.OneUIntArrayHelper = function() {
558 this._uints = [];
559 this._ptr = null;
560
561 Object.defineProperty(this, 'length', {
562 enumerable: true,
563 get: function() {
564 return this._uints.length;
565 },
566 });
567}
568
569/**
570 * push the unsigned int onto the end of the array - if build() has already
571 * been called, the call will return without modifying anything.
572 */
573CanvasKit.OneUIntArrayHelper.prototype.push = function(u) {
574 if (this._ptr) {
575 SkDebug('Cannot push more points - already built');
576 return;
577 }
578 this._uints.push(u);
579}
580
581/**
582 * Set the uint at a given index - if build() has already
583 * been called, the WASM memory will be written to directly.
584 */
585CanvasKit.OneUIntArrayHelper.prototype.set = function(idx, u) {
586 if (idx < 0 || idx >= this._uints.length) {
587 SkDebug('Cannot set index ' + idx + ', it is out of range', this._uints.length);
588 return;
589 }
590 idx *= 4;
591 var BYTES_PER_ELEMENT = 4;
592 if (this._ptr) {
593 // convert this._ptr from uint8_t* to SkScalar* by dividing by 4
594 var uintPtr = (this._ptr / BYTES_PER_ELEMENT) + idx;
595 CanvasKit.HEAPU32[uintPtr] = u;
596 return;
597 }
598 this._uints[idx] = u;
599}
600
601/**
602 * Copies the uint data to the WASM memory and returns a pointer
603 * to that allocated memory. Once build has been called, this
604 * unit array cannot be made bigger.
605 */
606CanvasKit.OneUIntArrayHelper.prototype.build = function() {
607 if (this._ptr) {
608 return this._ptr;
609 }
610 this._ptr = copy1dArray(this._uints, CanvasKit.HEAPU32);
611 return this._ptr;
612}
613
614/**
615 * Frees the wasm memory associated with this array. Of note,
616 * the points are not removed, so push/set/build can all
617 * be called to make a newly allocated (possibly bigger)
618 * uint array.
619 */
620CanvasKit.OneUIntArrayHelper.prototype.delete = function() {
621 if (this._ptr) {
622 CanvasKit._free(this._ptr);
623 this._ptr = null;
624 }
625}
626
627/**
628 * Helper for building an array of SkRects (which are just structs
629 * of 4 floats).
630 *
631 * It can be more performant to use this helper, as
632 * the C++-side array is only allocated once (on the first call)
633 * to build. Subsequent set() operations operate directly on
634 * the C++-side array, avoiding having to re-allocate (and free)
635 * the array every time.
636 *
637 * Input points are taken as left, top, right, bottom
638 */
639CanvasKit.SkRectBuilder = CanvasKit.FourFloatArrayHelper;
640/**
641 * Helper for building an array of RSXForms (which are just structs
642 * of 4 floats).
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 *
650 * An RSXForm is a compressed form of a rotation+scale matrix.
651 *
652 * [ scos -ssin tx ]
653 * [ ssin scos ty ]
654 * [ 0 0 1 ]
655 *
656 * Input points are taken as scos, ssin, tx, ty
657 */
658CanvasKit.RSXFormBuilder = CanvasKit.FourFloatArrayHelper;
659
660/**
661 * Helper for building an array of SkColor
662 *
663 * It can be more performant to use this helper, as
664 * the C++-side array is only allocated once (on the first call)
665 * to build. Subsequent set() operations operate directly on
666 * the C++-side array, avoiding having to re-allocate (and free)
667 * the array every time.
668 */
669CanvasKit.SkColorBuilder = CanvasKit.OneUIntArrayHelper;
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400670
671/**
672 * Malloc returns a TypedArray backed by the C++ memory of the
673 * given length. It should only be used by advanced users who
674 * can manage memory and initialize values properly. When used
675 * correctly, it can save copying of data between JS and C++.
676 * When used incorrectly, it can lead to memory leaks.
Kevin Lubickcf118922020-05-28 14:43:38 -0400677 * Any memory allocated by CanvasKit.Malloc needs to be released with CanvasKit.Free.
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400678 *
Kevin Lubick462a8602020-06-01 15:43:03 -0400679 * const mObj = CanvasKit.Malloc(Float32Array, 20);
Kevin Lubick93f1a382020-06-02 16:15:23 -0400680 * Get a TypedArray view around the malloc'd memory (this does not copy anything).
Kevin Lubick462a8602020-06-01 15:43:03 -0400681 * const ta = mObj.toTypedArray();
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400682 * // store data into ta
Kevin Lubick93f1a382020-06-02 16:15:23 -0400683 * const cf = CanvasKit.SkColorFilter.MakeMatrix(ta); // mObj could also be used.
Kevin Lubick462a8602020-06-01 15:43:03 -0400684 *
685 * // eventually...
686 * CanvasKit.Free(mObj);
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400687 *
688 * @param {TypedArray} typedArray - constructor for the typedArray.
Kevin Lubick6aa38692020-06-01 11:25:47 -0400689 * @param {number} len - number of *elements* to store.
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400690 */
691CanvasKit.Malloc = function(typedArray, len) {
692 var byteLen = len * typedArray.BYTES_PER_ELEMENT;
693 var ptr = CanvasKit._malloc(byteLen);
Kevin Lubick462a8602020-06-01 15:43:03 -0400694 return {
695 '_ck': true,
696 'length': len,
697 'byteOffset': ptr,
698 typedArray: null,
699 'toTypedArray': function() {
700 // Check if the previously allocated array is still usable.
701 // If it's falsey, then we haven't created an array yet.
702 // If it's empty, then WASM resized memory and emptied the array.
703 if (this.typedArray && this.typedArray.length) {
704 return this.typedArray;
705 }
706 this.typedArray = new typedArray(CanvasKit.HEAPU8.buffer, ptr, len);
707 // add a marker that this was allocated in C++ land
708 this.typedArray['_ck'] = true;
709 return this.typedArray;
710 },
711 };
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400712}
Kevin Lubickcf118922020-05-28 14:43:38 -0400713
714/**
715 * Free frees the memory returned by Malloc.
716 * Any memory allocated by CanvasKit.Malloc needs to be released with CanvasKit.Free.
717 */
Kevin Lubick462a8602020-06-01 15:43:03 -0400718CanvasKit.Free = function(mallocObj) {
719 CanvasKit._free(mallocObj['byteOffset']);
720 mallocObj['byteOffset'] = nullptr;
721 // Set these to null to make sure the TypedArrays can be garbage collected.
722 mallocObj['toTypedArray'] = null;
723 mallocObj.typedArray = null;
Kevin Lubickcf118922020-05-28 14:43:38 -0400724}
725
726// This helper will free the given pointer unless the provided array is one
727// that was returned by CanvasKit.Malloc.
728function freeArraysThatAreNotMallocedByUsers(ptr, arr) {
729 if (!arr || !arr['_ck']) {
730 CanvasKit._free(ptr);
731 }
Kevin Lubick6aa38692020-06-01 11:25:47 -0400732}