easyannotate 0.4.0__py3-none-any.whl

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 (109) hide show
  1. data_factory/__init__.py +82 -0
  2. data_factory/__main__.py +6 -0
  3. data_factory/annotate/__init__.py +15 -0
  4. data_factory/annotate/attach.py +398 -0
  5. data_factory/annotate/demo.py +161 -0
  6. data_factory/annotate/images.py +443 -0
  7. data_factory/annotate/labels.py +399 -0
  8. data_factory/annotate/loop.py +359 -0
  9. data_factory/annotate/projects.py +207 -0
  10. data_factory/annotate/review.py +471 -0
  11. data_factory/annotate/schema.sql +171 -0
  12. data_factory/annotate/shapes.py +488 -0
  13. data_factory/annotate/store.py +292 -0
  14. data_factory/annotate/tools/__init__.py +39 -0
  15. data_factory/annotate/tools/fake.py +170 -0
  16. data_factory/annotate/tools/install.py +254 -0
  17. data_factory/annotate/tools/local.py +389 -0
  18. data_factory/annotate/tools/postprocess.py +175 -0
  19. data_factory/annotate/tools/protocol.py +238 -0
  20. data_factory/annotate/tools/registry.py +196 -0
  21. data_factory/annotate/tools/results.py +83 -0
  22. data_factory/annotate/tools/serve.py +106 -0
  23. data_factory/cli/__init__.py +21 -0
  24. data_factory/cli/main.py +837 -0
  25. data_factory/cli/menu.py +173 -0
  26. data_factory/cli/render.py +158 -0
  27. data_factory/core/__init__.py +11 -0
  28. data_factory/core/annotations/__init__.py +5 -0
  29. data_factory/core/annotations/coco.py +394 -0
  30. data_factory/core/annotations/csvfmt.py +174 -0
  31. data_factory/core/annotations/dota.py +98 -0
  32. data_factory/core/annotations/formats.py +626 -0
  33. data_factory/core/annotations/labelme.py +153 -0
  34. data_factory/core/annotations/model.py +334 -0
  35. data_factory/core/annotations/voc.py +231 -0
  36. data_factory/core/annotations/yolo.py +283 -0
  37. data_factory/core/bktree.py +89 -0
  38. data_factory/core/fs.py +245 -0
  39. data_factory/core/imaging.py +626 -0
  40. data_factory/core/ops/__init__.py +44 -0
  41. data_factory/core/ops/analyze.py +383 -0
  42. data_factory/core/ops/annotate_export.py +326 -0
  43. data_factory/core/ops/audit.py +274 -0
  44. data_factory/core/ops/augment.py +454 -0
  45. data_factory/core/ops/collect.py +241 -0
  46. data_factory/core/ops/combine.py +582 -0
  47. data_factory/core/ops/convert.py +212 -0
  48. data_factory/core/ops/dataset.py +246 -0
  49. data_factory/core/ops/dedup.py +235 -0
  50. data_factory/core/ops/export.py +168 -0
  51. data_factory/core/ops/image.py +407 -0
  52. data_factory/core/ops/labels.py +215 -0
  53. data_factory/core/ops/pairing.py +133 -0
  54. data_factory/core/ops/rename.py +154 -0
  55. data_factory/core/ops/report.py +323 -0
  56. data_factory/core/ops/visualize.py +164 -0
  57. data_factory/core/pairs.py +144 -0
  58. data_factory/core/parallel.py +191 -0
  59. data_factory/core/provenance.py +136 -0
  60. data_factory/core/registry.py +339 -0
  61. data_factory/core/stats.py +403 -0
  62. data_factory/core/types.py +148 -0
  63. data_factory/core/writer.py +194 -0
  64. data_factory/desktop.py +207 -0
  65. data_factory/hardware.py +243 -0
  66. data_factory/pipeline.py +192 -0
  67. data_factory/py.typed +0 -0
  68. data_factory/service/__init__.py +26 -0
  69. data_factory/service/app.py +483 -0
  70. data_factory/service/binding.py +174 -0
  71. data_factory/service/deps.py +133 -0
  72. data_factory/service/jobs.py +177 -0
  73. data_factory/service/limits.py +71 -0
  74. data_factory/service/routers/__init__.py +11 -0
  75. data_factory/service/routers/annotate.py +582 -0
  76. data_factory/service/routers/local.py +464 -0
  77. data_factory/service/routers/media.py +154 -0
  78. data_factory/service/routers/predictions.py +116 -0
  79. data_factory/service/routers/promote.py +182 -0
  80. data_factory/service/routers/tools.py +308 -0
  81. data_factory/service/static/annotate/api.js +246 -0
  82. data_factory/service/static/annotate/app.js +1696 -0
  83. data_factory/service/static/annotate/assist.js +106 -0
  84. data_factory/service/static/annotate/filmstrip.js +286 -0
  85. data_factory/service/static/annotate/hit.js +146 -0
  86. data_factory/service/static/annotate/labels.js +197 -0
  87. data_factory/service/static/annotate/render.js +286 -0
  88. data_factory/service/static/annotate/scene.js +277 -0
  89. data_factory/service/static/annotate/shapelist.js +72 -0
  90. data_factory/service/static/annotate/tools/box.js +96 -0
  91. data_factory/service/static/annotate/tools/line.js +96 -0
  92. data_factory/service/static/annotate/tools/obb.js +88 -0
  93. data_factory/service/static/annotate/tools/point.js +49 -0
  94. data_factory/service/static/annotate/tools/polygon.js +110 -0
  95. data_factory/service/static/annotate/tools/select.js +227 -0
  96. data_factory/service/static/annotate/undo.js +176 -0
  97. data_factory/service/static/annotate/viewport.js +156 -0
  98. data_factory/service/static/annotate.html +390 -0
  99. data_factory/service/static/index.html +632 -0
  100. data_factory/service/workspace.py +244 -0
  101. easyannotate/__init__.py +64 -0
  102. easyannotate/__main__.py +5 -0
  103. easyannotate/project.py +181 -0
  104. easyannotate/py.typed +0 -0
  105. easyannotate-0.4.0.dist-info/METADATA +767 -0
  106. easyannotate-0.4.0.dist-info/RECORD +109 -0
  107. easyannotate-0.4.0.dist-info/WHEEL +4 -0
  108. easyannotate-0.4.0.dist-info/entry_points.txt +4 -0
  109. easyannotate-0.4.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,110 @@
1
+ // Drawing a polygon: click vertices, close to finish.
2
+ //
3
+ // Three ways to close, because people reach for different ones and being
4
+ // wrong about which costs a whole outline: Enter, double-click, or clicking
5
+ // the first point again. Escape abandons; Backspace removes the last vertex,
6
+ // which is what you want after a misplaced click on point 40.
7
+
8
+ import { draftId, rebuildBox } from "../scene.js";
9
+ import { addShape } from "../undo.js";
10
+
11
+ export const name = "polygon";
12
+ export const cursor = "crosshair";
13
+
14
+ //: Screen pixels within which a click counts as "on the first point".
15
+ const CLOSE_RADIUS = 12;
16
+
17
+ export function create(editor) {
18
+ let points = [];
19
+ let cursorAt = null;
20
+
21
+ function finish() {
22
+ if (points.length < 3) {
23
+ editor.say("a polygon needs at least three points");
24
+ return;
25
+ }
26
+ const outline = points.map(([x, y]) => [Math.round(x), Math.round(y)]);
27
+ points = [];
28
+ cursorAt = null;
29
+
30
+ const label = editor.currentLabel();
31
+ const geometry = rebuildBox({ polygon: outline, bbox: [0, 0, 0, 0] });
32
+
33
+ if (!label) {
34
+ editor.promptForLabel({ bbox: geometry.bbox, polygon: outline });
35
+ return;
36
+ }
37
+
38
+ const shape = editor.scene.clampShape({
39
+ id: draftId(),
40
+ label: label.name,
41
+ labelIdx: label.idx,
42
+ bbox: geometry.bbox,
43
+ polygon: outline,
44
+ origin: "human",
45
+ confidence: null,
46
+ edited: false,
47
+ });
48
+ editor.undo.run(addShape(editor.scene, shape));
49
+ editor.drew();
50
+ editor.queueSave();
51
+ }
52
+
53
+ return {
54
+ name,
55
+
56
+ pointerdown(event, ix, iy) {
57
+ if (event.detail >= 2) {
58
+ finish();
59
+ return;
60
+ }
61
+ if (points.length >= 3) {
62
+ const [fx, fy] = points[0];
63
+ const near =
64
+ Math.hypot(fx - ix, fy - iy) * editor.view.scale <= CLOSE_RADIUS;
65
+ if (near) {
66
+ finish();
67
+ return;
68
+ }
69
+ }
70
+ points.push([ix, iy]);
71
+ editor.scene.invalidate();
72
+ },
73
+
74
+ pointermove(event, ix, iy) {
75
+ if (!points.length) return;
76
+ cursorAt = [ix, iy];
77
+ editor.scene.invalidate();
78
+ },
79
+
80
+ pointerup() {},
81
+
82
+ key(event) {
83
+ if (event.key === "Enter") {
84
+ finish();
85
+ return true;
86
+ }
87
+ if (event.key === "Backspace" && points.length) {
88
+ points.pop();
89
+ editor.scene.invalidate();
90
+ return true;
91
+ }
92
+ if (event.key === "Escape" && points.length) {
93
+ this.cancel();
94
+ return true;
95
+ }
96
+ return false;
97
+ },
98
+
99
+ cancel() {
100
+ points = [];
101
+ cursorAt = null;
102
+ editor.scene.invalidate();
103
+ },
104
+
105
+ draft() {
106
+ if (!points.length) return null;
107
+ return { kind: "polygon", points, cursor: cursorAt };
108
+ },
109
+ };
110
+ }
@@ -0,0 +1,227 @@
1
+ // Select, move, resize, and edit polygon vertices.
2
+ //
3
+ // The default tool, and the one that has to feel right. Everything here was
4
+ // proven in the Phase 0 spike at 60fps with 300 shapes.
5
+ //
6
+ // The rule that keeps undo sane: a drag mutates the shape live, for feedback,
7
+ // but records exactly one command on pointerup. One undo per gesture, not one
8
+ // per mouse move.
9
+
10
+ import { hitTest } from "../hit.js";
11
+ import { centroid, rebuildBox, rotatePoints } from "../scene.js";
12
+ import { changeGeometry, snapshot } from "../undo.js";
13
+
14
+ export const name = "select";
15
+ export const cursor = "default";
16
+
17
+ export function create(editor) {
18
+ let drag = null;
19
+
20
+ return {
21
+ name,
22
+
23
+ pointerdown(event, ix, iy) {
24
+ const { scene, view } = editor;
25
+ const hit = hitTest(scene, ix, iy, view.scale, (s) => editor.visible(s));
26
+
27
+ if (!hit) {
28
+ if (!event.shiftKey) scene.clearSelection();
29
+ // Dragging empty space pans. No modifier, no mode -- the same gesture
30
+ // people already expect from every map.
31
+ drag = { pan: true, x: event.offsetX, y: event.offsetY };
32
+ return;
33
+ }
34
+
35
+ if (!scene.selection.has(hit.id)) {
36
+ scene.select(hit.id, { additive: event.shiftKey });
37
+ editor.onSelectionChanged();
38
+ }
39
+
40
+ const shape = scene.get(hit.id);
41
+
42
+ if (hit.part === "rotate" && shape.polygon) {
43
+ const [cx, cy] = centroid(shape.polygon);
44
+ drag = {
45
+ id: shape.id,
46
+ part: "rotate",
47
+ ix,
48
+ iy,
49
+ before: snapshot(shape),
50
+ centre: [cx, cy],
51
+ startAngle: Math.atan2(iy - cy, ix - cx),
52
+ };
53
+ return;
54
+ }
55
+
56
+ if (hit.part.startsWith("edge-") && shape.polygon) {
57
+ // Alt on an edge midpoint inserts a vertex there. Without a modifier
58
+ // the edge just moves the shape, so a stray click near an edge does
59
+ // not silently add geometry.
60
+ if (event.altKey) {
61
+ const index = Number(hit.part.slice(5));
62
+ const before = snapshot(shape);
63
+ const [ax, ay] = shape.polygon[index];
64
+ const [bx, by] = shape.polygon[(index + 1) % shape.polygon.length];
65
+ shape.polygon.splice(index + 1, 0, [(ax + bx) / 2, (ay + by) / 2]);
66
+ rebuildBox(shape);
67
+ scene.touch();
68
+ editor.undo.push(changeGeometry(scene, shape.id, before, snapshot(shape)));
69
+ drag = { id: shape.id, part: `vertex-${index + 1}`, ix, iy, before: snapshot(shape) };
70
+ return;
71
+ }
72
+ drag = { id: shape.id, part: "body", ix, iy, before: snapshot(shape) };
73
+ return;
74
+ }
75
+
76
+ if (hit.part.startsWith("vertex-") && event.altKey && shape.polygon) {
77
+ // Alt-click deletes a vertex -- but never below a triangle, which
78
+ // would leave an outline that cannot enclose anything.
79
+ const index = Number(hit.part.slice(7));
80
+ // A line needs two points; a polygon three; a rotated box keeps four.
81
+ const minimum = shape.kind === "line" ? 2 : 3;
82
+ if (shape.kind !== "obb" && shape.polygon.length > minimum) {
83
+ const before = snapshot(shape);
84
+ shape.polygon.splice(index, 1);
85
+ rebuildBox(shape);
86
+ scene.touch();
87
+ editor.undo.push(changeGeometry(scene, shape.id, before, snapshot(shape)));
88
+ } else {
89
+ editor.say(
90
+ shape.kind === "obb"
91
+ ? "a rotated box always has four corners"
92
+ : `a ${shape.kind === "line" ? "line needs at least two" : "polygon needs at least three"} points`
93
+ );
94
+ }
95
+ return;
96
+ }
97
+
98
+ drag = { id: hit.id, part: hit.part, ix, iy, before: snapshot(shape) };
99
+ },
100
+
101
+ pointermove(event, ix, iy) {
102
+ const { scene, view } = editor;
103
+
104
+ if (drag && drag.pan) {
105
+ view.panBy(event.offsetX - drag.x, event.offsetY - drag.y);
106
+ drag.x = event.offsetX;
107
+ drag.y = event.offsetY;
108
+ scene.invalidate();
109
+ return;
110
+ }
111
+
112
+ if (!drag) {
113
+ const hit = hitTest(scene, ix, iy, view.scale, (s) => editor.visible(s));
114
+ const id = hit ? hit.id : null;
115
+ if (id !== scene.hover) {
116
+ scene.hover = id;
117
+ scene.invalidate();
118
+ }
119
+ return;
120
+ }
121
+
122
+ const shape = scene.get(drag.id);
123
+ if (!shape) return;
124
+ const dx = ix - drag.ix;
125
+ const dy = iy - drag.iy;
126
+
127
+ if (drag.part === "body") {
128
+ shape.bbox = shape.bbox.map((v, i) => v + (i % 2 === 0 ? dx : dy));
129
+ if (shape.polygon) shape.polygon = shape.polygon.map(([x, y]) => [x + dx, y + dy]);
130
+ } else if (drag.part === "rotate") {
131
+ // Rotation is applied to the shape as it was when the drag began, so
132
+ // a long drag does not accumulate rounding from every mouse move.
133
+ const [cx, cy] = drag.centre;
134
+ const angle = Math.atan2(iy - cy, ix - cx) - drag.startAngle;
135
+ shape.polygon = rotatePoints(drag.before.polygon, cx, cy, angle);
136
+ rebuildBox(shape);
137
+ } else if (drag.part.startsWith("handle-")) {
138
+ resize(shape, Number(drag.part.slice(7)), dx, dy);
139
+ } else if (drag.part.startsWith("vertex-") && shape.polygon) {
140
+ const index = Number(drag.part.slice(7));
141
+ if (shape.kind === "obb") moveCorner(shape, index, ix, iy);
142
+ else shape.polygon[index] = [ix, iy];
143
+ rebuildBox(shape);
144
+ }
145
+
146
+ drag.ix = ix;
147
+ drag.iy = iy;
148
+ scene.touch();
149
+ },
150
+
151
+ pointerup() {
152
+ if (drag && !drag.pan && drag.id) {
153
+ const shape = editor.scene.get(drag.id);
154
+ if (shape) {
155
+ editor.scene.clampShape(shape);
156
+ const after = snapshot(shape);
157
+ // Only record a command if something actually moved. A click that
158
+ // merely selects should not consume an undo step.
159
+ if (JSON.stringify(after) !== JSON.stringify(drag.before)) {
160
+ editor.undo.push(changeGeometry(editor.scene, drag.id, drag.before, after));
161
+ editor.markEdited(shape);
162
+ editor.queueSave();
163
+ }
164
+ }
165
+ }
166
+ drag = null;
167
+ },
168
+
169
+ cancel() {
170
+ drag = null;
171
+ },
172
+
173
+ draft() {
174
+ return null;
175
+ },
176
+ };
177
+ }
178
+
179
+ // Dragging one corner of a rotated box keeps it a rectangle: the opposite
180
+ // corner stays put and the two neighbours slide along their edges. Without
181
+ // this a corner drag would turn the box into an arbitrary quadrilateral, and
182
+ // every OBB format would then be lying about what it holds.
183
+ function moveCorner(shape, index, ix, iy) {
184
+ const p = shape.polygon;
185
+ const [ox, oy] = p[(index + 2) % 4];
186
+ const u = unitVector(p[(index + 1) % 4], [ox, oy]);
187
+ const v = unitVector(p[(index + 3) % 4], [ox, oy]);
188
+ const a = (ix - ox) * u[0] + (iy - oy) * u[1];
189
+ const b = (ix - ox) * v[0] + (iy - oy) * v[1];
190
+ p[(index + 1) % 4] = [ox + a * u[0], oy + a * u[1]];
191
+ p[(index + 3) % 4] = [ox + b * v[0], oy + b * v[1]];
192
+ p[index] = [ox + a * u[0] + b * v[0], oy + a * u[1] + b * v[1]];
193
+ }
194
+
195
+ function unitVector([x, y], [fromX, fromY]) {
196
+ const dx = x - fromX;
197
+ const dy = y - fromY;
198
+ const len = Math.hypot(dx, dy) || 1;
199
+ return [dx / len, dy / len];
200
+ }
201
+
202
+ // Handle order matches `handlesOf`: four corners, then four edge midpoints.
203
+ // A handle dragged past its opposite side flips the box, which is normal and
204
+ // gets normalised by `clampShape` on release.
205
+ function resize(shape, handle, dx, dy) {
206
+ const box = shape.bbox.slice();
207
+ if (handle === 0 || handle === 3 || handle === 6) box[0] += dx;
208
+ if (handle === 1 || handle === 2 || handle === 7) box[2] += dx;
209
+ if (handle === 0 || handle === 1 || handle === 4) box[1] += dy;
210
+ if (handle === 2 || handle === 3 || handle === 5) box[3] += dy;
211
+
212
+ if (shape.polygon) {
213
+ // Resizing a polygon scales its outline within the new box, so the shape
214
+ // deforms with the handle instead of the box drifting away from the
215
+ // outline it is supposed to describe.
216
+ const [ox1, oy1, ox2, oy2] = shape.bbox;
217
+ const ow = Math.max(1, ox2 - ox1);
218
+ const oh = Math.max(1, oy2 - oy1);
219
+ const nw = box[2] - box[0];
220
+ const nh = box[3] - box[1];
221
+ shape.polygon = shape.polygon.map(([x, y]) => [
222
+ box[0] + ((x - ox1) / ow) * nw,
223
+ box[1] + ((y - oy1) / oh) * nh,
224
+ ]);
225
+ }
226
+ shape.bbox = box;
227
+ }
@@ -0,0 +1,176 @@
1
+ // Undo as a command stack: explicit do/undo pairs, client-side.
2
+ //
3
+ // Not snapshots of the scene. Snapshots of a thousand-shape image are large,
4
+ // and more importantly they cannot survive a failed save -- a snapshot taken
5
+ // before a save that the server rejected would restore state the server never
6
+ // had. A command knows how to reverse itself, so the stack stays valid
7
+ // whatever happened to the network.
8
+ //
9
+ // Depth is capped. An unbounded stack in a session that runs for a day is a
10
+ // slow memory leak that shows up as "the tab got sluggish".
11
+
12
+ export const MAX_DEPTH = 200;
13
+
14
+ export class UndoStack {
15
+ constructor(depth = MAX_DEPTH) {
16
+ this.depth = depth;
17
+ this.past = [];
18
+ this.future = [];
19
+ }
20
+
21
+ get canUndo() {
22
+ return this.past.length > 0;
23
+ }
24
+
25
+ get canRedo() {
26
+ return this.future.length > 0;
27
+ }
28
+
29
+ // `command` is { label, do(), undo() }. Runs it, then records it.
30
+ run(command) {
31
+ command.do();
32
+ this.push(command);
33
+ return command;
34
+ }
35
+
36
+ // For actions already applied by a tool as the user dragged -- recording
37
+ // after the fact keeps the drag itself free of bookkeeping.
38
+ push(command) {
39
+ this.past.push(command);
40
+ if (this.past.length > this.depth) this.past.shift();
41
+ // A new action makes any redo branch unreachable, which is what everyone
42
+ // expects and what avoids having to explain a tree to the user.
43
+ this.future.length = 0;
44
+ }
45
+
46
+ undo() {
47
+ const command = this.past.pop();
48
+ if (!command) return null;
49
+ command.undo();
50
+ this.future.push(command);
51
+ return command;
52
+ }
53
+
54
+ redo() {
55
+ const command = this.future.pop();
56
+ if (!command) return null;
57
+ command.do();
58
+ this.past.push(command);
59
+ return command;
60
+ }
61
+
62
+ clear() {
63
+ this.past.length = 0;
64
+ this.future.length = 0;
65
+ }
66
+ }
67
+
68
+ // -- the commands the editor actually uses ---------------------------------
69
+
70
+ import { cloneShape } from "./scene.js";
71
+
72
+ export function addShape(scene, shape) {
73
+ return {
74
+ label: "add shape",
75
+ do: () => {
76
+ if (!scene.has(shape.id)) scene.insertAt(shape, scene.order.length);
77
+ scene.select(shape.id);
78
+ },
79
+ undo: () => scene.remove(shape.id),
80
+ };
81
+ }
82
+
83
+ export function removeShape(scene, id) {
84
+ const shape = cloneShape(scene.get(id));
85
+ const index = scene.indexOf(id);
86
+ return {
87
+ label: "delete shape",
88
+ do: () => scene.remove(id),
89
+ // Back where it was, not on top: re-stacking it would silently change
90
+ // which shape wins a hit test.
91
+ undo: () => scene.insertAt(cloneShape(shape), index),
92
+ };
93
+ }
94
+
95
+ // Geometry changes are recorded as before/after copies. A box drag produces
96
+ // one command on pointerup, not one per mouse move.
97
+ export function changeGeometry(scene, id, before, after) {
98
+ return {
99
+ label: "move shape",
100
+ do: () => apply(scene, id, after),
101
+ undo: () => apply(scene, id, before),
102
+ };
103
+ }
104
+
105
+ // Several shapes changed by one gesture -- a nudge of a multi-selection.
106
+ // `entries` is [{ id, before, after }] and stays mutable, so a held arrow key
107
+ // can keep extending the same command instead of pushing one per repeat.
108
+ export function changeMany(scene, entries) {
109
+ return {
110
+ label: "nudge",
111
+ entries,
112
+ do: () => entries.forEach((e) => apply(scene, e.id, e.after)),
113
+ undo: () => entries.forEach((e) => apply(scene, e.id, e.before)),
114
+ };
115
+ }
116
+
117
+ export function changeLabel(scene, id, before, after) {
118
+ return {
119
+ label: "change class",
120
+ do: () => {
121
+ const shape = scene.get(id);
122
+ if (!shape) return;
123
+ shape.label = after.label;
124
+ shape.labelIdx = after.labelIdx;
125
+ scene.touch();
126
+ },
127
+ undo: () => {
128
+ const shape = scene.get(id);
129
+ if (!shape) return;
130
+ shape.label = before.label;
131
+ shape.labelIdx = before.labelIdx;
132
+ scene.touch();
133
+ },
134
+ };
135
+ }
136
+
137
+ // Occluded, truncated, difficult: flags on the box rather than more classes.
138
+ export function changeAttributes(scene, id, before, after) {
139
+ const set = (value) => {
140
+ const shape = scene.get(id);
141
+ if (!shape) return;
142
+ shape.attributes = { ...value };
143
+ scene.touch();
144
+ };
145
+ return { label: "change attribute", do: () => set(after), undo: () => set(before) };
146
+ }
147
+
148
+ export function addMany(scene, shapes) {
149
+ const copies = shapes.map(cloneShape);
150
+ return {
151
+ label: "copy shapes",
152
+ do: () => {
153
+ for (const shape of copies) {
154
+ if (!scene.has(shape.id)) scene.insertAt(cloneShape(shape), scene.order.length);
155
+ }
156
+ },
157
+ undo: () => {
158
+ for (const shape of copies) scene.remove(shape.id);
159
+ },
160
+ };
161
+ }
162
+
163
+ function apply(scene, id, state) {
164
+ const shape = scene.get(id);
165
+ if (!shape) return;
166
+ shape.bbox = state.bbox.slice();
167
+ shape.polygon = state.polygon ? state.polygon.map((p) => p.slice()) : null;
168
+ scene.touch();
169
+ }
170
+
171
+ export function snapshot(shape) {
172
+ return {
173
+ bbox: shape.bbox.slice(),
174
+ polygon: shape.polygon ? shape.polygon.map((p) => p.slice()) : null,
175
+ };
176
+ }
@@ -0,0 +1,156 @@
1
+ // The view transform, and the one technique that makes a canvas editor fast.
2
+ //
3
+ // Phase 0 measured this: drawing a 12-megapixel bitmap scaled down to 1600px
4
+ // wide costs 29ms per frame, because the browser resamples all 12 megapixels
5
+ // every time. Pre-building the image halved repeatedly and drawing from the
6
+ // level nearest the display size takes that to 0.6ms -- a 48x improvement, and
7
+ // the difference between unusable and idle.
8
+ //
9
+ // See spikes/canvas/README.md for the numbers.
10
+
11
+ export const MIN_SCALE = 0.02;
12
+ export const MAX_SCALE = 20;
13
+
14
+ export class Viewport {
15
+ constructor() {
16
+ this.scale = 1;
17
+ this.tx = 0;
18
+ this.ty = 0;
19
+ this.width = 1;
20
+ this.height = 1;
21
+ }
22
+
23
+ setImageSize(width, height) {
24
+ this.width = Math.max(1, width);
25
+ this.height = Math.max(1, height);
26
+ }
27
+
28
+ toImage(px, py) {
29
+ return [(px - this.tx) / this.scale, (py - this.ty) / this.scale];
30
+ }
31
+
32
+ toScreen(ix, iy) {
33
+ return [ix * this.scale + this.tx, iy * this.scale + this.ty];
34
+ }
35
+
36
+ // Fit the whole image with a small margin. `F` in the editor.
37
+ fit(rect) {
38
+ this.scale =
39
+ Math.min(rect.width / this.width, rect.height / this.height) * 0.95;
40
+ this.centre(rect);
41
+ }
42
+
43
+ // 1:1 pixels. `0` in the editor, and the only zoom at which fine polygon
44
+ // work is honest about what it is doing.
45
+ actual(rect) {
46
+ this.scale = 1;
47
+ this.centre(rect);
48
+ }
49
+
50
+ centre(rect) {
51
+ this.tx = (rect.width - this.width * this.scale) / 2;
52
+ this.ty = (rect.height - this.height * this.scale) / 2;
53
+ }
54
+
55
+ // Zoom about a point, so the pixel under the cursor stays under the cursor.
56
+ // Anchoring anywhere else is the single most disorienting thing an image
57
+ // editor can do.
58
+ zoomAt(px, py, factor) {
59
+ const [ix, iy] = this.toImage(px, py);
60
+ this.scale = clamp(this.scale * factor, MIN_SCALE, MAX_SCALE);
61
+ this.tx = px - ix * this.scale;
62
+ this.ty = py - iy * this.scale;
63
+ }
64
+
65
+ panBy(dx, dy) {
66
+ this.tx += dx;
67
+ this.ty += dy;
68
+ }
69
+ }
70
+
71
+ function clamp(value, low, high) {
72
+ return Math.max(low, Math.min(high, value));
73
+ }
74
+
75
+ // -- mip levels -------------------------------------------------------------
76
+
77
+ // Halve repeatedly down to 64px. Costs one pass over the image at load, and
78
+ // buys back most of the frame budget at every zoom below 1:1.
79
+ export function buildMips(source) {
80
+ const levels = [source];
81
+ let width = source.width;
82
+ let height = source.height;
83
+
84
+ while (width > 64 && height > 64) {
85
+ const previous = levels[levels.length - 1];
86
+ width = Math.max(1, Math.floor(width / 2));
87
+ height = Math.max(1, Math.floor(height / 2));
88
+ const canvas = document.createElement("canvas");
89
+ canvas.width = width;
90
+ canvas.height = height;
91
+ const ctx = canvas.getContext("2d");
92
+ ctx.imageSmoothingEnabled = true;
93
+ ctx.imageSmoothingQuality = "high";
94
+ ctx.drawImage(previous, 0, 0, width, height);
95
+ levels.push(canvas);
96
+ }
97
+ return levels;
98
+ }
99
+
100
+ // The smallest level still at least as wide as we need, so we downsample a
101
+ // little rather than upsampling a blurry one.
102
+ export function mipFor(levels, displayWidth) {
103
+ for (let i = levels.length - 1; i >= 0; i--) {
104
+ if (levels[i].width >= displayWidth) return levels[i];
105
+ }
106
+ return levels[0];
107
+ }
108
+
109
+ // Fetch, decode and mip an image without stalling the main thread: `decode()`
110
+ // and `createImageBitmap` both run off it, which matters because this is also
111
+ // how the next image is prefetched while somebody is mid-drag on this one.
112
+ // Resolves to null on failure rather than rejecting -- a missing image is an
113
+ // ordinary state the editor reports, not an exception.
114
+ export async function decodePixels(url) {
115
+ const img = new Image();
116
+ img.src = url;
117
+ try {
118
+ await img.decode();
119
+ } catch {
120
+ return null;
121
+ }
122
+ let mips;
123
+ try {
124
+ mips = await buildMipsAsync(img);
125
+ } catch {
126
+ mips = buildMips(img);
127
+ }
128
+ return { mips, width: img.naturalWidth, height: img.naturalHeight };
129
+ }
130
+
131
+ async function buildMipsAsync(source) {
132
+ if (typeof createImageBitmap !== "function") return buildMips(source);
133
+ const levels = [source];
134
+ let width = source.naturalWidth || source.width;
135
+ let height = source.naturalHeight || source.height;
136
+ while (width > 64 && height > 64) {
137
+ width = Math.max(1, Math.floor(width / 2));
138
+ height = Math.max(1, Math.floor(height / 2));
139
+ levels.push(
140
+ await createImageBitmap(levels[levels.length - 1], {
141
+ resizeWidth: width,
142
+ resizeHeight: height,
143
+ resizeQuality: "high",
144
+ }),
145
+ );
146
+ }
147
+ return levels;
148
+ }
149
+
150
+ // Bitmaps hold GPU/native memory the garbage collector does not see; give it
151
+ // back explicitly when an image leaves the cache.
152
+ export function releaseMips(levels) {
153
+ for (const level of levels || []) {
154
+ if (typeof ImageBitmap !== "undefined" && level instanceof ImageBitmap) level.close();
155
+ }
156
+ }