diff --git a/src/lib/litegraph/src/LGraphCanvas.ts b/src/lib/litegraph/src/LGraphCanvas.ts index cd79d803b7d..f8c2ccb0843 100644 --- a/src/lib/litegraph/src/LGraphCanvas.ts +++ b/src/lib/litegraph/src/LGraphCanvas.ts @@ -714,6 +714,9 @@ export class LGraphCanvas implements CustomEventDispatcher * performant than {@link visible_nodes} for visibility checks. */ private _visible_node_ids: Set = new Set() + + /** Cached per-frame link render context to avoid rebuilding per-link. */ + private _cachedLinkRenderContext: LinkRenderContext | null = null node_over?: LGraphNode node_capturing_input?: LGraphNode | null highlighted_links: Dictionary = {} @@ -5083,6 +5086,9 @@ export class LGraphCanvas implements CustomEventDispatcher if (!this.canvas || this.canvas.width == 0 || this.canvas.height == 0) return + // Reset per-frame caches so stale data is never used if a code path is skipped. + this._cachedLinkRenderContext = null + // fps counting const now = LiteGraph.getTime() this.render_time = (now - this.last_draw_time) * 0.001 @@ -5117,10 +5123,11 @@ export class LGraphCanvas implements CustomEventDispatcher getCurrentGraphNodesInFrameOrder(), this.visible_nodes ) - // Update visible node IDs - this._visible_node_ids = new Set( - this.visible_nodes.map((node) => node.id) - ) + // Update visible node IDs (reuse existing Set to avoid allocation) + this._visible_node_ids.clear() + for (const node of this.visible_nodes) { + this._visible_node_ids.add(node.id) + } // Arrange subgraph IO nodes const { subgraph } = this @@ -5351,10 +5358,7 @@ export class LGraphCanvas implements CustomEventDispatcher colour, fromDirection, dragDirection, - { - ...this.buildLinkRenderContext(), - linkMarkerShape: LinkMarkerShape.None - } + this._cachedLinkRenderContext ?? this.buildLinkRenderContext() ) } if (renderLink instanceof MovingInputLink) this.setDirty(false, true) @@ -6136,6 +6140,9 @@ export class LGraphCanvas implements CustomEventDispatcher this.renderedPaths.clear() if (this.links_render_mode === LinkRenderType.HIDDEN_LINK) return + // Cache the link render context once per frame + this._cachedLinkRenderContext = this.buildLinkRenderContext() + const { graph, subgraph } = this if (!graph) throw new NullGraphError() @@ -6414,19 +6421,28 @@ export class LGraphCanvas implements CustomEventDispatcher // Get all points this link passes through const reroutes = LLink.getReroutes(graph, link) - const points: [Point, ...Point[], Point] = [ - startPos, - ...reroutes.map((x) => x.pos), - endPos - ] - // Bounding box of all points (bezier overshoot on long links will be cut) - const pointsX = points.map((x) => x[0]) - const pointsY = points.map((x) => x[1]) - link_bounding[0] = Math.min(...pointsX) - link_bounding[1] = Math.min(...pointsY) - link_bounding[2] = Math.max(...pointsX) - link_bounding[0] - link_bounding[3] = Math.max(...pointsY) - link_bounding[1] + // Compute bounding box inline to avoid allocating temporary arrays + let minX = startPos[0] + let minY = startPos[1] + let maxX = minX + let maxY = minY + for (let i = 0; i < reroutes.length; i++) { + const pos = reroutes[i].pos + if (pos[0] < minX) minX = pos[0] + else if (pos[0] > maxX) maxX = pos[0] + if (pos[1] < minY) minY = pos[1] + else if (pos[1] > maxY) maxY = pos[1] + } + if (endPos[0] < minX) minX = endPos[0] + else if (endPos[0] > maxX) maxX = endPos[0] + if (endPos[1] < minY) minY = endPos[1] + else if (endPos[1] > maxY) maxY = endPos[1] + + link_bounding[0] = minX + link_bounding[1] = minY + link_bounding[2] = maxX - minX + link_bounding[3] = maxY - minY // skip links outside of the visible area of the canvas if (!overlapBounding(link_bounding, margin_area)) return @@ -6494,8 +6510,7 @@ export class LGraphCanvas implements CustomEventDispatcher // Skip the last segment if it is being dragged if (link._dragging) return - // Use runtime fallback; TypeScript cannot evaluate this correctly. - const segmentStartPos = points.at(-2) ?? startPos + const segmentStartPos = reroutes.at(-1)?.pos ?? startPos // Render final link segment this.renderLink( @@ -6616,7 +6631,8 @@ export class LGraphCanvas implements CustomEventDispatcher } = {} ): void { if (this.linkRenderer) { - const context = this.buildLinkRenderContext() + const context = + this._cachedLinkRenderContext ?? this.buildLinkRenderContext() this.linkRenderer.renderLinkDirect( ctx, a, diff --git a/src/lib/litegraph/src/LGraphNode.test.ts b/src/lib/litegraph/src/LGraphNode.test.ts index 4cdc98acfca..828753ad051 100644 --- a/src/lib/litegraph/src/LGraphNode.test.ts +++ b/src/lib/litegraph/src/LGraphNode.test.ts @@ -877,6 +877,132 @@ describe('LGraphNode', () => { expect(out[3]).toBe(120 + LiteGraph.NODE_TITLE_HEIGHT) }) }) + describe('_slotsDirty flag', () => { + test('starts dirty', () => { + const n = new LGraphNode('Test') + expect(n._slotsDirty).toBe(true) + }) + + test('is cleared by _setConcreteSlots', () => { + const n = new LGraphNode('Test') + n._setConcreteSlots() + expect(n._slotsDirty).toBe(false) + }) + + test('skips work when clean', () => { + const n = new LGraphNode('Test') + n.addInput('in', 'number') + n._setConcreteSlots() + expect(n._slotsDirty).toBe(false) + + const concreteInput = n.inputs[0] + n._setConcreteSlots() + expect(n.inputs[0]).toBe(concreteInput) + }) + + test('is set by addInput', () => { + const n = new LGraphNode('Test') + n._setConcreteSlots() + n.addInput('in', 'number') + expect(n._slotsDirty).toBe(true) + }) + + test('is set by removeInput', () => { + const n = new LGraphNode('Test') + n.addInput('in', 'number') + n._setConcreteSlots() + n.removeInput(0) + expect(n._slotsDirty).toBe(true) + }) + + test('is set by addOutput', () => { + const n = new LGraphNode('Test') + n._setConcreteSlots() + n.addOutput('out', 'number') + expect(n._slotsDirty).toBe(true) + }) + + test('is set by removeOutput', () => { + const n = new LGraphNode('Test') + n.addOutput('out', 'number') + n._setConcreteSlots() + n.removeOutput(0) + expect(n._slotsDirty).toBe(true) + }) + + test('refreshes drawn slots after direct array mutations', () => { + const n = new LGraphNode('Test') + n.addInput('old input', 'number') + n.addOutput('old output', 'number') + n._setConcreteSlots() + + const oldInput = n.inputs[0] + const oldOutput = n.outputs[0] + expect(oldInput).toBeInstanceOf(NodeInputSlot) + expect(oldOutput).toBeInstanceOf(NodeOutputSlot) + if (!(oldInput instanceof NodeInputSlot)) throw new Error('Invalid input') + if (!(oldOutput instanceof NodeOutputSlot)) + throw new Error('Invalid output') + const oldInputDraw = vi.spyOn(oldInput, 'draw') + const oldOutputDraw = vi.spyOn(oldOutput, 'draw') + + n.inputs.splice( + 0, + 1, + new NodeInputSlot({ name: 'new input', type: 'number', link: null }, n) + ) + n.outputs.splice( + 0, + 1, + new NodeOutputSlot( + { name: 'new output', type: 'number', links: null }, + n + ) + ) + expect(n._slotsDirty).toBe(true) + + n._setConcreteSlots() + const newInput = n.inputs[0] + const newOutput = n.outputs[0] + expect(newInput).toBeInstanceOf(NodeInputSlot) + expect(newOutput).toBeInstanceOf(NodeOutputSlot) + if (!(newInput instanceof NodeInputSlot)) throw new Error('Invalid input') + if (!(newOutput instanceof NodeOutputSlot)) + throw new Error('Invalid output') + const newInputDraw = vi + .spyOn(newInput, 'draw') + .mockImplementation(() => {}) + const newOutputDraw = vi + .spyOn(newOutput, 'draw') + .mockImplementation(() => {}) + + n.drawSlots(createMockCanvasRenderingContext2D(), { + colorContext: { + getConnectedColor: () => '#fff', + getDisconnectedColor: () => '#fff' + }, + editorAlpha: 1, + lowQuality: false + }) + + expect(oldInputDraw).not.toHaveBeenCalled() + expect(oldOutputDraw).not.toHaveBeenCalled() + expect(newInputDraw).toHaveBeenCalledOnce() + expect(newOutputDraw).toHaveBeenCalledOnce() + }) + + test('is set by configure', () => { + const n = new LGraphNode('Test') + n._setConcreteSlots() + n.configure( + getMockISerialisedNode({ + inputs: [{ name: 'a', type: 'number', link: null }], + outputs: [{ name: 'b', type: 'number', links: null }] + }) + ) + expect(n._slotsDirty).toBe(true) + }) + }) }) describe('snapToGrid', () => { diff --git a/src/lib/litegraph/src/LGraphNode.ts b/src/lib/litegraph/src/LGraphNode.ts index 3919e4bb8d9..6bf00c2bf55 100644 --- a/src/lib/litegraph/src/LGraphNode.ts +++ b/src/lib/litegraph/src/LGraphNode.ts @@ -63,6 +63,7 @@ import { } from './node/slotLinks' import { createInputSlotView, + createOutputSlotView, resolveInputSlotView } from './node/slotDescriptorView' import { initializeWidgetsView } from './node/widgetsView' @@ -406,6 +407,8 @@ export class LGraphNode private _concreteInputs: NodeInputSlot[] = [] private _concreteOutputs: NodeOutputSlot[] = [] + /** @internal Set when inputs/outputs change; cleared by {@link _setConcreteSlots}. */ + _slotsDirty: boolean = true get properties(): Dictionary { return this._state.properties @@ -1011,7 +1014,7 @@ export class LGraphNode initializeWidgetsView(this) this._state = createNodeShellState(title, type, this.title_mode) this._inputs = createInputSlotView(this, this._state.inputs) - this._outputs = this._state.outputs + this._outputs = createOutputSlotView(this, this._state.outputs) for (const property of [ 'inputs', 'outputs', @@ -1094,6 +1097,7 @@ export class LGraphNode this.inputs = this.inputs.map((input) => toClass(NodeInputSlot, input, this) ) + this._slotsDirty = true for (const [i, input] of this.inputs.entries()) { const serialisedLink = info.inputs?.[i]?.link const link = @@ -1886,6 +1890,7 @@ export class LGraphNode this.outputs ||= [] this.outputs.push(output) + this._slotsDirty = true const added = this.outputs.at(-1) as NodeOutputSlot & TProperties this.onOutputAdded?.(added) @@ -1907,6 +1912,7 @@ export class LGraphNode } const { outputs } = this outputs.splice(slot, 1) + this._slotsDirty = true // Only update link indices if node is part of a graph. Ascending order: // each decrement re-keys the link to an already-processed slot index. @@ -1953,6 +1959,7 @@ export class LGraphNode this.inputs ||= [] this.inputs.push(input) + this._slotsDirty = true const added = this.inputs.at(-1) as NodeInputSlot & TProperties this.expandToFitContent() @@ -1991,6 +1998,7 @@ export class LGraphNode } else { inputs.splice(slot, 1) } + this._slotsDirty = true this.onInputRemoved?.(slot, slotInfo) this.setDirtyCanvas(true, true) } @@ -4300,33 +4308,36 @@ export class LGraphNode ctx: CanvasRenderingContext2D, { fromSlot, colorContext, editorAlpha, lowQuality }: DrawSlotsOptions ) { - for (const slot of [...this._concreteInputs, ...this._concreteOutputs]) { - const isValidTarget = fromSlot && slot.isValidTarget(fromSlot) - const isMouseOverSlot = this._isMouseOverSlot(slot) - - // change opacity of incompatible slots when dragging a connection - const isValid = !fromSlot || isValidTarget - const highlight = isValid && isMouseOverSlot - - // Show slot if it's not a widget input slot - // or if it's a widget input slot and satisfies one of the following: - // - the mouse is over the widget - // - the slot is valid during link drop - // - the slot is connected - if ( - isMouseOverSlot || - isValidTarget || - !slot.isWidgetInputSlot || - this._isMouseOverWidget(this.getWidgetFromSlot(slot)) || - slot.isConnected || - slot.alwaysVisible - ) { - ctx.globalAlpha = isValid ? editorAlpha : 0.4 * editorAlpha - slot.draw(ctx, { - colorContext, - lowQuality, - highlight - }) + for (const slots of [this._concreteInputs, this._concreteOutputs]) { + for (let s = 0; s < slots.length; s++) { + const slot = slots[s] + const isValidTarget = fromSlot && slot.isValidTarget(fromSlot) + const isMouseOverSlot = this._isMouseOverSlot(slot) + + // change opacity of incompatible slots when dragging a connection + const isValid = !fromSlot || isValidTarget + const highlight = isValid && isMouseOverSlot + + // Show slot if it's not a widget input slot + // or if it's a widget input slot and satisfies one of the following: + // - the mouse is over the widget + // - the slot is valid during link drop + // - the slot is connected + if ( + isMouseOverSlot || + isValidTarget || + !slot.isWidgetInputSlot || + this._isMouseOverWidget(this.getWidgetFromSlot(slot)) || + slot.isConnected || + slot.alwaysVisible + ) { + ctx.globalAlpha = isValid ? editorAlpha : 0.4 * editorAlpha + slot.draw(ctx, { + colorContext, + lowQuality, + highlight + }) + } } } } @@ -4458,6 +4469,8 @@ export class LGraphNode * invalidate slot-array subscribers. */ _setConcreteSlots(): void { + if (!this._slotsDirty) return + const { inputs, outputs } = this this._concreteInputs = inputs.map((slot, i) => { const concrete = toClass(NodeInputSlot, slot, this) @@ -4469,6 +4482,7 @@ export class LGraphNode if (concrete !== slot) outputs[i] = concrete return concrete }) + this._slotsDirty = false } /** diff --git a/src/lib/litegraph/src/LLink.test.ts b/src/lib/litegraph/src/LLink.test.ts index 2dc8b382e78..86a45062abb 100644 --- a/src/lib/litegraph/src/LLink.test.ts +++ b/src/lib/litegraph/src/LLink.test.ts @@ -3,6 +3,7 @@ import { describe, expect } from 'vitest' import { LLink } from '@/lib/litegraph/src/litegraph' import { toLinkId } from '@/types/linkId' import { toNodeId } from '@/types/nodeId' +import { toRerouteId } from '@/types/rerouteId' import { test } from './__fixtures__/testExtensions' @@ -35,4 +36,20 @@ describe('LLink', () => { type: 'INT' }) }) + + describe('getReroutes', () => { + test('returns the same empty array for missing reroutes', () => { + const network = { reroutes: new Map() } + const link1 = new LLink(toLinkId(1), 'float', 4, 2, 5, 3) + const link2 = new LLink(toLinkId(2), 'float', 4, 2, 5, 3) + link2.parentId = toRerouteId(999) + + const result1 = LLink.getReroutes(network, link1) + const result2 = LLink.getReroutes(network, link2) + + expect(result1).toHaveLength(0) + expect(result1).toBe(result2) + expect(Object.isFrozen(result1)).toBe(true) + }) + }) }) diff --git a/src/lib/litegraph/src/LLink.ts b/src/lib/litegraph/src/LLink.ts index 23d360de302..062dc7ee46e 100644 --- a/src/lib/litegraph/src/LLink.ts +++ b/src/lib/litegraph/src/LLink.ts @@ -35,6 +35,8 @@ import type { Serialisable, SerialisableLLink } from './types/serialisation' import { toRaw } from 'vue' export type { LinkId } from '@/types/linkId' + +const EMPTY_REROUTES: readonly Reroute[] = Object.freeze([]) export type SerialisedLLinkArray = [ id: number, origin_id: SerializedNodeId, @@ -325,9 +327,12 @@ export class LLink implements LinkSegment, Serialisable { static getReroutes( network: Pick, linkSegment: LinkSegment - ): Reroute[] { - if (linkSegment.parentId === undefined) return [] - return network.reroutes.get(linkSegment.parentId)?.getReroutes() ?? [] + ): readonly Reroute[] { + if (linkSegment.parentId === undefined) return EMPTY_REROUTES + return ( + network.reroutes.get(linkSegment.parentId)?.getReroutes() ?? + EMPTY_REROUTES + ) } static getFirstReroute( diff --git a/src/lib/litegraph/src/node/slotDescriptorView.ts b/src/lib/litegraph/src/node/slotDescriptorView.ts index af519cd9f37..0657e9c71a9 100644 --- a/src/lib/litegraph/src/node/slotDescriptorView.ts +++ b/src/lib/litegraph/src/node/slotDescriptorView.ts @@ -1,5 +1,8 @@ import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' -import type { INodeInputSlot } from '@/lib/litegraph/src/interfaces' +import type { + INodeInputSlot, + INodeOutputSlot +} from '@/lib/litegraph/src/interfaces' import { NodeInputSlot } from '@/lib/litegraph/src/node/NodeInputSlot' import { toClass } from '@/lib/litegraph/src/utils/type' @@ -13,21 +16,47 @@ export function createInputSlotView( inputs: INodeInputSlot[] ): INodeInputSlot[] { const assignedViews = new WeakMap() - const view = new Proxy(inputs, { - set(target, property, value: unknown, receiver) { - const input = - isArrayIndex(property) && isInputSlot(value) - ? toClass(NodeInputSlot, value, node) - : value - if (isInputSlot(value) && isInputSlot(input) && value !== input) - assignedViews.set(value, input) - return Reflect.set(target, property, input, receiver) - } + const view = createSlotView(node, inputs, (value) => { + const input = isInputSlot(value) + ? toClass(NodeInputSlot, value, node) + : value + if (isInputSlot(value) && isInputSlot(input) && value !== input) + assignedViews.set(value, input) + return input }) assignedInputViews.set(view, assignedViews) return view } +export function createOutputSlotView( + node: LGraphNode, + outputs: INodeOutputSlot[] +): INodeOutputSlot[] { + return createSlotView(node, outputs) +} + +function createSlotView( + node: LGraphNode, + slots: T[], + normalize: (value: unknown) => unknown = (value) => value +): T[] { + return new Proxy(slots, { + set(target, property, value: unknown, receiver) { + const nextValue = isArrayIndex(property) ? normalize(value) : value + const changed = Reflect.get(target, property) !== nextValue + const updated = Reflect.set(target, property, nextValue, receiver) + if (updated && changed) node._slotsDirty = true + return updated + }, + deleteProperty(target, property) { + const changed = Reflect.has(target, property) + const updated = Reflect.deleteProperty(target, property) + if (updated && changed) node._slotsDirty = true + return updated + } + }) +} + export function resolveInputSlotView( inputs: INodeInputSlot[], input: INodeInputSlot