Line data Source code
1 : import type { ContentStore } from '#/content'
2 : import type { RasterData, SceneNode } from '#/node'
3 : import type { Point2D as Vec2 } from '@comfyorg/shared-frontend-utils/geometry'
4 : import { toLocalFrame } from '#/tools/transformMath'
5 :
6 : export const PICK_OPACITY_THRESHOLD = 0.25
7 :
8 : export type AlphaSampler = (
9 : canvas: HTMLCanvasElement,
10 : x: number,
11 : y: number
12 : ) => number
13 :
14 0 : function defaultAlphaSampler(
15 : canvas: HTMLCanvasElement,
16 : x: number,
17 : y: number
18 : ): number {
19 0 : let ctx: CanvasRenderingContext2D | null
20 0 : try {
21 0 : ctx = canvas.getContext('2d', { willReadFrequently: true })
22 : } catch {
23 0 : ctx = null
24 : }
25 0 : if (!ctx) return 1
26 0 : try {
27 0 : const px = Math.max(0, Math.min(canvas.width - 1, Math.floor(x)))
28 0 : const py = Math.max(0, Math.min(canvas.height - 1, Math.floor(y)))
29 : const data = ctx.getImageData(px, py, 1, 1).data
30 0 : return (data.at(3) ?? 255) / 255
31 : } catch {
32 0 : return 1
33 : }
34 : }
35 :
36 0 : function rasterAlphaAt(
37 : node: RasterData,
38 : pt: Vec2,
39 : content: ContentStore,
40 : sample: AlphaSampler
41 : ): number {
42 0 : const t = node.transform
43 0 : if (t.w <= 0 || t.h <= 0) return 0
44 0 : const local = toLocalFrame(t, pt)
45 0 : if (Math.abs(local.x) > t.w / 2 || Math.abs(local.y) > t.h / 2) return 0
46 0 : const canvas = content.get(node.contentId)?.canvas
47 0 : if (!canvas || canvas.width <= 0 || canvas.height <= 0) return 1
48 : const cx = ((local.x + t.w / 2) / t.w) * canvas.width
49 : const cy = ((local.y + t.h / 2) / t.h) * canvas.height
50 0 : return sample(canvas, cx, cy)
51 : }
52 :
53 0 : function boxAlphaAt(node: SceneNode, pt: Vec2): number {
54 0 : const t = node.transform
55 0 : if (t.w <= 0 || t.h <= 0) return 0
56 0 : const local = toLocalFrame(t, pt)
57 0 : return Math.abs(local.x) <= t.w / 2 && Math.abs(local.y) <= t.h / 2 ? 1 : 0
58 : }
59 :
60 0 : export function layerOpacityAt(
61 : node: SceneNode,
62 : pt: Vec2,
63 : content: ContentStore,
64 : sample: AlphaSampler = defaultAlphaSampler
65 : ): number {
66 0 : if (!node.visible || node.opacity <= 0) return 0
67 0 : switch (node.kind) {
68 : case 'group': {
69 0 : let best = 0
70 0 : for (const child of node.children) {
71 0 : best = Math.max(best, layerOpacityAt(child, pt, content, sample))
72 0 : if (best >= 1) break
73 : }
74 0 : return best * node.opacity
75 : }
76 : case 'raster':
77 0 : return rasterAlphaAt(node, pt, content, sample)
78 : default:
79 0 : return boxAlphaAt(node, pt)
80 : }
81 : }
82 :
83 0 : export function pickLayerAt(
84 : layers: readonly SceneNode[],
85 : pt: Vec2,
86 : content: ContentStore,
87 : sample: AlphaSampler = defaultAlphaSampler
88 : ): SceneNode | null {
89 0 : for (let i = layers.length - 1; i >= 0; i--) {
90 0 : const node = layers[i]
91 0 : if (layerOpacityAt(node, pt, content, sample) > PICK_OPACITY_THRESHOLD)
92 0 : return node
93 : }
94 0 : return null
95 : }
|