@rosepetal/node-red-contrib-image-tools 1.6.3 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/.claude/rules/node-implementation-template.md +1 -1
  2. package/README.md +2 -0
  3. package/node-red-contrib-image-tools/lib/bmp-decode.js +18 -68
  4. package/node-red-contrib-image-tools/lib/cpp-bridge.js +202 -104
  5. package/node-red-contrib-image-tools/lib/node-utils.js +78 -78
  6. package/node-red-contrib-image-tools/nodes/blend/add-bbs.html +11 -4
  7. package/node-red-contrib-image-tools/nodes/blend/add-mask.html +11 -4
  8. package/node-red-contrib-image-tools/nodes/blend/add-masks.html +11 -4
  9. package/node-red-contrib-image-tools/nodes/blend/blend.html +11 -4
  10. package/node-red-contrib-image-tools/nodes/io/folder-in.js +98 -46
  11. package/node-red-contrib-image-tools/nodes/io/image-in.js +3 -4
  12. package/node-red-contrib-image-tools/nodes/io/image-out.html +11 -4
  13. package/node-red-contrib-image-tools/nodes/io/image-out.js +93 -146
  14. package/node-red-contrib-image-tools/nodes/mix/advanced-mosaic.html +11 -4
  15. package/node-red-contrib-image-tools/nodes/mix/concat.html +11 -4
  16. package/node-red-contrib-image-tools/nodes/mix/mosaic.html +11 -4
  17. package/node-red-contrib-image-tools/nodes/specialized/cropBB.js +3 -3
  18. package/node-red-contrib-image-tools/nodes/specialized/heat-diff.js +3 -3
  19. package/node-red-contrib-image-tools/nodes/specialized/image-align.html +3 -2
  20. package/node-red-contrib-image-tools/nodes/specialized/image-align.js +3 -3
  21. package/node-red-contrib-image-tools/nodes/transform/color-convert.js +3 -3
  22. package/node-red-contrib-image-tools/nodes/transform/crop.html +11 -4
  23. package/node-red-contrib-image-tools/nodes/transform/crop.js +3 -3
  24. package/node-red-contrib-image-tools/nodes/transform/filter.html +11 -4
  25. package/node-red-contrib-image-tools/nodes/transform/filter.js +3 -3
  26. package/node-red-contrib-image-tools/nodes/transform/padding.html +11 -4
  27. package/node-red-contrib-image-tools/nodes/transform/padding.js +3 -3
  28. package/node-red-contrib-image-tools/nodes/transform/resize.html +3 -3
  29. package/node-red-contrib-image-tools/nodes/transform/resize.js +3 -3
  30. package/node-red-contrib-image-tools/nodes/transform/rotate.html +11 -4
  31. package/node-red-contrib-image-tools/nodes/transform/rotate.js +3 -3
  32. package/npm/darwin-arm64/package.json +1 -1
  33. package/npm/darwin-x64/package.json +1 -1
  34. package/npm/linux-arm64/package.json +1 -1
  35. package/npm/linux-x64/package.json +1 -1
  36. package/npm/linuxmusl-x64/package.json +1 -1
  37. package/npm/win32-x64/package.json +1 -1
  38. package/package.json +6 -6
  39. package/rosepetal-image-engine/binding.gyp +2 -1
  40. package/rosepetal-image-engine/src/add-bbs.cpp +123 -123
  41. package/rosepetal-image-engine/src/add-mask.cpp +30 -15
  42. package/rosepetal-image-engine/src/add-masks.cpp +145 -102
  43. package/rosepetal-image-engine/src/advanced-mosaic.cpp +200 -129
  44. package/rosepetal-image-engine/src/blend.cpp +34 -20
  45. package/rosepetal-image-engine/src/codec.cpp +157 -0
  46. package/rosepetal-image-engine/src/color-convert.cpp +22 -19
  47. package/rosepetal-image-engine/src/concat.cpp +38 -43
  48. package/rosepetal-image-engine/src/crop.cpp +23 -26
  49. package/rosepetal-image-engine/src/draw.cpp +33 -10
  50. package/rosepetal-image-engine/src/filter.cpp +22 -26
  51. package/rosepetal-image-engine/src/heat-diff.cpp +31 -8
  52. package/rosepetal-image-engine/src/image-align.cpp +36 -32
  53. package/rosepetal-image-engine/src/main.cpp +4 -0
  54. package/rosepetal-image-engine/src/mosaic.cpp +31 -40
  55. package/rosepetal-image-engine/src/padding.cpp +30 -29
  56. package/rosepetal-image-engine/src/resize.cpp +20 -25
  57. package/rosepetal-image-engine/src/rotate.cpp +22 -23
  58. package/rosepetal-image-engine/src/utils.h +243 -144
  59. package/scripts/dual-register.js +32 -25
  60. package/scripts/sync-version.js +58 -41
@@ -8,117 +8,208 @@
8
8
  #include <vector>
9
9
  #include <string>
10
10
  #include <chrono>
11
+ #include <stdexcept>
11
12
 
12
13
  /**
13
- * Converts JS input to cv::Mat supporting:
14
- * - Image object: {data, width, height, channels, colorSpace, dtype}
15
- * - Buffer: Raw image file data (JPEG/PNG/WebP)
14
+ * ImageSource — a JS image input captured on the JS thread, decoded on the
15
+ * worker thread.
16
+ *
17
+ * Supported inputs:
18
+ * - Raw image object {data, width, height, channels, colorSpace, dtype}:
19
+ * the cv::Mat is a zero-copy view over the JS Buffer. `mat` and
20
+ * `colorSpace` are valid immediately after CaptureImage().
21
+ * - Encoded Buffer (JPEG/PNG/WebP/BMP...): only the pointer/length are
22
+ * captured. Nothing is decoded until Materialize() is called, which MUST
23
+ * happen inside AsyncWorker::Execute() so cv::imdecode never blocks the
24
+ * Node.js event loop.
25
+ *
26
+ * A persistent reference to the JS Buffer keeps its memory alive for the
27
+ * whole lifetime of the worker (the reference is released on the JS thread
28
+ * when the worker is destroyed).
16
29
  */
17
- inline cv::Mat ConvertToMat(const Napi::Value& input) {
30
+ struct ImageSource {
31
+ cv::Mat mat; // raw: zero-copy view; encoded: filled by Materialize()
32
+ std::string colorSpace; // "GRAY" | "RGB" | "RGBA" | "BGR" | "BGRA"
33
+ bool encoded = false;
34
+ const uchar* encPtr = nullptr;
35
+ size_t encLen = 0;
36
+ Napi::ObjectReference ref; // keeps the JS Buffer alive (move-only)
37
+
38
+ ImageSource() = default;
39
+ ImageSource(ImageSource&&) = default;
40
+ ImageSource& operator=(ImageSource&&) = default;
41
+ ImageSource(const ImageSource&) = delete;
42
+ ImageSource& operator=(const ImageSource&) = delete;
43
+
44
+ bool IsEncoded() const { return encoded; }
45
+ bool Ready() const { return !mat.empty(); }
46
+
47
+ // Worker-thread only. Decodes an encoded buffer (no-op for raw inputs).
48
+ // Throws std::runtime_error if the buffer cannot be decoded.
49
+ void Materialize() {
50
+ if (!encoded || !mat.empty()) return;
51
+ if (encPtr == nullptr || encLen == 0) {
52
+ throw std::runtime_error("Failed to decode image buffer: empty buffer.");
53
+ }
54
+ cv::Mat tmp(1, static_cast<int>(encLen), CV_8UC1, const_cast<uchar*>(encPtr));
55
+ cv::Mat img = cv::imdecode(tmp, cv::IMREAD_UNCHANGED);
56
+ if (img.empty()) {
57
+ throw std::runtime_error("Failed to decode image buffer.");
58
+ }
59
+ // imdecode returns BGR/BGRA regardless of file format; the toolkit
60
+ // labels decoded buffers as RGB/RGBA so we swap once here.
61
+ if (img.channels() == 3) cv::cvtColor(img, img, cv::COLOR_BGR2RGB);
62
+ else if (img.channels() == 4) cv::cvtColor(img, img, cv::COLOR_BGRA2RGBA);
63
+ mat = img;
64
+ colorSpace = (img.channels() == 4) ? "RGBA" : (img.channels() == 3) ? "RGB" : "GRAY";
65
+ }
66
+ };
67
+
68
+ // Resolves the pointer/length of a Buffer / TypedArray / ArrayBuffer value.
69
+ inline bool ResolveBytes(const Napi::Value& v, const uchar*& ptr, size_t& len) {
70
+ if (v.IsBuffer()) {
71
+ auto b = v.As<Napi::Buffer<uint8_t>>();
72
+ ptr = b.Data(); len = b.Length();
73
+ return true;
74
+ }
75
+ if (v.IsTypedArray()) {
76
+ auto ta = v.As<Napi::TypedArray>();
77
+ auto ab = ta.ArrayBuffer();
78
+ ptr = static_cast<const uchar*>(ab.Data()) + ta.ByteOffset();
79
+ len = ta.ByteLength();
80
+ return true;
81
+ }
82
+ if (v.IsArrayBuffer()) {
83
+ auto ab = v.As<Napi::ArrayBuffer>();
84
+ ptr = static_cast<const uchar*>(ab.Data()); len = ab.ByteLength();
85
+ return true;
86
+ }
87
+ return false;
88
+ }
89
+
90
+ /**
91
+ * Captures a JS image input on the JS thread. Performs NO decoding and NO
92
+ * pixel work — only reads metadata and takes a persistent reference.
93
+ * Throws Napi::Error on invalid input.
94
+ */
95
+ inline ImageSource CaptureImage(const Napi::Value& input) {
18
96
  Napi::Env env = input.Env();
97
+ ImageSource src;
19
98
 
20
99
  // --- 1. Raw image object -------------------------
21
- if (input.IsObject() && !input.IsBuffer()) {
100
+ if (input.IsObject() && !input.IsBuffer() && !input.IsTypedArray() && !input.IsArrayBuffer()) {
22
101
  Napi::Object obj = input.As<Napi::Object>();
23
102
  if (obj.Has("data") && obj.Has("width") && obj.Has("height")) {
103
+ Napi::Value dataVal = obj.Get("data");
104
+ const uchar* ptr = nullptr; size_t len = 0;
105
+ if (!ResolveBytes(dataVal, ptr, len)) {
106
+ throw Napi::Error::New(env, "Image data must be a Buffer or TypedArray");
107
+ }
24
108
 
25
- auto dataBuf = obj.Get("data").As<Napi::Buffer<uint8_t>>();
26
-
27
109
  int width = obj.Get("width").As<Napi::Number>().Int32Value();
28
110
  int height = obj.Get("height").As<Napi::Number>().Int32Value();
111
+ if (width <= 0 || height <= 0) {
112
+ throw Napi::Error::New(env, "Invalid image dimensions");
113
+ }
29
114
 
30
115
  // Determine channel count and color space
31
116
  int channels = 3; // default
32
- std::string colorSpace = "RGB"; // default
33
-
117
+ std::string colorSpace;
118
+
34
119
  if (obj.Has("channels")) {
35
120
  auto channelsVal = obj.Get("channels");
36
-
37
121
  if (channelsVal.IsNumber()) {
38
122
  channels = channelsVal.As<Napi::Number>().Int32Value();
39
-
40
- // Get colorSpace if available
41
- if (obj.Has("colorSpace")) {
42
- colorSpace = obj.Get("colorSpace").As<Napi::String>().Utf8Value();
43
- } else {
44
- // Default colorSpace based on channels
45
- switch (channels) {
46
- case 1: colorSpace = "GRAY"; break;
47
- case 3: colorSpace = "RGB"; break;
48
- case 4: colorSpace = "RGBA"; break;
49
- default:
50
- throw Napi::Error::New(env, "Unsupported channel count: " + std::to_string(channels));
51
- }
52
- }
53
123
  } else {
54
124
  throw Napi::Error::New(env, "Channels must be a number");
55
125
  }
56
126
  }
127
+ if (obj.Has("colorSpace") && obj.Get("colorSpace").IsString()) {
128
+ colorSpace = obj.Get("colorSpace").As<Napi::String>().Utf8Value();
129
+ } else {
130
+ switch (channels) {
131
+ case 1: colorSpace = "GRAY"; break;
132
+ case 3: colorSpace = "RGB"; break;
133
+ case 4: colorSpace = "RGBA"; break;
134
+ default:
135
+ throw Napi::Error::New(env, "Unsupported channel count: " + std::to_string(channels));
136
+ }
137
+ }
57
138
 
58
139
  // Determine OpenCV type based on dtype and channels
59
140
  int cvType = CV_8UC3; // default
60
-
61
- if (obj.Has("dtype")) {
62
- std::string dtype = obj.Get("dtype").As<Napi::String>().Utf8Value();
63
- if (dtype == "uint8") {
64
- switch (channels) {
65
- case 1: cvType = CV_8UC1; break;
66
- case 3: cvType = CV_8UC3; break;
67
- case 4: cvType = CV_8UC4; break;
68
- default: throw Napi::Error::New(env, "Unsupported channel count for uint8: " + std::to_string(channels));
69
- }
70
- } else if (dtype == "uint16") {
71
- switch (channels) {
72
- case 1: cvType = CV_16UC1; break;
73
- case 3: cvType = CV_16UC3; break;
74
- case 4: cvType = CV_16UC4; break;
75
- default: throw Napi::Error::New(env, "Unsupported channel count for uint16: " + std::to_string(channels));
76
- }
77
- } else if (dtype == "float32") {
78
- switch (channels) {
79
- case 1: cvType = CV_32FC1; break;
80
- case 3: cvType = CV_32FC3; break;
81
- case 4: cvType = CV_32FC4; break;
82
- default: throw Napi::Error::New(env, "Unsupported channel count for float32: " + std::to_string(channels));
83
- }
84
- } else {
85
- throw Napi::Error::New(env, "Unsupported dtype: " + dtype);
86
- }
87
- } else {
88
- // Default uint8 handling
141
+ size_t elemBytes = 1;
142
+ std::string dtype = "uint8";
143
+ if (obj.Has("dtype") && obj.Get("dtype").IsString()) {
144
+ dtype = obj.Get("dtype").As<Napi::String>().Utf8Value();
145
+ }
146
+ if (dtype == "uint8") {
147
+ elemBytes = 1;
89
148
  switch (channels) {
90
149
  case 1: cvType = CV_8UC1; break;
91
150
  case 3: cvType = CV_8UC3; break;
92
151
  case 4: cvType = CV_8UC4; break;
93
- default: throw Napi::Error::New(env, "Unsupported channel count: " + std::to_string(channels));
152
+ default: throw Napi::Error::New(env, "Unsupported channel count for uint8: " + std::to_string(channels));
153
+ }
154
+ } else if (dtype == "uint16") {
155
+ elemBytes = 2;
156
+ switch (channels) {
157
+ case 1: cvType = CV_16UC1; break;
158
+ case 3: cvType = CV_16UC3; break;
159
+ case 4: cvType = CV_16UC4; break;
160
+ default: throw Napi::Error::New(env, "Unsupported channel count for uint16: " + std::to_string(channels));
94
161
  }
162
+ } else if (dtype == "float32") {
163
+ elemBytes = 4;
164
+ switch (channels) {
165
+ case 1: cvType = CV_32FC1; break;
166
+ case 3: cvType = CV_32FC3; break;
167
+ case 4: cvType = CV_32FC4; break;
168
+ default: throw Napi::Error::New(env, "Unsupported channel count for float32: " + std::to_string(channels));
169
+ }
170
+ } else {
171
+ throw Napi::Error::New(env, "Unsupported dtype: " + dtype);
172
+ }
173
+
174
+ const size_t expected = static_cast<size_t>(width) * static_cast<size_t>(height) *
175
+ static_cast<size_t>(channels) * elemBytes;
176
+ if (len < expected) {
177
+ throw Napi::Error::New(env,
178
+ "Image data too small: expected " + std::to_string(expected) +
179
+ " bytes, got " + std::to_string(len));
95
180
  }
96
181
 
97
- return cv::Mat(height, width, cvType, dataBuf.Data());
182
+ src.mat = cv::Mat(height, width, cvType, const_cast<uchar*>(ptr));
183
+ src.colorSpace = colorSpace;
184
+ src.ref = Napi::Persistent(dataVal.As<Napi::Object>());
185
+ return src;
98
186
  }
99
187
  }
100
188
 
101
- // --- 2. Direct Buffer (JPEG/PNG/WebP file data) -------------------------
102
- if (input.IsBuffer()) {
103
- auto buf = input.As<Napi::Buffer<uint8_t>>();
104
- cv::Mat tmp(1, buf.Length(), CV_8UC1, buf.Data());
105
- cv::Mat img = cv::imdecode(tmp, cv::IMREAD_UNCHANGED);
106
-
107
- if (img.empty()) {
108
- throw Napi::Error::New(env, "Failed to decode image buffer.");
189
+ // --- 2. Encoded bytes (JPEG/PNG/WebP/BMP file data) -------------------------
190
+ {
191
+ const uchar* ptr = nullptr; size_t len = 0;
192
+ if (ResolveBytes(input, ptr, len)) {
193
+ src.encoded = true;
194
+ src.encPtr = ptr;
195
+ src.encLen = len;
196
+ src.ref = Napi::Persistent(input.As<Napi::Object>());
197
+ return src;
109
198
  }
110
-
111
- // imdecode returns BGR/BGRA regardless of file format, assume input is RGB/RGBA
112
- if (img.channels() == 3) cv::cvtColor(img, img, cv::COLOR_BGR2RGB);
113
- else if (img.channels() == 4) cv::cvtColor(img, img, cv::COLOR_BGRA2RGBA);
114
- return img; // RGB/RGBA/GRAY, matching the colorSpace labels nodes assign
115
199
  }
116
200
 
117
201
  throw Napi::Error::New(env,
118
202
  "Invalid input: Expected Buffer or image object with {data, width, height}.");
119
203
  }
120
204
 
121
-
205
+ // Worker-thread helper: makes sure a result Mat owns contiguous memory so
206
+ // MatToRawJS() can hand it to JS with zero copies on the JS thread.
207
+ inline void FinalizeForOutput(cv::Mat& m) {
208
+ if (m.empty()) return;
209
+ if (!m.isContinuous() || m.u == nullptr) {
210
+ m = m.clone();
211
+ }
212
+ }
122
213
 
123
214
  // Convierte a BGR 3-canales para JPEG si hace falta
124
215
  inline cv::Mat ToBgrForJpg(const cv::Mat& src, const std::string& order) {
@@ -137,7 +228,8 @@ enum class ImageFormat {
137
228
  RAW = 0,
138
229
  JPG = 1,
139
230
  PNG = 2,
140
- WEBP = 3
231
+ WEBP = 3,
232
+ BMP = 4
141
233
  };
142
234
 
143
235
  // Convert format string to enum
@@ -145,12 +237,13 @@ inline ImageFormat ParseImageFormat(const std::string& format) {
145
237
  if (format == "jpg" || format == "jpeg") return ImageFormat::JPG;
146
238
  if (format == "png") return ImageFormat::PNG;
147
239
  if (format == "webp") return ImageFormat::WEBP;
240
+ if (format == "bmp") return ImageFormat::BMP;
148
241
  return ImageFormat::RAW;
149
242
  }
150
243
 
151
244
  // Convert to the correct channel order for OpenCV's encoders.
152
245
  // - JPG: requires BGR (alpha is dropped)
153
- // - PNG/WebP: support BGR/BGRA (alpha preserved for *A variants)
246
+ // - PNG/WebP/BMP: support BGR/BGRA (alpha preserved for *A variants)
154
247
  inline cv::Mat PrepareForEncoding(const cv::Mat& src,
155
248
  const std::string& order,
156
249
  const std::string& outputFormat)
@@ -160,7 +253,7 @@ inline cv::Mat PrepareForEncoding(const cv::Mat& src,
160
253
  return ToBgrForJpg(src, order);
161
254
  }
162
255
 
163
- // PNG/WebP: keep alpha when present
256
+ // PNG/WebP/BMP: keep alpha when present
164
257
  if (src.channels() == 1 || order == "BGR" || order == "BGRA" || order == "GRAY") {
165
258
  return src;
166
259
  }
@@ -234,6 +327,12 @@ inline double EncodeToFormat(const cv::Mat& src,
234
327
  cv::imencode(".webp", src, out, params);
235
328
  break;
236
329
  }
330
+ case ImageFormat::BMP: {
331
+ // Uncompressed BI_RGB; 8-bit gray (palette), 24-bit BGR or 32-bit BGRA.
332
+ out.reserve(src.total() * src.elemSize() + 1078);
333
+ cv::imencode(".bmp", src, out);
334
+ break;
335
+ }
237
336
  default:
238
337
  // RAW format - should not reach here, handled at higher level
239
338
  throw std::runtime_error("RAW format encoding not supported");
@@ -333,27 +432,6 @@ t.Set("encodeMs", Napi::Number::New(env, encodeMs));
333
432
  return t;
334
433
  }
335
434
 
336
- // Helper function to detect channel format for individual images (shared between blend and concat)
337
- inline std::string DetectChannelFormatShared(const Napi::Value& jsImg, const cv::Mat& mat) {
338
- if (jsImg.IsObject() && !jsImg.IsBuffer()) {
339
- Napi::Object obj = jsImg.As<Napi::Object>();
340
-
341
- // Check for colorSpace field first
342
- if (obj.Has("colorSpace")) {
343
- return obj.Get("colorSpace").As<Napi::String>().Utf8Value();
344
- }
345
- // Default based on channel count
346
- else {
347
- const int channels = mat.channels();
348
- return (channels == 4) ? "RGBA" : (channels == 3) ? "RGB" : "GRAY";
349
- }
350
- } else {
351
- // Buffer input - determine from OpenCV Mat
352
- const int channels = mat.channels();
353
- return (channels == 4) ? "RGBA" : (channels == 3) ? "RGB" : "GRAY";
354
- }
355
- }
356
-
357
435
  // Helper function to convert image to target channel format (shared between blend and concat)
358
436
  inline cv::Mat ConvertToTargetFormatShared(const cv::Mat& src, const std::string& srcFormat, const std::string& targetFormat) {
359
437
  if (srcFormat == targetFormat) {
@@ -443,32 +521,31 @@ inline cv::Mat removeColorBackground(const cv::Mat& src, const cv::Scalar& bgCol
443
521
  cv::cvtColor(bg_mat, hsv_bg, cv::COLOR_BGR2HSV);
444
522
  cv::Vec3b target_hsv = hsv_bg.at<cv::Vec3b>(0, 0);
445
523
 
446
- // Create mask based on color distance in HSV space
447
- cv::Mat mask = cv::Mat::zeros(hsv_src.size(), CV_8UC1);
448
-
449
524
  // Calculate tolerance thresholds
450
525
  double h_tolerance = tolerance * 180; // Hue range: 0-180
451
526
  double s_tolerance = tolerance * 255; // Saturation range: 0-255
452
527
  double v_tolerance = tolerance * 255; // Value range: 0-255
453
-
454
- for (int y = 0; y < hsv_src.rows; y++) {
455
- for (int x = 0; x < hsv_src.cols; x++) {
456
- cv::Vec3b pixel_hsv = hsv_src.at<cv::Vec3b>(y, x);
457
-
458
- // Calculate distance in HSV space
459
- double h_diff = std::abs(pixel_hsv[0] - target_hsv[0]);
460
- double s_diff = std::abs(pixel_hsv[1] - target_hsv[1]);
461
- double v_diff = std::abs(pixel_hsv[2] - target_hsv[2]);
462
-
463
- // Handle hue wraparound (0 and 180 are close)
464
- if (h_diff > 90) h_diff = 180 - h_diff;
465
-
466
- // Check if pixel matches background color within tolerance
467
- if (h_diff <= h_tolerance && s_diff <= s_tolerance && v_diff <= v_tolerance) {
468
- mask.at<uchar>(y, x) = 255; // Mark for removal
469
- }
470
- }
471
- }
528
+
529
+ // Mask of pixels within tolerance of the background colour, computed with
530
+ // whole-image OpenCV operations (identical result to the former per-pixel
531
+ // loop: |h-t| with wraparound, |s-t|, |v-t|, all <= tolerance).
532
+ std::vector<cv::Mat> hsvCh;
533
+ cv::split(hsv_src, hsvCh);
534
+ cv::Mat hDiff, sDiff, vDiff;
535
+ cv::absdiff(hsvCh[0], cv::Scalar(target_hsv[0]), hDiff);
536
+ cv::absdiff(hsvCh[1], cv::Scalar(target_hsv[1]), sDiff);
537
+ cv::absdiff(hsvCh[2], cv::Scalar(target_hsv[2]), vDiff);
538
+ // Hue wraparound (0 and 180 are close): h = min(h, 180 - h)
539
+ cv::Mat hWrap;
540
+ cv::subtract(cv::Scalar(180), hDiff, hWrap);
541
+ cv::min(hDiff, hWrap, hDiff);
542
+
543
+ cv::Mat mh, ms, mv, mask;
544
+ cv::compare(hDiff, h_tolerance, mh, cv::CMP_LE);
545
+ cv::compare(sDiff, s_tolerance, ms, cv::CMP_LE);
546
+ cv::compare(vDiff, v_tolerance, mv, cv::CMP_LE);
547
+ cv::bitwise_and(mh, ms, mask);
548
+ cv::bitwise_and(mask, mv, mask); // 255 = mark for removal
472
549
 
473
550
  // Apply Gaussian blur to mask edges for smooth transitions
474
551
  if (tolerance > 0.01) {
@@ -551,41 +628,63 @@ inline cv::Mat alphaComposite(const cv::Mat& base, const cv::Mat& overlay, doubl
551
628
 
552
629
  result = cv::Mat::zeros(base_bgra.size(), CV_8UC4);
553
630
 
554
- // Perform alpha compositing pixel by pixel
555
- for (int y = 0; y < result.rows; y++) {
556
- for (int x = 0; x < result.cols; x++) {
557
- cv::Vec4b base_pixel = base_bgra.at<cv::Vec4b>(y, x);
558
- cv::Vec4b overlay_pixel = overlay_bgra.at<cv::Vec4b>(y, x);
559
-
560
- // Normalize alpha values [0, 1]
561
- double base_alpha = base_pixel[3] / 255.0;
562
- double overlay_alpha = (overlay_pixel[3] / 255.0) * overlayOpacity;
563
-
564
- // Alpha compositing formula: result = overlay * overlay_alpha + base * (1 - overlay_alpha)
565
- // But we need to handle the case where overlay is transparent
566
- double result_alpha = overlay_alpha + base_alpha * (1.0 - overlay_alpha);
567
-
568
- cv::Vec4b result_pixel;
569
-
570
- if (result_alpha > 0.001) { // Avoid division by very small numbers
571
- for (int c = 0; c < 3; c++) { // BGR channels
572
- double result_color = (overlay_pixel[c] * overlay_alpha +
573
- base_pixel[c] * base_alpha * (1.0 - overlay_alpha)) / result_alpha;
574
- result_pixel[c] = cv::saturate_cast<uchar>(result_color);
575
- }
576
- result_pixel[3] = cv::saturate_cast<uchar>(result_alpha * 255);
577
- } else {
578
- // Fully transparent
579
- result_pixel = cv::Vec4b(0, 0, 0, 0);
631
+ // Alpha compositing with row pointers (same arithmetic as the former
632
+ // per-pixel .at<>() loop). Fully transparent results stay at zero.
633
+ const int rows = result.rows, cols = result.cols;
634
+ cv::parallel_for_(cv::Range(0, rows), [&](const cv::Range& range) {
635
+ for (int y = range.start; y < range.end; y++) {
636
+ const uchar* b = base_bgra.ptr<uchar>(y);
637
+ const uchar* o = overlay_bgra.ptr<uchar>(y);
638
+ uchar* r = result.ptr<uchar>(y);
639
+ for (int x = 0; x < cols; x++, b += 4, o += 4, r += 4) {
640
+ // Normalize alpha values [0, 1]
641
+ const double base_alpha = b[3] / 255.0;
642
+ const double overlay_alpha = (o[3] / 255.0) * overlayOpacity;
643
+
644
+ // result = overlay * overlay_alpha + base * base_alpha * (1 - overlay_alpha)
645
+ const double result_alpha = overlay_alpha + base_alpha * (1.0 - overlay_alpha);
646
+ if (result_alpha <= 0.001) continue; // fully transparent → (0,0,0,0)
647
+
648
+ const double base_w = base_alpha * (1.0 - overlay_alpha);
649
+ r[0] = cv::saturate_cast<uchar>((o[0] * overlay_alpha + b[0] * base_w) / result_alpha);
650
+ r[1] = cv::saturate_cast<uchar>((o[1] * overlay_alpha + b[1] * base_w) / result_alpha);
651
+ r[2] = cv::saturate_cast<uchar>((o[2] * overlay_alpha + b[2] * base_w) / result_alpha);
652
+ r[3] = cv::saturate_cast<uchar>(result_alpha * 255);
580
653
  }
581
-
582
- result.at<cv::Vec4b>(y, x) = result_pixel;
583
654
  }
584
- }
655
+ });
585
656
 
586
657
  return result;
587
658
  }
588
659
 
660
+ // 216 candidate colours evenly spread over HSV (24 hues × 3 saturations × 3
661
+ // values), in BGR float [0,1]. Computed once per process instead of on every
662
+ // call (it used to cost 216 tiny cvtColor invocations per unmapped class).
663
+ inline const std::vector<cv::Vec3f>& CandidateColorPalette() {
664
+ static const std::vector<cv::Vec3f> palette = []() {
665
+ std::vector<cv::Vec3f> out;
666
+ const int numHues = 24; // Every 15 degrees
667
+ const int numSaturations = 3; // 60%, 80%, 100%
668
+ const int numValues = 3; // 60%, 80%, 100%
669
+ out.reserve(numHues * numSaturations * numValues);
670
+ for (int h = 0; h < numHues; h++) {
671
+ for (int s = 0; s < numSaturations; s++) {
672
+ for (int v = 0; v < numValues; v++) {
673
+ float hue = (h * 360.0f / numHues);
674
+ float saturation = 0.6f + s * 0.2f;
675
+ float value = 0.6f + v * 0.2f;
676
+ cv::Mat hsv(1, 1, CV_32FC3, cv::Scalar(hue / 360.0f, saturation, value));
677
+ cv::Mat bgr;
678
+ cv::cvtColor(hsv, bgr, cv::COLOR_HSV2BGR);
679
+ out.push_back(bgr.at<cv::Vec3f>(0, 0));
680
+ }
681
+ }
682
+ }
683
+ return out;
684
+ }();
685
+ return palette;
686
+ }
687
+
589
688
  // Parse color string to cv::Scalar, supporting hex colors
590
689
  inline cv::Scalar parseColorString(const std::string& colorStr) {
591
690
  if (colorStr.empty()) {
@@ -14,7 +14,7 @@
14
14
  * Usage: node scripts/dual-register.js [--dry-run]
15
15
  */
16
16
 
17
- const fs = require('fs');
17
+ const fs = require('fs').promises;
18
18
  const path = require('path');
19
19
 
20
20
  const DRY_RUN = process.argv.includes('--dry-run');
@@ -110,9 +110,9 @@ function findMatchingBrace(content, openPos) {
110
110
  // JS: Find registerType('rp-TYPE', C) → add registerType('TYPE', C)
111
111
  // ─────────────────────────────────────────────────────────────
112
112
 
113
- function addLegacyJs(filePath, oldType) {
113
+ async function addLegacyJs(filePath, oldType) {
114
114
  const rpType = 'rp-' + oldType;
115
- let content = fs.readFileSync(filePath, 'utf8');
115
+ let content = await fs.readFile(filePath, 'utf8');
116
116
 
117
117
  // Find: RED.nodes.registerType('rp-TYPE', Constructor);
118
118
  const regex = new RegExp(
@@ -132,7 +132,7 @@ function addLegacyJs(filePath, oldType) {
132
132
 
133
133
  content = content.replace(fullMatch, fullMatch + legacyLine);
134
134
 
135
- if (!DRY_RUN) fs.writeFileSync(filePath, content);
135
+ if (!DRY_RUN) await fs.writeFile(filePath, content);
136
136
  console.log(` JS: ✓ Added legacy registerType('${oldType}', ${constructor})`);
137
137
  return true;
138
138
  }
@@ -217,8 +217,8 @@ function addLegacyScriptBlock(content, attrName, oldType) {
217
217
  return content.replace(fullBlock, fullBlock + '\n\n' + legacyBlock);
218
218
  }
219
219
 
220
- function addLegacyHtml(filePath, oldType) {
221
- let content = fs.readFileSync(filePath, 'utf8');
220
+ async function addLegacyHtml(filePath, oldType) {
221
+ let content = await fs.readFile(filePath, 'utf8');
222
222
 
223
223
  // 1. Add legacy JS registration
224
224
  const transformed = addLegacyHtmlRegistration(content, oldType);
@@ -231,7 +231,7 @@ function addLegacyHtml(filePath, oldType) {
231
231
  // 3. Duplicate help block for legacy type name
232
232
  content = addLegacyScriptBlock(content, 'data-help-name', oldType);
233
233
 
234
- if (!DRY_RUN) fs.writeFileSync(filePath, content);
234
+ if (!DRY_RUN) await fs.writeFile(filePath, content);
235
235
  console.log(` HTML: ✓ Added legacy registration + template + help for '${oldType}'`);
236
236
  return true;
237
237
  }
@@ -240,28 +240,35 @@ function addLegacyHtml(filePath, oldType) {
240
240
  // Main
241
241
  // ─────────────────────────────────────────────────────────────
242
242
 
243
- console.log('=== Add Legacy Compatibility (CI) ===');
244
- if (DRY_RUN) console.log('(DRY RUN — no files will be modified)\n');
245
- else console.log('');
243
+ async function main() {
244
+ console.log('=== Add Legacy Compatibility (CI) ===');
245
+ if (DRY_RUN) console.log('(DRY RUN — no files will be modified)\n');
246
+ else console.log('');
246
247
 
247
- let jsOk = 0, htmlOk = 0, jsFail = 0, htmlFail = 0;
248
+ let jsOk = 0, htmlOk = 0, jsFail = 0, htmlFail = 0;
248
249
 
249
- for (const node of NODES) {
250
- console.log(`[${node.oldType}]`);
251
- const jsFile = path.join(BASE, node.path + '.js');
252
- const htmlFile = path.join(BASE, node.path + '.html');
250
+ for (const node of NODES) {
251
+ console.log(`[${node.oldType}]`);
252
+ const jsFile = path.join(BASE, node.path + '.js');
253
+ const htmlFile = path.join(BASE, node.path + '.html');
253
254
 
254
- if (addLegacyJs(jsFile, node.oldType)) jsOk++;
255
- else jsFail++;
255
+ if (await addLegacyJs(jsFile, node.oldType)) jsOk++;
256
+ else jsFail++;
256
257
 
257
- if (addLegacyHtml(htmlFile, node.oldType)) htmlOk++;
258
- else htmlFail++;
258
+ if (await addLegacyHtml(htmlFile, node.oldType)) htmlOk++;
259
+ else htmlFail++;
259
260
 
260
- console.log('');
261
+ console.log('');
262
+ }
263
+
264
+ console.log('\n=== Summary ===');
265
+ console.log(` JS: ${jsOk} ok, ${jsFail} failed`);
266
+ console.log(` HTML: ${htmlOk} ok, ${htmlFail} failed`);
267
+ if (DRY_RUN) console.log('\n(Dry run — re-run without --dry-run to apply changes)');
268
+ else console.log('\nDone! Legacy compatibility added. Ready to publish.');
261
269
  }
262
270
 
263
- console.log('\n=== Summary ===');
264
- console.log(` JS: ${jsOk} ok, ${jsFail} failed`);
265
- console.log(` HTML: ${htmlOk} ok, ${htmlFail} failed`);
266
- if (DRY_RUN) console.log('\n(Dry run — re-run without --dry-run to apply changes)');
267
- else console.log('\nDone! Legacy compatibility added. Ready to publish.');
271
+ main().catch((err) => {
272
+ console.error(`✗ ${err.message}`);
273
+ process.exit(1);
274
+ });