blob: 80994b651fc5a74f718adcf1be95ae5511a47de0 [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 Lubick9adc1d42020-06-04 08:25:16 -040020// Constructs a Color as a 32 bit unsigned integer, with 8 bits assigned to each channel.
Kevin Lubick93f1a382020-06-02 16:15:23 -040021// 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 }
Kevin Lubick9adc1d42020-06-04 08:25:16 -040027 // This is consistent with how Skia represents colors in C++, as an unsigned int.
Kevin Lubick59e087e2020-06-03 12:24:07 -040028 // This is also consistent with how Flutter represents colors:
29 // https://github.com/flutter/engine/blob/243bb59c7179a7e701ce478080d6ce990710ae73/lib/web_ui/lib/src/ui/painting.dart#L50
Kevin Lubick9adc1d42020-06-04 08:25:16 -040030 return (((clamp(a) << 24) | (clamp(r) << 16) | (clamp(g) << 8) | (clamp(b) << 0)
31 & 0xFFFFFFF) // This truncates the unsigned to 32 bits and signals to JS engines they can
32 // represent the number with an int instead of a double.
33 >>> 0); // This makes the value an unsigned int.
Kevin Lubick93f1a382020-06-02 16:15:23 -040034}
Nathaniel Nifonge5d32542020-03-26 09:27:48 -040035// Construct a 4-float color.
36// Opaque if opacity is omitted.
37CanvasKit.Color4f = function(r, g, b, a) {
38 if (a === undefined) {
39 a = 1;
40 }
41 return Float32Array.of(r, g, b, a);
42}
43
44// Color constants use property getters to prevent other code from accidentally
45// changing them.
46Object.defineProperty(CanvasKit, "TRANSPARENT", {
47 get: function() { return CanvasKit.Color4f(0, 0, 0, 0); }
48});
49Object.defineProperty(CanvasKit, "BLACK", {
50 get: function() { return CanvasKit.Color4f(0, 0, 0, 1); }
51});
52Object.defineProperty(CanvasKit, "WHITE", {
53 get: function() { return CanvasKit.Color4f(1, 1, 1, 1); }
54});
55Object.defineProperty(CanvasKit, "RED", {
56 get: function() { return CanvasKit.Color4f(1, 0, 0, 1); }
57});
58Object.defineProperty(CanvasKit, "GREEN", {
59 get: function() { return CanvasKit.Color4f(0, 1, 0, 1); }
60});
61Object.defineProperty(CanvasKit, "BLUE", {
62 get: function() { return CanvasKit.Color4f(0, 0, 1, 1); }
63});
64Object.defineProperty(CanvasKit, "YELLOW", {
65 get: function() { return CanvasKit.Color4f(1, 1, 0, 1); }
66});
67Object.defineProperty(CanvasKit, "CYAN", {
68 get: function() { return CanvasKit.Color4f(0, 1, 1, 1); }
69});
70Object.defineProperty(CanvasKit, "MAGENTA", {
71 get: function() { return CanvasKit.Color4f(1, 0, 1, 1); }
72});
73
74// returns a css style [r, g, b, a] from a CanvasKit.Color
75// where r, g, b are returned as ints in the range [0, 255]
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050076// where a is scaled between 0 and 1.0
77CanvasKit.getColorComponents = function(color) {
78 return [
Nathaniel Nifonge5d32542020-03-26 09:27:48 -040079 Math.floor(color[0]*255),
80 Math.floor(color[1]*255),
81 Math.floor(color[2]*255),
82 color[3]
83 ];
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050084}
85
Kevin Lubick39284662020-02-20 10:29:55 -050086// parseColorString takes in a CSS color value and returns a CanvasKit.Color
Nathaniel Nifonge5d32542020-03-26 09:27:48 -040087// (which is an array of 4 floats in RGBA order). An optional colorMap
88// may be provided which maps custom strings to values.
Kevin Lubick39284662020-02-20 10:29:55 -050089// In the CanvasKit canvas2d shim layer, we provide this map for processing
90// canvas2d calls, but not here for code size reasons.
91CanvasKit.parseColorString = function(colorStr, colorMap) {
92 colorStr = colorStr.toLowerCase();
93 // See https://drafts.csswg.org/css-color/#typedef-hex-color
94 if (colorStr.startsWith('#')) {
95 var r, g, b, a = 255;
96 switch (colorStr.length) {
97 case 9: // 8 hex chars #RRGGBBAA
98 a = parseInt(colorStr.slice(7, 9), 16);
99 case 7: // 6 hex chars #RRGGBB
100 r = parseInt(colorStr.slice(1, 3), 16);
101 g = parseInt(colorStr.slice(3, 5), 16);
102 b = parseInt(colorStr.slice(5, 7), 16);
103 break;
104 case 5: // 4 hex chars #RGBA
105 // multiplying by 17 is the same effect as
106 // appending another character of the same value
107 // e.g. e => ee == 14 => 238
108 a = parseInt(colorStr.slice(4, 5), 16) * 17;
109 case 4: // 6 hex chars #RGB
110 r = parseInt(colorStr.slice(1, 2), 16) * 17;
111 g = parseInt(colorStr.slice(2, 3), 16) * 17;
112 b = parseInt(colorStr.slice(3, 4), 16) * 17;
113 break;
114 }
115 return CanvasKit.Color(r, g, b, a/255);
116
117 } else if (colorStr.startsWith('rgba')) {
118 // Trim off rgba( and the closing )
119 colorStr = colorStr.slice(5, -1);
120 var nums = colorStr.split(',');
121 return CanvasKit.Color(+nums[0], +nums[1], +nums[2],
122 valueOrPercent(nums[3]));
123 } else if (colorStr.startsWith('rgb')) {
124 // Trim off rgba( and the closing )
125 colorStr = colorStr.slice(4, -1);
126 var nums = colorStr.split(',');
127 // rgb can take 3 or 4 arguments
128 return CanvasKit.Color(+nums[0], +nums[1], +nums[2],
129 valueOrPercent(nums[3]));
130 } else if (colorStr.startsWith('gray(')) {
131 // TODO
132 } else if (colorStr.startsWith('hsl')) {
133 // TODO
134 } else if (colorMap) {
135 // Try for named color
136 var nc = colorMap[colorStr];
137 if (nc !== undefined) {
138 return nc;
139 }
140 }
141 SkDebug('unrecognized color ' + colorStr);
142 return CanvasKit.BLACK;
143}
144
Nathaniel Nifonge5d32542020-03-26 09:27:48 -0400145function isCanvasKitColor(ob) {
146 if (!ob) {
147 return false;
148 }
149 return (ob.constructor === Float32Array && ob.length === 4);
150}
151
152// Warning information is lost by this conversion
153function toUint32Color(c) {
154 return ((clamp(c[3]*255) << 24) | (clamp(c[0]*255) << 16) | (clamp(c[1]*255) << 8) | (clamp(c[2]*255) << 0)) >>> 0;
155}
Nathaniel Nifongd05fd0c2020-06-11 08:44:20 -0400156// Accepts various colors representations and converts them to an array of int colors.
157// Does not handle builders.
158function assureIntColors(arr) {
159 if (arr instanceof Float32Array) {
160 var count = Math.floor(arr.length / 4);
161 var result = new Uint32Array(count);
162 for (var i = 0; i < count; i ++) {
163 result[i] = toUint32Color(arr.slice(i*4, (i+1)*4));
164 }
165 return result;
166 } else if (arr instanceof Uint32Array) {
167 return arr;
168 } else if (arr instanceof Array && arr[0] instanceof Float32Array) {
169 return arr.map(toUint32Color);
170 }
171
172}
Nathaniel Nifonge5d32542020-03-26 09:27:48 -0400173function uIntColorToCanvasKitColor(c) {
174 return CanvasKit.Color(
175 (c >> 16) & 0xFF,
176 (c >> 8) & 0xFF,
177 (c >> 0) & 0xFF,
178 ((c >> 24) & 0xFF) / 255
179 );
180}
181
Kevin Lubick39284662020-02-20 10:29:55 -0500182function valueOrPercent(aStr) {
183 if (aStr === undefined) {
184 return 1; // default to opaque.
185 }
186 var a = parseFloat(aStr);
187 if (aStr && aStr.indexOf('%') !== -1) {
188 return a / 100;
189 }
190 return a;
191}
192
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500193CanvasKit.multiplyByAlpha = function(color, alpha) {
Nathaniel Nifonge5d32542020-03-26 09:27:48 -0400194 // make a copy of the color so the function remains pure.
195 var result = color.slice();
196 result[3] = Math.max(0, Math.min(result[3] * alpha, 1));
197 return result;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500198}
Kevin Lubick61ef7b22018-11-27 13:26:59 -0500199
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500200function radiansToDegrees(rad) {
201 return (rad / Math.PI) * 180;
202}
Kevin Lubick12c0e502018-11-28 12:51:56 -0500203
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500204function degreesToRadians(deg) {
205 return (deg / 180) * Math.PI;
206}
Kevin Lubick12c0e502018-11-28 12:51:56 -0500207
208// See https://stackoverflow.com/a/31090240
209// This contraption keeps closure from minifying away the check
210// if btoa is defined *and* prevents runtime "btoa" or "window" is not defined.
211// Defined outside any scopes to make it available in all files.
212var isNode = !(new Function("try {return this===window;}catch(e){ return false;}")());
Kevin Lubick1646e7d2018-12-07 13:03:08 -0500213
214function almostEqual(floata, floatb) {
215 return Math.abs(floata - floatb) < 0.00001;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500216}
217
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500218var nullptr = 0; // emscripten doesn't like to take null as uintptr_t
219
220// arr can be a normal JS array or a TypedArray
Kevin Lubick9c401e72020-06-09 14:22:20 -0400221// dest is a string like "HEAPU32" that specifies the type the src array
222// should be copied into.
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400223// ptr can be optionally provided if the memory was already allocated.
224function copy1dArray(arr, dest, ptr) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500225 if (!arr || !arr.length) {
226 return nullptr;
227 }
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400228 // This was created with CanvasKit.Malloc, so it's already been copied.
229 if (arr['_ck']) {
230 return arr.byteOffset;
231 }
Kevin Lubick69e46da2020-06-05 07:13:48 -0400232 var bytesPerElement = CanvasKit[dest].BYTES_PER_ELEMENT;
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400233 if (!ptr) {
Kevin Lubick69e46da2020-06-05 07:13:48 -0400234 ptr = CanvasKit._malloc(arr.length * bytesPerElement);
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400235 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500236 // In c++ terms, the WASM heap is a uint8_t*, a long buffer/array of single
237 // byte elements. When we run _malloc, we always get an offset/pointer into
238 // that block of memory.
239 // CanvasKit exposes some different views to make it easier to work with
240 // different types. HEAPF32 for example, exposes it as a float*
241 // However, to make the ptr line up, we have to do some pointer arithmetic.
242 // Concretely, we need to convert ptr to go from an index into a 1-byte-wide
243 // buffer to an index into a 4-byte-wide buffer (in the case of HEAPF32)
244 // and thus we divide ptr by 4.
Kevin Lubick69e46da2020-06-05 07:13:48 -0400245 // It is important to make sure we are grabbing the freshest view of the
246 // memory possible because if we call _malloc and the heap needs to grow,
247 // the TypedArrayView will no longer be valid.
248 CanvasKit[dest].set(arr, ptr / bytesPerElement);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500249 return ptr;
250}
251
252// arr should be a non-jagged 2d JS array (TypedArrays can't be nested
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500253// inside themselves). A common use case is points.
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500254// dest is something like CanvasKit.HEAPF32
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400255// ptr can be optionally provided if the memory was already allocated.
Kevin Lubick69e46da2020-06-05 07:13:48 -0400256// TODO(kjlubick): Remove 2d arrays - everything should be flat.
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400257function copy2dArray(arr, dest, ptr) {
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500258 if (!arr || !arr.length) {
259 return nullptr;
260 }
Kevin Lubick69e46da2020-06-05 07:13:48 -0400261 var bytesPerElement = CanvasKit[dest].BYTES_PER_ELEMENT;
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400262 if (!ptr) {
Kevin Lubick69e46da2020-06-05 07:13:48 -0400263 ptr = CanvasKit._malloc(arr.length * arr[0].length * bytesPerElement);
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400264 }
Kevin Lubick69e46da2020-06-05 07:13:48 -0400265 // Make sure we have a fresh view of the heap after we malloc.
266 dest = CanvasKit[dest];
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500267 var idx = 0;
Kevin Lubick69e46da2020-06-05 07:13:48 -0400268 var adjustedPtr = ptr / bytesPerElement;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500269 for (var r = 0; r < arr.length; r++) {
270 for (var c = 0; c < arr[0].length; c++) {
271 dest[adjustedPtr + idx] = arr[r][c];
272 idx++;
273 }
274 }
275 return ptr;
276}
277
Nathaniel Nifongd05fd0c2020-06-11 08:44:20 -0400278// Copies an array of colors to wasm, returning an object with the pointer
279// and info necessary to use the copied colors.
280// Accepts either a flat Float32Array, flat Uint32Array or Array of Float32Arrays.
281// If color is an object that was allocated with CanvasKit.Malloc, it's pointer is
282// returned and no extra copy is performed.
283// Array of Float32Arrays is deprecated and planned to be removed, prefer flat
284// Float32Array
285// TODO(nifong): have this accept color builders.
286function copyFlexibleColorArray(colors) {
287 var result = {
288 colorPtr: nullptr,
289 count: colors.length,
290 colorType: CanvasKit.ColorType.RGBA_F32,
291 }
292 if (colors instanceof Float32Array) {
293 result.colorPtr = copy1dArray(colors, "HEAPF32");
294 result.count = colors.length / 4;
295
296 } else if (colors instanceof Uint32Array) {
297 result.colorPtr = copy1dArray(colors, "HEAPU32");
298 result.colorType = CanvasKit.ColorType.RGBA_8888;
299
300 } else if (colors instanceof Array && colors[0] instanceof Float32Array) {
301 result.colorPtr = copy2dArray(colors, "HEAPF32");
302 } else {
303 throw('Invalid argument to copyFlexibleColorArray, Not a color array '+typeof(colors));
304 }
305 return result;
306}
307
Kevin Lubick6bffe392020-04-02 15:24:15 -0400308var defaultPerspective = Float32Array.of(0, 0, 1);
309
Kevin Lubick6aa38692020-06-01 11:25:47 -0400310var _scratch3x3MatrixPtr = nullptr;
Kevin Lubick462a8602020-06-01 15:43:03 -0400311var _scratch3x3Matrix; // the result from CanvasKit.Malloc
Kevin Lubick6aa38692020-06-01 11:25:47 -0400312
Kevin Lubick6bffe392020-04-02 15:24:15 -0400313// Copies the given DOMMatrix/Array/TypedArray to the CanvasKit heap and
314// returns a pointer to the memory. This memory is a float* of length 9.
315// If the passed in matrix is null/undefined, we return 0 (nullptr). All calls
316// on the C++ side should check for nullptr where appropriate. It is generally
317// the responsibility of the JS side code to call CanvasKit._free on the
318// allocated memory before returning to the user code.
319function copy3x3MatrixToWasm(matr) {
320 if (!matr) {
321 return nullptr;
322 }
Kevin Lubick6aa38692020-06-01 11:25:47 -0400323
Kevin Lubick6bffe392020-04-02 15:24:15 -0400324 if (matr.length) {
325 // TODO(kjlubick): Downsample a 16 length (4x4 matrix)
326 if (matr.length !== 6 && matr.length !== 9) {
327 throw 'invalid matrix size';
328 }
329 // This should be an array or typed array.
330 // have to divide the pointer by 4 to "cast" it from bytes to float.
Kevin Lubick69e46da2020-06-05 07:13:48 -0400331 var mPtr = copy1dArray(matr, "HEAPF32", _scratch3x3MatrixPtr);
Kevin Lubick6bffe392020-04-02 15:24:15 -0400332 if (matr.length === 6) {
Kevin Lubick6aa38692020-06-01 11:25:47 -0400333 // Overwrite the last 3 floats with the default perspective. The divide
334 // by 4 casts the pointer into a float pointer.
335 CanvasKit.HEAPF32.set(defaultPerspective, 6 + mPtr / 4);
Kevin Lubick6bffe392020-04-02 15:24:15 -0400336 }
Kevin Lubick6aa38692020-06-01 11:25:47 -0400337 return mPtr;
Kevin Lubick6bffe392020-04-02 15:24:15 -0400338 }
Kevin Lubick462a8602020-06-01 15:43:03 -0400339 var wasm3x3Matrix = _scratch3x3Matrix['toTypedArray']();
Kevin Lubick6aa38692020-06-01 11:25:47 -0400340 // Try as if it's a DOMMatrix. Reminder that DOMMatrix is column-major.
Kevin Lubick462a8602020-06-01 15:43:03 -0400341 wasm3x3Matrix[0] = matr.m11;
342 wasm3x3Matrix[1] = matr.m21;
343 wasm3x3Matrix[2] = matr.m41;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400344
Kevin Lubick462a8602020-06-01 15:43:03 -0400345 wasm3x3Matrix[3] = matr.m12;
346 wasm3x3Matrix[4] = matr.m22;
347 wasm3x3Matrix[5] = matr.m42;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400348
Kevin Lubick462a8602020-06-01 15:43:03 -0400349 wasm3x3Matrix[6] = matr.m14;
350 wasm3x3Matrix[7] = matr.m24;
351 wasm3x3Matrix[8] = matr.m44;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400352 return _scratch3x3MatrixPtr;
Kevin Lubick6bffe392020-04-02 15:24:15 -0400353}
354
Kevin Lubick6aa38692020-06-01 11:25:47 -0400355var _scratch4x4MatrixPtr = nullptr;
Kevin Lubick462a8602020-06-01 15:43:03 -0400356var _scratch4x4Matrix; // the result from CanvasKit.Malloc
Kevin Lubick6aa38692020-06-01 11:25:47 -0400357
Kevin Lubickc1d08982020-04-06 13:52:15 -0400358function copy4x4MatrixToWasm(matr) {
359 if (!matr) {
360 return nullptr;
361 }
Kevin Lubick462a8602020-06-01 15:43:03 -0400362 var wasm4x4Matrix = _scratch4x4Matrix['toTypedArray']();
Kevin Lubickc1d08982020-04-06 13:52:15 -0400363 if (matr.length) {
364 if (matr.length !== 16 && matr.length !== 6 && matr.length !== 9) {
365 throw 'invalid matrix size';
366 }
367 if (matr.length === 16) {
368 // This should be an array or typed array.
369 // have to divide the pointer by 4 to "cast" it from bytes to float.
Kevin Lubick69e46da2020-06-05 07:13:48 -0400370 return copy1dArray(matr, "HEAPF32", _scratch4x4MatrixPtr);
Kevin Lubickc1d08982020-04-06 13:52:15 -0400371 }
Kevin Lubick6aa38692020-06-01 11:25:47 -0400372 // Upscale the row-major 3x3 or 3x2 matrix into a 4x4 row-major matrix
373 // TODO(skbug.com/10108) This will need to change when we convert our
374 // JS 4x4 to be column-major.
375 // When upscaling, we need to overwrite the 3rd column and the 3rd row with
376 // 0s. It's easiest to just do that with a fill command.
Kevin Lubick462a8602020-06-01 15:43:03 -0400377 wasm4x4Matrix.fill(0);
378 wasm4x4Matrix[0] = matr[0];
379 wasm4x4Matrix[1] = matr[1];
Kevin Lubick6aa38692020-06-01 11:25:47 -0400380 // skip col 2
Kevin Lubick462a8602020-06-01 15:43:03 -0400381 wasm4x4Matrix[3] = matr[2];
Kevin Lubick6aa38692020-06-01 11:25:47 -0400382
Kevin Lubick462a8602020-06-01 15:43:03 -0400383 wasm4x4Matrix[4] = matr[3];
384 wasm4x4Matrix[5] = matr[4];
Kevin Lubick6aa38692020-06-01 11:25:47 -0400385 // skip col 2
Kevin Lubick462a8602020-06-01 15:43:03 -0400386 wasm4x4Matrix[7] = matr[5];
Kevin Lubick6aa38692020-06-01 11:25:47 -0400387
388 // skip row 2
389
Kevin Lubick462a8602020-06-01 15:43:03 -0400390 wasm4x4Matrix[12] = matr[6];
391 wasm4x4Matrix[13] = matr[7];
Kevin Lubick6aa38692020-06-01 11:25:47 -0400392 // skip col 2
Kevin Lubick462a8602020-06-01 15:43:03 -0400393 wasm4x4Matrix[15] = matr[8];
Kevin Lubick6aa38692020-06-01 11:25:47 -0400394
395 if (matr.length === 6) {
396 // fix perspective for the 3x2 case (from above, they will be undefined).
Kevin Lubick462a8602020-06-01 15:43:03 -0400397 wasm4x4Matrix[12]=0;
398 wasm4x4Matrix[13]=0;
399 wasm4x4Matrix[15]=1;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400400 }
401 return _scratch4x4MatrixPtr;
Kevin Lubickc1d08982020-04-06 13:52:15 -0400402 }
Kevin Lubick6aa38692020-06-01 11:25:47 -0400403 // Try as if it's a DOMMatrix. Reminder that DOMMatrix is column-major.
Kevin Lubick462a8602020-06-01 15:43:03 -0400404 wasm4x4Matrix[0] = matr.m11;
405 wasm4x4Matrix[1] = matr.m21;
406 wasm4x4Matrix[2] = matr.m31;
407 wasm4x4Matrix[3] = matr.m41;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400408
Kevin Lubick462a8602020-06-01 15:43:03 -0400409 wasm4x4Matrix[4] = matr.m12;
410 wasm4x4Matrix[5] = matr.m22;
411 wasm4x4Matrix[6] = matr.m32;
412 wasm4x4Matrix[7] = matr.m42;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400413
Kevin Lubick462a8602020-06-01 15:43:03 -0400414 wasm4x4Matrix[8] = matr.m13;
415 wasm4x4Matrix[9] = matr.m23;
416 wasm4x4Matrix[10] = matr.m33;
417 wasm4x4Matrix[11] = matr.m43;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400418
Kevin Lubick462a8602020-06-01 15:43:03 -0400419 wasm4x4Matrix[12] = matr.m14;
420 wasm4x4Matrix[13] = matr.m24;
421 wasm4x4Matrix[14] = matr.m34;
422 wasm4x4Matrix[15] = matr.m44;
Kevin Lubick6aa38692020-06-01 11:25:47 -0400423 return _scratch4x4MatrixPtr;
Kevin Lubickc1d08982020-04-06 13:52:15 -0400424}
425
Kevin Lubick6aa38692020-06-01 11:25:47 -0400426// copies a 4x4 matrix at the given pointer into a JS array. It is the caller's
427// responsibility to free the matrPtr if needed.
Kevin Lubickc1d08982020-04-06 13:52:15 -0400428function copy4x4MatrixFromWasm(matrPtr) {
429 // read them out into an array. TODO(kjlubick): If we change SkMatrix to be
430 // typedArrays, then we should return a typed array here too.
431 var rv = new Array(16);
432 for (var i = 0; i < 16; i++) {
433 rv[i] = CanvasKit.HEAPF32[matrPtr/4 + i]; // divide by 4 to "cast" to float.
434 }
Kevin Lubickc1d08982020-04-06 13:52:15 -0400435 return rv;
436}
437
Kevin Lubick6aa38692020-06-01 11:25:47 -0400438var _scratchColorPtr = nullptr;
Kevin Lubick93f1a382020-06-02 16:15:23 -0400439var _scratchColor; // the result from CanvasKit.Malloc
Kevin Lubick6aa38692020-06-01 11:25:47 -0400440
441function copyColorToWasm(color4f, ptr) {
Kevin Lubick69e46da2020-06-05 07:13:48 -0400442 return copy1dArray(color4f, "HEAPF32", ptr || _scratchColorPtr);
Kevin Lubick6aa38692020-06-01 11:25:47 -0400443}
444
Kevin Lubick93f1a382020-06-02 16:15:23 -0400445function copyColorComponentsToWasm(r, g, b, a) {
446 var colors = _scratchColor['toTypedArray']();
447 colors[0] = r;
448 colors[1] = g;
449 colors[2] = b;
450 colors[3] = a;
451 return _scratchColorPtr;
452}
453
Kevin Lubick6aa38692020-06-01 11:25:47 -0400454function copyColorToWasmNoScratch(color4f) {
455 // TODO(kjlubick): accept 4 floats or int color
Kevin Lubick69e46da2020-06-05 07:13:48 -0400456 return copy1dArray(color4f, "HEAPF32");
Kevin Lubick6aa38692020-06-01 11:25:47 -0400457}
458
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400459// copies the four floats at the given pointer in a js Float32Array
460function copyColorFromWasm(colorPtr) {
461 var rv = new Float32Array(4);
462 for (var i = 0; i < 4; i++) {
463 rv[i] = CanvasKit.HEAPF32[colorPtr/4 + i]; // divide by 4 to "cast" to float.
464 }
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400465 return rv;
Kevin Lubickcf118922020-05-28 14:43:38 -0400466}
Nathaniel Nifong1bedbeb2020-05-04 16:46:17 -0400467
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500468// Caching the Float32Arrays can save having to reallocate them
469// over and over again.
470var Float32ArrayCache = {};
471
472// Takes a 2D array of commands and puts them into the WASM heap
473// as a 1D array. This allows them to referenced from the C++ code.
474// Returns a 2 element array, with the first item being essentially a
475// pointer to the array and the second item being the length of
476// the new 1D array.
477//
478// Example usage:
479// let cmds = [
480// [CanvasKit.MOVE_VERB, 0, 10],
481// [CanvasKit.LINE_VERB, 30, 40],
482// [CanvasKit.QUAD_VERB, 20, 50, 45, 60],
483// ];
484function loadCmdsTypedArray(arr) {
485 var len = 0;
486 for (var r = 0; r < arr.length; r++) {
487 len += arr[r].length;
488 }
489
490 var ta;
491 if (Float32ArrayCache[len]) {
492 ta = Float32ArrayCache[len];
493 } else {
494 ta = new Float32Array(len);
495 Float32ArrayCache[len] = ta;
496 }
497 // Flatten into a 1d array
498 var i = 0;
499 for (var r = 0; r < arr.length; r++) {
500 for (var c = 0; c < arr[r].length; c++) {
501 var item = arr[r][c];
502 ta[i] = item;
503 i++;
504 }
505 }
506
Kevin Lubick69e46da2020-06-05 07:13:48 -0400507 var ptr = copy1dArray(ta, "HEAPF32");
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500508 return [ptr, len];
509}
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400510
Kevin Lubickcc13fd32019-04-05 13:00:01 -0400511function saveBytesToFile(bytes, fileName) {
512 if (!isNode) {
513 // https://stackoverflow.com/a/32094834
514 var blob = new Blob([bytes], {type: 'application/octet-stream'});
515 url = window.URL.createObjectURL(blob);
516 var a = document.createElement('a');
517 document.body.appendChild(a);
518 a.href = url;
519 a.download = fileName;
520 a.click();
521 // clean up after because FF might not download it synchronously
522 setTimeout(function() {
523 URL.revokeObjectURL(url);
524 a.remove();
525 }, 50);
526 } else {
527 var fs = require('fs');
528 // https://stackoverflow.com/a/42006750
529 // https://stackoverflow.com/a/47018122
530 fs.writeFile(fileName, new Buffer(bytes), function(err) {
531 if (err) throw err;
532 });
533 }
534}
Kevin Lubickee91c072019-03-29 10:39:52 -0400535/**
536 * Generic helper for dealing with an array of four floats.
537 */
538CanvasKit.FourFloatArrayHelper = function() {
539 this._floats = [];
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400540 this._ptr = null;
Kevin Lubickee91c072019-03-29 10:39:52 -0400541
542 Object.defineProperty(this, 'length', {
543 enumerable: true,
544 get: function() {
545 return this._floats.length / 4;
546 },
547 });
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400548}
549
550/**
Kevin Lubickee91c072019-03-29 10:39:52 -0400551 * push the four floats onto the end of the array - if build() has already
552 * been called, the call will return without modifying anything.
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400553 */
Kevin Lubickee91c072019-03-29 10:39:52 -0400554CanvasKit.FourFloatArrayHelper.prototype.push = function(f1, f2, f3, f4) {
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400555 if (this._ptr) {
556 SkDebug('Cannot push more points - already built');
557 return;
558 }
Kevin Lubickee91c072019-03-29 10:39:52 -0400559 this._floats.push(f1, f2, f3, f4);
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400560}
561
Kevin Lubickee91c072019-03-29 10:39:52 -0400562/**
563 * Set the four floats at a given index - if build() has already
564 * been called, the WASM memory will be written to directly.
565 */
566CanvasKit.FourFloatArrayHelper.prototype.set = function(idx, f1, f2, f3, f4) {
567 if (idx < 0 || idx >= this._floats.length/4) {
568 SkDebug('Cannot set index ' + idx + ', it is out of range', this._floats.length/4);
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 floatPtr = (this._ptr / BYTES_PER_ELEMENT) + idx;
576 CanvasKit.HEAPF32[floatPtr] = f1;
577 CanvasKit.HEAPF32[floatPtr + 1] = f2;
578 CanvasKit.HEAPF32[floatPtr + 2] = f3;
579 CanvasKit.HEAPF32[floatPtr + 3] = f4;
580 return;
581 }
582 this._floats[idx] = f1;
583 this._floats[idx + 1] = f2;
584 this._floats[idx + 2] = f3;
585 this._floats[idx + 3] = f4;
586}
587
588/**
589 * Copies the float data to the WASM memory and returns a pointer
590 * to that allocated memory. Once build has been called, this
591 * float array cannot be made bigger.
592 */
593CanvasKit.FourFloatArrayHelper.prototype.build = function() {
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400594 if (this._ptr) {
595 return this._ptr;
596 }
Kevin Lubick69e46da2020-06-05 07:13:48 -0400597 this._ptr = copy1dArray(this._floats, "HEAPF32");
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400598 return this._ptr;
599}
600
Kevin Lubickee91c072019-03-29 10:39:52 -0400601/**
602 * Frees the wasm memory associated with this array. Of note,
603 * the points are not removed, so push/set/build can all
604 * be called to make a newly allocated (possibly bigger)
605 * float array.
606 */
607CanvasKit.FourFloatArrayHelper.prototype.delete = function() {
Kevin Lubickd3cfbca2019-03-15 15:36:29 -0400608 if (this._ptr) {
609 CanvasKit._free(this._ptr);
610 this._ptr = null;
611 }
612}
Kevin Lubickee91c072019-03-29 10:39:52 -0400613
614/**
615 * Generic helper for dealing with an array of unsigned ints.
616 */
617CanvasKit.OneUIntArrayHelper = function() {
618 this._uints = [];
619 this._ptr = null;
620
621 Object.defineProperty(this, 'length', {
622 enumerable: true,
623 get: function() {
624 return this._uints.length;
625 },
626 });
627}
628
629/**
630 * push the unsigned int onto the end of the array - if build() has already
631 * been called, the call will return without modifying anything.
632 */
633CanvasKit.OneUIntArrayHelper.prototype.push = function(u) {
634 if (this._ptr) {
635 SkDebug('Cannot push more points - already built');
636 return;
637 }
638 this._uints.push(u);
639}
640
641/**
642 * Set the uint at a given index - if build() has already
643 * been called, the WASM memory will be written to directly.
644 */
645CanvasKit.OneUIntArrayHelper.prototype.set = function(idx, u) {
646 if (idx < 0 || idx >= this._uints.length) {
647 SkDebug('Cannot set index ' + idx + ', it is out of range', this._uints.length);
648 return;
649 }
650 idx *= 4;
651 var BYTES_PER_ELEMENT = 4;
652 if (this._ptr) {
653 // convert this._ptr from uint8_t* to SkScalar* by dividing by 4
654 var uintPtr = (this._ptr / BYTES_PER_ELEMENT) + idx;
655 CanvasKit.HEAPU32[uintPtr] = u;
656 return;
657 }
658 this._uints[idx] = u;
659}
660
661/**
662 * Copies the uint data to the WASM memory and returns a pointer
663 * to that allocated memory. Once build has been called, this
664 * unit array cannot be made bigger.
665 */
666CanvasKit.OneUIntArrayHelper.prototype.build = function() {
667 if (this._ptr) {
668 return this._ptr;
669 }
Kevin Lubick69e46da2020-06-05 07:13:48 -0400670 this._ptr = copy1dArray(this._uints, "HEAPU32");
Kevin Lubickee91c072019-03-29 10:39:52 -0400671 return this._ptr;
672}
673
674/**
675 * Frees the wasm memory associated with this array. Of note,
676 * the points are not removed, so push/set/build can all
677 * be called to make a newly allocated (possibly bigger)
678 * uint array.
679 */
680CanvasKit.OneUIntArrayHelper.prototype.delete = function() {
681 if (this._ptr) {
682 CanvasKit._free(this._ptr);
683 this._ptr = null;
684 }
685}
686
687/**
688 * Helper for building an array of SkRects (which are just structs
689 * of 4 floats).
690 *
691 * It can be more performant to use this helper, as
692 * the C++-side array is only allocated once (on the first call)
693 * to build. Subsequent set() operations operate directly on
694 * the C++-side array, avoiding having to re-allocate (and free)
695 * the array every time.
696 *
697 * Input points are taken as left, top, right, bottom
698 */
699CanvasKit.SkRectBuilder = CanvasKit.FourFloatArrayHelper;
700/**
701 * Helper for building an array of RSXForms (which are just structs
702 * of 4 floats).
703 *
704 * It can be more performant to use this helper, as
705 * the C++-side array is only allocated once (on the first call)
706 * to build. Subsequent set() operations operate directly on
707 * the C++-side array, avoiding having to re-allocate (and free)
708 * the array every time.
709 *
710 * An RSXForm is a compressed form of a rotation+scale matrix.
711 *
712 * [ scos -ssin tx ]
713 * [ ssin scos ty ]
714 * [ 0 0 1 ]
715 *
716 * Input points are taken as scos, ssin, tx, ty
717 */
718CanvasKit.RSXFormBuilder = CanvasKit.FourFloatArrayHelper;
719
720/**
721 * Helper for building an array of SkColor
722 *
723 * It can be more performant to use this helper, as
724 * the C++-side array is only allocated once (on the first call)
725 * to build. Subsequent set() operations operate directly on
726 * the C++-side array, avoiding having to re-allocate (and free)
727 * the array every time.
728 */
729CanvasKit.SkColorBuilder = CanvasKit.OneUIntArrayHelper;
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400730
731/**
732 * Malloc returns a TypedArray backed by the C++ memory of the
733 * given length. It should only be used by advanced users who
734 * can manage memory and initialize values properly. When used
735 * correctly, it can save copying of data between JS and C++.
736 * When used incorrectly, it can lead to memory leaks.
Kevin Lubickcf118922020-05-28 14:43:38 -0400737 * Any memory allocated by CanvasKit.Malloc needs to be released with CanvasKit.Free.
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400738 *
Kevin Lubick462a8602020-06-01 15:43:03 -0400739 * const mObj = CanvasKit.Malloc(Float32Array, 20);
Kevin Lubick93f1a382020-06-02 16:15:23 -0400740 * Get a TypedArray view around the malloc'd memory (this does not copy anything).
Kevin Lubick462a8602020-06-01 15:43:03 -0400741 * const ta = mObj.toTypedArray();
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400742 * // store data into ta
Kevin Lubick93f1a382020-06-02 16:15:23 -0400743 * const cf = CanvasKit.SkColorFilter.MakeMatrix(ta); // mObj could also be used.
Kevin Lubick462a8602020-06-01 15:43:03 -0400744 *
745 * // eventually...
746 * CanvasKit.Free(mObj);
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400747 *
748 * @param {TypedArray} typedArray - constructor for the typedArray.
Kevin Lubick6aa38692020-06-01 11:25:47 -0400749 * @param {number} len - number of *elements* to store.
Kevin Lubicke25df6c2019-10-22 09:04:32 -0400750 */
751CanvasKit.Malloc = function(typedArray, len) {
752 var byteLen = len * typedArray.BYTES_PER_ELEMENT;
753 var ptr = CanvasKit._malloc(byteLen);
Kevin Lubick462a8602020-06-01 15:43:03 -0400754 return {
755 '_ck': true,
756 'length': len,
757 'byteOffset': ptr,
758 typedArray: null,
759 'toTypedArray': function() {
760 // Check if the previously allocated array is still usable.
761 // If it's falsey, then we haven't created an array yet.
762 // If it's empty, then WASM resized memory and emptied the array.
763 if (this.typedArray && this.typedArray.length) {
764 return this.typedArray;
765 }
766 this.typedArray = new typedArray(CanvasKit.HEAPU8.buffer, ptr, len);
767 // add a marker that this was allocated in C++ land
768 this.typedArray['_ck'] = true;
769 return this.typedArray;
770 },
771 };
Kevin Lubick26133322020-06-11 13:48:16 -0400772};
Kevin Lubickcf118922020-05-28 14:43:38 -0400773
774/**
775 * Free frees the memory returned by Malloc.
776 * Any memory allocated by CanvasKit.Malloc needs to be released with CanvasKit.Free.
777 */
Kevin Lubick462a8602020-06-01 15:43:03 -0400778CanvasKit.Free = function(mallocObj) {
779 CanvasKit._free(mallocObj['byteOffset']);
780 mallocObj['byteOffset'] = nullptr;
781 // Set these to null to make sure the TypedArrays can be garbage collected.
782 mallocObj['toTypedArray'] = null;
783 mallocObj.typedArray = null;
Kevin Lubick26133322020-06-11 13:48:16 -0400784};
Kevin Lubickcf118922020-05-28 14:43:38 -0400785
786// This helper will free the given pointer unless the provided array is one
787// that was returned by CanvasKit.Malloc.
788function freeArraysThatAreNotMallocedByUsers(ptr, arr) {
Kevin Lubicke7b329e2020-06-05 15:58:01 -0400789 if (!arr['_ck']) {
Kevin Lubickcf118922020-05-28 14:43:38 -0400790 CanvasKit._free(ptr);
791 }
Kevin Lubick6aa38692020-06-01 11:25:47 -0400792}