Line data Source code
1 : import type {
2 : Bounds,
3 : Point2D as Point
4 : } from '@comfyorg/shared-frontend-utils/geometry'
5 : import type { NodeLayout } from '@comfyorg/graph-model/layout'
6 :
7 : export const REROUTE_RADIUS = 8
8 :
9 1868 : export function pointInBounds(point: Point, bounds: Bounds): boolean {
10 1868 : return (
11 : point.x >= bounds.x &&
12 : point.x <= bounds.x + bounds.width &&
13 : point.y >= bounds.y &&
14 : point.y <= bounds.y + bounds.height
15 : )
16 : }
17 :
18 : export function boundsIntersect(a: Bounds, b: Bounds): boolean {
19 : return !(
20 : a.x + a.width < b.x ||
21 : b.x + b.width < a.x ||
22 : a.y + a.height < b.y ||
23 : b.y + b.height < a.y
24 : )
25 : }
26 :
27 357 : function segmentTouchesBounds(a: Point, b: Point, bounds: Bounds): boolean {
28 357 : if (![a.x, a.y, b.x, b.y].every(Number.isFinite)) return false
29 357 : const left = bounds.x
30 357 : const right = bounds.x + bounds.width
31 357 : const top = bounds.y
32 357 : const bottom = bounds.y + bounds.height
33 357 : let tMin = 0
34 357 : let tMax = 1
35 357 : const dx = b.x - a.x
36 357 : const dy = b.y - a.y
37 357 : const clips: [number, number][] = [
38 : [-dx, a.x - left],
39 : [dx, right - a.x],
40 : [-dy, a.y - top],
41 : [dy, bottom - a.y]
42 : ]
43 357 : for (const [p, q] of clips) {
44 474 : if (p === 0) {
45 0 : if (q < 0) return false
46 0 : continue
47 : }
48 474 : const t = q / p
49 474 : if (p < 0) tMin = Math.max(tMin, t)
50 102 : else tMax = Math.min(tMax, t)
51 474 : if (tMin > tMax) return false
52 : }
53 6 : return true
54 : }
55 :
56 24 : export function polylineIntersectsBounds(
57 : points: readonly Point[],
58 : bounds: Bounds
59 : ): boolean {
60 24 : for (let i = 1; i < points.length; i++) {
61 357 : if (segmentTouchesBounds(points[i - 1], points[i], bounds)) return true
62 : }
63 18 : return false
64 : }
65 :
66 : export function calculateBounds(nodes: NodeLayout[]): Bounds {
67 : let minX = Infinity,
68 : minY = Infinity
69 : let maxX = -Infinity,
70 : maxY = -Infinity
71 :
72 : for (const node of nodes) {
73 : const bounds = node.bounds
74 : minX = Math.min(minX, bounds.x)
75 : minY = Math.min(minY, bounds.y)
76 : maxX = Math.max(maxX, bounds.x + bounds.width)
77 : maxY = Math.max(maxY, bounds.y + bounds.height)
78 : }
79 :
80 : return {
81 : x: minX,
82 : y: minY,
83 : width: maxX - minX,
84 : height: maxY - minY
85 : }
86 : }
|