Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- ComfyUI-KJNodes/__pycache__/__init__.cpython-310.pycAdded
- ComfyUI-KJNodes/nodes/__pycache__/nodes.cpython-310.pycAdded
- ComfyUI-KJNodes/nodes/__pycache__/sharpen_nodes.cpython-310.pycAdded
- ComfyUI-KJNodes/utility/__pycache__/utility.cpython-310.pycAdded
- ComfyUI-KJNodes/utility/fluid.pyAdded+67
- ComfyUI-KJNodes/utility/magictex.pyAdded+95
- ComfyUI-KJNodes/utility/numerical.pyAdded+25
- ComfyUI-KJNodes/utility/utility.pyAdded+88
- ComfyUI-KJNodes/web/js/appearance.jsAdded+23
- ComfyUI-KJNodes/web/js/canvas_background.jsAdded+476
- ComfyUI-KJNodes/web/js/contextmenu.jsAdded+256
- ComfyUI-KJNodes/web/js/editors/editor_base.jsAdded+707
- ComfyUI-KJNodes/web/js/editors/interpolation.jsAdded+211
- ComfyUI-KJNodes/web/js/editors/point_editor_canvas.jsAdded+370
- ComfyUI-KJNodes/web/js/editors/spline_editor_canvas.jsAdded+708
- ComfyUI-KJNodes/web/js/fast_preview.jsAdded+31
- ComfyUI-KJNodes/web/js/fillconnect.jsAdded+218
- ComfyUI-KJNodes/web/js/help_popup.jsAdded+468
- ComfyUI-KJNodes/web/js/jsnodes.jsAdded+402
- ComfyUI-KJNodes/web/js/nodeswap.jsAdded+404
- ComfyUI-KJNodes/web/js/performance.jsAdded+286
- ComfyUI-KJNodes/web/js/play_sound.jsAdded+94
- ComfyUI-KJNodes/web/js/screencap_stream.jsAdded+500
- ComfyUI-KJNodes/web/js/setgetnodes.jsAdded+1544
- ComfyUI-KJNodes/web/js/utility.jsAdded+230
- ComfyUI-LatentSyncWrapper/.github/ISSUE_TEMPLATE/bug_report.mdAdded+38
- ComfyUI-LatentSyncWrapper/.github/workflows/issue-template.ymlAdded+22
- ComfyUI-LatentSyncWrapper/.github/workflows/publish.ymlAdded+26
- ComfyUI-LatentSyncWrapper/.gitignoreAdded+173
- ComfyUI-LatentSyncWrapper/README.mdAdded+193
- ComfyUI-LatentSyncWrapper/__init__.pyAdded+3
- ComfyUI-LatentSyncWrapper/__pycache__/__init__.cpython-310.pycAdded
- ComfyUI-LatentSyncWrapper/__pycache__/nodes.cpython-310.pycAdded
- ComfyUI-LatentSyncWrapper/checkpoints/put checkpoints hereAdded
- ComfyUI-LatentSyncWrapper/configs/audio.yamlAdded+23
- ComfyUI-LatentSyncWrapper/configs/scheduler_config.jsonAdded+12
- ComfyUI-LatentSyncWrapper/configs/syncnet/syncnet_16_latent.yamlAdded+46
- ComfyUI-LatentSyncWrapper/configs/syncnet/syncnet_16_pixel.yamlAdded+46
- ComfyUI-LatentSyncWrapper/configs/syncnet/syncnet_16_pixel_attn.yamlAdded+46
- ComfyUI-LatentSyncWrapper/configs/syncnet/syncnet_25_pixel.yamlAdded+44
- ComfyUI-LatentSyncWrapper/configs/unet/stage1.yamlAdded+96
- ComfyUI-LatentSyncWrapper/configs/unet/stage1_512.yamlAdded+96
- ComfyUI-LatentSyncWrapper/configs/unet/stage2.yamlAdded+99
- ComfyUI-LatentSyncWrapper/configs/unet/stage2_512.yamlAdded+99
- ComfyUI-LatentSyncWrapper/configs/unet/stage2_efficient.yamlAdded+99
- ComfyUI-LatentSyncWrapper/eval/detectors/README.mdAdded+3
- ComfyUI-LatentSyncWrapper/eval/detectors/__init__.pyAdded+1
- ComfyUI-LatentSyncWrapper/eval/detectors/s3fd/__init__.pyAdded+63
- ComfyUI-LatentSyncWrapper/eval/detectors/s3fd/box_utils.pyAdded+221
- ComfyUI-LatentSyncWrapper/eval/detectors/s3fd/nets.pyAdded+174
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import numpy as np
from scipy.ndimage import map_coordinates, spline_filter
from scipy.sparse.linalg import factorized
from .numerical import difference, operator
class Fluid:
def __init__(self, shape, *quantities, pressure_order=1, advect_order=3):
self.shape = shape
self.dimensions = len(shape)
# Prototyping is simplified by dynamically
# creating advected quantities as needed.
self.quantities = quantities
for q in quantities:
setattr(self, q, np.zeros(shape))
self.indices = np.indices(shape)
self.velocity = np.zeros((self.dimensions, *shape))
laplacian = operator(shape, difference(2, pressure_order))
self.pressure_solver = factorized(laplacian)
self.advect_order = advect_order
def step(self):
# Advection is computed backwards in time as described in Stable Fluids.
advection_map = self.indices - self.velocity
# SciPy's spline filter introduces checkerboard divergence.
# A linear blend of the filtered and unfiltered fields based
# on some value epsilon eliminates this error.
def advect(field, filter_epsilon=10e-2, mode='constant'):
filtered = spline_filter(field, order=self.advect_order, mode=mode)
field = filtered * (1 - filter_epsilon) + field * filter_epsilon
return map_coordinates(field, advection_map, prefilter=False, order=self.advect_order, mode=mode)
# Apply advection to each axis of the
# velocity field and each user-defined quantity.
for d in range(self.dimensions):
self.velocity[d] = advect(self.velocity[d])
for q in self.quantities:
setattr(self, q, advect(getattr(self, q)))
# Compute the jacobian at each point in the
# velocity field to extract curl and divergence.
jacobian_shape = (self.dimensions,) * 2
partials = tuple(np.gradient(d) for d in self.velocity)
jacobian = np.stack(partials).reshape(*jacobian_shape, *self.shape)
divergence = jacobian.trace()
# If this curl calculation is extended to 3D, the y-axis value must be negated.
# This corresponds to the coefficients of the levi-civita symbol in that dimension.
# Higher dimensions do not have a vector -> scalar, or vector -> vector,
# correspondence between velocity and curl due to differing isomorphisms
# between exterior powers in dimensions != 2 or 3 respectively.
curl_mask = np.triu(np.ones(jacobian_shape, dtype=bool), k=1)
curl = (jacobian[curl_mask] - jacobian[curl_mask.T]).squeeze()
# Apply the pressure correction to the fluid's velocity field.
pressure = self.pressure_solver(divergence.flatten()).reshape(self.shape)
self.velocity -= np.gradient(pressure)
return divergence, curl, pressure1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495"""Generates psychedelic color textures in the spirit of Blender's magic texture shader using Python/Numpy
https://github.com/cheind/magic-texture
"""
from typing import Tuple, Optional
import numpy as np
def coordinate_grid(shape: Tuple[int, int], dtype=np.float32):
"""Returns a three-dimensional coordinate grid of given shape for use in `magic`."""
x = np.linspace(-1, 1, shape[1], endpoint=True, dtype=dtype)
y = np.linspace(-1, 1, shape[0], endpoint=True, dtype=dtype)
X, Y = np.meshgrid(x, y)
XYZ = np.stack((X, Y, np.ones_like(X)), -1)
return XYZ
def random_transform(coords: np.ndarray, rng: np.random.Generator = None):
"""Returns randomly transformed coordinates"""
H, W = coords.shape[:2]
rng = rng or np.random.default_rng()
m = rng.uniform(-1.0, 1.0, size=(3, 3)).astype(coords.dtype)
return (coords.reshape(-1, 3) @ m.T).reshape(H, W, 3)
def magic(
coords: np.ndarray,
depth: Optional[int] = None,
distortion: Optional[int] = None,
rng: np.random.Generator = None,
):
"""Returns color magic color texture.
The implementation is based on Blender's (https://www.blender.org/) magic
texture shader. The following adaptions have been made:
- we exchange the nested if-cascade by a probabilistic iterative approach
Kwargs
------
coords: HxWx3 array
Coordinates transformed into colors by this method. See
`magictex.coordinate_grid` to generate the default.
depth: int (optional)
Number of transformations applied. Higher numbers lead to more
nested patterns. If not specified, randomly sampled.
distortion: float (optional)
Distortion of patterns. Larger values indicate more distortion,
lower values tend to generate smoother patterns. If not specified,
randomly sampled.
rng: np.random.Generator
Optional random generator to draw samples from.
Returns
-------
colors: HxWx3 array
Three channel color image in range [0,1]
"""
rng = rng or np.random.default_rng()
if distortion is None:
distortion = rng.uniform(1, 4)
if depth is None:
depth = rng.integers(1, 5)
H, W = coords.shape[:2]
XYZ = coords
x = np.sin((XYZ[..., 0] + XYZ[..., 1] + XYZ[..., 2]) * distortion)
y = np.cos((-XYZ[..., 0] + XYZ[..., 1] - XYZ[..., 2]) * distortion)
z = -np.cos((-XYZ[..., 0] - XYZ[..., 1] + XYZ[..., 2]) * distortion)
if depth > 0:
x *= distortion
y *= distortion
z *= distortion
y = -np.cos(x - y + z)
y *= distortion
xyz = [x, y, z]
fns = [np.cos, np.sin]
for _ in range(1, depth):
axis = rng.choice(3)
fn = fns[rng.choice(2)]
signs = rng.binomial(n=1, p=0.5, size=4) * 2 - 1
xyz[axis] = signs[-1] * fn(
signs[0] * xyz[0] + signs[1] * xyz[1] + signs[2] * xyz[2]
)
xyz[axis] *= distortion
x, y, z = xyz
x /= 2 * distortion
y /= 2 * distortion
z /= 2 * distortion
c = 0.5 - np.stack((x, y, z), -1)
np.clip(c, 0, 1.0)
return c12345678910111213141516171819202122232425from functools import reduce
from itertools import cycle
from math import factorial
import numpy as np
import scipy.sparse as sp
def difference(derivative, accuracy=1):
# Central differences implemented based on the article here:
# http://web.media.mit.edu/~crtaylor/calculator.html
derivative += 1
radius = accuracy + derivative // 2 - 1
points = range(-radius, radius + 1)
coefficients = np.linalg.inv(np.vander(points))
return coefficients[-derivative] * factorial(derivative - 1), points
def operator(shape, *differences):
# Credit to Philip Zucker for figuring out
# that kronsum's argument order is reversed.
# Without that bit of wisdom I'd have lost it.
differences = zip(shape, cycle(differences))
factors = (sp.diags(*diff, shape=(dim,) * 2) for dim, diff in differences)
return reduce(lambda a, f: sp.kronsum(f, a, format='csc'), factors)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788import torch
import numpy as np
from PIL import Image, ImageColor
from typing import Union, List
import logging
# Utility functions from mtb nodes: https://github.com/melMass/comfy_mtb
def pil2tensor(image: Union[Image.Image, List[Image.Image]]) -> torch.Tensor:
if isinstance(image, list):
return torch.cat([pil2tensor(img) for img in image], dim=0)
return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
def np2tensor(img_np: Union[np.ndarray, List[np.ndarray]]) -> torch.Tensor:
if isinstance(img_np, list):
return torch.cat([np2tensor(img) for img in img_np], dim=0)
return torch.from_numpy(img_np.astype(np.float32) / 255.0).unsqueeze(0)
def tensor2np(tensor: torch.Tensor):
if len(tensor.shape) == 3: # Single image
return np.clip(255.0 * tensor.cpu().numpy(), 0, 255).astype(np.uint8)
else: # Batch of images
return [np.clip(255.0 * t.cpu().numpy(), 0, 255).astype(np.uint8) for t in tensor]
def tensor2pil(image: torch.Tensor) -> List[Image.Image]:
batch_count = image.size(0) if len(image.shape) > 3 else 1
if batch_count > 1:
out = []
for i in range(batch_count):
out.extend(tensor2pil(image[i]))
return out
return [
Image.fromarray(
np.clip(255.0 * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)
)
]
def string_to_color(color_string: str) -> List[int]:
color_list = [0, 0, 0] # Default fallback (black)
if ',' in color_string:
# Handle CSV format (e.g., "255, 0, 0" or "255, 0, 0, 128" or "1.0, 0.5, 0.0")
try:
values = [float(channel.strip()) for channel in color_string.split(',')]
# Convert to 0-255 range if values are in 0-1 range
if all(0 <= v <= 1 for v in values):
color_list = [int(v * 255) for v in values]
else:
color_list = [int(v) for v in values]
except ValueError:
logging.warning(f"Invalid color format: {color_string}. Using default black.")
elif color_string.startswith('#') or (color_string.lstrip('#').isalnum() and not color_string.lstrip('#').replace('.', '', 1).isdigit()):
# Could be Hex format or color name
color_string_stripped = color_string.lstrip('#')
# Try hex first
if len(color_string_stripped) in [6, 8] and all(c in '0123456789ABCDEFabcdef' for c in color_string_stripped):
if len(color_string_stripped) == 6: # #RRGGBB
color_list = [int(color_string_stripped[i:i+2], 16) for i in (0, 2, 4)]
elif len(color_string_stripped) == 8: # #RRGGBBAA
color_list = [int(color_string_stripped[i:i+2], 16) for i in (0, 2, 4, 6)]
else:
# Try color name (e.g., "red", "blue", "cyan")
try:
rgb = ImageColor.getrgb(color_string)
color_list = list(rgb)
except ValueError:
logging.warning(f"Invalid color name or hex format: {color_string}. Using default black.")
else:
# Handle single value (grayscale) - can be int or float
try:
value = float(color_string.strip())
# Convert to 0-255 range if it's a float between 0-1
if 0 <= value <= 1:
value = int(value * 255)
else:
value = int(value)
color_list = [value, value, value]
except ValueError:
logging.warning(f"Invalid color format: {color_string}. Using default black.")
# Clip values to valid range
color_list = np.clip(color_list, 0, 255).tolist()
return color_list1234567891011121314151617181920212223const { app } = window.comfyAPI.app;
app.registerExtension({
name: "KJNodes.appearance",
nodeCreated(node) {
switch (node.comfyClass) {
case "INTConstant":
node.setSize([200, 58]);
node.color = "#1b4669";
node.bgcolor = "#29699c";
break;
case "FloatConstant":
node.setSize([200, 58]);
node.color = LGraphCanvas.node_colors.green.color;
node.bgcolor = LGraphCanvas.node_colors.green.bgcolor;
break;
case "ConditioningMultiCombine":
node.color = LGraphCanvas.node_colors.brown.color;
node.bgcolor = LGraphCanvas.node_colors.brown.bgcolor;
break;
}
}
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476const { app } = window.comfyAPI.app;
// ── Helpers ─────────────────────────────────────────────────────────────────
/** Linearly mix two hex colors: 0 = pure a, 1 = pure b. */
function mixColors(a, b, t) {
const parse = (hex) => {
if (hex.length === 4) hex = `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}`;
return [parseInt(hex.slice(1, 3), 16), parseInt(hex.slice(3, 5), 16), parseInt(hex.slice(5, 7), 16)];
};
const ca = parse(a), cb = parse(b);
const r = Math.round(ca[0] + (cb[0] - ca[0]) * t);
const g = Math.round(ca[1] + (cb[1] - ca[1]) * t);
const bl = Math.round(ca[2] + (cb[2] - ca[2]) * t);
return `#${((1 << 24) | (r << 16) | (g << 8) | bl).toString(16).slice(1)}`;
}
/** Ensure a color string has a leading '#' (PrimeVue ColorPicker omits it). */
function asHex(color, fallback = "#000000") {
if (!color) return fallback;
return color.startsWith("#") ? color : `#${color}`;
}
function getSetting(id, fallback) {
return app.ui.settings.getSettingValue(id) ?? fallback;
}
// ── Pattern generators ──────────────────────────────────────────────────────
// Each returns an OffscreenCanvas to be used with createPattern("repeat").
// `size` = tile size, `fg`/`bg` = hex colors, `t` = feature thickness.
function makeDots(size, fg, bg, t) {
const c = new OffscreenCanvas(size, size);
const ctx = c.getContext("2d");
ctx.fillStyle = bg;
ctx.fillRect(0, 0, size, size);
ctx.fillStyle = fg;
ctx.beginPath();
ctx.arc(size / 2, size / 2, t * 2, 0, Math.PI * 2);
ctx.fill();
return c;
}
function makeGrid(size, fg, bg, t) {
const c = new OffscreenCanvas(size, size);
const ctx = c.getContext("2d");
ctx.fillStyle = bg;
ctx.fillRect(0, 0, size, size);
ctx.fillStyle = fg;
ctx.fillRect(size - t, 0, t, size - t);
ctx.fillRect(0, size - t, size, t);
return c;
}
function makeCrossDots(size, fg, bg, t) {
const c = new OffscreenCanvas(size, size);
const ctx = c.getContext("2d");
ctx.fillStyle = bg;
ctx.fillRect(0, 0, size, size);
const half = size / 2;
const arm = Math.max(t + 1, size * 0.08);
const ht = t / 2;
ctx.fillStyle = fg;
ctx.fillRect(half - arm, half - ht, arm * 2, t);
ctx.fillRect(half - ht, half - arm, t, arm * 2);
return c;
}
function makeBlueprint(size, fg, bg, t) {
const c = new OffscreenCanvas(size, size);
const ctx = c.getContext("2d");
ctx.fillStyle = bg;
ctx.fillRect(0, 0, size, size);
const sub = size / 4;
const subColor = mixColors(bg, fg, 0.3);
ctx.fillStyle = subColor;
for (let i = sub; i < size; i += sub) {
ctx.fillRect(i, 0, t, size - t);
ctx.fillRect(0, i, size, t);
}
ctx.fillStyle = fg;
ctx.fillRect(size - t, 0, t, size - t);
ctx.fillRect(0, size - t, size, t);
return c;
}
function makeIsometric(size, fg, bg, t) {
const w = size;
const h = Math.round(size / 2);
const c = new OffscreenCanvas(w, h);
const ctx = c.getContext("2d");
ctx.fillStyle = bg;
ctx.fillRect(0, 0, w, h);
ctx.strokeStyle = fg;
ctx.lineWidth = t;
ctx.beginPath();
ctx.moveTo(0, h / 2);
ctx.lineTo(w / 2, 0);
ctx.lineTo(w, h / 2);
ctx.moveTo(0, h / 2);
ctx.lineTo(w / 2, h);
ctx.lineTo(w, h / 2);
ctx.stroke();
return c;
}
function makeHexagons(size, fg, bg, t) {
const r = size / 2;
const w = r * 3;
const h = Math.round(r * Math.sqrt(3));
const c = new OffscreenCanvas(w, h);
const ctx = c.getContext("2d");
ctx.fillStyle = bg;
ctx.fillRect(0, 0, w, h);
ctx.strokeStyle = fg;
ctx.lineWidth = t;
function hex(cx, cy) {
ctx.beginPath();
for (let i = 0; i < 6; i++) {
const a = Math.PI / 3 * i;
const px = cx + r * Math.cos(a);
const py = cy + r * Math.sin(a);
if (i === 0) ctx.moveTo(px, py);
else ctx.lineTo(px, py);
}
ctx.closePath();
ctx.stroke();
}
hex(r, h / 2);
hex(r * 2.5, 0);
hex(r * 2.5, h);
return c;
}
function makeOctagons(size, fg, bg, t) {
const c = new OffscreenCanvas(size, size);
const ctx = c.getContext("2d");
ctx.fillStyle = bg;
ctx.fillRect(0, 0, size, size);
ctx.strokeStyle = fg;
ctx.lineWidth = t;
const s = size / (1 + Math.SQRT2);
const d = (size - s) / 2;
ctx.beginPath();
ctx.moveTo(d, 0);
ctx.lineTo(size - d, 0);
ctx.lineTo(size, d);
ctx.lineTo(size, size - d);
ctx.lineTo(size - d, size);
ctx.lineTo(d, size);
ctx.lineTo(0, size - d);
ctx.lineTo(0, d);
ctx.closePath();
ctx.stroke();
return c;
}
function makeWaves(size, fg, bg, t) {
const c = new OffscreenCanvas(size, size);
const ctx = c.getContext("2d");
ctx.fillStyle = bg;
ctx.fillRect(0, 0, size, size);
ctx.lineWidth = t;
const lines = Math.max(2, Math.round(size / 20));
const spacing = size / lines;
for (let i = 0; i < lines; i++) {
const blend = 0.1 + (i % 3) * 0.07;
ctx.strokeStyle = mixColors(bg, fg, blend);
const baseY = spacing * i + spacing / 2;
const amp = spacing * (0.15 + (i % 4) * 0.05);
ctx.beginPath();
for (let x = 0; x <= size; x++) {
const y = baseY + Math.sin((x / size) * Math.PI * 2 + i * 0.8) * amp;
if (x === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
ctx.stroke();
}
return c;
}
function makeCarbonFiber(size, fg, bg, t) {
const cell = Math.max(2, Math.round(size / 4));
const s = cell * 4;
const c = new OffscreenCanvas(s, s);
const ctx = c.getContext("2d");
const dark = bg;
const light = mixColors(bg, fg, 0.2);
const groove = mixColors(bg, fg, 0.07);
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 4; col++) {
const phase = (col + row) % 4;
ctx.fillStyle = (phase < 2) ? light : dark;
ctx.fillRect(col * cell, row * cell, cell, cell);
}
}
ctx.fillStyle = groove;
const gt = Math.max(1, Math.round(t));
for (let i = 1; i < 4; i++) {
ctx.fillRect(0, i * cell, s, gt);
ctx.fillRect(i * cell, 0, gt, s);
}
return c;
}
const PATTERNS = {
default: null,
none: null,
dots: makeDots,
grid: makeGrid,
"cross dots": makeCrossDots,
blueprint: makeBlueprint,
isometric: makeIsometric,
hexagons: makeHexagons,
octagons: makeOctagons,
waves: makeWaves,
"carbon fiber": makeCarbonFiber,
};
// ── State ───────────────────────────────────────────────────────────────────
let currentType = "default";
let currentFg = "#444444";
let currentBg = "#212121";
let currentSize = 32;
let currentThickness = 2;
let dirty = true;
function invalidateCache() {
dirty = true;
app.canvas?.setDirty(true, true);
}
function readSettings() {
currentType = getSetting("KJNodes.canvasBg.pattern", "default");
currentFg = asHex(getSetting("KJNodes.canvasBg.patternColor", "#444444"));
currentBg = asHex(getSetting("KJNodes.canvasBg.bgColor", "#212121"));
currentSize = getSetting("KJNodes.canvasBg.scale", 32);
currentThickness = getSetting("KJNodes.canvasBg.thickness", 2);
}
// ── Commands ────────────────────────────────────────────────────────────────
const patternCommands = Object.keys(PATTERNS).map((key) => ({
id: `KJNodes.canvasBg.setPattern.${key}`,
label: key.charAt(0).toUpperCase() + key.slice(1),
menubarLabel: key.charAt(0).toUpperCase() + key.slice(1),
function: () => {
app.ui.settings.setSettingValue("KJNodes.canvasBg.pattern", key);
},
active: () => getSetting("KJNodes.canvasBg.pattern", "default") === key,
}));
// Single source of truth for slider bounds — commands reference these same objects.
const SCALE_ATTRS = { min: 8, max: 512, step: 4 };
const THICKNESS_ATTRS = { min: 0.5, max: 20, step: 0.5 };
function stepSetting(id, fallback, attrs, direction) {
const cur = getSetting(id, fallback);
const next = cur + attrs.step * direction;
if (next >= attrs.min && next <= attrs.max) {
app.ui.settings.setSettingValue(id, next);
}
}
const scaleCommands = [
{
id: "KJNodes.canvasBg.increaseScale",
label: "Increase pattern scale",
menubarLabel: "Increase scale",
function: () => stepSetting("KJNodes.canvasBg.scale", 32, SCALE_ATTRS, 1),
active: () => false,
},
{
id: "KJNodes.canvasBg.decreaseScale",
label: "Decrease pattern scale",
menubarLabel: "Decrease scale",
function: () => stepSetting("KJNodes.canvasBg.scale", 32, SCALE_ATTRS, -1),
active: () => false,
},
];
const thicknessCommands = [
{
id: "KJNodes.canvasBg.increaseThickness",
label: "Increase pattern thickness",
menubarLabel: "Increase thickness",
function: () => stepSetting("KJNodes.canvasBg.thickness", 2, THICKNESS_ATTRS, 1),
active: () => false,
},
{
id: "KJNodes.canvasBg.decreaseThickness",
label: "Decrease pattern thickness",
menubarLabel: "Decrease thickness",
function: () => stepSetting("KJNodes.canvasBg.thickness", 2, THICKNESS_ATTRS, -1),
active: () => false,
},
];
// ── Extension ───────────────────────────────────────────────────────────────
app.registerExtension({
name: "KJNodes.CanvasBackground",
commands: [...patternCommands, ...scaleCommands, ...thicknessCommands],
menuCommands: [
{
path: ["KJNodes", "Canvas Background"],
commands: patternCommands.map((c) => c.id),
},
{
path: ["KJNodes", "Canvas Background"],
commands: scaleCommands.map((c) => c.id),
},
{
path: ["KJNodes", "Canvas Background"],
commands: thicknessCommands.map((c) => c.id),
},
],
settings: [
{
id: "KJNodes.canvasBg.pattern",
name: "Background pattern",
category: ["KJNodes", "Canvas Background", "Pattern"],
tooltip: "Choose a background pattern for the node graph canvas. 'default' uses LiteGraph's built-in dot grid. 'none' disables all background drawing.",
type: "combo",
defaultValue: "default",
options: Object.keys(PATTERNS),
onChange: invalidateCache,
},
{
id: "KJNodes.canvasBg.patternColor",
name: "Pattern color",
category: ["KJNodes", "Canvas Background", "Pattern color"],
tooltip: "Foreground color of the pattern",
type: "color",
defaultValue: "#444444",
onChange: invalidateCache,
},
{
id: "KJNodes.canvasBg.bgColor",
name: "Background color",
category: ["KJNodes", "Canvas Background", "Background color"],
tooltip: "Background fill color behind the pattern",
type: "color",
defaultValue: "#212121",
onChange: invalidateCache,
},
{
id: "KJNodes.canvasBg.scale",
name: "Pattern scale",
category: ["KJNodes", "Canvas Background", "Pattern scale"],
tooltip: "Size of one pattern tile in pixels",
type: "slider",
defaultValue: 32,
attrs: SCALE_ATTRS,
onChange: invalidateCache,
},
{
id: "KJNodes.canvasBg.thickness",
name: "Pattern thickness",
category: ["KJNodes", "Canvas Background", "Pattern thickness"],
tooltip: "Thickness of lines and size of dots in pixels",
type: "slider",
defaultValue: 2,
attrs: THICKNESS_ATTRS,
onChange: invalidateCache,
},
],
setup() {
const canvas = app.canvas;
if (!canvas) return;
let patternToken = null; // null = default, "" = none, string = custom
// Snapshot palette values lazily on first override so we capture post-palette state
let origBackgroundImage = null;
let origClearBgColor = null;
let origsCaptured = false;
function captureOriginals() {
if (origsCaptured) return;
origsCaptured = true;
origBackgroundImage = canvas.background_image;
origClearBgColor = canvas.clear_background_color;
}
function applyToLiteGraph() {
if (!dirty) return;
dirty = false;
readSettings();
// If ComfyUI's own background image setting is active, don't interfere
if (getSetting("Comfy.Canvas.BackgroundImage", "")) {
patternToken = null;
return;
}
if (currentType === "default") {
if (origsCaptured) {
canvas.background_image = origBackgroundImage;
canvas.clear_background_color = origClearBgColor;
canvas._pattern = undefined;
canvas._bg_img = undefined;
}
patternToken = null;
canvas.setDirty(true, true);
return;
}
// Capture originals before we overwrite them for the first time
captureOriginals();
if (currentType === "none") {
canvas.background_image = "";
canvas.clear_background_color = currentBg;
canvas._pattern = undefined;
canvas._bg_img = undefined;
patternToken = "";
canvas.setDirty(true, true);
return;
}
// Generate tile as OffscreenCanvas — passed directly to LiteGraph's
// createPattern which accepts any CanvasImageSource.
const gen = PATTERNS[currentType];
if (!gen) return;
const tile = gen(currentSize, currentFg, currentBg, currentThickness);
patternToken = `kjbg_${currentType}_${currentSize}_${currentThickness}_${currentFg}_${currentBg}`;
tile.name = patternToken;
canvas.background_image = patternToken;
canvas.clear_background_color = currentBg;
canvas._bg_img = tile;
canvas._pattern = undefined;
canvas.setDirty(true, true);
}
applyToLiteGraph();
// Enforce our values if palette service overwrites them.
// Returns false — LiteGraph's native code does all drawing.
const origCallback = canvas.onRenderBackground;
canvas.onRenderBackground = function (cvs, ctx) {
if (origCallback) {
const result = origCallback.call(this, cvs, ctx);
if (result) return true;
}
applyToLiteGraph();
// If palette service overwrote our values, mark dirty for next frame.
if (!dirty && patternToken !== null && this.background_image !== patternToken) {
dirty = true;
}
return false;
};
},
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256const { app } = window.comfyAPI.app;
function addNode(name, nextTo, options) {
options = { side: "left", select: true, shiftY: 0, shiftX: 0, ...(options || {}) };
const node = LiteGraph.createNode(name);
const graph = app.canvas?.graph || app.graph;
graph.add(node);
node.pos = [
options.side === "left" ? nextTo.pos[0] - (node.size[0] + options.offset): nextTo.pos[0] + nextTo.size[0] + options.offset,
nextTo.pos[1] + options.shiftY,
];
// Automatically connect nodes
if (options.side === "left") {
// New node on left: connect new node's first output to nextTo's first free input
if (node.outputs && node.outputs.length > 0 && nextTo.inputs && nextTo.inputs.length > 0) {
for (let i = 0; i < nextTo.inputs.length; i++) {
if (!nextTo.inputs[i].link) {
node.pos[1] += i * (node.size[1] + 32);
node.connect(0, nextTo, i);
break;
}
}
}
} else {
// New node on right: connect nextTo's first free output to new node's first free input
if (nextTo.outputs && nextTo.outputs.length > 0 && node.inputs && node.inputs.length > 0) {
for (let o = 0; o < nextTo.outputs.length; o++) {
if (!nextTo.outputs[o].links || nextTo.outputs[o].links.length === 0) {
// Offset vertically by slot index so multiple Set nodes don't overlap
node.pos[1] += o * (node.size[1] + 32);
for (let i = 0; i < node.inputs.length; i++) {
if (!node.inputs[i].link) {
nextTo.connect(o, node, i);
break;
}
}
break;
}
}
}
}
if (options.select) {
app.canvas.selectNode(node, false);
}
return node;
}
// Expose addNode for use in setgetnodes.js
window.kjNodes = window.kjNodes || {};
window.kjNodes.addNode = addNode;
app.registerExtension({
name: "KJNodes.Contextmenu",
settings: [
{
id: "KJNodes.nodeAutoColor",
name: "Auto-color nodes",
category: ["KJNodes", "Set & Get", "Auto-color nodes"],
tooltip: "Automatically color Set/Get nodes based on their connection type",
type: "boolean",
defaultValue: true,
},
{
id: "KJNodes.disablePrefix",
name: "Disable Set_/Get_ prefix",
category: ["KJNodes", "Set & Get", "Disable Set_/Get_ prefix"],
tooltip: "Prevents automatically adding Set_ and Get_ prefixes to node titles",
defaultValue: false,
type: "boolean",
},
{
id: "KJNodes.helpPopup",
name: "Help popups",
category: ["KJNodes", "General", "Help popups"],
tooltip: "Show help popups when hovering over KJNodes",
defaultValue: true,
type: "boolean",
},
{
id: "KJNodes.shiftMiddleClickSetGet",
name: "Shift+middle-click creates Set/Get",
category: ["KJNodes", "Set & Get", "Shift+middle-click creates Set/Get"],
tooltip: "Shift+middle-click on a slot creates a connected SetNode (output) or GetNode (input) instead of Reroute",
type: "boolean",
defaultValue: true,
},
{
id: "KJNodes.middleClickSetGet",
name: "Middle-click creates Set/Get",
category: ["KJNodes", "Set & Get", "Middle-click creates Set/Get"],
tooltip: "Middle-click on a slot creates Set/Get instead of Reroute (overrides core behavior)",
type: "boolean",
defaultValue: false,
},
{
id: "KJNodes.showSetGetInConnectionMenu",
name: "Show Set/Get in connection menu",
category: ["KJNodes", "Set & Get", "Show Set/Get in connection menu"],
tooltip: "Add Set/Get entries to the slot connection menu (next to Add Reroute)",
type: "boolean",
defaultValue: true,
},
],
getNodeMenuItems(node) {
if (!node.inputs || node.inputs.length === 0) return [];
const selectedForConvert = window.kjNodes.snapshotSelectedNodes(node);
return [
{
content: "Add GetNode",
callback: () => { addNode("GetNode", node, { side: "left", offset: 30 }); }
},
{
content: "Add SetNode",
callback: () => { addNode("SetNode", node, { side: "right", offset: 30 }); }
},
{
content: "Add PreviewAsTextNode",
callback: () => { addNode("PreviewAny", node, { side: "right", offset: 30 }); }
},
{
content: "Convert all outputs to Set/Get",
callback: () => {
for (const n of selectedForConvert) window.kjNodes.convertOutputsToSetGet(node.graph, n);
}
},
];
},
async setup(app) {
// Patch showConnectionMenu to inject "Add SetNode" / "Add GetNode" entries.
const origShowConnectionMenu = app.canvas.showConnectionMenu.bind(app.canvas);
app.canvas.showConnectionMenu = function(optPass) {
if (!(app.ui.settings.getSettingValue("KJNodes.showSetGetInConnectionMenu") ?? true)) return origShowConnectionMenu(optPass);
const isFrom = optPass.nodeFrom && optPass.slotFrom;
const nodeType = isFrom ? "SetNode" : "GetNode";
const label = isFrom ? "Add SetNode" : "Add GetNode";
// Capture original canvas position from the event
const origEvent = optPass.e;
const OrigCM = LiteGraph.ContextMenu;
let interceptActive = true;
LiteGraph.ContextMenu = function(options, menuOpts) {
// Always restore before doing anything else
LiteGraph.ContextMenu = OrigCM;
// If another caller triggered this, pass through untouched
if (!interceptActive) return new OrigCM(options, menuOpts);
interceptActive = false;
// Insert after "Add Reroute"
const idx = options.indexOf("Add Reroute");
if (idx !== -1) options.splice(idx + 1, 0, label);
// Wrap callback to handle our entry
const origCb = menuOpts.callback;
menuOpts.callback = function(v, cbOpts, e) {
if (v === label) {
const canvas = app.canvas;
const graph = canvas.graph || app.graph;
const node = LiteGraph.createNode(nodeType);
if (!node || !graph) return;
// Use the original drag event's canvas position
node.pos = [origEvent?.canvasX ?? 0, origEvent?.canvasY ?? 0];
graph.add(node);
if (isFrom && optPass.nodeFrom) {
const slotObj = optPass.slotFrom;
const slotIdx = typeof slotObj === 'number'
? slotObj
: optPass.nodeFrom.findOutputSlot(slotObj.name);
optPass.nodeFrom.connect(slotIdx, node, 0);
} else if (optPass.nodeTo) {
const slotObj = optPass.slotTo;
const slotIdx = typeof slotObj === 'number'
? slotObj
: optPass.nodeTo.findInputSlot(slotObj.name);
node.connect(0, optPass.nodeTo, slotIdx);
}
graph.change();
canvas.setDirty(true, true);
return;
}
return origCb?.call(this, v, cbOpts, e);
};
return new OrigCM(options, menuOpts);
};
LiteGraph.ContextMenu.prototype = OrigCM.prototype;
const result = origShowConnectionMenu(optPass);
// Safety: ensure restoration even if origShowConnectionMenu didn't trigger the constructor
LiteGraph.ContextMenu = OrigCM;
interceptActive = false;
return result;
};
// Middle-click Set/Get: let the core do slot hit detection, then intercept
// createDefaultNodeForSlot to create Set/Get instead of reroute.
let _fromMiddleClick = false;
let _lastMiddleClickShift = false;
const origProcessMiddle = LGraphCanvas.prototype._processMiddleButton;
LGraphCanvas.prototype._processMiddleButton = function(e, node) {
_fromMiddleClick = true;
_lastMiddleClickShift = !!e.shiftKey;
const wantSetGet = _lastMiddleClickShift
? app.ui.settings.getSettingValue("KJNodes.shiftMiddleClickSetGet") ?? true
: app.ui.settings.getSettingValue("KJNodes.middleClickSetGet") ?? false;
const saved = LiteGraph.middle_click_slot_add_default_node;
if (wantSetGet) {
LiteGraph.middle_click_slot_add_default_node = true;
} else {
// Workaround: core slotDefaults.init() resets this flag to true
const coreSetting = app.ui.settings.getSettingValue("Comfy.Node.MiddleClickRerouteNode");
if (coreSetting === false) LiteGraph.middle_click_slot_add_default_node = false;
}
const result = origProcessMiddle.call(this, e, node);
LiteGraph.middle_click_slot_add_default_node = saved;
return result;
};
const origCreateDefault = LGraphCanvas.prototype.createDefaultNodeForSlot;
LGraphCanvas.prototype.createDefaultNodeForSlot = function(optPass) {
if (!_fromMiddleClick) return origCreateDefault.call(this, optPass);
_fromMiddleClick = false;
const wantSetGet = _lastMiddleClickShift
? app.ui.settings.getSettingValue("KJNodes.shiftMiddleClickSetGet") ?? true
: app.ui.settings.getSettingValue("KJNodes.middleClickSetGet") ?? false;
if (!wantSetGet) return origCreateDefault.call(this, optPass);
const isFrom = optPass.nodeFrom && optPass.slotFrom !== null;
const sourceNode = isFrom ? optPass.nodeFrom : optPass.nodeTo;
const slotIndex = isFrom ? optPass.slotFrom : optPass.slotTo;
if (!sourceNode || slotIndex == null) return origCreateDefault.call(this, optPass);
const graph = this.graph || app.graph;
if (!graph) return origCreateDefault.call(this, optPass);
const newNode = LiteGraph.createNode(isFrom ? "SetNode" : "GetNode");
if (!newNode) return false;
const bounding = sourceNode.getBounding();
newNode.pos = [
isFrom ? bounding[0] + bounding[2] + 30 : bounding[0] - 200,
optPass.position?.[1] ?? bounding[1]
];
graph.add(newNode);
if (isFrom) sourceNode.connect(slotIndex, newNode, 0);
else newNode.connect(0, sourceNode, slotIndex);
graph.change();
this.setDirty(true, true);
return true;
};
}
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707import { addMiddleClickPan, chainCallback, makeUUID, watchImageInputs } from '../utility.js';
export function createEditorStylesheet(id, className) {
let styleTag = document.head.querySelector(`#${id}`)
if (!styleTag) {
styleTag = document.createElement('style')
styleTag.type = 'text/css'
styleTag.id = id
styleTag.innerHTML = `
.${className} {
position: absolute;
font: 12px monospace;
line-height: 1.5em;
padding: 10px;
z-index: 0;
overflow: hidden;
}
.${className} canvas {
position: relative;
z-index: 2;
}
`
document.head.appendChild(styleTag)
}
}
function styleMenuItem(menuItem) {
menuItem.style.display = "block";
menuItem.style.padding = "5px";
menuItem.style.color = "#FFF";
menuItem.style.fontFamily = "Arial, sans-serif";
menuItem.style.fontSize = "16px";
menuItem.style.textDecoration = "none";
menuItem.style.marginBottom = "5px";
}
function createMenuItem(id, textContent) {
let menuItem = document.createElement("a");
menuItem.href = "#";
menuItem.dataset.menuId = id;
menuItem.textContent = textContent;
styleMenuItem(menuItem);
return menuItem;
}
function setupMenuItems(contextMenu, menuItems) {
menuItems.forEach(mi => {
mi.addEventListener('mouseover', function () { this.style.backgroundColor = "gray"; });
mi.addEventListener('mouseout', function () { this.style.backgroundColor = "#202020"; });
contextMenu.appendChild(mi);
});
}
export function createContextMenuElement(className) {
const menu = document.createElement("div");
if (className) menu.className = className;
menu.id = `context-menu-${Math.random().toString(36).slice(2, 10)}`;
menu.style.display = "none";
menu.style.position = "absolute";
menu.style.backgroundColor = "#202020";
menu.style.minWidth = "100px";
menu.style.boxShadow = "0px 8px 16px 0px rgba(0,0,0,0.2)";
menu.style.zIndex = "100";
menu.style.padding = "5px";
return menu;
}
// ─── Base Editor Canvas ───
const maxDisplayDim = 1024;
export class BaseEditorCanvas {
constructor(context, reset = false) {
this.node = context;
this.reset = reset;
this.bgImage = null;
this.margin = 14;
this.dragIndex = -1;
this.dragType = null;
this.dragOffset = null;
this._uploadGeneration = 0;
}
// ─── Shared Methods ───
setNodeWidth(width) {
this.node.setSize([width, this.node.size[1]]);
const nodeEl = document.querySelector(`[data-node-id="${this.node.id}"]`);
if (nodeEl) nodeEl.style.setProperty('--node-width', `${width}px`);
}
// Scale factors: coord space → canvas space
get scaleX() { return this.width / this.coordWidth; }
get scaleY() { return this.height / this.coordHeight; }
// Returns mouse position in coord space
getLocalMouse(e) {
const rect = this.canvas.getBoundingClientRect();
const canvasScaleX = this.canvas.width / rect.width;
const canvasScaleY = this.canvas.height / rect.height;
const canvasX = (e.clientX - rect.left) * canvasScaleX - this.margin;
const canvasY = (e.clientY - rect.top) * canvasScaleY - this.margin;
return {
x: canvasX / this.scaleX,
y: canvasY / this.scaleY
};
}
// Clamp to coord space
clamp(x, y) {
return {
x: Math.max(0, Math.min(this.coordWidth, x)),
y: Math.max(0, Math.min(this.coordHeight, y))
};
}
// ─── Canvas Setup ───
createCanvas(parentElement) {
this.canvas = document.createElement('canvas');
this.canvas.width = this.width + this.margin * 2;
this.canvas.height = this.height + this.margin * 2;
this.ctx = this.canvas.getContext('2d');
parentElement.appendChild(this.canvas);
}
resizeCanvas() {
this.canvas.width = this.width + this.margin * 2;
this.canvas.height = this.height + this.margin * 2;
}
// ─── Event Listeners ───
setupEventListeners() {
this._onDragMove = (e) => this.onMouseMove(e);
this._onDragEnd = (e) => this.onMouseUp(e);
this._removeMiddleClickPan = addMiddleClickPan(this.canvas);
this._onCanvasPointerDown = (e) => { e.stopPropagation(); this.onMouseDown(e); };
this._onCanvasPointerMove = (e) => this.onMouseMove(e);
this._onCanvasContextMenu = (e) => { e.preventDefault(); e.stopPropagation(); };
this.canvas.addEventListener('pointerdown', this._onCanvasPointerDown);
this.canvas.addEventListener('pointermove', this._onCanvasPointerMove);
this.canvas.addEventListener('contextmenu', this._onCanvasContextMenu);
}
removeEventListeners() {
if (this.canvas) {
this.canvas.removeEventListener('pointerdown', this._onCanvasPointerDown);
this.canvas.removeEventListener('pointermove', this._onCanvasPointerMove);
this.canvas.removeEventListener('pointermove', this._onDragMove);
this.canvas.removeEventListener('pointerup', this._onDragEnd);
this.canvas.removeEventListener('contextmenu', this._onCanvasContextMenu);
}
document.removeEventListener('pointermove', this._onDragMove);
document.removeEventListener('pointerup', this._onDragEnd);
if (this._removeMiddleClickPan) this._removeMiddleClickPan();
}
startDocumentDrag(e) {
if (e && e.pointerId !== undefined) {
this.canvas.setPointerCapture(e.pointerId);
this._capturedPointerId = e.pointerId;
// With pointer capture, events fire on the canvas, not document
this.canvas.addEventListener('pointermove', this._onDragMove);
this.canvas.addEventListener('pointerup', this._onDragEnd);
} else {
document.addEventListener('pointermove', this._onDragMove);
document.addEventListener('pointerup', this._onDragEnd);
}
}
endDrag() {
this.dragIndex = -1;
this.dragType = null;
this.dragOffset = null;
this.canvas.style.cursor = 'default';
if (this._capturedPointerId !== undefined) {
try { this.canvas.releasePointerCapture(this._capturedPointerId); } catch (_) {}
this._capturedPointerId = undefined;
this.canvas.removeEventListener('pointermove', this._onDragMove);
this.canvas.removeEventListener('pointerup', this._onDragEnd);
} else {
document.removeEventListener('pointermove', this._onDragMove);
document.removeEventListener('pointerup', this._onDragEnd);
}
}
// ─── Render Batching ───
render() {
if (this._renderPending) return;
this._renderPending = true;
requestAnimationFrame(() => {
this._renderPending = false;
this._render();
});
}
// Subclasses must implement _render()
// ─── Common Render Helpers ───
// Convert coord-space point to canvas-space pixel
toCanvas(x, y) {
return { x: x * this.scaleX, y: y * this.scaleY };
}
// Call at start of _render() — clears and draws background
beginRender() {
const ctx = this.ctx;
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
ctx.save();
ctx.translate(this.margin, this.margin);
ctx.fillStyle = '#222';
ctx.fillRect(0, 0, this.width, this.height);
ctx.strokeStyle = 'gray';
ctx.lineWidth = 2;
ctx.strokeRect(0, 0, this.width, this.height);
if (this.bgImage) {
ctx.drawImage(this.bgImage, 0, 0, this.width, this.height);
}
}
endRender() {
this.ctx.restore();
}
// ─── Image Handling ───
handleImageLoad = (img, downscaledImg) => {
// Set coord space to image dimensions
this.coordWidth = img.width;
this.coordHeight = img.height;
this.widthWidget.value = img.width;
this.heightWidget.value = img.height;
this.onImageResize?.(img);
// Cap display size, preserving aspect ratio
let displayW = img.width, displayH = img.height;
if (displayW > maxDisplayDim || displayH > maxDisplayDim) {
const scale = maxDisplayDim / Math.max(displayW, displayH);
displayW = Math.round(displayW * scale);
displayH = Math.round(displayH * scale);
}
if (displayW !== this.width || displayH !== this.height) {
this.width = displayW;
this.height = displayH;
this.resizeCanvas();
if (displayW > 256) this.setNodeWidth(displayW + 45);
this.onSizeChanged();
if (this.node.graph) {
try { this.node.arrange?.(); } catch (_) {}
this.node.graph.setDirtyCanvas(true, true);
}
}
// Use downscaled image if available to avoid holding full-res in memory
this.bgImage = downscaledImg || img;
this.render();
this.onDataChanged();
};
// resizeCanvas: if true (default), resize editor canvas to match image.
// If false, just store the image and update the background without resizing.
processImage = (img, { resize = true } = {}) => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
let width = img.width, height = img.height;
if (width > maxDisplayDim || height > maxDisplayDim) {
const scale = maxDisplayDim / Math.max(width, height);
width = Math.round(width * scale);
height = Math.round(height * scale);
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
const { app } = window.comfyAPI.app;
const embed = app.ui.settings.getSettingValue("KJNodes.editors.embedBackgroundImage") ?? false;
// Use the downscaled canvas directly as bgImage — drawImage accepts canvas elements,
// avoids a data URL round-trip, and is immediately available (no async decode).
const onStored = () => {
if (resize) {
this.handleImageLoad(img, canvas);
} else {
this.bgImage = canvas;
this.render();
}
};
const gen = ++this._uploadGeneration;
if (embed) {
const base64String = canvas.toDataURL('image/webp', 0.5).replace(/^data:.+?,/, '');
if (gen !== this._uploadGeneration) return;
this.node.properties.imgData = { type: 'image/webp', base64: base64String };
onStored();
} else {
canvas.toBlob((blob) => {
if (gen !== this._uploadGeneration) return;
const filename = `editor_bg_${this.node.id}_${Date.now()}.webp`;
const formData = new FormData();
formData.append('image', blob, filename);
formData.append('type', 'temp');
formData.append('overwrite', 'true');
fetch('/upload/image', { method: 'POST', body: formData })
.then(r => r.json())
.then(result => {
if (gen !== this._uploadGeneration) return;
this.node.properties.imgData = { type: 'temp', filename: result.name };
onStored();
})
.catch(e => console.error("Failed to upload editor background:", e));
}, 'image/webp', 0.5);
}
};
handleImageFile = (file) => {
const url = URL.createObjectURL(file);
const img = new Image();
img.onload = () => { URL.revokeObjectURL(url); this.processImage(img); };
img.onerror = () => URL.revokeObjectURL(url);
img.src = url;
};
refreshBackgroundImage = () => {
const imgData = this.node.properties.imgData;
if (!imgData) return;
const img = new Image();
img.onerror = (e) => console.error("Background image failed to load:", e);
img.onload = () => {
// Just set the background — don't resize canvas, widget values are already correct from serialization
this.bgImage = img;
this.render();
};
if (imgData.base64) {
const mimeType = imgData.type || 'image/png';
img.src = `data:${mimeType};base64,${imgData.base64}`;
} else if (imgData.filename) {
img.src = `/view?filename=${encodeURIComponent(imgData.filename)}&type=temp&no-cache=${Date.now()}`;
}
};
// ─── Context Menu Helpers ───
// Set up document-level listeners for context menu behavior
setupContextMenuListeners(editorIdPrefix) {
this._onContextMenu = (e) => {
if (e.target.closest(`#${editorIdPrefix}-${this.node.uuid}`) ||
this.node.contextMenu.contains(e.target)) {
e.preventDefault();
}
};
this._onDocClick = (e) => {
if (!this.node.contextMenu.contains(e.target)) {
this.node.contextMenu.style.display = 'none';
}
};
document.addEventListener('contextmenu', this._onContextMenu);
document.addEventListener('click', this._onDocClick);
}
// Clean up previous editor instance
cleanupPreviousEditor(context) {
if (context.editor) {
context.editor.destroy();
}
}
// Full cleanup — override in subclass to add additional cleanup
destroy() {
this._uploadGeneration++; // Invalidate any pending async image uploads
this.removeEventListeners();
if (this._onContextMenu) document.removeEventListener('contextmenu', this._onContextMenu);
if (this._onDocClick) document.removeEventListener('click', this._onDocClick);
if (this._onKeyUp) document.removeEventListener('keyup', this._onKeyUp);
}
// Common menu actions
openImageFilePicker() {
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = 'image/*';
fileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
if (file) this.handleImageFile(file);
});
fileInput.click();
}
clearBackgroundImage() {
this.bgImage = null;
this.node.properties.imgData = null;
this.render();
}
// Find a widget by name on the node
findWidget(name) {
const w = this.node.widgets.find(w => w.name === name);
if (!w) console.warn(`${this.constructor.name}: widget "${name}" not found`);
return w;
}
// Show context menu at mouse position
showContextMenu(e) {
this._updateMenuToggleStates();
const menu = this.node.contextMenu;
menu.style.display = 'block';
menu.style.left = `${e.clientX}px`;
menu.style.top = `${e.clientY}px`;
// Adjust if menu overflows viewport
const rect = menu.getBoundingClientRect();
if (rect.right > window.innerWidth) menu.style.left = `${Math.max(0, e.clientX - rect.width)}px`;
if (rect.bottom > window.innerHeight) menu.style.top = `${Math.max(0, e.clientY - rect.height)}px`;
}
// ─── Width/Height Resize ───
setupSizeCallbacks() {
this.widthWidget.callback = () => {
const oldCoordW = this.coordWidth;
this.coordWidth = this.widthWidget.value;
this.onCoordSpaceResized(oldCoordW, this.coordHeight);
this.render();
this.onDataChanged();
};
this.heightWidget.callback = () => {
const oldCoordH = this.coordHeight;
this.coordHeight = this.heightWidget.value;
this.onCoordSpaceResized(this.coordWidth, oldCoordH);
this.render();
this.onDataChanged();
};
}
// ─── imgData persistence ───
// Call once from onNodeCreated to ensure imgData survives save/reload
static setupImgDataPersistence(node) {
chainCallback(node, "onSerialize", function (o) {
if (this.properties.imgData && o.properties) {
o.properties.imgData = this.properties.imgData;
}
});
chainCallback(node, "onConfigure", function (info) {
if (info?.properties?.imgData) {
this.properties.imgData = info.properties.imgData;
}
});
}
// ─── Node registration helper ───
// Call from onNodeCreated to set up the common editor scaffolding.
// config: { editorClass, editorKey, heightKey, className, menuItems, hiddenWidgets, initialSize, extraProperties }
// editorClass: the editor constructor (e.g. SplineEditor)
// editorKey: node property name for the DOM widget (e.g. 'splineEditor')
// heightKey: node property name for editor height (e.g. 'splineEditorHeight')
// className: CSS class for the editor container
// menuItems: { id: { label, action(editor), toggle?(editor) }, ... } — context menu definition
// menuClassName: optional CSS class for the context menu
// hiddenWidgets: widget names to hide
// initialSize: [width, height] for the node
// extraProperties: array of [name, default, type] to register via addProperty on first create
static setupNode(node, nodeData, config) {
const { editorClass, editorKey, heightKey, className, menuItems,
menuClassName, hiddenWidgets, initialSize, extraProperties } = config;
if (!node.properties) node.properties = {};
if (node.properties.imgData === undefined) node.properties.imgData = null;
// File handling — set up once per node, delegate to current editor
node.pasteFile = (file) => {
if (node.editor && file.type.startsWith("image/")) {
node.editor.handleImageFile(file);
return true;
}
return false;
};
node.onDragOver = (e) => {
if (node.editor && e.dataTransfer && e.dataTransfer.items) {
return [...e.dataTransfer.items].some(f => f.kind === "file" && f.type.startsWith("image/"));
}
return false;
};
node.onDragDrop = (e) => {
if (!node.editor) return false;
let handled = false;
for (const file of e.dataTransfer.files) {
if (file.type.startsWith("image/")) {
node.editor.handleImageFile(file);
handled = true;
}
}
return handled;
};
for (const name of (hiddenWidgets || [])) {
const w = node.widgets.find(w => w.name === name);
if (w) w.hidden = true;
}
const element = document.createElement("div");
node.uuid = makeUUID();
element.id = `${className}-${node.uuid}`;
node.previewMediaType = 'image';
node[editorKey] = node.addDOMWidget(nodeData.name, `${editorClass.name}Widget`, element, {
serialize: false, hideOnZoom: false,
getMinHeight: () => node[heightKey] || 550,
getMaxHeight: () => node[heightKey] || 550,
getHeight: () => node[heightKey] || 550,
});
node[heightKey] = 550;
node.contextMenu = createContextMenuElement(menuClassName);
node._menuDef = menuItems;
const menuEls = Object.entries(menuItems).map(([id, def]) => createMenuItem(id, def.label || id));
setupMenuItems(node.contextMenu, menuEls);
document.body.appendChild(node.contextMenu);
node.addWidget("button", "Reset canvas", null, () => {
try { node.editor = new editorClass(node, true); }
catch (error) { console.error(`Error creating ${editorClass.name}:`, error); }
});
node.setSize(initialSize);
node[editorKey].parentEl = document.createElement("div");
node[editorKey].parentEl.className = className;
node[editorKey].parentEl.id = `${className}-${node.uuid}`;
element.appendChild(node[editorKey].parentEl);
// Auto-create for new nodes; onConfigure cancels this for saved workflows
node._autoCreatePending = setTimeout(() => {
if (!node.editor) {
try {
node.editor = new editorClass(node);
for (const [name, value, type] of (extraProperties || [])) {
node.addProperty(name, value, type);
}
} catch (error) { console.error(`Error creating ${editorClass.name}:`, error); }
}
}, 0);
BaseEditorCanvas.setupImgDataPersistence(node);
chainCallback(node, "onResize", function () {
const editor = this.editor;
if (!editor) return;
const newWidth = Math.max(64, Math.round(this.size[0] - 45));
if (newWidth === editor.width) return;
// Only change display size — coord space stays the same
editor.width = newWidth;
editor.height = Math.round(newWidth * (editor.coordHeight / editor.coordWidth));
editor.resizeCanvas();
editor.onSizeChanged();
editor.render();
});
chainCallback(node, "onConfigure", function () {
clearTimeout(this._autoCreatePending);
try { this.editor = new editorClass(this); }
catch (error) { console.error(`Error configuring ${editorClass.name}:`, error); }
// Allow watchImageInputs to operate only after configure + a delay,
// so refreshBackgroundImage has time to restore the saved image first.
node._bgWatchReady = false;
setTimeout(() => { node._bgWatchReady = true; }, 500);
});
chainCallback(node, "onExecuted", function (message) {
let bg_image = message["bg_image"];
if (Array.isArray(bg_image)) bg_image = bg_image[0];
if (bg_image) {
const img = new Image();
img.src = `data:image/jpeg;base64,${bg_image}`;
img.onload = () => {
if (this.editor) this.editor.processImage(img);
};
}
});
// Load background image from connected source node (LoadImage, VHS, etc.)
// _bgWatchReady is false during reload until the editor has restored its saved background.
// _bgFromConnectedSource tracks whether the current bg came from a connection (vs execution/paste).
node._bgFromConnectedSource = false;
node._bgWatchReady = true; // true for new nodes, set false during onConfigure
watchImageInputs(node, "bg_image", (sources) => {
if (!node.editor || !node._bgWatchReady) return;
const source = sources[0];
if (source && !source.isVideo) {
node._bgFromConnectedSource = true;
const img = new Image();
img.crossOrigin = "anonymous";
img.onerror = (e) => console.error("[Editor] source image load error:", e);
img.onload = () => { if (node.editor) node.editor.processImage(img); };
img.src = source.url;
} else if (!source && node._bgFromConnectedSource) {
node._bgFromConnectedSource = false;
node.editor.clearBackgroundImage();
}
});
chainCallback(node, "onRemoved", function () {
if (this.editor) this.editor.destroy();
if (this.contextMenu?.parentNode) this.contextMenu.parentNode.removeChild(this.contextMenu);
});
}
// ─── Shared constructor flow ───
// Call from subclass constructor after setting up widgets and data.
// editorKey: e.g. 'pointsEditor' or 'splineEditor'
// heightKey: e.g. 'pointsEditorHeight' or 'splineEditorHeight'
// heightOffset: pixels added to canvas height for full node height (e.g. 310 or 460)
initEditor(editorKey, heightKey, heightOffset) {
this._editorKey = editorKey;
this._heightKey = heightKey;
this._heightOffset = heightOffset;
this.createCanvas(this.node[editorKey].element);
if (this.width > 256) this.setNodeWidth(this.width + 45);
this.node[heightKey] = this.height + 40;
this.node.setSize([this.node.size[0], this.height + heightOffset]);
this.setupEventListeners();
this.render();
}
// Shared onSizeChanged — uses stored heightKey/heightOffset
onSizeChanged() {
this.node[this._heightKey] = this.height + 40;
this.node.setSize([this.node.size[0], this.height + this._heightOffset]);
if (this.node.graph) this.node.graph.setDirtyCanvas(true, true);
}
// Shared constructor preamble — cleanup, reset, context menu, coord/display init
initEditorPreamble(editorKey, className) {
this._className = className;
this.cleanupPreviousEditor(this.node);
if (this.reset && this.node[editorKey].element) {
this.node[editorKey].element.innerHTML = '';
}
this.createContextMenu();
}
// Shared coord/display size init from widgets + saved node size
initDisplaySize() {
this.coordWidth = this.widthWidget.value;
this.coordHeight = this.heightWidget.value;
const savedWidth = Math.max(64, Math.round(this.node.size[0] - 45));
this.width = Math.min(savedWidth, maxDisplayDim);
this.height = Math.round(this.width * (this.coordHeight / this.coordWidth));
}
// Shared context menu creation — clone to clear stale listeners, wire up action handlers
createContextMenu() {
const oldMenu = this.node.contextMenu;
const newMenu = oldMenu.cloneNode(true);
oldMenu.parentNode.replaceChild(newMenu, oldMenu);
this.node.contextMenu = newMenu;
this.setupContextMenuListeners(this._className);
const self = this;
newMenu.addEventListener('click', (e) => {
e.preventDefault();
if (e.target.tagName !== 'A') return;
const id = e.target.dataset.menuId;
const def = this.node._menuDef[id];
if (def?.action) {
def.action(self);
self._updateMenuToggleStates();
}
newMenu.style.display = 'none';
});
}
// Update toggle item styling from menu definitions
_updateMenuToggleStates() {
const menuDef = this.node._menuDef;
this.node.contextMenu.querySelectorAll('a').forEach(item => {
const def = menuDef[item.dataset.menuId];
if (def?.toggle) {
const on = def.toggle(this);
item.style.color = on ? '#4fc3f7' : '#FFF';
item.style.borderLeft = on ? '3px solid #4fc3f7' : '3px solid transparent';
item.style.paddingLeft = '8px';
}
});
}
// ─── Hooks for subclasses ───
// Override these instead of duplicating logic:
// Called after data changes (render + update widgets)
onDataChanged() {}
// Called on image load for editor-specific state (e.g., drawRuler = false)
onImageResize() {}
// Called when coord space changes — override to rescale coordinates
onCoordSpaceResized(_oldWidth, _oldHeight) {}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211// ─── Interpolation: SVG path d-string builders ───
// Ported from protovis basis/cardinal/monotone/hermite algorithms
const Interpolation = {
_basisPoint(t0, p0, t1, p1, t2, p2, t3, p3) {
return t0 * p0 + t1 * p1 + t2 * p2 + t3 * p3;
},
_pathBasis(p0, p1, p2, p3) {
const bp = Interpolation._basisPoint;
const x1 = bp(0, p0.x, 2/3, p1.x, 1/3, p2.x, 0, p3.x);
const y1 = bp(0, p0.y, 2/3, p1.y, 1/3, p2.y, 0, p3.y);
const x2 = bp(0, p0.x, 1/3, p1.x, 2/3, p2.x, 0, p3.x);
const y2 = bp(0, p0.y, 1/3, p1.y, 2/3, p2.y, 0, p3.y);
const x = bp(0, p0.x, 1/6, p1.x, 2/3, p2.x, 1/6, p3.x);
const y = bp(0, p0.y, 1/6, p1.y, 2/3, p2.y, 1/6, p3.y);
return `C${x1},${y1},${x2},${y2},${x},${y}`;
},
basis(points) {
if (points.length <= 2) return Interpolation.linear(points);
let d = '';
let b0 = points[0], b1 = points[0], b2 = points[0], b3 = points[1];
d += Interpolation._pathBasis(b0, b1, b2, b3);
for (let i = 2; i < points.length; i++) {
b0 = b1; b1 = b2; b2 = b3; b3 = points[i];
d += Interpolation._pathBasis(b0, b1, b2, b3);
}
b0 = b1; b1 = b2; b2 = b3;
d += Interpolation._pathBasis(b0, b1, b2, b3);
b0 = b1; b1 = b2;
d += Interpolation._pathBasis(b0, b1, b2, b3);
return d;
},
_cardinalTangents(points, tension) {
const alpha = (1 - tension) / 2;
const tangents = [];
let f = points[0], g = points[1], h = points[2];
for (let i = 3; i < points.length; i++) {
tangents.push({ x: alpha * (h.x - f.x), y: alpha * (h.y - f.y) });
f = g; g = h; h = points[i];
}
tangents.push({ x: alpha * (h.x - f.x), y: alpha * (h.y - f.y) });
return tangents;
},
_hermite(points, tangents) {
if (tangents.length < 1 ||
(points.length !== tangents.length && points.length !== tangents.length + 2))
return '';
const quad = points.length !== tangents.length;
let d = '';
let g = points[0], h = points[1], i = tangents[0], j = i, k = 1;
if (quad) {
d += `Q${h.x - i.x * 2/3},${h.y - i.y * 2/3},${h.x},${h.y}`;
g = points[1]; k = 2;
}
if (tangents.length > 1) {
j = tangents[1]; h = points[k]; k++;
d += `C${g.x + i.x},${g.y + i.y},${h.x - j.x},${h.y - j.y},${h.x},${h.y}`;
for (let idx = 2; idx < tangents.length; idx++, k++) {
h = points[k]; j = tangents[idx];
d += `S${h.x - j.x},${h.y - j.y},${h.x},${h.y}`;
}
}
if (quad) {
const last = points[k];
d += `Q${h.x + j.x * 2/3},${h.y + j.y * 2/3},${last.x},${last.y}`;
}
return d;
},
cardinal(points, tension) {
if (points.length <= 2) return Interpolation.linear(points);
return Interpolation._hermite(points, Interpolation._cardinalTangents(points, tension));
},
_monotoneTangents(points) {
const n = points.length;
const d = [], m = [], dx = [];
for (let i = 0; i < n - 1; i++) d.push((points[i + 1].y - points[i].y) / (points[i + 1].x - points[i].x));
m.push(d[0]);
for (let i = 1; i < n - 1; i++) m.push((d[i - 1] + d[i]) / 2);
m.push(d[n - 2]);
dx.push(points[1].x - points[0].x);
for (let i = 1; i < n - 1; i++) dx.push((points[i + 1].x - points[i - 1].x) / 2);
dx.push(points[n - 1].x - points[n - 2].x);
for (let i = 0; i < n - 1; i++) { if (Math.abs(d[i]) < 1e-7) { m[i] = 0; m[i + 1] = 0; } }
for (let i = 0; i < n - 1; i++) {
if (Math.abs(m[i]) >= 1e-5 && Math.abs(m[i + 1]) >= 1e-5) {
const alpha = m[i] / d[i], beta = m[i + 1] / d[i], sigma = alpha * alpha + beta * beta;
if (sigma > 9) { const k = 3 / Math.sqrt(sigma); m[i] = k * alpha * d[i]; m[i + 1] = k * beta * d[i]; }
}
}
const tangents = [];
for (let i = 0; i < n; i++) { const denom = 1 + m[i] * m[i]; tangents.push({ x: dx[i] / 3 / denom, y: m[i] * dx[i] / 3 / denom }); }
return tangents;
},
monotone(points) {
if (points.length <= 2) return Interpolation.linear(points);
return Interpolation._hermite(points, Interpolation._monotoneTangents(points));
},
linear(points) { let d = ''; for (let i = 1; i < points.length; i++) d += `L${points[i].x},${points[i].y}`; return d; },
stepBefore(points) { let d = ''; for (let i = 1; i < points.length; i++) d += `V${points[i].y}H${points[i].x}`; return d; },
stepAfter(points) { let d = ''; for (let i = 1; i < points.length; i++) d += `H${points[i].x}V${points[i].y}`; return d; },
bezier(points) {
let d = '';
for (let i = 1; i < points.length; i++) {
const prev = points[i - 1], cur = points[i];
d += `C${prev.h2x ?? prev.x},${prev.h2y ?? prev.y},${cur.h1x ?? cur.x},${cur.h1y ?? cur.y},${cur.x},${cur.y}`;
}
return d;
},
ensureBezierHandles(points) {
for (let i = 0; i < points.length; i++) {
if (points[i].h1x !== undefined) continue;
const prev = points[Math.max(0, i - 1)], next = points[Math.min(points.length - 1, i + 1)];
const dx = (next.x - prev.x) * 0.25, dy = (next.y - prev.y) * 0.25;
points[i].h1x = points[i].x - dx; points[i].h1y = points[i].y - dy;
points[i].h2x = points[i].x + dx; points[i].h2y = points[i].y + dy;
}
},
buildPathD(points, interpolation, tension) {
if (!points || points.length === 0) return '';
let d = `M${points[0].x},${points[0].y}`;
if (points.length === 1) return d;
switch (interpolation) {
case 'basis': d += Interpolation.basis(points); break;
case 'cardinal': d += Interpolation.cardinal(points, tension); break;
case 'monotone': d += Interpolation.monotone(points); break;
case 'step-before': d += Interpolation.stepBefore(points); break;
case 'step-after': d += Interpolation.stepAfter(points); break;
case 'bezier': Interpolation.ensureBezierHandles(points); d += Interpolation.bezier(points); break;
case 'linear': default: d += Interpolation.linear(points); break;
}
return d;
},
drawOnCanvas(ctx, points, interpolation, tension) {
if (!points || points.length < 2) return;
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
switch (interpolation) {
case 'basis':
if (points.length < 3) { ctx.lineTo(points[1].x, points[1].y); break; }
Interpolation._drawBasisCanvas(ctx, points); break;
case 'cardinal':
if (points.length < 3) { ctx.lineTo(points[1].x, points[1].y); break; }
Interpolation._drawHermiteCanvas(ctx, points, Interpolation._cardinalTangents(points, tension)); break;
case 'monotone':
if (points.length < 3) { ctx.lineTo(points[1].x, points[1].y); break; }
Interpolation._drawHermiteCanvas(ctx, points, Interpolation._monotoneTangents(points)); break;
case 'step-before':
for (let i = 1; i < points.length; i++) { ctx.lineTo(points[i - 1].x, points[i].y); ctx.lineTo(points[i].x, points[i].y); } break;
case 'step-after':
for (let i = 1; i < points.length; i++) { ctx.lineTo(points[i].x, points[i - 1].y); ctx.lineTo(points[i].x, points[i].y); } break;
case 'bezier':
Interpolation.ensureBezierHandles(points);
for (let i = 1; i < points.length; i++) {
const prev = points[i - 1], cur = points[i];
ctx.bezierCurveTo(prev.h2x ?? prev.x, prev.h2y ?? prev.y, cur.h1x ?? cur.x, cur.h1y ?? cur.y, cur.x, cur.y);
} break;
case 'linear': default:
for (let i = 1; i < points.length; i++) ctx.lineTo(points[i].x, points[i].y); break;
}
},
_drawBasisCanvas(ctx, points) {
const bp = Interpolation._basisPoint;
const drawSeg = (p0, p1, p2, p3) => {
ctx.bezierCurveTo(
bp(0,p0.x,2/3,p1.x,1/3,p2.x,0,p3.x), bp(0,p0.y,2/3,p1.y,1/3,p2.y,0,p3.y),
bp(0,p0.x,1/3,p1.x,2/3,p2.x,0,p3.x), bp(0,p0.y,1/3,p1.y,2/3,p2.y,0,p3.y),
bp(0,p0.x,1/6,p1.x,2/3,p2.x,1/6,p3.x), bp(0,p0.y,1/6,p1.y,2/3,p2.y,1/6,p3.y));
};
let b0 = points[0], b1 = points[0], b2 = points[0], b3 = points[1];
drawSeg(b0, b1, b2, b3);
for (let i = 2; i < points.length; i++) { b0 = b1; b1 = b2; b2 = b3; b3 = points[i]; drawSeg(b0, b1, b2, b3); }
b0 = b1; b1 = b2; b2 = b3; drawSeg(b0, b1, b2, b3);
b0 = b1; b1 = b2; drawSeg(b0, b1, b2, b3);
},
_drawHermiteCanvas(ctx, points, tangents) {
if (tangents.length < 1 || (points.length !== tangents.length && points.length !== tangents.length + 2)) return;
const quad = points.length !== tangents.length;
let g = points[0], h = points[1], i = tangents[0], j = i, k = 1;
let prevCp2x, prevCp2y;
if (quad) { ctx.quadraticCurveTo(h.x - i.x * 2/3, h.y - i.y * 2/3, h.x, h.y); g = points[1]; k = 2; }
if (tangents.length > 1) {
j = tangents[1]; h = points[k]; k++;
prevCp2x = h.x - j.x; prevCp2y = h.y - j.y;
ctx.bezierCurveTo(g.x + i.x, g.y + i.y, prevCp2x, prevCp2y, h.x, h.y);
for (let idx = 2; idx < tangents.length; idx++, k++) {
const prevH = h; h = points[k]; j = tangents[idx];
const rcp1x = 2 * prevH.x - prevCp2x, rcp1y = 2 * prevH.y - prevCp2y;
prevCp2x = h.x - j.x; prevCp2y = h.y - j.y;
ctx.bezierCurveTo(rcp1x, rcp1y, prevCp2x, prevCp2y, h.x, h.y);
}
}
if (quad) { const last = points[k]; ctx.quadraticCurveTo(h.x + j.x * 2/3, h.y + j.y * 2/3, last.x, last.y); }
}
};
export { Interpolation };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370import { chainCallback, rectHitTest, cursorForBboxMode } from '../utility.js';
import { BaseEditorCanvas, createEditorStylesheet } from './editor_base.js';
const { app } = window.comfyAPI.app;
createEditorStylesheet('kj-pointseditor-stylesheet', 'points-editor');
app.registerExtension({
name: 'KJNodes.PointEditor',
async beforeRegisterNodeDef(nodeType, nodeData) {
if (nodeData?.name === 'PointsEditor') {
chainCallback(nodeType.prototype, "onNodeCreated", function () {
BaseEditorCanvas.setupNode(this, nodeData, {
editorClass: PointsEditor,
editorKey: 'pointsEditor',
heightKey: 'pointsEditorHeight',
className: 'points-editor',
menuItems: {
"Load Image": { action: (ed) => ed.openImageFilePicker() },
"Clear Image": { action: (ed) => ed.clearBackgroundImage() },
},
hiddenWidgets: ["coordinates", "neg_coordinates", "bboxes"],
initialSize: [550, 550],
extraProperties: [
["points", this.constructor.type, "string"],
["neg_points", this.constructor.type, "string"],
],
});
});
}
}
});
class PointsEditor extends BaseEditorCanvas {
constructor(context, reset = false) {
super(context, reset);
this.initEditorPreamble('pointsEditor', 'points-editor');
this.pos_coordWidget = this.findWidget("coordinates");
this.neg_coordWidget = this.findWidget("neg_coordinates");
this.pointsStoreWidget = this.findWidget("points_store");
this.widthWidget = this.findWidget("width");
this.heightWidget = this.findWidget("height");
this.bboxStoreWidget = this.findWidget("bbox_store");
this.bboxWidget = this.findWidget("bboxes");
this.setupSizeCallbacks();
this.pointsStoreWidget.callback = () => {
try {
const parsed = JSON.parse(this.pointsStoreWidget.value);
this.points = parsed.positive || [];
this.neg_points = parsed.negative || [];
} catch (e) { console.error("Error parsing points data:", e); }
this.render();
this.updateData();
};
this.bboxStoreWidget.callback = () => {
try { this.bbox = JSON.parse(this.bboxStoreWidget.value); }
catch (e) { console.error("Error parsing bbox data:", e); }
this.render();
this.updateData();
};
this.initDisplaySize();
this.points = [];
this.neg_points = [];
this.bbox = [{}];
this.drawing = false;
this.selectedIndex = -1;
this.pointRadius = Math.max(4, Math.log(Math.max(1, Math.min(this.coordWidth, this.coordHeight))) * 4);
if (!reset && this.pointsStoreWidget.value !== "") {
try {
const parsed = JSON.parse(this.pointsStoreWidget.value);
this.points = parsed.positive || [];
this.neg_points = parsed.negative || [];
this.bbox = JSON.parse(this.bboxStoreWidget.value);
} catch (e) {
console.error("Error parsing stored points:", e);
this.points = [{ x: this.coordWidth / 2, y: this.coordHeight / 2 }];
this.neg_points = [];
this.bbox = [{}];
}
} else {
this.points = [{ x: this.coordWidth / 2, y: this.coordHeight / 2 }];
this.neg_points = [];
this.pointsStoreWidget.value = JSON.stringify({ positive: this.points, negative: this.neg_points });
this.bboxStoreWidget.value = JSON.stringify(this.bbox);
}
this.initEditor('pointsEditor', 'pointsEditorHeight', 310);
this.updateData();
this.refreshBackgroundImage();
}
onDataChanged() { this.updateData(); }
onCoordSpaceResized(oldWidth, oldHeight) {
const sx = this.coordWidth / oldWidth, sy = this.coordHeight / oldHeight;
const clampPt = (p) => { p.x = Math.max(0, Math.min(this.coordWidth, p.x * sx)); p.y = Math.max(0, Math.min(this.coordHeight, p.y * sy)); };
for (const p of this.points) clampPt(p);
for (const p of this.neg_points) clampPt(p);
for (const b of this.bbox) {
if (b.startX != null) {
b.startX = Math.max(0, Math.min(this.coordWidth, b.startX * sx));
b.startY = Math.max(0, Math.min(this.coordHeight, b.startY * sy));
b.endX = Math.max(0, Math.min(this.coordWidth, b.endX * sx));
b.endY = Math.max(0, Math.min(this.coordHeight, b.endY * sy));
}
}
this.pointRadius = Math.max(4, Math.log(Math.max(1, Math.min(this.coordWidth, this.coordHeight))) * 4);
}
// ─── Hit Testing ───
findPointAt(x, y, pointsArray) {
// Convert pixel radius to coord space
const r = this.pointRadius / Math.min(this.scaleX, this.scaleY);
for (let i = pointsArray.length - 1; i >= 0; i--) {
const p = pointsArray[i];
const dx = p.x - x, dy = p.y - y;
if (dx * dx + dy * dy <= r * r) return i;
}
return -1;
}
normBbox() {
const b = this.bbox[0];
if (!b || Object.keys(b).length === 0) return null;
return {
x1: Math.min(b.startX, b.endX), y1: Math.min(b.startY, b.endY),
x2: Math.max(b.startX, b.endX), y2: Math.max(b.startY, b.endY),
};
}
hitTestBbox(mx, my) {
const n = this.normBbox();
if (!n) return null;
return rectHitTest(mx, my, n.x1, n.y1, n.x2, n.y2, 10 / Math.min(this.scaleX, this.scaleY));
}
// ─── Mouse Handlers ───
onMouseDown(e) {
const mouse = this.getLocalMouse(e);
const clamped = this.clamp(mouse.x, mouse.y);
if (e.shiftKey && e.button === 2) {
this.neg_points.push({ x: clamped.x, y: clamped.y });
this.dragType = 'negative'; this.dragIndex = this.neg_points.length - 1;
this.selectedIndex = this.dragIndex;
this.dragOffset = { x: 0, y: 0 };
this.render(); this.updateData(); this.startDocumentDrag(e); return;
}
if (e.shiftKey && e.button === 0) {
this.points.push({ x: clamped.x, y: clamped.y });
this.dragType = 'positive'; this.dragIndex = this.points.length - 1;
this.selectedIndex = this.dragIndex;
this.dragOffset = { x: 0, y: 0 };
this.render(); this.updateData(); this.startDocumentDrag(e); return;
}
if (e.button === 2) {
const posIdx = this.findPointAt(mouse.x, mouse.y, this.points);
if (posIdx >= 0) { this.points.splice(posIdx, 1); this.render(); this.updateData(); return; }
const negIdx = this.findPointAt(mouse.x, mouse.y, this.neg_points);
if (negIdx >= 0) { this.neg_points.splice(negIdx, 1); this.render(); this.updateData(); return; }
const bboxHit = this.hitTestBbox(mouse.x, mouse.y);
if (bboxHit) { this.bbox = [{}]; this.render(); this.updateData(); return; }
this.showContextMenu(e);
return;
}
if (e.button !== 0) return;
if (e.ctrlKey) {
this.drawing = true;
this.dragType = 'bbox-draw';
this.bbox[0] = { startX: clamped.x, startY: clamped.y, endX: clamped.x, endY: clamped.y };
this.render(); this.startDocumentDrag(e); return;
}
const bboxHit = this.hitTestBbox(mouse.x, mouse.y);
if (bboxHit) {
const n = this.normBbox();
this.bboxAtDragStart = { startX: n.x1, startY: n.y1, endX: n.x2, endY: n.y2 };
this.dragStart = { x: mouse.x, y: mouse.y };
this.dragType = bboxHit === "move" ? 'bbox-move' : bboxHit;
this.dragIndex = 0;
this.startDocumentDrag(e); return;
}
const posIdx = this.findPointAt(mouse.x, mouse.y, this.points);
if (posIdx >= 0) {
this.dragType = 'positive'; this.dragIndex = posIdx; this.selectedIndex = posIdx;
this.dragOffset = { x: mouse.x - this.points[posIdx].x, y: mouse.y - this.points[posIdx].y };
this.render(); this.startDocumentDrag(e); return;
}
const negIdx = this.findPointAt(mouse.x, mouse.y, this.neg_points);
if (negIdx >= 0) {
this.dragType = 'negative'; this.dragIndex = negIdx; this.selectedIndex = negIdx;
this.dragOffset = { x: mouse.x - this.neg_points[negIdx].x, y: mouse.y - this.neg_points[negIdx].y };
this.render(); this.startDocumentDrag(e); return;
}
}
onMouseMove(e) {
const mouse = this.getLocalMouse(e);
const clamped = this.clamp(mouse.x, mouse.y);
if (!this.drawing && this.dragIndex < 0 && !this.dragType) {
const bboxHit = this.hitTestBbox(mouse.x, mouse.y);
const bboxCursor = cursorForBboxMode(bboxHit);
if (bboxCursor) { this.canvas.style.cursor = bboxCursor; }
else if (this.findPointAt(mouse.x, mouse.y, this.points) >= 0 ||
this.findPointAt(mouse.x, mouse.y, this.neg_points) >= 0) { this.canvas.style.cursor = "move"; }
else { this.canvas.style.cursor = "default"; }
return;
}
if (this.dragType === 'bbox-draw') {
this.bbox[0].endX = clamped.x; this.bbox[0].endY = clamped.y;
this.render(); return;
}
if (this.dragType === 'bbox-move' && this.bboxAtDragStart) {
const dx = mouse.x - this.dragStart.x, dy = mouse.y - this.dragStart.y;
const bs = this.bboxAtDragStart;
const bw = bs.endX - bs.startX, bh = bs.endY - bs.startY;
const nx = Math.max(0, Math.min(this.coordWidth - bw, bs.startX + dx));
const ny = Math.max(0, Math.min(this.coordHeight - bh, bs.startY + dy));
this.bbox[0] = { startX: nx, startY: ny, endX: nx + bw, endY: ny + bh };
this.render(); return;
}
if (this.dragType?.startsWith('resize-') && this.bboxAtDragStart) {
const bs = this.bboxAtDragStart;
const offX = this.dragStart.x - (this.dragType === 'resize-tl' || this.dragType === 'resize-bl' ? bs.startX : bs.endX);
const offY = this.dragStart.y - (this.dragType === 'resize-tl' || this.dragType === 'resize-tr' ? bs.startY : bs.endY);
const cx = Math.max(0, Math.min(this.coordWidth, mouse.x - offX));
const cy = Math.max(0, Math.min(this.coordHeight, mouse.y - offY));
if (this.dragType === 'resize-tl') this.bbox[0] = { startX: bs.endX, startY: bs.endY, endX: cx, endY: cy };
else if (this.dragType === 'resize-tr') this.bbox[0] = { startX: bs.startX, startY: bs.endY, endX: cx, endY: cy };
else if (this.dragType === 'resize-bl') this.bbox[0] = { startX: bs.endX, startY: bs.startY, endX: cx, endY: cy };
else this.bbox[0] = { startX: bs.startX, startY: bs.startY, endX: cx, endY: cy };
this.render(); return;
}
if (this.dragType === 'positive' && this.dragIndex >= 0 && this.dragIndex < this.points.length) {
const ox = this.dragOffset?.x || 0, oy = this.dragOffset?.y || 0;
const target = this.clamp(mouse.x - ox, mouse.y - oy);
this.points[this.dragIndex] = { x: target.x, y: target.y };
this.render();
} else if (this.dragType === 'negative' && this.dragIndex >= 0 && this.dragIndex < this.neg_points.length) {
const ox = this.dragOffset?.x || 0, oy = this.dragOffset?.y || 0;
const target = this.clamp(mouse.x - ox, mouse.y - oy);
this.neg_points[this.dragIndex] = { x: target.x, y: target.y };
this.render();
}
}
onMouseUp() {
if (this.drawing || this.dragType) {
this.drawing = false;
this.bboxAtDragStart = null;
this.dragStart = null;
this.endDrag();
this.updateData();
}
}
// ─── Rendering ───
_render() {
const ctx = this.ctx;
this.beginRender();
// Bounding box
const nb = this.normBbox();
if (nb) {
const tl = this.toCanvas(nb.x1, nb.y1), br = this.toCanvas(nb.x2, nb.y2);
const bw = br.x - tl.x, bh = br.y - tl.y;
ctx.fillStyle = 'rgba(70, 130, 180, 0.3)';
ctx.fillRect(tl.x, tl.y, bw, bh);
ctx.strokeStyle = 'rgba(0, 0, 0, 0.5)'; ctx.lineWidth = 4;
ctx.strokeRect(tl.x, tl.y, bw, bh);
ctx.strokeStyle = 'steelblue'; ctx.lineWidth = 2;
ctx.strokeRect(tl.x, tl.y, bw, bh);
// Center cross
const cx = (tl.x + br.x) / 2, cy = (tl.y + br.y) / 2;
ctx.strokeStyle = 'steelblue'; ctx.lineWidth = 1;
ctx.beginPath(); ctx.moveTo(cx - 5, cy); ctx.lineTo(cx + 5, cy);
ctx.moveTo(cx, cy - 5); ctx.lineTo(cx, cy + 5); ctx.stroke();
// Corner handles
const hs = 5;
ctx.fillStyle = 'steelblue';
for (const [hx, hy] of [[tl.x, tl.y], [br.x, tl.y], [tl.x, br.y], [br.x, br.y]]) {
ctx.fillRect(hx - hs, hy - hs, hs * 2, hs * 2);
}
}
// Points
this._badgePositions = [];
this._drawPoints(ctx, this.points, '#139613', '#07f907', 'positive');
// Negative points
this._drawPoints(ctx, this.neg_points, '#891616', '#f91111', 'negative');
this.endRender();
}
_drawPoints(ctx, points, color, selectedColor, type) {
const r = this.pointRadius;
for (let i = 0; i < points.length; i++) {
const p = points[i];
const cp = this.toCanvas(p.x, p.y);
const isSelected = (this.dragType === type && this.dragIndex === i);
// Outer circle
ctx.beginPath(); ctx.arc(cp.x, cp.y, r, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(100, 100, 100, 0.25)'; ctx.fill();
ctx.strokeStyle = isSelected ? selectedColor : color; ctx.lineWidth = 2; ctx.stroke();
// Center dot
ctx.beginPath(); ctx.arc(cp.x, cp.y, 1.5, 0, Math.PI * 2);
ctx.fillStyle = 'red'; ctx.fill();
// Index badge
const label = i.toString();
const badgeR = label.length > 1 ? 8 : 7;
const off = r * 0.7;
const candidates = [
{ x: cp.x + off, y: cp.y - off },
{ x: cp.x - off, y: cp.y - off },
{ x: cp.x + off, y: cp.y + off },
{ x: cp.x - off, y: cp.y + off },
];
const valid = candidates.filter(c => c.x - badgeR >= 0 && c.x + badgeR <= this.width && c.y - badgeR >= 0 && c.y + badgeR <= this.height);
const pool = valid.length > 0 ? valid : candidates;
let badge = pool[0];
const minDist = badgeR * 2.2;
for (const c of pool) {
const overlaps = this._badgePositions.some(b => Math.abs(c.x - b.x) < minDist && Math.abs(c.y - b.y) < minDist);
if (!overlaps) { badge = c; break; }
}
this._badgePositions.push(badge);
ctx.font = 'bold 10px sans-serif';
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.beginPath(); ctx.arc(badge.x, badge.y, badgeR, 0, Math.PI * 2);
ctx.fillStyle = isSelected ? selectedColor : color; ctx.fill();
ctx.fillStyle = '#fff';
ctx.fillText(label, badge.x, badge.y + 0.5);
ctx.textAlign = 'start'; ctx.textBaseline = 'alphabetic';
}
}
// ─── Data ───
updateData() {
const combinedPoints = { positive: this.points || [], negative: this.neg_points || [] };
this.pointsStoreWidget.value = JSON.stringify(combinedPoints);
this.pos_coordWidget.value = JSON.stringify(this.points || []);
this.neg_coordWidget.value = JSON.stringify(this.neg_points || []);
if (this.bbox.length !== 0) {
let bboxString = JSON.stringify(this.bbox);
this.bboxStoreWidget.value = bboxString;
this.bboxWidget.value = bboxString;
}
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708import { chainCallback } from '../utility.js';
import { BaseEditorCanvas, createEditorStylesheet } from './editor_base.js';
import { Interpolation } from './interpolation.js';
const { app } = window.comfyAPI.app;
createEditorStylesheet('kj-splineeditor-stylesheet', 'spline-editor');
// ─── Hidden SVG for path sampling (singleton) ───
let _sharedSampler = null;
let _samplerRefCount = 0;
class PathSampler {
constructor() {
const ns = 'http://www.w3.org/2000/svg';
this._svg = document.createElementNS(ns, 'svg');
this._svg.style.cssText = 'position:absolute;width:0;height:0;overflow:hidden;pointer-events:none;';
this._svg.setAttribute('aria-hidden', 'true');
document.body.appendChild(this._svg);
this._path = document.createElementNS(ns, 'path');
this._svg.appendChild(this._path);
}
static acquire() {
if (_sharedSampler) { _samplerRefCount++; return _sharedSampler; }
_sharedSampler = new PathSampler();
_samplerRefCount = 1;
return _sharedSampler;
}
setPath(d) { this._path.setAttribute('d', d); }
getTotalLength() { return this._path.getTotalLength(); }
getPointAtLength(len) { return this._path.getPointAtLength(len); }
release() {
_samplerRefCount--;
if (_samplerRefCount <= 0 && this._svg && this._svg.parentNode) {
this._svg.parentNode.removeChild(this._svg);
_sharedSampler = null;
}
}
findPointAtX(targetX, pathLength) {
let low = 0, high = pathLength, bestPoint = this.getPointAtLength(0);
const epsilon = 0.5;
while (high - low > epsilon) {
const mid = (low + high) / 2, point = this.getPointAtLength(mid);
if (Math.abs(point.x - targetX) < Math.abs(bestPoint.x - targetX)) bestPoint = point;
if (Math.abs(point.x - targetX) < 0.5) return point;
if (point.x < targetX) low = mid; else high = mid;
}
return bestPoint;
}
}
// ─── Extension Registration ───
app.registerExtension({
name: 'KJNodes.SplineEditor',
init() {
app.ui.settings.addSetting({
id: "KJNodes.splineEditor.showControlLines",
name: "Show control lines",
category: ["KJNodes", "Editors", "Show control lines"],
tooltip: "Display straight lines between control points",
type: "boolean",
defaultValue: false,
});
app.ui.settings.addSetting({
id: "KJNodes.splineEditor.showSamplePoints",
name: "Show sample points",
category: ["KJNodes", "Editors", "Show sample points"],
tooltip: "Display the sampled output points as red dots",
type: "boolean",
defaultValue: false,
});
app.ui.settings.addSetting({
id: "KJNodes.splineEditor.showArrows",
name: "Show direction arrows",
category: ["KJNodes", "Editors", "Show direction arrows"],
tooltip: "Display chevron arrows on control points showing curve direction",
type: "boolean",
defaultValue: true,
});
app.ui.settings.addSetting({
id: "KJNodes.editors.embedBackgroundImage",
name: "Embed background image in workflow",
category: ["KJNodes", "Editors", "Embed background image"],
tooltip: "When enabled, editor background images are embedded as base64 in the workflow file (portable, larger files). When disabled, images are stored as temp files on the server (small workflows, survives refresh, but not portable).",
type: "boolean",
defaultValue: false,
});
},
async beforeRegisterNodeDef(nodeType, nodeData) {
if (nodeData?.name === 'SplineEditor') {
chainCallback(nodeType.prototype, "onNodeCreated", function () {
BaseEditorCanvas.setupNode(this, nodeData, {
editorClass: SplineEditor,
editorKey: 'splineEditor',
heightKey: 'splineEditorHeight',
className: 'spline-editor',
menuClassName: 'spline-editor-context-menu',
menuItems: {
"Display control lines": { toggle: (ed) => ed.drawHandles, action: (ed) => { ed.drawHandles = !ed.drawHandles; app.ui.settings.setSettingValue("KJNodes.splineEditor.showControlLines", ed.drawHandles); ed.render(); } },
"Display sample points": { toggle: (ed) => ed.drawSamplePoints, action: (ed) => { ed.drawSamplePoints = !ed.drawSamplePoints; app.ui.settings.setSettingValue("KJNodes.splineEditor.showSamplePoints", ed.drawSamplePoints); ed.updatePath(); } },
"Display arrows": { toggle: (ed) => ed.showChevrons, action: (ed) => { ed.showChevrons = !ed.showChevrons; app.ui.settings.setSettingValue("KJNodes.splineEditor.showArrows", ed.showChevrons); ed.render(); } },
"Background image": { action: (ed) => ed.openImageFilePicker() },
"Invert point order": { action: (ed) => { ed.splines[ed.activeSplineIndex].points.reverse(); ed.render(); ed.updatePath(); } },
"Clear Image": { action: (ed) => { ed.clearBackgroundImage(); ed.drawRuler = true; } },
"Add new spline": { action: (ed) => { const idx = ed.splines.length; ed.splines.push({ points: [{ x: 0, y: ed.coordHeight }, { x: ed.coordWidth / 2, y: ed.coordHeight / 2 }, { x: ed.coordWidth, y: 0 }], color: ed.getSplineColor(idx), name: `Spline ${idx + 1}` }); ed.activeSplineIndex = idx; ed.render(); ed.updatePath(); } },
"Add new single point": { action: (ed) => { const idx = ed.splines.length; ed.splines.push({ points: [{ x: ed.lastContextMenuPos.x, y: ed.lastContextMenuPos.y }], color: ed.getSplineColor(idx), name: `Spline ${idx + 1}`, isSinglePoint: true }); ed.activeSplineIndex = idx; ed.render(); ed.updatePath(); } },
"Delete current spline": { action: (ed) => { if (ed.splines.length > 1) { ed.splines.splice(ed.activeSplineIndex, 1); ed.activeSplineIndex = Math.min(ed.activeSplineIndex, ed.splines.length - 1); ed.render(); ed.updatePath(); } } },
"Next spline": { action: (ed) => { ed.activeSplineIndex = (ed.activeSplineIndex + 1) % ed.splines.length; ed.render(); ed.updatePath(); } },
},
hiddenWidgets: ["coordinates"],
initialSize: [550, 1000],
extraProperties: [
["points", this.constructor.type, "string"],
],
});
});
}
}
});
// ─── SplineEditor class ───
class SplineEditor extends BaseEditorCanvas {
constructor(context, reset = false) {
super(context, reset);
this.initEditorPreamble('splineEditor', 'spline-editor');
this.sampler = PathSampler.acquire();
this.drawSamplePoints = app.ui.settings.getSettingValue("KJNodes.splineEditor.showSamplePoints") ?? false;
this.drawHandles = app.ui.settings.getSettingValue("KJNodes.splineEditor.showControlLines") ?? false;
this.showChevrons = app.ui.settings.getSettingValue("KJNodes.splineEditor.showArrows") ?? true;
this.drawRuler = true;
this.coordWidget = this.findWidget("coordinates");
this.interpolationWidget = this.findWidget("interpolation");
this.pointsWidget = this.findWidget("points_to_sample");
this.pointsStoreWidget = this.findWidget("points_store");
this.tensionWidget = this.findWidget("tension");
this.samplingMethodWidget = this.findWidget("sampling_method");
this.widthWidget = this.findWidget("mask_width");
this.heightWidget = this.findWidget("mask_height");
this.interpolationWidget.callback = () => this.updatePath(true);
this.samplingMethodWidget.callback = () => {
if (this.samplingMethod === "controlpoints") this.drawSamplePoints = true;
else this.drawSamplePoints = false;
if (this.samplingMethod === "path" || this.samplingMethod === "speed") this.showChevrons = true;
this.updatePath(true);
};
this.tensionWidget.callback = () => this.updatePath(true);
this.pointsWidget.callback = () => this.updatePath(true);
this.setupSizeCallbacks();
this.pointsStoreWidget.callback = () => {
this.parseSplineData();
this.render(); this.updatePath(true);
};
this.initDisplaySize();
this.splines = [];
this.activeSplineIndex = 0;
this.hoverSplineIndex = -1;
this.hoverIndex = -1;
this.sampledCoords = null;
this.lastContextMenuPos = { x: this.coordWidth / 2, y: this.coordHeight / 2 };
if (!reset && this.pointsStoreWidget.value !== "") {
this.parseSplineData();
} else {
this.initializeDefaultSplines();
this.pointsStoreWidget.value = JSON.stringify(this.splines);
}
this._onKeyUp = (e) => {
if (e.key === 'Control' && this.subdividePreview) { this.subdividePreview = null; this.render(); }
};
document.addEventListener('keyup', this._onKeyUp);
this.initEditor('splineEditor', 'splineEditorHeight', 460);
this.updatePath();
this.refreshBackgroundImage();
}
// ─── Widget value getters ───
get interpolation() { return this.interpolationWidget.value; }
get tension() { return this.tensionWidget.value; }
get points_to_sample() { return this.pointsWidget.value; }
get samplingMethod() { return this.samplingMethodWidget.value; }
// ─── Base class hooks ───
destroy() {
super.destroy();
if (this.sampler) this.sampler.release();
}
onDataChanged() { this.updatePath(true); }
onImageResize() { this.drawRuler = false; }
onCoordSpaceResized(oldWidth, oldHeight) {
const sx = this.coordWidth / oldWidth, sy = this.coordHeight / oldHeight;
const cw = this.coordWidth, ch = this.coordHeight;
const clamp = (v, max) => Math.max(0, Math.min(max, v));
for (const spline of this.splines) {
for (const p of spline.points) {
p.x = clamp(p.x * sx, cw); p.y = clamp(p.y * sy, ch);
if (p.h1x !== undefined) { p.h1x = clamp(p.h1x * sx, cw); p.h1y = clamp(p.h1y * sy, ch); }
if (p.h2x !== undefined) { p.h2x = clamp(p.h2x * sx, cw); p.h2y = clamp(p.h2y * sy, ch); }
}
}
}
// ─── Spline Helpers ───
parseSplineData() {
try {
const parsed = JSON.parse(this.pointsStoreWidget.value);
if (Array.isArray(parsed) && parsed.length > 0 && parsed[0].hasOwnProperty('points')) {
this.splines = parsed;
} else {
this.splines = [{ points: parsed, color: "#1f77b4", name: "Spline 1" }];
}
} catch (e) {
console.error("Error parsing spline data:", e);
this.initializeDefaultSplines();
}
if (this.activeSplineIndex >= this.splines.length) {
this.activeSplineIndex = Math.max(0, this.splines.length - 1);
}
}
initializeDefaultSplines() {
this.splines = [{
points: [
{ x: 0, y: this.coordHeight },
{ x: this.coordWidth / 5 * 2, y: 50 + Math.random() * (this.coordHeight - 100) },
{ x: this.coordWidth, y: 0 }
],
color: this.getSplineColor(0),
name: "Spline 1"
}];
}
getSplineColor(index) {
const colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"];
return colors[index % colors.length];
}
// ─── Hit Testing ───
findPointAt(x, y) {
const activePoints = this.splines[this.activeSplineIndex]?.points;
if (!activePoints) return -1;
const r = 12 / Math.min(this.scaleX, this.scaleY);
for (let i = activePoints.length - 1; i >= 0; i--) {
const dx = activePoints[i].x - x, dy = activePoints[i].y - y;
if (dx * dx + dy * dy <= r * r) return i;
}
return -1;
}
findHandleAt(x, y) {
if (this.interpolation !== 'bezier') return null;
const activePoints = this.splines[this.activeSplineIndex]?.points;
if (!activePoints) return null;
const r = 8 / Math.min(this.scaleX, this.scaleY);
for (let i = activePoints.length - 1; i >= 0; i--) {
const p = activePoints[i];
if (i > 0 && p.h1x !== undefined) { const dx = p.h1x - x, dy = p.h1y - y; if (dx * dx + dy * dy <= r * r) return { index: i, type: 'h1' }; }
if (i < activePoints.length - 1 && p.h2x !== undefined) { const dx = p.h2x - x, dy = p.h2y - y; if (dx * dx + dy * dy <= r * r) return { index: i, type: 'h2' }; }
}
return null;
}
findSplineAt(x, y) {
const threshold = 15 / Math.min(this.scaleX, this.scaleY);
let bestDist = Infinity, bestIdx = -1;
for (let si = 0; si < this.splines.length; si++) {
const spline = this.splines[si];
if (spline.isSinglePoint || (spline.points && spline.points.length === 1)) {
const p = spline.points[0], d = Math.sqrt((p.x - x) ** 2 + (p.y - y) ** 2);
if (d < threshold && d < bestDist) { bestDist = d; bestIdx = si; }
continue;
}
const pathD = Interpolation.buildPathD(spline.points, this.interpolation, this.tension);
this.sampler.setPath(pathD);
const len = this.sampler.getTotalLength();
const steps = Math.min(200, Math.max(50, Math.round(len / 3)));
for (let i = 0; i <= steps; i++) {
const pt = this.sampler.getPointAtLength(len * i / steps);
const d = Math.sqrt((pt.x - x) ** 2 + (pt.y - y) ** 2);
if (d < threshold && d < bestDist) { bestDist = d; bestIdx = si; }
}
}
return bestIdx;
}
findClosestPoints(points, clickedPoint) {
if (points.length < 2) return null;
let distances = points.map((point, idx) => {
const dx = clickedPoint.x - point.x, dy = clickedPoint.y - point.y;
return { index: idx, distance: Math.sqrt(dx * dx + dy * dy) };
});
distances.sort((a, b) => a.distance - b.distance);
let i1 = distances[0].index, i2 = distances[1].index;
if (i1 > i2) [i1, i2] = [i2, i1];
return { point1Index: i1, point2Index: i2 };
}
// ─── Mouse Handlers ───
onMouseDown(e) {
const mouse = this.getLocalMouse(e);
const clamped = this.clamp(mouse.x, mouse.y);
const activeSpline = this.splines[this.activeSplineIndex];
const activePoints = activeSpline?.points;
if (e.shiftKey && e.button === 0 && activePoints) {
activePoints.push({ x: clamped.x, y: clamped.y });
this.render(); this.updatePath(); return;
}
if (e.ctrlKey && e.button === 0 && activePoints && activePoints.length >= 2) {
const closest = this.findClosestPoints(activePoints, clamped);
if (closest) {
const p1 = activePoints[closest.point1Index], p2 = activePoints[closest.point2Index];
activePoints.splice(closest.point2Index, 0, { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 });
this.render(); this.updatePath();
}
return;
}
if (e.button === 2) {
const ptIdx = this.findPointAt(mouse.x, mouse.y);
if (activePoints && ptIdx > 0 && ptIdx < activePoints.length - 1) {
activePoints.splice(ptIdx, 1); this.render(); this.updatePath(); return;
}
this.lastContextMenuPos = { x: clamped.x, y: clamped.y };
this.showContextMenu(e);
return;
}
if (e.button !== 0) return;
// Bezier handle drag
const handle = this.findHandleAt(mouse.x, mouse.y);
if (handle && activePoints) {
this.dragIndex = handle.index; this.dragType = handle.type;
const p = activePoints[handle.index];
const hx = handle.type === 'h1' ? p.h1x : p.h2x, hy = handle.type === 'h1' ? p.h1y : p.h2y;
this.dragOffset = { x: mouse.x - hx, y: mouse.y - hy };
this.render(); this.startDocumentDrag(e); return;
}
// Point drag
const ptIdx = this.findPointAt(mouse.x, mouse.y);
if (ptIdx >= 0) {
this.dragIndex = ptIdx; this.dragType = 'point'; this.hoverIndex = ptIdx;
const p = activePoints[ptIdx];
this.dragOffset = { x: mouse.x - p.x, y: mouse.y - p.y };
this.render(); this.startDocumentDrag(e); return;
}
// Spline selection
const splineIdx = this.findSplineAt(mouse.x, mouse.y);
if (splineIdx >= 0 && splineIdx !== this.activeSplineIndex) {
this.activeSplineIndex = splineIdx; this.render(); this.updatePath(); return;
}
}
onMouseMove(e) {
const mouse = this.getLocalMouse(e);
const clamped = this.clamp(mouse.x, mouse.y);
// Bezier handle drag
if ((this.dragType === 'h1' || this.dragType === 'h2') && this.dragIndex >= 0) {
const activePoints = this.splines[this.activeSplineIndex]?.points;
if (activePoints && this.dragIndex < activePoints.length) {
const p = activePoints[this.dragIndex];
const clampH = (hx, hy) => ({ x: Math.max(0, Math.min(this.coordWidth, hx)), y: Math.max(0, Math.min(this.coordHeight, hy)) });
const ox = this.dragOffset?.x || 0, oy = this.dragOffset?.y || 0;
const prevH1x = p.h1x, prevH1y = p.h1y, prevH2x = p.h2x, prevH2y = p.h2y;
if (this.dragType === 'h1') {
const c = clampH(mouse.x - ox, mouse.y - oy);
p.h1x = c.x; p.h1y = c.y;
if (!e.altKey) { const dx = p.x - p.h1x, dy = p.y - p.h1y; const mc = clampH(p.x + dx, p.y + dy); p.h2x = mc.x; p.h2y = mc.y; }
} else {
const c = clampH(mouse.x - ox, mouse.y - oy);
p.h2x = c.x; p.h2y = c.y;
if (!e.altKey) { const dx = p.x - p.h2x, dy = p.y - p.h2y; const mc = clampH(p.x + dx, p.y + dy); p.h1x = mc.x; p.h1y = mc.y; }
}
if (p.h1x === prevH1x && p.h1y === prevH1y && p.h2x === prevH2x && p.h2y === prevH2y) return;
this.render();
}
return;
}
// Point drag
if (this.dragType === 'point' && this.dragIndex >= 0) {
const activePoints = this.splines[this.activeSplineIndex]?.points;
if (activePoints && this.dragIndex < activePoints.length) {
const p = activePoints[this.dragIndex];
const ox = this.dragOffset?.x || 0, oy = this.dragOffset?.y || 0;
const target = this.clamp(mouse.x - ox, mouse.y - oy);
if (target.x === p.x && target.y === p.y) return;
const dx = target.x - p.x, dy = target.y - p.y;
if (this.interpolation === 'bezier' && p.h1x !== undefined) {
p.h1x += dx; p.h1y += dy; p.h2x += dx; p.h2y += dy;
}
p.x = target.x; p.y = target.y;
this.render();
}
return;
}
// Hover detection
if (!this.dragType) {
const ptIdx = this.findPointAt(mouse.x, mouse.y);
const activePoints = this.splines[this.activeSplineIndex]?.points;
// Ctrl preview
if (e.ctrlKey && activePoints && activePoints.length >= 2) {
const closest = this.findClosestPoints(activePoints, clamped);
if (closest) {
const p1 = activePoints[closest.point1Index], p2 = activePoints[closest.point2Index];
this.subdividePreview = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 };
this.canvas.style.cursor = 'copy'; this.render(); return;
}
} else if (this.subdividePreview) { this.subdividePreview = null; this.render(); }
// Handle hover
const handleHit = this.findHandleAt(mouse.x, mouse.y);
if (handleHit) { this.canvas.style.cursor = 'crosshair'; if (ptIdx !== this.hoverIndex) { this.hoverIndex = ptIdx; this.render(); } return; }
if (ptIdx !== this.hoverIndex) {
this.hoverIndex = ptIdx;
this.canvas.style.cursor = ptIdx >= 0 ? 'move' : 'default';
this.render();
}
// Spline hover
if (ptIdx < 0 && this.splines.length > 1) {
const splineIdx = this.findSplineAt(mouse.x, mouse.y);
const newSplineHover = splineIdx >= 0 && splineIdx !== this.activeSplineIndex ? splineIdx : -1;
if (newSplineHover !== this.hoverSplineIndex) {
this.hoverSplineIndex = newSplineHover;
this.canvas.style.cursor = newSplineHover >= 0 ? 'pointer' : 'default';
this.render();
}
} else if (this.hoverSplineIndex >= 0) { this.hoverSplineIndex = -1; this.render(); }
}
}
onMouseUp() {
if (this.dragType) {
this.endDrag();
this.updatePath();
}
}
// ─── Path Building & Sampling ───
samplePoints(splineIndex, numSamples, samplingMethod) {
const spline = this.splines[splineIndex];
if (!spline || !spline.points || spline.points.length < 2) return [];
if (spline.isSinglePoint) {
const point = spline.points[0];
return Array(numSamples).fill().map(() => ({ x: point.x, y: point.y }));
}
if (numSamples < 2) {
const p = spline.points[0];
return [{ x: p.x, y: p.y }];
}
const pathD = Interpolation.buildPathD(spline.points, this.interpolation, this.tension);
if (!pathD) return [];
this.sampler.setPath(pathD);
const pathLength = this.sampler.getTotalLength();
const points = [];
if (samplingMethod === "speed") {
if (pathLength < 0.001) return [{ x: spline.points[0].x, y: spline.points[0].y }];
const controlPoints = spline.points;
// Pair each control point with its path position, then sort together
const cpWithPos = controlPoints.map(cp => {
let bestDist = Infinity, bestPos = 0;
for (let pos = 0; pos <= pathLength; pos += pathLength / 100) {
const pt = this.sampler.getPointAtLength(pos);
const dist = Math.sqrt((pt.x - cp.x) ** 2 + (pt.y - cp.y) ** 2);
if (dist < bestDist) { bestDist = dist; bestPos = pos; }
}
return { cp, pos: bestPos };
});
cpWithPos.sort((a, b) => a.pos - b.pos);
const pathPositions = cpWithPos.map(c => c.pos);
const densities = [];
let totalWeight = 0;
for (let i = 0; i < cpWithPos.length - 1; i++) {
const segLength = pathPositions[i + 1] - pathPositions[i];
const d = 1 / Math.max(segLength, 0.0001);
densities.push(d);
totalWeight += d;
}
const cumulativeWeights = [];
let cum = 0;
for (let i = 0; i < densities.length; i++) {
cum += densities[i] / totalWeight;
cumulativeWeights.push(cum);
}
const mapToPath = (t) => {
if (t === 0) return 0; if (t === 1) return pathLength;
let segIdx = cumulativeWeights.length - 1;
for (let i = 0; i < cumulativeWeights.length; i++) { if (t <= cumulativeWeights[i]) { segIdx = i; break; } }
const segStart = segIdx > 0 ? cumulativeWeights[segIdx - 1] : 0;
const segT = (t - segStart) / (cumulativeWeights[segIdx] - segStart);
return pathPositions[segIdx] + segT * (pathPositions[segIdx + 1] - pathPositions[segIdx]);
};
for (let i = 0; i < numSamples; i++) {
const pt = this.sampler.getPointAtLength(mapToPath(i / (numSamples - 1)));
points.push({ x: pt.x, y: pt.y });
}
return points;
}
for (let i = 0; i < numSamples; i++) {
let point;
if (samplingMethod === "time") {
point = this.sampler.findPointAtX((this.coordWidth / (numSamples - 1)) * i, pathLength);
} else {
point = this.sampler.getPointAtLength((pathLength / (numSamples - 1)) * i);
}
points.push({ x: point.x, y: point.y });
}
if (points.length > 0 && spline.points.length > 1) {
points[points.length - 1].y = spline.points[spline.points.length - 1].y;
}
return points;
}
updatePath(allDirty = false) {
if (!this.splines || this.splines.length === 0) return;
// Rebuild cache when spline count changes or full refresh requested
if (!this._sampledCache || this._sampledCache.length !== this.splines.length || allDirty) {
this._sampledCache = new Array(this.splines.length).fill(null);
}
const method = this.samplingMethod;
const useControlPoints = method === "controlpoints";
for (let i = 0; i < this.splines.length; i++) {
if (useControlPoints) {
this._sampledCache[i] = this.splines[i].points;
} else if (i === this.activeSplineIndex || !this._sampledCache[i]) {
this._sampledCache[i] = this.samplePoints(i, this.points_to_sample, method);
}
}
this.sampledCoords = this._sampledCache[this.activeSplineIndex] || [];
this.pointsStoreWidget.value = JSON.stringify(this.splines);
if (this.coordWidget) this.coordWidget.value = JSON.stringify(this._sampledCache);
this.render();
}
// ─── Rendering ───
_render() {
const ctx = this.ctx;
const h = this.coordHeight;
this.beginRender();
// Ruler lines
if (this.drawRuler && !this.bgImage) {
ctx.strokeStyle = 'rgba(128,128,128,0.3)'; ctx.lineWidth = 1;
for (let y = 64; y < h; y += 64) {
const cy = y * this.scaleY;
ctx.beginPath(); ctx.moveTo(0, cy); ctx.lineTo(this.width, cy); ctx.stroke();
}
}
const tc = (x, y) => this.toCanvas(x, y);
// Draw all splines — use scale transform for curves, toCanvas for discrete elements
for (let si = 0; si < this.splines.length; si++) {
const spline = this.splines[si];
const isActive = si === this.activeSplineIndex, isHover = si === this.hoverSplineIndex;
if (spline.isSinglePoint || (spline.points && spline.points.length === 1)) {
const cp = tc(spline.points[0].x, spline.points[0].y), sz = isActive ? 8 : 6;
ctx.fillStyle = spline.color; ctx.fillRect(cp.x - sz, cp.y - sz, sz * 2, sz * 2);
ctx.strokeStyle = 'black'; ctx.lineWidth = 2; ctx.strokeRect(cp.x - sz, cp.y - sz, sz * 2, sz * 2);
continue;
}
if (spline.points.length < 2) continue;
// Build path once, stroke twice (outline + color) to avoid recomputing interpolation
const pathD = Interpolation.buildPathD(spline.points, this.interpolation, this.tension);
const curvePath = new Path2D(pathD);
ctx.save(); ctx.scale(this.scaleX, this.scaleY);
ctx.lineWidth = (isActive ? 5 : isHover ? 4 : 3.5) / Math.min(this.scaleX, this.scaleY); ctx.strokeStyle = 'black';
ctx.stroke(curvePath);
ctx.lineWidth = (isActive ? 3 : isHover ? 2 : 1.5) / Math.min(this.scaleX, this.scaleY); ctx.strokeStyle = spline.color;
ctx.stroke(curvePath);
ctx.restore();
}
const activeSpline = this.splines[this.activeSplineIndex];
// Handle lines
if (this.drawHandles) {
const activePoints = this.splines[this.activeSplineIndex]?.points;
if (activePoints && activePoints.length >= 2) {
ctx.strokeStyle = '#ff7f0e'; ctx.lineWidth = 1; ctx.beginPath();
const c0 = tc(activePoints[0].x, activePoints[0].y);
ctx.moveTo(c0.x, c0.y);
for (let i = 1; i < activePoints.length; i++) { const ci = tc(activePoints[i].x, activePoints[i].y); ctx.lineTo(ci.x, ci.y); }
ctx.stroke();
}
}
// Control points for active spline
if (activeSpline && activeSpline.points && !activeSpline.isSinglePoint) {
const dotRadius = 12;
for (let i = 0; i < activeSpline.points.length; i++) {
const p = activeSpline.points[i];
const cp = tc(p.x, p.y);
const isHovered = this.hoverIndex === i;
ctx.fillStyle = 'rgba(100, 100, 100, 0.3)';
ctx.strokeStyle = isHovered ? '#ff7f0e' : '#1f77b4'; ctx.lineWidth = 2;
ctx.beginPath(); ctx.arc(cp.x, cp.y, dotRadius, 0, Math.PI * 2); ctx.fill(); ctx.stroke();
// Chevron
const isEndpoint = i === 0 || i === activeSpline.points.length - 1;
const showChevron = this.showChevrons && (
(this.samplingMethod === 'path' || this.samplingMethod === 'speed')
|| (this.samplingMethod === 'time' && isEndpoint));
if (showChevron && activeSpline.points.length > 1) {
let angle = 0;
if (i > 0 && i < activeSpline.points.length - 1) { const prev = activeSpline.points[i-1], next = activeSpline.points[i+1]; angle = Math.atan2((next.y - prev.y) * this.scaleY, (next.x - prev.x) * this.scaleX); }
else if (i === 0) { const next = activeSpline.points[1]; angle = Math.atan2((next.y - p.y) * this.scaleY, (next.x - p.x) * this.scaleX); }
else { const prev = activeSpline.points[i-1]; angle = Math.atan2((p.y - prev.y) * this.scaleY, (p.x - prev.x) * this.scaleX); }
ctx.save();
ctx.translate(cp.x, cp.y);
ctx.rotate(angle);
ctx.strokeStyle = isHovered ? '#fff' : 'rgba(255,255,255,0.7)';
ctx.lineWidth = 2.5; ctx.lineCap = 'round'; ctx.lineJoin = 'round';
ctx.beginPath();
ctx.moveTo(-dotRadius * 0.2, -dotRadius * 0.35);
ctx.lineTo(dotRadius * 0.3, 0);
ctx.lineTo(-dotRadius * 0.2, dotRadius * 0.35);
ctx.stroke();
ctx.lineCap = 'butt'; ctx.lineJoin = 'miter';
ctx.restore();
}
if (isHovered) {
ctx.font = '11px monospace';
const label = `${i}: (${Math.round(p.x)}, ${Math.round(p.y)})`;
ctx.strokeStyle = '#000'; ctx.lineWidth = 3; ctx.strokeText(label, cp.x + dotRadius + 5, cp.y - 5);
ctx.fillStyle = '#fff'; ctx.fillText(label, cp.x + dotRadius + 5, cp.y - 5);
}
}
}
// Bezier handles
if (this.interpolation === 'bezier' && activeSpline && activeSpline.points && !activeSpline.isSinglePoint) {
const pts = activeSpline.points;
Interpolation.ensureBezierHandles(pts);
const hr = 5;
for (let i = 0; i < pts.length; i++) {
const p = pts[i];
const cp = tc(p.x, p.y);
if (i > 0 && p.h1x !== undefined) {
const h1 = tc(p.h1x, p.h1y);
ctx.strokeStyle = 'rgba(255,255,255,0.4)'; ctx.lineWidth = 1;
ctx.beginPath(); ctx.moveTo(cp.x, cp.y); ctx.lineTo(h1.x, h1.y); ctx.stroke();
ctx.fillStyle = (this.dragType === 'h1' && this.dragIndex === i) ? '#fff' : 'rgba(255,255,255,0.8)';
ctx.strokeStyle = '#1f77b4'; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.arc(h1.x, h1.y, hr, 0, Math.PI * 2); ctx.fill(); ctx.stroke();
}
if (i < pts.length - 1 && p.h2x !== undefined) {
const h2 = tc(p.h2x, p.h2y);
ctx.strokeStyle = 'rgba(255,255,255,0.4)'; ctx.lineWidth = 1;
ctx.beginPath(); ctx.moveTo(cp.x, cp.y); ctx.lineTo(h2.x, h2.y); ctx.stroke();
ctx.fillStyle = (this.dragType === 'h2' && this.dragIndex === i) ? '#fff' : 'rgba(255,255,255,0.8)';
ctx.strokeStyle = '#ff7f0e'; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.arc(h2.x, h2.y, hr, 0, Math.PI * 2); ctx.fill(); ctx.stroke();
}
}
}
// Sample points
if (this.drawSamplePoints && this.sampledCoords) {
ctx.fillStyle = 'red'; ctx.strokeStyle = 'black'; ctx.lineWidth = 1;
for (const pt of this.sampledCoords) { const cp = tc(pt.x, pt.y); ctx.beginPath(); ctx.arc(cp.x, cp.y, 5, 0, Math.PI * 2); ctx.fill(); ctx.stroke(); }
}
// Subdivide preview
if (this.subdividePreview) {
const sp = tc(this.subdividePreview.x, this.subdividePreview.y);
ctx.beginPath(); ctx.arc(sp.x, sp.y, 10, 0, Math.PI * 2);
ctx.strokeStyle = 'rgba(0,255,0,0.3)'; ctx.lineWidth = 4; ctx.stroke();
ctx.beginPath(); ctx.arc(sp.x, sp.y, 8, 0, Math.PI * 2);
ctx.strokeStyle = '#0f0'; ctx.lineWidth = 2; ctx.stroke();
}
this.endRender();
}
}12345678910111213141516171819202122232425262728293031import { chainCallback } from './utility.js';
const { app } = window.comfyAPI.app;
const { api } = window.comfyAPI.api;
app.registerExtension({
name: 'KJNodes.FastPreview',
async beforeRegisterNodeDef(nodeType, nodeData) {
if (nodeData?.name === 'FastPreview') {
chainCallback(nodeType.prototype, "onNodeCreated", function () {
this.setSize([550, 550]);
const nodeRef = this;
api.addEventListener("b_preview_with_metadata", function (event) {
const { blob, nodeId, displayNodeId } = event.detail;
const targetId = String(displayNodeId || nodeId);
if (targetId !== String(nodeRef.id)) return;
const img = new Image();
img.onload = () => {
nodeRef.imgs = [img];
nodeRef.setDirtyCanvas(true);
};
img.src = URL.createObjectURL(blob);
});
});
}
}
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218const { app } = window.comfyAPI.app;
import { getSlotPos } from "./utility.js";
/**
* Check type compatibility. Returns a match tier:
* 2 = exact single-type match, 1 = multi-type or wildcard match, -1 = incompatible
*/
function typeMatchTier(outType, inType) {
if (!LiteGraph.isValidConnection(outType, inType)) return -1;
if (typeof outType === "string" && typeof inType === "string"
&& !outType.includes(",") && !inType.includes(",")
&& outType.toUpperCase() === inType.toUpperCase()) return 2;
return 1;
}
/**
* Order selected nodes for connection.
* Respects existing links between them (topological sort),
* then inserts unconnected nodes by spatial position (left-to-right, top-to-bottom).
*/
function orderNodes(nodes, graph) {
const selectedIds = new Set(nodes.map(n => n.id));
const nodeById = new Map(nodes.map(n => [n.id, n]));
const outEdges = new Map();
const inDegree = new Map();
for (const n of nodes) {
outEdges.set(n.id, new Set());
inDegree.set(n.id, 0);
}
for (const node of nodes) {
for (const out of (node.outputs || [])) {
for (const linkId of (out.links || [])) {
const link = graph.getLink(linkId);
if (link && selectedIds.has(link.target_id) && link.target_id !== node.id) {
if (!outEdges.get(node.id).has(link.target_id)) {
outEdges.get(node.id).add(link.target_id);
inDegree.set(link.target_id, inDegree.get(link.target_id) + 1);
}
}
}
}
}
const bySpatial = (a, b) => a.pos[0] - b.pos[0] || a.pos[1] - b.pos[1];
const queue = nodes.filter(n => inDegree.get(n.id) === 0);
queue.sort(bySpatial);
const ordered = [];
while (queue.length > 0) {
const node = queue.shift();
ordered.push(node);
for (const targetId of outEdges.get(node.id)) {
const deg = inDegree.get(targetId) - 1;
inDegree.set(targetId, deg);
if (deg === 0 && nodeById.has(targetId)) {
queue.push(nodeById.get(targetId));
queue.sort(bySpatial);
}
}
}
// Cycle fallback: append remaining by position
if (ordered.length < nodes.length) {
const inOrdered = new Set(ordered.map(n => n.id));
const remaining = nodes.filter(n => !inOrdered.has(n.id));
remaining.sort(bySpatial);
ordered.push(...remaining);
}
return ordered;
}
/**
* Collect all candidate connections and assign globally by closest 2D distance.
* Each input and output is used at most once per invocation.
*/
function planConnections(ordered) {
// Collect all candidates globally across all target nodes
const candidates = [];
for (let b = 1; b < ordered.length; b++) {
const nodeB = ordered[b];
if (!nodeB.inputs) continue;
for (let inIdx = 0; inIdx < nodeB.inputs.length; inIdx++) {
const inp = nodeB.inputs[inIdx];
if (inp.link != null) continue;
const inPos = getSlotPos(nodeB, true, inIdx);
const inputCandidates = [];
let hasExact = false;
for (let a = b - 1; a >= 0; a--) {
const nodeA = ordered[a];
if (!nodeA.outputs) continue;
for (let outIdx = 0; outIdx < nodeA.outputs.length; outIdx++) {
const tier = typeMatchTier(nodeA.outputs[outIdx].type, inp.type);
if (tier < 0) continue;
if (tier === 2) hasExact = true;
const outPos = getSlotPos(nodeA, false, outIdx);
const dx = outPos[0] - inPos[0];
const dy = outPos[1] - inPos[1];
inputCandidates.push({
targetNode: nodeB,
inIdx,
sourceNode: nodeA,
outIdx,
tier,
dist: dx * dx + dy * dy,
});
}
}
for (const c of inputCandidates) {
c.hasExact = hasExact;
}
candidates.push(...inputCandidates);
}
}
// Filter out non-exact matches for inputs that have an exact candidate
const filtered = candidates.filter(c => c.tier === 2 || !c.hasExact);
// Sort globally: higher tier first, then closest pair
filtered.sort((x, y) => (y.tier - x.tier) || (x.dist - y.dist));
// Greedy global assignment — closest pairs first
const planned = [];
const usedInputs = new Set();
const usedOutputs = new Set();
for (const c of filtered) {
const inKey = `${c.targetNode.id}:${c.inIdx}`;
if (usedInputs.has(inKey)) continue;
const outKey = `${c.sourceNode.id}:${c.outIdx}`;
if (usedOutputs.has(outKey)) continue;
planned.push({
sourceNode: c.sourceNode,
outIdx: c.outIdx,
targetNode: c.targetNode,
inIdx: c.inIdx,
});
usedInputs.add(inKey);
usedOutputs.add(outKey);
}
return planned;
}
function connectPlanned(planned, graph) {
for (const p of planned) {
p.sourceNode.connect(p.outIdx, p.targetNode, p.inIdx);
}
graph.change();
}
function fillConnectSelected() {
if (!app.ui.settings.getSettingValue("KJNodes.fillConnectEnabled")) return;
const canvas = app.canvas;
const graph = canvas.graph;
const nodes = Object.values(canvas.selected_nodes || {});
if (nodes.length < 2) return;
const ordered = orderNodes(nodes, graph);
const planned = planConnections(ordered);
if (planned.length > 0) {
connectPlanned(planned, graph);
}
if (app.extensionManager?.toast) {
app.extensionManager.toast.add({
severity: planned.length > 0 ? "info" : "warn",
summary: planned.length > 0
? `Connected ${planned.length} link${planned.length > 1 ? "s" : ""}`
: "No compatible connections found",
life: 2000,
});
}
}
app.registerExtension({
name: "KJNodes.FillConnect",
settings: [
{
id: "KJNodes.fillConnectEnabled",
name: "Enable Fill-Connect hotkey",
category: ["KJNodes", "Fill-Connect"],
tooltip: "Fill-connect selected nodes by compatible types",
type: "boolean",
defaultValue: true,
},
],
commands: [
{
id: "KJNodes.fillConnectSelected",
label: "Fill-Connect Selected Nodes",
function: fillConnectSelected,
},
],
keybindings: [
{
commandId: "KJNodes.fillConnectSelected",
combo: { key: "f" },
targetElementId: "graph-canvas",
},
],
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468const { app } = window.comfyAPI.app;
// code based on mtb nodes by Mel Massadian https://github.com/melMass/comfy_mtb/
export const loadScript = (
FILE_URL,
async = true,
type = 'text/javascript',
) => {
return new Promise((resolve, reject) => {
try {
// Check if the script already exists
const existingScript = document.querySelector(`script[src="${FILE_URL}"]`)
if (existingScript) {
resolve({ status: true, message: 'Script already loaded' })
return
}
const scriptEle = document.createElement('script')
scriptEle.type = type
scriptEle.async = async
scriptEle.src = FILE_URL
scriptEle.addEventListener('load', (ev) => {
resolve({ status: true })
})
scriptEle.addEventListener('error', (ev) => {
reject({
status: false,
message: `Failed to load the script ${FILE_URL}`,
})
})
document.body.appendChild(scriptEle)
} catch (error) {
reject(error)
}
})
}
loadScript('kjweb_async/marked.min.js').catch((e) => {
console.error(e)
})
loadScript('kjweb_async/purify.min.js').catch((e) => {
console.error(e)
})
const categories = ["KJNodes", "SUPIR", "VoiceCraft", "Marigold", "IC-Light", "WanVideoWrapper"];
const nodeDescriptions = new Map();
function isHelpPopupEnabled() {
return app.ui.settings.getSettingValue("KJNodes.helpPopup") !== false;
}
app.registerExtension({
name: "KJNodes.HelpPopup",
async beforeRegisterNodeDef(nodeType, nodeData) {
if (!isHelpPopupEnabled()) return;
try {
categories.forEach(category => {
if (nodeData?.category?.startsWith(category)) {
if (nodeData.description) {
nodeDescriptions.set(nodeData.name, nodeData.description);
}
addDocumentation(nodeData, nodeType);
}
else return
});
} catch (error) {
console.error("Error in registering KJNodes.HelpPopup", error);
}
},
nodeCreated(node) {
if (!isHelpPopupEnabled()) return;
const description = nodeDescriptions.get(node.type) || nodeDescriptions.get(node.comfyClass);
if (!description) return;
node._kjHelpDescription = description;
},
setup() {
if (!isHelpPopupEnabled()) return;
setupHelpObserver();
},
});
const create_documentation_stylesheet = () => {
const tag = 'kj-documentation-stylesheet'
let styleTag = document.getElementById(tag)
if (!styleTag) {
styleTag = document.createElement('style')
styleTag.type = 'text/css'
styleTag.id = tag
styleTag.innerHTML = `
.kj-documentation-popup {
background: var(--comfy-menu-bg);
position: absolute;
color: var(--fg-color);
font: 12px monospace;
line-height: 1.5em;
padding: 10px;
border-radius: 10px;
border-style: solid;
border-width: medium;
border-color: var(--border-color);
z-index: 5;
overflow: hidden;
}
.content-wrapper {
overflow: auto;
max-height: 100%;
/* Scrollbar styling for Chrome */
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: var(--bg-color);
}
&::-webkit-scrollbar-thumb {
background-color: var(--fg-color);
border-radius: 6px;
border: 3px solid var(--bg-color);
}
/* Scrollbar styling for Firefox */
scrollbar-width: thin;
scrollbar-color: var(--fg-color) var(--bg-color);
a {
color: yellow;
}
a:visited {
color: orange;
}
a:hover {
color: red;
}
}
`
document.head.appendChild(styleTag)
}
}
/**
* Creates the documentation popup DOM and wires up resize/close interactions.
* Returns { docElement, contentWrapper }.
* @param {string} description - Markdown description text
* @param {AbortSignal} signal - Signal to clean up event listeners
* @param {() => void} onClose - Called when the close button is clicked
* @param {{ scaleResize: boolean }} opts - If scaleResize is true, resize deltas are divided by canvas scale
*/
function createDocPopup(description, signal, onClose, opts = {}) {
create_documentation_stylesheet()
const docElement = document.createElement('div')
const contentWrapper = document.createElement('div')
docElement.appendChild(contentWrapper)
contentWrapper.classList.add('content-wrapper')
docElement.classList.add('kj-documentation-popup')
// Try ComfyUI's built-in markdown renderer first (available after frontend PR #10700)
if (app.extensionManager?.renderMarkdownToHtml) {
contentWrapper.innerHTML = app.extensionManager.renderMarkdownToHtml(description)
} else if (typeof marked !== 'undefined' && typeof DOMPurify !== 'undefined') {
contentWrapper.innerHTML = DOMPurify.sanitize(marked.parse(description))
} else {
// Fallback: convert markdown links to <a> tags, auto-link bare URLs, preserve line breaks
const escaped = description
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
.replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g, '<a href="$2" target="_blank">$1</a>')
.replace(/(^|[^"'])(https?:\/\/[^\s<]+)/g, '$1<a href="$2" target="_blank">$2</a>')
.replace(/\n/g, '<br>')
contentWrapper.innerHTML = escaped
}
// resize handle
const resizeHandle = document.createElement('div')
resizeHandle.style.width = '0'
resizeHandle.style.height = '0'
resizeHandle.style.position = 'absolute'
resizeHandle.style.bottom = '0'
resizeHandle.style.right = '0'
resizeHandle.style.cursor = 'se-resize'
const borderColor = getComputedStyle(document.documentElement).getPropertyValue('--border-color').trim()
resizeHandle.style.borderTop = '10px solid transparent'
resizeHandle.style.borderLeft = '10px solid transparent'
resizeHandle.style.borderBottom = `10px solid ${borderColor}`
resizeHandle.style.borderRight = `10px solid ${borderColor}`
docElement.appendChild(resizeHandle)
let isResizing = false
let startX, startY, startWidth, startHeight
resizeHandle.addEventListener('mousedown', (e) => {
e.preventDefault()
e.stopPropagation()
isResizing = true
startX = e.clientX
startY = e.clientY
startWidth = parseInt(document.defaultView.getComputedStyle(docElement).width, 10)
startHeight = parseInt(document.defaultView.getComputedStyle(docElement).height, 10)
}, { signal })
document.addEventListener('mousemove', (e) => {
if (!isResizing) return
const scaleFactor = opts.scaleResize ? app.canvas.ds.scale : 1
const newWidth = startWidth + (e.clientX - startX) / scaleFactor
const newHeight = startHeight + (e.clientY - startY) / scaleFactor
docElement.style.width = `${newWidth}px`
docElement.style.height = `${newHeight}px`
}, { signal })
document.addEventListener('mouseup', () => {
isResizing = false
}, { signal })
// close button
const closeButton = document.createElement('div')
closeButton.textContent = '❌'
closeButton.style.position = 'absolute'
closeButton.style.top = '0'
closeButton.style.right = '0'
closeButton.style.cursor = 'pointer'
closeButton.style.padding = '5px'
closeButton.style.color = 'red'
closeButton.style.fontSize = '12px'
docElement.appendChild(closeButton)
closeButton.addEventListener('mousedown', (e) => {
e.stopPropagation()
onClose()
}, { signal })
document.body.appendChild(docElement)
return { docElement, contentWrapper }
}
// ─── Legacy canvas mode (onDrawForeground) ───
/** Add documentation widget to the selected node (legacy canvas rendering) */
export const addDocumentation = (
nodeData,
nodeType,
opts = { icon_size: 14, icon_margin: 4 },) => {
opts = opts || {}
const iconSize = opts.icon_size ? opts.icon_size : 14
const iconMargin = opts.icon_margin ? opts.icon_margin : 4
let docElement = null
let contentWrapper = null
if (!nodeData.description) {
return
}
const drawFg = nodeType.prototype.onDrawForeground
nodeType.prototype.onDrawForeground = function (ctx) {
const r = drawFg ? drawFg.apply(this, arguments) : undefined
if (this.flags.collapsed) return r
const x = this.size[0] - iconSize - iconMargin
// create the popup
if (this.show_doc && docElement === null) {
const popup = createDocPopup(
nodeData.description,
this.docCtrl.signal,
() => {
this.show_doc = !this.show_doc
docElement.parentNode.removeChild(docElement)
docElement = null
contentWrapper = null
},
{ scaleResize: true }
)
docElement = popup.docElement
contentWrapper = popup.contentWrapper
}
// close the popup
else if (!this.show_doc && docElement !== null) {
docElement.parentNode.removeChild(docElement)
docElement = null
}
// update position of the popup
if (this.show_doc && docElement !== null) {
const rect = ctx.canvas.getBoundingClientRect()
const scaleX = rect.width / ctx.canvas.width
const scaleY = rect.height / ctx.canvas.height
const transform = new DOMMatrix()
.scaleSelf(scaleX, scaleY)
.multiplySelf(ctx.getTransform())
.translateSelf(this.size[0] * scaleX * Math.max(1.0,window.devicePixelRatio) , 0)
.translateSelf(10, -32)
const scale = new DOMMatrix()
.scaleSelf(transform.a, transform.d);
const bcr = app.canvas.canvas.getBoundingClientRect()
const styleObject = {
transformOrigin: '0 0',
transform: scale,
left: `${transform.a + bcr.x + transform.e}px`,
top: `${transform.d + bcr.y + transform.f}px`,
};
Object.assign(docElement.style, styleObject);
}
ctx.save()
ctx.translate(x - 2, iconSize - 34)
ctx.scale(iconSize / 32, iconSize / 32)
ctx.strokeStyle = 'rgba(255,255,255,0.3)'
ctx.lineCap = 'round'
ctx.lineJoin = 'round'
ctx.lineWidth = 2.4
ctx.font = 'bold 36px monospace'
ctx.fillStyle = 'orange';
ctx.fillText('?', 0, 24)
ctx.restore()
return r
}
// handle clicking of the icon
const mouseDown = nodeType.prototype.onMouseDown
nodeType.prototype.onMouseDown = function (e, localPos, canvas) {
const r = mouseDown ? mouseDown.apply(this, arguments) : undefined
const iconX = this.size[0] - iconSize - iconMargin
const iconY = iconSize - 34
if (
localPos[0] > iconX &&
localPos[0] < iconX + iconSize &&
localPos[1] > iconY &&
localPos[1] < iconY + iconSize
) {
if (this.show_doc === undefined) {
this.show_doc = true
} else {
this.show_doc = !this.show_doc
}
if (this.show_doc) {
this.docCtrl = new AbortController()
} else {
this.docCtrl.abort()
}
return true;
}
return r;
}
const onRem = nodeType.prototype.onRemoved
nodeType.prototype.onRemoved = function () {
const r = onRem ? onRem.apply(this, []) : undefined
if (docElement) {
docElement.remove()
docElement = null
contentWrapper = null
}
return r
}
}
// ─── Vue nodes mode (DOM injection via MutationObserver) ───
/** Per-node popup state, keyed by node ID */
const popupState = new Map()
function getNodeById(nodeId) {
return app.graph?.getNodeById(nodeId)
}
function closeNodePopup(nodeId) {
const state = popupState.get(nodeId)
if (!state) return
if (state.docElement) {
state.docElement.remove()
}
if (state.abortCtrl) {
state.abortCtrl.abort()
}
if (state.animFrame) {
cancelAnimationFrame(state.animFrame)
}
popupState.delete(nodeId)
}
function openNodePopup(nodeId, description) {
closeNodePopup(nodeId)
const state = popupState.get(nodeId) || {}
popupState.set(nodeId, state)
state.abortCtrl = new AbortController()
const popup = createDocPopup(
description,
state.abortCtrl.signal,
() => closeNodePopup(nodeId),
{ scaleResize: false }
)
state.docElement = popup.docElement
function updatePosition() {
if (!state.docElement || !state.docElement.parentNode) return
const nodeEl = document.querySelector(`[data-node-id="${nodeId}"]`)
if (nodeEl) {
const rect = nodeEl.getBoundingClientRect()
state.docElement.style.left = `${rect.right + 10}px`
state.docElement.style.top = `${rect.top}px`
}
state.animFrame = requestAnimationFrame(updatePosition)
}
state.animFrame = requestAnimationFrame(updatePosition)
}
/** Try to inject a "?" button into a Vue node header */
function tryInjectHelpButton(header) {
if (header.querySelector('.kj-help-btn')) return
const nodeEl = header.closest('[data-node-id]')
if (!nodeEl) return
const nodeId = nodeEl.dataset.nodeId
const node = getNodeById(nodeId)
if (!node) return
const description = node._kjHelpDescription
if (!description) return
const flexContainer = header.querySelector(':scope > div')
if (!flexContainer) return
const helpBtn = document.createElement('span')
helpBtn.className = 'kj-help-btn'
helpBtn.textContent = '?'
helpBtn.style.cssText = `
color: orange;
font-weight: bold;
font-size: 14px;
cursor: pointer;
flex-shrink: 0;
padding: 0 4px;
line-height: 1;
user-select: none;
`
helpBtn.title = 'Show help'
helpBtn.addEventListener('click', (e) => {
e.stopPropagation()
const state = popupState.get(nodeId)
if (state?.docElement) {
closeNodePopup(nodeId)
} else {
openNodePopup(nodeId, description)
}
})
flexContainer.appendChild(helpBtn)
}
/** Observe the DOM for Vue node headers appearing and inject help buttons */
function setupHelpObserver() {
// Inject into any headers already in the DOM
document.querySelectorAll('.lg-node-header').forEach(tryInjectHelpButton)
let pending = false
const observer = new MutationObserver(() => {
if (pending) return
pending = true
requestAnimationFrame(() => {
pending = false
document.querySelectorAll('.lg-node-header:not(:has(.kj-help-btn))').forEach(tryInjectHelpButton)
})
})
observer.observe(document.body, { childList: true, subtree: true })
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402const { app } = window.comfyAPI.app;
const { applyTextReplacements } = window.comfyAPI.utils;
app.registerExtension({
name: "KJNodes.jsnodes",
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if(!nodeData?.category?.startsWith("KJNodes")) {
return;
}
switch (nodeData.name) {
case "ConditioningMultiCombine":
nodeType.prototype.onNodeCreated = function () {
this._type = "CONDITIONING"
this.inputs_offset = nodeData.name.includes("selective")?1:0
this.addWidget("button", "Update inputs", null, () => {
if (!this.inputs) {
this.inputs = [];
}
const target_number_of_inputs = this.widgets.find(w => w.name === "inputcount")["value"];
const num_inputs = this.inputs.filter(input => input.type === this._type).length
if(target_number_of_inputs===num_inputs)return; // already set, do nothing
if(target_number_of_inputs < num_inputs){
const inputs_to_remove = num_inputs - target_number_of_inputs;
for(let i = 0; i < inputs_to_remove; i++) {
this.removeInput(this.inputs.length - 1);
}
}
else{
for(let i = num_inputs+1; i <= target_number_of_inputs; ++i)
this.addInput(`conditioning_${i}`, this._type)
}
});
}
break;
case "ImageBatchMulti":
case "ImageAddMulti":
case "ImageConcatMulti":
case "CrossFadeImagesMulti":
case "TransitionImagesMulti":
nodeType.prototype.onNodeCreated = function () {
this._type = "IMAGE"
this.addWidget("button", "Update inputs", null, () => {
if (!this.inputs) {
this.inputs = [];
}
const target_number_of_inputs = this.widgets.find(w => w.name === "inputcount")["value"];
const num_inputs = this.inputs.filter(input => input.type === this._type).length
if(target_number_of_inputs===num_inputs)return; // already set, do nothing
if(target_number_of_inputs < num_inputs){
const inputs_to_remove = num_inputs - target_number_of_inputs;
for(let i = 0; i < inputs_to_remove; i++) {
this.removeInput(this.inputs.length - 1);
}
}
else{
for(let i = num_inputs+1; i <= target_number_of_inputs; ++i)
this.addInput(`image_${i}`, this._type, {shape: 7});
}
});
}
break;
case "MaskBatchMulti":
nodeType.prototype.onNodeCreated = function () {
this._type = "MASK"
this.addWidget("button", "Update inputs", null, () => {
if (!this.inputs) {
this.inputs = [];
}
const target_number_of_inputs = this.widgets.find(w => w.name === "inputcount")["value"];
const num_inputs = this.inputs.filter(input => input.type === this._type).length
if(target_number_of_inputs===num_inputs)return; // already set, do nothing
if(target_number_of_inputs < num_inputs){
const inputs_to_remove = num_inputs - target_number_of_inputs;
for(let i = 0; i < inputs_to_remove; i++) {
this.removeInput(this.inputs.length - 1);
}
}
else{
for(let i = num_inputs+1; i <= target_number_of_inputs; ++i)
this.addInput(`mask_${i}`, this._type)
}
});
}
break;
case "FluxBlockLoraSelect":
case "HunyuanVideoBlockLoraSelect":
case "Wan21BlockLoraSelect":
case "LTX2BlockLoraSelect":
nodeType.prototype.onNodeCreated = function () {
this.addWidget("button", "Set all", null, () => {
const userInput = prompt("Enter the values to set for widgets (e.g., s0,1,2-7=2.0, d0,1,2-7=2.0, or 1.0):", "");
if (userInput) {
const regex = /([sd])?(\d+(?:,\d+|-?\d+)*?)?=(\d+(\.\d+)?)/;
const match = userInput.match(regex);
if (match) {
const type = match[1];
const indicesPart = match[2];
const value = parseFloat(match[3]);
let targetWidgets = [];
if (type === 's') {
targetWidgets = this.widgets.filter(widget => widget.name.includes("single"));
} else if (type === 'd') {
targetWidgets = this.widgets.filter(widget => widget.name.includes("double"));
} else {
targetWidgets = this.widgets; // No type specified, all widgets
}
if (indicesPart) {
const indices = indicesPart.split(',').flatMap(part => {
if (part.includes('-')) {
const [start, end] = part.split('-').map(Number);
return Array.from({ length: end - start + 1 }, (_, i) => start + i);
}
return Number(part);
});
for (const index of indices) {
if (index < targetWidgets.length) {
targetWidgets[index].value = value;
}
}
} else {
// No indices provided, set value for all target widgets
for (const widget of targetWidgets) {
widget.value = value;
}
}
} else if (!isNaN(parseFloat(userInput))) {
// Single value provided, set it for all widgets
const value = parseFloat(userInput);
for (const widget of this.widgets) {
widget.value = value;
}
} else {
alert("Invalid input format. Please use the format s0,1,2-7=2.0, d0,1,2-7=2.0, or 1.0");
}
} else {
alert("Invalid input. Please enter a value.");
}
});
};
break;
case "GetMaskSizeAndCount":
const onGetMaskSizeConnectInput = nodeType.prototype.onConnectInput;
nodeType.prototype.onConnectInput = function (targetSlot, type, output, originNode, originSlot) {
const v = onGetMaskSizeConnectInput? onGetMaskSizeConnectInput.apply(this, arguments): undefined
this.outputs[1]["label"] = "width"
this.outputs[2]["label"] = "height"
this.outputs[3]["label"] = "count"
return v;
}
const onGetMaskSizeExecuted = nodeType.prototype.onAfterExecuteNode;
nodeType.prototype.onExecuted = function(message) {
const r = onGetMaskSizeExecuted? onGetMaskSizeExecuted.apply(this,arguments): undefined
let values = message["text"].toString().split('x').map(Number);
this.outputs[1]["label"] = values[1] + " width"
this.outputs[2]["label"] = values[2] + " height"
this.outputs[3]["label"] = values[0] + " count"
return r
}
break;
case "GetImageSizeAndCount":
const onGetImageSizeConnectInput = nodeType.prototype.onConnectInput;
nodeType.prototype.onConnectInput = function (targetSlot, type, output, originNode, originSlot) {
console.log(this)
const v = onGetImageSizeConnectInput? onGetImageSizeConnectInput.apply(this, arguments): undefined
//console.log(this)
this.outputs[1]["label"] = "width"
this.outputs[2]["label"] = "height"
this.outputs[3]["label"] = "count"
return v;
}
//const onGetImageSizeExecuted = nodeType.prototype.onExecuted;
const onGetImageSizeExecuted = nodeType.prototype.onAfterExecuteNode;
nodeType.prototype.onExecuted = function(message) {
console.log(this)
const r = onGetImageSizeExecuted? onGetImageSizeExecuted.apply(this,arguments): undefined
let values = message["text"].toString().split('x').map(Number);
console.log(values)
this.outputs[1]["label"] = values[1] + " width"
this.outputs[2]["label"] = values[2] + " height"
this.outputs[3]["label"] = values[0] + " count"
return r
}
break;
case "GetLatentSizeAndCount":
const onGetLatentConnectInput = nodeType.prototype.onConnectInput;
nodeType.prototype.onConnectInput = function (targetSlot, type, output, originNode, originSlot) {
console.log(this)
const v = onGetLatentConnectInput? onGetLatentConnectInput.apply(this, arguments): undefined
//console.log(this)
this.outputs[1]["label"] = "batch_size"
this.outputs[2]["label"] = "channels"
this.outputs[3]["label"] = "frames"
this.outputs[4]["label"] = "height"
this.outputs[5]["label"] = "width"
return v;
}
//const onGetImageSizeExecuted = nodeType.prototype.onExecuted;
const onGetLatentSizeExecuted = nodeType.prototype.onAfterExecuteNode;
nodeType.prototype.onExecuted = function(message) {
console.log(this)
const r = onGetLatentSizeExecuted? onGetLatentSizeExecuted.apply(this,arguments): undefined
let values = message["text"].toString().split('x').map(Number);
console.log(values)
this.outputs[1]["label"] = values[0] + " batch"
this.outputs[2]["label"] = values[1] + " channels"
this.outputs[3]["label"] = values[2] + " frames"
this.outputs[4]["label"] = values[3] + " height"
this.outputs[5]["label"] = values[4] + " width"
return r
}
break;
case "PreviewAnimation":
const onPreviewAnimationConnectInput = nodeType.prototype.onConnectInput;
nodeType.prototype.onConnectInput = function (targetSlot, type, output, originNode, originSlot) {
const v = onPreviewAnimationConnectInput? onPreviewAnimationConnectInput.apply(this, arguments): undefined
this.title = "Preview Animation"
return v;
}
const onPreviewAnimationExecuted = nodeType.prototype.onAfterExecuteNode;
nodeType.prototype.onExecuted = function(message) {
const r = onPreviewAnimationExecuted? onPreviewAnimationExecuted.apply(this,arguments): undefined
let values = message["text"].toString();
this.title = "Preview Animation " + values
return r
}
break;
case "VRAM_Debug":
const onVRAM_DebugConnectInput = nodeType.prototype.onConnectInput;
nodeType.prototype.onConnectInput = function (targetSlot, type, output, originNode, originSlot) {
const v = onVRAM_DebugConnectInput? onVRAM_DebugConnectInput.apply(this, arguments): undefined
this.outputs[3]["label"] = "freemem_before"
this.outputs[4]["label"] = "freemem_after"
return v;
}
const onVRAM_DebugExecuted = nodeType.prototype.onAfterExecuteNode;
nodeType.prototype.onExecuted = function(message) {
const r = onVRAM_DebugExecuted? onVRAM_DebugExecuted.apply(this,arguments): undefined
let values = message["text"].toString().split('x');
this.outputs[3]["label"] = values[0] + " freemem_before"
this.outputs[4]["label"] = values[1] + " freemem_after"
return r
}
break;
case "JoinStringMulti":
const originalOnNodeCreated = nodeType.prototype.onNodeCreated || function() {};
nodeType.prototype.onNodeCreated = function () {
originalOnNodeCreated.apply(this, arguments);
this._type = "STRING";
this.addWidget("button", "Update inputs", null, () => {
if (!this.inputs) {
this.inputs = [];
}
const target_number_of_inputs = this.widgets.find(w => w.name === "inputcount")["value"];
const num_inputs = this.inputs.filter(input => input.name && input.name.toLowerCase().includes("string_")).length
if (target_number_of_inputs === num_inputs) return; // already set, do nothing
if(target_number_of_inputs < num_inputs){
const inputs_to_remove = num_inputs - target_number_of_inputs;
for(let i = 0; i < inputs_to_remove; i++) {
this.removeInput(this.inputs.length - 1);
}
}
else{
for(let i = num_inputs+1; i <= target_number_of_inputs; ++i)
this.addInput(`string_${i}`, this._type, {shape: 7});
}
});
}
break;
case "SoundReactive":
nodeType.prototype.onNodeCreated = function () {
let audioContext;
let microphoneStream;
let animationFrameId;
let analyser;
let dataArray;
let startRangeHz;
let endRangeHz;
let smoothingFactor = 0.5;
let smoothedSoundLevel = 0;
// Function to update the widget value in real-time
const updateWidgetValueInRealTime = () => {
// Ensure analyser and dataArray are defined before using them
if (analyser && dataArray) {
analyser.getByteFrequencyData(dataArray);
const startRangeHzWidget = this.widgets.find(w => w.name === "start_range_hz");
if (startRangeHzWidget) startRangeHz = startRangeHzWidget.value;
const endRangeHzWidget = this.widgets.find(w => w.name === "end_range_hz");
if (endRangeHzWidget) endRangeHz = endRangeHzWidget.value;
const smoothingFactorWidget = this.widgets.find(w => w.name === "smoothing_factor");
if (smoothingFactorWidget) smoothingFactor = smoothingFactorWidget.value;
// Calculate frequency bin width (frequency resolution)
const frequencyBinWidth = audioContext.sampleRate / analyser.fftSize;
// Convert the widget values from Hz to indices
const startRangeIndex = Math.floor(startRangeHz / frequencyBinWidth);
const endRangeIndex = Math.floor(endRangeHz / frequencyBinWidth);
// Function to calculate the average value for a frequency range
const calculateAverage = (start, end) => {
const sum = dataArray.slice(start, end).reduce((acc, val) => acc + val, 0);
const average = sum / (end - start);
// Apply exponential moving average smoothing
smoothedSoundLevel = (average * (1 - smoothingFactor)) + (smoothedSoundLevel * smoothingFactor);
return smoothedSoundLevel;
};
// Calculate the average levels for each frequency range
const soundLevel = calculateAverage(startRangeIndex, endRangeIndex);
// Update the widget values
const lowLevelWidget = this.widgets.find(w => w.name === "sound_level");
if (lowLevelWidget) lowLevelWidget.value = soundLevel;
animationFrameId = requestAnimationFrame(updateWidgetValueInRealTime);
}
};
// Function to start capturing audio from the microphone
const startMicrophoneCapture = () => {
// Only create the audio context and analyser once
if (!audioContext) {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
// Access the sample rate of the audio context
console.log(`Sample rate: ${audioContext.sampleRate}Hz`);
analyser = audioContext.createAnalyser();
analyser.fftSize = 2048;
dataArray = new Uint8Array(analyser.frequencyBinCount);
// Get the range values from widgets (assumed to be in Hz)
const lowRangeWidget = this.widgets.find(w => w.name === "low_range_hz");
if (lowRangeWidget) startRangeHz = lowRangeWidget.value;
const midRangeWidget = this.widgets.find(w => w.name === "mid_range_hz");
if (midRangeWidget) endRangeHz = midRangeWidget.value;
}
navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => {
microphoneStream = stream;
const microphone = audioContext.createMediaStreamSource(stream);
microphone.connect(analyser);
updateWidgetValueInRealTime();
}).catch(error => {
console.error('Access to microphone was denied or an error occurred:', error);
});
};
// Function to stop capturing audio from the microphone
const stopMicrophoneCapture = () => {
if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
}
if (microphoneStream) {
microphoneStream.getTracks().forEach(track => track.stop());
}
if (audioContext) {
audioContext.close();
// Reset audioContext to ensure it can be created again when starting
audioContext = null;
}
};
// Add start button
this.addWidget("button", "Start mic capture", null, startMicrophoneCapture);
// Add stop button
this.addWidget("button", "Stop mic capture", null, stopMicrophoneCapture);
};
break;
case "SaveImageKJ":
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function() {
const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : void 0;
const widget = this.widgets.find((w) => w.name === "filename_prefix");
widget.serializeValue = () => {
return applyTextReplacements(app, widget.value);
};
return r;
};
break;
}
},
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404const { app } = window.comfyAPI.app;
import { typesCompatible, clientToCanvas, getNodeAtPoint } from "./utility.js";
let swapTargetNode = null;
let swapDraggedNode = null;
let swapDragStartPos = null;
let swapAnimating = false;
let swapHasMoved = false;
let swapKeyDown = false;
/** Find the topmost node whose bounding box overlaps with draggedNode */
function getOverlappingNode(graph, draggedNode) {
const ax = draggedNode.pos[0];
const ay = draggedNode.pos[1];
const aw = draggedNode.size[0] || 100;
const ah = draggedNode.size[1] || 60;
for (let i = graph._nodes.length - 1; i >= 0; i--) {
const n = graph._nodes[i];
if (n === draggedNode) continue;
const bx = n.pos[0];
const by = n.pos[1];
if (ax < bx + (n.size[0] || 100) && ax + aw > bx &&
ay < by + (n.size[1] || 60) && ay + ah > by) {
return n;
}
}
return null;
}
function startHighlightAnim(lgCanvas) {
if (swapAnimating) return;
swapAnimating = true;
function tick() {
if (!swapTargetNode) {
swapAnimating = false;
return;
}
lgCanvas.setDirty(false, true);
requestAnimationFrame(tick);
}
requestAnimationFrame(tick);
}
function clearSwapState() {
swapTargetNode = null;
swapDraggedNode = null;
swapDragStartPos = null;
swapHasMoved = false;
}
function snapshotConnections(graph, node) {
const inputs = [];
for (let i = 0; i < (node.inputs?.length ?? 0); i++) {
const inp = node.inputs[i];
if (inp.link == null) continue;
const link = graph.getLink(inp.link);
if (!link) continue;
inputs.push({
slotIndex: i,
type: inp.type,
originNodeId: link.origin_id,
originSlot: link.origin_slot,
});
}
const outputs = [];
for (let o = 0; o < (node.outputs?.length ?? 0); o++) {
const out = node.outputs[o];
if (!out.links?.length) continue;
const targets = out.links
.map((linkId) => graph.getLink(linkId))
.filter(Boolean)
.map((link) => ({ targetNodeId: link.target_id, targetSlot: link.target_slot }));
if (targets.length > 0) {
outputs.push({ slotIndex: o, type: out.type, targets });
}
}
return { inputs, outputs };
}
function disconnectAll(node) {
if (node.inputs) {
for (let i = node.inputs.length - 1; i >= 0; i--) {
if (node.inputs[i].link != null) node.disconnectInput(i);
}
}
if (node.outputs) {
for (let o = node.outputs.length - 1; o >= 0; o--) {
if (node.outputs[o].links?.length) node.disconnectOutput(o);
}
}
}
// Find a compatible slot on node, preferring sameIndex. Returns -1 if none found.
// For inputs, isAvailable checks link == null and usedInputs; for outputs, always true.
function findCompatibleSlot(slots, type, sameIndex, isAvailable) {
if (!slots) return -1;
if (sameIndex < slots.length && isAvailable(sameIndex) && typesCompatible(type, slots[sameIndex].type)) {
return sameIndex;
}
for (let s = 0; s < slots.length; s++) {
if (isAvailable(s) && typesCompatible(type, slots[s].type)) return s;
}
return -1;
}
// Reconnect external connections from a snapshot onto newNode.
// Tries same-slot first, then scans for a compatible free slot by type.
function reconnectExternal(graph, snapshot, newNode, otherNodeId) {
const usedInputs = new Set();
for (const inp of snapshot.inputs) {
if (inp.originNodeId === otherNodeId) continue;
const originNode = graph.getNodeById(inp.originNodeId);
if (!originNode) continue;
const slot = findCompatibleSlot(
newNode.inputs, inp.type, inp.slotIndex,
(s) => !usedInputs.has(s) && newNode.inputs[s].link == null,
);
if (slot === -1) continue;
originNode.connect(inp.originSlot, newNode, slot);
usedInputs.add(slot);
}
for (const out of snapshot.outputs) {
const bestSlot = findCompatibleSlot(
newNode.outputs, out.type, out.slotIndex,
() => true,
);
if (bestSlot === -1) continue;
for (const tgt of out.targets) {
if (tgt.targetNodeId === otherNodeId) continue;
const targetNode = graph.getNodeById(tgt.targetNodeId);
if (!targetNode) continue;
newNode.connect(bestSlot, targetNode, tgt.targetSlot);
}
}
}
// Reconnect links that were between the two swapped nodes in one direction.
// A→B becomes B→A, if slot types are compatible.
function reconnectInternalOneDirection(snap, fromNodeId, srcNode, dstNode) {
for (const out of snap.outputs) {
for (const tgt of out.targets) {
if (tgt.targetNodeId !== fromNodeId) continue;
if (!srcNode.outputs || out.slotIndex >= srcNode.outputs.length) continue;
if (!dstNode.inputs || tgt.targetSlot >= dstNode.inputs.length) continue;
if (!typesCompatible(srcNode.outputs[out.slotIndex].type, dstNode.inputs[tgt.targetSlot].type)) continue;
srcNode.connect(out.slotIndex, dstNode, tgt.targetSlot);
}
}
}
function getNodeElement(nodeId) {
return document.querySelector(`[data-node-id="${nodeId}"]`);
}
function animateSwapVue(nodeA, toA, nodeB, toB, duration) {
const elA = getNodeElement(nodeA.id);
const elB = getNodeElement(nodeB.id);
const transition = `transform ${duration}ms cubic-bezier(0.65, 0, 0.35, 1)`;
if (elA) elA.style.transition = transition;
if (elB) elB.style.transition = transition;
nodeA.pos = [toA[0], toA[1]];
nodeB.pos = [toB[0], toB[1]];
app.canvas.setDirty(true, true);
setTimeout(() => {
if (elA) elA.style.transition = "";
if (elB) elB.style.transition = "";
}, duration + 16);
}
function animateSwapCanvas(nodeA, fromA, toA, nodeB, fromB, toB, duration) {
const start = performance.now();
function ease(t) {
return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
}
function frame(now) {
const t = Math.min((now - start) / duration, 1);
const e = ease(t);
nodeA.pos = [
fromA[0] + (toA[0] - fromA[0]) * e,
fromA[1] + (toA[1] - fromA[1]) * e,
];
nodeB.pos = [
fromB[0] + (toB[0] - fromB[0]) * e,
fromB[1] + (toB[1] - fromB[1]) * e,
];
app.canvas.setDirty(true, true);
if (t < 1) requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
}
function executeNodeSwap(canvas, nodeA, nodeB, originalPosA) {
const graph = canvas.graph || app.graph;
const snapA = snapshotConnections(graph, nodeA);
const snapB = snapshotConnections(graph, nodeB);
const posA = originalPosA || [nodeA.pos[0], nodeA.pos[1]];
const posB = [nodeB.pos[0], nodeB.pos[1]];
disconnectAll(nodeA);
disconnectAll(nodeB);
reconnectExternal(graph, snapA, nodeB, nodeA.id);
reconnectExternal(graph, snapB, nodeA, nodeB.id);
reconnectInternalOneDirection(snapA, nodeB.id, nodeB, nodeA);
reconnectInternalOneDirection(snapB, nodeA.id, nodeA, nodeB);
if (LiteGraph.vueNodesMode) {
animateSwapVue(nodeA, posB, nodeB, posA, 200);
} else {
animateSwapCanvas(nodeA, [nodeA.pos[0], nodeA.pos[1]], posB,
nodeB, [nodeB.pos[0], nodeB.pos[1]], posA, 200);
}
graph.change();
canvas.setDirty(true, true);
}
app.registerExtension({
name: "KJNodes.NodeSwap",
settings: [
{
id: "KJNodes.nodeSwapEnabled",
name: "Enable node swap on drag",
category: ["KJNodes", "Node Swap", "Enable"],
tooltip: "Hold swap key (default: S, rebindable in Keybindings) and drag a node onto another to swap their positions and reconnect links",
type: "boolean",
defaultValue: true,
},
],
commands: [
{
id: "KJNodes.ToggleNodeSwap",
label: "Toggle node swap on drag",
active: () => app.ui.settings.getSettingValue("KJNodes.nodeSwapEnabled"),
function: () => {
const cur = app.ui.settings.getSettingValue("KJNodes.nodeSwapEnabled");
app.ui.settings.setSettingValue("KJNodes.nodeSwapEnabled", !cur);
},
},
{
id: "KJNodes.NodeSwapMode",
label: "Node swap mode (hold to activate)",
active: () => swapKeyDown,
function: () => {
swapKeyDown = true;
// If already dragging a node, check for overlap immediately
// (handles case where node is already on top of another when key is pressed)
if (swapDraggedNode) {
const graph = app.canvas?.graph || app.graph;
if (graph) {
swapTargetNode = getOverlappingNode(graph, swapDraggedNode);
if (swapTargetNode) startHighlightAnim(app.canvas);
}
}
},
},
],
keybindings: [
{
commandId: "KJNodes.NodeSwapMode",
combo: { key: "s" },
targetElementId: "graph-canvas",
},
],
async setup() {
await new Promise((resolve) => {
function check() {
if (app.canvas) return resolve();
requestAnimationFrame(check);
}
check();
});
const lgCanvas = app.canvas;
const canvasEl = lgCanvas.canvas;
// The command system handles keydown (sets swapKeyDown = true).
// Any keyup clears it since the user must hold the key.
document.addEventListener("keyup", () => {
if (swapKeyDown) {
swapKeyDown = false;
if (swapTargetNode) {
swapTargetNode = null;
lgCanvas.setDirty(false, true);
}
}
});
// Pointermove/pointerup handlers — only attached while pointer is down.
function onPointerMove() {
swapHasMoved = true;
if (!swapKeyDown) {
if (swapTargetNode) {
swapTargetNode = null;
lgCanvas.setDirty(false, true);
}
return;
}
if (!swapDraggedNode) return;
const graph = lgCanvas.graph || app.graph;
if (!graph) return;
const prev = swapTargetNode;
swapTargetNode = getOverlappingNode(graph, swapDraggedNode);
if (swapTargetNode && !prev) {
startHighlightAnim(lgCanvas);
}
}
function onPointerUp(e) {
if (e.button !== 0) return;
document.removeEventListener("pointermove", onPointerMove);
document.removeEventListener("pointerup", onPointerUp, true);
const targetNode = swapTargetNode;
const draggedNode = swapDraggedNode;
const startPos = swapDragStartPos;
const hasMoved = swapHasMoved;
clearSwapState();
if (!hasMoved || !targetNode || !draggedNode || !swapKeyDown) return;
if (!targetNode.flags?.pinned && !draggedNode.flags?.pinned) {
executeNodeSwap(lgCanvas, draggedNode, targetNode, startPos);
}
}
// Record clicked node and its original position.
// Listen on document to catch events from both the canvas and Vue node overlays.
const graphContainer = canvasEl.closest(".graph-canvas-container") || canvasEl.parentElement;
document.addEventListener("pointerdown", (e) => {
if (e.button !== 0) return;
if (!app.ui.settings.getSettingValue("KJNodes.nodeSwapEnabled")) return;
if (!graphContainer?.contains(e.target)) return;
swapHasMoved = false;
const graph = lgCanvas.graph || app.graph;
if (!graph) return;
const [cx, cy] = clientToCanvas(lgCanvas, e.clientX, e.clientY);
const node = getNodeAtPoint(graph, cx, cy);
if (node && (node.inputs || node.outputs)) {
swapDraggedNode = node;
swapDragStartPos = [node.pos[0], node.pos[1]];
document.addEventListener("pointermove", onPointerMove);
document.addEventListener("pointerup", onPointerUp, true);
}
}, true);
// Draw pulsing glow outline on the swap target node
const origOnDrawBg = lgCanvas.onDrawBackground;
lgCanvas.onDrawBackground = function (ctx, ...args) {
origOnDrawBg?.call(this, ctx, ...args);
const target = swapTargetNode;
if (!target) return;
const [x, y] = target.pos;
const w = target.size[0] || 100;
const h = target.size[1] || 60;
const titleH = LiteGraph.NODE_TITLE_HEIGHT || 20;
const pulse = 0.5 + 0.3 * Math.sin(Date.now() / 200);
const isPinned = target.flags?.pinned;
const color = isPinned ? "255, 80, 80" : "100, 200, 255";
const pad = 5;
ctx.save();
ctx.strokeStyle = `rgba(${color}, ${pulse})`;
ctx.lineWidth = 3;
ctx.shadowColor = `rgba(${color}, 0.8)`;
ctx.shadowBlur = 15;
ctx.beginPath();
ctx.roundRect(x - pad, y - titleH - pad, w + pad * 2, h + titleH + pad * 2, 8);
ctx.stroke();
ctx.fillStyle = `rgba(${color}, ${isPinned ? 0.08 : 0.05})`;
ctx.fill();
ctx.restore();
};
},
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286const { app } = window.comfyAPI.app;
const _savedRoundRadius = typeof LiteGraph !== "undefined" ? LiteGraph.ROUND_RADIUS : 8;
function getSetting(id, fallback) {
return app.ui.settings.getSettingValue(id) ?? fallback;
}
function toggleSetting(id) {
const cur = app.ui.settings.getSettingValue(id);
app.ui.settings.setSettingValue(id, !cur);
}
app.registerExtension({
name: "KJNodes.Performance",
commands: [
{
id: "KJNodes.perf.toggleSingleCanvasPan",
label: "Single-canvas mode during pan",
menubarLabel: "Single-canvas mode during pan",
function: () => toggleSetting("KJNodes.perf.singleCanvasPan"),
active: () => getSetting("KJNodes.perf.singleCanvasPan", false),
},
{
id: "KJNodes.perf.toggleDisableShadows",
label: "Disable node shadows",
menubarLabel: "Disable node shadows",
function: () => toggleSetting("KJNodes.perf.disableShadows"),
active: () => getSetting("KJNodes.perf.disableShadows", false),
},
{
id: "KJNodes.perf.toggleDisableConnectionBorders",
label: "Disable connection borders",
menubarLabel: "Disable connection borders",
function: () => toggleSetting("KJNodes.perf.disableConnectionBorders"),
active: () => getSetting("KJNodes.perf.disableConnectionBorders", false),
},
{
id: "KJNodes.perf.toggleDisableRoundedCorners",
label: "Disable rounded corners",
menubarLabel: "Disable rounded corners",
function: () => toggleSetting("KJNodes.perf.disableRoundedCorners"),
active: () => getSetting("KJNodes.perf.disableRoundedCorners", false),
},
{
id: "KJNodes.perf.toggleThrottleRenderInfo",
label: "Throttle info overlay",
menubarLabel: "Throttle info overlay",
function: () => toggleSetting("KJNodes.perf.throttleRenderInfo"),
active: () => getSetting("KJNodes.perf.throttleRenderInfo", false),
},
],
menuCommands: [
{
path: ["KJNodes", "Performance"],
commands: [
"KJNodes.perf.toggleSingleCanvasPan",
"KJNodes.perf.toggleDisableShadows",
"KJNodes.perf.toggleDisableConnectionBorders",
"KJNodes.perf.toggleDisableRoundedCorners",
"KJNodes.perf.toggleThrottleRenderInfo",
],
},
],
settings: [
{
id: "KJNodes.perf.singleCanvasPan",
name: "Single-canvas mode during pan",
category: ["KJNodes", "Performance", "Single-canvas mode during pan"],
tooltip: "Eliminates the expensive bgcanvas-to-canvas copy during panning. Significant improvement without hardware acceleration.",
type: "boolean",
defaultValue: false,
onChange: (value) => {
const canvas = app.canvas;
if (!canvas) return;
if (value) {
installSingleCanvasPan(canvas);
} else {
uninstallSingleCanvasPan(canvas);
}
},
},
{
id: "KJNodes.perf.disableShadows",
name: "Disable node shadows",
category: ["KJNodes", "Performance", "Disable node shadows"],
tooltip: "Disable shadow rendering on nodes for better performance without hardware acceleration.",
type: "boolean",
defaultValue: false,
onChange: (value) => {
if (app.canvas) {
app.canvas.render_shadows = !value;
app.canvas.setDirty(true, true);
}
},
},
{
id: "KJNodes.perf.disableConnectionBorders",
name: "Disable connection borders",
category: ["KJNodes", "Performance", "Disable connection borders"],
tooltip: "Disable the outer border stroke on connection lines. Each link draws two strokes instead of one when enabled.",
type: "boolean",
defaultValue: false,
onChange: (value) => {
if (app.canvas) {
app.canvas.render_connections_border = !value;
app.canvas.setDirty(true, true);
}
},
},
{
id: "KJNodes.perf.disableRoundedCorners",
name: "Disable rounded corners",
category: ["KJNodes", "Performance", "Disable rounded corners"],
tooltip: "Use square corners on nodes instead of rounded. Avoids roundRect calls in software rendering.",
type: "boolean",
defaultValue: false,
onChange: (value) => {
if (typeof LiteGraph !== "undefined") {
LiteGraph.ROUND_RADIUS = value ? 0 : _savedRoundRadius;
app.canvas?.setDirty(true, true);
}
},
},
{
id: "KJNodes.perf.throttleRenderInfo",
name: "Throttle info overlay",
category: ["KJNodes", "Performance", "Throttle info overlay"],
tooltip: "Cache the FPS/info text overlay and only re-render it a few times per second. Saves ~20ms per frame in software rendering.",
type: "boolean",
defaultValue: false,
onChange: (value) => {
const canvas = app.canvas;
if (!canvas) return;
if (value) {
installThrottleRenderInfo(canvas);
} else {
uninstallThrottleRenderInfo(canvas);
}
},
},
],
setup() {
const canvas = app.canvas;
if (!canvas) return;
if (getSetting("KJNodes.perf.singleCanvasPan", false)) {
installSingleCanvasPan(canvas);
}
if (getSetting("KJNodes.perf.disableShadows", false)) {
canvas.render_shadows = false;
}
if (getSetting("KJNodes.perf.disableConnectionBorders", false)) {
canvas.render_connections_border = false;
}
if (getSetting("KJNodes.perf.disableRoundedCorners", false)) {
LiteGraph.ROUND_RADIUS = 0;
}
if (getSetting("KJNodes.perf.throttleRenderInfo", false)) {
installThrottleRenderInfo(canvas);
}
},
});
// ── Single-canvas mode during pan ───────────────────────────────────────────
let _origDraw = null;
let _panInstalledOn = null;
function installSingleCanvasPan(canvas) {
if (_origDraw && _panInstalledOn === canvas) return;
if (_origDraw && _panInstalledOn !== canvas) {
// Canvas was replaced — discard stale reference
_origDraw = null;
}
_panInstalledOn = canvas;
_origDraw = canvas.draw;
let panning = false;
let savedBgCanvas = null;
let savedBgCtx = null;
canvas.draw = function (force_canvas, force_bgcanvas) {
if (this.dragging_canvas) {
if (!panning) {
// Flush any pending bg redraw before aliasing to avoid a stale-frame flash
if (this.dirty_bgcanvas) {
_origDraw.call(this, false, true);
}
savedBgCanvas = this.bgcanvas;
savedBgCtx = this.bgctx;
panning = true;
this.bgcanvas = this.canvas;
this.bgctx = this.ctx;
}
} else if (panning) {
panning = false;
this.bgcanvas = savedBgCanvas;
this.bgctx = savedBgCtx;
this.dirty_bgcanvas = true;
this.dirty_canvas = true;
}
_origDraw.call(this, force_canvas, force_bgcanvas);
};
}
function uninstallSingleCanvasPan(canvas) {
if (!_origDraw) return;
if (_panInstalledOn === canvas) {
canvas.draw = _origDraw;
}
_origDraw = null;
_panInstalledOn = null;
canvas.dirty_bgcanvas = true;
canvas.dirty_canvas = true;
}
// ── Throttle renderInfo ─────────────────────────────────────────────────────
let _origRenderInfo = null;
let _infoCanvas = null;
let _infoInstalledOn = null;
function installThrottleRenderInfo(canvas) {
if (_origRenderInfo && _infoInstalledOn === canvas) return;
if (_origRenderInfo && _infoInstalledOn !== canvas) {
_origRenderInfo = null;
_infoCanvas = null;
}
_infoInstalledOn = canvas;
_origRenderInfo = canvas.renderInfo;
_infoCanvas = document.createElement("canvas");
let infoCtx = _infoCanvas.getContext("2d");
let lastInfoTime = 0;
let cachedDpr = 0;
let _infoDrawX = 10;
let _infoDrawY = 0;
canvas.renderInfo = function (ctx, x, y) {
const dpr = window.devicePixelRatio || 1;
// Resize offscreen canvas if DPR changed
if (dpr !== cachedDpr) {
cachedDpr = dpr;
_infoCanvas.width = Math.ceil(200 * dpr);
_infoCanvas.height = Math.ceil(100 * dpr);
infoCtx = _infoCanvas.getContext("2d");
infoCtx.scale(dpr, dpr);
lastInfoTime = 0;
}
const now = performance.now();
if (now - lastInfoTime > 250) {
lastInfoTime = now;
infoCtx.clearRect(0, 0, 200, 100);
// Render with the same x/y the original would use, but offset
// into offscreen canvas coordinates
const origX = x || 10;
const lineHeight = 13;
const lineCount = (this.graph ? 5 : 1) + (this.info_text ? 1 : 0);
const origY = y || (this.canvas.height / dpr - (lineCount + 1) * lineHeight);
// Store the computed position for blitting
_infoDrawX = origX;
_infoDrawY = origY;
// Draw into offscreen at (1, 1), text flows from there
_origRenderInfo.call(this, infoCtx, 1, 1);
}
// Blit cached text at the original position
ctx.drawImage(_infoCanvas, _infoDrawX - 1, _infoDrawY - 1, 200, 100);
};
}
function uninstallThrottleRenderInfo(canvas) {
if (!_origRenderInfo) return;
if (_infoInstalledOn === canvas) {
canvas.renderInfo = _origRenderInfo;
}
_origRenderInfo = null;
_infoCanvas = null;
_infoInstalledOn = null;
canvas.setDirty(true, true);
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394const { app } = window.comfyAPI.app;
const { api } = window.comfyAPI.api;
app.registerExtension({
name: "KJNodes.PlaySound",
async beforeRegisterNodeDef(nodeType, nodeData) {
if (nodeData.name !== "PlaySoundKJ") return;
const onExecuted = nodeType.prototype.onExecuted;
nodeType.prototype.onExecuted = function (output) {
onExecuted?.call(this, output);
const audios = output?.audio;
if (!audios?.length) return;
const modeWidget = this.widgets?.find(w => w.name === "mode");
const volumeWidget = this.widgets?.find(w => w.name === "volume");
const durationWidget = this.widgets?.find(w => w.name === "duration");
const mode = modeWidget?.value ?? "always";
const volume = volumeWidget?.value ?? 0.5;
const duration = durationWidget?.value ?? 0;
// on_change: skip if audio content hasn't changed
if (mode === "on_change") {
const audioHash = output?.audio_hash?.[0];
if (audioHash != null && this._kjLastAudioHash === audioHash) return;
this._kjLastAudioHash = audioHash;
}
// Clean up previous state
if (this._kjStatusListener) {
api.removeEventListener("status", this._kjStatusListener);
this._kjStatusListener = null;
}
clearTimeout(this._kjQueueDebounce);
this._kjPendingAudio = null;
if (this._kjPlayingAudio) {
this._kjPlayingAudio.pause();
this._kjPlayingAudio = null;
}
if (this._kjPlayTimer != null) {
clearTimeout(this._kjPlayTimer);
this._kjPlayTimer = null;
}
const startPlayback = () => {
const { filename, subfolder, type } = audios[0];
const params = new URLSearchParams({
filename: filename ?? "",
subfolder: subfolder ?? "",
type: type ?? "temp",
});
const url = api.apiURL(`/view?${params.toString()}`);
const audio = new Audio(url);
audio.volume = Math.max(0, Math.min(1, volume));
audio.play().catch(() => {});
this._kjPlayingAudio = audio;
if (duration > 0) {
this._kjPlayTimer = setTimeout(() => {
audio.pause();
this._kjPlayingAudio = null;
this._kjPlayTimer = null;
}, duration * 1000);
}
};
if (mode === "on_empty_queue") {
this._kjPendingAudio = startPlayback;
this._kjStatusListener = ({ detail }) => {
const remaining = detail?.exec_info?.queue_remaining ?? 0;
if (remaining === 0) {
// Debounce: confirm queue is truly empty
// (status can briefly show 0 between dispatches)
clearTimeout(this._kjQueueDebounce);
this._kjQueueDebounce = setTimeout(() => {
if (this._kjPendingAudio) {
this._kjPendingAudio();
this._kjPendingAudio = null;
}
api.removeEventListener("status", this._kjStatusListener);
this._kjStatusListener = null;
}, 1000);
} else {
clearTimeout(this._kjQueueDebounce);
}
};
api.addEventListener("status", this._kjStatusListener);
} else {
startPlayback();
}
};
},
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500import { addMiddleClickPan, addWheelPassthrough } from "./utility.js";
const { app } = window.comfyAPI.app;
app.registerExtension({
name: "KJNodes.ScreencapStream",
async beforeRegisterNodeDef(nodeType, nodeData) {
if (nodeData.name !== "ScreencapStream") return;
nodeType.prototype.onNodeCreated = function () {
const node = this;
const frameWidget = this.widgets.find(w => w.name === "frame_data");
frameWidget.computeSize = () => [0, -4];
// --- State ---
let stream = null;
let crop = null; // { x, y, w, h } in video pixel coords, or null
let previewVisible = true;
let previewInterval = null;
let bitmapInterval = null;
let cachedBitmap = null; // downscaled ImageBitmap for preview
let bitmapPending = false;
let drag = null;
let drawPending = false;
let cachedLayout = null;
let layoutDirty = true;
let updatingFromCrop = false;
let captureStartTime = null;
let timerInterval = null;
const EDGE = 8;
// separate canvases to avoid conflicts between preview and serialization
const serializeCanvas = document.createElement("canvas");
const serializeCtx = serializeCanvas.getContext("2d");
// --- DOM elements ---
const video = document.createElement("video");
video.autoplay = true;
video.muted = true;
video.style.cssText = "position:absolute;width:1px;height:1px;opacity:0;pointer-events:none;overflow:hidden;";
const container = document.createElement("div");
container.style.cssText = "width:100%;height:100%;background:#000;border-radius:4px;overflow:hidden;position:relative;";
container.appendChild(video);
const overlay = document.createElement("canvas");
overlay.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;cursor:crosshair;";
container.appendChild(overlay);
const overlayCtx = overlay.getContext("2d");
addMiddleClickPan(container);
addWheelPassthrough(container);
// --- Widget references ---
const cropWWidget = node.widgets.find(w => w.name === "crop_width");
const cropHWidget = node.widgets.find(w => w.name === "crop_height");
const PREVIEW_MAX_RES = 960; // preview-only cap for performance
// --- Layout ---
function invalidateLayout() { layoutDirty = true; }
function getLayout() {
if (!layoutDirty && cachedLayout) return cachedLayout;
const oRect = overlay.getBoundingClientRect();
const vw = video.videoWidth, vh = video.videoHeight;
if (!vw || !vh || !oRect.width || !oRect.height) { cachedLayout = null; return null; }
const scale = Math.min(oRect.width / vw, oRect.height / vh);
cachedLayout = {
scale, vw, vh,
offX: (oRect.width - vw * scale) / 2,
offY: (oRect.height - vh * scale) / 2,
};
layoutDirty = false;
return cachedLayout;
}
function toVideoCoords(cx, cy) {
const L = getLayout();
if (!L) return { x: 0, y: 0 };
return {
x: Math.round(Math.max(0, Math.min(L.vw, (cx - L.offX) / L.scale))),
y: Math.round(Math.max(0, Math.min(L.vh, (cy - L.offY) / L.scale))),
};
}
function pointerToLocal(e) {
const r = overlay.getBoundingClientRect();
return { x: e.clientX - r.left, y: e.clientY - r.top };
}
// --- Output dimensions ---
// Single source of truth for what the output size will be.
function getOutputDimensions() {
const vw = video.videoWidth, vh = video.videoHeight;
if (!vw || !vh) return null;
const sw = crop ? crop.w : vw;
const sh = crop ? crop.h : vh;
return { w: sw, h: sh };
}
function updateSizeWidgets() {
updatingFromCrop = true;
const dims = getOutputDimensions();
if (dims) {
cropWWidget.value = dims.w;
cropHWidget.value = dims.h;
// clamp max to full capture dimensions
if (cropWWidget.options) cropWWidget.options.max = video.videoWidth || dims.w;
if (cropHWidget.options) cropHWidget.options.max = video.videoHeight || dims.h;
}
app.graph.setDirtyCanvas(true);
updatingFromCrop = false;
}
function updateCropFromWidgets() {
if (updatingFromCrop || !video.videoWidth || !crop) return;
const newW = Math.min(cropWWidget.value, video.videoWidth);
const newH = Math.min(cropHWidget.value, video.videoHeight);
if (newW <= 0 || newH <= 0) return;
const cx = crop.x + crop.w / 2;
const cy = crop.y + crop.h / 2;
let x = Math.round(cx - newW / 2);
let y = Math.round(cy - newH / 2);
x = Math.max(0, Math.min(x, video.videoWidth - newW));
y = Math.max(0, Math.min(y, video.videoHeight - newH));
crop = { x, y, w: newW, h: newH };
drawOverlay();
}
function clearCrop() {
if (video.videoWidth && video.videoHeight) {
crop = { x: 0, y: 0, w: video.videoWidth, h: video.videoHeight };
} else {
crop = null;
}
drawOverlay();
updateSizeWidgets();
}
// --- Cached bitmap ---
// Updated every 500ms for preview display.
// Downscaled to PREVIEW_MAX_RES for performance.
async function updateCachedBitmap() {
if (bitmapPending || !stream || !video.videoWidth) return;
bitmapPending = true;
try {
const vw = video.videoWidth, vh = video.videoHeight;
if (vw <= 0 || vh <= 0) { bitmapPending = false; return; }
// always full frame for preview — crop is drawn as overlay
let outW = vw, outH = vh;
if (Math.max(vw, vh) > PREVIEW_MAX_RES) {
const s = PREVIEW_MAX_RES / Math.max(vw, vh);
outW = Math.round(vw * s);
outH = Math.round(vh * s);
}
const bmp = await createImageBitmap(video, {
resizeWidth: outW,
resizeHeight: outH,
resizeQuality: "medium",
});
if (cachedBitmap) cachedBitmap.close();
cachedBitmap = bmp;
} catch { /* frame not ready */ }
bitmapPending = false;
}
function startBitmapLoop() {
stopBitmapLoop();
bitmapInterval = setInterval(updateCachedBitmap, 500);
}
function stopBitmapLoop() {
if (bitmapInterval) { clearInterval(bitmapInterval); bitmapInterval = null; }
}
// --- Preview drawing ---
function drawOverlay() {
if (drawPending) return;
drawPending = true;
requestAnimationFrame(() => {
drawPending = false;
renderOverlay();
});
}
function renderOverlay() {
const r = overlay.getBoundingClientRect();
const w = Math.round(r.width), h = Math.round(r.height);
if (overlay.width !== w || overlay.height !== h) {
overlay.width = w; overlay.height = h;
invalidateLayout();
}
overlayCtx.clearRect(0, 0, w, h);
if (!previewVisible) return;
const L = getLayout();
if (!L) return;
// draw from cached bitmap if available, else raw video
const src = cachedBitmap || video;
overlayCtx.drawImage(src, L.offX, L.offY, L.vw * L.scale, L.vh * L.scale);
if (!crop) return;
const rx = L.offX + crop.x * L.scale;
const ry = L.offY + crop.y * L.scale;
const rw = crop.w * L.scale;
const rh = crop.h * L.scale;
// darken outside crop
overlayCtx.fillStyle = "rgba(0,0,0,0.5)";
overlayCtx.fillRect(0, 0, w, ry);
overlayCtx.fillRect(0, ry + rh, w, h - ry - rh);
overlayCtx.fillRect(0, ry, rx, rh);
overlayCtx.fillRect(rx + rw, ry, w - rx - rw, rh);
overlayCtx.strokeStyle = "#fff";
overlayCtx.lineWidth = 1.5;
overlayCtx.setLineDash([4, 3]);
overlayCtx.strokeRect(rx, ry, rw, rh);
overlayCtx.setLineDash([]);
}
function startPreviewLoop() {
stopPreviewLoop();
previewInterval = setInterval(() => drawOverlay(), 100);
}
function stopPreviewLoop() {
if (previewInterval) { clearInterval(previewInterval); previewInterval = null; }
}
// --- Hit testing ---
function hitTest(lx, ly) {
if (!crop) return "draw";
const L = getLayout();
if (!L) return "draw";
const rx = L.offX + crop.x * L.scale;
const ry = L.offY + crop.y * L.scale;
const rw = crop.w * L.scale;
const rh = crop.h * L.scale;
const nearL = Math.abs(lx - rx) < EDGE;
const nearR = Math.abs(lx - (rx + rw)) < EDGE;
const nearT = Math.abs(ly - ry) < EDGE;
const nearB = Math.abs(ly - (ry + rh)) < EDGE;
const inX = lx > rx - EDGE && lx < rx + rw + EDGE;
const inY = ly > ry - EDGE && ly < ry + rh + EDGE;
if (nearT && nearL && inX && inY) return "nw";
if (nearT && nearR && inX && inY) return "ne";
if (nearB && nearL && inX && inY) return "sw";
if (nearB && nearR && inX && inY) return "se";
if (nearT && inX) return "n";
if (nearB && inX) return "s";
if (nearL && inY) return "w";
if (nearR && inY) return "e";
if (lx > rx && lx < rx + rw && ly > ry && ly < ry + rh) return "move";
return "draw";
}
const cursorMap = {
nw: "nwse-resize", se: "nwse-resize",
ne: "nesw-resize", sw: "nesw-resize",
n: "ns-resize", s: "ns-resize",
w: "ew-resize", e: "ew-resize",
move: "grab", draw: "crosshair",
};
// --- Widget callbacks ---
const origWCb = cropWWidget.callback;
const origHCb = cropHWidget.callback;
cropWWidget.callback = function() { origWCb?.apply(this, arguments); updateCropFromWidgets(); };
cropHWidget.callback = function() { origHCb?.apply(this, arguments); updateCropFromWidgets(); };
// --- Pointer events ---
overlay.addEventListener("pointermove", (e) => {
if (drag) {
e.stopPropagation();
e.preventDefault();
const p = pointerToLocal(e);
const v = toVideoCoords(p.x, p.y);
const dx = v.x - drag.startVX;
const dy = v.y - drag.startVY;
const o = drag.origCrop;
const maxW = video.videoWidth, maxH = video.videoHeight;
if (drag.type === "draw") {
let w = Math.abs(v.x - drag.startVX);
let h = Math.abs(v.y - drag.startVY);
if (e.shiftKey && w > 0 && h > 0) {
const aspect = drag.aspect || w / h;
drag.aspect = aspect;
if (w / h > aspect) w = Math.round(h * aspect);
else h = Math.round(w / aspect);
} else {
drag.aspect = null;
}
crop = {
x: v.x < drag.startVX ? drag.startVX - w : drag.startVX,
y: v.y < drag.startVY ? drag.startVY - h : drag.startVY,
w, h,
};
} else if (drag.type === "move") {
let nx = o.x + dx, ny = o.y + dy;
nx = Math.max(0, Math.min(maxW - o.w, nx));
ny = Math.max(0, Math.min(maxH - o.h, ny));
crop = { x: nx, y: ny, w: o.w, h: o.h };
} else {
let { x, y, w, h } = { ...o };
if (drag.type.includes("w")) { x = o.x + dx; w = o.w - dx; }
if (drag.type.includes("e")) { w = o.w + dx; }
if (drag.type.includes("n")) { y = o.y + dy; h = o.h - dy; }
if (drag.type.includes("s")) { h = o.h + dy; }
if (w < 0) { x += w; w = -w; }
if (h < 0) { y += h; h = -h; }
if (e.shiftKey && o.w > 0 && o.h > 0 && w > 0 && h > 0) {
const aspect = o.w / o.h;
if (drag.type.length === 2) {
if (w / h > aspect) w = Math.round(h * aspect);
else h = Math.round(w / aspect);
if (drag.type.includes("w")) x = o.x + o.w - w;
if (drag.type.includes("n")) y = o.y + o.h - h;
} else if (drag.type === "n" || drag.type === "s") {
w = Math.round(h * aspect);
x = o.x + Math.round((o.w - w) / 2);
} else {
h = Math.round(w / aspect);
y = o.y + Math.round((o.h - h) / 2);
}
}
x = Math.max(0, x); y = Math.max(0, y);
w = Math.min(w, maxW - x); h = Math.min(h, maxH - y);
crop = { x, y, w, h };
}
drawOverlay();
updateSizeWidgets();
return;
}
if (!previewVisible || !stream) return;
const p = pointerToLocal(e);
overlay.style.cursor = cursorMap[hitTest(p.x, p.y)];
});
overlay.addEventListener("pointerdown", (e) => {
if (!previewVisible || !stream) return;
e.stopPropagation();
e.preventDefault();
overlay.setPointerCapture(e.pointerId);
const p = pointerToLocal(e);
const type = hitTest(p.x, p.y);
const v = toVideoCoords(p.x, p.y);
drag = {
type,
startVX: v.x, startVY: v.y,
origCrop: crop ? { ...crop } : null,
};
if (type === "move") overlay.style.cursor = "grabbing";
});
overlay.addEventListener("pointerup", (e) => {
if (!drag) return;
e.stopPropagation();
if (drag.type === "move") overlay.style.cursor = "grab";
drag = null;
if (crop && (crop.w < 5 || crop.h < 5)) {
crop = { x: 0, y: 0, w: video.videoWidth, h: video.videoHeight };
}
drawOverlay();
updateSizeWidgets();
});
overlay.addEventListener("dblclick", (e) => {
e.stopPropagation();
e.preventDefault();
clearCrop();
});
overlay.addEventListener("contextmenu", (e) => {
e.stopPropagation();
e.preventDefault();
clearCrop();
});
// --- Resize observer ---
const resizeObs = new ResizeObserver(() => { invalidateLayout(); drawOverlay(); });
resizeObs.observe(container);
// --- Timer ---
function formatElapsed(ms) {
const s = Math.floor(ms / 1000);
const m = Math.floor(s / 60);
const h = Math.floor(m / 60);
const pad = (n) => String(n).padStart(2, "0");
if (h > 0) return `${h}:${pad(m % 60)}:${pad(s % 60)}`;
return `${m}:${pad(s % 60)}`;
}
function updateBtnTimer() {
if (!captureStartTime || !btnWidget) return;
const elapsed = formatElapsed(Date.now() - captureStartTime);
btnWidget.name = `\uD83D\uDD34 ${elapsed} - Stop capture`;
app.graph.setDirtyCanvas(true);
}
function startTimer() {
captureStartTime = Date.now();
timerInterval = setInterval(updateBtnTimer, 1000);
updateBtnTimer();
}
function stopTimer() {
if (timerInterval) { clearInterval(timerInterval); timerInterval = null; }
captureStartTime = null;
}
// --- Stream management ---
let btnWidget = null;
function stopStream() {
stopPreviewLoop();
stopBitmapLoop();
stopTimer();
if (cachedBitmap) { cachedBitmap.close(); cachedBitmap = null; }
if (stream) stream.getTracks().forEach(t => t.stop());
stream = null;
crop = null;
video.srcObject = null;
if (btnWidget) btnWidget.name = "Start capture";
app.graph.setDirtyCanvas(true);
}
btnWidget = this.addWidget("button", "Start capture", null, async () => {
if (stream) { stopStream(); return; }
try {
// capture at native resolution — browser constraints
// cause green tint. Preview is downscaled via
// createImageBitmap, output goes to Python at full res.
stream = await navigator.mediaDevices.getDisplayMedia({
video: { frameRate: { ideal: 5, max: 10 } },
});
video.srcObject = stream;
startTimer();
const track = stream.getVideoTracks()[0];
track.addEventListener("ended", stopStream);
video.addEventListener("loadedmetadata", () => {
crop = { x: 0, y: 0, w: video.videoWidth, h: video.videoHeight };
invalidateLayout();
updateSizeWidgets();
startBitmapLoop();
if (previewVisible) startPreviewLoop();
}, { once: true });
} catch { /* user cancelled */ }
});
// --- DOM widget ---
this.addDOMWidget("preview", "ScreencapPreview", container, {
serialize: false,
hideOnZoom: false,
getMinHeight: () => 200,
});
const previewBtn = this.addWidget("button", "Hide preview", null, () => {
previewVisible = !previewVisible;
previewBtn.name = previewVisible ? "Hide preview" : "Show preview";
if (previewVisible && stream) {
invalidateLayout();
startBitmapLoop();
startPreviewLoop();
} else {
stopPreviewLoop();
stopBitmapLoop();
overlayCtx.clearRect(0, 0, overlay.width, overlay.height);
}
app.graph.setDirtyCanvas(true);
});
// --- Frame serialization ---
// Always send full crop resolution to Python.
// Python handles downscaling with Lanczos for better quality.
frameWidget.serializeValue = () => {
if (!stream || !video.videoWidth) return "";
const vw = video.videoWidth, vh = video.videoHeight;
const sx = crop ? Math.min(crop.x, vw) : 0;
const sy = crop ? Math.min(crop.y, vh) : 0;
const sw = crop ? Math.min(crop.w, vw - sx) : vw;
const sh = crop ? Math.min(crop.h, vh - sy) : vh;
if (sw <= 0 || sh <= 0) return "";
serializeCanvas.width = sw;
serializeCanvas.height = sh;
serializeCtx.drawImage(video, sx, sy, sw, sh, 0, 0, sw, sh);
return serializeCanvas.toDataURL("image/png");
};
// --- Cleanup ---
const origOnRemoved = this.onRemoved;
this.onRemoved = function () {
stopStream();
resizeObs.disconnect();
origOnRemoved?.apply(this, arguments);
};
};
},
});12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544const { app } = window.comfyAPI.app;
// originally based on diffus3's SetGet: https://github.com/diffus3/ComfyUI-extensions
// Nodes that allow you to hide connections for cleaner graphs
let _typeColorMap;
function setColorAndBgColor(node, type) {
if (!_typeColorMap) {
_typeColorMap = {
"DEFAULT": LGraphCanvas.node_colors.gray,
"MODEL": LGraphCanvas.node_colors.blue,
"LATENT": LGraphCanvas.node_colors.purple,
"VAE": LGraphCanvas.node_colors.red,
"WANVAE": LGraphCanvas.node_colors.red,
"CONDITIONING": LGraphCanvas.node_colors.brown,
"IMAGE": LGraphCanvas.node_colors.pale_blue,
"CLIP": LGraphCanvas.node_colors.yellow,
"FLOAT": LGraphCanvas.node_colors.green,
"MASK": { color: "#1c5715", bgcolor: "#1f401b"},
"INT": { color: "#1b4669", bgcolor: "#29699c"},
"CONTROL_NET": { color: "#156653", bgcolor: "#1c453b"},
"NOISE": { color: "#2e2e2e", bgcolor: "#242121"},
"GUIDER": { color: "#3c7878", bgcolor: "#1c453b"},
"SAMPLER": { color: "#614a4a", bgcolor: "#3b2c2c"},
"SIGMAS": { color: "#485248", bgcolor: "#272e27"},
};
}
const colors = _typeColorMap[type] || LGraphCanvas.node_colors?.gray;
if (colors) {
node.color = colors.color;
node.bgcolor = colors.bgcolor;
}
}
function getDisablePrefix() {
return app.ui.settings.getSettingValue("KJNodes.disablePrefix") ?? false;
}
function prefixedTitle(prefix, name) {
return (getDisablePrefix() ? "" : prefix + "_") + name;
}
function autoColor(node, type) {
if (!app.ui.settings.getSettingValue("KJNodes.nodeAutoColor")) return;
if (type === '*') { node.color = null; node.bgcolor = null; }
else setColorAndBgColor(node, type);
}
function addNodeToSelectedOrCursor(nodeType, side) {
const selected = Object.values(app.canvas.selected_nodes || {});
if (selected.length > 0) {
for (const n of selected) window.kjNodes.addNode(nodeType, n, { side, offset: 30 });
} else {
const canvas = app.canvas, graph = canvas.graph || app.graph;
const node = LiteGraph.createNode(nodeType);
if (!node) return;
node.pos = [canvas.graph_mouse[0], canvas.graph_mouse[1]];
graph.add(node);
canvas.selectNode(node, false);
canvas.setDirty(true, true);
}
}
// Temporary map for paste rename coordination between Set and Get nodes.
// Key: old name, Value: new name. Cleared via setTimeout(0) after each paste cycle.
// This works because both onConfigure calls (Set + Get) fire synchronously within
// the same paste operation, before the timeout clears the entry.
const _pasteRenameMap = new Map();
let _forceShowAllLinks = false;
function getShowLinksMode() {
if (_forceShowAllLinks) return "always";
return app.ui.settings.getSettingValue("KJNodes.showSetGetLinks") ?? "never";
}
const LGraphNode = LiteGraph.LGraphNode
// Cross-graph traversal utilities with lexical scoping for subgraph support.
// Set nodes propagate downward: a Set in a parent graph is visible to all descendant subgraphs.
// Get nodes look upward: a Get searches its own graph first, then parent, then grandparent, etc.
// Duplicate names are allowed across unrelated (sibling) subgraphs.
function findRootGraph(graph) {
if (!graph) return null;
return graph.rootGraph || graph;
}
// Find which SubgraphNode in parentGraph wraps the given subgraph
function findSubgraphNodeFor(parentGraph, innerNode) {
if (!parentGraph?._nodes || !innerNode?.graph) return null;
for (const n of parentGraph._nodes) {
if (n.subgraph && n.subgraph === innerNode.graph) return n;
}
return null;
}
// Walk from a subgraph up to root, returning [graph, parent, grandparent, ..., root]
function getGraphAncestors(graph) {
if (!graph) return [];
const root = findRootGraph(graph);
if (!root || graph === root) return [root];
const chain = [graph];
const visited = new Set([graph]);
let current = graph;
// Walk up: find which SubgraphNode wraps current, then get its parent graph
while (current !== root) {
let found = false;
// Search root nodes
for (const n of root._nodes) {
if (n.subgraph === current) {
chain.push(root);
current = root;
found = true;
break;
}
}
if (found) break;
// Search sibling subgraphs (for nested subgraphs)
const subgraphs = root._subgraphs || root.subgraphs;
if (subgraphs) {
for (const sg of subgraphs.values()) {
if (sg === current || !sg._nodes) continue;
for (const n of sg._nodes) {
if (n.subgraph === current) {
if (visited.has(sg)) { found = false; break; }
visited.add(sg);
chain.push(sg);
current = sg;
found = true;
break;
}
}
if (found) break;
}
}
if (!found) {
// Can't find parent, add root as fallback
if (!chain.includes(root)) chain.push(root);
break;
}
}
return chain;
}
// Get all descendant subgraphs of a graph (children, grandchildren, etc.)
function getGraphDescendants(graph, _visited) {
if (!graph?._nodes) return [];
const visited = _visited || new Set();
if (visited.has(graph)) return [];
visited.add(graph);
const descendants = [];
for (const n of graph._nodes) {
if (n.subgraph && !visited.has(n.subgraph)) {
descendants.push(n.subgraph);
descendants.push(...getGraphDescendants(n.subgraph, visited));
}
}
return descendants;
}
// Collect nodes of a type from specific graphs
function collectNodesOfType(graphs, type) {
const results = [];
for (const g of graphs) {
if (!g?._nodes) continue;
for (const node of g._nodes) {
if (node.type === type) results.push({ node, graph: g });
}
}
return results;
}
// Find all nodes of type across ALL graphs (root + all subgraphs). Used for global operations.
function findAllNodesOfType(graph, type) {
const root = findRootGraph(graph);
if (!root) return [];
const allGraphs = [root];
const subgraphs = root._subgraphs || root.subgraphs;
if (subgraphs) {
for (const sg of subgraphs.values()) allGraphs.push(sg);
}
return collectNodesOfType(allGraphs, type);
}
// Scoped setter lookup: search current graph, then ancestors (look up).
function findSetterByName(graph, name) {
if (!name) return null;
for (const g of getGraphAncestors(graph)) {
if (!g?._nodes) continue;
for (const node of g._nodes) {
if (node.type === 'SetNode' && node.widgets[0].value === name) {
return { node, graph: g };
}
}
}
return null;
}
// Scoped getter lookup: search current graph + descendants (propagate down).
function findGettersByName(graph, name) {
if (!name) return [];
const graphs = [graph, ...getGraphDescendants(graph)];
return collectNodesOfType(graphs, 'GetNode')
.filter(entry => entry.node.widgets[0].value === name);
}
// Get all visible SetNode names for a GetNode's combo dropdown.
// Shows names from current graph + ancestors (what's in scope).
// Also builds a source map for getOptionLabel. This module-level variable is safe
// because the values getter and getOptionLabel run in the same synchronous render pass.
let _setNameSourceMap = new Map();
function getVisibleSetNames(graph, filterType) {
const sourceMap = new Map();
const ancestors = getGraphAncestors(graph);
const entries = collectNodesOfType(ancestors, 'SetNode');
for (const e of entries) {
const name = e.node.widgets[0].value;
if (!name) continue;
if (filterType && filterType !== '*') {
const setType = e.node.inputs[0]?.type;
if (setType && setType !== '*') {
const filterTypes = String(filterType).split(",");
if (!filterTypes.some(ft => ft === setType || setType.split(",").includes(ft))) continue;
}
}
if (!sourceMap.has(name)) {
sourceMap.set(name, e.graph === graph ? "local" : "parent");
}
}
_setNameSourceMap = sourceMap;
return [...sourceMap.keys()].sort();
}
// Exposed globally for use in contextmenu.js
window.kjNodes = window.kjNodes || {};
window.kjNodes.convertOutputsToSetGet = convertOutputsToSetGet;
window.kjNodes.snapshotSelectedNodes = snapshotSelectedNodes;
function convertOutputsToSetGet(graph, node) {
if (!graph || !node) return;
for (let slotIdx = 0; slotIdx < node.outputs.length; slotIdx++) {
const output = node.outputs[slotIdx];
if (!output.links || output.links.length === 0) continue;
const linkType = output.type || "*";
const linkName = output.name || linkType;
// Collect targets and link IDs to remove, skipping existing Set/Get nodes
const targets = [];
const linksToRemove = [];
for (const linkId of [...output.links]) {
const link = getLink(graph, linkId);
if (link) {
const targetNode = graph.getNodeById(link.target_id);
if (targetNode && targetNode.type !== 'SetNode' && targetNode.type !== 'GetNode') {
targets.push({ targetId: link.target_id, targetSlot: link.target_slot });
linksToRemove.push(linkId);
}
}
}
if (targets.length === 0) continue;
// Create Set node
const setNode = LiteGraph.createNode("SetNode");
if (!setNode) continue;
setNode.pos = [
node.pos[0] + node.size[0] + 30,
node.pos[1] + slotIdx * 60
];
graph.add(setNode);
setNode.flags.collapsed = true;
for (const linkId of linksToRemove) graph.removeLink(linkId);
// Connect source → Set node input
node.connect(slotIdx, setNode, 0);
// Set the name widget
setNode.widgets[0].value = linkName;
setNode.title = prefixedTitle("Set", linkName);
setNode.validateName(graph);
const finalName = setNode.widgets[0].value;
setNode.properties.previousName = finalName;
// Create a Get node for each target
for (const target of targets) {
const targetNode = graph.getNodeById(target.targetId);
if (!targetNode) continue;
const getNode = LiteGraph.createNode("GetNode");
if (!getNode) continue;
getNode.pos = [
targetNode.pos[0] - getNode.size[0] - 30,
targetNode.pos[1]
];
graph.add(getNode);
getNode.flags.collapsed = true;
getNode.widgets[0].value = finalName;
getNode.onRename();
getNode.connect(0, targetNode, target.targetSlot);
}
}
app.canvas.setDirty(true, true);
}
// Snapshot selection immediately (before right-click changes it)
function snapshotSelectedNodes(node, typeFilter) {
const selected = Object.values(app.canvas.selected_nodes || {});
// Always include the right-clicked node, even if selection state is inconsistent
const nodeSet = new Set(selected);
nodeSet.add(node);
let nodes = [...nodeSet];
if (typeFilter) nodes = nodes.filter(n => n.type === typeFilter);
return nodes;
}
// Tracks nodes flagged with has_errors so they can be cleared on the next alert.
// Always cleared before repopulating, so it only holds nodes from the most recent alert.
const _errorNodes = new Set();
function showAlert(message, nodes) {
const nodeList = nodes ? (Array.isArray(nodes) ? nodes : [nodes]) : [];
const nodeInfo = nodeList.map(n =>
`${n.title || n.type} [${Math.round(n.pos[0])}, ${Math.round(n.pos[1])}]`
).join(', ');
if (nodeList.length) {
// Clear previous error flags
for (const n of _errorNodes) n.has_errors = false;
_errorNodes.clear();
setTimeout(() => {
for (const n of nodeList) {
n.has_errors = true;
_errorNodes.add(n);
}
app.canvas?.setDirty(true, true);
}, 100);
}
app.extensionManager.toast.add({
severity: 'warn',
summary: "KJ Set/Get",
detail: nodeInfo ? `${message} — ${nodeInfo}` : message,
life: 5000,
});
}
function convertAllSetGetToLinks(graph) {
if (!graph) return;
const rootGraph = findRootGraph(graph);
// First pass: handle cross-graph pairs (must run before same-graph
// because converting cross-graph creates real links that replace
// the Set/Get, and same-graph pass would miss the removed nodes)
const allSetEntries = findAllNodesOfType(rootGraph, 'SetNode');
for (const { node: setNode, graph: setGraph } of [...allSetEntries]) {
const name = setNode.widgets[0].value;
if (!name) continue;
const allGetEntries = findGettersByName(rootGraph, name);
const crossGraphGetters = allGetEntries.filter(e => e.graph !== setGraph);
if (crossGraphGetters.length > 0) {
convertCrossGraphSetGet(setNode, setGraph, crossGraphGetters);
}
}
// Second pass: handle remaining same-graph pairs
for (const { node: setNode, graph: g } of [...findAllNodesOfType(rootGraph, 'SetNode')]) {
convertSetGetToLinks(g, setNode);
}
}
// Compat shim: older frontends may lack graph.getLink(), and _links may be a Map or
// plain object depending on the litegraph version. The == null check catches both null
// and undefined intentionally.
function getLink(graph, linkId) {
if (linkId == null) return null;
if (graph.getLink) return graph.getLink(linkId);
return graph._links instanceof Map ? graph._links.get(linkId) : graph._links?.[linkId] ?? null;
}
// Collect {targetId, targetSlot} from an output slot's links
function collectOutputConnections(graph, output) {
const connections = [];
if (output?.links) {
for (const linkId of [...output.links]) {
const link = getLink(graph, linkId);
if (link) connections.push({ targetId: link.target_id, targetSlot: link.target_slot });
}
}
return connections;
}
function convertCrossGraphSetGet(setNode, setGraph, crossGraphGetters) {
// Find what's connected to the SetNode's input
const setInput = setNode.inputs[0];
if (setInput.link == null) return;
const sourceLink = getLink(setGraph, setInput.link);
if (!sourceLink) return;
const sourceNode = setGraph.getNodeById(sourceLink.origin_id);
if (!sourceNode) return;
const sourceSlot = sourceLink.origin_slot;
const linkType = setNode.inputs[0].type || '*';
for (const { node: getter, graph: getterGraph } of crossGraphGetters) {
// Collect getter's downstream connections before removing it
const connections = collectOutputConnections(getterGraph, getter.outputs[0]);
if (connections.length === 0) {
getterGraph.remove(getter);
continue;
}
// Determine direction and create SubgraphInput or SubgraphOutput
const rootGraph = findRootGraph(setGraph);
const sgNodeForGetter = findSubgraphNodeFor(rootGraph, getter);
const sgNodeForSetter = findSubgraphNodeFor(rootGraph, setNode);
if (sgNodeForGetter && setGraph === rootGraph) {
// Set in root, Get in subgraph → create SubgraphInput
const subgraph = sgNodeForGetter.subgraph;
const inputName = setNode.widgets[0].value || linkType;
const newInput = subgraph.addInput(inputName, linkType);
const inputIndex = subgraph.inputs.indexOf(newInput);
// Connect source → SubgraphNode's new input in root graph
sourceNode.connect(sourceSlot, sgNodeForGetter, inputIndex);
// Inside subgraph: connect SubgraphInput slot → getter's targets
for (const conn of connections) {
if (conn.targetId === subgraph.outputNode?.id) {
// GetNode fed a SubgraphOutput — bypass it and connect source directly in parent graph.
const sgNodeOutput = sgNodeForGetter.outputs[conn.targetSlot];
if (sgNodeOutput?.links) {
for (const parentLinkId of [...sgNodeOutput.links]) {
const parentLink = getLink(rootGraph, parentLinkId);
if (parentLink) {
const parentTarget = rootGraph.getNodeById(parentLink.target_id);
if (parentTarget) {
sourceNode.connect(sourceSlot, parentTarget, parentLink.target_slot);
}
}
}
}
// Remove the now-unnecessary SubgraphOutput
const sgOutput = subgraph.outputs[conn.targetSlot];
if (sgOutput) {
subgraph.removeOutput(sgOutput);
}
} else {
const targetNode = getterGraph.getNodeById(conn.targetId);
if (targetNode) {
newInput.connect(targetNode.inputs[conn.targetSlot], targetNode);
}
}
}
// If no connections used the SubgraphInput, remove it
if (newInput.linkIds.length === 0) {
subgraph.removeInput(newInput);
}
getterGraph.remove(getter);
} else if (sgNodeForSetter && getterGraph === rootGraph) {
// Set in subgraph, Get in root → create SubgraphOutput
const subgraph = sgNodeForSetter.subgraph;
const outputName = setNode.widgets[0].value || linkType;
const newOutput = subgraph.addOutput(outputName, linkType);
const outputIndex = subgraph.outputs.indexOf(newOutput);
// Inside subgraph: connect source output → SubgraphOutput slot
newOutput.connect(sourceNode.outputs[sourceSlot], sourceNode);
// In root graph: connect SubgraphNode's new output → getter's targets
for (const conn of connections) {
const targetNode = getterGraph.getNodeById(conn.targetId);
if (targetNode) {
sgNodeForSetter.connect(outputIndex, targetNode, conn.targetSlot);
}
}
getterGraph.remove(getter);
} else {
// Both in different subgraphs (sibling) — would need both input and output
// Skip for now, too complex
console.warn(`KJNodes: Cannot convert cross-graph Set/Get "${setNode.widgets[0].value}" between sibling subgraphs`);
}
}
// Remove SetNode if all its getters have been handled (check if any same-graph getters remain)
const remainingGetters = setGraph._nodes.filter(
n => n.type === 'GetNode' && n.widgets[0].value === setNode.widgets[0].value
);
if (remainingGetters.length === 0) {
setGraph.remove(setNode);
}
}
function convertSetGetToLinks(graph, setNode) {
if (!graph || !setNode) return;
const name = setNode.widgets[0].value;
let sameGraphGetters = [];
if (name) {
const allGetters = findGettersByName(graph, name);
const crossGetters = [];
for (const entry of allGetters) {
if (entry.graph === graph) sameGraphGetters.push(entry.node);
else crossGetters.push(entry);
}
if (crossGetters.length > 0) {
convertCrossGraphSetGet(setNode, graph, crossGetters);
}
}
// Find the source connected to the Set node's input
const setInput = setNode.inputs[0];
if (setInput.link == null) return;
const sourceLink = getLink(graph, setInput.link);
if (!sourceLink) return;
const sourceNode = graph.getNodeById(sourceLink.origin_id);
if (!sourceNode) return;
const sourceSlot = sourceLink.origin_slot;
// Collect all consumer connections from Get nodes and SetNode's own output passthrough
const connections = [];
for (const getter of sameGraphGetters) {
connections.push(...collectOutputConnections(graph, getter.outputs[0]));
}
connections.push(...collectOutputConnections(graph, setNode.outputs[0]));
// Remove all Get nodes (this also removes their links)
for (const getter of sameGraphGetters) {
graph.remove(getter);
}
// Remove the Set node
graph.remove(setNode);
// Create direct links from source to each consumer
for (const conn of connections) {
const targetNode = graph.getNodeById(conn.targetId);
if (targetNode) {
sourceNode.connect(sourceSlot, targetNode, conn.targetSlot);
}
}
app.canvas?.setDirty(true, true);
}
// region SetNode
app.registerExtension({
name: "KJNodes.SetNode",
registerCustomNodes() {
class SetNode extends LGraphNode {
static title = "Set";
static category = "KJNodes";
serialize_widgets = true;
drawConnection = false;
slotColor = "#FFF";
canvas = app.canvas;
constructor(title) {
super(title)
if (!this.properties) {
this.properties = {
"previousName": ""
};
}
this.properties["Node name for S&R"] = "SetNode";
this.properties["aux_id"] = "kijai/ComfyUI-KJNodes";
this.isVirtualNode = true; // This node is purely frontend and does not impact the resulting prompt so should not be serialized
this.addWidget(
"text",
"Constant",
'',
() => {
if (!this.graph || app.configuringGraph) return;
this.validateName(this.graph);
if (this.widgets[0].value !== '') {
this.title = prefixedTitle("Set", this.widgets[0].value);
}
this.update();
this.properties.previousName = this.widgets[0].value;
},
{}
)
this.addInput("*", "*");
this.addOutput("*", '*');
}
onConnectionsChange(
slotType,
slot,
isChangeConnect,
link_info
) {
// During graph load, slots are restored by configure — skip side effects
if (app.configuringGraph) return;
//On Disconnect
if (slotType === LiteGraph.INPUT && !isChangeConnect) {
const outputConnected = this.outputs[0]?.links?.length > 0;
if (outputConnected) {
this.inputs[slot].type = this.outputs[0].type;
this.inputs[slot].name = this.outputs[0].name;
} else {
this.inputs[slot].type = '*';
this.inputs[slot].name = '*';
this.outputs[0].type = '*';
this.outputs[0].name = '*';
this.title = "Set";
this.color = null;
this.bgcolor = null;
}
this.update();
}
if (slotType === LiteGraph.OUTPUT && !isChangeConnect) {
if (this.outputs && this.outputs[slot]) {
// Keep type if input has a real connection
const inputConnected = this.inputs[0]?.link != null;
if (inputConnected) {
this.outputs[slot].type = this.inputs[0].type;
this.outputs[slot].name = this.inputs[0].name;
} else {
this.inputs[0].type = '*';
this.inputs[0].name = '*';
this.outputs[slot].type = '*';
this.outputs[slot].name = '*';
this.color = null;
this.bgcolor = null;
}
}
}
//On Connect
if (link_info && this.graph && slotType === LiteGraph.INPUT && isChangeConnect) {
const resolve = link_info.resolve(this.graph)
const resolvedSlot = resolve?.subgraphInput ?? resolve?.output;
const type = resolvedSlot?.type;
if (type) {
if (this.title === "Set"){
this.title = prefixedTitle("Set", type);
}
if (this.widgets[0].value === '' || this.widgets[0].value === '*'){
// Determine the initial widget value based on naming setting
const namingMode = app.ui.settings.getSettingValue("KJNodes.setGetNaming") ?? "empty";
if (namingMode !== "empty") {
const link = getLink(this.graph, this.inputs[0]?.link);
const sourceNode = link ? this.graph.getNodeById(link.origin_id) : null;
const slotName = sourceNode?.outputs?.[link?.origin_slot]?.name || type;
switch (namingMode) {
case "slot name": this.widgets[0].value = slotName; break;
case "slot name (lowercase)": this.widgets[0].value = slotName.toLowerCase(); break;
case "slot name (UPPERCASE)": this.widgets[0].value = slotName.toUpperCase(); break;
}
}
}
this.validateName(this.graph);
this.properties.previousName = this.widgets[0].value;
this.inputs[0].type = type;
this.inputs[0].name = type;
this.outputs[0].type = type;
this.outputs[0].name = type;
autoColor(this, type);
} else {
showAlert(`node ${this.title} input undefined.`, this)
}
}
if (link_info && this.graph && slotType === LiteGraph.OUTPUT && isChangeConnect) {
const inputType = this.inputs[0]?.type;
if (inputType && inputType !== '*') {
this.outputs[0].type = inputType;
this.outputs[0].name = inputType;
} else {
const resolve = link_info.resolve(this.graph);
const type = resolve?.input?.type;
if (type && type !== '*') {
this.inputs[0].type = type;
this.inputs[0].name = type;
this.outputs[0].type = type;
this.outputs[0].name = type;
autoColor(this, type);
}
}
}
//Update either way
this.update();
}
// Returns true if the name was changed
validateName(graph, sameGraphOnly) {
let widgetValue = this.widgets[0].value;
if (widgetValue !== '') {
let tries = 0;
const existingValues = new Set();
// sameGraphOnly: only check the immediate graph (for paste/clone)
// otherwise check full scope (own graph + ancestors)
const scopeGraphs = sameGraphOnly ? [graph] : getGraphAncestors(graph);
const scopedSetNodes = collectNodesOfType(scopeGraphs, 'SetNode');
scopedSetNodes.forEach(entry => {
if (entry.node !== this) {
existingValues.add(entry.node.widgets[0].value);
}
});
const originalValue = widgetValue;
// Only strip _N suffix during paste to avoid FOO_0_1_2 accumulation.
// For manual renames, keep the full name as base (user may intend FOO_3).
const baseName = this._justAdded ? widgetValue.replace(/_\d+$/, '') : widgetValue;
while (existingValues.has(widgetValue)) {
widgetValue = baseName + "_" + tries;
tries++;
}
this.widgets[0].value = widgetValue;
this.title = prefixedTitle("Set", widgetValue);
return widgetValue !== originalValue;
}
return false;
}
clone() {
const cloned = super.clone();
cloned.inputs[0].name = '*';
cloned.inputs[0].type = '*';
cloned.properties.previousName = '';
cloned.size = cloned.computeSize();
return cloned;
}
onAdded() {
this._justAdded = true;
}
onConfigure() {
// Only run paste logic when actually pasting, not during workflow load
if (this._justAdded && this.graph && !app.configuringGraph) {
const oldName = this.widgets[0].value;
this.validateName(this.graph, true);
this._justAdded = false;
const newName = this.widgets[0].value;
if (newName !== oldName) {
_pasteRenameMap.set(oldName, newName);
// Clear the map after this paste cycle
setTimeout(() => _pasteRenameMap.delete(oldName), 0);
}
// Reset type and color on paste — nothing is connected yet
if (this.inputs[0]?.link == null) {
this.inputs[0].type = '*';
this.inputs[0].name = '*';
this.outputs[0].type = '*';
this.outputs[0].name = '*';
this.color = null;
this.bgcolor = null;
}
}
this._justAdded = false;
}
update() {
if (!this.graph) return;
const getters = this.findGetters(this.graph);
getters.forEach(getter => {
getter.setType(this.inputs[0].type);
});
if (this.widgets[0].value && this.properties.previousName) {
const gettersWithPreviousName = this.findGetters(this.graph, true);
gettersWithPreviousName.forEach(getter => {
getter.setName(this.widgets[0].value);
});
}
app.canvas?.setDirty(true, true);
}
findGetters(graph, checkForPreviousName) {
const name = checkForPreviousName ? this.properties.previousName : this.widgets[0].value;
if (!name || name === '') return [];
// Scoped: searches own graph + descendant subgraphs
return findGettersByName(graph, name).map(entry => entry.node);
}
getExtraMenuOptions(_, options) {
options.unshift(
{
content: this.drawConnection ? "Hide connections" : "Show connections",
callback: () => {
this.drawConnection = !this.drawConnection;
const linkType = this.inputs[0].type;
this.slotColor = this.canvas.default_connection_color_byType[linkType];
this.canvas.setDirty(true, true);
},
},
{
content: "Hide all connections",
callback: () => {
for (const n of this.graph._nodes) {
if (n.type === "GetNode" || n.type === "SetNode") n.drawConnection = false;
}
this.canvas.setDirty(true, true);
},
},
);
options.unshift({
content: "Convert to links",
callback: () => {
const graph = this.graph;
for (const n of snapshotSelectedNodes(this, 'SetNode')) convertSetGetToLinks(graph, n);
},
});
options.unshift({
content: "Add paired GetNode",
callback: () => {
const graph = this.graph;
const getNode = LiteGraph.createNode("GetNode");
if (!getNode) return;
getNode.pos = [this.pos[0] + this.size[0] + 30, this.pos[1]];
graph.add(getNode);
// Set the widget value to match — this drives type, color, and connection
const name = this.widgets[0].value;
if (getNode.widgets?.[0]) {
getNode.widgets[0].value = name;
}
getNode.onRename?.();
app.canvas.selectNode(getNode, false);
app.canvas.setDirty(true, true);
},
});
// Dynamically add a submenu for all getters
const allGettersForMenu = this.findGetters(this.graph);
if (allGettersForMenu.length) {
let gettersSubmenu = allGettersForMenu.map(getter => {
const sameGraph = getter.graph === this.graph;
const sgNode = !sameGraph ? findSubgraphNodeFor(this.graph, getter) : null;
const label = sameGraph
? `${getter.title} id: ${getter.id}`
: `${getter.title} (in subgraph${sgNode ? ': ' + (sgNode.title || sgNode.type) : ''})`;
return {
content: label,
callback: () => {
if (sameGraph) {
this.canvas.centerOnNode(getter);
this.canvas.selectNode(getter, false);
} else if (sgNode) {
this.canvas.openSubgraph(sgNode.subgraph, sgNode);
// Center on the getter after entering the subgraph
setTimeout(() => {
this.canvas.centerOnNode(getter);
this.canvas.selectNode(getter, false);
}, 0);
}
this.canvas.setDirty(true, true);
},
};
});
options.unshift({
content: "Getters",
has_submenu: true,
submenu: {
title: "GetNodes",
options: gettersSubmenu,
}
});
}
}
}
LiteGraph.registerNodeType("SetNode", SetNode);
},
});
// region GetNode
app.registerExtension({
name: "KJNodes.GetNode",
registerCustomNodes() {
class GetNode extends LGraphNode {
static title = "Get";
static category = "KJNodes";
serialize_widgets = true;
drawConnection = false;
currentSetter = null;
canvas = app.canvas;
constructor(title) {
super(title)
if (!this.properties) {
this.properties = {};
}
this.properties["Node name for S&R"] = "GetNode";
this.properties["aux_id"] = "kijai/ComfyUI-KJNodes";
this.isVirtualNode = true; // This node is purely frontend and does not impact the resulting prompt so should not be serialized
const comboOptions = {
getOptionLabel: (value) => {
if (!value) return "";
const source = _setNameSourceMap.get(value);
if (!source || source === "local") return value;
return `${value} (${source})`;
},
};
Object.defineProperty(comboOptions, 'values', {
get: () => {
if (!this.graph) return [];
let filterType = null;
if (app.ui.settings.getSettingValue("KJNodes.filterGetNodeOptions") !== false
&& this.outputs[0]?.links?.length) {
const linkId = this.outputs[0].links[0];
const link = getLink(this.graph, linkId);
if (link) {
const targetNode = this.graph.getNodeById(link.target_id);
filterType = targetNode?.inputs?.[link.target_slot]?.type || null;
}
}
return getVisibleSetNames(this.graph, filterType);
},
enumerable: true,
configurable: true
});
this.addWidget("combo", "Constant", "", () => { if (!app.configuringGraph) this.onRename(); }, comboOptions)
this.addOutput("*", '*');
}
onConnectionsChange() {
if (app.configuringGraph) return;
this.validateLinks();
}
setName(name) {
this.widgets[0].value = name;
this.onRename();
this.serialize();
}
onRename() {
const setter = this.findSetter(this.graph);
if (setter) {
this.setType(setter.inputs[0].type);
this.title = prefixedTitle("Get", setter.widgets[0].value);
} else {
this.setType('*');
const name = this.widgets[0].value;
this.title = name ? prefixedTitle("Get", name) : "Get";
}
app.canvas?.setDirty(true, true);
}
clone() {
const cloned = super.clone();
cloned.size = cloned.computeSize();
return cloned;
}
validateLinks() {
if (this.outputs[0].type !== '*' && this.outputs[0].links && this.graph) {
this.outputs[0].links.filter(linkId => {
const link = getLink(this.graph, linkId);
if (!link || !link.type) return false;
if (link.type === '*') return false;
const targetNode = this.graph.getNodeById(link.target_id);
const targetType = targetNode?.inputs?.[link.target_slot]?.type;
if (targetType === '*') return false;
if (targetType) {
const targetTypes = String(targetType).split(",");
if (targetTypes.includes(this.outputs[0].type)) return false;
}
return !link.type.split(",").includes(this.outputs[0].type);
}).forEach(linkId => {
this.graph.removeLink(linkId);
});
}
}
setType(type) {
this.outputs[0].name = type;
this.outputs[0].type = type;
this.validateLinks();
autoColor(this, type);
}
findSetter(graph) {
const name = this.widgets[0].value;
// Scoped: searches own graph first, then ancestors
const result = findSetterByName(graph, name);
return result ? result.node : undefined;
}
goToSetter() {
if (!this.currentSetter) return;
const setterGraph = this.currentSetter.graph;
if (setterGraph && setterGraph !== this.graph) {
this.canvas.setGraph(setterGraph);
setTimeout(() => {
this.canvas.centerOnNode(this.currentSetter);
this.canvas.selectNode(this.currentSetter, false);
this.canvas.setDirty(true, true);
}, 0);
} else {
this.canvas.centerOnNode(this.currentSetter);
this.canvas.selectNode(this.currentSetter, false);
}
}
onAdded() {
this._justAdded = true;
}
onConfigure() {
if (this._justAdded && !app.configuringGraph) {
const name = this.widgets[0].value;
if (name) {
// Check if our paired SetNode was renamed during this paste
const newName = _pasteRenameMap.get(name);
if (newName) {
this.widgets[0].value = newName;
}
// Restore type/color from setter after paste
setTimeout(() => this.onRename(), 0);
}
}
this._justAdded = false;
}
getInputLink(slot) {
// Same-graph: standard resolveOutput path.
// Cross-graph: handled by resolveVirtualOutput.
const name = this.widgets[0].value;
if (!name || name === '') return null;
const setter = this.graph?._nodes?.find(
n => n.type === 'SetNode' && n.widgets[0].value === name
);
if (setter) {
const slotInfo = setter.inputs[slot];
if (!slotInfo || slotInfo.link == null) return null;
return getLink(this.graph, slotInfo.link);
}
// Scoped lookup: no setter found in own graph or ancestors
if (name && !findSetterByName(this.graph, name)) {
showAlert("No SetNode found for " + name + "(" + this.type + ")", this);
}
return null;
}
resolveVirtualOutput(slot) {
const name = this.widgets[0].value;
// Scoped lookup: own graph first, then ancestors
const result = findSetterByName(this.graph, name);
if (!result) return undefined;
// Same graph — let the standard getInputLink path handle it
if (result.graph === this.graph) return undefined;
// Warn if multiple SetNodes with this name exist in scope
const scopeGraphs = getGraphAncestors(this.graph);
const scopedSetters = collectNodesOfType(scopeGraphs, 'SetNode')
.filter(e => e.node.widgets[0].value === name);
if (scopedSetters.length > 1) {
showAlert(`Multiple SetNodes named "${name}" found in scope. Rename duplicates or use "Convert to links" to resolve`, [this, ...scopedSetters.map(e => e.node)]);
return undefined;
}
const { node: setter, graph: setterGraph } = result;
const slotInfo = setter.inputs[slot];
if (!slotInfo || slotInfo.link == null) return undefined;
const link = getLink(setterGraph, slotInfo.link);
if (!link) return undefined;
const sourceNode = setterGraph.getNodeById(link.origin_id);
if (!sourceNode) return undefined;
return { node: sourceNode, slot: link.origin_slot };
}
getExtraMenuOptions(_, options) {
this.currentSetter = this.findSetter(this.graph)
if (!this.currentSetter) return
const sameGraph = this.currentSetter.graph === this.graph;
if (sameGraph) {
let menuEntry = this.drawConnection ? "Hide connections" : "Show connections";
options.unshift(
{
content: "Convert to links",
callback: () => {
const graph = this.graph;
const setters = new Set(snapshotSelectedNodes(this, 'GetNode')
.map(n => n.findSetter?.(graph)).filter(Boolean));
for (const s of setters) convertSetGetToLinks(graph, s);
},
},
{
content: "Go to setter",
callback: () => {
this.goToSetter();
},
},
{
content: menuEntry,
callback: () => {
if (!this.currentSetter) return;
const linkType = this.currentSetter.inputs[0].type;
// Toggle on the SetNode so the canvas-level hook draws it
this.currentSetter.drawConnection = !this.currentSetter.drawConnection;
this.currentSetter.slotColor = this.canvas.default_connection_color_byType[linkType];
this.drawConnection = this.currentSetter.drawConnection;
this.canvas.setDirty(true, true);
},
},
);
} else {
// Cross-graph setter — navigate to its graph
const setterGraph = this.currentSetter.graph;
const isRoot = setterGraph === findRootGraph(this.graph);
options.unshift(
{
content: `Go to setter (in ${isRoot ? 'parent graph' : 'subgraph'})`,
callback: () => {
const canvas = this.canvas;
canvas.setGraph(setterGraph);
setTimeout(() => {
canvas.centerOnNode(this.currentSetter);
canvas.selectNode(this.currentSetter, false);
canvas.setDirty(true, true);
}, 0);
},
},
);
}
}
}
LiteGraph.registerNodeType("GetNode", GetNode);
},
});
// region UI: commands, keybindings, canvas menu, draw hook, settings
app.registerExtension({
name: "KJNodes.SetGetUI",
settings: [
{
id: "KJNodes.setGetNaming",
name: "Default SetNode widget value",
category: ["KJNodes", "Set & Get", "Default SetNode widget value"],
tooltip: "Initial Constant value when a Set node is first connected to a slot",
type: "combo",
options: ["empty", "slot name", "slot name (lowercase)", "slot name (UPPERCASE)"],
defaultValue: "empty",
},
{
id: "KJNodes.showSetGetLinks",
name: "Show links",
category: ["KJNodes", "Set & Get", "Show links"],
tooltip: "When to show virtual links between Set/Get pairs",
type: "combo",
options: ["never", "selected", "always"],
defaultValue: "never",
onChange: () => app.canvas?.setDirty(true, true),
},
],
commands: [
{
id: "KJNodes.AddSetNodeToSelected",
label: "Add Set node to selected / at cursor",
function: () => addNodeToSelectedOrCursor("SetNode", "right"),
},
{
id: "KJNodes.AddGetNodeAtCursor",
label: "Add Get node to selected / at cursor",
function: () => addNodeToSelectedOrCursor("GetNode", "left"),
},
{
id: "KJNodes.ToggleForceShowSetGetLinks",
label: "Toggle force-show all Set/Get connections",
function: () => {
_forceShowAllLinks = !_forceShowAllLinks;
app.canvas.setDirty(true, true);
},
},
],
keybindings: [
{
commandId: "KJNodes.AddSetNodeToSelected",
combo: { key: "s", ctrl: true, shift: true },
targetElementId: "graph-canvas",
},
{
commandId: "KJNodes.AddGetNodeAtCursor",
combo: { key: "g", ctrl: true, shift: true },
targetElementId: "graph-canvas",
},
{
commandId: "KJNodes.ToggleForceShowSetGetLinks",
combo: { key: "l", ctrl: true, shift: true },
targetElementId: "graph-canvas",
},
],
getCanvasMenuItems() {
return [
{
content: "KJNodes",
has_submenu: true,
submenu: {
options: [
{
content: "Convert outputs on all selected nodes to Set/Get",
callback: () => {
const selected = Object.values(app.canvas.selected_nodes || {});
if (selected.length === 0) return;
for (const n of selected) convertOutputsToSetGet(app.graph, n);
},
},
{
content: "Convert selected Set/Get to links",
callback: () => {
const graph = app.graph;
const selected = Object.values(app.canvas.selected_nodes || {});
const setNodes = selected.filter(n => n.type === 'SetNode');
const getNodes = selected.filter(n => n.type === 'GetNode');
for (const n of setNodes) convertSetGetToLinks(graph, n);
const setters = new Set(getNodes.map(n => n.findSetter?.(graph)).filter(Boolean));
for (const s of setters) convertSetGetToLinks(graph, s);
},
},
],
},
},
];
},
setup() {
// Double-click GetNode to jump to its SetNode (works in both legacy and Vue modes)
document.addEventListener("dblclick", (e) => {
// Don't interfere when a ContextMenu (e.g. combo dropdown) is open
if (document.querySelector(".litecontextmenu")) return;
const canvas = app.canvas;
if (!canvas) return;
const selected = Object.values(canvas.selected_nodes || {});
if (selected.length !== 1) return;
const node = selected[0];
if (node.type === "GetNode") {
node.currentSetter = node.findSetter(node.graph);
if (node.currentSetter) node.goToSetter();
}
});
// Suppress title rename on collapsed GetNodes so double-click navigates instead
document.addEventListener("litegraph:canvas", (e) => {
if (e.detail?.subType !== 'node-double-click') return;
const node = e.detail.node;
if (node?.type === "GetNode" && node.flags?.collapsed) {
e.stopImmediatePropagation();
}
});
// Monkey-patch: no extension hook exists for filtering visible nodes.
// Keep Set/Get nodes with visible virtual connections in the visible set
// even when offscreen, so the link lines don't get clipped.
const originalComputeVisibleNodes = LGraphCanvas.prototype.computeVisibleNodes;
LGraphCanvas.prototype.computeVisibleNodes = function () {
const visible = originalComputeVisibleNodes.apply(this, arguments);
for (const node of this.graph._nodes) {
if ((node.type === "SetNode" || node.type === "GetNode") && node.drawConnection && !visible.includes(node)) {
visible.push(node);
}
}
return visible;
};
// Monkey-patch: no extension hook exists for custom canvas drawing.
// Draws virtual links between Set/Get pairs.
// Handles per-node "Show connections", "selected" mode, and "always" mode.
const origCanvasOnDrawBackground = app.canvas.onDrawBackground;
app.canvas.onDrawBackground = function(ctx, visibleArea) {
origCanvasOnDrawBackground?.call(this, ctx, visibleArea);
const graph = this.graph || app.graph;
if (!graph?._nodes) return;
const mode = getShowLinksMode();
// Build set of selected Set/Get names for "selected" mode
let selectedNames = null;
if (mode === "selected") {
const sel = Object.values(this.selected_nodes || {});
if (!sel.length) {
// No selection — still honor per-node drawConnection
if (!graph._nodes.some(n => n.type === 'SetNode' && n.drawConnection)) return;
} else {
selectedNames = new Set();
for (const n of sel) {
if (n.type === 'SetNode' || n.type === 'GetNode') {
selectedNames.add(n.widgets?.[0]?.value ?? n.title);
}
}
if (!selectedNames.size && !graph._nodes.some(n => n.type === 'SetNode' && n.drawConnection)) return;
}
} else if (mode === "never") {
if (!graph._nodes.some(n => n.type === 'SetNode' && n.drawConnection)) return;
}
// Collect all GetNodes once across current graph + descendants, grouped by name.
// This avoids re-discovering descendant graphs and re-scanning nodes per SetNode.
const gettersByName = new Map();
const scopeGraphs = [graph, ...getGraphDescendants(graph)];
for (const g of scopeGraphs) {
if (!g?._nodes) continue;
for (const node of g._nodes) {
if (node.type !== 'GetNode') continue;
const n = node.widgets?.[0]?.value;
if (!n) continue;
let list = gettersByName.get(n);
if (!list) { list = []; gettersByName.set(n, list); }
list.push(node);
}
}
for (const setNode of graph._nodes) {
if (setNode.type !== 'SetNode') continue;
const name = setNode.widgets?.[0]?.value ?? setNode.title;
const showByMode = mode === "always" || (mode === "selected" && selectedNames?.has(name));
if (!showByMode && !setNode.drawConnection) continue;
const allGetters = gettersByName.get(name) || [];
const drawTargets = [];
const seenSubgraphs = new Set();
for (const getter of allGetters) {
if (getter.graph === graph) {
drawTargets.push(getter);
} else {
const sgNode = findSubgraphNodeFor(graph, getter);
if (sgNode && !seenSubgraphs.has(sgNode)) {
seenSubgraphs.add(sgNode);
drawTargets.push(sgNode);
}
}
}
if (!drawTargets.length) continue;
const linkType = setNode.inputs[0]?.type;
const slotColor = app.canvas.default_connection_color_byType?.[linkType]
|| LGraphCanvas.link_type_colors?.[linkType]
|| setNode.bgcolor
|| (setNode.slotColor !== "#FFF" ? setNode.slotColor : null) || "#AAA";
const startPos = setNode.getConnectionPos(false, 0);
for (const target of drawTargets) {
const endPos = target.getConnectionPos(true, 0);
const highlighted = setNode.is_selected || target.is_selected;
const color = highlighted ? "#FFF" : slotColor;
app.canvas.renderLink(
ctx,
startPos,
endPos,
null,
false,
null,
color,
LiteGraph.RIGHT,
LiteGraph.LEFT
);
}
}
};
app.ui.settings.addSetting({
id: "KJNodes.filterGetNodeOptions",
name: "Filter Get node options by type",
category: ["KJNodes", "Set & Get", "Filter Get node options by type"],
tooltip: "When a Get node is connected, only show Set nodes with compatible types in the dropdown",
type: "boolean",
defaultValue: true,
});
app.ui.settings.addSetting({
id: "KJNodes.convertAllSetGet",
name: "Convert ALL Set/Get to links",
category: ["KJNodes", "Set & Get", "Convert ALL Set/Get to links"],
tooltip: "Replaces all Set/Get node pairs with direct links, including across subgraph boundaries (irreversible)",
type: () => {
const btn = document.createElement("button");
btn.textContent = "Convert ALL Set/Get to links";
btn.style.cssText = "padding: 6px 12px; cursor: pointer;";
btn.onclick = () => {
if (confirm("This will replace ALL Set/Get pairs with direct links. This is irreversible. Continue?")) {
convertAllSetGetToLinks(app.graph);
app.canvas?.setDirty(true, true);
app.extensionManager.toast.add({
severity: 'info',
summary: "KJ Set/Get",
detail: "All Set/Get nodes converted to direct links",
life: 3000,
});
}
};
return btn;
},
defaultValue: false,
});
}
});
// Temporary backwards-compat patch: makes cross-subgraph Set/Get work on frontends
// that don't natively support resolveVirtualOutput. Remove when no longer needed.
app.registerExtension({
name: "KJNodes.CrossGraphSetGet",
setup() {
let patched = false;
const originalGraphToPrompt = app.graphToPrompt.bind(app);
app.graphToPrompt = async function(...args) {
if (!patched) {
try {
const subgraphNode = app.graph._nodes.find(n => typeof n.getInnerNodes === 'function');
if (subgraphNode) {
const tempMap = new Map();
const dtos = subgraphNode.getInnerNodes(tempMap, []);
if (dtos.length > 0) {
const proto = Object.getPrototypeOf(dtos[0]);
const DtoClass = proto.constructor;
const nativeSource = proto.resolveOutput.toString();
const hasNativeSupport = nativeSource.includes('resolveVirtualOutput');
console.log(`[KJNodes] Cross-graph Set/Get: frontend native support ${hasNativeSupport ? 'detected, skipping patch' : 'not found, applying patch'}`);
if (!hasNativeSupport) {
const origResolveOutput = proto.resolveOutput;
proto.resolveOutput = function(slot, type, visited) {
if (typeof this.node?.resolveVirtualOutput === 'function') {
const virtualSource = this.node.resolveVirtualOutput(slot);
if (virtualSource) {
const inputNodeDto = [...this.nodesByExecutionId.values()]
.find(dto => dto instanceof DtoClass && dto.node === virtualSource.node);
if (inputNodeDto) {
return inputNodeDto.resolveOutput(virtualSource.slot, type, visited);
}
throw new Error(`KJNodes: No DTO found for cross-graph source node [${virtualSource.node.id}]`);
}
}
return origResolveOutput.call(this, slot, type, visited);
};
}
patched = true;
}
}
} catch (e) {
console.warn('[KJNodes] Failed to probe ExecutableNodeDTO for cross-graph patch:', e);
}
}
return originalGraphToPrompt(...args);
};
}
});
// Monkey-patch: no hook exists to extend the link context menu.
// Appends a "Convert to Set/Get" entry by counting DOM menus before/after
// the original call to find the newly created one. Fragile but unavoidable.
app.registerExtension({
name: "KJNodes.LinkToSetGet",
setup() {
const originalShowLinkMenu = LGraphCanvas.prototype.showLinkMenu;
LGraphCanvas.prototype.showLinkMenu = function(segment, e) {
const menusBefore = document.querySelectorAll(".litecontextmenu").length;
const result = originalShowLinkMenu.call(this, segment, e);
const graph = this.graph;
if (!graph) return result;
// Get the full link object to access target info
const link = getLink(graph, segment.id);
if (!link || link.origin_id == null || link.target_id == null) return result;
// Find the newly created context menu
const menus = document.querySelectorAll(".litecontextmenu");
if (menus.length <= menusBefore) return result;
const lastMenu = menus[menus.length - 1];
if (!lastMenu) return result;
const entries = lastMenu.querySelector(".litemenu-entry")?.parentElement;
if (!entries) return result;
// Create separator
const separator = document.createElement("div");
separator.className = "litemenu-entry separator";
entries.appendChild(separator);
// Create menu entry
const menuItem = document.createElement("div");
menuItem.className = "litemenu-entry submenu";
menuItem.textContent = "Convert to Set/Get";
entries.appendChild(menuItem);
const canvas = this;
menuItem.addEventListener("click", function() {
// Close menu
lastMenu.remove();
const originNode = graph.getNodeById(link.origin_id);
const targetNode = graph.getNodeById(link.target_id);
if (!originNode || !targetNode) return;
const outputSlot = originNode.outputs[link.origin_slot];
const linkType = outputSlot?.type || "*";
const linkName = outputSlot?.name || linkType;
// Create Set node near the source
const setNode = LiteGraph.createNode("SetNode");
if (!setNode) return;
setNode.pos = [
originNode.pos[0] + originNode.size[0] + 30,
originNode.pos[1]
];
graph.add(setNode);
// Create Get node near the target
const getNode = LiteGraph.createNode("GetNode");
if (!getNode) return;
graph.add(getNode);
getNode.pos = [
targetNode.pos[0] - getNode.size[0] - 30,
targetNode.pos[1]
];
// Remove the original link
graph.removeLink(link.id);
// Connect source -> Set node input
originNode.connect(link.origin_slot, setNode, 0);
// Set the name widget on the Set node
setNode.widgets[0].value = linkName;
setNode.title = prefixedTitle("Set", linkName);
setNode.validateName(graph);
setNode.properties.previousName = setNode.widgets[0].value;
// Update Get node to match
const finalName = setNode.widgets[0].value;
getNode.widgets[0].value = finalName;
getNode.onRename();
// Connect Get node output -> target node input
getNode.connect(0, targetNode, link.target_slot);
canvas.setDirty(true, true);
});
return result;
};
}
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230const { app } = window.comfyAPI.app;
// ─── General-purpose helpers shared across KJNodes JS ───
export function makeUUID() {
let dt = new Date().getTime()
const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = ((dt + Math.random() * 16) % 16) | 0
dt = Math.floor(dt / 16)
return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16)
})
return uuid
}
export function chainCallback(object, property, callback) {
if (object == undefined) {
console.error("Tried to add callback to non-existant object")
return;
}
if (property in object) {
const callback_orig = object[property]
object[property] = function () {
const r = callback_orig.apply(this, arguments);
callback.apply(this, arguments);
return r
};
} else {
object[property] = callback;
}
}
export function hideWidgetForGood(node, widget, suffix = '') {
widget.origType = widget.type
widget.origComputeSize = widget.computeSize
widget.origSerializeValue = widget.serializeValue
widget.computeSize = () => [0, -4]
widget.type = "converted-widget" + suffix
if (widget.linkedWidgets) {
for (const w of widget.linkedWidgets) {
hideWidgetForGood(node, w, ':' + widget.name)
}
}
}
// ─── Graph coordinate helpers ───
export function clientToCanvas(lgCanvas, clientX, clientY) {
const rect = lgCanvas.canvas.getBoundingClientRect();
return [
(clientX - rect.left) / lgCanvas.ds.scale - lgCanvas.ds.offset[0],
(clientY - rect.top) / lgCanvas.ds.scale - lgCanvas.ds.offset[1],
];
}
export function getNodeAtPoint(graph, cx, cy) {
for (let i = graph._nodes.length - 1; i >= 0; i--) {
if (graph._nodes[i].isPointInside(cx, cy)) return graph._nodes[i];
}
return null;
}
export function typesCompatible(a, b) {
if (a === "*" || b === "*") return true;
if (a === b) return true;
if (typeof a === "string" && typeof b === "string" && a.toUpperCase() === b.toUpperCase()) return true;
return false;
}
// ─── Slot position helper ───
// Uses modern API (DOM-registered positions in Vue mode) with legacy fallback
export function getSlotPos(node, isInput, slotIdx) {
if (isInput && node.getInputPos) return node.getInputPos(slotIdx);
if (!isInput && node.getOutputPos) return node.getOutputPos(slotIdx);
const out = [0, 0];
node.getConnectionPos(isInput, slotIdx, out);
return out;
}
// ─── Middle-click pan passthrough for DOM widgets ───
// Allows panning the LiteGraph canvas via middle-click drag on any DOM element
export function addMiddleClickPan(element) {
const onMouseDown = (e) => {
if (e.button !== 1) return;
e.preventDefault();
const ds = app.canvas?.ds;
if (!ds) return;
const startX = e.clientX, startY = e.clientY;
const startOffsetX = ds.offset[0], startOffsetY = ds.offset[1];
const onMove = (me) => {
ds.offset[0] = startOffsetX + (me.clientX - startX);
ds.offset[1] = startOffsetY + (me.clientY - startY);
app.canvas.setDirty(true, true);
};
const onUp = () => {
document.removeEventListener('mousemove', onMove);
document.removeEventListener('mouseup', onUp);
};
document.addEventListener('mousemove', onMove);
document.addEventListener('mouseup', onUp);
};
element.addEventListener('mousedown', onMouseDown);
return () => element.removeEventListener('mousedown', onMouseDown);
}
// ─── Resolve preview image/video from a connected source node ───
// Walks the graph link to find what's connected to node.inputs[inputSlot]
// and returns { url, isVideo, videoEl } or null
export function resolveSourcePreview(node, inputSlot) {
if (!node.graph) return null;
const input = node.inputs?.[inputSlot];
if (!input || input.link == null) return null;
const link = node.graph.links?.[input.link] ?? node.graph.links?.get?.(input.link);
if (!link) return null;
const srcNode = node.graph.getNodeById(link.origin_id);
if (!srcNode) return null;
// Check for VHS-style video preview widget
const vpWidget = srcNode.widgets?.find((w) => w.name === "videopreview");
if (vpWidget?.videoEl?.src) {
return { isVideo: true, videoEl: vpWidget.videoEl };
}
// Look for a LoadImage "image" widget or LoadVideo "video" widget
const w = srcNode.widgets?.find((w) => w.name === "image" || w.name === "video");
if (w?.value) {
let subfolder = "", fname = w.value;
const lastSlash = fname.lastIndexOf("/");
if (lastSlash >= 0) { subfolder = fname.substring(0, lastSlash); fname = fname.substring(lastSlash + 1); }
const isVideo = w.name === "video";
const url = `/view?filename=${encodeURIComponent(fname)}&type=input&subfolder=${encodeURIComponent(subfolder)}`;
return { url, isVideo };
}
// Fallback: check node.imgs (set after execution)
if (srcNode.imgs?.length > 0 && srcNode.imgs[0].src) {
return { url: srcNode.imgs[0].src, isVideo: false };
}
return null;
}
// ─── Source input watcher ───
// Watches a named IMAGE input for connection changes and source widget changes.
// Calls onChange(sources) when connections change or the source node's image/video widget changes.
// sources: array of { url, isVideo, videoEl } per connected IMAGE input matching inputName (or all if inputName is null).
// Returns a cleanup function.
export function watchImageInputs(node, inputName, onChange) {
let watchedWidgets = [];
function unwatchWidgets() {
for (const { widget, origCb } of watchedWidgets) widget.callback = origCb;
watchedWidgets = [];
}
function resolve() {
if (!node.inputs) return [];
const slots = inputName
? node.inputs.map((inp, i) => inp.name === inputName ? i : -1).filter(i => i >= 0)
: node.inputs.map((inp, i) => inp.type === "IMAGE" ? i : -1).filter(i => i >= 0);
return slots.map(i => resolveSourcePreview(node, i)).filter(s => s !== null);
}
function watch() {
unwatchWidgets();
if (!node.inputs || !node.graph) return;
const slots = inputName
? node.inputs.map((inp, i) => inp.name === inputName ? i : -1).filter(i => i >= 0)
: node.inputs.map((inp, i) => inp.type === "IMAGE" ? i : -1).filter(i => i >= 0);
for (const slotIdx of slots) {
const input = node.inputs[slotIdx];
if (!input || input.link == null) continue;
const link = node.graph.links?.[input.link] ?? node.graph.links?.get?.(input.link);
if (!link) continue;
const srcNode = node.graph.getNodeById(link.origin_id);
if (!srcNode) continue;
const w = srcNode.widgets?.find(w => w.name === "image" || w.name === "video");
if (!w) continue;
const origCb = w.callback;
w.callback = function (...args) {
if (origCb) origCb.apply(this, args);
setTimeout(() => onChange(resolve()), 100);
};
watchedWidgets.push({ widget: w, origCb });
}
}
chainCallback(node, "onConnectionsChange", function () {
setTimeout(() => {
watch();
onChange(resolve());
}, 100);
});
chainCallback(node, "onRemoved", unwatchWidgets);
return unwatchWidgets;
}
// ─── Bounding box hit test ───
// Tests whether (mx, my) hits a corner handle or the interior of a rect defined by (x1, y1)–(x2, y2).
// Returns "resize-tl", "resize-tr", "resize-bl", "resize-br", "move", or null.
export function rectHitTest(mx, my, x1, y1, x2, y2, radius) {
const hit = (cx, cy) => Math.abs(mx - cx) < radius && Math.abs(my - cy) < radius;
if (hit(x1, y1)) return "resize-tl";
if (hit(x2, y1)) return "resize-tr";
if (hit(x1, y2)) return "resize-bl";
if (hit(x2, y2)) return "resize-br";
if (mx >= x1 && mx <= x2 && my >= y1 && my <= y2) return "move";
return null;
}
// Returns the appropriate CSS cursor for a bbox hit mode string.
export function cursorForBboxMode(mode) {
if (mode === "move") return "move";
if (mode === "resize-tl" || mode === "resize-br") return "nwse-resize";
if (mode === "resize-tr" || mode === "resize-bl") return "nesw-resize";
return null;
}
// ─── Wheel zoom passthrough for DOM widgets ───
// Re-dispatches wheel events to the LiteGraph canvas for zoom
export function addWheelPassthrough(element) {
element.addEventListener("wheel", (e) => {
const gc = document.getElementById("graph-canvas");
if (gc) {
gc.dispatchEvent(new WheelEvent(e.type, e));
e.preventDefault();
}
}, { passive: false });
}
1234567891011121314151617181920212223242526272829303132333435363738---
name: Bug Report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
<!--
🔍 STOP! Before creating a new issue:
1. Please search the closed issues first: https://github.com/ShmuelRonen/ComfyUI-LatentSyncWrapper/issues?q=is%3Aissue+is%3Aclosed
2. Check if your issue has already been resolved in past discussions.
3. If you find a similar issue, please add a comment there instead of creating a new one.
-->
**Describe the bug**
A clear and concise description of what the bug is.
**Steps To Reproduce**
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Additional context**
Add any other context about the problem here.
A clear and concise description of what you expected to happen.
## Additional Context
Add any other context about the problem here (screenshots, logs, etc.).
## Environment
- OS: [e.g. Windows 10, Ubuntu 20.04]
- Browser: [e.g. Chrome, Firefox]
- Version: [e.g. 22]12345678910111213141516171819202122name: Add Support Link to Issues
on:
issues:
types: [opened]
jobs:
add-comment:
runs-on: ubuntu-latest
steps:
- name: Add Buy Me a Coffee comment
uses: peter-evans/create-or-update-comment@v3
with:
issue-number: ${{ github.event.issue.number }}
body: |
Thanks for opening this issue!
If you find this project helpful, consider buying me a coffee:
[](https://buymeacoffee.com/shmuelronen)
I'll look into this issue as soon as possible.1234567891011121314151617181920212223242526name: Publish to Comfy registry
on:
workflow_dispatch:
push:
branches:
- main
- master
paths:
- "pyproject.toml"
jobs:
publish-node:
name: Publish Custom Node to registry
runs-on: ubuntu-latest
# if this is a forked repository. Skipping the workflow.
if: github.event.repository.fork == false
steps:
- name: Check out code
uses: actions/checkout@v4
with:
submodules: true
- name: Publish Custom Node
uses: Comfy-Org/publish-node-action@main
with:
## Add your own personal access token to your Github Repository secrets and reference it here.
personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# UV
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
#uv.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
# PyPI configuration file
.pypirc
checkpoints/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193# ComfyUI-LatentSyncWrapper 1.6
## Support My Work
If you find this project helpful, consider buying me a coffee:
[](https://buymeacoffee.com/shmuelronen)
Unofficial [LatentSync 1.6](https://github.com/bytedance/LatentSync) implementation for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) on Windows and WSL 2.0.
This node provides advanced lip-sync capabilities in ComfyUI using ByteDance's LatentSync 1.6 model. It allows you to synchronize video lips with audio input with enhanced clarity and resolution, addressing the blurriness issues found in previous versions.
## ⚠️ IMPORTANT UPGRADE NOTICE ⚠️
**If you have a previous version of ComfyUI-LatentSyncWrapper installed, you MUST completely remove it before installing version 1.6:**
1. **Stop ComfyUI** completely
2. **Delete the entire folder**: `ComfyUI/custom_nodes/ComfyUI-LatentSyncWrapper/`
3. **Clean installation**: Follow the installation steps below for a fresh 1.6 installation
4. **Do NOT try to update** - version 1.6 requires a complete reinstallation due to significant changes
**Failure to remove the previous version will cause conflicts and prevent proper operation.**

### Last Changes:
#### June-14-25 - Updated to LatentSync 1.6 with 512×512 resolution training for significantly improved clarity and detail in teeth and lip generation.
#### April-29-25 - To avoid GPU memory allocation issues, frames are now moved to CPU before uint8 conversion. This change enables generation of longer videos without OOM errors.
## What's new in LatentSync 1.6?
1. **Enhanced Resolution Training**: LatentSync 1.6 is trained on 512×512 resolution videos to address the blurriness issues reported in LatentSync 1.5
2. **Improved Visual Quality**: Significantly reduces blurriness in teeth and lips that was common in version 1.5
3. **Backward Compatibility**: The current code is compatible with both LatentSync 1.5 and 1.6, requiring only checkpoint changes
4. **Same Model Architecture**: No changes to model structure or training strategy - only upgraded training dataset resolution
5. **Maintained Performance**: All the improvements from version 1.5 are retained:
- **Temporal Layer Improvements**: Corrected implementation provides significantly improved temporal consistency
- **Better Chinese Language Support**: Enhanced performance on Chinese videos through additional training data
- **Reduced VRAM Requirements**: Optimized to run on 20GB VRAM (RTX 3090 compatible)
- **Code Optimizations**: Native PyTorch FlashAttention-2 implementation without xFormers dependency
## Prerequisites
Before installing this node, you must install the following in order:
1. [ComfyUI](https://github.com/comfyanonymous/ComfyUI) installed and working
2. FFmpeg installed on your system:
- Windows: Download from [here](https://github.com/BtbN/FFmpeg-Builds/releases) and add to system PATH
## Installation
**Note**: A complete pre-configured checkpoints package is available via Google Drive (recommended), or you can download models individually from HuggingFace repositories.
Only proceed with installation after confirming all prerequisites are installed and working.
1. Clone this repository into your ComfyUI custom_nodes directory:
```bash
cd ComfyUI/custom_nodes
git clone https://github.com/ShmuelRonen/ComfyUI-LatentSyncWrapper.git
cd ComfyUI-LatentSyncWrapper
pip install -r requirements.txt
```
## Required Dependencies
```
diffusers>=0.32.2
transformers
huggingface-hub
omegaconf
einops
opencv-python
mediapipe
face-alignment
decord
ffmpeg-python
safetensors
soundfile
DeepCache
```
## Manual Model Download Required
**Important**: LatentSync 1.6 requires manual model downloads because the LatentSync 1.6 models are hosted on a private HuggingFace repository that cannot be automatically accessed. You must download the following models before first use:
### Manual Individual Downloads
### 1. VAE Model Download
Create a `vae` folder inside your `checkpoints` directory and download the VAE model:
```bash
# Create the vae directory
mkdir checkpoints/vae
```
**Manual download steps:**
1. Visit: https://huggingface.co/stabilityai/sd-vae-ft-mse/tree/main
2. Download **only these 2 files**:
- `diffusion_pytorch_model.safetensors`
- `config.json`
3. Place them in `checkpoints/vae/` folder (inside the extension directory)
### 2. LatentSync 1.6 Checkpoints Download
Download the main LatentSync 1.6 models:
```bash
# Download LatentSync 1.6 models from HuggingFace
# Visit: https://huggingface.co/ByteDance/LatentSync-1.6/tree/main
# Download all files from the repository into checkpoints/ folder
```
**Manual download steps:**
1. **Ensure you have access** to the private HuggingFace repository
2. Visit: https://huggingface.co/ByteDance/LatentSync-1.6/tree/main
3. Download all files from the repository
4. Place them directly in the `checkpoints/` folder
### Checkpoint Directory Structure
After downloading models (using either option), your checkpoint directory structure should look like this:
```
./checkpoints/
|-- .cache/
|-- auxiliary/
|-- vae/
| |-- config.json
| `-- diffusion_pytorch_model.safetensors
|-- whisper/
| `-- tiny.pt
|-- config.json
|-- latentsync_unet.pt (~5GB)
|-- stable_syncnet.pt (~1.6GB)
```
Make sure all these files are present for proper functionality. The main model files are:
- `vae/diffusion_pytorch_model.safetensors`: The Stable Diffusion VAE model for encoding/decoding
- `vae/config.json`: VAE configuration file
- `latentsync_unet.pt`: The primary LatentSync 1.6 model trained at 512×512 resolution
- `stable_syncnet.pt`: The SyncNet model for lip-sync supervision
- `whisper/tiny.pt`: The Whisper model for audio processing
## Usage
1. Select an input video file with AceNodes video loader
2. Load an audio file using ComfyUI audio loader
3. (Optional) Set a seed value for reproducible results
4. (Optional) Adjust the lips_expression parameter to control lip movement intensity
5. (Optional) Modify the inference_steps parameter to balance quality and speed
6. Connect to the LatentSync1.6 node
7. Run the workflow
The processed video will be saved in ComfyUI's output directory.
### Node Parameters:
- `video_path`: Path to input video file
- `audio`: Audio input from AceNodes audio loader
- `seed`: Random seed for reproducible results (default: 1247)
- `lips_expression`: Controls the expressiveness of lip movements (default: 1.5)
- Higher values (2.0-3.0): More pronounced lip movements, better for expressive speech
- Lower values (1.0-1.5): Subtler lip movements, better for calm speech
- This parameter affects the model's guidance scale, balancing between natural movement and lip sync accuracy
- `inference_steps`: Number of denoising steps during inference (default: 20)
- Higher values (30-50): Better quality results but slower processing
- Lower values (10-15): Faster processing but potentially lower quality
- The default of 20 usually provides a good balance between quality and speed
### Tips for Better Results:
- **Enhanced 512×512 Resolution**: LatentSync 1.6 provides significantly clearer teeth and lip details compared to version 1.5
- For speeches or presentations where clear lip movements are important, try increasing the lips_expression value to 2.0-2.5
- For casual conversations, the default value of 1.5 usually works well
- If lip movements appear unnatural or exaggerated, try lowering the lips_expression value
- Different values may work better for different languages and speech patterns
- If you need higher quality results and have time to wait, increase inference_steps to 30-50
- For quicker previews or less critical applications, reduce inference_steps to 10-15
## Known Limitations
- Works best with clear, frontal face videos
- Currently does not support anime/cartoon faces
- Video should be at 25 FPS (will be automatically converted)
- Face should be visible throughout the video
- **Requires manual model downloads** - LatentSync 1.6 models are hosted on a private HuggingFace repository, but a complete package is available via Google Drive
- Individual model downloads require access to the ByteDance/LatentSync-1.6 HuggingFace repository
## Credits
This is an unofficial implementation based on:
- [LatentSync 1.6](https://github.com/bytedance/LatentSync) by ByteDance Research
- [ComfyUI](https://github.com/comfyanonymous/ComfyUI)
## License
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.123from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS']1234567891011121314151617181920212223audio:
num_mels: 80 # Number of mel-spectrogram channels and local conditioning dimensionality
rescale: true # Whether to rescale audio prior to preprocessing
rescaling_max: 0.9 # Rescaling value
use_lws:
false # Use LWS (https://github.com/Jonathan-LeRoux/lws) for STFT and phase reconstruction
# It"s preferred to set True to use with https://github.com/r9y9/wavenet_vocoder
# Does not work if n_ffit is not multiple of hop_size!!
n_fft: 800 # Extra window size is filled with 0 paddings to match this parameter
hop_size: 200 # For 16000Hz, 200 = 12.5 ms (0.0125 * sample_rate)
win_size: 800 # For 16000Hz, 800 = 50 ms (If None, win_size = n_fft) (0.05 * sample_rate)
sample_rate: 16000 # 16000Hz (corresponding to librispeech) (sox --i <filename>)
frame_shift_ms: null
signal_normalization: true
allow_clipping_in_normalization: true
symmetric_mels: true
max_abs_value: 4.0
preemphasize: true # whether to apply filter
preemphasis: 0.97 # filter coefficient.
min_level_db: -100
ref_level_db: 20
fmin: 55
fmax: 7600123456789101112{
"_class_name": "DDIMScheduler",
"beta_end": 0.012,
"beta_schedule": "scaled_linear",
"beta_start": 0.00085,
"clip_sample": false,
"num_train_timesteps": 1000,
"set_alpha_to_one": false,
"steps_offset": 1,
"trained_betas": null,
"skip_prk_steps": true
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546model:
audio_encoder: # input (1, 80, 52)
in_channels: 1
block_out_channels: [32, 64, 128, 256, 512, 1024]
downsample_factors: [[2, 1], 2, 2, 2, 2, [2, 3]]
attn_blocks: [0, 0, 0, 0, 0, 0]
dropout: 0.0
visual_encoder: # input (64, 32, 32)
in_channels: 64
block_out_channels: [64, 128, 256, 256, 512, 1024]
downsample_factors: [2, 2, 2, 1, 2, 2]
attn_blocks: [0, 0, 0, 0, 0, 0]
dropout: 0.0
ckpt:
resume_ckpt_path: ""
inference_ckpt_path: ""
save_ckpt_steps: 2500
data:
train_output_dir: debug/syncnet
num_val_samples: 1200
batch_size: 120 # 40
gradient_accumulation_steps: 1
num_workers: 12 # 12
latent_space: true
num_frames: 16
resolution: 256
train_fileslist: /mnt/bn/maliva-gen-ai-v2/chunyu.li/fileslist/data_v10_core.txt
train_data_dir: ""
val_fileslist: ""
val_data_dir: /mnt/bn/maliva-gen-ai-v2/chunyu.li/VoxCeleb2/high_visual_quality/val
audio_mel_cache_dir: /mnt/bn/maliva-gen-ai-v2/chunyu.li/audio_cache/mel
lower_half: false
audio_sample_rate: 16000
video_fps: 25
optimizer:
lr: 1e-5
max_grad_norm: 1.0
run:
max_train_steps: 10000000
validation_steps: 2500
mixed_precision_training: true
seed: 4212345678910111213141516171819202122232425262728293031323334353637383940414243444546model:
audio_encoder: # input (1, 80, 52)
in_channels: 1
block_out_channels: [32, 64, 128, 256, 512, 1024, 2048]
downsample_factors: [[2, 1], 2, 2, 1, 2, 2, [2, 3]]
attn_blocks: [0, 0, 0, 0, 0, 0, 0]
dropout: 0.0
visual_encoder: # input (48, 128, 256)
in_channels: 48
block_out_channels: [64, 128, 256, 256, 512, 1024, 2048, 2048]
downsample_factors: [[1, 2], 2, 2, 2, 2, 2, 2, 2]
attn_blocks: [0, 0, 0, 0, 0, 0, 0, 0]
dropout: 0.0
ckpt:
resume_ckpt_path: ""
inference_ckpt_path: ""
save_ckpt_steps: 2500
data:
train_output_dir: debug/syncnet
num_val_samples: 2048
batch_size: 256 # 256
gradient_accumulation_steps: 1
num_workers: 12 # 12
latent_space: false
num_frames: 16
resolution: 256
train_fileslist: /mnt/bn/maliva-gen-ai-v2/chunyu.li/fileslist/data_v10_core.txt
train_data_dir: ""
val_fileslist: ""
val_data_dir: /mnt/bn/maliva-gen-ai-v2/chunyu.li/VoxCeleb2/high_visual_quality/val
audio_mel_cache_dir: /mnt/bn/maliva-gen-ai-v2/chunyu.li/audio_cache/mel
lower_half: true
audio_sample_rate: 16000
video_fps: 25
optimizer:
lr: 1e-5
max_grad_norm: 1.0
run:
max_train_steps: 10000000
validation_steps: 2500
mixed_precision_training: true
seed: 4212345678910111213141516171819202122232425262728293031323334353637383940414243444546model:
audio_encoder: # input (1, 80, 52)
in_channels: 1
block_out_channels: [32, 64, 128, 256, 512, 1024, 2048]
downsample_factors: [[2, 1], 2, 2, 1, 2, 2, [2, 3]]
attn_blocks: [0, 0, 0, 1, 1, 0, 0]
dropout: 0.0
visual_encoder: # input (48, 128, 256)
in_channels: 48
block_out_channels: [64, 128, 256, 256, 512, 1024, 2048, 2048]
downsample_factors: [[1, 2], 2, 2, 2, 2, 2, 2, 2]
attn_blocks: [0, 0, 0, 0, 1, 1, 0, 0]
dropout: 0.0
ckpt:
resume_ckpt_path: ""
inference_ckpt_path: checkpoints/stable_syncnet.pt
save_ckpt_steps: 2500
data:
train_output_dir: debug/syncnet
num_val_samples: 2048
batch_size: 256 # 256
gradient_accumulation_steps: 1
num_workers: 12 # 12
latent_space: false
num_frames: 16
resolution: 256
train_fileslist: /mnt/bn/maliva-gen-ai-v2/chunyu.li/fileslist/data_v10_core.txt
train_data_dir: ""
val_fileslist: ""
val_data_dir: /mnt/bn/maliva-gen-ai-v2/chunyu.li/VoxCeleb2/high_visual_quality/val
audio_mel_cache_dir: /mnt/bn/maliva-gen-ai-v2/chunyu.li/audio_cache/mel
lower_half: true
audio_sample_rate: 16000
video_fps: 25
optimizer:
lr: 1e-5
max_grad_norm: 1.0
run:
max_train_steps: 10000000
validation_steps: 2500
mixed_precision_training: true
seed: 421234567891011121314151617181920212223242526272829303132333435363738394041424344model:
audio_encoder: # input (1, 80, 80)
in_channels: 1
block_out_channels: [64, 128, 256, 256, 512, 1024]
downsample_factors: [2, 2, 2, 2, 2, 2]
dropout: 0.0
visual_encoder: # input (75, 128, 256)
in_channels: 75
block_out_channels: [128, 128, 256, 256, 512, 512, 1024, 1024]
downsample_factors: [[1, 2], 2, 2, 2, 2, 2, 2, 2]
dropout: 0.0
ckpt:
resume_ckpt_path: ""
inference_ckpt_path: ""
save_ckpt_steps: 2500
data:
train_output_dir: debug/syncnet
num_val_samples: 2048
batch_size: 64 # 64
gradient_accumulation_steps: 1
num_workers: 12 # 12
latent_space: false
num_frames: 25
resolution: 256
train_fileslist: /mnt/bn/maliva-gen-ai-v2/chunyu.li/fileslist/data_v10_core.txt
train_data_dir: ""
val_fileslist: ""
val_data_dir: /mnt/bn/maliva-gen-ai-v2/chunyu.li/VoxCeleb2/high_visual_quality/val
audio_mel_cache_dir: /mnt/bn/maliva-gen-ai-v2/chunyu.li/audio_cache/mel
lower_half: true
audio_sample_rate: 16000
video_fps: 25
optimizer:
lr: 1e-5
max_grad_norm: 1.0
run:
max_train_steps: 10000000
validation_steps: 2500
mixed_precision_training: true
seed: 42123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596data:
syncnet_config_path: configs/syncnet/syncnet_16_pixel_attn.yaml
train_output_dir: debug/unet
train_fileslist: /mnt/bn/maliva-gen-ai-v2/chunyu.li/fileslist/data_v10_core.txt
train_data_dir: ""
audio_embeds_cache_dir: /mnt/bn/maliva-gen-ai-v2/chunyu.li/audio_cache/embeds
audio_mel_cache_dir: /mnt/bn/maliva-gen-ai-v2/chunyu.li/audio_cache/mel
val_video_path: assets/demo1_video.mp4
val_audio_path: assets/demo1_audio.wav
batch_size: 1 # 24
num_workers: 12 # 12
num_frames: 16
resolution: 256
mask_image_path: latentsync/utils/mask.png
audio_sample_rate: 16000
video_fps: 25
audio_feat_length: [2, 2]
ckpt:
resume_ckpt_path: checkpoints/latentsync_unet.pt
save_ckpt_steps: 10000
run:
pixel_space_supervise: false
use_syncnet: false
sync_loss_weight: 0.05
perceptual_loss_weight: 0.1 # 0.1
recon_loss_weight: 1 # 1
guidance_scale: 2.0 # [1.0 - 3.0]
trepa_loss_weight: 10
inference_steps: 20
seed: 1247
use_mixed_noise: true
mixed_noise_alpha: 1 # 1
mixed_precision_training: true
enable_gradient_checkpointing: true
max_train_steps: 10000000
max_train_epochs: -1
optimizer:
lr: 1e-5
scale_lr: false
max_grad_norm: 1.0
lr_scheduler: constant
lr_warmup_steps: 0
model:
act_fn: silu
add_audio_layer: true
attention_head_dim: 8
block_out_channels: [320, 640, 1280, 1280]
center_input_sample: false
cross_attention_dim: 384
down_block_types:
[
"CrossAttnDownBlock3D",
"CrossAttnDownBlock3D",
"CrossAttnDownBlock3D",
"DownBlock3D",
]
mid_block_type: UNetMidBlock3DCrossAttn
up_block_types:
[
"UpBlock3D",
"CrossAttnUpBlock3D",
"CrossAttnUpBlock3D",
"CrossAttnUpBlock3D",
]
downsample_padding: 1
flip_sin_to_cos: true
freq_shift: 0
in_channels: 13 # 49
layers_per_block: 2
mid_block_scale_factor: 1
norm_eps: 1e-5
norm_num_groups: 32
out_channels: 4 # 16
sample_size: 64
resnet_time_scale_shift: default # Choose between [default, scale_shift]
use_motion_module: false
motion_module_resolutions: [1, 2, 4, 8]
motion_module_mid_block: false
motion_module_decoder_only: false
motion_module_type: Vanilla
motion_module_kwargs:
num_attention_heads: 8
num_transformer_block: 1
attention_block_types:
- Temporal_Self
- Temporal_Self
temporal_position_encoding: true
temporal_position_encoding_max_len: 24
temporal_attention_dim_div: 1
zero_initialize: true123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596data:
syncnet_config_path: configs/syncnet/syncnet_16_pixel_attn.yaml
train_output_dir: debug/unet
train_fileslist: /mnt/bn/maliva-gen-ai-v2/chunyu.li/fileslist/data_v10_core.txt
train_data_dir: ""
audio_embeds_cache_dir: /mnt/bn/maliva-gen-ai-v2/chunyu.li/audio_cache/embeds
audio_mel_cache_dir: /mnt/bn/maliva-gen-ai-v2/chunyu.li/audio_cache/mel
val_video_path: assets/demo1_video.mp4
val_audio_path: assets/demo1_audio.wav
batch_size: 1 # 8
num_workers: 12 # 12
num_frames: 16
resolution: 512
mask_image_path: latentsync/utils/mask.png
audio_sample_rate: 16000
video_fps: 25
audio_feat_length: [2, 2]
ckpt:
resume_ckpt_path: checkpoints/latentsync_unet.pt
save_ckpt_steps: 10000
run:
pixel_space_supervise: false
use_syncnet: false
sync_loss_weight: 0.05
perceptual_loss_weight: 0.1 # 0.1
recon_loss_weight: 1 # 1
guidance_scale: 2.0 # [1.0 - 3.0]
trepa_loss_weight: 10
inference_steps: 20
seed: 1247
use_mixed_noise: true
mixed_noise_alpha: 1 # 1
mixed_precision_training: true
enable_gradient_checkpointing: true
max_train_steps: 10000000
max_train_epochs: -1
optimizer:
lr: 1e-5
scale_lr: false
max_grad_norm: 1.0
lr_scheduler: constant
lr_warmup_steps: 0
model:
act_fn: silu
add_audio_layer: true
attention_head_dim: 8
block_out_channels: [320, 640, 1280, 1280]
center_input_sample: false
cross_attention_dim: 384
down_block_types:
[
"CrossAttnDownBlock3D",
"CrossAttnDownBlock3D",
"CrossAttnDownBlock3D",
"DownBlock3D",
]
mid_block_type: UNetMidBlock3DCrossAttn
up_block_types:
[
"UpBlock3D",
"CrossAttnUpBlock3D",
"CrossAttnUpBlock3D",
"CrossAttnUpBlock3D",
]
downsample_padding: 1
flip_sin_to_cos: true
freq_shift: 0
in_channels: 13 # 49
layers_per_block: 2
mid_block_scale_factor: 1
norm_eps: 1e-5
norm_num_groups: 32
out_channels: 4 # 16
sample_size: 64
resnet_time_scale_shift: default # Choose between [default, scale_shift]
use_motion_module: false
motion_module_resolutions: [1, 2, 4, 8]
motion_module_mid_block: false
motion_module_decoder_only: false
motion_module_type: Vanilla
motion_module_kwargs:
num_attention_heads: 8
num_transformer_block: 1
attention_block_types:
- Temporal_Self
- Temporal_Self
temporal_position_encoding: true
temporal_position_encoding_max_len: 24
temporal_attention_dim_div: 1
zero_initialize: true123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899data:
syncnet_config_path: configs/syncnet/syncnet_16_pixel_attn.yaml
train_output_dir: debug/unet
train_fileslist: /mnt/bn/maliva-gen-ai-v2/chunyu.li/fileslist/data_v10_core.txt
train_data_dir: ""
audio_embeds_cache_dir: /mnt/bn/maliva-gen-ai-v2/chunyu.li/audio_cache/embeds
audio_mel_cache_dir: /mnt/bn/maliva-gen-ai-v2/chunyu.li/audio_cache/mel
val_video_path: assets/demo1_video.mp4
val_audio_path: assets/demo1_audio.wav
batch_size: 1 # 4
num_workers: 12 # 12
num_frames: 16
resolution: 256
mask_image_path: latentsync/utils/mask.png
audio_sample_rate: 16000
video_fps: 25
audio_feat_length: [2, 2]
ckpt:
resume_ckpt_path: checkpoints/latentsync_unet.pt
save_ckpt_steps: 10000
run:
pixel_space_supervise: true
use_syncnet: true
sync_loss_weight: 0.05
perceptual_loss_weight: 0.1 # 0.1
recon_loss_weight: 1 # 1
guidance_scale: 2.0 # [1.0 - 3.0]
trepa_loss_weight: 10
inference_steps: 20
trainable_modules:
- motion_modules.
- attentions.
seed: 1247
use_mixed_noise: true
mixed_noise_alpha: 1 # 1
mixed_precision_training: true
enable_gradient_checkpointing: true
max_train_steps: 10000000
max_train_epochs: -1
optimizer:
lr: 1e-5
scale_lr: false
max_grad_norm: 1.0
lr_scheduler: constant
lr_warmup_steps: 0
model:
act_fn: silu
add_audio_layer: true
attention_head_dim: 8
block_out_channels: [320, 640, 1280, 1280]
center_input_sample: false
cross_attention_dim: 384
down_block_types:
[
"CrossAttnDownBlock3D",
"CrossAttnDownBlock3D",
"CrossAttnDownBlock3D",
"DownBlock3D",
]
mid_block_type: UNetMidBlock3DCrossAttn
up_block_types:
[
"UpBlock3D",
"CrossAttnUpBlock3D",
"CrossAttnUpBlock3D",
"CrossAttnUpBlock3D",
]
downsample_padding: 1
flip_sin_to_cos: true
freq_shift: 0
in_channels: 13 # 49
layers_per_block: 2
mid_block_scale_factor: 1
norm_eps: 1e-5
norm_num_groups: 32
out_channels: 4 # 16
sample_size: 64
resnet_time_scale_shift: default # Choose between [default, scale_shift]
use_motion_module: true
motion_module_resolutions: [1, 2, 4, 8]
motion_module_mid_block: false
motion_module_decoder_only: false
motion_module_type: Vanilla
motion_module_kwargs:
num_attention_heads: 8
num_transformer_block: 1
attention_block_types:
- Temporal_Self
- Temporal_Self
temporal_position_encoding: true
temporal_position_encoding_max_len: 24
temporal_attention_dim_div: 1
zero_initialize: true123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899data:
syncnet_config_path: configs/syncnet/syncnet_16_pixel_attn.yaml
train_output_dir: debug/unet
train_fileslist: /mnt/bn/maliva-gen-ai-v2/chunyu.li/fileslist/data_v10_core.txt
train_data_dir: ""
audio_embeds_cache_dir: /mnt/bn/maliva-gen-ai-v2/chunyu.li/audio_cache/embeds
audio_mel_cache_dir: /mnt/bn/maliva-gen-ai-v2/chunyu.li/audio_cache/mel
val_video_path: assets/demo1_video.mp4
val_audio_path: assets/demo1_audio.wav
batch_size: 1 # 4
num_workers: 12 # 12
num_frames: 16
resolution: 512
mask_image_path: latentsync/utils/mask.png
audio_sample_rate: 16000
video_fps: 25
audio_feat_length: [2, 2]
ckpt:
resume_ckpt_path: checkpoints/latentsync_unet.pt
save_ckpt_steps: 10000
run:
pixel_space_supervise: true
use_syncnet: true
sync_loss_weight: 0.05
perceptual_loss_weight: 0.1 # 0.1
recon_loss_weight: 1 # 1
guidance_scale: 2.0 # [1.0 - 3.0]
trepa_loss_weight: 10
inference_steps: 20
trainable_modules:
- motion_modules.
- attentions.
seed: 1247
use_mixed_noise: true
mixed_noise_alpha: 1 # 1
mixed_precision_training: true
enable_gradient_checkpointing: true
max_train_steps: 10000000
max_train_epochs: -1
optimizer:
lr: 1e-5
scale_lr: false
max_grad_norm: 1.0
lr_scheduler: constant
lr_warmup_steps: 0
model:
act_fn: silu
add_audio_layer: true
attention_head_dim: 8
block_out_channels: [320, 640, 1280, 1280]
center_input_sample: false
cross_attention_dim: 384
down_block_types:
[
"CrossAttnDownBlock3D",
"CrossAttnDownBlock3D",
"CrossAttnDownBlock3D",
"DownBlock3D",
]
mid_block_type: UNetMidBlock3DCrossAttn
up_block_types:
[
"UpBlock3D",
"CrossAttnUpBlock3D",
"CrossAttnUpBlock3D",
"CrossAttnUpBlock3D",
]
downsample_padding: 1
flip_sin_to_cos: true
freq_shift: 0
in_channels: 13 # 49
layers_per_block: 2
mid_block_scale_factor: 1
norm_eps: 1e-5
norm_num_groups: 32
out_channels: 4 # 16
sample_size: 64
resnet_time_scale_shift: default # Choose between [default, scale_shift]
use_motion_module: true
motion_module_resolutions: [1, 2, 4, 8]
motion_module_mid_block: false
motion_module_decoder_only: false
motion_module_type: Vanilla
motion_module_kwargs:
num_attention_heads: 8
num_transformer_block: 1
attention_block_types:
- Temporal_Self
- Temporal_Self
temporal_position_encoding: true
temporal_position_encoding_max_len: 24
temporal_attention_dim_div: 1
zero_initialize: true123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899data:
syncnet_config_path: configs/syncnet/syncnet_16_pixel_attn.yaml
train_output_dir: debug/unet
train_fileslist: /mnt/bn/maliva-gen-ai-v2/chunyu.li/fileslist/data_v10_core.txt
train_data_dir: ""
audio_embeds_cache_dir: /mnt/bn/maliva-gen-ai-v2/chunyu.li/audio_cache/embeds
audio_mel_cache_dir: /mnt/bn/maliva-gen-ai-v2/chunyu.li/audio_cache/mel
val_video_path: assets/demo1_video.mp4
val_audio_path: assets/demo1_audio.wav
batch_size: 1 # 4
num_workers: 12 # 12
num_frames: 16
resolution: 256
mask_image_path: latentsync/utils/mask.png
audio_sample_rate: 16000
video_fps: 25
audio_feat_length: [2, 2]
ckpt:
resume_ckpt_path: checkpoints/latentsync_unet.pt
save_ckpt_steps: 10000
run:
pixel_space_supervise: true
use_syncnet: true
sync_loss_weight: 0.05
perceptual_loss_weight: 0.1 # 0.1
recon_loss_weight: 1 # 1
guidance_scale: 2.0 # [1.0 - 3.0]
trepa_loss_weight: 0
inference_steps: 20
trainable_modules:
- motion_modules.
- attn2.
seed: 1247
use_mixed_noise: true
mixed_noise_alpha: 1 # 1
mixed_precision_training: true
enable_gradient_checkpointing: true
max_train_steps: 10000000
max_train_epochs: -1
optimizer:
lr: 1e-5
scale_lr: false
max_grad_norm: 1.0
lr_scheduler: constant
lr_warmup_steps: 0
model:
act_fn: silu
add_audio_layer: true
attention_head_dim: 8
block_out_channels: [320, 640, 1280, 1280]
center_input_sample: false
cross_attention_dim: 384
down_block_types:
[
"CrossAttnDownBlock3D",
"CrossAttnDownBlock3D",
"CrossAttnDownBlock3D",
"DownBlock3D",
]
mid_block_type: UNetMidBlock3DCrossAttn
up_block_types:
[
"UpBlock3D",
"CrossAttnUpBlock3D",
"CrossAttnUpBlock3D",
"CrossAttnUpBlock3D",
]
downsample_padding: 1
flip_sin_to_cos: true
freq_shift: 0
in_channels: 13 # 49
layers_per_block: 2
mid_block_scale_factor: 1
norm_eps: 1e-5
norm_num_groups: 32
out_channels: 4 # 16
sample_size: 64
resnet_time_scale_shift: default # Choose between [default, scale_shift]
use_motion_module: true
motion_module_resolutions: [1, 2, 4, 8]
motion_module_mid_block: false
motion_module_decoder_only: true
motion_module_type: Vanilla
motion_module_kwargs:
num_attention_heads: 8
num_transformer_block: 1
attention_block_types:
- Temporal_Self
- Temporal_Self
temporal_position_encoding: true
temporal_position_encoding_max_len: 24
temporal_attention_dim_div: 1
zero_initialize: true123# Face detector
This face detector is adapted from `https://github.com/cs-giung/face-detection-pytorch`.1from .s3fd import S3FD123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263import time
import numpy as np
import cv2
import torch
from torchvision import transforms
from .nets import S3FDNet
from .box_utils import nms_
from latentsync.utils.util import check_model_and_download
PATH_WEIGHT = "checkpoints/auxiliary/sfd_face.pth"
img_mean = np.array([104.0, 117.0, 123.0])[:, np.newaxis, np.newaxis].astype("float32")
class S3FD:
def __init__(self, device="cuda"):
tstamp = time.time()
self.device = device
print("[S3FD] loading with", self.device)
self.net = S3FDNet(device=self.device).to(self.device)
check_model_and_download(PATH_WEIGHT)
state_dict = torch.load(PATH_WEIGHT, map_location=self.device, weights_only=True)
self.net.load_state_dict(state_dict)
self.net.eval()
print("[S3FD] finished loading (%.4f sec)" % (time.time() - tstamp))
def detect_faces(self, image, conf_th=0.8, scales=[1]):
w, h = image.shape[1], image.shape[0]
bboxes = np.empty(shape=(0, 5))
with torch.no_grad():
for s in scales:
scaled_img = cv2.resize(image, dsize=(0, 0), fx=s, fy=s, interpolation=cv2.INTER_LINEAR)
scaled_img = np.swapaxes(scaled_img, 1, 2)
scaled_img = np.swapaxes(scaled_img, 1, 0)
scaled_img = scaled_img[[2, 1, 0], :, :]
scaled_img = scaled_img.astype("float32")
scaled_img -= img_mean
scaled_img = scaled_img[[2, 1, 0], :, :]
x = torch.from_numpy(scaled_img).unsqueeze(0).to(self.device)
y = self.net(x)
detections = y.data
scale = torch.Tensor([w, h, w, h])
for i in range(detections.size(1)):
j = 0
while detections[0, i, j, 0] > conf_th:
score = detections[0, i, j, 0]
pt = (detections[0, i, j, 1:] * scale).cpu().numpy()
bbox = (pt[0], pt[1], pt[2], pt[3], score)
bboxes = np.vstack((bboxes, bbox))
j += 1
keep = nms_(bboxes, 0.1)
bboxes = bboxes[keep]
return bboxes123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221import numpy as np
from itertools import product as product
import torch
from torch.autograd import Function
import warnings
def nms_(dets, thresh):
"""
Courtesy of Ross Girshick
[https://github.com/rbgirshick/py-faster-rcnn/blob/master/lib/nms/py_cpu_nms.py]
"""
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
scores = dets[:, 4]
areas = (x2 - x1) * (y2 - y1)
order = scores.argsort()[::-1]
keep = []
while order.size > 0:
i = order[0]
keep.append(int(i))
xx1 = np.maximum(x1[i], x1[order[1:]])
yy1 = np.maximum(y1[i], y1[order[1:]])
xx2 = np.minimum(x2[i], x2[order[1:]])
yy2 = np.minimum(y2[i], y2[order[1:]])
w = np.maximum(0.0, xx2 - xx1)
h = np.maximum(0.0, yy2 - yy1)
inter = w * h
ovr = inter / (areas[i] + areas[order[1:]] - inter)
inds = np.where(ovr <= thresh)[0]
order = order[inds + 1]
return np.array(keep).astype(np.int32)
def decode(loc, priors, variances):
"""Decode locations from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
loc (tensor): location predictions for loc layers,
Shape: [num_priors,4]
priors (tensor): Prior boxes in center-offset form.
Shape: [num_priors,4].
variances: (list[float]) Variances of priorboxes
Return:
decoded bounding box predictions
"""
boxes = torch.cat((
priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:],
priors[:, 2:] * torch.exp(loc[:, 2:] * variances[1])), 1)
boxes[:, :2] -= boxes[:, 2:] / 2
boxes[:, 2:] += boxes[:, :2]
return boxes
def nms(boxes, scores, overlap=0.5, top_k=200):
"""Apply non-maximum suppression at test time to avoid detecting too many
overlapping bounding boxes for a given object.
Args:
boxes: (tensor) The location preds for the img, Shape: [num_priors,4].
scores: (tensor) The class predscores for the img, Shape:[num_priors].
overlap: (float) The overlap thresh for suppressing unnecessary boxes.
top_k: (int) The Maximum number of box preds to consider.
Return:
The indices of the kept boxes with respect to num_priors.
"""
keep = scores.new(scores.size(0)).zero_().long()
if boxes.numel() == 0:
return keep, 0
x1 = boxes[:, 0]
y1 = boxes[:, 1]
x2 = boxes[:, 2]
y2 = boxes[:, 3]
area = torch.mul(x2 - x1, y2 - y1)
v, idx = scores.sort(0) # sort in ascending order
# I = I[v >= 0.01]
idx = idx[-top_k:] # indices of the top-k largest vals
xx1 = boxes.new()
yy1 = boxes.new()
xx2 = boxes.new()
yy2 = boxes.new()
w = boxes.new()
h = boxes.new()
# keep = torch.Tensor()
count = 0
while idx.numel() > 0:
i = idx[-1] # index of current largest val
# keep.append(i)
keep[count] = i
count += 1
if idx.size(0) == 1:
break
idx = idx[:-1] # remove kept element from view
# load bboxes of next highest vals
with warnings.catch_warnings():
# Ignore UserWarning within this block
warnings.simplefilter("ignore", category=UserWarning)
torch.index_select(x1, 0, idx, out=xx1)
torch.index_select(y1, 0, idx, out=yy1)
torch.index_select(x2, 0, idx, out=xx2)
torch.index_select(y2, 0, idx, out=yy2)
# store element-wise max with next highest score
xx1 = torch.clamp(xx1, min=x1[i])
yy1 = torch.clamp(yy1, min=y1[i])
xx2 = torch.clamp(xx2, max=x2[i])
yy2 = torch.clamp(yy2, max=y2[i])
w.resize_as_(xx2)
h.resize_as_(yy2)
w = xx2 - xx1
h = yy2 - yy1
# check sizes of xx1 and xx2.. after each iteration
w = torch.clamp(w, min=0.0)
h = torch.clamp(h, min=0.0)
inter = w * h
# IoU = i / (area(a) + area(b) - i)
rem_areas = torch.index_select(area, 0, idx) # load remaining areas)
union = (rem_areas - inter) + area[i]
IoU = inter / union # store result in iou
# keep only elements with an IoU <= overlap
idx = idx[IoU.le(overlap)]
return keep, count
class Detect(object):
def __init__(self, num_classes=2,
top_k=750, nms_thresh=0.3, conf_thresh=0.05,
variance=[0.1, 0.2], nms_top_k=5000):
self.num_classes = num_classes
self.top_k = top_k
self.nms_thresh = nms_thresh
self.conf_thresh = conf_thresh
self.variance = variance
self.nms_top_k = nms_top_k
def forward(self, loc_data, conf_data, prior_data):
num = loc_data.size(0)
num_priors = prior_data.size(0)
conf_preds = conf_data.view(num, num_priors, self.num_classes).transpose(2, 1)
batch_priors = prior_data.view(-1, num_priors, 4).expand(num, num_priors, 4)
batch_priors = batch_priors.contiguous().view(-1, 4)
decoded_boxes = decode(loc_data.view(-1, 4), batch_priors, self.variance)
decoded_boxes = decoded_boxes.view(num, num_priors, 4)
output = torch.zeros(num, self.num_classes, self.top_k, 5)
for i in range(num):
boxes = decoded_boxes[i].clone()
conf_scores = conf_preds[i].clone()
for cl in range(1, self.num_classes):
c_mask = conf_scores[cl].gt(self.conf_thresh)
scores = conf_scores[cl][c_mask]
if scores.dim() == 0:
continue
l_mask = c_mask.unsqueeze(1).expand_as(boxes)
boxes_ = boxes[l_mask].view(-1, 4)
ids, count = nms(boxes_, scores, self.nms_thresh, self.nms_top_k)
count = count if count < self.top_k else self.top_k
output[i, cl, :count] = torch.cat((scores[ids[:count]].unsqueeze(1), boxes_[ids[:count]]), 1)
return output
class PriorBox(object):
def __init__(self, input_size, feature_maps,
variance=[0.1, 0.2],
min_sizes=[16, 32, 64, 128, 256, 512],
steps=[4, 8, 16, 32, 64, 128],
clip=False):
super(PriorBox, self).__init__()
self.imh = input_size[0]
self.imw = input_size[1]
self.feature_maps = feature_maps
self.variance = variance
self.min_sizes = min_sizes
self.steps = steps
self.clip = clip
def forward(self):
mean = []
for k, fmap in enumerate(self.feature_maps):
feath = fmap[0]
featw = fmap[1]
for i, j in product(range(feath), range(featw)):
f_kw = self.imw / self.steps[k]
f_kh = self.imh / self.steps[k]
cx = (j + 0.5) / f_kw
cy = (i + 0.5) / f_kh
s_kw = self.min_sizes[k] / self.imw
s_kh = self.min_sizes[k] / self.imh
mean += [cx, cy, s_kw, s_kh]
output = torch.FloatTensor(mean).view(-1, 4)
if self.clip:
output.clamp_(max=1, min=0)
return output123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from .box_utils import Detect, PriorBox
class L2Norm(nn.Module):
def __init__(self, n_channels, scale):
super(L2Norm, self).__init__()
self.n_channels = n_channels
self.gamma = scale or None
self.eps = 1e-10
self.weight = nn.Parameter(torch.Tensor(self.n_channels))
self.reset_parameters()
def reset_parameters(self):
init.constant_(self.weight, self.gamma)
def forward(self, x):
norm = x.pow(2).sum(dim=1, keepdim=True).sqrt() + self.eps
x = torch.div(x, norm)
out = self.weight.unsqueeze(0).unsqueeze(2).unsqueeze(3).expand_as(x) * x
return out
class S3FDNet(nn.Module):
def __init__(self, device='cuda'):
super(S3FDNet, self).__init__()
self.device = device
self.vgg = nn.ModuleList([
nn.Conv2d(3, 64, 3, 1, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(64, 64, 3, 1, padding=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(2, 2),
nn.Conv2d(64, 128, 3, 1, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(128, 128, 3, 1, padding=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(2, 2),
nn.Conv2d(128, 256, 3, 1, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(256, 256, 3, 1, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(256, 256, 3, 1, padding=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(2, 2, ceil_mode=True),
nn.Conv2d(256, 512, 3, 1, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(512, 512, 3, 1, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(512, 512, 3, 1, padding=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(2, 2),
nn.Conv2d(512, 512, 3, 1, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(512, 512, 3, 1, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(512, 512, 3, 1, padding=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(2, 2),
nn.Conv2d(512, 1024, 3, 1, padding=6, dilation=6),
nn.ReLU(inplace=True),
nn.Conv2d(1024, 1024, 1, 1),
nn.ReLU(inplace=True),
])
self.L2Norm3_3 = L2Norm(256, 10)
self.L2Norm4_3 = L2Norm(512, 8)
self.L2Norm5_3 = L2Norm(512, 5)
self.extras = nn.ModuleList([
nn.Conv2d(1024, 256, 1, 1),
nn.Conv2d(256, 512, 3, 2, padding=1),
nn.Conv2d(512, 128, 1, 1),
nn.Conv2d(128, 256, 3, 2, padding=1),
])
self.loc = nn.ModuleList([
nn.Conv2d(256, 4, 3, 1, padding=1),
nn.Conv2d(512, 4, 3, 1, padding=1),
nn.Conv2d(512, 4, 3, 1, padding=1),
nn.Conv2d(1024, 4, 3, 1, padding=1),
nn.Conv2d(512, 4, 3, 1, padding=1),
nn.Conv2d(256, 4, 3, 1, padding=1),
])
self.conf = nn.ModuleList([
nn.Conv2d(256, 4, 3, 1, padding=1),
nn.Conv2d(512, 2, 3, 1, padding=1),
nn.Conv2d(512, 2, 3, 1, padding=1),
nn.Conv2d(1024, 2, 3, 1, padding=1),
nn.Conv2d(512, 2, 3, 1, padding=1),
nn.Conv2d(256, 2, 3, 1, padding=1),
])
self.softmax = nn.Softmax(dim=-1)
self.detect = Detect()
def forward(self, x):
size = x.size()[2:]
sources = list()
loc = list()
conf = list()
for k in range(16):
x = self.vgg[k](x)
s = self.L2Norm3_3(x)
sources.append(s)
for k in range(16, 23):
x = self.vgg[k](x)
s = self.L2Norm4_3(x)
sources.append(s)
for k in range(23, 30):
x = self.vgg[k](x)
s = self.L2Norm5_3(x)
sources.append(s)
for k in range(30, len(self.vgg)):
x = self.vgg[k](x)
sources.append(x)
# apply extra layers and cache source layer outputs
for k, v in enumerate(self.extras):
x = F.relu(v(x), inplace=True)
if k % 2 == 1:
sources.append(x)
# apply multibox head to source layers
loc_x = self.loc[0](sources[0])
conf_x = self.conf[0](sources[0])
max_conf, _ = torch.max(conf_x[:, 0:3, :, :], dim=1, keepdim=True)
conf_x = torch.cat((max_conf, conf_x[:, 3:, :, :]), dim=1)
loc.append(loc_x.permute(0, 2, 3, 1).contiguous())
conf.append(conf_x.permute(0, 2, 3, 1).contiguous())
for i in range(1, len(sources)):
x = sources[i]
conf.append(self.conf[i](x).permute(0, 2, 3, 1).contiguous())
loc.append(self.loc[i](x).permute(0, 2, 3, 1).contiguous())
features_maps = []
for i in range(len(loc)):
feat = []
feat += [loc[i].size(1), loc[i].size(2)]
features_maps += [feat]
loc = torch.cat([o.view(o.size(0), -1) for o in loc], 1)
conf = torch.cat([o.view(o.size(0), -1) for o in conf], 1)
with torch.no_grad():
self.priorbox = PriorBox(size, features_maps)
self.priors = self.priorbox.forward()
output = self.detect.forward(
loc.view(loc.size(0), -1, 4),
self.softmax(conf.view(conf.size(0), -1, 2)),
self.priors.type(type(x.data)).to(self.device)
)
return outputComfyUI-KJNodes/__pycache__/__init__.cpython-310.pycAdded
ComfyUI-KJNodes/nodes/__pycache__/nodes.cpython-310.pycAdded
ComfyUI-KJNodes/nodes/__pycache__/sharpen_nodes.cpython-310.pycAdded
ComfyUI-KJNodes/utility/__pycache__/utility.cpython-310.pycAdded
ComfyUI-KJNodes/utility/fluid.pyAdded+67
ComfyUI-KJNodes/utility/magictex.pyAdded+95
ComfyUI-KJNodes/utility/numerical.pyAdded+25
ComfyUI-KJNodes/utility/utility.pyAdded+88
ComfyUI-KJNodes/web/js/appearance.jsAdded+23
ComfyUI-KJNodes/web/js/canvas_background.jsAdded+476
ComfyUI-KJNodes/web/js/contextmenu.jsAdded+256
ComfyUI-KJNodes/web/js/editors/editor_base.jsAdded+707
ComfyUI-KJNodes/web/js/editors/interpolation.jsAdded+211
ComfyUI-KJNodes/web/js/editors/point_editor_canvas.jsAdded+370
ComfyUI-KJNodes/web/js/editors/spline_editor_canvas.jsAdded+708
ComfyUI-KJNodes/web/js/fast_preview.jsAdded+31
ComfyUI-KJNodes/web/js/fillconnect.jsAdded+218
ComfyUI-KJNodes/web/js/help_popup.jsAdded+468
ComfyUI-KJNodes/web/js/jsnodes.jsAdded+402
ComfyUI-KJNodes/web/js/nodeswap.jsAdded+404
ComfyUI-KJNodes/web/js/performance.jsAdded+286
ComfyUI-KJNodes/web/js/play_sound.jsAdded+94
ComfyUI-KJNodes/web/js/screencap_stream.jsAdded+500
ComfyUI-KJNodes/web/js/setgetnodes.jsAdded+1544
ComfyUI-KJNodes/web/js/utility.jsAdded+230
ComfyUI-LatentSyncWrapper/.github/ISSUE_TEMPLATE/bug_report.mdAdded+38
ComfyUI-LatentSyncWrapper/.github/workflows/issue-template.ymlAdded+22
ComfyUI-LatentSyncWrapper/.github/workflows/publish.ymlAdded+26
ComfyUI-LatentSyncWrapper/.gitignoreAdded+173
ComfyUI-LatentSyncWrapper/README.mdAdded+193
ComfyUI-LatentSyncWrapper/__init__.pyAdded+3
ComfyUI-LatentSyncWrapper/__pycache__/__init__.cpython-310.pycAdded
ComfyUI-LatentSyncWrapper/__pycache__/nodes.cpython-310.pycAdded
ComfyUI-LatentSyncWrapper/checkpoints/put checkpoints hereAdded
ComfyUI-LatentSyncWrapper/configs/audio.yamlAdded+23
ComfyUI-LatentSyncWrapper/configs/scheduler_config.jsonAdded+12
ComfyUI-LatentSyncWrapper/configs/syncnet/syncnet_16_latent.yamlAdded+46
ComfyUI-LatentSyncWrapper/configs/syncnet/syncnet_16_pixel.yamlAdded+46
ComfyUI-LatentSyncWrapper/configs/syncnet/syncnet_16_pixel_attn.yamlAdded+46
ComfyUI-LatentSyncWrapper/configs/syncnet/syncnet_25_pixel.yamlAdded+44
ComfyUI-LatentSyncWrapper/configs/unet/stage1.yamlAdded+96
ComfyUI-LatentSyncWrapper/configs/unet/stage1_512.yamlAdded+96
ComfyUI-LatentSyncWrapper/configs/unet/stage2.yamlAdded+99
ComfyUI-LatentSyncWrapper/configs/unet/stage2_512.yamlAdded+99
ComfyUI-LatentSyncWrapper/configs/unet/stage2_efficient.yamlAdded+99
ComfyUI-LatentSyncWrapper/eval/detectors/README.mdAdded+3
ComfyUI-LatentSyncWrapper/eval/detectors/__init__.pyAdded+1
ComfyUI-LatentSyncWrapper/eval/detectors/s3fd/__init__.pyAdded+63
ComfyUI-LatentSyncWrapper/eval/detectors/s3fd/box_utils.pyAdded+221
ComfyUI-LatentSyncWrapper/eval/detectors/s3fd/nets.pyAdded+174