-
-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathfilltool.js
More file actions
433 lines (378 loc) · 13.4 KB
/
filltool.js
File metadata and controls
433 lines (378 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
/* global graphTool, JXG */
'use strict';
(() => {
if (graphTool && graphTool.fillTool) return;
graphTool.fillTool = {
Fill(gt) {
return class Fill extends gt.GraphObject {
static strId = 'fill';
supportsSolidDash = false;
constructor(point) {
super(point);
// Make the point invisible, but not with the jsxgraph visible attribute.
// The icon will be shown instead.
point.setAttribute({
strokeOpacity: 0,
highlightStrokeOpacity: 0,
fillOpacity: 0,
highlightFillOpacity: 0,
fixed: gt.isStatic,
tabindex: 0,
aria: {
enabled: true,
label: (p) => `shade the region containing the point ${p.X()}, ${p.Y()}`,
roledescription: 'shading point',
live: 'assertive',
atomic: true
}
});
this.definingPts.push(point);
this.focusPoint = point;
this.isAnswer = gt.graphingAnswers;
this.focused = true;
this.updateTimeout = 0;
this.update();
this.isStatic = gt.isStatic;
point.rendNode.classList.add('hidden-fill-point');
// The icon is what is actually shown. It is centered on the point which is the actual object.
this.icon = gt.board.create(
'image',
[
() => this.constructor.fillIcon(this.focused ? gt.color.pointHighlight : gt.color.fill),
[() => point.X() - 12 / gt.board.unitX, () => point.Y() - 12 / gt.board.unitY],
[() => 24 / gt.board.unitX, () => 24 / gt.board.unitY]
],
{
withLabel: false,
highlight: false,
layer: 8,
name: 'FillIcon',
fixed: true,
tabindex: '',
aria: { enabled: true, hidden: true, live: 'off' }
}
);
if (!gt.isStatic) {
this.on('drag', (e) => {
gt.adjustDragPosition(e, this.baseObj);
this.update();
gt.updateText();
});
}
}
// The fill object has an invisible focus object. So the focus/blur methods need to be overridden.
blur() {
this.focused = false;
this.baseObj.setAttribute({ fixed: true });
gt.board.update();
gt.updateHelp();
}
focus() {
this.focused = true;
this.baseObj.setAttribute({ fixed: false });
gt.board.update();
this.baseObj.rendNode.focus();
gt.updateHelp();
}
remove() {
gt.board.removeObject(this.icon);
if (this.fillObj) gt.board.removeObject(this.fillObj);
super.remove();
}
update() {
const updateReal = () => {
this.updateTimeout = 0;
if (this.fillObj) {
gt.board.removeObject(this.fillObj);
delete this.fillObj;
}
// If the fill point is not on the board, then the flood fill algorithm will loop infinitely.
// So bail.
if (!gt.boardHasPoint(...this.baseObj.coords.usrCoords.slice(1))) return;
const allObjects = gt.graphedObjs
.concat(gt.staticObjs)
.filter((o) => !(o instanceof gt.graphObjectTypes['fill']));
// Determine which side of each object needs to be shaded. If the point
// is on a graphed object, then don't fill.
const a_vals = Array(allObjects.length);
for (const [i, object] of allObjects.entries()) {
a_vals[i] = object.fillCmp(this.baseObj.coords.usrCoords);
if (a_vals[i] == 0) return;
}
const bBox = gt.board.getBoundingBox();
const canvas = document.createElement('canvas');
canvas.width = gt.board.canvasWidth + 1;
canvas.height = gt.board.canvasHeight + 1;
const context = canvas.getContext('2d');
const colorLayerData = context.getImageData(0, 0, canvas.width, canvas.height);
const fillRed = Number('0x' + gt.color.fill.slice(1, 3));
const fillBlue = Number('0x' + gt.color.fill.slice(3, 5));
const fillGreen = Number('0x' + gt.color.fill.slice(5));
const fillPixel = (pixelPos) => {
colorLayerData.data[pixelPos] = fillRed;
colorLayerData.data[pixelPos + 1] = fillBlue;
colorLayerData.data[pixelPos + 2] = fillGreen;
colorLayerData.data[pixelPos + 3] = 255;
};
if (gt.options.useFloodFill) {
const isFilled = (pixelPos) =>
colorLayerData.data[pixelPos] == fillRed &&
colorLayerData.data[pixelPos + 1] == fillBlue &&
colorLayerData.data[pixelPos + 2] == fillGreen;
const isBoundaryPixel = (x, y, fromDir) => {
const curPixel = [1, bBox[0] + x / gt.board.unitX, bBox[1] - y / gt.board.unitY];
const fromPixel = [
1,
curPixel[1] + fromDir[0] / gt.board.unitX,
curPixel[2] + fromDir[1] / gt.board.unitY
];
for (const [i, object] of allObjects.entries()) {
if (object.onBoundary(curPixel, a_vals[i], fromPixel)) return true;
}
return false;
};
const pixelStack = [
[
Math.round((this.definingPts[0].X() - bBox[0]) * gt.board.unitX),
Math.round((bBox[1] - this.definingPts[0].Y()) * gt.board.unitY)
]
];
while (pixelStack.length) {
const newPos = pixelStack.pop();
let x = newPos[0];
let y = newPos[1];
// Get current pixel position.
let pixelPos = (y * canvas.width + x) * 4;
// Go up until the boundary of the fill region or the edge of the canvas is reached.
while (y >= 0 && !isBoundaryPixel(x, y, [0, 1])) {
y -= 1;
pixelPos -= canvas.width * 4;
}
y += 1;
pixelPos += canvas.width * 4;
let reachLeft = false;
let reachRight = false;
// Go down until the boundary of the fill region or the edge of the canvas is reached.
while (y < canvas.height && !isBoundaryPixel(x, y, [0, -1])) {
// FIXME: This should not be needed, but for some reason when several segments or
// vectors are plotted in certain positions the algorithm starts filling already
// filled pixels repeatedly and loops infinitely. The similar Perl code in the macro
// does not do this.
if (isFilled(pixelPos)) break;
fillPixel(pixelPos);
// While proceeding down check to the left and right to see
// if the fill region extends in those directions.
if (x > 0) {
if (!isFilled(pixelPos - 4) && !isBoundaryPixel(x - 1, y, [1, 0])) {
if (!reachLeft) {
// Add pixel to stack
pixelStack.push([x - 1, y]);
reachLeft = true;
}
} else reachLeft = false;
}
if (x < canvas.width - 1) {
if (!isFilled(pixelPos + 4) && !isBoundaryPixel(x + 1, y, [-1, 0])) {
if (!reachRight) {
// Add pixel to stack
pixelStack.push([x + 1, y]);
reachRight = true;
}
} else reachRight = false;
}
y += 1;
pixelPos += canvas.width * 4;
}
}
} else {
const isFillPixel = (x, y) => {
const curPixel = [
1.0,
(x - gt.board.origin.scrCoords[1]) / gt.board.unitX,
(gt.board.origin.scrCoords[2] - y) / gt.board.unitY
];
for (let i = 0; i < allObjects.length; ++i) {
if (allObjects[i].fillCmp(curPixel) != a_vals[i]) return false;
}
return true;
};
for (let j = 0; j < canvas.width; ++j) {
for (let k = 0; k < canvas.height; ++k) {
if (isFillPixel(j, k)) fillPixel((k * canvas.width + j) * 4);
}
}
}
context.putImageData(colorLayerData, 0, 0);
const dataURL = canvas.toDataURL('image/png');
canvas.remove();
this.fillObj = gt.board.create(
'image',
[dataURL, [bBox[0], bBox[3]], [bBox[2] - bBox[0], bBox[1] - bBox[3]]],
{
withLabel: false,
highlight: false,
fixed: true,
layer: 0,
tabindex: '',
aria: {
enabled: true,
label: () =>
`shaded region containing the point ${this.baseObj.X()}, ${this.baseObj.Y()}`,
roledescription: 'shading',
live: 'assertive',
atomic: true
}
}
);
};
if (!('isStatic' in this) || (gt.isStatic && !gt.graphingAnswers) || this.isAnswer) {
// The only time this happens is on initial construction or if the board is static.
updateReal();
return;
} else if (this.isStatic) return;
if (this.updateTimeout) clearTimeout(this.updateTimeout);
this.updateTimeout = setTimeout(updateReal, 100);
}
stringify() {
return [
this.constructor.strId,
`(${gt.snapRound(this.baseObj.X(), gt.snapSizeX)},${gt.snapRound(
this.baseObj.Y(),
gt.snapSizeY
)})`
].join(',');
}
static restore(string) {
let pointData = gt.pointRegexp.exec(string);
const points = [];
while (pointData) {
points.push(pointData.slice(1, 3));
pointData = gt.pointRegexp.exec(string);
}
if (!points.length) return false;
return new this(gt.createPoint(parseFloat(points[0][0]), parseFloat(points[0][1])));
}
// This is the icon used for the fill tool and fill graph object.
static fillIcon(color) {
return (
'data:image/svg+xml,' +
encodeURIComponent(
"<svg xmlns:svg='http://www.w3.org/2000/svg' xmlns='http://www.w3.org/2000/svg' " +
"version='1.1' viewBox='0 0 32 32' height='32px' width='32px'><g>" +
"<path d='m 13.466084,10.267728 -4.9000003,8.4 4.9000003,4.9 8.4,-4.9 z' " +
`opacity='1' fill='${color}' fill-opacity='1' stroke='#000000' ` +
"stroke-width='1.3' stroke-linecap='butt' stroke-linejoin='miter' " +
"stroke-opacity='1' stroke-miterlimit='4' stroke-dasharray='none' />" +
"<path d='M 16.266084,15.780798 V 6.273173' fill='none' stroke='#000000' " +
"stroke-width='1.38' stroke-linecap='round' stroke-linejoin='miter' " +
"stroke-miterlimit='4' stroke-dasharray='none' stroke-opacity='1' />" +
"<path d='m 20,16 c 0,0 2,-1 3,0 1,0 1,1 2,2 0,1 0,2 0,3 0,1 0,2 0,2 0,0 -1,0 " +
"-1,0 -1,-1 -1,-1 -1,-2 0,-1 0,-1 -1,-2 0,-1 0,-2 -1,-2 -1,-1 -2,-1 -1,-1 z' " +
"fill='#0900ff' fill-opacity='1' stroke='#000000' stroke-width='0.7px' " +
"stroke-linecap='butt' stroke-linejoin='miter' stroke-opacity='1' />" +
'</g></svg>'
)
);
}
};
},
FillTool(gt) {
return class FillTool extends gt.GenericTool {
object = 'fill';
useStandardActivation = true;
activationHelpText = 'Choose a point in the region to be filled.';
useStandardDeactivation = true;
constructor(container, iconName, tooltip) {
super(
container,
iconName ?? 'fill',
tooltip ?? 'Region Shading Tool: Shade a region in the graph.'
);
}
handleKeyEvent(e) {
if (!this.hlObjs.hl_point || !gt.board.containerObj.contains(document.activeElement)) return;
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
e.stopPropagation();
this.phase1(this.hlObjs.hl_point.coords.usrCoords);
}
}
updateHighlights(e) {
this.hlObjs.hl_point?.rendNode.focus();
let coords;
if (e instanceof MouseEvent && e.type === 'pointermove') {
coords = gt.getMouseCoords(e);
this.hlObjs.hl_point?.setPosition(JXG.COORDS_BY_USER, [
coords.usrCoords[1],
coords.usrCoords[2]
]);
} else if (e instanceof KeyboardEvent && e.type === 'keydown') {
coords = this.hlObjs.hl_point.coords;
} else if (e instanceof JXG.Coords) {
coords = e;
this.hlObjs.hl_point?.setPosition(JXG.COORDS_BY_USER, [
coords.usrCoords[1],
coords.usrCoords[2]
]);
} else return false;
if (!this.hlObjs.hl_point) {
this.hlObjs.hl_point = gt.board.create('point', [coords.usrCoords[1], coords.usrCoords[2]], {
size: 2,
strokeColor: 'transparent',
fillColor: 'transparent',
strokeOpacity: 0,
fillOpacity: 0,
highlight: false,
withLabel: false,
snapToGrid: true,
snapSizeX: gt.snapSizeX,
snapSizeY: gt.snapSizeY,
tabindex: 0,
aria: {
enabled: true,
label: (p) => `shade the region containing the point ${p.X()}, ${p.Y()}`,
roledescription: 'shading point',
live: 'assertive',
atomic: true
}
});
this.hlObjs.hl_point.rendNode.classList.add('hidden-fill-point');
this.hlObjs.hl_icon = gt.board.create(
'image',
[
gt.graphObjectTypes.fill.fillIcon(gt.color.fill),
[
() => this.hlObjs.hl_point.X() - 12 / gt.board.unitX,
() => this.hlObjs.hl_point.Y() - 12 / gt.board.unitY
],
[() => 24 / gt.board.unitX, () => 24 / gt.board.unitY]
],
{
withLabel: false,
highlight: false,
fixed: true,
layer: 8,
tabindex: '',
aria: { enabled: true, hidden: true, live: 'off' }
}
);
this.hlObjs.hl_point.rendNode.focus();
}
// Make sure the point/icon is not moved off the board.
if (e instanceof Event) gt.adjustDragPosition(e, this.hlObjs.hl_point);
gt.setTextCoords(coords.usrCoords[1], coords.usrCoords[2]);
gt.board.update();
return true;
}
phase1(coords) {
// Don't allow the fill to be created off the board
if (!gt.boardHasPoint(coords[1], coords[2])) return;
gt.board.off('up');
gt.selectedObj = new gt.graphObjectTypes[this.object](gt.createPoint(coords[1], coords[2]));
gt.graphedObjs.push(gt.selectedObj);
this.finish();
}
};
}
};
})();