@windowkit/appkit 0.34.0 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1927 @@
1
+ // ctxDrawFilterGraph: an SVG filter graph (<filter> and its fe* primitives)
2
+ // run by Metal compute kernels and drawn into a surface, the macOS half of
3
+ // react-x11-components' docs/prd-svg-filters-gpu.md.
4
+ //
5
+ // The graph is react-x11-components' CompiledFilter as data (FilterGraph):
6
+ // the region's size, the user-to-region matrix, and the primitives in order,
7
+ // each with its inputs, its subregion in region pixels, the colour space it
8
+ // works in and its numbers. src/html/css/svg-filter.ts's runFilter is the
9
+ // reference, primitive by primitive: where its numbers and these differ, it
10
+ // is this file that is wrong.
11
+ //
12
+ // A run, on the calling thread:
13
+ // 1. the graph is read and checked whole: a primitive or a value this does
14
+ // not take answers false before anything is made, so the caller runs the
15
+ // filter itself and nothing is half drawn;
16
+ // 2. the source surface is wrapped in a texture without a copy: its
17
+ // IOSurface, or a buffer laid over its bitmap from the page the bitmap
18
+ // begins in (copied once only where Metal will not have that);
19
+ // 3. one compute pass per primitive (two to six for a blur) into RGBA16F
20
+ // textures (RGBA32F where the graph asks for `precision: 'float'`)
21
+ // from a pool, each in its primitive's colour space — a
22
+ // conversion is done where an input is read, never as a pass of its
23
+ // own — and a result's texture goes back to the run's free list after
24
+ // its last read, as runFilter lets a plane go;
25
+ // 4. the last result, in sRGB, premultiplied 8-bit into a shared buffer;
26
+ // the command buffer is waited for, and the buffer drawn as a CGImage
27
+ // with its corner at (dx, dy) under the destination's state, as
28
+ // ctxDrawSurface draws.
29
+ //
30
+ // The shaders are compiled from source at the first call (filterGraph-
31
+ // Primitives or ctxDrawFilterGraph), with fast math off: feTurbulence's
32
+ // lattice arithmetic is the reference code's, and a fast reciprocal moved
33
+ // its noise by more than the two levels a GPU path is held to.
34
+
35
+ #import <Foundation/Foundation.h>
36
+ #import <Metal/Metal.h>
37
+ #import <CoreGraphics/CoreGraphics.h>
38
+ #import <IOSurface/IOSurface.h>
39
+ #include <mach/mach.h>
40
+ #include <napi.h>
41
+
42
+ #include <algorithm>
43
+ #include <cmath>
44
+ #include <cstring>
45
+ #include <mutex>
46
+ #include <string>
47
+ #include <vector>
48
+
49
+ // backend.mm
50
+ struct CALSurfaceView {
51
+ CGContextRef ctx;
52
+ IOSurfaceRef iosurface;
53
+ uint8_t* data;
54
+ size_t width, height, bytesPerRow;
55
+ };
56
+ bool CALSurfaceViewOf(Napi::Value v, CALSurfaceView* out);
57
+
58
+ namespace {
59
+
60
+ // ---------------------------------------------------------------------------
61
+ // The kernels. Every argument struct is 4-byte scalars and arrays of them, so
62
+ // its layout is the same on both sides; texture(0) is what a pass writes,
63
+ // texture(1) and texture(2) what it reads.
64
+
65
+ const char* kShaders = R"METAL(
66
+ #include <metal_stdlib>
67
+ using namespace metal;
68
+
69
+ struct Sub { int x0, y0, x1, y1; };
70
+ // how an input is read: conv 0 as it is, 1 sRGB to linear, 2 linear to
71
+ // sRGB; alpha 1 for SourceAlpha, its colour dropped
72
+ struct In { int conv; int alpha; };
73
+
74
+ static inline bool inside(int2 p, Sub s) {
75
+ return p.x >= s.x0 && p.x < s.x1 && p.y >= s.y0 && p.y < s.y1;
76
+ }
77
+ static inline float lin1(float c) {
78
+ return c <= 0.04045f ? c / 12.92f : pow((c + 0.055f) / 1.055f, 2.4f);
79
+ }
80
+ static inline float srgb1(float c) {
81
+ return c <= 0.0031308f ? c * 12.92f : 1.055f * pow(c, 1.0f / 2.4f) - 0.055f;
82
+ }
83
+ static inline float4 convert(float4 v, int mode) {
84
+ if (mode == 0) return v;
85
+ float a = v.a;
86
+ if (!(a > 0.0f)) return float4(0.0f);
87
+ float3 c = v.rgb / a;
88
+ if (mode == 1) c = float3(lin1(c.r), lin1(c.g), lin1(c.b));
89
+ else c = float3(srgb1(c.r), srgb1(c.g), srgb1(c.b));
90
+ return float4(c * a, a);
91
+ }
92
+ static inline float4 fetch(texture2d<float, access::read> t, int2 p, In i) {
93
+ float4 v = t.read(uint2(p));
94
+ if (i.alpha != 0) v = float4(0.0f, 0.0f, 0.0f, v.a);
95
+ return convert(v, i.conv);
96
+ }
97
+ static inline float unit(float v) { return clamp(v, 0.0f, 1.0f); }
98
+ // x to the power y, 0 to the 0 being 1 as JavaScript's Math.pow has it
99
+ static inline float power(float x, float y) {
100
+ return y == 0.0f ? 1.0f : pow(x, y);
101
+ }
102
+ #define BOUNDS \
103
+ if (gid.x >= out.get_width() || gid.y >= out.get_height()) return; \
104
+ int2 p = int2(gid);
105
+ #define W int(out.get_width())
106
+ #define H int(out.get_height())
107
+ #define inRegion(q) ((q).x >= 0 && (q).x < W && (q).y >= 0 && (q).y < H)
108
+
109
+ struct FloodArgs { Sub sub; float c[4]; };
110
+ kernel void k_flood(texture2d<float, access::write> out [[texture(0)]],
111
+ constant FloodArgs& A [[buffer(0)]],
112
+ uint2 gid [[thread_position_in_grid]]) {
113
+ BOUNDS
114
+ out.write(inside(p, A.sub) ? float4(A.c[0], A.c[1], A.c[2], A.c[3]) : float4(0.0f), gid);
115
+ }
116
+
117
+ struct CopyArgs { Sub sub; In i0; };
118
+ kernel void k_copy(texture2d<float, access::write> out [[texture(0)]],
119
+ texture2d<float, access::read> in0 [[texture(1)]],
120
+ constant CopyArgs& A [[buffer(0)]],
121
+ uint2 gid [[thread_position_in_grid]]) {
122
+ BOUNDS
123
+ out.write(inside(p, A.sub) ? fetch(in0, p, A.i0) : float4(0.0f), gid);
124
+ }
125
+
126
+ struct OffsetArgs { Sub sub; In i0; int dx, dy; };
127
+ kernel void k_offset(texture2d<float, access::write> out [[texture(0)]],
128
+ texture2d<float, access::read> in0 [[texture(1)]],
129
+ constant OffsetArgs& A [[buffer(0)]],
130
+ uint2 gid [[thread_position_in_grid]]) {
131
+ BOUNDS
132
+ int2 q = p - int2(A.dx, A.dy);
133
+ out.write(inside(p, A.sub) && inRegion(q) ? fetch(in0, q, A.i0) : float4(0.0f), gid);
134
+ }
135
+
136
+ // one pass of a blur along a row (axis 0) or a column (1) of the subregion,
137
+ // what is past its ends nothing: a box of [lo, hi] (mode 0) or a Gaussian of
138
+ // `reach` each way with `w`'s weights (mode 1). Outside the subregion the
139
+ // input as it is where `keep`, else nothing.
140
+ struct BlurArgs { Sub sub; In i0; int axis, mode, lo, hi, reach, keep; };
141
+ kernel void k_blur(texture2d<float, access::write> out [[texture(0)]],
142
+ texture2d<float, access::read> in0 [[texture(1)]],
143
+ constant BlurArgs& A [[buffer(0)]],
144
+ constant float* w [[buffer(1)]],
145
+ uint2 gid [[thread_position_in_grid]]) {
146
+ BOUNDS
147
+ if (!inside(p, A.sub)) {
148
+ out.write(A.keep != 0 ? fetch(in0, p, A.i0) : float4(0.0f), gid);
149
+ return;
150
+ }
151
+ bool across = A.axis == 0;
152
+ int i = across ? p.x - A.sub.x0 : p.y - A.sub.y0;
153
+ int len = across ? A.sub.x1 - A.sub.x0 : A.sub.y1 - A.sub.y0;
154
+ float4 sum = float4(0.0f);
155
+ if (A.mode == 0) {
156
+ int lo = max(0, i + A.lo);
157
+ int hi = min(len - 1, i + A.hi);
158
+ for (int k = lo; k <= hi; k++) {
159
+ int2 q = across ? int2(A.sub.x0 + k, p.y) : int2(p.x, A.sub.y0 + k);
160
+ sum += fetch(in0, q, A.i0);
161
+ }
162
+ sum /= float(A.hi - A.lo + 1);
163
+ } else {
164
+ int lo = max(0, i - A.reach);
165
+ int hi = min(len - 1, i + A.reach);
166
+ for (int k = lo; k <= hi; k++) {
167
+ int2 q = across ? int2(A.sub.x0 + k, p.y) : int2(p.x, A.sub.y0 + k);
168
+ sum += fetch(in0, q, A.i0) * w[k - i + A.reach];
169
+ }
170
+ }
171
+ out.write(sum, gid);
172
+ }
173
+
174
+ // feDropShadow: the input's alpha in the shadow's colour, over all of the
175
+ // region, and then that blurred (k_blur, keep) cast under the input
176
+ struct SeedArgs { In i0; float c[4]; };
177
+ kernel void k_shadow_seed(texture2d<float, access::write> out [[texture(0)]],
178
+ texture2d<float, access::read> in0 [[texture(1)]],
179
+ constant SeedArgs& A [[buffer(0)]],
180
+ uint2 gid [[thread_position_in_grid]]) {
181
+ BOUNDS
182
+ float a = fetch(in0, p, A.i0).a * A.c[3];
183
+ out.write(float4(A.c[0] * a, A.c[1] * a, A.c[2] * a, a), gid);
184
+ }
185
+ struct ShadowArgs { Sub sub; In i0; int dx, dy; };
186
+ kernel void k_shadow_cast(texture2d<float, access::write> out [[texture(0)]],
187
+ texture2d<float, access::read> in0 [[texture(1)]],
188
+ texture2d<float, access::read> shadow [[texture(2)]],
189
+ constant ShadowArgs& A [[buffer(0)]],
190
+ uint2 gid [[thread_position_in_grid]]) {
191
+ BOUNDS
192
+ if (!inside(p, A.sub)) { out.write(float4(0.0f), gid); return; }
193
+ int2 q = p - int2(A.dx, A.dy);
194
+ float4 m = inRegion(q) ? shadow.read(uint2(q)) : float4(0.0f);
195
+ float4 s = fetch(in0, p, A.i0);
196
+ out.write(s + m * (1.0f - s.a), gid);
197
+ }
198
+
199
+ struct MatrixArgs { Sub sub; In i0; float m[20]; };
200
+ kernel void k_colormatrix(texture2d<float, access::write> out [[texture(0)]],
201
+ texture2d<float, access::read> in0 [[texture(1)]],
202
+ constant MatrixArgs& A [[buffer(0)]],
203
+ uint2 gid [[thread_position_in_grid]]) {
204
+ BOUNDS
205
+ if (!inside(p, A.sub)) { out.write(float4(0.0f), gid); return; }
206
+ float4 s = fetch(in0, p, A.i0);
207
+ float a = s.a;
208
+ float r = a > 0.0f ? s.r / a : 0.0f;
209
+ float g = a > 0.0f ? s.g / a : 0.0f;
210
+ float b = a > 0.0f ? s.b / a : 0.0f;
211
+ constant float* m = A.m;
212
+ float r1 = unit(m[0] * r + m[1] * g + m[2] * b + m[3] * a + m[4]);
213
+ float g1 = unit(m[5] * r + m[6] * g + m[7] * b + m[8] * a + m[9]);
214
+ float b1 = unit(m[10] * r + m[11] * g + m[12] * b + m[13] * a + m[14]);
215
+ float a1 = unit(m[15] * r + m[16] * g + m[17] * b + m[18] * a + m[19]);
216
+ out.write(float4(r1 * a1, g1 * a1, b1 * a1, a1), gid);
217
+ }
218
+
219
+ // a channel's function: type 0 none, 1 table, 2 discrete, 3 linear, 4 gamma;
220
+ // a table's values at `off` in `t`, `n` of them
221
+ struct TransferArgs { Sub sub; In i0; int type[4]; int off[4]; int n[4];
222
+ float p0[4]; float p1[4]; float p2[4]; };
223
+ static inline float transfer(constant TransferArgs& A, constant float* t, int ch, float c) {
224
+ int n = A.n[ch];
225
+ constant float* v = t + A.off[ch];
226
+ switch (A.type[ch]) {
227
+ case 1: {
228
+ int m = n - 1;
229
+ if (m == 0) return v[0];
230
+ int k = min(m - 1, int(floor(c * float(m))));
231
+ return v[k] + (c * float(m) - float(k)) * (v[k + 1] - v[k]);
232
+ }
233
+ case 2: return v[min(n - 1, int(floor(c * float(n))))];
234
+ case 3: return A.p0[ch] * c + A.p1[ch];
235
+ case 4: return A.p0[ch] * power(c, A.p1[ch]) + A.p2[ch];
236
+ }
237
+ return c;
238
+ }
239
+ kernel void k_transfer(texture2d<float, access::write> out [[texture(0)]],
240
+ texture2d<float, access::read> in0 [[texture(1)]],
241
+ constant TransferArgs& A [[buffer(0)]],
242
+ constant float* t [[buffer(1)]],
243
+ uint2 gid [[thread_position_in_grid]]) {
244
+ BOUNDS
245
+ if (!inside(p, A.sub)) { out.write(float4(0.0f), gid); return; }
246
+ float4 s = fetch(in0, p, A.i0);
247
+ float a = s.a;
248
+ float r = a > 0.0f ? s.r / a : 0.0f;
249
+ float g = a > 0.0f ? s.g / a : 0.0f;
250
+ float b = a > 0.0f ? s.b / a : 0.0f;
251
+ float a1 = a;
252
+ if (A.type[0] != 0) r = unit(transfer(A, t, 0, r));
253
+ if (A.type[1] != 0) g = unit(transfer(A, t, 1, g));
254
+ if (A.type[2] != 0) b = unit(transfer(A, t, 2, b));
255
+ if (A.type[3] != 0) a1 = unit(transfer(A, t, 3, a));
256
+ out.write(float4(r * a1, g * a1, b * a1, a1), gid);
257
+ }
258
+
259
+ // op 0 over, 1 in, 2 out, 3 atop, 4 xor, 5 lighter, 6 arithmetic
260
+ struct CompositeArgs { Sub sub; In i0; In i1; int op; float k[4]; };
261
+ kernel void k_composite(texture2d<float, access::write> out [[texture(0)]],
262
+ texture2d<float, access::read> in0 [[texture(1)]],
263
+ texture2d<float, access::read> in1 [[texture(2)]],
264
+ constant CompositeArgs& A [[buffer(0)]],
265
+ uint2 gid [[thread_position_in_grid]]) {
266
+ BOUNDS
267
+ if (!inside(p, A.sub)) { out.write(float4(0.0f), gid); return; }
268
+ float4 a = fetch(in0, p, A.i0);
269
+ float4 b = fetch(in1, p, A.i1);
270
+ float4 o;
271
+ if (A.op == 6) {
272
+ o = clamp(A.k[0] * a * b + A.k[1] * a + A.k[2] * b + A.k[3], 0.0f, 1.0f);
273
+ o.rgb = min(o.rgb, float3(o.a));
274
+ } else {
275
+ float fa0 = 1, faB = 0, fb0 = 1, fbA = -1;
276
+ switch (A.op) {
277
+ case 1: fa0 = 0; faB = 1; fb0 = 0; fbA = 0; break;
278
+ case 2: fa0 = 1; faB = -1; fb0 = 0; fbA = 0; break;
279
+ case 3: fa0 = 0; faB = 1; fb0 = 1; fbA = -1; break;
280
+ case 4: fa0 = 1; faB = -1; fb0 = 1; fbA = -1; break;
281
+ case 5: fa0 = 1; faB = 0; fb0 = 1; fbA = 0; break;
282
+ }
283
+ float fa = fa0 + faB * b.a;
284
+ float fb = fb0 + fbA * a.a;
285
+ o = min(float4(1.0f), a * fa + b * fb);
286
+ }
287
+ out.write(o, gid);
288
+ }
289
+
290
+ static inline float lum(float3 c) { return 0.3f * c.r + 0.59f * c.g + 0.11f * c.b; }
291
+ static inline float3 clipColour(float3 c) {
292
+ float l = lum(c);
293
+ float lo = min(c.r, min(c.g, c.b));
294
+ float hi = max(c.r, max(c.g, c.b));
295
+ if (lo < 0.0f) c = l + (c - l) * l / (l - lo);
296
+ if (hi > 1.0f) c = l + (c - l) * (1.0f - l) / (hi - l);
297
+ return c;
298
+ }
299
+ static inline float3 setLum(float3 c, float l) { return clipColour(c + (l - lum(c))); }
300
+ static inline float sat(float3 c) { return max(c.r, max(c.g, c.b)) - min(c.r, min(c.g, c.b)); }
301
+ static inline float3 setSat(float3 c, float s) {
302
+ // the channels' order, lowest first, ties kept in channel order as a
303
+ // stable sort keeps them
304
+ int lo = 0, mid = 1, hi = 2;
305
+ float v[3] = {c.r, c.g, c.b};
306
+ if (v[mid] < v[lo]) { int t = lo; lo = mid; mid = t; }
307
+ if (v[hi] < v[mid]) { int t = mid; mid = hi; hi = t; }
308
+ if (v[mid] < v[lo]) { int t = lo; lo = mid; mid = t; }
309
+ float o[3] = {0.0f, 0.0f, 0.0f};
310
+ if (v[hi] > v[lo]) {
311
+ o[mid] = (v[mid] - v[lo]) * s / (v[hi] - v[lo]);
312
+ o[hi] = s;
313
+ }
314
+ o[lo] = 0.0f;
315
+ return float3(o[0], o[1], o[2]);
316
+ }
317
+ static inline float hardLight(float cs, float cb) {
318
+ return cs <= 0.5f ? cb * 2.0f * cs : cb + (2.0f * cs - 1.0f) - cb * (2.0f * cs - 1.0f);
319
+ }
320
+ static inline float blend1(int mode, float cs, float cb) {
321
+ switch (mode) {
322
+ case 1: return cs * cb;
323
+ case 2: return cs + cb - cs * cb;
324
+ case 3: return hardLight(cb, cs);
325
+ case 4: return min(cs, cb);
326
+ case 5: return max(cs, cb);
327
+ case 6: return cb == 0.0f ? 0.0f : cs == 1.0f ? 1.0f : min(1.0f, cb / (1.0f - cs));
328
+ case 7: return cb == 1.0f ? 1.0f : cs == 0.0f ? 0.0f : 1.0f - min(1.0f, (1.0f - cb) / cs);
329
+ case 8: return hardLight(cs, cb);
330
+ case 9: {
331
+ if (cs <= 0.5f) return cb - (1.0f - 2.0f * cs) * cb * (1.0f - cb);
332
+ float d = cb <= 0.25f ? ((16.0f * cb - 12.0f) * cb + 4.0f) * cb : sqrt(cb);
333
+ return cb + (2.0f * cs - 1.0f) * (d - cb);
334
+ }
335
+ case 10: return abs(cs - cb);
336
+ case 11: return cs + cb - 2.0f * cs * cb;
337
+ }
338
+ return cs;
339
+ }
340
+ // mode 0 normal, 1 multiply … 11 exclusion as blend1, 12 hue, 13 saturation,
341
+ // 14 color, 15 luminosity
342
+ struct BlendArgs { Sub sub; In i0; In i1; int mode; };
343
+ kernel void k_blend(texture2d<float, access::write> out [[texture(0)]],
344
+ texture2d<float, access::read> in0 [[texture(1)]],
345
+ texture2d<float, access::read> in1 [[texture(2)]],
346
+ constant BlendArgs& A [[buffer(0)]],
347
+ uint2 gid [[thread_position_in_grid]]) {
348
+ BOUNDS
349
+ if (!inside(p, A.sub)) { out.write(float4(0.0f), gid); return; }
350
+ float4 a = fetch(in0, p, A.i0);
351
+ float4 b = fetch(in1, p, A.i1);
352
+ float as = a.a, ab = b.a;
353
+ float ao = as + ab - as * ab;
354
+ float3 cs = as > 0.0f ? a.rgb / as : float3(0.0f);
355
+ float3 cb = ab > 0.0f ? b.rgb / ab : float3(0.0f);
356
+ float3 mixed;
357
+ switch (A.mode) {
358
+ case 12: mixed = setLum(setSat(cs, sat(cb)), lum(cb)); break;
359
+ case 13: mixed = setLum(setSat(cb, sat(cs)), lum(cb)); break;
360
+ case 14: mixed = setLum(cs, lum(cb)); break;
361
+ case 15: mixed = setLum(cb, lum(cs)); break;
362
+ default:
363
+ mixed = float3(blend1(A.mode, cs.r, cb.r), blend1(A.mode, cs.g, cb.g),
364
+ blend1(A.mode, cs.b, cb.b));
365
+ }
366
+ float3 blended = (1.0f - ab) * cs + ab * mixed;
367
+ out.write(float4(as * blended + ab * cb * (1.0f - as), ao), gid);
368
+ }
369
+
370
+ // feMerge, a layer at a time: the layer over what is merged so far
371
+ struct MergeArgs { Sub sub; In i0; int first; };
372
+ kernel void k_merge(texture2d<float, access::write> out [[texture(0)]],
373
+ texture2d<float, access::read> layer [[texture(1)]],
374
+ texture2d<float, access::read> acc [[texture(2)]],
375
+ constant MergeArgs& A [[buffer(0)]],
376
+ uint2 gid [[thread_position_in_grid]]) {
377
+ BOUNDS
378
+ if (!inside(p, A.sub)) { out.write(float4(0.0f), gid); return; }
379
+ float4 d = fetch(layer, p, A.i0);
380
+ float4 so = A.first != 0 ? float4(0.0f) : acc.read(gid);
381
+ out.write(d + so * (1.0f - d.a), gid);
382
+ }
383
+
384
+ struct TileArgs { Sub sub; In i0; int fx, fy, fw, fh; };
385
+ kernel void k_tile(texture2d<float, access::write> out [[texture(0)]],
386
+ texture2d<float, access::read> in0 [[texture(1)]],
387
+ constant TileArgs& A [[buffer(0)]],
388
+ uint2 gid [[thread_position_in_grid]]) {
389
+ BOUNDS
390
+ if (!inside(p, A.sub) || A.fw <= 0 || A.fh <= 0) { out.write(float4(0.0f), gid); return; }
391
+ int2 q = int2(A.fx + (((p.x - A.fx) % A.fw) + A.fw) % A.fw,
392
+ A.fy + (((p.y - A.fy) % A.fh) + A.fh) % A.fh);
393
+ out.write(inRegion(q) ? fetch(in0, q, A.i0) : float4(0.0f), gid);
394
+ }
395
+
396
+ // one pass of feMorphology along a row (axis 0) or a column, what is past
397
+ // the region nothing
398
+ struct MorphArgs { Sub sub; In i0; int axis, r, dilate; };
399
+ kernel void k_morph(texture2d<float, access::write> out [[texture(0)]],
400
+ texture2d<float, access::read> in0 [[texture(1)]],
401
+ constant MorphArgs& A [[buffer(0)]],
402
+ uint2 gid [[thread_position_in_grid]]) {
403
+ BOUNDS
404
+ if (!inside(p, A.sub)) { out.write(float4(0.0f), gid); return; }
405
+ bool dilate = A.dilate != 0;
406
+ float4 best = float4(dilate ? 0.0f : 1.0f);
407
+ for (int k = -A.r; k <= A.r; k++) {
408
+ int2 q = A.axis == 0 ? int2(p.x + k, p.y) : int2(p.x, p.y + k);
409
+ float4 v = inRegion(q) ? fetch(in0, q, A.i0) : float4(0.0f);
410
+ best = dilate ? max(best, v) : min(best, v);
411
+ }
412
+ out.write(best, gid);
413
+ }
414
+
415
+ // feDisplacementMap: `in` (texture 1) read in its own space, the map
416
+ // (texture 2) in the primitive's
417
+ struct DisplaceArgs { Sub sub; In i0; In i1; float sx, sy; int xc, yc; };
418
+ kernel void k_displace(texture2d<float, access::write> out [[texture(0)]],
419
+ texture2d<float, access::read> in0 [[texture(1)]],
420
+ texture2d<float, access::read> map [[texture(2)]],
421
+ constant DisplaceArgs& A [[buffer(0)]],
422
+ uint2 gid [[thread_position_in_grid]]) {
423
+ BOUNDS
424
+ if (!inside(p, A.sub)) { out.write(float4(0.0f), gid); return; }
425
+ float4 m = fetch(map, p, A.i1);
426
+ float a = m.a;
427
+ float4 straight = a > 0.0f ? float4(m.rgb / a, a) : float4(0.0f, 0.0f, 0.0f, a);
428
+ float dx = A.sx * (straight[A.xc] - 0.5f);
429
+ float dy = A.sy * (straight[A.yc] - 0.5f);
430
+ int2 q = int2(int(floor(float(p.x) + dx + 0.5f)), int(floor(float(p.y) + dy + 0.5f)));
431
+ out.write(inRegion(q) ? fetch(in0, q, A.i0) : float4(0.0f), gid);
432
+ }
433
+
434
+ // edge 0 duplicate, 1 wrap, 2 none: the subregion's edge (9.12)
435
+ struct ConvolveArgs { Sub sub; In i0; int ox, oy, tx, ty, edge, preserve; float divisor, bias; };
436
+ static inline float4 convolveAt(texture2d<float, access::read> t, constant ConvolveArgs& A,
437
+ int2 q, thread bool& none) {
438
+ Sub s = A.sub;
439
+ none = false;
440
+ if (!inside(q, s)) {
441
+ if (A.edge == 2) { none = true; return float4(0.0f); }
442
+ if (A.edge == 1) {
443
+ int w = s.x1 - s.x0, h = s.y1 - s.y0;
444
+ q = int2(s.x0 + (((q.x - s.x0) % w) + w) % w, s.y0 + (((q.y - s.y0) % h) + h) % h);
445
+ } else {
446
+ q = clamp(q, int2(s.x0, s.y0), int2(s.x1 - 1, s.y1 - 1));
447
+ }
448
+ }
449
+ return fetch(t, q, A.i0);
450
+ }
451
+ kernel void k_convolve(texture2d<float, access::write> out [[texture(0)]],
452
+ texture2d<float, access::read> in0 [[texture(1)]],
453
+ constant ConvolveArgs& A [[buffer(0)]],
454
+ constant float* kern [[buffer(1)]],
455
+ uint2 gid [[thread_position_in_grid]]) {
456
+ BOUNDS
457
+ if (!inside(p, A.sub)) { out.write(float4(0.0f), gid); return; }
458
+ float alpha = fetch(in0, p, A.i0).a;
459
+ float4 sums = float4(0.0f);
460
+ for (int j = 0; j < A.oy; j++) {
461
+ for (int k = 0; k < A.ox; k++) {
462
+ float weight = kern[(A.oy - 1 - j) * A.ox + (A.ox - 1 - k)];
463
+ bool none;
464
+ float4 v = convolveAt(in0, A, int2(p.x - A.tx + k, p.y - A.ty + j), none);
465
+ if (A.preserve != 0) {
466
+ float a = v.a;
467
+ sums.rgb += (a > 0.0f ? v.rgb / a : float3(0.0f)) * weight;
468
+ } else {
469
+ sums += v * weight;
470
+ }
471
+ }
472
+ }
473
+ float4 o;
474
+ if (A.preserve != 0) {
475
+ o = float4(clamp(sums.rgb / A.divisor + A.bias, 0.0f, 1.0f) * alpha, alpha);
476
+ } else {
477
+ float a = unit(sums.a / A.divisor + A.bias);
478
+ o = float4(min(float3(a), clamp(sums.rgb / A.divisor + A.bias, 0.0f, 1.0f)), a);
479
+ }
480
+ out.write(o, gid);
481
+ }
482
+
483
+ // feDiffuseLighting and feSpecularLighting. kind 0 none, 1 distant (l, a
484
+ // unit vector toward the light), 2 point and 3 spot (l, the light's
485
+ // position in region pixels, d the unit vector it points along)
486
+ struct LightArgs { Sub sub; In i0; int specular, kind; float c[3];
487
+ float ss, kd, ks, exp; float l[3]; float d[3];
488
+ float cosCone, spotExp; };
489
+ kernel void k_lighting(texture2d<float, access::write> out [[texture(0)]],
490
+ texture2d<float, access::read> in0 [[texture(1)]],
491
+ constant LightArgs& A [[buffer(0)]],
492
+ uint2 gid [[thread_position_in_grid]]) {
493
+ BOUNDS
494
+ if (!inside(p, A.sub)) { out.write(float4(0.0f), gid); return; }
495
+ if (A.kind == 0) {
496
+ out.write(A.specular != 0 ? float4(0.0f) : float4(0.0f, 0.0f, 0.0f, 1.0f), gid);
497
+ return;
498
+ }
499
+ int w1 = W - 1, h1 = H - 1;
500
+ #define AT(dx, dy) in0.read(uint2(clamp(p.x + (dx), 0, w1), clamp(p.y + (dy), 0, h1))).a
501
+ float ss = A.ss;
502
+ // Sobel, as 9.14's table has it at the edges (clamped neighbours)
503
+ float nx = -ss * 0.25f * (AT(1, -1) + 2.0f * AT(1, 0) + AT(1, 1) -
504
+ AT(-1, -1) - 2.0f * AT(-1, 0) - AT(-1, 1));
505
+ float ny = -ss * 0.25f * (AT(-1, 1) + 2.0f * AT(0, 1) + AT(1, 1) -
506
+ AT(-1, -1) - 2.0f * AT(0, -1) - AT(1, -1));
507
+ float z = ss * AT(0, 0);
508
+ #undef AT
509
+ float nlen = sqrt(nx * nx + ny * ny + 1.0f);
510
+ float3 N = float3(nx, ny, 1.0f) / nlen;
511
+ float3 L = float3(A.l[0], A.l[1], A.l[2]);
512
+ float3 colour = float3(A.c[0], A.c[1], A.c[2]);
513
+ float3 lc = colour;
514
+ if (A.kind != 1) {
515
+ float3 v = float3(A.l[0] - (float(p.x) + 0.5f), A.l[1] - (float(p.y) + 0.5f), A.l[2] - z);
516
+ float len = length(v);
517
+ if (!(len > 0.0f)) len = 1.0f;
518
+ L = v / len;
519
+ if (A.kind == 3) {
520
+ float minus = -dot(L, float3(A.d[0], A.d[1], A.d[2]));
521
+ if (minus < A.cosCone || minus <= 0.0f) lc = float3(0.0f);
522
+ else lc = colour * power(minus, A.spotExp);
523
+ }
524
+ }
525
+ float4 o;
526
+ if (A.specular != 0) {
527
+ float3 Hv = float3(L.x, L.y, L.z + 1.0f);
528
+ float hl = length(Hv);
529
+ if (!(hl > 0.0f)) hl = 1.0f;
530
+ float nh = dot(N, Hv) / hl;
531
+ float k = A.ks * power(max(0.0f, nh), A.exp);
532
+ float3 c = clamp(k * lc, 0.0f, 1.0f);
533
+ o = float4(c, max(c.r, max(c.g, c.b)));
534
+ } else {
535
+ float k = A.kd * max(0.0f, dot(N, L));
536
+ o = float4(clamp(k * lc, 0.0f, 1.0f), 1.0f);
537
+ }
538
+ out.write(o, gid);
539
+ }
540
+
541
+ // feTurbulence, Filter Effects 1, 9.21's reference code with its lattice
542
+ // handed in: `sel` 514 entries, `grad` channel ch's gradient for b at
543
+ // (ch * 514 + b) * 2. m is region pixels to user units, its translation
544
+ // already brought within the noise's period. Where the reference adds
545
+ // PerlinN (4096) and truncates, this floors: the same lattice cell and
546
+ // fraction for every point past -4096 cells, without the float32 bits the
547
+ // addition costs.
548
+ struct TurbulenceArgs { Sub sub; float m[6]; float bx, by; int octaves, fractal; };
549
+ kernel void k_turbulence(texture2d<float, access::write> out [[texture(0)]],
550
+ constant TurbulenceArgs& A [[buffer(0)]],
551
+ constant int* sel [[buffer(1)]],
552
+ constant float* grad [[buffer(2)]],
553
+ uint2 gid [[thread_position_in_grid]]) {
554
+ BOUNDS
555
+ if (!inside(p, A.sub)) { out.write(float4(0.0f), gid); return; }
556
+ float px = float(p.x) + 0.5f;
557
+ float py = float(p.y) + 0.5f;
558
+ float ux = A.m[0] * px + A.m[2] * py + A.m[4];
559
+ float uy = A.m[1] * px + A.m[3] * py + A.m[5];
560
+ float4 s = float4(0.0f);
561
+ float fx = A.bx, fy = A.by, ratio = 1.0f;
562
+ bool fractal = A.fractal != 0;
563
+ for (int o = 0; o < A.octaves; o++) {
564
+ float t = ux * fx;
565
+ float f = floor(t);
566
+ int bx0 = int(f) & 255;
567
+ int bx1 = (bx0 + 1) & 255;
568
+ float rx0 = t - f;
569
+ float rx1 = rx0 - 1.0f;
570
+ t = uy * fy;
571
+ f = floor(t);
572
+ int by0 = int(f) & 255;
573
+ int by1 = (by0 + 1) & 255;
574
+ float ry0 = t - f;
575
+ float ry1 = ry0 - 1.0f;
576
+ int i = sel[bx0];
577
+ int j = sel[bx1];
578
+ int q00 = sel[i + by0] * 2;
579
+ int q10 = sel[j + by0] * 2;
580
+ int q01 = sel[i + by1] * 2;
581
+ int q11 = sel[j + by1] * 2;
582
+ float sx = rx0 * rx0 * (3.0f - 2.0f * rx0);
583
+ float sy = ry0 * ry0 * (3.0f - 2.0f * ry0);
584
+ for (int ch = 0; ch < 4; ch++) {
585
+ constant float* g = grad + ch * 1028;
586
+ float u = rx0 * g[q00] + ry0 * g[q00 + 1];
587
+ float v = rx1 * g[q10] + ry0 * g[q10 + 1];
588
+ float a = u + sx * (v - u);
589
+ u = rx0 * g[q01] + ry1 * g[q01 + 1];
590
+ v = rx1 * g[q11] + ry1 * g[q11 + 1];
591
+ float b = u + sx * (v - u);
592
+ float n = a + sy * (b - a);
593
+ s[ch] += (fractal ? n : abs(n)) / ratio;
594
+ }
595
+ fx *= 2.0f;
596
+ fy *= 2.0f;
597
+ ratio *= 2.0f;
598
+ }
599
+ float4 c = clamp(fractal ? (s + 1.0f) / 2.0f : s, 0.0f, 1.0f);
600
+ out.write(float4(c.rgb * c.a, c.a), gid);
601
+ }
602
+
603
+ // the last result, sRGB and premultiplied, as host-order BGRA bytes
604
+ struct FinalArgs { In i0; int width, height, stride; };
605
+ kernel void k_final(texture2d<float, access::read> in0 [[texture(1)]],
606
+ constant FinalArgs& A [[buffer(0)]],
607
+ device uchar4* out [[buffer(1)]],
608
+ uint2 gid [[thread_position_in_grid]]) {
609
+ if (int(gid.x) >= A.width || int(gid.y) >= A.height) return;
610
+ float4 v = clamp(fetch(in0, int2(gid), A.i0), 0.0f, 1.0f);
611
+ v.rgb = min(v.rgb, float3(v.a));
612
+ uint4 b = uint4(round(v * 255.0f));
613
+ out[gid.y * uint(A.stride) + gid.x] = uchar4(b.b, b.g, b.r, b.a);
614
+ }
615
+ )METAL";
616
+
617
+ // The argument structs, as the shaders have them.
618
+ struct Sub { int32_t x0, y0, x1, y1; };
619
+ struct In { int32_t conv, alpha; };
620
+ struct FloodArgs { Sub sub; float c[4]; };
621
+ struct CopyArgs { Sub sub; In i0; };
622
+ struct OffsetArgs { Sub sub; In i0; int32_t dx, dy; };
623
+ struct BlurArgs { Sub sub; In i0; int32_t axis, mode, lo, hi, reach, keep; };
624
+ struct SeedArgs { In i0; float c[4]; };
625
+ struct ShadowArgs { Sub sub; In i0; int32_t dx, dy; };
626
+ struct MatrixArgs { Sub sub; In i0; float m[20]; };
627
+ struct TransferArgs { Sub sub; In i0; int32_t type[4]; int32_t off[4]; int32_t n[4];
628
+ float p0[4]; float p1[4]; float p2[4]; };
629
+ struct CompositeArgs { Sub sub; In i0; In i1; int32_t op; float k[4]; };
630
+ struct BlendArgs { Sub sub; In i0; In i1; int32_t mode; };
631
+ struct MergeArgs { Sub sub; In i0; int32_t first; };
632
+ struct TileArgs { Sub sub; In i0; int32_t fx, fy, fw, fh; };
633
+ struct MorphArgs { Sub sub; In i0; int32_t axis, r, dilate; };
634
+ struct DisplaceArgs { Sub sub; In i0; In i1; float sx, sy; int32_t xc, yc; };
635
+ struct ConvolveArgs { Sub sub; In i0; int32_t ox, oy, tx, ty, edge, preserve; float divisor, bias; };
636
+ struct LightArgs { Sub sub; In i0; int32_t specular, kind; float c[3];
637
+ float ss, kd, ks, exp; float l[3]; float d[3];
638
+ float cosCone, spotExp; };
639
+ struct TurbulenceArgs { Sub sub; float m[6]; float bx, by; int32_t octaves, fractal; };
640
+ struct FinalArgs { In i0; int32_t width, height, stride; };
641
+
642
+ enum Pipe {
643
+ P_FLOOD, P_COPY, P_OFFSET, P_BLUR, P_SEED, P_CAST, P_MATRIX, P_TRANSFER,
644
+ P_COMPOSITE, P_BLEND, P_MERGE, P_TILE, P_MORPH, P_DISPLACE, P_CONVOLVE,
645
+ P_LIGHTING, P_TURBULENCE, P_FINAL, P_COUNT
646
+ };
647
+ const char* kPipeNames[P_COUNT] = {
648
+ "k_flood", "k_copy", "k_offset", "k_blur", "k_shadow_seed", "k_shadow_cast",
649
+ "k_colormatrix", "k_transfer", "k_composite", "k_blend", "k_merge", "k_tile",
650
+ "k_morph", "k_displace", "k_convolve", "k_lighting", "k_turbulence", "k_final",
651
+ };
652
+
653
+ // ---------------------------------------------------------------------------
654
+ // The primitives, as the graph names them.
655
+
656
+ enum Kind {
657
+ K_FLOOD, K_OFFSET, K_BLUR, K_DROPSHADOW, K_COLORMATRIX, K_TRANSFER,
658
+ K_COMPOSITE, K_BLEND, K_MERGE, K_TILE, K_MORPHOLOGY, K_DISPLACE,
659
+ K_CONVOLVE, K_DIFFUSE, K_SPECULAR, K_TURBULENCE, K_IMAGE, K_COUNT
660
+ };
661
+ const char* kKindNames[K_COUNT] = {
662
+ "feflood", "feoffset", "fegaussianblur", "fedropshadow", "fecolormatrix",
663
+ "fecomponenttransfer", "fecomposite", "feblend", "femerge", "fetile",
664
+ "femorphology", "fedisplacementmap", "feconvolvematrix",
665
+ "fediffuselighting", "fespecularlighting", "feturbulence", "feimage",
666
+ };
667
+ // how many inputs each reads: -1 any number (feMerge's nodes)
668
+ const int kKindInputs[K_COUNT] = {0, 1, 1, 1, 1, 1, 2, 2, -1, 1, 1, 2, 1, 1, 1, 0, 0};
669
+
670
+ const int kSourceGraphic = -1;
671
+ const int kSourceAlpha = -2;
672
+ const int kGradients = 514; // BSize + BSize + 2
673
+ // the most a texture side may be: every Mac GPU since macOS 11 has 16384
674
+ const long kMostSide = 16384;
675
+ // the most taps a morphology or convolution pass may take per pixel, past
676
+ // which the JavaScript path is left to it
677
+ const double kMostRadius = 1024;
678
+ const size_t kMostKernel = 1024;
679
+
680
+ struct Transfer {
681
+ int type = 0; // 0 none, 1 table, 2 discrete, 3 linear, 4 gamma
682
+ std::vector<float> values;
683
+ float p0 = 0, p1 = 0, p2 = 0;
684
+ };
685
+
686
+ struct Light {
687
+ int kind = 0; // 0 none, 1 distant, 2 point, 3 spot
688
+ double azimuth = 0, elevation = 0;
689
+ double x = 0, y = 0, z = 0, px = 0, py = 0, pz = 0;
690
+ double exponent = 1;
691
+ bool hasCone = false;
692
+ double cone = 90;
693
+ };
694
+
695
+ struct Node {
696
+ Kind kind;
697
+ std::vector<int> inputs; // a result's index, kSourceGraphic, kSourceAlpha
698
+ Sub sub; // clipped to the region
699
+ bool linear = true;
700
+ // the numbers each kind takes
701
+ double rgba[4] = {0, 0, 0, 0}; // premultiplied sRGB
702
+ double dx = 0, dy = 0, sdx = 0, sdy = 0;
703
+ float matrix[20] = {0};
704
+ Transfer funcs[4];
705
+ int op = 0;
706
+ float k[4] = {0, 0, 0, 0};
707
+ int mode = 0;
708
+ double rx = 0, ry = 0;
709
+ bool dilate = false;
710
+ double scaleX = 0, scaleY = 0;
711
+ int xc = 3, yc = 3;
712
+ int ox = 3, oy = 3, tx = 1, ty = 1, edge = 0;
713
+ bool preserveAlpha = false;
714
+ double divisor = 1, bias = 0;
715
+ std::vector<float> kernel;
716
+ double surfaceScale = 1, kd = 1, ks = 1, exp = 1;
717
+ Light light;
718
+ double bx = 0, by = 0;
719
+ int octaves = 1;
720
+ bool fractal = false;
721
+ std::vector<int32_t> sel;
722
+ std::vector<float> grad;
723
+ int image = 0;
724
+ };
725
+
726
+ struct Graph {
727
+ long width = 0, height = 0;
728
+ // RGBA32F planes where the graph asks for 'float', RGBA16F otherwise
729
+ bool wide = false;
730
+ double matrix[6] = {1, 0, 0, 1, 0, 0};
731
+ std::vector<Node> nodes;
732
+ };
733
+
734
+ // ---------------------------------------------------------------------------
735
+ // Reading the graph. Each reader answers false where a value is one this
736
+ // does not take, and the whole graph is then the JavaScript path's.
737
+
738
+ bool NumberOf(Napi::Value v, double* out) {
739
+ if (!v.IsNumber()) return false;
740
+ double d = v.As<Napi::Number>().DoubleValue();
741
+ if (!std::isfinite(d)) return false;
742
+ *out = d;
743
+ return true;
744
+ }
745
+
746
+ // a number param, `fallback` where it is absent; false where it is there and
747
+ // not a finite number
748
+ bool Param(Napi::Object o, const char* key, double fallback, double* out) {
749
+ Napi::Value v = o.Get(key);
750
+ if (v.IsUndefined() || v.IsNull()) {
751
+ *out = fallback;
752
+ return true;
753
+ }
754
+ if (v.IsBoolean()) {
755
+ *out = v.As<Napi::Boolean>().Value() ? 1 : 0;
756
+ return true;
757
+ }
758
+ return NumberOf(v, out);
759
+ }
760
+
761
+ bool BoolParam(Napi::Object o, const char* key, bool fallback) {
762
+ Napi::Value v = o.Get(key);
763
+ if (v.IsUndefined() || v.IsNull()) return fallback;
764
+ return v.ToBoolean().Value();
765
+ }
766
+
767
+ std::string StringParam(Napi::Object o, const char* key, const char* fallback) {
768
+ Napi::Value v = o.Get(key);
769
+ if (!v.IsString()) return fallback;
770
+ return v.As<Napi::String>().Utf8Value();
771
+ }
772
+
773
+ // an array or a typed array of finite numbers
774
+ bool Numbers(Napi::Value v, std::vector<double>* out, size_t most = 1 << 20) {
775
+ if (!v.IsObject()) return false;
776
+ Napi::Object a = v.As<Napi::Object>();
777
+ Napi::Value len = a.Get("length");
778
+ if (!len.IsNumber()) return false;
779
+ double n = len.As<Napi::Number>().DoubleValue();
780
+ if (!(n >= 0) || n > (double)most) return false;
781
+ out->resize((size_t)n);
782
+ for (uint32_t i = 0; i < (uint32_t)n; i++) {
783
+ if (!NumberOf(a.Get(i), &(*out)[i])) return false;
784
+ }
785
+ return true;
786
+ }
787
+
788
+ bool Colour(Napi::Object o, const char* key, double* rgba) {
789
+ std::vector<double> v;
790
+ if (!Numbers(o.Get(key), &v) || v.size() != 4) return false;
791
+ for (int i = 0; i < 4; i++) rgba[i] = std::min(1.0, std::max(0.0, v[i]));
792
+ return true;
793
+ }
794
+
795
+ bool ReadTransfer(Napi::Value v, Transfer* t) {
796
+ t->type = 0;
797
+ if (v.IsUndefined() || v.IsNull()) return true;
798
+ if (!v.IsObject()) return false;
799
+ Napi::Object o = v.As<Napi::Object>();
800
+ std::string type = StringParam(o, "type", "");
801
+ std::vector<double> values;
802
+ if (type == "table" || type == "discrete") {
803
+ Napi::Value tv = o.Get("tableValues");
804
+ if (tv.IsUndefined()) tv = o.Get("values");
805
+ if (!Numbers(tv, &values, 4096)) return false;
806
+ // no values is no function, as runFilter's transferOf has it
807
+ if (values.empty()) return true;
808
+ t->type = type == "table" ? 1 : 2;
809
+ t->values.assign(values.begin(), values.end());
810
+ return true;
811
+ }
812
+ double a, b, c;
813
+ if (type == "linear") {
814
+ if (!Param(o, "slope", 1, &a) || !Param(o, "intercept", 0, &b)) return false;
815
+ t->type = 3;
816
+ t->p0 = (float)a;
817
+ t->p1 = (float)b;
818
+ return true;
819
+ }
820
+ if (type == "gamma") {
821
+ if (!Param(o, "amplitude", 1, &a) || !Param(o, "exponent", 1, &b) ||
822
+ !Param(o, "offset", 0, &c)) {
823
+ return false;
824
+ }
825
+ t->type = 4;
826
+ t->p0 = (float)a;
827
+ t->p1 = (float)b;
828
+ t->p2 = (float)c;
829
+ return true;
830
+ }
831
+ // identity, or a type no function is made of
832
+ return true;
833
+ }
834
+
835
+ bool ReadLight(Napi::Value v, Light* l) {
836
+ if (v.IsUndefined() || v.IsNull()) return true;
837
+ if (!v.IsObject()) return false;
838
+ Napi::Object o = v.As<Napi::Object>();
839
+ std::string kind = StringParam(o, "kind", "none");
840
+ if (kind == "none") l->kind = 0;
841
+ else if (kind == "distant") l->kind = 1;
842
+ else if (kind == "point") l->kind = 2;
843
+ else if (kind == "spot") l->kind = 3;
844
+ else return false;
845
+ if (!Param(o, "azimuth", 0, &l->azimuth) || !Param(o, "elevation", 0, &l->elevation) ||
846
+ !Param(o, "x", 0, &l->x) || !Param(o, "y", 0, &l->y) || !Param(o, "z", 0, &l->z) ||
847
+ !Param(o, "px", 0, &l->px) || !Param(o, "py", 0, &l->py) || !Param(o, "pz", 0, &l->pz) ||
848
+ !Param(o, "exponent", 1, &l->exponent)) {
849
+ return false;
850
+ }
851
+ Napi::Value cone = o.Get("cone");
852
+ if (!cone.IsUndefined() && !cone.IsNull()) {
853
+ if (!NumberOf(cone, &l->cone)) return false;
854
+ l->hasCone = true;
855
+ }
856
+ return true;
857
+ }
858
+
859
+ // The reference code's lattice for a seed (Filter Effects 1, 9.21's
860
+ // setup_seed, random and init), for a graph that hands a seed and no
861
+ // lattice: runFilter's flatLattice to the bit.
862
+ void LatticeOf(double seedIn, std::vector<int32_t>* sel, std::vector<float>* grad) {
863
+ const long BSize = 0x100;
864
+ const long RAND_m = 2147483647, RAND_a = 16807, RAND_q = 127773, RAND_r = 2836;
865
+ auto random = [&](long s) {
866
+ s = RAND_a * (s % RAND_q) - RAND_r * (long)std::floor((double)s / RAND_q);
867
+ if (s <= 0) s += RAND_m;
868
+ return s;
869
+ };
870
+ // Math.round, halves up
871
+ long seed = (long)std::floor(seedIn + 0.5);
872
+ if (seed <= 0) seed = -(seed % (RAND_m - 1)) + 1;
873
+ if (seed > RAND_m - 1) seed = RAND_m - 1;
874
+ std::vector<long> lattice(kGradients);
875
+ std::vector<double> g(4 * kGradients * 2);
876
+ for (int k = 0; k < 4; k++) {
877
+ for (long i = 0; i < BSize; i++) {
878
+ lattice[i] = i;
879
+ for (int j = 0; j < 2; j++) {
880
+ seed = random(seed);
881
+ g[(k * kGradients + i) * 2 + j] =
882
+ (double)((seed % (BSize + BSize)) - BSize) / BSize;
883
+ }
884
+ double* v = &g[(k * kGradients + i) * 2];
885
+ double s = std::sqrt(v[0] * v[0] + v[1] * v[1]);
886
+ v[0] /= s;
887
+ v[1] /= s;
888
+ }
889
+ }
890
+ for (long i = BSize - 1; i > 0; i--) {
891
+ long k = lattice[i];
892
+ seed = random(seed);
893
+ long j = seed % BSize;
894
+ lattice[i] = lattice[j];
895
+ lattice[j] = k;
896
+ }
897
+ for (long i = 0; i < BSize + 2; i++) {
898
+ lattice[BSize + i] = lattice[i];
899
+ for (int k = 0; k < 4; k++) {
900
+ g[(k * kGradients + BSize + i) * 2] = g[(k * kGradients + i) * 2];
901
+ g[(k * kGradients + BSize + i) * 2 + 1] = g[(k * kGradients + i) * 2 + 1];
902
+ }
903
+ }
904
+ sel->assign(lattice.begin(), lattice.end());
905
+ grad->assign(g.begin(), g.end());
906
+ }
907
+
908
+ bool ReadParams(Napi::Object p, Node* n) {
909
+ switch (n->kind) {
910
+ case K_FLOOD:
911
+ return Colour(p, "rgba", n->rgba);
912
+ case K_OFFSET:
913
+ return Param(p, "dx", 0, &n->dx) && Param(p, "dy", 0, &n->dy);
914
+ case K_BLUR:
915
+ return Param(p, "sdx", 0, &n->sdx) && Param(p, "sdy", n->sdx, &n->sdy);
916
+ case K_DROPSHADOW:
917
+ return Colour(p, "rgba", n->rgba) && Param(p, "dx", 0, &n->dx) &&
918
+ Param(p, "dy", 0, &n->dy) && Param(p, "sdx", 0, &n->sdx) &&
919
+ Param(p, "sdy", n->sdx, &n->sdy);
920
+ case K_COLORMATRIX: {
921
+ std::vector<double> m;
922
+ if (!Numbers(p.Get("matrix"), &m) || m.size() != 20) return false;
923
+ for (int i = 0; i < 20; i++) n->matrix[i] = (float)m[i];
924
+ return true;
925
+ }
926
+ case K_TRANSFER: {
927
+ Napi::Value f = p.Get("funcs");
928
+ if (!f.IsObject()) return false;
929
+ Napi::Object fo = f.As<Napi::Object>();
930
+ for (uint32_t i = 0; i < 4; i++) {
931
+ if (!ReadTransfer(fo.Get(i), &n->funcs[i])) return false;
932
+ }
933
+ return true;
934
+ }
935
+ case K_COMPOSITE: {
936
+ std::string op = StringParam(p, "op", "over");
937
+ // an operator it does not know is over, as runFilter's composite reads it
938
+ n->op = op == "in" ? 1 : op == "out" ? 2 : op == "atop" ? 3 : op == "xor" ? 4
939
+ : op == "lighter" ? 5 : op == "arithmetic" ? 6 : 0;
940
+ Napi::Value kv = p.Get("k");
941
+ if (!kv.IsUndefined()) {
942
+ std::vector<double> k;
943
+ if (!Numbers(kv, &k) || k.size() != 4) return false;
944
+ for (int i = 0; i < 4; i++) n->k[i] = (float)k[i];
945
+ }
946
+ return true;
947
+ }
948
+ case K_BLEND: {
949
+ static const char* modes[] = {
950
+ "normal", "multiply", "screen", "overlay", "darken", "lighten",
951
+ "color-dodge", "color-burn", "hard-light", "soft-light", "difference",
952
+ "exclusion", "hue", "saturation", "color", "luminosity",
953
+ };
954
+ std::string mode = StringParam(p, "mode", "normal");
955
+ n->mode = 0;
956
+ for (int i = 0; i < 16; i++) {
957
+ if (mode == modes[i]) n->mode = i;
958
+ }
959
+ return true;
960
+ }
961
+ case K_MERGE:
962
+ case K_TILE:
963
+ return true;
964
+ case K_MORPHOLOGY:
965
+ n->dilate = StringParam(p, "op", "erode") == "dilate";
966
+ return Param(p, "rx", 0, &n->rx) && Param(p, "ry", n->rx, &n->ry) &&
967
+ std::fabs(n->rx) <= kMostRadius && std::fabs(n->ry) <= kMostRadius;
968
+ case K_DISPLACE: {
969
+ double scale;
970
+ if (!Param(p, "scale", 0, &scale) || !Param(p, "scaleX", scale, &n->scaleX) ||
971
+ !Param(p, "scaleY", scale, &n->scaleY)) {
972
+ return false;
973
+ }
974
+ auto channel = [&](const char* key, int* out) {
975
+ Napi::Value v = p.Get(key);
976
+ if (v.IsUndefined() || v.IsNull()) {
977
+ *out = 3;
978
+ return true;
979
+ }
980
+ if (v.IsString()) {
981
+ std::string s = v.As<Napi::String>().Utf8Value();
982
+ size_t at = std::string("RGBA").find(s);
983
+ *out = s.size() == 1 && at != std::string::npos ? (int)at : 3;
984
+ return true;
985
+ }
986
+ double d;
987
+ if (!NumberOf(v, &d) || d != std::floor(d) || d < 0 || d > 3) return false;
988
+ *out = (int)d;
989
+ return true;
990
+ };
991
+ return channel("xc", &n->xc) && channel("yc", &n->yc);
992
+ }
993
+ case K_CONVOLVE: {
994
+ double ox, oy, tx, ty;
995
+ std::vector<double> kernel;
996
+ if (!Param(p, "ox", 3, &ox) || !Param(p, "oy", ox, &oy) ||
997
+ ox != std::floor(ox) || oy != std::floor(oy) || ox < 1 || oy < 1 ||
998
+ ox * oy > (double)kMostKernel) {
999
+ return false;
1000
+ }
1001
+ if (!Numbers(p.Get("kernel"), &kernel) || kernel.size() != (size_t)(ox * oy)) {
1002
+ return false;
1003
+ }
1004
+ if (!Param(p, "tx", std::floor(ox / 2), &tx) || !Param(p, "ty", std::floor(oy / 2), &ty) ||
1005
+ tx != std::floor(tx) || ty != std::floor(ty) || tx < 0 || tx >= ox || ty < 0 ||
1006
+ ty >= oy) {
1007
+ return false;
1008
+ }
1009
+ double sum = 0;
1010
+ for (double k : kernel) sum += k;
1011
+ if (!Param(p, "divisor", sum != 0 ? sum : 1, &n->divisor) ||
1012
+ !Param(p, "bias", 0, &n->bias)) {
1013
+ return false;
1014
+ }
1015
+ if (n->divisor == 0) n->divisor = sum != 0 ? sum : 1;
1016
+ n->ox = (int)ox;
1017
+ n->oy = (int)oy;
1018
+ n->tx = (int)tx;
1019
+ n->ty = (int)ty;
1020
+ n->kernel.assign(kernel.begin(), kernel.end());
1021
+ std::string edge = StringParam(p, "edge", "duplicate");
1022
+ n->edge = edge == "wrap" ? 1 : edge == "none" ? 2 : 0;
1023
+ n->preserveAlpha = BoolParam(p, "preserveAlpha", false);
1024
+ return true;
1025
+ }
1026
+ case K_DIFFUSE:
1027
+ case K_SPECULAR:
1028
+ return Colour(p, "rgba", n->rgba) && Param(p, "surfaceScale", 1, &n->surfaceScale) &&
1029
+ Param(p, "kd", 1, &n->kd) && Param(p, "ks", 1, &n->ks) &&
1030
+ Param(p, "exp", 1, &n->exp) && ReadLight(p.Get("light"), &n->light);
1031
+ case K_TURBULENCE: {
1032
+ double octaves;
1033
+ if (!Param(p, "bx", 0, &n->bx) || !Param(p, "by", n->bx, &n->by) ||
1034
+ !Param(p, "octaves", 1, &octaves)) {
1035
+ return false;
1036
+ }
1037
+ // a negative frequency is none at all (9.21), as runFilter reads it
1038
+ if (n->bx < 0 || n->by < 0) n->bx = n->by = 0;
1039
+ // past 24 octaves what one adds is under 2^-24: nothing in 8 bits
1040
+ n->octaves = (int)std::max(0.0, std::min(24.0, std::floor(octaves)));
1041
+ n->fractal = BoolParam(p, "fractal", false);
1042
+ std::vector<double> sel, grad;
1043
+ Napi::Value sv = p.Get("sel");
1044
+ if (!sv.IsUndefined() && !sv.IsNull()) {
1045
+ if (!Numbers(sv, &sel) || sel.size() != (size_t)kGradients ||
1046
+ !Numbers(p.Get("grad"), &grad) || grad.size() != (size_t)(4 * kGradients * 2)) {
1047
+ return false;
1048
+ }
1049
+ n->sel.resize(kGradients);
1050
+ for (int i = 0; i < kGradients; i++) {
1051
+ if (sel[i] != std::floor(sel[i]) || sel[i] < 0 || sel[i] > 255) return false;
1052
+ n->sel[i] = (int32_t)sel[i];
1053
+ }
1054
+ n->grad.assign(grad.begin(), grad.end());
1055
+ } else {
1056
+ double seed;
1057
+ if (!Param(p, "seed", 0, &seed)) return false;
1058
+ LatticeOf(seed, &n->sel, &n->grad);
1059
+ }
1060
+ return true;
1061
+ }
1062
+ case K_IMAGE: {
1063
+ double image;
1064
+ if (!Param(p, "image", 0, &image) || image != std::floor(image) || image < 0) {
1065
+ return false;
1066
+ }
1067
+ n->image = (int)image;
1068
+ return true;
1069
+ }
1070
+ default:
1071
+ return false;
1072
+ }
1073
+ }
1074
+
1075
+ bool ReadGraph(Napi::Value v, Graph* g, size_t images) {
1076
+ if (!v.IsObject()) return false;
1077
+ Napi::Object o = v.As<Napi::Object>();
1078
+ double w, h;
1079
+ if (!NumberOf(o.Get("width"), &w) || !NumberOf(o.Get("height"), &h) ||
1080
+ w != std::floor(w) || h != std::floor(h) || w < 1 || h < 1 || w > kMostSide ||
1081
+ h > kMostSide) {
1082
+ return false;
1083
+ }
1084
+ g->width = (long)w;
1085
+ g->height = (long)h;
1086
+ std::string precision = StringParam(o, "precision", "half");
1087
+ if (precision != "half" && precision != "float") return false;
1088
+ g->wide = precision == "float";
1089
+ Napi::Value mv = o.Get("matrix");
1090
+ if (!mv.IsUndefined()) {
1091
+ std::vector<double> m;
1092
+ if (!Numbers(mv, &m) || m.size() != 6) return false;
1093
+ for (int i = 0; i < 6; i++) g->matrix[i] = m[i];
1094
+ }
1095
+ Napi::Value pv = o.Get("primitives");
1096
+ if (!pv.IsObject()) return false;
1097
+ Napi::Object prims = pv.As<Napi::Object>();
1098
+ double count;
1099
+ if (!NumberOf(prims.Get("length"), &count) || count < 0 || count > 4096) return false;
1100
+ for (uint32_t i = 0; i < (uint32_t)count; i++) {
1101
+ Napi::Value nv = prims.Get(i);
1102
+ if (!nv.IsObject()) return false;
1103
+ Napi::Object no = nv.As<Napi::Object>();
1104
+ Node n;
1105
+ std::string kind = StringParam(no, "kind", "");
1106
+ int k = -1;
1107
+ for (int j = 0; j < K_COUNT; j++) {
1108
+ if (kind == kKindNames[j]) k = j;
1109
+ }
1110
+ if (k < 0) return false;
1111
+ n.kind = (Kind)k;
1112
+ n.linear = StringParam(no, "space", "linear") != "srgb";
1113
+ // the subregion on whole pixels, as runFilter's clipTo keeps it, and
1114
+ // within the region
1115
+ std::vector<double> sub;
1116
+ Napi::Value sv = no.Get("sub");
1117
+ if (sv.IsUndefined()) {
1118
+ sub = {0, 0, w, h};
1119
+ } else if (!Numbers(sv, &sub) || sub.size() != 4) {
1120
+ return false;
1121
+ }
1122
+ n.sub.x0 = (int32_t)std::max(0.0, std::min(w, std::ceil(sub[0])));
1123
+ n.sub.y0 = (int32_t)std::max(0.0, std::min(h, std::ceil(sub[1])));
1124
+ n.sub.x1 = (int32_t)std::max(0.0, std::min(w, std::ceil(sub[0] + sub[2])));
1125
+ n.sub.y1 = (int32_t)std::max(0.0, std::min(h, std::ceil(sub[1] + sub[3])));
1126
+ // inputs: a result before it, a source, or null for the one before (the
1127
+ // source graphic for the first)
1128
+ std::vector<Napi::Value> refs;
1129
+ Napi::Value iv = no.Get("inputs");
1130
+ if (iv.IsObject()) {
1131
+ Napi::Object io = iv.As<Napi::Object>();
1132
+ double len;
1133
+ if (!NumberOf(io.Get("length"), &len) || len < 0 || len > 4096) return false;
1134
+ for (uint32_t j = 0; j < (uint32_t)len; j++) refs.push_back(io.Get(j));
1135
+ } else if (!iv.IsUndefined() && !iv.IsNull()) {
1136
+ return false;
1137
+ }
1138
+ int want = kKindInputs[k];
1139
+ size_t take = want < 0 ? refs.size() : (size_t)want;
1140
+ for (size_t j = 0; j < take; j++) {
1141
+ Napi::Value r = j < refs.size() ? refs[j] : Napi::Value();
1142
+ if (r.IsEmpty() || r.IsUndefined() || r.IsNull()) {
1143
+ n.inputs.push_back(i == 0 ? kSourceGraphic : (int)i - 1);
1144
+ } else if (r.IsNumber()) {
1145
+ double d = r.As<Napi::Number>().DoubleValue();
1146
+ if (d != std::floor(d) || d < 0 || d >= i) return false;
1147
+ n.inputs.push_back((int)d);
1148
+ } else if (r.IsString()) {
1149
+ std::string s = r.As<Napi::String>().Utf8Value();
1150
+ if (s == "SourceGraphic") n.inputs.push_back(kSourceGraphic);
1151
+ else if (s == "SourceAlpha") n.inputs.push_back(kSourceAlpha);
1152
+ // BackgroundImage, the paints: what a graph may not read
1153
+ else return false;
1154
+ } else {
1155
+ return false;
1156
+ }
1157
+ }
1158
+ Napi::Value params = no.Get("params");
1159
+ Napi::Object po = params.IsObject() ? params.As<Napi::Object>() : Napi::Object::New(v.Env());
1160
+ if (!ReadParams(po, &n)) return false;
1161
+ if (n.kind == K_IMAGE && (size_t)n.image >= images) return false;
1162
+ g->nodes.push_back(std::move(n));
1163
+ }
1164
+ return true;
1165
+ }
1166
+
1167
+ // ---------------------------------------------------------------------------
1168
+ // The device, the pipelines and the texture pool.
1169
+
1170
+ struct GPU {
1171
+ id<MTLDevice> device;
1172
+ id<MTLCommandQueue> queue;
1173
+ id<MTLComputePipelineState> pipes[P_COUNT];
1174
+ NSUInteger linearAlign;
1175
+ bool unified;
1176
+ };
1177
+
1178
+ GPU* TheGPU() {
1179
+ static GPU* gpu = nullptr;
1180
+ static std::once_flag once;
1181
+ std::call_once(once, [] {
1182
+ @autoreleasepool {
1183
+ id<MTLDevice> device = MTLCreateSystemDefaultDevice();
1184
+ if (!device) return;
1185
+ MTLCompileOptions* opts = [MTLCompileOptions new];
1186
+ #pragma clang diagnostic push
1187
+ #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1188
+ opts.fastMathEnabled = NO;
1189
+ #pragma clang diagnostic pop
1190
+ NSError* err = nil;
1191
+ id<MTLLibrary> lib = [device newLibraryWithSource:@(kShaders) options:opts error:&err];
1192
+ if (!lib) {
1193
+ NSLog(@"appkit filter graph: shaders did not compile: %@", err);
1194
+ return;
1195
+ }
1196
+ auto* g = new GPU();
1197
+ g->device = device;
1198
+ g->queue = [device newCommandQueue];
1199
+ g->unified = device.hasUnifiedMemory;
1200
+ g->linearAlign = [device minimumLinearTextureAlignmentForPixelFormat:MTLPixelFormatBGRA8Unorm];
1201
+ for (int i = 0; i < P_COUNT; i++) {
1202
+ id<MTLFunction> fn = [lib newFunctionWithName:@(kPipeNames[i])];
1203
+ g->pipes[i] = fn ? [device newComputePipelineStateWithFunction:fn error:&err] : nil;
1204
+ if (!g->pipes[i]) {
1205
+ NSLog(@"appkit filter graph: no pipeline for %s: %@", kPipeNames[i], err);
1206
+ delete g;
1207
+ return;
1208
+ }
1209
+ }
1210
+ if (!g->queue) {
1211
+ delete g;
1212
+ return;
1213
+ }
1214
+ gpu = g;
1215
+ }
1216
+ });
1217
+ return gpu;
1218
+ }
1219
+
1220
+ // Free plane textures, kept between runs: a scroll runs the same graph at
1221
+ // the same size every frame. A run takes from here and gives back only once
1222
+ // its command buffer is done, so two threads never share one in flight;
1223
+ // what is kept is the last run's size, as many as it held at most.
1224
+ std::mutex gPoolLock;
1225
+ std::vector<id<MTLTexture>> gPool;
1226
+ // the output buffer, kept likewise while no image is drawing from it
1227
+ id<MTLBuffer> gSpareOut;
1228
+
1229
+ id<MTLTexture> NewPlane(GPU* g, long w, long h, MTLPixelFormat format) {
1230
+ {
1231
+ std::lock_guard<std::mutex> lock(gPoolLock);
1232
+ for (size_t i = 0; i < gPool.size(); i++) {
1233
+ if ((long)gPool[i].width == w && (long)gPool[i].height == h &&
1234
+ gPool[i].pixelFormat == format) {
1235
+ id<MTLTexture> t = gPool[i];
1236
+ gPool.erase(gPool.begin() + i);
1237
+ return t;
1238
+ }
1239
+ }
1240
+ }
1241
+ MTLTextureDescriptor* d =
1242
+ [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:format
1243
+ width:(NSUInteger)w
1244
+ height:(NSUInteger)h
1245
+ mipmapped:NO];
1246
+ d.usage = MTLTextureUsageShaderRead | MTLTextureUsageShaderWrite;
1247
+ d.storageMode = MTLStorageModePrivate;
1248
+ return [g->device newTextureWithDescriptor:d];
1249
+ }
1250
+
1251
+ void GiveBack(std::vector<id<MTLTexture>>& planes, long w, long h, MTLPixelFormat format) {
1252
+ std::lock_guard<std::mutex> lock(gPoolLock);
1253
+ // only the size just run is worth keeping
1254
+ gPool.erase(std::remove_if(gPool.begin(), gPool.end(),
1255
+ [&](id<MTLTexture> t) {
1256
+ return (long)t.width != w || (long)t.height != h ||
1257
+ t.pixelFormat != format;
1258
+ }),
1259
+ gPool.end());
1260
+ for (auto& t : planes) {
1261
+ if (t && gPool.size() < 8) gPool.push_back(t);
1262
+ }
1263
+ planes.clear();
1264
+ }
1265
+
1266
+ // A surface as a texture to read: the IOSurface under it, a buffer over its
1267
+ // bitmap where Metal can lie one there, or else a copy. Only its top-left
1268
+ // w x h is read; a surface smaller than that is copied into one that size,
1269
+ // what it does not have transparent.
1270
+ id<MTLTexture> SurfaceTexture(GPU* g, const CALSurfaceView& s, long w, long h,
1271
+ std::vector<id>* keep) {
1272
+ bool big = (long)s.width >= w && (long)s.height >= h;
1273
+ MTLStorageMode shared = g->unified ? MTLStorageModeShared : MTLStorageModeManaged;
1274
+ if (big && s.iosurface && IOSurfaceGetPixelFormat(s.iosurface) == 'BGRA') {
1275
+ MTLTextureDescriptor* d =
1276
+ [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
1277
+ width:s.width
1278
+ height:s.height
1279
+ mipmapped:NO];
1280
+ d.usage = MTLTextureUsageShaderRead;
1281
+ d.storageMode = shared;
1282
+ id<MTLTexture> t = [g->device newTextureWithDescriptor:d iosurface:s.iosurface plane:0];
1283
+ if (t) return t;
1284
+ }
1285
+ if (!s.data) return nil;
1286
+ if (big && g->unified && !s.iosurface) {
1287
+ // a buffer can only begin on a page, and CoreGraphics' bitmaps do not:
1288
+ // it begins on the page the bitmap begins in, and the texture at the
1289
+ // bitmap's offset into it. The pages either end shares with something
1290
+ // else are mapped, being the bitmap's too, and are only read.
1291
+ size_t page = vm_page_size;
1292
+ uintptr_t start = (uintptr_t)s.data / page * page;
1293
+ size_t offset = (uintptr_t)s.data - start;
1294
+ size_t len = offset + s.bytesPerRow * s.height;
1295
+ size_t rounded = (len + page - 1) / page * page;
1296
+ if (offset % g->linearAlign == 0 && s.bytesPerRow % g->linearAlign == 0) {
1297
+ id<MTLBuffer> b = [g->device newBufferWithBytesNoCopy:(void*)start
1298
+ length:rounded
1299
+ options:MTLResourceStorageModeShared
1300
+ deallocator:nil];
1301
+ if (b) {
1302
+ MTLTextureDescriptor* d =
1303
+ [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
1304
+ width:s.width
1305
+ height:s.height
1306
+ mipmapped:NO];
1307
+ d.usage = MTLTextureUsageShaderRead;
1308
+ d.storageMode = MTLStorageModeShared;
1309
+ id<MTLTexture> t = [b newTextureWithDescriptor:d offset:offset bytesPerRow:s.bytesPerRow];
1310
+ if (t) {
1311
+ keep->push_back(b);
1312
+ return t;
1313
+ }
1314
+ }
1315
+ }
1316
+ }
1317
+ MTLTextureDescriptor* d =
1318
+ [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
1319
+ width:(NSUInteger)w
1320
+ height:(NSUInteger)h
1321
+ mipmapped:NO];
1322
+ d.usage = MTLTextureUsageShaderRead;
1323
+ d.storageMode = shared;
1324
+ id<MTLTexture> t = [g->device newTextureWithDescriptor:d];
1325
+ if (!t) return nil;
1326
+ long cw = std::min(w, (long)s.width);
1327
+ long ch = std::min(h, (long)s.height);
1328
+ if (cw < w || ch < h) {
1329
+ std::vector<uint8_t> zero((size_t)w * 4, 0);
1330
+ for (long y = 0; y < h; y++) {
1331
+ [t replaceRegion:MTLRegionMake2D(0, y, w, 1) mipmapLevel:0 withBytes:zero.data()
1332
+ bytesPerRow:w * 4];
1333
+ }
1334
+ }
1335
+ if (s.iosurface) IOSurfaceLock(s.iosurface, kIOSurfaceLockReadOnly, nullptr);
1336
+ [t replaceRegion:MTLRegionMake2D(0, 0, cw, ch) mipmapLevel:0 withBytes:s.data
1337
+ bytesPerRow:s.bytesPerRow];
1338
+ if (s.iosurface) IOSurfaceUnlock(s.iosurface, kIOSurfaceLockReadOnly, nullptr);
1339
+ return t;
1340
+ }
1341
+
1342
+ double ToLinear(double c) {
1343
+ return c <= 0.04045 ? c / 12.92 : std::pow((c + 0.055) / 1.055, 2.4);
1344
+ }
1345
+
1346
+ // ---------------------------------------------------------------------------
1347
+ // A run.
1348
+
1349
+ // a plane a primitive made or a source: its texture, the space it is in,
1350
+ // and whether it is the source's alpha alone
1351
+ struct Plane {
1352
+ id<MTLTexture> tex;
1353
+ bool linear = false;
1354
+ bool alpha = false;
1355
+ bool pooled = false;
1356
+ };
1357
+
1358
+ struct Run {
1359
+ GPU* g;
1360
+ long W, H;
1361
+ MTLPixelFormat format;
1362
+ id<MTLComputeCommandEncoder> enc;
1363
+ std::vector<id<MTLTexture>> held; // every pooled texture this run took
1364
+ std::vector<id<MTLTexture>> spare; // those of them free again
1365
+ std::vector<id> keep; // what must outlive the command buffer
1366
+
1367
+ id<MTLTexture> Take() {
1368
+ id<MTLTexture> t;
1369
+ if (!spare.empty()) {
1370
+ t = spare.back();
1371
+ spare.pop_back();
1372
+ return t;
1373
+ }
1374
+ t = NewPlane(g, W, H, format);
1375
+ if (t) held.push_back(t);
1376
+ return t;
1377
+ }
1378
+ void Free(id<MTLTexture> t) { spare.push_back(t); }
1379
+
1380
+ void Dispatch(Pipe p, id<MTLTexture> out, id<MTLTexture> a, id<MTLTexture> b,
1381
+ const void* args, size_t len, const void* extra = nullptr,
1382
+ size_t extraLen = 0, const void* extra2 = nullptr, size_t extra2Len = 0) {
1383
+ id<MTLComputePipelineState> ps = g->pipes[p];
1384
+ [enc setComputePipelineState:ps];
1385
+ if (out) [enc setTexture:out atIndex:0];
1386
+ if (a) [enc setTexture:a atIndex:1];
1387
+ [enc setTexture:(b ? b : a) atIndex:2];
1388
+ [enc setBytes:args length:len atIndex:0];
1389
+ auto bind = [&](const void* bytes, size_t n, NSUInteger at) {
1390
+ if (!bytes) {
1391
+ static const float none[4] = {0, 0, 0, 0};
1392
+ [enc setBytes:none length:sizeof none atIndex:at];
1393
+ } else if (n <= 4096) {
1394
+ [enc setBytes:bytes length:n atIndex:at];
1395
+ } else {
1396
+ id<MTLBuffer> buf = [g->device newBufferWithBytes:bytes
1397
+ length:n
1398
+ options:MTLResourceStorageModeShared];
1399
+ keep.push_back(buf);
1400
+ [enc setBuffer:buf offset:0 atIndex:at];
1401
+ }
1402
+ };
1403
+ bind(extra, extraLen, 1);
1404
+ bind(extra2, extra2Len, 2);
1405
+ NSUInteger tw = ps.threadExecutionWidth;
1406
+ NSUInteger th = std::max<NSUInteger>(1, ps.maxTotalThreadsPerThreadgroup / tw);
1407
+ MTLSize group = MTLSizeMake(tw, th, 1);
1408
+ MTLSize grid = MTLSizeMake((W + tw - 1) / tw, (H + th - 1) / th, 1);
1409
+ [enc dispatchThreadgroups:grid threadsPerThreadgroup:group];
1410
+ }
1411
+ };
1412
+
1413
+ Sub Whole(long W, long H) { return Sub{0, 0, (int32_t)W, (int32_t)H}; }
1414
+
1415
+ // how a plane is read for a primitive working in `linear`, or as it is where
1416
+ // `own`
1417
+ In ReadAs(const Plane& p, bool linear, bool own = false) {
1418
+ In in;
1419
+ in.alpha = p.alpha ? 1 : 0;
1420
+ // alpha alone is the same in either space
1421
+ in.conv = own || p.alpha || p.linear == linear ? 0 : linear ? 1 : 2;
1422
+ return in;
1423
+ }
1424
+
1425
+ // A blur of `src` read as `in`, sdx across and sdy down in region pixels,
1426
+ // within `sub`: react-x11-components' blurPass along each axis, three boxes
1427
+ // at a deviation of 2 or more and the Gaussian's weights under it. Outside
1428
+ // `sub` it is the input where `keep`, else nothing. The result is a texture
1429
+ // of the run's.
1430
+ id<MTLTexture> EncodeBlur(Run& run, id<MTLTexture> src, In in, double sdx, double sdy,
1431
+ Sub sub, bool keep) {
1432
+ struct Pass {
1433
+ int axis, mode, lo, hi, reach;
1434
+ std::vector<float> weights;
1435
+ };
1436
+ std::vector<Pass> passes;
1437
+ auto axis = [&](int a, double sigma) {
1438
+ if (!(sigma > 0)) return;
1439
+ if (sigma >= 2) {
1440
+ int d = (int)std::floor(sigma * 3 * std::sqrt(2 * M_PI) / 4 + 0.5);
1441
+ int half = d >> 1;
1442
+ if (d % 2 == 1) {
1443
+ for (int i = 0; i < 3; i++) passes.push_back({a, 0, -half, half, 0, {}});
1444
+ } else {
1445
+ passes.push_back({a, 0, -half, half - 1, 0, {}});
1446
+ passes.push_back({a, 0, -half + 1, half, 0, {}});
1447
+ passes.push_back({a, 0, -half, half, 0, {}});
1448
+ }
1449
+ return;
1450
+ }
1451
+ int reach = (int)std::ceil(3 * sigma);
1452
+ std::vector<double> w(2 * reach + 1);
1453
+ double total = 0;
1454
+ for (int k = -reach; k <= reach; k++) {
1455
+ w[k + reach] = std::exp(-(double)(k * k) / (2 * sigma * sigma));
1456
+ total += w[k + reach];
1457
+ }
1458
+ Pass p{a, 1, 0, 0, reach, {}};
1459
+ for (double v : w) p.weights.push_back((float)(v / total));
1460
+ passes.push_back(std::move(p));
1461
+ };
1462
+ axis(0, sdx);
1463
+ axis(1, sdy);
1464
+ bool empty = sub.x0 >= sub.x1 || sub.y0 >= sub.y1;
1465
+ if (passes.empty() || empty) {
1466
+ id<MTLTexture> out = run.Take();
1467
+ CopyArgs a{keep ? Whole(run.W, run.H) : sub, in};
1468
+ if (empty && !keep) a.sub = Sub{0, 0, 0, 0};
1469
+ run.Dispatch(P_COPY, out, src, nil, &a, sizeof a);
1470
+ return out;
1471
+ }
1472
+ id<MTLTexture> from = src;
1473
+ In fromIn = in;
1474
+ id<MTLTexture> made = nil;
1475
+ for (auto& p : passes) {
1476
+ id<MTLTexture> out = run.Take();
1477
+ BlurArgs a{sub, fromIn, p.axis, p.mode, p.lo, p.hi, p.reach, keep ? 1 : 0};
1478
+ run.Dispatch(P_BLUR, out, from, nil, &a, sizeof a,
1479
+ p.weights.empty() ? nullptr : p.weights.data(), p.weights.size() * sizeof(float));
1480
+ if (made) run.Free(made);
1481
+ made = out;
1482
+ from = out;
1483
+ fromIn = In{0, 0};
1484
+ }
1485
+ return made;
1486
+ }
1487
+
1488
+ } // namespace
1489
+
1490
+ // filterGraphPrimitives() -> string[]
1491
+ //
1492
+ // The primitives ctxDrawFilterGraph runs, by element name in lower case:
1493
+ // none where there is no Metal device or its shaders did not compile. The
1494
+ // first call compiles them.
1495
+ static Napi::Value FilterGraphPrimitives(const Napi::CallbackInfo& info) {
1496
+ Napi::Env env = info.Env();
1497
+ Napi::Array out = Napi::Array::New(env);
1498
+ if (!TheGPU()) return out;
1499
+ for (uint32_t i = 0; i < K_COUNT; i++) out.Set(i, Napi::String::New(env, kKindNames[i]));
1500
+ return out;
1501
+ }
1502
+
1503
+ // ctxDrawFilterGraph(dst, src, graph, dx, dy, images?) -> boolean
1504
+ //
1505
+ // `graph` run over `src` (premultiplied, the filter region's size; its
1506
+ // top-left `graph.width` x `graph.height` is read) by Metal, and what it
1507
+ // makes drawn with its corner at (dx, dy), a graph.width x graph.height rect
1508
+ // under the destination's transform, clip, alpha and blend mode, as
1509
+ // ctxDrawSurface draws. `images` are the surfaces feImage primitives name by
1510
+ // index. False where it did not draw: a primitive or a value this does not
1511
+ // take, no Metal device, a texture it could not have; nothing is drawn then.
1512
+ static Napi::Value CtxDrawFilterGraph(const Napi::CallbackInfo& info) {
1513
+ Napi::Env env = info.Env();
1514
+ auto no = [&] { return Napi::Boolean::New(env, false); };
1515
+ CALSurfaceView dst, src;
1516
+ if (info.Length() < 5) return no();
1517
+ if (!CALSurfaceViewOf(info[0], &dst)) return env.Undefined();
1518
+ if (!CALSurfaceViewOf(info[1], &src)) return env.Undefined();
1519
+ double dx, dy;
1520
+ if (!NumberOf(info[3], &dx) || !NumberOf(info[4], &dy)) return no();
1521
+ std::vector<CALSurfaceView> images;
1522
+ if (info.Length() > 5 && info[5].IsObject()) {
1523
+ Napi::Object list = info[5].As<Napi::Object>();
1524
+ double len;
1525
+ if (!NumberOf(list.Get("length"), &len) || len < 0 || len > 256) return no();
1526
+ for (uint32_t i = 0; i < (uint32_t)len; i++) {
1527
+ CALSurfaceView v;
1528
+ if (!CALSurfaceViewOf(list.Get(i), &v)) return env.Undefined();
1529
+ images.push_back(v);
1530
+ }
1531
+ }
1532
+ Graph graph;
1533
+ if (!ReadGraph(info[2], &graph, images.size())) return no();
1534
+ // a graph of nothing makes nothing, drawn
1535
+ if (graph.nodes.empty()) return Napi::Boolean::New(env, true);
1536
+ GPU* g = TheGPU();
1537
+ if (!g) return no();
1538
+ const long W = graph.width, H = graph.height;
1539
+
1540
+ @autoreleasepool {
1541
+ Run run;
1542
+ run.g = g;
1543
+ run.W = W;
1544
+ run.H = H;
1545
+ run.format = graph.wide ? MTLPixelFormatRGBA32Float : MTLPixelFormatRGBA16Float;
1546
+ id<MTLCommandBuffer> cb = [g->queue commandBuffer];
1547
+ run.enc = [cb computeCommandEncoder];
1548
+ bool ok = true;
1549
+
1550
+ id<MTLTexture> srcTex = SurfaceTexture(g, src, W, H, &run.keep);
1551
+ std::vector<id<MTLTexture>> imageTex(images.size());
1552
+ if (!srcTex) ok = false;
1553
+
1554
+ // how many reads each plane has left, the source's as the last slot, so
1555
+ // a result's texture is free again after its last (runFilter's `left`)
1556
+ size_t count = graph.nodes.size();
1557
+ std::vector<int> left(count + 1, 0);
1558
+ auto slot = [&](int ref) { return ref < 0 ? count : (size_t)ref; };
1559
+ for (auto& n : graph.nodes) {
1560
+ for (int r : n.inputs) left[slot(r)]++;
1561
+ }
1562
+ left[count - 1]++;
1563
+ std::vector<Plane> results(count);
1564
+ Plane source{srcTex, false, false, false};
1565
+ auto input = [&](int ref) {
1566
+ Plane p = ref >= 0 ? results[ref] : source;
1567
+ if (ref == kSourceAlpha) p.alpha = true;
1568
+ return p;
1569
+ };
1570
+ auto release = [&](const Node& n) {
1571
+ for (int r : n.inputs) {
1572
+ size_t s = slot(r);
1573
+ // every result is a texture of its own, so its last read frees it
1574
+ if (--left[s] == 0 && r >= 0 && results[r].pooled && results[r].tex) {
1575
+ run.Free(results[r].tex);
1576
+ results[r].tex = nil;
1577
+ }
1578
+ }
1579
+ };
1580
+
1581
+ for (size_t i = 0; ok && i < count; i++) {
1582
+ const Node& n = graph.nodes[i];
1583
+ bool lin = n.linear;
1584
+ Plane made{nil, lin, false, true};
1585
+ std::vector<Plane> ins;
1586
+ for (int r : n.inputs) ins.push_back(input(r));
1587
+ auto plane = [&]() {
1588
+ id<MTLTexture> t = run.Take();
1589
+ if (!t) ok = false;
1590
+ return t;
1591
+ };
1592
+ // a colour of the graph's (premultiplied sRGB) as the primitive's space
1593
+ // has it, straight
1594
+ auto straight = [&](const double* c, float* out3) {
1595
+ double a = c[3];
1596
+ for (int k = 0; k < 3; k++) {
1597
+ double v = a > 0 ? std::min(1.0, c[k] / a) : c[k];
1598
+ out3[k] = (float)(lin ? ToLinear(v) : v);
1599
+ }
1600
+ };
1601
+ switch (n.kind) {
1602
+ case K_FLOOD: {
1603
+ FloodArgs a{n.sub, {0, 0, 0, (float)n.rgba[3]}};
1604
+ straight(n.rgba, a.c);
1605
+ for (int k = 0; k < 3; k++) a.c[k] *= a.c[3];
1606
+ made.tex = plane();
1607
+ if (ok) run.Dispatch(P_FLOOD, made.tex, nil, nil, &a, sizeof a);
1608
+ break;
1609
+ }
1610
+ case K_OFFSET: {
1611
+ OffsetArgs a{n.sub, ReadAs(ins[0], lin), (int32_t)std::lround(n.dx),
1612
+ (int32_t)std::lround(n.dy)};
1613
+ made.tex = plane();
1614
+ if (ok) run.Dispatch(P_OFFSET, made.tex, ins[0].tex, nil, &a, sizeof a);
1615
+ break;
1616
+ }
1617
+ case K_BLUR:
1618
+ made.tex = EncodeBlur(run, ins[0].tex, ReadAs(ins[0], lin), n.sdx, n.sdy, n.sub, false);
1619
+ if (!made.tex) ok = false;
1620
+ break;
1621
+ case K_DROPSHADOW: {
1622
+ SeedArgs sa{ReadAs(ins[0], lin), {0, 0, 0, (float)n.rgba[3]}};
1623
+ straight(n.rgba, sa.c);
1624
+ id<MTLTexture> seed = plane();
1625
+ if (!ok) break;
1626
+ run.Dispatch(P_SEED, seed, ins[0].tex, nil, &sa, sizeof sa);
1627
+ id<MTLTexture> blurred = EncodeBlur(run, seed, In{0, 0}, n.sdx, n.sdy, n.sub, true);
1628
+ run.Free(seed);
1629
+ ShadowArgs a{n.sub, ReadAs(ins[0], lin), (int32_t)std::lround(n.dx),
1630
+ (int32_t)std::lround(n.dy)};
1631
+ made.tex = plane();
1632
+ if (ok && blurred) run.Dispatch(P_CAST, made.tex, ins[0].tex, blurred, &a, sizeof a);
1633
+ if (blurred) run.Free(blurred);
1634
+ break;
1635
+ }
1636
+ case K_COLORMATRIX: {
1637
+ MatrixArgs a{n.sub, ReadAs(ins[0], lin), {0}};
1638
+ memcpy(a.m, n.matrix, sizeof a.m);
1639
+ made.tex = plane();
1640
+ if (ok) run.Dispatch(P_MATRIX, made.tex, ins[0].tex, nil, &a, sizeof a);
1641
+ break;
1642
+ }
1643
+ case K_TRANSFER: {
1644
+ TransferArgs a{};
1645
+ a.sub = n.sub;
1646
+ a.i0 = ReadAs(ins[0], lin);
1647
+ std::vector<float> tables;
1648
+ for (int c = 0; c < 4; c++) {
1649
+ const Transfer& t = n.funcs[c];
1650
+ a.type[c] = t.type;
1651
+ a.off[c] = (int32_t)tables.size();
1652
+ a.n[c] = (int32_t)t.values.size();
1653
+ a.p0[c] = t.p0;
1654
+ a.p1[c] = t.p1;
1655
+ a.p2[c] = t.p2;
1656
+ tables.insert(tables.end(), t.values.begin(), t.values.end());
1657
+ }
1658
+ if (tables.empty()) tables.push_back(0);
1659
+ made.tex = plane();
1660
+ if (ok) {
1661
+ run.Dispatch(P_TRANSFER, made.tex, ins[0].tex, nil, &a, sizeof a, tables.data(),
1662
+ tables.size() * sizeof(float));
1663
+ }
1664
+ break;
1665
+ }
1666
+ case K_COMPOSITE: {
1667
+ CompositeArgs a{n.sub, ReadAs(ins[0], lin), ReadAs(ins[1], lin), n.op,
1668
+ {n.k[0], n.k[1], n.k[2], n.k[3]}};
1669
+ made.tex = plane();
1670
+ if (ok) run.Dispatch(P_COMPOSITE, made.tex, ins[0].tex, ins[1].tex, &a, sizeof a);
1671
+ break;
1672
+ }
1673
+ case K_BLEND: {
1674
+ BlendArgs a{n.sub, ReadAs(ins[0], lin), ReadAs(ins[1], lin), n.mode};
1675
+ made.tex = plane();
1676
+ if (ok) run.Dispatch(P_BLEND, made.tex, ins[0].tex, ins[1].tex, &a, sizeof a);
1677
+ break;
1678
+ }
1679
+ case K_MERGE: {
1680
+ if (ins.empty()) {
1681
+ FloodArgs a{Sub{0, 0, 0, 0}, {0, 0, 0, 0}};
1682
+ made.tex = plane();
1683
+ if (ok) run.Dispatch(P_FLOOD, made.tex, nil, nil, &a, sizeof a);
1684
+ break;
1685
+ }
1686
+ id<MTLTexture> acc = nil;
1687
+ for (size_t k = 0; ok && k < ins.size(); k++) {
1688
+ id<MTLTexture> out = plane();
1689
+ if (!ok) break;
1690
+ MergeArgs a{n.sub, ReadAs(ins[k], lin), k == 0 ? 1 : 0};
1691
+ run.Dispatch(P_MERGE, out, ins[k].tex, acc ? acc : ins[k].tex, &a, sizeof a);
1692
+ if (acc) run.Free(acc);
1693
+ acc = out;
1694
+ }
1695
+ made.tex = acc;
1696
+ break;
1697
+ }
1698
+ case K_TILE: {
1699
+ // what is tiled is the input's subregion, the region's for a source
1700
+ int r = n.inputs[0];
1701
+ Sub from = r >= 0 ? graph.nodes[r].sub : Whole(W, H);
1702
+ TileArgs a{n.sub, ReadAs(ins[0], lin), from.x0, from.y0, from.x1 - from.x0,
1703
+ from.y1 - from.y0};
1704
+ made.tex = plane();
1705
+ if (ok) run.Dispatch(P_TILE, made.tex, ins[0].tex, nil, &a, sizeof a);
1706
+ break;
1707
+ }
1708
+ case K_MORPHOLOGY: {
1709
+ // a negative radius is transparent, one of nothing leaves it as it
1710
+ // is (9.17, as Chrome reads it)
1711
+ if (n.rx < 0 || n.ry < 0) {
1712
+ FloodArgs a{Sub{0, 0, 0, 0}, {0, 0, 0, 0}};
1713
+ made.tex = plane();
1714
+ if (ok) run.Dispatch(P_FLOOD, made.tex, nil, nil, &a, sizeof a);
1715
+ break;
1716
+ }
1717
+ if (n.rx == 0 && n.ry == 0) {
1718
+ CopyArgs a{n.sub, ReadAs(ins[0], lin)};
1719
+ made.tex = plane();
1720
+ if (ok) run.Dispatch(P_COPY, made.tex, ins[0].tex, nil, &a, sizeof a);
1721
+ break;
1722
+ }
1723
+ id<MTLTexture> across = plane();
1724
+ if (!ok) break;
1725
+ MorphArgs h{Whole(W, H), ReadAs(ins[0], lin), 0, (int32_t)std::lround(n.rx),
1726
+ n.dilate ? 1 : 0};
1727
+ run.Dispatch(P_MORPH, across, ins[0].tex, nil, &h, sizeof h);
1728
+ MorphArgs v{n.sub, In{0, 0}, 1, (int32_t)std::lround(n.ry), n.dilate ? 1 : 0};
1729
+ made.tex = plane();
1730
+ if (ok) run.Dispatch(P_MORPH, made.tex, across, nil, &v, sizeof v);
1731
+ run.Free(across);
1732
+ break;
1733
+ }
1734
+ case K_DISPLACE: {
1735
+ // `in` is moved in its own space, and the result is in it (9.13)
1736
+ made.linear = ins[0].alpha ? false : ins[0].linear;
1737
+ made.tex = plane();
1738
+ if (!ok) break;
1739
+ if (n.scaleX == 0 && n.scaleY == 0) {
1740
+ CopyArgs a{n.sub, ReadAs(ins[0], lin, true)};
1741
+ run.Dispatch(P_COPY, made.tex, ins[0].tex, nil, &a, sizeof a);
1742
+ break;
1743
+ }
1744
+ DisplaceArgs a{n.sub, ReadAs(ins[0], lin, true), ReadAs(ins[1], lin),
1745
+ (float)n.scaleX, (float)n.scaleY, n.xc, n.yc};
1746
+ run.Dispatch(P_DISPLACE, made.tex, ins[0].tex, ins[1].tex, &a, sizeof a);
1747
+ break;
1748
+ }
1749
+ case K_CONVOLVE: {
1750
+ ConvolveArgs a{n.sub, ReadAs(ins[0], lin), n.ox, n.oy, n.tx, n.ty, n.edge,
1751
+ n.preserveAlpha ? 1 : 0, (float)n.divisor, (float)n.bias};
1752
+ made.tex = plane();
1753
+ if (ok) {
1754
+ run.Dispatch(P_CONVOLVE, made.tex, ins[0].tex, nil, &a, sizeof a, n.kernel.data(),
1755
+ n.kernel.size() * sizeof(float));
1756
+ }
1757
+ break;
1758
+ }
1759
+ case K_DIFFUSE:
1760
+ case K_SPECULAR: {
1761
+ LightArgs a{};
1762
+ a.sub = n.sub;
1763
+ a.i0 = ReadAs(ins[0], lin);
1764
+ a.specular = n.kind == K_SPECULAR ? 1 : 0;
1765
+ a.kind = n.light.kind;
1766
+ straight(n.rgba, a.c);
1767
+ a.ss = (float)n.surfaceScale;
1768
+ a.kd = (float)n.kd;
1769
+ a.ks = (float)n.ks;
1770
+ a.exp = (float)n.exp;
1771
+ const Light& l = n.light;
1772
+ if (l.kind == 1) {
1773
+ double az = l.azimuth * M_PI / 180, el = l.elevation * M_PI / 180;
1774
+ a.l[0] = (float)(std::cos(az) * std::cos(el));
1775
+ a.l[1] = (float)(std::sin(az) * std::cos(el));
1776
+ a.l[2] = (float)std::sin(el);
1777
+ } else {
1778
+ a.l[0] = (float)l.x;
1779
+ a.l[1] = (float)l.y;
1780
+ a.l[2] = (float)l.z;
1781
+ }
1782
+ if (l.kind == 3) {
1783
+ double d[3] = {l.px - l.x, l.py - l.y, l.pz - l.z};
1784
+ double len = std::sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
1785
+ if (!(len > 0)) len = 1;
1786
+ for (int k = 0; k < 3; k++) a.d[k] = (float)(d[k] / len);
1787
+ }
1788
+ a.cosCone = l.hasCone
1789
+ ? (float)std::cos(std::min(90.0, std::fabs(l.cone)) * M_PI / 180)
1790
+ : -2.0f;
1791
+ a.spotExp = (float)l.exponent;
1792
+ made.tex = plane();
1793
+ if (ok) run.Dispatch(P_LIGHTING, made.tex, ins[0].tex, nil, &a, sizeof a);
1794
+ break;
1795
+ }
1796
+ case K_TURBULENCE: {
1797
+ TurbulenceArgs a{};
1798
+ a.sub = n.sub;
1799
+ const double* m = graph.matrix;
1800
+ double det = m[0] * m[3] - m[1] * m[2];
1801
+ made.tex = plane();
1802
+ if (!ok) break;
1803
+ if (!det || n.octaves == 0) {
1804
+ FloodArgs f{Sub{0, 0, 0, 0}, {0, 0, 0, 0}};
1805
+ run.Dispatch(P_FLOOD, made.tex, nil, nil, &f, sizeof f);
1806
+ break;
1807
+ }
1808
+ double inv[6] = {m[3] / det, -m[1] / det, -m[2] / det, m[0] / det,
1809
+ (m[2] * m[5] - m[3] * m[4]) / det,
1810
+ (m[1] * m[4] - m[0] * m[5]) / det};
1811
+ // the noise repeats every 256 lattice cells of its first octave,
1812
+ // and so of every octave: the translation brought within a period,
1813
+ // in double, so float32 keeps its bits for the fraction
1814
+ if (n.bx > 0) {
1815
+ double period = 256 / n.bx;
1816
+ inv[4] = std::fmod(inv[4], period);
1817
+ }
1818
+ if (n.by > 0) {
1819
+ double period = 256 / n.by;
1820
+ inv[5] = std::fmod(inv[5], period);
1821
+ }
1822
+ for (int k = 0; k < 6; k++) a.m[k] = (float)inv[k];
1823
+ a.bx = (float)n.bx;
1824
+ a.by = (float)n.by;
1825
+ a.octaves = n.octaves;
1826
+ a.fractal = n.fractal ? 1 : 0;
1827
+ run.Dispatch(P_TURBULENCE, made.tex, nil, nil, &a, sizeof a, n.sel.data(),
1828
+ n.sel.size() * sizeof(int32_t), n.grad.data(),
1829
+ n.grad.size() * sizeof(float));
1830
+ break;
1831
+ }
1832
+ case K_IMAGE: {
1833
+ if (!imageTex[n.image]) {
1834
+ imageTex[n.image] = SurfaceTexture(g, images[n.image], W, H, &run.keep);
1835
+ }
1836
+ if (!imageTex[n.image]) {
1837
+ ok = false;
1838
+ break;
1839
+ }
1840
+ // what an feImage shows is sRGB, whatever its primitive's space
1841
+ made.linear = false;
1842
+ CopyArgs a{n.sub, In{0, 0}};
1843
+ made.tex = plane();
1844
+ if (ok) run.Dispatch(P_COPY, made.tex, imageTex[n.image], nil, &a, sizeof a);
1845
+ break;
1846
+ }
1847
+ default:
1848
+ ok = false;
1849
+ }
1850
+ if (!made.tex) ok = false;
1851
+ results[i] = made;
1852
+ release(n);
1853
+ }
1854
+
1855
+ id<MTLBuffer> outBuf = nil;
1856
+ size_t stride = (size_t)W;
1857
+ size_t bytes = stride * 4 * (size_t)H;
1858
+ if (ok) {
1859
+ {
1860
+ std::lock_guard<std::mutex> lock(gPoolLock);
1861
+ if (gSpareOut && gSpareOut.length >= bytes && gSpareOut.length <= bytes * 2) {
1862
+ outBuf = gSpareOut;
1863
+ gSpareOut = nil;
1864
+ }
1865
+ }
1866
+ if (!outBuf) {
1867
+ outBuf = [g->device newBufferWithLength:bytes options:MTLResourceStorageModeShared];
1868
+ }
1869
+ if (!outBuf) ok = false;
1870
+ }
1871
+ if (ok) {
1872
+ const Plane& last = results[count - 1];
1873
+ FinalArgs a{ReadAs(last, false), (int32_t)W, (int32_t)H, (int32_t)stride};
1874
+ [run.enc setComputePipelineState:g->pipes[P_FINAL]];
1875
+ [run.enc setTexture:last.tex atIndex:1];
1876
+ [run.enc setBytes:&a length:sizeof a atIndex:0];
1877
+ [run.enc setBuffer:outBuf offset:0 atIndex:1];
1878
+ id<MTLComputePipelineState> ps = g->pipes[P_FINAL];
1879
+ NSUInteger tw = ps.threadExecutionWidth;
1880
+ NSUInteger th = std::max<NSUInteger>(1, ps.maxTotalThreadsPerThreadgroup / tw);
1881
+ [run.enc dispatchThreadgroups:MTLSizeMake((W + tw - 1) / tw, (H + th - 1) / th, 1)
1882
+ threadsPerThreadgroup:MTLSizeMake(tw, th, 1)];
1883
+ }
1884
+ [run.enc endEncoding];
1885
+ if (ok) {
1886
+ [cb commit];
1887
+ [cb waitUntilCompleted];
1888
+ if (cb.status != MTLCommandBufferStatusCompleted) ok = false;
1889
+ }
1890
+ GiveBack(run.held, W, H, run.format);
1891
+ if (!ok) return no();
1892
+
1893
+ // the bytes as an image, drawn as ctxDrawSurface draws a surface; the
1894
+ // buffer goes back to be the next run's once the image lets it go
1895
+ CGDataProviderRef provider = CGDataProviderCreateWithData(
1896
+ (void*)CFBridgingRetain(outBuf), outBuf.contents, bytes,
1897
+ [](void* info, const void*, size_t) {
1898
+ id<MTLBuffer> b = (id<MTLBuffer>)CFBridgingRelease(info);
1899
+ std::lock_guard<std::mutex> lock(gPoolLock);
1900
+ if (!gSpareOut || gSpareOut.length < b.length) gSpareOut = b;
1901
+ });
1902
+ CGColorSpaceRef cs = CGBitmapContextGetColorSpace(src.ctx);
1903
+ CGColorSpaceRef srgb = nullptr;
1904
+ if (!cs) cs = srgb = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
1905
+ CGImageRef image = CGImageCreate(
1906
+ (size_t)W, (size_t)H, 8, 32, stride * 4, cs,
1907
+ kCGImageAlphaPremultipliedFirst | (CGBitmapInfo)kCGBitmapByteOrder32Host, provider,
1908
+ nullptr, false, kCGRenderingIntentDefault);
1909
+ if (srgb) CGColorSpaceRelease(srgb);
1910
+ CGDataProviderRelease(provider);
1911
+ if (!image) return no();
1912
+ CGContextSaveGState(dst.ctx);
1913
+ // the base CTM is flipped; flip back around the destination rect so the
1914
+ // image lands upright
1915
+ CGContextTranslateCTM(dst.ctx, dx, dy + (double)H);
1916
+ CGContextScaleCTM(dst.ctx, 1, -1);
1917
+ CGContextDrawImage(dst.ctx, CGRectMake(0, 0, (double)W, (double)H), image);
1918
+ CGContextRestoreGState(dst.ctx);
1919
+ CGImageRelease(image);
1920
+ }
1921
+ return Napi::Boolean::New(env, true);
1922
+ }
1923
+
1924
+ void InitFilterGraph(Napi::Env env, Napi::Object exports) {
1925
+ exports.Set("filterGraphPrimitives", Napi::Function::New(env, FilterGraphPrimitives));
1926
+ exports.Set("ctxDrawFilterGraph", Napi::Function::New(env, CtxDrawFilterGraph));
1927
+ }