qrdx 0.0.46 → 0.0.47
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +353 -300
- package/dist/index.js +27 -7
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +27 -7
- package/dist/index.mjs.map +1 -1
- package/dist/qr-code-canvas.js +12 -0
- package/dist/qr-code-canvas.js.map +1 -0
- package/dist/qr-code-canvas.mjs +12 -0
- package/dist/qr-code-canvas.mjs.map +1 -0
- package/dist/src/api.d.ts.map +1 -1
- package/dist/src/art-trace.d.ts +46 -0
- package/dist/src/art-trace.d.ts.map +1 -0
- package/dist/src/art.d.ts +138 -0
- package/dist/src/art.d.ts.map +1 -0
- package/dist/src/body-patterns.d.ts +34 -0
- package/dist/src/body-patterns.d.ts.map +1 -0
- package/dist/src/codegen.d.ts +5 -5
- package/dist/src/codegen.d.ts.map +1 -1
- package/dist/src/codeword-map.d.ts +40 -0
- package/dist/src/codeword-map.d.ts.map +1 -0
- package/dist/src/constants.d.ts +4 -7
- package/dist/src/constants.d.ts.map +1 -1
- package/dist/src/corner-dot.d.ts +3 -1
- package/dist/src/corner-dot.d.ts.map +1 -1
- package/dist/src/corner-eye.d.ts +5 -2
- package/dist/src/corner-eye.d.ts.map +1 -1
- package/dist/src/detection.d.ts.map +1 -1
- package/dist/src/download.d.ts +22 -5
- package/dist/src/download.d.ts.map +1 -1
- package/dist/src/eps.d.ts +62 -0
- package/dist/src/eps.d.ts.map +1 -0
- package/dist/src/frame-icons.d.ts +11 -0
- package/dist/src/frame-icons.d.ts.map +1 -0
- package/dist/src/frame-import.d.ts +61 -0
- package/dist/src/frame-import.d.ts.map +1 -0
- package/dist/src/frame-spec.d.ts +24 -0
- package/dist/src/frame-spec.d.ts.map +1 -0
- package/dist/src/frame-styles.d.ts +50 -0
- package/dist/src/frame-styles.d.ts.map +1 -0
- package/dist/src/frame.d.ts +126 -0
- package/dist/src/frame.d.ts.map +1 -0
- package/dist/src/frames/builtin.d.ts +8 -0
- package/dist/src/frames/builtin.d.ts.map +1 -0
- package/dist/src/frames/official.d.ts +18 -0
- package/dist/src/frames/official.d.ts.map +1 -0
- package/dist/src/helpers.d.ts +15 -2
- package/dist/src/helpers.d.ts.map +1 -1
- package/dist/src/index.d.ts +24 -13
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/logo-budget.d.ts +54 -0
- package/dist/src/logo-budget.d.ts.map +1 -0
- package/dist/src/logo-cleanup.d.ts +25 -0
- package/dist/src/logo-cleanup.d.ts.map +1 -0
- package/dist/src/logo.d.ts +28 -0
- package/dist/src/logo.d.ts.map +1 -0
- package/dist/src/print.d.ts +73 -0
- package/dist/src/print.d.ts.map +1 -0
- package/dist/src/qr-code-canvas.d.ts +13 -0
- package/dist/src/qr-code-canvas.d.ts.map +1 -0
- package/dist/src/qr-code.d.ts +4 -2
- package/dist/src/qr-code.d.ts.map +1 -1
- package/dist/src/qr-outline.d.ts +41 -0
- package/dist/src/qr-outline.d.ts.map +1 -0
- package/dist/src/qr-shape.d.ts +72 -0
- package/dist/src/qr-shape.d.ts.map +1 -0
- package/dist/src/scan-risk.d.ts +40 -0
- package/dist/src/scan-risk.d.ts.map +1 -0
- package/dist/src/scan-score.d.ts +154 -0
- package/dist/src/scan-score.d.ts.map +1 -0
- package/dist/src/shapes.d.ts +36 -0
- package/dist/src/shapes.d.ts.map +1 -0
- package/dist/src/silhouette.d.ts +28 -0
- package/dist/src/silhouette.d.ts.map +1 -0
- package/dist/src/utils/color.d.ts.map +1 -1
- package/dist/src/utils/fmt.d.ts +24 -0
- package/dist/src/utils/fmt.d.ts.map +1 -0
- package/dist/src/utils/paint.d.ts +80 -0
- package/dist/src/utils/paint.d.ts.map +1 -0
- package/dist/src/utils/parse-color.d.ts +21 -0
- package/dist/src/utils/parse-color.d.ts.map +1 -0
- package/dist/src/utils/path-data.d.ts +24 -0
- package/dist/src/utils/path-data.d.ts.map +1 -0
- package/dist/src/utils/png.d.ts +16 -0
- package/dist/src/utils/png.d.ts.map +1 -0
- package/dist/src/utils/polygon-clip.d.ts +26 -0
- package/dist/src/utils/polygon-clip.d.ts.map +1 -0
- package/dist/src/utils/print-shared.d.ts +20 -0
- package/dist/src/utils/print-shared.d.ts.map +1 -0
- package/dist/src/utils/svg-geometry.d.ts +49 -0
- package/dist/src/utils/svg-geometry.d.ts.map +1 -0
- package/dist/src/utils/svg-gradient.d.ts +59 -0
- package/dist/src/utils/svg-gradient.d.ts.map +1 -0
- package/dist/src/utils/svg-painter.d.ts +152 -0
- package/dist/src/utils/svg-painter.d.ts.map +1 -0
- package/dist/src/utils.d.ts +18 -2
- package/dist/src/utils.d.ts.map +1 -1
- package/dist/types/art.d.ts +64 -0
- package/dist/types/art.d.ts.map +1 -0
- package/dist/types/color.d.ts +125 -7
- package/dist/types/color.d.ts.map +1 -1
- package/dist/types/corner-dot.d.ts +52 -2
- package/dist/types/corner-dot.d.ts.map +1 -1
- package/dist/types/corner-eye.d.ts +43 -2
- package/dist/types/corner-eye.d.ts.map +1 -1
- package/dist/types/frame-spec.d.ts +3509 -0
- package/dist/types/frame-spec.d.ts.map +1 -0
- package/dist/types/frame.d.ts +68 -0
- package/dist/types/frame.d.ts.map +1 -0
- package/dist/types/image-pattern.d.ts +15 -1
- package/dist/types/image-pattern.d.ts.map +1 -1
- package/dist/types/index.d.ts +15 -9
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js +6 -0
- package/dist/types/index.js.map +1 -0
- package/dist/types/index.mjs +6 -0
- package/dist/types/index.mjs.map +1 -0
- package/dist/types/qr.d.ts +1684 -4
- package/dist/types/qr.d.ts.map +1 -1
- package/dist/types/template.d.ts +2 -2
- package/dist/types/template.d.ts.map +1 -1
- package/package.json +68 -25
- package/src/api.tsx +67 -17
- package/src/art-trace.ts +554 -0
- package/src/art.tsx +2226 -0
- package/src/body-patterns.tsx +389 -0
- package/src/codegen.ts +10 -5
- package/src/codeword-map.ts +265 -0
- package/src/constants.ts +4 -8
- package/src/corner-dot.tsx +209 -33
- package/src/corner-eye.ts +328 -60
- package/src/detection.ts +5 -11
- package/src/download.tsx +123 -52
- package/src/eps.ts +701 -0
- package/src/frame-icons.ts +325 -0
- package/src/frame-import.ts +1198 -0
- package/src/frame-spec.ts +518 -0
- package/src/frame-styles.ts +1095 -0
- package/src/frame.tsx +630 -0
- package/src/frames/builtin/banner-bottom.json +58 -0
- package/src/frames/builtin/circle.json +81 -0
- package/src/frames/builtin/rounded-border.json +60 -0
- package/src/frames/builtin/ticket.json +51 -0
- package/src/frames/builtin.ts +20 -0
- package/src/frames/official/attendance.json +110 -0
- package/src/frames/official/audio-guide.json +95 -0
- package/src/frames/official/book-now.json +103 -0
- package/src/frames/official/check-in.json +110 -0
- package/src/frames/official/christmas.json +131 -0
- package/src/frames/official/donate.json +77 -0
- package/src/frames/official/event-ticket.json +77 -0
- package/src/frames/official/feedback-bubble.json +73 -0
- package/src/frames/official/follow-us.json +83 -0
- package/src/frames/official/get-the-app.json +107 -0
- package/src/frames/official/halloween.json +80 -0
- package/src/frames/official/new-year.json +94 -0
- package/src/frames/official/order-at-table.json +86 -0
- package/src/frames/official/product-info.json +119 -0
- package/src/frames/official/register-product.json +77 -0
- package/src/frames/official/review-us.json +127 -0
- package/src/frames/official/rsvp-card.json +112 -0
- package/src/frames/official/save-contact.json +117 -0
- package/src/frames/official/scan-to-pay.json +94 -0
- package/src/frames/official/shop-window.json +81 -0
- package/src/frames/official/sign-rider.json +81 -0
- package/src/frames/official/table-tent.json +75 -0
- package/src/frames/official/wifi-card.json +89 -0
- package/src/frames/official/winter.json +142 -0
- package/src/frames/official.ts +77 -0
- package/src/helpers.ts +168 -11
- package/src/index.tsx +141 -172
- package/src/logo-budget.ts +226 -0
- package/src/logo-cleanup.ts +146 -0
- package/src/logo.tsx +137 -0
- package/src/print.ts +794 -0
- package/src/qr-code-canvas.tsx +241 -0
- package/src/qr-code.tsx +51 -16
- package/src/qr-outline.ts +511 -0
- package/src/qr-shape.ts +255 -0
- package/src/scan-risk.ts +197 -0
- package/src/scan-score.ts +1629 -0
- package/src/shapes.ts +169 -0
- package/src/silhouette.ts +334 -0
- package/src/utils/color.ts +10 -1
- package/src/utils/fmt.ts +59 -0
- package/src/utils/paint.ts +317 -0
- package/src/utils/parse-color.ts +135 -0
- package/src/utils/path-data.ts +182 -0
- package/src/utils/png.ts +175 -0
- package/src/utils/polygon-clip.ts +163 -0
- package/src/utils/print-shared.ts +74 -0
- package/src/utils/svg-geometry.ts +838 -0
- package/src/utils/svg-gradient.ts +407 -0
- package/src/utils/svg-painter.ts +946 -0
- package/src/utils.tsx +794 -385
- package/types/art.ts +74 -0
- package/types/color.ts +132 -12
- package/types/corner-dot.ts +41 -4
- package/types/corner-eye.ts +31 -4
- package/types/frame-spec.ts +748 -0
- package/types/frame.ts +67 -0
- package/types/image-pattern.ts +15 -0
- package/types/index.ts +106 -4
- package/types/qr.ts +180 -2
- package/types/template.ts +2 -2
- package/dist/cli.js +0 -4319
package/src/art.tsx
ADDED
|
@@ -0,0 +1,2226 @@
|
|
|
1
|
+
/** biome-ignore-all lint/style/noMagicNumbers: color math and module geometry */
|
|
2
|
+
// Art modes: Logo QR and Image QR, as plain vector shapes (no AI, no images),
|
|
3
|
+
// so SVG, PNG, PDF and EPS exports all look the same.
|
|
4
|
+
//
|
|
5
|
+
// Both modes rest on one scan model. A phone camera blurs the code by about
|
|
6
|
+
// a third of a module (σ ≈ 0.3) and its binarizer compares each module's
|
|
7
|
+
// center with the average of the modules around it. So every module gets a
|
|
8
|
+
// center dot in its true dark/light value, and the picture around the dot is
|
|
9
|
+
// left as it is wherever the blurred result already reads correctly; only
|
|
10
|
+
// modules that would read wrong are pushed toward dark or light, and only as
|
|
11
|
+
// far as needed. That keeps the picture faithful and every code scannable.
|
|
12
|
+
//
|
|
13
|
+
// - Logo QR, "blend": the logo, traced into crisp vector shapes, fills the
|
|
14
|
+
// code under a dot screen (dark dots on dark modules, light dots on light
|
|
15
|
+
// ones, skipped where the logo already gives the right tone).
|
|
16
|
+
// - Logo QR, "badge": the logo on a rounded plate in the middle, with modules
|
|
17
|
+
// and eyes tinted in the logo's colors. The plate is sized from the code's
|
|
18
|
+
// real error correction (codeword-map.ts), not from its width.
|
|
19
|
+
// - Image QR, "color": the photo at 3–4 sub-cells per module, luminance
|
|
20
|
+
// adjusted per module where needed, under tinted center dots.
|
|
21
|
+
// - Image QR, "mono": Floyd–Steinberg halftone of the photo at 3 × 3
|
|
22
|
+
// sub-cells per module, with each module's center sub-cell forced to its
|
|
23
|
+
// value (after Chu et al., "Halftone QR Codes", SIGGRAPH Asia 2013).
|
|
24
|
+
// Finder, alignment and format patterns always stay crisp.
|
|
25
|
+
import type { JSX } from "react";
|
|
26
|
+
import {
|
|
27
|
+
QR_ART_MAX_SAMPLE_SIZE,
|
|
28
|
+
QR_ART_MODES,
|
|
29
|
+
QR_ART_VARIANTS,
|
|
30
|
+
type QRArt,
|
|
31
|
+
type QRArtImage,
|
|
32
|
+
type QRArtMode,
|
|
33
|
+
type QRArtVariant,
|
|
34
|
+
} from "../types/art";
|
|
35
|
+
import type { Modules } from "../types/common";
|
|
36
|
+
import type { EyePosition } from "../types/qr";
|
|
37
|
+
import {
|
|
38
|
+
type ArtBitmap,
|
|
39
|
+
luma,
|
|
40
|
+
type RGB,
|
|
41
|
+
type TracedLogo,
|
|
42
|
+
traceLogo,
|
|
43
|
+
} from "./art-trace";
|
|
44
|
+
import {
|
|
45
|
+
type CodewordMap,
|
|
46
|
+
damagedCodewords,
|
|
47
|
+
getCodewordMap,
|
|
48
|
+
} from "./codeword-map";
|
|
49
|
+
import { roundTo } from "./utils/fmt";
|
|
50
|
+
import { parseColor } from "./utils/parse-color";
|
|
51
|
+
|
|
52
|
+
/** Intensity used when `art.intensity` is not set. */
|
|
53
|
+
export const DEFAULT_ART_INTENSITY = 0.6;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Sample grid sizes `loadQRArtImage` uses per mode. 160 × 160 RGBA is about
|
|
57
|
+
* 133 KB of base64, under the ~150 KB budget for art saved in themes.
|
|
58
|
+
*/
|
|
59
|
+
export const QR_ART_SAMPLE_SIZES: Record<QRArtMode, number> = {
|
|
60
|
+
logo: 160,
|
|
61
|
+
halftone: 160,
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
export interface QRArtPixels {
|
|
65
|
+
/** RGBA bytes, row by row */
|
|
66
|
+
data: ArrayLike<number>;
|
|
67
|
+
width: number;
|
|
68
|
+
height: number;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
type DecodedArtImage = ArtBitmap;
|
|
72
|
+
|
|
73
|
+
// ── Encoding ───────────────────────────────────────────────────────────────
|
|
74
|
+
|
|
75
|
+
function encodeBase64(bytes: Uint8Array): string {
|
|
76
|
+
let binary = "";
|
|
77
|
+
const chunk = 0x80_00;
|
|
78
|
+
for (let i = 0; i < bytes.length; i += chunk) {
|
|
79
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
|
|
80
|
+
}
|
|
81
|
+
return btoa(binary);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Small LRU keyed by an image's base64 data. */
|
|
85
|
+
class ImageCache<T> {
|
|
86
|
+
private readonly entries = new Map<string, T>();
|
|
87
|
+
private readonly limit: number;
|
|
88
|
+
|
|
89
|
+
constructor(limit: number) {
|
|
90
|
+
this.limit = limit;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
get(key: string, create: () => T): T {
|
|
94
|
+
const cached = this.entries.get(key);
|
|
95
|
+
if (cached !== undefined) {
|
|
96
|
+
this.entries.delete(key);
|
|
97
|
+
this.entries.set(key, cached);
|
|
98
|
+
return cached;
|
|
99
|
+
}
|
|
100
|
+
const value = create();
|
|
101
|
+
if (this.entries.size >= this.limit) {
|
|
102
|
+
const oldest = this.entries.keys().next().value;
|
|
103
|
+
if (oldest !== undefined) {
|
|
104
|
+
this.entries.delete(oldest);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
this.entries.set(key, value);
|
|
108
|
+
return value;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const decodedCache = new ImageCache<Uint8Array>(8);
|
|
113
|
+
|
|
114
|
+
function decodeBase64(data: string): Uint8Array {
|
|
115
|
+
return decodedCache.get(data, () => {
|
|
116
|
+
const binary = atob(data);
|
|
117
|
+
const bytes = new Uint8Array(binary.length);
|
|
118
|
+
for (let i = 0; i < binary.length; i++) {
|
|
119
|
+
bytes[i] = binary.charCodeAt(i);
|
|
120
|
+
}
|
|
121
|
+
return bytes;
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function decodeArtImage(image: QRArtImage): DecodedArtImage | null {
|
|
126
|
+
const { width, height, data } = image;
|
|
127
|
+
if (
|
|
128
|
+
!(Number.isInteger(width) && Number.isInteger(height)) ||
|
|
129
|
+
width < 1 ||
|
|
130
|
+
height < 1 ||
|
|
131
|
+
width > QR_ART_MAX_SAMPLE_SIZE ||
|
|
132
|
+
height > QR_ART_MAX_SAMPLE_SIZE ||
|
|
133
|
+
typeof data !== "string"
|
|
134
|
+
) {
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
try {
|
|
138
|
+
const bytes = decodeBase64(data);
|
|
139
|
+
return bytes.length === width * height * 4
|
|
140
|
+
? { width, height, data: bytes }
|
|
141
|
+
: null;
|
|
142
|
+
} catch {
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Downsamples raw RGBA pixels (from a canvas, `sharp().raw()`, …) into the
|
|
149
|
+
* compact bitmap `art.image` expects. Works everywhere, no DOM needed.
|
|
150
|
+
* `square` crops the center square first (photos are drawn cover-fit, so
|
|
151
|
+
* the crop keeps every stored pixel useful).
|
|
152
|
+
*/
|
|
153
|
+
export function createQRArtImage(
|
|
154
|
+
pixels: QRArtPixels,
|
|
155
|
+
options: { maxSize?: number; square?: boolean } = {}
|
|
156
|
+
): QRArtImage {
|
|
157
|
+
const { width: fullWidth, height: fullHeight, data } = pixels;
|
|
158
|
+
if (
|
|
159
|
+
!(fullWidth > 0 && fullHeight > 0) ||
|
|
160
|
+
data.length < fullWidth * fullHeight * 4
|
|
161
|
+
) {
|
|
162
|
+
throw new Error("Art image pixels must be width × height × 4 RGBA bytes");
|
|
163
|
+
}
|
|
164
|
+
const side = Math.min(fullWidth, fullHeight);
|
|
165
|
+
const left = options.square ? Math.floor((fullWidth - side) / 2) : 0;
|
|
166
|
+
const top = options.square ? Math.floor((fullHeight - side) / 2) : 0;
|
|
167
|
+
const sourceWidth = options.square ? side : fullWidth;
|
|
168
|
+
const sourceHeight = options.square ? side : fullHeight;
|
|
169
|
+
const maxSize = Math.min(
|
|
170
|
+
Math.max(Math.round(options.maxSize ?? QR_ART_SAMPLE_SIZES.halftone), 1),
|
|
171
|
+
QR_ART_MAX_SAMPLE_SIZE
|
|
172
|
+
);
|
|
173
|
+
const scale = Math.min(1, maxSize / Math.max(sourceWidth, sourceHeight));
|
|
174
|
+
const width = Math.max(1, Math.round(sourceWidth * scale));
|
|
175
|
+
const height = Math.max(1, Math.round(sourceHeight * scale));
|
|
176
|
+
const out = new Uint8Array(width * height * 4);
|
|
177
|
+
|
|
178
|
+
for (let y = 0; y < height; y++) {
|
|
179
|
+
const y0 = Math.floor((y * sourceHeight) / height);
|
|
180
|
+
const y1 = Math.max(y0 + 1, Math.floor(((y + 1) * sourceHeight) / height));
|
|
181
|
+
for (let x = 0; x < width; x++) {
|
|
182
|
+
const x0 = Math.floor((x * sourceWidth) / width);
|
|
183
|
+
const x1 = Math.max(x0 + 1, Math.floor(((x + 1) * sourceWidth) / width));
|
|
184
|
+
// Alpha-weighted box filter, so transparent pixels don't darken edges.
|
|
185
|
+
let r = 0;
|
|
186
|
+
let g = 0;
|
|
187
|
+
let b = 0;
|
|
188
|
+
let a = 0;
|
|
189
|
+
let count = 0;
|
|
190
|
+
for (let sy = y0; sy < y1; sy++) {
|
|
191
|
+
for (let sx = x0; sx < x1; sx++) {
|
|
192
|
+
const i = ((sy + top) * fullWidth + sx + left) * 4;
|
|
193
|
+
const alpha = (data[i + 3] as number) / 255;
|
|
194
|
+
r += (data[i] as number) * alpha;
|
|
195
|
+
g += (data[i + 1] as number) * alpha;
|
|
196
|
+
b += (data[i + 2] as number) * alpha;
|
|
197
|
+
a += alpha;
|
|
198
|
+
count++;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
const o = (y * width + x) * 4;
|
|
202
|
+
out[o] = a > 0 ? Math.round(r / a) : 0;
|
|
203
|
+
out[o + 1] = a > 0 ? Math.round(g / a) : 0;
|
|
204
|
+
out[o + 2] = a > 0 ? Math.round(b / a) : 0;
|
|
205
|
+
out[o + 3] = Math.round((a / count) * 255);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return { width, height, data: encodeBase64(out) };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async function toImageElement(
|
|
212
|
+
source: string | Blob | HTMLImageElement
|
|
213
|
+
): Promise<HTMLImageElement> {
|
|
214
|
+
if (typeof source !== "string" && !(source instanceof Blob)) {
|
|
215
|
+
if (!source.complete) {
|
|
216
|
+
await new Promise((resolve) => {
|
|
217
|
+
source.addEventListener("load", resolve, { once: true });
|
|
218
|
+
source.addEventListener("error", resolve, { once: true });
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
return source;
|
|
222
|
+
}
|
|
223
|
+
const url = typeof source === "string" ? source : URL.createObjectURL(source);
|
|
224
|
+
try {
|
|
225
|
+
return await new Promise((resolve, reject) => {
|
|
226
|
+
const img = new Image();
|
|
227
|
+
img.crossOrigin = "anonymous";
|
|
228
|
+
img.onload = () => resolve(img);
|
|
229
|
+
img.onerror = () => reject(new Error("Could not load the art image"));
|
|
230
|
+
img.src = url;
|
|
231
|
+
});
|
|
232
|
+
} finally {
|
|
233
|
+
if (typeof source !== "string") {
|
|
234
|
+
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Loads an image (data URL, same-origin URL, Blob or <img>) in the browser
|
|
241
|
+
* and samples it for `art.image`. Use `createQRArtImage` on the server.
|
|
242
|
+
* Photos (mode "halftone") are cropped to their center square.
|
|
243
|
+
*/
|
|
244
|
+
export async function loadQRArtImage(
|
|
245
|
+
source: string | Blob | HTMLImageElement,
|
|
246
|
+
options: { mode?: QRArtMode; maxSize?: number } = {}
|
|
247
|
+
): Promise<QRArtImage> {
|
|
248
|
+
if (typeof document === "undefined") {
|
|
249
|
+
throw new Error(
|
|
250
|
+
"loadQRArtImage needs a browser; pass decoded pixels to createQRArtImage instead"
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
const mode = options.mode ?? "halftone";
|
|
254
|
+
const maxSize = options.maxSize ?? QR_ART_SAMPLE_SIZES[mode];
|
|
255
|
+
const img = await toImageElement(source);
|
|
256
|
+
const naturalWidth = img.naturalWidth || img.width || maxSize;
|
|
257
|
+
const naturalHeight = img.naturalHeight || img.height || maxSize;
|
|
258
|
+
const square = mode === "halftone";
|
|
259
|
+
// Draw at up to 4× the target, then box-filter down for smooth sampling.
|
|
260
|
+
const fit = Math.min(
|
|
261
|
+
1,
|
|
262
|
+
(maxSize * 4) /
|
|
263
|
+
(square
|
|
264
|
+
? Math.min(naturalWidth, naturalHeight)
|
|
265
|
+
: Math.max(naturalWidth, naturalHeight))
|
|
266
|
+
);
|
|
267
|
+
const width = Math.max(1, Math.round(naturalWidth * fit));
|
|
268
|
+
const height = Math.max(1, Math.round(naturalHeight * fit));
|
|
269
|
+
const canvas = document.createElement("canvas");
|
|
270
|
+
canvas.width = width;
|
|
271
|
+
canvas.height = height;
|
|
272
|
+
const ctx = canvas.getContext("2d", { willReadFrequently: true });
|
|
273
|
+
if (!ctx) {
|
|
274
|
+
throw new Error("Could not get a canvas context");
|
|
275
|
+
}
|
|
276
|
+
ctx.imageSmoothingQuality = "high";
|
|
277
|
+
ctx.drawImage(img, 0, 0, width, height);
|
|
278
|
+
let pixels: ImageData;
|
|
279
|
+
try {
|
|
280
|
+
pixels = ctx.getImageData(0, 0, width, height);
|
|
281
|
+
} catch {
|
|
282
|
+
throw new Error(
|
|
283
|
+
"Could not read the art image (cross-origin images need CORS); upload it instead"
|
|
284
|
+
);
|
|
285
|
+
} finally {
|
|
286
|
+
canvas.remove();
|
|
287
|
+
}
|
|
288
|
+
return createQRArtImage(pixels, { maxSize, square });
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** True when `art` has a known mode and a well-formed image. */
|
|
292
|
+
export function isQRArtActive(art: QRArt | null | undefined): art is QRArt {
|
|
293
|
+
return Boolean(
|
|
294
|
+
art &&
|
|
295
|
+
(QR_ART_MODES as readonly string[]).includes(art.mode) &&
|
|
296
|
+
art.image &&
|
|
297
|
+
decodeArtImage(art.image)
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** The variant `art` renders with (the mode's default when unset or foreign). */
|
|
302
|
+
export function getQRArtVariant(
|
|
303
|
+
art: Pick<QRArt, "mode" | "variant">
|
|
304
|
+
): QRArtVariant {
|
|
305
|
+
const variants: readonly QRArtVariant[] = QR_ART_VARIANTS[art.mode];
|
|
306
|
+
return art.variant && variants.includes(art.variant)
|
|
307
|
+
? art.variant
|
|
308
|
+
: (variants[0] as QRArtVariant);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// ── Function patterns ──────────────────────────────────────────────────────
|
|
312
|
+
|
|
313
|
+
/** Row/column centers of the alignment patterns for a code of `version`. */
|
|
314
|
+
export function alignmentPositions(version: number, size: number): number[] {
|
|
315
|
+
if (version === 1) {
|
|
316
|
+
return [];
|
|
317
|
+
}
|
|
318
|
+
const count = Math.floor(version / 7) + 2;
|
|
319
|
+
const step =
|
|
320
|
+
version === 32 ? 26 : Math.ceil((version * 4 + 4) / (count * 2 - 2)) * 2;
|
|
321
|
+
const result = [6];
|
|
322
|
+
for (let pos = size - 7; result.length < count; pos -= step) {
|
|
323
|
+
result.splice(1, 0, pos);
|
|
324
|
+
}
|
|
325
|
+
return result;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** Alignment pattern centers, without the three under the finders. */
|
|
329
|
+
function alignmentCenters(version: number, size: number): [number, number][] {
|
|
330
|
+
const positions = alignmentPositions(version, size);
|
|
331
|
+
const last = positions.length - 1;
|
|
332
|
+
const centers: [number, number][] = [];
|
|
333
|
+
for (const [i, cx] of positions.entries()) {
|
|
334
|
+
for (const [j, cy] of positions.entries()) {
|
|
335
|
+
if (
|
|
336
|
+
!(
|
|
337
|
+
(i === 0 && j === 0) ||
|
|
338
|
+
(i === 0 && j === last) ||
|
|
339
|
+
(i === last && j === 0)
|
|
340
|
+
)
|
|
341
|
+
) {
|
|
342
|
+
centers.push([cx, cy]);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
return centers;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const KIND_DATA = 0;
|
|
350
|
+
/** Finder plus separator (8 × 8 at three corners); eyes are drawn there */
|
|
351
|
+
const KIND_FINDER = 1;
|
|
352
|
+
const KIND_ALIGNMENT = 2;
|
|
353
|
+
/** Format and version modules: drawn like data, but extra robust */
|
|
354
|
+
const KIND_STRONG = 3;
|
|
355
|
+
/** Timing patterns: decoders sample the grid without them, so drawn as data */
|
|
356
|
+
const KIND_TIMING = 4;
|
|
357
|
+
|
|
358
|
+
const kindsCache = new Map<number, Uint8Array>();
|
|
359
|
+
|
|
360
|
+
function moduleKinds(version: number): Uint8Array {
|
|
361
|
+
const cached = kindsCache.get(version);
|
|
362
|
+
if (cached) {
|
|
363
|
+
return cached;
|
|
364
|
+
}
|
|
365
|
+
const size = version * 4 + 17;
|
|
366
|
+
const kinds = new Uint8Array(size * size);
|
|
367
|
+
const set = (x0: number, y0: number, w: number, h: number, kind: number) => {
|
|
368
|
+
for (let y = Math.max(0, y0); y < Math.min(size, y0 + h); y++) {
|
|
369
|
+
for (let x = Math.max(0, x0); x < Math.min(size, x0 + w); x++) {
|
|
370
|
+
kinds[y * size + x] = kind;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
// Timing patterns, then format information
|
|
375
|
+
set(6, 0, 1, size, KIND_TIMING);
|
|
376
|
+
set(0, 6, size, 1, KIND_TIMING);
|
|
377
|
+
set(0, 8, 9, 1, KIND_STRONG);
|
|
378
|
+
set(8, 0, 1, 9, KIND_STRONG);
|
|
379
|
+
set(size - 8, 8, 8, 1, KIND_STRONG);
|
|
380
|
+
set(8, size - 8, 1, 8, KIND_STRONG);
|
|
381
|
+
if (version >= 7) {
|
|
382
|
+
set(size - 11, 0, 3, 6, KIND_STRONG);
|
|
383
|
+
set(0, size - 11, 6, 3, KIND_STRONG);
|
|
384
|
+
}
|
|
385
|
+
for (const [cx, cy] of alignmentCenters(version, size)) {
|
|
386
|
+
set(cx - 2, cy - 2, 5, 5, KIND_ALIGNMENT);
|
|
387
|
+
}
|
|
388
|
+
set(0, 0, 8, 8, KIND_FINDER);
|
|
389
|
+
set(size - 8, 0, 8, 8, KIND_FINDER);
|
|
390
|
+
set(0, size - 8, 8, 8, KIND_FINDER);
|
|
391
|
+
kindsCache.set(version, kinds);
|
|
392
|
+
return kinds;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Modules that belong to function patterns (finders with separators, timing,
|
|
397
|
+
* alignment, format and version information) for a code of `version`.
|
|
398
|
+
*/
|
|
399
|
+
export function getQRFunctionModules(version: number): boolean[][] {
|
|
400
|
+
const size = version * 4 + 17;
|
|
401
|
+
const kinds = moduleKinds(version);
|
|
402
|
+
return Array.from({ length: size }, (_, y) =>
|
|
403
|
+
Array.from({ length: size }, (_, x) => kinds[y * size + x] !== KIND_DATA)
|
|
404
|
+
);
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
type ErrorLevel = "L" | "M" | "Q" | "H";
|
|
408
|
+
|
|
409
|
+
/** Error correction level, read back from the code's format bits. */
|
|
410
|
+
function errorLevelOf(modules: Modules): ErrorLevel {
|
|
411
|
+
const row = modules[8];
|
|
412
|
+
// Format bits 14 and 13 hold the level, masked with 0b10.
|
|
413
|
+
const high = row?.[0] ? 1 : 0;
|
|
414
|
+
const low = row?.[1] ? 1 : 0;
|
|
415
|
+
const bits = (1 - high) * 2 + low;
|
|
416
|
+
return (["M", "L", "H", "Q"] as const)[bits] ?? "M";
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// ── Color math (gamma-encoded sRGB, 0–1; luma as camera binarizers see it) ─
|
|
420
|
+
|
|
421
|
+
function rgbFrom(color: string, fallback: RGB): RGB {
|
|
422
|
+
const parsed = parseColor(color);
|
|
423
|
+
if (!parsed || parsed.a === 0) {
|
|
424
|
+
return fallback;
|
|
425
|
+
}
|
|
426
|
+
return [parsed.r / 255, parsed.g / 255, parsed.b / 255];
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
const mix = (a: RGB, b: RGB, t: number): RGB => [
|
|
430
|
+
a[0] + (b[0] - a[0]) * t,
|
|
431
|
+
a[1] + (b[1] - a[1]) * t,
|
|
432
|
+
a[2] + (b[2] - a[2]) * t,
|
|
433
|
+
];
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* Moves `color` toward `anchor` just far enough to reach luma `target`
|
|
437
|
+
* (darker: at most target; lighter: at least target). Mixing in gamma space
|
|
438
|
+
* changes luma linearly and keeps the hue.
|
|
439
|
+
*/
|
|
440
|
+
function toward(color: RGB, anchor: RGB, target: number, darker: boolean) {
|
|
441
|
+
const y = luma(color);
|
|
442
|
+
if (darker ? y <= target : y >= target) {
|
|
443
|
+
return color;
|
|
444
|
+
}
|
|
445
|
+
const ya = luma(anchor);
|
|
446
|
+
if (Math.abs(y - ya) < 1e-6) {
|
|
447
|
+
return anchor;
|
|
448
|
+
}
|
|
449
|
+
return mix(color, anchor, Math.min(1, Math.max(0, (y - target) / (y - ya))));
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
const chroma = (c: RGB) => Math.max(...c) - Math.min(...c);
|
|
453
|
+
|
|
454
|
+
const distance2 = (a: RGB, b: RGB) =>
|
|
455
|
+
(a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;
|
|
456
|
+
|
|
457
|
+
const hexByte = (n: number) => n.toString(16).padStart(2, "0");
|
|
458
|
+
|
|
459
|
+
/** Hex color; `step` > 1 posterizes channels so similar colors share a path. */
|
|
460
|
+
function toHex(color: RGB, step = 1): string {
|
|
461
|
+
const q = (value: number) =>
|
|
462
|
+
Math.min(
|
|
463
|
+
255,
|
|
464
|
+
Math.round(Math.round(Math.min(Math.max(value, 0), 1) * 255) / step) *
|
|
465
|
+
step
|
|
466
|
+
);
|
|
467
|
+
return `#${hexByte(q(color[0]))}${hexByte(q(color[1]))}${hexByte(q(color[2]))}`;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/** erf, Abramowitz & Stegun 7.1.26 (error < 1.5e-7) */
|
|
471
|
+
function erf(x: number): number {
|
|
472
|
+
const sign = x < 0 ? -1 : 1;
|
|
473
|
+
const a = Math.abs(x);
|
|
474
|
+
const t = 1 / (1 + 0.327_591_1 * a);
|
|
475
|
+
const y =
|
|
476
|
+
1 -
|
|
477
|
+
((((1.061_405_429 * t - 1.453_152_027) * t + 1.421_413_741) * t -
|
|
478
|
+
0.284_496_736) *
|
|
479
|
+
t +
|
|
480
|
+
0.254_829_592) *
|
|
481
|
+
t *
|
|
482
|
+
Math.exp(-a * a);
|
|
483
|
+
return sign * y;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** Camera blur in modules (σ), the scan model's main assumption */
|
|
487
|
+
const BLUR = 0.3;
|
|
488
|
+
/** Share of a blurred module center that comes from a centered dot */
|
|
489
|
+
const circleWeight = (diameter: number) =>
|
|
490
|
+
1 - Math.exp(-((diameter / 2) ** 2) / (2 * BLUR ** 2));
|
|
491
|
+
const squareWeight = (side: number) => erf(side / (2 * BLUR * Math.SQRT2)) ** 2;
|
|
492
|
+
|
|
493
|
+
const smoothstep = (edge0: number, edge1: number, x: number) => {
|
|
494
|
+
const t = Math.min(1, Math.max(0, (x - edge0) / (edge1 - edge0)));
|
|
495
|
+
return t * t * (3 - 2 * t);
|
|
496
|
+
};
|
|
497
|
+
|
|
498
|
+
// ── Sampling ───────────────────────────────────────────────────────────────
|
|
499
|
+
|
|
500
|
+
/** Maps module-space points (0…size) onto the art image. */
|
|
501
|
+
interface Placement {
|
|
502
|
+
/** Modules per image pixel */
|
|
503
|
+
scale: number;
|
|
504
|
+
offsetX: number;
|
|
505
|
+
offsetY: number;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
function placement(
|
|
509
|
+
width: number,
|
|
510
|
+
height: number,
|
|
511
|
+
box: number,
|
|
512
|
+
fit: "contain" | "cover"
|
|
513
|
+
): Placement {
|
|
514
|
+
const scale =
|
|
515
|
+
fit === "cover"
|
|
516
|
+
? Math.max(box / width, box / height)
|
|
517
|
+
: Math.min(box / width, box / height);
|
|
518
|
+
return {
|
|
519
|
+
scale,
|
|
520
|
+
offsetX: (box - width * scale) / 2,
|
|
521
|
+
offsetY: (box - height * scale) / 2,
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/** Float RGB + alpha copy of an art bitmap. */
|
|
526
|
+
interface FloatImage {
|
|
527
|
+
width: number;
|
|
528
|
+
height: number;
|
|
529
|
+
rgb: Float32Array;
|
|
530
|
+
alpha: Float32Array;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function toFloatImage(
|
|
534
|
+
image: DecodedArtImage,
|
|
535
|
+
alpha?: Float32Array
|
|
536
|
+
): FloatImage {
|
|
537
|
+
const { width, height, data } = image;
|
|
538
|
+
const rgb = new Float32Array(width * height * 3);
|
|
539
|
+
const a = alpha ?? new Float32Array(width * height);
|
|
540
|
+
for (let p = 0; p < width * height; p++) {
|
|
541
|
+
rgb[p * 3] = data[p * 4] / 255;
|
|
542
|
+
rgb[p * 3 + 1] = data[p * 4 + 1] / 255;
|
|
543
|
+
rgb[p * 3 + 2] = data[p * 4 + 2] / 255;
|
|
544
|
+
if (!alpha) {
|
|
545
|
+
a[p] = data[p * 4 + 3] / 255;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
return { width, height, rgb, alpha: a };
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* Photos: stretch luma to the 1st–99th percentile (at most 1.6×) and lift
|
|
553
|
+
* saturation slightly, so hazy photos keep their contrast once the code's
|
|
554
|
+
* dots sit on them.
|
|
555
|
+
*/
|
|
556
|
+
function toneMap(image: DecodedArtImage): FloatImage {
|
|
557
|
+
const float = toFloatImage(image);
|
|
558
|
+
const { rgb, alpha } = float;
|
|
559
|
+
const histogram = new Float64Array(256);
|
|
560
|
+
let total = 0;
|
|
561
|
+
for (let p = 0; p < alpha.length; p++) {
|
|
562
|
+
if (alpha[p] < 0.5) {
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
const y = luma([rgb[p * 3], rgb[p * 3 + 1], rgb[p * 3 + 2]]);
|
|
566
|
+
histogram[Math.min(255, Math.floor(y * 256))] += 1;
|
|
567
|
+
total++;
|
|
568
|
+
}
|
|
569
|
+
const percentile = (share: number) => {
|
|
570
|
+
let sum = 0;
|
|
571
|
+
for (let i = 0; i < 256; i++) {
|
|
572
|
+
sum += histogram[i];
|
|
573
|
+
if (sum >= share * total) {
|
|
574
|
+
return i / 255;
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
return 1;
|
|
578
|
+
};
|
|
579
|
+
let lo = total ? percentile(0.01) : 0;
|
|
580
|
+
let hi = total ? percentile(0.99) : 1;
|
|
581
|
+
if (hi - lo < 0.15) {
|
|
582
|
+
lo = 0;
|
|
583
|
+
hi = 1;
|
|
584
|
+
}
|
|
585
|
+
const gain = Math.min(1.6, 1 / (hi - lo));
|
|
586
|
+
const offset = (lo + hi) / 2;
|
|
587
|
+
for (let p = 0; p < alpha.length; p++) {
|
|
588
|
+
const c: RGB = [rgb[p * 3], rgb[p * 3 + 1], rgb[p * 3 + 2]];
|
|
589
|
+
const y = luma(c);
|
|
590
|
+
const stretched = 0.5 + (y - offset) * gain;
|
|
591
|
+
for (let k = 0; k < 3; k++) {
|
|
592
|
+
rgb[p * 3 + k] = Math.min(1, Math.max(0, stretched + (c[k] - y) * 1.12));
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
return float;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* Bilinear color of `image` at image-space (x, y), composited over
|
|
600
|
+
* `backdrop` (`strength` < 1 fades the image toward the backdrop).
|
|
601
|
+
*/
|
|
602
|
+
function sampleOver(
|
|
603
|
+
image: FloatImage,
|
|
604
|
+
x: number,
|
|
605
|
+
y: number,
|
|
606
|
+
backdrop: RGB,
|
|
607
|
+
strength = 1
|
|
608
|
+
): RGB {
|
|
609
|
+
const { width, height, rgb, alpha } = image;
|
|
610
|
+
const fx = Math.min(Math.max(x - 0.5, 0), width - 1);
|
|
611
|
+
const fy = Math.min(Math.max(y - 0.5, 0), height - 1);
|
|
612
|
+
const x0 = Math.floor(fx);
|
|
613
|
+
const y0 = Math.floor(fy);
|
|
614
|
+
const x1 = Math.min(x0 + 1, width - 1);
|
|
615
|
+
const y1 = Math.min(y0 + 1, height - 1);
|
|
616
|
+
const tx = fx - x0;
|
|
617
|
+
const ty = fy - y0;
|
|
618
|
+
let r = 0;
|
|
619
|
+
let g = 0;
|
|
620
|
+
let b = 0;
|
|
621
|
+
let a = 0;
|
|
622
|
+
const add = (px: number, py: number, weight: number) => {
|
|
623
|
+
const p = py * width + px;
|
|
624
|
+
const w = alpha[p] * weight;
|
|
625
|
+
r += rgb[p * 3] * w;
|
|
626
|
+
g += rgb[p * 3 + 1] * w;
|
|
627
|
+
b += rgb[p * 3 + 2] * w;
|
|
628
|
+
a += w;
|
|
629
|
+
};
|
|
630
|
+
add(x0, y0, (1 - tx) * (1 - ty));
|
|
631
|
+
add(x1, y0, tx * (1 - ty));
|
|
632
|
+
add(x0, y1, (1 - tx) * ty);
|
|
633
|
+
add(x1, y1, tx * ty);
|
|
634
|
+
if (a <= 0) {
|
|
635
|
+
return backdrop;
|
|
636
|
+
}
|
|
637
|
+
const k = a * strength;
|
|
638
|
+
return [
|
|
639
|
+
backdrop[0] + (r / a - backdrop[0]) * k,
|
|
640
|
+
backdrop[1] + (g / a - backdrop[1]) * k,
|
|
641
|
+
backdrop[2] + (b / a - backdrop[2]) * k,
|
|
642
|
+
];
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
const toneCache = new ImageCache<FloatImage>(4);
|
|
646
|
+
const traceCache = new ImageCache<TracedLogo>(6);
|
|
647
|
+
const logoPixelCache = new ImageCache<FloatImage>(6);
|
|
648
|
+
|
|
649
|
+
function tracedLogo(art: QRArt, image: DecodedArtImage): TracedLogo {
|
|
650
|
+
return traceCache.get(art.image.data, () => traceLogo(image));
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/** Logo pixels with the backdrop removed (the traced logo's opacity). */
|
|
654
|
+
function logoPixels(art: QRArt, image: DecodedArtImage, traced: TracedLogo) {
|
|
655
|
+
return logoPixelCache.get(art.image.data, () =>
|
|
656
|
+
toFloatImage(image, traced.alpha)
|
|
657
|
+
);
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
// ── SVG building ───────────────────────────────────────────────────────────
|
|
661
|
+
|
|
662
|
+
// Art paths snap to 0.01 px and their scale factors to 4 decimals
|
|
663
|
+
const round = (n: number) => roundTo(n, 2);
|
|
664
|
+
const round4 = (n: number) => roundTo(n, 4);
|
|
665
|
+
|
|
666
|
+
class PathGroups {
|
|
667
|
+
private readonly groups = new Map<string, string[]>();
|
|
668
|
+
|
|
669
|
+
add(color: string, segment: string) {
|
|
670
|
+
const list = this.groups.get(color);
|
|
671
|
+
if (list) {
|
|
672
|
+
list.push(segment);
|
|
673
|
+
} else {
|
|
674
|
+
this.groups.set(color, [segment]);
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/** A run of `length` 1×1 cells starting at integer cell (x, y). */
|
|
679
|
+
cellRun(color: string, x: number, y: number, length: number) {
|
|
680
|
+
this.add(color, `M${x} ${y}h${length}.04v1.04h-${length}.04z`);
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
circle(color: string, cx: number, cy: number, r: number) {
|
|
684
|
+
this.add(color, circlePath(cx, cy, r));
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
toElements(keyPrefix: string): JSX.Element[] {
|
|
688
|
+
return [...this.groups].map(([color, segments], index) => (
|
|
689
|
+
<path d={segments.join("")} fill={color} key={`${keyPrefix}-${index}`} />
|
|
690
|
+
));
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
function circlePath(cx: number, cy: number, r: number) {
|
|
695
|
+
const d = round(r * 2);
|
|
696
|
+
const rr = round(r);
|
|
697
|
+
return `M${round(cx - r)} ${round(cy)}a${rr} ${rr} 0 1 0 ${d} 0a${rr} ${rr} 0 1 0 ${-d} 0z`;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/** Rounded rectangle (clockwise). */
|
|
701
|
+
function roundedRectPath(
|
|
702
|
+
x: number,
|
|
703
|
+
y: number,
|
|
704
|
+
w: number,
|
|
705
|
+
h: number,
|
|
706
|
+
radius: number
|
|
707
|
+
) {
|
|
708
|
+
const r = Math.min(radius, w / 2, h / 2);
|
|
709
|
+
if (r <= 0) {
|
|
710
|
+
return `M${round(x)} ${round(y)}h${round(w)}v${round(h)}h${round(-w)}z`;
|
|
711
|
+
}
|
|
712
|
+
const rr = round(r);
|
|
713
|
+
return (
|
|
714
|
+
`M${round(x + r)} ${round(y)}h${round(w - 2 * r)}a${rr} ${rr} 0 0 1 ${rr} ${rr}` +
|
|
715
|
+
`v${round(h - 2 * r)}a${rr} ${rr} 0 0 1 ${-rr} ${rr}` +
|
|
716
|
+
`h${round(-(w - 2 * r))}a${rr} ${rr} 0 0 1 ${-rr} ${-rr}` +
|
|
717
|
+
`v${round(-(h - 2 * r))}a${rr} ${rr} 0 0 1 ${rr} ${-rr}z`
|
|
718
|
+
);
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/** Solid alignment patterns (5 × 5 ring and center), as one even-odd path. */
|
|
722
|
+
function alignmentPath(
|
|
723
|
+
centers: [number, number][],
|
|
724
|
+
margin: number,
|
|
725
|
+
pixelSize: number
|
|
726
|
+
): string {
|
|
727
|
+
let d = "";
|
|
728
|
+
for (const [cx, cy] of centers) {
|
|
729
|
+
const x = (cx - 2 + margin) * pixelSize;
|
|
730
|
+
const y = (cy - 2 + margin) * pixelSize;
|
|
731
|
+
d += roundedRectPath(x, y, 5 * pixelSize, 5 * pixelSize, pixelSize * 0.35);
|
|
732
|
+
d += roundedRectPath(
|
|
733
|
+
x + pixelSize,
|
|
734
|
+
y + pixelSize,
|
|
735
|
+
3 * pixelSize,
|
|
736
|
+
3 * pixelSize,
|
|
737
|
+
pixelSize * 0.15
|
|
738
|
+
);
|
|
739
|
+
d += roundedRectPath(
|
|
740
|
+
x + 2 * pixelSize,
|
|
741
|
+
y + 2 * pixelSize,
|
|
742
|
+
pixelSize,
|
|
743
|
+
pixelSize,
|
|
744
|
+
pixelSize * 0.12
|
|
745
|
+
);
|
|
746
|
+
}
|
|
747
|
+
return d;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// ── Rendering ──────────────────────────────────────────────────────────────
|
|
751
|
+
|
|
752
|
+
export interface QRArtRenderOptions {
|
|
753
|
+
art: QRArt;
|
|
754
|
+
/** Module grid without margin (after any logo excavation) */
|
|
755
|
+
modules: Modules;
|
|
756
|
+
/** QR version of `modules` (1–40) */
|
|
757
|
+
version: number;
|
|
758
|
+
margin: number;
|
|
759
|
+
/** Width of one module in output units */
|
|
760
|
+
pixelSize: number;
|
|
761
|
+
/** Solid dark color (gradients: first stop) */
|
|
762
|
+
fgColor: string;
|
|
763
|
+
/** Solid light color (gradients: first stop) */
|
|
764
|
+
bgColor: string;
|
|
765
|
+
/**
|
|
766
|
+
* Draws dark modules in the caller's body pattern (finder modules are
|
|
767
|
+
* skipped by the caller). Logo "badge" uses it so the code keeps the
|
|
768
|
+
* chosen dot shape; without it, art draws round dots.
|
|
769
|
+
*/
|
|
770
|
+
body?: (modules: Modules) => JSX.Element | JSX.Element[] | null;
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
interface RenderContext {
|
|
774
|
+
art: QRArt;
|
|
775
|
+
image: DecodedArtImage;
|
|
776
|
+
modules: Modules;
|
|
777
|
+
size: number;
|
|
778
|
+
version: number;
|
|
779
|
+
kinds: Uint8Array;
|
|
780
|
+
margin: number;
|
|
781
|
+
pixelSize: number;
|
|
782
|
+
/** Effective strength, 0–1 */
|
|
783
|
+
t: number;
|
|
784
|
+
fg: RGB;
|
|
785
|
+
bg: RGB;
|
|
786
|
+
variant: QRArtVariant;
|
|
787
|
+
body?: QRArtRenderOptions["body"];
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/**
|
|
791
|
+
* Highest strength each variant renders with: past it the scan gate
|
|
792
|
+
* (tests/art-quality.test.ts) starts failing, so stronger settings look the
|
|
793
|
+
* same rather than stop scanning. Mono's dithered surroundings carry less
|
|
794
|
+
* contrast than solid color, so it tops out earlier.
|
|
795
|
+
*/
|
|
796
|
+
const MAX_STRENGTH: Record<QRArtVariant, number> = {
|
|
797
|
+
blend: 1,
|
|
798
|
+
badge: 1,
|
|
799
|
+
color: 0.9,
|
|
800
|
+
mono: 0.7,
|
|
801
|
+
};
|
|
802
|
+
|
|
803
|
+
/**
|
|
804
|
+
* How much lighter (luma, 0–1) the background must be than the dots for art
|
|
805
|
+
* to render. Art needs dark modules on a light background with room in
|
|
806
|
+
* between; otherwise the plain look is kept so nothing gets worse.
|
|
807
|
+
*/
|
|
808
|
+
export const QR_ART_MIN_LUMA_GAP = 0.35;
|
|
809
|
+
|
|
810
|
+
/** Why art can't render with these colors, if it can't. */
|
|
811
|
+
export type QRArtColorIssue = "inverted" | "low-contrast";
|
|
812
|
+
|
|
813
|
+
/**
|
|
814
|
+
* Null when art renders with `fgColor` on `bgColor`; otherwise why not:
|
|
815
|
+
* "inverted" (dots lighter than the background) or "low-contrast" (too
|
|
816
|
+
* close). Gradients: pass the first stop, as the renderer does. Editors use
|
|
817
|
+
* this to explain why art isn't showing instead of failing silently.
|
|
818
|
+
*/
|
|
819
|
+
export function getQRArtColorIssue(
|
|
820
|
+
fgColor: string,
|
|
821
|
+
bgColor: string
|
|
822
|
+
): QRArtColorIssue | null {
|
|
823
|
+
const fg = rgbFrom(fgColor, [0, 0, 0]);
|
|
824
|
+
const bg = rgbFrom(bgColor, [1, 1, 1]);
|
|
825
|
+
const gap = luma(bg) - luma(fg);
|
|
826
|
+
if (gap >= QR_ART_MIN_LUMA_GAP) {
|
|
827
|
+
return null;
|
|
828
|
+
}
|
|
829
|
+
return gap <= -QR_ART_MIN_LUMA_GAP ? "inverted" : "low-contrast";
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
/** Strength actually used: 0 when colors are inverted or too close. */
|
|
833
|
+
function effectiveStrength(art: QRArt, fg: RGB, bg: RGB): number {
|
|
834
|
+
const t = Math.min(
|
|
835
|
+
Math.max(art.intensity ?? DEFAULT_ART_INTENSITY, 0),
|
|
836
|
+
MAX_STRENGTH[getQRArtVariant(art)]
|
|
837
|
+
);
|
|
838
|
+
return luma(bg) - luma(fg) >= QR_ART_MIN_LUMA_GAP ? t : 0;
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
function context(options: QRArtRenderOptions): RenderContext | null {
|
|
842
|
+
const { art, modules, version } = options;
|
|
843
|
+
const image = art.image && decodeArtImage(art.image);
|
|
844
|
+
if (!(image && (QR_ART_MODES as readonly string[]).includes(art.mode))) {
|
|
845
|
+
return null;
|
|
846
|
+
}
|
|
847
|
+
const size = modules.length;
|
|
848
|
+
if (size !== version * 4 + 17) {
|
|
849
|
+
return null;
|
|
850
|
+
}
|
|
851
|
+
const fg = rgbFrom(options.fgColor, [0, 0, 0]);
|
|
852
|
+
const bg = rgbFrom(options.bgColor, [1, 1, 1]);
|
|
853
|
+
const t = effectiveStrength(art, fg, bg);
|
|
854
|
+
if (t <= 0) {
|
|
855
|
+
return null;
|
|
856
|
+
}
|
|
857
|
+
return {
|
|
858
|
+
art,
|
|
859
|
+
image,
|
|
860
|
+
modules,
|
|
861
|
+
size,
|
|
862
|
+
version,
|
|
863
|
+
kinds: moduleKinds(version),
|
|
864
|
+
margin: options.margin,
|
|
865
|
+
pixelSize: options.pixelSize,
|
|
866
|
+
t,
|
|
867
|
+
fg,
|
|
868
|
+
bg,
|
|
869
|
+
variant: getQRArtVariant(art),
|
|
870
|
+
body: options.body,
|
|
871
|
+
};
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
/**
|
|
875
|
+
* Draws every module that is not a finder eye in the art style. Returns null
|
|
876
|
+
* when `art` is not usable (or its strength is 0), so callers fall back to
|
|
877
|
+
* the normal body pattern.
|
|
878
|
+
*/
|
|
879
|
+
export function renderQRArt(options: QRArtRenderOptions): JSX.Element | null {
|
|
880
|
+
const ctx = context(options);
|
|
881
|
+
if (!ctx) {
|
|
882
|
+
return null;
|
|
883
|
+
}
|
|
884
|
+
let content: JSX.Element[];
|
|
885
|
+
if (ctx.art.mode === "halftone") {
|
|
886
|
+
content =
|
|
887
|
+
ctx.variant === "mono"
|
|
888
|
+
? renderMonoHalftone(ctx)
|
|
889
|
+
: renderColorHalftone(ctx);
|
|
890
|
+
} else {
|
|
891
|
+
content =
|
|
892
|
+
ctx.variant === "badge" ? renderLogoBadge(ctx) : renderLogoBlend(ctx);
|
|
893
|
+
}
|
|
894
|
+
return (
|
|
895
|
+
<g data-qrdx-art={ctx.art.mode} data-qrdx-art-variant={ctx.variant}>
|
|
896
|
+
{content}
|
|
897
|
+
</g>
|
|
898
|
+
);
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
// ── Image QR ───────────────────────────────────────────────────────────────
|
|
902
|
+
|
|
903
|
+
interface Cells {
|
|
904
|
+
/** Sub-cells per module side */
|
|
905
|
+
n: number;
|
|
906
|
+
/** Sub-cells per code side */
|
|
907
|
+
count: number;
|
|
908
|
+
/** RGB per sub-cell; NaN where nothing is drawn (finders, alignment) */
|
|
909
|
+
rgb: Float32Array;
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
/** Mono halftone parameters for strength t (lumas relative to fg…bg). */
|
|
913
|
+
function monoParams(t: number, n: number) {
|
|
914
|
+
return {
|
|
915
|
+
/**
|
|
916
|
+
* Wanted margin between a module's blurred center and its surroundings;
|
|
917
|
+
* dithered surroundings are noisy, and a 1-sub-cell core (n = 3) is
|
|
918
|
+
* weaker than a 2 × 2 one, so they ask for more.
|
|
919
|
+
*/
|
|
920
|
+
margin: 0.42 - 0.17 * t + (n === 3 ? 0.04 : 0),
|
|
921
|
+
/**
|
|
922
|
+
* Dark modules' surroundings never lighter than this, light ones never
|
|
923
|
+
* darker than its mirror. Binarizers (jsQR, ZXing) treat low-range blocks
|
|
924
|
+
* as flat, so large codes need absolute contrast, not just relative.
|
|
925
|
+
*/
|
|
926
|
+
darkCap: 0.4 + 0.3 * t,
|
|
927
|
+
};
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
/** How far the eye plates reach from the code's corners, in modules. */
|
|
931
|
+
const PLATE_REACH = 8.5;
|
|
932
|
+
|
|
933
|
+
const plateCache = new Map<number, Uint8Array>();
|
|
934
|
+
|
|
935
|
+
/**
|
|
936
|
+
* Light "plates" that keep function patterns crisp on a picture: each eye's
|
|
937
|
+
* finder and separator plus half of the next module ring, and each
|
|
938
|
+
* alignment pattern plus a half-module halo. Data dots still draw on top.
|
|
939
|
+
* Returns a test for module-space points (half-module resolution).
|
|
940
|
+
*/
|
|
941
|
+
function plates(version: number): (u: number, v: number) => boolean {
|
|
942
|
+
const size = version * 4 + 17;
|
|
943
|
+
let grid = plateCache.get(version);
|
|
944
|
+
if (!grid) {
|
|
945
|
+
const side = size * 2;
|
|
946
|
+
const map = new Uint8Array(side * side);
|
|
947
|
+
const reach = PLATE_REACH * 2;
|
|
948
|
+
for (let y = 0; y < side; y++) {
|
|
949
|
+
for (let x = 0; x < side; x++) {
|
|
950
|
+
const nearX = x < reach || x >= side - reach;
|
|
951
|
+
const nearY = y < reach || y >= side - reach;
|
|
952
|
+
if (nearX && nearY && !(x >= side - reach && y >= side - reach)) {
|
|
953
|
+
map[y * side + x] = 1;
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
for (const [cx, cy] of alignmentCenters(version, size)) {
|
|
958
|
+
for (let y = (cy - 2) * 2 - 1; y < (cy + 3) * 2 + 1; y++) {
|
|
959
|
+
for (let x = (cx - 2) * 2 - 1; x < (cx + 3) * 2 + 1; x++) {
|
|
960
|
+
if (x >= 0 && y >= 0 && x < side && y < side) {
|
|
961
|
+
map[y * side + x] = 1;
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
plateCache.set(version, map);
|
|
967
|
+
grid = map;
|
|
968
|
+
}
|
|
969
|
+
const map = grid;
|
|
970
|
+
const side = size * 2;
|
|
971
|
+
return (u, v) => {
|
|
972
|
+
const x = Math.floor(u * 2);
|
|
973
|
+
const y = Math.floor(v * 2);
|
|
974
|
+
return x >= 0 && y >= 0 && x < side && y < side && map[y * side + x] === 1;
|
|
975
|
+
};
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
/** Samples the photo into sub-cells (cover fit, soft fade at the edge). */
|
|
979
|
+
function sampleCells(ctx: RenderContext, n: number, frosted = false): Cells {
|
|
980
|
+
const { image, size, kinds, fg, bg } = ctx;
|
|
981
|
+
const tone = toneCache.get(ctx.art.image.data, () => toneMap(image));
|
|
982
|
+
const place = placement(image.width, image.height, size, "cover");
|
|
983
|
+
const count = size * n;
|
|
984
|
+
const rgb = new Float32Array(count * count * 3).fill(Number.NaN);
|
|
985
|
+
const footprint = 1 / (n * place.scale);
|
|
986
|
+
const taps = footprint > 1.3 ? 2 : 1;
|
|
987
|
+
const frost = luma(bg) - 0.1 * (luma(bg) - luma(fg));
|
|
988
|
+
const onPlate = plates(ctx.version);
|
|
989
|
+
for (let y = 0; y < size; y++) {
|
|
990
|
+
for (let x = 0; x < size; x++) {
|
|
991
|
+
const kind = kinds[y * size + x];
|
|
992
|
+
const pattern = kind === KIND_FINDER || kind === KIND_ALIGNMENT;
|
|
993
|
+
if (pattern && !frosted) {
|
|
994
|
+
continue;
|
|
995
|
+
}
|
|
996
|
+
for (let j = 0; j < n; j++) {
|
|
997
|
+
for (let i = 0; i < n; i++) {
|
|
998
|
+
let r = 0;
|
|
999
|
+
let g = 0;
|
|
1000
|
+
let b = 0;
|
|
1001
|
+
for (let sy = 0; sy < taps; sy++) {
|
|
1002
|
+
for (let sx = 0; sx < taps; sx++) {
|
|
1003
|
+
const u = x + (i + (sx + 0.5) / taps) / n;
|
|
1004
|
+
const v = y + (j + (sy + 0.5) / taps) / n;
|
|
1005
|
+
const c = sampleOver(
|
|
1006
|
+
tone,
|
|
1007
|
+
(u - place.offsetX) / place.scale,
|
|
1008
|
+
(v - place.offsetY) / place.scale,
|
|
1009
|
+
bg
|
|
1010
|
+
);
|
|
1011
|
+
r += c[0];
|
|
1012
|
+
g += c[1];
|
|
1013
|
+
b += c[2];
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
const samples = taps * taps;
|
|
1017
|
+
let color: RGB = [r / samples, g / samples, b / samples];
|
|
1018
|
+
// Soft quiet zone: the photo fades a little into the border.
|
|
1019
|
+
const u = x + (i + 0.5) / n;
|
|
1020
|
+
const v = y + (j + 0.5) / n;
|
|
1021
|
+
const edge = Math.min(u, v, size - u, size - v);
|
|
1022
|
+
if (edge < 1.5) {
|
|
1023
|
+
color = mix(color, bg, 0.35 * (1 - edge / 1.5));
|
|
1024
|
+
}
|
|
1025
|
+
if (frosted && (pattern || onPlate(u, v))) {
|
|
1026
|
+
// Frosted plate under eyes and alignment patterns
|
|
1027
|
+
color = toward(color, bg, frost, false);
|
|
1028
|
+
}
|
|
1029
|
+
const o = ((y * n + j) * count + x * n + i) * 3;
|
|
1030
|
+
rgb[o] = color[0];
|
|
1031
|
+
rgb[o + 1] = color[1];
|
|
1032
|
+
rgb[o + 2] = color[2];
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
return { n, count, rgb };
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
/**
|
|
1041
|
+
* The scan model (see the file comment): pushes each module's surroundings
|
|
1042
|
+
* toward dark or light only where its blurred center would read wrong.
|
|
1043
|
+
* `weight` is the dot's share of the blurred center, `dark` / `light` the
|
|
1044
|
+
* dot lumas, and `under` marks sub-cells the dot hides.
|
|
1045
|
+
*/
|
|
1046
|
+
function enforceContrast(
|
|
1047
|
+
ctx: RenderContext,
|
|
1048
|
+
cells: Cells,
|
|
1049
|
+
dot: { weight: number; dark: number; light: number; under: boolean[] }
|
|
1050
|
+
) {
|
|
1051
|
+
const { size, kinds, modules, fg, bg, t } = ctx;
|
|
1052
|
+
const { n, count, rgb } = cells;
|
|
1053
|
+
const yFg = luma(fg);
|
|
1054
|
+
const yBg = luma(bg);
|
|
1055
|
+
const range = yBg - yFg;
|
|
1056
|
+
const params = monoParams(t, n);
|
|
1057
|
+
const cellLuma = (o: number) =>
|
|
1058
|
+
0.2126 * rgb[o] + 0.7152 * rgb[o + 1] + 0.0722 * rgb[o + 2];
|
|
1059
|
+
// Mean luma per module (finders count as background, alignment as its
|
|
1060
|
+
// own pattern), for the 5 × 5 module neighbourhood average.
|
|
1061
|
+
const mean = new Float32Array(size * size);
|
|
1062
|
+
const surround = new Float32Array(size * size);
|
|
1063
|
+
for (let y = 0; y < size; y++) {
|
|
1064
|
+
for (let x = 0; x < size; x++) {
|
|
1065
|
+
const kind = kinds[y * size + x];
|
|
1066
|
+
if (kind === KIND_FINDER) {
|
|
1067
|
+
mean[y * size + x] = yBg;
|
|
1068
|
+
continue;
|
|
1069
|
+
}
|
|
1070
|
+
if (kind === KIND_ALIGNMENT) {
|
|
1071
|
+
mean[y * size + x] = modules[y]?.[x] ? yFg : yBg;
|
|
1072
|
+
continue;
|
|
1073
|
+
}
|
|
1074
|
+
let all = 0;
|
|
1075
|
+
let around = 0;
|
|
1076
|
+
let aroundCount = 0;
|
|
1077
|
+
for (let j = 0; j < n; j++) {
|
|
1078
|
+
for (let i = 0; i < n; i++) {
|
|
1079
|
+
const value = cellLuma(((y * n + j) * count + x * n + i) * 3);
|
|
1080
|
+
all += value;
|
|
1081
|
+
if (!dot.under[j * n + i]) {
|
|
1082
|
+
around += value;
|
|
1083
|
+
aroundCount++;
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
mean[y * size + x] = all / (n * n);
|
|
1088
|
+
surround[y * size + x] = aroundCount
|
|
1089
|
+
? around / aroundCount
|
|
1090
|
+
: all / (n * n);
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
const stride = size + 1;
|
|
1094
|
+
const sat = new Float64Array(stride * stride);
|
|
1095
|
+
for (let y = 0; y < size; y++) {
|
|
1096
|
+
for (let x = 0; x < size; x++) {
|
|
1097
|
+
sat[(y + 1) * stride + x + 1] =
|
|
1098
|
+
mean[y * size + x] +
|
|
1099
|
+
sat[y * stride + x + 1] +
|
|
1100
|
+
sat[(y + 1) * stride + x] -
|
|
1101
|
+
sat[y * stride + x];
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
const reach = 2;
|
|
1105
|
+
const localMean = (x: number, y: number) => {
|
|
1106
|
+
const x0 = Math.max(0, x - reach);
|
|
1107
|
+
const y0 = Math.max(0, y - reach);
|
|
1108
|
+
const x1 = Math.min(size, x + reach + 1);
|
|
1109
|
+
const y1 = Math.min(size, y + reach + 1);
|
|
1110
|
+
const total =
|
|
1111
|
+
sat[y1 * stride + x1] -
|
|
1112
|
+
sat[y0 * stride + x1] -
|
|
1113
|
+
sat[y1 * stride + x0] +
|
|
1114
|
+
sat[y0 * stride + x0];
|
|
1115
|
+
return total / ((x1 - x0) * (y1 - y0));
|
|
1116
|
+
};
|
|
1117
|
+
const w = dot.weight;
|
|
1118
|
+
for (let y = 0; y < size; y++) {
|
|
1119
|
+
for (let x = 0; x < size; x++) {
|
|
1120
|
+
const kind = kinds[y * size + x];
|
|
1121
|
+
if (kind === KIND_FINDER || kind === KIND_ALIGNMENT) {
|
|
1122
|
+
continue;
|
|
1123
|
+
}
|
|
1124
|
+
const strong = kind === KIND_STRONG;
|
|
1125
|
+
const margin = (params.margin + (strong ? 0.08 : 0)) * range;
|
|
1126
|
+
const cap = (params.darkCap - (strong ? 0.12 : 0)) * range;
|
|
1127
|
+
// Allowed offset of the surroundings from the local mean: positive
|
|
1128
|
+
// when the dot alone already gives enough contrast.
|
|
1129
|
+
const slack = (w * ((dot.light - dot.dark) / 2) - margin) / (1 - w);
|
|
1130
|
+
const local = localMean(x, y);
|
|
1131
|
+
const mu = surround[y * size + x];
|
|
1132
|
+
const dark = Boolean(modules[y]?.[x]);
|
|
1133
|
+
let k = 0;
|
|
1134
|
+
let anchor = bg;
|
|
1135
|
+
if (dark) {
|
|
1136
|
+
const limit = Math.min(local + slack, yFg + cap);
|
|
1137
|
+
if (mu > limit) {
|
|
1138
|
+
k = (mu - limit) / Math.max(mu - yFg, 1e-6);
|
|
1139
|
+
anchor = fg;
|
|
1140
|
+
}
|
|
1141
|
+
} else {
|
|
1142
|
+
const limit = Math.max(local - slack, yBg - cap);
|
|
1143
|
+
if (mu < limit) {
|
|
1144
|
+
k = (limit - mu) / Math.max(yBg - mu, 1e-6);
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
if (k <= 0) {
|
|
1148
|
+
continue;
|
|
1149
|
+
}
|
|
1150
|
+
k = Math.min(1, k);
|
|
1151
|
+
for (let j = 0; j < n; j++) {
|
|
1152
|
+
for (let i = 0; i < n; i++) {
|
|
1153
|
+
const o = ((y * n + j) * count + x * n + i) * 3;
|
|
1154
|
+
for (let c = 0; c < 3; c++) {
|
|
1155
|
+
rgb[o + c] += (anchor[c] - rgb[o + c]) * k;
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
/** Run-length cell rows grouped by color, under one transform. */
|
|
1164
|
+
function cellLayer(
|
|
1165
|
+
ctx: RenderContext,
|
|
1166
|
+
cells: Cells,
|
|
1167
|
+
colorOf: (cell: number) => string | null,
|
|
1168
|
+
key: string
|
|
1169
|
+
): JSX.Element {
|
|
1170
|
+
const { count } = cells;
|
|
1171
|
+
const runs = new PathGroups();
|
|
1172
|
+
for (let row = 0; row < count; row++) {
|
|
1173
|
+
let start = 0;
|
|
1174
|
+
let current: string | null = colorOf(row * count);
|
|
1175
|
+
for (let col = 1; col <= count; col++) {
|
|
1176
|
+
const color = col < count ? colorOf(row * count + col) : null;
|
|
1177
|
+
if (col === count || color !== current) {
|
|
1178
|
+
if (current) {
|
|
1179
|
+
runs.cellRun(current, start, row, col - start);
|
|
1180
|
+
}
|
|
1181
|
+
start = col;
|
|
1182
|
+
current = color;
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
const cell = ctx.pixelSize / cells.n;
|
|
1187
|
+
const offset = round(ctx.margin * ctx.pixelSize);
|
|
1188
|
+
return (
|
|
1189
|
+
<g
|
|
1190
|
+
key={key}
|
|
1191
|
+
transform={`translate(${offset} ${offset}) scale(${round4(cell)})`}
|
|
1192
|
+
>
|
|
1193
|
+
{runs.toElements(key)}
|
|
1194
|
+
</g>
|
|
1195
|
+
);
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
function alignmentLayer(ctx: RenderContext, color: string): JSX.Element[] {
|
|
1199
|
+
const centers = alignmentCenters(ctx.version, ctx.size);
|
|
1200
|
+
if (centers.length === 0) {
|
|
1201
|
+
return [];
|
|
1202
|
+
}
|
|
1203
|
+
return [
|
|
1204
|
+
<path
|
|
1205
|
+
d={alignmentPath(centers, ctx.margin, ctx.pixelSize)}
|
|
1206
|
+
fill={color}
|
|
1207
|
+
fillRule="evenodd"
|
|
1208
|
+
key="art-alignment"
|
|
1209
|
+
/>,
|
|
1210
|
+
];
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
/** Sub-cells per module side: 4 when the sample has the detail for it. */
|
|
1214
|
+
function subCells(ctx: RenderContext): number {
|
|
1215
|
+
const { image, size } = ctx;
|
|
1216
|
+
return Math.floor(Math.min(image.width, image.height) / size) >= 4 &&
|
|
1217
|
+
size <= 45
|
|
1218
|
+
? 4
|
|
1219
|
+
: 3;
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
/** Inverse of `circleWeight`: the dot diameter that gives weight `w`. */
|
|
1223
|
+
const diameterFor = (w: number) =>
|
|
1224
|
+
2 * BLUR * Math.sqrt(-2 * Math.log(1 - Math.min(w, 0.95)));
|
|
1225
|
+
|
|
1226
|
+
/** Box mean of a size × size grid over (2·reach+1)² cells, edges clamped. */
|
|
1227
|
+
function boxMean(grid: Float32Array, size: number, reach: number) {
|
|
1228
|
+
const stride = size + 1;
|
|
1229
|
+
const sat = new Float64Array(stride * stride);
|
|
1230
|
+
for (let y = 0; y < size; y++) {
|
|
1231
|
+
for (let x = 0; x < size; x++) {
|
|
1232
|
+
sat[(y + 1) * stride + x + 1] =
|
|
1233
|
+
grid[y * size + x] +
|
|
1234
|
+
sat[y * stride + x + 1] +
|
|
1235
|
+
sat[(y + 1) * stride + x] -
|
|
1236
|
+
sat[y * stride + x];
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
const out = new Float32Array(size * size);
|
|
1240
|
+
for (let y = 0; y < size; y++) {
|
|
1241
|
+
for (let x = 0; x < size; x++) {
|
|
1242
|
+
const x0 = Math.max(0, x - reach);
|
|
1243
|
+
const y0 = Math.max(0, y - reach);
|
|
1244
|
+
const x1 = Math.min(size, x + reach + 1);
|
|
1245
|
+
const y1 = Math.min(size, y + reach + 1);
|
|
1246
|
+
out[y * size + x] =
|
|
1247
|
+
(sat[y1 * stride + x1] -
|
|
1248
|
+
sat[y0 * stride + x1] -
|
|
1249
|
+
sat[y1 * stride + x0] +
|
|
1250
|
+
sat[y0 * stride + x0]) /
|
|
1251
|
+
((x1 - x0) * (y1 - y0));
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
return out;
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
interface DotRules {
|
|
1258
|
+
/** Smallest dot, for modules whose picture already reads right */
|
|
1259
|
+
base: number;
|
|
1260
|
+
/** Largest dot */
|
|
1261
|
+
max: number;
|
|
1262
|
+
/** Lumas of dark and light dots */
|
|
1263
|
+
dark: number;
|
|
1264
|
+
light: number;
|
|
1265
|
+
/** Wanted gap between a module's blurred center and the local mean */
|
|
1266
|
+
margin: number;
|
|
1267
|
+
/** Blurred dark centers at most yFg + cap, light ones at least yBg − cap */
|
|
1268
|
+
cap: number;
|
|
1269
|
+
/** Leave out dots the picture doesn't need (Logo QR at higher strength) */
|
|
1270
|
+
skip: boolean;
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
interface DotPlan {
|
|
1274
|
+
/** Per module; 0 = no dot */
|
|
1275
|
+
diameter: Float32Array;
|
|
1276
|
+
/** Surroundings' luma the module still needs (NaN: picture untouched) */
|
|
1277
|
+
surround: Float32Array;
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
/**
|
|
1281
|
+
* Amplitude-modulated dots from the scan model: every module gets the
|
|
1282
|
+
* smallest dot that makes its blurred center read right against its
|
|
1283
|
+
* neighbourhood, so dots stay small where the picture agrees with the code
|
|
1284
|
+
* and grow where it doesn't. Only when even the largest dot isn't enough is
|
|
1285
|
+
* the picture around it adjusted (`surround`).
|
|
1286
|
+
*/
|
|
1287
|
+
function planDots(
|
|
1288
|
+
ctx: RenderContext,
|
|
1289
|
+
mean: Float32Array,
|
|
1290
|
+
surround: Float32Array,
|
|
1291
|
+
rules: DotRules
|
|
1292
|
+
): DotPlan {
|
|
1293
|
+
const { size, kinds, modules, fg, bg } = ctx;
|
|
1294
|
+
const yFg = luma(fg);
|
|
1295
|
+
const yBg = luma(bg);
|
|
1296
|
+
const range = yBg - yFg;
|
|
1297
|
+
const local = boxMean(mean, size, 2);
|
|
1298
|
+
const diameter = new Float32Array(size * size);
|
|
1299
|
+
const target = new Float32Array(size * size).fill(Number.NaN);
|
|
1300
|
+
for (let y = 0; y < size; y++) {
|
|
1301
|
+
for (let x = 0; x < size; x++) {
|
|
1302
|
+
const m = y * size + x;
|
|
1303
|
+
const kind = kinds[m];
|
|
1304
|
+
if (kind === KIND_FINDER || kind === KIND_ALIGNMENT) {
|
|
1305
|
+
continue;
|
|
1306
|
+
}
|
|
1307
|
+
const strong = kind === KIND_STRONG;
|
|
1308
|
+
const base = rules.base + (strong ? 0.08 : 0);
|
|
1309
|
+
const margin = (rules.margin + (strong ? 0.03 : 0)) * range;
|
|
1310
|
+
const cap = (rules.cap - (strong ? 0.04 : 0)) * range;
|
|
1311
|
+
const wBase = circleWeight(base);
|
|
1312
|
+
const wMax = circleWeight(strong ? Math.max(rules.max, 0.94) : rules.max);
|
|
1313
|
+
// The rendered neighbourhood: the picture plus dots of both values.
|
|
1314
|
+
const localS =
|
|
1315
|
+
wBase * ((rules.dark + rules.light) / 2) + (1 - wBase) * local[m];
|
|
1316
|
+
const mu = surround[m];
|
|
1317
|
+
const dark = Boolean(modules[y]?.[x]);
|
|
1318
|
+
const dot = dark ? rules.dark : rules.light;
|
|
1319
|
+
const goal = dark
|
|
1320
|
+
? Math.min(localS - margin, yFg + cap)
|
|
1321
|
+
: Math.max(localS + margin, yBg - cap);
|
|
1322
|
+
const agrees = dark ? mu <= goal : mu >= goal;
|
|
1323
|
+
let w = agrees ? 0 : (mu - goal) / (mu - dot);
|
|
1324
|
+
if (w > wMax) {
|
|
1325
|
+
w = wMax;
|
|
1326
|
+
target[m] = Math.min(
|
|
1327
|
+
yBg,
|
|
1328
|
+
Math.max(yFg, (goal - wMax * dot) / (1 - wMax))
|
|
1329
|
+
);
|
|
1330
|
+
}
|
|
1331
|
+
const clearly = dark ? mu <= goal - 0.06 : mu >= goal + 0.06;
|
|
1332
|
+
if (!(rules.skip && clearly && !strong)) {
|
|
1333
|
+
w = Math.max(w, wBase);
|
|
1334
|
+
}
|
|
1335
|
+
diameter[m] = w > 0 ? diameterFor(w) : 0;
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
return { diameter, surround: target };
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
function renderColorHalftone(ctx: RenderContext): JSX.Element[] {
|
|
1342
|
+
const { size, kinds, modules, fg, bg, t, margin, pixelSize } = ctx;
|
|
1343
|
+
const n = subCells(ctx);
|
|
1344
|
+
const cells = sampleCells(ctx, n, true);
|
|
1345
|
+
const yFg = luma(fg);
|
|
1346
|
+
const yBg = luma(bg);
|
|
1347
|
+
const dotDark = yFg + 0.1 * (yBg - yFg);
|
|
1348
|
+
const dotLight = yBg - 0.05 * (yBg - yFg);
|
|
1349
|
+
const { count, rgb } = cells;
|
|
1350
|
+
const cellAt = (x: number, y: number, i: number, j: number) =>
|
|
1351
|
+
((y * n + j) * count + x * n + i) * 3;
|
|
1352
|
+
|
|
1353
|
+
// Module mean lumas (finders count as background, alignment as itself)
|
|
1354
|
+
const mean = new Float32Array(size * size);
|
|
1355
|
+
for (let y = 0; y < size; y++) {
|
|
1356
|
+
for (let x = 0; x < size; x++) {
|
|
1357
|
+
const kind = kinds[y * size + x];
|
|
1358
|
+
if (kind === KIND_FINDER || kind === KIND_ALIGNMENT) {
|
|
1359
|
+
mean[y * size + x] =
|
|
1360
|
+
kind === KIND_ALIGNMENT && modules[y]?.[x] ? yFg : yBg;
|
|
1361
|
+
continue;
|
|
1362
|
+
}
|
|
1363
|
+
let sum = 0;
|
|
1364
|
+
for (let j = 0; j < n; j++) {
|
|
1365
|
+
for (let i = 0; i < n; i++) {
|
|
1366
|
+
const o = cellAt(x, y, i, j);
|
|
1367
|
+
sum += 0.2126 * rgb[o] + 0.7152 * rgb[o + 1] + 0.0722 * rgb[o + 2];
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
mean[y * size + x] = sum / (n * n);
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
const plan = planDots(ctx, mean, mean, {
|
|
1374
|
+
base: 0.6 - 0.28 * t,
|
|
1375
|
+
max: 0.86,
|
|
1376
|
+
dark: dotDark,
|
|
1377
|
+
light: dotLight,
|
|
1378
|
+
margin: 0.2 - 0.1 * t,
|
|
1379
|
+
cap: 0.4 + 0.14 * t,
|
|
1380
|
+
skip: false,
|
|
1381
|
+
});
|
|
1382
|
+
|
|
1383
|
+
// Where the biggest dot isn't enough, move the photo around it just as far
|
|
1384
|
+
// as needed (toward the dark or light color, keeping its hue).
|
|
1385
|
+
for (let y = 0; y < size; y++) {
|
|
1386
|
+
for (let x = 0; x < size; x++) {
|
|
1387
|
+
const goal = plan.surround[y * size + x];
|
|
1388
|
+
if (Number.isNaN(goal)) {
|
|
1389
|
+
continue;
|
|
1390
|
+
}
|
|
1391
|
+
const mu = mean[y * size + x];
|
|
1392
|
+
const darker = goal < mu;
|
|
1393
|
+
const anchor = darker ? fg : bg;
|
|
1394
|
+
const k = Math.min(
|
|
1395
|
+
1,
|
|
1396
|
+
Math.abs(mu - goal) / Math.max(Math.abs(mu - luma(anchor)), 1e-6)
|
|
1397
|
+
);
|
|
1398
|
+
for (let j = 0; j < n; j++) {
|
|
1399
|
+
for (let i = 0; i < n; i++) {
|
|
1400
|
+
const o = cellAt(x, y, i, j);
|
|
1401
|
+
for (let c = 0; c < 3; c++) {
|
|
1402
|
+
rgb[o + c] += (anchor[c] - rgb[o + c]) * k;
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
const layers: JSX.Element[] = [
|
|
1410
|
+
cellLayer(
|
|
1411
|
+
ctx,
|
|
1412
|
+
cells,
|
|
1413
|
+
(cell) => {
|
|
1414
|
+
const o = cell * 3;
|
|
1415
|
+
return Number.isNaN(rgb[o])
|
|
1416
|
+
? null
|
|
1417
|
+
: toHex([rgb[o], rgb[o + 1], rgb[o + 2]], 8);
|
|
1418
|
+
},
|
|
1419
|
+
"art-photo"
|
|
1420
|
+
),
|
|
1421
|
+
];
|
|
1422
|
+
|
|
1423
|
+
// Center dots, tinted with the module's own color.
|
|
1424
|
+
const dots = new PathGroups();
|
|
1425
|
+
for (let y = 0; y < size; y++) {
|
|
1426
|
+
for (let x = 0; x < size; x++) {
|
|
1427
|
+
const diameter = plan.diameter[y * size + x];
|
|
1428
|
+
if (!(diameter > 0)) {
|
|
1429
|
+
continue;
|
|
1430
|
+
}
|
|
1431
|
+
let r = 0;
|
|
1432
|
+
let g = 0;
|
|
1433
|
+
let b = 0;
|
|
1434
|
+
for (let j = 0; j < n; j++) {
|
|
1435
|
+
for (let i = 0; i < n; i++) {
|
|
1436
|
+
const o = cellAt(x, y, i, j);
|
|
1437
|
+
r += rgb[o];
|
|
1438
|
+
g += rgb[o + 1];
|
|
1439
|
+
b += rgb[o + 2];
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
const average: RGB = [r / (n * n), g / (n * n), b / (n * n)];
|
|
1443
|
+
const color = modules[y]?.[x]
|
|
1444
|
+
? toward(average, fg, dotDark, true)
|
|
1445
|
+
: toward(average, bg, dotLight, false);
|
|
1446
|
+
dots.circle(
|
|
1447
|
+
toHex(color, 10),
|
|
1448
|
+
(x + margin + 0.5) * pixelSize,
|
|
1449
|
+
(y + margin + 0.5) * pixelSize,
|
|
1450
|
+
(diameter / 2) * pixelSize
|
|
1451
|
+
);
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
layers.push(...dots.toElements("art-dot"), ...alignmentLayer(ctx, toHex(fg)));
|
|
1455
|
+
return layers;
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
function renderMonoHalftone(ctx: RenderContext): JSX.Element[] {
|
|
1459
|
+
const { size, kinds, modules, fg, bg } = ctx;
|
|
1460
|
+
const n = subCells(ctx);
|
|
1461
|
+
const cells = sampleCells(ctx, n);
|
|
1462
|
+
const yFg = luma(fg);
|
|
1463
|
+
const yBg = luma(bg);
|
|
1464
|
+
// The center sub-cell (3 × 3) or the center 2 × 2 (4 × 4) keeps the bit.
|
|
1465
|
+
const core = n % 2 === 1 ? 1 : 2;
|
|
1466
|
+
const lo = (n - core) / 2;
|
|
1467
|
+
const isCore = (i: number) => i >= lo && i < lo + core;
|
|
1468
|
+
const under: boolean[] = [];
|
|
1469
|
+
for (let j = 0; j < n; j++) {
|
|
1470
|
+
for (let i = 0; i < n; i++) {
|
|
1471
|
+
under.push(isCore(i) && isCore(j));
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
enforceContrast(ctx, cells, {
|
|
1475
|
+
weight: squareWeight(core / n),
|
|
1476
|
+
dark: yFg,
|
|
1477
|
+
light: yBg,
|
|
1478
|
+
under,
|
|
1479
|
+
});
|
|
1480
|
+
const { count, rgb } = cells;
|
|
1481
|
+
// Floyd–Steinberg (serpentine) in fg…bg units, on a contrast curve that
|
|
1482
|
+
// keeps mid-tones from dissolving into noise; each module's core is forced
|
|
1483
|
+
// to its value and its error diffuses like any other.
|
|
1484
|
+
const value = new Float32Array(count * count);
|
|
1485
|
+
const forced = new Int8Array(count * count).fill(-1);
|
|
1486
|
+
for (let c = 0; c < count * count; c++) {
|
|
1487
|
+
const o = c * 3;
|
|
1488
|
+
if (Number.isNaN(rgb[o])) {
|
|
1489
|
+
value[c] = Number.NaN;
|
|
1490
|
+
continue;
|
|
1491
|
+
}
|
|
1492
|
+
const v =
|
|
1493
|
+
(0.2126 * rgb[o] + 0.7152 * rgb[o + 1] + 0.0722 * rgb[o + 2] - yFg) /
|
|
1494
|
+
(yBg - yFg);
|
|
1495
|
+
value[c] = 0.5 + (smoothstep(0, 1, v) - 0.5) * 1.15;
|
|
1496
|
+
}
|
|
1497
|
+
for (let y = 0; y < size; y++) {
|
|
1498
|
+
for (let x = 0; x < size; x++) {
|
|
1499
|
+
const kind = kinds[y * size + x];
|
|
1500
|
+
if (kind === KIND_FINDER || kind === KIND_ALIGNMENT) {
|
|
1501
|
+
continue;
|
|
1502
|
+
}
|
|
1503
|
+
for (let j = lo; j < lo + core; j++) {
|
|
1504
|
+
for (let i = lo; i < lo + core; i++) {
|
|
1505
|
+
forced[(y * n + j) * count + x * n + i] = modules[y]?.[x] ? 0 : 1;
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
// Plates around eyes and alignment patterns stay light (cores excepted).
|
|
1511
|
+
const onPlate = plates(ctx.version);
|
|
1512
|
+
for (let cy = 0; cy < count; cy++) {
|
|
1513
|
+
for (let cx = 0; cx < count; cx++) {
|
|
1514
|
+
const c = cy * count + cx;
|
|
1515
|
+
if (forced[c] < 0 && onPlate((cx + 0.5) / n, (cy + 0.5) / n)) {
|
|
1516
|
+
forced[c] = 1;
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
const dark = new Uint8Array(count * count);
|
|
1521
|
+
// Error mostly stays inside its module, so one module's tone doesn't
|
|
1522
|
+
// leak into a neighbour of the opposite value.
|
|
1523
|
+
const CROSS_MODULE = 0.3;
|
|
1524
|
+
let fromX = 0;
|
|
1525
|
+
let fromY = 0;
|
|
1526
|
+
const push = (cx: number, cy: number, amount: number) => {
|
|
1527
|
+
if (cx < 0 || cx >= count || cy >= count) {
|
|
1528
|
+
return;
|
|
1529
|
+
}
|
|
1530
|
+
const c = cy * count + cx;
|
|
1531
|
+
if (!Number.isNaN(value[c])) {
|
|
1532
|
+
const same =
|
|
1533
|
+
Math.floor(cx / n) === Math.floor(fromX / n) &&
|
|
1534
|
+
Math.floor(cy / n) === Math.floor(fromY / n);
|
|
1535
|
+
value[c] += same ? amount : amount * CROSS_MODULE;
|
|
1536
|
+
}
|
|
1537
|
+
};
|
|
1538
|
+
for (let cy = 0; cy < count; cy++) {
|
|
1539
|
+
const dir = cy % 2 === 0 ? 1 : -1;
|
|
1540
|
+
for (let step = 0; step < count; step++) {
|
|
1541
|
+
const cx = dir === 1 ? step : count - 1 - step;
|
|
1542
|
+
const c = cy * count + cx;
|
|
1543
|
+
const old = value[c];
|
|
1544
|
+
if (Number.isNaN(old)) {
|
|
1545
|
+
continue;
|
|
1546
|
+
}
|
|
1547
|
+
const out = forced[c] >= 0 ? forced[c] : old >= 0.5 ? 1 : 0;
|
|
1548
|
+
dark[c] = out === 0 ? 1 : 0;
|
|
1549
|
+
const error = Math.min(0.75, Math.max(-0.75, old - out));
|
|
1550
|
+
fromX = cx;
|
|
1551
|
+
fromY = cy;
|
|
1552
|
+
push(cx + dir, cy, (error * 7) / 16);
|
|
1553
|
+
push(cx - dir, cy + 1, (error * 3) / 16);
|
|
1554
|
+
push(cx, cy + 1, (error * 5) / 16);
|
|
1555
|
+
push(cx + dir, cy + 1, error / 16);
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
const fgHex = toHex(fg);
|
|
1559
|
+
return [
|
|
1560
|
+
cellLayer(
|
|
1561
|
+
ctx,
|
|
1562
|
+
cells,
|
|
1563
|
+
(cell) => (dark[cell] ? fgHex : null),
|
|
1564
|
+
"art-halftone"
|
|
1565
|
+
),
|
|
1566
|
+
...alignmentLayer(ctx, fgHex),
|
|
1567
|
+
];
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
// ── Logo QR ────────────────────────────────────────────────────────────────
|
|
1571
|
+
|
|
1572
|
+
/** Most brand-like palette color: large, saturated, not near-white. */
|
|
1573
|
+
function primaryColor(traced: TracedLogo, avoid?: RGB): RGB | null {
|
|
1574
|
+
let best: RGB | null = null;
|
|
1575
|
+
let bestScore = 0;
|
|
1576
|
+
for (const entry of traced.palette) {
|
|
1577
|
+
if (avoid && distance2(entry.color, avoid) < 0.02) {
|
|
1578
|
+
continue;
|
|
1579
|
+
}
|
|
1580
|
+
const score =
|
|
1581
|
+
entry.area *
|
|
1582
|
+
(0.35 + chroma(entry.color)) *
|
|
1583
|
+
(luma(entry.color) > 0.86 ? 0.05 : 1);
|
|
1584
|
+
if (score > bestScore) {
|
|
1585
|
+
bestScore = score;
|
|
1586
|
+
best = entry.color;
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
return best;
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1592
|
+
/** Transform group that draws the traced logo into a box (output units). */
|
|
1593
|
+
function logoGroup(
|
|
1594
|
+
traced: TracedLogo,
|
|
1595
|
+
logo: FloatImage,
|
|
1596
|
+
box: { x: number; y: number; scale: number },
|
|
1597
|
+
colorOf: (color: RGB) => RGB,
|
|
1598
|
+
key: string
|
|
1599
|
+
): JSX.Element {
|
|
1600
|
+
let content: JSX.Element[];
|
|
1601
|
+
if (traced.photographic) {
|
|
1602
|
+
// Photos uploaded as logos: a fine mosaic of the sample itself.
|
|
1603
|
+
const runs = new PathGroups();
|
|
1604
|
+
const { width, height, rgb, alpha } = logo;
|
|
1605
|
+
for (let y = 0; y < height; y++) {
|
|
1606
|
+
let start = 0;
|
|
1607
|
+
let current: string | null = null;
|
|
1608
|
+
for (let x = 0; x <= width; x++) {
|
|
1609
|
+
const p = y * width + x;
|
|
1610
|
+
const color =
|
|
1611
|
+
x < width && alpha[p] >= 0.5
|
|
1612
|
+
? toHex(colorOf([rgb[p * 3], rgb[p * 3 + 1], rgb[p * 3 + 2]]), 6)
|
|
1613
|
+
: null;
|
|
1614
|
+
if (x === width || color !== current) {
|
|
1615
|
+
if (current) {
|
|
1616
|
+
runs.cellRun(current, start, y, x - start);
|
|
1617
|
+
}
|
|
1618
|
+
start = x;
|
|
1619
|
+
current = color;
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
content = runs.toElements(`${key}-px`);
|
|
1624
|
+
} else {
|
|
1625
|
+
content = traced.layers.map((layer, index) => (
|
|
1626
|
+
<path
|
|
1627
|
+
d={layer.d}
|
|
1628
|
+
fill={toHex(colorOf(layer.color))}
|
|
1629
|
+
fillRule="evenodd"
|
|
1630
|
+
key={`${key}-${index}`}
|
|
1631
|
+
/>
|
|
1632
|
+
));
|
|
1633
|
+
}
|
|
1634
|
+
return (
|
|
1635
|
+
<g
|
|
1636
|
+
key={key}
|
|
1637
|
+
transform={`translate(${round(box.x)} ${round(box.y)}) scale(${round4(box.scale)})`}
|
|
1638
|
+
>
|
|
1639
|
+
{content}
|
|
1640
|
+
</g>
|
|
1641
|
+
);
|
|
1642
|
+
}
|
|
1643
|
+
|
|
1644
|
+
function renderLogoBlend(ctx: RenderContext): JSX.Element[] {
|
|
1645
|
+
const { art, image, size, kinds, modules, fg, bg, t, margin, pixelSize } =
|
|
1646
|
+
ctx;
|
|
1647
|
+
const traced = tracedLogo(art, image);
|
|
1648
|
+
const logo = logoPixels(art, image, traced);
|
|
1649
|
+
const place = placement(traced.width, traced.height, size, "contain");
|
|
1650
|
+
// How strongly the logo shows: pastel at low strength, true color from 0.5.
|
|
1651
|
+
const fade = Math.min(1, 0.3 + 1.4 * t);
|
|
1652
|
+
const colorOf = (color: RGB) => mix(bg, color, fade);
|
|
1653
|
+
const bgHex = toHex(bg);
|
|
1654
|
+
const fgHex = toHex(fg);
|
|
1655
|
+
const layers: JSX.Element[] = [
|
|
1656
|
+
logoGroup(
|
|
1657
|
+
traced,
|
|
1658
|
+
logo,
|
|
1659
|
+
{
|
|
1660
|
+
x: (margin + place.offsetX) * pixelSize,
|
|
1661
|
+
y: (margin + place.offsetY) * pixelSize,
|
|
1662
|
+
scale: place.scale * pixelSize,
|
|
1663
|
+
},
|
|
1664
|
+
colorOf,
|
|
1665
|
+
"art-logo"
|
|
1666
|
+
),
|
|
1667
|
+
];
|
|
1668
|
+
|
|
1669
|
+
// Clean plates under the three eyes: finder, separator and half the next
|
|
1670
|
+
// ring of modules (their dots still draw on top), so a dark logo next to
|
|
1671
|
+
// an eye can't swallow the separator at small sizes. The outer corners
|
|
1672
|
+
// round off in the quiet zone.
|
|
1673
|
+
const reach = PLATE_REACH;
|
|
1674
|
+
const plate = (x: number, y: number) =>
|
|
1675
|
+
roundedRectPath(
|
|
1676
|
+
(x + margin) * pixelSize,
|
|
1677
|
+
(y + margin) * pixelSize,
|
|
1678
|
+
(reach + 0.4) * pixelSize,
|
|
1679
|
+
(reach + 0.4) * pixelSize,
|
|
1680
|
+
1.2 * pixelSize
|
|
1681
|
+
);
|
|
1682
|
+
// Alignment patterns get a half-module halo of background too.
|
|
1683
|
+
const halos = alignmentCenters(ctx.version, size)
|
|
1684
|
+
.map(([cx, cy]) =>
|
|
1685
|
+
roundedRectPath(
|
|
1686
|
+
(cx - 2.5 + margin) * pixelSize,
|
|
1687
|
+
(cy - 2.5 + margin) * pixelSize,
|
|
1688
|
+
6 * pixelSize,
|
|
1689
|
+
6 * pixelSize,
|
|
1690
|
+
pixelSize * 0.8
|
|
1691
|
+
)
|
|
1692
|
+
)
|
|
1693
|
+
.join("");
|
|
1694
|
+
layers.push(
|
|
1695
|
+
<path
|
|
1696
|
+
d={
|
|
1697
|
+
plate(-0.4, -0.4) +
|
|
1698
|
+
plate(size - reach, -0.4) +
|
|
1699
|
+
plate(-0.4, size - reach) +
|
|
1700
|
+
halos
|
|
1701
|
+
}
|
|
1702
|
+
fill={bgHex}
|
|
1703
|
+
key="art-plates"
|
|
1704
|
+
/>
|
|
1705
|
+
);
|
|
1706
|
+
const onPlate = plates(ctx.version);
|
|
1707
|
+
|
|
1708
|
+
// Dot screen: dark dots on dark modules, light dots on light ones, each
|
|
1709
|
+
// as small as the scan model allows (see planDots); at higher strength,
|
|
1710
|
+
// dots the logo doesn't need are left out.
|
|
1711
|
+
const yBg = luma(bg);
|
|
1712
|
+
const yFg = luma(fg);
|
|
1713
|
+
const mean = new Float32Array(size * size);
|
|
1714
|
+
const lowest = new Float32Array(size * size);
|
|
1715
|
+
const average: RGB[] = new Array(size * size);
|
|
1716
|
+
for (let y = 0; y < size; y++) {
|
|
1717
|
+
for (let x = 0; x < size; x++) {
|
|
1718
|
+
const m = y * size + x;
|
|
1719
|
+
const kind = kinds[m];
|
|
1720
|
+
if (kind === KIND_FINDER || kind === KIND_ALIGNMENT) {
|
|
1721
|
+
mean[m] = kind === KIND_ALIGNMENT && modules[y]?.[x] ? yFg : yBg;
|
|
1722
|
+
continue;
|
|
1723
|
+
}
|
|
1724
|
+
let lo = 1;
|
|
1725
|
+
let sum = 0;
|
|
1726
|
+
let r = 0;
|
|
1727
|
+
let g = 0;
|
|
1728
|
+
let b = 0;
|
|
1729
|
+
for (let j = 0; j < 4; j++) {
|
|
1730
|
+
for (let i = 0; i < 4; i++) {
|
|
1731
|
+
const u = x + (i + 0.5) / 4;
|
|
1732
|
+
const v = y + (j + 0.5) / 4;
|
|
1733
|
+
const c = onPlate(u, v)
|
|
1734
|
+
? bg
|
|
1735
|
+
: sampleOver(
|
|
1736
|
+
logo,
|
|
1737
|
+
(u - place.offsetX) / place.scale,
|
|
1738
|
+
(v - place.offsetY) / place.scale,
|
|
1739
|
+
bg,
|
|
1740
|
+
fade
|
|
1741
|
+
);
|
|
1742
|
+
const value = luma(c);
|
|
1743
|
+
lo = Math.min(lo, value);
|
|
1744
|
+
sum += value;
|
|
1745
|
+
r += c[0];
|
|
1746
|
+
g += c[1];
|
|
1747
|
+
b += c[2];
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
mean[m] = sum / 16;
|
|
1751
|
+
lowest[m] = lo;
|
|
1752
|
+
average[m] = [r / 16, g / 16, b / 16];
|
|
1753
|
+
}
|
|
1754
|
+
}
|
|
1755
|
+
const dotDark = yFg + 0.08 * (yBg - yFg);
|
|
1756
|
+
const dotLight = yBg - 0.04 * (yBg - yFg);
|
|
1757
|
+
const plan = planDots(ctx, mean, mean, {
|
|
1758
|
+
base: 0.74 - 0.26 * t,
|
|
1759
|
+
max: 0.9,
|
|
1760
|
+
dark: dotDark,
|
|
1761
|
+
light: dotLight,
|
|
1762
|
+
margin: 0.23 - 0.1 * t,
|
|
1763
|
+
cap: 0.4 + 0.1 * t,
|
|
1764
|
+
skip: t >= 0.7,
|
|
1765
|
+
});
|
|
1766
|
+
const dots = new PathGroups();
|
|
1767
|
+
for (let y = 0; y < size; y++) {
|
|
1768
|
+
for (let x = 0; x < size; x++) {
|
|
1769
|
+
const m = y * size + x;
|
|
1770
|
+
const diameter = plan.diameter[m];
|
|
1771
|
+
const dark = Boolean(modules[y]?.[x]);
|
|
1772
|
+
// Light dots on plain background would be invisible.
|
|
1773
|
+
if (!(diameter > 0) || (!dark && lowest[m] >= yBg - 0.02)) {
|
|
1774
|
+
continue;
|
|
1775
|
+
}
|
|
1776
|
+
// Dots take a deep (or pale) shade of the logo color under them.
|
|
1777
|
+
const color = dark
|
|
1778
|
+
? toward(average[m] as RGB, fg, dotDark, true)
|
|
1779
|
+
: toward(average[m] as RGB, bg, dotLight, false);
|
|
1780
|
+
dots.circle(
|
|
1781
|
+
toHex(color, 8),
|
|
1782
|
+
(x + margin + 0.5) * pixelSize,
|
|
1783
|
+
(y + margin + 0.5) * pixelSize,
|
|
1784
|
+
(diameter / 2) * pixelSize
|
|
1785
|
+
);
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
layers.push(...dots.toElements("art-dot"));
|
|
1789
|
+
layers.push(...alignmentLayer(ctx, fgHex));
|
|
1790
|
+
return layers;
|
|
1791
|
+
}
|
|
1792
|
+
|
|
1793
|
+
/** EC capacity relative to H, for sizing the badge. */
|
|
1794
|
+
const BADGE_LEVEL_SCALE: Record<ErrorLevel, number> = {
|
|
1795
|
+
L: 0.5,
|
|
1796
|
+
M: 0.72,
|
|
1797
|
+
Q: 0.88,
|
|
1798
|
+
H: 1,
|
|
1799
|
+
};
|
|
1800
|
+
|
|
1801
|
+
/** Largest logo box, as a share of the code width. */
|
|
1802
|
+
const BADGE_MAX_SHARE = 0.32;
|
|
1803
|
+
|
|
1804
|
+
/** Modules whose center is this close to the plate (or inside it) are cleared. */
|
|
1805
|
+
const BADGE_CLEARANCE = 0.55;
|
|
1806
|
+
|
|
1807
|
+
/**
|
|
1808
|
+
* Share of each Reed–Solomon block's repair capacity the plate may use up.
|
|
1809
|
+
* The rest absorbs camera noise, the logo-colored eyes and body, and modules
|
|
1810
|
+
* misread at the plate's edge. Measured over versions 1–6 × L/M/Q/H × six
|
|
1811
|
+
* sample logos × strengths 0.6–1, decoded with jsQR through the camera model
|
|
1812
|
+
* at 4, 6 and 9 px per module: at 0.6 the plate adds no failures to the
|
|
1813
|
+
* same codes drawn without one; 0.65–0.7 lose version 2-M codes and 0.75
|
|
1814
|
+
* loses version 2 and 3 codes at 6 px.
|
|
1815
|
+
*/
|
|
1816
|
+
const BADGE_EC_SAFETY = 0.6;
|
|
1817
|
+
|
|
1818
|
+
/**
|
|
1819
|
+
* Smallest logo box (modules) worth drawing. When the code can't spare
|
|
1820
|
+
* even that, the badge draws no plate and the code keeps the logo's colors.
|
|
1821
|
+
*/
|
|
1822
|
+
const BADGE_MIN_BOX = 2;
|
|
1823
|
+
|
|
1824
|
+
/** Badge geometry in modules for a logo box of `box` modules (longest side). */
|
|
1825
|
+
function badgeGeometry(box: number, aspect: number, size: number) {
|
|
1826
|
+
const logoW = aspect >= 1 ? box : box * aspect;
|
|
1827
|
+
const logoH = aspect >= 1 ? box / aspect : box;
|
|
1828
|
+
const pad = Math.max(0.7, box * 0.09);
|
|
1829
|
+
const plateW = logoW + 2 * pad;
|
|
1830
|
+
const plateH = logoH + 2 * pad;
|
|
1831
|
+
return {
|
|
1832
|
+
logoW,
|
|
1833
|
+
logoH,
|
|
1834
|
+
plateW,
|
|
1835
|
+
plateH,
|
|
1836
|
+
radius: Math.min(plateW, plateH) * 0.26,
|
|
1837
|
+
cx: size / 2,
|
|
1838
|
+
cy: size / 2,
|
|
1839
|
+
};
|
|
1840
|
+
}
|
|
1841
|
+
|
|
1842
|
+
type BadgeLayout = ReturnType<typeof badgeGeometry>;
|
|
1843
|
+
|
|
1844
|
+
const plateRect = (layout: BadgeLayout) => ({
|
|
1845
|
+
cx: layout.cx,
|
|
1846
|
+
cy: layout.cy,
|
|
1847
|
+
w: layout.plateW,
|
|
1848
|
+
h: layout.plateH,
|
|
1849
|
+
r: layout.radius,
|
|
1850
|
+
});
|
|
1851
|
+
|
|
1852
|
+
/** True when the plate clears module (x, y): its dot would touch the plate. */
|
|
1853
|
+
function plateClears(rect: ReturnType<typeof plateRect>, x: number, y: number) {
|
|
1854
|
+
return roundedRectDistance(x + 0.5, y + 0.5, rect) < BADGE_CLEARANCE;
|
|
1855
|
+
}
|
|
1856
|
+
|
|
1857
|
+
/** Modules (y × size + x) the plate clears. */
|
|
1858
|
+
function plateModules(layout: BadgeLayout, size: number): number[] {
|
|
1859
|
+
const rect = plateRect(layout);
|
|
1860
|
+
const reach = BADGE_CLEARANCE + 1;
|
|
1861
|
+
const x0 = Math.max(0, Math.floor(layout.cx - layout.plateW / 2 - reach));
|
|
1862
|
+
const x1 = Math.min(
|
|
1863
|
+
size - 1,
|
|
1864
|
+
Math.ceil(layout.cx + layout.plateW / 2 + reach)
|
|
1865
|
+
);
|
|
1866
|
+
const y0 = Math.max(0, Math.floor(layout.cy - layout.plateH / 2 - reach));
|
|
1867
|
+
const y1 = Math.min(
|
|
1868
|
+
size - 1,
|
|
1869
|
+
Math.ceil(layout.cy + layout.plateH / 2 + reach)
|
|
1870
|
+
);
|
|
1871
|
+
const cleared: number[] = [];
|
|
1872
|
+
for (let y = y0; y <= y1; y++) {
|
|
1873
|
+
for (let x = x0; x <= x1; x++) {
|
|
1874
|
+
if (plateClears(rect, x, y)) {
|
|
1875
|
+
cleared.push(y * size + x);
|
|
1876
|
+
}
|
|
1877
|
+
}
|
|
1878
|
+
}
|
|
1879
|
+
return cleared;
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
/**
|
|
1883
|
+
* Most codewords per block the plate may spoil: the block's repair capacity
|
|
1884
|
+
* (ISO/IEC 18004 Table 9) times BADGE_EC_SAFETY.
|
|
1885
|
+
*/
|
|
1886
|
+
const badgeBudget = (map: CodewordMap) =>
|
|
1887
|
+
Math.floor(map.correctable * BADGE_EC_SAFETY);
|
|
1888
|
+
|
|
1889
|
+
/** True when a badge with logo box `box` stays inside every block's budget. */
|
|
1890
|
+
function badgeFits(box: number, aspect: number, map: CodewordMap) {
|
|
1891
|
+
const layout = badgeGeometry(box, aspect, map.size);
|
|
1892
|
+
const budget = badgeBudget(map);
|
|
1893
|
+
return damagedCodewords(map, plateModules(layout, map.size)).every(
|
|
1894
|
+
(count) => count <= budget
|
|
1895
|
+
);
|
|
1896
|
+
}
|
|
1897
|
+
|
|
1898
|
+
/**
|
|
1899
|
+
* Largest logo box (modules) up to `ceiling` whose plate fits the budget,
|
|
1900
|
+
* by binary search; -1 when even the smallest plate doesn't. Codewords are
|
|
1901
|
+
* placed by the data layout, not by area, so the same share of a small code
|
|
1902
|
+
* can cost far more than a block repairs.
|
|
1903
|
+
*/
|
|
1904
|
+
function largestFit(map: CodewordMap, aspect: number, ceiling: number) {
|
|
1905
|
+
if (badgeFits(ceiling, aspect, map)) {
|
|
1906
|
+
return ceiling;
|
|
1907
|
+
}
|
|
1908
|
+
let lo = 0;
|
|
1909
|
+
let hi = ceiling;
|
|
1910
|
+
if (!badgeFits(lo, aspect, map)) {
|
|
1911
|
+
return -1;
|
|
1912
|
+
}
|
|
1913
|
+
// Invariant: lo fits, hi doesn't. 1/64 module is finer than any render.
|
|
1914
|
+
while (hi - lo > 1 / 64) {
|
|
1915
|
+
const mid = (lo + hi) / 2;
|
|
1916
|
+
if (badgeFits(mid, aspect, map)) {
|
|
1917
|
+
lo = mid;
|
|
1918
|
+
} else {
|
|
1919
|
+
hi = mid;
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
return lo;
|
|
1923
|
+
}
|
|
1924
|
+
|
|
1925
|
+
const maxBoxCache = new Map<string, number>();
|
|
1926
|
+
|
|
1927
|
+
/** Largest logo box any strength may use for this code and logo shape. */
|
|
1928
|
+
function badgeMaxBox(map: CodewordMap, aspect: number) {
|
|
1929
|
+
const key = `${map.version}${map.level}:${aspect.toFixed(3)}`;
|
|
1930
|
+
let limit = maxBoxCache.get(key);
|
|
1931
|
+
if (limit === undefined) {
|
|
1932
|
+
limit = largestFit(map, aspect, BADGE_MAX_SHARE * map.size);
|
|
1933
|
+
if (maxBoxCache.size >= 64) {
|
|
1934
|
+
maxBoxCache.clear();
|
|
1935
|
+
}
|
|
1936
|
+
maxBoxCache.set(key, limit);
|
|
1937
|
+
}
|
|
1938
|
+
return limit;
|
|
1939
|
+
}
|
|
1940
|
+
|
|
1941
|
+
/** Logo QR "badge" sizes for one code, in modules. */
|
|
1942
|
+
export interface QRArtBadgeLayout {
|
|
1943
|
+
/** Logo box (longest side) the strength asks for */
|
|
1944
|
+
wantedBox: number;
|
|
1945
|
+
/**
|
|
1946
|
+
* Largest logo box the code's error correction can spare: the plate may
|
|
1947
|
+
* spoil at most a set share of the codewords each Reed–Solomon block
|
|
1948
|
+
* repairs. Below 2 modules no plate is drawn.
|
|
1949
|
+
*/
|
|
1950
|
+
maxBox: number;
|
|
1951
|
+
/** Logo box drawn: the wanted box, capped at `maxBox`; 0 with no plate */
|
|
1952
|
+
box: number;
|
|
1953
|
+
/** Logo and plate as drawn (centered on the code), or null with no plate */
|
|
1954
|
+
plate: {
|
|
1955
|
+
logoW: number;
|
|
1956
|
+
logoH: number;
|
|
1957
|
+
plateW: number;
|
|
1958
|
+
plateH: number;
|
|
1959
|
+
radius: number;
|
|
1960
|
+
cx: number;
|
|
1961
|
+
cy: number;
|
|
1962
|
+
} | null;
|
|
1963
|
+
}
|
|
1964
|
+
|
|
1965
|
+
/**
|
|
1966
|
+
* Badge sizes: strength grows the logo box, capped where the plate would
|
|
1967
|
+
* spoil more codewords than the code's error correction can spare. No
|
|
1968
|
+
* plate when the cap is under BADGE_MIN_BOX.
|
|
1969
|
+
*/
|
|
1970
|
+
function badgeLayout(ctx: RenderContext, traced: TracedLogo): QRArtBadgeLayout {
|
|
1971
|
+
const { size, t, modules, version } = ctx;
|
|
1972
|
+
const level = errorLevelOf(modules);
|
|
1973
|
+
const share = (0.18 + 0.15 * t) * BADGE_LEVEL_SCALE[level];
|
|
1974
|
+
const aspect = traced.width / traced.height;
|
|
1975
|
+
const wantedBox = Math.min(BADGE_MAX_SHARE, share) * size;
|
|
1976
|
+
const map = getCodewordMap(version, level);
|
|
1977
|
+
const maxBox = Math.max(0, badgeMaxBox(map, aspect));
|
|
1978
|
+
if (maxBox < BADGE_MIN_BOX) {
|
|
1979
|
+
return { wantedBox, maxBox, box: 0, plate: null };
|
|
1980
|
+
}
|
|
1981
|
+
// Within budget (the common case) the wanted box is kept as it is.
|
|
1982
|
+
const box = largestFit(map, aspect, Math.min(wantedBox, maxBox));
|
|
1983
|
+
return box < 0
|
|
1984
|
+
? { wantedBox, maxBox, box: 0, plate: null }
|
|
1985
|
+
: { wantedBox, maxBox, box, plate: badgeGeometry(box, aspect, size) };
|
|
1986
|
+
}
|
|
1987
|
+
|
|
1988
|
+
/**
|
|
1989
|
+
* Logo QR "badge" sizes for `options` (as `renderQRArt` would draw them), or
|
|
1990
|
+
* null when they don't render a badge. Editors can compare `box` with
|
|
1991
|
+
* `wantedBox` to say the code is too small for a bigger logo.
|
|
1992
|
+
*/
|
|
1993
|
+
export function getQRArtBadgeLayout(
|
|
1994
|
+
options: QRArtRenderOptions
|
|
1995
|
+
): QRArtBadgeLayout | null {
|
|
1996
|
+
const ctx = context(options);
|
|
1997
|
+
if (!(ctx && ctx.art.mode === "logo" && ctx.variant === "badge")) {
|
|
1998
|
+
return null;
|
|
1999
|
+
}
|
|
2000
|
+
return badgeLayout(ctx, tracedLogo(ctx.art, ctx.image));
|
|
2001
|
+
}
|
|
2002
|
+
|
|
2003
|
+
/** Signed distance from (px, py) to a centered rounded rectangle. */
|
|
2004
|
+
function roundedRectDistance(
|
|
2005
|
+
px: number,
|
|
2006
|
+
py: number,
|
|
2007
|
+
rect: { cx: number; cy: number; w: number; h: number; r: number }
|
|
2008
|
+
) {
|
|
2009
|
+
const qx = Math.abs(px - rect.cx) - (rect.w / 2 - rect.r);
|
|
2010
|
+
const qy = Math.abs(py - rect.cy) - (rect.h / 2 - rect.r);
|
|
2011
|
+
return (
|
|
2012
|
+
Math.hypot(Math.max(qx, 0), Math.max(qy, 0)) +
|
|
2013
|
+
Math.min(Math.max(qx, qy), 0) -
|
|
2014
|
+
rect.r
|
|
2015
|
+
);
|
|
2016
|
+
}
|
|
2017
|
+
|
|
2018
|
+
/** Body and eye-center colors of a badge code: the logo's colors, kept dark. */
|
|
2019
|
+
function badgeColors(
|
|
2020
|
+
ctx: Pick<RenderContext, "fg" | "bg" | "t">,
|
|
2021
|
+
traced: TracedLogo
|
|
2022
|
+
) {
|
|
2023
|
+
const { fg, bg, t } = ctx;
|
|
2024
|
+
const yFg = luma(fg);
|
|
2025
|
+
const yBg = luma(bg);
|
|
2026
|
+
const primary = primaryColor(traced);
|
|
2027
|
+
const tint = Math.min(1, t / 0.6);
|
|
2028
|
+
const capped = primary
|
|
2029
|
+
? toward(primary, fg, yFg + 0.3 * (yBg - yFg), true)
|
|
2030
|
+
: fg;
|
|
2031
|
+
const body = mix(fg, capped, tint);
|
|
2032
|
+
// The accent colors the eye centers only if it stays itself once darkened
|
|
2033
|
+
// enough to scan (a pale accent would turn muddy).
|
|
2034
|
+
const accent = primary ? primaryColor(traced, primary) : null;
|
|
2035
|
+
const accentTarget = yFg + 0.42 * (yBg - yFg);
|
|
2036
|
+
const inner =
|
|
2037
|
+
accent && luma(accent) <= accentTarget + 0.22
|
|
2038
|
+
? mix(fg, toward(accent, fg, accentTarget, true), tint)
|
|
2039
|
+
: body;
|
|
2040
|
+
return { body, inner };
|
|
2041
|
+
}
|
|
2042
|
+
|
|
2043
|
+
function renderLogoBadge(ctx: RenderContext): JSX.Element[] {
|
|
2044
|
+
const { art, image, size, kinds, modules, bg, margin, pixelSize, version } =
|
|
2045
|
+
ctx;
|
|
2046
|
+
const traced = tracedLogo(art, image);
|
|
2047
|
+
const layout = badgeLayout(ctx, traced).plate;
|
|
2048
|
+
const { body } = badgeColors(ctx, traced);
|
|
2049
|
+
const bodyHex = toHex(body);
|
|
2050
|
+
const rect = layout && plateRect(layout);
|
|
2051
|
+
// Clear every module whose dot would touch the plate, plus alignment
|
|
2052
|
+
// patterns (drawn solid below, or dropped when the plate covers them).
|
|
2053
|
+
const cleared = modules.map((row) => [...row]);
|
|
2054
|
+
for (let y = 0; y < size; y++) {
|
|
2055
|
+
for (let x = 0; x < size; x++) {
|
|
2056
|
+
const kind = kinds[y * size + x];
|
|
2057
|
+
if (
|
|
2058
|
+
kind === KIND_ALIGNMENT ||
|
|
2059
|
+
(rect && kind !== KIND_FINDER && plateClears(rect, x, y))
|
|
2060
|
+
) {
|
|
2061
|
+
(cleared[y] as boolean[])[x] = false;
|
|
2062
|
+
}
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
2065
|
+
const layers: JSX.Element[] = [];
|
|
2066
|
+
const drawn = ctx.body?.(cleared);
|
|
2067
|
+
if (drawn) {
|
|
2068
|
+
layers.push(
|
|
2069
|
+
<g fill={bodyHex} key="art-body">
|
|
2070
|
+
{drawn}
|
|
2071
|
+
</g>
|
|
2072
|
+
);
|
|
2073
|
+
} else {
|
|
2074
|
+
const dots = new PathGroups();
|
|
2075
|
+
for (let y = 0; y < size; y++) {
|
|
2076
|
+
for (let x = 0; x < size; x++) {
|
|
2077
|
+
if (cleared[y]?.[x] && kinds[y * size + x] !== KIND_FINDER) {
|
|
2078
|
+
dots.circle(
|
|
2079
|
+
bodyHex,
|
|
2080
|
+
(x + margin + 0.5) * pixelSize,
|
|
2081
|
+
(y + margin + 0.5) * pixelSize,
|
|
2082
|
+
0.45 * pixelSize
|
|
2083
|
+
);
|
|
2084
|
+
}
|
|
2085
|
+
}
|
|
2086
|
+
}
|
|
2087
|
+
layers.push(...dots.toElements("art-body"));
|
|
2088
|
+
}
|
|
2089
|
+
const visibleAlignment = alignmentCenters(version, size).filter(
|
|
2090
|
+
([cx, cy]) => !rect || roundedRectDistance(cx + 0.5, cy + 0.5, rect) > 3.2
|
|
2091
|
+
);
|
|
2092
|
+
if (visibleAlignment.length > 0) {
|
|
2093
|
+
layers.push(
|
|
2094
|
+
<path
|
|
2095
|
+
d={alignmentPath(visibleAlignment, margin, pixelSize)}
|
|
2096
|
+
fill={bodyHex}
|
|
2097
|
+
fillRule="evenodd"
|
|
2098
|
+
key="art-alignment"
|
|
2099
|
+
/>
|
|
2100
|
+
);
|
|
2101
|
+
}
|
|
2102
|
+
if (!layout) {
|
|
2103
|
+
return layers;
|
|
2104
|
+
}
|
|
2105
|
+
// Plate: background color with a hairline ring in a tint of the logo.
|
|
2106
|
+
const logo = logoPixels(art, image, traced);
|
|
2107
|
+
const plateX = (layout.cx - layout.plateW / 2 + margin) * pixelSize;
|
|
2108
|
+
const plateY = (layout.cy - layout.plateH / 2 + margin) * pixelSize;
|
|
2109
|
+
const plateW = layout.plateW * pixelSize;
|
|
2110
|
+
const plateH = layout.plateH * pixelSize;
|
|
2111
|
+
const radius = layout.radius * pixelSize;
|
|
2112
|
+
const ring = 0.1 * pixelSize;
|
|
2113
|
+
const outline = roundedRectPath(plateX, plateY, plateW, plateH, radius);
|
|
2114
|
+
layers.push(
|
|
2115
|
+
<path d={outline} fill={toHex(bg)} key="art-plate" />,
|
|
2116
|
+
<path
|
|
2117
|
+
d={
|
|
2118
|
+
outline +
|
|
2119
|
+
roundedRectPath(
|
|
2120
|
+
plateX + ring,
|
|
2121
|
+
plateY + ring,
|
|
2122
|
+
plateW - 2 * ring,
|
|
2123
|
+
plateH - 2 * ring,
|
|
2124
|
+
radius - ring
|
|
2125
|
+
)
|
|
2126
|
+
}
|
|
2127
|
+
fill={toHex(mix(bg, body, 0.16))}
|
|
2128
|
+
fillRule="evenodd"
|
|
2129
|
+
key="art-plate-ring"
|
|
2130
|
+
/>,
|
|
2131
|
+
logoGroup(
|
|
2132
|
+
traced,
|
|
2133
|
+
logo,
|
|
2134
|
+
{
|
|
2135
|
+
x: (layout.cx - layout.logoW / 2 + margin) * pixelSize,
|
|
2136
|
+
y: (layout.cy - layout.logoH / 2 + margin) * pixelSize,
|
|
2137
|
+
scale: (layout.logoW / traced.width) * pixelSize,
|
|
2138
|
+
},
|
|
2139
|
+
(color) => color,
|
|
2140
|
+
"art-logo"
|
|
2141
|
+
)
|
|
2142
|
+
);
|
|
2143
|
+
return layers;
|
|
2144
|
+
}
|
|
2145
|
+
|
|
2146
|
+
// ── Eyes ───────────────────────────────────────────────────────────────────
|
|
2147
|
+
|
|
2148
|
+
export interface QRArtEyeColorOptions {
|
|
2149
|
+
art: QRArt;
|
|
2150
|
+
/** QR version (1–40) */
|
|
2151
|
+
version: number;
|
|
2152
|
+
/** Solid dark color (gradients: first stop) */
|
|
2153
|
+
fgColor: string;
|
|
2154
|
+
/** Solid light color (gradients: first stop) */
|
|
2155
|
+
bgColor: string;
|
|
2156
|
+
}
|
|
2157
|
+
|
|
2158
|
+
/**
|
|
2159
|
+
* Logo QR: eye colors that match the logo, or null to keep the theme's.
|
|
2160
|
+
* "blend" colors each eye's center from the logo color nearest to it (the
|
|
2161
|
+
* frames keep the theme color); "badge" uses the logo's brand color for the
|
|
2162
|
+
* frames and its accent for the centers. Colors stay dark enough to scan.
|
|
2163
|
+
*/
|
|
2164
|
+
export function getQRArtEyeColors(
|
|
2165
|
+
options: QRArtEyeColorOptions
|
|
2166
|
+
): Partial<Record<EyePosition, { outer?: string; inner?: string }>> | null {
|
|
2167
|
+
const { art } = options;
|
|
2168
|
+
if (art.mode !== "logo" || art.matchEyes === false) {
|
|
2169
|
+
return null;
|
|
2170
|
+
}
|
|
2171
|
+
const image = art.image && decodeArtImage(art.image);
|
|
2172
|
+
if (!image) {
|
|
2173
|
+
return null;
|
|
2174
|
+
}
|
|
2175
|
+
const fg = rgbFrom(options.fgColor, [0, 0, 0]);
|
|
2176
|
+
const bg = rgbFrom(options.bgColor, [1, 1, 1]);
|
|
2177
|
+
const t = effectiveStrength(art, fg, bg);
|
|
2178
|
+
if (t <= 0) {
|
|
2179
|
+
return null;
|
|
2180
|
+
}
|
|
2181
|
+
const traced = tracedLogo(art, image);
|
|
2182
|
+
if (traced.palette.length === 0) {
|
|
2183
|
+
return null;
|
|
2184
|
+
}
|
|
2185
|
+
if (getQRArtVariant(art) === "badge") {
|
|
2186
|
+
const { body, inner } = badgeColors({ fg, bg, t }, traced);
|
|
2187
|
+
const colors = { outer: toHex(body), inner: toHex(inner) };
|
|
2188
|
+
return { topLeft: colors, topRight: colors, bottomLeft: colors };
|
|
2189
|
+
}
|
|
2190
|
+
const yFg = luma(fg);
|
|
2191
|
+
const yBg = luma(bg);
|
|
2192
|
+
const tint = Math.min(1, t / 0.6);
|
|
2193
|
+
const size = options.version * 4 + 17;
|
|
2194
|
+
const place = placement(traced.width, traced.height, size, "contain");
|
|
2195
|
+
const reach = 0.45 * Math.max(traced.width, traced.height);
|
|
2196
|
+
const eye = (mx: number, my: number) => {
|
|
2197
|
+
const ex = (mx - place.offsetX) / place.scale;
|
|
2198
|
+
const ey = (my - place.offsetY) / place.scale;
|
|
2199
|
+
let best: RGB | null = null;
|
|
2200
|
+
let bestScore = 0;
|
|
2201
|
+
for (const entry of traced.palette) {
|
|
2202
|
+
if (luma(entry.color) > 0.86) {
|
|
2203
|
+
continue;
|
|
2204
|
+
}
|
|
2205
|
+
const d2 = (entry.cx - ex) ** 2 + (entry.cy - ey) ** 2;
|
|
2206
|
+
const score =
|
|
2207
|
+
entry.area *
|
|
2208
|
+
(0.35 + chroma(entry.color)) *
|
|
2209
|
+
Math.exp(-d2 / (2 * reach ** 2));
|
|
2210
|
+
if (score > bestScore) {
|
|
2211
|
+
bestScore = score;
|
|
2212
|
+
best = entry.color;
|
|
2213
|
+
}
|
|
2214
|
+
}
|
|
2215
|
+
if (!best) {
|
|
2216
|
+
return {};
|
|
2217
|
+
}
|
|
2218
|
+
const capped = toward(best, fg, yFg + 0.42 * (yBg - yFg), true);
|
|
2219
|
+
return { inner: toHex(mix(fg, capped, tint)) };
|
|
2220
|
+
};
|
|
2221
|
+
return {
|
|
2222
|
+
topLeft: eye(3.5, 3.5),
|
|
2223
|
+
topRight: eye(size - 3.5, 3.5),
|
|
2224
|
+
bottomLeft: eye(3.5, size - 3.5),
|
|
2225
|
+
};
|
|
2226
|
+
}
|