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