@rosepetal/node-red-contrib-image-tools 1.1.3

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 (131) hide show
  1. package/.gitattributes +6 -0
  2. package/.github/workflows/build-prebuild.yml +326 -0
  3. package/LICENSE +13 -0
  4. package/README.md +161 -0
  5. package/artifacts/darwin-arm64/package.json +25 -0
  6. package/artifacts/linux-arm64/package.json +26 -0
  7. package/artifacts/linux-x64/package.json +26 -0
  8. package/artifacts/linuxmusl-x64/package.json +26 -0
  9. package/assets/flow_time_example.gif +0 -0
  10. package/assets/nodes/io/array-in-demo.gif +0 -0
  11. package/assets/nodes/io/array-out-demo.gif +0 -0
  12. package/assets/nodes/io/array-select-demo.gif +0 -0
  13. package/assets/nodes/io/image-in-demo.gif +0 -0
  14. package/assets/nodes/mix/concat-demo.gif +0 -0
  15. package/assets/nodes/mix/mosaic-demo.gif +0 -0
  16. package/assets/nodes/transform/crop-demo.gif +0 -0
  17. package/assets/nodes/transform/filter-demo.gif +0 -0
  18. package/assets/nodes/transform/padding-demo.gif +0 -0
  19. package/assets/nodes/transform/resize-demo.gif +0 -0
  20. package/assets/nodes/transform/rotate-demo.gif +0 -0
  21. package/docs/nodes/blend/add-mask.md +275 -0
  22. package/docs/nodes/blend/add-masks.md +284 -0
  23. package/docs/nodes/blend/blend.md +248 -0
  24. package/docs/nodes/io/array-in.md +119 -0
  25. package/docs/nodes/io/array-out.md +150 -0
  26. package/docs/nodes/io/array-select.md +157 -0
  27. package/docs/nodes/io/image-in.md +131 -0
  28. package/docs/nodes/io/image-out.md +179 -0
  29. package/docs/nodes/io/queue.md +57 -0
  30. package/docs/nodes/io/save-file.md +30 -0
  31. package/docs/nodes/mix/advanced-mosaic.md +108 -0
  32. package/docs/nodes/mix/concat.md +127 -0
  33. package/docs/nodes/mix/mosaic.md +146 -0
  34. package/docs/nodes/specialized/cropBB.md +271 -0
  35. package/docs/nodes/specialized/image-align.md +426 -0
  36. package/docs/nodes/transform/crop.md +132 -0
  37. package/docs/nodes/transform/draw.md +77 -0
  38. package/docs/nodes/transform/filter.md +84 -0
  39. package/docs/nodes/transform/padding.md +133 -0
  40. package/docs/nodes/transform/resize.md +158 -0
  41. package/docs/nodes/transform/rotate.md +121 -0
  42. package/docs/nodes/util/block-detect.md +46 -0
  43. package/install.sh +144 -0
  44. package/node-red-contrib-image-tools/lib/cpp-bridge.js +224 -0
  45. package/node-red-contrib-image-tools/lib/node-utils.js +529 -0
  46. package/node-red-contrib-image-tools/nodes/blend/add-bbs.html +590 -0
  47. package/node-red-contrib-image-tools/nodes/blend/add-bbs.js +241 -0
  48. package/node-red-contrib-image-tools/nodes/blend/add-mask.html +449 -0
  49. package/node-red-contrib-image-tools/nodes/blend/add-mask.js +170 -0
  50. package/node-red-contrib-image-tools/nodes/blend/add-masks.html +703 -0
  51. package/node-red-contrib-image-tools/nodes/blend/add-masks.js +321 -0
  52. package/node-red-contrib-image-tools/nodes/blend/blend.html +552 -0
  53. package/node-red-contrib-image-tools/nodes/blend/blend.js +124 -0
  54. package/node-red-contrib-image-tools/nodes/io/array-in.html +110 -0
  55. package/node-red-contrib-image-tools/nodes/io/array-in.js +113 -0
  56. package/node-red-contrib-image-tools/nodes/io/array-out.html +125 -0
  57. package/node-red-contrib-image-tools/nodes/io/array-out.js +213 -0
  58. package/node-red-contrib-image-tools/nodes/io/array-select.html +156 -0
  59. package/node-red-contrib-image-tools/nodes/io/array-select.js +187 -0
  60. package/node-red-contrib-image-tools/nodes/io/folder-in.html +248 -0
  61. package/node-red-contrib-image-tools/nodes/io/folder-in.js +335 -0
  62. package/node-red-contrib-image-tools/nodes/io/image-in.html +146 -0
  63. package/node-red-contrib-image-tools/nodes/io/image-in.js +143 -0
  64. package/node-red-contrib-image-tools/nodes/io/image-out.html +506 -0
  65. package/node-red-contrib-image-tools/nodes/io/image-out.js +545 -0
  66. package/node-red-contrib-image-tools/nodes/io/queue.html +119 -0
  67. package/node-red-contrib-image-tools/nodes/io/queue.js +191 -0
  68. package/node-red-contrib-image-tools/nodes/io/save-file.html +243 -0
  69. package/node-red-contrib-image-tools/nodes/io/save-file.js +440 -0
  70. package/node-red-contrib-image-tools/nodes/mix/advanced-mosaic.html +2149 -0
  71. package/node-red-contrib-image-tools/nodes/mix/advanced-mosaic.js +195 -0
  72. package/node-red-contrib-image-tools/nodes/mix/concat.html +390 -0
  73. package/node-red-contrib-image-tools/nodes/mix/concat.js +112 -0
  74. package/node-red-contrib-image-tools/nodes/mix/mosaic.html +550 -0
  75. package/node-red-contrib-image-tools/nodes/mix/mosaic.js +151 -0
  76. package/node-red-contrib-image-tools/nodes/specialized/cropBB.html +268 -0
  77. package/node-red-contrib-image-tools/nodes/specialized/cropBB.js +277 -0
  78. package/node-red-contrib-image-tools/nodes/specialized/image-align.html +528 -0
  79. package/node-red-contrib-image-tools/nodes/specialized/image-align.js +306 -0
  80. package/node-red-contrib-image-tools/nodes/transform/crop.html +410 -0
  81. package/node-red-contrib-image-tools/nodes/transform/crop.js +149 -0
  82. package/node-red-contrib-image-tools/nodes/transform/draw.html +719 -0
  83. package/node-red-contrib-image-tools/nodes/transform/draw.js +509 -0
  84. package/node-red-contrib-image-tools/nodes/transform/filter.html +578 -0
  85. package/node-red-contrib-image-tools/nodes/transform/filter.js +177 -0
  86. package/node-red-contrib-image-tools/nodes/transform/padding.html +475 -0
  87. package/node-red-contrib-image-tools/nodes/transform/padding.js +142 -0
  88. package/node-red-contrib-image-tools/nodes/transform/resize.html +429 -0
  89. package/node-red-contrib-image-tools/nodes/transform/resize.js +162 -0
  90. package/node-red-contrib-image-tools/nodes/transform/rotate.html +299 -0
  91. package/node-red-contrib-image-tools/nodes/transform/rotate.js +141 -0
  92. package/node-red-contrib-image-tools/nodes/util/block-detect.html +85 -0
  93. package/node-red-contrib-image-tools/nodes/util/block-detect.js +136 -0
  94. package/node-red-contrib-image-tools/nodes/util/clean-debug.html +201 -0
  95. package/node-red-contrib-image-tools/nodes/util/clean-debug.js +393 -0
  96. package/node-red-contrib-image-tools/package.json +64 -0
  97. package/npm/darwin-arm64/lib/.gitkeep +1 -0
  98. package/npm/darwin-arm64/package.json +25 -0
  99. package/npm/darwin-x64/lib/.gitkeep +1 -0
  100. package/npm/darwin-x64/package.json +25 -0
  101. package/npm/linux-arm64/lib/.gitkeep +1 -0
  102. package/npm/linux-arm64/package.json +26 -0
  103. package/npm/linux-x64/lib/.gitkeep +1 -0
  104. package/npm/linux-x64/package.json +26 -0
  105. package/npm/linuxmusl-x64/lib/.gitkeep +1 -0
  106. package/npm/linuxmusl-x64/package.json +26 -0
  107. package/npm/win32-x64/lib/.gitkeep +1 -0
  108. package/npm/win32-x64/package.json +25 -0
  109. package/package.json +74 -0
  110. package/rosepetal-image-engine/binding.gyp +153 -0
  111. package/rosepetal-image-engine/package.json +19 -0
  112. package/rosepetal-image-engine/src/add-bbs.cpp +433 -0
  113. package/rosepetal-image-engine/src/add-mask.cpp +240 -0
  114. package/rosepetal-image-engine/src/add-masks.cpp +638 -0
  115. package/rosepetal-image-engine/src/advanced-mosaic.cpp +740 -0
  116. package/rosepetal-image-engine/src/blend.cpp +200 -0
  117. package/rosepetal-image-engine/src/concat.cpp +329 -0
  118. package/rosepetal-image-engine/src/crop.cpp +139 -0
  119. package/rosepetal-image-engine/src/draw.cpp +414 -0
  120. package/rosepetal-image-engine/src/filter.cpp +230 -0
  121. package/rosepetal-image-engine/src/filters/kernels.h +171 -0
  122. package/rosepetal-image-engine/src/image-align.cpp +551 -0
  123. package/rosepetal-image-engine/src/main.cpp +36 -0
  124. package/rosepetal-image-engine/src/mosaic.cpp +373 -0
  125. package/rosepetal-image-engine/src/padding.cpp +124 -0
  126. package/rosepetal-image-engine/src/resize.cpp +210 -0
  127. package/rosepetal-image-engine/src/rotate.cpp +177 -0
  128. package/rosepetal-image-engine/src/utils.h +563 -0
  129. package/rosepetal-image-engine/test-formats.js +119 -0
  130. package/scripts/build-opencv-static.ps1 +166 -0
  131. package/scripts/build-opencv-static.sh +147 -0
@@ -0,0 +1,2149 @@
1
+ <!-- ───────── nodes/mix/advanced-mosaic.html ────────────── -->
2
+
3
+ <!-- 1 ▸ Runtime registration -->
4
+ <script type="text/javascript">
5
+ RED.nodes.registerType('advanced-mosaic',{
6
+
7
+ category:'RP Image',
8
+ color :'#DA70D6',
9
+ icon :'font-awesome/fa-th-large',
10
+
11
+ defaults:{
12
+ name:{value:""},
13
+ inputPath:{value:"payload"}, inputPathType:{value:"msg"},
14
+ outputPath:{value:"payload"}, outputPathType:{value:"msg"},
15
+ outputFormat:{value:"raw"},
16
+ outputQuality:{value:90},
17
+ pngOptimize:{value:false},
18
+ // Debug configuration
19
+ debugEnabled:{value:false},
20
+ debugWidth:{value:200},
21
+ debugWidthType:{value:"num"},
22
+
23
+ canvasWidth:{value:"800"}, canvasWidthType:{value:"num"},
24
+ canvasHeight:{value:"600"}, canvasHeightType:{value:"num"},
25
+ backgroundColor:{value:"#000000"},
26
+
27
+ imageConfigs:{value:[]}, // Array of {arrayIndex, x, y, width, height, rotation, zIndex} objects
28
+
29
+ propagateMasks:{value:false},
30
+ masksPath:{value:"masks"}, masksPathType:{value:"msg"},
31
+ masksOutputPath:{value:"masks"}, masksOutputPathType:{value:"msg"}
32
+ },
33
+
34
+ inputs:1, outputs:1,
35
+ label:function(){ return this.name || "advanced-mosaic"; },
36
+
37
+ /* ---------------- oneditprepare ---------------- */
38
+ oneditprepare:function(){
39
+ const node = this;
40
+
41
+ /* Standard I/O typedInputs */
42
+ $("#node-input-inputPath").typedInput({
43
+ default:'msg',types:['msg','flow','global'],
44
+ typeField:"#node-input-inputPathType"
45
+ });
46
+ $("#node-input-outputPath").typedInput({
47
+ default:'msg',types:['msg','flow','global'],
48
+ typeField:"#node-input-outputPathType"
49
+ });
50
+ $("#node-input-masksPath").typedInput({
51
+ default:'msg',types:['msg','flow','global'],
52
+ typeField:"#node-input-masksPathType"
53
+ });
54
+ $("#node-input-masksOutputPath").typedInput({
55
+ default:'msg',types:['msg','flow','global'],
56
+ typeField:"#node-input-masksOutputPathType"
57
+ });
58
+
59
+ /* Canvas dimension typedInputs */
60
+ $("#node-input-canvasWidth").typedInput({
61
+ default:'num',
62
+ types:['num','msg','flow','global'],
63
+ typeField:"#node-input-canvasWidthType"
64
+ });
65
+ $("#node-input-canvasHeight").typedInput({
66
+ default:'num',
67
+ types:['num','msg','flow','global'],
68
+ typeField:"#node-input-canvasHeightType"
69
+ });
70
+
71
+
72
+ /* Quality visibility based on output format */
73
+ function updateQualityVisibility(){
74
+ const format = $("#node-input-outputFormat").val();
75
+ $("#quality-row").toggle(format === "jpg" || format === "webp");
76
+ $("#png-optimize-row").toggle(format === "png");
77
+ }
78
+ $("#node-input-outputFormat").on("change", updateQualityVisibility);
79
+ updateQualityVisibility(); // initial state
80
+
81
+ // === Debug Display Logic ===
82
+ const debugCheckbox = $('#node-input-debugEnabled');
83
+ const debugWidthRow = $('#debug-width-row');
84
+
85
+ // Initialize debug width TypedInput
86
+ $("#node-input-debugWidth").typedInput({
87
+ default: 'num',
88
+ types: ['num', 'msg', 'flow', 'global'],
89
+ typeField: "#node-input-debugWidthType"
90
+ });
91
+
92
+ // Function to toggle debug width visibility
93
+ function updateDebugWidthVisibility() {
94
+ if (debugCheckbox.is(':checked')) {
95
+ debugWidthRow.show();
96
+ } else {
97
+ debugWidthRow.hide();
98
+ }
99
+ }
100
+
101
+ // Initialize debug state on node open
102
+ updateDebugWidthVisibility();
103
+
104
+ // Handle debug checkbox changes
105
+ debugCheckbox.on('change', function() {
106
+ updateDebugWidthVisibility();
107
+ });
108
+
109
+ // Mask propagation visibility
110
+ const propagateCheckbox = $('#node-input-propagateMasks');
111
+ const masksPathRow = $('#mask-path-row');
112
+ const masksOutputPathRow = $('#mask-output-path-row');
113
+ function updateMaskVisibility() {
114
+ if (propagateCheckbox.is(':checked')) {
115
+ masksPathRow.show();
116
+ masksOutputPathRow.show();
117
+ } else {
118
+ masksPathRow.hide();
119
+ masksOutputPathRow.hide();
120
+ }
121
+ }
122
+ propagateCheckbox.on('change', updateMaskVisibility);
123
+ updateMaskVisibility();
124
+
125
+ /* Initialize image configurations if empty */
126
+ if (!node.imageConfigs || node.imageConfigs.length === 0) {
127
+ node.imageConfigs = [{
128
+ arrayIndex: 0,
129
+ inputWidth: 800,
130
+ inputHeight: 600,
131
+ x: 50,
132
+ y: 50,
133
+ width: 200,
134
+ height: 150,
135
+ rotation: 0,
136
+ zIndex: 0
137
+ }];
138
+ }
139
+
140
+ /* Interactive Canvas Editor */
141
+ class MosaicCanvasEditor {
142
+ constructor(canvasElement, node) {
143
+ this.canvas = canvasElement;
144
+ this.ctx = this.canvas.getContext('2d');
145
+ this.node = node;
146
+ this.selectedIndex = -1;
147
+ this.isDragging = false;
148
+ this.isResizing = false;
149
+ this.isRotating = false;
150
+ this.resizeHandle = null; // 'nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'
151
+ this.dragStartX = 0;
152
+ this.dragStartY = 0;
153
+ this.originalBounds = null;
154
+ this.showGrid = true;
155
+ this.snapToGrid = true;
156
+ this.gridSize = 20;
157
+ this.handleSize = 14; // Increased from 8px for better usability
158
+ this.hitAreaSize = 24; // Expanded hit detection area
159
+
160
+ // Enhanced magnetic grid features
161
+ this.magneticSnap = true;
162
+ this.magneticDistance = 18; // Increased from 10px for better snapping
163
+ this.snapLines = []; // Visual feedback for snapping
164
+ this.snapLineThickness = 3; // Enhanced visual feedback
165
+ this.edgeMargins = [0, 5, 10, 20]; // Canvas edge snap margins
166
+
167
+ // Aspect ratio preservation
168
+ this.shiftPressed = false;
169
+ this.preserveAspectRatio = true; // Default behavior
170
+ this.originalAspectRatio = 1.0;
171
+
172
+ this.setupEventListeners();
173
+ this.updateCanvasSize();
174
+ this.render();
175
+ }
176
+
177
+ updateCanvasSize() {
178
+ const width = parseInt($("#node-input-canvasWidth").val()) || 800;
179
+ const height = parseInt($("#node-input-canvasHeight").val()) || 600;
180
+
181
+ // Get available width from the canvas container (Node-RED dialog width minus padding)
182
+ const containerWidth = $('#canvas-container').width() || 600;
183
+ const availableWidth = Math.min(containerWidth - 20, 800); // Leave some padding
184
+ const availableHeight = Math.min(availableWidth * 0.75, 500); // Maintain reasonable aspect ratio
185
+
186
+ // Scale to fit available space while maintaining aspect ratio
187
+ const scale = Math.min(availableWidth/width, availableHeight/height, 1);
188
+ this.canvas.width = width * scale;
189
+ this.canvas.height = height * scale;
190
+ this.canvas.style.width = `${width * scale}px`;
191
+ this.canvas.style.height = `${height * scale}px`;
192
+ this.canvas.style.maxWidth = '100%';
193
+ this.canvas.style.maxHeight = '500px';
194
+ this.scale = scale;
195
+ this.canvasWidth = width;
196
+ this.canvasHeight = height;
197
+ }
198
+
199
+ setupEventListeners() {
200
+ this.canvas.addEventListener('mousedown', (e) => this.handleMouseDown(e));
201
+ this.canvas.addEventListener('mousemove', (e) => {
202
+ this.handleMouseMove(e);
203
+ this.updateCursor(e);
204
+ });
205
+ this.canvas.addEventListener('mouseup', (e) => this.handleMouseUp(e));
206
+ this.canvas.addEventListener('click', (e) => this.handleClick(e));
207
+
208
+ // Global mouse tracking for resize operations outside canvas
209
+ this.globalMouseMoveHandler = (e) => {
210
+ if (this.isResizing || this.isDragging || this.isRotating) {
211
+ this.handleMouseMove(e);
212
+ }
213
+ };
214
+ this.globalMouseUpHandler = (e) => {
215
+ if (this.isResizing || this.isDragging || this.isRotating) {
216
+ this.handleMouseUp(e);
217
+ }
218
+ };
219
+
220
+ document.addEventListener('mousemove', this.globalMouseMoveHandler);
221
+ document.addEventListener('mouseup', this.globalMouseUpHandler);
222
+
223
+ // Canvas size change listeners
224
+ $("#node-input-canvasWidth, #node-input-canvasHeight").on('input', () => {
225
+ this.updateCanvasSize();
226
+ this.render();
227
+ });
228
+
229
+ // Window resize listener to adjust canvas size
230
+ $(window).on('resize', () => {
231
+ setTimeout(() => {
232
+ this.updateCanvasSize();
233
+ this.render();
234
+ }, 100);
235
+ });
236
+
237
+ // Keyboard event listeners for shift key detection
238
+ document.addEventListener('keydown', (e) => {
239
+ if (e.key === 'Shift') {
240
+ this.shiftPressed = true;
241
+ }
242
+ });
243
+
244
+ document.addEventListener('keyup', (e) => {
245
+ if (e.key === 'Shift') {
246
+ this.shiftPressed = false;
247
+ }
248
+ });
249
+ }
250
+
251
+ getMousePos(e) {
252
+ const rect = this.canvas.getBoundingClientRect();
253
+
254
+ // Enhanced mouse position calculation for operations outside canvas bounds
255
+ const rawX = (e.clientX - rect.left) / this.scale;
256
+ const rawY = (e.clientY - rect.top) / this.scale;
257
+
258
+ // During resize operations, allow coordinates outside canvas for easier edge-to-edge resizing
259
+ if (this.isResizing || this.isDragging || this.isRotating) {
260
+ return { x: rawX, y: rawY }; // Don't clamp during active operations
261
+ }
262
+
263
+ // For normal interactions, keep within reasonable bounds
264
+ return {
265
+ x: Math.max(-50, Math.min(rawX, this.canvasWidth + 50)), // Allow 50px buffer
266
+ y: Math.max(-50, Math.min(rawY, this.canvasHeight + 50))
267
+ };
268
+ }
269
+
270
+ snapToGridPos(x, y) {
271
+ if (!this.snapToGrid) return {x, y};
272
+ return {
273
+ x: Math.round(x / this.gridSize) * this.gridSize,
274
+ y: Math.round(y / this.gridSize) * this.gridSize
275
+ };
276
+ }
277
+
278
+ // Enhanced magnetic snapping to edges and canvas boundaries
279
+ magneticSnapPosition(x, y, width, height, excludeIndex = -1) {
280
+ if (!this.magneticSnap) return { x, y, snapLines: [] };
281
+
282
+ let snappedX = x;
283
+ let snappedY = y;
284
+ const snapLines = [];
285
+ const dist = this.magneticDistance;
286
+
287
+ // Enhanced canvas boundary and margin snapping
288
+ let verticalSnapped = false, horizontalSnapped = false;
289
+
290
+ // Canvas edge and margin snapping (left side)
291
+ for (let margin of this.edgeMargins) {
292
+ if (Math.abs(x - margin) < dist) {
293
+ snappedX = margin;
294
+ snapLines.push({ type: 'vertical', pos: margin, color: margin === 0 ? '#FF6B6B' : '#FF9F43' });
295
+ verticalSnapped = true;
296
+ break;
297
+ }
298
+ }
299
+
300
+ // Canvas edge and margin snapping (right side)
301
+ if (!verticalSnapped) {
302
+ for (let margin of this.edgeMargins) {
303
+ if (Math.abs(x + width - (this.canvasWidth - margin)) < dist) {
304
+ snappedX = this.canvasWidth - width - margin;
305
+ snapLines.push({ type: 'vertical', pos: this.canvasWidth - margin, color: margin === 0 ? '#FF6B6B' : '#FF9F43' });
306
+ verticalSnapped = true;
307
+ break;
308
+ }
309
+ }
310
+ }
311
+
312
+ // Canvas center-line snapping (vertical)
313
+ if (!verticalSnapped) {
314
+ const centerX = this.canvasWidth / 2;
315
+ const imageCenterX = x + width / 2;
316
+ if (Math.abs(imageCenterX - centerX) < dist) {
317
+ snappedX = centerX - width / 2;
318
+ snapLines.push({ type: 'vertical', pos: centerX, color: '#00D2D3' });
319
+ }
320
+ }
321
+
322
+ // Canvas edge and margin snapping (top)
323
+ for (let margin of this.edgeMargins) {
324
+ if (Math.abs(y - margin) < dist) {
325
+ snappedY = margin;
326
+ snapLines.push({ type: 'horizontal', pos: margin, color: margin === 0 ? '#FF6B6B' : '#FF9F43' });
327
+ horizontalSnapped = true;
328
+ break;
329
+ }
330
+ }
331
+
332
+ // Canvas edge and margin snapping (bottom)
333
+ if (!horizontalSnapped) {
334
+ for (let margin of this.edgeMargins) {
335
+ if (Math.abs(y + height - (this.canvasHeight - margin)) < dist) {
336
+ snappedY = this.canvasHeight - height - margin;
337
+ snapLines.push({ type: 'horizontal', pos: this.canvasHeight - margin, color: margin === 0 ? '#FF6B6B' : '#FF9F43' });
338
+ horizontalSnapped = true;
339
+ break;
340
+ }
341
+ }
342
+ }
343
+
344
+ // Canvas center-line snapping (horizontal)
345
+ if (!horizontalSnapped) {
346
+ const centerY = this.canvasHeight / 2;
347
+ const imageCenterY = y + height / 2;
348
+ if (Math.abs(imageCenterY - centerY) < dist) {
349
+ snappedY = centerY - height / 2;
350
+ snapLines.push({ type: 'horizontal', pos: centerY, color: '#00D2D3' });
351
+ }
352
+ }
353
+
354
+ // Grid line snapping to canvas borders - enhanced magnetic grid
355
+ if (this.showGrid) {
356
+ // Snap to vertical grid lines near canvas borders
357
+ for (let gridX = 0; gridX <= this.canvasWidth; gridX += this.gridSize) {
358
+ // Snap image left edge to grid line
359
+ if (Math.abs(x - gridX) < dist) {
360
+ snappedX = gridX;
361
+ snapLines.push({ type: 'vertical', pos: gridX, color: '#FFA500' });
362
+ break;
363
+ }
364
+ // Snap image right edge to grid line
365
+ if (Math.abs(x + width - gridX) < dist) {
366
+ snappedX = gridX - width;
367
+ snapLines.push({ type: 'vertical', pos: gridX, color: '#FFA500' });
368
+ break;
369
+ }
370
+ }
371
+
372
+ // Snap to horizontal grid lines near canvas borders
373
+ for (let gridY = 0; gridY <= this.canvasHeight; gridY += this.gridSize) {
374
+ // Snap image top edge to grid line
375
+ if (Math.abs(y - gridY) < dist) {
376
+ snappedY = gridY;
377
+ snapLines.push({ type: 'horizontal', pos: gridY, color: '#FFA500' });
378
+ break;
379
+ }
380
+ // Snap image bottom edge to grid line
381
+ if (Math.abs(y + height - gridY) < dist) {
382
+ snappedY = gridY - height;
383
+ snapLines.push({ type: 'horizontal', pos: gridY, color: '#FFA500' });
384
+ break;
385
+ }
386
+ }
387
+ }
388
+
389
+ // Image edge snapping
390
+ for (let i = 0; i < this.node.imageConfigs.length; i++) {
391
+ if (i === excludeIndex) continue;
392
+
393
+ const otherConfig = this.node.imageConfigs[i];
394
+ const otherBounds = this.getImageBounds(otherConfig, i);
395
+
396
+ // Horizontal alignment (X-axis snapping)
397
+ // Left to left
398
+ if (Math.abs(x - otherBounds.x) < dist) {
399
+ snappedX = otherBounds.x;
400
+ snapLines.push({ type: 'vertical', pos: otherBounds.x, color: '#4ECDC4' });
401
+ }
402
+ // Right to right
403
+ else if (Math.abs(x + width - (otherBounds.x + otherBounds.width)) < dist) {
404
+ snappedX = otherBounds.x + otherBounds.width - width;
405
+ snapLines.push({ type: 'vertical', pos: otherBounds.x + otherBounds.width, color: '#4ECDC4' });
406
+ }
407
+ // Left to right
408
+ else if (Math.abs(x - (otherBounds.x + otherBounds.width)) < dist) {
409
+ snappedX = otherBounds.x + otherBounds.width;
410
+ snapLines.push({ type: 'vertical', pos: otherBounds.x + otherBounds.width, color: '#45B7D1' });
411
+ }
412
+ // Right to left
413
+ else if (Math.abs(x + width - otherBounds.x) < dist) {
414
+ snappedX = otherBounds.x - width;
415
+ snapLines.push({ type: 'vertical', pos: otherBounds.x, color: '#45B7D1' });
416
+ }
417
+
418
+ // Vertical alignment (Y-axis snapping)
419
+ // Top to top
420
+ if (Math.abs(y - otherBounds.y) < dist) {
421
+ snappedY = otherBounds.y;
422
+ snapLines.push({ type: 'horizontal', pos: otherBounds.y, color: '#4ECDC4' });
423
+ }
424
+ // Bottom to bottom
425
+ else if (Math.abs(y + height - (otherBounds.y + otherBounds.height)) < dist) {
426
+ snappedY = otherBounds.y + otherBounds.height - height;
427
+ snapLines.push({ type: 'horizontal', pos: otherBounds.y + otherBounds.height, color: '#4ECDC4' });
428
+ }
429
+ // Top to bottom
430
+ else if (Math.abs(y - (otherBounds.y + otherBounds.height)) < dist) {
431
+ snappedY = otherBounds.y + otherBounds.height;
432
+ snapLines.push({ type: 'horizontal', pos: otherBounds.y + otherBounds.height, color: '#45B7D1' });
433
+ }
434
+ // Bottom to top
435
+ else if (Math.abs(y + height - otherBounds.y) < dist) {
436
+ snappedY = otherBounds.y - height;
437
+ snapLines.push({ type: 'horizontal', pos: otherBounds.y, color: '#45B7D1' });
438
+ }
439
+
440
+ // Center-to-center snapping (enhanced feature)
441
+ const currentCenterX = x + width / 2;
442
+ const currentCenterY = y + height / 2;
443
+ const otherCenterX = otherBounds.x + otherBounds.width / 2;
444
+ const otherCenterY = otherBounds.y + otherBounds.height / 2;
445
+
446
+ // Horizontal center alignment
447
+ if (Math.abs(currentCenterX - otherCenterX) < dist) {
448
+ snappedX = otherCenterX - width / 2;
449
+ snapLines.push({ type: 'vertical', pos: otherCenterX, color: '#E74C3C' });
450
+ }
451
+
452
+ // Vertical center alignment
453
+ if (Math.abs(currentCenterY - otherCenterY) < dist) {
454
+ snappedY = otherCenterY - height / 2;
455
+ snapLines.push({ type: 'horizontal', pos: otherCenterY, color: '#E74C3C' });
456
+ }
457
+ }
458
+
459
+ return { x: snappedX, y: snappedY, snapLines };
460
+ }
461
+
462
+ getImageBounds(config, index) {
463
+ // Match C++ processing pipeline exactly: resize → rotate → final bounds
464
+
465
+ // Step 1: Calculate resize dimensions (matching C++ logic lines 206-218)
466
+ let targetWidth, targetHeight;
467
+ const originalWidth = config.inputWidth || 800;
468
+ const originalHeight = config.inputHeight || 600;
469
+
470
+ if (config.width > 0 || config.height > 0) {
471
+ targetWidth = config.width > 0 ? config.width : originalWidth;
472
+ targetHeight = config.height > 0 ? config.height : originalHeight;
473
+
474
+ // Maintain aspect ratio if only one dimension specified (matching C++)
475
+ if (config.width > 0 && (config.height <= 0 || !config.height)) {
476
+ targetHeight = Math.round(targetWidth * originalHeight / originalWidth);
477
+ } else if (config.height > 0 && (config.width <= 0 || !config.width)) {
478
+ targetWidth = Math.round(targetHeight * originalWidth / originalHeight);
479
+ }
480
+ } else {
481
+ // Keep original dimensions
482
+ targetWidth = originalWidth;
483
+ targetHeight = originalHeight;
484
+ }
485
+
486
+ // Step 2: Calculate rotation expansion (matching C++ logic lines 241-248)
487
+ let finalWidth = targetWidth;
488
+ let finalHeight = targetHeight;
489
+
490
+ if (config.rotation && Math.abs(config.rotation) > 1e-3) {
491
+ const normalizedAngle = ((config.rotation % 360) + 360) % 360;
492
+ const eps = 1e-3;
493
+
494
+ // Fast-path for 90-degree rotations (matching C++ fast-path)
495
+ if (Math.abs(normalizedAngle) < eps || Math.abs(normalizedAngle - 360.0) < eps) {
496
+ // 0 degrees - no size change
497
+ } else if (Math.abs(normalizedAngle - 90.0) < eps) {
498
+ // 90° rotation swaps dimensions
499
+ finalWidth = targetHeight;
500
+ finalHeight = targetWidth;
501
+ } else if (Math.abs(normalizedAngle - 180.0) < eps) {
502
+ // 180° rotation - no size change
503
+ } else if (Math.abs(normalizedAngle - 270.0) < eps) {
504
+ // 270° rotation swaps dimensions
505
+ finalWidth = targetHeight;
506
+ finalHeight = targetWidth;
507
+ } else {
508
+ // Arbitrary angles - calculate expanded bounding box (matching C++ formula)
509
+ const radians = config.rotation * Math.PI / 180;
510
+ const cosA = Math.abs(Math.cos(radians));
511
+ const sinA = Math.abs(Math.sin(radians));
512
+ finalWidth = Math.round(targetHeight * sinA + targetWidth * cosA);
513
+ finalHeight = Math.round(targetHeight * cosA + targetWidth * sinA);
514
+ }
515
+ }
516
+
517
+ return {
518
+ x: config.x,
519
+ y: config.y,
520
+ width: finalWidth,
521
+ height: finalHeight
522
+ };
523
+ }
524
+
525
+ hitTestHandles(x, y) {
526
+ if (this.selectedIndex < 0) return null;
527
+
528
+ const config = this.node.imageConfigs[this.selectedIndex];
529
+ const bounds = this.getImageBounds(config, this.selectedIndex);
530
+ const h = this.handleSize; // Visual handle size
531
+ const hitArea = this.hitAreaSize; // Larger hit detection area
532
+
533
+ // Test rotation handle first (use larger hit area)
534
+ const rotHandleX = bounds.x + bounds.width/2;
535
+ const rotHandleY = bounds.y - 25;
536
+ const rotDist = Math.sqrt((x - rotHandleX)**2 + (y - rotHandleY)**2);
537
+ if (rotDist <= hitArea/2) {
538
+ return 'rotate';
539
+ }
540
+
541
+ // Test resize handles (use expanded hit areas for easier clicking)
542
+ const handles = {
543
+ 'nw': { x: bounds.x - h/2, y: bounds.y - h/2 },
544
+ 'n': { x: bounds.x + bounds.width/2 - h/2, y: bounds.y - h/2 },
545
+ 'ne': { x: bounds.x + bounds.width - h/2, y: bounds.y - h/2 },
546
+ 'e': { x: bounds.x + bounds.width - h/2, y: bounds.y + bounds.height/2 - h/2 },
547
+ 'se': { x: bounds.x + bounds.width - h/2, y: bounds.y + bounds.height - h/2 },
548
+ 's': { x: bounds.x + bounds.width/2 - h/2, y: bounds.y + bounds.height - h/2 },
549
+ 'sw': { x: bounds.x - h/2, y: bounds.y + bounds.height - h/2 },
550
+ 'w': { x: bounds.x - h/2, y: bounds.y + bounds.height/2 - h/2 }
551
+ };
552
+
553
+ for (let [handleType, handle] of Object.entries(handles)) {
554
+ // Use expanded hit area for easier clicking while keeping visual handle small
555
+ const hitX = handle.x + h/2 - hitArea/2; // Center the larger hit area on the visual handle
556
+ const hitY = handle.y + h/2 - hitArea/2;
557
+ if (x >= hitX && x <= hitX + hitArea &&
558
+ y >= hitY && y <= hitY + hitArea) {
559
+ return handleType;
560
+ }
561
+ }
562
+
563
+ return null;
564
+ }
565
+
566
+ hitTest(x, y) {
567
+ // First check handles if something is selected
568
+ const handleHit = this.hitTestHandles(x, y);
569
+ if (handleHit) return { type: 'handle', handle: handleHit, index: this.selectedIndex };
570
+
571
+ // Test in reverse order (highest z-index first)
572
+ const configs = [...this.node.imageConfigs].sort((a, b) => (b.zIndex || 0) - (a.zIndex || 0));
573
+
574
+ for (let config of configs) {
575
+ const originalIndex = this.node.imageConfigs.indexOf(config);
576
+ const bounds = this.getImageBounds(config, originalIndex);
577
+
578
+ if (x >= bounds.x && x <= bounds.x + bounds.width &&
579
+ y >= bounds.y && y <= bounds.y + bounds.height) {
580
+ return { type: 'image', index: originalIndex };
581
+ }
582
+ }
583
+ return null;
584
+ }
585
+
586
+ handleMouseDown(e) {
587
+ const pos = this.getMousePos(e);
588
+ const hit = this.hitTest(pos.x, pos.y);
589
+
590
+ if (hit && hit.type === 'handle') {
591
+ // Handle interaction
592
+ if (hit.handle === 'rotate') {
593
+ this.isRotating = true;
594
+ const config = this.node.imageConfigs[hit.index];
595
+ const bounds = this.getImageBounds(config, hit.index);
596
+ this.rotationCenter = { x: bounds.x + bounds.width/2, y: bounds.y + bounds.height/2 };
597
+ this.originalRotation = config.rotation || 0;
598
+ } else {
599
+ this.isResizing = true;
600
+ this.resizeHandle = hit.handle;
601
+ }
602
+
603
+ this.dragStartX = pos.x;
604
+ this.dragStartY = pos.y;
605
+ const config = this.node.imageConfigs[hit.index];
606
+ this.originalBounds = {
607
+ x: config.x,
608
+ y: config.y,
609
+ width: config.width || 100,
610
+ height: config.height || 100
611
+ };
612
+ } else if (hit && hit.type === 'image') {
613
+ // Image selection/drag
614
+ this.selectedIndex = hit.index;
615
+ this.isDragging = true;
616
+ this.dragStartX = pos.x - this.node.imageConfigs[hit.index].x;
617
+ this.dragStartY = pos.y - this.node.imageConfigs[hit.index].y;
618
+ this.updatePropertiesPanel();
619
+ this.render();
620
+ } else {
621
+ // Deselect
622
+ this.selectedIndex = -1;
623
+ this.updatePropertiesPanel();
624
+ this.render();
625
+ }
626
+ }
627
+
628
+ handleMouseMove(e) {
629
+ const pos = this.getMousePos(e);
630
+
631
+ if (this.isDragging && this.selectedIndex >= 0) {
632
+ // Enhanced dragging with magnetic snapping
633
+ const config = this.node.imageConfigs[this.selectedIndex];
634
+ const bounds = this.getImageBounds(config, this.selectedIndex);
635
+
636
+ let newX = pos.x - this.dragStartX;
637
+ let newY = pos.y - this.dragStartY;
638
+
639
+ // Apply magnetic snapping for dragging
640
+ const magneticResult = this.magneticSnapPosition(newX, newY, bounds.width, bounds.height, this.selectedIndex);
641
+ newX = magneticResult.x;
642
+ newY = magneticResult.y;
643
+ this.snapLines = magneticResult.snapLines;
644
+
645
+ // Apply grid snapping if magnetic snapping didn't activate
646
+ if (this.snapLines.length === 0) {
647
+ const gridSnapped = this.snapToGridPos(newX, newY);
648
+ newX = gridSnapped.x;
649
+ newY = gridSnapped.y;
650
+ }
651
+
652
+ // Bounds checking
653
+ newX = Math.max(0, Math.min(newX, this.canvasWidth - bounds.width));
654
+ newY = Math.max(0, Math.min(newY, this.canvasHeight - bounds.height));
655
+
656
+ config.x = newX;
657
+ config.y = newY;
658
+
659
+ this.updatePropertiesPanel();
660
+ this.render();
661
+ RED.nodes.dirty(true);
662
+ } else if (this.isResizing && this.selectedIndex >= 0) {
663
+ // Enhanced resize handling with aspect ratio preservation
664
+ const config = this.node.imageConfigs[this.selectedIndex];
665
+ const deltaX = pos.x - this.dragStartX;
666
+ const deltaY = pos.y - this.dragStartY;
667
+
668
+ let newBounds = { ...this.originalBounds };
669
+ const preserveRatio = this.preserveAspectRatio && !this.shiftPressed;
670
+
671
+ // Apply resize based on handle type with aspect ratio preservation
672
+ switch (this.resizeHandle) {
673
+ case 'nw':
674
+ if (preserveRatio) {
675
+ // Use the larger change to maintain aspect ratio
676
+ const scaleX = Math.max(20, this.originalBounds.width - deltaX) / this.originalBounds.width;
677
+ const scaleY = Math.max(20, this.originalBounds.height - deltaY) / this.originalBounds.height;
678
+ const scale = Math.min(scaleX, scaleY);
679
+
680
+ newBounds.width = Math.max(20, this.originalBounds.width * scale);
681
+ newBounds.height = Math.max(20, this.originalBounds.height * scale);
682
+ newBounds.x = this.originalBounds.x + (this.originalBounds.width - newBounds.width);
683
+ newBounds.y = this.originalBounds.y + (this.originalBounds.height - newBounds.height);
684
+ } else {
685
+ newBounds.width = Math.max(20, this.originalBounds.width - deltaX);
686
+ newBounds.height = Math.max(20, this.originalBounds.height - deltaY);
687
+ newBounds.x = this.originalBounds.x + deltaX;
688
+ newBounds.y = this.originalBounds.y + deltaY;
689
+ }
690
+ break;
691
+ case 'n':
692
+ if (preserveRatio) {
693
+ const scale = Math.max(20, this.originalBounds.height - deltaY) / this.originalBounds.height;
694
+ newBounds.width = Math.max(20, this.originalBounds.width * scale);
695
+ newBounds.height = Math.max(20, this.originalBounds.height * scale);
696
+ newBounds.x = this.originalBounds.x + (this.originalBounds.width - newBounds.width) / 2;
697
+ newBounds.y = this.originalBounds.y + (this.originalBounds.height - newBounds.height);
698
+ } else {
699
+ newBounds.height = Math.max(20, this.originalBounds.height - deltaY);
700
+ newBounds.y = this.originalBounds.y + deltaY;
701
+ }
702
+ break;
703
+ case 'ne':
704
+ if (preserveRatio) {
705
+ const scaleX = Math.max(20, this.originalBounds.width + deltaX) / this.originalBounds.width;
706
+ const scaleY = Math.max(20, this.originalBounds.height - deltaY) / this.originalBounds.height;
707
+ const scale = Math.min(scaleX, scaleY);
708
+
709
+ newBounds.width = Math.max(20, this.originalBounds.width * scale);
710
+ newBounds.height = Math.max(20, this.originalBounds.height * scale);
711
+ newBounds.y = this.originalBounds.y + (this.originalBounds.height - newBounds.height);
712
+ } else {
713
+ newBounds.width = Math.max(20, this.originalBounds.width + deltaX);
714
+ newBounds.height = Math.max(20, this.originalBounds.height - deltaY);
715
+ newBounds.y = this.originalBounds.y + deltaY;
716
+ }
717
+ break;
718
+ case 'e':
719
+ if (preserveRatio) {
720
+ const scale = Math.max(20, this.originalBounds.width + deltaX) / this.originalBounds.width;
721
+ newBounds.width = Math.max(20, this.originalBounds.width * scale);
722
+ newBounds.height = Math.max(20, this.originalBounds.height * scale);
723
+ newBounds.y = this.originalBounds.y + (this.originalBounds.height - newBounds.height) / 2;
724
+ } else {
725
+ newBounds.width = Math.max(20, this.originalBounds.width + deltaX);
726
+ }
727
+ break;
728
+ case 'se':
729
+ if (preserveRatio) {
730
+ const scaleX = Math.max(20, this.originalBounds.width + deltaX) / this.originalBounds.width;
731
+ const scaleY = Math.max(20, this.originalBounds.height + deltaY) / this.originalBounds.height;
732
+ const scale = Math.min(scaleX, scaleY);
733
+
734
+ newBounds.width = Math.max(20, this.originalBounds.width * scale);
735
+ newBounds.height = Math.max(20, this.originalBounds.height * scale);
736
+ } else {
737
+ newBounds.width = Math.max(20, this.originalBounds.width + deltaX);
738
+ newBounds.height = Math.max(20, this.originalBounds.height + deltaY);
739
+ }
740
+ break;
741
+ case 's':
742
+ if (preserveRatio) {
743
+ const scale = Math.max(20, this.originalBounds.height + deltaY) / this.originalBounds.height;
744
+ newBounds.width = Math.max(20, this.originalBounds.width * scale);
745
+ newBounds.height = Math.max(20, this.originalBounds.height * scale);
746
+ newBounds.x = this.originalBounds.x + (this.originalBounds.width - newBounds.width) / 2;
747
+ } else {
748
+ newBounds.height = Math.max(20, this.originalBounds.height + deltaY);
749
+ }
750
+ break;
751
+ case 'sw':
752
+ if (preserveRatio) {
753
+ const scaleX = Math.max(20, this.originalBounds.width - deltaX) / this.originalBounds.width;
754
+ const scaleY = Math.max(20, this.originalBounds.height + deltaY) / this.originalBounds.height;
755
+ const scale = Math.min(scaleX, scaleY);
756
+
757
+ newBounds.width = Math.max(20, this.originalBounds.width * scale);
758
+ newBounds.height = Math.max(20, this.originalBounds.height * scale);
759
+ newBounds.x = this.originalBounds.x + (this.originalBounds.width - newBounds.width);
760
+ } else {
761
+ newBounds.width = Math.max(20, this.originalBounds.width - deltaX);
762
+ newBounds.height = Math.max(20, this.originalBounds.height + deltaY);
763
+ newBounds.x = this.originalBounds.x + deltaX;
764
+ }
765
+ break;
766
+ case 'w':
767
+ if (preserveRatio) {
768
+ const scale = Math.max(20, this.originalBounds.width - deltaX) / this.originalBounds.width;
769
+ newBounds.width = Math.max(20, this.originalBounds.width * scale);
770
+ newBounds.height = Math.max(20, this.originalBounds.height * scale);
771
+ newBounds.x = this.originalBounds.x + (this.originalBounds.width - newBounds.width);
772
+ newBounds.y = this.originalBounds.y + (this.originalBounds.height - newBounds.height) / 2;
773
+ } else {
774
+ newBounds.width = Math.max(20, this.originalBounds.width - deltaX);
775
+ newBounds.x = this.originalBounds.x + deltaX;
776
+ }
777
+ break;
778
+ }
779
+
780
+ // All-or-nothing boundary checking - stop entire resize when hitting any edge
781
+ const wouldExceedBounds = (
782
+ newBounds.x < 0 ||
783
+ newBounds.y < 0 ||
784
+ newBounds.x + newBounds.width > this.canvasWidth ||
785
+ newBounds.y + newBounds.height > this.canvasHeight ||
786
+ newBounds.width < 20 ||
787
+ newBounds.height < 20
788
+ );
789
+
790
+ if (wouldExceedBounds) {
791
+ // Hit any boundary - stop resize completely, keep current dimensions
792
+ // Don't change config at all to preserve aspect ratio
793
+ } else {
794
+ // All boundaries respected - apply resize
795
+ config.x = newBounds.x;
796
+ config.y = newBounds.y;
797
+ config.width = newBounds.width;
798
+ config.height = newBounds.height;
799
+ }
800
+
801
+ this.updatePropertiesPanel();
802
+ this.render();
803
+ RED.nodes.dirty(true);
804
+ } else if (this.isRotating && this.selectedIndex >= 0) {
805
+ // Rotation handling - mathematical standard (counterclockwise positive)
806
+ const config = this.node.imageConfigs[this.selectedIndex];
807
+ const angle = Math.atan2(pos.y - this.rotationCenter.y, pos.x - this.rotationCenter.x);
808
+ // Convert to degrees with 0° pointing up (north), counterclockwise positive
809
+ const degrees = (angle * 180 / Math.PI + 90) % 360;
810
+ // Ensure angle is always positive
811
+ const normalizedDegrees = degrees < 0 ? degrees + 360 : degrees;
812
+
813
+ config.rotation = Math.round(normalizedDegrees);
814
+
815
+ this.updatePropertiesPanel();
816
+ this.render();
817
+ RED.nodes.dirty(true);
818
+ }
819
+ }
820
+
821
+ handleMouseUp(e) {
822
+ this.isDragging = false;
823
+ this.isResizing = false;
824
+ this.isRotating = false;
825
+ this.resizeHandle = null;
826
+ this.originalBounds = null;
827
+ this.snapLines = []; // Clear snap lines
828
+ this.canvas.style.cursor = 'default';
829
+ this.render(); // Re-render to clear snap lines
830
+ }
831
+
832
+ handleClick(e) {
833
+ // Selection is handled in mousedown
834
+ }
835
+
836
+ updateCursor(e) {
837
+ const pos = this.getMousePos(e);
838
+ const hit = this.hitTest(pos.x, pos.y);
839
+
840
+ // Enhanced cursor feedback during active operations
841
+ if (this.isDragging) {
842
+ // Show different cursors based on snapping state during drag
843
+ if (this.snapLines && this.snapLines.length > 0) {
844
+ this.canvas.style.cursor = 'grabbing'; // Indicates active snapping
845
+ } else {
846
+ this.canvas.style.cursor = 'move'; // Standard dragging
847
+ }
848
+ return;
849
+ } else if (this.isResizing) {
850
+ // Maintain resize cursor during active resize operation
851
+ const cursors = {
852
+ 'nw': 'nw-resize', 'n': 'n-resize', 'ne': 'ne-resize',
853
+ 'e': 'e-resize', 'se': 'se-resize', 's': 's-resize',
854
+ 'sw': 'sw-resize', 'w': 'w-resize'
855
+ };
856
+ this.canvas.style.cursor = cursors[this.resizeHandle] || 'pointer';
857
+ return;
858
+ } else if (this.isRotating) {
859
+ this.canvas.style.cursor = 'crosshair';
860
+ return;
861
+ }
862
+
863
+ // Enhanced static cursor feedback based on hit detection
864
+ if (hit && hit.type === 'handle') {
865
+ const cursors = {
866
+ 'nw': 'nw-resize', 'n': 'n-resize', 'ne': 'ne-resize',
867
+ 'e': 'e-resize', 'se': 'se-resize', 's': 's-resize',
868
+ 'sw': 'sw-resize', 'w': 'w-resize', 'rotate': 'crosshair'
869
+ };
870
+
871
+ // Enhanced cursor with visual feedback for different handle types
872
+ const cursor = cursors[hit.handle];
873
+ if (cursor) {
874
+ this.canvas.style.cursor = cursor;
875
+ // Add subtle visual hint - could be enhanced with canvas tooltip
876
+ this.canvas.title = this.getHandleTooltip(hit.handle);
877
+ } else {
878
+ this.canvas.style.cursor = 'pointer';
879
+ this.canvas.title = 'Click to interact';
880
+ }
881
+ } else if (hit && hit.type === 'image') {
882
+ // Enhanced feedback for image hover
883
+ this.canvas.style.cursor = 'grab'; // Better than 'move', indicates draggable
884
+ this.canvas.title = `Image ${hit.index + 1} - Click and drag to move, click to select`;
885
+ } else {
886
+ // Enhanced empty canvas feedback
887
+ this.canvas.style.cursor = 'default';
888
+
889
+ // Provide contextual hints based on canvas state
890
+ if (this.selectedIndex >= 0) {
891
+ this.canvas.title = 'Click empty area to deselect image';
892
+ } else if (this.node.imageConfigs && this.node.imageConfigs.length === 0) {
893
+ this.canvas.title = 'Click "Add Image" to start building your mosaic';
894
+ } else {
895
+ this.canvas.title = 'Click on an image to select it';
896
+ }
897
+ }
898
+
899
+ // Additional cursor feedback for proximity to snap zones
900
+ this.updateSnapProximityCursor(pos);
901
+ }
902
+
903
+ // Helper method to get tooltip text for handle types
904
+ getHandleTooltip(handleType) {
905
+ const tooltips = {
906
+ 'nw': 'Resize from top-left corner',
907
+ 'n': 'Resize height from top',
908
+ 'ne': 'Resize from top-right corner',
909
+ 'e': 'Resize width from right',
910
+ 'se': 'Resize from bottom-right corner',
911
+ 's': 'Resize height from bottom',
912
+ 'sw': 'Resize from bottom-left corner',
913
+ 'w': 'Resize width from left',
914
+ 'rotate': 'Click and drag to rotate image'
915
+ };
916
+ return tooltips[handleType] || 'Resize handle';
917
+ }
918
+
919
+ // Enhanced cursor feedback for proximity to snap zones
920
+ updateSnapProximityCursor(pos) {
921
+ if (this.isDragging || this.isResizing || this.isRotating) return;
922
+ if (!this.magneticSnap) return;
923
+
924
+ const snapProximity = this.magneticDistance * 1.5; // Larger detection area
925
+ let nearSnapZone = false;
926
+
927
+ // Check proximity to canvas edges
928
+ if (pos.x <= snapProximity || pos.x >= this.canvasWidth - snapProximity ||
929
+ pos.y <= snapProximity || pos.y >= this.canvasHeight - snapProximity) {
930
+ nearSnapZone = true;
931
+ }
932
+
933
+ // Check proximity to canvas center lines
934
+ const centerX = this.canvasWidth / 2;
935
+ const centerY = this.canvasHeight / 2;
936
+ if (Math.abs(pos.x - centerX) <= snapProximity || Math.abs(pos.y - centerY) <= snapProximity) {
937
+ nearSnapZone = true;
938
+ }
939
+
940
+ // Subtle cursor enhancement for snap zones (only when no image is under cursor)
941
+ const hit = this.hitTest(pos.x, pos.y);
942
+ if (nearSnapZone && !hit && this.canvas.style.cursor === 'default') {
943
+ this.canvas.style.cursor = 'crosshair';
944
+ this.canvas.title = 'Near snap zone - drag images here for precise alignment';
945
+ }
946
+ }
947
+
948
+ render() {
949
+ const ctx = this.ctx;
950
+ ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
951
+
952
+ // Scale context for display
953
+ ctx.save();
954
+ ctx.scale(this.scale, this.scale);
955
+
956
+ // Draw background
957
+ const bgColor = $("#node-input-backgroundColor").val() || '#000000';
958
+ ctx.fillStyle = bgColor;
959
+ ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
960
+
961
+ // Draw grid
962
+ if (this.showGrid) {
963
+ ctx.strokeStyle = '#ddd';
964
+ ctx.lineWidth = 1;
965
+ ctx.globalAlpha = 0.5;
966
+
967
+ for (let x = 0; x <= this.canvasWidth; x += this.gridSize) {
968
+ ctx.beginPath();
969
+ ctx.moveTo(x, 0);
970
+ ctx.lineTo(x, this.canvasHeight);
971
+ ctx.stroke();
972
+ }
973
+
974
+ for (let y = 0; y <= this.canvasHeight; y += this.gridSize) {
975
+ ctx.beginPath();
976
+ ctx.moveTo(0, y);
977
+ ctx.lineTo(this.canvasWidth, y);
978
+ ctx.stroke();
979
+ }
980
+
981
+ ctx.globalAlpha = 1;
982
+ }
983
+
984
+ // Draw image placeholders (sorted by z-index)
985
+ const sortedConfigs = [...this.node.imageConfigs]
986
+ .map((config, index) => ({config, index}))
987
+ .sort((a, b) => (a.config.zIndex || 0) - (b.config.zIndex || 0));
988
+
989
+ sortedConfigs.forEach(({config, index}) => {
990
+ this.drawImagePlaceholder(ctx, config, index);
991
+ });
992
+
993
+ // Draw selection handles for selected image
994
+ if (this.selectedIndex >= 0) {
995
+ this.drawSelectionHandles(ctx, this.node.imageConfigs[this.selectedIndex], this.selectedIndex);
996
+ }
997
+
998
+ // Draw magnetic snap lines for visual feedback
999
+ this.drawSnapLines(ctx);
1000
+
1001
+ // Draw aspect ratio indicator
1002
+ this.drawAspectRatioIndicator(ctx);
1003
+
1004
+ ctx.restore();
1005
+ }
1006
+
1007
+ drawImagePlaceholder(ctx, config, index) {
1008
+ const bounds = this.getImageBounds(config, index);
1009
+ const isSelected = index === this.selectedIndex;
1010
+
1011
+ // Generate consistent color for array index
1012
+ const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FECA57', '#FF9FF3', '#54A0FF', '#5F27CD'];
1013
+ const color = colors[config.arrayIndex % colors.length];
1014
+
1015
+ ctx.save();
1016
+
1017
+ // Calculate original image dimensions before rotation for visualization
1018
+ const originalWidth = config.inputWidth || 800;
1019
+ const originalHeight = config.inputHeight || 600;
1020
+
1021
+ // Calculate resize dimensions (same logic as getImageBounds)
1022
+ let targetWidth, targetHeight;
1023
+ if (config.width > 0 || config.height > 0) {
1024
+ targetWidth = config.width > 0 ? config.width : originalWidth;
1025
+ targetHeight = config.height > 0 ? config.height : originalHeight;
1026
+
1027
+ if (config.width > 0 && (config.height <= 0 || !config.height)) {
1028
+ targetHeight = Math.round(targetWidth * originalHeight / originalWidth);
1029
+ } else if (config.height > 0 && (config.width <= 0 || !config.width)) {
1030
+ targetWidth = Math.round(targetHeight * originalWidth / originalHeight);
1031
+ }
1032
+ } else {
1033
+ targetWidth = originalWidth;
1034
+ targetHeight = originalHeight;
1035
+ }
1036
+
1037
+ // Calculate z-index for depth effects
1038
+ const zIndex = config.zIndex || 0;
1039
+ const maxZ = Math.max(...this.node.imageConfigs.map(cfg => cfg.zIndex || 0));
1040
+ const minZ = Math.min(...this.node.imageConfigs.map(cfg => cfg.zIndex || 0));
1041
+ const zRange = Math.max(1, maxZ - minZ);
1042
+ const normalizedZ = (zIndex - minZ) / zRange; // 0 to 1
1043
+
1044
+ // Add depth shadow based on z-index (higher z = more prominent shadow)
1045
+ const shadowIntensity = normalizedZ * 0.5 + 0.1; // 0.1 to 0.6
1046
+ const shadowOffset = Math.round(normalizedZ * 4 + 2); // 2 to 6 pixels
1047
+
1048
+ ctx.shadowColor = `rgba(0, 0, 0, ${shadowIntensity})`;
1049
+ ctx.shadowBlur = shadowOffset * 2;
1050
+ ctx.shadowOffsetX = shadowOffset;
1051
+ ctx.shadowOffsetY = shadowOffset;
1052
+
1053
+ // Draw selection highlight background (glow effect)
1054
+ if (isSelected) {
1055
+ // Enhanced selection glow for better visibility
1056
+ ctx.shadowColor = '#FFD700';
1057
+ ctx.shadowBlur = 12;
1058
+ ctx.shadowOffsetX = 3;
1059
+ ctx.shadowOffsetY = 3;
1060
+
1061
+ // Selection background highlight
1062
+ ctx.fillStyle = 'rgba(255, 215, 0, 0.3)';
1063
+ ctx.fillRect(bounds.x - 6, bounds.y - 6, bounds.width + 12, bounds.height + 12);
1064
+ }
1065
+
1066
+ // Draw the final bounding box (expanded for rotation) - now transparent padding
1067
+ if (config.rotation && Math.abs(config.rotation) > 1e-3) {
1068
+ // For rotated images, show transparent padding area with subtle pattern
1069
+ ctx.fillStyle = 'rgba(200, 200, 200, 0.1)'; // Very light gray for transparent area
1070
+ ctx.globalAlpha = 0.5;
1071
+ ctx.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
1072
+ ctx.globalAlpha = 1;
1073
+
1074
+ // Add subtle diagonal pattern to indicate transparency
1075
+ ctx.strokeStyle = 'rgba(200, 200, 200, 0.3)';
1076
+ ctx.lineWidth = 1;
1077
+ ctx.setLineDash([3, 3]);
1078
+ const spacing = 10;
1079
+ for (let i = -bounds.height; i < bounds.width; i += spacing) {
1080
+ ctx.beginPath();
1081
+ ctx.moveTo(bounds.x + i, bounds.y);
1082
+ ctx.lineTo(bounds.x + i + bounds.height, bounds.y + bounds.height);
1083
+ ctx.stroke();
1084
+ }
1085
+ ctx.setLineDash([]);
1086
+ }
1087
+
1088
+ // Draw the actual rotated image area inside the bounding box
1089
+ if (config.rotation && Math.abs(config.rotation) > 1e-3) {
1090
+ const centerX = bounds.x + bounds.width / 2;
1091
+ const centerY = bounds.y + bounds.height / 2;
1092
+
1093
+ ctx.translate(centerX, centerY);
1094
+ ctx.rotate((config.rotation * Math.PI) / 180);
1095
+
1096
+ // Draw the actual image rectangle (before expansion)
1097
+ ctx.fillStyle = color;
1098
+ ctx.globalAlpha = isSelected ? 0.9 : 0.7;
1099
+ ctx.fillRect(-targetWidth / 2, -targetHeight / 2, targetWidth, targetHeight);
1100
+
1101
+ // Draw border around actual image
1102
+ ctx.strokeStyle = isSelected ? '#000' : '#333';
1103
+ ctx.lineWidth = isSelected ? 2 : 1;
1104
+ ctx.globalAlpha = 1;
1105
+ ctx.strokeRect(-targetWidth / 2, -targetHeight / 2, targetWidth, targetHeight);
1106
+
1107
+ ctx.resetTransform();
1108
+ ctx.scale(this.scale, this.scale); // Restore canvas scaling
1109
+ } else {
1110
+ // No rotation - draw normally
1111
+ ctx.fillStyle = color;
1112
+ ctx.globalAlpha = isSelected ? 0.9 : 0.7;
1113
+ ctx.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
1114
+
1115
+ ctx.strokeStyle = isSelected ? '#000' : '#333';
1116
+ ctx.lineWidth = isSelected ? 2 : 1;
1117
+ ctx.globalAlpha = 1;
1118
+ ctx.strokeRect(bounds.x, bounds.y, bounds.width, bounds.height);
1119
+ }
1120
+
1121
+ // Draw expanded bounding box border
1122
+ if (isSelected) {
1123
+ // Double border for selection on the expanded area
1124
+ ctx.strokeStyle = '#FFD700';
1125
+ ctx.lineWidth = 4;
1126
+ ctx.globalAlpha = 1;
1127
+ ctx.strokeRect(bounds.x - 2, bounds.y - 2, bounds.width + 4, bounds.height + 4);
1128
+ }
1129
+
1130
+ // Draw the final bounds border
1131
+ ctx.strokeStyle = '#666';
1132
+ ctx.lineWidth = 1;
1133
+ ctx.setLineDash([5, 5]); // Dashed line to show it's the expanded bounds
1134
+ ctx.globalAlpha = 0.8;
1135
+ ctx.strokeRect(bounds.x, bounds.y, bounds.width, bounds.height);
1136
+ ctx.setLineDash([]); // Reset line dash
1137
+
1138
+ // Draw labels with better contrast
1139
+ ctx.fillStyle = isSelected ? '#000' : '#333';
1140
+ ctx.font = isSelected ? 'bold 12px Arial' : '12px Arial';
1141
+ ctx.textAlign = 'center';
1142
+ ctx.textBaseline = 'middle';
1143
+
1144
+ // White text outline for better readability
1145
+ if (isSelected) {
1146
+ ctx.strokeStyle = '#FFF';
1147
+ ctx.lineWidth = 3;
1148
+ ctx.strokeText(
1149
+ `Image ${config.arrayIndex}`,
1150
+ bounds.x + bounds.width / 2,
1151
+ bounds.y + bounds.height / 2 - 8
1152
+ );
1153
+ }
1154
+
1155
+ ctx.fillText(
1156
+ `Image ${config.arrayIndex} (Z:${zIndex})`,
1157
+ bounds.x + bounds.width / 2,
1158
+ bounds.y + bounds.height / 2 - 16
1159
+ );
1160
+
1161
+ // Draw dimensions - show both original and final dimensions if different
1162
+ ctx.font = isSelected ? 'bold 10px Arial' : '10px Arial';
1163
+
1164
+ const dimensionText = config.rotation && Math.abs(config.rotation) > 1e-3
1165
+ ? `${targetWidth}×${targetHeight} → ${bounds.width}×${bounds.height}`
1166
+ : `${bounds.width}×${bounds.height}`;
1167
+
1168
+ if (isSelected) {
1169
+ ctx.strokeText(
1170
+ dimensionText,
1171
+ bounds.x + bounds.width / 2,
1172
+ bounds.y + bounds.height / 2
1173
+ );
1174
+ }
1175
+
1176
+ ctx.fillText(
1177
+ dimensionText,
1178
+ bounds.x + bounds.width / 2,
1179
+ bounds.y + bounds.height / 2
1180
+ );
1181
+
1182
+ // Draw rotation indicator
1183
+ if (config.rotation && config.rotation !== 0) {
1184
+ if (isSelected) {
1185
+ ctx.strokeText(
1186
+ `${config.rotation}°`,
1187
+ bounds.x + bounds.width / 2,
1188
+ bounds.y + bounds.height / 2 + 16
1189
+ );
1190
+ }
1191
+
1192
+ ctx.fillText(
1193
+ `${config.rotation}°`,
1194
+ bounds.x + bounds.width / 2,
1195
+ bounds.y + bounds.height / 2 + 16
1196
+ );
1197
+ }
1198
+
1199
+ // Draw z-index indicator badge in top-right corner
1200
+ const badgeSize = 16;
1201
+ const badgeX = bounds.x + bounds.width - badgeSize - 2;
1202
+ const badgeY = bounds.y + 2;
1203
+
1204
+ // Reset shadow for badge
1205
+ ctx.shadowColor = 'transparent';
1206
+ ctx.shadowBlur = 0;
1207
+ ctx.shadowOffsetX = 0;
1208
+ ctx.shadowOffsetY = 0;
1209
+
1210
+ // Badge background (color-coded by z-index level)
1211
+ const badgeAlpha = normalizedZ * 0.6 + 0.4; // 0.4 to 1.0
1212
+ ctx.fillStyle = `rgba(0, 100, 200, ${badgeAlpha})`;
1213
+ ctx.fillRect(badgeX, badgeY, badgeSize, badgeSize);
1214
+
1215
+ // Badge border
1216
+ ctx.strokeStyle = '#003366';
1217
+ ctx.lineWidth = 1;
1218
+ ctx.strokeRect(badgeX, badgeY, badgeSize, badgeSize);
1219
+
1220
+ // Z-index number
1221
+ ctx.fillStyle = '#FFFFFF';
1222
+ ctx.font = 'bold 10px Arial';
1223
+ ctx.textAlign = 'center';
1224
+ ctx.textBaseline = 'middle';
1225
+ ctx.fillText(
1226
+ zIndex.toString(),
1227
+ badgeX + badgeSize / 2,
1228
+ badgeY + badgeSize / 2
1229
+ );
1230
+
1231
+ ctx.restore();
1232
+ }
1233
+
1234
+ drawSelectionHandles(ctx, config, index) {
1235
+ const bounds = this.getImageBounds(config, index);
1236
+ const h = this.handleSize;
1237
+
1238
+ ctx.save();
1239
+
1240
+ // Don't rotate handles - they stay aligned to screen
1241
+ // Apply same scaling as main rendering
1242
+
1243
+ // Define handle positions
1244
+ const handles = {
1245
+ 'nw': { x: bounds.x - h/2, y: bounds.y - h/2 },
1246
+ 'n': { x: bounds.x + bounds.width/2 - h/2, y: bounds.y - h/2 },
1247
+ 'ne': { x: bounds.x + bounds.width - h/2, y: bounds.y - h/2 },
1248
+ 'e': { x: bounds.x + bounds.width - h/2, y: bounds.y + bounds.height/2 - h/2 },
1249
+ 'se': { x: bounds.x + bounds.width - h/2, y: bounds.y + bounds.height - h/2 },
1250
+ 's': { x: bounds.x + bounds.width/2 - h/2, y: bounds.y + bounds.height - h/2 },
1251
+ 'sw': { x: bounds.x - h/2, y: bounds.y + bounds.height - h/2 },
1252
+ 'w': { x: bounds.x - h/2, y: bounds.y + bounds.height/2 - h/2 }
1253
+ };
1254
+
1255
+ // Draw resize handles
1256
+ ctx.fillStyle = '#FFD700';
1257
+ ctx.strokeStyle = '#000';
1258
+ ctx.lineWidth = 1;
1259
+
1260
+ Object.values(handles).forEach(handle => {
1261
+ ctx.fillRect(handle.x, handle.y, h, h);
1262
+ ctx.strokeRect(handle.x, handle.y, h, h);
1263
+ });
1264
+
1265
+ // Draw rotation handle
1266
+ const rotHandleX = bounds.x + bounds.width/2;
1267
+ const rotHandleY = bounds.y - 25;
1268
+
1269
+ // Connection line to rotation handle
1270
+ ctx.strokeStyle = '#FFD700';
1271
+ ctx.lineWidth = 2;
1272
+ ctx.setLineDash([3, 3]);
1273
+ ctx.beginPath();
1274
+ ctx.moveTo(bounds.x + bounds.width/2, bounds.y);
1275
+ ctx.lineTo(rotHandleX, rotHandleY + h/2);
1276
+ ctx.stroke();
1277
+ ctx.setLineDash([]);
1278
+
1279
+ // Rotation handle (circle)
1280
+ ctx.fillStyle = '#FF6B6B';
1281
+ ctx.strokeStyle = '#000';
1282
+ ctx.lineWidth = 2;
1283
+ ctx.beginPath();
1284
+ ctx.arc(rotHandleX, rotHandleY, h/2, 0, 2 * Math.PI);
1285
+ ctx.fill();
1286
+ ctx.stroke();
1287
+
1288
+ // Rotation symbol
1289
+ ctx.fillStyle = '#FFF';
1290
+ ctx.font = 'bold 10px Arial';
1291
+ ctx.textAlign = 'center';
1292
+ ctx.textBaseline = 'middle';
1293
+ ctx.fillText('↻', rotHandleX, rotHandleY);
1294
+
1295
+ ctx.restore();
1296
+ }
1297
+
1298
+ // Draw magnetic snap lines for visual feedback
1299
+ drawSnapLines(ctx) {
1300
+ if (!this.snapLines || this.snapLines.length === 0) return;
1301
+
1302
+ ctx.save();
1303
+ ctx.lineWidth = this.snapLineThickness; // Use configured thickness (3px)
1304
+ ctx.globalAlpha = 0.9; // Increased opacity for better visibility
1305
+
1306
+ // Group lines by type for optimized rendering
1307
+ const verticalLines = [];
1308
+ const horizontalLines = [];
1309
+
1310
+ this.snapLines.forEach(line => {
1311
+ if (line.type === 'vertical') {
1312
+ verticalLines.push(line);
1313
+ } else if (line.type === 'horizontal') {
1314
+ horizontalLines.push(line);
1315
+ }
1316
+ });
1317
+
1318
+ // Enhanced visual styling based on snap type
1319
+ const drawLineGroup = (lines, isVertical) => {
1320
+ lines.forEach(line => {
1321
+ ctx.save();
1322
+
1323
+ // Set line style based on color/type for better visual distinction
1324
+ if (line.color === '#E74C3C') { // Center-to-center snapping (red)
1325
+ ctx.setLineDash([8, 4]); // Distinctive dash pattern
1326
+ ctx.strokeStyle = line.color;
1327
+ ctx.shadowBlur = 2;
1328
+ ctx.shadowColor = 'rgba(231, 76, 60, 0.3)';
1329
+ } else if (line.color === '#F39C12') { // Canvas edges (orange)
1330
+ ctx.setLineDash([6, 3]); // Medium dash pattern
1331
+ ctx.strokeStyle = line.color;
1332
+ ctx.shadowBlur = 1;
1333
+ ctx.shadowColor = 'rgba(243, 156, 18, 0.2)';
1334
+ } else if (line.color === '#3498DB') { // Canvas center-lines (blue)
1335
+ ctx.setLineDash([10, 2]); // Long dash pattern for center-lines
1336
+ ctx.strokeStyle = line.color;
1337
+ ctx.shadowBlur = 2;
1338
+ ctx.shadowColor = 'rgba(52, 152, 219, 0.3)';
1339
+ } else { // Default/other snap types
1340
+ ctx.setLineDash([5, 5]); // Standard dash pattern
1341
+ ctx.strokeStyle = line.color || '#27AE60'; // Default green
1342
+ ctx.shadowBlur = 1;
1343
+ ctx.shadowColor = 'rgba(39, 174, 96, 0.2)';
1344
+ }
1345
+
1346
+ ctx.beginPath();
1347
+
1348
+ if (isVertical) {
1349
+ ctx.moveTo(line.pos, 0);
1350
+ ctx.lineTo(line.pos, this.canvasHeight);
1351
+ } else {
1352
+ ctx.moveTo(0, line.pos);
1353
+ ctx.lineTo(this.canvasWidth, line.pos);
1354
+ }
1355
+
1356
+ ctx.stroke();
1357
+ ctx.restore();
1358
+ });
1359
+ };
1360
+
1361
+ // Draw vertical and horizontal lines with optimized grouping
1362
+ drawLineGroup(verticalLines, true);
1363
+ drawLineGroup(horizontalLines, false);
1364
+
1365
+ ctx.restore();
1366
+ }
1367
+
1368
+ // Draw aspect ratio preservation indicator
1369
+ drawAspectRatioIndicator(ctx) {
1370
+ if (!this.isResizing || this.selectedIndex < 0) return;
1371
+
1372
+ ctx.save();
1373
+
1374
+ // Draw indicator in top-right corner
1375
+ const indicatorX = this.canvasWidth - 100;
1376
+ const indicatorY = 20;
1377
+
1378
+ // Background
1379
+ ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
1380
+ ctx.roundRect = ctx.roundRect || function(x, y, w, h, r) {
1381
+ this.beginPath();
1382
+ this.moveTo(x + r, y);
1383
+ this.arcTo(x + w, y, x + w, y + h, r);
1384
+ this.arcTo(x + w, y + h, x, y + h, r);
1385
+ this.arcTo(x, y + h, x, y, r);
1386
+ this.arcTo(x, y, x + w, y, r);
1387
+ this.closePath();
1388
+ };
1389
+ ctx.roundRect(indicatorX - 10, indicatorY - 5, 90, 25, 5);
1390
+ ctx.fill();
1391
+
1392
+ // Text
1393
+ ctx.fillStyle = '#FFF';
1394
+ ctx.font = '12px Arial';
1395
+ ctx.textAlign = 'left';
1396
+ ctx.textBaseline = 'middle';
1397
+
1398
+ const preserveRatio = this.preserveAspectRatio && !this.shiftPressed;
1399
+ const text = preserveRatio ? '🔒 Aspect Locked' : '🔓 Free Resize';
1400
+ ctx.fillText(text, indicatorX - 5, indicatorY + 7);
1401
+
1402
+ ctx.restore();
1403
+ }
1404
+
1405
+ updatePropertiesPanel() {
1406
+ const panel = $('#selected-properties');
1407
+
1408
+ if (this.selectedIndex >= 0) {
1409
+ const config = this.node.imageConfigs[this.selectedIndex];
1410
+ panel.show();
1411
+
1412
+ // Input dimensions
1413
+ $('#prop-array-index').val(config.arrayIndex || 0);
1414
+ $('#prop-input-width').val(config.inputWidth || 800);
1415
+ $('#prop-input-height').val(config.inputHeight || 600);
1416
+
1417
+ // Resize dimensions
1418
+ $('#prop-width').val(config.width || '');
1419
+ $('#prop-height').val(config.height || '');
1420
+
1421
+ // Transform
1422
+ $('#prop-rotation').val(config.rotation || 0);
1423
+ $('#prop-z-index').val(config.zIndex || this.selectedIndex);
1424
+
1425
+ // Position
1426
+ $('#prop-x').val(config.x || 0);
1427
+ $('#prop-y').val(config.y || 0);
1428
+
1429
+ // Calculate and display computed dimensions
1430
+ const originalWidth = config.inputWidth || 800;
1431
+ const originalHeight = config.inputHeight || 600;
1432
+
1433
+ // Step 1: Calculate resize dimensions
1434
+ let targetWidth, targetHeight;
1435
+ if (config.width > 0 || config.height > 0) {
1436
+ targetWidth = config.width > 0 ? config.width : originalWidth;
1437
+ targetHeight = config.height > 0 ? config.height : originalHeight;
1438
+
1439
+ if (config.width > 0 && (config.height <= 0 || !config.height)) {
1440
+ targetHeight = Math.round(targetWidth * originalHeight / originalWidth);
1441
+ } else if (config.height > 0 && (config.width <= 0 || !config.width)) {
1442
+ targetWidth = Math.round(targetHeight * originalWidth / originalHeight);
1443
+ }
1444
+ } else {
1445
+ targetWidth = originalWidth;
1446
+ targetHeight = originalHeight;
1447
+ }
1448
+
1449
+ $('#prop-computed-resize').val(`${targetWidth} × ${targetHeight}`);
1450
+
1451
+ // Step 2: Calculate final dimensions after rotation
1452
+ const bounds = this.getImageBounds(config, this.selectedIndex);
1453
+ $('#prop-computed-final').val(`${bounds.width} × ${bounds.height}`);
1454
+
1455
+ // Calculate expansion factor
1456
+ const originalArea = targetWidth * targetHeight;
1457
+ const finalArea = bounds.width * bounds.height;
1458
+ const expansionFactor = (finalArea / originalArea).toFixed(2);
1459
+ $('#prop-expansion-factor').val(`${expansionFactor}×`);
1460
+
1461
+ $('#remove-selected-config').prop('disabled', false);
1462
+ } else {
1463
+ panel.hide();
1464
+ $('#remove-selected-config').prop('disabled', true);
1465
+ }
1466
+ }
1467
+
1468
+ updateConfigFromProperties() {
1469
+ if (this.selectedIndex >= 0) {
1470
+ const config = this.node.imageConfigs[this.selectedIndex];
1471
+
1472
+ // Input dimensions are now locked - skip updating them
1473
+ // config.arrayIndex, config.inputWidth, config.inputHeight are read-only
1474
+
1475
+ // Resize dimensions
1476
+ const widthVal = $('#prop-width').val();
1477
+ config.width = widthVal === '' ? null : parseInt(widthVal);
1478
+
1479
+ const heightVal = $('#prop-height').val();
1480
+ config.height = heightVal === '' ? null : parseInt(heightVal);
1481
+
1482
+ // Transform
1483
+ config.rotation = parseFloat($('#prop-rotation').val()) || 0;
1484
+ config.zIndex = parseInt($('#prop-z-index').val()) || 0;
1485
+
1486
+ // Position
1487
+ config.x = parseFloat($('#prop-x').val()) || 0;
1488
+ config.y = parseFloat($('#prop-y').val()) || 0;
1489
+
1490
+ this.render();
1491
+ RED.nodes.dirty(true);
1492
+ }
1493
+ }
1494
+ }
1495
+
1496
+ // Initialize canvas editor with delay to ensure container is sized
1497
+ setTimeout(() => {
1498
+ const canvasEditor = new MosaicCanvasEditor(document.getElementById('mosaic-canvas'), node);
1499
+
1500
+ // Store reference for event handlers
1501
+ node.canvasEditor = canvasEditor;
1502
+
1503
+ // Event handlers for canvas controls
1504
+ $('#add-image-config').on('click', function() {
1505
+ // Use native JavaScript prompts to collect input dimensions
1506
+ const arrayIndex = prompt('Enter Array Index (which image from input array to use):', node.imageConfigs.length);
1507
+ if (arrayIndex === null) return; // User cancelled
1508
+
1509
+ const inputWidth = prompt('Enter Input Width (original image width in pixels):', '800');
1510
+ if (inputWidth === null) return; // User cancelled
1511
+
1512
+ const inputHeight = prompt('Enter Input Height (original image height in pixels):', '600');
1513
+ if (inputHeight === null) return; // User cancelled
1514
+
1515
+ // Validate inputs
1516
+ const parsedArrayIndex = parseInt(arrayIndex) || 0;
1517
+ const parsedInputWidth = parseInt(inputWidth) || 800;
1518
+ const parsedInputHeight = parseInt(inputHeight) || 600;
1519
+
1520
+ // Get current canvas dimensions for proportional scaling (1/6 scale)
1521
+ const canvasWidth = parseInt($("#node-input-canvasWidth").val()) || 800;
1522
+ const canvasHeight = parseInt($("#node-input-canvasHeight").val()) || 600;
1523
+
1524
+ // Calculate 1/6 scale with aspect ratio preservation
1525
+ const scaleSize = Math.min(canvasWidth, canvasHeight) / 6;
1526
+ const aspectRatio = parsedInputWidth / parsedInputHeight;
1527
+
1528
+ let displayWidth, displayHeight;
1529
+ if (aspectRatio >= 1) {
1530
+ // Wide/square - fit to scale width
1531
+ displayWidth = Math.round(scaleSize);
1532
+ displayHeight = Math.round(scaleSize / aspectRatio);
1533
+ } else {
1534
+ // Tall - fit to scale height
1535
+ displayHeight = Math.round(scaleSize);
1536
+ displayWidth = Math.round(scaleSize * aspectRatio);
1537
+ }
1538
+
1539
+ // Create new image config with user-provided values
1540
+ node.imageConfigs.push({
1541
+ arrayIndex: parsedArrayIndex,
1542
+ inputWidth: parsedInputWidth,
1543
+ inputHeight: parsedInputHeight,
1544
+ x: 50 + (node.imageConfigs.length * 20),
1545
+ y: 50 + (node.imageConfigs.length * 20),
1546
+ width: displayWidth,
1547
+ height: displayHeight,
1548
+ rotation: 0,
1549
+ zIndex: node.imageConfigs.length,
1550
+ locked: true // Mark as locked
1551
+ });
1552
+
1553
+ canvasEditor.render();
1554
+ RED.nodes.dirty(true);
1555
+ });
1556
+
1557
+ $('#remove-selected-config').on('click', function() {
1558
+ if (canvasEditor.selectedIndex >= 0) {
1559
+ node.imageConfigs.splice(canvasEditor.selectedIndex, 1);
1560
+ canvasEditor.selectedIndex = -1;
1561
+ canvasEditor.updatePropertiesPanel();
1562
+ canvasEditor.render();
1563
+ RED.nodes.dirty(true);
1564
+ }
1565
+ });
1566
+
1567
+ $('#show-grid').on('change', function() {
1568
+ canvasEditor.showGrid = $(this).is(':checked');
1569
+ canvasEditor.render();
1570
+ });
1571
+
1572
+ $('#snap-to-grid').on('change', function() {
1573
+ canvasEditor.snapToGrid = $(this).is(':checked');
1574
+ });
1575
+
1576
+ $('#magnetic-snap').on('change', function() {
1577
+ canvasEditor.magneticSnap = $(this).is(':checked');
1578
+ });
1579
+
1580
+ $('#preserve-aspect').on('change', function() {
1581
+ canvasEditor.preserveAspectRatio = $(this).is(':checked');
1582
+ });
1583
+
1584
+ $('#duplicate-selected').on('click', function() {
1585
+ if (canvasEditor.selectedIndex >= 0) {
1586
+ const original = node.imageConfigs[canvasEditor.selectedIndex];
1587
+ const duplicate = {
1588
+ arrayIndex: original.arrayIndex,
1589
+ inputWidth: original.inputWidth,
1590
+ inputHeight: original.inputHeight,
1591
+ x: original.x + 30,
1592
+ y: original.y + 30,
1593
+ width: original.width,
1594
+ height: original.height,
1595
+ rotation: original.rotation,
1596
+ zIndex: node.imageConfigs.length
1597
+ };
1598
+ node.imageConfigs.push(duplicate);
1599
+ canvasEditor.render();
1600
+ RED.nodes.dirty(true);
1601
+ }
1602
+ });
1603
+
1604
+ // Z-Index control buttons
1605
+ $('#bring-to-front').on('click', function() {
1606
+ if (canvasEditor.selectedIndex >= 0) {
1607
+ const maxZ = Math.max(...node.imageConfigs.map(cfg => cfg.zIndex || 0));
1608
+ node.imageConfigs[canvasEditor.selectedIndex].zIndex = maxZ + 1;
1609
+ canvasEditor.updatePropertiesPanel();
1610
+ canvasEditor.render();
1611
+ RED.nodes.dirty(true);
1612
+ }
1613
+ });
1614
+
1615
+ $('#send-to-back').on('click', function() {
1616
+ if (canvasEditor.selectedIndex >= 0) {
1617
+ const minZ = Math.min(...node.imageConfigs.map(cfg => cfg.zIndex || 0));
1618
+ node.imageConfigs[canvasEditor.selectedIndex].zIndex = minZ - 1;
1619
+ canvasEditor.updatePropertiesPanel();
1620
+ canvasEditor.render();
1621
+ RED.nodes.dirty(true);
1622
+ }
1623
+ });
1624
+
1625
+ $('#move-up').on('click', function() {
1626
+ if (canvasEditor.selectedIndex >= 0) {
1627
+ const currentZ = node.imageConfigs[canvasEditor.selectedIndex].zIndex || 0;
1628
+ node.imageConfigs[canvasEditor.selectedIndex].zIndex = currentZ + 1;
1629
+ canvasEditor.updatePropertiesPanel();
1630
+ canvasEditor.render();
1631
+ RED.nodes.dirty(true);
1632
+ }
1633
+ });
1634
+
1635
+ $('#move-down').on('click', function() {
1636
+ if (canvasEditor.selectedIndex >= 0) {
1637
+ const currentZ = node.imageConfigs[canvasEditor.selectedIndex].zIndex || 0;
1638
+ node.imageConfigs[canvasEditor.selectedIndex].zIndex = currentZ - 1;
1639
+ canvasEditor.updatePropertiesPanel();
1640
+ canvasEditor.render();
1641
+ RED.nodes.dirty(true);
1642
+ }
1643
+ });
1644
+
1645
+ // Properties panel event handlers
1646
+ $('#selected-properties input').on('input', function() {
1647
+ canvasEditor.updateConfigFromProperties();
1648
+ });
1649
+
1650
+ // Background color change
1651
+ $('#node-input-backgroundColor').on('change', function() {
1652
+ canvasEditor.render();
1653
+ });
1654
+
1655
+ // Actualize Canvas button handler
1656
+ $('#actualize-canvas-btn').on('click', function() {
1657
+ // Get current input values
1658
+ const currentWidth = $("#node-input-canvasWidth").val();
1659
+ const currentHeight = $("#node-input-canvasHeight").val();
1660
+
1661
+ // Update node config directly
1662
+ node.canvasWidth = currentWidth;
1663
+ node.canvasHeight = currentHeight;
1664
+
1665
+ // Mark node as dirty for saving
1666
+ RED.nodes.dirty(true);
1667
+
1668
+ // Update visual canvas
1669
+ canvasEditor.updateCanvasSize();
1670
+ canvasEditor.render();
1671
+
1672
+ // User feedback
1673
+ const btn = $(this);
1674
+ const originalText = btn.text();
1675
+ btn.text('✅ Applied!').css('background', '#45a049');
1676
+ setTimeout(() => {
1677
+ btn.text(originalText).css('background', '#4CAF50');
1678
+ }, 1500);
1679
+ });
1680
+ }, 100);
1681
+ }
1682
+ });
1683
+
1684
+ // Debug image display renderer - shared across all image processing nodes
1685
+ if (!window.debugImageRendererInitialized) {
1686
+ window.debugImageRendererInitialized = true;
1687
+
1688
+ (function() {
1689
+ var isSubscribed = false;
1690
+
1691
+ function subscribeToDebugImages() {
1692
+ if (isSubscribed || typeof RED === 'undefined' || !RED.comms) return;
1693
+ isSubscribed = true;
1694
+
1695
+ RED.comms.subscribe('debug-image', function(event, data) {
1696
+ if (!data || !data.id) return;
1697
+
1698
+ try {
1699
+ renderDebugImage(data);
1700
+ } catch (err) {
1701
+ console.warn('Debug image render error:', err);
1702
+ }
1703
+ });
1704
+ }
1705
+
1706
+ function renderDebugImage(data) {
1707
+ const nodeId = data.id;
1708
+ const base64Data = data.data;
1709
+ const format = data.format || 'unknown';
1710
+ const mimeType = data.mimeType || 'jpeg';
1711
+
1712
+ if (!base64Data) {
1713
+ removeDebugImage(nodeId);
1714
+ return;
1715
+ }
1716
+
1717
+ const nodeElement = document.getElementById(nodeId);
1718
+ if (!nodeElement) return;
1719
+
1720
+ let debugContainer = document.getElementById('debug-img-container-' + nodeId);
1721
+
1722
+ if (!debugContainer) {
1723
+ // Create SVG foreignObject to embed HTML content in SVG
1724
+ debugContainer = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject');
1725
+ debugContainer.id = 'debug-img-container-' + nodeId;
1726
+ debugContainer.setAttribute('x', '70');
1727
+ debugContainer.setAttribute('y', '5');
1728
+ debugContainer.setAttribute('width', '120');
1729
+ debugContainer.setAttribute('height', '120');
1730
+ debugContainer.style.overflow = 'visible';
1731
+
1732
+ // Create simple image directly inside foreignObject
1733
+ const img = document.createElement('img');
1734
+ img.id = 'debug-img-' + nodeId;
1735
+ img.style.width = '100%';
1736
+ img.style.height = 'auto';
1737
+ img.style.display = 'block';
1738
+ img.style.cursor = 'pointer';
1739
+ img.style.maxHeight = '100px';
1740
+ img.style.maxWidth = '100px';
1741
+
1742
+ img.onclick = function() {
1743
+ removeDebugImage(nodeId);
1744
+ };
1745
+
1746
+ debugContainer.appendChild(img);
1747
+ nodeElement.appendChild(debugContainer);
1748
+ }
1749
+
1750
+ const img = document.getElementById('debug-img-' + nodeId);
1751
+
1752
+ if (img) {
1753
+ img.src = `data:image/${mimeType};base64,${base64Data}`;
1754
+ img.title = 'Debug image (click to hide)';
1755
+ }
1756
+ }
1757
+
1758
+ function removeDebugImage(nodeId) {
1759
+ const debugContainer = document.getElementById('debug-img-container-' + nodeId);
1760
+ if (debugContainer) {
1761
+ debugContainer.remove();
1762
+ }
1763
+ }
1764
+
1765
+ function initializeWhenReady() {
1766
+ if (typeof RED !== 'undefined' && RED.comms) {
1767
+ subscribeToDebugImages();
1768
+
1769
+ // Clean up orphaned debug images periodically
1770
+ setInterval(function() {
1771
+ const debugContainers = document.querySelectorAll('[id^="debug-img-container-"]');
1772
+ debugContainers.forEach(container => {
1773
+ const nodeId = container.id.replace('debug-img-container-', '');
1774
+ const nodeElement = document.getElementById(nodeId);
1775
+ if (!nodeElement) {
1776
+ container.remove();
1777
+ }
1778
+ });
1779
+ }, 5000);
1780
+ } else {
1781
+ setTimeout(initializeWhenReady, 100);
1782
+ }
1783
+ }
1784
+
1785
+ if (document.readyState === 'loading') {
1786
+ document.addEventListener('DOMContentLoaded', initializeWhenReady);
1787
+ } else {
1788
+ initializeWhenReady();
1789
+ }
1790
+ })();
1791
+ }
1792
+ </script>
1793
+
1794
+ <!-- 2 ▸ Edit‑dialog template -->
1795
+ <script type="text/x-red" data-template-name="advanced-mosaic">
1796
+
1797
+ <!-- Name -->
1798
+ <div class="form-row">
1799
+ <label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
1800
+ <input type="text" id="node-input-name" placeholder="Name">
1801
+ </div>
1802
+
1803
+ <hr>
1804
+
1805
+ <!-- STANDARD I/O SECTION -->
1806
+ <div class="form-row">
1807
+ <label for="node-input-inputPath"><i class="fa fa-sign-in"></i> Input from</label>
1808
+ <input type="text" id="node-input-inputPath" style="width: 70%;">
1809
+ <input type="hidden" id="node-input-inputPathType">
1810
+ </div>
1811
+ <div class="form-row">
1812
+ <label for="node-input-outputPath"><i class="fa fa-sign-out"></i> Output to</label>
1813
+ <input type="text" id="node-input-outputPath" style="width: 70%;">
1814
+ <input type="hidden" id="node-input-outputPathType">
1815
+ </div>
1816
+ <div class="form-row">
1817
+ <label for="node-input-propagateMasks"><i class="fa fa-object-group"></i> Propagate masks</label>
1818
+ <input type="checkbox" id="node-input-propagateMasks" style="display:inline-block; width:auto; vertical-align:baseline;">
1819
+ <span style="margin-left: 6px; color: #666;">Apply same transforms to mask array</span>
1820
+ </div>
1821
+ <div class="form-row" id="mask-path-row">
1822
+ <label for="node-input-masksPath"><i class="fa fa-sign-in"></i> Masks from</label>
1823
+ <input type="text" id="node-input-masksPath" style="width: 70%;">
1824
+ <input type="hidden" id="node-input-masksPathType">
1825
+ </div>
1826
+ <div class="form-row" id="mask-output-path-row">
1827
+ <label for="node-input-masksOutputPath"><i class="fa fa-sign-out"></i> Masks to</label>
1828
+ <input type="text" id="node-input-masksOutputPath" style="width: 70%;">
1829
+ <input type="hidden" id="node-input-masksOutputPathType">
1830
+ </div>
1831
+ <div class="form-row">
1832
+ <label for="node-input-outputFormat"><i class="fa fa-file-image-o"></i> Output Format</label>
1833
+ <select id="node-input-outputFormat" style="width: 200px;">
1834
+ <option value="raw">Raw (fastest)</option>
1835
+ <option value="jpg">JPEG</option>
1836
+ <option value="png">PNG</option>
1837
+ <option value="webp">WebP</option>
1838
+ </select>
1839
+ </div>
1840
+ <div class="form-row" id="quality-row">
1841
+ <label for="node-input-outputQuality"><i class="fa fa-sliders"></i> Quality</label>
1842
+ <input type="number" id="node-input-outputQuality" min="1" max="100" value="90" style="width: 70px;">
1843
+ <span style="margin-left: 10px; color: #666;">1-100 (JPG/WebP only)</span>
1844
+ </div>
1845
+ <div class="form-row" id="png-optimize-row" style="display: none;">
1846
+ <label for="node-input-pngOptimize"><i class="fa fa-compress"></i> PNG Optimize</label>
1847
+ <input type="checkbox" id="node-input-pngOptimize" style="display:inline-block; width:auto; vertical-align:baseline;">
1848
+ <label for="node-input-pngOptimize" style="width:auto; margin-left:5px;">Compress PNG (slower, smaller file)</label>
1849
+ </div>
1850
+
1851
+ <!-- Debug Configuration -->
1852
+ <div class="form-row">
1853
+ <label for="node-input-debugEnabled"><i class="fa fa-bug"></i> Debug</label>
1854
+ <input type="checkbox" id="node-input-debugEnabled" style="display:inline-block; width:auto; vertical-align:baseline;">
1855
+ <label for="node-input-debugEnabled" style="width:auto; margin-left:5px;">Show processed image</label>
1856
+ </div>
1857
+ <div class="form-row" id="debug-width-row" style="display: none;">
1858
+ <label for="node-input-debugWidth"><i class="fa fa-arrows-h"></i> Debug Width</label>
1859
+ <input type="text" id="node-input-debugWidth" style="width: 120px;">
1860
+ <input type="hidden" id="node-input-debugWidthType">
1861
+ <span style="margin-left: 10px; color: #666;">pixels</span>
1862
+ </div>
1863
+
1864
+ <hr>
1865
+
1866
+ <!-- CANVAS CONFIGURATION -->
1867
+ <div class="form-row">
1868
+ <label for="node-input-canvasWidth"><i class="fa fa-arrows-h"></i> Canvas Width</label>
1869
+ <input type="text" id="node-input-canvasWidth" style="width: 70%;" placeholder="800">
1870
+ <input type="hidden" id="node-input-canvasWidthType">
1871
+ </div>
1872
+ <div class="form-row">
1873
+ <label for="node-input-canvasHeight"><i class="fa fa-arrows-v"></i> Canvas Height</label>
1874
+ <input type="text" id="node-input-canvasHeight" style="width: 70%;" placeholder="600">
1875
+ <input type="hidden" id="node-input-canvasHeightType">
1876
+ </div>
1877
+ <div class="form-row">
1878
+ <label></label>
1879
+ <button type="button" id="actualize-canvas-btn" style="background: #4CAF50; color: white; border: none; padding: 8px 16px; cursor: pointer; border-radius: 4px; font-size: 12px;">
1880
+ Apply Canvas Size
1881
+ </button>
1882
+ <span style="margin-left: 10px; color: #666; font-size: 11px;">Click to apply canvas dimension changes</span>
1883
+ </div>
1884
+ <div class="form-row">
1885
+ <label for="node-input-backgroundColor"><i class="fa fa-paint-brush"></i> Background Color</label>
1886
+ <input type="color" id="node-input-backgroundColor" style="width: 70px; height: 30px;">
1887
+ </div>
1888
+
1889
+
1890
+ <hr>
1891
+
1892
+ <!-- INTERACTIVE CANVAS EDITOR -->
1893
+ <div class="form-row">
1894
+ <label style="width: 100%; margin-bottom: 10px;"><i class="fa fa-th-large"></i> Visual Canvas Editor</label>
1895
+
1896
+ <!-- Canvas Controls -->
1897
+ <div style="display: flex; gap: 10px; margin-bottom: 10px; align-items: center;">
1898
+ <button type="button" id="add-image-config" style="background: #4CAF50; color: white; border: none; padding: 6px 12px; cursor: pointer; font-size: 12px;">Add Image</button>
1899
+ <button type="button" id="remove-selected-config" style="background: #ff4444; color: white; border: none; padding: 6px 12px; cursor: pointer; font-size: 12px;" disabled>Remove Selected</button>
1900
+ <label style="display: flex; align-items: center; gap: 5px; margin-left: auto;">
1901
+ <input type="checkbox" id="show-grid" checked> Show Grid
1902
+ </label>
1903
+ <label style="display: flex; align-items: center; gap: 5px;">
1904
+ <input type="checkbox" id="snap-to-grid" checked> Snap to Grid
1905
+ </label>
1906
+ <label style="display: flex; align-items: center; gap: 5px;">
1907
+ <input type="checkbox" id="magnetic-snap" checked> Magnetic Snap
1908
+ </label>
1909
+ <label style="display: flex; align-items: center; gap: 5px;">
1910
+ <input type="checkbox" id="preserve-aspect" checked> Lock Aspect Ratio
1911
+ </label>
1912
+ </div>
1913
+
1914
+ <!-- Canvas Container -->
1915
+ <div id="canvas-container" style="border: 2px solid #ddd; background: #f9f9f9; position: relative; margin-bottom: 10px; width: 100%; min-height: 300px; display: flex; justify-content: center; align-items: center;">
1916
+ <canvas id="mosaic-canvas" width="400" height="300" style="display: block; cursor: default; border: 1px solid #ccc;"></canvas>
1917
+ </div>
1918
+
1919
+ <!-- Selected Image Properties -->
1920
+ <div id="selected-properties" style="display: none; background: #f0f0f0; padding: 10px; border-radius: 4px; font-size: 12px;">
1921
+ <strong>Selected Image Properties:</strong>
1922
+
1923
+ <!-- Input Dimensions Section -->
1924
+ <div style="background: #e8f4fd; padding: 8px; margin: 8px 0; border-radius: 4px;">
1925
+ <strong style="color: #1976d2;">Input Dimensions (Original Image):</strong>
1926
+ <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; margin-top: 8px;">
1927
+ <div>
1928
+ <label>Array Index:</label>
1929
+ <input type="number" id="prop-array-index" min="0" style="width: 100%; font-size: 11px; background-color: #f5f5f5;" readonly>
1930
+ <small style="color: #999; font-size: 9px;">🔒 Locked</small>
1931
+ </div>
1932
+ <div>
1933
+ <label>Input Width:</label>
1934
+ <input type="number" id="prop-input-width" min="1" style="width: 100%; font-size: 11px; background-color: #f5f5f5;" placeholder="800" readonly>
1935
+ <small style="color: #999; font-size: 9px;">🔒 Locked</small>
1936
+ </div>
1937
+ <div>
1938
+ <label>Input Height:</label>
1939
+ <input type="number" id="prop-input-height" min="1" style="width: 100%; font-size: 11px; background-color: #f5f5f5;" placeholder="600" readonly>
1940
+ <small style="color: #999; font-size: 9px;">🔒 Locked</small>
1941
+ </div>
1942
+ </div>
1943
+ <div style="margin-top: 5px;">
1944
+ <small style="color: #999; font-style: italic;">These values are locked after creation. Delete and recreate the image to change them.</small>
1945
+ </div>
1946
+ </div>
1947
+
1948
+ <!-- Resize & Transform Section -->
1949
+ <div style="background: #fff3e0; padding: 8px; margin: 8px 0; border-radius: 4px;">
1950
+ <strong style="color: #f57c00;">Resize & Transform:</strong>
1951
+ <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; margin-top: 8px;">
1952
+ <div>
1953
+ <label>Resize Width:</label>
1954
+ <input type="number" id="prop-width" min="1" style="width: 100%; font-size: 11px;" placeholder="Keep original">
1955
+ </div>
1956
+ <div>
1957
+ <label>Resize Height:</label>
1958
+ <input type="number" id="prop-height" min="1" style="width: 100%; font-size: 11px;" placeholder="Keep original">
1959
+ </div>
1960
+ <div>
1961
+ <label>Rotation (°):</label>
1962
+ <input type="number" id="prop-rotation" step="any" style="width: 100%; font-size: 11px;">
1963
+ </div>
1964
+ </div>
1965
+ </div>
1966
+
1967
+ <!-- Computed Final Dimensions Section -->
1968
+ <div style="background: #e8f5e8; padding: 8px; margin: 8px 0; border-radius: 4px;">
1969
+ <strong style="color: #2e7d32;">Final Computed Dimensions:</strong>
1970
+ <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; margin-top: 8px;">
1971
+ <div>
1972
+ <label>After Resize:</label>
1973
+ <input type="text" id="prop-computed-resize" readonly style="width: 100%; font-size: 11px; background: #f5f5f5;" placeholder="Computed...">
1974
+ </div>
1975
+ <div>
1976
+ <label>After Rotation:</label>
1977
+ <input type="text" id="prop-computed-final" readonly style="width: 100%; font-size: 11px; background: #f5f5f5;" placeholder="Computed...">
1978
+ </div>
1979
+ <div>
1980
+ <label>Expansion Factor:</label>
1981
+ <input type="text" id="prop-expansion-factor" readonly style="width: 100%; font-size: 11px; background: #f5f5f5;" placeholder="1.0x">
1982
+ </div>
1983
+ </div>
1984
+ </div>
1985
+
1986
+ <!-- Position Section -->
1987
+ <div style="background: #f3e5f5; padding: 8px; margin: 8px 0; border-radius: 4px;">
1988
+ <strong style="color: #7b1fa2;">Position & Actions:</strong>
1989
+ <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; margin-top: 8px;">
1990
+ <div>
1991
+ <label>X Position:</label>
1992
+ <input type="number" id="prop-x" step="any" style="width: 100%; font-size: 11px;">
1993
+ </div>
1994
+ <div>
1995
+ <label>Y Position:</label>
1996
+ <input type="number" id="prop-y" step="any" style="width: 100%; font-size: 11px;">
1997
+ </div>
1998
+ <div>
1999
+ <label>Actions:</label>
2000
+ <div style="display: flex; gap: 4px; flex-wrap: wrap;">
2001
+ <button type="button" id="duplicate-selected" style="background: #2196F3; color: white; border: none; padding: 4px 8px; cursor: pointer; font-size: 10px;">Duplicate</button>
2002
+ </div>
2003
+ </div>
2004
+ </div>
2005
+ </div>
2006
+
2007
+ <!-- Layering Control Section -->
2008
+ <div style="background: #fff8e1; padding: 8px; margin: 8px 0; border-radius: 4px;">
2009
+ <strong style="color: #f57c00;">Layer Control (Z-Index):</strong>
2010
+ <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 10px; margin-top: 8px;">
2011
+ <div>
2012
+ <label>Z-Index:</label>
2013
+ <input type="number" id="prop-z-index" style="width: 100%; font-size: 11px;">
2014
+ </div>
2015
+ <div>
2016
+ <label>Layer Actions:</label>
2017
+ <div style="display: flex; gap: 4px; flex-wrap: wrap;">
2018
+ <button type="button" id="bring-to-front" style="background: #4CAF50; color: white; border: none; padding: 4px 8px; cursor: pointer; font-size: 10px;">Bring to Front</button>
2019
+ <button type="button" id="send-to-back" style="background: #FF9800; color: white; border: none; padding: 4px 8px; cursor: pointer; font-size: 10px;">Send to Back</button>
2020
+ <button type="button" id="move-up" style="background: #2196F3; color: white; border: none; padding: 4px 8px; cursor: pointer; font-size: 10px;">Move Up</button>
2021
+ <button type="button" id="move-down" style="background: #9C27B0; color: white; border: none; padding: 4px 8px; cursor: pointer; font-size: 10px;">Move Down</button>
2022
+ </div>
2023
+ </div>
2024
+ </div>
2025
+ </div>
2026
+ </div>
2027
+ </div>
2028
+
2029
+ <div class="form-tips">
2030
+ <b>Enhanced Canvas Editor Instructions:</b>
2031
+ <ul>
2032
+ <li><b>Add Image:</b> Click "Add Image" to create a new placeholder rectangle</li>
2033
+ <li><b>Select & Drag:</b> Click on any placeholder to select it, then drag to reposition with magnetic snapping</li>
2034
+ <li><b>Resize with Aspect Ratio:</b> Drag resize handles to resize - aspect ratio is preserved by default, hold Shift to resize freely</li>
2035
+ <li><b>Accurate Preview:</b> The canvas shows exact dimensions matching the C++ processing pipeline</li>
2036
+ <li><b>Transparent Rotation:</b> Rotated images use transparent padding (diagonal pattern) allowing layered compositions</li>
2037
+ <li><b>Properties Panel:</b> Shows computed dimensions after resize and rotation, plus expansion factors</li>
2038
+ <li><b>Enhanced Grid Snapping:</b> Magnetic snap to grid lines, canvas borders, and other image edges</li>
2039
+ <li><b>Z-Index Control:</b> Visual depth indicators with easy layer management buttons (bring to front, send to back)</li>
2040
+ <li><b>Aspect Ratio Lock:</b> Toggle "Lock Aspect Ratio" to control default resize behavior</li>
2041
+ <li><b>Visual Feedback:</b> Colored snap lines appear during dragging, aspect ratio indicator shows during resize</li>
2042
+ <li><b>Color Coding:</b> Each array index has a unique color for easy identification</li>
2043
+ <li><b>Duplicate:</b> Use "Duplicate" button to copy the selected image configuration</li>
2044
+ </ul>
2045
+ </div>
2046
+ </script>
2047
+
2048
+ <!-- 3 ▸ Help panel -->
2049
+ <script type="text/x-red" data-help-name="advanced-mosaic">
2050
+ <p><b>rosepetal-advanced-mosaic</b> creates composite images with per-image transformations including resize, rotate, and positioning. This advanced node extends the basic mosaic functionality by allowing individual transformation of each image before placement on the canvas.</p>
2051
+
2052
+ <h3>Details</h3>
2053
+ <p>This node processes arrays of images and applies individual transformations (resize, rotate) to each image before placing them on a customizable canvas. Each image can be independently resized, rotated, and positioned using an interactive visual canvas editor with drag-and-drop functionality.</p>
2054
+
2055
+ <h3>Properties</h3>
2056
+ <dl class="message-properties">
2057
+ <dt>Input from <span class="property-type">string</span></dt>
2058
+ <dd>Message property path containing the input image array.</dd>
2059
+
2060
+ <dt>Output to <span class="property-type">string</span></dt>
2061
+ <dd>Message property path where the composite image will be stored.</dd>
2062
+
2063
+ <dt>Output Format <span class="property-type">string</span></dt>
2064
+ <dd>Format for the output image: <code>raw</code> (fastest), <code>jpg</code>, <code>png</code>, or <code>webp</code>.</dd>
2065
+
2066
+ <dt>Quality <span class="property-type">number</span></dt>
2067
+ <dd>Compression quality (1-100) for JPEG and WebP formats.</dd>
2068
+
2069
+ <dt>Canvas Width/Height <span class="property-type">number|string</span></dt>
2070
+ <dd>Dimensions of the output canvas in pixels. Supports dynamic values from context.</dd>
2071
+
2072
+ <dt>Background Color <span class="property-type">color</span></dt>
2073
+ <dd>Canvas background color in hex format.</dd>
2074
+
2075
+ <dt>Normalized Coords <span class="property-type">boolean</span></dt>
2076
+ <dd>When enabled, position coordinates use normalized values (0.0-1.0).</dd>
2077
+
2078
+ <dt>Visual Canvas Editor <span class="property-type">interactive</span></dt>
2079
+ <dd>Interactive canvas interface for visually configuring image transformations with drag-and-drop positioning, magnetic helpers, and real-time preview.</dd>
2080
+ </dl>
2081
+
2082
+ <h3>Image Transformations</h3>
2083
+ <h4>Resize Options</h4>
2084
+ <ul>
2085
+ <li><b>Absolute Sizing:</b> Set specific width and height in pixels</li>
2086
+ <li><b>Aspect Ratio Preservation:</b> Specify only width or height to maintain proportions</li>
2087
+ <li><b>Original Size:</b> Leave width/height empty to use original dimensions</li>
2088
+ </ul>
2089
+
2090
+ <h4>Rotation System</h4>
2091
+ <ul>
2092
+ <li><b>Arbitrary Angles:</b> Rotate by any angle in degrees (counterclockwise positive)</li>
2093
+ <li><b>Optimized 90° Rotations:</b> Fast-path processing for 90°, 180°, 270°</li>
2094
+ <li><b>Transparent Padding:</b> Rotation expansion uses transparent padding for layered compositions</li>
2095
+ <li><b>Alpha Blending:</b> Rotated images blend seamlessly with underlying content</li>
2096
+ </ul>
2097
+
2098
+ <h4>Layering Control</h4>
2099
+ <ul>
2100
+ <li><b>Z-Index Ordering:</b> Control which images appear on top</li>
2101
+ <li><b>Automatic Z-Assignment:</b> Default ordering based on configuration sequence</li>
2102
+ </ul>
2103
+
2104
+ <h3>Performance Optimizations</h3>
2105
+ <ul>
2106
+ <li><b>C++ Backend:</b> High-performance OpenCV-based processing with SIMD acceleration</li>
2107
+ <li><b>Transformation Pipeline:</b> Optimized resize → rotate → place sequence</li>
2108
+ <li><b>Zero-Copy Operations:</b> Minimal memory allocation and copying</li>
2109
+ <li><b>Parallel Processing:</b> Multiple images processed concurrently when beneficial</li>
2110
+ <li><b>Fast-Path Rotations:</b> Optimized handling for common rotation angles</li>
2111
+ </ul>
2112
+
2113
+ <h3>Configuration Workflow</h3>
2114
+ <h4>Interactive Canvas Editor</h4>
2115
+ <ul>
2116
+ <li><b>Visual Positioning:</b> Drag-and-drop placeholder rectangles to position images</li>
2117
+ <li><b>Magnetic Helpers:</b> Snap-to-grid and alignment guides for precise positioning</li>
2118
+ <li><b>Properties Panel:</b> Fine-tune settings for selected images with numeric inputs</li>
2119
+ <li><b>Real-time Preview:</b> See exactly how your mosaic will look with color-coded placeholders</li>
2120
+ <li><b>Dynamic Management:</b> Add, remove, and duplicate image configurations with visual feedback</li>
2121
+ <li><b>Grid System:</b> Optional grid overlay with configurable snap-to-grid functionality</li>
2122
+ </ul>
2123
+
2124
+ <h3>Error Handling & Validation</h3>
2125
+ <ul>
2126
+ <li><b>Input Validation:</b> Comprehensive validation of image arrays and configurations</li>
2127
+ <li><b>Bounds Checking:</b> Automatic handling of out-of-bounds coordinates and indices</li>
2128
+ <li><b>Transformation Validation:</b> Safe handling of invalid resize and rotation parameters</li>
2129
+ <li><b>Canvas Validation:</b> Ensures valid canvas dimensions and background colors</li>
2130
+ <li><b>Warning System:</b> Non-fatal issues reported without stopping execution</li>
2131
+ </ul>
2132
+
2133
+ <h3>Example Configurations</h3>
2134
+ <h4>Photo Collage</h4>
2135
+ <ul>
2136
+ <li>Canvas: 1200x800 pixels, white background</li>
2137
+ <li>Image 0: Resize to 300x200, position at (50, 50)</li>
2138
+ <li>Image 1: Keep original size, rotate 15°, position at (400, 100)</li>
2139
+ <li>Image 2: Resize to 250x250, position at (700, 300)</li>
2140
+ </ul>
2141
+
2142
+ <h4>Dashboard Layout</h4>
2143
+ <ul>
2144
+ <li>Canvas: 1920x1080 pixels, dark background</li>
2145
+ <li>Header image: Full width resize, position at (0, 0)</li>
2146
+ <li>Sidebar: Fixed height, position at (0, 100)</li>
2147
+ <li>Main content: Scaled, position at (300, 100)</li>
2148
+ </ul>
2149
+ </script>