-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfilters.js
More file actions
838 lines (690 loc) · 23.7 KB
/
Copy pathfilters.js
File metadata and controls
838 lines (690 loc) · 23.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
// WebGL CRT shader, inspired by crt-geom and ShaderGlass
const CRT_VERT = `#version 300 es
in vec2 a_pos;
out vec2 v_uv;
void main() {
v_uv = a_pos * 0.5 + 0.5;
v_uv.y = 1.0 - v_uv.y;
gl_Position = vec4(a_pos, 0.0, 1.0);
}`;
const CRT_FRAG = `#version 300 es
precision highp float;
in vec2 v_uv;
out vec4 outColor;
uniform sampler2D u_tex;
uniform vec2 u_resolution;
uniform float u_time;
const float CURVATURE = 0.20; // barrel distortion strength
const float CORNER_SIZE = 0.04; // rounded corner radius
const float CORNER_SMOOTH = 650.0; // corner edge softness
const float SCANLINE_WEIGHT = 0.65; // how dark the scanlines get
const float SCANLINE_SPEED = 0.0; // rolling scanline (0 = off)
const float DOT_MASK = 0.25; // RGB phosphor mask strength
const float CHROM_AB = 0.003; // chromatic aberration amount
const float VIGNETTE = 0.5; // edge darkening strength
const float BRIGHTNESS = 1.45; // brightness boost to compensate for darkening
vec2 barrel(vec2 uv) {
vec2 cc = uv - 0.5;
float r2 = dot(cc, cc);
return uv + cc * r2 * CURVATURE * (1.0 + r2 * 0.6);
}
float cornerMask(vec2 uv) {
vec2 q = abs(uv - 0.5) * 2.0;
vec2 d = max(q - (1.0 - vec2(CORNER_SIZE)), 0.0);
float dist = length(d);
return clamp((CORNER_SIZE - dist) * CORNER_SMOOTH, 0.0, 1.0);
}
// Brighter pixels get wider scanlines. Uses pre-distortion UV to avoid moiré.
float scanline(float screenY, float luminance) {
float width = 0.5 + luminance * 0.3;
float s = sin(screenY * 3.14159265);
return 1.0 - SCANLINE_WEIGHT * (1.0 - pow(abs(s), width));
}
void main() {
vec2 uv = barrel(v_uv);
if (uv.x < -0.01 || uv.x > 1.01 || uv.y < -0.01 || uv.y > 1.01) {
outColor = vec4(0.0, 0.0, 0.0, 1.0);
return;
}
float cmask = cornerMask(uv);
vec2 dir = (uv - 0.5) * CHROM_AB;
float r = texture(u_tex, uv - dir).r;
float g = texture(u_tex, uv).g;
float b = texture(u_tex, uv + dir).b;
vec3 col = vec3(r, g, b);
// Screen-space Y so scanlines don't moiré with barrel distortion.
float scanY = gl_FragCoord.y / 8.0 + u_time * SCANLINE_SPEED;
float lum = dot(col, vec3(0.299, 0.587, 0.114));
col *= scanline(scanY, lum);
// RGB phosphor dot mask
float px = gl_FragCoord.x;
int phase = int(mod(px, 3.0));
vec3 mask = vec3(1.0 - DOT_MASK);
if (phase == 0) mask.r = 1.0;
else if (phase == 1) mask.g = 1.0;
else mask.b = 1.0;
col *= mask;
float dist = length(uv - 0.5) * 2.0; // 0 at center, ~1.4 at corners
col *= 1.0 - VIGNETTE * dist * dist;
col *= BRIGHTNESS;
col *= cmask;
outColor = vec4(col, 1.0);
}`;
// Gameboy DMG shader
const GAMEBOY_FRAG = `#version 300 es
precision highp float;
in vec2 v_uv;
out vec4 outColor;
uniform sampler2D u_tex;
uniform vec2 u_resolution;
const float DOT_SIZE = 4.0;
const float CELL_SIZE = 6.0;
const vec3 PAL0 = vec3(0.608, 0.737, 0.059); // #9bbc0f — lightest
const vec3 PAL1 = vec3(0.545, 0.675, 0.059); // #8bac0f — light
const vec3 PAL2 = vec3(0.365, 0.529, 0.122); // #5d871f — mid
const vec3 PAL3 = vec3(0.188, 0.384, 0.188); // #306230 — dark
const vec3 PAL4 = vec3(0.059, 0.220, 0.059); // #0f380f — darkest
const vec3 GAP_COLOR = vec3(0.043, 0.165, 0.043); // dark green gap
const float DITHER_STRENGTH = 0.15; // how much dither to apply per palette step
float bayer4(vec2 pos) {
ivec2 p = ivec2(mod(pos, 4.0));
int idx = p.x + p.y * 4;
float m;
if (idx == 0) m = 0.0; else if (idx == 1) m = 8.0;
else if (idx == 2) m = 2.0; else if (idx == 3) m = 10.0;
else if (idx == 4) m = 12.0; else if (idx == 5) m = 4.0;
else if (idx == 6) m = 14.0; else if (idx == 7) m = 6.0;
else if (idx == 8) m = 3.0; else if (idx == 9) m = 11.0;
else if (idx == 10) m = 1.0; else if (idx == 11) m = 9.0;
else if (idx == 12) m = 15.0; else if (idx == 13) m = 7.0;
else if (idx == 14) m = 13.0; else m = 5.0;
return (m / 16.0) - 0.5; // range: -0.5 to +0.4375
}
void main() {
vec2 px = gl_FragCoord.xy;
vec2 cell = mod(px, CELL_SIZE);
vec2 cellIdx = floor(px / CELL_SIZE);
vec2 sampleUV = (cellIdx * CELL_SIZE + CELL_SIZE * 0.5) / u_resolution;
sampleUV.y = 1.0 - sampleUV.y; // flip Y for GL coordinates
vec3 col = texture(u_tex, sampleUV).rgb;
float lum = dot(col, vec3(0.299, 0.587, 0.114));
lum += bayer4(cellIdx) * DITHER_STRENGTH;
vec3 out_col;
if (lum > 0.80) out_col = PAL0;
else if (lum > 0.60) out_col = PAL1;
else if (lum > 0.40) out_col = PAL2;
else if (lum > 0.20) out_col = PAL3;
else out_col = PAL4;
if (cell.x >= DOT_SIZE || cell.y >= DOT_SIZE) {
outColor = vec4(GAP_COLOR, 1.0);
return;
}
outColor = vec4(out_col, 1.0);
}`;
// CRT filter
let _gl = null;
let _program = null;
let _posBuf = null;
let _texture = null;
let _overlayCanvas = null;
let _feedCanvas = null; // offscreen canvas to grab visible portion
let _feedCtx = null;
let _uRes = null;
let _uTime = null;
let _startTime = 0;
function _compileShader(gl, type, src) {
const s = gl.createShader(type);
gl.shaderSource(s, src);
gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
console.error("Shader compile error:", gl.getShaderInfoLog(s));
gl.deleteShader(s);
return null;
}
return s;
}
function initCRTFilter(overlayCanvas) {
_overlayCanvas = overlayCanvas;
const gl = overlayCanvas.getContext("webgl2", {
alpha: true,
premultipliedAlpha: false,
antialias: false,
});
if (!gl) {
console.error("WebGL2 not available");
return false;
}
_gl = gl;
_startTime = performance.now();
// Compile program
const vs = _compileShader(gl, gl.VERTEX_SHADER, CRT_VERT);
const fs = _compileShader(gl, gl.FRAGMENT_SHADER, CRT_FRAG);
_program = gl.createProgram();
gl.attachShader(_program, vs);
gl.attachShader(_program, fs);
gl.linkProgram(_program);
if (!gl.getProgramParameter(_program, gl.LINK_STATUS)) {
console.error("Program link error:", gl.getProgramInfoLog(_program));
return false;
}
// Fullscreen quad (two triangles)
_posBuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, _posBuf);
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]),
gl.STATIC_DRAW,
);
// Texture for the source feed
_texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, _texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
// Uniform locations
gl.useProgram(_program);
_uRes = gl.getUniformLocation(_program, "u_resolution");
_uTime = gl.getUniformLocation(_program, "u_time");
// Offscreen canvas for grabbing the visible portion
_feedCanvas = document.createElement("canvas");
_feedCtx = _feedCanvas.getContext("2d");
_feedCtx.imageSmoothingEnabled = false;
return true;
}
function renderCRTFrame(sourceCanvas, displayX, displayY, dpr) {
if (!_gl || !_overlayCanvas) return;
const gl = _gl;
const vw = window.innerWidth;
const vh = window.innerHeight;
// Size the overlay to fill the viewport at device pixel ratio
const pxW = Math.round(vw * devicePixelRatio);
const pxH = Math.round(vh * devicePixelRatio);
if (_overlayCanvas.width !== pxW || _overlayCanvas.height !== pxH) {
_overlayCanvas.width = pxW;
_overlayCanvas.height = pxH;
_overlayCanvas.style.width = vw + "px";
_overlayCanvas.style.height = vh + "px";
}
// Copy the visible portion of the source canvas into the feed canvas
const sx = Math.round(displayX * dpr);
const sy = Math.round(displayY * dpr);
const sw = Math.round(vw * dpr);
const sh = Math.round(vh * dpr);
if (_feedCanvas.width !== sw || _feedCanvas.height !== sh) {
_feedCanvas.width = sw;
_feedCanvas.height = sh;
}
_feedCtx.drawImage(sourceCanvas, sx, sy, sw, sh, 0, 0, sw, sh);
// Upload to GPU
gl.bindTexture(gl.TEXTURE_2D, _texture);
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
gl.RGBA,
gl.UNSIGNED_BYTE,
_feedCanvas,
);
// Render
gl.viewport(0, 0, pxW, pxH);
gl.useProgram(_program);
gl.uniform2f(_uRes, pxW, pxH);
gl.uniform1f(_uTime, (performance.now() - _startTime) / 1000.0);
const aPos = gl.getAttribLocation(_program, "a_pos");
gl.bindBuffer(gl.ARRAY_BUFFER, _posBuf);
gl.enableVertexAttribArray(aPos);
gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
// Gameboy filter
let _gb_gl = null;
let _gb_program = null;
let _gb_posBuf = null;
let _gb_texture = null;
let _gb_overlayCanvas = null;
let _gb_feedCanvas = null;
let _gb_feedCtx = null;
let _gb_uRes = null;
function initGameboyFilter(overlayCanvas) {
_gb_overlayCanvas = overlayCanvas;
const gl = overlayCanvas.getContext("webgl2", {
alpha: true,
premultipliedAlpha: false,
antialias: false,
});
if (!gl) {
console.error("WebGL2 not available for Gameboy filter");
return false;
}
_gb_gl = gl;
const vs = _compileShader(gl, gl.VERTEX_SHADER, CRT_VERT);
const fs = _compileShader(gl, gl.FRAGMENT_SHADER, GAMEBOY_FRAG);
_gb_program = gl.createProgram();
gl.attachShader(_gb_program, vs);
gl.attachShader(_gb_program, fs);
gl.linkProgram(_gb_program);
if (!gl.getProgramParameter(_gb_program, gl.LINK_STATUS)) {
console.error(
"Gameboy program link error:",
gl.getProgramInfoLog(_gb_program),
);
return false;
}
_gb_posBuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, _gb_posBuf);
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]),
gl.STATIC_DRAW,
);
_gb_texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, _gb_texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.useProgram(_gb_program);
_gb_uRes = gl.getUniformLocation(_gb_program, "u_resolution");
_gb_feedCanvas = document.createElement("canvas");
_gb_feedCtx = _gb_feedCanvas.getContext("2d");
_gb_feedCtx.imageSmoothingEnabled = false;
return true;
}
function renderGameboyFrame(sourceCanvas, displayX, displayY, dpr) {
if (!_gb_gl || !_gb_overlayCanvas) return;
const gl = _gb_gl;
const vw = window.innerWidth;
const vh = window.innerHeight;
const pxW = Math.round(vw * devicePixelRatio);
const pxH = Math.round(vh * devicePixelRatio);
if (_gb_overlayCanvas.width !== pxW || _gb_overlayCanvas.height !== pxH) {
_gb_overlayCanvas.width = pxW;
_gb_overlayCanvas.height = pxH;
_gb_overlayCanvas.style.width = vw + "px";
_gb_overlayCanvas.style.height = vh + "px";
}
const sx = Math.round(displayX * dpr);
const sy = Math.round(displayY * dpr);
const sw = Math.round(vw * dpr);
const sh = Math.round(vh * dpr);
if (_gb_feedCanvas.width !== sw || _gb_feedCanvas.height !== sh) {
_gb_feedCanvas.width = sw;
_gb_feedCanvas.height = sh;
}
_gb_feedCtx.drawImage(sourceCanvas, sx, sy, sw, sh, 0, 0, sw, sh);
gl.bindTexture(gl.TEXTURE_2D, _gb_texture);
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
gl.RGBA,
gl.UNSIGNED_BYTE,
_gb_feedCanvas,
);
gl.viewport(0, 0, pxW, pxH);
gl.useProgram(_gb_program);
gl.uniform2f(_gb_uRes, pxW, pxH);
const aPos = gl.getAttribLocation(_gb_program, "a_pos");
gl.bindBuffer(gl.ARRAY_BUFFER, _gb_posBuf);
gl.enableVertexAttribArray(aPos);
gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
// Liquid diamond filter
let _diamondInstance = null;
function initGlassFilter(overlayEl) {
_diamondInstance = window.attachLiquidPyramid({ parent: overlayEl });
return true;
}
function showGlassFilter() {
if (_diamondInstance) _diamondInstance.show();
}
function hideGlassFilter() {
if (_diamondInstance) _diamondInstance.hide();
}
function updateDiamondRotation(ox, oy) {
if (_diamondInstance) _diamondInstance.setRotation(ox, oy);
}
// Translate filter (OCR via PaddleOCR + translation)
let _trOverlay = null;
let _trBoxContainer = null;
let _trOcrInstance = null;
let _trReady = false;
let _trBusy = false;
let _trResults = null;
let _trResultsDirty = false;
let _trLastOcrX = 0;
let _trLastOcrY = 0;
let _trLastOcrTime = 0;
let _trLastMoveTime = 0;
let _trPrevX = null;
let _trPrevY = null;
const TR_MOVE_SETTLE_MS = 64;
let _trFeedCanvas = null;
let _trFeedCtx = null;
let _trTranslator = null;
let _trCache = new Map();
let _trCacheVersion = 0;
let _trRenderedCacheVersion = 0;
let _trOcrW = 0;
let _trOcrH = 0;
const TR_OCR_MAX_WIDTH = 1500;
const TR_OCR_COOLDOWN = 2000;
const TR_OCR_FORCE_INTERVAL = 4000;
const TR_OCR_MOVE_THRESHOLD = 50;
const TR_CONFIDENCE_MIN = 0.4;
const TR_TEXT_RE = /\p{Letter}{2,}/u;
const PADDLE_ASSETS = "https://cdn.jsdelivr.net/npm/paddleocr-browser/dist/";
function _trIsText(str) {
if (!TR_TEXT_RE.test(str)) return false;
const letters = str.replace(/[^\p{Letter}]/gu, "").length;
return letters / str.length >= 0.5;
}
// Compute axis-aligned rect + rotation from a quadrilateral box [[x,y], [x,y], [x,y], [x,y]]
function _trQuadToRect(box, ocrW, ocrH, iw, ih) {
const [tl, tr, br, bl] = box.map((p) => [
(p[0] / ocrW) * iw,
(p[1] / ocrH) * ih,
]);
const left = Math.min(tl[0], bl[0]);
const top = Math.min(tl[1], tr[1]);
const right = Math.max(tr[0], br[0]);
const bottom = Math.max(bl[1], br[1]);
const width = right - left;
const height = bottom - top;
const angle = Math.atan2(tr[1] - tl[1], tr[0] - tl[0]);
// Box height from left edge (for font sizing)
const boxH = Math.hypot(bl[0] - tl[0], bl[1] - tl[1]);
return { left, top, width, height, angle, boxH };
}
async function _trInitPaddle(statusEl) {
// Wait for Paddle module to be available
if (!window.Paddle) {
await new Promise((resolve) => {
window.addEventListener("paddle-ready", resolve, { once: true });
});
}
if (statusEl) statusEl.textContent = "Loading OCR models...";
// Wait for OpenCV.js WASM to fully initialize
if (!window.cv || typeof window.cv.matFromImageData !== "function") {
await new Promise((resolve) => {
function onCvReady() {
if (typeof window.cv === "function") {
window.cv().then((cvModule) => {
window.cv = cvModule;
resolve();
});
} else if (
window.cv &&
typeof window.cv.matFromImageData === "function"
) {
resolve();
} else if (window.cv) {
const orig = window.cv.onRuntimeInitialized;
window.cv.onRuntimeInitialized = () => {
if (orig) orig();
resolve();
};
} else {
const id = setInterval(() => {
if (window.cv && typeof window.cv.matFromImageData === "function") {
clearInterval(id);
resolve();
}
}, 100);
}
}
if (window.cv) {
onCvReady();
} else {
window.addEventListener("opencv-ready", onCvReady, { once: true });
}
});
}
// Fetch dictionary text (esearch-ocr expects content via `dic`, not a path)
const dicText = await fetch(PADDLE_ASSETS + "ppocr_keys_v1.txt").then((r) =>
r.text(),
);
if (statusEl) statusEl.textContent = "Initializing OCR...";
// esearch-ocr v5 internal API uses flat props: detPath, recPath, dic, cv, ort
_trOcrInstance = await window.Paddle.init({
detPath: PADDLE_ASSETS + "ppocr_det.onnx",
recPath: PADDLE_ASSETS + "ppocr_rec.onnx",
dic: dicText,
cv: window.cv,
ort: window.ort,
});
_trReady = true;
}
function initTranslateFilter(overlayEl) {
_trOverlay = overlayEl;
_trFeedCanvas = document.createElement("canvas");
_trFeedCtx = _trFeedCanvas.getContext("2d");
_trBoxContainer = document.createElement("div");
_trBoxContainer.style.cssText =
"position:absolute;top:0;left:0;width:100%;height:100%;will-change:transform";
_trOverlay.appendChild(_trBoxContainer);
_trOverlay.insertAdjacentHTML(
"beforeend",
'<div class="translate-status">Loading OCR engine...</div>',
);
const statusEl = _trOverlay.querySelector(".translate-status");
_trInitPaddle(statusEl)
.then(() => {
if (statusEl) statusEl.textContent = "OCR ready — scanning...";
setTimeout(() => {
const s = _trOverlay.querySelector(".translate-status");
if (s && s.textContent === "OCR ready — scanning...") s.remove();
}, 2000);
})
.catch((e) => {
console.error("PaddleOCR init failed:", e);
if (statusEl) statusEl.textContent = "OCR failed to load";
});
(async () => {
if ("Translator" in self) {
try {
_trTranslator = await Translator.create({
sourceLanguage: "de",
targetLanguage: "en",
});
} catch (e) {
console.log("Chrome Translator API not available:", e);
}
}
})();
return true;
}
function showTranslateFilter() {
_trResults = null;
_trResultsDirty = false;
_trLastOcrTime = 0;
_trLastMoveTime = 0;
_trPrevX = null;
_trPrevY = null;
_trCache.clear();
_trCacheVersion = 0;
_trRenderedCacheVersion = 0;
if (_trBoxContainer) _trBoxContainer.innerHTML = "";
}
function hideTranslateFilter() {
if (_trBoxContainer) _trBoxContainer.innerHTML = "";
_trResults = null;
_trResultsDirty = false;
}
function _trTriggerOcr(sourceCanvas, displayX, displayY, dpr) {
if (!_trReady || _trBusy) return;
const now = performance.now();
// Skip OCR while the window is still moving.
if (_trPrevX !== null && (displayX !== _trPrevX || displayY !== _trPrevY)) {
_trLastMoveTime = now;
}
_trPrevX = displayX;
_trPrevY = displayY;
if (now - _trLastMoveTime < TR_MOVE_SETTLE_MS) return;
const timeSince = now - _trLastOcrTime;
const dist = Math.hypot(displayX - _trLastOcrX, displayY - _trLastOcrY);
const shouldRun =
_trLastOcrTime === 0 ||
(timeSince > TR_OCR_COOLDOWN && dist > TR_OCR_MOVE_THRESHOLD) ||
timeSince > TR_OCR_FORCE_INTERVAL;
if (!shouldRun) return;
_trBusy = true;
const sx = displayX * dpr;
const sy = displayY * dpr;
const sw = window.innerWidth * dpr;
const sh = window.innerHeight * dpr;
const scale = Math.min(1, TR_OCR_MAX_WIDTH / (sw / dpr));
const ocrW = Math.round((sw / dpr) * scale);
const ocrH = Math.round((sh / dpr) * scale);
_trFeedCanvas.width = ocrW;
_trFeedCanvas.height = ocrH;
_trFeedCtx.drawImage(sourceCanvas, sx, sy, sw, sh, 0, 0, ocrW, ocrH);
_trOcrW = ocrW;
_trOcrH = ocrH;
console.log("OCR: running on", ocrW, "x", ocrH, "canvas");
_trOcrInstance
.ocr(_trFeedCanvas)
.then((result) => {
console.log("OCR result:", result);
_trResults = result;
_trResultsDirty = true;
_trLastOcrX = displayX;
_trLastOcrY = displayY;
_trLastOcrTime = performance.now();
_trBusy = false;
_trTranslateResults(result);
})
.catch((e) => {
console.error("OCR failed:", e);
_trBusy = false;
});
}
function _trTranslateResults(result) {
if (!_trTranslator || !result || !result.src) return;
for (const item of result.src) {
const text = item.text.trim();
if (!text || !_trIsText(text) || _trCache.has(text)) continue;
_trTranslator
.translate(text)
.then((translated) => {
_trCache.set(text, translated);
_trCacheVersion++;
})
.catch(() => {});
}
}
function _trRebuildBoxes() {
if (!_trBoxContainer || !_trResults || !_trResults.src) return;
const iw = window.innerWidth;
const ih = window.innerHeight;
const ocrW = _trOcrW || 1;
const ocrH = _trOcrH || 1;
let html = "";
for (const item of _trResults.src) {
if (item.mean < TR_CONFIDENCE_MIN) continue;
const text = item.text.trim();
if (!text || !_trIsText(text)) continue;
const r = _trQuadToRect(item.box, ocrW, ocrH, iw, ih);
const ocrSize = Math.max(8, Math.min(r.boxH * 0.75, 32));
// const fontSize = Math.round((14 + ocrSize) / 2);
const fontSize = 20 * (1 / 3) + ocrSize * (2 / 3);
const extraTranslateBoxPadding = 6;
const displayText = _trCache.get(text) || text;
const escaped = displayText
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """);
html += `<div class="translate-box" style="left:${r.left - extraTranslateBoxPadding}px;top:${r.top - extraTranslateBoxPadding}px;width:${r.width + extraTranslateBoxPadding * 2}px;height:${r.height + extraTranslateBoxPadding * 2}px;font-size:${fontSize}px;">${escaped}</div>`;
}
_trBoxContainer.innerHTML = html;
_trResultsDirty = false;
_trRenderedCacheVersion = _trCacheVersion;
}
function renderTranslateFrame(sourceCanvas, displayX, displayY, dpr) {
_trTriggerOcr(sourceCanvas, displayX, displayY, dpr);
if (_trResultsDirty || _trCacheVersion !== _trRenderedCacheVersion) {
_trRebuildBoxes();
}
if (_trBoxContainer && _trResults) {
const dx = -(displayX - _trLastOcrX);
const dy = -(displayY - _trLastOcrY);
_trBoxContainer.style.transform = `translate(${dx}px, ${dy}px)`;
}
}
// OCR Debug filter (localhost only) — reuses PaddleOCR engine
let _dbgOverlay = null;
let _dbgBoxContainer = null;
let _dbgLastResultsRef = null;
function initOcrDebugFilter(overlayEl) {
_dbgOverlay = overlayEl;
_dbgBoxContainer = document.createElement("div");
_dbgBoxContainer.style.cssText =
"position:absolute;top:0;left:0;width:100%;height:100%;will-change:transform";
_dbgOverlay.appendChild(_dbgBoxContainer);
if (!_trFeedCanvas) {
_trFeedCanvas = document.createElement("canvas");
_trFeedCtx = _trFeedCanvas.getContext("2d");
}
if (!_trReady) {
_dbgOverlay.insertAdjacentHTML(
"beforeend",
'<div class="translate-status">Loading OCR engine...</div>',
);
const statusEl = _dbgOverlay.querySelector(".translate-status");
_trInitPaddle(statusEl)
.then(() => {
if (statusEl) statusEl.remove();
})
.catch((e) => {
console.error("PaddleOCR init failed:", e);
});
}
return true;
}
function showOcrDebugFilter() {
_dbgLastResultsRef = null;
if (_dbgBoxContainer) _dbgBoxContainer.innerHTML = "";
_trLastOcrTime = 0;
_trLastMoveTime = 0;
_trPrevX = null;
_trPrevY = null;
}
function hideOcrDebugFilter() {
if (_dbgBoxContainer) _dbgBoxContainer.innerHTML = "";
_dbgLastResultsRef = null;
}
function _dbgRebuildBoxes() {
if (!_dbgBoxContainer || !_trResults || !_trResults.src) return;
const iw = window.innerWidth;
const ih = window.innerHeight;
const ocrW = _trOcrW || 1;
const ocrH = _trOcrH || 1;
let html = "";
for (const item of _trResults.src) {
const r = _trQuadToRect(item.box, ocrW, ocrH, iw, ih);
const text = item.text.trim();
// Quadrilateral outline via SVG
const pts = item.box
.map((p) => `${(p[0] / ocrW) * iw},${(p[1] / ocrH) * ih}`)
.join(" ");
html += `<svg style="position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;overflow:visible"><polygon points="${pts}" fill="none" stroke="rgba(255,0,0,0.7)" stroke-width="1"/></svg>`;
// Label
html += `<div class="ocr-debug-label" style="left:${r.left}px;top:${r.top - 10}px">c:${item.mean.toFixed(2)} "${text.substring(0, 60)}"</div>`;
}
_dbgBoxContainer.innerHTML = html;
_dbgLastResultsRef = _trResults;
}
function renderOcrDebugFrame(sourceCanvas, displayX, displayY, dpr) {
_trTriggerOcr(sourceCanvas, displayX, displayY, dpr);
if (_trResults !== _dbgLastResultsRef) {
_dbgRebuildBoxes();
}
if (_dbgBoxContainer && _trResults) {
const dx = -(displayX - _trLastOcrX);
const dy = -(displayY - _trLastOcrY);
_dbgBoxContainer.style.transform = `translate(${dx}px, ${dy}px)`;
}
}