Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cecffcc592 | ||
|
|
2edd8c0859 |
@@ -7,10 +7,6 @@ on:
|
||||
description: Full commit SHA from ComfyUI-AusBoss-Model-Downloader main
|
||||
required: true
|
||||
type: string
|
||||
changelog:
|
||||
description: Release note for this version, shown in the Registry's Updates section
|
||||
required: true
|
||||
type: string
|
||||
|
||||
# The existing AusBoss publisher credential stays in this repository. This
|
||||
# manual job publishes only the separately maintained Model Downloader addon.
|
||||
@@ -66,16 +62,12 @@ jobs:
|
||||
id: publish
|
||||
env:
|
||||
REGISTRY_ACCESS_TOKEN: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
|
||||
COMFY_NODE_CHANGELOG: ${{ inputs.changelog }}
|
||||
COMFY_NODE_CHANGELOG: 'Initial release: model downloads from Civitai and Hugging Face, installed-file checks, saved model lists, and AusBoss Workflow Note integration.'
|
||||
run: |
|
||||
if [ -z "$REGISTRY_ACCESS_TOKEN" ]; then
|
||||
echo '::error::REGISTRY_ACCESS_TOKEN is not configured.'
|
||||
exit 1
|
||||
fi
|
||||
if [ -z "${COMFY_NODE_CHANGELOG// /}" ]; then
|
||||
echo '::error::The changelog input is empty; the Registry shows it as the release note.'
|
||||
exit 1
|
||||
fi
|
||||
comfy --skip-prompt --no-enable-telemetry node publish --token "$REGISTRY_ACCESS_TOKEN"
|
||||
- name: Report Registry review status
|
||||
if: always() && steps.publish.outcome != 'skipped'
|
||||
|
||||
+8
-340
@@ -2,347 +2,14 @@
|
||||
|
||||
All notable changes to ComfyUI-AusBoss are documented here.
|
||||
|
||||
## 2.26.2 - 2026-11-14
|
||||
## Unreleased
|
||||
|
||||
- **Loaders never look up a file name they refused.** Before each run,
|
||||
Load Image 🆎, Load Image + Pad 🆎, Image Crop + Rotate + Pad 🆎 and both
|
||||
Video Crop + Rotate + Pad nodes check whether their file changed. When the
|
||||
name was one they do not accept, such as a whole path or a network share,
|
||||
that check still looked it up on disk. On Windows, looking up a share
|
||||
contacts its server and hands it the computer's login. Now a refused name
|
||||
is only compared as text.
|
||||
- **The pack's scripts are found without looking up the address.** The pack
|
||||
tags its scripts with a version as the browser asks for them. It found
|
||||
each one by joining the address the browser sent to its own folder and
|
||||
looking the result up on disk, and only then checked that the file was
|
||||
its own. Now it looks the address up in a list of its scripts made when
|
||||
ComfyUI starts, so no address reaches the disk.
|
||||
- **Save Image's Save button copies only pictures it holds.** With Auto
|
||||
save off, the list of a run's held pictures was a file in ComfyUI's temp
|
||||
folder. That folder takes uploads, so a planted list could copy another
|
||||
file on the server into the output folder. The list now stays in
|
||||
ComfyUI's memory, and a held picture is found only by its run, its number
|
||||
and one of Save Image's formats. The Save button works for the last 256
|
||||
runs, up to 10,000 pictures each; held pictures still go when ComfyUI
|
||||
restarts, as before.
|
||||
|
||||
## 2.26.1 - 2026-11-14
|
||||
|
||||
- **A path that starts with `~` is no longer expanded.** Image Folder used
|
||||
to turn a pasted `~/...` path into a full one before checking that it sits
|
||||
inside ComfyUI's folders; now only a path written out in full is checked.
|
||||
LaMa Inpaint only opens a model from ComfyUI's `models/lama` list. Nothing
|
||||
outside those folders could be read before either; this removes the code
|
||||
that looked as if it could.
|
||||
|
||||
## 2.26.0 - 2026-11-14
|
||||
|
||||
- **Missing LoRAs show in ComfyUI's missing-models list.** When a workflow
|
||||
needs a LoRA you don't have, ComfyUI's Issues panel now lists it with the
|
||||
other missing models, so **Download all** fetches it too. Before, the
|
||||
list skipped every LoRA in a LoRA Loader 🆎, and Run then stopped on
|
||||
"missing LoRA file". A LoRA that moved to another folder, or a row that is
|
||||
switched off, is not listed.
|
||||
|
||||
- **Link tiles and title tiles snap by the edge you see.** A tile draws a
|
||||
card inside a wider see-through frame, and Snap into line used that frame,
|
||||
so tiles lined up with a gap around them, and a tile you dragged never
|
||||
snapped at all. Now a dragged tile lines up, and other nodes line up with
|
||||
it, by the card's own edges.
|
||||
|
||||
- **Cards work in App mode.** App mode is ComfyUI's simple form view of a
|
||||
workflow: a few labelled fields and a Run button. A field from a node
|
||||
with a card (a picture or video loader, H3 Prompt Writer) used to show
|
||||
as an empty row there. Now it shows a real control: a file list with an
|
||||
upload button, a video list, a text box. Back in the graph, the node
|
||||
looks the same as before.
|
||||
- **The video crop nodes take uploads in App mode.** Video Crop + Rotate +
|
||||
Pad and its Clip version now tell ComfyUI that their video list takes
|
||||
uploads, as the picture nodes do. In App mode the clip field gets the same
|
||||
picker as a picture field: your videos as thumbnails, an Upload button and
|
||||
a folder button. On the node itself nothing changes.
|
||||
|
||||
- **Models you already have are picked for you.** When a workflow asks for
|
||||
a model file you keep in a subfolder (`minimax-h3/model.safetensors`),
|
||||
ComfyUI used to mark its loader red until you clicked **Use it** on the
|
||||
workflow's Guide. Now the Guide switches the loader to your copy as the
|
||||
workflow opens and says so in a short message. That matters most in App
|
||||
mode, which shows no Guide to click. With two copies in different
|
||||
subfolders it still asks. Turn it off in Settings, 🆎 AusBoss, Models.
|
||||
|
||||
- **The video clip's timing is three boxes: Start, Duration, Ends at.** On
|
||||
Video Crop + Rotate + Pad (Clip), the Length on/off switch is gone. Drag
|
||||
the start to move the clip, drag the end or type a Duration to change how
|
||||
long it is, and switch between seconds and frames. Details sit in hover
|
||||
text; a short note shows only when something needs fixing, with a button
|
||||
to fix it. Saved workflows open with the same values and run the same.
|
||||
- **A linked frame rate no longer stops the clip's start too early.** With
|
||||
a rate wired in, a typed start of frame 60 used to settle on frame 7; it
|
||||
now lands where you put it, and the start handle stops only where the
|
||||
Duration no longer fits. A rate set inside a subgraph now counts as
|
||||
known, so the clip shows its length before you run.
|
||||
- **Linked clip lengths say where they come from.** A box set by another
|
||||
node shows a **linked** button that jumps to that node. A cap that the
|
||||
video cannot fill says how many frames you get, and a count only known
|
||||
when the graph runs shows the room left after the start.
|
||||
- **H3 Prompt Writer says how much of the clip H3 uses.** When the video
|
||||
comes from the clip node, it shows how many of the clip's frames H3
|
||||
makes and where in the video that stops, and which Durations use all of
|
||||
it.
|
||||
- **Crop + Rotate + Pad panels fill the node's width.** The rows under the
|
||||
picture used to stop at 460 px and sit in the middle of a wide node.
|
||||
- **Load Video uses the same timing boxes as the clip node.** Start,
|
||||
Duration and Ends at replace the IN and OUT fields and the separate
|
||||
Limit row, with the same seconds | frames switch. Saved workflows open
|
||||
with the same values and run the same.
|
||||
- **Load Video counts the frames the file really has.** The face used to
|
||||
work the count out from the length and could say one frame too many (248
|
||||
for a 247-frame clip); it now reads it from the file.
|
||||
- **Load Audio has Start, Duration and Ends at boxes.** They replace the IN
|
||||
and OUT times and the separate Max length row, so the red "cut" stripe is
|
||||
gone: the Duration is the length you get.
|
||||
- **A number wired through a Reroute or a subgraph now shows on the face.**
|
||||
The clip node, Load Video, Load Audio and Layout Boxes read a linked
|
||||
number the same way, so it no longer drops out behind a Reroute, a
|
||||
subgraph or an older Primitive node.
|
||||
|
||||
## 2.25.3 - 2026-11-13
|
||||
|
||||
- **The video clip's frame readout explains itself.** On Video Crop + Rotate
|
||||
+ Pad (Clip), the small `fr 52 · 0:02.17` beside Play now says in plain
|
||||
words, when you point at it, which frame the picture shows and how many
|
||||
seconds into the video it is. The help page explains it too.
|
||||
|
||||
## 2.25.2 - 2026-11-13
|
||||
|
||||
- **The video clip's IN handle always drags.** On Video Crop + Rotate + Pad
|
||||
(Clip), a Length as long as the clip or longer used to lock IN, and the
|
||||
only way to trim the start was to turn Length off. Now IN drags anyway:
|
||||
the Length then only caps the clip, and the clip's own end is OUT. A
|
||||
Length shorter than the clip works as before.
|
||||
|
||||
## 2.25.1 - 2026-11-13
|
||||
|
||||
- **Edit Lock Restore 🆎 takes out the pink tint.** MiniMax H3 Image gives
|
||||
every edit a faint pink, slightly lighter tint over the whole picture.
|
||||
Edit Lock already removed it wherever it locked, but when it stepped
|
||||
aside (a new hair color, a new background, rain) the tint stayed. A new
|
||||
**Remove tint** switch, on by default, reads the tint from the part of
|
||||
the picture the edit left alone and takes it out of the whole picture.
|
||||
Edits meant to recolor everything, such as golden hour or red light, are
|
||||
left as they are. Turn it off to get the old behavior.
|
||||
|
||||
## 2.25.0 - 2026-11-12
|
||||
|
||||
- **New node: Load Image.** Loads a picture and sets its size in the same
|
||||
node, so a workflow needs no resize node after its loader. Size can be a
|
||||
megapixel count, a longest side, a scale, a box the picture fits inside, or
|
||||
a box it fills by cropping, rounded to a multiple you choose. It can also
|
||||
cut a piece or a shape such as 16:9 out of the picture without resizing,
|
||||
and you pick which part is kept: the center, a side or a corner. Arrows
|
||||
step through the pictures in the input folder. Two small pictures on the
|
||||
node show what goes in and what comes out, with both sizes and what is
|
||||
cut off, before you run. It also gives the file's name and its original
|
||||
size. With Size off the picture comes out exactly as the file has it.
|
||||
|
||||
- **Clear VRAM from the right-click menu.** Right-click the empty canvas
|
||||
and pick **Clear VRAM 🆎** to unload every model and free memory on the
|
||||
ComfyUI server, the same as ComfyUI's own "Unload Models and Execution
|
||||
Cache". A short message says when it is done. Turn the entry off in
|
||||
Settings, 🆎 AusBoss, Memory.
|
||||
|
||||
- **Callout 🆎: Info card.** Right-click a Callout and pick **Info card**
|
||||
for a small card with a title, a list of labels and values, and small
|
||||
print, such as a table of run times. Write a row as `label | value`; a
|
||||
row in **bold** is drawn in teal so the one to pick stands out. The first
|
||||
line is the title, and a ⏱️ ℹ️ ⚠️ 💡 or ✅ at its start becomes a small
|
||||
icon. An older pack shows the card as a plain note with its rows written
|
||||
out.
|
||||
|
||||
- **Save Image shows big pictures at once.** The node now shows a small
|
||||
copy of each picture, a few hundred kilobytes, where it used to load the
|
||||
whole file. A 30 MB sheet on a ComfyUI opened from another computer took
|
||||
half a minute to show, or never did; it now shows as the run ends. The
|
||||
saved file is the same full-size file as before.
|
||||
|
||||
- **Save Image: the Save button is hard to miss.** With **Auto save** off,
|
||||
a row over the picture now says **Not saved yet** and holds a solid
|
||||
**Save picture** button. Before, it was a small SAVE label in the corner.
|
||||
With several pictures the button reads **Save all 4**, or **Save this
|
||||
one** when the arrows are on one picture. After a save the row says the
|
||||
name the picture was saved under.
|
||||
|
||||
- **A picture that loads slowly no longer leaves the old one up.** When a
|
||||
result took more than about 16 seconds to reach the browser, the node
|
||||
kept the picture from the run before. Now the new picture always shows,
|
||||
and the old one dims while the new one loads. This fixes Select Frame,
|
||||
Mask Refine, Mask by Name and LaMa Inpaint as well as Save Image.
|
||||
|
||||
## 2.24.0 - 2026-11-12
|
||||
|
||||
- **New node: Edit Lock.** Keeps every part of your picture that an edit
|
||||
did not change exactly where it was, with the colors it had. Edit models
|
||||
redraw the whole picture, so untouched parts often come back a little
|
||||
zoomed, shifted or tinted. Put Edit Lock between the model and the
|
||||
sampler and give it the picture you are editing. It needs no mask. It
|
||||
steps aside when the edit changes the whole picture, and lets rain,
|
||||
snow and haze through while holding the picture in place. Tested on
|
||||
MiniMax-H3-Image.
|
||||
|
||||
- **New node: Edit Lock Restore.** Puts your picture's own pixels back in
|
||||
every part the edit did not change. Add it after the VAE Decode with
|
||||
Edit Lock's `edit_lock` output. It also gives a mask of what the edit
|
||||
changed and a one-line report.
|
||||
|
||||
- **New node: Text Lines.** It runs what comes after once for each line of
|
||||
your text. Type five prompts, one on each line, and one run makes five
|
||||
pictures. It also takes a list a text model wrote: empty lines are
|
||||
skipped, a leading number or bullet comes off, and **Limit** stops a list
|
||||
that ran long.
|
||||
|
||||
- **Save Image shows every picture of a run at once.** When a run saves
|
||||
several pictures, they now show side by side in the node, the way the
|
||||
core Save Image does. The arrows still go to each picture by itself, and
|
||||
round again to all of them. Select Frame, Mask Refine, Mask by Name and
|
||||
LaMa Inpaint show a batch the same way.
|
||||
|
||||
- **Save Image can wait for a click before it saves.** Switch **Auto save**
|
||||
off and a run only shows its pictures on the node. **SAVE ALL** over them
|
||||
keeps every one; step to one picture with the arrows and **SAVE** keeps
|
||||
just that one. Good for making a batch and keeping the best. Auto save is
|
||||
on unless you switch it off, so nothing changes for workflows you have.
|
||||
|
||||
- **New node: Prompt Variations.** A prompt box that picks one choice from
|
||||
each set in curly brackets, such as `a {red|blue|green} {sweater|jacket}`,
|
||||
on every run. The seed decides the picks, so the same seed gives the same
|
||||
prompt again. Queue 50 runs with a random seed and get 50 different
|
||||
prompts, with no wildcard pack.
|
||||
|
||||
- **Mask by Touch: type a name to take it out of the mask.** The name field
|
||||
under the picture now has a sign in front. Click it to switch between **+**
|
||||
(add by name) and **−** (take away by name), then type "face" or "hair" and
|
||||
press Enter. Typing "-face" takes it away whatever the sign says. Before,
|
||||
a typed name was only taken away while Erase was chosen, which nothing on
|
||||
the node said.
|
||||
|
||||
- **Mask by Touch: Ctrl-click only takes away what you point at.** With a
|
||||
sweater picked, a Ctrl-click on the face offered the whole person, and the
|
||||
sweater went with it. Now a spot where nothing is picked says so and
|
||||
changes nothing.
|
||||
|
||||
- **Mask by Touch works on big pictures.** A look at a 3840 pixel picture took
|
||||
twice as long as at 2048, and at 8192 pixels it ran a 32 GB graphics card
|
||||
out of memory. The node now asks SAM 3 about a copy of at most 2048 pixels
|
||||
and brings the answer back to full size. Pictures up to 2048 pixels come
|
||||
out exactly as before. On bigger ones a mask's edge can sit a pixel or two
|
||||
differently.
|
||||
|
||||
- **Mask by Touch no longer fills the queue.** With Image Crop + Rotate + Pad
|
||||
or Load Image + Pad wired in, every change to the loader (each step of its
|
||||
megapixels, for one) queued one more look at a picture that was already
|
||||
replaced. Now only the newest look waits. The button that pauses the
|
||||
looking also says **Pause** and **Look on**.
|
||||
|
||||
- **New node: FlashVSR Upscale 🆎.** Makes a video larger and sharper with
|
||||
the FlashVSR v1.1 model, from 1x to 4x. It needs one model file and no
|
||||
other pack: the help page has the download link. A long clip needs no more
|
||||
graphics memory than a short one, and a result too large for the free
|
||||
memory is made in tiles.
|
||||
The new example `FlashVSR Video Upscale (AusBoss)` shows it between Load
|
||||
Video and Save Video.
|
||||
|
||||
- **Two errors from outside a workflow now say what to do.** When a MiniMax H3
|
||||
run stops with `KeyError: 'latent'` because the Muse MiniMax Director pack is
|
||||
installed, a message names that pack and says to turn it off. When an older
|
||||
ComfyUI cannot read a `w6a8` model file, a message says to update ComfyUI.
|
||||
ComfyUI's own error report stays as it is.
|
||||
|
||||
- **ComfyUI starts when the pack is installed twice.** A Manager install
|
||||
(`custom_nodes/ausboss-nodes`) beside a git clone
|
||||
(`custom_nodes/ComfyUI-AusBoss`) stopped ComfyUI while it started. Now one
|
||||
copy loads and the other steps aside, and the console says which folder to
|
||||
delete. A copy from 2.23.0 or older is the one that loads when it sits
|
||||
beside a newer one, so delete the older folder.
|
||||
|
||||
- **A Workflow Note popup closes when you click outside it.** Opening an
|
||||
info tile (a Tips note, say) showed the full note, and only its Close
|
||||
button or Escape put it away. A click on the dark area around it now
|
||||
closes it too. Selecting text in the note, or a drag that starts on it,
|
||||
keeps it open, and the Edit form still asks before it drops a change.
|
||||
|
||||
## 2.23.0 - 2026-11-09
|
||||
|
||||
- **Mask by Touch keeps your picks when the picture changes.** Your clicks
|
||||
and paint move onto the new picture, in the same places, so an edit before
|
||||
the node no longer means picking everything again. On a picture of another
|
||||
size they are scaled to fit. A click finds whatever is at that spot now;
|
||||
paint stays exactly as painted. For the old way, set **New picture**, under
|
||||
More, to **start over**.
|
||||
|
||||
- **Workflow Switches: a switch that changes a setting no longer turns its
|
||||
node off.** The node it sets keeps running. LoRA choices keep every field
|
||||
that differs between them, and the add-choice button shows as soon as a
|
||||
node is selected.
|
||||
|
||||
- **Mask by Touch clears a stopped run's message once a run works.** When
|
||||
a run stopped at the node, its message stayed on the picture after the
|
||||
next run from the Run button had worked. It now goes as soon as the new
|
||||
result comes in.
|
||||
|
||||
- **Video Crop + Rotate + Pad → Clip: the fixed_frames input sits on its own
|
||||
row again.** In workflows saved by an earlier release, newer ComfyUI drew
|
||||
fixed_frames on top of force_rate, so a link could not be dropped on it.
|
||||
Every input the pack moves into the input column now gets its own row.
|
||||
|
||||
- **Node colours stay after a save and reload.** A colour picked from the
|
||||
right-click menu now survives saving, reloading and pasting. In Nodes 2.0,
|
||||
About this node is in the right-click menu, and dragging a node's corner
|
||||
snaps to nearby lines (hold Shift to skip the snap).
|
||||
|
||||
- **Image Folder shows the right pictures when you change folders.**
|
||||
Switching folders or reloading a workflow no longer shows old or mixed-up
|
||||
results, a very large folder keeps its newest files, and thumbnails refresh
|
||||
when a picture is saved over.
|
||||
|
||||
- **Crop for Inpaint keeps the whole soft edge inside the crop.** The blend
|
||||
at the seam is now complete. Crops and blend masks can come out slightly
|
||||
different from earlier releases for the same inputs.
|
||||
|
||||
- **Compare, the preview bar and Save Image no longer show a stale picture.**
|
||||
A late reply is ignored once the picture has changed, and Save Image
|
||||
forgets its old saved file when the folder changes. Save Image also takes
|
||||
bfloat16 and one-channel images, and a blank linked caption writes no
|
||||
caption file.
|
||||
|
||||
- **Color Match leaves a picture alone when matched to itself.** When the
|
||||
reference is the same picture, or the same colours at another size, the
|
||||
picture now comes back unchanged instead of shifting colour. Other matches
|
||||
can differ from earlier releases by less than one shade step.
|
||||
|
||||
- **Krea 2 Outpaint Model Patch no longer reuses an old reference.** On a
|
||||
fresh server's first run, its reference cache could hand back a stale
|
||||
reference, so the new area came out different from a run without the
|
||||
cache. Now both match exactly. Other model patches on the same model also
|
||||
apply alongside it.
|
||||
|
||||
- **Three example workflow notes now match their graphs.** Krea 2 Rotate +
|
||||
Outpaint says its tone match is on, Qwen Image 2.1 Inpaint says its seed is
|
||||
fixed, and Qwen Image 2.1 Upscale + Restore says the redraw is at least
|
||||
about 2 MP.
|
||||
|
||||
- **The pack's own checks are stricter.** They read pyproject.toml properly
|
||||
and catch more ways a node could be hidden from the Registry's scanners.
|
||||
Nothing changes in your workflows.
|
||||
|
||||
## 2.22.0 - 2026-11-07
|
||||
|
||||
- **Node cards have a calmer, easier-to-read look.** Number boxes, choices,
|
||||
switches, fields and buttons are now one solid gray with no outlines, on a
|
||||
dark card. Labels, units and section names are lighter and easier to read,
|
||||
and every control in a card row is the same height. The bar above a result
|
||||
picture (the picture arrows, the Preview steps and Preview switches, and
|
||||
buttons such as AUTO) and the picture's frame match the cards. The colors
|
||||
live in one shared file, so the rest of the pack can follow.
|
||||
- **New node: Camera Move 🆎.** Moves the camera of your own clip. Drag the
|
||||
picture on the node to turn the camera, pull back or push in, and set keys
|
||||
on a time bar. What the old camera never saw comes out pink, ready for
|
||||
MiniMax H3 with the CrossView-Warp LoRA to paint in. The new MiniMax H3
|
||||
Camera Move example puts it all in one box between Load Video and Save
|
||||
Video.
|
||||
|
||||
- **Mask by Touch 🆎 no longer fills holes unless you ask.** Fill small
|
||||
holes, under More, now starts off, so a hole you pick stays a hole. Saved
|
||||
@@ -359,6 +26,7 @@ All notable changes to ComfyUI-AusBoss are documented here.
|
||||
the old one, the new picture now shows on the node, ready to pick from. A
|
||||
new reload button beside Undo shows it any time, without running the
|
||||
workflow.
|
||||
|
||||
- **Save Image and Save Video: the Steps switch is now called Preview steps.** It
|
||||
shows the picture or the clip's first frame while it is being made, and "Steps"
|
||||
read like a sampler's step count. It works the same, and saved workflows keep
|
||||
|
||||
+3
-9
@@ -193,7 +193,7 @@ example_workflows/ # example workflows (regular workflow JSON, not API JSON)
|
||||
drag). Messages to the user go through `showToast`, never `alert()`.
|
||||
- The mouse wheel over a node zooms the graph, on every part of its face.
|
||||
`js/canvas_passthrough/` hands the wheel on from the pack's panels, and
|
||||
keeps it only for a box that can still scroll, typed in or not,
|
||||
keeps it only for a box that can still scroll or a field being typed in,
|
||||
so a panel adds no wheel listener of its own
|
||||
(`tests/canvas_passthrough.test.mjs` lists the few that exist). After a
|
||||
change to a node face, `scripts/dev/wheel_sweep.mjs` turns the wheel at
|
||||
@@ -210,7 +210,8 @@ example_workflows/ # example workflows (regular workflow JSON, not API JSON)
|
||||
never a classic canvas number widget on a finished node face. Units
|
||||
(`px`, `MP`, `×`) ride inside the box in a fixed-width slot that every
|
||||
single-field row reserves, so the numbers down a card share one centre
|
||||
line. Known, deliberate exception: the Seed card's seed (typed).
|
||||
line. Known, deliberate exceptions: the Seed card's seed (typed) and Load
|
||||
Video's trim timecodes (typed).
|
||||
- **Node faces are widget cards.** A node whose face would be classic
|
||||
LiteGraph widgets (full-width rows with an arrow at each end) gets an
|
||||
entry in `js/widget_cards/index.js` instead: `mountWidgetCard` from
|
||||
@@ -233,13 +234,6 @@ example_workflows/ # example workflows (regular workflow JSON, not API JSON)
|
||||
widget per row. A value that is meant to be wired rather than typed is a
|
||||
backend `forceInput: True` socket (Math Expression `a`/`b`/`c`), and a
|
||||
multi-type string such as `"FLOAT,INT"` accepts either kind of link.
|
||||
- **App mode** is ComfyUI's form view of a workflow (fields and a Run
|
||||
button). A file list from the input folder declares its upload flag
|
||||
(`image_upload`, `video_upload`, `audio_upload`): the form builds the
|
||||
field's Upload button from it, and without it the field is a bare list.
|
||||
`tests/test_video_upload_flag.py` holds the video lists to it. A card's
|
||||
hidden widgets reach the form through `js/app_mode/`, so a card needs
|
||||
nothing of its own for App mode.
|
||||
- Preview-carrying nodes (Select Frame, Mask Refine, Mask by Name, LaMa
|
||||
Inpaint, Save Image) share
|
||||
`js/input_preview/`: a thin bar (node tools left, a small `preview`
|
||||
|
||||
@@ -8,8 +8,6 @@
|
||||
<a href="https://github.com/ausboss/ComfyUI-AusBoss/releases/latest"><img src="assets/readme/release.svg" alt="Latest release"></a>
|
||||
<a href="https://www.youtube.com/@ausbossdev"><img src="https://img.shields.io/badge/YouTube-%40ausbossdev-00b4aa?style=flat-square&logo=youtube&logoColor=white" alt="YouTube @ausbossdev"></a>
|
||||
<a href="https://discord.gg/RwVxY9Fuaj"><img src="https://img.shields.io/badge/Discord-AusBoss-00b4aa?style=flat-square&logo=discord&logoColor=white" alt="Discord: AusBoss"></a>
|
||||
<a href="https://huggingface.co/ausboss"><img src="https://img.shields.io/badge/Hugging%20Face-ausboss-00b4aa?style=flat-square&logo=huggingface&logoColor=white" alt="Hugging Face: ausboss"></a>
|
||||
<a href="https://x.com/Zanzibased"><img src="https://img.shields.io/badge/X-%40Zanzibased-00b4aa?style=flat-square&logo=x&logoColor=white" alt="X @Zanzibased"></a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -20,7 +18,6 @@ Most of them are for image and video work. ComfyUI's core nodes already cover th
|
||||
- **[Mask by Touch](#mask-by-touch):** click a thing on the picture and get its mask. Hover shows what a click would take, and **Fine edges** follows hair and fur.
|
||||
- **[Mask by Name](#mask-by-name):** type "the red jacket" and get its mask and a cut-out.
|
||||
- **[Image Crop + Rotate + Pad](#image-crop--rotate--pad):** turn, crop and pad a picture by dragging handles on the node, for outpainting.
|
||||
- **[Edit Lock](#edit-lock):** an edit changes what you asked for, and the rest of the picture stays exactly where it was. No mask needed.
|
||||
- **[Stitch Inpaint](#stitch-inpaint):** after an inpaint or outpaint, everything you didn't ask to change is your original pixels again.
|
||||
- **[Video Crop + Rotate + Pad → Clip](#video-crop--rotate--pad--clip):** trim a clip on a timeline, and pad or crop it to a new shape.
|
||||
- **[Tiled Upscale](#tiled-upscale):** upscale a picture in tiles to the megapixels you set.
|
||||
@@ -30,7 +27,7 @@ Most of them are for image and video work. ComfyUI's core nodes already cover th
|
||||
- **[LoRA Loader](#lora-loader):** a whole LoRA stack in one node, each row with its own switch and strength.
|
||||
- **[Workflow Switches](#workflow-switches):** turn parts of a workflow off and on from one small card.
|
||||
|
||||
The **?** in a classic node's title bar opens a short card with its inputs and outputs. In Nodes 2.0, right-click the node and choose **About this node**. Every node also has a longer help page in ComfyUI's node help panel. I post the workflows I make with them on [Civitai](https://civitai.com/user/AusBoss) and [X @Zanzibased](https://x.com/Zanzibased), and videos of them on [YouTube @ausbossdev](https://www.youtube.com/@ausbossdev). Can't open Civitai? All my workflows are on [my Discord](https://discord.gg/RwVxY9Fuaj) too. If a node saves you time, a star on the repo helps other people find it.
|
||||
The **?** in a node's title bar opens a short card with its inputs and outputs, and every node has a longer help page in ComfyUI's node help panel. I post the workflows I make with them on [Civitai](https://civitai.com/user/AusBoss) and [X @Zanzibased](https://x.com/Zanzibased), and videos of them on [YouTube @ausbossdev](https://www.youtube.com/@ausbossdev). Can't open Civitai? All my workflows are on [my Discord](https://discord.gg/RwVxY9Fuaj) too. If a node saves you time, a star on the repo helps other people find it.
|
||||
|
||||
## Install
|
||||
|
||||
@@ -43,8 +40,6 @@ git clone https://github.com/ausboss/ComfyUI-AusBoss.git
|
||||
|
||||
Restart ComfyUI and search the node library for **AusBoss**.
|
||||
|
||||
Install it one way, not both. Manager puts the pack in `custom_nodes/ausboss-nodes` and a clone in `custom_nodes/ComfyUI-AusBoss`. They are the same pack, so if both folders are there, delete one. The console says which copy it skipped.
|
||||
|
||||
After an update, through Manager or `git pull`, restart ComfyUI and hard-refresh the browser with **Ctrl+Shift+R**. Otherwise the browser keeps the old JavaScript, and the pack warns you about it. Manager can install a version or two behind while the Comfy Registry reviews a new release. To get the newest one, pick it in Manager's version list, or update by hand: delete the pack's folder in `ComfyUI/custom_nodes` and clone the repository as shown above.
|
||||
|
||||
The pack uses the Pillow, NumPy, Torch and PyAV that come with ComfyUI. Each example lists the models it needs on its Workflow Note. LaMa Inpaint also needs [`big-lama.pt`](https://github.com/Sanster/models/releases/download/add_big_lama/big-lama.pt) in `ComfyUI/models/lama/`. The pack never downloads weights by itself.
|
||||
@@ -80,12 +75,6 @@ It returns the `image`, a `mask` of everything the model paints (padding, see-th
|
||||
|
||||
Krea 2 Rotate + Outpaint turns a photo, pads it and paints the new area in one pass. [Try the Krea 2 Rotate + Outpaint example →](example_workflows/Krea%202%20Rotate%20%2B%20Outpaint%20%28AusBoss%29.json)
|
||||
|
||||
### Load Image
|
||||
|
||||
Loads a picture and sets its size in one node. Pick a file, upload one, or step through the input folder with the arrows. **Size** can stay off, or bring the picture to a megapixel count, a longest side, a scale, a box it must fit inside, or a box it fills by cropping. It can also cut a piece or a shape such as 16:9 out of the picture without resizing, and **Keep** picks which part stays: the center, a side or a corner. **Round to** keeps the result on a multiple of 8, 16 or whatever the model wants. The node shows the picture going in and coming out, with both sizes, before you run, such as `912 × 1632 → 1144 × 2048`.
|
||||
|
||||
It returns the `image`, a `mask` of its see-through parts, the new `width` and `height`, the `filename` for a save prefix, and the file's `original_width` and `original_height`.
|
||||
|
||||
### Load Image + Pad
|
||||
|
||||
Makes a canvas for outpainting: drag the edges out to add room around a picture. The Source list shows the picture under the pointer. The new area can be a solid color, the average color of the nearest edge, the edge pixels smeared outward, a blurred copy of the picture, or a mirror of it. The card also has a seam feather, a canvas multiple and a megapixel budget, and **Exact padding** opens one control per side. A budget of 0 keeps the picture's size, and anything higher resizes the picture before padding. A picture wired into `source_image` is padded instead of the chosen file.
|
||||
@@ -146,18 +135,6 @@ The same watercolor edit without and with Realign to Source: 61 px off before, 0
|
||||
|
||||
Qwen drew this watercolor 5.6% taller, and Realign to Source lined it back up with the original.
|
||||
|
||||
### Edit Lock
|
||||
|
||||
Keeps every part of your picture that an edit did not change exactly where it was, with the colors it had. An edit model redraws the whole picture, so the parts you did not ask about often come back a little zoomed in, shifted or tinted, and the picture jumps when you flip between before and after. Put Edit Lock between the model and the sampler and give it the picture you are editing. It needs no mask: it sees what the edit changes while the picture is being made, and holds on to everything else.
|
||||
|
||||
When the edit changes the whole picture (a new style, new light), there is nothing to keep, so the node steps aside and the edit runs as usual. A soft effect over the whole picture, such as rain or falling snow, is let through as well: the node then only holds the picture in place. **Lock** (`lock`) set to `off` does nothing at all, `always` locks even a whole-picture edit, and an optional `mask` says where the edit may happen. **Tolerance** (`tolerance`) sets how big a change must be to count as part of the edit.
|
||||
|
||||
On MiniMax-H3-Image, 4 megapixel edits moved the picture by up to 14 px without the lock (measured at 1 megapixel) and by 0.2 px or less with it (0.08 px or less on 35 of the 36 locked runs), on 19 local edits at two seeds each. After five edits in a row on one picture the plain chain had drifted 1.65 px and turned visibly pink; the locked chain sat at 0.04 px with no tint.
|
||||
|
||||
### Edit Lock Restore
|
||||
|
||||
Puts your picture's own pixels back in every part the edit did not change. Edit Lock keeps those parts in place, but they still pass through the VAE, which softens fine detail a little. Add this right after the VAE Decode and wire in Edit Lock's `edit_lock` output. **Feather** (`feather`) sets how softly the original fades into the edit. It also returns `edit_mask`, white where the edit changed the picture, and a one-line `report` of how much was kept.
|
||||
|
||||
### Image Compare A/B
|
||||
|
||||
Compares two pictures with a slider, or flips between them whole. Nothing covers the picture, and its size shows underneath. The panel grows with the node, and images A and B pass through, so you can put it anywhere on an image wire. **Erase** mixes the two by hand: rub parts of one picture away with a brush so the other shows through, then save the mix as a PNG under a name you type, with a layered PSD for Photoshop or GIMP if you want it.
|
||||
@@ -180,23 +157,29 @@ The example keeps the clip's audio when there is any. The outpaint LoRA needs a
|
||||
|
||||
### Load Video
|
||||
|
||||
Upload a video, or pick one from the Source list, which plays the clip under the pointer. Set the part you want with Start, Duration and Ends at, in seconds or frames, or drag the handles under the player. The player plays the part you kept and can loop it. Width and height resize while decoding, and setting only one keeps the shape. `every_nth` skips frames and lowers the reported fps so the timing stays right, and the Duration caps how many frames load.
|
||||
Upload a video, or pick one from the Source list, which plays the clip under the pointer. Trim it with IN and OUT handles or typed timecodes. The player plays the part you kept and can loop it. Width and height resize while decoding, and setting only one keeps the shape. `every_nth` skips frames and lowers the reported fps so the timing stays right, and `max_frames` caps how many frames load.
|
||||
|
||||
It returns the frames, audio, frame count, fps, width, height, duration and a core `VIDEO`. Only the part you kept is decoded, and it checks memory before a large load. When you save the frames, wire its fps into the save node.
|
||||
|
||||
### Load Audio
|
||||
|
||||
Upload a sound file, or pick one from the Source list, and the node shows it as a wave. Drag the two handles to keep only the part you want, or type a Start, a Duration or an Ends at. Press play to hear just that part. Set the Duration to the length the next step needs, such as a video's length.
|
||||
Upload a sound file, or pick one from the Source list, and the node shows it as a wave. Drag the IN and OUT handles to keep only the part you want, or type the times. Press play to hear just that part. Set **Max length** to the longest sound the next step can take, such as a video's length: anything past it turns red and is cut off, so you see what comes out before you run. Click the red length next to OUT to move OUT to the cut.
|
||||
|
||||
It returns the `audio` you kept and its length in `seconds`. Only that part is decoded. [Help page](js/docs/AUSBOSS_NODES_LoadAudio.md).
|
||||
|
||||
### Camera Move
|
||||
|
||||
Moves the camera of your own clip. Press **Show my clip** and the node shows your clip in 3D. Drag the picture to turn the camera, scroll or pinch to pull back or push in, and click the time bar to set keys. What the old camera never saw comes out pink, and MiniMax H3 with Cseti's CrossView-Warp LoRA paints it in. Stay within about 45° left or right, 30° up and 20° down. Your keys add to any move your clip's camera already makes.
|
||||
|
||||
It needs depth from the core **MoGe Inference** node and returns the `guide` clip for H3 and a `holes` mask. [Help page](js/docs/AUSBOSS_NODES_CameraMove.md). [Open the MiniMax H3 Camera Move workflow →](example_workflows/MiniMax%20H3%20Camera%20Move%20%28AusBoss%29.json)
|
||||
|
||||
### Video Crop + Rotate + Pad → Frame
|
||||
|
||||
Picks one frame from a video, then gives you the same rotate, crop and pad controls as the image node, plus an optional megapixel resize. Scrub to the frame with the playhead on the node; the editor adds frame-by-frame stepping and playback. It returns the transformed `image`, a `mask` of the added area, a `stitcher`, the chosen `original` frame, and the output `width` and `height`. For a whole clip, use the Clip version below.
|
||||
|
||||
### Video Crop + Rotate + Pad → Clip
|
||||
|
||||
Applies one rotate, crop and pad to every frame of a trimmed clip. It has the source picker, a timeline with a playhead and frame-accurate start and end handles, Start, Duration and Ends at boxes, frame skipping, the transform handles and output resizing. While you drag a trim handle, the node shows the exact first or last frame the run keeps. The bright part of the selection is what gets output.
|
||||
Applies one rotate, crop and pad to every frame of a trimmed clip. It has the source picker, a timeline with a playhead and frame-accurate IN and OUT handles, frame skipping, a frame limit, the transform handles and output resizing. While you drag a trim handle, the node shows the exact first or last frame the run keeps. The bright part of the selection is what gets output.
|
||||
|
||||
Fill, feather and the resize budget are in **Crop, pad & resize** below the timeline, and a new clip keeps them. That matters for video outpainting, because the black, hard-edged canvas the model needs survives a source swap. A fresh Clip node starts with that canvas, and the editor's **Reset transform** goes back to it. **Frames for** trims the end to the frame count the next video model takes: LTX (8n+1) or Wan (4n+1). Tap a ratio to pad the clip to it; a new clip is padded to the lit ratio too. The padlock keeps the shape while you drag a handle.
|
||||
|
||||
@@ -218,12 +201,6 @@ Changes a clip's frame rate by making in-between frames. You set the source and
|
||||
|
||||
It returns the new frames and their fps. It doesn't touch audio, so carry the source audio to Save Video separately. The [help page](js/docs/AUSBOSS_NODES_FrameInterpolate.md) covers the weights and timing.
|
||||
|
||||
### FlashVSR Upscale
|
||||
|
||||
Makes a video larger and sharper with the FlashVSR model. Set **Scale** from 1 to 4 and it returns every frame at the new size, with fine detail drawn back in. It reads the clip a few frames at a time, so a long clip needs no more graphics memory than a short one, and a result too large for the free memory is made in tiles.
|
||||
|
||||
It needs one model file in `ComfyUI/models/diffusion_models` and no other pack. The [help page](js/docs/AUSBOSS_NODES_FlashVSRUpscale.md) has the download link, the memory it needs and the speed. [Try the FlashVSR Video Upscale example →](example_workflows/FlashVSR%20Video%20Upscale%20%28AusBoss%29.json)
|
||||
|
||||
### Save Video
|
||||
|
||||
Saves a frame batch or a core `VIDEO` as MP4 (H.264 or H.265), WebM (VP9 or AV1), ProRes MOV, lossless FFV1 MKV, GIF or WebP. Which encoders you get depends on your FFmpeg and PyAV build, and H.264 and H.265 come in CPU and NVENC versions. The videos carry color tags, and optionally audio and the workflow.
|
||||
@@ -369,14 +346,6 @@ Puts batch `b` after `a`. When the sizes match, nothing is resized. When they di
|
||||
|
||||
A text box that grows with the node and sends its text, unchanged, down a `STRING` wire. Use it for a prompt, caption, path or other text that several nodes share. Spaces and line breaks are kept. Ctrl + Up and Ctrl + Down change the weight of the selected words, as in ComfyUI's own prompt boxes.
|
||||
|
||||
### Text Lines
|
||||
|
||||
Runs what comes after once for each line of your text. Type five prompts, one on each line, and one run makes five pictures. It also takes a list another node wrote, skips empty lines, and can take a leading `1.` or `-` off each line. `number` counts the lines from 1, to give each its own seed.
|
||||
|
||||
### Prompt Variations
|
||||
|
||||
A prompt box that changes on every run. Write choices in curly brackets, split by `|`, such as `a {red|blue|green} {sweater|jacket}`, and the node picks one from each set. Wire in the seed your sampler uses: a new seed gives a new mix, and the same seed gives the same prompt again. Set the seed to randomize and queue 50 runs to get 50 different prompts. Text without brackets comes out exactly as typed, so a JSON prompt is safe.
|
||||
|
||||
### H3 Prompt Writer
|
||||
|
||||
Type what happens, one line for each moment, and leave a blank line to cut to a new place. Connect up to four pictures and give each one a job: a person, a place, an outfit, a thing or a style. Copy the moves from a video, keep a clip going, or add a voice or a song. A timeline on the node shows when each moment plays before you run it. It needs no extra model and you never see H3's prompt format. Connect a small text model and it fills in a one-line idea.
|
||||
@@ -429,7 +398,7 @@ Turns parts of a workflow off and on from one small card. Select the nodes of on
|
||||
|
||||
## Example workflows
|
||||
|
||||
These are the workflows where the nodes do something core ComfyUI doesn't do by itself: outpainting and inpainting that put your original picture back, lining an edit back up with its source, upscaling a picture in tiles, masking a thing by its name or with a click, removing a watermark from a clip, and making a clip larger and sharper. Open a JSON file from [`example_workflows/`](example_workflows), or find them under this pack in ComfyUI's template browser. Each one has a thumbnail, numbered groups and a Workflow Note with the setup steps and model downloads.
|
||||
These are the workflows where the nodes do something core ComfyUI doesn't do by itself: outpainting and inpainting that put your original picture back, lining an edit back up with its source, upscaling a picture in tiles, masking a thing by its name or with a click, and removing a watermark from a clip. Open a JSON file from [`example_workflows/`](example_workflows), or find them under this pack in ComfyUI's template browser. Each one has a thumbnail, numbered groups and a Workflow Note with the setup steps and model downloads.
|
||||
|
||||

|
||||
|
||||
@@ -450,7 +419,6 @@ The workflows open with their image and video loaders empty, so you load your ow
|
||||
| [Mask by Name](example_workflows/Mask%20by%20Name%20%28AusBoss%29.json) | Type what to find in a picture, and get its mask and a cut-out with a see-through background | ComfyUI's own SAM 3.1 (ComfyUI 0.20 or newer) |
|
||||
| [Mask by Touch](example_workflows/Mask%20by%20Touch%20%28AusBoss%29.json) | Click a thing in a picture, or its whole subject, and get its mask and a cut-out with hair-fine edges | ComfyUI's own SAM 3.1 and its background-removal model (ComfyUI 0.21 or newer) |
|
||||
| [Simple Video Watermark Remover](example_workflows/Simple%20Video%20Watermark%20Remover%20%28AusBoss%29.json) | Find an overlay in a clip and remove it, with a one-frame comparison branch | ComfyUI's own SAM 3.1 (ComfyUI 0.20 or newer), plus `big-lama.pt` |
|
||||
| [FlashVSR Video Upscale](example_workflows/FlashVSR%20Video%20Upscale%20%28AusBoss%29.json) | Make a clip larger and sharper with one node | `flashvsr_v1.1_fp16.safetensors` |
|
||||
|
||||
Every example uses only core nodes and this pack. Speed and memory use depend on the models, the sizes, the frame count and whatever else is using the GPU.
|
||||
|
||||
@@ -471,7 +439,7 @@ People who download your workflow get the nodes through ComfyUI-Manager's missin
|
||||
|
||||
## Pack-wide tools
|
||||
|
||||
- **Help cards:** the **?** in a classic node's title bar opens its description, inputs and outputs. Nodes 2.0 and titleless nodes such as Run Timer have **About this node** in their right-click menu.
|
||||
- **Help cards:** the **?** in a node's title bar opens its description, inputs and outputs. Run Timer has no title bar, so it has **About this node** in its right-click menu.
|
||||
- **Recreate node 🆎** (right-click an AusBoss node) rebuilds a node saved by an older version from the current definition. It keeps the values, links, position and colors.
|
||||
- **Replace with AusBoss nodes 🆎** (canvas right-click or the command palette) finds third-party nodes this pack can stand in for, such as VideoHelperSuite's Load Video and Video Combine or KJNodes' Color Match. It previews each swap and replaces the ones you leave ticked.
|
||||
- **Snap into line:** a node, group or selection you drag lines up with the nodes and groups around it, edge to edge or middle to middle, and a teal line shows what it lines up with. Pulling a corner to resize lines up the same way. Hold Shift while you drag to skip it, or turn it off in Settings → 🆎 AusBoss → Canvas.
|
||||
@@ -486,7 +454,7 @@ People who download your workflow get the nodes through ComfyUI-Manager's missin
|
||||
- Hold Shift while you turn the green rotation handle to snap to 15° steps.
|
||||
- In the full-screen editor, the mouse wheel zooms, and the middle mouse button or Alt-drag pans. On the node itself, the wheel and middle mouse button still move the graph.
|
||||
- **Alt+E** opens the selected node's transform editor. Change the key in Settings → Keybindings.
|
||||
- The video editors have frame stepping, playback and exact timeline seeking, on the node face as well as in the editor. The Clip node's start and end handles sit on the source's own frames, so the frame shown at the start is the first one decoded and the frame shown at the end is the last.
|
||||
- The video editors have frame stepping, playback and exact timeline seeking, on the node face as well as in the editor. The Clip node's IN and OUT handles sit on the source's own frames, so the frame shown for IN is the first one decoded and the frame shown for OUT is the last.
|
||||
- Your own aspect presets go in `ausboss_presets.json` beside the pack. Copy [`ausboss_presets_example.json`](ausboss_presets_example.json) to start. Your file survives updates.
|
||||
|
||||
LoRA Loader and Latent Size have their own gear menus for per-node preferences.
|
||||
|
||||
+12
-43
@@ -11,7 +11,7 @@ of taking the whole pack down, so one broken node never hides the rest.
|
||||
|
||||
import importlib
|
||||
import os
|
||||
import tomllib
|
||||
import re
|
||||
import traceback
|
||||
|
||||
# One entry per file in nodes/, kept alphabetical. The order has no
|
||||
@@ -20,10 +20,9 @@ NODE_MODULES = [
|
||||
"node_align_image",
|
||||
"node_batch_utils",
|
||||
"node_callout",
|
||||
"node_camera_move",
|
||||
"node_color_match",
|
||||
"node_compare",
|
||||
"node_edit_lock",
|
||||
"node_flashvsr_upscale",
|
||||
"node_frame_interpolate",
|
||||
"node_free_memory",
|
||||
"node_h3_prompt_writer",
|
||||
@@ -37,7 +36,6 @@ NODE_MODULES = [
|
||||
"node_lama_inpaint",
|
||||
"node_layout_boxes",
|
||||
"node_literals",
|
||||
"node_load_image",
|
||||
"node_load_image_pad",
|
||||
"node_load_audio",
|
||||
"node_load_video",
|
||||
@@ -45,7 +43,6 @@ NODE_MODULES = [
|
||||
"node_mask_by_name",
|
||||
"node_mask_by_touch",
|
||||
"node_math",
|
||||
"node_prompt_variations",
|
||||
"node_realign_to_source",
|
||||
"node_refine_mask",
|
||||
"node_resolution",
|
||||
@@ -56,7 +53,6 @@ NODE_MODULES = [
|
||||
"node_select_frame",
|
||||
"node_show_text",
|
||||
"node_step_preview",
|
||||
"node_text_lines",
|
||||
"node_tiled_upscale",
|
||||
"node_video_crop_rotate_pad",
|
||||
"node_video_crop_rotate_pad_clip",
|
||||
@@ -68,19 +64,7 @@ NODE_CLASS_MAPPINGS = {}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {}
|
||||
_failed_modules = []
|
||||
|
||||
# Two copies of the pack (a Manager install beside a git clone) add every
|
||||
# route twice and ComfyUI stops while starting. Only one copy loads.
|
||||
_other_copy = None
|
||||
try:
|
||||
from .nodes._single_copy import other_copy_that_loads
|
||||
|
||||
_other_copy = other_copy_that_loads(os.path.dirname(__file__))
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
|
||||
for _module_name in NODE_MODULES:
|
||||
if _other_copy:
|
||||
break
|
||||
try:
|
||||
_module = importlib.import_module(f".nodes.{_module_name}", __name__)
|
||||
NODE_CLASS_MAPPINGS.update(getattr(_module, "NODE_CLASS_MAPPINGS", {}))
|
||||
@@ -93,7 +77,7 @@ for _module_name in NODE_MODULES:
|
||||
|
||||
# Folder ComfyUI serves to the browser; every .js file in it is loaded as a
|
||||
# frontend extension. Shared modules use .mjs so they are import-only.
|
||||
WEB_DIRECTORY = None if _other_copy else "./js"
|
||||
WEB_DIRECTORY = "./js"
|
||||
|
||||
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
|
||||
|
||||
@@ -102,9 +86,9 @@ def _read_version():
|
||||
"""Version straight from pyproject.toml so it is never duplicated."""
|
||||
try:
|
||||
pyproject = os.path.join(os.path.dirname(__file__), "pyproject.toml")
|
||||
with open(pyproject, "rb") as f:
|
||||
version = tomllib.load(f).get("project", {}).get("version")
|
||||
return version if isinstance(version, str) and version.strip() else "unknown"
|
||||
with open(pyproject, "r", encoding="utf-8") as f:
|
||||
match = re.search(r'^version\s*=\s*"([^"]+)"', f.read(), re.MULTILINE)
|
||||
return match.group(1) if match else "unknown"
|
||||
except Exception:
|
||||
return "unknown"
|
||||
|
||||
@@ -129,26 +113,11 @@ def _print_banner():
|
||||
print(bar)
|
||||
|
||||
|
||||
def _print_second_copy():
|
||||
# ASCII only, as in the banner.
|
||||
red = "\033[0;31m"
|
||||
reset = "\033[0m"
|
||||
own = os.path.basename(os.path.dirname(os.path.realpath(__file__)))
|
||||
other = os.path.basename(_other_copy["folder"])
|
||||
print(f"{red}AusBoss: this pack is installed twice.{reset}")
|
||||
print(f" Using: custom_nodes/{other} (v{_other_copy['version']})")
|
||||
print(f" Skipping: custom_nodes/{own} (v{_read_version()})")
|
||||
print(" Delete one of the two folders, then restart ComfyUI.")
|
||||
try:
|
||||
from .nodes._frontend_cache import register_frontend_cache_guard
|
||||
|
||||
register_frontend_cache_guard()
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
|
||||
if _other_copy:
|
||||
_print_second_copy()
|
||||
else:
|
||||
try:
|
||||
from .nodes._frontend_cache import register_frontend_cache_guard
|
||||
|
||||
register_frontend_cache_guard()
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
|
||||
_print_banner()
|
||||
_print_banner()
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20" role="img" aria-label="release: v2.26.2">
|
||||
<title>release: v2.26.2</title>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20" role="img" aria-label="release: v2.21.2">
|
||||
<title>release: v2.21.2</title>
|
||||
<path fill="#555" d="M0 0h48v20H0z"/>
|
||||
<path fill="#00b4aa" d="M48 0h57v20H48z"/>
|
||||
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
|
||||
<text x="24" y="14">release</text>
|
||||
<text x="76.5" y="14">v2.26.2</text>
|
||||
<text x="76.5" y="14">v2.21.2</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 425 B After Width: | Height: | Size: 425 B |
Binary file not shown.
|
Before Width: | Height: | Size: 127 KiB |
@@ -1,526 +0,0 @@
|
||||
{
|
||||
"id": "0b455c1f-6b0c-4f69-8a7e-86f8de61df5c",
|
||||
"revision": 0,
|
||||
"last_node_id": 5,
|
||||
"last_link_id": 4,
|
||||
"nodes": [
|
||||
{
|
||||
"id": 1,
|
||||
"type": "AUSBOSS_NODES_WorkflowNote",
|
||||
"pos": [
|
||||
0,
|
||||
30
|
||||
],
|
||||
"size": [
|
||||
440,
|
||||
640
|
||||
],
|
||||
"flags": {},
|
||||
"order": 0,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "note",
|
||||
"type": "STRING",
|
||||
"link": null,
|
||||
"widget": {
|
||||
"name": "note"
|
||||
}
|
||||
}
|
||||
],
|
||||
"outputs": [],
|
||||
"title": "🆎 AusBoss",
|
||||
"properties": {
|
||||
"cnr_id": "ausboss-nodes",
|
||||
"ver": "2.24.0",
|
||||
"Node name for S&R": "AUSBOSS_NODES_WorkflowNote"
|
||||
},
|
||||
"widgets_values": [
|
||||
"{\"v\": 1, \"title\": \"FlashVSR Video Upscale\", \"subtitle\": \"Make a video larger and sharper with one node and one model file.\", \"author\": \"AusBoss\", \"layout\": \"card\", \"accent\": \"\", \"body\": \"[▶ AusBoss on YouTube](https://www.youtube.com/@ausbossdev) · videos on these nodes and workflows\\n\\n---\\n\\n1. Load your video.\\n2. Set **Scale**: how many times larger each side gets. At 1 the video keeps its size and is only sharpened.\\n3. Press **Run**, then play the result in **Save Video**.\\n\\nTo try a short piece first, drag the right end of the bar under the player in Load Video.\\n\\nA long video needs no more graphics memory than a short one. A large result is made in tiles, so it fits the memory you have and takes longer.\\n\\nNeeds AusBoss nodes 2.24.0 or newer. No other pack is needed.\", \"models\": [{\"name\": \"flashvsr_v1.1_fp16.safetensors\", \"dir\": \"diffusion_models\", \"size\": \"3.5 GB\", \"url\": \"https://huggingface.co/ausboss/FlashVSR-v1.1-ComfyUI/resolve/main/flashvsr_v1.1_fp16.safetensors\", \"note\": \"FlashVSR v1.1 by Junhao Zhuang and the OpenImagingLab team, in one file\"}], \"packs\": [{\"name\": \"ComfyUI-AusBoss\", \"url\": \"https://github.com/ausboss/ComfyUI-AusBoss\", \"node\": \"AUSBOSS_NODES_FlashVSRUpscale\"}], \"links\": [{\"label\": \"YouTube · ausbossdev\", \"url\": \"https://www.youtube.com/@ausbossdev\"}, {\"label\": \"GitHub · ausboss\", \"url\": \"https://github.com/ausboss\"}, {\"label\": \"Civitai · AusBoss\", \"url\": \"https://civitai.com/user/AusBoss\"}, {\"label\": \"X · Zanzibased\", \"url\": \"https://x.com/Zanzibased\"}]}",
|
||||
""
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"note": "{\"v\": 1, \"title\": \"FlashVSR Video Upscale\", \"subtitle\": \"Make a video larger and sharper with one node and one model file.\", \"author\": \"AusBoss\", \"layout\": \"card\", \"accent\": \"\", \"body\": \"[▶ AusBoss on YouTube](https://www.youtube.com/@ausbossdev) · videos on these nodes and workflows\\n\\n---\\n\\n1. Load your video.\\n2. Set **Scale**: how many times larger each side gets. At 1 the video keeps its size and is only sharpened.\\n3. Press **Run**, then play the result in **Save Video**.\\n\\nTo try a short piece first, drag the right end of the bar under the player in Load Video.\\n\\nA long video needs no more graphics memory than a short one. A large result is made in tiles, so it fits the memory you have and takes longer.\\n\\nNeeds AusBoss nodes 2.24.0 or newer. No other pack is needed.\", \"models\": [{\"name\": \"flashvsr_v1.1_fp16.safetensors\", \"dir\": \"diffusion_models\", \"size\": \"3.5 GB\", \"url\": \"https://huggingface.co/ausboss/FlashVSR-v1.1-ComfyUI/resolve/main/flashvsr_v1.1_fp16.safetensors\", \"note\": \"FlashVSR v1.1 by Junhao Zhuang and the OpenImagingLab team, in one file\"}], \"packs\": [{\"name\": \"ComfyUI-AusBoss\", \"url\": \"https://github.com/ausboss/ComfyUI-AusBoss\", \"node\": \"AUSBOSS_NODES_FlashVSRUpscale\"}], \"links\": [{\"label\": \"YouTube · ausbossdev\", \"url\": \"https://www.youtube.com/@ausbossdev\"}, {\"label\": \"GitHub · ausboss\", \"url\": \"https://github.com/ausboss\"}, {\"label\": \"Civitai · AusBoss\", \"url\": \"https://civitai.com/user/AusBoss\"}, {\"label\": \"X · Zanzibased\", \"url\": \"https://x.com/Zanzibased\"}]}",
|
||||
"ausboss_workflow_note_panel": ""
|
||||
},
|
||||
"color": "#14424d",
|
||||
"bgcolor": "#161f21"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"type": "AUSBOSS_NODES_LoadVideo",
|
||||
"pos": [
|
||||
500,
|
||||
80
|
||||
],
|
||||
"size": [
|
||||
420,
|
||||
760
|
||||
],
|
||||
"flags": {},
|
||||
"order": 0,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "video",
|
||||
"type": "COMBO",
|
||||
"link": null,
|
||||
"widget": {
|
||||
"name": "video"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "start_seconds",
|
||||
"type": "FLOAT",
|
||||
"link": null,
|
||||
"widget": {
|
||||
"name": "start_seconds"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "end_seconds",
|
||||
"type": "FLOAT",
|
||||
"link": null,
|
||||
"widget": {
|
||||
"name": "end_seconds"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "custom_width",
|
||||
"type": "INT",
|
||||
"link": null,
|
||||
"widget": {
|
||||
"name": "custom_width"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "custom_height",
|
||||
"type": "INT",
|
||||
"link": null,
|
||||
"widget": {
|
||||
"name": "custom_height"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "every_nth",
|
||||
"type": "INT",
|
||||
"link": null,
|
||||
"widget": {
|
||||
"name": "every_nth"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "max_frames",
|
||||
"type": "INT",
|
||||
"link": null,
|
||||
"widget": {
|
||||
"name": "max_frames"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "single_frame",
|
||||
"type": "BOOLEAN",
|
||||
"link": null,
|
||||
"widget": {
|
||||
"name": "single_frame"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "upload",
|
||||
"type": "IMAGEUPLOAD",
|
||||
"link": null,
|
||||
"widget": {
|
||||
"name": "upload"
|
||||
}
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "frames",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
1
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "audio",
|
||||
"type": "AUDIO",
|
||||
"links": [
|
||||
3
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "frame_count",
|
||||
"type": "INT",
|
||||
"links": []
|
||||
},
|
||||
{
|
||||
"name": "fps",
|
||||
"type": "FLOAT",
|
||||
"links": [
|
||||
4
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "width",
|
||||
"type": "INT",
|
||||
"links": []
|
||||
},
|
||||
{
|
||||
"name": "height",
|
||||
"type": "INT",
|
||||
"links": []
|
||||
},
|
||||
{
|
||||
"name": "duration",
|
||||
"type": "FLOAT",
|
||||
"links": []
|
||||
},
|
||||
{
|
||||
"name": "video",
|
||||
"type": "VIDEO",
|
||||
"links": []
|
||||
}
|
||||
],
|
||||
"title": "Load Video - Your video",
|
||||
"properties": {
|
||||
"cnr_id": "ausboss-nodes",
|
||||
"ver": "2.24.0",
|
||||
"Node name for S&R": "AUSBOSS_NODES_LoadVideo",
|
||||
"ausboss_load_video_loop": true
|
||||
},
|
||||
"widgets_values": {
|
||||
"video": "",
|
||||
"start_seconds": 0,
|
||||
"end_seconds": 0,
|
||||
"custom_width": 0,
|
||||
"custom_height": 0,
|
||||
"every_nth": 1,
|
||||
"max_frames": 0,
|
||||
"single_frame": false
|
||||
},
|
||||
"widgets_values_named": {
|
||||
"video": "",
|
||||
"start_seconds": 0,
|
||||
"end_seconds": 0,
|
||||
"custom_width": 0,
|
||||
"custom_height": 0,
|
||||
"every_nth": 1,
|
||||
"max_frames": 0,
|
||||
"single_frame": false,
|
||||
"upload": "image",
|
||||
"ausboss_widget_card": "",
|
||||
"ausboss_load_video_viewer": ""
|
||||
},
|
||||
"color": "#14424d",
|
||||
"bgcolor": "#161f21"
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"type": "AUSBOSS_NODES_FlashVSRUpscale",
|
||||
"pos": [
|
||||
980,
|
||||
80
|
||||
],
|
||||
"size": [
|
||||
360,
|
||||
190
|
||||
],
|
||||
"flags": {},
|
||||
"order": 0,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "frames",
|
||||
"type": "IMAGE",
|
||||
"link": 1
|
||||
},
|
||||
{
|
||||
"name": "vae",
|
||||
"type": "VAE",
|
||||
"shape": 7,
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "model",
|
||||
"type": "COMBO",
|
||||
"link": null,
|
||||
"widget": {
|
||||
"name": "model"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "scale",
|
||||
"type": "FLOAT",
|
||||
"link": null,
|
||||
"widget": {
|
||||
"name": "scale"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "color_match",
|
||||
"type": "BOOLEAN",
|
||||
"link": null,
|
||||
"widget": {
|
||||
"name": "color_match"
|
||||
}
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "frames",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
2
|
||||
]
|
||||
}
|
||||
],
|
||||
"title": "FlashVSR Upscale",
|
||||
"properties": {
|
||||
"cnr_id": "ausboss-nodes",
|
||||
"ver": "2.24.0",
|
||||
"Node name for S&R": "AUSBOSS_NODES_FlashVSRUpscale",
|
||||
"models": [
|
||||
{
|
||||
"name": "flashvsr_v1.1_fp16.safetensors",
|
||||
"url": "https://huggingface.co/ausboss/FlashVSR-v1.1-ComfyUI/resolve/main/flashvsr_v1.1_fp16.safetensors",
|
||||
"directory": "diffusion_models"
|
||||
}
|
||||
]
|
||||
},
|
||||
"widgets_values": [
|
||||
"flashvsr_v1.1_fp16.safetensors",
|
||||
2,
|
||||
true,
|
||||
""
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"model": "flashvsr_v1.1_fp16.safetensors",
|
||||
"scale": 2,
|
||||
"color_match": true,
|
||||
"ausboss_widget_card": ""
|
||||
},
|
||||
"color": "#14424d",
|
||||
"bgcolor": "#161f21"
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"type": "AUSBOSS_NODES_SaveVideo",
|
||||
"pos": [
|
||||
1400,
|
||||
80
|
||||
],
|
||||
"size": [
|
||||
440,
|
||||
640
|
||||
],
|
||||
"flags": {},
|
||||
"order": 0,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "frames",
|
||||
"type": "IMAGE",
|
||||
"link": 2
|
||||
},
|
||||
{
|
||||
"name": "audio",
|
||||
"type": "AUDIO",
|
||||
"link": 3
|
||||
},
|
||||
{
|
||||
"name": "video",
|
||||
"type": "VIDEO",
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "fps",
|
||||
"type": "FLOAT",
|
||||
"link": 4
|
||||
},
|
||||
{
|
||||
"name": "filename_prefix",
|
||||
"type": "STRING",
|
||||
"link": null,
|
||||
"widget": {
|
||||
"name": "filename_prefix"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "crf",
|
||||
"type": "INT",
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "format",
|
||||
"type": "COMBO",
|
||||
"link": null,
|
||||
"widget": {
|
||||
"name": "format"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "pingpong",
|
||||
"type": "BOOLEAN",
|
||||
"link": null,
|
||||
"widget": {
|
||||
"name": "pingpong"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "save_metadata",
|
||||
"type": "BOOLEAN",
|
||||
"link": null,
|
||||
"widget": {
|
||||
"name": "save_metadata"
|
||||
}
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "file_path",
|
||||
"type": "STRING",
|
||||
"links": []
|
||||
}
|
||||
],
|
||||
"title": "Save Video",
|
||||
"properties": {
|
||||
"cnr_id": "ausboss-nodes",
|
||||
"ver": "2.24.0",
|
||||
"Node name for S&R": "AUSBOSS_NODES_SaveVideo",
|
||||
"ausboss_save_video_loop": true
|
||||
},
|
||||
"widgets_values": {
|
||||
"fps": 24,
|
||||
"filename_prefix": "flashvsr_upscaled",
|
||||
"crf": 19,
|
||||
"format": "mp4 h264",
|
||||
"pingpong": false,
|
||||
"save_metadata": true
|
||||
},
|
||||
"widgets_values_named": {
|
||||
"fps": 24,
|
||||
"filename_prefix": "flashvsr_upscaled",
|
||||
"crf": 19,
|
||||
"format": "mp4 h264",
|
||||
"pingpong": false,
|
||||
"save_metadata": true,
|
||||
"ausboss_widget_card": "",
|
||||
"ausboss_save_video_viewer": ""
|
||||
},
|
||||
"color": "#14424d",
|
||||
"bgcolor": "#161f21"
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"type": "AUSBOSS_NODES_RunTimer",
|
||||
"pos": [
|
||||
1515,
|
||||
770
|
||||
],
|
||||
"size": [
|
||||
210,
|
||||
67
|
||||
],
|
||||
"flags": {},
|
||||
"order": 0,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [],
|
||||
"title": "Run Timer",
|
||||
"properties": {
|
||||
"cnr_id": "ausboss-nodes",
|
||||
"ver": "2.24.0",
|
||||
"Node name for S&R": "AUSBOSS_NODES_RunTimer"
|
||||
},
|
||||
"color": "#14424d",
|
||||
"bgcolor": "#161f21"
|
||||
}
|
||||
],
|
||||
"links": [
|
||||
[
|
||||
1,
|
||||
2,
|
||||
0,
|
||||
3,
|
||||
0,
|
||||
"IMAGE"
|
||||
],
|
||||
[
|
||||
2,
|
||||
3,
|
||||
0,
|
||||
4,
|
||||
0,
|
||||
"IMAGE"
|
||||
],
|
||||
[
|
||||
3,
|
||||
2,
|
||||
1,
|
||||
4,
|
||||
1,
|
||||
"AUDIO"
|
||||
],
|
||||
[
|
||||
4,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
3,
|
||||
"FLOAT"
|
||||
]
|
||||
],
|
||||
"groups": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "1 · Your video",
|
||||
"bounding": [
|
||||
480,
|
||||
0,
|
||||
460,
|
||||
880
|
||||
],
|
||||
"color": "#1d5560",
|
||||
"flags": {}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "2 · Make it larger",
|
||||
"bounding": [
|
||||
960,
|
||||
0,
|
||||
400,
|
||||
880
|
||||
],
|
||||
"color": "#1d5560",
|
||||
"flags": {}
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "3 · Result",
|
||||
"bounding": [
|
||||
1380,
|
||||
0,
|
||||
480,
|
||||
880
|
||||
],
|
||||
"color": "#1d5560",
|
||||
"flags": {}
|
||||
}
|
||||
],
|
||||
"definitions": {
|
||||
"subgraphs": []
|
||||
},
|
||||
"config": {},
|
||||
"extra": {
|
||||
"ds": {
|
||||
"scale": 0.73,
|
||||
"offset": [
|
||||
137,
|
||||
20
|
||||
]
|
||||
}
|
||||
},
|
||||
"version": 0.4
|
||||
}
|
||||
@@ -1913,7 +1913,7 @@
|
||||
"The painted area, grown a little, is filled with flat gray, so Krea 2 knows where to paint. The plain crop goes along too."
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"text": "The painted area, grown a little, is filled with flat gray, so Krea 2 knows where to paint. The plain crop goes along too."
|
||||
"text": "The painted area, grown a little, is filled with flat gray. Krea 2 never sees what you are replacing."
|
||||
},
|
||||
"color": "#1f2c38",
|
||||
"bgcolor": "#2a3b4a"
|
||||
@@ -3052,7 +3052,7 @@
|
||||
"The gray-filled crop is the reference. Painting starts from the plain crop, inside the noise mask: the painted area, widened by 24 px."
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"text": "The gray-filled crop is the reference. Painting starts from the plain crop, inside the noise mask: the painted area, widened by 24 px."
|
||||
"text": "The gray-filled crop is the reference. The noise mask is the grown painted area, widened by 24 px. Krea 2 paints only inside it."
|
||||
},
|
||||
"color": "#1f2c38",
|
||||
"bgcolor": "#2a3b4a"
|
||||
@@ -3482,4 +3482,4 @@
|
||||
"frontendVersion": "1.53.6"
|
||||
},
|
||||
"version": 0.4
|
||||
}
|
||||
}
|
||||
@@ -2139,10 +2139,10 @@
|
||||
"title": "Note",
|
||||
"properties": {},
|
||||
"widgets_values": [
|
||||
"Blend in fades the model's picture into yours just inside its edge. Tone match is fully on, so the new area is adjusted to your picture's tone."
|
||||
"Blend in fades the model's picture into yours just inside its edge, with no tone shift. The new area stays as painted."
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"text": "Blend in fades the model's picture into yours just inside its edge. Tone match is fully on, so the new area is adjusted to your picture's tone."
|
||||
"text": "Blend in fades the model's picture into yours just inside its edge, with no tone shift. The new area stays as painted."
|
||||
},
|
||||
"color": "#1f2c38",
|
||||
"bgcolor": "#2a3b4a"
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 118 KiB |
File diff suppressed because it is too large
Load Diff
@@ -37,10 +37,10 @@
|
||||
"Node name for S&R": "AUSBOSS_NODES_WorkflowNote"
|
||||
},
|
||||
"widgets_values": [
|
||||
"{\"v\": 1, \"title\": \"Qwen Image 2.1 Inpaint\", \"subtitle\": \"Click a thing in your picture and say what to change. Only that part is repainted.\", \"author\": \"AusBoss\", \"layout\": \"card\", \"accent\": \"\", \"body\": \"1. Load your image. You can crop it right there with the blue handles.\\n2. On **Mask by Touch**, click the thing you want to change. It lights up before you click.\\n3. In **What to change**, say it the way you would ask a person: \\\"Replace the cup with a glass of orange juice.\\\"\\n4. Press **Run**.\\n\\nOnly the picked part is repainted. Everything outside it stays your own picture.\\n\\n### Tips\\n- Wrong thing picked? The arrows under the picture swap it for the next thing it could mean.\\n- Name everything that should go: \\\"the iced coffee and its straw\\\". What you do not name can stay.\\n- To remove something, pick it and write \\\"Remove the cup.\\\" Pick its shadow too, or the shadow stays.\\n- To add something, switch to **Paint** and paint where it should go, with some room. Say how big: \\\"Add small black sunglasses on her eyes.\\\"\\n- Not what you wanted? Change **Seed** and run it again. It stays fixed between runs.\\n\\n### Switches\\n- **Fast** on: 8 steps with the Viggle Turbo LoRA from the list below. Off: 25 steps without it, about twice as long.\\n\\nNeeds ComfyUI 0.38 or newer and AusBoss nodes 2.12.0 or newer (update first).\", \"models\": [{\"name\": \"qwen_image_2.1_int8_convrot.safetensors\", \"dir\": \"diffusion_models\", \"size\": \"7.26 GB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/diffusion_models/qwen_image_2.1_int8_convrot.safetensors\", \"note\": \"\"}, {\"name\": \"qwen3vl_8b_int8_convrot.safetensors\", \"dir\": \"text_encoders\", \"size\": \"9.35 GB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/text_encoders/qwen3vl_8b_int8_convrot.safetensors\", \"note\": \"\"}, {\"name\": \"qwen_image_2.1_vae_bf16.safetensors\", \"dir\": \"vae\", \"size\": \"676 MB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/vae/qwen_image_2.1_vae_bf16.safetensors\", \"note\": \"\"}, {\"name\": \"sam3.1_multiplex_fp16.safetensors\", \"dir\": \"checkpoints\", \"size\": \"1.75 GB\", \"url\": \"https://huggingface.co/Comfy-Org/sam3.1/resolve/main/checkpoints/sam3.1_multiplex_fp16.safetensors\", \"note\": \"by Meta, packaged by Comfy-Org\"}, {\"name\": \"Qwen-Image-2.1-viggle-turbo-v0.3-6step-lora-r128.safetensors\", \"dir\": \"loras\", \"size\": \"680 MB\", \"url\": \"https://huggingface.co/Viggle/Qwen-Image-2.1-viggle-turbo/resolve/main/Qwen-Image-2.1-viggle-turbo-v0.3-6step-lora-r128.safetensors\", \"note\": \"optional, for Fast · Qwen Research License, research use\"}], \"packs\": [{\"name\": \"ComfyUI-AusBoss\", \"url\": \"https://github.com/ausboss/ComfyUI-AusBoss\", \"node\": \"AUSBOSS_NODES_MaskByTouch\"}], \"links\": [{\"label\": \"YouTube · this workflow\", \"url\": \"https://youtu.be/iMgaiXoB0v4\"}, {\"label\": \"GitHub · ausboss\", \"url\": \"https://github.com/ausboss\"}, {\"label\": \"Civitai · AusBoss\", \"url\": \"https://civitai.com/user/AusBoss\"}, {\"label\": \"X · Zanzibased\", \"url\": \"https://x.com/Zanzibased\"}]}"
|
||||
"{\"v\": 1, \"title\": \"Qwen Image 2.1 Inpaint\", \"subtitle\": \"Click a thing in your picture and say what to change. Only that part is repainted.\", \"author\": \"AusBoss\", \"layout\": \"card\", \"accent\": \"\", \"body\": \"1. Load your image. You can crop it right there with the blue handles.\\n2. On **Mask by Touch**, click the thing you want to change. It lights up before you click.\\n3. In **What to change**, say it the way you would ask a person: \\\"Replace the cup with a glass of orange juice.\\\"\\n4. Press **Run**.\\n\\nOnly the picked part is repainted. Everything outside it stays your own picture.\\n\\n### Tips\\n- Wrong thing picked? The arrows under the picture swap it for the next thing it could mean.\\n- Name everything that should go: \\\"the iced coffee and its straw\\\". What you do not name can stay.\\n- To remove something, pick it and write \\\"Remove the cup.\\\" Pick its shadow too, or the shadow stays.\\n- To add something, switch to **Paint** and paint where it should go, with some room. Say how big: \\\"Add small black sunglasses on her eyes.\\\"\\n- Not what you wanted? Run it again. The seed changes each run.\\n\\n### Switches\\n- **Fast** on: 8 steps with the Viggle Turbo LoRA from the list below. Off: 25 steps without it, about twice as long.\\n\\nNeeds ComfyUI 0.38 or newer and AusBoss nodes 2.12.0 or newer (update first).\", \"models\": [{\"name\": \"qwen_image_2.1_int8_convrot.safetensors\", \"dir\": \"diffusion_models\", \"size\": \"7.26 GB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/diffusion_models/qwen_image_2.1_int8_convrot.safetensors\", \"note\": \"\"}, {\"name\": \"qwen3vl_8b_int8_convrot.safetensors\", \"dir\": \"text_encoders\", \"size\": \"9.35 GB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/text_encoders/qwen3vl_8b_int8_convrot.safetensors\", \"note\": \"\"}, {\"name\": \"qwen_image_2.1_vae_bf16.safetensors\", \"dir\": \"vae\", \"size\": \"676 MB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/vae/qwen_image_2.1_vae_bf16.safetensors\", \"note\": \"\"}, {\"name\": \"sam3.1_multiplex_fp16.safetensors\", \"dir\": \"checkpoints\", \"size\": \"1.75 GB\", \"url\": \"https://huggingface.co/Comfy-Org/sam3.1/resolve/main/checkpoints/sam3.1_multiplex_fp16.safetensors\", \"note\": \"by Meta, packaged by Comfy-Org\"}, {\"name\": \"Qwen-Image-2.1-viggle-turbo-v0.3-6step-lora-r128.safetensors\", \"dir\": \"loras\", \"size\": \"680 MB\", \"url\": \"https://huggingface.co/Viggle/Qwen-Image-2.1-viggle-turbo/resolve/main/Qwen-Image-2.1-viggle-turbo-v0.3-6step-lora-r128.safetensors\", \"note\": \"optional, for Fast · Qwen Research License, research use\"}], \"packs\": [{\"name\": \"ComfyUI-AusBoss\", \"url\": \"https://github.com/ausboss/ComfyUI-AusBoss\", \"node\": \"AUSBOSS_NODES_MaskByTouch\"}], \"links\": [{\"label\": \"YouTube · this workflow\", \"url\": \"https://youtu.be/iMgaiXoB0v4\"}, {\"label\": \"GitHub · ausboss\", \"url\": \"https://github.com/ausboss\"}, {\"label\": \"Civitai · AusBoss\", \"url\": \"https://civitai.com/user/AusBoss\"}, {\"label\": \"X · Zanzibased\", \"url\": \"https://x.com/Zanzibased\"}]}"
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"note": "{\"v\": 1, \"title\": \"Qwen Image 2.1 Inpaint\", \"subtitle\": \"Click a thing in your picture and say what to change. Only that part is repainted.\", \"author\": \"AusBoss\", \"layout\": \"card\", \"accent\": \"\", \"body\": \"1. Load your image. You can crop it right there with the blue handles.\\n2. On **Mask by Touch**, click the thing you want to change. It lights up before you click.\\n3. In **What to change**, say it the way you would ask a person: \\\"Replace the cup with a glass of orange juice.\\\"\\n4. Press **Run**.\\n\\nOnly the picked part is repainted. Everything outside it stays your own picture.\\n\\n### Tips\\n- Wrong thing picked? The arrows under the picture swap it for the next thing it could mean.\\n- Name everything that should go: \\\"the iced coffee and its straw\\\". What you do not name can stay.\\n- To remove something, pick it and write \\\"Remove the cup.\\\" Pick its shadow too, or the shadow stays.\\n- To add something, switch to **Paint** and paint where it should go, with some room. Say how big: \\\"Add small black sunglasses on her eyes.\\\"\\n- Not what you wanted? Change **Seed** and run it again. It stays fixed between runs.\\n\\n### Switches\\n- **Fast** on: 8 steps with the Viggle Turbo LoRA from the list below. Off: 25 steps without it, about twice as long.\\n\\nNeeds ComfyUI 0.38 or newer and AusBoss nodes 2.12.0 or newer (update first).\", \"models\": [{\"name\": \"qwen_image_2.1_int8_convrot.safetensors\", \"dir\": \"diffusion_models\", \"size\": \"7.26 GB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/diffusion_models/qwen_image_2.1_int8_convrot.safetensors\", \"note\": \"\"}, {\"name\": \"qwen3vl_8b_int8_convrot.safetensors\", \"dir\": \"text_encoders\", \"size\": \"9.35 GB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/text_encoders/qwen3vl_8b_int8_convrot.safetensors\", \"note\": \"\"}, {\"name\": \"qwen_image_2.1_vae_bf16.safetensors\", \"dir\": \"vae\", \"size\": \"676 MB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/vae/qwen_image_2.1_vae_bf16.safetensors\", \"note\": \"\"}, {\"name\": \"sam3.1_multiplex_fp16.safetensors\", \"dir\": \"checkpoints\", \"size\": \"1.75 GB\", \"url\": \"https://huggingface.co/Comfy-Org/sam3.1/resolve/main/checkpoints/sam3.1_multiplex_fp16.safetensors\", \"note\": \"by Meta, packaged by Comfy-Org\"}, {\"name\": \"Qwen-Image-2.1-viggle-turbo-v0.3-6step-lora-r128.safetensors\", \"dir\": \"loras\", \"size\": \"680 MB\", \"url\": \"https://huggingface.co/Viggle/Qwen-Image-2.1-viggle-turbo/resolve/main/Qwen-Image-2.1-viggle-turbo-v0.3-6step-lora-r128.safetensors\", \"note\": \"optional, for Fast · Qwen Research License, research use\"}], \"packs\": [{\"name\": \"ComfyUI-AusBoss\", \"url\": \"https://github.com/ausboss/ComfyUI-AusBoss\", \"node\": \"AUSBOSS_NODES_MaskByTouch\"}], \"links\": [{\"label\": \"YouTube · this workflow\", \"url\": \"https://youtu.be/iMgaiXoB0v4\"}, {\"label\": \"GitHub · ausboss\", \"url\": \"https://github.com/ausboss\"}, {\"label\": \"Civitai · AusBoss\", \"url\": \"https://civitai.com/user/AusBoss\"}, {\"label\": \"X · Zanzibased\", \"url\": \"https://x.com/Zanzibased\"}]}"
|
||||
"note": "{\"v\": 1, \"title\": \"Qwen Image 2.1 Inpaint\", \"subtitle\": \"Click a thing in your picture and say what to change. Only that part is repainted.\", \"author\": \"AusBoss\", \"layout\": \"card\", \"accent\": \"\", \"body\": \"1. Load your image. You can crop it right there with the blue handles.\\n2. On **Mask by Touch**, click the thing you want to change. It lights up before you click.\\n3. In **What to change**, say it the way you would ask a person: \\\"Replace the cup with a glass of orange juice.\\\"\\n4. Press **Run**.\\n\\nOnly the picked part is repainted. Everything outside it stays your own picture.\\n\\n### Tips\\n- Wrong thing picked? The arrows under the picture swap it for the next thing it could mean.\\n- Name everything that should go: \\\"the iced coffee and its straw\\\". What you do not name can stay.\\n- To remove something, pick it and write \\\"Remove the cup.\\\" Pick its shadow too, or the shadow stays.\\n- To add something, switch to **Paint** and paint where it should go, with some room. Say how big: \\\"Add small black sunglasses on her eyes.\\\"\\n- Not what you wanted? Run it again. The seed changes each run.\\n\\n### Switches\\n- **Fast** on: 8 steps with the Viggle Turbo LoRA from the list below. Off: 25 steps without it, about twice as long.\\n\\nNeeds ComfyUI 0.38 or newer and AusBoss nodes 2.12.0 or newer (update first).\", \"models\": [{\"name\": \"qwen_image_2.1_int8_convrot.safetensors\", \"dir\": \"diffusion_models\", \"size\": \"7.26 GB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/diffusion_models/qwen_image_2.1_int8_convrot.safetensors\", \"note\": \"\"}, {\"name\": \"qwen3vl_8b_int8_convrot.safetensors\", \"dir\": \"text_encoders\", \"size\": \"9.35 GB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/text_encoders/qwen3vl_8b_int8_convrot.safetensors\", \"note\": \"\"}, {\"name\": \"qwen_image_2.1_vae_bf16.safetensors\", \"dir\": \"vae\", \"size\": \"676 MB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/vae/qwen_image_2.1_vae_bf16.safetensors\", \"note\": \"\"}, {\"name\": \"sam3.1_multiplex_fp16.safetensors\", \"dir\": \"checkpoints\", \"size\": \"1.75 GB\", \"url\": \"https://huggingface.co/Comfy-Org/sam3.1/resolve/main/checkpoints/sam3.1_multiplex_fp16.safetensors\", \"note\": \"by Meta, packaged by Comfy-Org\"}, {\"name\": \"Qwen-Image-2.1-viggle-turbo-v0.3-6step-lora-r128.safetensors\", \"dir\": \"loras\", \"size\": \"680 MB\", \"url\": \"https://huggingface.co/Viggle/Qwen-Image-2.1-viggle-turbo/resolve/main/Qwen-Image-2.1-viggle-turbo-v0.3-6step-lora-r128.safetensors\", \"note\": \"optional, for Fast · Qwen Research License, research use\"}], \"packs\": [{\"name\": \"ComfyUI-AusBoss\", \"url\": \"https://github.com/ausboss/ComfyUI-AusBoss\", \"node\": \"AUSBOSS_NODES_MaskByTouch\"}], \"links\": [{\"label\": \"YouTube · this workflow\", \"url\": \"https://youtu.be/iMgaiXoB0v4\"}, {\"label\": \"GitHub · ausboss\", \"url\": \"https://github.com/ausboss\"}, {\"label\": \"Civitai · AusBoss\", \"url\": \"https://civitai.com/user/AusBoss\"}, {\"label\": \"X · Zanzibased\", \"url\": \"https://x.com/Zanzibased\"}]}"
|
||||
},
|
||||
"color": "#14424d",
|
||||
"bgcolor": "#161f21"
|
||||
|
||||
@@ -37,10 +37,10 @@
|
||||
"ver": "2.9.0"
|
||||
},
|
||||
"widgets_values": [
|
||||
"{\"v\": 1, \"title\": \"Qwen Image 2.1 Upscale + Restore\", \"subtitle\": \"Load a small, soft or worn picture. Qwen Image 2.1 redraws it sharp at the megapixels you set, in its own colors.\", \"author\": \"AusBoss\", \"layout\": \"card\", \"accent\": \"\", \"body\": \"[▶ AusBoss on YouTube](https://www.youtube.com/@ausbossdev) · videos on these nodes and workflows\\n\\n---\\n\\n1. Load your image. You can crop it right there with the blue handles.\\n2. Set **Megapixels**: the size of the result.\\n3. Press **Run**.\\n4. Slide **Before and after** to compare. The result is saved as a PNG.\\n\\n### What you get\\n\\n- Your picture redrawn sharp, at the size you asked for.\\n- Its own colors, also on a noisy or faded photo.\\n\\n### Megapixels\\n\\n- Up to about 2: one pass.\\n- Over that: redrawn in tiles of about 2 megapixels and joined. 4 takes two tiles, 8 takes four.\\n- The redraw limit for a small picture is 8 times its own megapixels or one roughly 2 megapixel tile, whichever is larger. The rest is enlarged the plain way.\\n- A picture of 1 megapixel or more only looks better when it grows about 1.6 times per side.\\n\\n### Switches\\n\\n- **Fast** on: 8 steps with the Viggle Turbo LoRA. Off: 25 steps without it, about three times as long.\\n\\n### Tips\\n\\n- It is a redraw. Fine detail is made up to fit, so a face stays the same person, not the same pixels.\\n- Small lettering on signs and labels can come back misspelled.\\n- Each tile is matched to your picture's colors. To let Qwen's own colors through, lower **Keep colors** inside the box.\\n- If the run stops at a red **LoRA Loader**, a LoRA that is switched on is missing. Download it from the list below.\\n- Not tested on blur from a moving camera or missed focus.\\n\\nNeeds ComfyUI 0.38 or newer and AusBoss nodes 2.9.0 or newer (update first).\", \"models\": [{\"name\": \"qwen_image_2.1_int8_convrot.safetensors\", \"dir\": \"diffusion_models\", \"size\": \"7.26 GB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/diffusion_models/qwen_image_2.1_int8_convrot.safetensors\", \"note\": \"\"}, {\"name\": \"qwen3vl_8b_int8_convrot.safetensors\", \"dir\": \"text_encoders\", \"size\": \"9.35 GB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/text_encoders/qwen3vl_8b_int8_convrot.safetensors\", \"note\": \"\"}, {\"name\": \"qwen_image_2.1_vae_bf16.safetensors\", \"dir\": \"vae\", \"size\": \"676 MB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/vae/qwen_image_2.1_vae_bf16.safetensors\", \"note\": \"\"}, {\"name\": \"qwen-image-2.1-restore.safetensors\", \"dir\": \"loras\", \"size\": \"159 MB\", \"url\": \"https://huggingface.co/ausboss/Qwen-Image-2.1-Restore-LoRA/resolve/main/qwen-image-2.1-restore.safetensors\", \"note\": \"keeps the result close to your picture\"}, {\"name\": \"Qwen-Image-2.1-viggle-turbo-v0.3-6step-lora-r128.safetensors\", \"dir\": \"loras\", \"size\": \"680 MB\", \"url\": \"https://huggingface.co/Viggle/Qwen-Image-2.1-viggle-turbo/resolve/main/Qwen-Image-2.1-viggle-turbo-v0.3-6step-lora-r128.safetensors\", \"note\": \"for Fast on · Qwen Research License, research use\"}], \"packs\": [{\"name\": \"ComfyUI-AusBoss\", \"url\": \"https://github.com/ausboss/ComfyUI-AusBoss\", \"node\": \"AUSBOSS_NODES_TiledUpscale\"}], \"links\": [{\"label\": \"YouTube · ausbossdev\", \"url\": \"https://www.youtube.com/@ausbossdev\"}, {\"label\": \"GitHub · ausboss\", \"url\": \"https://github.com/ausboss\"}, {\"label\": \"Civitai · AusBoss\", \"url\": \"https://civitai.com/user/AusBoss\"}, {\"label\": \"X · Zanzibased\", \"url\": \"https://x.com/Zanzibased\"}]}"
|
||||
"{\"v\": 1, \"title\": \"Qwen Image 2.1 Upscale + Restore\", \"subtitle\": \"Load a small, soft or worn picture. Qwen Image 2.1 redraws it sharp at the megapixels you set, in its own colors.\", \"author\": \"AusBoss\", \"layout\": \"card\", \"accent\": \"\", \"body\": \"[▶ AusBoss on YouTube](https://www.youtube.com/@ausbossdev) · videos on these nodes and workflows\\n\\n---\\n\\n1. Load your image. You can crop it right there with the blue handles.\\n2. Set **Megapixels**: the size of the result.\\n3. Press **Run**.\\n4. Slide **Before and after** to compare. The result is saved as a PNG.\\n\\n### What you get\\n\\n- Your picture redrawn sharp, at the size you asked for.\\n- Its own colors, also on a noisy or faded photo.\\n\\n### Megapixels\\n\\n- Up to about 2: one pass.\\n- Over that: redrawn in tiles of about 2 megapixels and joined. 4 takes two tiles, 8 takes four.\\n- A small picture is redrawn at up to 8 times its own megapixels, then enlarged the plain way.\\n- A picture of 1 megapixel or more only looks better when it grows about 1.6 times per side.\\n\\n### Switches\\n\\n- **Fast** on: 8 steps with the Viggle Turbo LoRA. Off: 25 steps without it, about three times as long.\\n\\n### Tips\\n\\n- It is a redraw. Fine detail is made up to fit, so a face stays the same person, not the same pixels.\\n- Small lettering on signs and labels can come back misspelled.\\n- Each tile is matched to your picture's colors. To let Qwen's own colors through, lower **Keep colors** inside the box.\\n- If the run stops at a red **LoRA Loader**, a LoRA that is switched on is missing. Download it from the list below.\\n- Not tested on blur from a moving camera or missed focus.\\n\\nNeeds ComfyUI 0.38 or newer and AusBoss nodes 2.9.0 or newer (update first).\", \"models\": [{\"name\": \"qwen_image_2.1_int8_convrot.safetensors\", \"dir\": \"diffusion_models\", \"size\": \"7.26 GB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/diffusion_models/qwen_image_2.1_int8_convrot.safetensors\", \"note\": \"\"}, {\"name\": \"qwen3vl_8b_int8_convrot.safetensors\", \"dir\": \"text_encoders\", \"size\": \"9.35 GB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/text_encoders/qwen3vl_8b_int8_convrot.safetensors\", \"note\": \"\"}, {\"name\": \"qwen_image_2.1_vae_bf16.safetensors\", \"dir\": \"vae\", \"size\": \"676 MB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/vae/qwen_image_2.1_vae_bf16.safetensors\", \"note\": \"\"}, {\"name\": \"qwen-image-2.1-restore.safetensors\", \"dir\": \"loras\", \"size\": \"159 MB\", \"url\": \"https://huggingface.co/ausboss/Qwen-Image-2.1-Restore-LoRA/resolve/main/qwen-image-2.1-restore.safetensors\", \"note\": \"keeps the result close to your picture\"}, {\"name\": \"Qwen-Image-2.1-viggle-turbo-v0.3-6step-lora-r128.safetensors\", \"dir\": \"loras\", \"size\": \"680 MB\", \"url\": \"https://huggingface.co/Viggle/Qwen-Image-2.1-viggle-turbo/resolve/main/Qwen-Image-2.1-viggle-turbo-v0.3-6step-lora-r128.safetensors\", \"note\": \"for Fast on · Qwen Research License, research use\"}], \"packs\": [{\"name\": \"ComfyUI-AusBoss\", \"url\": \"https://github.com/ausboss/ComfyUI-AusBoss\", \"node\": \"AUSBOSS_NODES_TiledUpscale\"}], \"links\": [{\"label\": \"YouTube · ausbossdev\", \"url\": \"https://www.youtube.com/@ausbossdev\"}, {\"label\": \"GitHub · ausboss\", \"url\": \"https://github.com/ausboss\"}, {\"label\": \"Civitai · AusBoss\", \"url\": \"https://civitai.com/user/AusBoss\"}, {\"label\": \"X · Zanzibased\", \"url\": \"https://x.com/Zanzibased\"}]}"
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"note": "{\"v\": 1, \"title\": \"Qwen Image 2.1 Upscale + Restore\", \"subtitle\": \"Load a small, soft or worn picture. Qwen Image 2.1 redraws it sharp at the megapixels you set, in its own colors.\", \"author\": \"AusBoss\", \"layout\": \"card\", \"accent\": \"\", \"body\": \"[▶ AusBoss on YouTube](https://www.youtube.com/@ausbossdev) · videos on these nodes and workflows\\n\\n---\\n\\n1. Load your image. You can crop it right there with the blue handles.\\n2. Set **Megapixels**: the size of the result.\\n3. Press **Run**.\\n4. Slide **Before and after** to compare. The result is saved as a PNG.\\n\\n### What you get\\n\\n- Your picture redrawn sharp, at the size you asked for.\\n- Its own colors, also on a noisy or faded photo.\\n\\n### Megapixels\\n\\n- Up to about 2: one pass.\\n- Over that: redrawn in tiles of about 2 megapixels and joined. 4 takes two tiles, 8 takes four.\\n- The redraw limit for a small picture is 8 times its own megapixels or one roughly 2 megapixel tile, whichever is larger. The rest is enlarged the plain way.\\n- A picture of 1 megapixel or more only looks better when it grows about 1.6 times per side.\\n\\n### Switches\\n\\n- **Fast** on: 8 steps with the Viggle Turbo LoRA. Off: 25 steps without it, about three times as long.\\n\\n### Tips\\n\\n- It is a redraw. Fine detail is made up to fit, so a face stays the same person, not the same pixels.\\n- Small lettering on signs and labels can come back misspelled.\\n- Each tile is matched to your picture's colors. To let Qwen's own colors through, lower **Keep colors** inside the box.\\n- If the run stops at a red **LoRA Loader**, a LoRA that is switched on is missing. Download it from the list below.\\n- Not tested on blur from a moving camera or missed focus.\\n\\nNeeds ComfyUI 0.38 or newer and AusBoss nodes 2.9.0 or newer (update first).\", \"models\": [{\"name\": \"qwen_image_2.1_int8_convrot.safetensors\", \"dir\": \"diffusion_models\", \"size\": \"7.26 GB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/diffusion_models/qwen_image_2.1_int8_convrot.safetensors\", \"note\": \"\"}, {\"name\": \"qwen3vl_8b_int8_convrot.safetensors\", \"dir\": \"text_encoders\", \"size\": \"9.35 GB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/text_encoders/qwen3vl_8b_int8_convrot.safetensors\", \"note\": \"\"}, {\"name\": \"qwen_image_2.1_vae_bf16.safetensors\", \"dir\": \"vae\", \"size\": \"676 MB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/vae/qwen_image_2.1_vae_bf16.safetensors\", \"note\": \"\"}, {\"name\": \"qwen-image-2.1-restore.safetensors\", \"dir\": \"loras\", \"size\": \"159 MB\", \"url\": \"https://huggingface.co/ausboss/Qwen-Image-2.1-Restore-LoRA/resolve/main/qwen-image-2.1-restore.safetensors\", \"note\": \"keeps the result close to your picture\"}, {\"name\": \"Qwen-Image-2.1-viggle-turbo-v0.3-6step-lora-r128.safetensors\", \"dir\": \"loras\", \"size\": \"680 MB\", \"url\": \"https://huggingface.co/Viggle/Qwen-Image-2.1-viggle-turbo/resolve/main/Qwen-Image-2.1-viggle-turbo-v0.3-6step-lora-r128.safetensors\", \"note\": \"for Fast on · Qwen Research License, research use\"}], \"packs\": [{\"name\": \"ComfyUI-AusBoss\", \"url\": \"https://github.com/ausboss/ComfyUI-AusBoss\", \"node\": \"AUSBOSS_NODES_TiledUpscale\"}], \"links\": [{\"label\": \"YouTube · ausbossdev\", \"url\": \"https://www.youtube.com/@ausbossdev\"}, {\"label\": \"GitHub · ausboss\", \"url\": \"https://github.com/ausboss\"}, {\"label\": \"Civitai · AusBoss\", \"url\": \"https://civitai.com/user/AusBoss\"}, {\"label\": \"X · Zanzibased\", \"url\": \"https://x.com/Zanzibased\"}]}"
|
||||
"note": "{\"v\": 1, \"title\": \"Qwen Image 2.1 Upscale + Restore\", \"subtitle\": \"Load a small, soft or worn picture. Qwen Image 2.1 redraws it sharp at the megapixels you set, in its own colors.\", \"author\": \"AusBoss\", \"layout\": \"card\", \"accent\": \"\", \"body\": \"[▶ AusBoss on YouTube](https://www.youtube.com/@ausbossdev) · videos on these nodes and workflows\\n\\n---\\n\\n1. Load your image. You can crop it right there with the blue handles.\\n2. Set **Megapixels**: the size of the result.\\n3. Press **Run**.\\n4. Slide **Before and after** to compare. The result is saved as a PNG.\\n\\n### What you get\\n\\n- Your picture redrawn sharp, at the size you asked for.\\n- Its own colors, also on a noisy or faded photo.\\n\\n### Megapixels\\n\\n- Up to about 2: one pass.\\n- Over that: redrawn in tiles of about 2 megapixels and joined. 4 takes two tiles, 8 takes four.\\n- A small picture is redrawn at up to 8 times its own megapixels, then enlarged the plain way.\\n- A picture of 1 megapixel or more only looks better when it grows about 1.6 times per side.\\n\\n### Switches\\n\\n- **Fast** on: 8 steps with the Viggle Turbo LoRA. Off: 25 steps without it, about three times as long.\\n\\n### Tips\\n\\n- It is a redraw. Fine detail is made up to fit, so a face stays the same person, not the same pixels.\\n- Small lettering on signs and labels can come back misspelled.\\n- Each tile is matched to your picture's colors. To let Qwen's own colors through, lower **Keep colors** inside the box.\\n- If the run stops at a red **LoRA Loader**, a LoRA that is switched on is missing. Download it from the list below.\\n- Not tested on blur from a moving camera or missed focus.\\n\\nNeeds ComfyUI 0.38 or newer and AusBoss nodes 2.9.0 or newer (update first).\", \"models\": [{\"name\": \"qwen_image_2.1_int8_convrot.safetensors\", \"dir\": \"diffusion_models\", \"size\": \"7.26 GB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/diffusion_models/qwen_image_2.1_int8_convrot.safetensors\", \"note\": \"\"}, {\"name\": \"qwen3vl_8b_int8_convrot.safetensors\", \"dir\": \"text_encoders\", \"size\": \"9.35 GB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/text_encoders/qwen3vl_8b_int8_convrot.safetensors\", \"note\": \"\"}, {\"name\": \"qwen_image_2.1_vae_bf16.safetensors\", \"dir\": \"vae\", \"size\": \"676 MB\", \"url\": \"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/vae/qwen_image_2.1_vae_bf16.safetensors\", \"note\": \"\"}, {\"name\": \"qwen-image-2.1-restore.safetensors\", \"dir\": \"loras\", \"size\": \"159 MB\", \"url\": \"https://huggingface.co/ausboss/Qwen-Image-2.1-Restore-LoRA/resolve/main/qwen-image-2.1-restore.safetensors\", \"note\": \"keeps the result close to your picture\"}, {\"name\": \"Qwen-Image-2.1-viggle-turbo-v0.3-6step-lora-r128.safetensors\", \"dir\": \"loras\", \"size\": \"680 MB\", \"url\": \"https://huggingface.co/Viggle/Qwen-Image-2.1-viggle-turbo/resolve/main/Qwen-Image-2.1-viggle-turbo-v0.3-6step-lora-r128.safetensors\", \"note\": \"for Fast on · Qwen Research License, research use\"}], \"packs\": [{\"name\": \"ComfyUI-AusBoss\", \"url\": \"https://github.com/ausboss/ComfyUI-AusBoss\", \"node\": \"AUSBOSS_NODES_TiledUpscale\"}], \"links\": [{\"label\": \"YouTube · ausbossdev\", \"url\": \"https://www.youtube.com/@ausbossdev\"}, {\"label\": \"GitHub · ausboss\", \"url\": \"https://github.com/ausboss\"}, {\"label\": \"Civitai · AusBoss\", \"url\": \"https://civitai.com/user/AusBoss\"}, {\"label\": \"X · Zanzibased\", \"url\": \"https://x.com/Zanzibased\"}]}"
|
||||
},
|
||||
"color": "#14424d",
|
||||
"bgcolor": "#161f21"
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
// App mode for nodes with cards: the simple form view shows a real control
|
||||
// for each field instead of an empty row. The logic is in
|
||||
// js/shared/app_mode.mjs; this file watches which mode the open workflow is
|
||||
// in and hands the fields over.
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { createAppModeSync, workflowMode } from "../shared/app_mode.mjs";
|
||||
|
||||
const sync = createAppModeSync({
|
||||
find(nodeId, name) {
|
||||
const graph = app.rootGraph ?? app.graph;
|
||||
const node = graph?.getNodeById?.(/^\d+$/.test(nodeId) ? Number(nodeId) : nodeId);
|
||||
const widget = node?.widgets?.find((entry) => entry.name === name);
|
||||
return widget ? { node, widget } : null;
|
||||
},
|
||||
changed(node) {
|
||||
node.setDirtyCanvas?.(true, true);
|
||||
},
|
||||
});
|
||||
|
||||
let queued = false;
|
||||
// After the current task: a card hides its widgets in a microtask once the
|
||||
// node has loaded, and the form's fields are shown after that.
|
||||
function schedule() {
|
||||
if (queued) return;
|
||||
queued = true;
|
||||
setTimeout(() => {
|
||||
queued = false;
|
||||
try {
|
||||
const workflow = app.extensionManager?.workflow?.activeWorkflow;
|
||||
sync(workflowMode(workflow), (app.rootGraph ?? app.graph)?.extra?.linearData);
|
||||
} catch (error) {
|
||||
console.warn("[AusBoss] App mode fields:", error);
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "ausboss.app.mode",
|
||||
setup() {
|
||||
app.extensionManager?.workflow?.$subscribe?.(schedule);
|
||||
},
|
||||
afterConfigureGraph() {
|
||||
schedule();
|
||||
},
|
||||
});
|
||||
+14
-28
@@ -23,7 +23,6 @@ import { openInfoCard } from "../shared/settings_menu.mjs";
|
||||
|
||||
const SETTING_ID = "AusBoss.Appearance.NodeColor";
|
||||
const CUSTOM_SETTING_ID = "AusBoss.Appearance.CustomColor";
|
||||
const COLOR_OVERRIDE = "ausbossColor";
|
||||
|
||||
// Stored bare (no "#") to match the color setting's storage contract.
|
||||
const DEFAULT_CUSTOM_COLOR = "00b4aa";
|
||||
@@ -41,7 +40,6 @@ let activeCustomColor = DEFAULT_CUSTOM_COLOR;
|
||||
let activeCustomTitle = normalizeHexColor(DEFAULT_CUSTOM_COLOR);
|
||||
|
||||
function setActiveCustomColor(value) {
|
||||
if (!normalizeHexColor(value)) return;
|
||||
activeCustomColor = value;
|
||||
activeCustomTitle = normalizeHexColor(value);
|
||||
}
|
||||
@@ -58,7 +56,6 @@ function applyScheme(node, colors) {
|
||||
function repaintAll(next, previous) {
|
||||
for (const node of collectGraphNodes(app.graph)) {
|
||||
if (!isAusbossNode(node)) continue;
|
||||
if (Object.hasOwn(node.properties ?? {}, COLOR_OVERRIDE)) continue;
|
||||
if (!shouldRecolor(node, previous)) continue;
|
||||
applyScheme(node, next);
|
||||
}
|
||||
@@ -152,8 +149,8 @@ app.registerExtension({
|
||||
},
|
||||
getNodeMenuItems(node) {
|
||||
if (!isAusbossNode(node)) return [];
|
||||
// Vue nodes skip the canvas badge callbacks; title-less nodes have no bar.
|
||||
const about = isTitleless(node) || globalThis.LiteGraph?.vueNodesMode === true
|
||||
// A title-less node has no bar for the "?" badge; its card opens here.
|
||||
const about = isTitleless(node)
|
||||
? [{ content: "About this node", callback: () => openHelpCard(node, null) }]
|
||||
: [];
|
||||
return [
|
||||
@@ -165,14 +162,12 @@ app.registerExtension({
|
||||
options: SCHEME_NAMES.map((name) => ({
|
||||
content: name,
|
||||
callback: () => {
|
||||
// Keep an explicit choice, including no colors, through saves
|
||||
// and setting changes. Custom stores the pair picked today.
|
||||
// A menu pick writes the colors directly; shouldRecolor then
|
||||
// treats them as the user's choice during setting sweeps.
|
||||
const colors = schemeColors(name, activeCustomColor);
|
||||
// Custom with an unusable stored color resolves to null, which
|
||||
// would wrongly read as "Theme default" — do nothing instead.
|
||||
if (name === CUSTOM_SCHEME && !colors) return;
|
||||
node.properties ??= {};
|
||||
node.properties[COLOR_OVERRIDE] = colors ? { ...colors } : null;
|
||||
applyScheme(node, colors);
|
||||
app.graph?.setDirtyCanvas?.(true, true);
|
||||
},
|
||||
@@ -184,26 +179,16 @@ app.registerExtension({
|
||||
nodeCreated(node) {
|
||||
if (!isAusbossNode(node)) return;
|
||||
installHelpBadge(node);
|
||||
restoreAppearance(node);
|
||||
// Construction precedes saved fields; reload, paste and undo restore
|
||||
// their colors and properties before this callback runs.
|
||||
chainCallback(node, "onConfigure", function (saved) {
|
||||
restoreAppearance(this, saved);
|
||||
});
|
||||
// Colors restored from a saved workflow (and manual picks) land before
|
||||
// this hook runs — an already-colored node is left alone, unless it
|
||||
// wears a retired flagship pair: those colors were ours, so the node
|
||||
// upgrades to the active scheme instead of keeping them forever.
|
||||
if ((node.color || node.bgcolor) && !wearsLegacyScheme(node)) return;
|
||||
const colors = schemeColors(activeScheme, activeCustomColor);
|
||||
if (colors) applyScheme(node, colors);
|
||||
},
|
||||
});
|
||||
|
||||
function restoreAppearance(node, saved) {
|
||||
if (Object.hasOwn(node.properties ?? {}, COLOR_OVERRIDE)) {
|
||||
// A later pick in ComfyUI's own color menu is saved in the native fields.
|
||||
if (saved?.color || saved?.bgcolor) return;
|
||||
applyScheme(node, node.properties[COLOR_OVERRIDE]);
|
||||
return;
|
||||
}
|
||||
if ((node.color || node.bgcolor) && !wearsLegacyScheme(node)) return;
|
||||
applyScheme(node, schemeColors(activeScheme, activeCustomColor));
|
||||
}
|
||||
|
||||
function isTitleless(node) {
|
||||
return (node.title_mode ?? node.constructor?.title_mode) === (globalThis.LiteGraph?.NO_TITLE ?? 1);
|
||||
}
|
||||
@@ -219,8 +204,9 @@ function openHelpCard(node, event) {
|
||||
});
|
||||
}
|
||||
|
||||
// Classic nodes get a quiet "?" in the title bar. Vue nodes open the same
|
||||
// card from their context menu. Its text comes from DESCRIPTION and tooltips.
|
||||
// Every AusBoss node gets a quiet "?" in the title bar; clicking it opens a
|
||||
// card built from the node's own DESCRIPTION and tooltips, so the docs on
|
||||
// screen are exactly the docs in the source.
|
||||
function installHelpBadge(node) {
|
||||
// A title-less node (Run Timer) has no bar to hang the badge on; its
|
||||
// card opens from the node's context menu instead.
|
||||
|
||||
+23
-115
@@ -13,12 +13,10 @@ import { BRAND, chainCallback, keepDomWidgetWidthAuto } from "../shared/index.mj
|
||||
import {
|
||||
ARROW_ANGLE,
|
||||
ARROW_CHOICES,
|
||||
CARD_TEMPLATE,
|
||||
DOUBLE_ARROWS,
|
||||
arrowText,
|
||||
fitFontSize,
|
||||
parseBlocks,
|
||||
parseCard,
|
||||
pastedLink,
|
||||
repointLinks,
|
||||
targetId,
|
||||
@@ -47,10 +45,6 @@ const LINK_TILES = {
|
||||
youtube: { label: "Watch Me on YouTube", url: "https://www.youtube.com/@ausbossdev" },
|
||||
discord: { label: "Join for Help or More Workflows", url: "https://discord.gg/RwVxY9Fuaj" },
|
||||
};
|
||||
// A new Info card opens at this size, which shows its starter text whole.
|
||||
const CARD_SIZE = [300, 230];
|
||||
// The card's text grows with the node like a note's, but a card stays a card.
|
||||
const CARD_FONT_MAX = 20;
|
||||
const FRAME_FILL = 0.8; // the share of the view a node brought into view takes, as in Workflow Switches
|
||||
const FONT = '"IBM Plex Sans", "Inter", "Segoe UI", system-ui, -apple-system, sans-serif';
|
||||
|
||||
@@ -87,20 +81,6 @@ ${TILE_FACE_CSS}
|
||||
.ausboss-callout-card[data-tile] .ausboss-callout-url svg{width:36px;height:28px;flex:none}
|
||||
.ausboss-callout-card[data-tile] .ausboss-callout-out{margin-left:auto}
|
||||
.ausboss-callout-card[data-tile] .ausboss-callout-tools{right:27px;}
|
||||
.ausboss-callout-card[data-card]{background:#111818;border:1px solid #2e3c3b;}
|
||||
.ausboss-callout-card[data-card] .ausboss-callout-inner{padding:.8em 1em;color:#d9e4e3;font-weight:400;line-height:1.45;}
|
||||
.ausboss-callout-card[data-card] b{color:#f2f7f6;font-weight:650;}
|
||||
.ausboss-card-block{margin:0 0 .85em;}
|
||||
.ausboss-card-block:last-child{margin-bottom:0;}
|
||||
.ausboss-card-block>*+*{margin-top:.3em;}
|
||||
.ausboss-card-title{display:flex;align-items:center;gap:.4em;color:#f2f7f6;font-size:1.08em;font-weight:650;}
|
||||
.ausboss-card-icon{flex:none;width:1em;height:1em;color:#c9d6d4;}
|
||||
.ausboss-card-icon svg{display:block;width:100%;height:100%;}
|
||||
.ausboss-card-row{display:flex;justify-content:space-between;align-items:baseline;gap:1em;}
|
||||
.ausboss-card-row>span:last-child{flex:none;text-align:right;white-space:nowrap;}
|
||||
.ausboss-card-row.is-mark,.ausboss-card-row.is-mark b{color:#6fe0d6;font-weight:500;}
|
||||
.ausboss-card-small,.ausboss-card-small b{color:#93a6a4;}
|
||||
.ausboss-card-small{font-size:.92em;}
|
||||
.ausboss-callout-empty{color:#6f8987;font-size:14px;font-weight:400;}
|
||||
.ausboss-callout-arrow{display:inline-block;width:1.2em;height:1.2em;margin:0 .1em;vertical-align:-.26em;filter:drop-shadow(0 0 .3em rgba(0,180,170,.55));}
|
||||
.ausboss-callout-arrow svg{display:block;width:100%;height:100%;overflow:visible;}
|
||||
@@ -174,25 +154,6 @@ function arrowIcon(kind) {
|
||||
return root;
|
||||
}
|
||||
|
||||
// The small line icons an Info card's title can start with.
|
||||
const CARD_ICON_PATHS = {
|
||||
clock: ["M12 7v5l3.2 2"],
|
||||
info: ["M12 11v6", "M12 7.6v.01"],
|
||||
warning: ["M12 3.5 2.8 19.5h18.4Z", "M12 10v4", "M12 16.9v.01"],
|
||||
tip: ["M9.5 18h5", "M10.5 21h3", "M12 3a6 6 0 0 0-3.6 10.8c.7.6 1.1 1.3 1.1 2.2h5c0-.9.4-1.6 1.1-2.2A6 6 0 0 0 12 3Z"],
|
||||
check: ["M8 12.4l2.8 2.8 5.2-5.6"],
|
||||
};
|
||||
const CARD_ICON_RING = new Set(["clock", "info", "check"]);
|
||||
|
||||
function cardIcon(kind) {
|
||||
const span = el("span", "ausboss-card-icon");
|
||||
const root = svg("svg", { viewBox: "0 0 24 24", "aria-hidden": "true", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round" });
|
||||
if (CARD_ICON_RING.has(kind)) root.append(svg("circle", { cx: 12, cy: 12, r: 9 }));
|
||||
for (const d of CARD_ICON_PATHS[kind] ?? []) root.append(svg("path", { d }));
|
||||
span.append(root);
|
||||
return span;
|
||||
}
|
||||
|
||||
// The node a link names, looked up in the graph the note sits in.
|
||||
function linkedNode(state, id) {
|
||||
const graph = state.node.graph ?? app.graph;
|
||||
@@ -301,79 +262,17 @@ function bringIntoView(target) {
|
||||
}
|
||||
}
|
||||
|
||||
// One line's pieces into an element. The pieces of one link sit in one
|
||||
// element; a link that leaves ComfyUI ends with a small ↗.
|
||||
function appendPieces(state, into, line) {
|
||||
let run = null;
|
||||
let wrap = null;
|
||||
const close = () => {
|
||||
if (wrap?.classList.contains("ausboss-callout-url")) wrap.append(el("span", "ausboss-callout-out", "↗"));
|
||||
};
|
||||
for (const piece of line) {
|
||||
if (piece.run !== run) {
|
||||
close();
|
||||
run = piece.run;
|
||||
wrap = run === undefined ? null : linkRun(state, piece);
|
||||
if (wrap) into.append(wrap);
|
||||
}
|
||||
const target = wrap ?? into;
|
||||
if (piece.arrow) target.append(arrowSpan(state, piece.arrow, piece));
|
||||
else target.append(piece.bold ? el("b", "", piece.text) : document.createTextNode(piece.text));
|
||||
}
|
||||
close();
|
||||
}
|
||||
|
||||
// An Info card: a title, rows of label and value, and small print.
|
||||
function renderCard(state, blocks) {
|
||||
for (const lines of blocks) {
|
||||
const block = el("div", "ausboss-card-block");
|
||||
for (const line of lines) {
|
||||
let row;
|
||||
if (line.kind === "title") {
|
||||
row = el("div", "ausboss-card-title");
|
||||
if (line.icon) row.append(cardIcon(line.icon));
|
||||
const words = el("span");
|
||||
appendPieces(state, words, line.pieces);
|
||||
row.append(words);
|
||||
} else if (line.kind === "row") {
|
||||
row = el("div", `ausboss-card-row${line.highlight ? " is-mark" : ""}`);
|
||||
for (const cell of line.cells) {
|
||||
const side = el("span");
|
||||
appendPieces(state, side, cell);
|
||||
row.append(side);
|
||||
}
|
||||
} else {
|
||||
row = el("div", "ausboss-card-text");
|
||||
appendPieces(state, row, line.pieces);
|
||||
}
|
||||
if (line.small) row.classList.add("ausboss-card-small");
|
||||
block.append(row);
|
||||
}
|
||||
state.inner.append(block);
|
||||
}
|
||||
}
|
||||
|
||||
function renderText(state) {
|
||||
const style = state.node.properties?.ausbossCalloutTile;
|
||||
if (["youtube","discord","title"].includes(style)) state.card.dataset.tile = style;
|
||||
else delete state.card.dataset.tile;
|
||||
// An Info card has no title bar, like a tile, but keeps the full editor
|
||||
// and saves as a plain Callout: an older pack shows its text as a note.
|
||||
if (style === "card") state.card.dataset.card = "";
|
||||
else delete state.card.dataset.card;
|
||||
const isCard = style === "card";
|
||||
setTileFace(state.node, state.root, Boolean(state.card.dataset.tile) || isCard, () => startEdit(state));
|
||||
const blocks = isCard ? parseCard(state.valueWidget.value) : parseBlocks(state.valueWidget.value);
|
||||
setTileFace(state.node, state.root, Boolean(state.card.dataset.tile), () => startEdit(state));
|
||||
const blocks = parseBlocks(state.valueWidget.value);
|
||||
state.inner.replaceChildren();
|
||||
state.empty = blocks.length === 0;
|
||||
if (state.empty) {
|
||||
state.inner.append(el("div", "ausboss-callout-empty", "Double-click to write a note"));
|
||||
}
|
||||
if (isCard) {
|
||||
renderCard(state, blocks);
|
||||
fit(state);
|
||||
return;
|
||||
}
|
||||
for (const lines of blocks) {
|
||||
const point = el("div", "ausboss-callout-point");
|
||||
lines.forEach((line, index) => {
|
||||
@@ -381,7 +280,21 @@ function renderText(state) {
|
||||
// lines are told apart by a break, as before; a block needs none.
|
||||
const into = line.small ? el("div", "ausboss-callout-small") : point;
|
||||
if (index && !line.small && !lines[index - 1].small) point.append(document.createElement("br"));
|
||||
appendPieces(state, into, line);
|
||||
let run = null;
|
||||
let wrap = null;
|
||||
for (const piece of line) {
|
||||
// The pieces of one link sit in one element.
|
||||
if (piece.run !== run) {
|
||||
if (wrap?.classList.contains("ausboss-callout-url")) wrap.append(el("span", "ausboss-callout-out", "↗"));
|
||||
run = piece.run;
|
||||
wrap = run === undefined ? null : linkRun(state, piece);
|
||||
if (wrap) into.append(wrap);
|
||||
}
|
||||
const target = wrap ?? into;
|
||||
if (piece.arrow) target.append(arrowSpan(state, piece.arrow, piece));
|
||||
else target.append(piece.bold ? el("b", "", piece.text) : document.createTextNode(piece.text));
|
||||
}
|
||||
if (wrap?.classList.contains("ausboss-callout-url")) wrap.append(el("span", "ausboss-callout-out", "↗"));
|
||||
if (line.small) point.append(into);
|
||||
});
|
||||
state.inner.append(point);
|
||||
@@ -451,7 +364,7 @@ function fit(state) {
|
||||
inner.style.fontSize = `${px}px`;
|
||||
return inner.offsetHeight <= height && inner.scrollWidth <= width + 1;
|
||||
};
|
||||
const size = fitFontSize(fits, undefined, card.dataset.card === undefined ? undefined : CARD_FONT_MAX);
|
||||
const size = fitFontSize(fits);
|
||||
const social = card.dataset.tile === "youtube" || card.dataset.tile === "discord";
|
||||
inner.style.fontSize = `${social ? Math.min(size, 16) : size}px`;
|
||||
}
|
||||
@@ -540,9 +453,7 @@ function startEdit(state) {
|
||||
const wrap = el("div", "ausboss-callout-editor");
|
||||
const area = el("textarea", "ausboss-callout-edit");
|
||||
area.value = state.valueWidget.value ?? "";
|
||||
area.placeholder = state.card.dataset.card === undefined
|
||||
? "One idea per paragraph. **Bold** a word to stress it. The buttons below add an arrow, make a line small or make words a link."
|
||||
: "The first line is the title. Write label | value for a row. **Bold** a whole row to make it teal. Small makes a line small print.";
|
||||
area.placeholder = "One idea per paragraph. **Bold** a word to stress it. The buttons below add an arrow, make a line small or make words a link.";
|
||||
area.spellcheck = true;
|
||||
const bar = el("div", "ausboss-callout-arrowbar");
|
||||
bar.append(el("span", "", "Arrow"));
|
||||
@@ -649,6 +560,7 @@ function startEdit(state) {
|
||||
if (event.target !== area) event.preventDefault();
|
||||
});
|
||||
wrap.addEventListener("pointerdown", (event) => event.stopPropagation());
|
||||
wrap.addEventListener("wheel", (event) => event.stopPropagation(), { passive: true });
|
||||
// Clicking another node on the canvas takes the keyboard from the text box.
|
||||
// That is how the link is picked, so the edit stays open then; a click on
|
||||
// empty canvas, or on the note itself, ends it.
|
||||
@@ -775,7 +687,7 @@ app.registerExtension({
|
||||
const state = buildPanel(this);
|
||||
if (!state) return;
|
||||
renderText(state);
|
||||
if ((state.card.dataset.tile || state.card.dataset.card !== undefined) && Number.isFinite(saved?.size?.[1])) {
|
||||
if (state.card.dataset.tile && Number.isFinite(saved?.size?.[1])) {
|
||||
this.setSize?.([this.size[0], saved.size[1]]);
|
||||
}
|
||||
});
|
||||
@@ -787,18 +699,14 @@ app.registerExtension({
|
||||
chainCallback(nodeType.prototype, "getExtraMenuOptions", function (_canvas, options) {
|
||||
const state = this.__ausbossCallout;
|
||||
if (!state || !Array.isArray(options)) return;
|
||||
for (const [style, label] of [["plain","Plain callout"],["card","Info card"],["title","Title tile"],["youtube","Set YouTube link tile"],["discord","Set Discord link tile"]]) {
|
||||
for (const [style, label] of [["plain","Plain callout"],["title","Title tile"],["youtube","Set YouTube link tile"],["discord","Set Discord link tile"]]) {
|
||||
options.unshift({ content: label, callback: () => {
|
||||
this.properties ??= {};
|
||||
this.properties.ausbossCalloutTile = style;
|
||||
const preset = LINK_TILES[style];
|
||||
if (preset) commitWidgetValue(this, state.valueWidget, `[${preset.label}](${preset.url})`, app.canvas);
|
||||
// An empty card starts with text that shows how one is written.
|
||||
const starter = style === "card" && !String(state.valueWidget.value ?? "").trim();
|
||||
if (starter) commitWidgetValue(this, state.valueWidget, CARD_TEMPLATE, app.canvas);
|
||||
renderText(state);
|
||||
if (starter) this.setSize?.([Math.max(this.size[0], CARD_SIZE[0]), CARD_SIZE[1]]);
|
||||
else if (style !== "plain" && style !== "card") this.setSize?.([this.size[0], style === "title" ? 86 : 78]);
|
||||
if (style !== "plain") this.setSize?.([this.size[0], style === "title" ? 86 : 78]);
|
||||
markChanged();
|
||||
}});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
// The settings brought up to a Camera Move box, as one compact card above
|
||||
// the shot: what people change per clip on top (size, seed), the model files
|
||||
// folded under "Models", since they are set once. A LoRA Loader's rows keep
|
||||
// their own panel, with its strength bars; the camera keys are the shot.
|
||||
//
|
||||
// A box row shares its options with the setting inside the box, and Nodes 2.0
|
||||
// reads "hidden" from there, so a row the card takes over is hidden inside the
|
||||
// box too in that renderer (the classic canvas still shows it). Its value is
|
||||
// set from the box either way.
|
||||
|
||||
import { mountWidgetCard } from "../shared/widget_card.mjs";
|
||||
import { boxRowInputs } from "../shared/lora_box.mjs";
|
||||
import { hideWidget } from "../shared/widget_visibility.mjs";
|
||||
|
||||
const STASH = "__ausbossVisibilityStash"; // widget_visibility.mjs: a row already hidden
|
||||
const MODEL_FILE = /\.(safetensors|sft|ckpt|pt|pth|bin|gguf|onnx)$/i;
|
||||
const SUFFIX = { megapixels: "MP" };
|
||||
const ROW_TYPES = new Set(["number", "slider", "combo", "toggle", "text"]);
|
||||
const isLoraLoader = (node) => node?.type === "AUSBOSS_NODES_LoraLoader" || node?.comfyClass === "AUSBOSS_NODES_LoraLoader";
|
||||
|
||||
const isModelRow = (widget) => {
|
||||
if (widget?.type !== "combo") return false;
|
||||
if (MODEL_FILE.test(String(widget.value ?? ""))) return true;
|
||||
const values = typeof widget.options?.values === "function" ? [] : widget.options?.values;
|
||||
return Array.isArray(values) && values.some((value) => MODEL_FILE.test(String(value)));
|
||||
};
|
||||
|
||||
function labelOf(box, widget) {
|
||||
const input = (box.inputs ?? []).find((slot) => slot?.widget?.name === widget.name);
|
||||
const text = String(input?.label || widget.label || widget.name).replace(/_/g, " ");
|
||||
return text.charAt(0).toUpperCase() + text.slice(1);
|
||||
}
|
||||
|
||||
// The rows a box's card shows: every setting brought up to it except `skip`
|
||||
// (the camera keys), a LoRA Loader's rows and anything with its own panel.
|
||||
export function boxCardRows(box, skip) {
|
||||
const loraRows = new Set(boxRowInputs(box, isLoraLoader).map((entry) => entry.name));
|
||||
const top = [], models = [];
|
||||
for (const widget of box.widgets ?? []) {
|
||||
if (!widget || widget === skip || widget.element || !ROW_TYPES.has(String(widget.type)) || loraRows.has(widget.name)) continue;
|
||||
if (widget[STASH] && !widget.__ausbossCameraCard) continue;
|
||||
const row = { widget: widget.name, label: labelOf(box, widget) };
|
||||
if (isModelRow(widget)) models.push({ ...row, kind: "select", group: "models" });
|
||||
else top.push(SUFFIX[innerName(box, widget)] ? { ...row, suffix: SUFFIX[innerName(box, widget)] } : row);
|
||||
}
|
||||
return models.length ? [...top, { group: "models", label: `Models · ${models.length} files` }, ...models] : top;
|
||||
}
|
||||
|
||||
// The name of the setting inside the box that a box row stands for.
|
||||
function innerName(box, widget) {
|
||||
const input = (box.subgraph?.inputs ?? []).find((slot) => slot?.name === widget.name);
|
||||
for (const id of input?.linkIds ?? []) {
|
||||
const link = box.subgraph.getLink?.(id) ?? box.subgraph.links?.get?.(id) ?? box.subgraph.links?.[id];
|
||||
const node = link && (box.subgraph.getNodeById?.(link.target_id));
|
||||
const name = node?.inputs?.[link.target_slot]?.widget?.name ?? node?.inputs?.[link.target_slot]?.name;
|
||||
if (name) return name;
|
||||
}
|
||||
return widget.name;
|
||||
}
|
||||
|
||||
// The frontend now and then makes a box's rows afresh (a new object under
|
||||
// the same name), so the card hides its rows again whenever it finds one
|
||||
// showing. Cheap: a handful of names.
|
||||
export function rehideBoxCard(box) {
|
||||
let changed = false;
|
||||
for (const name of box.__ausbossCameraCardRows ?? []) {
|
||||
const widget = (box.widgets ?? []).find((w) => w?.name === name);
|
||||
if (!widget || widget[STASH]) continue;
|
||||
hideWidget(widget);
|
||||
widget.__ausbossCameraCard = true;
|
||||
changed = true;
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
// Mount the card once per box. Settings brought up later show as plain rows.
|
||||
// `tidy` puts the box's panels back in order and says whether it moved one.
|
||||
export function mountBoxCard(box, skip, tidy) {
|
||||
if (box.__ausbossCameraCard) { rehideBoxCard(box); return false; }
|
||||
const rows = boxCardRows(box, skip);
|
||||
if (!rows.length) return false;
|
||||
box.__ausbossCameraCardRows = rows.filter((row) => row.widget).map((row) => row.widget);
|
||||
rehideBoxCard(box);
|
||||
mountWidgetCard(box, { rows, minWidth: 300, first: true });
|
||||
box.__ausbossCameraCard = true;
|
||||
const draw = box.onDrawForeground;
|
||||
box.onDrawForeground = function (...args) {
|
||||
if (rehideBoxCard(this) | Boolean(tidy?.(this))) this.setDirtyCanvas?.(true, true);
|
||||
return draw?.apply(this, args);
|
||||
};
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
// Camera Move: the camera maths the face shares with the node.
|
||||
//
|
||||
// The same keys, pose and easing as nodes/_camera_move_helpers.py, so the
|
||||
// picture on the node is the shot the warp makes. No DOM and no app import:
|
||||
// tests/camera_move.test.mjs runs it under node:test.
|
||||
//
|
||||
// Axes are OpenCV's: x right, y down, z into the picture. A key is
|
||||
// { t, az, el, back, px, py }: t from 0 to 1 over the clip, turn and rise in
|
||||
// degrees, back and the pan in distances to the pivot.
|
||||
|
||||
export const LIM = { az: [-90, 90], el: [-30, 60], back: [-0.6, 2], px: [-1, 1], py: [-1, 1] };
|
||||
export const K0 = { az: 0, el: 0, back: 0, px: 0, py: 0 };
|
||||
export const FIELDS = Object.keys(K0);
|
||||
// Two keys this close on the clip are the same key.
|
||||
export const SAME_KEY = 0.015;
|
||||
export const MAX_KEYS = 64;
|
||||
export const LORA_RANGE = { az: 45, up: 30, down: -20 };
|
||||
export const DEFAULT_KEYS = [{ t: 0, ...K0 }, { t: 1, ...K0, az: 30, el: 5 }];
|
||||
|
||||
export const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
|
||||
const num = (v, fallback = 0) => {
|
||||
const n = Number(v);
|
||||
return Number.isFinite(n) ? n : fallback;
|
||||
};
|
||||
|
||||
export function cleanKey(raw) {
|
||||
const key = { t: clamp(num(raw?.t), 0, 1) };
|
||||
for (const name of FIELDS) key[name] = clamp(num(raw?.[name]), ...LIM[name]);
|
||||
return key;
|
||||
}
|
||||
|
||||
// The camera a node holds: { keys, pivot }. Unreadable text gives the default move.
|
||||
export function parseCamera(text) {
|
||||
let data = null;
|
||||
if (text && typeof text === "object") data = text;
|
||||
else if (typeof text === "string" && text.trim()) {
|
||||
try { data = JSON.parse(text); } catch { data = null; }
|
||||
}
|
||||
const fallback = !data || !Array.isArray(data.keys) || !data.keys.length;
|
||||
if (fallback) data = { keys: DEFAULT_KEYS, pivot: null };
|
||||
const keys = [];
|
||||
for (const raw of data.keys.slice(0, MAX_KEYS)) {
|
||||
const key = cleanKey(raw);
|
||||
const same = keys.find((k) => Math.abs(k.t - key.t) < SAME_KEY);
|
||||
if (same) Object.assign(same, key);
|
||||
else keys.push(key);
|
||||
}
|
||||
keys.sort((a, b) => a.t - b.t);
|
||||
const p = data.pivot;
|
||||
const pivot = p && typeof p === "object" && "u" in p && "v" in p
|
||||
? { u: clamp(num(p.u, 0.5), 0, 1), v: clamp(num(p.v, 0.5), 0, 1), t: clamp(num(p.t), 0, 1) }
|
||||
: null;
|
||||
return { keys, pivot, fallback };
|
||||
}
|
||||
|
||||
const round = (v, places) => Math.round(v * 10 ** places) / 10 ** places;
|
||||
|
||||
export function cameraText({ keys, pivot }) {
|
||||
const out = {
|
||||
v: 1,
|
||||
keys: keys.map((k) => ({ t: round(k.t, 4), az: round(k.az, 2), el: round(k.el, 2), back: round(k.back, 3), px: round(k.px, 3), py: round(k.py, 3) })),
|
||||
pivot: pivot ? { u: round(pivot.u, 4), v: round(pivot.v, 4), t: round(pivot.t, 4) } : null,
|
||||
};
|
||||
return JSON.stringify(out);
|
||||
}
|
||||
|
||||
// How fast one field moves as it passes each key: zero at the first and last
|
||||
// key (a gentle start and end) and where the field turns back or holds (it
|
||||
// never runs past a key); elsewhere it keeps its speed through the key, so a
|
||||
// move made of several keys does not slow down at each one.
|
||||
function keySlopes(ts, ys) {
|
||||
const n = ys.length, m = new Array(n).fill(0);
|
||||
for (let k = 1; k < n - 1; k++) {
|
||||
const h0 = ts[k] - ts[k - 1], h1 = ts[k + 1] - ts[k];
|
||||
if (h0 <= 0 || h1 <= 0) continue;
|
||||
const d0 = (ys[k] - ys[k - 1]) / h0, d1 = (ys[k + 1] - ys[k]) / h1;
|
||||
if (d0 * d1 > 0) m[k] = 3 * (h0 + h1) / ((2 * h1 + h0) / d0 + (h1 + 2 * h0) / d1);
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
// Where the camera is at moment t: through every key, gently at the ends.
|
||||
// Same maths as camera_at in nodes/_camera_move_helpers.py.
|
||||
export function camAt(keys, t) {
|
||||
if (!keys.length) return { ...K0 };
|
||||
const n = keys.length;
|
||||
const pick = (k) => { const o = {}; for (const f of FIELDS) o[f] = k[f] || 0; return o; };
|
||||
if (n === 1 || t <= keys[0].t) return pick(keys[0]);
|
||||
if (t >= keys[n - 1].t) return pick(keys[n - 1]);
|
||||
const ts = keys.map((k) => k.t);
|
||||
for (let i = 0; i < n - 1; i++) {
|
||||
const a = keys[i], b = keys[i + 1];
|
||||
if (t >= a.t && t <= b.t) {
|
||||
const h = Math.max(1e-6, b.t - a.t), s = (t - a.t) / h;
|
||||
const h00 = 2 * s ** 3 - 3 * s ** 2 + 1, h10 = s ** 3 - 2 * s ** 2 + s, h01 = -2 * s ** 3 + 3 * s ** 2, h11 = s ** 3 - s ** 2;
|
||||
const o = {};
|
||||
for (const f of FIELDS) {
|
||||
const m = keySlopes(ts, keys.map((k) => k[f] || 0));
|
||||
o[f] = h00 * (a[f] || 0) + h10 * h * m[i] + h01 * (b[f] || 0) + h11 * h * m[i + 1];
|
||||
}
|
||||
return o;
|
||||
}
|
||||
}
|
||||
return pick(keys[n - 1]);
|
||||
}
|
||||
|
||||
export const keyAt = (keys, t) => keys.findIndex((k) => Math.abs(k.t - t) < SAME_KEY);
|
||||
|
||||
// Moving the camera at the time bar sets the key there, or adds one.
|
||||
export function setKeyAt(keys, t, cam) {
|
||||
const c = {};
|
||||
for (const f of FIELDS) c[f] = clamp(num(cam[f]), ...LIM[f]);
|
||||
const i = keyAt(keys, t);
|
||||
if (i >= 0) { Object.assign(keys[i], c); return keys; }
|
||||
if (keys.length >= MAX_KEYS) return keys;
|
||||
keys.push({ t: clamp(t, 0, 1), ...c });
|
||||
keys.sort((a, b) => a.t - b.t);
|
||||
return keys;
|
||||
}
|
||||
|
||||
export const pastLoraRange = (c) => Math.abs(c.az) > LORA_RANGE.az || c.el > LORA_RANGE.up || c.el < LORA_RANGE.down;
|
||||
|
||||
// R = Ry(-az) Rx(-el), row-major.
|
||||
export function rot(az, el) {
|
||||
const th = -az * Math.PI / 180, ph = -el * Math.PI / 180;
|
||||
const ct = Math.cos(th), st = Math.sin(th), cp = Math.cos(ph), sp = Math.sin(ph);
|
||||
return [ct, st * sp, st * cp, 0, cp, -sp, -st, ct * sp, ct * cp];
|
||||
}
|
||||
export const mv = (R, v) => [R[0] * v[0] + R[1] * v[1] + R[2] * v[2], R[3] * v[0] + R[4] * v[1] + R[5] * v[2], R[6] * v[0] + R[7] * v[1] + R[8] * v[2]];
|
||||
|
||||
// The moved camera's rotation R and centre C. Pan slides the camera in its own frame.
|
||||
export function pose(cam, pivot) {
|
||||
const R = rot(cam.az, cam.el), p = pivot, Rp = mv(R, p), d = Math.hypot(p[0], p[1], p[2]);
|
||||
const b = mv(R, [(cam.px || 0) * d, (cam.py || 0) * d, -(cam.back || 0) * d]);
|
||||
return { R, C: [p[0] - Rp[0] + b[0], p[1] - Rp[1] + b[1], p[2] - Rp[2] + b[2]] };
|
||||
}
|
||||
|
||||
// A world point in the moved camera: R^T (P - C).
|
||||
export function toCam(R, C, P) {
|
||||
const d = [P[0] - C[0], P[1] - C[1], P[2] - C[2]];
|
||||
return [R[0] * d[0] + R[3] * d[1] + R[6] * d[2], R[1] * d[0] + R[4] * d[1] + R[7] * d[2], R[2] * d[0] + R[5] * d[1] + R[8] * d[2]];
|
||||
}
|
||||
|
||||
// The node's depth picture: red is the high byte, green the low one, on a log
|
||||
// scale from zmin to zmax; 0 is no depth (sky), which sits at `far`.
|
||||
export function unpackDepth(rgba, count, zmin, zmax, far) {
|
||||
const z = new Float32Array(count), valid = new Uint8Array(count);
|
||||
const lmin = Math.log(zmin), lr = Math.log(zmax) - lmin;
|
||||
for (let i = 0; i < count; i++) {
|
||||
const q = rgba[i * 4] * 256 + rgba[i * 4 + 1];
|
||||
if (q === 0) z[i] = far;
|
||||
else { z[i] = Math.exp(lmin + (q - 1) / 65534 * lr); valid[i] = 1; }
|
||||
}
|
||||
return { z, valid };
|
||||
}
|
||||
|
||||
// The 3D spot under a pixel of a frame: the middle of the nearest depth found
|
||||
// within three pixels, as the node does it. Null over sky.
|
||||
export function pivotFromPixel(frame, u, v) {
|
||||
const { W, H, z, valid, fx, fy, cx, cy } = frame;
|
||||
const x = clamp(Math.floor(u * W), 0, W - 1), y = clamp(Math.floor(v * H), 0, H - 1);
|
||||
for (let r = 0; r <= 3; r++) {
|
||||
const found = [];
|
||||
for (let yy = Math.max(0, y - r); yy <= Math.min(H - 1, y + r); yy++) {
|
||||
for (let xx = Math.max(0, x - r); xx <= Math.min(W - 1, x + r); xx++) if (valid[yy * W + xx]) found.push(z[yy * W + xx]);
|
||||
}
|
||||
if (found.length) {
|
||||
found.sort((a, b) => a - b);
|
||||
const depth = found.length % 2 ? found[found.length >> 1] : (found[found.length / 2 - 1] + found[found.length / 2]) / 2;
|
||||
return [(x + 0.5 - cx) / fx * depth, (y + 0.5 - cy) / fy * depth, depth];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Words for where the camera is.
|
||||
export function fmtAz(v) { const r = Math.round(v); return r === 0 ? "0°" : `${Math.abs(r)}° ${r > 0 ? "right" : "left"}`; }
|
||||
export function fmtEl(v) { const r = Math.round(v); return r === 0 ? "0°" : `${Math.abs(r)}° ${r > 0 ? "up" : "down"}`; }
|
||||
export function describe(c) {
|
||||
const part = (v, neg, pos) => (Math.abs(v) < 0.005 ? "" : `${Math.abs(v).toFixed(2)} ${v > 0 ? pos : neg}`);
|
||||
const pan = [part(c.px, "left", "right"), part(c.py, "up", "down")].filter(Boolean).join(", ");
|
||||
return `Turn ${fmtAz(c.az)} · Rise ${fmtEl(c.el)} · ${c.back < -0.004 ? "In" : "Back"} ${Math.abs(c.back).toFixed(2)}×${pan ? ` · Pan ${pan}` : ""}`;
|
||||
}
|
||||
@@ -0,0 +1,900 @@
|
||||
// Camera Move's face: the shot on the node, steered by grabbing it.
|
||||
//
|
||||
// Drag the picture to turn the camera round, pinch or scroll to pull back,
|
||||
// two fingers or Shift to pan, tap a spot to circle round it. Top right, as
|
||||
// in Blender: an axis ball, a magnifier, a hand, and a camera that puts you
|
||||
// back on your own shot. Under it the time bar with its keys.
|
||||
//
|
||||
// No app import: index.js hands in where the camera is kept, how to run the
|
||||
// node and how to reach a file, so the same face sits on the node or on the
|
||||
// box that holds it.
|
||||
//
|
||||
// The stage is the one part of the node that keeps the mouse wheel (it zooms
|
||||
// the camera, as in Blender); its root carries no "ausboss-" class, so the
|
||||
// pack's wheel hand-off leaves it alone. The controls under it do carry one,
|
||||
// and the wheel there zooms the graph as everywhere else.
|
||||
|
||||
import { makeScrubInput } from "../shared/scrub_input.mjs";
|
||||
import {
|
||||
K0, LIM, SAME_KEY, camAt, cameraText, clamp, describe, keyAt, mv, parseCamera, pastLoraRange,
|
||||
pivotFromPixel, pose, rot, setKeyAt, toCam, unpackDepth,
|
||||
} from "./camera_math.mjs";
|
||||
|
||||
export const MIN_WIDTH = 380; // the play row on one line, with "243 / 243" frames
|
||||
export const MIN_STAGE = 184;
|
||||
export const CONTROLS_HEIGHT = 168;
|
||||
const FPS = 24; // H3 renders at 24 frames a second; only playback speed uses it
|
||||
const MAG = 0xFFFF00FF;
|
||||
|
||||
const CSS = `
|
||||
.acm-face{position:relative;display:flex;flex-direction:column;width:100%;height:100%;box-sizing:border-box;
|
||||
--acm-teal:#4fb3a9;--acm-teal-dim:#2b605b;--acm-line:#34413f;--acm-fg:#e3e9e8;--acm-muted:#92a2a1;--acm-amber:#e2a94c;
|
||||
--acm-stage:#0c0f10;--acm-panel:#1f2629;--acm-head:#283236;color:var(--acm-fg);font:12.5px system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
|
||||
.acm-face *{box-sizing:border-box}
|
||||
.acm-stage{position:relative;flex:1 1 auto;min-height:${MIN_STAGE}px;background:var(--acm-stage);border-radius:6px;overflow:hidden;
|
||||
touch-action:none;user-select:none;-webkit-user-select:none}
|
||||
.acm-stage>canvas.acm-pic{position:absolute;display:block;cursor:grab}
|
||||
.acm-stage>canvas.acm-pic:active{cursor:grabbing}
|
||||
.acm-pivot{position:absolute;width:18px;height:18px;margin:-9px 0 0 -9px;border:2px solid var(--acm-teal);border-radius:50%;pointer-events:none;box-shadow:0 0 0 1px rgba(0,0,0,.6)}
|
||||
.acm-pivot::after{content:"";position:absolute;left:50%;top:50%;width:3px;height:3px;margin:-1.5px;background:var(--acm-teal);border-radius:50%}
|
||||
.acm-nav{position:absolute;top:6px;right:6px;display:flex;flex-direction:column;align-items:center;gap:5px}
|
||||
.acm-nav canvas{width:64px;height:64px;cursor:grab;touch-action:none;margin-bottom:1px}
|
||||
.acm-nav button,.acm-helpbtn{width:30px;height:30px;border-radius:50%;border:1px solid rgba(146,162,161,.4);background:rgba(12,15,16,.62);
|
||||
color:var(--acm-fg);padding:0;display:grid;place-items:center;touch-action:none;box-shadow:0 1px 6px rgba(0,0,0,.45);cursor:pointer}
|
||||
.acm-nav button svg{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
|
||||
.acm-nav button:hover,.acm-helpbtn:hover{border-color:var(--acm-teal)}
|
||||
.acm-nav button.on,.acm-helpbtn[aria-expanded="true"]{background:var(--acm-teal-dim);border-color:var(--acm-teal)}
|
||||
.acm-nav .pan{cursor:move}.acm-nav .zoom{cursor:ns-resize}
|
||||
.acm-helpbtn{position:absolute;top:6px;left:6px;width:24px;height:24px;font:600 12px system-ui,sans-serif}
|
||||
.acm-inset{position:absolute;left:6px;bottom:6px;width:36%;border:1px solid var(--acm-line);border-radius:5px;overflow:hidden;background:var(--acm-stage);
|
||||
box-shadow:0 2px 10px rgba(0,0,0,.5);pointer-events:none}
|
||||
.acm-inset canvas{display:block;width:100%;height:auto}
|
||||
.acm-tag{position:absolute;top:4px;left:5px;font-size:10px;color:var(--acm-muted);background:rgba(12,15,16,.7);padding:1px 5px;border-radius:4px;pointer-events:none}
|
||||
.acm-empty{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;padding:16px;text-align:center;color:var(--acm-muted);line-height:1.4}
|
||||
.acm-empty b{color:var(--acm-fg);font-weight:600;font-size:13px}
|
||||
.ausboss-camera-move-controls{flex:0 0 auto;display:flex;flex-direction:column;gap:6px;padding:7px 0 2px}
|
||||
.acm-readout{display:flex;justify-content:space-between;gap:8px;font-size:11.5px;color:var(--acm-fg);font-variant-numeric:tabular-nums;min-height:15px}
|
||||
.acm-readout .acm-where{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.acm-readout .acm-pink{color:var(--acm-muted);flex:0 0 auto}
|
||||
.acm-warn{color:var(--acm-amber);font-size:11.5px;line-height:15px;height:15px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.acm-back{display:flex;align-items:center;gap:8px}
|
||||
.acm-back>span{width:40px;color:var(--acm-muted)}
|
||||
.acm-track{position:relative;height:34px;background:var(--acm-stage);border:1px solid var(--acm-line);border-radius:6px;touch-action:none;cursor:pointer}
|
||||
.acm-track .acm-fill{position:absolute;top:15px;height:2px;left:8px;right:8px;background:var(--acm-line)}
|
||||
.acm-track .acm-inner{position:absolute;left:8px;right:8px;top:0;bottom:0}
|
||||
.acm-track .acm-key{position:absolute;top:10px;width:12px;height:12px;margin-left:-6px;transform:rotate(45deg);background:var(--acm-teal);border:1px solid #0c0f10;cursor:ew-resize}
|
||||
.acm-track .acm-key.on{background:#bfe9e4}
|
||||
.acm-track .acm-head{position:absolute;top:2px;bottom:2px;width:2px;margin-left:-1px;background:var(--acm-fg);pointer-events:none}
|
||||
.acm-track .acm-head::before{content:"";position:absolute;top:-2px;left:-4px;width:10px;height:6px;background:var(--acm-fg);border-radius:2px}
|
||||
.acm-row{display:flex;align-items:center;gap:6px}
|
||||
.acm-row>.acm-keynav,.acm-row>.acm-btn{flex:none;white-space:nowrap}
|
||||
.acm-btn{border:1px solid var(--acm-line);background:var(--acm-head);color:var(--acm-fg);font:inherit;font-size:12.5px;padding:6px 10px;border-radius:6px;cursor:pointer;line-height:1.1}
|
||||
.acm-btn:disabled{opacity:.4;cursor:default}
|
||||
.acm-btn.primary{background:var(--acm-teal-dim);border-color:var(--acm-teal-dim)}
|
||||
.acm-keynav{display:inline-flex;border:1px solid var(--acm-line);border-radius:6px;background:var(--acm-head);overflow:hidden}
|
||||
.acm-keynav button{width:32px;height:29px;border:0;background:transparent;color:var(--acm-fg);padding:0;display:grid;place-items:center;cursor:pointer}
|
||||
.acm-keynav button+button{border-left:1px solid var(--acm-line)}
|
||||
.acm-keynav button:disabled{color:var(--acm-muted);opacity:.35;cursor:default}
|
||||
.acm-keynav button:not(:disabled):hover{background:var(--acm-panel)}
|
||||
.acm-keynav svg{width:14px;height:14px}
|
||||
.acm-keynav .dia svg{width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:1.6}
|
||||
.acm-keynav .dia.on svg{fill:#bfe9e4;stroke:#bfe9e4}
|
||||
.acm-keynav .arr svg{fill:currentColor}
|
||||
.acm-keynav.transport .play{width:36px;background:var(--acm-teal-dim);font-size:12px}
|
||||
.acm-keynav.transport .play:hover{background:var(--acm-teal)}
|
||||
.acm-keynav.transport .loop{color:var(--acm-muted)}
|
||||
.acm-keynav.transport .loop svg{width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round}
|
||||
.acm-keynav.transport .loop[aria-pressed="true"]{color:#bfe9e4;background:var(--acm-teal-dim)}
|
||||
.acm-time{margin-left:auto;font-size:11.5px;color:var(--acm-muted);font-variant-numeric:tabular-nums;white-space:nowrap}
|
||||
.acm-help{position:absolute;top:36px;left:6px;right:6px;z-index:5;background:#172023;border:1px solid var(--acm-line);border-radius:8px;
|
||||
padding:10px 12px 12px;box-shadow:0 8px 28px rgba(0,0,0,.55);max-height:calc(100% - 44px);overflow:auto}
|
||||
.acm-help-h{display:flex;justify-content:space-between;align-items:center;font-weight:600;font-size:13px;margin-bottom:6px}
|
||||
.acm-help-x{border:0;background:transparent;color:var(--acm-muted);font-size:20px;line-height:1;cursor:pointer;padding:0 2px}
|
||||
.acm-help dl{margin:0;display:grid;grid-template-columns:auto 1fr;gap:7px 12px;font-size:12.5px;line-height:1.4}
|
||||
.acm-help dt{color:var(--acm-teal);font-weight:600}.acm-help dd{margin:0}
|
||||
.acm-nav,.acm-keynav,.acm-btn,.acm-helpbtn{-webkit-touch-callout:none;-webkit-user-select:none;user-select:none}
|
||||
.acm-tip{position:fixed;z-index:10000;max-width:250px;background:#0a0d0e;color:#e3e9e8;border:1px solid #34413f;border-radius:6px;
|
||||
padding:5px 8px;font:12px/1.35 system-ui,sans-serif;pointer-events:none;box-shadow:0 4px 14px rgba(0,0,0,.5)}
|
||||
.acm-face [hidden],.acm-tip[hidden]{display:none!important}
|
||||
`;
|
||||
|
||||
function ensureCss() {
|
||||
if (document.getElementById("ausboss-camera-move-css")) return;
|
||||
const style = document.createElement("style");
|
||||
style.id = "ausboss-camera-move-css";
|
||||
style.textContent = CSS;
|
||||
document.head.append(style);
|
||||
}
|
||||
|
||||
const el = (tag, cls, attrs = {}) => {
|
||||
const e = document.createElement(tag);
|
||||
if (cls) e.className = cls;
|
||||
for (const [k, v] of Object.entries(attrs)) {
|
||||
if (k === "text") e.textContent = v;
|
||||
else if (k === "html") e.innerHTML = v;
|
||||
else e.setAttribute(k, v);
|
||||
}
|
||||
return e;
|
||||
};
|
||||
|
||||
const NAV_ICONS = {
|
||||
zoom: '<svg viewBox="0 0 24 24"><circle cx="10.5" cy="10.5" r="6"/><path d="M15 15l5 5"/></svg>',
|
||||
pan: '<svg viewBox="0 0 24 24"><path d="M7.5 12.5V6.3a1.25 1.25 0 0 1 2.5 0v5M10 11.3V4.8a1.25 1.25 0 0 1 2.5 0v6.5M12.5 11.3V5.6a1.25 1.25 0 0 1 2.5 0v6M15 11.8V8a1.25 1.25 0 0 1 2.5 0v5.5c0 3.9-2.6 6.8-6.3 6.8h-.6c-2.1 0-3.6-.9-4.8-2.6l-2.4-3.5a1.35 1.35 0 0 1 2.1-1.7l2 2.3"/></svg>',
|
||||
shot: '<svg viewBox="0 0 24 24"><rect x="2.8" y="7.3" width="12.6" height="9.4" rx="1.8"/><path d="M15.4 10.6 21 7.8v8.4l-5.6-2.8"/></svg>',
|
||||
};
|
||||
const NAV_TIPS = { zoom: "Zoom: drag up to push in, down to pull back", pan: "Pan: drag to slide the camera", shot: "Back to your own shot" };
|
||||
const GZ = 64;
|
||||
// Blender's names for the scene's directions: X to the right, Y into the picture, Z up.
|
||||
const AXES = [
|
||||
{ n: "X", v: [1, 0, 0], col: "#e05561", pos: { az: 90, el: 0 }, neg: { az: -90, el: 0 } },
|
||||
{ n: "Y", v: [0, 0, 1], col: "#86b84a", pos: null, neg: { az: 0, el: 0 } }, // nothing to see from behind the scene
|
||||
{ n: "Z", v: [0, -1, 0], col: "#4b8fdf", pos: { az: 0, el: LIM.el[1] }, neg: { az: 0, el: LIM.el[0] } },
|
||||
];
|
||||
const SUB = [[-0.25, -0.25], [0.25, -0.25], [-0.25, 0.25], [0.25, 0.25]];
|
||||
const VIEW = { az: -58, el: 28 }; // the corner map looks at the scene from the left
|
||||
|
||||
// ---------- tooltips: hover on a computer, press and hold a button on a phone ----------
|
||||
let tipEl = null, tipTimer = 0, tipFor = null, tipXY = [0, 0], tipHeld = false;
|
||||
function tip() {
|
||||
if (!tipEl || !tipEl.isConnected) {
|
||||
tipEl = el("div", "acm-tip", { role: "tooltip" });
|
||||
tipEl.hidden = true;
|
||||
document.body.append(tipEl);
|
||||
}
|
||||
return tipEl;
|
||||
}
|
||||
function placeTip(target) {
|
||||
const t = target.dataset.tip, box = tip();
|
||||
if (!t || !target.isConnected) return hideTip();
|
||||
box.textContent = t;
|
||||
box.hidden = false;
|
||||
const r = target.getBoundingClientRect(), tw = box.offsetWidth, th = box.offsetHeight, atPtr = target.dataset.tipAt === "pointer";
|
||||
if (target.closest(".acm-nav")) { // the column top right: the tip opens to its left and covers no other button
|
||||
box.style.left = `${Math.max(8, r.left - tw - 8)}px`;
|
||||
box.style.top = `${r.top + r.height / 2 - th / 2}px`;
|
||||
return;
|
||||
}
|
||||
const ax = atPtr ? tipXY[0] : r.left + r.width / 2;
|
||||
const below = atPtr ? tipXY[1] + 22 : r.bottom + 8, above = atPtr ? tipXY[1] - th - 12 : r.top - th - 8;
|
||||
box.style.left = `${clamp(ax - tw / 2, 8, innerWidth - tw - 8)}px`;
|
||||
box.style.top = `${below + th > innerHeight - 8 ? above : below}px`;
|
||||
}
|
||||
function hideTip() { clearTimeout(tipTimer); if (tipEl) tipEl.hidden = true; tipFor = null; }
|
||||
const armTip = (target, ms) => { clearTimeout(tipTimer); tipFor = target; tipTimer = setTimeout(() => placeTip(target), ms); };
|
||||
function wireTips(root) {
|
||||
const targetOf = (e) => e.target?.closest?.("[data-tip]") ?? null;
|
||||
root.addEventListener("pointermove", (e) => {
|
||||
if (e.pointerType !== "mouse") return;
|
||||
tipXY = [e.clientX, e.clientY];
|
||||
if (e.buttons) { if (tipFor) hideTip(); return; }
|
||||
const t = targetOf(e);
|
||||
if (!t) { if (tipFor) hideTip(); return; }
|
||||
if (t !== tipFor) { hideTip(); armTip(t, t.dataset.tipAt === "pointer" ? 900 : 450); }
|
||||
else if (t.dataset.tipAt === "pointer") { hideTip(); armTip(t, 900); } // over a picture the tip waits until the mouse rests
|
||||
}, true);
|
||||
root.addEventListener("pointerleave", hideTip);
|
||||
root.addEventListener("pointerdown", (e) => {
|
||||
hideTip();
|
||||
if (e.pointerType === "mouse") return;
|
||||
const t = targetOf(e);
|
||||
if (!t || t.dataset.tipAt === "pointer") return;
|
||||
const x0 = e.clientX, y0 = e.clientY;
|
||||
armTip(t, 500);
|
||||
const done = () => { removeEventListener("pointermove", move, true); removeEventListener("pointerup", up, true); removeEventListener("pointercancel", up, true); };
|
||||
const move = (m) => { if (Math.hypot(m.clientX - x0, m.clientY - y0) > 8) { clearTimeout(tipTimer); done(); } };
|
||||
const up = () => {
|
||||
if (tipEl && !tipEl.hidden) { tipHeld = true; setTimeout(() => { tipHeld = false; }, 400); setTimeout(hideTip, 1600); } else clearTimeout(tipTimer);
|
||||
done();
|
||||
};
|
||||
addEventListener("pointermove", move, true); addEventListener("pointerup", up, true); addEventListener("pointercancel", up, true);
|
||||
}, true);
|
||||
// A hold that showed a tip is not a click.
|
||||
root.addEventListener("click", (e) => { if (tipHeld) { tipHeld = false; e.preventDefault(); e.stopPropagation(); } }, true);
|
||||
root.addEventListener("contextmenu", (e) => { if (e.target.closest?.(".acm-nav, .acm-keynav, .acm-btn")) e.preventDefault(); });
|
||||
}
|
||||
|
||||
// ---------- one frame of the clip, as points ----------
|
||||
async function loadFrame(entry, info, view, blobOf) {
|
||||
const W = info.w, H = info.h;
|
||||
const picture = new Image();
|
||||
picture.decoding = "async";
|
||||
const pictureReady = new Promise((ok, fail) => { picture.onload = ok; picture.onerror = () => fail(new Error("picture")); });
|
||||
picture.src = view(entry.color);
|
||||
const depthBlob = await blobOf(entry.depth);
|
||||
const depthBitmap = await createImageBitmap(depthBlob, { colorSpaceConversion: "none", premultiplyAlpha: "none" });
|
||||
await pictureReady;
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = W; canvas.height = H;
|
||||
const g = canvas.getContext("2d", { willReadFrequently: true });
|
||||
g.drawImage(picture, 0, 0, W, H);
|
||||
const rgba = new Uint32Array(g.getImageData(0, 0, W, H).data.buffer.slice(0));
|
||||
g.clearRect(0, 0, W, H);
|
||||
g.drawImage(depthBitmap, 0, 0, W, H);
|
||||
const { z, valid } = unpackDepth(g.getImageData(0, 0, W, H).data, W * H, info.zmin, info.zmax, info.far);
|
||||
// the corner map leaves out what is very far away
|
||||
const zs = [];
|
||||
for (let i = 0; i < W * H; i += 5) if (valid[i]) zs.push(z[i]);
|
||||
zs.sort((a, b) => a - b);
|
||||
const zcap = Math.min(zs[Math.floor(zs.length * 0.97)] || info.far, (zs[zs.length >> 1] || 1) * 3.5);
|
||||
return { ...entry, W, H, z, valid, rgba, zcap, picture };
|
||||
}
|
||||
|
||||
// ---------- the face ----------
|
||||
// opts: read() -> camera text, write(text), run() -> Promise<boolean>,
|
||||
// view(fileEntry) -> url, onSize() when the floor changes.
|
||||
export function mountCameraFace(opts) {
|
||||
ensureCss();
|
||||
const root = el("div", "acm-face");
|
||||
const stage = el("div", "acm-stage");
|
||||
const pic = el("canvas", "acm-pic", { "data-tip": "Drag to turn · Shift-drag to pan · wheel to zoom · click a spot to circle round it", "data-tip-at": "pointer" });
|
||||
const picCtx = pic.getContext("2d");
|
||||
const pivotMark = el("div", "acm-pivot");
|
||||
const nav = el("div", "acm-nav");
|
||||
const gizmo = el("canvas", "", { "data-tip": "Drag to turn. Click an axis to look from that side.", role: "img", "aria-label": "Axis ball: drag to turn the camera, tap an axis to look from that side" });
|
||||
gizmo.width = GZ * 2; gizmo.height = GZ * 2;
|
||||
const gctx = gizmo.getContext("2d");
|
||||
nav.append(gizmo);
|
||||
const inset = el("div", "acm-inset");
|
||||
const out = el("canvas");
|
||||
out.width = 360; out.height = 225;
|
||||
const outCtx = out.getContext("2d");
|
||||
const outImg = outCtx.createImageData(out.width, out.height);
|
||||
const outZ = new Float32Array(out.width * out.height);
|
||||
inset.append(out, el("span", "acm-tag", { text: "where the camera is" }));
|
||||
const helpBtn = el("button", "acm-helpbtn", { text: "?", "aria-label": "How to steer", "aria-expanded": "false", "data-tip": "How to steer" });
|
||||
const empty = el("div", "acm-empty");
|
||||
stage.append(pic, pivotMark, inset, nav, helpBtn, empty);
|
||||
|
||||
const controls = el("div", "ausboss-camera-move-controls");
|
||||
const readout = el("div", "acm-readout");
|
||||
const where = el("span", "acm-where");
|
||||
const pink = el("span", "acm-pink", { "data-tip": "How much of the frame the camera never saw. The LoRA paints it in." });
|
||||
readout.append(where, pink);
|
||||
// Always one line tall, empty or not, so a warning never pushes the controls down.
|
||||
const warn = el("div", "acm-warn");
|
||||
const backRow = el("div", "acm-back");
|
||||
const back = makeScrubInput({
|
||||
value: 0, min: LIM.back[0], max: LIM.back[1], step: 0.05, fineStep: 0.01, decimals: 2, unit: "×", unitWidth: 14, width: 132,
|
||||
title: "How far the camera pulls back from what it circles. Below 0 pushes in.",
|
||||
onChange: (v) => { stopPlay(); setCam({ ...camAt(keys, p), back: v }); },
|
||||
});
|
||||
backRow.append(el("span", "", { text: "Back" }), back.root);
|
||||
const track = el("div", "acm-track", { "data-tip": "Click to put a key here. Drag to move the time bar, or drag a key to change its time.", "data-tip-at": "pointer" });
|
||||
const inner = el("div", "acm-inner");
|
||||
const head = el("div", "acm-head");
|
||||
inner.append(head);
|
||||
track.append(el("div", "acm-fill"), inner);
|
||||
const row = el("div", "acm-row");
|
||||
const transport = el("span", "acm-keynav transport", { role: "group", "aria-label": "Playback" });
|
||||
const toStartBtn = el("button", "arr", { "aria-label": "Back to the start", "data-tip": "Back to the start", html: '<svg viewBox="0 0 14 14"><path d="M2.5 2.5h1.6v9H2.5zM11.5 2.5v9L5 7z"/></svg>' });
|
||||
const play = el("button", "play", { text: "▶", "aria-label": "Play", "data-tip": "Play" });
|
||||
const loop = el("button", "loop", { "aria-label": "Play on a loop", "aria-pressed": "false", "data-tip": "Play on a loop", html: '<svg viewBox="0 0 16 16"><path d="M3 9.5V7a2.5 2.5 0 0 1 2.5-2.5H12M10 2.5l2 2-2 2M13 6.5V9a2.5 2.5 0 0 1-2.5 2.5H4M6 13.5l-2-2 2-2"/></svg>' });
|
||||
transport.append(toStartBtn, play, loop);
|
||||
const keynav = el("span", "acm-keynav", { role: "group", "aria-label": "Keys" });
|
||||
const prevKey = el("button", "arr", { "aria-label": "Previous key", "data-tip": "Previous key", html: '<svg viewBox="0 0 14 14"><path d="M10 2.5v9L3.5 7z"/></svg>' });
|
||||
const toggleKey = el("button", "dia", { "aria-label": "Add a key here", "data-tip": "Add a key here", html: '<svg viewBox="0 0 16 16"><path d="M8 1.8 14.2 8 8 14.2 1.8 8z"/></svg>' });
|
||||
const nextKey = el("button", "arr", { "aria-label": "Next key", "data-tip": "Next key", html: '<svg viewBox="0 0 14 14"><path d="M4 2.5v9L10.5 7z"/></svg>' });
|
||||
keynav.append(prevKey, toggleKey, nextKey);
|
||||
const reset = el("button", "acm-btn", { text: "Start over", "data-tip": "One key again, on your own shot" });
|
||||
const time = el("span", "acm-time", { "data-tip": "Frame at the time bar" });
|
||||
row.append(transport, keynav, reset, time);
|
||||
controls.append(readout, warn, backRow, track, row);
|
||||
const help = el("div", "acm-help");
|
||||
help.hidden = true;
|
||||
root.append(stage, controls, help);
|
||||
wireTips(root);
|
||||
|
||||
// ---------- state ----------
|
||||
let keys = [], pivotSpec = null, lastText = null, p = 0, playing = false, lastT = 0, dirty = true, alive = true;
|
||||
let info = null, frames = [], shown = null, pivot = [0, 0, 2], pinkPct = 0, status = "idle", statusNote = "";
|
||||
let flashText = "", flashUntil = 0, gBalls = [], gHot = false, hovered = false, overFace = false, looping = false, needsWrite = false;
|
||||
let buf = null; // z, colour and source pixel of the moved view
|
||||
const fallbackLens = { W: 416, H: 234, fx: 380, fy: 380, cx: 208, cy: 117 };
|
||||
|
||||
function readCamera() {
|
||||
const text = opts.read();
|
||||
if (text === lastText) return;
|
||||
lastText = text;
|
||||
const parsed = parseCamera(text);
|
||||
keys = parsed.keys;
|
||||
pivotSpec = parsed.pivot;
|
||||
resolvePivot();
|
||||
dirty = true;
|
||||
}
|
||||
function writeSoon() { needsWrite = true; dirty = true; }
|
||||
function flushWrite() {
|
||||
if (!needsWrite) return;
|
||||
needsWrite = false;
|
||||
const text = cameraText({ keys, pivot: pivotSpec });
|
||||
lastText = text;
|
||||
if (text !== opts.read()) opts.write(text);
|
||||
}
|
||||
function setCam(cam) { setKeyAt(keys, p, cam); writeSoon(); }
|
||||
|
||||
function lens() { return shown ?? (info ? { ...fallbackLens, ...info.frames[0], W: info.w, H: info.h } : fallbackLens); }
|
||||
function resolvePivot() {
|
||||
if (!info) { pivot = [0, 0, 2]; return; }
|
||||
if (!pivotSpec) { pivot = info.pivot_auto?.slice() ?? [0, 0, 2]; return; }
|
||||
if (info.pivot_from && Math.abs(info.pivot_from.u - pivotSpec.u) < 1e-4 && Math.abs(info.pivot_from.v - pivotSpec.v) < 1e-4
|
||||
&& Math.abs(info.pivot_from.t - pivotSpec.t) < 1e-4) { pivot = info.pivot.slice(); return; }
|
||||
const f = nearestLoaded(pivotSpec.t);
|
||||
const found = f && pivotFromPixel(f, pivotSpec.u, pivotSpec.v);
|
||||
if (found) pivot = found;
|
||||
}
|
||||
|
||||
// ---------- frames ----------
|
||||
function nearestFrame(t) {
|
||||
let best = null;
|
||||
for (const f of frames) if (!best || Math.abs(f.t - t) < Math.abs(best.t - t)) best = f;
|
||||
return best;
|
||||
}
|
||||
function nearestLoaded(t) {
|
||||
let best = null;
|
||||
for (const f of frames) if (f.data && (!best || Math.abs(f.t - t) < Math.abs(best.t - t))) best = f;
|
||||
return best?.data ?? null;
|
||||
}
|
||||
async function loadAll(payload) {
|
||||
const order = [...frames].sort((a, b) => Math.abs(a.t - p) - Math.abs(b.t - p));
|
||||
let failed = 0, next = 0;
|
||||
// Four at a time, the frames nearest the time bar first.
|
||||
const worker = async () => {
|
||||
while (next < order.length) {
|
||||
const f = order[next++];
|
||||
if (info !== payload) return;
|
||||
try { f.data = await loadFrame(f.entry, payload, opts.view, opts.blob); } catch { failed++; }
|
||||
if (info !== payload) return;
|
||||
if (f.data && status !== "ready") { status = "ready"; resolvePivot(); }
|
||||
dirty = true;
|
||||
}
|
||||
};
|
||||
await Promise.all([worker(), worker(), worker(), worker()]);
|
||||
if (info !== payload) return;
|
||||
if (failed === frames.length) { info = null; frames = []; shown = null; status = "idle"; statusNote = "The last run's pictures are gone. Run it again to see your clip."; dirty = true; }
|
||||
}
|
||||
|
||||
// ---------- the camera's view ----------
|
||||
function fitPicture() {
|
||||
const L = lens(), sw = stage.clientWidth, sh = stage.clientHeight;
|
||||
if (!sw || !sh) return null;
|
||||
const s = Math.min(sw / L.W, sh / L.H), w = L.W * s, h = L.H * s, x = (sw - w) / 2, y = (sh - h) / 2;
|
||||
Object.assign(pic.style, { left: `${x}px`, top: `${y}px`, width: `${w}px`, height: `${h}px` });
|
||||
inset.hidden = !shown || sw < 300 || sh < MIN_STAGE;
|
||||
return { x, y, w, h };
|
||||
}
|
||||
function renderPreview(cam, fit) {
|
||||
const f = shown;
|
||||
if (!f) { pic.hidden = true; pivotMark.hidden = true; return; }
|
||||
pic.hidden = false;
|
||||
const { W, H, z, rgba, fx, fy, cx, cy } = f;
|
||||
if (!buf || buf.W !== W || buf.H !== H) {
|
||||
buf = { W, H, zbuf: new Float32Array(W * H), cbuf: new Uint32Array(W * H), ibuf: new Int32Array(W * H), fill: new Uint8Array(W * H), img: picCtx.createImageData(W, H) };
|
||||
pic.width = W; pic.height = H;
|
||||
buf.img = picCtx.createImageData(W, H);
|
||||
}
|
||||
const { zbuf, cbuf, ibuf, fill, img } = buf;
|
||||
const { R, C } = pose(cam, pivot);
|
||||
const [r0, r1, r2, r3, r4, r5, r6, r7, r8] = R, [Cx, Cy, Cz] = C;
|
||||
zbuf.fill(Infinity); ibuf.fill(-1);
|
||||
for (let y = 0, i = 0; y < H; y++) for (let x = 0; x < W; x++, i++) {
|
||||
const zz = z[i], c = rgba[i];
|
||||
for (let s = 0; s < 4; s++) {
|
||||
const X = (x + 0.5 + SUB[s][0] - cx) / fx * zz - Cx, Y = (y + 0.5 + SUB[s][1] - cy) / fy * zz - Cy, Z = zz - Cz;
|
||||
const zc = r2 * X + r5 * Y + r8 * Z;
|
||||
if (zc <= 1e-3) continue;
|
||||
const u = fx * (r0 * X + r3 * Y + r6 * Z) / zc + cx, v = fy * (r1 * X + r4 * Y + r7 * Z) / zc + cy;
|
||||
if (u < 0 || v < 0 || u >= W || v >= H) continue;
|
||||
const idx = (v | 0) * W + (u | 0);
|
||||
if (zc < zbuf[idx]) { zbuf[idx] = zc; cbuf[idx] = c; ibuf[idx] = i; }
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < W * H; i++) fill[i] = zbuf[i] < Infinity ? 1 : 0;
|
||||
// fill one-pixel cracks: a gap mostly surrounded by picture takes their average (two passes, like the node)
|
||||
for (let pass = 0; pass < 2; pass++) {
|
||||
const was = fill.slice(), src = cbuf.slice();
|
||||
let any = false;
|
||||
for (let y = 1; y < H - 1; y++) for (let x = 1; x < W - 1; x++) {
|
||||
const i = y * W + x;
|
||||
if (was[i]) continue;
|
||||
let n = 0, r = 0, g = 0, b = 0;
|
||||
for (let oy = -1; oy <= 1; oy++) for (let ox = -1; ox <= 1; ox++) {
|
||||
const q = i + oy * W + ox;
|
||||
if (!was[q]) continue;
|
||||
const c = src[q]; n++; r += c & 255; g += (c >>> 8) & 255; b += (c >>> 16) & 255;
|
||||
}
|
||||
if (n >= 5) { cbuf[i] = 0xFF000000 | ((b / n) << 16) | ((g / n) << 8) | (r / n); fill[i] = 1; any = true; }
|
||||
}
|
||||
if (!any) break;
|
||||
}
|
||||
const o = new Uint32Array(img.data.buffer);
|
||||
let holes = 0;
|
||||
for (let i = 0; i < W * H; i++) { if (fill[i]) o[i] = cbuf[i]; else { o[i] = MAG; holes++; } }
|
||||
picCtx.putImageData(img, 0, 0);
|
||||
pinkPct = 100 * holes / (W * H);
|
||||
const q = toCam(R, C, pivot);
|
||||
if (fit && q[2] > 1e-3) {
|
||||
pivotMark.hidden = false;
|
||||
pivotMark.style.left = `${fit.x + fit.w * (fx * q[0] / q[2] + cx) / W}px`;
|
||||
pivotMark.style.top = `${fit.y + fit.h * (fy * q[1] / q[2] + cy) / H}px`;
|
||||
} else pivotMark.hidden = true;
|
||||
}
|
||||
|
||||
// ---------- the corner map: your scene from the side, and the camera in it ----------
|
||||
function viewer() {
|
||||
const P = pivot, d = Math.hypot(P[0], P[1], P[2]), T = [P[0] * 0.55, P[1] * 0.55, P[2] * 0.55];
|
||||
const R = rot(VIEW.az, VIEW.el), b = mv(R, [0, 0, -d * 2.3]);
|
||||
return { R, C: [T[0] + b[0], T[1] + b[1], T[2] + b[2]], f: 0.95 * out.width };
|
||||
}
|
||||
function proj(V, P) {
|
||||
const q = toCam(V.R, V.C, P);
|
||||
return q[2] <= 1e-3 ? null : [V.f * q[0] / q[2] + out.width / 2, V.f * q[1] / q[2] + out.height / 2, q[2]];
|
||||
}
|
||||
function frustum(V, cam, color, width) {
|
||||
const L = lens(), { R, C } = pose(cam, pivot), s = Math.hypot(...pivot) * 0.3;
|
||||
const corners = [[0, 0], [L.W, 0], [L.W, L.H], [0, L.H]].map(([x, y]) => {
|
||||
const l = mv(R, [(x - L.cx) / L.fx * s, (y - L.cy) / L.fy * s, s]);
|
||||
return proj(V, [C[0] + l[0], C[1] + l[1], C[2] + l[2]]);
|
||||
});
|
||||
const a = proj(V, C);
|
||||
if (!a || corners.some((c) => !c)) return;
|
||||
outCtx.strokeStyle = color; outCtx.lineWidth = width; outCtx.beginPath();
|
||||
for (const c of corners) { outCtx.moveTo(a[0], a[1]); outCtx.lineTo(c[0], c[1]); }
|
||||
outCtx.moveTo(corners[0][0], corners[0][1]);
|
||||
for (const c of [...corners.slice(1), corners[0]]) outCtx.lineTo(c[0], c[1]);
|
||||
outCtx.stroke();
|
||||
// a small roof on the top edge, so up and down never mix
|
||||
outCtx.fillStyle = color; outCtx.beginPath(); outCtx.moveTo(corners[0][0], corners[0][1]); outCtx.lineTo(corners[1][0], corners[1][1]);
|
||||
const up = mv(R, [0, -L.H / 2 / L.fy * s * 1.35, s]), ut = proj(V, [C[0] + up[0], C[1] + up[1], C[2] + up[2]]);
|
||||
if (ut) { outCtx.lineTo(ut[0], ut[1]); outCtx.closePath(); outCtx.globalAlpha = 0.6; outCtx.fill(); outCtx.globalAlpha = 1; }
|
||||
}
|
||||
function renderOutside(cam) {
|
||||
if (inset.hidden) return;
|
||||
const w = out.width, h = out.height, V = viewer(), o = new Uint32Array(outImg.data.buffer);
|
||||
o.fill(0xFF100D0C); outZ.fill(Infinity);
|
||||
const f = shown;
|
||||
if (f) {
|
||||
const { W, H, z, valid, rgba, zcap, fx, fy, cx, cy } = f, [r0, r1, r2, r3, r4, r5, r6, r7, r8] = V.R, [Cx, Cy, Cz] = V.C;
|
||||
for (let y = 0; y < H; y += 2) for (let x = 0; x < W; x += 2) {
|
||||
const i = y * W + x, zz = z[i];
|
||||
if (!valid[i] || zz > zcap) continue;
|
||||
const dx = (x + 0.5 - cx) / fx * zz - Cx, dy = (y + 0.5 - cy) / fy * zz - Cy, dz = zz - Cz, zc = r2 * dx + r5 * dy + r8 * dz;
|
||||
if (zc <= 1e-3) continue;
|
||||
const u = V.f * (r0 * dx + r3 * dy + r6 * dz) / zc + w / 2, v = V.f * (r1 * dx + r4 * dy + r7 * dz) / zc + h / 2;
|
||||
const sz = clamp(Math.round(V.f * (zz / fx * 2.2) / zc), 1, 4), x0 = (u - sz / 2) | 0, y0 = (v - sz / 2) | 0;
|
||||
for (let yy = y0; yy < y0 + sz; yy++) {
|
||||
if (yy < 0 || yy >= h) continue;
|
||||
for (let xx = x0; xx < x0 + sz; xx++) { if (xx < 0 || xx >= w) continue; const q = yy * w + xx; if (zc < outZ[q]) { outZ[q] = zc; o[q] = rgba[i]; } }
|
||||
}
|
||||
}
|
||||
}
|
||||
outCtx.putImageData(outImg, 0, 0);
|
||||
frustum(V, { ...K0 }, "rgba(200,210,210,.55)", 1.5);
|
||||
const project = (c) => proj(V, pose(c, pivot).C);
|
||||
outCtx.strokeStyle = "rgba(79,179,169,.9)"; outCtx.lineWidth = 2; outCtx.setLineDash([5, 4]); outCtx.beginPath();
|
||||
let first = true;
|
||||
for (let i = 0; i <= 48; i++) {
|
||||
const q = project(camAt(keys, i / 48));
|
||||
if (!q) { first = true; continue; }
|
||||
if (first) outCtx.moveTo(q[0], q[1]); else outCtx.lineTo(q[0], q[1]);
|
||||
first = false;
|
||||
}
|
||||
outCtx.stroke(); outCtx.setLineDash([]);
|
||||
for (const k of keys) {
|
||||
const q = project(k);
|
||||
if (!q) continue;
|
||||
outCtx.save(); outCtx.translate(q[0], q[1]); outCtx.rotate(Math.PI / 4);
|
||||
outCtx.fillStyle = Math.abs(k.t - p) < SAME_KEY ? "#bfe9e4" : "#4fb3a9"; outCtx.strokeStyle = "#0c0f10"; outCtx.lineWidth = 1.5;
|
||||
outCtx.fillRect(-5, -5, 10, 10); outCtx.strokeRect(-5, -5, 10, 10); outCtx.restore();
|
||||
}
|
||||
const pv = proj(V, pivot), cc = project(cam);
|
||||
if (pv && cc) { outCtx.strokeStyle = "rgba(79,179,169,.45)"; outCtx.lineWidth = 1; outCtx.beginPath(); outCtx.moveTo(cc[0], cc[1]); outCtx.lineTo(pv[0], pv[1]); outCtx.stroke(); }
|
||||
frustum(V, cam, "#4fb3a9", 2.5);
|
||||
}
|
||||
|
||||
// ---------- the axis ball ----------
|
||||
function drawGizmo(cam) {
|
||||
const g = gctx, c = GZ / 2, L = 21, R = rot(cam.az, cam.el);
|
||||
g.setTransform(2, 0, 0, 2, 0, 0); g.clearRect(0, 0, GZ, GZ);
|
||||
g.fillStyle = gHot ? "rgba(146,162,161,.26)" : "rgba(12,15,16,.42)"; g.beginPath(); g.arc(c, c, c - 1, 0, 7); g.fill();
|
||||
gBalls = [];
|
||||
for (const a of AXES) for (const sg of [1, -1]) {
|
||||
const w = [a.v[0] * sg, a.v[1] * sg, a.v[2] * sg]; // the direction as the camera sees it
|
||||
const q = [R[0] * w[0] + R[3] * w[1] + R[6] * w[2], R[1] * w[0] + R[4] * w[1] + R[7] * w[2], R[2] * w[0] + R[5] * w[1] + R[8] * w[2]];
|
||||
gBalls.push({ a, sg, x: c + q[0] * L, y: c + q[1] * L, z: q[2], view: sg > 0 ? a.pos : a.neg });
|
||||
}
|
||||
gBalls.sort((m, n) => n.z - m.z); // far balls first, near ones on top
|
||||
for (const b of gBalls) {
|
||||
if (b.sg > 0) { g.strokeStyle = b.a.col; g.lineWidth = 2; g.beginPath(); g.moveTo(c, c); g.lineTo(b.x, b.y); g.stroke(); }
|
||||
g.beginPath(); g.arc(b.x, b.y, b.sg > 0 ? 7 : 6, 0, 7);
|
||||
if (b.sg > 0) {
|
||||
g.fillStyle = b.a.col; g.fill();
|
||||
g.fillStyle = "#0c0f10"; g.font = "bold 9px system-ui, sans-serif"; g.textAlign = "center"; g.textBaseline = "middle"; g.fillText(b.a.n, b.x, b.y + 0.5);
|
||||
} else { g.globalAlpha = 0.35; g.fillStyle = b.a.col; g.fill(); g.globalAlpha = 1; g.strokeStyle = b.a.col; g.lineWidth = 1.2; g.stroke(); }
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- gestures ----------
|
||||
const picRect = () => pic.getBoundingClientRect();
|
||||
function panBy(cam, dx, dy) { // the spot you circle stays under your finger
|
||||
const L = lens(), r = picRect(), d = Math.hypot(...pivot), zz = Math.max(0.05 * d, pivot[2] + cam.back * d);
|
||||
const du = dx * L.W / (r.width || 1), dv = dy * L.H / (r.height || 1);
|
||||
return { px: (cam.px || 0) - du * zz / (L.fx * d), py: (cam.py || 0) - dv * zz / (L.fy * d) };
|
||||
}
|
||||
function dragTo(kind, cam, dx, dy) {
|
||||
const r = picRect(), w = r.width || stage.clientWidth || 1, h = r.height || stage.clientHeight || 1;
|
||||
if (kind === "orbit") setCam({ ...cam, az: cam.az - dx * 90 / w, el: cam.el + dy * 90 / w }); // the picture follows your finger
|
||||
else if (kind === "pan") setCam({ ...cam, ...panBy(cam, dx, dy) });
|
||||
else if (kind === "zoom") setCam({ ...cam, back: cam.back + dy / h * 2.4 }); // up = in, down = back
|
||||
}
|
||||
const kindFor = (e) => (e.shiftKey ? "pan" : (e.ctrlKey || e.metaKey) ? "zoom" : "orbit");
|
||||
(() => {
|
||||
const pts = new Map();
|
||||
let g = null;
|
||||
const begin = (kind, carry) => {
|
||||
const v = [...pts.values()], cam = camAt(keys, p);
|
||||
if (v.length >= 2) {
|
||||
const [a, b] = v;
|
||||
g = { kind: "pinch", cam, d: Math.max(8, Math.hypot(a[0] - b[0], a[1] - b[1])), mx: (a[0] + b[0]) / 2, my: (a[1] + b[1]) / 2, moved: true, multi: true };
|
||||
} else if (v.length === 1) g = { kind, cam, x: v[0][0], y: v[0][1], moved: Boolean(carry), multi: Boolean(carry) };
|
||||
else g = null;
|
||||
};
|
||||
pic.addEventListener("mousedown", (e) => { if (e.button === 1) e.preventDefault(); }); // no auto-scroll on middle click
|
||||
pic.addEventListener("pointerdown", (e) => {
|
||||
if (e.button > 1) return;
|
||||
e.preventDefault(); e.stopPropagation();
|
||||
pic.setPointerCapture(e.pointerId); pts.set(e.pointerId, [e.clientX, e.clientY]); stopPlay();
|
||||
begin(kindFor(e));
|
||||
});
|
||||
pic.addEventListener("pointermove", (e) => {
|
||||
if (!pts.has(e.pointerId) || !g) return;
|
||||
pts.set(e.pointerId, [e.clientX, e.clientY]);
|
||||
if (g.kind === "pinch") {
|
||||
const [a, b] = [...pts.values()], d = Math.max(8, Math.hypot(a[0] - b[0], a[1] - b[1]));
|
||||
const c = { ...g.cam, back: g.cam.back - Math.log(d / g.d) * 0.9 };
|
||||
Object.assign(c, panBy(g.cam, (a[0] + b[0]) / 2 - g.mx, (a[1] + b[1]) / 2 - g.my));
|
||||
setCam(c);
|
||||
return;
|
||||
}
|
||||
const dx = e.clientX - g.x, dy = e.clientY - g.y;
|
||||
if (!g.moved && Math.hypot(dx, dy) < 5) return;
|
||||
g.moved = true;
|
||||
dragTo(g.kind, g.cam, dx, dy);
|
||||
});
|
||||
const up = (e) => {
|
||||
if (!pts.has(e.pointerId)) return;
|
||||
pts.delete(e.pointerId);
|
||||
if (pts.size === 0) {
|
||||
if (g && !g.moved && !g.multi && g.kind === "orbit" && e.type === "pointerup" && e.button === 0) pickPivot(e);
|
||||
g = null;
|
||||
return;
|
||||
}
|
||||
begin("orbit", true); // a finger left: carry on from here
|
||||
};
|
||||
pic.addEventListener("pointerup", up);
|
||||
pic.addEventListener("pointercancel", up);
|
||||
})();
|
||||
function pickPivot(e) { // tap: circle round what you tapped
|
||||
const f = shown, r = picRect();
|
||||
if (!f || !buf || !r.width) return;
|
||||
const x = ((e.clientX - r.left) / r.width * f.W) | 0, y = ((e.clientY - r.top) / r.height * f.H) | 0;
|
||||
if (x < 0 || y < 0 || x >= f.W || y >= f.H) return;
|
||||
let best = -1;
|
||||
for (let rr = 0; rr <= 3 && best < 0; rr++) for (let oy = -rr; oy <= rr && best < 0; oy++) for (let ox = -rr; ox <= rr; ox++) {
|
||||
const xx = x + ox, yy = y + oy;
|
||||
if (xx < 0 || yy < 0 || xx >= f.W || yy >= f.H) continue;
|
||||
const i = buf.ibuf[yy * f.W + xx];
|
||||
if (i >= 0) { best = i; break; }
|
||||
}
|
||||
if (best < 0 || !f.valid[best]) return; // sky: nothing to circle
|
||||
const spec = { u: ((best % f.W) + 0.5) / f.W, v: (Math.floor(best / f.W) + 0.5) / f.H, t: f.t };
|
||||
const found = pivotFromPixel(f, spec.u, spec.v);
|
||||
if (!found) return;
|
||||
pivotSpec = spec; pivot = found;
|
||||
writeSoon();
|
||||
}
|
||||
stage.addEventListener("wheel", (e) => {
|
||||
e.preventDefault(); e.stopPropagation(); stopPlay();
|
||||
const unit = e.deltaMode === 1 ? 33 : e.deltaMode === 2 ? 400 : 1, c = camAt(keys, p);
|
||||
if (e.shiftKey) { const a = (e.deltaY || e.deltaX) * unit; setCam({ ...c, ...panBy(c, 0, -a * 0.4) }); return; } // Shift + wheel pans up and down
|
||||
setCam({ ...c, back: c.back + e.deltaY * unit * (e.ctrlKey ? 0.01 : 0.0008) }); // wheel, and a trackpad pinch (Ctrl), zoom
|
||||
}, { passive: false });
|
||||
stage.addEventListener("gesturestart", (e) => e.preventDefault()); // Safari: never zoom the page instead
|
||||
stage.addEventListener("pointerdown", (e) => { if (e.button === 1) { e.preventDefault(); e.stopPropagation(); } });
|
||||
stage.addEventListener("pointerenter", () => { hovered = true; });
|
||||
stage.addEventListener("pointerleave", () => { hovered = false; });
|
||||
// Blender's numpad, while the pointer is over the picture.
|
||||
const onKey = (e) => {
|
||||
if (!hovered || !alive || e.altKey || e.target?.closest?.("input, textarea, select, [contenteditable]")) return;
|
||||
const c = camAt(keys, p), w = picRect().width || 300, step = 15, pan = e.ctrlKey || e.metaKey;
|
||||
const go = { Numpad4: [-1, 0], Numpad6: [1, 0], Numpad8: [0, 1], Numpad2: [0, -1] }[e.code];
|
||||
if (go) setCam(pan ? { ...c, ...panBy(c, -go[0] * w * 0.1, go[1] * w * 0.1) } : { ...c, az: c.az + go[0] * step, el: c.el + go[1] * step });
|
||||
else if (e.code === "NumpadAdd" || e.code === "NumpadSubtract") setCam({ ...c, back: c.back + (e.code === "NumpadAdd" ? -0.1 : 0.1) });
|
||||
else if (e.code === "Numpad1" && !pan) setCam({ ...c, az: 0, el: 0 }); // front
|
||||
else if (e.code === "Numpad3") setCam({ ...c, az: pan ? -90 : 90, el: 0 }); // right, Ctrl: left
|
||||
else if (e.code === "Numpad7") setCam({ ...c, az: 0, el: pan ? LIM.el[0] : LIM.el[1] }); // top, Ctrl: bottom
|
||||
else if (e.code === "Numpad0") setCam({ ...K0 }); // your own shot
|
||||
else if (e.key === "Escape" && !help.hidden) { openHelp(false); }
|
||||
else return;
|
||||
e.preventDefault(); e.stopPropagation(); stopPlay();
|
||||
};
|
||||
window.addEventListener("keydown", onKey, true);
|
||||
// Space plays and pauses, Home goes to the start, while the pointer is over the face.
|
||||
// Held there, Space would otherwise start a canvas pan.
|
||||
root.addEventListener("pointerenter", () => { overFace = true; });
|
||||
root.addEventListener("pointerleave", () => { overFace = false; });
|
||||
const onPlayKey = (e) => {
|
||||
if (!overFace || !alive || e.altKey || e.ctrlKey || e.metaKey || e.repeat && e.code === "Space") return;
|
||||
if (e.target?.closest?.("input, textarea, select, button, [contenteditable]")) return;
|
||||
if (e.key === "Home") toStart();
|
||||
else if (e.code === "Space") play.click();
|
||||
else return;
|
||||
e.preventDefault(); e.stopPropagation();
|
||||
};
|
||||
window.addEventListener("keydown", onPlayKey, true);
|
||||
|
||||
// the axis ball: drag turns, a tap on an axis looks from that side
|
||||
(() => {
|
||||
let g = null;
|
||||
gizmo.addEventListener("pointerenter", () => { gHot = true; dirty = true; });
|
||||
gizmo.addEventListener("pointerleave", () => { if (!g) { gHot = false; dirty = true; } });
|
||||
gizmo.addEventListener("pointerdown", (e) => {
|
||||
if (e.button > 1) return;
|
||||
e.preventDefault(); e.stopPropagation();
|
||||
gizmo.setPointerCapture(e.pointerId); stopPlay(); gHot = true; dirty = true;
|
||||
g = { id: e.pointerId, x: e.clientX, y: e.clientY, cam: camAt(keys, p), moved: false };
|
||||
});
|
||||
gizmo.addEventListener("pointermove", (e) => {
|
||||
if (!g || e.pointerId !== g.id) return;
|
||||
const dx = e.clientX - g.x, dy = e.clientY - g.y;
|
||||
if (!g.moved && Math.hypot(dx, dy) < 4) return;
|
||||
g.moved = true;
|
||||
dragTo("orbit", g.cam, dx * 1.5, dy * 1.5);
|
||||
});
|
||||
const end = (e) => {
|
||||
if (!g || e.pointerId !== g.id) return;
|
||||
if (!g.moved && e.type === "pointerup" && (e.pointerType === "mouse" || !tipEl || tipEl.hidden)) {
|
||||
const r = gizmo.getBoundingClientRect(), x = (e.clientX - r.left) * GZ / r.width, y = (e.clientY - r.top) * GZ / r.height;
|
||||
let hit = null;
|
||||
for (const b of gBalls) if (Math.hypot(b.x - x, b.y - y) <= 9) hit = b;
|
||||
if (hit?.view) setCam({ ...camAt(keys, p), ...hit.view });
|
||||
else if (hit) flash("Nothing behind: the camera never saw the back.");
|
||||
}
|
||||
g = null;
|
||||
if (e.pointerType !== "mouse") gHot = false;
|
||||
dirty = true;
|
||||
};
|
||||
gizmo.addEventListener("pointerup", end);
|
||||
gizmo.addEventListener("pointercancel", end);
|
||||
})();
|
||||
for (const kind of ["zoom", "pan", "shot"]) {
|
||||
const b = el("button", kind, { html: NAV_ICONS[kind], "data-tip": NAV_TIPS[kind], "aria-label": NAV_TIPS[kind] });
|
||||
nav.append(b);
|
||||
if (kind === "shot") { b.onclick = (e) => { e.stopPropagation(); stopPlay(); setCam({ ...K0 }); }; continue; }
|
||||
let g = null;
|
||||
b.addEventListener("pointerdown", (e) => {
|
||||
if (e.button > 1) return;
|
||||
e.preventDefault(); e.stopPropagation();
|
||||
b.setPointerCapture(e.pointerId); stopPlay(); b.classList.add("on");
|
||||
g = { id: e.pointerId, x: e.clientX, y: e.clientY, cam: camAt(keys, p) };
|
||||
});
|
||||
b.addEventListener("pointermove", (e) => {
|
||||
if (!g || e.pointerId !== g.id) return;
|
||||
const m = kind === "pan" ? 1 : 1.5;
|
||||
dragTo(kind, g.cam, (e.clientX - g.x) * m, (e.clientY - g.y) * m);
|
||||
});
|
||||
const end = (e) => { if (g && e.pointerId === g.id) { g = null; b.classList.remove("on"); } };
|
||||
b.addEventListener("pointerup", end);
|
||||
b.addEventListener("pointercancel", end);
|
||||
}
|
||||
function flash(text) { flashText = text; flashUntil = performance.now() + 2600; dirty = true; setTimeout(() => { dirty = true; }, 2700); }
|
||||
|
||||
// ---------- the ? : the whole how-to, out of the way until asked for ----------
|
||||
function buildHelp() {
|
||||
help.innerHTML = "";
|
||||
const h = el("div", "acm-help-h", { text: "How to steer" });
|
||||
const x = el("button", "acm-help-x", { text: "×", "aria-label": "Close" });
|
||||
x.onclick = () => openHelp(false);
|
||||
h.append(x);
|
||||
const dl = el("dl");
|
||||
const rows = [
|
||||
["Picture", "Drag to turn the camera round. Pinch or scroll to pull back or push in; two fingers or Shift pan. Tap a spot to circle round it."],
|
||||
["Top right", "Drag the axis ball to turn, or tap an axis to look from that side. Drag the magnifier to zoom and the hand to pan. The camera puts you back on your own shot."],
|
||||
["Keys", "Click the time bar to put a key there, or drag the time bar and move the camera. ◆ adds or removes a key, ◀ ▶ jump between keys. Drag a key along the bar to change its time."],
|
||||
["Play", "⏮ goes back to the start, ▶ plays, and the loop button plays it round and round."],
|
||||
["Mouse", "Like Blender: middle-drag turns, Shift pans, Ctrl zooms, the wheel zooms. Numpad 4 6 8 2 turn, + − zoom, 1 3 7 front, right, top, 0 your own shot. Space plays, Home goes to the start."],
|
||||
["Pink", "What the camera never saw. The CrossView-Warp LoRA paints it in."],
|
||||
];
|
||||
for (const [k, v] of rows) dl.append(el("dt", "", { text: k }), el("dd", "", { text: v }));
|
||||
help.append(h, dl);
|
||||
}
|
||||
function openHelp(open) { if (open) buildHelp(); help.hidden = !open; helpBtn.setAttribute("aria-expanded", String(open)); }
|
||||
helpBtn.addEventListener("pointerdown", (e) => e.stopPropagation());
|
||||
helpBtn.onclick = (e) => { e.stopPropagation(); openHelp(help.hidden); };
|
||||
const closeHelp = (e) => { if (!help.hidden && !help.contains(e.target) && !helpBtn.contains(e.target)) openHelp(false); };
|
||||
document.addEventListener("pointerdown", closeHelp, true);
|
||||
|
||||
// ---------- the time bar ----------
|
||||
let keyEls = [];
|
||||
function drawTrack() {
|
||||
for (const k of keyEls) k.remove();
|
||||
keyEls = [];
|
||||
for (const k of keys) {
|
||||
const d = el("div", `acm-key${Math.abs(k.t - p) < SAME_KEY ? " on" : ""}`);
|
||||
d.style.left = `${k.t * 100}%`;
|
||||
inner.insertBefore(d, head);
|
||||
keyEls.push(d);
|
||||
}
|
||||
head.style.left = `${p * 100}%`;
|
||||
const count = info?.count ?? 0;
|
||||
time.textContent = count ? `${Math.round(p * (count - 1)) + 1} / ${count}` : `${Math.round(p * 100)}%`;
|
||||
// the diamond is filled while the time bar sits on a key, hollow when it does not
|
||||
const on = keyAt(keys, p) >= 0;
|
||||
toggleKey.classList.toggle("on", on);
|
||||
const tipText = !on ? "Add a key here" : keys.length > 1 ? "Remove this key" : "The last key stays";
|
||||
toggleKey.dataset.tip = tipText; toggleKey.setAttribute("aria-label", tipText);
|
||||
toggleKey.disabled = on && keys.length < 2;
|
||||
prevKey.disabled = !keys.some((k) => k.t < p - SAME_KEY);
|
||||
nextKey.disabled = !keys.some((k) => k.t > p + SAME_KEY);
|
||||
}
|
||||
(() => {
|
||||
let drag = null;
|
||||
const tAt = (e) => { const r = inner.getBoundingClientRect(); return clamp((e.clientX - r.left) / (r.width || 1), 0, 1); };
|
||||
const set = (e) => { let t = tAt(e); for (const k of keys) if (Math.abs(k.t - t) < 0.03) t = k.t; p = t; dirty = true; };
|
||||
track.addEventListener("pointerdown", (e) => {
|
||||
if (e.button !== 0) return;
|
||||
e.stopPropagation();
|
||||
track.setPointerCapture(e.pointerId); stopPlay();
|
||||
const r = inner.getBoundingClientRect();
|
||||
let hit = null, best = 11; // press on a key to grab it; anywhere else moves the time bar
|
||||
for (const k of keys) { const d = Math.abs(r.left + k.t * r.width - e.clientX); if (d < best) { best = d; hit = k; } }
|
||||
drag = { key: hit, x: e.clientX, moved: false };
|
||||
if (hit) { p = hit.t; dirty = true; } else set(e);
|
||||
});
|
||||
track.addEventListener("pointermove", (e) => {
|
||||
if (!drag) return;
|
||||
if (!drag.key) { if (Math.abs(e.clientX - drag.x) >= 4) drag.moved = true; set(e); return; }
|
||||
if (!drag.moved && Math.abs(e.clientX - drag.x) < 4) return;
|
||||
drag.moved = true; // a key slides between its neighbours and never jumps over one
|
||||
const i = keys.indexOf(drag.key), lo = i > 0 ? keys[i - 1].t + 0.02 : 0, hi = i < keys.length - 1 ? keys[i + 1].t - 0.02 : 1;
|
||||
drag.key.t = clamp(tAt(e), lo, hi); p = drag.key.t;
|
||||
writeSoon();
|
||||
});
|
||||
// A click on an empty spot of the bar puts a key there; a drag only moves the time bar.
|
||||
const end = (e) => {
|
||||
if (drag && !drag.key && !drag.moved && e.type === "pointerup" && keyAt(keys, p) < 0) setCam(camAt(keys, p));
|
||||
drag = null;
|
||||
};
|
||||
track.addEventListener("pointerup", end);
|
||||
track.addEventListener("pointercancel", end);
|
||||
})();
|
||||
const playLabel = (on) => { play.textContent = on ? "❚❚" : "▶"; play.dataset.tip = on ? "Pause" : "Play"; play.setAttribute("aria-label", play.dataset.tip); };
|
||||
function stopPlay() { if (playing) { playing = false; playLabel(false); } }
|
||||
play.onclick = () => {
|
||||
if (playing) { stopPlay(); return; }
|
||||
if (p >= 0.999) p = 0;
|
||||
playing = true; lastT = performance.now(); playLabel(true);
|
||||
};
|
||||
loop.onclick = () => {
|
||||
looping = !looping;
|
||||
loop.setAttribute("aria-pressed", String(looping));
|
||||
loop.dataset.tip = looping ? "Looping: click to play once" : "Play on a loop";
|
||||
loop.setAttribute("aria-label", loop.dataset.tip);
|
||||
};
|
||||
const toStart = () => { p = 0; lastT = performance.now(); dirty = true; }; // playing carries on from the start
|
||||
toStartBtn.onclick = toStart;
|
||||
toggleKey.onclick = () => { // add a key at the time bar, or remove the one it sits on
|
||||
stopPlay();
|
||||
const i = keyAt(keys, p);
|
||||
if (i < 0) setCam(camAt(keys, p));
|
||||
else if (keys.length > 1) { keys.splice(i, 1); writeSoon(); }
|
||||
};
|
||||
const jump = (dir) => {
|
||||
stopPlay();
|
||||
const k = dir < 0 ? [...keys].reverse().find((x) => x.t < p - SAME_KEY) : keys.find((x) => x.t > p + SAME_KEY);
|
||||
if (k) { p = k.t; dirty = true; }
|
||||
};
|
||||
prevKey.onclick = () => jump(-1);
|
||||
nextKey.onclick = () => jump(1);
|
||||
reset.onclick = () => {
|
||||
stopPlay();
|
||||
keys.length = 0; keys.push({ t: 0, ...K0 });
|
||||
pivotSpec = null; resolvePivot(); p = 0;
|
||||
writeSoon();
|
||||
};
|
||||
for (const b of [play, prevKey, toggleKey, nextKey, reset]) b.addEventListener("pointerdown", (e) => e.stopPropagation());
|
||||
|
||||
// ---------- before there is a clip to look at ----------
|
||||
function drawEmpty() {
|
||||
const show = status !== "ready";
|
||||
empty.hidden = !show;
|
||||
if (!show) return;
|
||||
const key = `${status}|${statusNote}`;
|
||||
if (empty.dataset.key === key) return;
|
||||
empty.dataset.key = key;
|
||||
empty.innerHTML = "";
|
||||
if (status === "running") {
|
||||
empty.append(el("b", "", { text: "Reading the depth…" }), el("span", "", { text: "MoGe looks at every frame once. A long clip takes a while." }));
|
||||
return;
|
||||
}
|
||||
if (status === "loading") { empty.append(el("b", "", { text: "Loading your clip…" })); return; }
|
||||
const go = el("button", "acm-btn primary", { text: "Show my clip", "data-tip": "Runs this node and the depth before it, not the whole workflow" });
|
||||
go.addEventListener("pointerdown", (e) => e.stopPropagation());
|
||||
go.onclick = async (e) => {
|
||||
e.stopPropagation();
|
||||
status = "running"; statusNote = ""; dirty = true;
|
||||
let ok = false;
|
||||
try { ok = await opts.run(); } catch { ok = false; }
|
||||
if (!ok && status === "running") { status = "idle"; statusNote = "It did not run. Pick a clip in Load Video, and check MoGe Inference is connected."; dirty = true; }
|
||||
};
|
||||
empty.append(el("b", "", { text: "Steer the camera on your clip" }), el("span", "", { text: statusNote || "Run the depth once to see your first frame here." }), go);
|
||||
}
|
||||
|
||||
// ---------- loop ----------
|
||||
function frame(now) {
|
||||
if (!alive) return;
|
||||
requestAnimationFrame(frame);
|
||||
if (!root.isConnected) return;
|
||||
readCamera();
|
||||
if (playing) {
|
||||
const dur = Math.max(1, (info?.count ?? 121) / FPS);
|
||||
p += (now - lastT) / 1000 / dur; lastT = now; dirty = true;
|
||||
if (p >= 1) { if (looping) p %= 1; else { p = 1; stopPlay(); } }
|
||||
}
|
||||
flushWrite();
|
||||
if (!dirty) return;
|
||||
if (root.offsetParent === null && !root.getClientRects().length) return;
|
||||
dirty = false;
|
||||
const cam = camAt(keys, p);
|
||||
const want = nearestLoaded(p);
|
||||
// a new run's frames take over as they load; until then the last ones stay up
|
||||
if (want && want !== shown) shown = want;
|
||||
if (!info) shown = null;
|
||||
const fit = fitPicture();
|
||||
drawEmpty();
|
||||
renderPreview(cam, fit);
|
||||
drawGizmo(cam);
|
||||
renderOutside(cam);
|
||||
drawTrack();
|
||||
where.textContent = describe(cam);
|
||||
pink.textContent = shown ? `pink ${pinkPct.toFixed(0)}%` : "";
|
||||
const over = pastLoraRange(cam), fl = performance.now() < flashUntil;
|
||||
const warnText = fl ? flashText : over ? "Past the LoRA's range: it learned up to 45° of turn, 30° up and 20° down." : "";
|
||||
if (warn.textContent !== warnText) { warn.textContent = warnText; warn.dataset.tip = warnText; }
|
||||
if (!warnText) delete warn.dataset.tip;
|
||||
back.set(cam.back);
|
||||
}
|
||||
const resize = new ResizeObserver(() => { dirty = true; });
|
||||
resize.observe(stage);
|
||||
requestAnimationFrame(frame);
|
||||
|
||||
return {
|
||||
root,
|
||||
// What a run of the node sent back: the frames to look at.
|
||||
takeScene(payload) {
|
||||
if (!payload || !Array.isArray(payload.frames) || !payload.frames.length) return;
|
||||
info = payload;
|
||||
frames = payload.frames.map((entry) => ({ t: entry.t, entry, data: null }));
|
||||
shown = null;
|
||||
if (status !== "ready") status = "loading";
|
||||
resolvePivot();
|
||||
dirty = true;
|
||||
loadAll(payload);
|
||||
},
|
||||
runFailed(note) {
|
||||
if (status !== "running") return;
|
||||
status = "idle"; statusNote = note || "It did not run. Pick a clip in Load Video, and check MoGe Inference is connected."; dirty = true;
|
||||
},
|
||||
running() { if (status !== "ready") { status = "running"; dirty = true; } },
|
||||
refresh() { lastText = null; dirty = true; },
|
||||
get hasScene() { return Boolean(info); },
|
||||
// The least height the face needs: the picture's least, and the controls as they measure.
|
||||
floor() { return MIN_STAGE + (controls.offsetHeight || CONTROLS_HEIGHT); },
|
||||
destroy() {
|
||||
alive = false;
|
||||
resize.disconnect();
|
||||
window.removeEventListener("keydown", onKey, true);
|
||||
window.removeEventListener("keydown", onPlayKey, true);
|
||||
document.removeEventListener("pointerdown", closeHelp, true);
|
||||
hideTip();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
// Camera Move: the shot on the node, and on the box (subgraph node) that holds it.
|
||||
//
|
||||
// The face itself is face.mjs. This file mounts it, keeps it pointed at
|
||||
// wherever the camera keys are kept, runs the node alone when the face asks
|
||||
// for the clip, and hands it what a run sent back.
|
||||
//
|
||||
// Where the keys are kept:
|
||||
// - on the node, in its own `camera` setting;
|
||||
// - once `camera` is brought up to a box (a subgraph input linked to it),
|
||||
// in the box's own copy of the setting, one copy per box. The face then
|
||||
// sits on the box too, and the node inside shows that box's keys.
|
||||
|
||||
import { api } from "../../../scripts/api.js";
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange, showToast } from "../shared/index.mjs";
|
||||
import { executionIdOf, isSwitchedOff } from "../shared/graph_ids.mjs";
|
||||
import { SUBGRAPH_INPUT_ID, boxesOf, hostBox, workflowNodes } from "../shared/lora_box.mjs";
|
||||
import { WIDGET_FRAME, ensureNodeMinHeight, fillNodeHeight } from "../shared/panel_layout.mjs";
|
||||
import { hideWidget } from "../shared/widget_visibility.mjs";
|
||||
import { CONTROLS_HEIGHT, MIN_STAGE, MIN_WIDTH, mountCameraFace } from "./face.mjs";
|
||||
import { mountBoxCard } from "./box_card.mjs";
|
||||
import { CARD_WIDGET } from "../shared/widget_card.mjs";
|
||||
|
||||
const NODE_CLASS = "AUSBOSS_NODES_CameraMove";
|
||||
const CAMERA = "camera";
|
||||
const UI_KEY = "ausboss_camera_scene";
|
||||
const FACE_WIDGET = "ausboss_camera_move";
|
||||
const OPENING_WIDTH = 460;
|
||||
const OPENING_ROOM = 90; // a new node opens this much taller than its floor, so a wide clip fills the picture
|
||||
const MIN_HEIGHT = MIN_STAGE + CONTROLS_HEIGHT + WIDGET_FRAME;
|
||||
const mounts = new Set();
|
||||
|
||||
const rootGraph = () => app.rootGraph ?? app.graph;
|
||||
const isMove = (node) => node?.type === NODE_CLASS || node?.comfyClass === NODE_CLASS;
|
||||
const same = (a, b) => a != null && b != null && String(a) === String(b);
|
||||
const linkOf = (graph, id) => (id == null || !graph ? null : graph.getLink?.(id) ?? graph.links?.get?.(id) ?? graph.links?.[id] ?? null);
|
||||
const nodeOf = (graph, id) => graph?.getNodeById?.(id) ?? (graph?.nodes ?? graph?._nodes ?? []).find((node) => same(node?.id, id)) ?? null;
|
||||
const ownCamera = (node) => node?.widgets?.find((widget) => widget?.name === CAMERA) ?? null;
|
||||
const boxCopy = (box, name) => (box?.widgets ?? []).find((widget) => widget?.name === name && typeof widget.value === "string") ?? null;
|
||||
|
||||
// The subgraph input that brings a node's camera in from its box, or null.
|
||||
function cameraInputName(node) {
|
||||
const graph = node?.graph;
|
||||
const index = (node?.inputs ?? []).findIndex((input) => input?.name === CAMERA);
|
||||
if (!graph || index < 0) return null;
|
||||
const link = linkOf(graph, node.inputs[index].link);
|
||||
if (!link || !same(link.origin_id, SUBGRAPH_INPUT_ID)) return null;
|
||||
return graph.inputs?.[link.origin_slot]?.name ?? null;
|
||||
}
|
||||
|
||||
// The first Camera Move inside a box whose camera comes up to the box: { name, inner }.
|
||||
function boxCamera(box) {
|
||||
const subgraph = box?.subgraph;
|
||||
for (const input of subgraph?.inputs ?? []) {
|
||||
for (const id of input?.linkIds ?? []) {
|
||||
const link = linkOf(subgraph, id);
|
||||
const inner = link && nodeOf(subgraph, link.target_id);
|
||||
if (isMove(inner) && inner.inputs?.[link.target_slot]?.name === CAMERA) return { name: input.name, inner };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Where a face reads and writes the keys, and which run of the node it shows.
|
||||
function sourceOf(mount) {
|
||||
const root = rootGraph();
|
||||
if (mount.box) {
|
||||
const widget = boxCopy(mount.box, mount.inputName);
|
||||
if (widget) hideWidget(widget);
|
||||
const at = executionIdOf(root, mount.box);
|
||||
return { widget, id: at ? `${at}:${mount.inner.id}` : null, holder: mount.box };
|
||||
}
|
||||
const node = mount.inner;
|
||||
const fed = cameraInputName(node);
|
||||
if (fed) {
|
||||
const box = hostBox(node.graph, boxesOf(node.graph, workflowNodes(root)), null);
|
||||
const widget = box && boxCopy(box, fed);
|
||||
const at = box && executionIdOf(root, box);
|
||||
if (widget) return { widget, id: at ? `${at}:${node.id}` : executionIdOf(root, node), holder: box };
|
||||
}
|
||||
return { widget: ownCamera(node), id: executionIdOf(root, node), holder: node };
|
||||
}
|
||||
|
||||
const viewRoute = (file) => `/view?${new URLSearchParams({ filename: file.filename, type: file.type || "temp", subfolder: file.subfolder || "" })}`;
|
||||
const viewUrl = (file) => api.apiURL(viewRoute(file));
|
||||
// The depth picture's exact bytes, through ComfyUI's own request helper.
|
||||
const viewBlob = async (file) => {
|
||||
const response = await api.fetchApi(viewRoute(file));
|
||||
if (!response.ok) throw new Error(`depth ${response.status}`);
|
||||
return response.blob();
|
||||
};
|
||||
|
||||
function locatorOf(node) {
|
||||
const graph = node?.graph;
|
||||
if (!graph || node.id == null) return null;
|
||||
const root = graph.rootGraph ?? graph;
|
||||
return graph !== root && graph.id ? `${graph.id}:${node.id}` : String(node.id);
|
||||
}
|
||||
|
||||
function restore(mount) {
|
||||
if (mount.face.hasScene) return;
|
||||
const scene = app.nodeOutputs?.[locatorOf(mount.inner)]?.[UI_KEY]?.[0];
|
||||
if (scene) mount.face.takeScene(scene);
|
||||
}
|
||||
|
||||
function mount(host, { box = null, inputName = null, inner = host } = {}) {
|
||||
const entry = { host, box, inputName, inner, face: null, widget: null };
|
||||
const face = mountCameraFace({
|
||||
read: () => String(sourceOf(entry).widget?.value ?? ""),
|
||||
write: (text) => {
|
||||
const widget = sourceOf(entry).widget;
|
||||
if (!widget) return;
|
||||
widget.value = text;
|
||||
app.canvas?.setDirty?.(true, false);
|
||||
notifyAusbossChange();
|
||||
},
|
||||
view: viewUrl,
|
||||
blob: viewBlob,
|
||||
run: async () => {
|
||||
const { id, holder } = sourceOf(entry);
|
||||
if (!id || typeof app.queuePrompt !== "function") return false;
|
||||
if (isSwitchedOff(rootGraph(), holder) || isSwitchedOff(rootGraph(), inner)) {
|
||||
showToast({ severity: "warn", summary: "Camera Move", detail: "This node is switched off (bypassed or muted), so it cannot run." });
|
||||
return false;
|
||||
}
|
||||
entry.askedAt = performance.now();
|
||||
// At the front of the queue: the clip shows up once the job running now is done.
|
||||
const queued = await app.queuePrompt(-1, 1, [id]);
|
||||
// Refused: an empty loader, a missing link, or a check that stopped it (it says why in a note).
|
||||
// Nothing was queued, so the face must not wait for a picture that never comes.
|
||||
if (queued === false) return false;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
entry.face = face;
|
||||
const widget = host.addDOMWidget(box ? `${FACE_WIDGET}:${inputName}` : FACE_WIDGET, FACE_WIDGET, face.root, { serialize: false, hideOnZoom: false });
|
||||
keepDomWidgetWidthAuto(widget);
|
||||
// Never saved with the workflow: options.serialize only keeps it out of the prompt.
|
||||
widget.serialize = false;
|
||||
// The floor follows the controls as they measure on this screen (fonts differ between phones).
|
||||
fillNodeHeight(widget, { minWidth: MIN_WIDTH, minHeight: () => face.floor() + WIDGET_FRAME, minNodeSize: [MIN_WIDTH, MIN_HEIGHT], exactMinWidth: true });
|
||||
entry.widget = widget;
|
||||
mounts.add(entry);
|
||||
restore(entry);
|
||||
holdFloor(host);
|
||||
return entry;
|
||||
}
|
||||
|
||||
// A node or box kept shorter than the face needs (a saved size, a font that
|
||||
// runs taller on this screen) would cut the controls off at its bottom edge.
|
||||
function holdFloor(host) {
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => {
|
||||
if (ensureNodeMinHeight(host)) host.setDirtyCanvas?.(true, true);
|
||||
}));
|
||||
}
|
||||
|
||||
function unmount(entry) {
|
||||
mounts.delete(entry);
|
||||
entry.face.destroy();
|
||||
try { entry.host.removeWidget?.(entry.widget); } catch { entry.widget?.onRemove?.(); }
|
||||
}
|
||||
|
||||
// A new node or box opens with room for the picture; a saved size wins.
|
||||
function openRoomy(host) {
|
||||
const floor = Number(host.computeSize?.()?.[1]);
|
||||
if (!Number.isFinite(floor) || host.size?.[1] > floor + 40) return;
|
||||
host.setSize?.([Math.max(host.size?.[0] ?? 0, OPENING_WIDTH), floor + OPENING_ROOM]);
|
||||
}
|
||||
|
||||
function build(node) {
|
||||
if (node.__ausbossCameraMove) return node.__ausbossCameraMove;
|
||||
hideWidget(ownCamera(node));
|
||||
node.__ausbossCameraMove = mount(node);
|
||||
return node.__ausbossCameraMove;
|
||||
}
|
||||
|
||||
// The settings card and any LoRA rows sit on top; the shot comes last and
|
||||
// takes the rest of the box, so its buttons stay on the bottom edge.
|
||||
function faceLast(box) {
|
||||
// A box makes `widgets` afresh on every read (its settings, then the panels
|
||||
// added to it), so the panels are put in order in their own list: any other
|
||||
// panel (a LoRA Loader's rows), the settings card, then the face. Nodes 2.0
|
||||
// lays them out in the order they were made, which is the same.
|
||||
const widgets = Array.isArray(box._extraWidgets) ? box._extraWidgets : box.widgets ?? [];
|
||||
const order = [widgets.find((w) => w?.name === CARD_WIDGET), box.__ausbossCameraBox?.widget].filter(Boolean);
|
||||
const want = [...widgets.filter((w) => !order.includes(w)), ...order];
|
||||
if (want.every((w, i) => widgets[i] === w)) return false;
|
||||
widgets.splice(0, widgets.length, ...want);
|
||||
box.setDirtyCanvas?.(true, true);
|
||||
return true;
|
||||
}
|
||||
|
||||
// A box row reads its options from the widget inside. A node with a card
|
||||
// (Image Resize) hides its own rows by setting options.hidden there, and
|
||||
// Nodes 2.0 would then hide the box's row too. The box keeps every setting
|
||||
// brought up to it in view, except the camera text the face stands in for.
|
||||
const SHOWN = new WeakMap();
|
||||
function shownOptions(options) {
|
||||
if (!options || typeof options !== "object" || !options.hidden) return options;
|
||||
let view = SHOWN.get(options);
|
||||
if (!view) {
|
||||
view = new Proxy(options, { get: (target, key) => (key === "hidden" ? false : Reflect.get(target, key)) });
|
||||
SHOWN.set(options, view);
|
||||
}
|
||||
return view;
|
||||
}
|
||||
|
||||
function showSettings(box, keep) {
|
||||
for (const widget of box.widgets ?? []) {
|
||||
if (widget === keep || widget.__ausbossCameraShown || !widget.options?.hidden) continue;
|
||||
const own = Object.getOwnPropertyDescriptor(widget, "options");
|
||||
if (!own?.get || !own.configurable || widget.__ausbossVisibilityStash) continue;
|
||||
Object.defineProperty(widget, "options", { ...own, get() { return shownOptions(own.get.call(this)); } });
|
||||
widget.__ausbossCameraShown = true;
|
||||
}
|
||||
}
|
||||
|
||||
// A box shows the face while the camera of a Camera Move inside comes up to it.
|
||||
function syncBox(box) {
|
||||
if (!box?.isSubgraphNode?.() || !box.graph) return;
|
||||
const found = boxCamera(box);
|
||||
const have = box.__ausbossCameraBox;
|
||||
if (have && (!found || have.inner !== found.inner || have.inputName !== found.name || !boxCopy(box, found.name))) {
|
||||
unmount(have);
|
||||
box.__ausbossCameraBox = null;
|
||||
box.setSize?.([box.size[0], box.computeSize?.()[1] ?? box.size[1]]);
|
||||
}
|
||||
if (box.__ausbossCameraBox) {
|
||||
if (mountBoxCard(box, boxCopy(box, box.__ausbossCameraBox.inputName), faceLast)) holdFloor(box);
|
||||
faceLast(box);
|
||||
showSettings(box, boxCopy(box, box.__ausbossCameraBox.inputName));
|
||||
return;
|
||||
}
|
||||
if (!found || !boxCopy(box, found.name)) return;
|
||||
hideWidget(boxCopy(box, found.name));
|
||||
// The card before the face: Nodes 2.0 lays a box's panels out in the order they were made.
|
||||
mountBoxCard(box, boxCopy(box, found.name), faceLast);
|
||||
box.__ausbossCameraBox = mount(box, { box, inputName: found.name, inner: found.inner });
|
||||
faceLast(box);
|
||||
showSettings(box, boxCopy(box, found.name));
|
||||
if (!box.__ausbossCameraSized) openRoomy(box);
|
||||
box.__ausbossCameraSized = true;
|
||||
box.setDirtyCanvas?.(true, true);
|
||||
}
|
||||
|
||||
function watchBox(box) {
|
||||
if (!box?.isSubgraphNode?.() || box.__ausbossCameraWatch) return;
|
||||
const abort = new AbortController();
|
||||
box.__ausbossCameraWatch = abort;
|
||||
const later = () => requestAnimationFrame(() => syncBox(box));
|
||||
for (const type of ["widget-promoted", "widget-demoted", "input-added", "removing-input"]) {
|
||||
box.subgraph?.events?.addEventListener?.(type, later, { signal: abort.signal });
|
||||
}
|
||||
chainCallback(box, "onConfigure", (info) => { if (info?.size) box.__ausbossCameraSized = true; later(); holdFloor(box); });
|
||||
chainCallback(box, "onRemoved", () => {
|
||||
abort.abort();
|
||||
if (box.__ausbossCameraBox) unmount(box.__ausbossCameraBox);
|
||||
box.__ausbossCameraBox = null;
|
||||
});
|
||||
later();
|
||||
}
|
||||
|
||||
// What a run sent back reaches every face that shows that run of the node.
|
||||
api.addEventListener("executed", ({ detail }) => {
|
||||
try {
|
||||
const scene = detail?.output?.[UI_KEY]?.[0];
|
||||
if (!scene) return;
|
||||
const ids = new Set([String(detail.node ?? ""), String(detail.display_node ?? "")]);
|
||||
for (const entry of mounts) if (ids.has(String(sourceOf(entry).id))) entry.face.takeScene(scene);
|
||||
} catch {
|
||||
// Never in the way of a run.
|
||||
}
|
||||
});
|
||||
const stopped = (note) => { for (const entry of mounts) entry.face.runFailed(note); };
|
||||
api.addEventListener("execution_error", ({ detail }) => {
|
||||
if (/OutOfMemory/i.test(String(detail?.exception_type ?? ""))) {
|
||||
stopped("The graphics card is full. Close other jobs using it, then try again.");
|
||||
return;
|
||||
}
|
||||
const why = String(detail?.exception_message ?? "").split("\n")[0].slice(0, 160);
|
||||
stopped(why ? `The run stopped: ${why}` : null);
|
||||
});
|
||||
api.addEventListener("execution_interrupted", () => stopped("The run was stopped."));
|
||||
// A run that ended without sending the clip (it never reached the node)
|
||||
// would leave a face waiting for good. Once the queue is empty, it stops.
|
||||
api.addEventListener("status", ({ detail }) => {
|
||||
if (detail?.exec_info?.queue_remaining !== 0) return;
|
||||
const now = performance.now();
|
||||
for (const entry of mounts) if (now - (entry.askedAt ?? 0) > 1500) entry.face.runFailed();
|
||||
});
|
||||
|
||||
app.registerExtension({
|
||||
name: "ausboss.camera_move",
|
||||
onNodeOutputsUpdated() {
|
||||
for (const entry of mounts) restore(entry);
|
||||
},
|
||||
nodeCreated(node) {
|
||||
if (node?.isSubgraphNode?.()) watchBox(node);
|
||||
},
|
||||
loadedGraphNode(node) {
|
||||
if (node?.isSubgraphNode?.()) watchBox(node);
|
||||
},
|
||||
beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData?.name !== NODE_CLASS) return;
|
||||
chainCallback(nodeType.prototype, "onNodeCreated", function () {
|
||||
build(this);
|
||||
});
|
||||
chainCallback(nodeType.prototype, "onAdded", function () {
|
||||
if (this.__ausbossCameraSized) return;
|
||||
this.__ausbossCameraSized = true;
|
||||
openRoomy(this);
|
||||
});
|
||||
chainCallback(nodeType.prototype, "onConfigure", function (info) {
|
||||
if (info?.size) this.__ausbossCameraSized = true;
|
||||
const entry = build(this);
|
||||
hideWidget(ownCamera(this));
|
||||
queueMicrotask(() => { entry.face.refresh(); restore(entry); });
|
||||
holdFloor(this);
|
||||
});
|
||||
chainCallback(nodeType.prototype, "onConnectionsChange", function () {
|
||||
this.__ausbossCameraMove?.face.refresh();
|
||||
// The camera may have just come up to a box, or gone back inside.
|
||||
for (const box of boxesOf(this.graph, workflowNodes(rootGraph()))) requestAnimationFrame(() => syncBox(box));
|
||||
});
|
||||
chainCallback(nodeType.prototype, "onRemoved", function () {
|
||||
const entry = this.__ausbossCameraMove;
|
||||
if (entry) unmount(entry);
|
||||
this.__ausbossCameraMove = null;
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -5,7 +5,7 @@
|
||||
// zooming stopped over Compare, the crop previews, the video viewers and every
|
||||
// control on a card. One listener here hands those gestures back, the same way
|
||||
// ComfyUI does for its own text boxes. A panel that wants the wheel for itself
|
||||
// (a scrolling list, a long text box) keeps it while it can still scroll.
|
||||
// (a scrolling list, a focused text field, an editor) still keeps it.
|
||||
//
|
||||
// A file dragged in from the desktop, or a picture's card from the Assets
|
||||
// panel, has the same problem in the classic renderer: dropped on a node's
|
||||
@@ -31,7 +31,7 @@ function onWheel(event) {
|
||||
const root = panelRoot(target);
|
||||
const lgCanvas = canvas();
|
||||
if (!root || !lgCanvas || event.defaultPrevented) return;
|
||||
if (panelKeepsWheel(target, event, { root, host: panelHost(target), styleOf: (el) => getComputedStyle(el) })) return;
|
||||
if (panelKeepsWheel(target, event, { root, host: panelHost(target), styleOf: (el) => getComputedStyle(el), activeElement: document.activeElement })) return;
|
||||
event.preventDefault();
|
||||
lgCanvas.processMouseWheel(event);
|
||||
}
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
// Clear VRAM 🆎 — a right-click entry on the empty canvas that unloads every
|
||||
// model and frees memory on the ComfyUI server this page is connected to.
|
||||
//
|
||||
// It sends the same request as ComfyUI's own "Unload Models and Execution
|
||||
// Cache" command (top menu, Edit): POST /free with unload_models and
|
||||
// free_memory. That command is not on the right-click menu, so this entry
|
||||
// puts it one click away. A setting hides the entry; a ComfyUI that turns
|
||||
// manual unloading off (Comfy.Memory.AllowManualUnload) hides it too.
|
||||
import { api } from "../../../scripts/api.js";
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { showToast } from "../shared/index.mjs";
|
||||
|
||||
const SETTING_ID = "AusBoss.Memory.ClearVramMenu";
|
||||
const MENU_LABEL = "Clear VRAM 🆎";
|
||||
|
||||
function setting(id) {
|
||||
return app.ui?.settings?.getSettingValue?.(id);
|
||||
}
|
||||
|
||||
async function clearVram() {
|
||||
try {
|
||||
const response = await api.fetchApi("/free", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ unload_models: true, free_memory: true }),
|
||||
});
|
||||
if (!response.ok) throw new Error(`the server answered ${response.status}`);
|
||||
showToast({ severity: "success", summary: MENU_LABEL, detail: "Models unloaded and memory freed.", life: 3000 });
|
||||
} catch (error) {
|
||||
showToast({ severity: "error", summary: MENU_LABEL, detail: `Could not clear VRAM: ${error?.message ?? error}` });
|
||||
}
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "ausboss.clear.vram",
|
||||
settings: [
|
||||
{
|
||||
id: SETTING_ID,
|
||||
name: "Clear VRAM on the right-click menu",
|
||||
type: "boolean",
|
||||
defaultValue: true,
|
||||
category: ["🆎 AusBoss", "Memory", "Clear VRAM menu"],
|
||||
tooltip:
|
||||
"Right-click the empty canvas for Clear VRAM: it unloads every model and frees "
|
||||
+ "memory on the ComfyUI server. Off hides the entry.",
|
||||
},
|
||||
],
|
||||
getCanvasMenuItems() {
|
||||
if (setting(SETTING_ID) === false) return [];
|
||||
if (setting("Comfy.Memory.AllowManualUnload") === false) return [];
|
||||
return [{ content: MENU_LABEL, callback: clearVram }];
|
||||
},
|
||||
});
|
||||
+1
-2
@@ -463,9 +463,8 @@ app.registerExtension({
|
||||
]);
|
||||
});
|
||||
chainCallback(nodeType.prototype, "onConfigure", function () {
|
||||
const state = this.__ausbossCompare;
|
||||
queueMicrotask(() => {
|
||||
if (!state || this.__ausbossCompare !== state || state.abort.signal.aborted) return;
|
||||
const state = buildPanel(this);
|
||||
state.showingB = this.properties?.ausboss_compare_side === "B";
|
||||
syncErase(state);
|
||||
// The saved paint, if the pictures are already up.
|
||||
|
||||
@@ -15,38 +15,7 @@ Right-click the Callout and choose **Title tile** to give your existing text a b
|
||||
- Double-click a title to edit it. **Save** or `Ctrl+Enter` keeps the change; **Cancel** or `Esc` leaves the original text.
|
||||
- Drag the visible bottom-right grip to resize. You can also focus the grip and use arrow keys; hold **Shift** for smaller changes. Resizing keeps the tile in place and supports Undo.
|
||||
|
||||
## Info card
|
||||
|
||||
A small card for facts people look up: run times, settings, what each choice
|
||||
does. Right-click the Callout and choose **Info card**. An empty note starts
|
||||
with sample text that shows each part.
|
||||
|
||||
Write it like this:
|
||||
|
||||
```text
|
||||
⏱️ Too slow?
|
||||
###### Redraw time on an RTX 5090. Smaller cards take longer.
|
||||
|
||||
2x, 18 steps | ~4 min
|
||||
2x, 10 steps | ~3 min
|
||||
1.5x, 18 steps | ~2.5 min
|
||||
**1.5x, 10 steps (default) | ~2 min**
|
||||
|
||||
###### 1.5x is a 4608-wide sheet, 2x is 6144.
|
||||
```
|
||||
|
||||
- The first line is the card's title. Start it with ⏱️ ℹ️ ⚠️ 💡 or ✅ and
|
||||
that emoji is drawn as a small icon.
|
||||
- A line with a `|` in it is a row: the words before the `|` on the left,
|
||||
the rest on the right.
|
||||
- Put the whole row in two stars, `**like this | value**`, and it is drawn
|
||||
in teal. Use it for the default or the one to pick.
|
||||
- Small print (the **Small** button) is a grey line, for a subtitle or a note
|
||||
at the bottom.
|
||||
- A blank line leaves a gap. Arrows and links work as in any callout.
|
||||
- Double-click the card to edit it. Choose **Plain callout** to turn it back
|
||||
into a note; the text stays.
|
||||
|
||||
## Writing
|
||||
|
||||
- On a plain callout, double-click the note, or press **Edit**, to type. Click outside the box to
|
||||
keep the text. **Esc** drops what you typed.
|
||||
@@ -121,13 +90,5 @@ In the text a link is written `[the words](https://example.com)`, or
|
||||
it to read the address before you click.
|
||||
- An older version of the pack shows a link as typed, brackets and address
|
||||
included, so the address can still be read and copied there.
|
||||
- An Info card is saved as an ordinary Callout with the text you typed.
|
||||
The card look is a setting on the node, so an older version of the pack
|
||||
shows the same text as a plain note, rows written out as `label | value`.
|
||||
A plain callout never reads `|` as a row, so notes written before look
|
||||
the same.
|
||||
- A row splits at its first `|` that is not inside a link. A row pasted
|
||||
from a Markdown table loses its outer pipes, and the table's `---` line
|
||||
is skipped. An Info card's text grows with the card, up to 20 px.
|
||||
- The font is IBM Plex Sans when the computer has it, otherwise the system
|
||||
font. The node loads no fonts and makes no network requests.
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
# Camera Move
|
||||
|
||||
Moves the camera of your clip. You steer it on the node's picture, the way
|
||||
you turn a model in a 3D viewer, and set keys on the time bar. What the old
|
||||
camera never saw comes out pink, and the CrossView-Warp LoRA for MiniMax H3
|
||||
paints it in.
|
||||
|
||||
## How to use it
|
||||
|
||||
1. Load your clip, scale it to the size you will render, and run it through
|
||||
**Load MoGe Model** and **MoGe Inference** (core ComfyUI nodes).
|
||||
2. Connect MoGe Inference's geometry to Camera Move.
|
||||
3. Press **Show my clip** on the node. It runs the depth once and shows your
|
||||
first frame.
|
||||
4. Steer:
|
||||
- Drag the picture to turn the camera round.
|
||||
- Pinch or scroll to pull back or push in. Two fingers, or Shift-drag, pan.
|
||||
- Tap a spot to circle round it.
|
||||
- Top right: drag the axis ball to turn, or tap an axis to look from that
|
||||
side. Drag the magnifier to zoom and the hand to pan. The camera button
|
||||
puts you back on your own shot.
|
||||
5. Keys: click the time bar to put a key there, using the camera at that
|
||||
moment. Or drag the time bar, then move the camera, and a key appears
|
||||
there. The diamond adds or removes a key; the arrows either side jump
|
||||
between keys. Drag a key along the bar to change its time.
|
||||
⏮ goes back to the start, ▶ plays, and the loop button plays it round
|
||||
and round.
|
||||
6. Run the workflow. `guide` goes to the H3 guide at frame 0.
|
||||
|
||||
The keys move the camera from where your clip's own camera was. If your
|
||||
clip's camera already moves (walks down an aisle, for example), that move
|
||||
stays, and your keys add to it. After the last key the camera holds that
|
||||
turn, but it still travels along with your clip.
|
||||
|
||||
The line under the picture turns amber when a key goes past where the LoRA
|
||||
was trained: 45° of turn, 30° up, 20° down. Past that it may leave pink.
|
||||
|
||||
### Mouse and keys (like Blender)
|
||||
|
||||
Middle-drag turns, Shift + middle-drag pans, Ctrl + middle-drag zooms, and
|
||||
the wheel zooms. On the numpad: 4 6 8 2 turn, Ctrl with them pans, + and −
|
||||
zoom, 1 is the front, 3 the right side (Ctrl: left), 7 the top (Ctrl:
|
||||
bottom), 0 your own shot. Space plays and pauses and Home goes back to the
|
||||
start, while the pointer is over the node.
|
||||
|
||||
The wheel over the picture zooms the camera, not the graph. Everywhere else
|
||||
on the node it zooms the graph as usual.
|
||||
|
||||
## Inputs and outputs
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `moge_geometry` | Depth from MoGe Inference, one per frame. |
|
||||
| `camera` | The keys, written by the node's picture. You never type here. |
|
||||
| `guide` | Your clip from the moved camera, pink where nothing was seen. |
|
||||
| `holes` | White where the guide is pink. |
|
||||
|
||||
## Technical details
|
||||
|
||||
- Each key holds a moment `t` (0 to 1 over the clip), a turn `az` and a rise
|
||||
`el` in degrees, `back` (how far the camera pulls back, in distances to the
|
||||
pivot; below 0 pushes in), and a pan `px`, `py` (same unit). The camera
|
||||
passes through each key without slowing down, and only eases at the first
|
||||
and last key. Each value follows a monotone cubic through the keys
|
||||
(Fritsch-Butland slopes), so it never runs past a key: a value that turns
|
||||
back or holds at a key stops there.
|
||||
- The camera turns round the pivot: a spot you tap (saved as a place on one
|
||||
frame, `pivot: {u, v, t}`) or, by default, the nearest fifth of what sits in
|
||||
the middle of the first frame, never further than 3 m.
|
||||
- `R = Ry(-az) · Rx(-el)`, `C = pivot − R·pivot + R·[px·d, py·d, −back·d]`
|
||||
with `d = |pivot|`, in OpenCV axes (x right, y down, z forward).
|
||||
- MoGe's depth scale and lens wobble from frame to frame, which shook the
|
||||
moved picture. Every frame is scaled so its median depth follows a
|
||||
smoothed line (15 frames wide) through all of them, and every frame uses
|
||||
the clip's median lens.
|
||||
- Each pixel is drawn as 4 points, nearest wins, and gaps mostly surrounded
|
||||
by picture (5 of 8 neighbours, two passes) are filled. Everything else
|
||||
stays magenta (1, 0, 1).
|
||||
- The node is an output node so its picture can run it on its own. Each run
|
||||
writes up to 61 small frames (416 px on the long side) with their depth to
|
||||
ComfyUI's temp folder; the depth is a PNG with a log scale in red (high
|
||||
byte) and green (low byte), 0 for no depth.
|
||||
@@ -110,7 +110,7 @@ parts back.
|
||||
|
||||
## Technical details
|
||||
|
||||
- Starting values: Context `1.2`, Blend `16` px, Multiple `32`; Grow, Blur,
|
||||
- Starting values: Context `1.2`, Blend `16` px, Multiple `8`; Grow, Blur,
|
||||
Extra context, the Target rows and the Extend rows start at `0`.
|
||||
- With no Target size set, the crop is still rounded up to **Multiple**, so
|
||||
with **Stay in picture** on it can still reach a few pixels (at most
|
||||
|
||||
@@ -1,142 +0,0 @@
|
||||
# Edit Lock
|
||||
|
||||
Keeps every part of your picture that an edit did not change exactly where
|
||||
it was, with the colors it had.
|
||||
|
||||
An edit model redraws the whole picture, also the parts you did not ask it
|
||||
to change. Those parts often come back a little zoomed in, shifted or
|
||||
tinted. Flip between the original and the edit and the whole picture
|
||||
jumps. Edit Lock stops that: only the edit is new.
|
||||
|
||||
It needs no mask. It sees what the edit changes while the picture is being
|
||||
made, and holds on to everything else.
|
||||
|
||||
## Quick start
|
||||
|
||||
1. Put **Edit Lock 🆎** between the model and the sampler: the model (after
|
||||
any LoRA loader) goes in, and its `model` output goes to the sampler or
|
||||
guider.
|
||||
2. Wire the VAE into `vae` and the picture you are editing into `image`.
|
||||
Use the same picture the edit model gets, at the size of the result.
|
||||
3. After the VAE Decode, add **Edit Lock Restore 🆎**. Wire the decoded
|
||||
picture into `image` and Edit Lock's `edit_lock` output into
|
||||
`edit_lock`. This puts your own pixels back in the untouched parts.
|
||||
4. Wire Restore's `report` into **Show Text 🆎** to read how much was kept.
|
||||
|
||||
Run your edit as usual. Prompt, steps and seed stay as they were.
|
||||
|
||||
## What it does with each kind of edit
|
||||
|
||||
- **A local edit** (add glasses, repaint the car, change the sign): the
|
||||
edit happens, and the rest of the picture stays put.
|
||||
- **An edit of the whole picture** (a new style, new light, fog):
|
||||
there is nothing to keep, so Edit Lock steps aside and the edit runs as
|
||||
if the node were not there. The report says so.
|
||||
- **A soft effect over the whole picture** (rain, falling snow, haze):
|
||||
it touches everything a little, so there is no untouched part to put
|
||||
back. Edit Lock lets the effect through and only holds the picture in
|
||||
place, so it does not come back zoomed or shifted. The report says so.
|
||||
- **A soft effect and a clear change in one edit** (rain and an umbrella):
|
||||
the node may lock on the umbrella and hold the rain back everywhere
|
||||
else. If the effect is missing outside the changed part, set **Lock** to
|
||||
`off`.
|
||||
- **Something in between** (a new hair color on a close-up, a new
|
||||
background behind a person): it may lock or step aside. The report says
|
||||
which. These edits often change the light on the face too. `auto` steps
|
||||
aside for most of them, so the new light comes with the new hair.
|
||||
`always` keeps the old light on everything it keeps, which can look
|
||||
wrong on a face. A mask settles it: paint the hair and the face, and
|
||||
the rest is locked.
|
||||
- **The model ignores your picture and draws a new one:** that reads as a
|
||||
whole-picture edit, so `auto` steps aside. `always` holds the model to
|
||||
your picture.
|
||||
|
||||
## Controls
|
||||
|
||||
- **model**: the edit model. Patch last, after any LoRAs.
|
||||
- **vae**: the same VAE the workflow decodes with.
|
||||
- **image**: the picture you are editing, at the size of the result. If
|
||||
the sizes differ by more than a few percent the lock does nothing, and
|
||||
the report says so.
|
||||
- **Lock** (`lock`): `auto` (the default) locks the untouched parts and
|
||||
steps aside when the whole picture changes. `always` locks even then.
|
||||
`off` does nothing, which makes a quick before and after.
|
||||
- **Tolerance** (`tolerance`): how big a change must be to count as part of
|
||||
the edit. 1 is the default. Raise it if small unwanted changes get
|
||||
through. Lower it if the lock holds back part of your edit.
|
||||
- **mask** (optional): white marks where the edit may happen; everything
|
||||
else is locked. With a mask the node does not look for the change
|
||||
itself. A mask from **Mask by Touch 🆎** or **Mask by Name 🆎** works.
|
||||
|
||||
## Outputs
|
||||
|
||||
- **model**: the model with the lock on.
|
||||
- **edit_lock**: what the lock kept, for Edit Lock Restore 🆎.
|
||||
|
||||
## Good to know
|
||||
|
||||
- The lock belongs to one picture. For an edit with two pictures, give it
|
||||
the one the result should line up with.
|
||||
- It works on single pictures, not video.
|
||||
- The node watches the first steps of a run and locks for the rest, so
|
||||
the model finishes the edit on top of your real picture. Shadows and
|
||||
reflections the edit adds next to the changed part still come through.
|
||||
- If your edit is missing and the report says nearly all of the picture
|
||||
was kept, set **Lock** to `off`.
|
||||
- Tested on MiniMax-H3-Image. The lock itself is not tied to one model, but
|
||||
the line between "local edit" and "whole picture" was measured there.
|
||||
|
||||
## Technical details
|
||||
|
||||
At every step an edit model predicts the finished picture. Edit Lock
|
||||
compares that prediction with your picture in latent space.
|
||||
|
||||
**Watching.** The first prediction of a run is a blur, and rain, snow or
|
||||
the light a new hair color throws on a face only show a few steps in. So
|
||||
the node watches until the noise is down to 0.8 of where it began: step 4
|
||||
of a 6-step MiniMax-H3-Image run. A run that never gets that low decides
|
||||
at its last step. While it watches, the model draws its own picture and
|
||||
only one thing is corrected. The model often draws the whole picture about
|
||||
one percent larger, or a little shifted. The node measures that zoom and
|
||||
shift at every step, on the calmer half of the picture, and moves the
|
||||
prediction back so it sits where your picture does.
|
||||
|
||||
**Deciding.** Change is measured against the quiet part of the picture:
|
||||
the tenth where the prediction differs least. An even tint over the whole
|
||||
picture is taken out first, so a color cast is not read as a change. A
|
||||
spot counts as changed when it differs by 3 times the quiet level, or by 2
|
||||
times while it touches a spot that does. So a faint change beside a clear
|
||||
one belongs to the edit, and a faint change alone is redraw noise.
|
||||
**Tolerance** multiplies both numbers.
|
||||
|
||||
**Locking.** From the decision on, wherever the picture did not change,
|
||||
the original latent is put back before the sampler takes its next step. A
|
||||
part once read as changed stays changed for the rest of the run. The last
|
||||
step ends on the original there, so what was kept is the original itself,
|
||||
not a redrawn copy.
|
||||
|
||||
**Stepping aside.** `auto` does not lock in three cases:
|
||||
|
||||
- At the first step the whole picture is already changing (a new style,
|
||||
new light). The node reads the calmest fifth of a smoothed copy, where a
|
||||
slightly larger redraw nearly vanishes and a new style does not. On
|
||||
MiniMax-H3-Image, local edits at 1, 4 and 16 megapixels read 0.22 or
|
||||
less there and whole-picture edits 0.27 or more; the line sits at 0.243.
|
||||
The model then runs untouched.
|
||||
- At the decision no place has changed clearly: the strongest spot of the
|
||||
picture is under 4 times the quiet level. That is light rain or fog.
|
||||
Local edits read 4.7 or more there, glasses and makeup included.
|
||||
- At the decision the lock would hand a tenth of the picture or more to
|
||||
the edit, yet the strongest hundredth of the picture is under 4 times
|
||||
the quiet level. That is heavier rain or snow, and a lock would let it
|
||||
through in patches. Local edits that wide read 4.4 or more; rain and
|
||||
snow read 3.6 or less.
|
||||
|
||||
In the last two cases the node keeps undoing the zoom and shift to the end
|
||||
of the run, and puts nothing back. An edit close to one of these lines (a
|
||||
hair color change on a close-up, a new background, smoke) can fall on
|
||||
either side. The report says which, and **Lock** overrides it.
|
||||
|
||||
This is the target the TailSteer paper trains a model toward (the source
|
||||
where nothing changed, the model's own edit elsewhere), applied while
|
||||
sampling. It needs no LoRA and no training.
|
||||
@@ -1,73 +0,0 @@
|
||||
# Edit Lock Restore
|
||||
|
||||
Puts your picture's own pixels back in every part the edit did not change,
|
||||
and takes out the faint pink tint some edit models add to the whole picture.
|
||||
|
||||
**Edit Lock 🆎** keeps the untouched parts in place while the picture is
|
||||
made. They still pass through the VAE, which softens fine detail a little.
|
||||
This node swaps your original pixels in for those parts, so they match
|
||||
your picture pixel for pixel. Only the edit is new.
|
||||
|
||||
## Quick start
|
||||
|
||||
1. Add it right after the VAE Decode, before any upscaler.
|
||||
2. Wire the decoded picture into `image`.
|
||||
3. Wire the `edit_lock` output of Edit Lock 🆎 into `edit_lock`.
|
||||
4. Wire `report` into **Show Text 🆎** to read what was kept.
|
||||
|
||||
## Controls
|
||||
|
||||
- **image**: the edited picture, straight from the VAE Decode.
|
||||
- **edit_lock**: from Edit Lock 🆎. It carries your original picture and
|
||||
the map of what the edit changed, so there is nothing else to wire.
|
||||
- **Feather** (`feather`): how softly your original fades into the edit,
|
||||
in pixels. 16 is the default. The fade lies outside the edit, so the
|
||||
edit itself is never mixed with the old picture.
|
||||
- **Remove tint** (`remove_tint`): on by default. MiniMax H3 Image makes
|
||||
every edit a little pinker and lighter all over. This reads that tint
|
||||
from the part of the picture the edit left alone and takes it out of the
|
||||
whole picture, the edit included. It matters most when Edit Lock stepped
|
||||
aside, such as for a new hair color, a new background or rain, because
|
||||
then nothing else removes it. Edits meant to recolor everything (golden
|
||||
hour, red light, a new art style) are left alone. Turn it off if a color
|
||||
change you asked for comes out weaker.
|
||||
|
||||
## Outputs
|
||||
|
||||
- **image**: the edit, with your original pixels in the untouched parts.
|
||||
- **edit_mask**: white where the edit changed the picture. Use it to see
|
||||
what the lock decided, or for a later step that should only touch the
|
||||
edit.
|
||||
- **report**: one line, such as "Edit Lock kept 82% of your picture as it
|
||||
was and left 18% to the edit". When the tint was taken out it adds a
|
||||
sentence that says so.
|
||||
|
||||
## When nothing was locked
|
||||
|
||||
Your original pixels are not pasted back, the mask is all white, and the
|
||||
report says why: the edit changed the whole picture, the lock was off, or
|
||||
the picture and the result were different sizes. Remove tint still works
|
||||
here, so the picture can come out with the tint taken out.
|
||||
|
||||
## Technical details
|
||||
|
||||
The map of what changed is made while sampling, on the latent grid. Here
|
||||
it is enlarged to the picture's size, widened by the feather and blurred
|
||||
by the same amount, and used to blend the decoded picture with your
|
||||
original. If the decoded picture is not the size of your original (after
|
||||
an upscale), the original is resized to fit first, which costs it some
|
||||
sharpness. That is why this node goes before an upscaler.
|
||||
|
||||
**Remove tint.** The edit is lined up with your original (edits often come
|
||||
back about one percent larger or a little shifted), both are averaged
|
||||
into coarse cells of about 8 px at 1 megapixel, and their difference is
|
||||
taken in Lab color. The tint is the even shift most cells share: it starts
|
||||
at the median and keeps only cells within 4 Lab units of it, five times
|
||||
over, so a new background or new hair drops out of the count. It is taken
|
||||
out only when it looks like the model's own tint: a between +0.5 and +10,
|
||||
b between -8 and 0, L between -1 and +6, read on at least 15% of the
|
||||
picture. On 21 test edits at 16 megapixels it took out the tint on the 5
|
||||
it should (a +2.6 to +6.5 down to +0.4 or less) and left the other 16
|
||||
alone, golden hour, red light and an anime restyle included. It cannot
|
||||
tell this tint from an edit that asks for a slightly pinker, lighter look
|
||||
over the whole picture; turn it off for one of those.
|
||||
@@ -1,69 +0,0 @@
|
||||
# FlashVSR Upscale
|
||||
|
||||
Makes a video larger and sharper. Give it the frames of a clip, set how much
|
||||
larger, and it returns the same clip with more detail. Use it as the last
|
||||
step before Save Video, for a generated clip or one you loaded.
|
||||
|
||||
It needs one model file and no other pack.
|
||||
|
||||
## The model file
|
||||
|
||||
Download `flashvsr_v1.1_fp16.safetensors` (3.5 GB) from
|
||||
[ausboss/FlashVSR-v1.1-ComfyUI](https://huggingface.co/ausboss/FlashVSR-v1.1-ComfyUI)
|
||||
and put it in `ComfyUI/models/diffusion_models`. Then refresh the page, or
|
||||
press `R`, and pick it under **Model**.
|
||||
|
||||
The file holds the official FlashVSR v1.1 weights in one piece. Another
|
||||
FlashVSR file will not load here: the node stops and says which part is
|
||||
missing.
|
||||
|
||||
## Controls
|
||||
|
||||
- **frames**: The clip, as a batch of frames. Load Video's frames output
|
||||
goes here.
|
||||
- **Model** (`model`): The model file above. The list shows the files in
|
||||
`diffusion_models` that have FlashVSR in their name.
|
||||
- **Scale** (`scale`, starts at `2`): How many times larger each side gets,
|
||||
from 1 to 4. At `1` the clip keeps its size and is only sharpened.
|
||||
- **Keep colors** (`color_match`, starts on): Brings each frame's colours
|
||||
back to those of your clip. Leave it on unless you want the model's own
|
||||
colours.
|
||||
- **vae** (optional): Connect the Wan 2.1 VAE for a slower, finer finish.
|
||||
With nothing connected, the fast decoder inside the model file makes the
|
||||
picture.
|
||||
|
||||
## Outputs
|
||||
|
||||
- **frames**: The larger frames, as many as went in, in the same order.
|
||||
The frame rate and the sound are not touched, so wire those from Load
|
||||
Video to Save Video as before.
|
||||
|
||||
## What to expect
|
||||
|
||||
FlashVSR redraws fine detail: skin, hair, cloth and edges come back
|
||||
sharper than the clip had them. It keeps the scene, the motion and the
|
||||
timing.
|
||||
|
||||
A long clip needs no more graphics memory than a short one. The node reads
|
||||
the clip a few frames at a time and keeps only the last few in memory.
|
||||
|
||||
## Technical details
|
||||
|
||||
- **Size.** The result is exactly your size times **Scale**, rounded to
|
||||
even numbers. Inside, the model works at a multiple of 128 pixels each
|
||||
way; the node pads the picture for that and cuts the padding off again,
|
||||
so nothing of your picture is cropped.
|
||||
- **Graphics memory.** About 10 GB for a 576 x 1024 result. A result too
|
||||
large for the free memory is made in overlapping tiles and blended, and
|
||||
the tile size is chosen from the memory that is free when the node runs.
|
||||
1152 x 2048 ran in two tiles at about 16 GB. On an 8 GB card (RTX 3070
|
||||
Laptop) the same result ran in smaller tiles at about 6.5 GB, at about 3
|
||||
seconds a frame.
|
||||
- **Speed.** On an RTX 5090: about 7 frames a second for a 576 x 1024
|
||||
result and about 2 frames a second for 1152 x 2048.
|
||||
- **One step.** The model runs once per group of frames. There are no
|
||||
steps, sampler, prompt or seed to set.
|
||||
- **The model.** FlashVSR v1.1 by Junhao Zhuang and the OpenImagingLab
|
||||
team, released under Apache-2.0. It is built on the Wan 2.1 1.3B video
|
||||
model. This node is the pack's own code in plain PyTorch.
|
||||
- The node makes no network requests and writes no files.
|
||||
@@ -5,31 +5,37 @@ clip, a song or any sound a video model or a save node takes, when you want
|
||||
one part of the file and not the whole thing.
|
||||
|
||||
The node shows the whole file as a wave, so you can see where the loud parts
|
||||
are. The part that comes out is bright. Under the wave are three boxes:
|
||||
**Start**, **Duration** and **Ends at**, in seconds. Drag the left handle to
|
||||
move the start, drag the right handle or type a Duration to change how long
|
||||
the sound is, or drag the bright part to slide it. Click somewhere else on
|
||||
the wave to move it there. Typing **Ends at** sets the Duration for you.
|
||||
are. The part that comes out is bright. Drag the white **IN** and **OUT**
|
||||
handles to set where it starts and stops, drag the bright part to slide it,
|
||||
or click somewhere else on the wave to move it there. You can also type a time
|
||||
under the wave, in seconds (`12.5`) or minutes and seconds (`1:02.5`).
|
||||
|
||||
Press **▶** to hear only the part that comes out. **LOOP** plays it again and
|
||||
again.
|
||||
|
||||
Set the Duration to the length the next step needs, such as the length of
|
||||
the video you are making. An empty Duration runs to the end of the file.
|
||||
## Max length
|
||||
|
||||
A box set by another node, such as Float 🆎, shows a **linked** button that
|
||||
jumps to that node, and the wave shows the part that number picks.
|
||||
Set **Max length** to the longest sound the next step can take, such as the
|
||||
length of the video you are making. The start stays where it is, and anything
|
||||
past the limit turns red with a dashed line where it is cut. Next to OUT,
|
||||
the node shows how long the sound that comes out is, such as `15.0 s`. It
|
||||
turns red when part of your pick is cut; hold the mouse over it to see how
|
||||
much, and click it to move OUT to the cut. Play stops at the cut, so what you
|
||||
hear is what comes out. `0` means no limit.
|
||||
|
||||
Max length can be wired. When the wire comes from a number node such as
|
||||
Float 🆎, the wave shows the cut for that number; otherwise the length's tooltip says
|
||||
`max wired` and the run still cuts the sound to the wired length.
|
||||
|
||||
## Controls
|
||||
|
||||
- **Source** (`audio`): a sound file in ComfyUI's input folder. **Upload**
|
||||
adds one. Videos are listed as well, for their sound.
|
||||
- **Start** (`start_seconds`): where the sound starts.
|
||||
- **Duration** (`max_seconds`): how long the sound is, in seconds. Empty, or
|
||||
`0`, runs to the end of the file.
|
||||
- **Ends at**: where the sound stops. Typing it sets the Duration.
|
||||
A workflow saved with an end time (`end_seconds`) keeps it and runs the
|
||||
same.
|
||||
- **Max length** (`max_seconds`): the longest the sound may be, in seconds.
|
||||
`0` means no limit.
|
||||
- **IN** (`start_seconds`): where the sound starts.
|
||||
- **OUT** (`end_seconds`): where the sound stops. `0` means the end of the
|
||||
file.
|
||||
|
||||
## Outputs
|
||||
|
||||
@@ -43,4 +49,4 @@ jumps to that node, and the wave shows the part that number picks.
|
||||
- The sound keeps its own sample rate and channels.
|
||||
- A start past the end of the file stops the run with a message that says so.
|
||||
- The wave is drawn in the browser from the file itself; nothing extra is
|
||||
stored with the workflow besides the node's own values.
|
||||
stored with the workflow besides the four values above.
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
# Load Image
|
||||
|
||||
Loads a picture and sets its size in the same node, so a workflow does not
|
||||
need a resize node and a size node after its loader.
|
||||
|
||||
Pick a file in **Source**, press **Load** to upload one, or use the arrows
|
||||
under it to step through the pictures in ComfyUI's input folder. The line
|
||||
beside the arrows shows the size of the file and, when the size changes, the
|
||||
size that comes out:
|
||||
|
||||
`912 × 1632 → 1144 × 2048`
|
||||
|
||||
That is the real output size, worked out before you run.
|
||||
|
||||
Under that line are two small pictures: the file as it goes in, and the
|
||||
picture as it comes out. On the first one the part that is kept is lit and
|
||||
the part that is cut off is dark. Between them the node says the shape
|
||||
(`3:4 → 1:1`) and what happens (`77% size`, `cuts 449 px of height`).
|
||||
|
||||
## Size
|
||||
|
||||
**Size** (`size`) picks how the picture is resized. Each choice shows only
|
||||
the numbers it uses.
|
||||
|
||||
| Choice | What it does | Its number |
|
||||
|---|---|---|
|
||||
| **off** | The picture comes out exactly as the file has it. | none |
|
||||
| **megapixels** | Brings the whole picture to a total size and keeps its shape. | **Megapixels** (`megapixels`): 1.0 is about 1024 × 1024 |
|
||||
| **longest side** | Sets the longer edge; the other edge follows. | **Longest side** (`longest_side`), in pixels |
|
||||
| **scale** | Multiplies both edges. | **Scale** (`scale`): 0.5 is half, 2 is double |
|
||||
| **fit inside** | Makes the picture as big as it can be inside a box, with nothing cut off. | **Width** and **Height** (`width`, `height`) |
|
||||
| **crop to fill** | Covers the box completely and cuts off what sticks out. | **Width** and **Height** |
|
||||
| **crop** | Cuts a piece of that size out of the picture. Nothing is resized. | **Width** and **Height** |
|
||||
| **crop to ratio** | Cuts the largest piece of a shape, such as 16:9, out of the picture. Nothing is resized. | **Ratio** (`ratio`) |
|
||||
|
||||
**Round to** (`multiple`) rounds the new width and height to a multiple of
|
||||
that number. Most models want 8 or 16. Set it to 1 to keep the numbers as
|
||||
they are. It does nothing while Size is off.
|
||||
|
||||
## Which part is kept
|
||||
|
||||
The three crop choices show **Keep** (`crop_from`). It picks the part of the
|
||||
picture that stays: `center` cuts evenly from both sides, `top` keeps the top
|
||||
and cuts from the bottom, `bottom left` keeps that corner, and so on.
|
||||
|
||||
You can also click the first small picture: click its top to keep the top,
|
||||
a corner to keep that corner. The lit part moves so you see what you get.
|
||||
|
||||
In **Ratio**, `width : height` takes the shape from the Width and Height
|
||||
boxes, for a shape that is not in the list (1600 and 900 give 16:9).
|
||||
|
||||
## More
|
||||
|
||||
- **Method** (`method`): how pixels are resampled. `lanczos` is the sharpest
|
||||
for photos. `nearest` keeps pixel art crisp.
|
||||
- **Enlarge** (`enlarge`): on, a small picture is made bigger to reach the
|
||||
size you asked for. Off, a picture is only ever made smaller: one that is
|
||||
already below the target comes out at its own size, and crop to fill cuts
|
||||
the box's shape out of it without growing it.
|
||||
|
||||
## The picture on the node
|
||||
|
||||
The picture under the settings is ComfyUI's own preview, the same one the
|
||||
stock Load Image shows. Drop a file on the node or paste one to upload it,
|
||||
and right-click the node for the mask editor and for copy and paste.
|
||||
|
||||
## Outputs
|
||||
|
||||
- `image`: the picture at its new size.
|
||||
- `mask`: white where the picture is see-through and black where it is
|
||||
solid, as the stock loader gives it. A picture with no transparency gives
|
||||
an all black mask. It is always the same size as `image`.
|
||||
- `width`, `height`: the size that comes out.
|
||||
- `filename`: the file's name without its folder or its ending
|
||||
(`shots/hero.png` gives `hero`), ready for a save node's prefix.
|
||||
- `original_width`, `original_height`: the size of the file before any
|
||||
resize. Use them to bring a result back to the size you started from.
|
||||
|
||||
## Which loader to use
|
||||
|
||||
- **Load Image** (this node): load a picture and set its size.
|
||||
- **Load Image + Pad**: add empty space around a picture for outpainting.
|
||||
- **Image Crop + Rotate + Pad**: turn, crop and pad a picture by hand.
|
||||
|
||||
## Technical details
|
||||
|
||||
- Every frame of an animated file comes through as a batch, all at the same
|
||||
new size. A phone photo is turned the way its EXIF data says.
|
||||
- With Size off the pixels are the file's own, bit for bit, and Round to is
|
||||
not applied.
|
||||
- Rounding moves each edge to the nearest multiple, so the shape can change
|
||||
by up to half a step. Fit inside rounds down instead, so the result never
|
||||
leaves its box.
|
||||
- Crop to fill resizes the picture until it covers the box, then cuts the
|
||||
box out at the side Keep names. The mask goes through the same resize and
|
||||
the same cut.
|
||||
- Crop and crop to ratio only cut. A box larger than the picture is cut down
|
||||
to the picture, and Round to rounds down so the piece stays inside it.
|
||||
Enlarge does not apply to them.
|
||||
- The small pictures are drawn on one scale, so a picture made half as large
|
||||
is drawn half as large.
|
||||
- With Enlarge off, a rounded size is rounded down so it never passes the
|
||||
file's own size.
|
||||
- The size line on the node uses the same arithmetic as the run. The pack's
|
||||
tests hold the two to the same answers over a table of cases.
|
||||
- Files are read only from ComfyUI's input, output and temp folders. A name
|
||||
such as `photo.png [output]` loads a picture ComfyUI made.
|
||||
- The node runs again when the file changes on disk or a setting changes.
|
||||
@@ -1,33 +1,37 @@
|
||||
# Load Video
|
||||
|
||||
Loads a video from ComfyUI's input folder as an `IMAGE` frame batch plus its
|
||||
audio. The player shows the video; the timing card under it picks the part
|
||||
that comes out.
|
||||
audio. One responsive player shows the source and previews the selected trim.
|
||||
Drag the high-contrast **IN** and **OUT** handles below it, drag the selected
|
||||
range to move the whole window, or type a time into the two fields, in seconds
|
||||
(`95.5`) or as a timecode (`1:35.5`). Click the strip outside the selection to
|
||||
move the window to that spot.
|
||||
The playhead follows each edit, so the frame at either boundary is visible
|
||||
while trimming. In **Source**, the list plays the clip under the pointer, muted, and filters as you type.
|
||||
|
||||
The timing card has three boxes: **Start**, **Duration** and **Ends at**.
|
||||
Drag the left handle on the bar to move the start, drag the right handle or
|
||||
type a Duration to change how long the clip is, or drag the middle of the
|
||||
clip to slide it. **s | fr** switches every box between seconds and frames;
|
||||
it only changes what you see, never a saved value. **Use as start** starts
|
||||
the clip at the frame in the picture, and **Whole video** puts the clip back
|
||||
to the full file. In **Source**, the list plays the clip under the pointer,
|
||||
muted, and filters as you type.
|
||||
Playback is constrained to the selected window. **LOOP** repeats it; turn loop
|
||||
off and playback pauses at OUT. The reload button refreshes the source without
|
||||
creating a second preview. The player takes the height you give the node:
|
||||
drag the node taller for a bigger picture. A tall video is shown whole, never
|
||||
cropped.
|
||||
|
||||
The player takes the height you give the node: drag the node taller for a
|
||||
bigger picture. A tall video is shown whole, never cropped. **LOOP** plays
|
||||
the clip again and again; with it off, playback pauses at the clip's end.
|
||||
The reload button refreshes the source.
|
||||
**FRAME** switches the loader into a frame picker: the trim strip becomes a
|
||||
single scrub rail, and only the frame at the marker loads — a one-image batch,
|
||||
ready for image workflows without a separate frame-select node. Click or drag
|
||||
anywhere on the rail to choose the frame, or type an exact time into the AT
|
||||
field. Playback runs the whole source freely in this mode so you can hunt for
|
||||
the right moment. Picking a frame moves IN to that time. When you toggle back,
|
||||
OUT stays where it was, unless the frame is at or after OUT: then OUT moves to
|
||||
the end of the video.
|
||||
|
||||
**FRAME** turns the loader into a frame picker: only the frame at the marker
|
||||
loads, as a one-image batch, ready for image workflows without a separate
|
||||
frame-select node. Drag the bar to choose the frame, or type it into the
|
||||
**FRAME** box. Playback runs the whole video in this mode so you can hunt for
|
||||
the right moment. Picking a frame moves the clip's start there.
|
||||
|
||||
The boxes count real frames: the frame rate and frame count come from the
|
||||
file itself, so a 4.1 s clip at 60 fps reads 247 frames, the same number
|
||||
the run loads. When a box is set by another node it shows a **linked**
|
||||
button that jumps to that node.
|
||||
The label between IN and OUT reports what one Run will actually load — e.g.
|
||||
`0:04.0 of 0:10.0 · 48 frames @ 12 fps`, or `1 frame at 0:05.2` while FRAME
|
||||
is on. The preview cannot re-render `every_nth` frame drops or a `max_frames`
|
||||
cap, so it counts them instead: the frame total and playback rate come from
|
||||
the source's real frame rate (probed from the file, since the browser's
|
||||
player never exposes it) with `every_nth` and `max_frames` applied. When a
|
||||
deciding value arrives over a link, or the rate cannot be probed, the count
|
||||
drops out rather than guessing.
|
||||
|
||||
## Drop a video onto the node
|
||||
|
||||
@@ -44,21 +48,21 @@ embedded workflow replaces the whole graph.
|
||||
|
||||
- **Source** (`video`): A file in the input folder; **Upload** adds new ones.
|
||||
A video ComfyUI made, named like `clip.mp4 [output]`, loads too.
|
||||
- **Start** (`start_seconds`): Skip everything before this time.
|
||||
- **Duration** (`max_frames`): How many frames the clip keeps. **Whole
|
||||
video** removes the limit, so the clip runs to the end (the widget holds
|
||||
`0`). The decode stops early, so a short clip from a long video stays
|
||||
quick.
|
||||
- **Ends at**: Where the clip stops. Typing it sets the Duration. A
|
||||
workflow saved with an end time (`end_seconds`) keeps it and runs the same.
|
||||
- **Every nth** (`every_nth`): Keep one frame in this many; `2` halves the
|
||||
frame count. The `fps` output divides to match, so the clip still plays at
|
||||
real speed downstream.
|
||||
- **LOOP**: Repeat the clip during preview. It starts on and is saved with
|
||||
the workflow.
|
||||
- **FRAME** (`single_frame`): Load only the frame at the marker as a
|
||||
one-image batch; the Duration and Every nth are ignored while it is on.
|
||||
- **↻**: Reload the source preview.
|
||||
- **IN** (`start_seconds`): Skip everything before this time.
|
||||
- **OUT** (`end_seconds`): Stop at this time; `0` means the source end until a
|
||||
handle is moved.
|
||||
- **Every nth** (`every_nth`): Keep one frame in this many — `2` halves the frame count.
|
||||
The `fps` output divides to match, so the clip still plays at real speed
|
||||
downstream.
|
||||
- **Limit** (`max_frames`): Stop after this many kept frames; `0` loads the
|
||||
whole trim window. Caps memory on long clips — the decode ends early
|
||||
instead of loading and discarding.
|
||||
- **LOOP**: Repeat the selected window during preview. It starts on and is
|
||||
saved with the workflow.
|
||||
- **FRAME** (`single_frame`): Load only the frame at the IN time (the field
|
||||
reads **AT** while FRAME is on) as a one-image batch; `end_seconds`,
|
||||
`every_nth`, and `max_frames` are ignored while it is on.
|
||||
- **↻**: Reload the selected source preview.
|
||||
- **Width** / **Height** (`custom_width` / `custom_height`): `0` keeps the
|
||||
source size. Set one side only and the other follows the aspect ratio,
|
||||
rounded to an even number.
|
||||
|
||||
@@ -266,14 +266,6 @@ red with advice to re-pick. Thumbnails, the info card, and range lookups
|
||||
all use the resolved name, so a moved file keeps its previews and Civitai
|
||||
data.
|
||||
|
||||
A missing LoRA is also listed in ComfyUI's own missing-models list (the
|
||||
Issues panel, and the "Download all" button) next to the other models the
|
||||
workflow needs, with a Download button when the workflow saved where the
|
||||
file comes from. Rows that are switched off, at zero strength, or whose
|
||||
file moved folders are left off that list, because the run does not need
|
||||
them or finds them anyway. Rows that come into the node over a link are
|
||||
listed by the node that sets them, not here.
|
||||
|
||||
The run side matches: a stale saved path resolves by name at load time
|
||||
(exact → unique case-insensitive path → unique basename, with a one-line
|
||||
console note when it remaps). A LoRA that is genuinely missing **stops the
|
||||
|
||||
@@ -19,8 +19,8 @@ What is lit in teal is what the mask will be. When it is right, press Run
|
||||
for the whole workflow.
|
||||
|
||||
The first time the pointer rests on a picture, the node looks at it. A
|
||||
button under the picture shows how far along it is, **❚❚ Pause · looking
|
||||
40/104**, filling up as it goes. The first things light up after a few seconds, and
|
||||
small button under the picture shows how far along it is, **❚❚ 40/104**,
|
||||
filling up as it goes. The first things light up after a few seconds, and
|
||||
it has seen the whole picture after about 20.
|
||||
|
||||
You do not have to wait for that. Whatever is lit under the pointer can be
|
||||
@@ -28,7 +28,7 @@ picked: a click takes it at once, also while the node is still looking.
|
||||
|
||||
Click that button to pause the looking when what you need is already lit:
|
||||
what is lit stays, and you go on picking and painting. It turns into
|
||||
**▶ Look on**; click it to look on from where it stopped. A click on a spot where
|
||||
**▶**; click it to look on from where it stopped. A click on a spot where
|
||||
nothing is lit yet looks on as well.
|
||||
|
||||
A click on a spot where nothing is lit yet is not lost: a dot marks it, the
|
||||
@@ -50,9 +50,6 @@ at that spot.
|
||||
A stroke across two things, like both shoes, takes both.
|
||||
- Did the thing not light up at all? Type its name into the field under the
|
||||
picture, like "screen" or "earring", and press Enter.
|
||||
- Is something in the mask that should not be, like the face or the hair of
|
||||
a person you picked? Click the **+** in front of that field so it shows
|
||||
**−**, type "face" and press Enter. Or hold Ctrl and click the face.
|
||||
- When nothing fits, switch to **Paint** and paint the area yourself.
|
||||
|
||||
## The whole subject, or the background
|
||||
@@ -62,10 +59,6 @@ click: the person, the animal, the product. **Background** picks everything
|
||||
else. They are picks like any other: click more things to add them, or
|
||||
Ctrl-click a thing to take it away again.
|
||||
|
||||
Ctrl-click takes away the thing under the pointer, where it is in the mask.
|
||||
On a spot where nothing is picked it changes nothing, and the picture says
|
||||
so.
|
||||
|
||||
Both need ComfyUI's background-removal model, see "The model for Fine
|
||||
edges" below.
|
||||
|
||||
@@ -122,11 +115,8 @@ or an area you painted.
|
||||
it.
|
||||
- **all 3** on a chip takes every thing of that name instead of the one you
|
||||
clicked: all five birds, both shoes.
|
||||
- The field at the end picks every thing of the name you type. The sign in
|
||||
front of it says what happens to the name: **+** adds it, **−** takes it
|
||||
away. Click the sign to change it. A name typed with a minus in front,
|
||||
like "-face", is taken away whatever the sign shows. With Erase chosen the
|
||||
sign starts on **−**.
|
||||
- The field at the end, **+ type a name**, picks every thing of the name
|
||||
you type. With Erase chosen it takes them away.
|
||||
|
||||
## The tools on the node
|
||||
|
||||
@@ -170,9 +160,6 @@ or an area you painted.
|
||||
everything except what you picked.
|
||||
- **More → If nothing** (`if_nothing`): **stop the run** or **empty mask**,
|
||||
see below.
|
||||
- **More → New picture** (`new_picture`): **keep picks** or **start over**,
|
||||
for when a different picture comes in. See "Which picture the picks belong
|
||||
to" below.
|
||||
- **More → Free VRAM** (`free_vram`): takes SAM 3 out of the graphics card's
|
||||
memory right after the search, so the next model has the room. Turn it on
|
||||
in a workflow that loads a big model after this node.
|
||||
@@ -222,17 +209,11 @@ nothing instead.
|
||||
|
||||
## Which picture the picks belong to
|
||||
|
||||
Picks belong to the picture they were made on. When a different picture
|
||||
comes in, **New picture** (under More) decides what happens to them:
|
||||
|
||||
- **Keep picks** (the default): your clicks and paint move onto the new
|
||||
picture, in the same places. On a picture of another size they are
|
||||
scaled to fit it. A click finds whatever is at that spot now; paint stays
|
||||
exactly as painted. Press **Clear** to start over.
|
||||
- **Start over**: the node shows the new picture with nothing picked. If the
|
||||
workflow runs before you pick again, the run stops and says the picks
|
||||
were made on another picture. The new picture shows on the node then,
|
||||
ready to pick from.
|
||||
Picks belong to the picture they were made on. Load another picture and the
|
||||
node shows it with nothing picked, and says the old picks are not used.
|
||||
If the workflow runs before the node has shown the new picture, the run
|
||||
stops and says the picks were made on another picture. The new picture
|
||||
shows on the node then, ready to pick from.
|
||||
|
||||
- **The reload button** (the round arrow beside Undo) shows the picture
|
||||
coming in now. Use it after you change the picture before this node, for
|
||||
@@ -283,15 +264,6 @@ then.
|
||||
|
||||
### How SAM 3 is asked
|
||||
|
||||
- A picture whose long side is over 2048 pixels is asked about on a copy
|
||||
with its long side at 2048. SAM 3 reads every picture at 1008 pixels
|
||||
anyway, and returns each answer at the size it was given, on the graphics
|
||||
card: at 8192 pixels one word with many matches needed over 27 GB. The
|
||||
answer is brought back to the picture's own size, so the mask, the cut-out
|
||||
and your touches stay in pixels of the picture. Paint is never scaled.
|
||||
Measured on a 3840 pixel picture, five words: the new masks share 95 to
|
||||
99.6 % of their area with the old ones, the edge sits a median 0 to 2
|
||||
pixels differently, and a look takes 31 seconds in place of 53.
|
||||
- The search is ComfyUI's own SAM 3: SAM3 Detect, asked about points, or
|
||||
about a word that CLIP Text Encode has read. Both use ComfyUI's own
|
||||
settings (threshold 0.5, two edge passes). The node needs ComfyUI 0.20 or
|
||||
@@ -352,10 +324,7 @@ no browser:
|
||||
used.
|
||||
- **`paint`**: exactly the stroke's own area. SAM 3 is not asked.
|
||||
- **`key`** names the picture the picks were made on: its size and a
|
||||
fingerprint of every pixel. Picks made on another picture are moved onto
|
||||
the one that came in, scaled from the size in their key to its size, and
|
||||
the face is sent the moved touches. With `new_picture` set to `start
|
||||
over` they are ignored instead.
|
||||
fingerprint of every pixel. Picks made on another picture are ignored.
|
||||
Leave `key` out when you write `touches` by hand.
|
||||
|
||||
### How an area is tidied
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
# Prompt Variations
|
||||
|
||||
A prompt box that changes on every run. Write choices in curly brackets and
|
||||
the node picks one from each set:
|
||||
|
||||
```text
|
||||
A woman in a {plain|striped|patterned} {tank top|sweater|button-up shirt}
|
||||
and {jeans|a pleated skirt|cargo shorts}, {standing|sitting on a stool|leaning on the wall}.
|
||||
```
|
||||
|
||||
One run might give "A woman in a striped sweater and jeans, sitting on a
|
||||
stool." The next gives another mix.
|
||||
|
||||
Use it to make many different pictures in one go. Wire in the seed, set the
|
||||
Seed node to **randomize**, and set the number of runs next to the Run
|
||||
button to 50. Each run gets a new seed, so each picture gets new choices.
|
||||
|
||||
## Controls
|
||||
|
||||
- The text box (`text`): your prompt. Put each set of choices in curly
|
||||
brackets and split the choices with `|`. Write as many sets as you like,
|
||||
each with as many choices as you like.
|
||||
- `seed` (a socket): the seed your sampler uses. A new seed picks new
|
||||
choices. The same seed picks the same ones again, so a picture you like
|
||||
can be made again from its seed.
|
||||
|
||||
## Output
|
||||
|
||||
- **prompt**: your text with one choice picked from each set. Wire it to
|
||||
Show Text to see what was picked.
|
||||
|
||||
## Tips
|
||||
|
||||
- An empty choice lets a part come and go: `a {|striped} shirt` gives "a
|
||||
shirt" or "a striped shirt".
|
||||
- Sets can go inside sets: `{a {red|blue} hat|a scarf}`.
|
||||
- Text without curly brackets comes out exactly as typed.
|
||||
- To make one choice come up more often, write it more than once:
|
||||
`{jeans|jeans|skirt}`.
|
||||
|
||||
## Technical details
|
||||
|
||||
Only brackets that hold a `|` are choices. Brackets without one are left as
|
||||
they are, so a JSON prompt such as `{"light": "soft"}` passes through
|
||||
unchanged. A `|` inside JSON brackets still counts as a choice.
|
||||
|
||||
The innermost sets are picked first, from left to right, with Python's
|
||||
`random.Random(seed)`. The same text and seed always give the same prompt,
|
||||
on any machine. Spaces around each choice are trimmed, and an empty pick
|
||||
also drops the one space in front of it.
|
||||
|
||||
The picks happen when the prompt runs, on the server, not in the browser.
|
||||
ComfyUI's own `{a|b}` choices in some text boxes are picked by the browser
|
||||
when you queue, with no seed; this node does not use them.
|
||||
@@ -31,8 +31,8 @@ names from here on; how it measures may still improve.
|
||||
moved a boat keeps the boat where it drew it, so the result lines up
|
||||
closely, not pixel for pixel.
|
||||
- **Leaves alone:** a picture it can't measure, or a zoom bigger than
|
||||
**Max zoom** after allowing for padded reframing. That picture only
|
||||
comes out resized, and the report says why.
|
||||
**Max zoom**. That picture only comes out resized, and the report says
|
||||
why.
|
||||
|
||||
## Controls
|
||||
|
||||
@@ -50,10 +50,8 @@ names from here on; how it measures may still improve.
|
||||
with nothing in it. `edge` (the default) stretches the nearest pixels
|
||||
into it, `source` fills it from the original, `gray` fills it flat gray
|
||||
for inpainting. With a big enough margin there is no strip.
|
||||
- **Max zoom**: the zoom limit in percent (20 by default). For a padded
|
||||
picture, zooming in to fill the padding gets an extra allowance; the
|
||||
setting limits zoom beyond that. Zooming out still uses the stated limit.
|
||||
Anything beyond those limits is treated as a change you meant and left alone.
|
||||
- **Max zoom**: the biggest zoom it will undo, in percent (20 by default).
|
||||
Anything bigger is treated as a change you meant and left alone.
|
||||
|
||||
## Outputs
|
||||
|
||||
@@ -123,10 +121,6 @@ new cloud, are left out. It trusts the fit when at least 10 blocks, and at
|
||||
least a quarter of them, agree. With a stitcher, the blocks tile the
|
||||
picture's area only.
|
||||
|
||||
For padded reframing, the extra zoom-in allowance on each axis is the
|
||||
canvas size divided by the source picture's size, minus one. It is added
|
||||
to **Max zoom**; zooming out gets no extra allowance.
|
||||
|
||||
It runs on the CPU in a fraction of a second per 1 MP frame. No new
|
||||
dependencies, and no model.
|
||||
|
||||
|
||||
@@ -50,22 +50,8 @@ file's name. A caption on the `caption_text` input writes the paired `.txt`.
|
||||
shorter; on again, the node returns to its height with the last saved
|
||||
image. It is display only: the file is saved either way and the queue
|
||||
still lists it. When a run saves more than one image (a batch, or a list
|
||||
such as a folder of images), they all show side by side. The arrows
|
||||
beside the switch (‹ all 5 ›) go on to each one by itself (‹ 2 / 5 ›) and
|
||||
back round to all of them. A run of more than 48 shows one at a time.
|
||||
The node shows a small copy of each picture (up to 2048 pixels on the
|
||||
long side), so a big file shows at once on a slow connection too. The
|
||||
saved file is always full size. The copies are in ComfyUI's temp folder.
|
||||
- **Auto save** (`autosave`, on by default): on, every run saves its
|
||||
pictures. Off, a run only shows them here and saves nothing. A row over
|
||||
the picture then says **Not saved yet**, with a **Save picture** button.
|
||||
With several pictures it reads **Save all 4**, and with the arrows on one
|
||||
picture, **Save this one**. After a save the row says what is saved.
|
||||
Use it to make a batch, look, and keep only the good ones. The pictures
|
||||
are saved under the name and folder set above, in the format picked,
|
||||
with the workflow inside if **Embed workflow** is on. They wait in
|
||||
ComfyUI's temp folder, which is emptied when ComfyUI restarts, so save
|
||||
what you want before that. The Save button works for the last 256 runs.
|
||||
such as a folder of images), arrows beside the switch (‹ 2 / 5 ›) step
|
||||
through them.
|
||||
- **Preview steps** (`step_preview`, off by default): the switch left of
|
||||
**preview** shows the picture while it is being made, one step at a time,
|
||||
where the saved image goes, with a **STOP** button on the bar. Stop a run
|
||||
|
||||
@@ -67,11 +67,9 @@ are in the model's own picture.
|
||||
Tone match 0 the new area is bit-identical to what the model painted, and
|
||||
the whole stitch is the 2.4.0 blend in, pixel for pixel.
|
||||
- With the classic seam, feeding the crop back unchanged reproduces the
|
||||
original image exactly only when there is no resizing in either direction,
|
||||
with Tone match at 0 and `fix_edge_halo` off. Resizing can lose detail even
|
||||
when the crop comes back unchanged; the halo fix rewrites the feathered
|
||||
band on purpose. Blend in does not promise this: it keeps the model's
|
||||
version of the thin strip at your picture's edge.
|
||||
original image exactly (with `fix_edge_halo` off; the fix rewrites the
|
||||
feathered band on purpose). Blend in does not promise this: it keeps the
|
||||
model's version of the thin strip at your picture's edge.
|
||||
- A stitcher built from one image broadcasts over any number of inpainted
|
||||
frames. A stitcher built from **more** frames than came back is trimmed to
|
||||
the leading ones with a console note - video models keep 8n+1 (LTX) or
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
# Text Lines
|
||||
|
||||
Runs what comes after once for each line of your text. Type five prompts,
|
||||
one on each line, press Run once, and you get five pictures.
|
||||
|
||||
Use it for a list of prompts you typed, or for a list another node wrote,
|
||||
such as a text model asked for "five different poses".
|
||||
|
||||
## How to use it
|
||||
|
||||
1. Type your lines in the box, or wire text into **text**.
|
||||
2. Wire **line** to where one prompt would go, such as a text encoder's
|
||||
prompt.
|
||||
3. Run. Every node after it runs once for each line, and a Save Image at the
|
||||
end saves one picture for each.
|
||||
|
||||
Empty lines are skipped. Models and pictures that do not depend on the line
|
||||
are loaded once, not once for each line.
|
||||
|
||||
## Controls
|
||||
|
||||
- The text box (`text`): One line for each run.
|
||||
- **Split at** (`split`): **each line** makes every line its own run.
|
||||
**blank line** keeps lines together and starts the next run at an empty
|
||||
line. Pick it when one prompt is several lines long.
|
||||
- **Numbering** (`remove_numbering`): **remove** takes a number or bullet
|
||||
off the start of each line, such as `1.`, `2)`, `-` or `[prompt 3]`.
|
||||
Lists a text model writes usually have them. **keep** leaves every line
|
||||
as written.
|
||||
- **Limit** (`limit`): The most lines to run. 0 runs them all. Set it when
|
||||
a text model might write more lines than you asked for.
|
||||
|
||||
## Outputs
|
||||
|
||||
- **line**: Each line, one at a time.
|
||||
- **number**: The line's place in the list, starting at 1. Add it to a seed
|
||||
with Math Expression (`a + b`) to give each line its own seed.
|
||||
- **count**: How many lines run.
|
||||
|
||||
## Notes
|
||||
|
||||
- With no lines at all, the run stops at this node and says so.
|
||||
- Every run uses the same seed unless you add **number** to it. Different
|
||||
prompts still give different pictures.
|
||||
- A line such as "2 women on a beach" or "1.5x zoom" keeps its number: only
|
||||
a number followed by a period, bracket or colon counts as numbering.
|
||||
|
||||
## Technical details
|
||||
|
||||
**line** and **number** are ComfyUI lists (`OUTPUT_IS_LIST`), the same way
|
||||
Image Folder hands out pictures. ComfyUI runs each later node once for each
|
||||
item and keeps the results in order. A node that takes a whole list at once,
|
||||
such as core Rebatch Images, gets all of them together.
|
||||
|
||||
Numbering that is removed: a number in square, round or CJK brackets with an
|
||||
optional word before it (`[prompt 1]`, `(2)`), a word and a number followed by
|
||||
a colon, period, bracket or dash (`Shot 3:`), a bare number followed by a
|
||||
period, bracket or colon that has no digit right after it, and the bullets
|
||||
`-`, `*` and `•` followed by a space. Only one marker is removed from each
|
||||
line.
|
||||
@@ -14,43 +14,28 @@ model that paints black regions.
|
||||
- **Inputs**: Pick an existing input video (the list plays the clip under the pointer, muted, and filters as you type), click **Load**, or drop a video file
|
||||
onto the node. The old source widgets remain compatible with saved workflows, but
|
||||
are now driven by this compact card. Choosing another video keeps the canvas
|
||||
settings - Fill, Feather, **Align**, Resize, Every nth, Frames for, Duration - and
|
||||
settings - Fill, Feather, **Align**, Resize, Every nth, Frames for, Length - and
|
||||
fits the new clip to the lit ratio button, the way **Fit** is set. Rotation, crop,
|
||||
padding, the clip's timing and the playhead start over.
|
||||
padding, IN/OUT and the playhead start over.
|
||||
- **Outputs** (`source_mode` / `local_path`): Pick a video from ComfyUI's output folder,
|
||||
such as one you just rendered. The list shows the newest first and previews the video
|
||||
under the pointer. The video is read in place, without an upload copy. In an API prompt
|
||||
it is named the way ComfyUI names a file there: `clip.mp4 [output]`. A whole path such
|
||||
as `/home/me/ComfyUI/output/clip.mp4` is not read, for queued runs and the editor's live
|
||||
preview alike.
|
||||
- **Play / Pause** beside the timeline plays the clip from its start and stops at its end. Pause and Play again to carry on from where you stopped.
|
||||
- **Timeline** (right under the picture): Press or drag anywhere on it to look at
|
||||
another frame; the picture shows it. Point at the bar to see where you are, the
|
||||
clip in words and the source's frame rate. Drag the **start** handle to move the
|
||||
clip (its Duration stays), and the **end** handle to change the Duration. The
|
||||
start stops where the whole Duration still fits, and a short note says so.
|
||||
**Use as start** starts the clip at the frame on the picture.
|
||||
- **Start / Duration / Ends at**: the clip in three boxes. Start and Ends at are
|
||||
places in the source video; Duration is how long the clip is. Type any of them,
|
||||
or drag over a box to scrub it. The small **s | fr** switch shows them in seconds
|
||||
or frames: Start and Ends at count source frames, Duration counts the frames the
|
||||
clip sends on, at the output rate. Point at a box for the other unit and what it
|
||||
covers. Typing a Start that leaves too little video is allowed: an amber note says
|
||||
how many frames still fit and offers to shorten the clip or move the start.
|
||||
- **Linked timing**: when another node feeds `start_frame`, `end_frame`,
|
||||
`frame_load_cap` or `fixed_frames`, that box is locked and its label shows a small
|
||||
**linked** button that jumps to the node. `fixed_frames` is an exact count;
|
||||
`frame_load_cap` is only a limit, so when the video ends first the note says how
|
||||
many frames you get. A count only worked out when the graph runs (a Math
|
||||
Expression, say) shows as **at run time**, and the timeline shows striped room
|
||||
after the start instead of a clip. A rate typed inside a subgraph counts as known.
|
||||
- **Technical details**: `start_seconds` / `end_seconds` are derived from the frames
|
||||
(the end is exclusive, 0 means the end of the source), and the Duration is stored
|
||||
as `max_frames`. Arrow keys on a handle move one second, Shift one frame. With
|
||||
Every nth or Frames for the end steps to the frames the run keeps, and a dim tail
|
||||
marks frames the window holds but the run drops.
|
||||
In the editor, **Set IN** / **Set OUT** (or the **I** / **O** keys) put a
|
||||
trim point at the playhead, and **Whole video** resets the clip. The editor also
|
||||
- **Play / Pause** beside the scrubber previews the selected frames and stops at OUT. Press Play at OUT to start from IN again.
|
||||
- **Timeline** (right under the preview and size line): The rail on the node and in the editor is one timeline. Press or
|
||||
drag anywhere on it to scrub the **playhead**, with Length on or off; the stage shows
|
||||
that frame. Drag the **IN** or **OUT** handle to trim: the playhead rides on the handle, so what you see
|
||||
is the first (IN) or last (OUT) frame the run keeps, and it stays there when you let
|
||||
go. IN and OUT are frames, snapped to the source's frame grid; the boxes under the
|
||||
rail take a frame number, and `start_seconds` / `end_seconds` are derived from them
|
||||
(OUT is exclusive, 0 means the end of the source). Arrow keys on a handle move one
|
||||
second, Shift one frame. **OUT always sits on the last frame the run outputs**, so
|
||||
the handle and the bright bar end together; with Every nth or Frames for it steps to the
|
||||
frames the run keeps, and a dim tail marks frames the window holds but the run
|
||||
drops. In the editor, **Set IN** / **Set OUT** (or the **I** / **O** keys) put a
|
||||
trim point at the playhead, and **Full clip** resets the window. The editor also
|
||||
has buttons for the first and last frame, steps of 1, 25, 50 and 100 frames, and
|
||||
**Play**. Arrow keys step one frame (10 with Shift), Home and End jump to the
|
||||
ends, and Space plays or pauses. **Save & close** keeps your edits; **Cancel** or
|
||||
@@ -70,16 +55,22 @@ model that paints black regions.
|
||||
fill colour with a faint hatch, so black bands show on the black stage. A fresh clip node starts
|
||||
with black and feather 0 and the editor's **Reset transform** returns to them;
|
||||
the image nodes keep their grey fill and feathered mask.
|
||||
- **Whole video / To start** (bottom right of the timing card): **Whole video**
|
||||
uses the whole source, with no Duration limit. When the length is linked, the
|
||||
button reads **To start** and moves the start to the beginning instead. The
|
||||
Duration stays when you swap the video, so a workflow built for 97 frames keeps
|
||||
taking 97.
|
||||
- **Length** (`max_frames`): the one other way to set how long the clip is. **Off**
|
||||
(the default): OUT ends the clip. **On**: a number of output frames from IN; OUT
|
||||
sits that many frames after IN and follows it when you drag IN, and dragging OUT or
|
||||
typing the number changes the Length. To move the whole clip, drag IN or the small
|
||||
grip in the middle of the kept part (the grip also slides a trimmed window with
|
||||
Length off). When the Length is the whole clip there is nowhere to move it, and the
|
||||
row says so: "= the whole clip. Shorten it to move IN." The Length stays when you
|
||||
swap the video, so a workflow built for 97 frames keeps taking 97. Turning it on or
|
||||
off never moves anything: the count becomes the OUT, or the OUT the count. If the
|
||||
source ends first, the footer says how many frames are left. **To start** moves IN
|
||||
to the start of the source.
|
||||
- **Every nth** (`every_nth`): Thin the batch. The `fps` output divides to match
|
||||
every_nth, so the clip keeps real-time downstream; a Duration counts the frames kept.
|
||||
every_nth, so the clip keeps real-time downstream; a Length counts the frames kept.
|
||||
- **Frames for** (`frame_snap`): Keep a frame count a video model takes:
|
||||
**LTX (8n+1)** (49, 97, 121) or **Wan (4n+1)**. **any** keeps every frame in the window.
|
||||
Dragging the end and typing a Duration step through those counts.
|
||||
OUT drags and the Length step through those counts.
|
||||
With it on, `frame_count`, `duration`, the audio window and the stitcher all match the
|
||||
clip the sampler hands back, so wiring `frame_count` into the empty latent's length
|
||||
never leaves the stitch with more source frames than generated ones.
|
||||
@@ -111,7 +102,7 @@ with the padlock on it also takes away the bands the lock added.
|
||||
**Reset** on the node clears rotation, crop and padding and turns the padlock off;
|
||||
fill, feather, **Align** and the timeline stay.
|
||||
**Reset transform** in the editor resets rotation, crop, padding, fill, feather and
|
||||
**Align**; it keeps the source, current frame, trim, Duration, resize and stitch
|
||||
**Align**; it keeps the source, current frame, trim, Length, resize and stitch
|
||||
settings. **Align** makes the width and height divide evenly by the number
|
||||
you pick: padding grows by a few pixels, and a side with no padding is trimmed by
|
||||
a few instead. Some models need sizes divisible by 8, 16 or 32; 1 turns it off.
|
||||
@@ -171,8 +162,8 @@ Five optional sockets sit on the left, above the editor:
|
||||
| `force_rate` | Sample at this fps before Every nth. 0 keeps the source rate. Drops or repeats frames to keep playback speed. Accepts FLOAT or INT. |
|
||||
| `start_frame` | Zero-based source start frame. Overrides timeline IN. |
|
||||
| `end_frame` | Exclusive source end frame. 0 means the end of the source. Overrides timeline OUT. |
|
||||
| `fixed_frames` | Exact output frames from IN; the source must be long enough. Connected, it sets the length: Duration, Ends at and Frames for step aside. |
|
||||
| `frame_load_cap` | Maximum frames after rate conversion and Every nth, before Frames for. 0 means unlimited. Connected, it sets the length in place of Duration. When the count is known, dragging the start stops at the last start that fits the kept frames. |
|
||||
| `fixed_frames` | Exact output frames from IN; the source must be long enough. Connected, it sets the length: OUT, Length and Frames for step aside. |
|
||||
| `frame_load_cap` | Maximum frames after rate conversion and Every nth, before Frames for. 0 means unlimited. Connected, it sets the length in place of Length. When the count is known, dragging IN stops at the last start that fits the kept frames. |
|
||||
| `last_seconds` | Load only this many seconds from the end of the clip, or of the part before OUT. 0 loads all of it. Use it to carry on from a clip: a long clip then costs no more memory than a short one. |
|
||||
|
||||
Frame bounds use the source's frame-rate grid, independent of `force_rate`.
|
||||
@@ -186,17 +177,17 @@ For example, start 24 and end 72 select two seconds from a 24 fps source.
|
||||
A 12 fps forced rate returns 24 frames; a cap of 10 then keeps only the first
|
||||
10 of those. Audio and duration follow the returned batch.
|
||||
|
||||
A connected start or end locks that handle and its box on both
|
||||
A connected start or end locks that handle and its IN/OUT field on both
|
||||
the node and fullscreen editor. Hover to see why. Disconnect to restore
|
||||
local control. While timing inputs are connected, the preview shows the local
|
||||
trim as a reference and avoids claiming an output count before the linked
|
||||
values are evaluated at run time.
|
||||
|
||||
**A connected length input takes over the length.** Connect a count to
|
||||
`fixed_frames` (exact) or `frame_load_cap` (at most) and the end handle goes
|
||||
away, Duration and Ends at lock, and only Start is left to set: the clip starts
|
||||
there and the input decides where it ends. Literal Integer/Float nodes (including
|
||||
`fixed_frames` (exact) or `frame_load_cap` (at most) and the OUT handle goes
|
||||
away, OUT and Length grey out, and only IN is left to set: the clip starts at
|
||||
IN and the input decides where it ends. Literal Integer/Float nodes (including
|
||||
AusBoss cards and reroutes) show the resulting frames on the rail before
|
||||
running; calculated counts show "at run time". An older workflow that saved a
|
||||
Fixed frames number without a connection reads as a Duration; the first change
|
||||
Fixed frames number without a connection reads as a Length; the first change
|
||||
here turns it into one.
|
||||
|
||||
@@ -60,12 +60,10 @@ answered on the same line as the button.
|
||||
- A found file swaps its Download button for an **✓ installed** pill; hovering
|
||||
the pill shows where it was found. A file that lives in a subfolder still
|
||||
counts. When a loader in the workflow still asks for the bare file name,
|
||||
which ComfyUI cannot find there (it marks that loader red), the note points
|
||||
that loader at your copy by itself and says so in a short message. If you
|
||||
have two copies in different subfolders, the row says where one is
|
||||
(**in LTXV 2.3/**) and **Use it** picks it. To always choose yourself, turn
|
||||
off Settings, 🆎 AusBoss, Models, **Pick found files**. The check only asks
|
||||
the ComfyUI server for its own model lists.
|
||||
which ComfyUI cannot find there (it marks that loader red), the row says
|
||||
where the file is instead (**in LTXV 2.3/**) and **Use it** points those
|
||||
loaders at the copy it found. The check only asks the ComfyUI server for its
|
||||
own model lists.
|
||||
- **↻ check files** re-runs the check after you move files in. ComfyUI's own
|
||||
**R** refresh triggers it as well.
|
||||
- Folder `input` is for a sample image or clip shipped with the workflow: it
|
||||
|
||||
@@ -17,7 +17,6 @@ help panel.
|
||||
| Pick a picture size by shape and megapixels, in place of Empty Latent | Latent Size (`AUSBOSS_NODES_Resolution`) |
|
||||
| Resize a picture, or snap its size to a multiple | Image Resize (`AUSBOSS_NODES_ImageResize`), Align Image (`AUSBOSS_NODES_AlignImage`) |
|
||||
| Read a picture's width and height | Image Size (`AUSBOSS_NODES_ImageSize`) |
|
||||
| Load a picture and set its size or crop it (megapixels, longest side, a box, a ratio) in one node | Load Image (`AUSBOSS_NODES_LoadImage`) |
|
||||
| Outpaint: load a picture and add empty space around it | Load Image + Pad (`AUSBOSS_NODES_LoadImagePad`) |
|
||||
| Turn, crop and pad a picture in one node | Image Crop + Rotate + Pad (`AUSBOSS_NODES_ImageCropRotatePad`) |
|
||||
| Inpaint only the masked part, then put it back | Crop For Inpaint (`AUSBOSS_NODES_CropForInpaint`) then Stitch Inpaint (`AUSBOSS_NODES_StitchInpaint`) |
|
||||
@@ -25,7 +24,6 @@ help panel.
|
||||
| Get a mask by typing what to find | Mask by Name (`AUSBOSS_NODES_MaskByName`) |
|
||||
| Get a mask by clicking the thing | Mask by Touch (`AUSBOSS_NODES_MaskByTouch`) |
|
||||
| Grow, shrink, fill or smooth a mask | Mask Refine (`AUSBOSS_NODES_RefineMask`) |
|
||||
| Keep the untouched parts of a picture exactly as they were while an edit model edits it | Edit Lock (`AUSBOSS_NODES_EditLock`) then Edit Lock Restore (`AUSBOSS_NODES_EditLockRestore`) |
|
||||
| Line an edited picture back up with the original | Realign to Source (`AUSBOSS_NODES_RealignToSource`, experimental) |
|
||||
| Match one picture's colors to another | Color Match (`AUSBOSS_NODES_ColorMatch`) |
|
||||
| Upscale big pictures in tiles | Tiled Upscale (`AUSBOSS_NODES_TiledUpscale`) then Tiled Upscale Stitch (`AUSBOSS_NODES_TiledUpscaleStitch`) |
|
||||
@@ -39,11 +37,8 @@ help panel.
|
||||
| Load a sound file and keep only part of it, up to a set length | Load Audio (`AUSBOSS_NODES_LoadAudio`) |
|
||||
| Turn, crop and pad a video: one frame, or the whole clip | Video Crop + Rotate + Pad → Frame (`AUSBOSS_NODES_VideoCropRotatePad`), → Clip (`AUSBOSS_NODES_VideoCropRotatePadClip`) |
|
||||
| Change a clip's frame rate | Frame Interpolate (`AUSBOSS_NODES_FrameInterpolate`) |
|
||||
| Make a clip larger and sharper | FlashVSR Upscale (`AUSBOSS_NODES_FlashVSRUpscale`) |
|
||||
| Work with frame batches | Select Frame, Select Every Nth, Split Batch, Merge Batches (`AUSBOSS_NODES_SelectFrame`, `_SelectEveryNth`, `_SplitBatch`, `_MergeBatches`) |
|
||||
| Run a workflow once for each line of text, such as a list of prompts | Text Lines (`AUSBOSS_NODES_TextLines`) |
|
||||
| One shared seed, number or text | Seed, Integer, Float, Text (`AUSBOSS_NODES_Seed`, `_Integer`, `_Float`, `_Text`) |
|
||||
| A prompt that picks from `{a\|b\|c}` choices on each run, by seed | Prompt Variations (`AUSBOSS_NODES_PromptVariations`) |
|
||||
| Do maths on numbers | Math Expression (`AUSBOSS_NODES_MathExpression`) |
|
||||
| Show text on the node, or the picture while it is made | Show Text (`AUSBOSS_NODES_ShowText`), Step Preview (`AUSBOSS_NODES_StepPreview`) |
|
||||
| Free graphics memory between steps | Free Memory (`AUSBOSS_NODES_FreeMemory`) |
|
||||
|
||||
+13
-57
@@ -26,7 +26,6 @@ import {
|
||||
childOf,
|
||||
countLine,
|
||||
foldersAddress,
|
||||
folderContext,
|
||||
isPicked,
|
||||
listAddress,
|
||||
nameAt,
|
||||
@@ -275,7 +274,6 @@ async function refresh(state) {
|
||||
}
|
||||
|
||||
function scheduleRefresh(state, delay = 160) {
|
||||
++state.token;
|
||||
clearTimeout(state.timer);
|
||||
state.timer = setTimeout(() => refresh(state), delay);
|
||||
}
|
||||
@@ -344,7 +342,6 @@ async function upload(file, subfolder, overwrite) {
|
||||
|
||||
// Loose pictures go into the folder the node shows.
|
||||
async function addFiles(state, files) {
|
||||
if (!state.alive) return false;
|
||||
const now = settings(state.node);
|
||||
const images = [...(files ?? [])].filter(isPicture);
|
||||
if (!images.length) return false;
|
||||
@@ -355,13 +352,10 @@ async function addFiles(state, files) {
|
||||
const added = [];
|
||||
let failed = 0;
|
||||
for (const file of images) {
|
||||
if (!state.alive) return true;
|
||||
const name = await upload(file, now.folder, false);
|
||||
if (!state.alive) return true;
|
||||
if (name) added.push(name); else failed += 1;
|
||||
}
|
||||
await refresh(state);
|
||||
if (!state.alive) return true;
|
||||
// A hand-made pick takes the new pictures in: they were just put there to be used.
|
||||
const picked = parsePicked(settings(state.node).pictures);
|
||||
if (picked !== null && added.length) setPicked(state, [...picked, ...added.filter((name) => state.names.includes(name))]);
|
||||
@@ -394,7 +388,6 @@ function closeAsk(answer = false) {
|
||||
}
|
||||
|
||||
function askBig(state, name, pictures) {
|
||||
if (!state.alive) return Promise.resolve(false);
|
||||
const bytes = pictures.reduce((sum, item) => sum + (Number(item.file?.size) || 0), 0);
|
||||
if (pictures.length <= BIG_COUNT && bytes <= BIG_BYTES) return Promise.resolve(true);
|
||||
closeAsk(false);
|
||||
@@ -411,7 +404,7 @@ function askBig(state, name, pictures) {
|
||||
foot.append(cancel, go);
|
||||
root.append(foot);
|
||||
const abort = new AbortController();
|
||||
openAsk = { root, abort, done, state };
|
||||
openAsk = { root, abort, done };
|
||||
cancel.addEventListener("click", () => closeAsk(false));
|
||||
go.addEventListener("click", () => closeAsk(true));
|
||||
document.body.append(root);
|
||||
@@ -427,17 +420,7 @@ function askBig(state, name, pictures) {
|
||||
// input/<its name>, folders inside it too, and the node moves there. Copying
|
||||
// the same folder again writes over its copies instead of piling up doubles.
|
||||
async function copyFolder(state, name, pictures) {
|
||||
if (!state.alive || state.copyLocked) return;
|
||||
state.copyLocked = true;
|
||||
try {
|
||||
if (!(await askBig(state, name, pictures)) || !state.alive) return;
|
||||
await copyPictures(state, name, pictures);
|
||||
} finally {
|
||||
state.copyLocked = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function copyPictures(state, name, pictures) {
|
||||
if (!(await askBig(state, name, pictures)) || !state.alive) return;
|
||||
const target = folderName(name);
|
||||
const queue = pictures.slice(0, COPY_LIMIT);
|
||||
state.copying = { done: 0, total: queue.length, name, target };
|
||||
@@ -448,9 +431,7 @@ async function copyPictures(state, name, pictures) {
|
||||
for (;;) {
|
||||
const next = queue.shift();
|
||||
if (!next || !state.alive) return;
|
||||
const added = await upload(next.file, next.folder ? `${target}/${next.folder}` : target, true);
|
||||
if (!state.alive) return;
|
||||
if (added) copied += 1;
|
||||
if (await upload(next.file, next.folder ? `${target}/${next.folder}` : target, true)) copied += 1;
|
||||
state.copying.done += 1;
|
||||
paint(state);
|
||||
cover(state);
|
||||
@@ -463,7 +444,6 @@ async function copyPictures(state, name, pictures) {
|
||||
if (!state.alive) return;
|
||||
const moved = write(state.node, "source", "input") | write(state.node, "folder", target);
|
||||
if (moved) notifyAusbossChange(); else await refresh(state);
|
||||
if (!state.alive) return;
|
||||
paint(state);
|
||||
showToast({ detail: `Copied ${copied} picture${copied === 1 ? "" : "s"} from "${name}" into your ComfyUI input folder (input/${target}).` });
|
||||
if (copied < total) showToast({ severity: "warn", detail: `${total - copied} could not be copied.` });
|
||||
@@ -526,7 +506,7 @@ function addMenu(state, anchor) {
|
||||
closeMenu();
|
||||
const root = el("div", "ausboss-if-menu");
|
||||
const abort = new AbortController();
|
||||
openMenu = { root, abort, state };
|
||||
openMenu = { root, abort };
|
||||
const row = (text, title, run) => {
|
||||
const button = el("button", "ausboss-if-browse-row", text);
|
||||
button.type = "button"; button.title = title;
|
||||
@@ -565,25 +545,19 @@ async function browse(state, anchor) {
|
||||
foot.append(cancel, use);
|
||||
root.append(path, list, foot);
|
||||
const abort = new AbortController();
|
||||
openBrowse = { root, abort, state };
|
||||
openBrowse = { root, abort };
|
||||
let at = now.folder;
|
||||
let source = now.source;
|
||||
let navigation = 0;
|
||||
|
||||
const show = async (folder) => {
|
||||
const token = ++navigation;
|
||||
use.disabled = true;
|
||||
let data = null;
|
||||
try {
|
||||
const response = await api.fetchApi(foldersAddress({ source, folder }));
|
||||
const response = await api.fetchApi(foldersAddress({ source: now.source, folder }));
|
||||
if (response.ok) data = await response.json();
|
||||
} catch { /* shown as an empty list below */ }
|
||||
if (openBrowse?.root !== root || token !== navigation || !state.alive) return;
|
||||
if (openBrowse?.root !== root) return;
|
||||
if (!data && folder) return show(""); // a folder that is gone: start at the top
|
||||
at = data?.folder ?? "";
|
||||
source = data?.source ?? source;
|
||||
use.disabled = false;
|
||||
path.replaceChildren(document.createTextNode(`${source} / `), el("b", "", at || "(the folder itself)"));
|
||||
path.replaceChildren(document.createTextNode(`${now.source} / `), el("b", "", at || "(the folder itself)"));
|
||||
list.replaceChildren();
|
||||
if (at) {
|
||||
const up = el("button", "ausboss-if-browse-row up", "↑ up");
|
||||
@@ -608,9 +582,7 @@ async function browse(state, anchor) {
|
||||
};
|
||||
|
||||
use.addEventListener("click", () => {
|
||||
if (use.disabled || !state.alive) return;
|
||||
const moved = write(state.node, "source", source) | write(state.node, "folder", at);
|
||||
if (moved) notifyAusbossChange();
|
||||
if (write(state.node, "folder", at)) notifyAusbossChange();
|
||||
closeBrowse();
|
||||
});
|
||||
cancel.addEventListener("click", closeBrowse);
|
||||
@@ -734,12 +706,6 @@ function buildPanel(node) {
|
||||
const now = settings(node);
|
||||
const key = `${now.source}|${now.folder}|${now.subfolders}|${now.sort}`;
|
||||
if (key === state.key) { paint(state); return; }
|
||||
const context = folderContext(now);
|
||||
if (context !== state.context) {
|
||||
state.done.clear();
|
||||
state.loadedLine = "";
|
||||
state.context = context;
|
||||
}
|
||||
// Another folder holds other names: a pick made in the old one means nothing there.
|
||||
const moved = state.key && (now.source !== state.shown.source || now.folder !== state.shown.folder || now.subfolders !== state.shown.subfolders);
|
||||
state.key = key;
|
||||
@@ -759,9 +725,7 @@ function buildPanel(node) {
|
||||
const now = settings(node);
|
||||
if (now.run !== "one per run" || isLinked(node, "position")) return;
|
||||
const count = pickedNames(parsePicked(now.pictures), state.names).length;
|
||||
// The folder can change on disk or arrive through a link. Only the
|
||||
// backend knows where it ends; a cached gallery must not cap "next".
|
||||
const next = nextPosition(now.position, now.afterRun === "next" ? null : count, now.afterRun, now.atTheEnd);
|
||||
const next = nextPosition(now.position, count, now.afterRun, now.atTheEnd);
|
||||
if (next !== now.position) { position.value = next; position.callback?.(next); }
|
||||
});
|
||||
}
|
||||
@@ -784,7 +748,6 @@ function buildPanel(node) {
|
||||
});
|
||||
|
||||
const now = settings(node);
|
||||
state.context = folderContext(now);
|
||||
state.key = `${now.source}|${now.folder}|${now.subfolders}|${now.sort}`;
|
||||
rebuild(state);
|
||||
scheduleRefresh(state, 60);
|
||||
@@ -810,18 +773,12 @@ app.registerExtension({
|
||||
});
|
||||
chainCallback(nodeType.prototype, "onConfigure", function (info) {
|
||||
const state = buildPanel(this);
|
||||
++state.token;
|
||||
clearTimeout(state.timer);
|
||||
state.done.clear();
|
||||
state.loadedLine = "";
|
||||
// A node that comes with a size keeps it, the smallest one too.
|
||||
if (info?.size) state.sized = true;
|
||||
// A loaded workflow brings its own folder and its own pick.
|
||||
state.restoring = true;
|
||||
queueMicrotask(() => {
|
||||
if (!state.alive) return;
|
||||
const now = settings(this);
|
||||
state.context = folderContext(now);
|
||||
state.key = `${now.source}|${now.folder}|${now.subfolders}|${now.sort}`;
|
||||
state.restoring = false;
|
||||
scheduleRefresh(state, 30);
|
||||
@@ -832,7 +789,6 @@ app.registerExtension({
|
||||
const state = this.__ausbossImageFolder;
|
||||
const note = output?.ausboss_image_folder?.[0];
|
||||
if (!state?.alive || !note) return;
|
||||
if (!note.context || folderContext(note.context) !== folderContext(settings(this))) return;
|
||||
for (const name of note.names ?? []) state.done.add(name);
|
||||
const loaded = note.loaded ?? [];
|
||||
state.loadedLine = loaded.length === 1
|
||||
@@ -849,9 +805,9 @@ app.registerExtension({
|
||||
state.abort.abort();
|
||||
state.choosing?.abort();
|
||||
clearTimeout(state.dropTimer);
|
||||
if (openBrowse?.state === state) closeBrowse();
|
||||
if (openMenu?.state === state) closeMenu();
|
||||
if (openAsk?.state === state) closeAsk(false);
|
||||
if (openBrowse) closeBrowse();
|
||||
if (openMenu) closeMenu();
|
||||
if (openAsk?.root && state.grid.isConnected === false) closeAsk(false);
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
+45
-346
@@ -14,28 +14,25 @@
|
||||
// switch lays each sampling step over the stage, with a Stop button on the
|
||||
// bar (shared/step_preview.mjs).
|
||||
|
||||
import { panelSwitch, primaryAction } from "../shared/panel_controls.mjs";
|
||||
import { panelSwitch } from "../shared/panel_controls.mjs";
|
||||
import { api } from "../../../scripts/api.js";
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { isForeignRun } from "../shared/prompt_scope.mjs";
|
||||
import { executionIdOf, nodeByExecutionId } from "../shared/graph_ids.mjs";
|
||||
import { FONT_UI, RADIUS_CONTROL, RADIUS_XS, THEME as T } from "../shared/theme.mjs";
|
||||
import { chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange } from "../shared/index.mjs";
|
||||
import { BRAND, chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange } from "../shared/index.mjs";
|
||||
import { ensureNodeMinHeight, fillNodeHeight, growToNodeFloor } from "../shared/panel_layout.mjs";
|
||||
import { suppressCoreImagePreview } from "../shared/core_preview.mjs";
|
||||
import { autoMaskValues } from "../shared/mask_auto.mjs";
|
||||
import { hideInputsInDef, hideWidget, setWidgetVisible } from "../shared/widget_visibility.mjs";
|
||||
import { makePictureStepper } from "../shared/picture_stepper.mjs";
|
||||
import { ALL, allLabel, gridShape, heldPlaces, keepIndex, keepWords, stepIndex, stepWithAll } from "../shared/picture_steps.mjs";
|
||||
import { keepIndex, stepIndex } from "../shared/picture_steps.mjs";
|
||||
import { addStepConsumer, mountStepOverlay, showsStepsOn, stepRun, stopStepRun, watchSteps } from "../shared/step_preview.mjs";
|
||||
import {
|
||||
describeNodePreview,
|
||||
describeSourcePreview,
|
||||
lightPreviewQuery,
|
||||
outputLocatorId,
|
||||
outputRecordCount,
|
||||
outputRecordQuery,
|
||||
ownResultIsCurrent,
|
||||
placeholderText,
|
||||
staleText,
|
||||
sourceFileWidget,
|
||||
@@ -56,15 +53,7 @@ const BAR_GAP = 6;
|
||||
const BAR_PADDING = 2;
|
||||
const PANEL_HEIGHT = STAGE_HEIGHT + BAR_HEIGHT + 4 + 16;
|
||||
const OFF_HEIGHT = BAR_HEIGHT + 16;
|
||||
// The row over pictures that wait for a Save, and the gap under it.
|
||||
const KEEP_HEIGHT = 30;
|
||||
const KEEP_SPACE = KEEP_HEIGHT + 4;
|
||||
const INPUT_SIDE = 1; // LiteGraph.INPUT
|
||||
// A run that left this many pictures or fewer opens with all of them side
|
||||
// by side. More than that and each would be a speck, so the arrows go
|
||||
// through them one at a time, as before.
|
||||
const GRID_MAX = 48;
|
||||
const GRID_GAP = 4;
|
||||
// The node's height from before its preview was switched off, so switching
|
||||
// it back on returns the node to it (saved with the workflow).
|
||||
const HEIGHT_PROPERTY = "ausboss_preview_height";
|
||||
@@ -124,17 +113,7 @@ const NODE_CONFIG = {
|
||||
},
|
||||
AUSBOSS_NODES_SelectFrame: { inputName: "frames", noun: "frames" },
|
||||
// Its result is the file it just saved; the card sits above the panel.
|
||||
// SAVE shows only for a run made with Auto save off, which holds its
|
||||
// pictures until this button keeps them.
|
||||
AUSBOSS_NODES_SaveImage: {
|
||||
inputName: "images",
|
||||
noun: "an image",
|
||||
switchTitle: "Show the saved image here. The file is saved either way.",
|
||||
steps: true,
|
||||
// Auto save off: a row over the picture says it is not saved yet and
|
||||
// holds the button that saves it.
|
||||
keep: "Save what is showing: every picture, or the one the arrows picked.",
|
||||
},
|
||||
AUSBOSS_NODES_SaveImage: { inputName: "images", noun: "an image", switchTitle: "Show the saved image here. The file is saved either way.", steps: true },
|
||||
};
|
||||
|
||||
// The picture sits out of flow, centred in the stage, so it can never set
|
||||
@@ -151,40 +130,28 @@ function ensureCss() {
|
||||
style.textContent = `
|
||||
.ausboss-input-preview{box-sizing:border-box;display:flex;flex-direction:column;gap:4px;width:100%;height:100%;padding:0 6px 6px;pointer-events:none;overflow:hidden;}
|
||||
.ausboss-input-preview-bar{box-sizing:border-box;flex:none;display:flex;align-items:center;gap:${BAR_GAP}px;height:${BAR_HEIGHT}px;padding:0 ${BAR_PADDING}px;pointer-events:none;}
|
||||
.ausboss-input-preview-stage{position:relative;flex:1 1 auto;min-height:0;display:flex;align-items:center;justify-content:center;width:100%;overflow:hidden;border:1px solid ${T.rule};border-radius:${RADIUS_CONTROL}px;background:${T.well};}
|
||||
.ausboss-input-preview-stage{position:relative;flex:1 1 auto;min-height:0;display:flex;align-items:center;justify-content:center;width:100%;overflow:hidden;border:1px solid rgba(0,180,170,.27);border-radius:6px;background:rgba(0,0,0,.28);}
|
||||
[data-node-id] .ausboss-input-preview-stage{box-sizing:border-box;min-height:${STAGE_HEIGHT}px;}
|
||||
.ausboss-input-preview.preview-off .ausboss-input-preview-stage{display:none;}
|
||||
.ausboss-input-preview.preview-off .ausboss-stepper{display:none;}
|
||||
.ausboss-input-preview-stage img,.ausboss-input-preview-stage video{display:none;position:absolute;inset:0;margin:auto;max-width:100%;max-height:100%;object-fit:contain;}
|
||||
.ausboss-input-preview-stage.show-image img{display:block;}
|
||||
.ausboss-input-preview-stage.loading-image img{opacity:.4;transition:opacity .3s ease 1.2s;}
|
||||
.ausboss-input-preview-stage.show-video video{display:block;}
|
||||
.ausboss-input-preview-grid{display:none;position:absolute;inset:0;box-sizing:border-box;gap:${GRID_GAP}px;padding:${GRID_GAP}px;justify-content:center;align-content:center;}
|
||||
.ausboss-input-preview-stage.show-grid .ausboss-input-preview-grid{display:grid;}
|
||||
.ausboss-input-preview-stage .ausboss-input-preview-grid img{display:block;position:static;margin:0;width:100%;height:100%;min-width:0;min-height:0;max-width:none;max-height:none;object-fit:contain;}
|
||||
.ausboss-input-preview-hint{display:none;max-width:86%;color:${T.faint};font:11px/1.35 ${FONT_UI};text-align:center;}
|
||||
.ausboss-input-preview-stage:not(.show-image):not(.show-video):not(.show-grid) .ausboss-input-preview-hint{display:block;}
|
||||
.ausboss-input-preview-keep{box-sizing:border-box;flex:none;display:flex;align-items:center;justify-content:space-between;gap:10px;height:${KEEP_HEIGHT}px;padding:0 4px 0 10px;border-radius:${RADIUS_CONTROL}px;background:${T.brandSoft};pointer-events:none;}
|
||||
.ausboss-input-preview-keep[hidden]{display:none;}
|
||||
.ausboss-input-preview-keep span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:${T.brandInk};font:600 11px/1.2 ${FONT_UI};}
|
||||
.ausboss-input-preview-keep.done{background:${T.fill};}
|
||||
.ausboss-input-preview-keep.done span{color:${T.label};}
|
||||
.ausboss-input-preview-hint{display:none;max-width:86%;color:#78908e;font:11px/1.35 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;text-align:center;}
|
||||
.ausboss-input-preview-stage:not(.show-image):not(.show-video) .ausboss-input-preview-hint{display:block;}
|
||||
.ausboss-input-preview-tools{display:flex;gap:4px;pointer-events:auto;}
|
||||
.ausboss-input-preview-tool{box-sizing:border-box;height:${BAR_HEIGHT}px;min-width:24px;padding:0 6px;border:1px solid transparent;border-radius:${RADIUS_XS}px;background:${T.fill};color:${T.label};font:600 9.5px/18px ${FONT_UI};letter-spacing:.02em;cursor:pointer;}
|
||||
.ausboss-input-preview-tool[hidden]{display:none;}
|
||||
.ausboss-input-preview-stage .ausboss-input-preview-grid img.kept{outline:2px solid ${T.brand};outline-offset:-2px;}
|
||||
.ausboss-input-preview-tool:hover{color:${T.ink};background:${T.fillHover};}
|
||||
.ausboss-input-preview-tool.active{color:${T.brandInk};background:${T.brandSoft};}
|
||||
.ausboss-input-preview-tool:focus-visible{outline:2px solid ${T.brand};outline-offset:1px;}
|
||||
.ausboss-input-preview-tool{box-sizing:border-box;height:${BAR_HEIGHT}px;min-width:24px;padding:0 6px;border:1px solid rgba(0,180,170,.52);border-radius:4px;background:rgba(0,0,0,.7);color:#c8dddd;font:700 9px/18px "Segoe UI",sans-serif;cursor:pointer;}
|
||||
.ausboss-input-preview-tool:hover{border-color:${BRAND};color:#fff;background:rgba(0,79,75,.78);}
|
||||
.ausboss-input-preview-tool.active{border-color:${BRAND};color:${BRAND};}
|
||||
.ausboss-input-preview:not(.preview-off) .ausboss-panel-switch.steps + .ausboss-panel-switch{margin-left:0;}
|
||||
.ausboss-input-preview.preview-off .ausboss-panel-switch.steps{display:none;}
|
||||
.ausboss-input-preview-tool.ausboss-steps-stop{visibility:hidden;}
|
||||
.ausboss-input-preview-tool.ausboss-steps-stop.live{visibility:visible;pointer-events:auto;}
|
||||
.ausboss-input-preview-readout{box-sizing:border-box;height:${BAR_HEIGHT}px;padding:0 7px;border:1px solid transparent;border-radius:999px;background:${T.brandSoft};color:${T.brandInk};font:600 9.5px/18px ${FONT_UI};font-variant-numeric:tabular-nums;white-space:nowrap;pointer-events:none;}
|
||||
.ausboss-input-preview-readout{box-sizing:border-box;height:${BAR_HEIGHT}px;padding:0 7px;border:1px solid rgba(0,180,170,.5);border-radius:10px;background:rgba(0,180,170,.14);color:${BRAND};font:700 9.5px/18px "Segoe UI",sans-serif;white-space:nowrap;pointer-events:none;}
|
||||
.ausboss-input-preview-readout:empty{display:none;}
|
||||
.ausboss-input-preview-readout.warn{background:${T.warnSoft};color:${T.warnInk};}
|
||||
.ausboss-input-preview-note{display:none;position:absolute;left:6px;right:6px;bottom:6px;z-index:6;padding:6px 8px;border:1px solid ${T.warn};border-radius:${RADIUS_CONTROL}px;background:${T.warnSoft};color:${T.warnInk};font:600 11px/1.35 ${FONT_UI};text-align:center;pointer-events:none;}
|
||||
.ausboss-input-preview-toast{position:absolute;left:50%;bottom:6px;z-index:5;max-width:88%;padding:3px 7px;border-radius:${RADIUS_XS}px;background:${T.fill};color:${T.inkSoft};font:10px/1.3 ${FONT_UI};text-align:center;transform:translateX(-50%);pointer-events:none;}
|
||||
.ausboss-input-preview-readout.warn{border-color:#c98a2b;background:rgba(201,138,43,.16);color:#ffd9a0;}
|
||||
.ausboss-input-preview-note{display:none;position:absolute;left:6px;right:6px;bottom:6px;z-index:6;padding:6px 8px;border:1px solid #c98a2b;border-radius:6px;background:rgba(20,10,0,.86);color:#ffd9a0;font:600 11px/1.35 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;text-align:center;pointer-events:none;}
|
||||
.ausboss-input-preview-toast{position:absolute;left:50%;bottom:6px;z-index:5;max-width:88%;padding:3px 7px;border-radius:4px;background:rgba(0,0,0,.78);color:#b8d3d1;font:10px/1.3 "Segoe UI",sans-serif;text-align:center;transform:translateX(-50%);pointer-events:none;}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
@@ -477,12 +444,12 @@ function syncPreviewMode(state, resize) {
|
||||
}
|
||||
if (!enabled) {
|
||||
// Nothing to show and nothing to fetch while it is off.
|
||||
clearMedia(state);
|
||||
state.img.removeAttribute("src");
|
||||
}
|
||||
if (resize) {
|
||||
const node = state.node;
|
||||
node.properties ??= {};
|
||||
const floor = node.computeSize?.()[1] ?? panelFloor(state);
|
||||
const floor = node.computeSize?.()[1] ?? (enabled ? PANEL_HEIGHT : OFF_HEIGHT);
|
||||
if (!enabled) {
|
||||
// Off: remember the height, then shrink to what is left.
|
||||
const height = Number(node.size?.[1]);
|
||||
@@ -525,7 +492,7 @@ function buildTools(state, tools, signal) {
|
||||
}
|
||||
|
||||
function showHint(state, text) {
|
||||
state.stage.classList.remove("show-image", "show-video", "show-grid");
|
||||
state.stage.classList.remove("show-image", "show-video");
|
||||
state.hint.textContent = text;
|
||||
state.placeholder = null;
|
||||
releaseSteps(state);
|
||||
@@ -540,76 +507,24 @@ function showPlaceholder(state, connected) {
|
||||
function showMedia(state, kind) {
|
||||
state.stage.classList.toggle("show-image", kind === "image");
|
||||
state.stage.classList.toggle("show-video", kind === "video");
|
||||
state.stage.classList.toggle("show-grid", kind === "grid");
|
||||
state.placeholder = null;
|
||||
releaseSteps(state);
|
||||
}
|
||||
|
||||
function clearMedia(state) {
|
||||
state.img.removeAttribute("src");
|
||||
state.stage.classList.remove("loading-image");
|
||||
state.video.pause?.();
|
||||
state.video.removeAttribute("src");
|
||||
clearGrid(state);
|
||||
}
|
||||
|
||||
function clearGrid(state) {
|
||||
if (!state.gridKey) return;
|
||||
state.gridKey = "";
|
||||
state.grid?.replaceChildren();
|
||||
}
|
||||
|
||||
// Every picture of the run at once, each as big as the stage allows.
|
||||
function layoutGrid(state) {
|
||||
const cells = [...(state.grid?.children ?? [])];
|
||||
if (!cells.length) return;
|
||||
const loaded = cells.find((cell) => cell.naturalWidth > 0 && cell.naturalHeight > 0);
|
||||
const aspect = loaded ? loaded.naturalWidth / loaded.naturalHeight : 1;
|
||||
const { columns, rows } = gridShape(cells.length, state.stage.clientWidth, state.stage.clientHeight, aspect);
|
||||
// Tracks the size of one picture, so the pictures sit together in the
|
||||
// middle of the stage with no bands between the rows.
|
||||
const wide = (state.stage.clientWidth - GRID_GAP * (columns + 1)) / columns;
|
||||
const tall = (state.stage.clientHeight - GRID_GAP * (rows + 1)) / rows;
|
||||
if (!(wide > 0) || !(tall > 0)) return;
|
||||
const width = Math.floor(Math.min(wide, tall * aspect));
|
||||
const height = Math.floor(width / aspect);
|
||||
state.grid.style.gridTemplateColumns = `repeat(${columns}, ${width}px)`;
|
||||
state.grid.style.gridTemplateRows = `repeat(${rows}, ${height}px)`;
|
||||
}
|
||||
|
||||
function showGrid(state, count) {
|
||||
const urls = Array.from({ length: count }, (_, index) => storedResultUrl(state.node, index) ?? "");
|
||||
const key = urls.join("\n");
|
||||
if (state.gridKey !== key) {
|
||||
state.gridKey = key;
|
||||
state.grid.replaceChildren(...urls.map((url, index) => {
|
||||
const cell = document.createElement("img");
|
||||
cell.alt = `Picture ${index + 1} of ${count}`;
|
||||
cell.decoding = "async";
|
||||
// The first picture to load tells the grid the shape to lay out for.
|
||||
cell.addEventListener("load", () => layoutGrid(state), { once: true });
|
||||
cell.addEventListener("error", () => dropLightPreview(state), { once: true });
|
||||
cell.src = url;
|
||||
return cell;
|
||||
}));
|
||||
}
|
||||
state.img.removeAttribute("src");
|
||||
state.video.pause?.();
|
||||
state.video.removeAttribute("src");
|
||||
layoutGrid(state);
|
||||
showMedia(state, "grid");
|
||||
}
|
||||
|
||||
// Each source has one hook, with subscribers that can leave in any order.
|
||||
const sourceWatchers = new WeakMap();
|
||||
// Restore the watched widget's callback if our hook is still the tail of the
|
||||
// chain; if someone chained after us the hook simply goes inert via
|
||||
// state.alive. We never create object URLs, so there is nothing to revoke.
|
||||
function unwatchSource(state) {
|
||||
const watched = state.watched;
|
||||
state.watched = null;
|
||||
if (!watched) return;
|
||||
watched.subscribers.delete(state);
|
||||
if (!watched.subscribers.size && watched.widget.callback === watched.hook) {
|
||||
if (watched && watched.widget.callback === watched.hook) {
|
||||
watched.widget.callback = watched.prior;
|
||||
sourceWatchers.delete(watched.widget);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -618,21 +533,14 @@ function rewatchSource(state, source) {
|
||||
if (state.watched?.widget === widget) return;
|
||||
unwatchSource(state);
|
||||
if (!widget) return;
|
||||
let watched = sourceWatchers.get(widget);
|
||||
if (!watched) {
|
||||
const prior = widget.callback;
|
||||
const subscribers = new Set();
|
||||
const hook = function (...args) {
|
||||
const result = prior?.apply(this, args);
|
||||
for (const subscriber of subscribers) if (subscriber.alive) scheduleRefresh(subscriber);
|
||||
return result;
|
||||
};
|
||||
watched = { widget, prior, hook, subscribers };
|
||||
sourceWatchers.set(widget, watched);
|
||||
widget.callback = hook;
|
||||
}
|
||||
watched.subscribers.add(state);
|
||||
state.watched = watched;
|
||||
const prior = widget.callback;
|
||||
const hook = function (...args) {
|
||||
const result = prior?.apply(this, args);
|
||||
if (state.alive) scheduleRefresh(state);
|
||||
return result;
|
||||
};
|
||||
widget.callback = hook;
|
||||
state.watched = { widget, prior, hook };
|
||||
}
|
||||
|
||||
// The node's stored output as a /view URL, for Nodes 2.0, where node.imgs
|
||||
@@ -641,36 +549,17 @@ function rewatchSource(state, source) {
|
||||
// record: an overwritten file reloads after the next run, and a plain refresh
|
||||
// never reloads the picture.
|
||||
const storedRand = new WeakMap();
|
||||
const outputRecord = (node) => app.nodeOutputs?.[outputLocatorId(node)];
|
||||
// Save Image also writes a small copy of each picture for its face, and the
|
||||
// panel shows that one: a few hundred kilobytes where the file can be tens
|
||||
// of megabytes. The copies are in the temp folder, which ComfyUI empties
|
||||
// when it starts; a record whose copy is gone goes back to the file itself.
|
||||
const lightGone = new WeakSet();
|
||||
function lightQuery(record, index = null) {
|
||||
return record && !lightGone.has(record) ? lightPreviewQuery(record, index) : null;
|
||||
}
|
||||
function storedResultUrl(node, index = null) {
|
||||
const record = outputRecord(node);
|
||||
const light = lightQuery(record, index);
|
||||
const query = light ?? outputRecordQuery(record, index);
|
||||
const record = app.nodeOutputs?.[outputLocatorId(node)];
|
||||
const query = outputRecordQuery(record, index);
|
||||
if (!query) return null;
|
||||
if (!storedRand.has(record)) storedRand.set(record, app.getRandParam?.() ?? "");
|
||||
return api.apiURL(`/view?${query}${light ? "" : app.getPreviewFormatParam?.() ?? ""}${storedRand.get(record)}`);
|
||||
}
|
||||
// A small copy that would not load: show the file itself from now on.
|
||||
function dropLightPreview(state) {
|
||||
const record = outputRecord(state.node);
|
||||
if (!lightQuery(record)) return false;
|
||||
lightGone.add(record);
|
||||
scheduleRefresh(state);
|
||||
return true;
|
||||
return api.apiURL(`/view?${query}${app.getPreviewFormatParam?.() ?? ""}${storedRand.get(record)}`);
|
||||
}
|
||||
|
||||
// Several pictures from one run (a list, or a batch Save Image saved one by
|
||||
// one): they all show side by side, and the arrows in the bar go on to each
|
||||
// one by itself and back round to all of them. One picture keeps the panel
|
||||
// as it was, with no arrows.
|
||||
// one): the arrows in the bar pick which one shows. One picture keeps the
|
||||
// panel as it was, with no arrows.
|
||||
function resultCount(state) {
|
||||
if (state.stale || state.resultGone) return 0;
|
||||
return outputRecordCount(app.nodeOutputs?.[outputLocatorId(state.node)]);
|
||||
@@ -686,174 +575,21 @@ function previewMinWidth(state) {
|
||||
return Math.max(PANEL_MIN_WIDTH, Math.ceil(state.node.size[0] - state.bar.clientWidth + needed));
|
||||
}
|
||||
|
||||
// --- pictures held until Save (Save Image with Auto save off) ---------------
|
||||
|
||||
// The pictures this node is holding, in the order it shows them. Empty when
|
||||
// the last run saved its pictures itself.
|
||||
function heldPictures(state) {
|
||||
if (state.stale || state.resultGone) return [];
|
||||
return heldPlaces(app.nodeOutputs?.[outputLocatorId(state.node)]);
|
||||
}
|
||||
|
||||
// Which of the shown pictures are kept, by their place on the node.
|
||||
function keptOf(state, held) {
|
||||
const key = held.map((picture) => `${picture.token}_${picture.index}`).join(" ");
|
||||
if (state.kept?.key !== key) state.kept = { key, indexes: new Set() };
|
||||
return state.kept.indexes;
|
||||
}
|
||||
|
||||
// A click keeps every picture, or only the one the arrows picked. With the
|
||||
// preview off there is no picture to pick, so it keeps them all.
|
||||
function keepsAll(state, count) {
|
||||
return count < 2 || showsAll(state, count) || !previewEnabled(state);
|
||||
}
|
||||
|
||||
// The row shows while the node holds pictures. It says what is saved, and
|
||||
// its button what a click will do (keepWords).
|
||||
function syncHeld(state, count = resultCount(state)) {
|
||||
const row = state.keepRow;
|
||||
if (!row) return;
|
||||
const held = heldPictures(state);
|
||||
const hidden = !held.length || count < 1;
|
||||
if (row.hidden !== hidden) {
|
||||
row.hidden = hidden;
|
||||
fitKeepRow(state);
|
||||
}
|
||||
if (hidden) return;
|
||||
const kept = keptOf(state, held);
|
||||
const all = keepsAll(state, count);
|
||||
const done = all ? kept.size >= held.length : kept.has(state.index);
|
||||
const words = keepWords({
|
||||
held: held.length, kept: kept.size, all, done, saving: Boolean(state.keeping), name: state.kept?.name ?? "",
|
||||
});
|
||||
state.keepNote.textContent = words.note;
|
||||
state.keepNote.title = state.kept?.path ? `ComfyUI/output/${state.kept.path}` : "";
|
||||
state.keepButton.textContent = words.button;
|
||||
state.keepButton.classList.toggle("quiet", words.quiet);
|
||||
state.keepButton.disabled = Boolean(state.keeping);
|
||||
row.classList.toggle("done", words.quiet && kept.size >= held.length);
|
||||
[...(state.grid?.children ?? [])].forEach((cell, index) => cell.classList.toggle("kept", kept.has(index)));
|
||||
}
|
||||
|
||||
// The row takes room of its own, so the picture keeps its floor: the node
|
||||
// grows to hold it, and a node with the preview off gives the room back.
|
||||
function fitKeepRow(state) {
|
||||
const node = state.node;
|
||||
if (previewEnabled(state)) {
|
||||
ensureNodeMinHeight(node);
|
||||
} else {
|
||||
const floor = Number(node.computeSize?.()?.[1]);
|
||||
if (Number.isFinite(floor)) node.setSize?.([node.size?.[0] ?? PANEL_MIN_WIDTH, floor]);
|
||||
}
|
||||
node.setDirtyCanvas?.(true, true);
|
||||
}
|
||||
|
||||
function buildKeepRow(state, title, signal) {
|
||||
const row = document.createElement("div");
|
||||
row.className = "ausboss-input-preview-keep";
|
||||
row.hidden = true;
|
||||
const note = document.createElement("span");
|
||||
const button = primaryAction("Save picture", title);
|
||||
// Stop the graph from seeing the click as a canvas drag on the node.
|
||||
button.addEventListener("pointerdown", (event) => event.stopPropagation(), { signal });
|
||||
button.addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
keepHeld(state);
|
||||
}, { signal });
|
||||
row.append(note, button);
|
||||
state.keepRow = row;
|
||||
state.keepNote = note;
|
||||
state.keepButton = button;
|
||||
return row;
|
||||
}
|
||||
|
||||
async function keepHeld(state) {
|
||||
const held = heldPictures(state);
|
||||
if (!held.length || state.keeping) return;
|
||||
const count = resultCount(state);
|
||||
const wanted = keepsAll(state, count) ? held.map((_, place) => place) : [state.index];
|
||||
// One request for each run, in the order the pictures show.
|
||||
const runs = new Map();
|
||||
for (const place of wanted) {
|
||||
const picture = held[place];
|
||||
if (!picture) continue;
|
||||
if (!runs.has(picture.token)) runs.set(picture.token, []);
|
||||
runs.get(picture.token).push(picture.index);
|
||||
}
|
||||
state.keeping = true;
|
||||
syncHeld(state);
|
||||
const kept = keptOf(state, held);
|
||||
const saved = [];
|
||||
let skipped = 0;
|
||||
try {
|
||||
for (const [token, picks] of runs) {
|
||||
const response = await api.fetchApi("/ausboss/save_image/keep", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ token, picks }),
|
||||
});
|
||||
const answer = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(answer.error || "Could not save.");
|
||||
if (!state.alive) return;
|
||||
const done = new Set(answer.kept ?? []);
|
||||
held.forEach((picture, place) => {
|
||||
if (picture.token === token && done.has(picture.index)) kept.add(place);
|
||||
});
|
||||
saved.push(...(answer.saved ?? []));
|
||||
// One picture: the row says the name it was saved under.
|
||||
const path = held.length === 1 ? answer.saved?.[0]?.path : null;
|
||||
if (typeof path === "string" && path && state.kept) {
|
||||
state.kept.path = path;
|
||||
state.kept.name = path.slice(path.lastIndexOf("/") + 1);
|
||||
}
|
||||
skipped += answer.skipped?.length ?? 0;
|
||||
}
|
||||
toast(state, saved.length === 1
|
||||
? `Saved ${saved[0].path}`
|
||||
: saved.length
|
||||
? `Saved ${saved.length} pictures`
|
||||
: skipped ? "Not saved: the file already exists" : "Already saved");
|
||||
} catch (error) {
|
||||
if (state.alive) toast(state, error?.message || "Could not save.");
|
||||
} finally {
|
||||
state.keeping = false;
|
||||
if (state.alive) syncHeld(state);
|
||||
}
|
||||
}
|
||||
|
||||
function showsAll(state, count) {
|
||||
return count > 1 && count <= GRID_MAX && state.all !== false;
|
||||
}
|
||||
|
||||
function stepPicture(state, step) {
|
||||
const count = resultCount(state);
|
||||
if (count < 2) return;
|
||||
if (count > GRID_MAX) {
|
||||
state.index = stepIndex(state.index, count, step);
|
||||
} else {
|
||||
const at = stepWithAll(showsAll(state, count) ? ALL : state.index, count, step);
|
||||
state.all = at === ALL;
|
||||
if (!state.all) state.index = at;
|
||||
}
|
||||
state.index = stepIndex(state.index, count, step);
|
||||
refresh(state);
|
||||
}
|
||||
|
||||
function refresh(state) {
|
||||
if (!state.alive) return;
|
||||
if (!previewEnabled(state)) {
|
||||
clearMedia(state);
|
||||
syncHeld(state);
|
||||
return;
|
||||
}
|
||||
const source = upstreamNode(state.node, state.inputName);
|
||||
rewatchSource(state, source);
|
||||
const count = resultCount(state);
|
||||
const hidden = state.stepper.root.hidden;
|
||||
state.index = keepIndex(state.index, count);
|
||||
const all = showsAll(state, count);
|
||||
state.stepper.set(state.index, count, all ? allLabel(count) : undefined);
|
||||
syncHeld(state, count);
|
||||
state.stepper.set(state.index, count);
|
||||
if (state.stepper.root.hidden !== hidden) growToNodeFloor(state.widget);
|
||||
if (state.stale) {
|
||||
// The node ran while its preview was off, so the picture it still has
|
||||
@@ -865,20 +601,11 @@ function refresh(state) {
|
||||
// A node that just stopped the run has no result for this picture: the
|
||||
// one it still holds is from an earlier run (Mask by Name's last find,
|
||||
// tinted), so show what feeds it instead.
|
||||
if (all) {
|
||||
showGrid(state, count);
|
||||
// The grid's cells are new: mark the ones already kept.
|
||||
syncHeld(state, count);
|
||||
return;
|
||||
}
|
||||
clearGrid(state);
|
||||
const described = state.resultGone
|
||||
? describeSourcePreview(source)
|
||||
: count > 1
|
||||
? { kind: "url", url: storedResultUrl(state.node, state.index) }
|
||||
: describeNodePreview(state.node, state.inputName, storedResultUrl(state.node),
|
||||
// The small copy goes first: node.imgs is the full file.
|
||||
!lightQuery(outputRecord(state.node)) && ownResultIsCurrent(state.node, outputRecord(state.node), state.imgsFor));
|
||||
: describeNodePreview(state.node, state.inputName, storedResultUrl(state.node));
|
||||
if (!described) {
|
||||
clearMedia(state);
|
||||
showPlaceholder(state, !!source);
|
||||
@@ -900,9 +627,6 @@ function refresh(state) {
|
||||
state.video.removeAttribute("src");
|
||||
if (state.img.getAttribute("src") !== url) {
|
||||
state.img.src = url;
|
||||
// The picture before stays up while this one loads. A slow load
|
||||
// dims it, so an old picture is never taken for the new one.
|
||||
state.stage.classList.toggle("loading-image", true);
|
||||
} else if (state.img.complete && state.img.naturalWidth > 0) {
|
||||
showMedia(state, "image");
|
||||
}
|
||||
@@ -925,19 +649,8 @@ function scheduleRefresh(state) {
|
||||
// Watching the property rather than an api event catches both routes that set
|
||||
// it - the progress frames streamed during a run and the ui payload delivered
|
||||
// when the node finishes - without this file having to know either event name.
|
||||
// The panel's floor: the bar and the picture, the bar alone with the
|
||||
// preview off, and the Save row on top while it shows.
|
||||
function panelFloor(state, enabled = state ? previewEnabled(state) : true) {
|
||||
const keep = state?.keepRow && !state.keepRow.hidden ? KEEP_SPACE : 0;
|
||||
return (enabled ? PANEL_HEIGHT : OFF_HEIGHT) + keep;
|
||||
}
|
||||
|
||||
function watchOwnResult(node, state) {
|
||||
let images = node.imgs;
|
||||
// Which output the pictures in node.imgs were loaded for. The frontend
|
||||
// gives up on a picture that loads slowly and keeps the run before, so
|
||||
// the panel checks this before it trusts node.imgs (ownResultIsCurrent).
|
||||
state.imgsFor = outputRecord(node);
|
||||
try {
|
||||
Object.defineProperty(node, "imgs", {
|
||||
configurable: true,
|
||||
@@ -945,7 +658,6 @@ function watchOwnResult(node, state) {
|
||||
get: () => images,
|
||||
set: (value) => {
|
||||
images = value;
|
||||
state.imgsFor = outputRecord(node);
|
||||
if (state.alive) scheduleRefresh(state);
|
||||
},
|
||||
});
|
||||
@@ -974,9 +686,7 @@ function buildPanel(node, config) {
|
||||
const toastEl = document.createElement("div");
|
||||
toastEl.className = "ausboss-input-preview-toast";
|
||||
toastEl.style.display = "none";
|
||||
const grid = document.createElement("div");
|
||||
grid.className = "ausboss-input-preview-grid";
|
||||
stage.append(img, video, grid, hint, toastEl);
|
||||
stage.append(img, video, hint, toastEl);
|
||||
const bar = document.createElement("div");
|
||||
bar.className = "ausboss-input-preview-bar";
|
||||
root.append(bar, stage);
|
||||
@@ -986,7 +696,7 @@ function buildPanel(node, config) {
|
||||
const widget = node.addDOMWidget(WIDGET_NAME, "ausboss_input_preview", root, {
|
||||
serialize: false,
|
||||
hideOnZoom: false,
|
||||
getMinHeight: () => panelFloor(node.__ausbossInputPreview, enabled()),
|
||||
getMinHeight: () => (enabled() ? PANEL_HEIGHT : OFF_HEIGHT),
|
||||
});
|
||||
keepDomWidgetWidthAuto(widget);
|
||||
// Not saved with the workflow either: options.serialize only keeps it out
|
||||
@@ -998,7 +708,7 @@ function buildPanel(node, config) {
|
||||
// dragged taller. With the preview off the floor is the bar alone.
|
||||
fillNodeHeight(widget, {
|
||||
minWidth: () => previewMinWidth(node.__ausbossInputPreview),
|
||||
minHeight: () => panelFloor(node.__ausbossInputPreview, enabled()),
|
||||
minHeight: () => (enabled() ? PANEL_HEIGHT : OFF_HEIGHT),
|
||||
minNodeSize: [PANEL_MIN_WIDTH, 90],
|
||||
exactMinWidth: true,
|
||||
});
|
||||
@@ -1010,10 +720,7 @@ function buildPanel(node, config) {
|
||||
noun: config.noun,
|
||||
switchTitle: config.switchTitle,
|
||||
advanced: config.advanced,
|
||||
root, bar, stage, img, video, grid, hint, widget, abort,
|
||||
// Several pictures open side by side; the arrows pick one (false).
|
||||
all: true,
|
||||
gridKey: "",
|
||||
root, bar, stage, img, video, hint, widget, abort,
|
||||
toast: toastEl,
|
||||
toastTimer: 0,
|
||||
toolButtons: null,
|
||||
@@ -1029,7 +736,6 @@ function buildPanel(node, config) {
|
||||
};
|
||||
livePanels.add(state);
|
||||
if (config.tools?.length) bar.append(buildTools(state, config.tools, abort.signal));
|
||||
if (config.keep) bar.after(buildKeepRow(state, config.keep, abort.signal));
|
||||
if (config.readout) {
|
||||
state.readout = document.createElement("span");
|
||||
state.readout.className = "ausboss-input-preview-readout";
|
||||
@@ -1048,16 +754,9 @@ function buildPanel(node, config) {
|
||||
installPreviewSwitch(state, abort.signal);
|
||||
if (config.steps) installStepsSwitch(state, abort.signal);
|
||||
|
||||
// The grid is laid out for the stage's shape, so a resized node lays it out again.
|
||||
if (typeof ResizeObserver === "function") {
|
||||
const watcher = new ResizeObserver(() => { if (state.alive && state.gridKey) layoutGrid(state); });
|
||||
watcher.observe(stage);
|
||||
abort.signal.addEventListener("abort", () => watcher.disconnect(), { once: true });
|
||||
}
|
||||
img.addEventListener("load", () => { stage.classList.remove("loading-image"); showMedia(state, "image"); });
|
||||
img.addEventListener("load", () => showMedia(state, "image"));
|
||||
img.addEventListener("error", () => {
|
||||
stage.classList.remove("loading-image");
|
||||
if (img.getAttribute("src") && !dropLightPreview(state)) showPlaceholder(state, true);
|
||||
if (img.getAttribute("src")) showPlaceholder(state, true);
|
||||
});
|
||||
video.addEventListener("loadeddata", () => showMedia(state, "video"));
|
||||
video.addEventListener("error", () => {
|
||||
@@ -1126,9 +825,9 @@ app.registerExtension({
|
||||
if (state) scheduleRefresh(state);
|
||||
});
|
||||
chainCallback(nodeType.prototype, "onConfigure", function () {
|
||||
const state = this.__ausbossInputPreview;
|
||||
queueMicrotask(() => {
|
||||
if (!state?.alive || this.__ausbossInputPreview !== state) return;
|
||||
const state = buildPanel(this, config);
|
||||
if (!state) return;
|
||||
// onNodeCreated already built the panel before this node's saved
|
||||
// properties existed, so the advanced toggle has to be re-applied
|
||||
// here or a workflow always reopens in the simple state.
|
||||
|
||||
@@ -288,9 +288,6 @@ function syncSizes() {
|
||||
const grabbed = together.grabbed;
|
||||
if (!grabbed) return;
|
||||
const was = together.before.get(grabbed);
|
||||
// A handle click is not a resize. Once a drag starts, keep syncing even
|
||||
// when it returns to its starting size so the other nodes follow it back.
|
||||
if (!together.sides && grabbed.size[0] === was.size[0] && grabbed.size[1] === was.size[1]) return;
|
||||
together.sides ??= sharedSides(
|
||||
[...together.before.values()].map(({ pos, size }) => ({ x: pos[0], y: pos[1], w: size[0], h: size[1] })),
|
||||
);
|
||||
|
||||
@@ -20,36 +20,21 @@ export function outputWindow(durationValue, startValue, endValue, maxValue = 0)
|
||||
return { start, end, keepEnd, length: keepEnd - start, cut: Math.max(0, end - keepEnd) };
|
||||
}
|
||||
|
||||
const hundredth = (value) => Math.round(value * 100) / 100;
|
||||
|
||||
// What the face stores for a pick from `start` to `end`: a Start and a
|
||||
// Duration (max_seconds, with end_seconds at 0, "to the end"). A pick that
|
||||
// reaches the end of the file needs no Duration. When another node sets the
|
||||
// Duration or the end, the pick is stored as a start and an end instead.
|
||||
// A key left out is not written.
|
||||
export function pickWrites(durationValue, startValue, endValue, { maxLinked = false, endLinked = false } = {}) {
|
||||
const duration = Math.max(0, finite(durationValue));
|
||||
const start = hundredth(Math.min(Math.max(0, finite(startValue)), duration));
|
||||
const end = hundredth(Math.max(start, Math.min(finite(endValue), duration)));
|
||||
const toEnd = end >= duration - 0.005;
|
||||
if (endLinked) return { start };
|
||||
if (maxLinked) return { start, end: toEnd ? 0 : end };
|
||||
return { start, end: 0, max: toEnd ? 0 : Math.max(0.01, hundredth(end - start)) };
|
||||
// "0:12.0" style, the way the IN and OUT fields write a time.
|
||||
export function secondsLabel(value) {
|
||||
const seconds = Math.max(0, finite(value));
|
||||
if (seconds < 60) return `${seconds.toFixed(1)} s`;
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
return `${minutes}:${(seconds - minutes * 60).toFixed(1).padStart(4, "0")}`;
|
||||
}
|
||||
|
||||
// A value typed into Start, Duration or Ends at, as the pick it makes.
|
||||
// Start keeps the Duration; Duration and Ends at keep the start. An empty
|
||||
// or 0 Duration, and an empty Ends at, run to the end of the file.
|
||||
export function typedPick(key, value, window, durationValue, minimum = 0.1) {
|
||||
const duration = Math.max(0, finite(durationValue));
|
||||
const clampTime = (time) => Math.min(duration, Math.max(0, finite(time)));
|
||||
if (key === "start") {
|
||||
const start = clampTime(value);
|
||||
return { start, end: Math.min(duration, start + window.length) };
|
||||
}
|
||||
if (value == null || (key === "duration" && !(finite(value) > 0))) return { start: window.start, end: duration };
|
||||
const end = key === "duration" ? window.start + Math.max(minimum, finite(value)) : Math.max(window.start + minimum, finite(value));
|
||||
return { start: window.start, end: clampTime(end) };
|
||||
// The line between IN and OUT: what comes out, and what the max cuts off.
|
||||
export function outputSummary(window, { maxFromLink = false } = {}) {
|
||||
if (!window || window.length <= 0) return "";
|
||||
const parts = [secondsLabel(window.length)];
|
||||
if (window.cut > 0.005) parts.push(`cut ${secondsLabel(window.cut)}`);
|
||||
if (maxFromLink) parts.push("max wired");
|
||||
return parts.join(" · ");
|
||||
}
|
||||
|
||||
// Loud and quiet across the file: for each of `buckets` slices, the lowest
|
||||
|
||||
+110
-118
@@ -1,35 +1,30 @@
|
||||
// Load Audio 🆎 - the wave, the timing and the player.
|
||||
// Load Audio 🆎 - the wave, the trim and the player.
|
||||
//
|
||||
// The card above (js/widget_cards) holds Source. This panel draws the whole
|
||||
// file as a wave: the part that comes out is bright and the rest is dim.
|
||||
// Under it, Start, Duration and Ends at, as on the video nodes. Drag a
|
||||
// handle on the wave to move the start or the end, drag the middle to slide
|
||||
// the sound, or click elsewhere to move it there. Play plays only what comes
|
||||
// out. The widgets underneath stay the source of truth: the Duration is
|
||||
// max_seconds with end_seconds at 0. A saved end (or a linked Max length)
|
||||
// still works: the part a Max length cuts off shows red.
|
||||
// The card above (js/widget_cards) holds Source and Max length. This panel
|
||||
// draws the whole file as a wave: the part that comes out is bright, the
|
||||
// part a Max length cuts off is red, and the rest is dim. Drag a handle to
|
||||
// move IN or OUT, drag the middle to slide the pick, or click elsewhere to
|
||||
// move it there. Play plays only what comes out. The widgets underneath
|
||||
// (start_seconds, end_seconds, max_seconds) stay the source of truth.
|
||||
import { api } from "../../../scripts/api.js";
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { BRAND, chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange, showToast } from "../shared/index.mjs";
|
||||
import { keepKeyInField } from "../shared/canvas_passthrough.mjs";
|
||||
import { WIDGET_FRAME, fillNodeHeight } from "../shared/panel_layout.mjs";
|
||||
import { formatTimecode } from "../shared/timecode.mjs";
|
||||
import { inputNumber } from "../shared/clip_rate.mjs";
|
||||
import { makeScrubInput } from "../shared/scrub_input.mjs";
|
||||
import { linkedNodeInfo } from "../shared/timing_links.mjs";
|
||||
import { formatTimecode, parseTimecode } from "../shared/timecode.mjs";
|
||||
import { parseImageReference } from "../shared/pad_canvas.mjs";
|
||||
import { mediaViewQuery, splitMediaName } from "../shared/video_preview.mjs";
|
||||
import { ensureVideoCss, hideCanvasWidget, makeToolButton } from "../shared/video_ui.mjs";
|
||||
import { MIN_TRIM_SECONDS, dragTrimHandle, slideTrimWindow } from "../load_video/trim_preview.mjs";
|
||||
import { grabZone, outputWindow, pickWrites, typedPick, wavePeaks } from "./audio_window.mjs";
|
||||
import { grabZone, outputSummary, outputWindow, secondsLabel, wavePeaks } from "./audio_window.mjs";
|
||||
|
||||
const NODE_NAME = "AUSBOSS_NODES_LoadAudio";
|
||||
const PANEL_WIDGET = "ausboss_load_audio_wave";
|
||||
// The frontend's own player for an audio_upload input. The wave replaces it.
|
||||
const CORE_AUDIO_WIDGET = "audioUI";
|
||||
const MIN_WIDTH = 280;
|
||||
// 8px root padding + the wave's 28px floor + 6px gap + the 38px Start,
|
||||
// Duration and Ends at row (a label over a box).
|
||||
const PANEL_MIN_HEIGHT = 80;
|
||||
// 8px root padding + the wave's 28px floor + 6px gap + the 22px play, IN/OUT and loop row.
|
||||
const PANEL_MIN_HEIGHT = 64;
|
||||
// Opens small and neat: 300 px wide, with a wave about as tall as a field
|
||||
// (32 px). Drag the corner down for a taller wave.
|
||||
const DEFAULT_WIDTH = 300;
|
||||
@@ -55,32 +50,26 @@ function hideCoreAudio(node) {
|
||||
}
|
||||
}
|
||||
|
||||
function linked(node, name) {
|
||||
return !!node.inputs?.some((slot) => slot?.widget?.name === name && slot.link != null);
|
||||
}
|
||||
|
||||
// A value as the run will see it: the widget, or the number a linked input
|
||||
// carries when the far end is a typed number (through Reroutes and
|
||||
// subgraphs). null when only the run knows it.
|
||||
function valueOf(state, name, widget) {
|
||||
if (!linked(state.node, name)) return Number(widget?.value) || 0;
|
||||
return inputNumber(state.node, name, null);
|
||||
// A wired Max length: the number the wire carries, when the far end is a
|
||||
// node that shows it (Float, Integer, a Primitive). null when it can't be known.
|
||||
function wiredMax(node) {
|
||||
const input = node.inputs?.find((slot) => slot?.widget?.name === "max_seconds");
|
||||
if (!input || input.link == null) return { wired: false, value: null };
|
||||
const graph = node.graph;
|
||||
const link = graph?.getLink?.(input.link) ?? graph?.links?.get?.(input.link) ?? graph?.links?.[input.link];
|
||||
const origin = link ? graph?.getNodeById?.(link.origin_id) : null;
|
||||
const shown = origin?.widgets?.find((widget) => typeof widget?.value === "number");
|
||||
return { wired: true, value: shown ? Number(shown.value) : null };
|
||||
}
|
||||
|
||||
function maxSeconds(state) {
|
||||
const fromLink = linked(state.node, "max_seconds");
|
||||
const value = valueOf(state, "max_seconds", state.maxWidget);
|
||||
return { value: value ?? 0, fromLink, known: value != null };
|
||||
const wired = wiredMax(state.node);
|
||||
if (wired.wired) return { value: wired.value ?? 0, fromLink: true, known: wired.value != null };
|
||||
return { value: Number(state.maxWidget?.value) || 0, fromLink: false, known: true };
|
||||
}
|
||||
|
||||
function currentWindow(state) {
|
||||
const start = valueOf(state, "start_seconds", state.startWidget) ?? 0;
|
||||
const max = maxSeconds(state).value;
|
||||
let end = valueOf(state, "end_seconds", state.endWidget) ?? 0;
|
||||
// No end and a Duration: the Duration is where the sound stops, so
|
||||
// nothing past it shows as cut off. Only an end past the Duration does.
|
||||
if (!(end > 0) && max > 0 && state.duration > 0) end = Math.min(state.duration, Math.max(0, start) + max);
|
||||
return outputWindow(state.duration, start, end, max);
|
||||
return outputWindow(state.duration, state.startWidget.value, state.endWidget.value, maxSeconds(state).value);
|
||||
}
|
||||
|
||||
async function loadPeaks(name, route) {
|
||||
@@ -116,15 +105,16 @@ function ensureAudioCss() {
|
||||
.ausboss-audio-error{pointer-events:auto;border:0;background:transparent;color:#e6bf87;font:11px system-ui;cursor:pointer;white-space:nowrap}
|
||||
.ausboss-audio-root canvas.ausboss-audio-wave{position:absolute;inset:0;width:100%;height:100%;display:block;}
|
||||
.ausboss-audio-root .ausboss-video-stage:not(.is-empty) .ausboss-video-status{display:none;}
|
||||
.ausboss-audio-root .ausboss-audio-wave-row{display:flex;align-items:stretch;gap:6px;flex:1 1 auto;min-height:28px;}
|
||||
.ausboss-audio-root .ausboss-audio-wave-row .ausboss-video-stage{flex:1 1 auto;min-width:0;}
|
||||
.ausboss-audio-root .ausboss-audio-play{flex:none;align-self:center;min-width:30px;font-size:10px;}
|
||||
.ausboss-audio-fields{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px;flex:none;padding:0 2px;color:#ddd;font:11px system-ui;}
|
||||
.ausboss-audio-field{display:flex;flex-direction:column;gap:2px;min-width:0;}
|
||||
.ausboss-audio-field .ausboss-scrub{width:100%;box-sizing:border-box;}
|
||||
.ausboss-audio-field-label{display:flex;align-items:center;gap:6px;min-width:0;color:#cadddb;}
|
||||
.ausboss-audio-go{border:0;background:transparent;padding:0;color:#45d6cb;font:600 10px system-ui;text-decoration:underline;cursor:pointer;}
|
||||
.ausboss-audio-go[hidden]{display:none;}
|
||||
.ausboss-audio-root .ausboss-audio-row{display:flex;align-items:center;gap:6px;flex:none;padding:0 2px;}
|
||||
.ausboss-audio-root .ausboss-audio-row .ausboss-video-values{flex:1 1 auto;min-width:0;}
|
||||
.ausboss-audio-root .ausboss-audio-play{min-width:30px;font-size:10px;}
|
||||
.ausboss-audio-root .ausboss-audio-length{flex:none;padding:0 2px;color:#7fd9d2;font-size:10px;font-variant-numeric:tabular-nums;white-space:nowrap;cursor:default;}
|
||||
.ausboss-audio-root .ausboss-audio-length:empty{display:none;}
|
||||
.ausboss-audio-root .ausboss-audio-length.has-cut{color:#ff9aa0;cursor:pointer;text-decoration:underline dotted rgba(224,82,90,.8);text-underline-offset:2px;}
|
||||
.ausboss-audio-root .ausboss-audio-row .ausboss-video-tool{flex:none;}
|
||||
.ausboss-audio-root .ausboss-video-values{display:flex;gap:8px;}
|
||||
.ausboss-audio-root .ausboss-video-value input{width:48px;}
|
||||
.ausboss-audio-root .ausboss-audio-length{margin-left:auto;}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
@@ -202,31 +192,21 @@ function draw(state) {
|
||||
}
|
||||
}
|
||||
|
||||
// One box's look: its value, whether it can be typed, and the "linked"
|
||||
// button when another node sets it.
|
||||
function showField(state, key, value, lockedBy, tip) {
|
||||
const field = state.fields[key];
|
||||
field.control.set(value);
|
||||
field.control.root.style.opacity = lockedBy ? ".45" : "";
|
||||
field.control.root.inert = Boolean(lockedBy);
|
||||
field.go.hidden = !lockedBy;
|
||||
field.cell.title = lockedBy ? `Set by ${lockedBy.title}. Click "linked" to go to that node.` : tip;
|
||||
if (lockedBy) field.go.onclick = () => lockedBy.go?.();
|
||||
}
|
||||
|
||||
function updateFace(state) {
|
||||
const win = currentWindow(state);
|
||||
const link = (name) => (linked(state.node, name) ? linkedNodeInfo(state.node, name) : null);
|
||||
// A linked value the page cannot read is only known when the graph runs:
|
||||
// its box, and the boxes that depend on it, stay empty.
|
||||
const known = (name) => !linked(state.node, name) || inputNumber(state.node, name, null) != null;
|
||||
const has = state.duration > 0;
|
||||
const startKnown = has && known("start_seconds");
|
||||
const lengthKnown = startKnown && known("max_seconds") && known("end_seconds");
|
||||
showField(state, "start", startKnown ? win.start : null, link("start_seconds"), `Where the sound starts in the file, of ${formatTimecode(state.duration)}.`);
|
||||
showField(state, "duration", lengthKnown ? win.length : null, link("max_seconds"),
|
||||
win.cut > 0.005 ? `How long the sound is. It stops ${formatTimecode(win.cut)} before the saved end (red).` : "How long the sound is. Clear it, or type 0, to run to the end of the file.");
|
||||
showField(state, "end", lengthKnown ? win.keepEnd : null, link("end_seconds"), "Where the sound stops in the file. Typing it changes the Duration.");
|
||||
const max = maxSeconds(state);
|
||||
if (document.activeElement !== state.startInput) state.startInput.value = formatTimecode(win.start);
|
||||
if (document.activeElement !== state.endInput) state.endInput.value = formatTimecode(win.end);
|
||||
if (state.duration > 0) {
|
||||
const summary = outputSummary(win, { maxFromLink: max.fromLink && !max.known });
|
||||
state.summary.textContent = win.length > 0 ? secondsLabel(win.length) : "";
|
||||
state.summary.classList.toggle("has-cut", win.cut > 0.005);
|
||||
state.summary.title = win.cut > 0.005
|
||||
? `${summary}. Max length is ${max.value} s, so ${formatTimecode(win.keepEnd)} to ${formatTimecode(win.end)} is cut off (red). Click to move OUT to ${formatTimecode(win.keepEnd)}.`
|
||||
: `${summary}: ${formatTimecode(win.start)} to ${formatTimecode(win.keepEnd)} comes out.`;
|
||||
} else {
|
||||
state.summary.textContent = "";
|
||||
}
|
||||
draw(state);
|
||||
}
|
||||
|
||||
@@ -237,19 +217,12 @@ function writeWidget(widget, value) {
|
||||
widget.callback?.(next);
|
||||
}
|
||||
|
||||
// The pick, stored the way the face shows it (pickWrites): a Start and a
|
||||
// Duration, or a start and an end when another node sets the Duration.
|
||||
function writeTrim(state, bounds) {
|
||||
state.writing = true;
|
||||
try {
|
||||
const startLinked = linked(state.node, "start_seconds");
|
||||
const writes = pickWrites(state.duration, startLinked ? currentWindow(state).start : bounds.start, bounds.end, {
|
||||
maxLinked: linked(state.node, "max_seconds") || !state.maxWidget,
|
||||
endLinked: linked(state.node, "end_seconds"),
|
||||
});
|
||||
if (!startLinked) writeWidget(state.startWidget, writes.start);
|
||||
if (writes.end !== undefined) writeWidget(state.endWidget, writes.end);
|
||||
if (writes.max !== undefined) writeWidget(state.maxWidget, writes.max);
|
||||
writeWidget(state.startWidget, bounds.start);
|
||||
// OUT at the very end stays 0, the widget's own "to the end".
|
||||
writeWidget(state.endWidget, bounds.end >= state.duration - 0.005 ? 0 : bounds.end);
|
||||
} finally {
|
||||
state.writing = false;
|
||||
}
|
||||
@@ -275,7 +248,7 @@ function installDrag(state) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const initial = infoAt(event.clientX);
|
||||
const bounds = { start: initial.win.start, end: initial.win.keepEnd };
|
||||
const bounds = { start: initial.win.start, end: initial.win.end };
|
||||
const anchor = initial.fraction * state.duration;
|
||||
const downX = event.clientX;
|
||||
let moved = false;
|
||||
@@ -289,7 +262,7 @@ function installDrag(state) {
|
||||
const next = infoAt(clientX);
|
||||
if (initial.zone === "start" || initial.zone === "end") {
|
||||
const now = currentWindow(state);
|
||||
writeTrim(state, dragTrimHandle(state.duration, { start: now.start, end: now.keepEnd }, initial.zone, next.fraction, MIN_TRIM_SECONDS));
|
||||
writeTrim(state, dragTrimHandle(state.duration, { start: now.start, end: now.end }, initial.zone, next.fraction, MIN_TRIM_SECONDS));
|
||||
} else if (initial.zone === "move") {
|
||||
writeTrim(state, slideTrimWindow(state.duration, bounds, next.fraction * state.duration - anchor));
|
||||
} else {
|
||||
@@ -363,6 +336,19 @@ function installPlayer(state) {
|
||||
state.stopPlayer = () => { audio.pause(); stop(); };
|
||||
}
|
||||
|
||||
function commitTimeInput(state, edge, input) {
|
||||
if (state.duration <= 0) return;
|
||||
const seconds = parseTimecode(input.value);
|
||||
const win = currentWindow(state);
|
||||
if (seconds === null) {
|
||||
input.value = formatTimecode(edge === "start" ? win.start : win.end);
|
||||
return;
|
||||
}
|
||||
writeTrim(state, dragTrimHandle(state.duration, { start: win.start, end: win.end }, edge, seconds / state.duration, MIN_TRIM_SECONDS));
|
||||
notifyAusbossChange();
|
||||
input.blur();
|
||||
}
|
||||
|
||||
function watchWidget(state, widget) {
|
||||
if (!widget || widget.__ausbossAudioWatch) return;
|
||||
widget.__ausbossAudioWatch = true;
|
||||
@@ -399,44 +385,37 @@ function buildPanel(node) {
|
||||
playButton.classList.add("ausboss-audio-play");
|
||||
const loopButton = makeToolButton("LOOP", "Play it again and again");
|
||||
stage.append(canvas, status);
|
||||
// Play and Loop sit either side of the wave, so neither covers a handle.
|
||||
loopButton.classList.add("ausboss-audio-play");
|
||||
const waveRow = document.createElement("div");
|
||||
waveRow.className = "ausboss-audio-wave-row";
|
||||
waveRow.append(playButton, stage, loopButton);
|
||||
|
||||
// Start, Duration and Ends at, as on the video nodes, in seconds.
|
||||
const fieldsRow = document.createElement("div");
|
||||
fieldsRow.className = "ausboss-audio-fields";
|
||||
const fields = {};
|
||||
const commit = (key, value) => {
|
||||
const state = node.__ausbossLoadAudio;
|
||||
if (!state || state.duration <= 0) return;
|
||||
writeTrim(state, typedPick(key, value, currentWindow(state), state.duration, MIN_TRIM_SECONDS));
|
||||
};
|
||||
for (const [key, caption] of [["start", "Start"], ["duration", "Duration"], ["end", "Ends at"]]) {
|
||||
const cell = document.createElement("div");
|
||||
cell.className = "ausboss-audio-field";
|
||||
const label = document.createElement("span");
|
||||
label.className = "ausboss-audio-field-label";
|
||||
label.textContent = caption;
|
||||
const go = document.createElement("button");
|
||||
go.type = "button";
|
||||
go.className = "ausboss-audio-go";
|
||||
go.textContent = "linked";
|
||||
go.hidden = true;
|
||||
label.append(go);
|
||||
const control = makeScrubInput({
|
||||
value: 0, min: 0, max: 86400, step: 0.1, fineStep: 0.01, decimals: 2, minDecimals: 0, unit: "s", unitWidth: 14,
|
||||
allowEmpty: true,
|
||||
onChange: (value) => commit(key, value),
|
||||
onSettle: () => notifyAusbossChange(),
|
||||
const values = document.createElement("div");
|
||||
values.className = "ausboss-video-values";
|
||||
const makeValue = (labelText, title) => {
|
||||
const wrap = document.createElement("div");
|
||||
wrap.className = "ausboss-video-value";
|
||||
const label = document.createElement("label");
|
||||
label.textContent = labelText;
|
||||
const input = document.createElement("input");
|
||||
input.type = "text";
|
||||
input.inputMode = "decimal";
|
||||
input.placeholder = "m:ss.s";
|
||||
input.title = title;
|
||||
input.addEventListener("keydown", (event) => {
|
||||
keepKeyInField(event);
|
||||
if (event.key === "Enter") input.dispatchEvent(new Event("change"));
|
||||
});
|
||||
cell.append(label, control.root);
|
||||
fieldsRow.append(cell);
|
||||
fields[key] = { cell, control, go };
|
||||
}
|
||||
root.append(waveRow, fieldsRow);
|
||||
wrap.append(label, input);
|
||||
return { wrap, input };
|
||||
};
|
||||
const startValue = makeValue("IN", "Where the sound starts. Type seconds (12.5) or a time (0:12.5).");
|
||||
const endValue = makeValue("OUT", "Where the sound stops. Type seconds (24) or a time (0:24.0).");
|
||||
// How long the output is, beside OUT and off the wave. Red when Max
|
||||
// length cuts the pick short; the tooltip says how much.
|
||||
const summary = document.createElement("div");
|
||||
summary.className = "ausboss-audio-length";
|
||||
values.append(startValue.wrap, endValue.wrap);
|
||||
const row = document.createElement("div");
|
||||
row.className = "ausboss-audio-row";
|
||||
row.append(playButton, values, summary, loopButton);
|
||||
root.append(stage, row);
|
||||
|
||||
const widget = node.addDOMWidget(PANEL_WIDGET, "ausboss_audio", root, {
|
||||
serialize: false,
|
||||
@@ -456,11 +435,22 @@ function buildPanel(node) {
|
||||
audio.preload = "auto";
|
||||
const abort = new AbortController();
|
||||
const state = node.__ausbossLoadAudio = {
|
||||
node, root, stage, canvas, status, playButton, loopButton, audio, fields,
|
||||
node, root, stage, canvas, status, playButton, loopButton, summary, audio,
|
||||
startInput: startValue.input, endInput: endValue.input,
|
||||
audioWidget, startWidget, endWidget, maxWidget: findWidget(node, "max_seconds"),
|
||||
duration: 0, peaks: null, abort, writing: false, dragging: false, raf: 0, loading: 0,
|
||||
};
|
||||
|
||||
// Clicking the red length moves OUT to where the sound really ends.
|
||||
summary.addEventListener("click", (event) => {
|
||||
const win = currentWindow(state);
|
||||
if (win.cut <= 0.005) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
writeTrim(state, { start: win.start, end: win.keepEnd });
|
||||
notifyAusbossChange();
|
||||
});
|
||||
|
||||
const updateLoop = () => loopButton.classList.toggle("active", loopEnabled(node));
|
||||
updateLoop();
|
||||
loopButton.addEventListener("click", (event) => {
|
||||
@@ -519,6 +509,8 @@ function buildPanel(node) {
|
||||
watchWidget(state, startWidget);
|
||||
watchWidget(state, endWidget);
|
||||
watchWidget(state, state.maxWidget);
|
||||
startValue.input.addEventListener("change", () => commitTimeInput(state, "start", startValue.input));
|
||||
endValue.input.addEventListener("change", () => commitTimeInput(state, "end", endValue.input));
|
||||
const observer = new ResizeObserver(() => draw(state));
|
||||
observer.observe(stage);
|
||||
state.observer = observer;
|
||||
|
||||
+367
-157
@@ -1,11 +1,9 @@
|
||||
import { api } from "../../../scripts/api.js";
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange } from "../shared/index.mjs";
|
||||
import { keepKeyInField } from "../shared/canvas_passthrough.mjs";
|
||||
import { WIDGET_FRAME, fillNodeHeight } from "../shared/panel_layout.mjs";
|
||||
import { inputNumber } from "../shared/clip_rate.mjs";
|
||||
import { clipInfo, windowSeconds } from "../shared/timeline_math.mjs";
|
||||
import { mountTransformTrim } from "../shared/transform_trim.mjs";
|
||||
import { linkedNodeInfo, timingUnits } from "../shared/timing_links.mjs";
|
||||
import { formatTimecode, parseTimecode } from "../shared/timecode.mjs";
|
||||
import { parseImageReference } from "../shared/pad_canvas.mjs";
|
||||
import {
|
||||
mediaInfo,
|
||||
@@ -21,31 +19,42 @@ import {
|
||||
suppressCoreVideoPreview,
|
||||
} from "../shared/video_ui.mjs";
|
||||
import {
|
||||
MIN_TRIM_SECONDS,
|
||||
clampTrimSeek,
|
||||
closestTrimHandle,
|
||||
dragTrimHandle,
|
||||
loadSummary,
|
||||
playbackBoundaryAction,
|
||||
singleFrameFraction,
|
||||
singleFrameTime,
|
||||
slideTrimWindow,
|
||||
trimAfterFramePick,
|
||||
trimBounds,
|
||||
trimFractions,
|
||||
} from "./trim_preview.mjs";
|
||||
|
||||
const NODE_NAME = "AUSBOSS_NODES_LoadVideo";
|
||||
const PREVIEW_WIDGET = "ausboss_load_video_viewer";
|
||||
const PREVIEW_CHROME = 88;
|
||||
// 8px root padding + the stage's 112px floor + 6px gap + the 152px timing
|
||||
// card (js/shared/transform_trim.mjs). The declared floor adds WIDGET_FRAME
|
||||
// on top, or the element comes up short and clips the card's bottom border
|
||||
// at the node's minimum height.
|
||||
const PANEL_MIN_HEIGHT = 278;
|
||||
// The shared video root's CSS minimum: 8px root padding + the stage's 112px
|
||||
// floor + 6px gap + the 76px trim strip. The declared floor adds
|
||||
// WIDGET_FRAME on top, or the element comes up short and clips the trim
|
||||
// strip's bottom border at the node's minimum height.
|
||||
const PANEL_MIN_HEIGHT = 202;
|
||||
// Height the node opens at. It used to fall out of the panel's computeSize;
|
||||
// with the panel free to follow the node, the default has to be stated. The
|
||||
// extra covers the tools over the picture and the timing card under it.
|
||||
const DEFAULT_NODE_SIZE = [380, responsivePreviewHeight(380) + PREVIEW_CHROME + 210];
|
||||
// chrome covers the transport row and the trim strip under the player.
|
||||
const DEFAULT_NODE_SIZE = [380, responsivePreviewHeight(380) + PREVIEW_CHROME + 190];
|
||||
const TRIM_EPSILON = 0.04;
|
||||
|
||||
function findWidget(node, name) {
|
||||
return node.widgets?.find((widget) => widget.name === name);
|
||||
}
|
||||
|
||||
function roundHundredth(value) {
|
||||
return Math.round(Number(value || 0) * 100) / 100;
|
||||
}
|
||||
|
||||
function getLoopEnabled(node) {
|
||||
node.properties ??= {};
|
||||
if (node.properties.ausboss_load_video_loop === undefined) {
|
||||
@@ -57,25 +66,14 @@ function getLoopEnabled(node) {
|
||||
function setEmpty(state, text) {
|
||||
state.stage.classList.add("is-empty");
|
||||
state.status.textContent = text;
|
||||
state.status.hidden = false;
|
||||
}
|
||||
|
||||
function setReady(state, text) {
|
||||
state.stage.classList.remove("is-empty");
|
||||
state.status.textContent = text;
|
||||
state.status.hidden = !text;
|
||||
}
|
||||
|
||||
// The run's window in seconds, as the timing card works it out (Start, and
|
||||
// the Duration or the end), or the plain start/end before the video's frame
|
||||
// rate is known.
|
||||
function currentBounds(state) {
|
||||
const info = clipInfo(state.metadata);
|
||||
const window = state.card?.window?.();
|
||||
if (info.fps > 0 && window && Number.isFinite(window.first)) {
|
||||
const last = Number.isFinite(window.last) ? window.last : info.count - 1;
|
||||
return { start: window.first / info.fps, end: Math.min(info.duration || Infinity, (last + 1) / info.fps) };
|
||||
}
|
||||
return trimBounds(state.video.duration, state.startWidget.value, state.endWidget.value);
|
||||
}
|
||||
|
||||
@@ -84,116 +82,271 @@ function isSingleFrame(state) {
|
||||
}
|
||||
|
||||
// Where the preview belongs for the current mode: the chosen frame, or the
|
||||
// clip's start.
|
||||
// trim window's IN point.
|
||||
function homeTime(state) {
|
||||
return isSingleFrame(state)
|
||||
? singleFrameTime(state.video.duration, state.startWidget.value)
|
||||
: currentBounds(state).start;
|
||||
}
|
||||
|
||||
function widgetLinkDriven(node, name) {
|
||||
return !!node.inputs?.some((input) => input?.widget?.name === name && input.link != null);
|
||||
}
|
||||
|
||||
// Frame rate and the real frame count come from the pack's metadata route:
|
||||
// the <video> element knows neither, and its length rounds up a frame.
|
||||
// Fail-soft: without it the card waits for a source.
|
||||
async function probeMetadata(state, name) {
|
||||
state.metadata = null;
|
||||
try {
|
||||
const query = new URLSearchParams({ source_mode: "input folder", video: name });
|
||||
const type = parseImageReference(name)?.type;
|
||||
if (type && type !== "input") {
|
||||
query.set("source_mode", "local path");
|
||||
query.set("local_path", name);
|
||||
}
|
||||
const response = await api.fetchApi(`/ausboss/transform/video/metadata?${query}`);
|
||||
if (!response.ok) return;
|
||||
const metadata = await response.json();
|
||||
if (state.videoWidget.value !== name) return; // a newer selection won
|
||||
state.metadata = metadata;
|
||||
state.card?.sync();
|
||||
} catch (_error) {
|
||||
/* no metadata, no timing card numbers */
|
||||
}
|
||||
}
|
||||
|
||||
function setWidget(widget, value) {
|
||||
if (!widget) return;
|
||||
if (widget.value === value) return;
|
||||
widget.value = value;
|
||||
widget.callback?.(value);
|
||||
}
|
||||
|
||||
// The timing card: the clip node's own, with Start, Duration and Ends at,
|
||||
// or, while FRAME is on, its frame picker. The player above it is the
|
||||
// picture, so the card leaves out its own Play button.
|
||||
function mountCard(state) {
|
||||
const { node } = state;
|
||||
const widgetFor = (name) => node.widgets?.find((widget) => widget.name === name);
|
||||
const fps = () => clipInfo(state.metadata).fps;
|
||||
const single = isSingleFrame(state);
|
||||
const card = mountTransformTrim({
|
||||
get: (name, fallback) => {
|
||||
if (name === "frame_index") return state.head ?? 0;
|
||||
const widget = widgetFor(name);
|
||||
return widget ? widget.value : fallback;
|
||||
},
|
||||
set: (name, value) => {
|
||||
state.writing = true;
|
||||
try { setWidget(widgetFor(name), value); } finally { state.writing = false; }
|
||||
if (state.video.readyState >= 1 && !state.video.paused) return;
|
||||
node.setDirtyCanvas?.(true, true);
|
||||
},
|
||||
has: (name) => Boolean(widgetFor(name)),
|
||||
driven: (name) => widgetLinkDriven(node, name),
|
||||
number: (name, fallback) => inputNumber(node, name, fallback),
|
||||
metadata: () => state.metadata,
|
||||
trim: !single,
|
||||
play: false,
|
||||
isPlaying: () => !state.video.paused,
|
||||
onTogglePlayback: () => {},
|
||||
onSeek: (frame, settled) => {
|
||||
state.head = frame;
|
||||
const rate = fps();
|
||||
if (single && rate > 0) {
|
||||
state.writing = true;
|
||||
try { setWidget(state.startWidget, windowSeconds(clipInfo(state.metadata), frame, frame).start_seconds); } finally { state.writing = false; }
|
||||
}
|
||||
if (state.video.readyState >= 1 && rate > 0) state.video.currentTime = Math.min(state.video.duration || Infinity, (frame + 0.5) / rate);
|
||||
if (settled) notifyAusbossChange();
|
||||
},
|
||||
onCommit: notifyAusbossChange,
|
||||
linkInfo: (name) => linkedNodeInfo(node, name),
|
||||
units: () => timingUnits(),
|
||||
setUnits: (next) => timingUnits(next),
|
||||
});
|
||||
state.card?.root.remove();
|
||||
state.card = card;
|
||||
state.cardSlot.append(card.root);
|
||||
return card;
|
||||
}
|
||||
|
||||
function applyMode(state) {
|
||||
const single = isSingleFrame(state);
|
||||
state.root.classList.toggle("is-single-frame", single);
|
||||
state.frameButton?.classList.toggle("active", single);
|
||||
if (state.cardMode !== single) {
|
||||
state.cardMode = single;
|
||||
mountCard(state);
|
||||
}
|
||||
state.card?.sync();
|
||||
state.startLabel.textContent = single ? "AT" : "IN";
|
||||
state.range.title = single
|
||||
? "Drag or click to choose the frame that loads"
|
||||
: "Drag either handle to set the trim; drag the selected range to move it";
|
||||
updateTrimFace(state);
|
||||
}
|
||||
|
||||
// The playhead follows the player, so the card's marker and readout move
|
||||
// with the picture.
|
||||
function followPlayer(state) {
|
||||
const rate = clipInfo(state.metadata).fps;
|
||||
if (!(rate > 0)) return;
|
||||
const frame = Math.max(0, Math.floor(state.video.currentTime * rate + 1e-6));
|
||||
if (frame === state.head) return;
|
||||
state.head = frame;
|
||||
state.card?.sync();
|
||||
function widgetLinkDriven(node, name) {
|
||||
return !!node.inputs?.some((input) => input?.widget?.name === name && input.link != null);
|
||||
}
|
||||
|
||||
// The honest "what will actually load" text for the label under the trim
|
||||
// strip, or "" when there is nothing honest to say. Any of the deciding
|
||||
// widgets driven by a link means its face value is stale, so the count
|
||||
// drops out rather than guessing.
|
||||
function trimLoadSummary(state, duration, bounds) {
|
||||
const deciders = ["start_seconds", "end_seconds", "every_nth", "max_frames", "single_frame"];
|
||||
if (deciders.some((name) => widgetLinkDriven(state.node, name))) return "";
|
||||
return loadSummary(
|
||||
duration,
|
||||
bounds,
|
||||
state.sourceFps,
|
||||
state.everyNthWidget?.value,
|
||||
state.maxFramesWidget?.value,
|
||||
isSingleFrame(state),
|
||||
);
|
||||
}
|
||||
|
||||
// The <video> element never exposes the source frame rate, so the frame
|
||||
// count in the label needs a probe of the pack's metadata route. Fail-soft:
|
||||
// on any error the label simply omits the count and the timecodes stand.
|
||||
async function probeSourceFps(state, name) {
|
||||
state.sourceFps = 0;
|
||||
try {
|
||||
const query = new URLSearchParams({ source_mode: "input folder", video: name });
|
||||
const response = await api.fetchApi(`/ausboss/transform/video/metadata?${query}`);
|
||||
if (!response.ok) return;
|
||||
const metadata = await response.json();
|
||||
if (state.videoWidget.value !== name) return; // a newer selection won
|
||||
state.sourceFps = Math.max(0, Number(metadata?.fps) || 0);
|
||||
updateTrimFace(state);
|
||||
} catch (_error) {
|
||||
/* no fps, no frame count */
|
||||
}
|
||||
}
|
||||
|
||||
function writeWidget(widget, value) {
|
||||
const next = roundHundredth(value);
|
||||
if (Math.abs(Number(widget.value || 0) - next) < 0.0001) return;
|
||||
widget.value = next;
|
||||
widget.callback?.(next);
|
||||
}
|
||||
|
||||
function writeTrim(state, bounds, seekEdge = null) {
|
||||
state.writing = true;
|
||||
try {
|
||||
writeWidget(state.startWidget, bounds.start);
|
||||
writeWidget(state.endWidget, bounds.end);
|
||||
} finally {
|
||||
state.writing = false;
|
||||
}
|
||||
updateTrimFace(state);
|
||||
if (state.video.readyState >= 1 && seekEdge) {
|
||||
state.video.currentTime = seekEdge === "start"
|
||||
? bounds.start
|
||||
: Math.max(bounds.start, bounds.end - TRIM_EPSILON);
|
||||
}
|
||||
state.node.setDirtyCanvas?.(true, true);
|
||||
state.node.graph?.setDirtyCanvas?.(true, true);
|
||||
}
|
||||
|
||||
function writeFrameTime(state, timeValue) {
|
||||
const duration = Number.isFinite(state.video.duration) ? state.video.duration : 0;
|
||||
const time = singleFrameTime(duration, timeValue);
|
||||
state.writing = true;
|
||||
try {
|
||||
writeWidget(state.startWidget, time);
|
||||
} finally {
|
||||
state.writing = false;
|
||||
}
|
||||
updateTrimFace(state);
|
||||
if (state.video.readyState >= 1) state.video.currentTime = time;
|
||||
state.node.setDirtyCanvas?.(true, true);
|
||||
state.node.graph?.setDirtyCanvas?.(true, true);
|
||||
}
|
||||
|
||||
function updateTrimFace(state) {
|
||||
const duration = Number.isFinite(state.video.duration) ? state.video.duration : 0;
|
||||
if (isSingleFrame(state)) {
|
||||
const time = singleFrameTime(duration, state.startWidget.value);
|
||||
const percent = singleFrameFraction(duration, time) * 100;
|
||||
state.selection.style.width = "0%";
|
||||
state.startHandle.style.left = `${percent}%`;
|
||||
if (document.activeElement !== state.startInput) state.startInput.value = formatTimecode(time);
|
||||
// "1 frame at 0:05.2" - the count comes from the same pure summary the
|
||||
// trim label uses, so both modes report what one Run will load.
|
||||
const summary = trimLoadSummary(state, duration, null);
|
||||
state.durationLabel.textContent = duration > 0
|
||||
? `${summary || "frame"} at ${formatTimecode(time)}`
|
||||
: "load a video to pick a frame";
|
||||
if (duration > 0) state.status.textContent = `frame at ${formatTimecode(time)}`;
|
||||
return;
|
||||
}
|
||||
const bounds = trimBounds(duration, state.startWidget.value, state.endWidget.value);
|
||||
const fractions = trimFractions(duration, bounds);
|
||||
const startPercent = fractions.start * 100;
|
||||
const endPercent = fractions.end * 100;
|
||||
state.selection.style.left = `${startPercent}%`;
|
||||
state.selection.style.width = `${Math.max(0, endPercent - startPercent)}%`;
|
||||
state.startHandle.style.left = `${startPercent}%`;
|
||||
state.endHandle.style.left = `${endPercent}%`;
|
||||
if (document.activeElement !== state.startInput) state.startInput.value = formatTimecode(bounds.start);
|
||||
if (document.activeElement !== state.endInput) state.endInput.value = formatTimecode(bounds.end);
|
||||
const selected = Math.max(0, bounds.end - bounds.start);
|
||||
// The preview cannot re-render every_nth or max_frames, so the label
|
||||
// reports them instead: "0:04.0 of 0:10.0 · 48 frames @ 12 fps".
|
||||
const summary = trimLoadSummary(state, duration, bounds);
|
||||
state.durationLabel.textContent = duration > 0
|
||||
? `${formatTimecode(selected)} of ${formatTimecode(duration)}${summary ? ` · ${summary}` : ""}`
|
||||
: "load a video to trim";
|
||||
state.status.textContent = duration > 0
|
||||
? `${formatTimecode(bounds.start)} → ${formatTimecode(bounds.end)}`
|
||||
: state.status.textContent;
|
||||
}
|
||||
|
||||
function installTrimDrag(state) {
|
||||
const { range } = state;
|
||||
const infoAt = (clientX) => {
|
||||
const rect = range.getBoundingClientRect();
|
||||
const duration = Number.isFinite(state.video.duration) ? state.video.duration : 0;
|
||||
const bounds = currentBounds(state);
|
||||
const fractions = trimFractions(duration, bounds);
|
||||
const x = clientX - rect.left;
|
||||
const hit = 10;
|
||||
let zone = "jump";
|
||||
const closest = closestTrimHandle(
|
||||
fractions.start,
|
||||
fractions.end,
|
||||
rect.width ? x / rect.width : 0,
|
||||
rect.width,
|
||||
hit,
|
||||
);
|
||||
if (closest) zone = closest;
|
||||
else if (x > fractions.start * rect.width && x < fractions.end * rect.width) zone = "move";
|
||||
return { rect, duration, bounds, fraction: rect.width ? x / rect.width : 0, zone };
|
||||
};
|
||||
|
||||
range.addEventListener("pointermove", (event) => {
|
||||
if (state.dragging) return;
|
||||
if (isSingleFrame(state)) {
|
||||
range.style.cursor = "ew-resize";
|
||||
return;
|
||||
}
|
||||
const { zone } = infoAt(event.clientX);
|
||||
range.style.cursor = zone === "start" || zone === "end"
|
||||
? "ew-resize"
|
||||
: zone === "move" ? "grab" : "pointer";
|
||||
});
|
||||
|
||||
range.addEventListener("pointerdown", (event) => {
|
||||
if (event.button !== 0 || state.dragging) return;
|
||||
const initial = infoAt(event.clientX);
|
||||
if (initial.duration <= 0) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (isSingleFrame(state)) {
|
||||
// Frame-picker gesture: the strip is one scrub rail. A click already
|
||||
// sets the frame; a drag keeps refining it until release.
|
||||
state.dragging = true;
|
||||
try { range.setPointerCapture(event.pointerId); } catch (_error) { /* mouse fallback */ }
|
||||
const scrub = (clientX) => {
|
||||
const next = infoAt(clientX);
|
||||
writeFrameTime(state, next.fraction * next.duration);
|
||||
};
|
||||
scrub(event.clientX);
|
||||
const move = (moveEvent) => {
|
||||
if (!(moveEvent.buttons & 1)) { finish(); return; }
|
||||
scrub(moveEvent.clientX);
|
||||
};
|
||||
const finish = () => {
|
||||
if (!state.dragging) return;
|
||||
state.dragging = false;
|
||||
range.removeEventListener("pointermove", move);
|
||||
try { range.releasePointerCapture(event.pointerId); } catch (_error) { /* already released */ }
|
||||
// One notification per gesture: the frame changed on pointerdown.
|
||||
notifyAusbossChange();
|
||||
};
|
||||
range.addEventListener("pointermove", move);
|
||||
range.addEventListener("pointerup", finish, { once: true });
|
||||
range.addEventListener("pointercancel", finish, { once: true });
|
||||
range.addEventListener("lostpointercapture", finish, { once: true });
|
||||
return;
|
||||
}
|
||||
state.dragging = true;
|
||||
try { range.setPointerCapture(event.pointerId); } catch (_error) { /* mouse fallback */ }
|
||||
const downX = event.clientX;
|
||||
const anchorTime = initial.fraction * initial.duration;
|
||||
let moved = false;
|
||||
|
||||
const apply = (clientX) => {
|
||||
const next = infoAt(clientX);
|
||||
if (initial.zone === "start" || initial.zone === "end") {
|
||||
writeTrim(
|
||||
state,
|
||||
dragTrimHandle(next.duration, currentBounds(state), initial.zone, next.fraction),
|
||||
initial.zone,
|
||||
);
|
||||
} else if (initial.zone === "move") {
|
||||
const pointerTime = next.fraction * next.duration;
|
||||
writeTrim(
|
||||
state,
|
||||
slideTrimWindow(next.duration, initial.bounds, pointerTime - anchorTime),
|
||||
"start",
|
||||
);
|
||||
} else {
|
||||
const span = initial.bounds.end - initial.bounds.start;
|
||||
const centeredStart = next.fraction * next.duration - span / 2;
|
||||
writeTrim(
|
||||
state,
|
||||
slideTrimWindow(next.duration, initial.bounds, centeredStart - initial.bounds.start),
|
||||
"start",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const move = (moveEvent) => {
|
||||
if (!(moveEvent.buttons & 1)) { finish(moveEvent); return; }
|
||||
if (!moved && Math.abs(moveEvent.clientX - downX) < 3) return;
|
||||
moved = true;
|
||||
apply(moveEvent.clientX);
|
||||
};
|
||||
const finish = (finishEvent) => {
|
||||
if (!state.dragging) return;
|
||||
state.dragging = false;
|
||||
range.removeEventListener("pointermove", move);
|
||||
try { range.releasePointerCapture(event.pointerId); } catch (_error) { /* already released */ }
|
||||
if (!moved && initial.zone === "jump") {
|
||||
const next = infoAt(finishEvent?.clientX ?? downX);
|
||||
const span = initial.bounds.end - initial.bounds.start;
|
||||
const centeredStart = next.fraction * next.duration - span / 2;
|
||||
writeTrim(
|
||||
state,
|
||||
slideTrimWindow(next.duration, initial.bounds, centeredStart - initial.bounds.start),
|
||||
"start",
|
||||
);
|
||||
}
|
||||
// One notification per gesture, on release — never per pointermove.
|
||||
if (moved || initial.zone === "jump") notifyAusbossChange();
|
||||
};
|
||||
range.addEventListener("pointermove", move);
|
||||
range.addEventListener("pointerup", finish, { once: true });
|
||||
range.addEventListener("pointercancel", finish, { once: true });
|
||||
range.addEventListener("lostpointercapture", finish, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
function installPlayback(state) {
|
||||
@@ -203,9 +356,9 @@ function installPlayback(state) {
|
||||
state.playRaf = 0;
|
||||
};
|
||||
const tick = () => {
|
||||
if (video.paused || video.ended) { stopTick(); followPlayer(state); return; }
|
||||
// Frame picking plays the whole source freely - the clip is not in
|
||||
// force, so there is no boundary to loop or stop at.
|
||||
if (video.paused || video.ended) { stopTick(); return; }
|
||||
// Frame picking plays the whole source freely — the trim window is not
|
||||
// in force, so there is no boundary to loop or stop at.
|
||||
if (!isSingleFrame(state)) {
|
||||
const bounds = currentBounds(state);
|
||||
const action = playbackBoundaryAction(video.currentTime, bounds, getLoopEnabled(state.node), TRIM_EPSILON);
|
||||
@@ -214,11 +367,9 @@ function installPlayback(state) {
|
||||
} else if (action === "stop") {
|
||||
video.pause();
|
||||
video.currentTime = Math.max(bounds.start, bounds.end - TRIM_EPSILON);
|
||||
followPlayer(state);
|
||||
return;
|
||||
}
|
||||
}
|
||||
followPlayer(state);
|
||||
state.playRaf = requestAnimationFrame(tick);
|
||||
};
|
||||
video.addEventListener("play", () => {
|
||||
@@ -239,7 +390,7 @@ function installPlayback(state) {
|
||||
state.correctingSeek = true;
|
||||
video.currentTime = target;
|
||||
}, { signal: state.abort.signal });
|
||||
video.addEventListener("seeked", () => { state.correctingSeek = false; followPlayer(state); }, { signal: state.abort.signal });
|
||||
video.addEventListener("seeked", () => { state.correctingSeek = false; }, { signal: state.abort.signal });
|
||||
state.stopTick = stopTick;
|
||||
}
|
||||
|
||||
@@ -250,8 +401,8 @@ function watchTrimWidget(state, widget) {
|
||||
widget.callback = function (...args) {
|
||||
const result = prior?.apply(this, args);
|
||||
if (!state.writing) {
|
||||
state.card?.sync();
|
||||
if (state.video.readyState >= 1 && state.video.paused) state.video.currentTime = homeTime(state);
|
||||
updateTrimFace(state);
|
||||
if (state.video.readyState >= 1) state.video.currentTime = homeTime(state);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
@@ -265,10 +416,7 @@ function watchFrameWidget(state, widget) {
|
||||
const result = prior?.apply(this, args);
|
||||
if (!isSingleFrame(state)) {
|
||||
const reopened = trimAfterFramePick(state.startWidget.value, state.endWidget.value);
|
||||
if (reopened) {
|
||||
state.writing = true;
|
||||
try { setWidget(state.endWidget, reopened.end); } finally { state.writing = false; }
|
||||
}
|
||||
if (reopened) writeTrim(state, reopened);
|
||||
}
|
||||
applyMode(state);
|
||||
if (state.video.readyState >= 1) state.video.currentTime = homeTime(state);
|
||||
@@ -276,6 +424,28 @@ function watchFrameWidget(state, widget) {
|
||||
};
|
||||
}
|
||||
|
||||
function commitTimeInput(state, edge, input) {
|
||||
const duration = Number.isFinite(state.video.duration) ? state.video.duration : 0;
|
||||
if (duration <= 0) return;
|
||||
const seconds = parseTimecode(input.value);
|
||||
if (seconds === null) {
|
||||
// Malformed entry: restore the previous value and keep focus for a retry.
|
||||
const bounds = currentBounds(state);
|
||||
input.value = formatTimecode(edge === "start" ? bounds.start : bounds.end);
|
||||
return;
|
||||
}
|
||||
if (isSingleFrame(state)) {
|
||||
writeFrameTime(state, seconds);
|
||||
notifyAusbossChange();
|
||||
input.blur();
|
||||
return;
|
||||
}
|
||||
const fraction = seconds / duration;
|
||||
writeTrim(state, dragTrimHandle(duration, currentBounds(state), edge, fraction), edge);
|
||||
notifyAusbossChange();
|
||||
input.blur();
|
||||
}
|
||||
|
||||
function buildPreview(node) {
|
||||
if (node.__ausbossLoadVideo) return node.__ausbossLoadVideo;
|
||||
const videoWidget = findWidget(node, "video");
|
||||
@@ -291,8 +461,6 @@ function buildPreview(node) {
|
||||
hideCanvasWidget(startWidget);
|
||||
hideCanvasWidget(endWidget);
|
||||
if (frameWidget) hideCanvasWidget(frameWidget);
|
||||
// Every nth and the frame limit (the Duration) live in the timing card;
|
||||
// the widget card hides their widgets (js/widget_cards).
|
||||
|
||||
const root = document.createElement("div");
|
||||
root.className = "ausboss-video-root";
|
||||
@@ -307,7 +475,7 @@ function buildPreview(node) {
|
||||
status.textContent = "Choose or upload a video";
|
||||
const tools = document.createElement("div");
|
||||
tools.className = "ausboss-video-tools";
|
||||
const loopButton = makeToolButton("LOOP", "Play the clip again and again");
|
||||
const loopButton = makeToolButton("LOOP", "Loop playback inside the selected trim");
|
||||
loopButton.classList.add("ausboss-video-loop");
|
||||
const reloadButton = makeToolButton("↻", "Reload the selected source video");
|
||||
const frameButton = frameWidget
|
||||
@@ -317,12 +485,45 @@ function buildPreview(node) {
|
||||
tools.append(loopButton, reloadButton);
|
||||
stage.append(video, status, tools);
|
||||
|
||||
// The timing card goes here (mountCard): the clip node's Start,
|
||||
// Duration and Ends at, or the frame picker while FRAME is on.
|
||||
const cardSlot = document.createElement("div");
|
||||
cardSlot.className = "ausboss-video-timing";
|
||||
cardSlot.style.flex = "none";
|
||||
root.append(stage, cardSlot);
|
||||
const trim = document.createElement("div");
|
||||
trim.className = "ausboss-video-trim";
|
||||
const range = document.createElement("div");
|
||||
range.className = "ausboss-video-range";
|
||||
range.title = "Drag either handle to set the trim; drag the selected range to move it";
|
||||
const selection = document.createElement("div");
|
||||
selection.className = "ausboss-video-selection";
|
||||
const startHandle = document.createElement("div");
|
||||
startHandle.className = "ausboss-video-handle";
|
||||
const endHandle = document.createElement("div");
|
||||
endHandle.className = "ausboss-video-handle is-end";
|
||||
range.append(selection, startHandle, endHandle);
|
||||
const values = document.createElement("div");
|
||||
values.className = "ausboss-video-values";
|
||||
const makeValue = (labelText) => {
|
||||
const wrap = document.createElement("div");
|
||||
wrap.className = "ausboss-video-value";
|
||||
const label = document.createElement("label");
|
||||
label.textContent = labelText;
|
||||
const input = document.createElement("input");
|
||||
input.type = "text";
|
||||
input.inputMode = "decimal";
|
||||
input.placeholder = "m:ss.s";
|
||||
input.title = `${labelText} point - type seconds (95.5) or a timecode (1:35.5, 1:02:03.5)`;
|
||||
input.addEventListener("keydown", (event) => {
|
||||
keepKeyInField(event);
|
||||
if (event.key === "Enter") input.dispatchEvent(new Event("change"));
|
||||
});
|
||||
wrap.append(label, input);
|
||||
return { wrap, input, label };
|
||||
};
|
||||
const startValue = makeValue("IN");
|
||||
const endValue = makeValue("OUT");
|
||||
endValue.wrap.classList.add("is-end");
|
||||
const durationLabel = document.createElement("div");
|
||||
durationLabel.className = "ausboss-video-duration";
|
||||
values.append(startValue.wrap, durationLabel, endValue.wrap);
|
||||
trim.append(range, values);
|
||||
root.append(stage, trim);
|
||||
|
||||
const widget = node.addDOMWidget(PREVIEW_WIDGET, "ausboss_video", root, {
|
||||
serialize: false,
|
||||
@@ -343,9 +544,15 @@ function buildPreview(node) {
|
||||
const abort = new AbortController();
|
||||
const state = node.__ausbossLoadVideo = {
|
||||
node, root, stage, video, status, loopButton, reloadButton, frameButton,
|
||||
cardSlot, card: null, cardMode: null, metadata: null, head: 0,
|
||||
trim, range, selection, startHandle, endHandle, startInput: startValue.input,
|
||||
endInput: endValue.input, startLabel: startValue.label, durationLabel,
|
||||
videoWidget, startWidget, endWidget, frameWidget,
|
||||
widget, abort, writing: false, correctingSeek: false, playRaf: 0,
|
||||
// Absent on a backend without these widgets; the summary then reads
|
||||
// its defaults (keep every frame, no cap).
|
||||
everyNthWidget: findWidget(node, "every_nth"),
|
||||
maxFramesWidget: findWidget(node, "max_frames"),
|
||||
sourceFps: 0,
|
||||
widget, abort, writing: false, dragging: false, correctingSeek: false, playRaf: 0,
|
||||
};
|
||||
|
||||
const updateLoopButton = () => loopButton.classList.toggle("active", getLoopEnabled(node));
|
||||
@@ -376,9 +583,9 @@ function buildPreview(node) {
|
||||
if (!name || typeof name !== "string") {
|
||||
video.pause();
|
||||
video.removeAttribute("src");
|
||||
state.metadata = null;
|
||||
state.sourceFps = 0;
|
||||
setEmpty(state, "Choose or upload a video");
|
||||
state.card?.sync();
|
||||
updateTrimFace(state);
|
||||
return;
|
||||
}
|
||||
const parts = splitMediaName(name);
|
||||
@@ -388,7 +595,7 @@ function buildPreview(node) {
|
||||
const type = parseImageReference(name)?.type ?? "input";
|
||||
video.src = api.apiURL(`/view?${mediaViewQuery({ ...parts, type }, "input")}`);
|
||||
video.load();
|
||||
probeMetadata(state, name);
|
||||
probeSourceFps(state, name);
|
||||
};
|
||||
state.refresh = refresh;
|
||||
reloadButton.addEventListener("click", (event) => {
|
||||
@@ -398,23 +605,31 @@ function buildPreview(node) {
|
||||
});
|
||||
|
||||
video.addEventListener("loadedmetadata", () => {
|
||||
const single = isSingleFrame(state);
|
||||
const bounds = currentBounds(state);
|
||||
if (!single && bounds.end - bounds.start < MIN_TRIM_SECONDS && video.duration >= MIN_TRIM_SECONDS) {
|
||||
writeTrim(state, { start: Math.max(0, bounds.end - MIN_TRIM_SECONDS), end: bounds.end });
|
||||
}
|
||||
video.currentTime = homeTime(state);
|
||||
// The card says where the clip is; the stage only names the source on hover.
|
||||
setReady(state, "");
|
||||
setReady(state, single
|
||||
? `frame at ${formatTimecode(homeTime(state))}`
|
||||
: `${formatTimecode(currentBounds(state).start)} → ${formatTimecode(currentBounds(state).end)}`);
|
||||
// Quiet source hint: resolution and duration from the loaded metadata.
|
||||
const sourceInfo = mediaInfo(null, video);
|
||||
stage.title = sourceInfo ? `Source: ${sourceInfo}` : "";
|
||||
state.card?.sync();
|
||||
durationLabel.title = sourceInfo ? `Source: ${sourceInfo}` : "";
|
||||
updateTrimFace(state);
|
||||
node.setDirtyCanvas?.(true, true);
|
||||
}, { signal: abort.signal });
|
||||
video.addEventListener("error", () => setEmpty(state, "Preview could not load this video"), { signal: abort.signal });
|
||||
|
||||
installTrimDrag(state);
|
||||
installPlayback(state);
|
||||
watchTrimWidget(state, startWidget);
|
||||
watchTrimWidget(state, endWidget);
|
||||
watchFrameWidget(state, frameWidget);
|
||||
watchTrimWidget(state, findWidget(node, "every_nth"));
|
||||
watchTrimWidget(state, findWidget(node, "max_frames"));
|
||||
applyMode(state);
|
||||
startValue.input.addEventListener("change", () => commitTimeInput(state, "start", startValue.input));
|
||||
endValue.input.addEventListener("change", () => commitTimeInput(state, "end", endValue.input));
|
||||
|
||||
const priorVideoCallback = videoWidget.callback;
|
||||
videoWidget.callback = function (...args) {
|
||||
@@ -449,11 +664,6 @@ app.registerExtension({
|
||||
}
|
||||
});
|
||||
});
|
||||
// A wire into a timing input changes what the card can show.
|
||||
chainCallback(nodeType.prototype, "onConnectionsChange", function () {
|
||||
const state = this.__ausbossLoadVideo;
|
||||
if (state) queueMicrotask(() => state.card?.sync());
|
||||
});
|
||||
chainCallback(nodeType.prototype, "onRemoved", function () {
|
||||
const state = this.__ausbossLoadVideo;
|
||||
state?.stopTick?.();
|
||||
|
||||
@@ -13,7 +13,6 @@ import { makeScrubInput } from "../shared/scrub_input.mjs";
|
||||
import { isAppShortcut, keepKeyInField } from "../shared/canvas_passthrough.mjs";
|
||||
import { resetUnknownValues } from "../shared/widget_card_math.mjs";
|
||||
import { boxRowInputs, boxRowsWidget, boxesOf, hostBox, rowsInputName, workflowNodes } from "../shared/lora_box.mjs";
|
||||
import { coreLoraList, syncFileWidgets } from "../shared/lora_file_widgets.mjs";
|
||||
import {
|
||||
SETTINGS_PROPERTY as SWITCHES_PROPERTY, releaseStackGroup, releaseStackRow, renameStackGroup, stackGroupOwners, stackRowOwners,
|
||||
} from "../shared/workflow_switches.mjs";
|
||||
@@ -725,47 +724,9 @@ function commitRows(state, rows, { structural = false, record = true } = {}) {
|
||||
state.node.graph?.setDirtyCanvas(true, true);
|
||||
if (structural) renderRows(state);
|
||||
else updateRowValues(state);
|
||||
syncLoraFiles(state.node);
|
||||
if (record) notifyAusbossChange();
|
||||
}
|
||||
|
||||
// ComfyUI's missing-models list sees a row's file only through a list
|
||||
// widget, so each row that needs a file gets a hidden one
|
||||
// (js/shared/lora_file_widgets.mjs). Rows that come in over a link (from a
|
||||
// box or another node) are not this node's to list.
|
||||
function syncLoraFiles(node) {
|
||||
if (node?.type !== NODE_CLASS) return;
|
||||
const widget = node.widgets?.find((item) => item.name === "loras");
|
||||
if (!widget) return;
|
||||
const fed = node.inputs?.find((item) => item?.name === "loras")?.link != null;
|
||||
syncFileWidgets(node, fed ? [] : parseRows(widget.value), {
|
||||
installed: () => coreLoraList(globalThis.LiteGraph?.registered_node_types?.LoraLoader?.nodeData)
|
||||
?? node.__ausbossLoraState?.available ?? null,
|
||||
hide: hideWidget,
|
||||
onPick: (rowId, name) => pickRowFile(node, rowId, name),
|
||||
});
|
||||
}
|
||||
|
||||
// ComfyUI put another file in a row's hidden list (a replacement picked in
|
||||
// its Issues panel): the row takes that file.
|
||||
function pickRowFile(node, rowId, name) {
|
||||
const widget = node.widgets?.find((item) => item.name === "loras");
|
||||
if (!widget) return;
|
||||
const rows = parseRows(widget.value);
|
||||
const row = rows.find((item) => item.id === rowId);
|
||||
if (!row || row.name === name) return;
|
||||
row.name = name;
|
||||
const state = node.__ausbossLoraState;
|
||||
if (state && !state.disposed && !state.readOnly && state.widget === widget) {
|
||||
commitRows(state, rows, { structural: true });
|
||||
return;
|
||||
}
|
||||
widget.value = serializeRows(rows);
|
||||
node.graph?.setDirtyCanvas(true, true);
|
||||
syncLoraFiles(node);
|
||||
notifyAusbossChange();
|
||||
}
|
||||
|
||||
// A box shows its loader's rows the way the loader does: one strength per
|
||||
// row, or model and CLIP apart.
|
||||
function linked(state) {
|
||||
@@ -3066,7 +3027,6 @@ function syncRows(state) {
|
||||
state.toggleSnapshot = snapshotEnabled(state.rows);
|
||||
renderRows(state);
|
||||
fitNode(state);
|
||||
syncLoraFiles(state.node);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -3364,12 +3324,6 @@ app.registerExtension({
|
||||
});
|
||||
chainCallback(nodeType.prototype, "onConfigure", function () {
|
||||
resetUnknownValues(this.widgets, RESET_UNKNOWN);
|
||||
// Now, not later: ComfyUI reads its missing-models list right after
|
||||
// the workflow is restored.
|
||||
syncLoraFiles(this);
|
||||
});
|
||||
chainCallback(nodeType.prototype, "onConnectionsChange", function () {
|
||||
syncLoraFiles(this);
|
||||
});
|
||||
},
|
||||
// A box (subgraph node) shows the rows of a loader inside once they come
|
||||
|
||||
@@ -47,24 +47,6 @@ async function stopLook(node) {
|
||||
return Boolean(running || waiting.length);
|
||||
}
|
||||
|
||||
// Take this node's own runs that still wait out of the queue: the looks and
|
||||
// touches its picture asked for (they carry an `ask`), never a run of the
|
||||
// workflow. Says how many went. The one that is running is left alone.
|
||||
async function dropWaiting(node) {
|
||||
const id = executionIdOf(app.rootGraph ?? app.graph, node);
|
||||
if (!id) return 0;
|
||||
const queue = await (await api.fetchApi("/queue")).json();
|
||||
const ours = (entry) => {
|
||||
const step = entry?.[2]?.[id];
|
||||
return step?.class_type === NODE_CLASS && String(step.inputs?.ask ?? "") !== "";
|
||||
};
|
||||
const waiting = (queue?.queue_pending ?? []).filter(ours).map((entry) => entry[1]);
|
||||
if (waiting.length) {
|
||||
await api.fetchApi("/queue", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ delete: waiting }) });
|
||||
}
|
||||
return waiting.length;
|
||||
}
|
||||
|
||||
// The picture goes above the settings: the stage widget sits ahead of the
|
||||
// node's card, whichever of the two was built first.
|
||||
function stageFirst(node) {
|
||||
@@ -110,7 +92,6 @@ function build(node) {
|
||||
const face = mountTouchStage(node, {
|
||||
lookOnButton: () => lookOnButton,
|
||||
stopLook: () => stopLook(node).catch(() => false),
|
||||
dropWaiting: () => dropWaiting(node).catch(() => 0),
|
||||
// A workflow is being opened: nothing is run on the person's behalf.
|
||||
loading: () => Boolean(app.configuringGraph),
|
||||
// Bypassed or muted, or inside a box that is: nothing is run for it.
|
||||
|
||||
@@ -30,7 +30,7 @@ import {
|
||||
} from "../shared/index.mjs";
|
||||
import { WIDGET_FRAME, fillNodeHeight, holdVueNodeMinWidth } from "../shared/panel_layout.mjs";
|
||||
import { hideInputsInDef, hideWidget } from "../shared/widget_visibility.mjs";
|
||||
import { liftSlot, markSocketless } from "../shared/widget_card_math.mjs";
|
||||
import { markSocketless } from "../shared/widget_card_math.mjs";
|
||||
import { makeScrubInput } from "../shared/scrub_input.mjs";
|
||||
import {
|
||||
closeSettingsMenu,
|
||||
@@ -1014,7 +1014,8 @@ function installResolutionNode(node) {
|
||||
const liftSockets = () => {
|
||||
for (const input of node.inputs ?? []) {
|
||||
if (["width", "height", "latent", "batch_size"].includes(input.widget?.name)) {
|
||||
liftSlot(input);
|
||||
delete input.widget;
|
||||
input._widget = undefined;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -26,7 +26,6 @@ import { nodeByExecutionId } from "../shared/graph_ids.mjs";
|
||||
import {
|
||||
collapseRepeatedErrors,
|
||||
emptySourceMessage,
|
||||
explainRunError,
|
||||
findEmptySources,
|
||||
nodeLacksSource,
|
||||
} from "../shared/run_check.mjs";
|
||||
@@ -175,20 +174,10 @@ function collapseAnswers() {
|
||||
api.queuePrompt = collapsing;
|
||||
}
|
||||
|
||||
// A run that stops on an error the pack knows the cause of gets one toast
|
||||
// that says what to do. ComfyUI's own error report is left as it is.
|
||||
function explainKnownErrors() {
|
||||
api.addEventListener("execution_error", ({ detail }) => {
|
||||
const known = explainRunError(detail);
|
||||
if (known) showToast({ severity: "warn", summary: known.summary, detail: known.detail, life: 30000 });
|
||||
});
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "ausboss.run_check",
|
||||
setup() {
|
||||
guardRuns();
|
||||
collapseAnswers();
|
||||
explainKnownErrors();
|
||||
},
|
||||
});
|
||||
|
||||
+5
-34
@@ -33,7 +33,7 @@ const CARD_HEIGHT = 288;
|
||||
const WRAPPER_INSET = 16;
|
||||
const HIDDEN = [
|
||||
"filename_prefix", "format", "save_metadata", "exact_name", "on_existing",
|
||||
"output_dir", "caption", "name_counter", "name_date", "name_time", "name_size", "name_batch", "autosave",
|
||||
"output_dir", "caption", "name_counter", "name_date", "name_time", "name_size", "name_batch",
|
||||
];
|
||||
const FONT = `-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif`;
|
||||
const MONO = `ui-monospace,SFMono-Regular,Menlo,Consolas,monospace`;
|
||||
@@ -60,10 +60,7 @@ function ensureCss() {
|
||||
.ausboss-save-chip:hover{color:#fff;border-color:${BRAND}}
|
||||
.ausboss-save-chip.on{background:${BRAND};border-color:${BRAND};color:#04201d}
|
||||
.ausboss-save-chips.off .ausboss-save-chip{opacity:.4;pointer-events:none}
|
||||
.ausboss-save-embed-label{flex:none;color:#8ba3a1;font-size:11px;white-space:nowrap;user-select:none}
|
||||
.ausboss-save-half{display:flex;align-items:center;gap:6px;flex:1 1 auto;min-width:0}
|
||||
.ausboss-save-half .ausboss-card-seg{flex:1 1 0;min-width:0}
|
||||
.ausboss-save-switches{gap:12px}
|
||||
.ausboss-save-embed-label{flex:0 0 30%;color:#8ba3a1;font-size:11px;user-select:none}
|
||||
.ausboss-save-browse{position:fixed;z-index:10000;width:260px;max-height:320px;overflow:auto;padding:4px;border:1px solid #3a4047;border-radius:7px;background:#1c1f23;box-shadow:0 8px 28px rgba(0,0,0,.5);font:12px/1.3 ${FONT};color:#d8ecea}
|
||||
.ausboss-save-browse-head{padding:5px 8px 6px;border-bottom:1px solid #2c3238;color:#78908e;font:10px/1 ${FONT};letter-spacing:.08em;text-transform:uppercase;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.ausboss-save-browse button{display:block;width:100%;padding:6px 8px;border:none;border-radius:5px;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer}
|
||||
@@ -149,7 +146,7 @@ async function openBrowse(state, anchor) {
|
||||
}
|
||||
path = listing.path;
|
||||
const use = el("button", "use", path ? `Use “${path}”` : "Use the output folder");
|
||||
use.addEventListener("click", () => { state.savedPath = null; setValue(state.node, "output_dir", path); state.refresh(); notifyAusbossChange(); closeBrowse(); });
|
||||
use.addEventListener("click", () => { setValue(state.node, "output_dir", path); state.refresh(); notifyAusbossChange(); closeBrowse(); });
|
||||
popup.append(use);
|
||||
if (path) {
|
||||
const up = el("button", "", "↑ up one level");
|
||||
@@ -285,29 +282,9 @@ function buildCard(node) {
|
||||
button.addEventListener("click", () => { if (setValue(node, "save_metadata", on)) notifyAusbossChange(); state.refresh(); });
|
||||
embedSeg.append(button); embedButtons.set(on, button);
|
||||
}
|
||||
const embedHalf = el("div", "ausboss-save-half");
|
||||
embedHalf.append(el("span", "ausboss-save-embed-label", PANEL_LABELS.embed), embedSeg);
|
||||
embedRow.classList.add("ausboss-save-switches");
|
||||
embedRow.append(embedHalf);
|
||||
embedRow.append(el("span", "ausboss-save-embed-label", PANEL_LABELS.embed), embedSeg);
|
||||
root.append(embedRow);
|
||||
|
||||
// Auto save: off shows the pictures without saving them; the Save button
|
||||
// over the picture (js/input_preview) then keeps the ones that are wanted.
|
||||
// It shares the Embed workflow row, so the card is no taller than before.
|
||||
const autoHalf = el("div", "ausboss-save-half");
|
||||
const autoSeg = el("div", "ausboss-card-seg ausboss-card-bool");
|
||||
autoSeg.setAttribute("role", "radiogroup");
|
||||
const autoButtons = new Map();
|
||||
const autoTitle = "On: every run saves its pictures. Off: the pictures only show here, and the Save button over them keeps the ones you want.";
|
||||
for (const [on, text] of [[false, PANEL_LABELS.off], [true, PANEL_LABELS.on]]) {
|
||||
const button = el("button", "", text);
|
||||
button.type = "button"; button.title = autoTitle;
|
||||
button.addEventListener("click", () => { if (setValue(node, "autosave", on)) { state.savedPath = null; notifyAusbossChange(); } state.refresh(); });
|
||||
autoSeg.append(button); autoButtons.set(on, button);
|
||||
}
|
||||
autoHalf.append(el("span", "ausboss-save-embed-label", "Auto save"), autoSeg);
|
||||
embedRow.append(autoHalf);
|
||||
|
||||
root.addEventListener("pointerdown", (event) => {
|
||||
if (event.target.closest("button,input,select")) event.stopPropagation();
|
||||
});
|
||||
@@ -353,11 +330,6 @@ function buildCard(node) {
|
||||
button.classList.toggle("on", on === embed);
|
||||
button.setAttribute("aria-checked", String(on === embed));
|
||||
}
|
||||
const auto = values.autosave !== false;
|
||||
for (const [on, button] of autoButtons) {
|
||||
button.classList.toggle("on", on === auto);
|
||||
button.setAttribute("aria-checked", String(on === auto));
|
||||
}
|
||||
};
|
||||
|
||||
const domWidget = node.addDOMWidget(WIDGET_NAME, WIDGET_NAME, root, {
|
||||
@@ -398,8 +370,7 @@ function buildCard(node) {
|
||||
chainCallback(node, "onExecuted", (output) => {
|
||||
if (isForeignRun()) return;
|
||||
const saved = output?.ausboss_saved_path?.[0];
|
||||
state.savedPath = typeof saved === "string" && saved ? saved : null;
|
||||
state.refresh();
|
||||
if (typeof saved === "string" && saved) { state.savedPath = saved; state.refresh(); }
|
||||
});
|
||||
chainCallback(node, "onRemoved", () => { state.alive = false; closeBrowse(); });
|
||||
state.refresh();
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
// App mode and the pack's cards. Pure logic, no DOM: tested under node:test.
|
||||
//
|
||||
// App mode is ComfyUI's simple form view of a workflow: a saved list of
|
||||
// fields (extra.linearData.inputs) and a Run button. Each field is a
|
||||
// widget. A node with a card or panel hides its standard widgets and shows
|
||||
// its own controls instead, and App mode reads that hidden flag too, so the
|
||||
// form drew an empty row for every field on such a node.
|
||||
//
|
||||
// While a workflow is in App mode, the widgets its form lists are shown
|
||||
// again; App mode draws its own control for each. Back in the graph they are
|
||||
// hidden again, so the node's face is unchanged. Only listed widgets move.
|
||||
import { hideWidget, isWidgetHidden, showWidget } from "./widget_visibility.mjs";
|
||||
|
||||
export const APP_MODE = "app";
|
||||
|
||||
// "app", "graph" or "builder:..." for the open workflow.
|
||||
export function workflowMode(workflow) {
|
||||
return workflow?.activeMode ?? workflow?.initialMode ?? "graph";
|
||||
}
|
||||
|
||||
// The form's fields as { nodeId, widget } pairs. A field is saved as
|
||||
// [nodeId, widgetName] or [nodeId, widgetName, { description }].
|
||||
export function appFields(linearData) {
|
||||
const inputs = Array.isArray(linearData?.inputs) ? linearData.inputs : [];
|
||||
const fields = [];
|
||||
for (const entry of inputs) {
|
||||
if (!Array.isArray(entry) || entry.length < 2) continue;
|
||||
const [nodeId, widget] = entry;
|
||||
if ((typeof nodeId !== "string" && typeof nodeId !== "number") || typeof widget !== "string") continue;
|
||||
fields.push({ nodeId: String(nodeId), widget });
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
// find(nodeId, widgetName) -> { node, widget } or null
|
||||
// changed(node) is called after a widget on that node changed visibility.
|
||||
export function createAppModeSync({ find, changed = () => {} }) {
|
||||
const lent = new Map(); // widget -> node, shown for the form
|
||||
return function sync(mode, linearData) {
|
||||
if (mode === APP_MODE) {
|
||||
for (const { nodeId, widget: name } of appFields(linearData)) {
|
||||
const found = find(nodeId, name);
|
||||
if (!found?.widget || !isWidgetHidden(found.widget)) continue;
|
||||
showWidget(found.widget);
|
||||
// An explicit false, not a deleted flag: the frontend keeps its own
|
||||
// copy of the hidden state and only hears about a written value.
|
||||
if (found.widget.options) found.widget.options.hidden = false;
|
||||
lent.set(found.widget, found.node);
|
||||
changed(found.node);
|
||||
}
|
||||
return lent.size;
|
||||
}
|
||||
for (const [widget, node] of lent) {
|
||||
if (hideWidget(widget)) changed(node);
|
||||
}
|
||||
lent.clear();
|
||||
return 0;
|
||||
};
|
||||
}
|
||||
@@ -289,86 +289,3 @@ export function repointLinks(text, nodes, groups) {
|
||||
.replace(ARROW_RE, (all, _arrow, id) => (id === undefined ? all : `${all.slice(0, -id.length - 1)}${follow(`#${id}`)}`));
|
||||
return changed ? next : null;
|
||||
}
|
||||
|
||||
// Info card: a small card with a title, rows and small print, chosen from the
|
||||
// note's menu. Its text is the note's ordinary text with one addition: a line
|
||||
// with a | in it is a row, the words before it on the left and the rest on
|
||||
// the right. A row in **bold** is the one to notice and is drawn in teal. The
|
||||
// first line is the card's title; a clock, info, warning, bulb or tick emoji
|
||||
// at its start is drawn as a small icon. A plain callout reads none of this,
|
||||
// so every note written before looks as it did, and a release before this
|
||||
// one shows the card as a plain note with its rows written out.
|
||||
const CARD_ICONS = new Map([
|
||||
["⏱", "clock"], ["⏲", "clock"], ["⏰", "clock"], ["\u{1F552}", "clock"], ["⌛", "clock"], ["⏳", "clock"],
|
||||
["ℹ", "info"], ["⚠", "warning"], ["\u{1F4A1}", "tip"], ["✅", "check"], ["✔", "check"],
|
||||
]);
|
||||
const CARD_ICON_RE = new RegExp(`^(${[...CARD_ICONS.keys()].join("|")})${VS16}?\\s*`, "u");
|
||||
export const CARD_TEMPLATE = [
|
||||
"ℹ️ Title",
|
||||
`${SMALL_MARK}A line of small print under the title.`,
|
||||
"",
|
||||
"Label | value",
|
||||
"**The one to notice | value**",
|
||||
"",
|
||||
`${SMALL_MARK}A note at the bottom.`,
|
||||
].join("\n");
|
||||
|
||||
// Where a row splits: the first | that is not inside a link, or -1.
|
||||
function cellSplit(line) {
|
||||
const masked = line.replace(WORDS_LINK_RE, (all) => " ".repeat(all.length));
|
||||
return masked.indexOf("|");
|
||||
}
|
||||
|
||||
// A row's two sides, or null when the line is not a row. The outer pipes of
|
||||
// a pasted Markdown table row are dropped.
|
||||
export function cardCells(line) {
|
||||
const bare = String(line ?? "").trim().replace(/^\|/, "").replace(/\|$/, "");
|
||||
const at = cellSplit(bare);
|
||||
if (at < 0) return null;
|
||||
let label = bare.slice(0, at).trim();
|
||||
let value = bare.slice(at + 1).trim();
|
||||
if (!label || !value) return null;
|
||||
// **label | value** marks the whole row.
|
||||
if (label.startsWith("**") && !label.slice(2).includes("**") && value.endsWith("**") && !value.slice(0, -2).includes("**")) {
|
||||
label = `${label}**`;
|
||||
value = `**${value}`;
|
||||
}
|
||||
return [label, value];
|
||||
}
|
||||
|
||||
// Text -> blocks of lines. A line is { kind: "title", icon, pieces },
|
||||
// { kind: "row", cells: [pieces, pieces], highlight } or { kind: "text",
|
||||
// pieces }; small print carries `small: true`. A Markdown table's ---|---
|
||||
// line is dropped.
|
||||
export function parseCard(text) {
|
||||
const blocks = [];
|
||||
let lines = [];
|
||||
let first = true;
|
||||
const flush = () => {
|
||||
if (lines.length) blocks.push(lines);
|
||||
lines = [];
|
||||
};
|
||||
for (const raw of String(text ?? "").replace(/\r\n?/g, "\n").split("\n")) {
|
||||
const line = raw.replace(HEADING_RE, "").trim();
|
||||
if (!line) { flush(); continue; }
|
||||
if (/^\|?[\s:|-]*-[\s:|-]*\|?$/.test(line) && line.includes("|")) continue;
|
||||
const small = SMALL_RE.test(raw);
|
||||
const cells = cardCells(line);
|
||||
let item;
|
||||
if (first && !small && !cells) {
|
||||
const icon = CARD_ICON_RE.exec(line);
|
||||
item = { kind: "title", icon: icon ? CARD_ICONS.get(icon[1]) : null, pieces: pieces(icon ? line.slice(icon[0].length) : line) };
|
||||
} else if (cells) {
|
||||
const sides = cells.map((cell) => pieces(cell));
|
||||
const shown = sides.flat().filter((piece) => piece.arrow || piece.text?.trim());
|
||||
item = { kind: "row", cells: sides, highlight: shown.length > 0 && shown.every((piece) => piece.bold) };
|
||||
} else {
|
||||
item = { kind: "text", pieces: pieces(line) };
|
||||
}
|
||||
first = false;
|
||||
if (small) item.small = true;
|
||||
lines.push(item);
|
||||
}
|
||||
flush();
|
||||
return blocks;
|
||||
}
|
||||
|
||||
@@ -9,34 +9,24 @@
|
||||
// in js/canvas_passthrough/ wires them to the page.
|
||||
|
||||
// The wheel belongs to the panel while it can still scroll that way (a long
|
||||
// text box, a list of rows). A text box with the cursor in it is no
|
||||
// exception: when it has nothing left to scroll, the wheel zooms the graph,
|
||||
// as it does over ComfyUI's own text boxes.
|
||||
export function canScrollFurther(element, delta, axis = "y") {
|
||||
if (!element || !delta) return false;
|
||||
const horizontal = axis === "x";
|
||||
const size = horizontal ? element.scrollWidth : element.scrollHeight;
|
||||
const visible = horizontal ? element.clientWidth : element.clientHeight;
|
||||
const start = horizontal ? element.scrollLeft : element.scrollTop;
|
||||
const room = size - visible;
|
||||
// text box, a list of rows), or while a text field has the keyboard.
|
||||
export function canScrollFurther(element, deltaY) {
|
||||
if (!element || !deltaY) return false;
|
||||
const room = element.scrollHeight - element.clientHeight;
|
||||
if (room <= 1) return false;
|
||||
return delta > 0 ? start + visible < size - 1 : start > 0;
|
||||
return deltaY > 0 ? element.scrollTop + element.clientHeight < element.scrollHeight - 1 : element.scrollTop > 0;
|
||||
}
|
||||
|
||||
// Does the wheel belong to something inside the panel, between the target
|
||||
// and the panel's own root? `styleOf` is getComputedStyle, passed in so this
|
||||
// stays testable without a page. `host` is the frontend's wrapper around the
|
||||
// panel: a pointer on the wrapper itself is on nothing inside the panel.
|
||||
// Ctrl + wheel, which is also how a trackpad pinch arrives, always zooms the
|
||||
// graph; left to a scrolling box it would zoom the whole page.
|
||||
export function panelKeepsWheel(target, event, { root, host, styleOf }) {
|
||||
if (event.ctrlKey || event.metaKey) return false;
|
||||
export function panelKeepsWheel(target, event, { root, host, styleOf, activeElement }) {
|
||||
for (let element = target; element && element !== root && element !== host; element = element.parentElement) {
|
||||
const style = styleOf(element);
|
||||
const overflow = style?.overflowY;
|
||||
const tag = String(element.tagName ?? "").toUpperCase();
|
||||
if ((tag === "TEXTAREA" || tag === "INPUT") && element === activeElement) return true;
|
||||
const overflow = styleOf(element)?.overflowY;
|
||||
if ((overflow === "auto" || overflow === "scroll") && canScrollFurther(element, event.deltaY)) return true;
|
||||
const overflowX = style?.overflowX;
|
||||
if ((overflowX === "auto" || overflowX === "scroll") && canScrollFurther(element, event.deltaX, "x")) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
+16
-64
@@ -1,76 +1,28 @@
|
||||
// Read only literal numeric sources. Calculated inputs must remain unknown
|
||||
// until execution; never evaluate an arbitrary upstream graph for a label.
|
||||
// A subgraph's output that comes straight from a literal inside it (Person
|
||||
// Swap's "Pick the model files" hands out its video fps that way) counts as
|
||||
// that literal: it is still a typed number, not a calculation.
|
||||
function tableLink(graph, id) {
|
||||
if (id == null || !graph) return null;
|
||||
return graph.getLink?.(id) ?? graph.links?.get?.(id) ?? graph.links?.[id] ?? graph._links?.get?.(id) ?? null;
|
||||
}
|
||||
|
||||
// The link into one of a node's inputs: the frontend's own accessor first
|
||||
// (newer frontends warn on reading input.link), the link table after it.
|
||||
// undefined when nothing is connected.
|
||||
function linkInto(node, index, graph) {
|
||||
if (typeof node?.getInputLink === "function" && node.graph) {
|
||||
try {
|
||||
return node.getInputLink(index) ?? undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
const id = node?.inputs?.[index]?.link;
|
||||
return id == null ? undefined : tableLink(node.graph ?? graph, id);
|
||||
}
|
||||
|
||||
// Where a linked input really comes from: the node and output slot at the
|
||||
// far end, through Reroutes and into a subgraph whose output is wired
|
||||
// straight to a node inside it. null for a muted or bypassed source, a loop,
|
||||
// or a subgraph output with nothing behind it. undefined when the input is
|
||||
// not linked at all.
|
||||
export function linkOrigin(node, name) {
|
||||
const index = node?.inputs?.findIndex((slot) => slot?.name === name || slot?.widget?.name === name) ?? -1;
|
||||
if (index < 0) return undefined;
|
||||
let graph = node.graph;
|
||||
let link = linkInto(node, index, graph);
|
||||
if (link === undefined) return undefined;
|
||||
export function inputNumber(node, name, fallback) {
|
||||
const input = node.inputs?.find((slot) => slot.name === name || slot.widget?.name === name);
|
||||
if (input?.link == null) return fallback;
|
||||
const graph = node.graph;
|
||||
let linkId = input.link;
|
||||
const seen = new Set();
|
||||
for (let depth = 0; depth < 16; depth++) {
|
||||
if (!link || seen.has(link)) return null;
|
||||
seen.add(link);
|
||||
const source = graph?.getNodeById?.(link.origin_id);
|
||||
if (seen.has(linkId)) return null;
|
||||
seen.add(linkId);
|
||||
const link = graph?.links?.[linkId] ?? graph?._links?.get?.(linkId);
|
||||
const source = graph?.getNodeById?.(link?.origin_id);
|
||||
if (!source || (source.mode ?? 0) !== 0) return null;
|
||||
if ((source.comfyClass ?? source.type) === "Reroute") {
|
||||
link = linkInto(source, 0, graph) ?? null;
|
||||
if (source.type === "Reroute") {
|
||||
linkId = source.inputs?.[0]?.link;
|
||||
if (linkId == null) return null;
|
||||
continue;
|
||||
}
|
||||
const inner = source.subgraph;
|
||||
if (inner && typeof source.isSubgraphNode === "function" && source.isSubgraphNode()) {
|
||||
link = tableLink(inner, inner.outputs?.[link.origin_slot]?.linkIds?.[0]);
|
||||
graph = inner;
|
||||
continue;
|
||||
}
|
||||
return { node: source, slot: link.origin_slot };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const LITERALS = ["PrimitiveFloat", "PrimitiveInt", "AUSBOSS_NODES_Integer", "AUSBOSS_NODES_Float"];
|
||||
|
||||
export function inputNumber(node, name, fallback) {
|
||||
const origin = linkOrigin(node, name);
|
||||
if (origin === undefined) return fallback;
|
||||
if (!origin) return null;
|
||||
const { node: source, slot } = origin;
|
||||
// ComfyUI's older Primitive node holds the value of the widget it feeds.
|
||||
if ((source.comfyClass ?? source.type) === "PrimitiveNode") {
|
||||
const value = source.widgets?.[0]?.value;
|
||||
if (!["PrimitiveFloat", "PrimitiveInt", "AUSBOSS_NODES_Integer", "AUSBOSS_NODES_Float"].includes(source.type) || link.origin_slot !== 0) return null;
|
||||
if (source.inputs?.some((slot) => slot.name === "value" && slot.link != null)) return null;
|
||||
const value = source.widgets?.find((widget) => widget.name === "value")?.value;
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
||||
}
|
||||
if (!LITERALS.includes(source.type) || slot !== 0) return null;
|
||||
if (source.inputs?.some((input) => input.name === "value" && input.link != null)) return null;
|
||||
const value = source.widgets?.find((widget) => widget.name === "value")?.value;
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function clipOutputRate(node, sourceFps, everyNth = 1) {
|
||||
|
||||
@@ -628,7 +628,7 @@ function installPointer(er, signal) {
|
||||
}
|
||||
|
||||
async function save(er) {
|
||||
if (er.signal.aborted || er.saving || !er.refs) return;
|
||||
if (er.saving || !er.refs) return;
|
||||
er.saving = true;
|
||||
syncTools(er);
|
||||
try {
|
||||
@@ -644,7 +644,6 @@ async function save(er) {
|
||||
})),
|
||||
});
|
||||
const answer = await response.json().catch(() => null);
|
||||
if (er.signal.aborted) return;
|
||||
if (!response.ok) {
|
||||
// No words from the route: this ComfyUI started before the update.
|
||||
const missing = (response.status === 404 || response.status === 405) && !answer?.error;
|
||||
@@ -653,11 +652,10 @@ async function save(er) {
|
||||
showToast({ severity: "success", summary: "Image Compare", detail: savedMessage(answer?.files) });
|
||||
er.onSaved?.(answer?.files ?? []);
|
||||
} catch (error) {
|
||||
if (er.signal.aborted) return;
|
||||
showToast({ severity: "error", summary: "Image Compare", detail: String(error?.message ?? error), life: 8000 });
|
||||
} finally {
|
||||
er.saving = false;
|
||||
if (!er.signal.aborted) syncTools(er);
|
||||
syncTools(er);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -665,24 +663,20 @@ async function save(er) {
|
||||
// to B as it came. The panel swaps in the pictures; Save and Copy then use
|
||||
// the lined-up B, and the paint stays where it is.
|
||||
async function align(er) {
|
||||
if (er.signal.aborted || er.aligning || !er.refs) return;
|
||||
if (er.aligning || !er.refs) return;
|
||||
if (er.refs.aligned) {
|
||||
er.onAligned?.(er.refs.original);
|
||||
return;
|
||||
}
|
||||
er.aligning = true;
|
||||
const refs = er.refs;
|
||||
const picturesVersion = er.picturesVersion;
|
||||
const current = () => !er.signal.aborted && er.refs === refs && er.picturesVersion === picturesVersion;
|
||||
syncTools(er);
|
||||
try {
|
||||
const response = await api.fetchApi(ALIGN_ROUTE, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ pair: refs.pair }),
|
||||
body: JSON.stringify({ pair: er.refs.pair }),
|
||||
});
|
||||
const answer = await response.json().catch(() => null);
|
||||
if (!current()) return;
|
||||
if (!response.ok) {
|
||||
// No words from the route: this ComfyUI started before the update.
|
||||
const missing = (response.status === 404 || response.status === 405) && !answer?.error;
|
||||
@@ -690,16 +684,15 @@ async function align(er) {
|
||||
}
|
||||
if (answer?.aligned && answer.b?.filename && typeof answer.pair === "string") {
|
||||
showToast({ severity: "success", summary: "Image Compare", detail: answer.message, life: 4000 });
|
||||
er.onAligned?.({ ...refs, b: answer.b, pair: answer.pair, aligned: true, original: refs });
|
||||
er.onAligned?.({ ...er.refs, b: answer.b, pair: answer.pair, aligned: true, original: er.refs });
|
||||
} else {
|
||||
showToast({ severity: "info", summary: "Image Compare", detail: answer?.message || "B was left as it is.", life: 6000 });
|
||||
}
|
||||
} catch (error) {
|
||||
if (!current()) return;
|
||||
showToast({ severity: "error", summary: "Image Compare", detail: String(error?.message ?? error), life: 8000 });
|
||||
} finally {
|
||||
er.aligning = false;
|
||||
if (!er.signal.aborted) syncTools(er);
|
||||
syncTools(er);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -771,7 +764,7 @@ function copy(er) {
|
||||
// pictures change.
|
||||
export function makeEraser({ node, root, stage, imageA, imageB, signal, onSaved, onAligned }) {
|
||||
const er = {
|
||||
node, root, stage, imageA, imageB, signal, onSaved, onAligned,
|
||||
node, root, stage, imageA, imageB, onSaved, onAligned,
|
||||
canvas: document.createElement("canvas"),
|
||||
mask: document.createElement("canvas"),
|
||||
live: document.createElement("canvas"),
|
||||
@@ -779,7 +772,7 @@ export function makeEraser({ node, root, stage, imageA, imageB, signal, onSaved,
|
||||
dab: document.createElement("canvas"),
|
||||
dabKey: "",
|
||||
maskScale: 1,
|
||||
refs: null, picturesVersion: 0, width: 0, height: 0, fit: null,
|
||||
refs: null, width: 0, height: 0, fit: null,
|
||||
strokes: [], history: [],
|
||||
active: false, stroke: null, adjust: null, pointer: null, back: false, flipKey: false,
|
||||
saving: false, copying: false, frame: 0, keys: null,
|
||||
@@ -992,7 +985,6 @@ export function makeEraser({ node, root, stage, imageA, imageB, signal, onSaved,
|
||||
// Both pictures are loaded (or, with null, on their way). The paint is
|
||||
// read from the node, and kept only while the picture keeps its size.
|
||||
setPictures(refs) {
|
||||
er.picturesVersion += 1;
|
||||
const ready = Boolean(refs && imageA.naturalWidth > 0 && imageB.naturalWidth > 0);
|
||||
er.refs = ready ? refs : null;
|
||||
finishStroke(er, null, true);
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
// A click on the dark area around a modal <dialog> closes it, the way people
|
||||
// expect any popup to work. The browser reports a click on a dialog's
|
||||
// backdrop as a click on the dialog element itself, so a click counts as
|
||||
// outside when it lands on the dialog element beyond its own box. Both the
|
||||
// press and the release must be outside: a text selection or a drag that
|
||||
// starts on the card and ends on the backdrop keeps the popup open.
|
||||
|
||||
export function pointOutside(rect, x, y) {
|
||||
return x < rect.left || x > rect.right || y < rect.top || y > rect.bottom;
|
||||
}
|
||||
|
||||
export function closeOnBackdropClick(dialog, close = () => dialog.close()) {
|
||||
const outside = (event) => event.target === dialog
|
||||
&& pointOutside(dialog.getBoundingClientRect(), event.clientX, event.clientY);
|
||||
let pressedOutside = false;
|
||||
dialog.addEventListener("pointerdown", (event) => {
|
||||
pressedOutside = outside(event);
|
||||
});
|
||||
dialog.addEventListener("click", (event) => {
|
||||
const started = pressedOutside;
|
||||
pressedOutside = false;
|
||||
if (started && outside(event)) close();
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
import { linkOrigin } from "./clip_rate.mjs";
|
||||
|
||||
// The same live-input rule used by the writer timeline: muted/bypassed
|
||||
// sources do not reach this node. This inspects the wire, never media bytes.
|
||||
export function linkSource(node, name) {
|
||||
@@ -11,43 +9,6 @@ export function linkSource(node, name) {
|
||||
return (source?.mode ?? 0) === 0 ? source ?? null : null;
|
||||
}
|
||||
|
||||
// Keep in step with Python video_frames (node_h3_prompt_writer.py): H3 makes
|
||||
// 5 frames plus steps of 17, at most 15 s at 24 fps, rounding a clip down.
|
||||
export const H3_FPS = 24;
|
||||
export function h3VideoFrames(frames) {
|
||||
const count = Math.trunc(Number(frames));
|
||||
if (!(count > 0)) return null;
|
||||
return Math.max(1, Math.floor((Math.min(count, 15 * H3_FPS) - 5) / 17)) * 17 + 5;
|
||||
}
|
||||
|
||||
// What the clip node's face last worked out for its run ({frames,
|
||||
// startSeconds, endSeconds}), or null when the clip is not that node or its
|
||||
// count is only known at run time.
|
||||
export function clipTimingFor(node) {
|
||||
// Through Reroutes and subgraphs, as every linked value is read.
|
||||
const timing = linkOrigin(node, "video")?.node?.__ausbossClipTiming;
|
||||
return timing && timing.frames > 0 ? timing : null;
|
||||
}
|
||||
|
||||
// The words under "From the clip": what H3 will make of the clip's frames.
|
||||
export function clipLengthWords(timing) {
|
||||
if (!timing) return null;
|
||||
const made = h3VideoFrames(timing.frames);
|
||||
const seconds = (frames) => String(Number((frames / H3_FPS).toFixed(2)));
|
||||
if (made < timing.frames) {
|
||||
const up = made + 17;
|
||||
const room = timing.roomFrames ?? Infinity;
|
||||
const stops = timing.startSeconds + made / H3_FPS;
|
||||
return {
|
||||
title: `H3 makes ${made} of the clip's ${timing.frames} frames · ${seconds(made)} s`,
|
||||
note: `Stops at ${String(Number(stops.toFixed(2)))} s in the video. To use all of it, set the clip's Duration to ${seconds(made)} s${up <= Math.min(room, 15 * H3_FPS) ? ` or ${seconds(up)} s` : ""}.`,
|
||||
warn: true,
|
||||
};
|
||||
}
|
||||
if (made === timing.frames) return { title: `H3 uses all ${made} frames · ${seconds(made)} s`, note: "The clip is already a length H3 makes.", warn: false };
|
||||
return { title: `H3 makes ${made} frames · ${seconds(made)} s`, note: `That is its shortest length; the clip has ${timing.frames} frames.`, warn: true };
|
||||
}
|
||||
|
||||
// Keep in step with Python KEEPS_ITS_LENGTH. Other jobs use seconds normally.
|
||||
export function clipSetsDuration(node, values) {
|
||||
return ["swap the person", "new voice", "change something"].includes(values.video_job)
|
||||
|
||||
@@ -93,10 +93,8 @@ export function nameAt(picked, names, position, atTheEnd) {
|
||||
// the first, so Picture always names a real picture. A Picture already past
|
||||
// the end (saved by an older version) steps on from the picture it loaded.
|
||||
// "random" jumps to any picked picture (`roll` is 0..1, for tests).
|
||||
// With an unknown count, "next" keeps advancing and the backend handles the end.
|
||||
export function nextPosition(position, count, afterRun, atTheEnd = "stop the run", roll = Math.random()) {
|
||||
const place = Math.max(1, Math.round(Number(position) || 1));
|
||||
if (count == null) return afterRun === "next" ? place + 1 : place;
|
||||
if (count < 1) return place;
|
||||
if (afterRun === "random") return Math.min(count, Math.floor(roll * count) + 1);
|
||||
if (afterRun !== "next") return place;
|
||||
@@ -126,12 +124,6 @@ export function childOf(folder, name) {
|
||||
return [...String(folder ?? "").split("/").filter(Boolean), name].join("/");
|
||||
}
|
||||
|
||||
// A relative name belongs to one folder, even when another has the same name.
|
||||
export function folderContext({ source, folder, subfolders }) {
|
||||
const relative = String(folder ?? "").trim().replaceAll("\\", "/").split("/").filter(part => part && part !== ".").join("/");
|
||||
return JSON.stringify([source, relative, Boolean(subfolders)]);
|
||||
}
|
||||
|
||||
// A query string. Every value is typed by a person or saved in a workflow.
|
||||
export function query(params) {
|
||||
return Object.entries(params)
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@ import { app } from "../../../scripts/app.js";
|
||||
// Must match `version` in pyproject.toml — scripts/release_preflight.py
|
||||
// enforces it. The backend serves its copy at /ausboss/pack_version; a
|
||||
// mismatch means the browser cached JavaScript from an older install.
|
||||
export const AUSBOSS_JS_VERSION = "2.26.2";
|
||||
export const AUSBOSS_JS_VERSION = "2.21.2";
|
||||
|
||||
export const BRAND = "#00b4aa"; // AusBoss teal — keep node accents consistent.
|
||||
export const BRAND_DARK = "#007f78";
|
||||
|
||||
@@ -107,59 +107,16 @@ export function outputRecordQuery(record, index = null) {
|
||||
}).toString();
|
||||
}
|
||||
|
||||
// The /view query of the small copy Save Image writes for its face
|
||||
// ({ ausboss_preview: ["ausboss_preview/<name>.webp"] }, one for each entry
|
||||
// of images, in the temp folder). Null when the record has none: an older
|
||||
// run, another node, or the preview switched off.
|
||||
export function lightPreviewQuery(record, index = null) {
|
||||
const places = record?.ausboss_preview;
|
||||
const count = outputRecordCount(record);
|
||||
if (!count || !Array.isArray(places) || places.length !== count) return null;
|
||||
const at = Number.isInteger(index) && index >= 0 && index < count ? index : count - 1;
|
||||
const place = places[at];
|
||||
if (typeof place !== "string" || !place) return null;
|
||||
const slash = place.lastIndexOf("/");
|
||||
return new URLSearchParams({
|
||||
filename: place.slice(slash + 1),
|
||||
subfolder: slash >= 0 ? place.slice(0, slash) : "",
|
||||
type: "temp",
|
||||
}).toString();
|
||||
}
|
||||
|
||||
// How many pictures the node's last run left in its output record.
|
||||
export function outputRecordCount(record) {
|
||||
return Array.isArray(record?.images) ? record.images.length : 0;
|
||||
}
|
||||
|
||||
// Is node.imgs the picture of this output record?
|
||||
//
|
||||
// The frontend loads a result into node.imgs with a time limit (two tries of
|
||||
// about 8 seconds). A picture that takes longer, a big one over a slow link,
|
||||
// is dropped without a word and node.imgs keeps the run before. `loadedFor`
|
||||
// is the record that was current when node.imgs was last set; the file name
|
||||
// is compared as well, for a newer run that arrived while a picture loaded.
|
||||
export function ownResultIsCurrent(node, record, loadedFor) {
|
||||
const images = node?.imgs;
|
||||
const src = Array.isArray(images) && images.length ? images[images.length - 1]?.src : null;
|
||||
if (typeof src !== "string" || !src) return false;
|
||||
const wanted = outputRecordQuery(record);
|
||||
// No stored picture to compare with, or a frame streamed during the run.
|
||||
if (!wanted || !/[?&]filename=/.test(src)) return true;
|
||||
if (loadedFor !== record) return false;
|
||||
const have = new URLSearchParams(src.slice(src.indexOf("?") + 1));
|
||||
const want = new URLSearchParams(wanted);
|
||||
return ["filename", "subfolder", "type"].every((key) => (have.get(key) ?? "") === (want.get(key) ?? ""));
|
||||
}
|
||||
|
||||
// What the panel shows, best first: this node's result (node.imgs, then the
|
||||
// URL of its stored output), then whatever feeds it, then nothing.
|
||||
// `ownIsCurrent` false: node.imgs is an older run's (ownResultIsCurrent), so
|
||||
// the stored output goes first.
|
||||
export function describeNodePreview(node, inputName, storedUrl = null, ownIsCurrent = true) {
|
||||
const stored = storedUrl ? { kind: "url", url: storedUrl } : null;
|
||||
return (ownIsCurrent ? null : stored)
|
||||
?? describeOwnResult(node)
|
||||
?? stored
|
||||
export function describeNodePreview(node, inputName, storedUrl = null) {
|
||||
return describeOwnResult(node)
|
||||
?? (storedUrl ? { kind: "url", url: storedUrl } : null)
|
||||
?? describeSourcePreview(upstreamNode(node, inputName));
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
// what it always was. The turn is made in canvas pixels, so a turned box is a
|
||||
// true rectangle on a canvas of any shape (nodes/_layout_boxes_helpers.py
|
||||
// turns it the same way).
|
||||
import { linkOrigin } from "./clip_rate.mjs";
|
||||
|
||||
export const DIM_MIN = 64;
|
||||
export const DIM_MAX = 16384;
|
||||
@@ -684,10 +683,8 @@ const isNumber = (value) => typeof value === "number" && Number.isFinite(value);
|
||||
// (Integer, Primitive). Reroutes are followed. Null when the input is not
|
||||
// wired or the value is only known once the workflow runs.
|
||||
export function wiredNumber(node, inputName) {
|
||||
// Through Reroutes and into subgraphs (js/shared/clip_rate.mjs), then
|
||||
// this node's own rule for which numbers count.
|
||||
const origin = linkOrigin(node, inputName);
|
||||
return origin ? wiredFrom(origin.node, origin.slot) : null;
|
||||
const source = wiredSource(node, inputName);
|
||||
return source ? wiredFrom(source.node, source.slot) : null;
|
||||
}
|
||||
|
||||
// The node (and its output slot) an input is wired to, through Reroutes.
|
||||
|
||||
@@ -1,211 +0,0 @@
|
||||
// The row under the file picker on Load Image: arrows that step through the
|
||||
// input folder, where the file is in the list ("14 / 212"), and the size the
|
||||
// picture goes in at and comes out at ("912 × 1632 → 1144 × 2048"). The
|
||||
// widgets underneath stay the source of truth: an arrow only changes the
|
||||
// image widget's value, the way picking from the list does.
|
||||
//
|
||||
// Under it, the preview: the picture as it goes in with the part that is
|
||||
// kept lit, and the picture as it comes out, both on one scale, with what
|
||||
// the size choice does in words. While the choice cuts something, a click
|
||||
// on the first picture picks the part to keep.
|
||||
import { api } from "../../../scripts/api.js";
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { CROP_MODES, changeText, cropSideAt, keptPart, placeText, planLoadSize, shapeText, sizeText, stepFile, thumbSizes } from "./load_size.mjs";
|
||||
import { mediaViewQuery } from "./media_list.mjs";
|
||||
import { FONT_UI, RADIUS_CONTROL, THEME as T } from "./theme.mjs";
|
||||
import { commitWidgetValue, comboValues } from "./widget_card_math.mjs";
|
||||
|
||||
const CSS_ID = "ausboss-load-strip-css";
|
||||
// Sizes already read, by file: stepping back to a picture shows its size at once.
|
||||
const SIZES_KEPT = 200;
|
||||
const sizes = new Map();
|
||||
|
||||
function ensureCss() {
|
||||
if (document.getElementById(CSS_ID)) return;
|
||||
const style = document.createElement("style");
|
||||
style.id = CSS_ID;
|
||||
style.textContent = `
|
||||
.ausboss-load-strip{display:flex;align-items:center;gap:6px;height:100%;min-width:0;font:500 11px/1 ${FONT_UI};color:${T.label}}
|
||||
.ausboss-load-step{flex:none;width:26px;height:100%;padding:0;border:1px solid transparent;border-radius:${RADIUS_CONTROL}px;background:${T.fill};color:${T.inkSoft};font:600 11px/1 ${FONT_UI};cursor:pointer}
|
||||
.ausboss-load-step:hover{background:${T.fillHover};color:${T.inkHover}}
|
||||
.ausboss-load-step:focus-visible{outline:2px solid ${T.brand};outline-offset:1px}
|
||||
.ausboss-load-step:disabled{opacity:.4;cursor:default}
|
||||
.ausboss-load-place{flex:none;color:${T.faint};font-variant-numeric:tabular-nums;white-space:nowrap;user-select:none}
|
||||
.ausboss-load-size{flex:1 1 0;min-width:0;overflow:hidden;text-align:right;white-space:nowrap;text-overflow:ellipsis;color:${T.inkSoft};font-weight:600;font-variant-numeric:tabular-nums}
|
||||
.ausboss-load-size b{color:${T.brandInk};font-weight:700}
|
||||
.ausboss-load-size i{color:${T.faint};font-style:normal;margin:0 5px}
|
||||
.ausboss-load-view{display:flex;align-items:center;justify-content:center;gap:10px;height:100%;min-width:0;font:500 10px/1.25 ${FONT_UI};color:${T.faint}}
|
||||
.ausboss-load-thumb{position:relative;flex:none;overflow:hidden;border-radius:2px;background-color:${T.fill};background-repeat:no-repeat}
|
||||
.ausboss-load-thumb.in{background-size:100% 100%}
|
||||
.ausboss-load-thumb.in.pick{cursor:pointer}
|
||||
.ausboss-load-thumb.out{outline:1px solid ${T.brand};outline-offset:0}
|
||||
.ausboss-load-kept{position:absolute;box-sizing:border-box;border:1px solid ${T.brand};box-shadow:0 0 0 400px rgba(8,10,11,.68);pointer-events:none}
|
||||
.ausboss-load-note{flex:0 1 auto;min-width:0;display:flex;flex-direction:column;align-items:center;gap:2px;text-align:center;user-select:none}
|
||||
.ausboss-load-note b{color:${T.inkSoft};font-weight:600;font-variant-numeric:tabular-nums;white-space:nowrap}
|
||||
.ausboss-load-note span{white-space:nowrap}
|
||||
`;
|
||||
document.head.append(style);
|
||||
}
|
||||
|
||||
const viewUrl = (value) => api.apiURL(`/view?${mediaViewQuery(value)}`);
|
||||
|
||||
// The picture's own size, read from the file the way the browser shows it.
|
||||
function readSize(file, done) {
|
||||
const known = sizes.get(file);
|
||||
if (known) return known;
|
||||
const picture = new Image();
|
||||
picture.onload = () => {
|
||||
if (sizes.size >= SIZES_KEPT) sizes.delete(sizes.keys().next().value);
|
||||
sizes.set(file, { width: picture.naturalWidth, height: picture.naturalHeight });
|
||||
done();
|
||||
};
|
||||
picture.src = viewUrl(file);
|
||||
return null;
|
||||
}
|
||||
|
||||
// The widest and tallest a preview picture is drawn.
|
||||
const THUMB_WIDTH = 76;
|
||||
const THUMB_HEIGHT = 68;
|
||||
|
||||
export function loadImagePreview(node) {
|
||||
ensureCss();
|
||||
const root = document.createElement("div");
|
||||
root.className = "ausboss-load-view";
|
||||
const input = document.createElement("div");
|
||||
input.className = "ausboss-load-thumb in";
|
||||
const kept = document.createElement("div");
|
||||
kept.className = "ausboss-load-kept";
|
||||
input.append(kept);
|
||||
const note = document.createElement("div");
|
||||
note.className = "ausboss-load-note";
|
||||
const output = document.createElement("div");
|
||||
output.className = "ausboss-load-thumb out";
|
||||
root.append(input, note, output);
|
||||
let last = {};
|
||||
|
||||
const side = () => node.widgets?.find((item) => item.name === "crop_from") ?? null;
|
||||
const sideLinked = () => node.inputs?.find((slot) => slot?.widget?.name === "crop_from")?.link != null;
|
||||
input.addEventListener("click", (event) => {
|
||||
const widget = side();
|
||||
if (!widget || !input.classList.contains("pick")) return;
|
||||
const box = input.getBoundingClientRect();
|
||||
if (!(box.width > 0 && box.height > 0)) return;
|
||||
const next = cropSideAt((event.clientX - box.left) / box.width, (event.clientY - box.top) / box.height);
|
||||
if (next === widget.value) return;
|
||||
commitWidgetValue(node, widget, next, app.canvas);
|
||||
node.setDirtyCanvas?.(true, true);
|
||||
});
|
||||
|
||||
const line = (tag, text) => {
|
||||
const item = document.createElement(tag);
|
||||
item.textContent = text;
|
||||
return item;
|
||||
};
|
||||
const sync = (values = last) => {
|
||||
last = values;
|
||||
const file = String(values.image ?? "");
|
||||
const source = file ? readSize(file, () => { if (String(last.image ?? "") === file) sync(); }) : null;
|
||||
const plan = source ? planLoadSize(source.width, source.height, values) : null;
|
||||
root.style.visibility = plan ? "" : "hidden";
|
||||
if (!plan) return;
|
||||
const picture = `url(${JSON.stringify(viewUrl(file))})`;
|
||||
const sizes = thumbSizes(source.width, source.height, plan, THUMB_WIDTH, THUMB_HEIGHT);
|
||||
const part = keptPart(plan);
|
||||
Object.assign(input.style, { width: `${sizes.input[0]}px`, height: `${sizes.input[1]}px`, backgroundImage: picture });
|
||||
Object.assign(kept.style, {
|
||||
left: `${part.x * 100}%`, top: `${part.y * 100}%`,
|
||||
width: `${part.width * 100}%`, height: `${part.height * 100}%`,
|
||||
});
|
||||
const spareWide = plan.resizeWidth - plan.width;
|
||||
const spareHigh = plan.resizeHeight - plan.height;
|
||||
Object.assign(output.style, {
|
||||
width: `${sizes.output[0]}px`, height: `${sizes.output[1]}px`, backgroundImage: picture,
|
||||
backgroundSize: `${(plan.resizeWidth / plan.width) * 100}% ${(plan.resizeHeight / plan.height) * 100}%`,
|
||||
backgroundPosition: `${spareWide > 0 ? (plan.cropX / spareWide) * 100 : 0}% ${spareHigh > 0 ? (plan.cropY / spareHigh) * 100 : 0}%`,
|
||||
});
|
||||
const picks = CROP_MODES.includes(values.size) && !sideLinked();
|
||||
input.classList.toggle("pick", picks);
|
||||
input.title = picks
|
||||
? "The picture going in. The lit part is kept. Click the part you want to keep."
|
||||
: "The picture going in. The lit part is kept.";
|
||||
output.title = "The picture coming out.";
|
||||
const from = shapeText(source.width, source.height);
|
||||
const to = shapeText(plan.width, plan.height);
|
||||
const change = changeText(source.width, source.height, plan);
|
||||
note.replaceChildren(
|
||||
line("b", from === to ? from : `${from} → ${to}`),
|
||||
...(change ? change.split(" · ").map((text) => line("span", text)) : [line("span", "no change")]),
|
||||
);
|
||||
};
|
||||
return { element: root, sync };
|
||||
}
|
||||
|
||||
export function loadImageStrip(node) {
|
||||
ensureCss();
|
||||
const root = document.createElement("div");
|
||||
root.className = "ausboss-load-strip";
|
||||
const widget = () => node.widgets?.find((item) => item.name === "image") ?? null;
|
||||
const linked = () => {
|
||||
const slot = node.inputs?.find((input) => input?.widget?.name === "image" || input?.name === "image");
|
||||
return slot?.link != null;
|
||||
};
|
||||
let last = {};
|
||||
|
||||
const step = (delta, label, title) => {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "ausboss-load-step";
|
||||
button.textContent = label;
|
||||
button.title = title;
|
||||
button.addEventListener("click", () => {
|
||||
const image = widget();
|
||||
if (!image) return;
|
||||
const next = stepFile(comboValues(image), image.value, delta);
|
||||
if (next === null || next === image.value) return;
|
||||
commitWidgetValue(node, image, next, app.canvas);
|
||||
node.setDirtyCanvas?.(true, true);
|
||||
});
|
||||
root.append(button);
|
||||
return button;
|
||||
};
|
||||
const back = step(-1, "◀", "The picture before this one in the input folder");
|
||||
const on = step(1, "▶", "The next picture in the input folder");
|
||||
const place = document.createElement("span");
|
||||
place.className = "ausboss-load-place";
|
||||
place.title = "Where this picture is in the input folder's list";
|
||||
const size = document.createElement("span");
|
||||
size.className = "ausboss-load-size";
|
||||
root.append(place, size);
|
||||
|
||||
const sync = (values = last) => {
|
||||
last = values;
|
||||
const image = widget();
|
||||
const files = comboValues(image);
|
||||
const file = String(values.image ?? "");
|
||||
place.textContent = placeText(files, file);
|
||||
const stuck = linked() || stepFile(files, file, 1) === null;
|
||||
back.disabled = stuck;
|
||||
on.disabled = stuck;
|
||||
const source = file ? readSize(file, () => { if (String(last.image ?? "") === file) sync(); }) : null;
|
||||
size.replaceChildren();
|
||||
if (!source) {
|
||||
size.title = "";
|
||||
return;
|
||||
}
|
||||
const plan = planLoadSize(source.width, source.height, values);
|
||||
const text = sizeText(source.width, source.height, plan);
|
||||
const [from, to] = text.split(" → ");
|
||||
size.append(from);
|
||||
if (to) {
|
||||
const arrow = document.createElement("i");
|
||||
arrow.textContent = "→";
|
||||
const out = document.createElement("b");
|
||||
out.textContent = to;
|
||||
size.append(arrow, out);
|
||||
}
|
||||
size.title = to
|
||||
? `The file is ${from}. The picture comes out at ${to}.`
|
||||
: `The picture comes out at its own size, ${from}.`;
|
||||
};
|
||||
return { element: root, sync };
|
||||
}
|
||||
@@ -1,206 +0,0 @@
|
||||
// Load Image: the size a picture comes out at, worked out in the browser so
|
||||
// the node can show it before a run. This repeats plan_load_size in
|
||||
// nodes/_load_image_helpers.py; tests/fixtures/load_size_cases.json holds
|
||||
// both to the same answers. No DOM in here.
|
||||
|
||||
export const SIZE_MODES = Object.freeze(["off", "megapixels", "longest side", "scale", "fit inside", "crop to fill", "crop", "crop to ratio"]);
|
||||
// Which part of the picture a crop keeps, as a 3 x 3 grid read row by row.
|
||||
export const CROP_GRID = Object.freeze(["top left", "top", "top right", "left", "center", "right", "bottom left", "bottom", "bottom right"]);
|
||||
// The choices that cut something off, so the kept part matters.
|
||||
export const CROP_MODES = Object.freeze(["crop to fill", "crop", "crop to ratio"]);
|
||||
|
||||
const roundHalfUp = (value) => Math.floor(value + 0.5);
|
||||
const whole = (value, fallback) => (Number.isFinite(Number(value)) ? Math.trunc(Number(value)) : fallback);
|
||||
// Nearest multiple, never below one step.
|
||||
const nearest = (value, step) => Math.max(step, roundHalfUp(value / step) * step);
|
||||
// The largest multiple that is not above the value, never below one step.
|
||||
const below = (value, step) => Math.max(step, Math.floor(value / step) * step);
|
||||
// Rounded down to a multiple, or left alone when smaller than one step.
|
||||
const inside = (value, step) => (value >= step ? Math.floor(value / step) * step : value);
|
||||
// Where a cut starts along one edge with `spare` pixels to lose.
|
||||
const cropStart = (spare, side, low, high) => (side.includes(low) ? 0 : side.includes(high) ? spare : Math.floor(spare / 2));
|
||||
|
||||
function ratioTerms(ratio, width, height) {
|
||||
if (ratio === "width : height") return [Math.max(1, width), Math.max(1, height)];
|
||||
const [across, down] = String(ratio ?? "1:1").split(":").map((term) => Math.trunc(Number(term)));
|
||||
return [Math.max(1, across || 1), Math.max(1, down || 1)];
|
||||
}
|
||||
|
||||
function target(sourceW, sourceH, size, { megapixels, longest_side: longestSide, scale, width, height }) {
|
||||
const scaled = (factor) => [Math.max(1, roundHalfUp(sourceW * factor)), Math.max(1, roundHalfUp(sourceH * factor))];
|
||||
if (size === "megapixels") {
|
||||
const amount = Number(megapixels);
|
||||
return amount > 0 ? scaled(Math.sqrt((amount * 1e6) / (sourceW * sourceH))) : [sourceW, sourceH];
|
||||
}
|
||||
if (size === "longest side") {
|
||||
const edge = whole(longestSide, 0);
|
||||
if (edge <= 0) return [sourceW, sourceH];
|
||||
const [w, h] = scaled(edge / Math.max(sourceW, sourceH));
|
||||
return sourceW >= sourceH ? [edge, h] : [w, edge];
|
||||
}
|
||||
if (size === "scale") {
|
||||
const factor = Number(scale);
|
||||
return factor > 0 ? scaled(factor) : [sourceW, sourceH];
|
||||
}
|
||||
const fit = Math.min(Math.max(1, whole(width, 1)) / sourceW, Math.max(1, whole(height, 1)) / sourceH);
|
||||
return scaled(fit);
|
||||
}
|
||||
|
||||
// { resizeWidth, resizeHeight, cropX, cropY, width, height } for a picture of
|
||||
// sourceWidth x sourceHeight and the node's values, or null when the picture
|
||||
// has no size yet or the choice is not one the node knows.
|
||||
export function planLoadSize(sourceWidth, sourceHeight, values = {}) {
|
||||
const sourceW = whole(sourceWidth, 0);
|
||||
const sourceH = whole(sourceHeight, 0);
|
||||
const size = values.size ?? "off";
|
||||
if (sourceW <= 0 || sourceH <= 0 || !SIZE_MODES.includes(size)) return null;
|
||||
const same = { resizeWidth: sourceW, resizeHeight: sourceH, cropX: 0, cropY: 0, width: sourceW, height: sourceH };
|
||||
if (size === "off") return same;
|
||||
const step = Math.max(1, whole(values.multiple, 1));
|
||||
const enlarge = values.enlarge !== false;
|
||||
const boxW = Math.max(1, whole(values.width, 1024));
|
||||
const boxH = Math.max(1, whole(values.height, 1024));
|
||||
const side = CROP_GRID.includes(values.crop_from) ? values.crop_from : "center";
|
||||
const cut = (resizeWidth, resizeHeight, width, height) => ({
|
||||
resizeWidth, resizeHeight,
|
||||
cropX: cropStart(resizeWidth - width, side, "left", "right"),
|
||||
cropY: cropStart(resizeHeight - height, side, "top", "bottom"),
|
||||
width, height,
|
||||
});
|
||||
|
||||
if (size === "crop") {
|
||||
return cut(sourceW, sourceH, inside(Math.min(boxW, sourceW), step), inside(Math.min(boxH, sourceH), step));
|
||||
}
|
||||
|
||||
if (size === "crop to ratio") {
|
||||
const [across, down] = ratioTerms(values.ratio, boxW, boxH);
|
||||
let width = sourceW;
|
||||
let height = sourceH;
|
||||
if (sourceW * down >= sourceH * across) width = Math.min(sourceW, Math.max(1, roundHalfUp((sourceH * across) / down)));
|
||||
else height = Math.min(sourceH, Math.max(1, roundHalfUp((sourceW * down) / across)));
|
||||
return cut(sourceW, sourceH, inside(width, step), inside(height, step));
|
||||
}
|
||||
|
||||
if (size === "crop to fill") {
|
||||
let width = boxW;
|
||||
let height = boxH;
|
||||
if (enlarge) {
|
||||
width = nearest(width, step);
|
||||
height = nearest(height, step);
|
||||
} else {
|
||||
const grow = Math.max(width / sourceW, height / sourceH);
|
||||
if (grow > 1) {
|
||||
width = Math.max(1, Math.floor(width / grow + 1e-6));
|
||||
height = Math.max(1, Math.floor(height / grow + 1e-6));
|
||||
}
|
||||
width = Math.min(below(width, step), Math.max(step, sourceW));
|
||||
height = Math.min(below(height, step), Math.max(step, sourceH));
|
||||
}
|
||||
const cover = Math.max(width / sourceW, height / sourceH);
|
||||
const resizeWidth = Math.max(width, Math.ceil(sourceW * cover - 1e-6));
|
||||
const resizeHeight = Math.max(height, Math.ceil(sourceH * cover - 1e-6));
|
||||
return cut(resizeWidth, resizeHeight, width, height);
|
||||
}
|
||||
|
||||
let [targetW, targetH] = target(sourceW, sourceH, size, { ...values, width: boxW, height: boxH });
|
||||
if (!enlarge && (targetW > sourceW || targetH > sourceH)) [targetW, targetH] = [sourceW, sourceH];
|
||||
const rounded = (wanted, source, box) => {
|
||||
let value = nearest(wanted, step);
|
||||
if (size === "fit inside" && value > box) value = below(box, step);
|
||||
if (!enlarge && value > source) value = below(source, step);
|
||||
return value;
|
||||
};
|
||||
const width = rounded(targetW, sourceW, boxW);
|
||||
const height = rounded(targetH, sourceH, boxH);
|
||||
return { resizeWidth: width, resizeHeight: height, cropX: 0, cropY: 0, width, height };
|
||||
}
|
||||
|
||||
// "912 × 1632" for a picture that comes out as it went in, "912 × 1632 →
|
||||
// 1144 × 2048" when its size changes, "" while the picture's size is unknown.
|
||||
export function sizeText(sourceWidth, sourceHeight, plan) {
|
||||
if (!(sourceWidth > 0 && sourceHeight > 0)) return "";
|
||||
const from = `${sourceWidth} × ${sourceHeight}`;
|
||||
if (!plan || (plan.width === sourceWidth && plan.height === sourceHeight)) return from;
|
||||
return `${from} → ${plan.width} × ${plan.height}`;
|
||||
}
|
||||
|
||||
// What a plan does to the picture, in a few words for the node: how much it
|
||||
// is resized and how much is cut off, in the file's own pixels. "" when the
|
||||
// picture comes out as it went in.
|
||||
export function changeText(sourceWidth, sourceHeight, plan) {
|
||||
if (!plan || !(sourceWidth > 0 && sourceHeight > 0)) return "";
|
||||
const parts = [];
|
||||
const percent = Math.round((plan.resizeWidth / sourceWidth) * 100);
|
||||
if (plan.resizeWidth !== sourceWidth || plan.resizeHeight !== sourceHeight) parts.push(`${percent}% size`);
|
||||
const cutWide = Math.round(((plan.resizeWidth - plan.width) * sourceWidth) / plan.resizeWidth);
|
||||
const cutHigh = Math.round(((plan.resizeHeight - plan.height) * sourceHeight) / plan.resizeHeight);
|
||||
if (cutWide > 0 && cutHigh > 0) parts.push(`cuts ${cutWide} × ${cutHigh} px`);
|
||||
else if (cutWide > 0) parts.push(`cuts ${cutWide} px of width`);
|
||||
else if (cutHigh > 0) parts.push(`cuts ${cutHigh} px of height`);
|
||||
return parts.join(" · ");
|
||||
}
|
||||
|
||||
const SHAPES = [[1, 1], [5, 4], [4, 3], [3, 2], [16, 10], [16, 9], [2, 1], [21, 9]];
|
||||
|
||||
// A picture's shape in words people use: "3:4", "16:9". A size within one
|
||||
// percent of a common shape gets that name (rounding to a multiple moves a
|
||||
// 16:9 picture a few pixels off it); any other gets "~1.34:1" or "~1:1.34".
|
||||
export function shapeText(width, height) {
|
||||
if (!(width > 0 && height > 0)) return "";
|
||||
const wide = width >= height;
|
||||
const value = wide ? width / height : height / width;
|
||||
const near = SHAPES.find(([across, down]) => Math.abs(value - across / down) <= (across / down) * 0.01);
|
||||
if (near) return wide ? `${near[0]}:${near[1]}` : `${near[1]}:${near[0]}`;
|
||||
const rounded = Math.round(value * 100) / 100;
|
||||
return wide ? `~${rounded}:1` : `~1:${rounded}`;
|
||||
}
|
||||
|
||||
// The part of the file a plan keeps, as fractions of the file's width and
|
||||
// height: { x, y, width, height }, all 0 to 1.
|
||||
export function keptPart(plan) {
|
||||
if (!plan) return { x: 0, y: 0, width: 1, height: 1 };
|
||||
return {
|
||||
x: plan.cropX / plan.resizeWidth,
|
||||
y: plan.cropY / plan.resizeHeight,
|
||||
width: Math.min(1, plan.width / plan.resizeWidth),
|
||||
height: Math.min(1, plan.height / plan.resizeHeight),
|
||||
};
|
||||
}
|
||||
|
||||
// The sizes two small pictures are drawn at so their difference shows: both
|
||||
// on one scale, the larger filling a box of maxWidth x maxHeight, and neither
|
||||
// edge under `least` pixels.
|
||||
export function thumbSizes(sourceWidth, sourceHeight, plan, maxWidth, maxHeight, least = 10) {
|
||||
const outW = plan?.width ?? sourceWidth;
|
||||
const outH = plan?.height ?? sourceHeight;
|
||||
const scale = Math.min(maxWidth / Math.max(sourceWidth, outW), maxHeight / Math.max(sourceHeight, outH));
|
||||
const at = (value) => Math.max(least, Math.round(value * scale));
|
||||
return { input: [at(sourceWidth), at(sourceHeight)], output: [at(outW), at(outH)] };
|
||||
}
|
||||
|
||||
// The crop side under a click at (x, y), each 0 to 1 across the picture.
|
||||
export function cropSideAt(x, y) {
|
||||
const third = (value) => (value < 1 / 3 ? 0 : value < 2 / 3 ? 1 : 2);
|
||||
return CROP_GRID[third(y) * 3 + third(x)];
|
||||
}
|
||||
|
||||
// The file one step before or after the current one in the list, going
|
||||
// round at the ends. A file that is not in the list steps to the first or
|
||||
// the last. null when the list has nothing to step to.
|
||||
export function stepFile(files, current, delta) {
|
||||
const list = (Array.isArray(files) ? files : []).filter((name) => name !== "" && name != null);
|
||||
if (!list.length) return null;
|
||||
const at = list.indexOf(current);
|
||||
if (at < 0) return delta < 0 ? list[list.length - 1] : list[0];
|
||||
if (list.length === 1) return null;
|
||||
return list[(at + (delta < 0 ? -1 : 1) + list.length) % list.length];
|
||||
}
|
||||
|
||||
// "14 / 212": where the current file is in the list. "" for an empty list,
|
||||
// "– / 212" for a file that is not in it.
|
||||
export function placeText(files, current) {
|
||||
const list = (Array.isArray(files) ? files : []).filter((name) => name !== "" && name != null);
|
||||
if (!list.length) return "";
|
||||
const at = list.indexOf(current);
|
||||
return `${at < 0 ? "–" : at + 1} / ${list.length}`;
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
// ComfyUI's missing-models list (the Issues panel, "Download all") only
|
||||
// looks at list widgets: a model is listed when a list on some node holds a
|
||||
// file name that is not one of its choices. LoRA Loader keeps its files in
|
||||
// the rows' text, so a LoRA a workflow needs never made that list, and
|
||||
// "Download all" then Run stopped on "missing LoRA file".
|
||||
//
|
||||
// The loader therefore carries one hidden list widget per row that needs a
|
||||
// file. Nothing else reads them: they are kept out of the saved workflow and
|
||||
// the prompt, have no socket, and are made again from the rows every time.
|
||||
// The rows stay the one source of truth.
|
||||
|
||||
import { resolveLoraName } from "./lora_stack.mjs";
|
||||
|
||||
export const FILE_WIDGET_PREFIX = "ausboss_lora_file_";
|
||||
export const FILE_WIDGET_FLAG = "ausbossLoraFile";
|
||||
|
||||
// Rows the server needs a file for when it runs: named, on, in a group that
|
||||
// is on, and not at zero strength (nodes/_lora_helpers.py, missing_lora_rows).
|
||||
export function rowsNeedingFiles(rows) {
|
||||
return (Array.isArray(rows) ? rows : []).filter((row) => {
|
||||
const name = typeof row?.name === "string" ? row.name.trim() : "";
|
||||
if (!name || row.enabled === false || row.group_off === true) return false;
|
||||
const strength = Number(row.strength ?? 1);
|
||||
const clip = Number(row.strength_clip ?? strength);
|
||||
return !(strength === 0 && clip === 0);
|
||||
});
|
||||
}
|
||||
|
||||
// The list ComfyUI checks a row's file against. A file the loader would
|
||||
// find anyway (saved in another folder, or with other capitals) counts as
|
||||
// installed; so does every file while the install's list is unknown, so a
|
||||
// slow list never shows a false alarm.
|
||||
export function fileChoices(name, installed) {
|
||||
if (!Array.isArray(installed)) return [name];
|
||||
return resolveLoraName(name, installed).status === "missing" ? installed : [...installed, name];
|
||||
}
|
||||
|
||||
// The install's LoRA files as ComfyUI's own LoRA loader lists them. The node
|
||||
// list arrives before any workflow opens, so this answers at once; null when
|
||||
// there is no such node to ask.
|
||||
export function coreLoraList(definition) {
|
||||
const spec = definition?.input?.required?.lora_name;
|
||||
if (!Array.isArray(spec)) return null;
|
||||
if (Array.isArray(spec[0])) return spec[0];
|
||||
if (spec[0] === "COMBO" && Array.isArray(spec[1]?.options)) return spec[1].options;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function isFileWidget(widget) {
|
||||
return Boolean(widget?.[FILE_WIDGET_FLAG]);
|
||||
}
|
||||
|
||||
// Bring the node's file widgets in line with its rows. `installed()` returns
|
||||
// the install's files (or null), `hide(widget)` folds a widget away, and
|
||||
// `onPick(rowId, name)` runs when ComfyUI puts another file in a widget
|
||||
// (choosing a replacement in the Issues panel). Returns true when a widget
|
||||
// was added or removed.
|
||||
export function syncFileWidgets(node, rows, { installed, hide, onPick }) {
|
||||
if (!node || !Array.isArray(node.widgets)) return false;
|
||||
const needed = rowsNeedingFiles(rows);
|
||||
const current = node.widgets.filter(isFileWidget);
|
||||
let changed = false;
|
||||
needed.forEach((row, index) => {
|
||||
let widget = current[index];
|
||||
if (!widget) {
|
||||
widget = node.addWidget("combo", `${FILE_WIDGET_PREFIX}${index + 1}`, row.name, (value) => {
|
||||
if (typeof value === "string" && value !== widget.ausbossRowName) onPick?.(widget.ausbossRowId, value);
|
||||
}, { values: () => fileChoices(widget.value, installed?.()), serialize: false });
|
||||
widget[FILE_WIDGET_FLAG] = true;
|
||||
widget.serialize = false;
|
||||
hide?.(widget);
|
||||
changed = true;
|
||||
}
|
||||
widget.value = row.name;
|
||||
widget.ausbossRowName = row.name;
|
||||
widget.ausbossRowId = row.id;
|
||||
});
|
||||
for (const widget of current.slice(needed.length)) {
|
||||
if (typeof node.removeWidget === "function") node.removeWidget(widget);
|
||||
else {
|
||||
const at = node.widgets.indexOf(widget);
|
||||
if (at >= 0) node.widgets.splice(at, 1);
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
// bar as long as the clip, with the cuts as marks. The server reads the script with the same code a run uses,
|
||||
// so the bar shows what will happen. It also colours the script box, so the
|
||||
// words the node reads as instructions (@1, 3s:, a cut) stand out.
|
||||
import { clipLengthWords, clipSetsDuration, clipTimingFor, linkSource } from "./h3_duration.mjs";
|
||||
import { clipSetsDuration, linkSource } from "./h3_duration.mjs";
|
||||
import { api } from "../../../scripts/api.js";
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { BRAND, chainCallback } from "./index.mjs";
|
||||
@@ -290,15 +290,12 @@ export function momentStrip(node) {
|
||||
asked += 1;
|
||||
ruler.textContent = "";
|
||||
track.textContent = "";
|
||||
// Say what H3 will make of the clip's frames, when the clip node knows
|
||||
// its count; it rounds down to 5 + 17n, so a 48-frame clip gives 39.
|
||||
const words = clipLengthWords(clipTimingFor(node));
|
||||
const message = el("ausboss-strip-words", words?.title ?? "Length comes from the clip");
|
||||
const message = el("ausboss-strip-words", "Length comes from the clip");
|
||||
message.style.cssText = "display:flex;align-items:center;height:100%";
|
||||
track.append(message);
|
||||
note.textContent = words?.note ?? "Set the clip's length on the clip node. H3 makes 5 + 17n frames (22, 39, 56 ...), rounding the clip down.";
|
||||
note.textContent = "Set the clip's length upstream. Timing controls are unavailable here.";
|
||||
note.title = note.textContent;
|
||||
note.classList.toggle("warn", Boolean(words?.warn));
|
||||
note.classList.remove("warn");
|
||||
return;
|
||||
}
|
||||
if (wired(node, "script")) {
|
||||
|
||||
@@ -5,11 +5,6 @@
|
||||
// 2.0 draws each node as an element on the page, which can run past those
|
||||
// bounds (its frame, a footer), so there the element itself is measured.
|
||||
// Groups are drawn on the canvas in both looks.
|
||||
//
|
||||
// A frameless tile (a link tile, a title, a note tile) draws only a card
|
||||
// inside a transparent node, so what people see is the card, not the node's
|
||||
// bounds. Such a node names that card as `ausbossOutlineElement`, and its
|
||||
// outline is the card's, in both looks.
|
||||
|
||||
function graphRectOf(element, canvas) {
|
||||
const box = element.getBoundingClientRect();
|
||||
@@ -39,11 +34,6 @@ export function nodeElements() {
|
||||
}
|
||||
|
||||
export function outlineOf(item, canvas, { node = true, elements = null } = {}) {
|
||||
const face = node && !item?.flags?.collapsed ? item?.ausbossOutlineElement : null;
|
||||
if (face?.isConnected && canvas?.canvas && canvas.ds) {
|
||||
const rect = graphRectOf(face, canvas);
|
||||
if (rect) return rect;
|
||||
}
|
||||
if (node && globalThis.LiteGraph?.vueNodesMode === true && item?.id != null && canvas?.canvas && canvas.ds) {
|
||||
const element = elements
|
||||
? elements.get(String(item.id))
|
||||
|
||||
@@ -1,35 +1,30 @@
|
||||
// Shared controls for compact node panels. Only elements explicitly given one
|
||||
// of these classes are styled; the owning panel decides where they sit.
|
||||
import { FONT_UI, RADIUS_XS, THEME as T } from "./theme.mjs";
|
||||
import { BRAND } from "./index.mjs";
|
||||
|
||||
export const PANEL_LABELS = Object.freeze({
|
||||
load: "Load", sources: { input: "Inputs", output: "Outputs" },
|
||||
embed: "Embed workflow", off: "Off", on: "On",
|
||||
});
|
||||
|
||||
const controlFont = FONT_UI;
|
||||
export const CAPTION_TYPE = `font:600 11px/1.25 ${controlFont};color:${T.label};`;
|
||||
export const HINT_TYPE = `font:400 10px/1.25 ${controlFont};color:${T.faint};`;
|
||||
const controlFont = 'system-ui, sans-serif';
|
||||
export const CAPTION_TYPE = `font:600 11px/1.25 ${controlFont};color:#b2c6c3;`;
|
||||
export const HINT_TYPE = `font:400 10px/1.25 ${controlFont};color:#95aba8;`;
|
||||
|
||||
export function ensurePanelControls() {
|
||||
if (document.getElementById("ausboss-panel-controls")) return;
|
||||
const style = document.createElement("style");
|
||||
style.id = "ausboss-panel-controls";
|
||||
style.textContent = `
|
||||
.ausboss-compact-action{box-sizing:border-box;flex:none;height:22px;min-width:24px;padding:0 7px;border:1px solid transparent;border-radius:${RADIUS_XS}px;background:${T.fill};color:${T.inkSoft};font:600 11px/1 ${controlFont};white-space:nowrap;cursor:pointer;pointer-events:auto}
|
||||
.ausboss-compact-action:hover:enabled{color:${T.ink};background:${T.fillHover}}
|
||||
.ausboss-compact-action.active{color:${T.brandInk};background:${T.brandSoft}}
|
||||
.ausboss-compact-action{box-sizing:border-box;flex:none;height:22px;min-width:24px;padding:0 7px;border:1px solid #365957;border-radius:4px;background:#111b1c;color:#bdd8d5;font:600 11px/1 ${controlFont};white-space:nowrap;cursor:pointer;pointer-events:auto}
|
||||
.ausboss-compact-action:hover:enabled,.ausboss-compact-action.active{color:#dbfffb;border-color:${BRAND};background:#173332}
|
||||
.ausboss-compact-action:disabled{opacity:.5;cursor:default}
|
||||
.ausboss-panel-switch{display:inline-flex;align-items:center;gap:6px;align-self:flex-end;flex:none;box-sizing:border-box;min-height:20px;margin-left:auto;padding:0 2px;background:transparent;border:0;color:${T.label};font:600 11px/1 ${controlFont};cursor:pointer;user-select:none;pointer-events:auto}
|
||||
.ausboss-panel-switch i{position:relative;width:24px;height:13px;border-radius:7px;background:${T.switchOff}}
|
||||
.ausboss-panel-switch i::after{content:"";position:absolute;top:2px;left:2px;width:9px;height:9px;border-radius:50%;background:${T.inkSoft}}
|
||||
.ausboss-panel-switch[aria-checked=true] i{background:${T.brand}}
|
||||
.ausboss-panel-switch[aria-checked=true] i::after{left:13px;background:${T.inkHover}}
|
||||
.ausboss-primary-action{box-sizing:border-box;flex:none;height:22px;min-width:24px;padding:0 14px;border:0;border-radius:${RADIUS_XS}px;background:${T.brand};color:${T.onBrand};font:700 11px/1 ${controlFont};white-space:nowrap;cursor:pointer;pointer-events:auto}
|
||||
.ausboss-primary-action:hover:enabled{filter:brightness(1.12)}
|
||||
.ausboss-primary-action.quiet{background:${T.fill};color:${T.inkSoft}}
|
||||
.ausboss-primary-action:disabled{opacity:.6;cursor:default}
|
||||
.ausboss-compact-action:focus-visible,.ausboss-primary-action:focus-visible,.ausboss-panel-switch:focus-visible{outline:2px solid ${T.brand};outline-offset:1px}
|
||||
.ausboss-panel-switch{display:inline-flex;align-items:center;gap:6px;align-self:flex-end;flex:none;box-sizing:border-box;min-height:20px;margin-left:auto;padding:0 2px;background:transparent;border:0;color:#b2c6c3;font:600 11px/1 ${controlFont};cursor:pointer;user-select:none;pointer-events:auto}
|
||||
.ausboss-panel-switch i{position:relative;width:24px;height:13px;border-radius:7px;background:#3a4445}
|
||||
.ausboss-panel-switch i::after{content:"";position:absolute;top:2px;left:2px;width:9px;height:9px;border-radius:50%;background:#b6c4c3}
|
||||
.ausboss-panel-switch[aria-checked=true] i{background:${BRAND}}
|
||||
.ausboss-panel-switch[aria-checked=true] i::after{left:13px;background:#fff}
|
||||
.ausboss-compact-action:focus-visible,.ausboss-panel-switch:focus-visible{outline:2px solid ${BRAND};outline-offset:1px}
|
||||
`;
|
||||
document.head.append(style);
|
||||
}
|
||||
@@ -44,19 +39,6 @@ export function compactAction(label, title = "") {
|
||||
return button;
|
||||
}
|
||||
|
||||
// The one thing a panel wants done next, as a solid button: Save Image's
|
||||
// "Save picture" over a picture that is not saved yet. `quiet` (a class the
|
||||
// panel sets) is the same button once it has nothing left to do.
|
||||
export function primaryAction(label, title = "") {
|
||||
ensurePanelControls();
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "ausboss-primary-action";
|
||||
button.textContent = label;
|
||||
button.title = title;
|
||||
return button;
|
||||
}
|
||||
|
||||
export function panelSwitch(label, title) {
|
||||
ensurePanelControls();
|
||||
const button = document.createElement("button");
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// steps through its pairs with it, and the preview panel of Save Image and
|
||||
// the other preview nodes through their results. It hides itself while
|
||||
// there is one picture or none, so a single picture looks as it always did.
|
||||
import { FONT_UI, RADIUS_CONTROL, RADIUS_XS, THEME as T } from "./theme.mjs";
|
||||
import { BRAND } from "./index.mjs";
|
||||
import { stepperLabel } from "./picture_steps.mjs";
|
||||
|
||||
const CSS_ID = "ausboss-picture-stepper-v1";
|
||||
@@ -13,12 +13,12 @@ function ensureCss() {
|
||||
const style = document.createElement("style");
|
||||
style.id = CSS_ID;
|
||||
style.textContent = `
|
||||
.ausboss-stepper{box-sizing:border-box;flex:none;display:flex;align-items:stretch;height:var(--ausboss-stepper-height,24px);padding:1px;border:1px solid transparent;border-radius:${RADIUS_CONTROL}px;background:${T.fill};pointer-events:auto;user-select:none;}
|
||||
.ausboss-stepper{box-sizing:border-box;flex:none;display:flex;align-items:stretch;height:var(--ausboss-stepper-height,24px);padding:1px;border:1px solid #2a3437;border-radius:6px;background:#0f1516;pointer-events:auto;user-select:none;}
|
||||
.ausboss-stepper[hidden]{display:none;}
|
||||
.ausboss-stepper button{box-sizing:border-box;width:20px;margin:0;padding:0;border:none;border-radius:${RADIUS_XS}px;background:transparent;color:${T.label};font:600 13px/1 ${FONT_UI};cursor:pointer;}
|
||||
.ausboss-stepper button:hover{color:${T.ink};background:${T.fillHover};}
|
||||
.ausboss-stepper button:focus-visible{outline:1px solid ${T.brand};outline-offset:-1px;}
|
||||
.ausboss-stepper span{min-width:34px;padding:0 3px;color:${T.ink};font:600 10px/1 ${FONT_UI};font-variant-numeric:tabular-nums;text-align:center;white-space:nowrap;align-self:center;}
|
||||
.ausboss-stepper button{box-sizing:border-box;width:20px;margin:0;padding:0;border:none;border-radius:4px;background:transparent;color:#8ba3a1;font:700 13px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;cursor:pointer;}
|
||||
.ausboss-stepper button:hover{color:#fff;background:rgba(0,79,75,.78);}
|
||||
.ausboss-stepper button:focus-visible{outline:1px solid ${BRAND};outline-offset:-1px;}
|
||||
.ausboss-stepper span{min-width:34px;padding:0 3px;color:#d8eeee;font:700 10px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;font-variant-numeric:tabular-nums;text-align:center;white-space:nowrap;align-self:center;}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
@@ -52,10 +52,9 @@ export function makePictureStepper({ noun = "picture", height = 24, onStep, sign
|
||||
root.append(arrow("‹", -1, `Previous ${noun}`), label, arrow("›", 1, `Next ${noun}`));
|
||||
return {
|
||||
root,
|
||||
// `text` replaces the "2 / 5" for a stop that is not one picture.
|
||||
set(index, count, text) {
|
||||
set(index, count) {
|
||||
root.hidden = !(count > 1);
|
||||
label.textContent = text ?? stepperLabel(index, count);
|
||||
label.textContent = stepperLabel(index, count);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -19,75 +19,3 @@ export function stepIndex(index, count, step) {
|
||||
export function stepperLabel(index, count) {
|
||||
return count > 1 ? `${keepIndex(index, count) + 1} / ${count}` : "";
|
||||
}
|
||||
|
||||
// The preview panel has one more stop, before picture 1: every picture at
|
||||
// once. ALL stands for it where an index would be.
|
||||
export const ALL = -1;
|
||||
|
||||
// One step back or on through "all, 1, 2 ... count", round at both ends.
|
||||
export function stepWithAll(index, count, step) {
|
||||
if (!(count > 0)) return ALL;
|
||||
const stops = count + 1;
|
||||
const at = index === ALL ? 0 : keepIndex(index, count) + 1;
|
||||
const next = (((at + Math.sign(Number(step) || 0)) % stops) + stops) % stops;
|
||||
return next === 0 ? ALL : next - 1;
|
||||
}
|
||||
|
||||
export function allLabel(count) {
|
||||
return count > 1 ? `all ${count}` : "";
|
||||
}
|
||||
|
||||
// How to lay `count` pictures out in a box so each one draws as big as it
|
||||
// can: the columns and rows that leave a picture of this shape (`aspect`,
|
||||
// width over height) the most room.
|
||||
export function gridShape(count, width, height, aspect = 1) {
|
||||
const total = Math.max(1, Math.trunc(Number(count) || 0));
|
||||
const shape = Number.isFinite(aspect) && aspect > 0 ? aspect : 1;
|
||||
if (!(width > 0) || !(height > 0)) {
|
||||
const columns = Math.ceil(Math.sqrt(total));
|
||||
return { columns, rows: Math.ceil(total / columns) };
|
||||
}
|
||||
let best = { columns: 1, rows: total, size: 0 };
|
||||
for (let columns = 1; columns <= total; columns += 1) {
|
||||
const rows = Math.ceil(total / columns);
|
||||
const size = Math.min(width / columns, (height / rows) * shape);
|
||||
if (size > best.size) best = { columns, rows, size };
|
||||
}
|
||||
return { columns: best.columns, rows: best.rows };
|
||||
}
|
||||
|
||||
// The held pictures in a Save Image result, in the order they show: each
|
||||
// one's run token and its place in that run. A list run saves once for each
|
||||
// item, so one result can hold several tokens. Empty when the result holds
|
||||
// none, or when a picture in it is not one of the held ones.
|
||||
export function heldPlaces(record) {
|
||||
const tokens = new Set(Array.isArray(record?.ausboss_held) ? record.ausboss_held : []);
|
||||
if (!tokens.size) return [];
|
||||
const held = (Array.isArray(record.images) ? record.images : []).map((image) => {
|
||||
const match = /^([0-9a-f]{16})_(\d{3})\./.exec(String(image?.filename ?? ""));
|
||||
return match && tokens.has(match[1]) ? { token: match[1], index: Number(match[2]) } : null;
|
||||
});
|
||||
return held.length && held.every(Boolean) ? held : [];
|
||||
}
|
||||
|
||||
// What the row over held pictures says, and what its button does.
|
||||
// held how many pictures the node holds
|
||||
// kept how many of them are saved already
|
||||
// all a click keeps every picture (one picture, the grid, preview off)
|
||||
// done nothing is left to keep where the click would act
|
||||
// saving a save is on its way
|
||||
// name the file a single picture was saved as, when known
|
||||
// `quiet` is the button once it has nothing left to do.
|
||||
export function keepWords({ held = 0, kept = 0, all = true, done = false, saving = false, name = "" } = {}) {
|
||||
const note = !kept
|
||||
? "Not saved yet"
|
||||
: held < 2
|
||||
? (name ? `Saved as ${name}` : "Saved")
|
||||
: kept >= held ? `All ${held} saved` : `${kept} of ${held} saved`;
|
||||
if (saving) return { note, button: "Saving...", quiet: false };
|
||||
if (done) return { note, button: "Saved", quiet: true };
|
||||
const button = held < 2
|
||||
? "Save picture"
|
||||
: !all ? "Save this one" : kept ? "Save the rest" : `Save all ${held}`;
|
||||
return { note, button, quiet: false };
|
||||
}
|
||||
|
||||
@@ -37,7 +37,6 @@ export const SOURCE_LOADERS = Object.freeze({
|
||||
LoadImageOutput: picture("image"),
|
||||
LoadVideo: video("file"),
|
||||
AUSBOSS_NODES_ImageCropRotatePad: picture("image"),
|
||||
AUSBOSS_NODES_LoadImage: picture("image"),
|
||||
// A wired source_image replaces the file, so the file may stay blank.
|
||||
AUSBOSS_NODES_LoadImagePad: (inputs) => (linked(inputs?.source_image) ? null : picture("image")(inputs)),
|
||||
AUSBOSS_NODES_LoadAudio: sound("audio"),
|
||||
@@ -161,51 +160,3 @@ export function collapseRepeatedErrors(nodeErrors) {
|
||||
}
|
||||
return nodeErrors;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ known run errors
|
||||
//
|
||||
// Some errors that stop a run come from outside the workflow and say nothing
|
||||
// a person can act on ("KeyError: 'latent'"). Each entry here names one such
|
||||
// error by what is in ComfyUI's own report, and says in plain words what to
|
||||
// do. An entry is added only after the cause was found for real.
|
||||
const KNOWN_RUN_ERRORS = Object.freeze([
|
||||
{
|
||||
// Muse MiniMax Director replaces part of H3 for every workflow, and that
|
||||
// part reads a picture from every guide. ComfyUI's own H3 nodes also make
|
||||
// guides that hold sound alone, which is how a clip keeps its sound.
|
||||
matches: ({ type, message, traceback }) =>
|
||||
type === "KeyError" && message.includes("'latent'") && traceback.includes("muse_minimax_hybrid_patch"),
|
||||
summary: "Another node pack stopped this run",
|
||||
detail:
|
||||
"This error comes from the Muse MiniMax Director pack, not from this workflow. Turn that pack off in "
|
||||
+ "Manager, restart ComfyUI and run again.",
|
||||
},
|
||||
{
|
||||
// The w6a8 H3 files load from ComfyUI 0.38.0 on; older versions stop in
|
||||
// the model loader on the name of the format.
|
||||
matches: ({ message }) => message.includes("w6a8_int8"),
|
||||
summary: "This model needs a newer ComfyUI",
|
||||
detail:
|
||||
"Your ComfyUI is too old to read this model file. Update ComfyUI to 0.38 or newer and run again.",
|
||||
},
|
||||
]);
|
||||
|
||||
/**
|
||||
* Plain advice for a run error the pack knows the cause of, from the
|
||||
* `execution_error` event's detail. `null` for every other error.
|
||||
*/
|
||||
export function explainRunError(detail) {
|
||||
const report = {
|
||||
type: String(detail?.exception_type ?? "").split(".").pop(),
|
||||
message: String(detail?.exception_message ?? ""),
|
||||
traceback: [].concat(detail?.traceback ?? []).join("\n"),
|
||||
};
|
||||
for (const known of KNOWN_RUN_ERRORS) {
|
||||
try {
|
||||
if (known.matches(report)) return { summary: known.summary, detail: known.detail };
|
||||
} catch (_error) {
|
||||
// A report in a shape this entry did not expect is simply not a match.
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -25,8 +25,10 @@
|
||||
// Shift's fine step and typed values are never snapped.
|
||||
|
||||
import { keepKeyInField } from "./canvas_passthrough.mjs";
|
||||
// theme.mjs has no imports, so this module's math stays testable in node:test.
|
||||
import { FONT_UI, RADIUS_CONTROL, THEME as T } from "./theme.mjs";
|
||||
|
||||
// Keep in sync with BRAND in shared/index.mjs - importing it would pull
|
||||
// /scripts/app.js into node:test, and this module's math must stay testable.
|
||||
const BRAND = "#00b4aa";
|
||||
|
||||
// Horizontal pixels of drag per step; small enough to feel light, large
|
||||
// enough that a shaky click cannot change the value. The dead zone keeps a
|
||||
@@ -179,19 +181,19 @@ function ensureScrubCss() {
|
||||
// for one) carry blanket `section input` rules, and these must outrank
|
||||
// them wherever the control is mounted.
|
||||
style.textContent = `
|
||||
.ausboss-scrub{display:flex;width:72px;height:24px;border:1px solid transparent;border-radius:${RADIUS_CONTROL}px;
|
||||
background:${T.fill};overflow:hidden;flex:none;color:${T.ink};font:500 12px ${FONT_UI};font-variant-numeric:tabular-nums}
|
||||
.ausboss-scrub:focus-within{border-color:${T.brand}}
|
||||
.ausboss-scrub{display:flex;width:72px;height:24px;border:1px solid #3a4047;border-radius:5px;
|
||||
background:#23272c;overflow:hidden;flex:none;color:#d7dde2;font:12px system-ui}
|
||||
.ausboss-scrub:focus-within{border-color:${BRAND}}
|
||||
.ausboss-scrub>.ausboss-scrub-input{flex:1 1 auto;min-width:0;width:100%;height:100%;border:none;
|
||||
padding:0;margin:0;background:transparent;color:inherit;text-align:center;cursor:ew-resize;
|
||||
user-select:none;font:inherit;outline:none;border-radius:0}
|
||||
.ausboss-scrub>.ausboss-scrub-input:focus{cursor:text;user-select:text}
|
||||
.ausboss-scrub>.ausboss-scrub-unit{flex:none;align-self:center;padding:0 3px 0 1px;color:${T.faint};font:600 10px ${FONT_UI};letter-spacing:.04em;text-transform:uppercase;text-align:center;user-select:none;pointer-events:none}
|
||||
.ausboss-scrub>.ausboss-scrub-unit{flex:none;align-self:center;padding:0 3px 0 1px;color:#5f7674;font-size:9.5px;letter-spacing:.06em;text-transform:uppercase;text-align:center;user-select:none;pointer-events:none}
|
||||
.ausboss-scrub>.ausboss-scrub-step{flex:none;width:14px;display:flex;flex-direction:column;
|
||||
border-left:1px solid transparent;background:${T.fillHover}}
|
||||
border-left:1px solid #3a4047}
|
||||
.ausboss-scrub>.ausboss-scrub-step>button{flex:1 1 0;min-height:0;border:none;background:transparent;
|
||||
color:${T.label};cursor:pointer;padding:0;margin:0;display:grid;place-items:center;border-radius:0}
|
||||
.ausboss-scrub>.ausboss-scrub-step>button:hover{color:${T.brand};background:rgba(255,255,255,.05)}
|
||||
color:#9ba2aa;cursor:pointer;padding:0;margin:0;display:grid;place-items:center;border-radius:0}
|
||||
.ausboss-scrub>.ausboss-scrub-step>button:hover{color:${BRAND};background:rgba(255,255,255,.05)}
|
||||
`;
|
||||
document.head.append(style);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// chosen one: the mode row of Image Compare A/B, and its off | on choices.
|
||||
// The choices share one width, so the marker only has to move. With `fit`
|
||||
// each choice is as wide as its own name, and the marker is measured.
|
||||
import { FONT_UI, RADIUS_CONTROL, RADIUS_XS, THEME as T } from "./theme.mjs";
|
||||
import { BRAND } from "./index.mjs";
|
||||
|
||||
const CSS_ID = "ausboss-slide-switch-v1";
|
||||
|
||||
@@ -11,17 +11,17 @@ function ensureCss() {
|
||||
const style = document.createElement("style");
|
||||
style.id = CSS_ID;
|
||||
style.textContent = `
|
||||
.ausboss-slide{position:relative;box-sizing:border-box;flex:none;display:grid;grid-auto-flow:column;grid-auto-columns:1fr;height:24px;padding:2px;border:1px solid transparent;border-radius:${RADIUS_CONTROL}px;background:${T.fill};}
|
||||
.ausboss-slide{position:relative;box-sizing:border-box;flex:none;display:grid;grid-auto-flow:column;grid-auto-columns:1fr;height:24px;padding:2px;border:1px solid #2a3437;border-radius:6px;background:#0f1516;}
|
||||
.ausboss-slide.fit{grid-auto-columns:max-content;}
|
||||
.ausboss-slide.fit button{padding:0 7px;}
|
||||
.ausboss-slide-mark{position:absolute;top:2px;bottom:2px;left:2px;border-radius:${RADIUS_XS}px;background:${T.brand};transition:transform .16s ease,width .16s ease;pointer-events:none;}
|
||||
.ausboss-slide-mark{position:absolute;top:2px;bottom:2px;left:2px;border-radius:4px;background:${BRAND};box-shadow:0 0 7px rgba(0,180,170,.3);transition:transform .16s ease,width .16s ease;pointer-events:none;}
|
||||
.ausboss-slide.none .ausboss-slide-mark{display:none;}
|
||||
.ausboss-slide button{position:relative;box-sizing:border-box;min-width:0;height:100%;margin:0;padding:0 9px;border:none;border-radius:${RADIUS_XS}px;background:transparent;color:${T.label};font:600 11px/1 ${FONT_UI};white-space:nowrap;cursor:pointer;transition:color .16s ease;}
|
||||
.ausboss-slide button:hover{color:${T.inkHover};}
|
||||
.ausboss-slide button.on,.ausboss-slide button.on:hover{color:${T.onBrand};}
|
||||
.ausboss-slide.off-left button.on:first-of-type,.ausboss-slide.off-left button.on:first-of-type:hover{color:${T.ink};}
|
||||
.ausboss-slide.off-left.is-off .ausboss-slide-mark{background:${T.switchOff};}
|
||||
.ausboss-slide button:focus-visible{outline:1px solid ${T.brand};outline-offset:1px;}
|
||||
.ausboss-slide button{position:relative;box-sizing:border-box;min-width:0;height:100%;margin:0;padding:0 9px;border:none;border-radius:4px;background:transparent;color:#8ba3a1;font:700 10px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;letter-spacing:.02em;white-space:nowrap;cursor:pointer;transition:color .16s ease;}
|
||||
.ausboss-slide button:hover{color:#fff;}
|
||||
.ausboss-slide button.on,.ausboss-slide button.on:hover{color:#04201d;}
|
||||
.ausboss-slide.off-left button.on:first-of-type,.ausboss-slide.off-left button.on:first-of-type:hover{color:#d8eeee;}
|
||||
.ausboss-slide.off-left.is-off .ausboss-slide-mark{background:#33423f;box-shadow:none;}
|
||||
.ausboss-slide button:focus-visible{outline:1px solid ${BRAND};outline-offset:1px;}
|
||||
@media (prefers-reduced-motion: reduce){.ausboss-slide-mark,.ausboss-slide button{transition:none;}}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
import { api } from "../../../scripts/api.js";
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { nodeByExecutionId } from "./graph_ids.mjs";
|
||||
import { FONT_UI, RADIUS_CONTROL, THEME as T } from "./theme.mjs";
|
||||
import { BRAND } from "./index.mjs";
|
||||
import { outputRecordQuery } from "./input_preview.mjs";
|
||||
import { isForeignRun } from "./prompt_scope.mjs";
|
||||
import {
|
||||
@@ -213,15 +213,15 @@ export function ensureStepCss() {
|
||||
.ausboss-steps.on{display:block;}
|
||||
.ausboss-steps-showing>img,.ausboss-steps-showing>video,.ausboss-steps-showing>.ausboss-input-preview-hint,.ausboss-steps-showing>.ausboss-video-status{visibility:hidden;}
|
||||
.ausboss-steps img,.ausboss-steps.on img{display:block;position:absolute;inset:0;width:100%;height:100%;max-width:none;max-height:none;margin:0;object-fit:contain;visibility:visible;}
|
||||
.ausboss-steps-line{position:absolute;left:0;top:0;height:3px;width:0;background:${T.brand};transition:width .15s linear;}
|
||||
.ausboss-steps-chip{position:absolute;left:6px;right:6px;bottom:6px;box-sizing:border-box;padding:4px 7px;border:1px solid transparent;border-radius:${RADIUS_CONTROL}px;background:rgba(21,24,26,.88);color:${T.inkSoft};font:600 10.5px/1.35 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
|
||||
.ausboss-steps-line{position:absolute;left:0;top:0;height:3px;width:0;background:${BRAND};box-shadow:0 0 6px rgba(0,180,170,.5);transition:width .15s linear;}
|
||||
.ausboss-steps-chip{position:absolute;left:6px;right:6px;bottom:6px;box-sizing:border-box;padding:4px 7px;border:1px solid rgba(255,255,255,.08);border-radius:5px;background:rgba(8,12,13,.84);color:#d8ecea;font:600 10.5px/1.35 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
|
||||
.ausboss-steps.stopped img{filter:brightness(.55) saturate(.7);}
|
||||
.ausboss-steps.stopped .ausboss-steps-line{display:none;}
|
||||
.ausboss-steps.stopped .ausboss-steps-chip{border-color:${T.danger};color:${T.dangerInk};}
|
||||
.ausboss-steps-hint{position:absolute;left:50%;top:50%;max-width:86%;transform:translate(-50%,-50%);color:${T.faint};font:11px/1.35 ${FONT_UI};text-align:center;}
|
||||
.ausboss-steps-stop{border-color:transparent!important;background:${T.dangerSoft}!important;color:${T.dangerInk}!important;}
|
||||
.ausboss-steps-stop:hover{background:rgba(120,38,33,.95)!important;color:${T.inkHover}!important;}
|
||||
.ausboss-steps-stop::before{content:"";display:inline-block;width:6px;height:6px;margin-right:5px;border-radius:1px;background:${T.danger};vertical-align:1px;}
|
||||
.ausboss-steps.stopped .ausboss-steps-chip{border-color:rgba(224,96,90,.55);color:#ffd0cc;}
|
||||
.ausboss-steps-hint{position:absolute;left:50%;top:50%;max-width:86%;transform:translate(-50%,-50%);color:#78908e;font:11px/1.35 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;text-align:center;}
|
||||
.ausboss-steps-stop{border-color:rgba(224,96,90,.8)!important;background:rgba(58,28,27,.9)!important;color:#ffd9d6!important;}
|
||||
.ausboss-steps-stop:hover{background:rgba(120,38,33,.95)!important;color:#fff!important;}
|
||||
.ausboss-steps-stop::before{content:"";display:inline-block;width:6px;height:6px;margin-right:5px;border-radius:1px;background:#e0605a;vertical-align:1px;}
|
||||
.ausboss-video-tool.ausboss-steps-stop{display:none;}
|
||||
.ausboss-video-tool.ausboss-steps-stop.live{display:inline-block;}
|
||||
.ausboss-video-stage.is-still .ausboss-video-tools.ausboss-steps-tools{display:flex;}
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
// The pack's node-face palette, in one place. Cards, number boxes and
|
||||
// switches read their colours, font and sizes from here instead of
|
||||
// carrying their own literals.
|
||||
//
|
||||
// The look: solid gray controls with no outlines on a near-black card,
|
||||
// neutral grays, and one teal accent for whatever is on or picked.
|
||||
//
|
||||
// No imports on purpose: scrub_input.mjs and the node:test suites load
|
||||
// this file without the ComfyUI app.
|
||||
|
||||
export const THEME = Object.freeze({
|
||||
brand: "#00b4aa", // the one accent: picked segment, switch on, focus ring
|
||||
onBrand: "#04201d", // text on a brand fill
|
||||
brandSoft: "rgba(0,180,170,.16)", // chip fill
|
||||
brandSoftHover: "rgba(0,180,170,.26)",
|
||||
brandInk: "#45d6cb", // chip text on brandSoft
|
||||
brandGlow: "#6fe0d6", // the big text look
|
||||
|
||||
card: "#101214", // widget card ground
|
||||
fill: "#2d3134", // every control: solid, no border
|
||||
fillHover: "#383c40", // control hover, the chevron column
|
||||
well: "#0f1112", // picture stage ground
|
||||
rule: "#2b2f32", // hairline after a section label
|
||||
switchOff: "#62676d", // the mark of a switch sitting on off
|
||||
|
||||
ink: "#f6f7f8", // values: numbers, picked options, typed text
|
||||
inkSoft: "#e0e3e5", // default card text
|
||||
inkHover: "#ffffff",
|
||||
label: "#b4b9bd", // row labels, unselected segments, chevrons
|
||||
faint: "#979da2", // units, section labels, placeholders, muted rows
|
||||
|
||||
danger: "#e0605a", // stop: the dot on the Stop button
|
||||
dangerInk: "#ffd9d6",
|
||||
dangerSoft: "#3a1c1b",
|
||||
|
||||
warn: "#e0a040",
|
||||
warnInk: "#ffdca8",
|
||||
warnSoft: "#3a2a10",
|
||||
});
|
||||
|
||||
export const FONT_UI = `system-ui,-apple-system,"Segoe UI",Roboto,sans-serif`;
|
||||
|
||||
// Every control in a card row is as tall as the row.
|
||||
export const CONTROL_HEIGHT = 26;
|
||||
export const RADIUS_XS = 4;
|
||||
export const RADIUS_CONTROL = 6;
|
||||
export const RADIUS_CARD = 10;
|
||||
|
||||
// The select's chevron, drawn in `label`.
|
||||
export const SELECT_CHEVRON = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' fill='none' stroke='%23b4b9bd' stroke-width='1.5'/%3E%3C/svg%3E")`;
|
||||
@@ -28,15 +28,11 @@ export function setTileFace(node, root, enabled, onEdit) {
|
||||
});
|
||||
}
|
||||
const listeners = new AbortController();
|
||||
// Snap into line and Line up use the card people see, not the
|
||||
// transparent node around it (js/shared/outline.mjs).
|
||||
node.ausbossOutlineElement = root.querySelector(".ausboss-callout-card,.ausboss-note-card") || root;
|
||||
installTileDrag(node, root, listeners.signal, onEdit);
|
||||
installTileResize(node, root, listeners.signal);
|
||||
originalDescriptors.set(node, { descriptors, listeners });
|
||||
} else {
|
||||
previous.listeners.abort();
|
||||
delete node.ausbossOutlineElement;
|
||||
for (const [key, descriptor] of previous.descriptors) {
|
||||
if (descriptor) Object.defineProperty(node, key, descriptor);
|
||||
else delete node[key];
|
||||
@@ -48,9 +44,6 @@ export function setTileFace(node, root, enabled, onEdit) {
|
||||
|
||||
function skipBadges() {}
|
||||
|
||||
// Sent from a tile's own drag after each move: js/snap_lines/ lines it up.
|
||||
export const TILE_MOVE = "ausboss-tile-move";
|
||||
|
||||
// A normal node moves by its header. Give the tile that gesture while
|
||||
// keeping a short click on a link or the info button as its usual action.
|
||||
function installTileDrag(node, root, signal, onEdit) {
|
||||
@@ -94,9 +87,6 @@ function installTileDrag(node, root, signal, onEdit) {
|
||||
for (const start of press.starts) start.item.pos = [start.x + dx / zoom, start.y + dy / zoom];
|
||||
node.setDirtyCanvas?.(true, true);
|
||||
event.stopPropagation();
|
||||
// The move stops here (Nodes 2.0 would pan the canvas with it), so tell
|
||||
// Snap into line separately, after the tile has been placed.
|
||||
root.dispatchEvent(new CustomEvent(TILE_MOVE, { bubbles: true, detail: event }));
|
||||
}, capture);
|
||||
const finish = (event) => {
|
||||
if (event.pointerId !== press?.id) return;
|
||||
|
||||
@@ -217,16 +217,6 @@ export function latestFirstFor(info, frames, everyNth = 1) {
|
||||
return Math.max(0, info.count - 1 - (lastFrameFor(0, frames, everyNth)));
|
||||
}
|
||||
|
||||
// How far a drag can move IN while a Length is on. A Length that fits stops
|
||||
// IN where OUT meets the source's end, so the count stays whole. A Length
|
||||
// as long as the clip or longer cannot keep its count anywhere: it only caps
|
||||
// the clip, the source's end is OUT, and IN moves over the whole clip.
|
||||
export function latestInFor(info, frames, everyNth = 1) {
|
||||
if (!info?.count) return 0;
|
||||
const latest = latestFirstFor(info, frames, everyNth);
|
||||
return latest > 0 ? latest : info.count - 1;
|
||||
}
|
||||
|
||||
// Everything the rail draws for the clip node, from the stored values:
|
||||
// mode which way sets the length (lengthMode)
|
||||
// first IN, the first source frame the run keeps
|
||||
@@ -273,14 +263,7 @@ export function clipLengthPlan(info, values = {}) {
|
||||
latestStart = clamp(Math.floor((end - lastTick - TRIM_EPSILON) * info.fps), 0, endFrame);
|
||||
}
|
||||
}
|
||||
if (values.resampled) {
|
||||
// A known output rate places every output frame: the backend samples
|
||||
// and holds on ticks at start + k / rate (decode_video_range), so the
|
||||
// count, the last source frame shown and the end are all known here.
|
||||
if (!(values.outputFps > 0) || !(info.fps > 0)) return { ...base, last: cap > 0 ? null : window.last, requested, latestStart };
|
||||
const resampled = resampledFrames(info, values, nth, requested, snap);
|
||||
return { ...base, ...resampled, requested, latestStart, truncated: requested != null && resampled.frames < requested };
|
||||
}
|
||||
if (values.resampled) return { ...base, last: cap > 0 ? null : window.last, requested, latestStart };
|
||||
const kept = keptFrames(window, nth, cap, snap);
|
||||
return { ...base, last: kept.lastKept, frames: kept.frames, requested, latestStart, truncated: requested != null && kept.frames < requested };
|
||||
};
|
||||
@@ -295,27 +278,6 @@ export function clipLengthPlan(info, values = {}) {
|
||||
return capped(mode === "length" ? stored : 0);
|
||||
}
|
||||
|
||||
// Output frames of a run that resamples to a known rate: ticks at
|
||||
// start + k / tickRate while before the end, thinned by every nth, capped,
|
||||
// then snapped. `last` is the source frame the final tick holds.
|
||||
export function resampledFrames(info, values, everyNth = 1, cap = null, snap = "free") {
|
||||
const nth = Math.max(1, Math.floor(finite(everyNth, 1)) || 1);
|
||||
const tickRate = finite(values.outputFps) * nth;
|
||||
const duration = info.duration || info.count / info.fps;
|
||||
const start = Math.max(0, finite(values.start));
|
||||
const end = finite(values.end) > 0 ? Math.min(finite(values.end), duration) : duration;
|
||||
const ticks = Math.max(0, Math.ceil((end - start) * tickRate - TRIM_EPSILON));
|
||||
let frames = Math.ceil(ticks / nth);
|
||||
if (cap != null && cap > 0) frames = Math.min(frames, cap);
|
||||
frames = snapFrameCount(frames, snap);
|
||||
const first = frameWindow(info, start, values.end).first;
|
||||
const lastTime = start + Math.max(0, frames - 1) * nth / tickRate;
|
||||
const last = clamp(Math.floor(lastTime * info.fps + TRIM_EPSILON), first, info.count - 1);
|
||||
const windowLast = frameWindow(info, start, values.end).last;
|
||||
// The last frame is held for one output frame, but never past the video.
|
||||
return { first, last, windowLast, frames, endSeconds: Math.min(end, start + frames / finite(values.outputFps)) };
|
||||
}
|
||||
|
||||
// Playback rate for a label, trimmed of float noise: 24 -> "24",
|
||||
// 23.976023... -> "23.976".
|
||||
export function formatFps(value) {
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
// Small pieces every timing card shares (the clip node, Load Video, Load
|
||||
// Audio): the seconds | frames choice and the "linked" button that goes to
|
||||
// the node feeding a value.
|
||||
import { app } from "../../../scripts/app.js";
|
||||
|
||||
// Seconds or frames on a timing card: a per-browser choice, like a view
|
||||
// setting. It never changes a stored value.
|
||||
const UNITS_KEY = "AusBoss.ClipTiming.Units";
|
||||
let unitsCache = null;
|
||||
export function timingUnits(next) {
|
||||
if (next === "s" || next === "f") {
|
||||
unitsCache = next;
|
||||
try { localStorage.setItem(UNITS_KEY, next); } catch { /* private window */ }
|
||||
return next;
|
||||
}
|
||||
if (unitsCache) return unitsCache;
|
||||
try { unitsCache = localStorage.getItem(UNITS_KEY) === "f" ? "f" : "s"; } catch { unitsCache = "s"; }
|
||||
return unitsCache;
|
||||
}
|
||||
|
||||
// The node feeding a linked input, by its title, with a way to go to it.
|
||||
export function linkedNodeInfo(node, name) {
|
||||
const slot = node.inputs?.find((input) => input?.name === name || input?.widget?.name === name);
|
||||
if (slot?.link == null) return null;
|
||||
const graph = node.graph;
|
||||
const link = graph?.links?.get?.(slot.link) ?? graph?.links?.[slot.link] ?? graph?._links?.get?.(slot.link);
|
||||
const source = graph?.getNodeById?.(link?.origin_id);
|
||||
if (!source) return { title: "the subgraph's input", go: null };
|
||||
const title = source.title || source.type || "another node";
|
||||
return {
|
||||
title,
|
||||
go: () => {
|
||||
try {
|
||||
app.canvas?.selectNode?.(source);
|
||||
app.canvas?.centerOnNode?.(source);
|
||||
app.canvas?.setDirty?.(true, true);
|
||||
} catch { /* an older canvas */ }
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -57,9 +57,9 @@ export function goesBehind(flying, ask, epoch) {
|
||||
|
||||
// The pack's own picture loaders. One of them wired straight into Mask by
|
||||
// Touch is run by the node itself, the way a press on Show picture runs it:
|
||||
// it may crop, turn, pad or resize its file, so the file alone is not the picture,
|
||||
// it may crop, turn or pad its file, so the file alone is not the picture,
|
||||
// but running it costs next to nothing.
|
||||
export const OWN_LOADERS = new Set(["AUSBOSS_NODES_ImageCropRotatePad", "AUSBOSS_NODES_LoadImage", "AUSBOSS_NODES_LoadImagePad"]);
|
||||
export const OWN_LOADERS = new Set(["AUSBOSS_NODES_ImageCropRotatePad", "AUSBOSS_NODES_LoadImagePad"]);
|
||||
|
||||
// What a loader will hand on, as far as the page can tell: its file and its
|
||||
// settings, as one text. Another text means another picture. Widgets that
|
||||
@@ -74,25 +74,6 @@ export function loaderSignature(widgets) {
|
||||
return JSON.stringify(settings);
|
||||
}
|
||||
|
||||
// What the picture says when a run stopped at the node. ComfyUI's own text
|
||||
// for a full graphics card is ten lines of numbers; here it is one plain
|
||||
// line. Anything else is said as it came.
|
||||
export const OUT_OF_MEMORY = "The graphics card ran out of memory, so the node could not look. Free some memory on it, then click again.";
|
||||
export function stopMessage(message) {
|
||||
const text = String(message ?? "");
|
||||
return /out of memory|OutOfMemory/i.test(text) ? OUT_OF_MEMORY : text;
|
||||
}
|
||||
|
||||
// A name as it is typed under the picture: "-face" (or the minus sign a
|
||||
// phone types) takes the name away, "+face" adds it; without a sign it does
|
||||
// what `takes` says. Returns { word, add }, the word cleaned.
|
||||
export function typedName(text, takes = false) {
|
||||
const typed = String(text ?? "").trim();
|
||||
const sign = /^[-\u2212\u2013+]/.exec(typed)?.[0] ?? "";
|
||||
const word = cleanWord(sign ? typed.slice(1) : typed);
|
||||
return { word, add: sign ? sign === "+" : !takes };
|
||||
}
|
||||
|
||||
// A word as the node sends it to SAM 3: commas, colons and brackets are the
|
||||
// text reader's own syntax and go; spaces are collapsed.
|
||||
export function cleanWord(word) {
|
||||
@@ -287,15 +268,6 @@ export function encodeTouches(key, items) {
|
||||
return JSON.stringify({ v: 1, key: String(key ?? ""), items: clean });
|
||||
}
|
||||
|
||||
// The picks the node moved onto a new picture (New picture: keep picks), as
|
||||
// the text to write: only while the widget still holds the picks they were
|
||||
// moved from (`current`). Anything picked since is kept, and then this is null.
|
||||
export function movedTouches(note, current) {
|
||||
const moved = note?.moved;
|
||||
if (!moved || typeof moved.touches !== "string" || typeof moved.from !== "string") return null;
|
||||
return stampOf(String(current ?? "")) === moved.from ? moved.touches : null;
|
||||
}
|
||||
|
||||
// Whether two runs of touches pick the same things. How they are written
|
||||
// decides, so a touch fresh from a click and the same one read back from the
|
||||
// widget compare equal.
|
||||
@@ -1063,46 +1035,19 @@ export function strokePieces(planes, list, sizes, pixels, stroke, ranks, wholes
|
||||
// picked area, and as untouched while almost none of it is.
|
||||
const NEARLY = 0.03;
|
||||
|
||||
// Which pieces hold a whole pick: nearly all of one picked area (`areas`,
|
||||
// on/off masks, one per chip) lies inside the piece. A person holds the
|
||||
// sweater picked on them; hair that a picked jacket only laps over does not.
|
||||
export const HOLDS = 0.9;
|
||||
export function piecesHolding(planes, count, areas) {
|
||||
const holds = new Uint8Array(count);
|
||||
for (const area of areas ?? []) {
|
||||
if (!area) continue;
|
||||
let size = 0;
|
||||
for (let index = 0; index < area.length; index += 1) if (area[index]) size += 1;
|
||||
if (!size) continue;
|
||||
const inside = piecesInside(planes, count, area);
|
||||
for (let piece = 0; piece < count; piece += 1) if (inside[piece] >= HOLDS * size) holds[piece] = 1;
|
||||
}
|
||||
return holds;
|
||||
}
|
||||
|
||||
// Which piece a pointer at pixel `index` lights up: the first piece there,
|
||||
// in the order they are offered (`ranks`; without it, smallest first), that
|
||||
// would still change something. Adding, that is a piece not yet (nearly)
|
||||
// all picked, so clicking the same spot again goes on from the glasses to
|
||||
// the face to the person. Taking away, it is a piece that has some of the
|
||||
// picked area in it. -1 when there is none.
|
||||
//
|
||||
// Taking away from a spot that is not picked itself (`here` false) never
|
||||
// means a thing that holds a whole pick somewhere else (`holds`, from
|
||||
// piecesHolding): with a sweater picked, pointing at the face does not
|
||||
// offer the person, which would take the sweater along.
|
||||
export function pieceAt(planes, index, { sizes, inside, adding = true, ranks = null, here = true, holds = null } = {}) {
|
||||
export function pieceAt(planes, index, { sizes, inside, adding = true, ranks = null } = {}) {
|
||||
for (const piece of candidatesAt(planes, index, ranks)) {
|
||||
const size = sizes?.[piece] ?? 0;
|
||||
if (!size) continue;
|
||||
const picked = inside?.[piece] ?? 0;
|
||||
const slack = Math.max(4, size * NEARLY);
|
||||
if (adding) {
|
||||
if (size - picked > slack) return piece;
|
||||
continue;
|
||||
}
|
||||
if (picked <= slack || (!here && holds?.[piece])) continue;
|
||||
return piece;
|
||||
if (adding ? size - picked > slack : picked > slack) return piece;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
+21
-123
@@ -63,7 +63,6 @@ import {
|
||||
loaderSignature,
|
||||
maskOn,
|
||||
maskShare,
|
||||
movedTouches,
|
||||
nameShown,
|
||||
nextGroup,
|
||||
numberChip,
|
||||
@@ -77,7 +76,6 @@ import {
|
||||
pieceRanks,
|
||||
pieceWholes,
|
||||
pieceSizes,
|
||||
piecesHolding,
|
||||
piecesInside,
|
||||
prefixStamps,
|
||||
previewPixels,
|
||||
@@ -86,11 +84,9 @@ import {
|
||||
sharedPixels,
|
||||
shrinkMask,
|
||||
stampOf,
|
||||
stopMessage,
|
||||
strokePieces,
|
||||
thinStroke,
|
||||
touchFits,
|
||||
typedName,
|
||||
} from "./touch_math.mjs";
|
||||
|
||||
const CSS_ID = "ausboss-touch-css";
|
||||
@@ -193,17 +189,9 @@ function ensureCss() {
|
||||
.ausboss-touch-chip>button:hover{opacity:1;background:rgba(255,255,255,.14);}
|
||||
.ausboss-touch-chip>button.more{padding:0 6px;background:rgba(0,0,0,.35);opacity:.95;}
|
||||
.ausboss-touch-chip.open>button.more{background:rgba(0,0,0,.2);}
|
||||
.ausboss-touch-namebox{box-sizing:border-box;flex:none;display:inline-flex;align-items:stretch;height:20px;border:1px dashed rgba(0,180,170,.5);border-radius:10px;overflow:hidden;}
|
||||
.ausboss-touch-namebox:focus-within{border-style:solid;border-color:${BRAND};background:rgba(0,0,0,.4);}
|
||||
.ausboss-touch-namebox.away{border-color:rgba(${LIT_AWAY.join(",")},.6);}
|
||||
.ausboss-touch-namebox.away:focus-within{border-color:rgb(${LIT_AWAY.join(",")});}
|
||||
.ausboss-touch-sign{box-sizing:border-box;flex:none;width:22px;padding:0;border:0;border-right:1px solid rgba(0,180,170,.35);background:rgba(0,180,170,.16);color:#dffcf9;font:700 13px/18px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;cursor:pointer;}
|
||||
.ausboss-touch-sign:hover{background:rgba(0,180,170,.34);color:#fff;}
|
||||
.ausboss-touch-sign:disabled{opacity:.4;cursor:default;}
|
||||
.ausboss-touch-namebox.away .ausboss-touch-sign{border-right-color:rgba(${LIT_AWAY.join(",")},.4);background:rgba(${LIT_AWAY.join(",")},.24);color:#ffe9e2;}
|
||||
.ausboss-touch-namebox.away .ausboss-touch-sign:hover{background:rgba(${LIT_AWAY.join(",")},.42);}
|
||||
.ausboss-touch-name{box-sizing:border-box;flex:none;width:118px;height:18px;padding:0 8px 0 6px;border:0;background:transparent;color:#dffcf9;font:600 10px/18px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;outline:none;}
|
||||
.ausboss-touch-name{box-sizing:border-box;flex:none;width:104px;height:20px;padding:0 9px;border:1px dashed rgba(0,180,170,.5);border-radius:10px;background:transparent;color:#dffcf9;font:600 10px/18px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;outline:none;}
|
||||
.ausboss-touch-name::placeholder{color:#78908e;font-weight:500;}
|
||||
.ausboss-touch-name:focus{border-style:solid;border-color:${BRAND};background:rgba(0,0,0,.4);}
|
||||
.ausboss-touch-gap{flex:1 1 auto;min-width:0;}
|
||||
.ausboss-touch-stage{position:relative;flex:1 1 auto;min-height:0;width:100%;overflow:hidden;border:1px solid rgba(0,180,170,.27);border-radius:6px;background:rgba(0,0,0,.28);}
|
||||
[data-node-id] .ausboss-touch-stage{box-sizing:border-box;min-height:${STAGE_MIN}px;}
|
||||
@@ -235,12 +223,9 @@ function ensureCss() {
|
||||
.ausboss-touch.fining .ausboss-touch-fining{display:flex;}
|
||||
.ausboss-touch-fining::before{content:"";flex:none;width:7px;height:7px;border-radius:50%;background:${BRAND};animation:ausboss-touch-pulse 1s ease-in-out infinite;}
|
||||
@keyframes ausboss-touch-pulse{0%,100%{opacity:.25;}50%{opacity:1;}}
|
||||
.ausboss-touch-btn.lookpill{display:inline-flex;align-items:center;gap:5px;height:${BAR_HEIGHT}px;padding:0 9px 0 0;overflow:hidden;border:1px solid rgba(0,180,170,.8);border-radius:10px;letter-spacing:0;text-transform:none;font:600 10px/18px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#dffcf9;background:linear-gradient(90deg,rgba(0,180,170,.38) var(--done,0%),rgba(0,180,170,.08) var(--done,0%));}
|
||||
.ausboss-touch-btn.lookpill{display:inline-flex;align-items:center;gap:5px;height:${BAR_HEIGHT}px;padding:0 9px 0 8px;border:1px solid rgba(0,180,170,.6);border-radius:10px;letter-spacing:0;text-transform:none;font:600 10px/18px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#dffcf9;background:linear-gradient(90deg,rgba(0,180,170,.38) var(--done,0%),rgba(0,180,170,.08) var(--done,0%));}
|
||||
.ausboss-touch-btn.lookpill:hover{border-color:${BRAND};color:#fff;background:linear-gradient(90deg,rgba(0,180,170,.5) var(--done,0%),rgba(0,180,170,.16) var(--done,0%));}
|
||||
.ausboss-touch-btn.lookpill .key{flex:none;display:inline-flex;align-items:center;gap:4px;align-self:stretch;padding:0 7px 0 8px;background:${BRAND};color:#04201e;font-weight:700;}
|
||||
.ausboss-touch-btn.lookpill:hover .key{background:#35d6cb;}
|
||||
.ausboss-touch-btn.lookpill.paused .key{background:#9fb4b2;}
|
||||
.ausboss-touch-btn.lookpill .icon{flex:none;font-size:8px;letter-spacing:-1px;}
|
||||
.ausboss-touch-btn.lookpill .icon{flex:none;font-size:8px;letter-spacing:-1px;opacity:.9;}
|
||||
.ausboss-touch-btn.lookpill.paused{border-color:rgba(120,144,142,.6);color:#c8dddd;background:linear-gradient(90deg,rgba(120,144,142,.3) var(--done,0%),rgba(120,144,142,.06) var(--done,0%));}
|
||||
.ausboss-touch-btn.lookpill.paused .icon{letter-spacing:0;}
|
||||
.ausboss-touch-btn.lookpill .count{opacity:.8;}
|
||||
@@ -541,7 +526,6 @@ function resolve(face) {
|
||||
face.raw = raw;
|
||||
face.exact = exact;
|
||||
face.chipAreas = null;
|
||||
face.holds = null;
|
||||
face.inside = pic.pieces ? piecesInside(pic.pieces.planes, pic.pieces.list.length, raw) : null;
|
||||
face.hoverMask = null;
|
||||
}
|
||||
@@ -712,11 +696,6 @@ function requestRun(face, ask) {
|
||||
return false;
|
||||
}
|
||||
const run = { ask, stamp: face.stamp, epoch: face.sourceEpoch, queued: false };
|
||||
// Runs of this node that are at a picture it no longer has. The one that
|
||||
// is running ends by itself once the next job waits; the ones that still
|
||||
// wait in the queue would each run for nothing, one after the other, so
|
||||
// they are taken out before this one is sent.
|
||||
const stale = face.flying.filter((other) => other.queued && other.epoch !== run.epoch);
|
||||
face.flying.push(run);
|
||||
face.inFlight = true;
|
||||
face.askedAt = performance.now();
|
||||
@@ -727,15 +706,7 @@ function requestRun(face, ask) {
|
||||
face.flying = face.flying.filter((other) => other !== run);
|
||||
if (!face.flying.length) settle(face);
|
||||
};
|
||||
const cleared = stale.length && face.host.dropWaiting
|
||||
? Promise.resolve(face.host.dropWaiting()).then((gone) => {
|
||||
// What was taken out never answers: the newest of the stale ones,
|
||||
// because a run of this node goes to the front of the queue.
|
||||
const out = new Set(stale.slice(Math.max(0, stale.length - (Number(gone) || 0))));
|
||||
if (out.size) face.flying = face.flying.filter((other) => !out.has(other));
|
||||
}, () => {})
|
||||
: Promise.resolve();
|
||||
cleared.then(() => face.host.run(ask === "scope" ? scopeAsk(face) : ask)).then((queued) => {
|
||||
Promise.resolve(face.host.run(ask === "scope" ? scopeAsk(face) : ask)).then((queued) => {
|
||||
if (queued === false) {
|
||||
failed();
|
||||
return;
|
||||
@@ -1286,23 +1257,11 @@ function takeAll(face, index) {
|
||||
refreshHover(face);
|
||||
}
|
||||
|
||||
// Whether a typed name is taken away: what the sign in front of the field
|
||||
// was set to, or else what the tool does right now (Erase, or Ctrl held).
|
||||
function nameTakes(face) {
|
||||
return face.nameAway ?? face.away;
|
||||
}
|
||||
|
||||
// A typed name, as every thing of that name. "-face" takes it away and
|
||||
// "+face" adds it, whatever the sign says.
|
||||
function addName(face, text) {
|
||||
const typed = typedName(text, nameTakes(face));
|
||||
if (!typed.word || !face.pic || face.held) return false;
|
||||
const word = cleanWord(text);
|
||||
if (!word || !face.pic || face.held) return false;
|
||||
flushPending(face);
|
||||
if (!typed.add && !face.items.some((item) => item.op === 1)) {
|
||||
setNote(face, "Nothing is picked yet. Pick something first, then take a name away from it.", { life: 3200 });
|
||||
return false;
|
||||
}
|
||||
addItem(face, { t: "all", op: typed.add ? 1 : 0, w: typed.word });
|
||||
addItem(face, { t: "all", op: face.away ? 0 : 1, w: word });
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1453,19 +1412,9 @@ function syncTools(face) {
|
||||
face.lookButton.style.display = offer ? "" : "none";
|
||||
}
|
||||
if (face.nameField) {
|
||||
const off = !live || face.held > 0;
|
||||
const takes = nameTakes(face);
|
||||
face.nameField.disabled = off;
|
||||
face.nameSign.disabled = off;
|
||||
face.nameBox.classList.toggle("away", takes);
|
||||
face.nameSign.textContent = takes ? "\u2212" : "+";
|
||||
face.nameSign.title = takes
|
||||
? "A name you type is taken away from the mask. Click to add by name instead."
|
||||
: "A name you type is added to the mask. Click to take away by name instead.";
|
||||
face.nameField.placeholder = takes ? "take away by name" : "add by name";
|
||||
face.nameField.title = takes
|
||||
? "Type what to take out of the mask, like \"face\" or \"hair\", and press Enter. Every thing of that name is taken away."
|
||||
: "Type what to pick, like \"screen\" or \"earring\", and press Enter. Every thing of that name is taken. Start with a minus, like \"-face\", to take it away instead.";
|
||||
face.nameField.disabled = !live || face.held > 0;
|
||||
// A typed name is added, or taken away while the tool takes away.
|
||||
face.nameField.placeholder = face.away ? "\u2212 type a name" : "+ type a name";
|
||||
}
|
||||
if (face.newButton) face.newButton.disabled = !live || face.held > 0 || Boolean(face.fresh);
|
||||
// The switch shows what a press does right now: with Ctrl held, Paint
|
||||
@@ -1584,9 +1533,6 @@ function followOwnLoader(face, now = false) {
|
||||
}
|
||||
|
||||
const OTHER_PICTURE = "This is another picture. The picks made on the last one are not used.";
|
||||
// With New picture on keep picks, the node moves them onto it instead.
|
||||
const PICKS_CARRY = "This is another picture. Your picks carry over once the node looks at it or the workflow runs.";
|
||||
const otherPictureNote = (face) => (widgetByName(face.node, "new_picture")?.value === "start over" ? OTHER_PICTURE : PICKS_CARRY);
|
||||
|
||||
function dropPicture(face) {
|
||||
dropPending(face);
|
||||
@@ -1654,7 +1600,7 @@ function syncSource(face) {
|
||||
});
|
||||
readItems(face);
|
||||
face.itemNotes = null;
|
||||
if (face.other) setNote(face, otherPictureNote(face), { life: 6000 });
|
||||
if (face.other) setNote(face, OTHER_PICTURE, { life: 6000 });
|
||||
resolve(face);
|
||||
syncState(face);
|
||||
draw(face);
|
||||
@@ -1700,7 +1646,6 @@ function syncState(face) {
|
||||
|
||||
function setNote(face, text, { life = 0 } = {}) {
|
||||
clearTimeout(face.noteTimer);
|
||||
face.stopNote = false;
|
||||
face.noteEl.textContent = text;
|
||||
face.noteEl.classList.toggle("on", Boolean(text));
|
||||
if (text && life) face.noteTimer = setTimeout(() => setNote(face, ""), life);
|
||||
@@ -1759,15 +1704,7 @@ function adopt(face, entry) {
|
||||
|
||||
function show(face, entry, note, answered, { restored = false, own = false, interim = false, areas = null } = {}) {
|
||||
const before = face.pic;
|
||||
// A run that stopped left its message up. A result since says it is over.
|
||||
if (face.stopNote && !interim && !restored) setNote(face, "");
|
||||
adopt(face, entry);
|
||||
// Picks made on another picture that the node moved onto this one (New
|
||||
// picture: keep picks) come back moved. They are taken only while the
|
||||
// widget still holds the picks they were moved from: anything picked
|
||||
// since stays.
|
||||
const moved = movedTouches(note, face.touches?.value);
|
||||
if (moved !== null) writeTouches(face, moved);
|
||||
readItems(face);
|
||||
let items = face.items;
|
||||
let mine = Boolean(answered) && note.stamp === face.stamp;
|
||||
@@ -1848,7 +1785,7 @@ function show(face, entry, note, answered, { restored = false, own = false, inte
|
||||
readItems(face);
|
||||
face.itemNotes = notes;
|
||||
}
|
||||
if (face.other) setNote(face, otherPictureNote(face), { life: 6000 });
|
||||
if (face.other) setNote(face, OTHER_PICTURE, { life: 6000 });
|
||||
if (face.shownPieces !== entry.piecesTag) {
|
||||
face.shownPieces = entry.piecesTag;
|
||||
face.hover = -1;
|
||||
@@ -1999,31 +1936,12 @@ function pointOf(face, event) {
|
||||
return [clamp(x, 0, face.pic.width - 1), clamp(y, 0, face.pic.height - 1)];
|
||||
}
|
||||
|
||||
// The pieces that hold a whole pick, worked out once per change to the
|
||||
// picks and only when something is being taken away.
|
||||
function holdsOf(face) {
|
||||
const pic = face.pic;
|
||||
if (!pic?.pieces || !face.raw) return null;
|
||||
if (!face.holds || face.holds.length !== pic.pieces.list.length) {
|
||||
const areas = chipGroups(face.items).filter((chip) => !chip.away).map((chip) => chipArea(face, chip));
|
||||
face.holds = piecesHolding(pic.pieces.planes, pic.pieces.list.length, areas);
|
||||
}
|
||||
return face.holds;
|
||||
}
|
||||
|
||||
function pieceUnder(face, point, adding) {
|
||||
const pic = face.pic;
|
||||
if (!pic?.pieces || !point) return -1;
|
||||
const x = clamp(Math.floor(point[0] * pic.scale), 0, pic.pw - 1);
|
||||
const y = clamp(Math.floor(point[1] * pic.scale), 0, pic.ph - 1);
|
||||
const at = y * pic.pw + x;
|
||||
if (adding) return pieceAt(pic.pieces.planes, at, { sizes: pic.pieces.sizes, inside: face.inside, ranks: pic.pieces.ranks });
|
||||
// Taking away from a spot that is not picked: never a thing that holds a
|
||||
// whole pick somewhere else (the person, for the sweater picked on them).
|
||||
return pieceAt(pic.pieces.planes, at, {
|
||||
sizes: pic.pieces.sizes, inside: face.inside, adding, ranks: pic.pieces.ranks,
|
||||
here: face.raw?.[at] >= 0.5, holds: holdsOf(face),
|
||||
});
|
||||
return pieceAt(pic.pieces.planes, y * pic.pw + x, { sizes: pic.pieces.sizes, inside: face.inside, adding, ranks: pic.pieces.ranks });
|
||||
}
|
||||
|
||||
// The pixel of the small copy under a point of the picture.
|
||||
@@ -2393,8 +2311,7 @@ function syncLooking(face) {
|
||||
pill.classList.toggle("paused", paused);
|
||||
pill.style.setProperty("--done", `${total ? Math.round((done / total) * 100) : 0}%`);
|
||||
face.lookIcon.textContent = paused ? "\u25b6" : "\u275a\u275a";
|
||||
face.lookVerb.textContent = paused ? "Look on" : "Pause";
|
||||
face.lookWord.textContent = paused ? "paused" : "looking";
|
||||
face.lookWord.textContent = paused ? "Paused" : "Looking";
|
||||
face.lookCount.textContent = total ? `${done}/${total}` : "\u2026";
|
||||
const far = total ? ` ${done} of ${total}` : "";
|
||||
pill.title = paused
|
||||
@@ -2787,8 +2704,6 @@ function setSoft(face, soft) {
|
||||
|
||||
// Pick takes whole things; Paint and Erase are the brush.
|
||||
function setTool(face, tool) {
|
||||
// The sign in front of the name field follows the tool again.
|
||||
face.nameAway = null;
|
||||
if (!TOOLS.includes(tool)) return;
|
||||
face.tool = tool;
|
||||
face.snap = tool === "pick";
|
||||
@@ -2845,21 +2760,16 @@ export function mountTouchStage(node, host) {
|
||||
const bar = el("div", "ausboss-touch-bar");
|
||||
const chips = el("div", "ausboss-touch-chips");
|
||||
const chipList = el("span", "ausboss-touch-chiplist");
|
||||
// A name typed here picks every thing of that name, or takes it away:
|
||||
// the sign in front says which, and a press on it changes it.
|
||||
const nameBox = el("span", "ausboss-touch-namebox");
|
||||
const nameSign = el("button", "ausboss-touch-sign", "+");
|
||||
nameSign.type = "button";
|
||||
const nameField = el("input", "ausboss-touch-name");
|
||||
nameField.type = "text";
|
||||
nameField.placeholder = "add by name";
|
||||
nameField.placeholder = "+ type a name";
|
||||
nameField.maxLength = 60;
|
||||
nameField.spellcheck = false;
|
||||
nameBox.append(nameSign, nameField);
|
||||
nameField.title = "Type what to pick, like \"screen\" or \"earring\", and press Enter. Every thing of that name is taken.";
|
||||
const newButton = el("button", "ausboss-touch-new", "+ new");
|
||||
newButton.type = "button";
|
||||
newButton.title = "Start a new area: what you paint next gets a chip of its own, also where it touches another area.";
|
||||
chips.append(chipList, newButton, nameBox);
|
||||
chips.append(chipList, newButton, nameField);
|
||||
root.append(tools, stage, bar, chips);
|
||||
|
||||
const frame = el("div", "ausboss-touch-frame");
|
||||
@@ -2904,7 +2814,7 @@ export function mountTouchStage(node, host) {
|
||||
|
||||
const face = node.__ausbossTouch = {
|
||||
node, host, root, stage, frame, img, tint, lit, ink, path, dots, ringBack, ring, coreRing, dab, brushLabel, tag, hint, noteEl, abort,
|
||||
chips, chipList, newButton, nameField, nameBox, nameSign, nameAway: null, chipsShown: null,
|
||||
chips, chipList, newButton, nameField, chipsShown: null,
|
||||
flying: [],
|
||||
pendingTimer: 0,
|
||||
alive: true,
|
||||
@@ -3108,15 +3018,10 @@ export function mountTouchStage(node, host) {
|
||||
if (face.pic?.paused && !face.inFlight) resumeLook(face);
|
||||
else pauseLook(face);
|
||||
}, signal);
|
||||
// The press it takes comes first, as a button of its own look: "Pause"
|
||||
// while the node looks, "Look on" once it is paused.
|
||||
face.lookIcon = el("span", "icon");
|
||||
face.lookVerb = el("span", "verb");
|
||||
face.lookWord = el("span", "word");
|
||||
face.lookCount = el("span", "count");
|
||||
const lookKey = el("span", "key");
|
||||
lookKey.append(face.lookIcon, face.lookVerb);
|
||||
face.lookPill.append(lookKey, face.lookWord, face.lookCount);
|
||||
face.lookPill.append(face.lookIcon, face.lookWord, face.lookCount);
|
||||
face.lookPill.style.display = "none";
|
||||
// First in the line under the picture: what the node is doing with the
|
||||
// picture, then what is picked; the buttons that pick come after.
|
||||
@@ -3126,11 +3031,6 @@ export function mountTouchStage(node, host) {
|
||||
for (const type of ["keydown", "keyup", "keypress", "pointerdown", "mousedown", "dblclick"]) {
|
||||
chips.addEventListener(type, (event) => event.stopPropagation(), { signal });
|
||||
}
|
||||
nameSign.addEventListener("click", () => {
|
||||
face.nameAway = !nameTakes(face);
|
||||
syncTools(face);
|
||||
nameField.focus();
|
||||
}, { signal });
|
||||
nameField.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
@@ -3183,9 +3083,7 @@ export function mountTouchStage(node, host) {
|
||||
// The run stopped at this node with a message for the person.
|
||||
face.stopped = (message) => {
|
||||
settle(face);
|
||||
setNote(face, stopMessage(message));
|
||||
// It stays up until something else is said or the next result comes in.
|
||||
face.stopNote = true;
|
||||
setNote(face, String(message ?? ""));
|
||||
};
|
||||
// A setting on the node changed: the edge follows it.
|
||||
face.settingsChanged = () => {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { api } from "../../../scripts/api.js";
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { linkedNodeInfo, timingUnits as clipUnits } from "./timing_links.mjs";
|
||||
import { PANEL_LABELS } from "./panel_controls.mjs";
|
||||
import { hideInputsInDef, hideWidget } from "./widget_visibility.mjs";
|
||||
import { mountTransformTrim } from "./transform_trim.mjs";
|
||||
@@ -104,6 +103,7 @@ const trimInputDriven = (node, name) => node.inputs?.some(
|
||||
|
||||
const RESIZE_METHODS = ["lanczos", "area", "bicubic", "bilinear", "nearest-exact"];
|
||||
// The widest the control rows get on a big node; the picture takes the rest.
|
||||
const CONTROL_MAX_WIDTH = 460;
|
||||
const TRANSFORM_DEFAULTS = resetTransformValues(false);
|
||||
const CORE_IMAGE_PREVIEW_WIDGET = "$$canvas-image-preview";
|
||||
|
||||
@@ -150,7 +150,7 @@ function installStyles() {
|
||||
style.id = "ausboss-transform-styles";
|
||||
style.textContent = `
|
||||
.ausboss-transform-panel{display:flex;flex-direction:column;gap:8px;padding:8px;color:#ddd;font:12px system-ui;box-sizing:border-box;width:100%;height:100%;overflow:hidden}
|
||||
.ausboss-transform-panel>:not(.ausboss-transform-preview){width:100%;align-self:stretch;box-sizing:border-box}
|
||||
.ausboss-transform-panel>:not(.ausboss-transform-preview){width:100%;max-width:${CONTROL_MAX_WIDTH}px;align-self:center;box-sizing:border-box}
|
||||
.ausboss-transform-preview{width:100%;flex:1 1 180px;min-height:0;border:1px solid #50555b;border-radius:8px;background:#111;display:block;touch-action:none}
|
||||
.ausboss-transform-source{display:flex;flex-direction:column;gap:7px;flex:0 0 auto;padding:8px;border:1px solid rgba(0,184,174,.28);border-radius:8px;background:rgba(0,0,0,.24)}
|
||||
.ausboss-transform-source-image{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center}
|
||||
@@ -189,14 +189,13 @@ function installStyles() {
|
||||
.ausboss-transform-group-meta{min-width:0;overflow:hidden;text-overflow:ellipsis}
|
||||
.ausboss-transform-group-body{display:flex;flex-direction:column;gap:7px;padding:8px;box-sizing:border-box}
|
||||
.ausboss-transform-group-body[hidden]{display:none}
|
||||
.ausboss-transform-readout{flex:0 0 auto;margin:-5px 0 -3px;color:#c9d0d6;font:11px/14px system-ui;font-variant-numeric:tabular-nums;text-align:center;overflow:hidden;cursor:default;user-select:none}
|
||||
.ausboss-transform-readout{flex:0 0 auto;margin-top:-3px;color:#c9d0d6;font:11px/14px system-ui;font-variant-numeric:tabular-nums;text-align:center;overflow:hidden;cursor:default;user-select:none}
|
||||
.ausboss-transform-readout:empty{display:none}
|
||||
.ausboss-transform-readout span{color:#8ca8a5}.ausboss-transform-readout b{color:#fff;font-weight:600}
|
||||
.ausboss-transform-readout>div,.ausboss-transform-readout i{display:flex;align-items:center;justify-content:center;gap:3px;height:14px;white-space:nowrap}
|
||||
.ausboss-transform-readout .ausboss-transform-ellipsis{min-width:0;overflow:hidden;text-overflow:ellipsis;color:inherit}
|
||||
.ausboss-transform-readout b,.ausboss-transform-readout button{flex:none}
|
||||
.ausboss-transform-readout i{color:#ffc46b;font-style:normal}
|
||||
.ausboss-transform-readout i:empty{display:none}
|
||||
.ausboss-transform-readout em{color:#8ca8a5;font-style:normal}
|
||||
.ausboss-transform-readout em.note.ausboss-transform-ellipsis{color:#ffc46b}
|
||||
.ausboss-transform-readout button{margin:0 0 0 6px;height:14px;padding:0 6px;border:1px solid #6b5a33;border-radius:3px;background:#2a2417;color:#ffd79a;font:600 9.5px/12px system-ui;cursor:pointer;vertical-align:top}
|
||||
@@ -2321,11 +2320,6 @@ function buildTrim(state) {
|
||||
onTogglePlayback: () => timelineCommand(state, "play"),
|
||||
onSeek: (frame, settled) => scrubTo(state, frame, settled),
|
||||
onCommit: notifyAusbossChange,
|
||||
linkInfo: (name) => linkedNodeInfo(state.node, name),
|
||||
// H3 Prompt Writer reads this to say what H3 makes of the clip.
|
||||
publish: (timing) => { state.node.__ausbossClipTiming = timing; },
|
||||
units: () => clipUnits(),
|
||||
setUnits: (next) => { clipUnits(next); for (const view of state.trimViews) view.sync(); },
|
||||
});
|
||||
state.trimViews.add(control);
|
||||
return control.root;
|
||||
@@ -2346,7 +2340,6 @@ function setPlayhead(state, index) {
|
||||
// also snaps the widgets to the decoded frame.
|
||||
function scrubTo(state, index, settled) {
|
||||
if (state.playing) stopPlayback(state, false);
|
||||
state.pausedAt = null;
|
||||
const frame = setPlayhead(state, index);
|
||||
syncTimelineRange(state);
|
||||
if (settled) { void seekFrame(state); return; }
|
||||
@@ -2407,11 +2400,7 @@ function startPlayback(state) {
|
||||
const trim = [...state.trimViews][0];
|
||||
const { first, last } = trim.window();
|
||||
const head = clampFrame(value(state.node, "frame_index", 0), info);
|
||||
// Play shows the clip from its start, so what plays is what the run
|
||||
// keeps; only a resume right after a pause inside the clip carries on.
|
||||
const resume = state.pausedAt != null && state.pausedAt === head && head >= first && head < last;
|
||||
let next = resume ? head + 1 : first;
|
||||
state.pausedAt = null;
|
||||
let next = head < first || head >= last ? first : head + 1;
|
||||
state.playing = true;
|
||||
syncTimelineRange(state);
|
||||
const session = ++state.playbackSession;
|
||||
@@ -2432,7 +2421,6 @@ function startPlayback(state) {
|
||||
function stopPlayback(state, settle = true) {
|
||||
const wasPlaying = Boolean(state.playing);
|
||||
state.playing = false;
|
||||
if (wasPlaying) state.pausedAt = clampFrame(value(state.node, "frame_index", 0), clipInfo(state.metadata));
|
||||
state.playbackSession = (state.playbackSession || 0) + 1; // orphan in-flight ticks
|
||||
if (state.playbackTimer) clearTimeout(state.playbackTimer);
|
||||
state.playbackTimer = null;
|
||||
|
||||
+169
-390
@@ -32,7 +32,7 @@ import {
|
||||
framesThrough,
|
||||
keyboardStep,
|
||||
lastFrameFor,
|
||||
latestInFor,
|
||||
latestFirstFor,
|
||||
railZone,
|
||||
setTrimFrame,
|
||||
slideRange,
|
||||
@@ -41,7 +41,7 @@ import {
|
||||
windowSeconds,
|
||||
} from "./timeline_math.mjs";
|
||||
|
||||
const CSS_ID = "ausboss-transform-trim-css-v5";
|
||||
const CSS_ID = "ausboss-transform-trim-css-v4";
|
||||
const HANDLE_HIT_PX = 9;
|
||||
// Connected inputs that set the length themselves, in the backend's order of
|
||||
// precedence: fixed_frames replaces the window, a cap replaces the Length.
|
||||
@@ -101,25 +101,6 @@ function installCss() {
|
||||
.ausboss-transform-trim-reset{flex:none;height:18px;box-sizing:border-box;border:1px solid #2c4d4b;border-radius:4px;background:#1b2627;color:#cadddb;font:600 10px/16px system-ui;cursor:pointer;padding:0 8px;white-space:nowrap}
|
||||
.ausboss-transform-trim-reset:hover{border-color:#8fa3a1;color:#fff}
|
||||
.ausboss-transform-trim-reset:disabled{opacity:.45;cursor:not-allowed}
|
||||
.ausboss-transform-trim-span.is-room{background:repeating-linear-gradient(90deg,rgba(0,180,170,.38) 0 6px,rgba(0,180,170,.1) 6px 12px)}
|
||||
.ausboss-transform-trim-line .ausboss-transform-trim-readout{text-align:left}
|
||||
.ausboss-transform-trim-inside{color:#45d6cb}
|
||||
.ausboss-transform-trim-outside{color:#8ca8a5}
|
||||
.ausboss-transform-trim-clip{flex:1 1 0;min-width:0;color:#45d6cb;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-variant-numeric:tabular-nums}
|
||||
.ausboss-transform-trim-fields{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;min-width:0}
|
||||
.ausboss-transform-trim-field{display:flex;flex-direction:column;gap:3px;min-width:0}
|
||||
.ausboss-transform-trim-field .ausboss-scrub{width:100%;box-sizing:border-box}
|
||||
.ausboss-transform-trim-field-label{color:#cadddb;display:flex;align-items:center;gap:6px;min-width:0}
|
||||
.ausboss-transform-trim-go[hidden]{display:none}
|
||||
.ausboss-transform-trim-sub{color:#8ca8a5;font-size:10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-variant-numeric:tabular-nums;min-height:12px}
|
||||
.ausboss-transform-trim-link{color:#9fe3dc;font-size:10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.ausboss-transform-trim-link[hidden]{display:none}
|
||||
.ausboss-transform-trim-go{border:0;background:transparent;padding:0;color:#45d6cb;font:600 10px system-ui;text-decoration:underline;cursor:pointer}
|
||||
.ausboss-transform-trim-note{display:flex;align-items:center;gap:6px;flex-wrap:wrap;color:#9fe3dc;font-size:11px;line-height:1.35}
|
||||
.ausboss-transform-trim-note[hidden]{display:none}
|
||||
.ausboss-transform-trim-note>span{flex:1 1 180px;min-width:0}
|
||||
.ausboss-transform-trim-note.warn{background:#3a2a10;box-shadow:inset 3px 0 0 #e0a040;border-radius:6px;padding:6px 8px;color:#ffdca8}
|
||||
.ausboss-transform-trim-note button[hidden]{display:none}
|
||||
`;
|
||||
document.head.append(style);
|
||||
}
|
||||
@@ -132,8 +113,6 @@ function el(tag, className = "", text = "") {
|
||||
}
|
||||
|
||||
const pct = (fraction) => `${(fraction * 100).toFixed(3)}%`;
|
||||
// Seconds for people: at most two decimals (1, 1.5, 2.17).
|
||||
const secondsText = (value) => String(Number((Number(value) || 0).toFixed(2)));
|
||||
|
||||
// options:
|
||||
// get(name, fallback) / set(name, value) widget access
|
||||
@@ -147,12 +126,7 @@ const secondsText = (value) => String(Number((Number(value) || 0).toFixed(2)));
|
||||
// (the clip node) or playhead only
|
||||
// onSeek(frame, settled) the playhead moved; settled on release
|
||||
// onCommit() a stored value settled (undo point)
|
||||
// linkInfo(name) {title, go()} of the node feeding
|
||||
// a linked input, or null
|
||||
// publish(timing) the clip's {frames, startSeconds,
|
||||
// endSeconds, roomFrames}, or null
|
||||
// units() / setUnits(units) "s" (seconds) or "f" (frames)
|
||||
export function mountTransformTrim({ get, set, has = () => true, driven = () => false, number = (name, fallback) => get(name, fallback), outputRate, metadata, trim = true, isPlaying, onTogglePlayback, onSeek, onCommit, linkInfo = () => null, publish, units: getUnits = () => "s", setUnits = () => {}, play: showPlay = true }) {
|
||||
export function mountTransformTrim({ get, set, has = () => true, driven = () => false, number = (name, fallback) => get(name, fallback), outputRate, metadata, trim = true, isPlaying, onTogglePlayback, onSeek, onCommit }) {
|
||||
installCss();
|
||||
const root = el("div", "ausboss-transform-trim");
|
||||
const rail = el("div", "ausboss-transform-trim-rail");
|
||||
@@ -170,9 +144,7 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
|
||||
const play = el("button", "ausboss-transform-trim-play");
|
||||
play.type = "button";
|
||||
play.addEventListener("click", onTogglePlayback);
|
||||
// A host with its own player (Load Video) leaves out the Play button.
|
||||
if (showPlay) transport.append(play);
|
||||
transport.append(rail);
|
||||
transport.append(play, rail);
|
||||
const info = () => clipInfo(metadata());
|
||||
const everyNth = () => Math.max(1, Math.trunc(Number(number("every_nth", get("every_nth", 1))) || 1));
|
||||
const snapRule = () => String(get("frame_snap", "free"));
|
||||
@@ -188,10 +160,11 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
|
||||
return number(name, get(name, 0)) ?? get(name, 0);
|
||||
};
|
||||
const countAtRunTime = () => COUNT_INPUTS.some((name) => driven(name) && number(name, null) == null);
|
||||
const outFps = () => (outputRate ? outputRate() : info().fps / everyNth());
|
||||
const planValues = () => {
|
||||
const plan = () => {
|
||||
if (!trim) return null;
|
||||
const clip = info();
|
||||
const wired = wiredBy();
|
||||
return {
|
||||
return clipLengthPlan(clip, {
|
||||
start: boundSeconds("start"),
|
||||
end: boundSeconds("end"),
|
||||
everyNth: everyNth(),
|
||||
@@ -200,48 +173,9 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
|
||||
fixedFrames: driven("fixed_frames") ? 0 : get("fixed_frames", 0),
|
||||
wired,
|
||||
wiredFrames: wired ? number(wired, null) : null,
|
||||
outputFps: outputRate ? outputRate() : info().fps,
|
||||
outputFps: outputRate ? outputRate() : clip.fps,
|
||||
resampled: driven("force_rate"),
|
||||
};
|
||||
};
|
||||
const plan = () => (trim ? clipLengthPlan(info(), planValues()) : null);
|
||||
// Output frames that fit between IN and the end of the video: the most a
|
||||
// Duration can be from here.
|
||||
const roomFrames = () => {
|
||||
if (!trim) return null;
|
||||
const room = clipLengthPlan(info(), { ...planValues(), maxFrames: 0, fixedFrames: 0, wired: null, wiredFrames: null });
|
||||
return room.frames ?? null;
|
||||
};
|
||||
// Where the clip ends, in source seconds (exclusive), when it is known.
|
||||
const endSecondsOf = (current) => {
|
||||
const clip = info();
|
||||
if (current?.endSeconds != null) return current.endSeconds;
|
||||
if (current?.last == null || !clip.fps) return null;
|
||||
return (current.last + 1) / clip.fps;
|
||||
};
|
||||
const endDriven = () => driven("end_frame") || driven("end_seconds");
|
||||
// The latest IN that keeps the whole Duration. With a connected rate the
|
||||
// count is in output frames, so the source grid would stop IN far too soon
|
||||
// (the 2.25 face stopped a 240-frame Length at IN 7 on a 247-frame clip).
|
||||
const latestIn = (current) => {
|
||||
const clip = info();
|
||||
if (driven("force_rate")) {
|
||||
if (current.latestStart == null) return clip.count - 1;
|
||||
return current.latestStart > 0 ? current.latestStart : clip.count - 1;
|
||||
}
|
||||
return latestInFor(clip, current.requested ?? get("max_frames", 1), everyNth());
|
||||
};
|
||||
// A Duration as long as the whole video only caps it: IN moves freely and
|
||||
// the clip runs to the end.
|
||||
const durationFills = (current) => {
|
||||
if (current.mode !== "length" || current.requested == null) return false;
|
||||
const whole = roomFromStart();
|
||||
return whole != null && current.requested >= whole;
|
||||
};
|
||||
const roomFromStart = () => {
|
||||
if (!trim) return null;
|
||||
const room = clipLengthPlan(info(), { ...planValues(), start: 0, maxFrames: 0, fixedFrames: 0, wired: null, wiredFrames: null });
|
||||
return room.frames ?? null;
|
||||
});
|
||||
};
|
||||
const currentWindow = () => {
|
||||
const clip = info();
|
||||
@@ -251,8 +185,7 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
|
||||
};
|
||||
const playheadFrame = () => clampFrame(get("frame_index", 0), info());
|
||||
const controls = {};
|
||||
// A short line under the fields after a drag stops at the video's end.
|
||||
let stopNote = "";
|
||||
let syncLength = () => {};
|
||||
// IN is locked by a connected bound; OUT by a connected bound in free
|
||||
// trim, and always when a connected input sets the length.
|
||||
const locked = (edge) => {
|
||||
@@ -263,10 +196,10 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
|
||||
return false;
|
||||
};
|
||||
const lockTip = (edge) => edge === "start"
|
||||
? "The starting frame is supplied by a connected input. Disconnect it to set Start here."
|
||||
? "The starting frame is supplied by a connected input. Disconnect it to edit IN here."
|
||||
: wiredBy()
|
||||
? `The connected ${wiredBy()} input sets the length, so the clip ends where it says. Disconnect it to set Duration or Ends at here.`
|
||||
: "The ending frame is supplied by a connected input. Disconnect it to set Ends at here.";
|
||||
? `The connected ${wiredBy()} input sets the length, so the clip ends where it says. Disconnect it to use OUT or Length.`
|
||||
: "The ending frame is supplied by a connected input. Disconnect it to edit OUT here.";
|
||||
const disableControl = (control, disabled, tip) => {
|
||||
if (!control) return;
|
||||
control.root.style.opacity = disabled ? ".45" : "";
|
||||
@@ -284,16 +217,7 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
|
||||
const writeEnd = (first, last) => set("end_seconds", windowSeconds(info(), first, last).end_seconds);
|
||||
// An older face's Fixed frames reads as a Length; the first edit makes it
|
||||
// one, keeping the window where the fixed count had placed it.
|
||||
// The face has no modes: a clip is a Start and a Duration. A window saved
|
||||
// as IN -> OUT (Length off) becomes a Duration of the same frames on its
|
||||
// first edit, so the run outputs exactly what it did. A connected end
|
||||
// keeps the window as it is.
|
||||
const adoptLength = (current) => {
|
||||
if (current.mode === "free" && !endDriven() && current.frames != null) {
|
||||
set("max_frames", Math.max(1, current.frames));
|
||||
set("end_seconds", 0);
|
||||
return plan();
|
||||
}
|
||||
if (current.mode !== "fixed") return current;
|
||||
set("fixed_frames", 0);
|
||||
set("max_frames", Math.max(1, current.requested ?? current.frames ?? 1));
|
||||
@@ -311,14 +235,8 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
|
||||
let parked;
|
||||
if (edge === "start") {
|
||||
if (current.mode === "length") {
|
||||
// A Duration drags the whole clip, stopping where its end meets the
|
||||
// video's end; a Duration past the video's end only caps it, so IN
|
||||
// moves freely.
|
||||
const latest = latestIn(current);
|
||||
parked = Math.max(0, Math.min(clampFrame(frame, clip), latest));
|
||||
stopNote = clampFrame(frame, clip) > latest
|
||||
? `Start stops at ${secondsText(parked / clip.fps)} s so all ${current.requested} frames fit.`
|
||||
: "";
|
||||
// A Length drags the whole window, stopping where OUT meets the end.
|
||||
parked = Math.max(0, Math.min(clampFrame(frame, clip), latestFirstFor(clip, current.requested ?? get("max_frames", 1), nth)));
|
||||
set("end_seconds", 0);
|
||||
} else if (current.mode === "wired" && current.latestStart != null && !countAtRunTime()) {
|
||||
parked = Math.min(clampFrame(frame, clip), current.latestStart);
|
||||
@@ -328,18 +246,11 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
|
||||
writeStart(parked);
|
||||
} else {
|
||||
const target = Math.max(current.first, clampFrame(frame, clip));
|
||||
stopNote = "";
|
||||
let frames = framesThrough(current.first, target, nth, snapRule());
|
||||
if (driven("force_rate") && outFps() > 0) {
|
||||
// Output frames at the linked rate from IN to the handle's boundary.
|
||||
frames = snapToValid(Math.max(1, Math.round(((target + 1) / clip.fps - boundSeconds("start")) * outFps())), snapRule());
|
||||
const room = roomFrames();
|
||||
if (room != null) frames = Math.min(frames, Math.max(1, room));
|
||||
}
|
||||
const frames = framesThrough(current.first, target, nth, snapRule());
|
||||
if (current.mode === "length") {
|
||||
set("max_frames", frames);
|
||||
set("end_seconds", 0);
|
||||
parked = plan()?.last ?? Math.min(clip.count - 1, lastFrameFor(current.first, frames, nth));
|
||||
parked = Math.min(clip.count - 1, lastFrameFor(current.first, frames, nth));
|
||||
} else {
|
||||
parked = driven("force_rate") ? target : lastFrameFor(current.first, frames, nth);
|
||||
writeEnd(current.first, parked);
|
||||
@@ -351,8 +262,7 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
|
||||
// The grip slides the kept part: a Length moves with IN (OUT follows), a
|
||||
// free window keeps its span and both edges move.
|
||||
const canSlide = () => {
|
||||
// With a connected rate, IN itself slides the clip at its Duration.
|
||||
if (!trim || locked("start") || driven("force_rate")) return false;
|
||||
if (!trim || locked("start")) return false;
|
||||
const current = plan();
|
||||
if (!current || !["length", "fixed", "free"].includes(current.mode)) return false;
|
||||
if (current.mode === "free" && locked("end")) return false;
|
||||
@@ -374,6 +284,26 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
|
||||
}
|
||||
moveEdge("start", first, settled);
|
||||
};
|
||||
// Length on keeps what the rail shows now as the count; off turns the
|
||||
// Length into an OUT at the same frame. Either way nothing moves.
|
||||
const setLength = (on) => {
|
||||
const current = plan();
|
||||
if (!current || current.mode === "wired" || (on === (current.mode !== "free"))) return;
|
||||
if (on) {
|
||||
const frames = current.frames ?? framesThrough(current.first, current.windowLast, everyNth(), snapRule());
|
||||
set("max_frames", Math.max(1, frames));
|
||||
set("end_seconds", 0);
|
||||
} else {
|
||||
const last = current.last ?? current.windowLast;
|
||||
writeStart(current.first);
|
||||
writeEnd(current.first, last);
|
||||
set("max_frames", 0);
|
||||
if (!driven("fixed_frames")) set("fixed_frames", 0);
|
||||
}
|
||||
sync();
|
||||
onCommit?.();
|
||||
};
|
||||
|
||||
const readout = el("span", "ausboss-transform-trim-readout");
|
||||
const summary = el("div", "ausboss-transform-trim-summary");
|
||||
|
||||
@@ -381,7 +311,7 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
|
||||
const clip = info();
|
||||
const playing = isPlaying();
|
||||
play.setAttribute("aria-label", playing ? "Pause" : "Play");
|
||||
play.title = playing ? "Pause on this frame" : trim ? "Play the clip from its start" : "Play the video to pick a frame";
|
||||
play.title = playing ? "Pause on this frame" : trim ? "Play the selected clip" : "Play the video to pick a frame";
|
||||
play.classList.toggle("is-playing", playing);
|
||||
play.disabled = !clip.count;
|
||||
const head = playheadFrame();
|
||||
@@ -389,41 +319,33 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
|
||||
playhead.style.left = pct(fractionOfFrame(head, clip, "center"));
|
||||
playhead.style.visibility = clip.count ? "" : "hidden";
|
||||
readout.replaceChildren();
|
||||
const current = trim ? plan() : null;
|
||||
if (clip.count) {
|
||||
readout.append(document.createTextNode("Preview "), el("b", "", `${secondsText(frameTime(head, clip))} s`), document.createTextNode(` · src fr ${head}`));
|
||||
if (trim) {
|
||||
const end = countAtRunTime() ? null : current.last;
|
||||
const inside = head >= current.first && (end == null || head <= end);
|
||||
readout.append(el("span", inside ? "ausboss-transform-trim-inside" : "ausboss-transform-trim-outside", inside ? " · in the clip" : " · outside the clip"));
|
||||
}
|
||||
readout.title = `The picture shows frame ${head} of ${clip.count}, ${frameTime(head, clip).toFixed(2)} seconds into the video. Press or drag the bar to look at another frame${trim ? "; Use as start starts the clip here." : "; this is the frame the node outputs."}`;
|
||||
readout.append(el("b", "", `fr ${head}`), document.createTextNode(` · ${formatTimecode(frameTime(head, clip))}`));
|
||||
readout.title = `Playhead: frame ${head} of ${clip.count} at ${frameTime(head, clip).toFixed(3)} s. Press or drag the rail to scrub; ${trim ? "the trim handles carry it with them." : "this is the frame the node outputs."}`;
|
||||
}
|
||||
controls.frame?.set(head);
|
||||
if (!trim) return;
|
||||
const current = plan();
|
||||
const wired = wiredBy();
|
||||
const unknown = countAtRunTime();
|
||||
const hasOut = current.last != null && current.mode !== "wired" && !unknown;
|
||||
const hasOut = current.last != null && current.mode !== "wired";
|
||||
const outFrame = current.last ?? current.windowLast;
|
||||
const startFraction = fractionOfFrame(current.first, clip, "start");
|
||||
const endSec = endSecondsOf(current);
|
||||
const endFraction = endSec != null && !unknown
|
||||
? Math.max(startFraction, Math.min(1, endSec * clip.fps / clip.count))
|
||||
: fractionOfFrame(outFrame, clip, "end");
|
||||
const endFraction = fractionOfFrame(outFrame, clip, "end");
|
||||
// Dim: frames the free window holds but the run drops (every nth, snap).
|
||||
const tailFraction = current.mode === "free" ? fractionOfFrame(current.windowLast, clip, "end") : endFraction;
|
||||
span.style.left = pct(startFraction);
|
||||
span.classList.toggle("is-room", unknown || current.last == null);
|
||||
// A length only the run knows: the dim part is the room the clip has.
|
||||
span.style.width = pct(unknown || current.last == null ? 1 - startFraction : Math.max(0, tailFraction - startFraction));
|
||||
span.style.width = pct(current.last == null && current.mode !== "free" ? 0 : Math.max(0, tailFraction - startFraction));
|
||||
kept.style.left = pct(startFraction);
|
||||
kept.style.width = current.last == null || unknown ? "0%" : pct(Math.max(0, endFraction - startFraction));
|
||||
span.title = unknown || current.last == null ? "Room for the clip: its length is set when the graph runs." : "";
|
||||
const fills = lengthFillsClip(clip, current, everyNth());
|
||||
const railWidth = rail.getBoundingClientRect().width || 0;
|
||||
const keptWidth = Math.max(0, endFraction - startFraction) * railWidth;
|
||||
grip.hidden = !canSlide() || unknown || (railWidth > 0 && keptWidth < 34);
|
||||
grip.style.left = pct((startFraction + endFraction) / 2);
|
||||
grip.title = "Drag to slide the clip; its Duration stays.";
|
||||
grip.title = current.mode === "free"
|
||||
? "Drag to slide the kept part: IN and OUT move together."
|
||||
: "Drag to slide the clip: OUT follows at the Length.";
|
||||
for (const edge of ["start", "end"]) {
|
||||
const handle = handles[edge];
|
||||
const frame = edge === "start" ? current.first : outFrame;
|
||||
@@ -436,9 +358,10 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
|
||||
handle.style.cursor = isLocked ? "not-allowed" : "";
|
||||
handle.title = isLocked ? lockTip(edge)
|
||||
: edge === "start"
|
||||
? durationFills(current) ? "Drag to start later. The Duration is longer than the video, so the clip runs to its end."
|
||||
: "Drag to move the clip; its Duration stays. Shift + arrow moves one frame."
|
||||
: "Drag to change the Duration; the start stays.";
|
||||
? current.mode === "free" ? "Drag IN to trim; Shift + arrow moves one frame."
|
||||
: fills ? "The Length is the whole clip, so IN has nowhere to go. Shorten the Length to move IN."
|
||||
: "Drag IN to move the clip; OUT follows at the Length. Shift + arrow moves one frame."
|
||||
: current.mode === "free" ? "Drag OUT to trim; it lands on the last frame the run keeps." : "Drag OUT to change the Length; IN stays.";
|
||||
handle.setAttribute("aria-valuemin", "0");
|
||||
const maxFrame = edge === "start" && current.mode === "wired" && !unknown
|
||||
? current.latestStart ?? current.windowLast : Math.max(0, clip.count - 1);
|
||||
@@ -446,16 +369,16 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
|
||||
handle.setAttribute("aria-valuenow", String(frame));
|
||||
handle.setAttribute("aria-valuetext", `frame ${frame}, ${formatTimecode(frameTime(frame, clip))}`);
|
||||
}
|
||||
if (useStart) {
|
||||
useStart.disabled = !clip.count || locked("start");
|
||||
useStart.title = locked("start") ? lockTip("start") : "Start the clip at the frame on the stage. The Duration stays.";
|
||||
}
|
||||
if (clip.count) syncFields(clip, current, wired, unknown);
|
||||
controls.start_seconds?.set(current.first);
|
||||
controls.end_seconds?.set(outFrame);
|
||||
disableControl(controls.start_seconds, locked("start"), lockTip("start"));
|
||||
disableControl(controls.end_seconds, locked("end") || !hasOut, lockTip("end"));
|
||||
syncLength(current, wired);
|
||||
if (controls.reset) {
|
||||
const free = current.mode !== "wired";
|
||||
controls.reset.textContent = free ? "Whole video" : "To start";
|
||||
controls.reset.title = free ? `Use the whole video: start at 0 with no Duration limit. Keeps Every nth${has("frame_snap") ? " and Frames for" : ""}.` : "Move the start to the beginning of the video; the linked length stays.";
|
||||
controls.reset.disabled = locked("start") && !free;
|
||||
const free = current.mode === "free";
|
||||
controls.reset.textContent = free ? "Full clip" : "To start";
|
||||
controls.reset.title = free ? "Reset IN/OUT to the full source. Keeps Every nth and Frames for." : "Move IN to the start of the source; the length stays.";
|
||||
controls.reset.disabled = !free && locked("start");
|
||||
}
|
||||
controls.every_nth?.set(get("every_nth", 1));
|
||||
disableControl(controls.every_nth, driven("every_nth"), "Every nth is supplied by a connected input.");
|
||||
@@ -463,21 +386,50 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
|
||||
controls.frame_snap.value = snapRule();
|
||||
const exact = current.mode === "fixed" || (current.mode === "wired" && wired === "fixed_frames");
|
||||
controls.frame_snap.disabled = exact || driven("frame_snap");
|
||||
controls.frame_snap.title = exact ? "An exact fixed_frames count is used as it is; this does not apply." : "Keep a frame count the video model takes: LTX wants 8n+1 (49, 97, 121), Wan 4n+1. The Duration steps to those counts. Any keeps every frame.";
|
||||
controls.frame_snap.title = exact ? "An exact fixed_frames count is used as it is; this does not apply." : "Keep a frame count the video model takes: LTX wants 8n+1 (49, 97, 121), Wan 4n+1. OUT and Length step to those counts. Any keeps every frame.";
|
||||
}
|
||||
syncSummary(clip);
|
||||
syncSummary(clip, current, wired, unknown);
|
||||
};
|
||||
|
||||
const syncSummary = (clip) => {
|
||||
const syncSummary = (clip, current, wired, unknown) => {
|
||||
if (!clip.count) {
|
||||
summary.textContent = "Choose a source to set the clip";
|
||||
summary.textContent = "Choose a source to set the clip window";
|
||||
summary.title = "";
|
||||
return;
|
||||
}
|
||||
const rate = outputRate?.();
|
||||
summary.textContent = `Source ${formatFps(clip.fps)} fps · ${clip.count} frames · ends at ${secondsText(clip.duration || clip.count / clip.fps)} s · clip out at ${rate == null ? "the rate set at run time" : `${formatFps(rate)} fps`}`;
|
||||
summary.title = "Start and Ends at are places in the source video. Duration counts the frames the clip sends on, at the output rate.";
|
||||
if (trim) rail.title = [clipLine?.textContent, summary.textContent, readout.textContent].filter(Boolean).join("\n");
|
||||
const fps = `Source ${formatFps(clip.fps)} fps → Output ${rate == null ? "rate at run time" : `${formatFps(rate)} fps`}`;
|
||||
if (current.mode === "wired") {
|
||||
summary.textContent = current.frames == null ? `${fps} · length from ${wired} at run time` : `${fps} · ${current.frames} frames from ${wired}`;
|
||||
summary.title = `The connected ${wired} input sets the length, so only IN is set here. Disconnect it to use OUT or a Length.`;
|
||||
return;
|
||||
}
|
||||
if (unknown || current.frames == null) {
|
||||
summary.textContent = `${fps} · frame count at run time`;
|
||||
summary.title = "IN, OUT and the playhead refer to source frames. A connected input decides the exact frame count when the workflow runs. Connect the fps output to the next video node's fps input.";
|
||||
return;
|
||||
}
|
||||
const from = formatTimecode(frameTime(current.first, clip));
|
||||
const to = formatTimecode((current.last + 1) / clip.fps);
|
||||
if (current.mode === "fixed") {
|
||||
summary.textContent = current.tooLong
|
||||
? `Fixed length needs more than the source's ${clip.duration.toFixed(3)}s`
|
||||
: `${fps} · exactly ${current.frames} frames · ${from} → ${to}`;
|
||||
summary.title = "An older Fixed frames value: an exact count from IN. Any change here turns it into a Length.";
|
||||
return;
|
||||
}
|
||||
const total = current.windowLast - current.first + 1;
|
||||
const count = current.mode === "length"
|
||||
? current.truncated ? `${current.frames} of ${current.requested} frames, source ends` : `${current.frames} frames`
|
||||
: current.frames < total ? `${current.frames} of ${total} frames` : `${current.frames} frames`;
|
||||
summary.textContent = `${fps} · ${count} · ${from} → ${to}`;
|
||||
summary.title = current.mode === "length"
|
||||
? current.truncated
|
||||
? `The source ends ${current.frames} frames after IN, before the Length of ${current.requested}. Move IN earlier or shorten the Length.`
|
||||
: "Length keeps OUT this many output frames after IN; drag IN to move the clip, OUT to change the Length."
|
||||
: current.frames < total
|
||||
? `The window holds ${total} frames; every nth and the snap rule keep ${current.frames}, ending at frame ${current.last}, where OUT sits. The dim part is dropped.`
|
||||
: "Frames the run outputs, at the fps the node reports.";
|
||||
};
|
||||
|
||||
// --- rail gestures --------------------------------------------------------
|
||||
@@ -579,19 +531,21 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
|
||||
}
|
||||
|
||||
// --- rows -----------------------------------------------------------------
|
||||
// The clip node: Preview (the playhead, and Use as start), the clip in
|
||||
// words with a Seconds | Frames switch, then Start, Duration and Ends at.
|
||||
// Start and Ends at are positions in the source video; Duration counts the
|
||||
// frames the clip sends on, at the output rate. No modes: dragging IN
|
||||
// slides the clip, dragging OUT or typing a Duration or an end changes the
|
||||
// Duration.
|
||||
const previewRow = el("div", "ausboss-transform-trim-line");
|
||||
let useStart = null;
|
||||
const timeRow = el("div", "ausboss-transform-trim-line");
|
||||
if (trim) {
|
||||
useStart = el("button", "ausboss-transform-trim-reset", "Use as start");
|
||||
useStart.type = "button";
|
||||
useStart.title = "Start the clip at the frame on the stage. The Duration stays.";
|
||||
useStart.addEventListener("click", () => moveEdge("start", playheadFrame(), true));
|
||||
for (const [name, caption, edge] of [["start_seconds", "IN", "start"], ["end_seconds", "OUT", "end"]]) {
|
||||
const label = el("label");
|
||||
label.append(el("span", "ausboss-transform-trim-caption", caption));
|
||||
controls[name] = makeScrubInput({
|
||||
value: 0, min: 0, max: 10000000, step: 1, decimals: 0,
|
||||
title: edge === "start" ? "IN frame: the first frame the run keeps (stored as start_seconds)." : "OUT frame: the last frame the run keeps. With Length on it follows IN; typing it changes the Length.",
|
||||
onChange: (frame) => moveEdge(edge, frame, false),
|
||||
onSettle: () => { const window = currentWindow(); seek(edge === "start" ? window.first : window.last, true); onCommit?.(); },
|
||||
});
|
||||
label.append(controls[name].root);
|
||||
timeRow.append(label);
|
||||
if (edge === "start") timeRow.append(readout);
|
||||
}
|
||||
} else {
|
||||
const label = el("label");
|
||||
label.append(el("span", "ausboss-transform-trim-caption", "FRAME"));
|
||||
@@ -602,237 +556,67 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
|
||||
onSettle: () => seek(playheadFrame(), true),
|
||||
});
|
||||
label.append(controls.frame.root);
|
||||
previewRow.append(label, readout);
|
||||
timeRow.append(label, readout);
|
||||
}
|
||||
root.append(transport);
|
||||
if (!trim) root.append(previewRow);
|
||||
root.append(transport, timeRow);
|
||||
|
||||
const fields = {};
|
||||
let clipLine = null;
|
||||
let unitPill = null;
|
||||
let noteRow = null;
|
||||
let noteText = null;
|
||||
const noteButtons = [];
|
||||
if (trim) {
|
||||
const clipRow = el("div", "ausboss-transform-trim-line");
|
||||
clipLine = el("span", "ausboss-transform-trim-clip");
|
||||
unitPill = el("div", "ausboss-transform-trim-pill");
|
||||
for (const [key, words, tip] of [["s", "s", "Show times in seconds."], ["f", "fr", "Show times in frames: source frames for Start and Ends at, clip frames for Duration."]]) {
|
||||
const button = el("button", "", words);
|
||||
button.type = "button";
|
||||
button.dataset.units = key;
|
||||
button.title = tip;
|
||||
button.addEventListener("click", () => { setUnits(key); sync(); });
|
||||
unitPill.append(button);
|
||||
}
|
||||
|
||||
const grid = el("div", "ausboss-transform-trim-fields");
|
||||
const toFrames = {
|
||||
start: (value) => (getUnits() === "f" ? Math.round(value) : Math.round(value * info().fps)),
|
||||
// Length: off, OUT ends the clip; on, a frame count from IN (max_frames,
|
||||
// end left open), so OUT follows IN and the count survives a new source.
|
||||
if (trim && has("max_frames")) {
|
||||
const lengthRow = el("div", "ausboss-transform-trim-line wrap");
|
||||
const label = el("label", "", "Length");
|
||||
const pill = el("div", "ausboss-transform-trim-pill");
|
||||
const off = el("button", "", "off");
|
||||
const on = el("button", "", "on");
|
||||
off.type = on.type = "button";
|
||||
off.title = "OUT ends the clip: drag both handles freely.";
|
||||
on.title = "Set the clip by a frame count from IN: OUT follows IN, and the count stays when you swap the video.";
|
||||
off.addEventListener("click", () => setLength(false));
|
||||
on.addEventListener("click", () => setLength(true));
|
||||
pill.append(off, on);
|
||||
const hint = el("span", "ausboss-transform-trim-hint");
|
||||
const count = makeScrubInput({ value: 1, min: 1, max: 100000, step: 1, decimals: 0, unit: "fr", width: 72,
|
||||
title: "Output frames from IN. Under a snap rule it steps to the counts the model keeps (97, 105, ... for 8n+1).",
|
||||
onChange: (next) => {
|
||||
const current = adoptLength(plan());
|
||||
if (current.mode !== "length") { sync(); return; }
|
||||
const was = current.requested ?? get("max_frames", 1);
|
||||
set("max_frames", snapToValid(next, snapRule(), Math.sign(next - was)));
|
||||
set("end_seconds", 0);
|
||||
sync();
|
||||
},
|
||||
onSettle: () => { const window = currentWindow(); seek(window.last, true); onCommit?.(); },
|
||||
});
|
||||
label.append(pill, count.root);
|
||||
lengthRow.append(label, hint);
|
||||
root.append(lengthRow);
|
||||
syncLength = (current, wired) => {
|
||||
const active = current.mode !== "free";
|
||||
const blocked = current.mode === "wired";
|
||||
off.classList.toggle("on", !active);
|
||||
on.classList.toggle("on", active);
|
||||
off.setAttribute("aria-pressed", String(!active));
|
||||
on.setAttribute("aria-pressed", String(active));
|
||||
pill.classList.toggle("is-disabled", blocked);
|
||||
off.disabled = on.disabled = blocked;
|
||||
pill.title = blocked ? lockTip("end") : "";
|
||||
count.root.style.display = active ? "" : "none";
|
||||
const step = snapStep(snapRule());
|
||||
count.setStep(step, step);
|
||||
count.set(blocked ? (current.requested ?? current.frames ?? 0) : (current.requested ?? get("max_frames", 1)));
|
||||
disableControl(count, blocked, lockTip("end"));
|
||||
const fills = lengthFillsClip(info(), current, everyNth());
|
||||
hint.textContent = blocked ? `from ${wired}` : current.mode === "fixed" ? "exact (older setting)" : fills ? "= the whole clip. Shorten it to move IN" : active ? "" : "OUT ends the clip";
|
||||
hint.classList.toggle("note", fills && !blocked);
|
||||
hint.title = fills && !blocked ? `The Length (${current.requested ?? current.frames} frames) covers the whole clip, so IN and the clip cannot move. The bar still scrubs.` : "";
|
||||
};
|
||||
// Output frames for a Duration typed in the current units.
|
||||
const durationFrames = (value) => {
|
||||
if (getUnits() === "f") return Math.round(value);
|
||||
const rate = outFps();
|
||||
return rate > 0 ? Math.round(value * rate) : null;
|
||||
};
|
||||
// Output frames from IN to an end typed in the current units.
|
||||
const framesToEnd = (value) => {
|
||||
const clip = info();
|
||||
const current = plan();
|
||||
const end = getUnits() === "f" ? (Math.round(value) + 1) / clip.fps : value;
|
||||
if (driven("force_rate")) {
|
||||
const rate = outFps();
|
||||
return rate > 0 ? Math.round((end - boundSeconds("start")) * rate) : null;
|
||||
}
|
||||
return framesThrough(current.first, Math.ceil(end * clip.fps - 1e-7) - 1, everyNth(), snapRule());
|
||||
};
|
||||
const setDuration = (frames) => {
|
||||
if (frames == null || !Number.isFinite(frames)) return;
|
||||
const current = adoptLength(plan());
|
||||
if (current.mode !== "length") return;
|
||||
const was = current.requested ?? get("max_frames", 1);
|
||||
set("max_frames", snapToValid(Math.max(1, frames), snapRule(), Math.sign(frames - was)));
|
||||
set("end_seconds", 0);
|
||||
stopNote = "";
|
||||
};
|
||||
const defs = [
|
||||
["start", "Start", "Where the clip starts in the source video."],
|
||||
["duration", "Duration", "How long the clip is. Counted in clip frames at the output rate."],
|
||||
["end", "Ends at", "Where the clip ends in the source video. Typing it changes the Duration."],
|
||||
];
|
||||
for (const [key, caption, tip] of defs) {
|
||||
const cell = el("div", "ausboss-transform-trim-field");
|
||||
const label = el("span", "ausboss-transform-trim-field-label", caption);
|
||||
const go = el("button", "ausboss-transform-trim-go", "linked");
|
||||
go.type = "button";
|
||||
label.append(go);
|
||||
const control = makeScrubInput({
|
||||
value: 0, min: 0, max: 10000000, step: 1, decimals: 2, minDecimals: 0, unit: "s", unitWidth: 34,
|
||||
title: tip,
|
||||
onChange: (value) => {
|
||||
if (key === "start") {
|
||||
if (locked("start")) return;
|
||||
// A typed start is kept even when the Duration no longer fits;
|
||||
// the note below says what fits and offers both fixes.
|
||||
adoptLength(plan());
|
||||
const frame = clampFrame(toFrames.start(value), info());
|
||||
writeStart(frame);
|
||||
stopNote = "";
|
||||
seek(frame, false);
|
||||
return;
|
||||
}
|
||||
if (key === "duration") setDuration(durationFrames(value));
|
||||
else setDuration(framesToEnd(value));
|
||||
sync();
|
||||
},
|
||||
onSettle: () => { const window = currentWindow(); seek(key === "start" ? window.first : window.last, true); onCommit?.(); },
|
||||
});
|
||||
cell.append(label, control.root);
|
||||
grid.append(cell);
|
||||
fields[key] = { control, go, cell, label };
|
||||
}
|
||||
|
||||
noteRow = el("div", "ausboss-transform-trim-note");
|
||||
noteText = el("span");
|
||||
noteRow.append(noteText);
|
||||
for (let index = 0; index < 2; index++) {
|
||||
const button = el("button", "ausboss-transform-trim-reset");
|
||||
button.type = "button";
|
||||
noteButtons.push(button);
|
||||
noteRow.append(button);
|
||||
}
|
||||
root.append(grid, noteRow);
|
||||
}
|
||||
|
||||
// One field's look: its value in the current units, the line under it,
|
||||
// and, when another node sets it, that node's name and a Go to button.
|
||||
const showField = (key, { value, unit, decimals, sub, lockedBy, readOnly, placeholder = "" }) => {
|
||||
const field = fields[key];
|
||||
if (!field) return;
|
||||
field.control.setRange({ decimals, minDecimals: 0, step: decimals ? 0.1 : 1, fineStep: decimals ? 0.01 : 1 });
|
||||
field.control.set(value);
|
||||
if (value == null) field.control.input.value = "";
|
||||
field.control.input.placeholder = placeholder;
|
||||
const unitSlot = field.control.root.querySelector(".ausboss-scrub-unit");
|
||||
if (unitSlot) unitSlot.textContent = unit;
|
||||
const tip = lockedBy ? `Set by ${lockedBy.title}: ${sub}. Click "linked" to go to that node.` : sub;
|
||||
disableControl(field.control, readOnly, tip);
|
||||
field.cell.title = tip;
|
||||
field.go.hidden = !lockedBy;
|
||||
if (lockedBy) {
|
||||
field.go.title = `Set by ${lockedBy.title}. Click to go to that node.`;
|
||||
field.go.onclick = () => lockedBy.go?.();
|
||||
}
|
||||
};
|
||||
const showNote = (text, kind = "", actions = []) => {
|
||||
if (!noteRow) return;
|
||||
noteRow.hidden = !text;
|
||||
noteRow.classList.toggle("warn", kind === "warn");
|
||||
noteText.textContent = text;
|
||||
noteButtons.forEach((button, index) => {
|
||||
const action = actions[index];
|
||||
button.hidden = !action;
|
||||
if (action) { button.textContent = action.label; button.onclick = () => { action.run(); sync(); onCommit?.(); }; }
|
||||
});
|
||||
};
|
||||
|
||||
const syncFields = (clip, current, wired, unknown) => {
|
||||
const seconds = getUnits() !== "f";
|
||||
for (const button of unitPill.children) button.classList.toggle("on", button.dataset.units === (seconds ? "s" : "f"));
|
||||
const rate = outFps();
|
||||
const rateText = rate > 0 ? `${formatFps(rate)} fps` : "the output rate";
|
||||
const first = current.first;
|
||||
const endSec = unknown ? null : endSecondsOf(current);
|
||||
const frames = unknown ? null : current.frames;
|
||||
const startLink = locked("start") ? linkInfo(driven("start_frame") ? "start_frame" : "start_seconds") : null;
|
||||
const lengthLink = current.mode === "wired" && wired ? linkInfo(wired) : null;
|
||||
const endLink = endDriven() && current.mode === "free" ? linkInfo(driven("end_frame") ? "end_frame" : "end_seconds") : null;
|
||||
const room = roomFrames();
|
||||
const fills = durationFills(current);
|
||||
|
||||
showField("start", {
|
||||
value: seconds ? frameTime(first, clip) : first,
|
||||
unit: seconds ? "s" : "fr", decimals: seconds ? 2 : 0,
|
||||
sub: seconds ? `source frame ${first}` : `source frame · ${secondsText(frameTime(first, clip))} s`,
|
||||
lockedBy: startLink, readOnly: locked("start"),
|
||||
});
|
||||
|
||||
// Duration: what was asked for (a Duration longer than what is left
|
||||
// only caps the clip), in clip frames or seconds at the output rate.
|
||||
const asked = current.mode === "wired" ? current.requested ?? current.frames : current.mode === "length" ? current.requested : frames;
|
||||
let durationSub;
|
||||
if (current.mode === "wired" && current.frames == null && current.requested == null) {
|
||||
durationSub = room != null && rate > 0 ? `up to ${secondsText(room / rate)} s (${room} frames) fit after this start` : "set when the graph runs";
|
||||
} else if (current.mode === "wired" && wired !== "fixed_frames" && current.truncated) {
|
||||
durationSub = `the video ends first: ${frames} frames${rate > 0 ? ` (${secondsText(frames / rate)} s)` : ""}`;
|
||||
} else if (current.mode === "wired") {
|
||||
durationSub = wired === "fixed_frames" ? `${asked} clip frames required` : `up to ${asked} clip frames`;
|
||||
} else if (frames == null) {
|
||||
durationSub = "frame count at run time";
|
||||
} else if (current.truncated) {
|
||||
durationSub = `the video ends first: ${frames} frames${rate > 0 ? ` (${secondsText(frames / rate)} s)` : ""}`;
|
||||
} else {
|
||||
durationSub = seconds ? `${frames} clip frames at ${rateText}` : rate > 0 ? `clip frames · ${secondsText(frames / rate)} s at ${rateText}` : "seconds known at run time";
|
||||
}
|
||||
const durationInSeconds = seconds && rate > 0;
|
||||
showField("duration", {
|
||||
value: asked == null ? null : durationInSeconds ? asked / rate : asked,
|
||||
unit: durationInSeconds ? "s" : "fr", decimals: durationInSeconds ? 2 : 0,
|
||||
sub: durationSub, lockedBy: lengthLink,
|
||||
readOnly: current.mode === "wired" || Boolean(endLink) || asked == null,
|
||||
placeholder: current.mode === "wired" && asked == null ? "at run time" : "",
|
||||
});
|
||||
|
||||
const lastSource = endSec == null ? null : Math.min(clip.count - 1, Math.max(first, Math.ceil(endSec * clip.fps - 1e-7) - 1));
|
||||
showField("end", {
|
||||
value: endSec == null ? null : seconds ? endSec : lastSource,
|
||||
unit: seconds ? "s" : "fr", decimals: seconds ? 2 : 0,
|
||||
sub: endSec == null ? "known after the run" : seconds ? `last source frame ${lastSource}` : `last source frame · ${secondsText(endSec)} s`,
|
||||
lockedBy: endLink, readOnly: current.mode === "wired" || Boolean(endLink) || endSec == null,
|
||||
placeholder: endSec == null ? "after Run" : "",
|
||||
});
|
||||
|
||||
// The clip in words.
|
||||
if (endSec == null) {
|
||||
clipLine.textContent = `Clip from ${seconds ? `${secondsText(frameTime(first, clip))} s` : `src fr ${first}`} · length set when the graph runs`;
|
||||
} else {
|
||||
const span = seconds
|
||||
? `Clip ${secondsText(frameTime(first, clip))} → ${secondsText(endSec)} s`
|
||||
: `Clip src fr ${first} → ${lastSource}`;
|
||||
clipLine.textContent = `${span} · ${frames} frames out`;
|
||||
}
|
||||
|
||||
// What needs saying: a start that leaves too little video, a linked
|
||||
// exact count that does not fit, or a drag that stopped at the end.
|
||||
const latest = current.mode === "length" ? latestIn(current) : current.latestStart;
|
||||
if (current.mode === "wired" && wired === "fixed_frames" && current.tooLong) {
|
||||
showNote(`Needs ${asked} frames; the video is shorter.`, "warn");
|
||||
} else if (current.mode === "wired" && wired === "fixed_frames" && latest != null && first > latest && !unknown) {
|
||||
showNote(`Needs ${asked} frames; only ${room ?? "fewer"} fit from here. The run will fail.`, "warn",
|
||||
locked("start") ? [] : [{ label: `Move start to ${secondsText(latest / clip.fps)} s`, run: () => writeStart(latest) }]);
|
||||
} else if (current.mode === "length" && current.truncated && !fills) {
|
||||
const actions = [{ label: `Shorten to ${rate > 0 ? `${secondsText(frames / rate)} s` : `${frames} frames`}`, run: () => { set("max_frames", Math.max(1, frames)); set("end_seconds", 0); } }];
|
||||
if (!locked("start") && latest != null && latest < first) actions.push({ label: `Move start to ${secondsText(latest / clip.fps)} s`, run: () => writeStart(latest) });
|
||||
showNote(`Only ${frames} of ${current.requested} frames fit from here.`, "warn", actions);
|
||||
} else if (current.mode === "wired" && wired !== "fixed_frames" && current.truncated && frames != null) {
|
||||
showNote(`Video ends first: ${frames} of ${asked} frames.`);
|
||||
} else if (current.mode === "length" && fills && current.truncated) {
|
||||
showNote("Runs to the end of the video.");
|
||||
} else if (stopNote) {
|
||||
showNote(stopNote);
|
||||
} else {
|
||||
showNote("");
|
||||
}
|
||||
|
||||
publish?.(endSec == null || frames == null ? null : { frames, startSeconds: frameTime(first, clip), endSeconds: endSec, roomFrames: room });
|
||||
};
|
||||
|
||||
if (trim) {
|
||||
const sampling = el("div", "ausboss-transform-trim-line wrap");
|
||||
const nthLabel = el("label", "", "Every nth");
|
||||
controls.every_nth = makeScrubInput({ value: get("every_nth", 1), min: 1, max: 512, step: 1, decimals: 0,
|
||||
title: "Keep one frame in this many. Output fps is adjusted to keep real-time playback; the Duration counts the frames kept.",
|
||||
title: "Keep one frame in this many. Output fps is adjusted to keep real-time playback; a Length counts the frames kept.",
|
||||
onChange: (next) => { if (!driven("every_nth")) set("every_nth", next); sync(); }, onSettle: onCommit,
|
||||
});
|
||||
nthLabel.append(controls.every_nth.root);
|
||||
@@ -864,20 +648,15 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
|
||||
reset.type = "button";
|
||||
reset.addEventListener("click", () => {
|
||||
const current = plan();
|
||||
if (current.mode !== "wired") {
|
||||
// The whole video: no start, no end, no Duration limit.
|
||||
if (current.mode === "free") {
|
||||
if (!locked("start")) set("start_seconds", 0);
|
||||
if (!endDriven()) set("end_seconds", 0);
|
||||
set("max_frames", 0);
|
||||
if (!driven("fixed_frames")) set("fixed_frames", 0);
|
||||
stopNote = "";
|
||||
seek(0, true); onCommit?.();
|
||||
if (!locked("end")) set("end_seconds", 0);
|
||||
sync(); onCommit?.();
|
||||
} else {
|
||||
moveEdge("start", 0, true);
|
||||
}
|
||||
});
|
||||
sampling.append(unitPill);
|
||||
footer.append(useStart, el("span", "spacer"), reset);
|
||||
footer.append(summary, reset);
|
||||
root.append(sampling, footer);
|
||||
}
|
||||
root.addEventListener("pointerdown", (event) => {
|
||||
|
||||
+52
-46
@@ -30,18 +30,17 @@
|
||||
// Pure decisions (which rows show, how tall the card is, how a number
|
||||
// scrubs, where a socket sits) live in widget_card_math.mjs for node:test;
|
||||
// this file is the DOM.
|
||||
import { chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange } from "./index.mjs";
|
||||
import { BRAND, chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange } from "./index.mjs";
|
||||
import { keepKeyInField } from "./canvas_passthrough.mjs";
|
||||
import { createMediaPicker } from "./media_picker.mjs";
|
||||
import { ensureNodeMinHeight, fillNodeHeight, holdNodeMinWidth, nodeHeightAfterCardChange, pinVuePanelHeight } from "./panel_layout.mjs";
|
||||
import { makeScrubInput, quantizeScrubValue, stepDecimals } from "./scrub_input.mjs";
|
||||
import { CONTROL_HEIGHT, FONT_UI, RADIUS_CARD, RADIUS_CONTROL, RADIUS_XS, SELECT_CHEVRON, THEME as T } from "./theme.mjs";
|
||||
import { limitsLabel, narrowedRange } from "./wired_limits.mjs";
|
||||
import { hideWidget } from "./widget_visibility.mjs";
|
||||
import {
|
||||
CARD_PADDING, GROUP_HEIGHT, ROW_GAP, ROW_HEIGHT, SECTION_HEIGHT, SLOT_OFFSET, UNIT_SLOT_WIDTH,
|
||||
cardChangeRestore, cardHeight, choiceLabel, commitWidgetValue, comboValues, rowHeight, rowInLook, rowKind, rowMuted, rowTops, scrubSteps, socketWidgetY, visibleRows,
|
||||
liftSocket, widgetTooltip,
|
||||
widgetTooltip,
|
||||
} from "./widget_card_math.mjs";
|
||||
|
||||
export * from "./widget_card_math.mjs";
|
||||
@@ -56,7 +55,7 @@ const WRAPPER_INSET = 16;
|
||||
// widget's layout y (DomWidgets: margin 10 per side).
|
||||
const WRAPPER_TOP = 10;
|
||||
|
||||
const FONT = FONT_UI;
|
||||
const FONT = `-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif`;
|
||||
// A boolean pill's state labels must fit half a control; longer text is a
|
||||
// tooltip, and the pill says on / off.
|
||||
const SWITCH_LABEL_MAX = 16;
|
||||
@@ -79,80 +78,76 @@ export function ensureCardCss() {
|
||||
const style = document.createElement("style");
|
||||
style.id = CSS_ID;
|
||||
style.textContent = `
|
||||
.ausboss-card{position:relative;box-sizing:border-box;width:100%;height:100%;display:flex;flex-direction:column;gap:${ROW_GAP}px;padding:${CARD_PADDING}px 8px;overflow:hidden;border:1px solid transparent;border-radius:${RADIUS_CARD}px;background:${T.card};font:12px/1.3 ${FONT};color:${T.inkSoft};pointer-events:none}
|
||||
.ausboss-card{position:relative;box-sizing:border-box;width:100%;height:100%;display:flex;flex-direction:column;gap:${ROW_GAP}px;padding:${CARD_PADDING}px 8px;overflow:hidden;border:1px solid rgba(0,180,170,.22);border-radius:8px;background:rgba(0,0,0,.28);font:12px/1.3 ${FONT};color:#c8dddd;pointer-events:none}
|
||||
.ausboss-card-row{display:grid;grid-template-columns:minmax(56px,30%) 1fr;align-items:center;gap:8px;height:${ROW_HEIGHT}px;flex:none;pointer-events:auto}
|
||||
.ausboss-card-row.hidden{display:none}
|
||||
.ausboss-card-row.linked{opacity:.5}
|
||||
.ausboss-card-row.linked .ausboss-card-control{pointer-events:none}
|
||||
.ausboss-card-row.muted .ausboss-card-control{opacity:.35;pointer-events:none}
|
||||
.ausboss-card-row.muted .ausboss-card-label{color:${T.faint}}
|
||||
.ausboss-card-range{margin-left:6px;color:${T.faint};font-size:10px;font-weight:600;letter-spacing:.02em;white-space:nowrap}
|
||||
.ausboss-card-row.muted .ausboss-card-label{color:#566b69}
|
||||
.ausboss-card-range{margin-left:6px;color:#5f7674;font-size:10px;font-weight:600;letter-spacing:.02em;white-space:nowrap}
|
||||
.ausboss-card.has-corner .ausboss-card-control{margin-right:var(--ausboss-card-corner,0px)}
|
||||
.ausboss-card-corner{position:absolute;top:${CARD_PADDING}px;right:8px;height:${ROW_HEIGHT}px;display:flex;align-items:center;justify-content:flex-end;gap:5px;pointer-events:auto}
|
||||
.ausboss-card-gear{width:24px;height:24px;flex:none;display:grid;place-items:center;padding:0;border:1px solid transparent;border-radius:${RADIUS_CONTROL}px;background:${T.fill};color:${T.label};cursor:pointer}
|
||||
.ausboss-card-gear:hover{background:${T.fillHover};color:${T.inkHover}}
|
||||
.ausboss-card-chip{height:20px;flex:none;padding:0 9px;border:none;border-radius:999px;background:${T.brandSoft};color:${T.brandInk};font:600 10px/1 ${FONT};letter-spacing:.02em;font-variant-numeric:tabular-nums;white-space:nowrap;cursor:pointer}
|
||||
.ausboss-card-chip:hover{background:${T.brandSoftHover};color:${T.inkHover}}
|
||||
.ausboss-card-gear{width:24px;height:24px;flex:none;display:grid;place-items:center;padding:0;border:1px solid #2a3437;border-radius:6px;background:#0f1516;color:#8ba3a1;cursor:pointer}
|
||||
.ausboss-card-gear:hover{border-color:${BRAND};color:${BRAND}}
|
||||
.ausboss-card-chip{height:20px;flex:none;padding:0 8px;border:1px solid rgba(0,180,170,.5);border-radius:10px;background:rgba(0,180,170,.14);color:${BRAND};font:600 10px/1 ${FONT};letter-spacing:.02em;white-space:nowrap;cursor:pointer}
|
||||
.ausboss-card-chip:hover{background:rgba(0,180,170,.24);color:#fff}
|
||||
.ausboss-card-chip[hidden]{display:none}
|
||||
.ausboss-card-row.area{display:block}
|
||||
.ausboss-card-row.panel{display:block}
|
||||
.ausboss-card-row.area.grow{flex:1 1 auto;height:auto}
|
||||
.ausboss-card-label{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;color:${T.label};font-size:11px;user-select:none}
|
||||
.ausboss-card-label{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;color:#8ba3a1;font-size:11px;user-select:none}
|
||||
.ausboss-card-control{display:flex;align-items:center;gap:6px;min-width:0;height:100%}
|
||||
.ausboss-card-field{display:flex;align-items:center;gap:6px;flex:1 1 0;min-width:0;height:100%}
|
||||
.ausboss-card-field.linked{opacity:.5;pointer-events:none}
|
||||
.ausboss-card .ausboss-scrub{height:${CONTROL_HEIGHT}px}
|
||||
.ausboss-card-field>.ausboss-scrub{flex:1 1 0;width:auto;min-width:0}
|
||||
.ausboss-card-field>.ausboss-scrub .ausboss-scrub-input{width:100%}
|
||||
.ausboss-card-sep{flex:none;color:${T.faint};font-size:11px}
|
||||
.ausboss-card-suffix{flex:none;color:${T.faint};font:600 10px ${FONT};letter-spacing:.1em;text-transform:uppercase;user-select:none}
|
||||
.ausboss-card-section{height:${SECTION_HEIGHT}px;flex:none;display:flex;align-items:flex-end;gap:8px;color:${T.faint};font:600 10px/1 ${FONT};letter-spacing:.1em;text-transform:uppercase;user-select:none}
|
||||
.ausboss-card-section::after{content:"";flex:1;height:1px;margin-bottom:4px;background:${T.rule}}
|
||||
.ausboss-card-sep{flex:none;color:#5f7674;font-size:11px}
|
||||
.ausboss-card-suffix{flex:none;color:#5f7674;font-size:10px;letter-spacing:.06em;text-transform:uppercase;user-select:none}
|
||||
.ausboss-card-section{height:${SECTION_HEIGHT}px;flex:none;display:flex;align-items:flex-end;color:#5f7674;font-size:9.5px;letter-spacing:.12em;text-transform:uppercase;user-select:none}
|
||||
.ausboss-card-section.hidden{display:none}
|
||||
.ausboss-card-group{height:${GROUP_HEIGHT}px;flex:none;display:flex;align-items:center;gap:6px;padding:0 4px;border:1px solid transparent;border-radius:${RADIUS_CONTROL}px;background:transparent;color:${T.faint};font:600 10px/1 ${FONT};letter-spacing:.1em;text-transform:uppercase;cursor:pointer;text-align:left;pointer-events:auto}
|
||||
.ausboss-card-group:hover{color:${T.inkHover}}
|
||||
.ausboss-card-group{height:${GROUP_HEIGHT}px;flex:none;display:flex;align-items:center;gap:6px;padding:0 4px;border:1px solid transparent;border-radius:6px;background:transparent;color:#78908e;font:600 10.5px/1 ${FONT};letter-spacing:.06em;text-transform:uppercase;cursor:pointer;text-align:left;pointer-events:auto}
|
||||
.ausboss-card-group:hover{color:#fff;border-color:#2a3437}
|
||||
.ausboss-card-group .glyph{display:inline-block;width:10px;transition:transform .12s}
|
||||
.ausboss-card-group.open .glyph{transform:rotate(90deg)}
|
||||
.ausboss-card-seg{display:grid;grid-auto-flow:column;grid-auto-columns:1fr;width:100%;height:${ROW_HEIGHT}px;padding:2px;box-sizing:border-box;border:1px solid transparent;border-radius:${RADIUS_CONTROL}px;background:${T.fill}}
|
||||
.ausboss-card-seg button{min-width:0;border:none;border-radius:${RADIUS_XS}px;padding:0 2px;background:transparent;color:${T.label};font:600 11px/1 ${FONT};cursor:pointer;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.ausboss-card-seg button:hover{color:${T.inkHover}}
|
||||
.ausboss-card-seg button.on{background:${T.brand};color:${T.onBrand}}
|
||||
.ausboss-card-bool button.on:first-child{background:${T.switchOff};color:${T.ink}}
|
||||
.ausboss-card-select{width:100%;height:${ROW_HEIGHT}px;padding:0 24px 0 8px;box-sizing:border-box;border:1px solid transparent;border-radius:${RADIUS_CONTROL}px;background:${T.fill} ${SELECT_CHEVRON} no-repeat right 9px center;color:${T.ink};font:500 12px ${FONT};appearance:none;-webkit-appearance:none;cursor:pointer;overflow:hidden;text-overflow:ellipsis}
|
||||
.ausboss-card-select:hover{background-color:${T.fillHover}}
|
||||
.ausboss-card-select:focus-visible{outline:2px solid ${T.brand};outline-offset:1px}
|
||||
.ausboss-card-text{width:100%;height:${ROW_HEIGHT}px;padding:0 8px;box-sizing:border-box;border:1px solid transparent;border-radius:${RADIUS_CONTROL}px;background:${T.fill};color:${T.ink};font:12px ${FONT};min-width:0}
|
||||
.ausboss-card-text:focus{outline:none;border-color:${T.brand}}
|
||||
.ausboss-card-text::placeholder{color:${T.faint}}
|
||||
.ausboss-card-area{display:block;width:100%;height:100%;padding:5px 8px;box-sizing:border-box;border:1px solid transparent;border-radius:${RADIUS_CONTROL}px;background:${T.fill};color:${T.ink};font:12px/1.4 ${FONT};resize:none;overflow:auto;min-width:0}
|
||||
.ausboss-card-area:focus{outline:none;border-color:${T.brand}}
|
||||
.ausboss-card-area::placeholder{color:${T.faint}}
|
||||
.ausboss-card.look-big .ausboss-card-row.area .ausboss-card-field{position:relative;display:block;border:1px solid transparent;border-radius:${RADIUS_CONTROL}px;background:${T.fill};cursor:text}
|
||||
.ausboss-card.look-big .ausboss-card-row.area .ausboss-card-field:focus-within{border-color:${T.brand}}
|
||||
.ausboss-card.look-big .ausboss-card-area{position:absolute;left:0;right:0;top:0;bottom:0;margin:auto 0;max-height:100%;padding:${BIG_PAD_Y}px ${BIG_PAD_X}px;border:none;border-radius:5px;background:transparent;color:${T.brandGlow};text-shadow:0 0 .35em rgba(0,180,170,.55);font:600 ${BIG_FONT}px/${BIG_LINE}px ${FONT};text-align:center;scrollbar-width:thin;scrollbar-color:${T.fillHover} transparent}
|
||||
.ausboss-card.look-big .ausboss-card-area::placeholder{color:${T.faint};text-shadow:none}
|
||||
.ausboss-card-seg{display:grid;grid-auto-flow:column;grid-auto-columns:1fr;width:100%;height:${ROW_HEIGHT}px;padding:2px;box-sizing:border-box;border:1px solid #2a3437;border-radius:6px;background:#0f1516}
|
||||
.ausboss-card-seg button{min-width:0;border:none;border-radius:4px;padding:0 2px;background:transparent;color:#8ba3a1;font:600 10.5px/1 ${FONT};cursor:pointer;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.ausboss-card-seg button:hover{color:#fff}
|
||||
.ausboss-card-seg button.on{background:${BRAND};color:#04201d}
|
||||
.ausboss-card-select{width:100%;height:${ROW_HEIGHT}px;padding:0 24px 0 8px;box-sizing:border-box;border:1px solid #2a3437;border-radius:6px;background:#0b0f10 url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' fill='none' stroke='%238ba3a1' stroke-width='1.5'/%3E%3C/svg%3E") no-repeat right 8px center;color:#d8ecea;font:600 11.5px ${FONT};appearance:none;-webkit-appearance:none;cursor:pointer;overflow:hidden;text-overflow:ellipsis}
|
||||
.ausboss-card-select:hover{border-color:${BRAND}}
|
||||
.ausboss-card-select:focus-visible{outline:2px solid ${BRAND};outline-offset:1px}
|
||||
.ausboss-card-text{width:100%;height:${ROW_HEIGHT}px;padding:0 8px;box-sizing:border-box;border:1px solid #2a3437;border-radius:6px;background:#0b0f10;color:#d8ecea;font:12px ${FONT};min-width:0}
|
||||
.ausboss-card-text:focus{outline:none;border-color:${BRAND}}
|
||||
.ausboss-card-text::placeholder{color:#4f6462}
|
||||
.ausboss-card-area{display:block;width:100%;height:100%;padding:5px 8px;box-sizing:border-box;border:1px solid #2a3437;border-radius:6px;background:#0b0f10;color:#d8ecea;font:12px/1.4 ${FONT};resize:none;overflow:auto;min-width:0}
|
||||
.ausboss-card-area:focus{outline:none;border-color:${BRAND}}
|
||||
.ausboss-card-area::placeholder{color:#4f6462}
|
||||
.ausboss-card.look-big .ausboss-card-row.area .ausboss-card-field{position:relative;display:block;border:1px solid #2a3437;border-radius:6px;background:#0b0f10;cursor:text}
|
||||
.ausboss-card.look-big .ausboss-card-row.area .ausboss-card-field:focus-within{border-color:${BRAND}}
|
||||
.ausboss-card.look-big .ausboss-card-area{position:absolute;left:0;right:0;top:0;bottom:0;margin:auto 0;max-height:100%;padding:${BIG_PAD_Y}px ${BIG_PAD_X}px;border:none;border-radius:5px;background:transparent;color:#6fe0d6;text-shadow:0 0 .35em rgba(0,180,170,.55);font:600 ${BIG_FONT}px/${BIG_LINE}px ${FONT};text-align:center;scrollbar-width:thin;scrollbar-color:#2f3d3c transparent}
|
||||
.ausboss-card.look-big .ausboss-card-area::placeholder{color:#4f6462;text-shadow:none}
|
||||
.ausboss-card.look-big .ausboss-card-row:not(.area){display:block}
|
||||
.ausboss-card.look-big .ausboss-card-row:not(.area) .ausboss-card-label{display:none}
|
||||
.ausboss-card.look-big .ausboss-card-row:not(.area) .ausboss-card-control{margin:0}
|
||||
.ausboss-card.look-big .ausboss-card-field>.ausboss-scrub{height:100%;justify-content:center;align-items:center;gap:4px;border-color:transparent;border-radius:${RADIUS_CONTROL}px;background:${T.fill}}
|
||||
.ausboss-card.look-big .ausboss-card-field>.ausboss-scrub:focus-within{border-color:${T.brand}}
|
||||
.ausboss-card.look-big .ausboss-card-field>.ausboss-scrub>.ausboss-scrub-input{order:1;flex:0 0 auto;width:auto;min-width:2ch;max-width:60%;field-sizing:content;color:${T.brandGlow};text-shadow:0 0 .35em rgba(0,180,170,.55);font:600 ${BIG_NUMBER_FONT}px ${FONT}}
|
||||
.ausboss-card.look-big .ausboss-card-field>.ausboss-scrub{height:100%;justify-content:center;align-items:center;gap:4px;border-color:#2a3437;border-radius:6px;background:#0b0f10}
|
||||
.ausboss-card.look-big .ausboss-card-field>.ausboss-scrub:focus-within{border-color:${BRAND}}
|
||||
.ausboss-card.look-big .ausboss-card-field>.ausboss-scrub>.ausboss-scrub-input{order:1;flex:0 0 auto;width:auto;min-width:2ch;max-width:60%;field-sizing:content;color:#6fe0d6;text-shadow:0 0 .35em rgba(0,180,170,.55);font:600 ${BIG_NUMBER_FONT}px ${FONT}}
|
||||
.ausboss-card.look-big .ausboss-card-field>.ausboss-scrub>.ausboss-scrub-unit{order:2}
|
||||
.ausboss-card.look-big .ausboss-card-field>.ausboss-scrub>.ausboss-scrub-unit:empty{display:none}
|
||||
.ausboss-card.look-big .ausboss-card-field>.ausboss-scrub>.ausboss-scrub-step{display:contents}
|
||||
.ausboss-card.look-big .ausboss-card-field>.ausboss-scrub>.ausboss-scrub-step>button{flex:none;width:30px;height:30px;border-radius:15px;color:${T.label}}
|
||||
.ausboss-card.look-big .ausboss-card-field>.ausboss-scrub>.ausboss-scrub-step>button{flex:none;width:30px;height:30px;border-radius:15px;color:#6f8886}
|
||||
.ausboss-card.look-big .ausboss-card-field>.ausboss-scrub>.ausboss-scrub-step>button:first-child{order:3}
|
||||
.ausboss-card.look-big .ausboss-card-field>.ausboss-scrub>.ausboss-scrub-step>button:last-child{order:0}
|
||||
.ausboss-card.look-big .ausboss-card-field>.ausboss-scrub>.ausboss-scrub-step>button>svg{transform:rotate(90deg) scale(1.6)}
|
||||
.ausboss-card.look-big .ausboss-card-corner{top:${CARD_PADDING + 4}px;right:12px;height:22px}
|
||||
.ausboss-card.look-big .ausboss-card-gear{width:22px;height:22px;border-color:transparent;background:transparent}
|
||||
.ausboss-card.look-big .ausboss-card-gear:hover{background:${T.fillHover}}
|
||||
.ausboss-card-swatch{flex:none;width:${ROW_HEIGHT}px;height:${ROW_HEIGHT}px;padding:0;border:1px solid transparent;border-radius:${RADIUS_CONTROL}px;background:${T.fill};cursor:pointer}
|
||||
.ausboss-card.look-big .ausboss-card-gear:hover{border-color:${BRAND}}
|
||||
.ausboss-card-swatch{flex:none;width:${ROW_HEIGHT}px;height:${ROW_HEIGHT}px;padding:0;border:1px solid #2a3437;border-radius:6px;background:#0b0f10;cursor:pointer}
|
||||
.ausboss-card-swatch::-webkit-color-swatch-wrapper{padding:3px}
|
||||
.ausboss-card-swatch::-webkit-color-swatch{border:none;border-radius:3px}
|
||||
.ausboss-card-btn{flex:none;height:${ROW_HEIGHT}px;padding:0 10px;border:1px solid transparent;border-radius:${RADIUS_CONTROL}px;background:${T.fill};color:${T.inkSoft};font:600 11px/1 ${FONT};cursor:pointer;white-space:nowrap}
|
||||
.ausboss-card-btn:hover{background:${T.fillHover};color:${T.inkHover}}
|
||||
.ausboss-card-btn:focus-visible{outline:2px solid ${T.brand};outline-offset:1px}
|
||||
.ausboss-card-btn{flex:none;height:${ROW_HEIGHT}px;padding:0 10px;border:1px solid #2a3437;border-radius:6px;background:#16201f;color:#d8ecea;font:600 11px/1 ${FONT};cursor:pointer;white-space:nowrap}
|
||||
.ausboss-card-btn:hover{border-color:${BRAND};color:#fff}
|
||||
`;
|
||||
document.head.append(style);
|
||||
}
|
||||
@@ -174,6 +169,17 @@ function widgetSlot(node, name) {
|
||||
return node.inputs?.find((input) => input?.widget?.name === name || input?.name === name) ?? null;
|
||||
}
|
||||
|
||||
// A `top: true` row's widgets keep their input slots but the slots stop
|
||||
// being widget inputs: the frontend then measures and draws them in the
|
||||
// node's slot column, and a link into one is resolved by input name.
|
||||
export function liftSocket(node, name) {
|
||||
const slot = node.inputs?.find((input) => input?.widget?.name === name);
|
||||
if (!slot) return false;
|
||||
delete slot.widget;
|
||||
slot._widget = undefined;
|
||||
return true;
|
||||
}
|
||||
|
||||
function widgetLinked(node, name) {
|
||||
const slot = widgetSlot(node, name);
|
||||
return Boolean(slot && slot.link !== null && slot.link !== undefined);
|
||||
|
||||
@@ -218,23 +218,3 @@ export function widgetTooltip(node, name, widget = null) {
|
||||
const text = Array.isArray(spec) ? spec[1]?.tooltip : undefined;
|
||||
return typeof text === "string" ? text : "";
|
||||
}
|
||||
|
||||
// A `top: true` row's widgets keep their input slots but the slots stop
|
||||
// being widget inputs: the frontend then measures and draws them in the
|
||||
// node's slot column, and a link into one is resolved by input name.
|
||||
// Newer frontends also stamp a widget's socket with the position of its
|
||||
// row (`slot.pos`) and keep honouring it once the widget is gone, so every
|
||||
// lifted socket would sit on the first slot's row. The stamp goes too.
|
||||
export function liftSocket(node, name) {
|
||||
const slot = node.inputs?.find((input) => input?.widget?.name === name);
|
||||
if (!slot) return false;
|
||||
liftSlot(slot);
|
||||
return true;
|
||||
}
|
||||
|
||||
// The same lift for a slot already in hand (a loop over `node.inputs`).
|
||||
export function liftSlot(slot) {
|
||||
delete slot.widget;
|
||||
slot._widget = undefined;
|
||||
delete slot.pos;
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
// panel's hidden storage widget stays hidden whichever renderer is on.
|
||||
|
||||
const STASH = "__ausbossVisibilityStash";
|
||||
const PAINT_KEYS = ["computeSize", "computeLayoutSize", "draw"];
|
||||
|
||||
// Collapse a widget to zero height. Returns true when this call changed
|
||||
// visibility, false when it was already hidden (callers use the return to
|
||||
@@ -28,10 +27,6 @@ export function hideWidget(widget) {
|
||||
computeSize: widget.computeSize,
|
||||
computeLayoutSize: widget.computeLayoutSize,
|
||||
draw: widget.draw,
|
||||
// Which of the three the widget carried itself. One it lacked is deleted
|
||||
// again on show: left behind as `undefined`, the frontend takes it for a
|
||||
// custom-drawn widget and App mode draws an empty row.
|
||||
own: Object.fromEntries(PAINT_KEYS.map((key) => [key, Object.prototype.hasOwnProperty.call(widget, key)])),
|
||||
hidden: widget.hidden,
|
||||
optionsHidden: options.hidden,
|
||||
optionsDescriptor: Object.getOwnPropertyDescriptor(widget, "options"),
|
||||
@@ -66,10 +61,9 @@ export function hideWidget(widget) {
|
||||
export function showWidget(widget) {
|
||||
const stash = widget?.[STASH];
|
||||
if (!stash) return false;
|
||||
for (const key of PAINT_KEYS) {
|
||||
if (stash.own && !stash.own[key]) delete widget[key];
|
||||
else widget[key] = stash[key];
|
||||
}
|
||||
widget.computeSize = stash.computeSize;
|
||||
widget.computeLayoutSize = stash.computeLayoutSize;
|
||||
widget.draw = stash.draw;
|
||||
widget.hidden = stash.hidden;
|
||||
const options = widget.options;
|
||||
try {
|
||||
@@ -90,11 +84,6 @@ export function showWidget(widget) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// True while hideWidget holds the widget hidden.
|
||||
export function isWidgetHidden(widget) {
|
||||
return Boolean(widget?.[STASH]);
|
||||
}
|
||||
|
||||
// Drive a widget toward a target visibility; true when anything changed.
|
||||
export function setWidgetVisible(widget, visible) {
|
||||
return visible ? showWidget(widget) : hideWidget(widget);
|
||||
|
||||
@@ -213,19 +213,6 @@ export function matchInstalled(name, files) {
|
||||
return loose ? { found: true, path: loose } : { found: false, path: null };
|
||||
}
|
||||
|
||||
// The copy of `name` to pick without asking: the exact path when the folder
|
||||
// has it, else the only file of that name in any subfolder. Two copies in
|
||||
// different subfolders give null: which one to use is the user's choice.
|
||||
export function onlyCopy(name, files) {
|
||||
const match = matchInstalled(name, files);
|
||||
if (!match.found) return null;
|
||||
const wanted = str(name, 1000).trim().replace(/\\/g, "/").toLowerCase();
|
||||
if (match.path.toLowerCase() === wanted) return match.path;
|
||||
const base = baseName(name).toLowerCase();
|
||||
const copies = files.filter((file) => baseName(str(file, 1000).replace(/\\/g, "/")).toLowerCase() === base);
|
||||
return copies.length === 1 ? match.path : null;
|
||||
}
|
||||
|
||||
// Node packs present in a graph, from each node type's python_module
|
||||
// ("custom_nodes.ComfyUI-AusBoss"). Core modules ("nodes",
|
||||
// "comfy_extras.*") are skipped: nobody needs to install those. The first
|
||||
|
||||
@@ -62,8 +62,7 @@ const CHOICES = {
|
||||
};
|
||||
|
||||
export function cleanTitle(title) {
|
||||
const text = ["string", "number", "boolean"].includes(typeof title) ? String(title) : "";
|
||||
return text.replace(/\s+/g, " ").trim().slice(0, TITLE_MAX);
|
||||
return String(title ?? "").replace(/\s+/g, " ").trim().slice(0, TITLE_MAX);
|
||||
}
|
||||
|
||||
// Node and group ids as a workflow file stores them: numbers, or text for a
|
||||
@@ -136,7 +135,7 @@ export function normalizeSwitches(raw) {
|
||||
const used = new Set();
|
||||
for (const item of Array.isArray(raw) ? raw : []) {
|
||||
if (!item || typeof item !== "object") continue;
|
||||
let id = typeof item.id === "number" || typeof item.id === "string" ? Number(item.id) : NaN;
|
||||
let id = Number(item.id);
|
||||
if (!Number.isInteger(id) || id < 1 || used.has(id)) {
|
||||
id = 1;
|
||||
while (used.has(id)) id += 1;
|
||||
@@ -358,7 +357,7 @@ export function stackRows(value) {
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!Array.isArray(rows)) return null;
|
||||
if (!Array.isArray(rows) || !rows.length) return null;
|
||||
const isRow = (row) => row && typeof row === "object" && typeof row.name === "string" && typeof row.enabled === "boolean";
|
||||
return rows.every(isRow) ? rows : null;
|
||||
}
|
||||
@@ -485,12 +484,7 @@ export function choicePairs(entry, switches) {
|
||||
for (const other of switches ?? []) {
|
||||
if (other === entry || !other.choice) continue;
|
||||
for (const pair of valuePairs({ on: entry.on, off: other.on })) {
|
||||
const previous = found.get(pairKey(pair));
|
||||
if (!previous) found.set(pairKey(pair), { ...pair, choice: true });
|
||||
else if (pair.row !== undefined) {
|
||||
previous.on = { ...previous.on, ...pair.on };
|
||||
previous.off = { ...pair.off, ...previous.off };
|
||||
}
|
||||
if (!found.has(pairKey(pair))) found.set(pairKey(pair), { ...pair, choice: true });
|
||||
}
|
||||
}
|
||||
return [...found.values()];
|
||||
@@ -545,9 +539,8 @@ export function stackRowOwners(boards, nodeId, widget, rowName) {
|
||||
const owners = [];
|
||||
if (!rowName) return owners;
|
||||
for (const { node, settings } of boards ?? []) {
|
||||
const { switches } = normalizeSettings(settings);
|
||||
for (const entry of switches) {
|
||||
const moves = (entry.choice ? choicePairs(entry, switches) : valuePairs(entry)).some(
|
||||
for (const entry of normalizeSettings(settings).switches) {
|
||||
const moves = valuePairs(entry).some(
|
||||
(pair) => pair.row !== undefined && String(pair.node) === String(nodeId) && pair.widget === widget && sameFile(pair.row, rowName),
|
||||
);
|
||||
if (moves) owners.push({ node, id: entry.id, title: entry.title });
|
||||
@@ -562,9 +555,8 @@ export function stackGroupOwners(boards, nodeId, widget, group) {
|
||||
const owners = [];
|
||||
if (!group) return owners;
|
||||
for (const { node, settings } of boards ?? []) {
|
||||
const { switches } = normalizeSettings(settings);
|
||||
for (const entry of switches) {
|
||||
const moves = (entry.choice ? choicePairs(entry, switches) : valuePairs(entry)).some(
|
||||
for (const entry of normalizeSettings(settings).switches) {
|
||||
const moves = valuePairs(entry).some(
|
||||
(pair) => pair.group === group && String(pair.node) === String(nodeId) && pair.widget === widget,
|
||||
);
|
||||
if (moves) owners.push({ node, id: entry.id, title: entry.title });
|
||||
@@ -650,9 +642,7 @@ export function readGroups(groups, placed, { counts = () => true } = {}) {
|
||||
group,
|
||||
rect,
|
||||
title: String(group.title ?? ""),
|
||||
// Group colors come from a hex picker; a CSS background must never
|
||||
// receive URL functions or references from a saved workflow.
|
||||
color: typeof group.color === "string" && /^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i.test(group.color.trim()) ? group.color.trim() : null,
|
||||
color: typeof group.color === "string" && group.color ? group.color : null,
|
||||
members,
|
||||
...partState(members, counts),
|
||||
};
|
||||
@@ -678,7 +668,6 @@ export function readSwitches(switches, placed, groupRows, { counts = () => true
|
||||
if (id !== undefined && id !== null && !groupById.has(String(id))) groupById.set(String(id), row);
|
||||
}
|
||||
return (switches ?? []).map((entry) => {
|
||||
const sides = new Set([...Object.keys(entry.on ?? {}), ...Object.keys(entry.off ?? {})]);
|
||||
const members = [];
|
||||
const offMembers = [];
|
||||
const seen = new Set();
|
||||
@@ -686,7 +675,6 @@ export function readSwitches(switches, placed, groupRows, { counts = () => true
|
||||
let gone = 0;
|
||||
const takeNodes = (ids, into) => {
|
||||
for (const id of ids ?? []) {
|
||||
if (sides.has(String(id))) continue;
|
||||
const hit = nodeById.get(String(id));
|
||||
if (!hit) {
|
||||
gone += 1;
|
||||
@@ -707,7 +695,7 @@ export function readSwitches(switches, placed, groupRows, { counts = () => true
|
||||
}
|
||||
rects.push(row.rect);
|
||||
for (const node of row.members) {
|
||||
if (seen.has(node) || sides.has(String(node.id))) continue;
|
||||
if (seen.has(node)) continue;
|
||||
seen.add(node);
|
||||
into.push(node);
|
||||
}
|
||||
@@ -720,6 +708,7 @@ export function readSwitches(switches, placed, groupRows, { counts = () => true
|
||||
// The nodes whose settings it changes: listed, framed and selected with
|
||||
// the rest, but never turned off by it.
|
||||
const valueNodes = [];
|
||||
const sides = new Set([...Object.keys(entry.on ?? {}), ...Object.keys(entry.off ?? {})]);
|
||||
for (const id of sides) {
|
||||
const hit = nodeById.get(id);
|
||||
if (!hit) {
|
||||
|
||||
+4
-30
@@ -11,7 +11,6 @@ import {
|
||||
unionOf,
|
||||
} from "../shared/snap_lines.mjs";
|
||||
import { boundsOf, nodeElements, outlineOf } from "../shared/outline.mjs";
|
||||
import { TILE_MOVE } from "../shared/tile_face.mjs";
|
||||
|
||||
// Snap into line: a node or group being dragged lines up with the nodes and
|
||||
// groups around it, and a teal line shows what it lines up with. A corner
|
||||
@@ -38,8 +37,7 @@ const OVERHANG_PX = 6;
|
||||
const state = {
|
||||
enabled: true,
|
||||
before: null, // Map item -> { pos, size, rect } taken when the button went down
|
||||
corner: null, // the corner a resize pulls, such as "SE"
|
||||
resizingNode: null, // the node whose Vue corner handle took the press
|
||||
corner: null, // the corner a classic resize pulls, such as "SE"
|
||||
drag: null, // the running move, or { idle: true } for a gesture left alone
|
||||
guides: [],
|
||||
frame: 0,
|
||||
@@ -201,8 +199,8 @@ function stepMove(canvas, drag, event) {
|
||||
canvas.setDirty?.(true, true);
|
||||
}
|
||||
|
||||
// The frontend has just sized the node from its corner, so pull the moving
|
||||
// edges onto any line within reach.
|
||||
// Classic look: LiteGraph has just sized the node from its corner, so pull
|
||||
// the moving edges onto any line within reach.
|
||||
function stepNodeResize(canvas, node, event) {
|
||||
// LiteGraph forgets the corner once the pointer leaves the node, so use the
|
||||
// one it had when the button went down.
|
||||
@@ -240,7 +238,6 @@ function step(event) {
|
||||
const canvas = app.canvas;
|
||||
if (!state.before || !canvas?.graph || !canvas.canvas || !canvas.ds) return;
|
||||
if (canvas.resizing_node) return stepNodeResize(canvas, canvas.resizing_node, event);
|
||||
if (state.resizingNode) return stepNodeResize(canvas, state.resizingNode, event);
|
||||
if (canvas.resizingGroup) return stepGroupResize(canvas, canvas.resizingGroup, event);
|
||||
if (!state.drag) state.drag = startMove(canvas, event);
|
||||
if (state.drag && !state.drag.idle) stepMove(canvas, state.drag, event);
|
||||
@@ -253,20 +250,6 @@ function onPointerDown(event) {
|
||||
if (OTHER_SNAPPERS.some(settingOn)) return;
|
||||
if (app.canvas?.graph && app.canvas.canvas && app.canvas.ds) state.before = takeBefore(app.canvas);
|
||||
state.corner = cornerOf(app.canvas);
|
||||
if (vueNodes() && state.before) {
|
||||
const handle = event.target?.closest?.("[data-corner]");
|
||||
const id = handle?.closest?.("[data-node-id]")?.dataset?.nodeId;
|
||||
const corner = handle?.dataset?.corner;
|
||||
if (id != null && ["SE", "SW", "NE", "NW"].includes(corner)) {
|
||||
for (const [item, was] of state.before) {
|
||||
if (was.kind === "node" && String(item.id) === id) {
|
||||
state.resizingNode = item;
|
||||
state.corner = corner;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function cornerOf(canvas) {
|
||||
@@ -276,7 +259,7 @@ function cornerOf(canvas) {
|
||||
|
||||
// Behind LiteGraph's own pointerdown, which names the corner a resize pulls.
|
||||
function afterPointerDown() {
|
||||
if (state.before && !state.resizingNode) state.corner = cornerOf(app.canvas) ?? state.corner;
|
||||
if (state.before) state.corner = cornerOf(app.canvas) ?? state.corner;
|
||||
}
|
||||
|
||||
function onPointerMove(event) {
|
||||
@@ -295,17 +278,9 @@ function onPointerMove(event) {
|
||||
});
|
||||
}
|
||||
|
||||
// A frameless tile moves itself and keeps its pointer moves to itself
|
||||
// (js/shared/tile_face.mjs), then reports each move here once placed.
|
||||
function onTileMove(event) {
|
||||
if (!state.before || !event.detail) return;
|
||||
step(event.detail);
|
||||
}
|
||||
|
||||
function end() {
|
||||
state.before = null;
|
||||
state.corner = null;
|
||||
state.resizingNode = null;
|
||||
state.drag = null;
|
||||
state.pending = null;
|
||||
setGuides([]);
|
||||
@@ -356,7 +331,6 @@ function install() {
|
||||
window.addEventListener("pointerdown", onPointerDown, true);
|
||||
window.addEventListener("pointerdown", afterPointerDown);
|
||||
window.addEventListener("pointermove", onPointerMove);
|
||||
window.addEventListener(TILE_MOVE, onTileMove);
|
||||
// Capture phase: the classic canvas stops its pointerup from bubbling.
|
||||
window.addEventListener("pointerup", end, true);
|
||||
window.addEventListener("pointercancel", end, true);
|
||||
|
||||
@@ -12,10 +12,8 @@ import { formatWidgetVisibility } from "../shared/save_video_formats.mjs";
|
||||
import { hideInputsInDef } from "../shared/widget_visibility.mjs";
|
||||
import { castChips } from "../shared/h3_cast_chips.mjs";
|
||||
import { clipSetsDuration } from "../shared/h3_duration.mjs";
|
||||
import { loadImagePreview, loadImageStrip } from "../shared/load_image_strip.mjs";
|
||||
import { momentStrip } from "../shared/moment_strip.mjs";
|
||||
import { mountWidgetCard } from "../shared/widget_card.mjs";
|
||||
import { FONT_UI, THEME } from "../shared/theme.mjs";
|
||||
import { SOCKETLESS_CHOICE, SOCKETLESS_TEXT, commitWidgetValue, markSocketless, resetUnknownValues } from "../shared/widget_card_math.mjs";
|
||||
import { mediaViewQuery } from "../shared/media_list.mjs";
|
||||
import { gearIconSvg, openSettingsMenu } from "../shared/settings_menu.mjs";
|
||||
@@ -28,9 +26,6 @@ import { valueToTake, wiredLimits } from "../shared/wired_limits.mjs";
|
||||
const viewUrl = (value) => api.apiURL(`/view?${mediaViewQuery(value)}`);
|
||||
|
||||
const isMode = (name, ...modes) => (values) => modes.includes(values[name]);
|
||||
// Load Image: the choices that read the width and height boxes.
|
||||
const loadImageUsesBox = (values) => ["fit inside", "crop to fill", "crop"].includes(values.size)
|
||||
|| (values.size === "crop to ratio" && values.ratio === "width : height");
|
||||
// Stitch Inpaint: Seam lives in the card's gear menu (shared/stitch_seam.mjs
|
||||
// holds the menu and the rules). The gear in the card's corner opens the
|
||||
// menu; a "blend in" chip beside it shows the mode at a glance and opens the
|
||||
@@ -64,7 +59,7 @@ function seamCorner(node, card) {
|
||||
const note = document.createElement("div");
|
||||
note.append("not used", document.createElement("br"), "by blend in");
|
||||
note.style.cssText = "position:absolute;top:33px;right:2px;text-align:right;white-space:nowrap;"
|
||||
+ `color:${THEME.faint};font:9px/11px ${FONT_UI};`
|
||||
+ "color:#6f8886;font:9px/11px -apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;"
|
||||
+ "pointer-events:none";
|
||||
tools.append(chip, gear, note);
|
||||
return {
|
||||
@@ -125,21 +120,6 @@ const CARDS = {
|
||||
{ widget: "interpolation", label: "Filter", kind: "select" },
|
||||
],
|
||||
},
|
||||
AUSBOSS_NODES_EditLock: {
|
||||
minWidth: 300,
|
||||
rows: [
|
||||
{ widget: "lock", label: "Lock", kind: "segment",
|
||||
titles: { auto: "Lock the untouched parts; step aside when the whole picture changes", always: "Lock even when the whole picture changes", off: "Do nothing" } },
|
||||
{ widget: "tolerance", label: "Tolerance", decimals: 2, suffix: "×" },
|
||||
],
|
||||
},
|
||||
AUSBOSS_NODES_EditLockRestore: {
|
||||
minWidth: 300,
|
||||
rows: [
|
||||
{ widget: "feather", label: "Feather", suffix: "px" },
|
||||
{ widget: "remove_tint", label: "Remove tint" },
|
||||
],
|
||||
},
|
||||
AUSBOSS_NODES_ColorMatch: {
|
||||
minWidth: 300,
|
||||
rows: [
|
||||
@@ -262,8 +242,6 @@ const CARDS = {
|
||||
{ widget: "fill_holes", label: "Fill small holes", group: "advanced" },
|
||||
{ widget: "invert", label: "Invert", group: "advanced" },
|
||||
{ widget: "if_nothing", label: "If nothing", kind: "segment", group: "advanced" },
|
||||
// What a different picture coming in does to the picks.
|
||||
{ widget: "new_picture", label: "New picture", kind: "segment", group: "advanced" },
|
||||
{ widget: "free_vram", label: "Free VRAM", group: "advanced" },
|
||||
],
|
||||
},
|
||||
@@ -300,14 +278,6 @@ const CARDS = {
|
||||
{ widget: "batch_size", label: "Batch" },
|
||||
],
|
||||
},
|
||||
AUSBOSS_NODES_FlashVSRUpscale: {
|
||||
minWidth: 340,
|
||||
rows: [
|
||||
{ widget: "model", label: "Model", kind: "select" },
|
||||
{ widget: "scale", label: "Scale", suffix: "×", decimals: 2 },
|
||||
{ widget: "color_match", label: "Keep colors" },
|
||||
],
|
||||
},
|
||||
AUSBOSS_NODES_AlignImage: {
|
||||
minWidth: 300,
|
||||
rows: [
|
||||
@@ -358,23 +328,6 @@ const CARDS = {
|
||||
rows: [{ widget: "text", kind: "textarea", placeholder: "Prompt, caption, or shared text", height: 100, grow: true,
|
||||
looks: { big: { height: 62, placeholder: "type here" } } }],
|
||||
},
|
||||
// One line for each run. The three settings under the box say where a run
|
||||
// ends, whether a leading "1." comes off, and how many lines run at most.
|
||||
AUSBOSS_NODES_TextLines: {
|
||||
minWidth: 320,
|
||||
rows: [
|
||||
{ widget: "text", kind: "textarea", placeholder: "One line for each run", height: 100, grow: true },
|
||||
{ widget: "split", label: "Split at", kind: "segment" },
|
||||
{ widget: "remove_numbering", label: "Numbering", onText: "remove", offText: "keep" },
|
||||
{ widget: "limit", label: "Limit" },
|
||||
],
|
||||
},
|
||||
// The seed arrives on a socket (forceInput), so the card is the prompt
|
||||
// alone, with its {a|b} choice sets.
|
||||
AUSBOSS_NODES_PromptVariations: {
|
||||
minWidth: 300,
|
||||
rows: [{ widget: "text", kind: "textarea", placeholder: "A woman in a {red|blue|green} {sweater|jacket}. One choice is picked from each set.", height: 100, grow: true }],
|
||||
},
|
||||
// All the words go in the box, and the strip under it shows when each
|
||||
// moment plays. The pictures, the video, the voice and the song arrive on
|
||||
// sockets, and each picture's job sits under the words.
|
||||
@@ -424,50 +377,24 @@ const CARDS = {
|
||||
],
|
||||
},
|
||||
AUSBOSS_NODES_LoadVideo: {
|
||||
// Every nth and the frame limit (as Duration) are in the timing card
|
||||
// under the player (js/load_video). The card hides them, so App mode can
|
||||
// still show them as fields.
|
||||
minWidth: 320, first: true, hide: ["upload", "every_nth", "max_frames"],
|
||||
minWidth: 320, first: true, hide: ["upload"],
|
||||
rows: [
|
||||
{ widget: "video", label: "Source", kind: "select", preview: { kind: "video", url: viewUrl },
|
||||
button: { text: PANEL_LABELS.load, title: "Upload a video into ComfyUI's input folder", onClick: (node) => node.widgets?.find((w) => w.name === "upload")?.callback?.() } },
|
||||
{ widget: "custom_width", label: "Width", suffix: "px", title: "0 keeps the source width; set one side only to keep the aspect." },
|
||||
{ widget: "custom_height", label: "Height", suffix: "px", title: "0 keeps the source height; set one side only to keep the aspect." },
|
||||
{ widget: "every_nth", label: "Every nth" },
|
||||
{ widget: "max_frames", label: "Limit" },
|
||||
],
|
||||
},
|
||||
AUSBOSS_NODES_LoadAudio: {
|
||||
// The wave and Start, Duration and Ends at live in the panel under the
|
||||
// card (js/load_audio); max_seconds is the Duration there. The card
|
||||
// hides it, so App mode can still show it as a field.
|
||||
minWidth: 280, first: true, hide: ["upload", "max_seconds"],
|
||||
// The wave, IN and OUT live in the panel under the card (js/load_audio).
|
||||
minWidth: 280, first: true, hide: ["upload"],
|
||||
rows: [
|
||||
{ widget: "audio", label: "Source", kind: "select",
|
||||
button: { text: PANEL_LABELS.load, title: "Upload a sound file into ComfyUI's input folder", onClick: (node) => node.widgets?.find((w) => w.name === "upload")?.callback?.() } },
|
||||
],
|
||||
},
|
||||
// Load Image: the file, then where it is in the folder and the size it
|
||||
// goes in and comes out at, then the size settings. ComfyUI's own picture
|
||||
// preview sits under the card, so its mask editor and copy and paste work
|
||||
// as they do on the stock loader.
|
||||
AUSBOSS_NODES_LoadImage: {
|
||||
minWidth: 320, first: true, hide: ["upload"],
|
||||
rows: [
|
||||
{ widget: "image", label: "Source", kind: "select", preview: { kind: "image", url: viewUrl },
|
||||
button: { text: PANEL_LABELS.load, title: "Upload a picture into ComfyUI's input folder", onClick: (node) => node.widgets?.find((w) => w.name === "upload")?.callback?.() } },
|
||||
{ panel: loadImageStrip, height: 26 },
|
||||
{ panel: loadImagePreview, height: 72 },
|
||||
{ widget: "size", label: "Size", kind: "select" },
|
||||
{ widget: "megapixels", label: "Megapixels", suffix: "MP", when: isMode("size", "megapixels") },
|
||||
{ widget: "longest_side", label: "Longest side", suffix: "px", when: isMode("size", "longest side") },
|
||||
{ widget: "scale", label: "Scale", suffix: "\u00d7", when: isMode("size", "scale") },
|
||||
{ widget: "ratio", label: "Ratio", kind: "select", when: isMode("size", "crop to ratio") },
|
||||
{ widget: "width", label: "Width", suffix: "px", when: loadImageUsesBox },
|
||||
{ widget: "height", label: "Height", suffix: "px", when: loadImageUsesBox },
|
||||
{ widget: "crop_from", label: "Keep", kind: "select", when: isMode("size", "crop to fill", "crop", "crop to ratio") },
|
||||
{ widget: "multiple", label: "Round to", snap: true, step: 8, when: (values) => values.size !== "off" },
|
||||
{ group: "more", label: "More" },
|
||||
{ widget: "method", label: "Method", kind: "select", group: "more" },
|
||||
{ widget: "enlarge", label: "Enlarge", group: "more" },
|
||||
{ widget: "max_seconds", label: "Max length", suffix: "s", decimals: 1, trimZeros: true,
|
||||
title: "The longest the sound may be. Anything past it is cut off and shows in red. 0 means no limit." },
|
||||
],
|
||||
},
|
||||
AUSBOSS_NODES_LoadImagePad: {
|
||||
|
||||
+19
-63
@@ -15,11 +15,10 @@ import { app } from "../../../scripts/app.js";
|
||||
import { setTileFace, TILE_FACE_CSS } from "../shared/tile_face.mjs";
|
||||
import { NOTE_TYPES, serializeNoteIdentity } from "../shared/note_identity.mjs";
|
||||
import { compactAction } from "../shared/panel_controls.mjs";
|
||||
import { BRAND, chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange, showToast } from "../shared/index.mjs";
|
||||
import { BRAND, chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange } from "../shared/index.mjs";
|
||||
import { collectGraphNodes } from "../shared/appearance.mjs";
|
||||
import { copyToClipboard } from "../shared/clipboard.mjs";
|
||||
import { confirmDiscard } from "../shared/discard_prompt.mjs";
|
||||
import { closeOnBackdropClick } from "../shared/dialog_backdrop.mjs";
|
||||
import { WIDGET_FRAME, fillNodeHeight, holdNodeMinHeight } from "../shared/panel_layout.mjs";
|
||||
import { hideInputsInDef, hideWidget } from "../shared/widget_visibility.mjs";
|
||||
import { suppressCoreImagePreview } from "../shared/core_preview.mjs";
|
||||
@@ -38,7 +37,6 @@ import {
|
||||
noteIsEmpty,
|
||||
noteShowsTileFace,
|
||||
normalizeNote,
|
||||
onlyCopy,
|
||||
packsFromGraph,
|
||||
parseMarkdown,
|
||||
rowFromCells,
|
||||
@@ -47,36 +45,8 @@ import {
|
||||
} from "../shared/workflow_note.mjs";
|
||||
import { comboValues, commitWidgetValue } from "../shared/widget_card_math.mjs";
|
||||
import { parseRows, serializeRows } from "../shared/lora_stack.mjs";
|
||||
import { isFileWidget } from "../shared/lora_file_widgets.mjs";
|
||||
|
||||
const CSS_ID = "ausboss-workflow-note-css";
|
||||
const PICK_FOUND_SETTING = "AusBoss.Models.PickFoundCopy";
|
||||
|
||||
function pickFoundCopies() {
|
||||
return app.ui?.settings?.getSettingValue?.(PICK_FOUND_SETTING) !== false;
|
||||
}
|
||||
|
||||
// Point the loaders (and LoRA Loader rows) that ask for a file by another
|
||||
// spelling at the copy the note found. Returns how many it changed.
|
||||
function useFoundCopy(path, loaders, loraRows, files) {
|
||||
for (const entry of loaders) {
|
||||
commitWidgetValue(entry.node, entry.widget, listedSpelling(path, entry.options), app.canvas);
|
||||
entry.node.setDirtyCanvas?.(true, true);
|
||||
}
|
||||
const stacks = new Map();
|
||||
for (const entry of loraRows) stacks.set(entry.widget, [...(stacks.get(entry.widget) ?? []), entry]);
|
||||
for (const [widget, entries] of stacks) {
|
||||
const rows = parseRows(widget.value);
|
||||
for (const entry of entries) {
|
||||
if (rows[entry.index]) rows[entry.index] = { ...rows[entry.index], name: listedSpelling(path, files) };
|
||||
}
|
||||
commitWidgetValue(entries[0].node, widget, serializeRows(rows), app.canvas);
|
||||
entries[0].node.setDirtyCanvas?.(true, true);
|
||||
}
|
||||
app.graph?.setDirtyCanvas?.(true, true);
|
||||
notifyAusbossChange();
|
||||
return loaders.length + loraRows.length;
|
||||
}
|
||||
const WIDGET_NAME = "ausboss_workflow_note_panel";
|
||||
const PANEL_MIN_WIDTH = 300;
|
||||
const CARD_MIN_HEIGHT = 160;
|
||||
@@ -446,7 +416,22 @@ function modelRow(state, row) {
|
||||
use.title = `Point ${names} at ${path}.`;
|
||||
use.addEventListener("pointerdown", (event) => event.stopPropagation());
|
||||
use.addEventListener("click", () => {
|
||||
useFoundCopy(path, loaders, loraRows, files);
|
||||
for (const entry of loaders) {
|
||||
commitWidgetValue(entry.node, entry.widget, listedSpelling(path, entry.options), app.canvas);
|
||||
entry.node.setDirtyCanvas?.(true, true);
|
||||
}
|
||||
const stacks = new Map();
|
||||
for (const entry of loraRows) stacks.set(entry.widget, [...(stacks.get(entry.widget) ?? []), entry]);
|
||||
for (const [widget, entries] of stacks) {
|
||||
const rows = parseRows(widget.value);
|
||||
for (const entry of entries) {
|
||||
if (rows[entry.index]) rows[entry.index] = { ...rows[entry.index], name: listedSpelling(path, files) };
|
||||
}
|
||||
commitWidgetValue(entries[0].node, widget, serializeRows(rows), app.canvas);
|
||||
entries[0].node.setDirtyCanvas?.(true, true);
|
||||
}
|
||||
app.graph?.setDirtyCanvas?.(true, true);
|
||||
notifyAusbossChange();
|
||||
checkModels(state, false);
|
||||
});
|
||||
action.append(pill, use);
|
||||
@@ -566,7 +551,6 @@ function render(state) {
|
||||
if (note.author) header.append(el("p", "", `by ${note.author}`));
|
||||
dialog.append(header);
|
||||
renderSections({ note, rows: [] }, dialog);
|
||||
closeOnBackdropClick(dialog);
|
||||
document.body.append(dialog);
|
||||
state.reader = dialog;
|
||||
dialog.addEventListener("close", () => {
|
||||
@@ -642,7 +626,6 @@ function renderSections(state, scroll) {
|
||||
async function checkModels(state, fresh) {
|
||||
const generation = (state.checkGeneration = (state.checkGeneration || 0) + 1);
|
||||
const rows = state.rows;
|
||||
const picked = [];
|
||||
for (const entry of rows) setDot(entry.dot, "checking", "checking…");
|
||||
const byDir = new Map();
|
||||
for (const entry of rows) {
|
||||
@@ -681,14 +664,7 @@ async function checkModels(state, fresh) {
|
||||
const elsewhere = match.found && subfolderOf(match.path);
|
||||
const loaders = elsewhere ? loadersNeeding(entry.row.name, match.path, graphListWidgets()) : [];
|
||||
const loraRows = elsewhere ? loraRowsNeeding(entry.row.name, match.path, graphLoraLoaders(), files) : [];
|
||||
if (match.found && (loaders.length || loraRows.length) && pickFoundCopies() && onlyCopy(entry.row.name, files) === match.path) {
|
||||
// One copy, so nothing to choose: the loaders take it without a
|
||||
// click (App mode shows no Guide to click in).
|
||||
useFoundCopy(match.path, loaders, loraRows, files);
|
||||
picked.push(match.path);
|
||||
setDot(entry.dot, "ok", `Found in ${subfolderOf(match.path)}/ and picked: ${match.path}`);
|
||||
entry.showInstalled(match.path);
|
||||
} else if (match.found && (loaders.length || loraRows.length)) {
|
||||
if (match.found && (loaders.length || loraRows.length)) {
|
||||
setDot(entry.dot, "ok", `Found in ${subfolderOf(match.path)}/: ${match.path}`);
|
||||
entry.showElsewhere(match.path, loaders, loraRows, files);
|
||||
} else if (match.found) {
|
||||
@@ -700,14 +676,6 @@ async function checkModels(state, fresh) {
|
||||
}
|
||||
}
|
||||
}));
|
||||
if (picked.length && generation === state.checkGeneration) {
|
||||
const folders = [...new Set(picked.map(subfolderOf))].map((folder) => `${folder}/`).join(", ");
|
||||
showToast({
|
||||
summary: "Models found",
|
||||
detail: `${picked.length === 1 ? "1 model file" : `${picked.length} model files`} found in ${folders} and picked for this workflow.`,
|
||||
life: 4000,
|
||||
});
|
||||
}
|
||||
if (state.domWidget && generation === state.checkGeneration) fitNote(state);
|
||||
}
|
||||
|
||||
@@ -786,7 +754,7 @@ function graphListWidgets() {
|
||||
seen.add(graph);
|
||||
for (const node of graph._nodes ?? graph.nodes ?? []) {
|
||||
for (const widget of node.widgets ?? []) {
|
||||
if (widget?.type !== "combo" || typeof widget.value !== "string" || isFileWidget(widget)) continue;
|
||||
if (widget?.type !== "combo" || typeof widget.value !== "string") continue;
|
||||
out.push({ node, widget, value: widget.value, options: comboValues(widget) });
|
||||
}
|
||||
if (node.subgraph) walk(node.subgraph);
|
||||
@@ -1208,18 +1176,6 @@ function buildPanel(node) {
|
||||
|
||||
app.registerExtension({
|
||||
name: "AusBoss.WorkflowNote",
|
||||
settings: [
|
||||
{
|
||||
id: PICK_FOUND_SETTING,
|
||||
name: "Pick model files found in a subfolder",
|
||||
type: "boolean",
|
||||
defaultValue: true,
|
||||
category: ["🆎 AusBoss", "Models", "Pick found files"],
|
||||
tooltip:
|
||||
"When a workflow's Guide finds a model you already have in a subfolder, the workflow switches to that "
|
||||
+ "file by itself. Off: the Guide shows a Use it button instead.",
|
||||
},
|
||||
],
|
||||
beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (!NOTE_TYPES.has(nodeData?.name)) return;
|
||||
hideInputsInDef(nodeData, ["note"]);
|
||||
|
||||
@@ -604,7 +604,7 @@ function newSwitch(state) {
|
||||
// has choices the nodes they hold, so the next one takes no selecting.
|
||||
function choiceSnapshots(state, nodes) {
|
||||
const graph = state.node.graph;
|
||||
const held = choiceNodeIds(settingsOf(state.node)).map((id) => graph?.getNodeById?.(id)).filter(Boolean);
|
||||
const held = choiceNodeIds(settingsOf(state.node)).map((id) => graph?.getNodeById?.(Number(id))).filter(Boolean);
|
||||
return [...new Set([...nodes, ...held])]
|
||||
.map((node) => ({ id: node.id, values: snapshotNode(node) }))
|
||||
.filter((item) => Object.keys(item.values).length);
|
||||
@@ -1156,7 +1156,7 @@ function refresh(state) {
|
||||
// The selection only shows in the edit view (the + Switch bar).
|
||||
const pick = edit ? picked(state) : { nodes: [], groups: [], count: 0 };
|
||||
const signature = [
|
||||
rowsSignature(rows, settings, rowKey), groups.length, edit, settingsOpen(node), pick.count, pick.nodes.length,
|
||||
rowsSignature(rows, settings, rowKey), groups.length, edit, settingsOpen(node), pick.count,
|
||||
].join("|");
|
||||
if (signature === state.signature) return;
|
||||
state.signature = signature;
|
||||
@@ -1166,7 +1166,7 @@ function refresh(state) {
|
||||
// Called on every canvas redraw: read the graph again at most every
|
||||
// RECHECK_MS, and always once after the last redraw.
|
||||
function scheduleCheck(state) {
|
||||
if (state.disposed || !state.node.graph || state.timer !== null) return;
|
||||
if (state.disposed || state.timer !== null) return;
|
||||
const shown = app.canvas?.getCurrentGraph?.() ?? app.canvas?.graph;
|
||||
if (state.node.graph && shown && state.node.graph !== shown) return;
|
||||
const wait = Math.max(0, state.checkedAt + RECHECK_MS - performance.now());
|
||||
@@ -1254,6 +1254,7 @@ function buildPanel(node) {
|
||||
trimNodeBottom(node);
|
||||
state.widget = widget;
|
||||
|
||||
live.add(state);
|
||||
ensureRedrawHook();
|
||||
return state;
|
||||
}
|
||||
|
||||
+10
-188
@@ -172,64 +172,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"AUSBOSS_NODES_EditLock": {
|
||||
"display_name": "编辑锁定 🆎",
|
||||
"description": "让图片里编辑没有改动的部分保持在原位,颜色也不变。编辑模型会把整张图重画一遍,没改的部分常常略微放大、偏移或偏色。把这个节点放在模型和采样器之间,并接上你要编辑的图片。不需要遮罩:它在出图过程中看出编辑改了哪里。如果编辑改变的是整张图(新风格、新光线、新天气),它会自动让开。解码后再接上编辑锁定还原 🆎,未改动的部分就能换回你原图的像素。",
|
||||
"inputs": {
|
||||
"model": {
|
||||
"name": "模型"
|
||||
},
|
||||
"vae": {
|
||||
"name": "vae"
|
||||
},
|
||||
"image": {
|
||||
"name": "图像"
|
||||
},
|
||||
"lock": {
|
||||
"name": "锁定"
|
||||
},
|
||||
"tolerance": {
|
||||
"name": "容差"
|
||||
},
|
||||
"mask": {
|
||||
"name": "遮罩"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "模型"
|
||||
},
|
||||
"1": {
|
||||
"name": "编辑锁"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AUSBOSS_NODES_EditLockRestore": {
|
||||
"display_name": "编辑锁定还原 🆎",
|
||||
"description": "把编辑没有改动的部分换回你原图自己的像素。放在 VAE 解码之后,并接上编辑锁定 🆎 的 edit_lock 输出。未改动的部分与原图逐像素一致,只有编辑的部分是新的。如果锁定让开了,图片原样通过。",
|
||||
"inputs": {
|
||||
"image": {
|
||||
"name": "图像"
|
||||
},
|
||||
"edit_lock": {
|
||||
"name": "编辑锁"
|
||||
},
|
||||
"feather": {
|
||||
"name": "羽化"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "图像"
|
||||
},
|
||||
"1": {
|
||||
"name": "编辑遮罩"
|
||||
},
|
||||
"2": {
|
||||
"name": "报告"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AUSBOSS_NODES_Float": {
|
||||
"display_name": "浮点数 🆎",
|
||||
"description": "一个独立的 FLOAT 值。在多个节点之间共用同一个强度、缩放或 CFG,只需在一处修改。",
|
||||
@@ -651,71 +593,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"AUSBOSS_NODES_LoadImage": {
|
||||
"display_name": "加载图像 🆎",
|
||||
"description": "在同一个节点里加载图片并设定尺寸。可以选择文件、上传,或用箭头逐张浏览输入文件夹。尺寸可以关闭,也可以按百万像素、最长边、缩放倍数、放入一个框内,或裁剪填满一个框来调整。也可以不缩放,直接从图片中裁出一块或裁成某个比例,并选择保留哪一边。运行之前,节点就会显示输入和输出的图片及两者的尺寸。",
|
||||
"inputs": {
|
||||
"image": {
|
||||
"name": "图像"
|
||||
},
|
||||
"size": {
|
||||
"name": "尺寸"
|
||||
},
|
||||
"megapixels": {
|
||||
"name": "百万像素"
|
||||
},
|
||||
"longest_side": {
|
||||
"name": "最长边"
|
||||
},
|
||||
"scale": {
|
||||
"name": "缩放倍数"
|
||||
},
|
||||
"width": {
|
||||
"name": "宽度"
|
||||
},
|
||||
"height": {
|
||||
"name": "高度"
|
||||
},
|
||||
"multiple": {
|
||||
"name": "取整倍数"
|
||||
},
|
||||
"method": {
|
||||
"name": "插值"
|
||||
},
|
||||
"enlarge": {
|
||||
"name": "放大"
|
||||
},
|
||||
"crop_from": {
|
||||
"name": "保留部分"
|
||||
},
|
||||
"ratio": {
|
||||
"name": "比例"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "图像"
|
||||
},
|
||||
"1": {
|
||||
"name": "遮罩"
|
||||
},
|
||||
"2": {
|
||||
"name": "宽度"
|
||||
},
|
||||
"3": {
|
||||
"name": "高度"
|
||||
},
|
||||
"4": {
|
||||
"name": "文件名"
|
||||
},
|
||||
"5": {
|
||||
"name": "原始宽度"
|
||||
},
|
||||
"6": {
|
||||
"name": "原始高度"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AUSBOSS_NODES_LoadImagePad": {
|
||||
"display_name": "加载图像 + 扩边 🆎",
|
||||
"description": "在一个节点里加载图像并扩边成扩图画布。拖动节点上画布的任意一边,直观地设置每边的扩边量;遮罩正好覆盖新扩出的部分,可选择向内羽化跨过接缝。画布会取整到整数倍,但不会给你没扩的边加条带;设置百万像素目标时会先缩放原图,让遮罩接缝保持清晰。",
|
||||
@@ -1175,9 +1052,6 @@
|
||||
},
|
||||
"step_preview": {
|
||||
"name": "步骤预览"
|
||||
},
|
||||
"autosave": {
|
||||
"name": "自动保存"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
@@ -1366,35 +1240,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"AUSBOSS_NODES_TextLines": {
|
||||
"display_name": "逐行文本 🆎",
|
||||
"description": "文本的每一行都会让后面的节点运行一次。输入五条提示词,每行一条,运行一次就得到五张图。空行会跳过,行首的序号或项目符号可以去掉。",
|
||||
"inputs": {
|
||||
"text": {
|
||||
"name": "文本"
|
||||
},
|
||||
"split": {
|
||||
"name": "分隔方式"
|
||||
},
|
||||
"remove_numbering": {
|
||||
"name": "去掉序号"
|
||||
},
|
||||
"limit": {
|
||||
"name": "上限"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "行"
|
||||
},
|
||||
"1": {
|
||||
"name": "序号"
|
||||
},
|
||||
"2": {
|
||||
"name": "数量"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AUSBOSS_NODES_TiledUpscale": {
|
||||
"display_name": "分块放大 🆎",
|
||||
"description": "以百万像素设置成品尺寸,并把图片切成模型可以逐块重画的图块。一块就能装下的图片保持完整。把图块送进采样器,再和 stitcher 一起送进分块放大拼合 🆎。小图不会被重画到远超其细节的程度:最多重画到原百万像素的 max_growth 倍,再用普通方式放大。report 会说明对你的图片做了什么。",
|
||||
@@ -1747,46 +1592,23 @@
|
||||
"display_name": "工作流说明卡片 🆎",
|
||||
"description": "点击打开完整说明的小按钮。点击铅笔编辑,拖动角落调整大小。旧版节点包会将它显示为缺失节点,请更新 ComfyUI-AusBoss。"
|
||||
},
|
||||
"AUSBOSS_NODES_FlashVSRUpscale": {
|
||||
"display_name": "FlashVSR 视频放大 🆎",
|
||||
"description": "用 FlashVSR 模型把视频放大并变清晰。选好模型文件,设定放大倍数,然后运行。节点每次只读取几帧,所以长视频和短视频占用的显存一样多,每一帧都会返回。接上 Wan 2.1 VAE 可以得到更慢但更细致的结果。",
|
||||
"AUSBOSS_NODES_CameraMove": {
|
||||
"display_name": "镜头移动 🆎",
|
||||
"description": "移动视频的镜头。在节点画面上拖动来转动镜头,捏合或滚轮拉远推近,并在时间轴上设置关键帧。原镜头从未拍到的地方显示为粉色,交给 CrossView-Warp LoRA 补画。需要 MoGe Inference 的深度。",
|
||||
"inputs": {
|
||||
"frames": {
|
||||
"name": "帧"
|
||||
"moge_geometry": {
|
||||
"name": "MoGe 几何"
|
||||
},
|
||||
"model": {
|
||||
"name": "模型"
|
||||
},
|
||||
"scale": {
|
||||
"name": "放大倍数"
|
||||
},
|
||||
"color_match": {
|
||||
"name": "保留颜色"
|
||||
},
|
||||
"vae": {
|
||||
"name": "vae"
|
||||
"camera": {
|
||||
"name": "镜头关键帧"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "帧"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AUSBOSS_NODES_PromptVariations": {
|
||||
"display_name": "提示词变体 🆎",
|
||||
"description": "每次运行都会变化的提示词框。把选项写在花括号里,例如 {红色|蓝色|绿色} 的 {毛衣|夹克},节点会从每组里选一个。种子决定选哪个:同一个种子得到同一个提示词,每次换新种子就得到新的组合。没有花括号的文字原样输出。",
|
||||
"inputs": {
|
||||
"text": {
|
||||
"name": "文本"
|
||||
"name": "引导"
|
||||
},
|
||||
"seed": {
|
||||
"name": "种子"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "提示词"
|
||||
"1": {
|
||||
"name": "空洞"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,428 @@
|
||||
"""Camera Move: the camera keys, the camera's pose and the depth warp.
|
||||
|
||||
The keys are what the node's face writes: a list of moments on the clip
|
||||
(t from 0 to 1) and where the camera is at each one. The camera passes
|
||||
through every key without slowing down, and starts and ends gently. The face draws its picture with the
|
||||
same maths, so what you steer on the node is what the warp makes.
|
||||
|
||||
Axes are OpenCV's: x right, y down, z into the picture. Each frame's points
|
||||
stay where the original camera saw them; only the camera moves.
|
||||
|
||||
Technical details
|
||||
-----------------
|
||||
A key holds az (turn, degrees, right is positive), el (rise, degrees, up is
|
||||
positive), back (pull back, in distances to the pivot; negative pushes in),
|
||||
px and py (slide right and down, in distances to the pivot).
|
||||
|
||||
R = Ry(-az) . Rx(-el)
|
||||
C = pivot - R.pivot + R.[px.d, py.d, -back.d] d = |pivot|
|
||||
|
||||
A point P lands in the new camera at R^T (P - C). The pivot is the spot the
|
||||
camera circles: picked by a tap on the face, else what sits in the middle
|
||||
of the first frame.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
|
||||
LIMITS = {"az": (-90.0, 90.0), "el": (-30.0, 60.0), "back": (-0.6, 2.0), "px": (-1.0, 1.0), "py": (-1.0, 1.0)}
|
||||
FIELDS = tuple(LIMITS)
|
||||
HOME = {name: 0.0 for name in FIELDS}
|
||||
# Where the LoRA was trained to work well. Past this the face warns.
|
||||
LORA_RANGE = {"az": 45.0, "el_up": 30.0, "el_down": -20.0}
|
||||
# Two keys within this much of the clip are the same key.
|
||||
SAME_KEY = 0.015
|
||||
MAX_KEYS = 64
|
||||
MAGENTA = (1.0, 0.0, 1.0)
|
||||
# The nearest thing in the middle of the first frame, never further than this
|
||||
# (in the depth model's metres): the move stays a move, not a flight.
|
||||
PIVOT_CAP = 3.0
|
||||
SCENE_LONG_SIDE = 416
|
||||
# Every second frame of a 5-second clip, so the face plays smoothly (about 190 KB a frame).
|
||||
SCENE_FRAMES = 61
|
||||
|
||||
DEFAULT_CAMERA = {
|
||||
"v": 1,
|
||||
"keys": [{"t": 0.0, **HOME}, {"t": 1.0, **HOME, "az": 30.0, "el": 5.0}],
|
||||
"pivot": None,
|
||||
}
|
||||
|
||||
|
||||
def default_camera_text() -> str:
|
||||
return json.dumps(DEFAULT_CAMERA, separators=(",", ":"))
|
||||
|
||||
|
||||
def _number(value, fallback=0.0) -> float:
|
||||
try:
|
||||
number = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return fallback
|
||||
return number if math.isfinite(number) else fallback
|
||||
|
||||
|
||||
def _clamp(value, low, high):
|
||||
return max(low, min(high, value))
|
||||
|
||||
|
||||
def clean_key(raw) -> dict:
|
||||
"""One key with every field present, inside its limits."""
|
||||
raw = raw if isinstance(raw, dict) else {}
|
||||
key = {"t": _clamp(_number(raw.get("t")), 0.0, 1.0)}
|
||||
for name, (low, high) in LIMITS.items():
|
||||
key[name] = _clamp(_number(raw.get(name)), low, high)
|
||||
return key
|
||||
|
||||
|
||||
def parse_camera(text) -> dict:
|
||||
"""The camera the face wrote. Anything unreadable falls back to the default move.
|
||||
|
||||
Returns {"keys": [...], "pivot": None | {"u", "v", "t"}, "fallback": bool}.
|
||||
Keys come back sorted by time, with keys at the same moment merged (the
|
||||
later one wins), and never empty.
|
||||
"""
|
||||
data = None
|
||||
if isinstance(text, dict):
|
||||
data = text
|
||||
elif isinstance(text, str) and text.strip():
|
||||
try:
|
||||
data = json.loads(text)
|
||||
except (ValueError, RecursionError):
|
||||
data = None
|
||||
fallback = not isinstance(data, dict) or not isinstance(data.get("keys"), list) or not data["keys"]
|
||||
if fallback:
|
||||
data = DEFAULT_CAMERA
|
||||
keys = []
|
||||
for raw in data["keys"][:MAX_KEYS]:
|
||||
key = clean_key(raw)
|
||||
same = next((k for k in keys if abs(k["t"] - key["t"]) < SAME_KEY), None)
|
||||
if same is not None:
|
||||
same.update(key)
|
||||
else:
|
||||
keys.append(key)
|
||||
keys.sort(key=lambda k: k["t"])
|
||||
pivot = data.get("pivot")
|
||||
if isinstance(pivot, dict) and all(name in pivot for name in ("u", "v")):
|
||||
pivot = {
|
||||
"u": _clamp(_number(pivot.get("u"), 0.5), 0.0, 1.0),
|
||||
"v": _clamp(_number(pivot.get("v"), 0.5), 0.0, 1.0),
|
||||
"t": _clamp(_number(pivot.get("t"), 0.0), 0.0, 1.0),
|
||||
}
|
||||
else:
|
||||
pivot = None
|
||||
return {"keys": keys, "pivot": pivot, "fallback": fallback}
|
||||
|
||||
|
||||
def _key_slopes(ts, ys):
|
||||
"""How fast one field moves as it passes each key.
|
||||
|
||||
Zero at the first and last key, so the move starts and ends gently. Zero
|
||||
at a key where the field turns back or holds, so it never runs past a
|
||||
key. Elsewhere it keeps its speed through the key (Fritsch-Butland), so
|
||||
a long move made of several keys does not slow down at each one.
|
||||
"""
|
||||
n = len(ys)
|
||||
slopes = [0.0] * n
|
||||
for k in range(1, n - 1):
|
||||
h0, h1 = ts[k] - ts[k - 1], ts[k + 1] - ts[k]
|
||||
if h0 <= 0 or h1 <= 0:
|
||||
continue
|
||||
d0, d1 = (ys[k] - ys[k - 1]) / h0, (ys[k + 1] - ys[k]) / h1
|
||||
if d0 * d1 > 0:
|
||||
slopes[k] = 3.0 * (h0 + h1) / ((2.0 * h1 + h0) / d0 + (h1 + 2.0 * h0) / d1)
|
||||
return slopes
|
||||
|
||||
|
||||
def camera_at(keys, t: float) -> dict:
|
||||
"""Where the camera is at moment t (0..1): through every key, gently at the ends."""
|
||||
if not keys:
|
||||
return dict(HOME)
|
||||
first, last = keys[0], keys[-1]
|
||||
if len(keys) == 1 or t <= first["t"]:
|
||||
return {name: first[name] for name in FIELDS}
|
||||
if t >= last["t"]:
|
||||
return {name: last[name] for name in FIELDS}
|
||||
ts = [k["t"] for k in keys]
|
||||
for i in range(len(keys) - 1):
|
||||
a, b = keys[i], keys[i + 1]
|
||||
if a["t"] <= t <= b["t"]:
|
||||
h = max(1e-6, b["t"] - a["t"])
|
||||
s = (t - a["t"]) / h
|
||||
h00, h10, h01, h11 = 2 * s**3 - 3 * s**2 + 1, s**3 - 2 * s**2 + s, -2 * s**3 + 3 * s**2, s**3 - s**2
|
||||
out = {}
|
||||
for name in FIELDS:
|
||||
m = _key_slopes(ts, [k[name] for k in keys])
|
||||
out[name] = h00 * a[name] + h10 * h * m[i] + h01 * b[name] + h11 * h * m[i + 1]
|
||||
return out
|
||||
return {name: last[name] for name in FIELDS}
|
||||
|
||||
|
||||
def frame_moments(count: int) -> list[float]:
|
||||
"""The moment (0..1) of each frame. One frame sits at the start."""
|
||||
if count <= 1:
|
||||
return [0.0] * max(0, count)
|
||||
return [i / (count - 1) for i in range(count)]
|
||||
|
||||
|
||||
def rotation(az: float, el: float) -> list[list[float]]:
|
||||
"""R = Ry(-az) . Rx(-el): az > 0 swings the camera right, el > 0 lifts it."""
|
||||
th, ph = math.radians(-az), math.radians(-el)
|
||||
ct, st, cp, sp = math.cos(th), math.sin(th), math.cos(ph), math.sin(ph)
|
||||
return [[ct, st * sp, st * cp], [0.0, cp, -sp], [-st, ct * sp, ct * cp]]
|
||||
|
||||
|
||||
def _mv(R, v):
|
||||
return [sum(R[r][c] * v[c] for c in range(3)) for r in range(3)]
|
||||
|
||||
|
||||
def pose(cam: dict, pivot) -> tuple[list[list[float]], list[float]]:
|
||||
"""The moved camera's rotation R and centre C, for a key and a pivot point."""
|
||||
R = rotation(cam["az"], cam["el"])
|
||||
d = math.sqrt(sum(x * x for x in pivot))
|
||||
Rp = _mv(R, pivot)
|
||||
b = _mv(R, [cam.get("px", 0.0) * d, cam.get("py", 0.0) * d, -cam["back"] * d])
|
||||
return R, [pivot[i] - Rp[i] + b[i] for i in range(3)]
|
||||
|
||||
|
||||
def past_lora_range(cam: dict) -> bool:
|
||||
return abs(cam["az"]) > LORA_RANGE["az"] or cam["el"] > LORA_RANGE["el_up"] or cam["el"] < LORA_RANGE["el_down"]
|
||||
|
||||
|
||||
def range_report(keys) -> str:
|
||||
"""One plain line when a key goes past where the LoRA was trained, else empty."""
|
||||
over = [k for k in keys if past_lora_range(k)]
|
||||
if not over:
|
||||
return ""
|
||||
when = ", ".join(f"{k['t']:.2f}" for k in over[:4])
|
||||
return (
|
||||
f"Camera Move: {len(over)} key(s) past the LoRA's range (at {when} of the clip). "
|
||||
"It learned up to 45 degrees of turn, 30 up and 20 down; more may leave pink."
|
||||
)
|
||||
|
||||
|
||||
def scene_frame_indices(count: int, most: int = SCENE_FRAMES) -> list[int]:
|
||||
"""Which frames the face gets to look at: evenly spread, first and last included."""
|
||||
if count <= 0:
|
||||
return []
|
||||
if count <= most:
|
||||
return list(range(count))
|
||||
return sorted({round(i * (count - 1) / (most - 1)) for i in range(most)})
|
||||
|
||||
|
||||
def scene_size(width: int, height: int, long_side: int = SCENE_LONG_SIDE) -> tuple[int, int]:
|
||||
scale = min(1.0, long_side / max(width, height))
|
||||
return max(1, round(width * scale)), max(1, round(height * scale))
|
||||
|
||||
|
||||
def pack_depth(z, valid, zmin: float, zmax: float):
|
||||
"""Depth as two bytes a pixel (red high, green low) on a log scale; 0 is no depth.
|
||||
|
||||
z and valid are numpy arrays. Returns an (H, W, 3) uint8 array.
|
||||
"""
|
||||
import numpy as np
|
||||
|
||||
lo, hi = math.log(max(zmin, 1e-6)), math.log(max(zmax, zmin * 1.0001, 1e-6))
|
||||
q = np.zeros(z.shape, dtype=np.uint32)
|
||||
if valid.any():
|
||||
zz = np.clip(z[valid], math.exp(lo), math.exp(hi))
|
||||
q[valid] = 1 + np.round((np.log(zz) - lo) / max(1e-9, hi - lo) * 65534).astype(np.uint32)
|
||||
out = np.zeros(z.shape + (3,), dtype=np.uint8)
|
||||
out[..., 0] = (q >> 8) & 255
|
||||
out[..., 1] = q & 255
|
||||
return out
|
||||
|
||||
|
||||
def unpack_depth(rgb, zmin: float, zmax: float, far: float):
|
||||
"""The face's reading of pack_depth, for tests."""
|
||||
import numpy as np
|
||||
|
||||
q = rgb[..., 0].astype(np.uint32) * 256 + rgb[..., 1].astype(np.uint32)
|
||||
lo, hi = math.log(zmin), math.log(zmax)
|
||||
z = np.exp(lo + (q.astype(np.float64) - 1) / 65534 * (hi - lo))
|
||||
return np.where(q == 0, far, z), q > 0
|
||||
|
||||
|
||||
# -- the warp (torch) ---------------------------------------------------------
|
||||
|
||||
|
||||
def pixel_intrinsics(K, width: int, height: int):
|
||||
"""MoGe's lens as pixels; it may come normalised to the picture size."""
|
||||
K = K.clone().float()
|
||||
if K[0, 2] < 4:
|
||||
K[0, :] *= width
|
||||
K[1, :] *= height
|
||||
return K
|
||||
|
||||
|
||||
def steady_depth(z, valid, image, radius: int = 4, colour_tol: float = 0.05):
|
||||
"""Calm the depth of things that hold still.
|
||||
|
||||
The depth model looks at every frame afresh, so a wall that never moves
|
||||
still gets a slightly different depth each frame, and the moved camera
|
||||
shakes. A spot whose colour stays the same a few frames either side has
|
||||
its depth averaged over those frames. Anything that changes in that
|
||||
window, such as a person moving, keeps its own depth.
|
||||
"""
|
||||
import torch
|
||||
|
||||
count = z.shape[0]
|
||||
if count < 2 or radius < 1:
|
||||
return z
|
||||
logz = torch.where(valid, z.clamp(min=1e-6).log(), torch.zeros_like(z))
|
||||
out = z.clone()
|
||||
inv = 1.0 / (2.0 * colour_tol * colour_tol)
|
||||
for i in range(count):
|
||||
lo, hi = max(0, i - radius), min(count, i + radius + 1)
|
||||
change = ((image[lo:hi] - image[i]) ** 2).sum(-1).amax(0)
|
||||
held = valid[lo:hi].all(0)
|
||||
still = torch.exp(-change * inv) * held
|
||||
mean = logz[lo:hi].sum(0) / (hi - lo)
|
||||
calm = (still * mean + (1 - still) * logz[i]).exp()
|
||||
out[i] = torch.where(valid[i] & held, calm, z[i])
|
||||
return out
|
||||
|
||||
|
||||
def prepare_geometry(geometry: dict, device=None):
|
||||
"""Points, colours and lens from a MOGE_GEOMETRY, with every frame held to one depth scale.
|
||||
|
||||
The depth model's scale and lens wobble from frame to frame, which shakes
|
||||
the moved picture. Each frame is scaled so its median depth follows a
|
||||
smoothed line through all of them, every frame gets the clip's median
|
||||
lens, and the depth of whatever holds still is calmed (steady_depth).
|
||||
"""
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
points = geometry.get("points")
|
||||
intrinsics = geometry.get("intrinsics")
|
||||
if points is None or intrinsics is None:
|
||||
raise ValueError(
|
||||
"Camera Move needs depth from MoGe Inference with its camera lens. "
|
||||
"Connect MoGe Inference's geometry, not a panorama."
|
||||
)
|
||||
points = points.float()
|
||||
count, height, width, _ = points.shape
|
||||
image = geometry["image"][..., :3].float()
|
||||
if image.shape[1:3] != (height, width):
|
||||
image = F.interpolate(image.movedim(-1, 1), size=(height, width), mode="bilinear", align_corners=False).movedim(1, -1)
|
||||
z = points[..., 2]
|
||||
valid = torch.isfinite(points).all(-1) & (z > 0)
|
||||
mask = geometry.get("mask")
|
||||
if mask is not None:
|
||||
valid &= mask.bool().to(valid.device)
|
||||
z = torch.where(valid, z, torch.zeros_like(z))
|
||||
meds = torch.stack([z[i][valid[i]].median() if valid[i].any() else torch.tensor(1.0) for i in range(count)])
|
||||
win = min(15, count) | 1
|
||||
padded = F.pad(meds.log()[None, None], (win // 2, win // 2), mode="replicate")
|
||||
smooth = F.avg_pool1d(padded, win, 1)[0, 0]
|
||||
z = z * (smooth - meds.log()).exp()[:, None, None]
|
||||
if device is not None:
|
||||
z = steady_depth(z.to(device), valid.to(device), image.to(device)).to(z.device)
|
||||
else:
|
||||
z = steady_depth(z, valid, image)
|
||||
# The depth model guesses the lens again for every frame and the guess
|
||||
# wobbles a few percent, which shakes the warp. One lens for the clip.
|
||||
K = torch.stack([pixel_intrinsics(intrinsics[i], width, height) for i in range(count)]).median(dim=0).values
|
||||
Ks = K[None].expand(count, 3, 3).clone()
|
||||
v0 = valid[0]
|
||||
far = float(torch.quantile(z[0][v0][::7], 0.98)) * 2.5 if v0.any() else float(meds.median()) * 10.0
|
||||
return {"z": z, "valid": valid, "image": image, "K": Ks, "far": far, "count": count, "width": width, "height": height}
|
||||
|
||||
|
||||
def unproject(K, x: float, y: float, depth: float) -> list[float]:
|
||||
fx, fy, cx, cy = float(K[0, 0]), float(K[1, 1]), float(K[0, 2]), float(K[1, 2])
|
||||
return [(x - cx) / fx * depth, (y - cy) / fy * depth, depth]
|
||||
|
||||
|
||||
def auto_pivot(scene) -> list[float]:
|
||||
"""What sits in the middle of the first frame: the nearest fifth of the centre box."""
|
||||
import torch
|
||||
|
||||
z0, v0, H, W = scene["z"][0], scene["valid"][0], scene["height"], scene["width"]
|
||||
box = (slice(int(H * 0.35), int(H * 0.65)), slice(int(W * 0.4), int(W * 0.6)))
|
||||
vb = v0[box]
|
||||
if vb.any():
|
||||
depth = float(torch.quantile(z0[box][vb].float(), 0.2))
|
||||
elif v0.any():
|
||||
depth = float(z0[v0].median())
|
||||
else:
|
||||
depth = 1.0
|
||||
return [0.0, 0.0, min(depth, PIVOT_CAP)]
|
||||
|
||||
|
||||
def resolve_pivot(scene, pivot) -> list[float]:
|
||||
"""The 3D spot the camera circles: the tapped one, else the automatic one."""
|
||||
if not pivot:
|
||||
return auto_pivot(scene)
|
||||
count, H, W = scene["count"], scene["height"], scene["width"]
|
||||
i = min(count - 1, max(0, round(pivot["t"] * (count - 1))))
|
||||
x = min(W - 1, max(0, int(pivot["u"] * W)))
|
||||
y = min(H - 1, max(0, int(pivot["v"] * H)))
|
||||
z, valid = scene["z"][i], scene["valid"][i]
|
||||
for r in range(0, 4):
|
||||
y0, y1, x0, x1 = max(0, y - r), min(H, y + r + 1), max(0, x - r), min(W, x + r + 1)
|
||||
patch = valid[y0:y1, x0:x1]
|
||||
if patch.any():
|
||||
depth = float(z[y0:y1, x0:x1][patch].median())
|
||||
return unproject(scene["K"][i], x + 0.5, y + 0.5, depth)
|
||||
return auto_pivot(scene)
|
||||
|
||||
|
||||
def _fill_cracks(img, filled, passes=2):
|
||||
"""Fill one-pixel gaps that are mostly surrounded by picture."""
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
k = torch.ones(1, 1, 3, 3, device=img.device)
|
||||
for _ in range(passes):
|
||||
f = filled.float()[None, None]
|
||||
cnt = F.conv2d(f, k, padding=1)[0, 0]
|
||||
s = F.conv2d((img * filled.float())[:, None], k, padding=1)[:, 0]
|
||||
take = (~filled) & (cnt >= 5)
|
||||
if not take.any():
|
||||
break
|
||||
img = torch.where(take[None], s / cnt.clamp(min=1), img)
|
||||
filled = filled | take
|
||||
return img, filled
|
||||
|
||||
|
||||
def warp_frame(scene, i: int, cam: dict, pivot, device):
|
||||
"""One frame seen from the moved camera. Returns (colour (H,W,3), hole (H,W) bool) on the CPU."""
|
||||
import torch
|
||||
|
||||
H, W = scene["height"], scene["width"]
|
||||
K = scene["K"][i].to(device)
|
||||
Kinv = torch.linalg.inv(K)
|
||||
valid = scene["valid"][i].to(device)
|
||||
zi = torch.where(valid, scene["z"][i].to(device), torch.full((H, W), scene["far"], device=device))
|
||||
col = scene["image"][i].to(device)
|
||||
sub = torch.tensor([[-0.25, -0.25], [0.25, -0.25], [-0.25, 0.25], [0.25, 0.25]], device=device)
|
||||
vv, uu = torch.meshgrid(torch.arange(H, device=device, dtype=torch.float32), torch.arange(W, device=device, dtype=torch.float32), indexing="ij")
|
||||
u = (uu[None] + 0.5 + sub[:, 0, None, None]).reshape(-1)
|
||||
v = (vv[None] + 0.5 + sub[:, 1, None, None]).reshape(-1)
|
||||
zz = zi[None].expand(4, H, W).reshape(-1)
|
||||
cc = col[None].expand(4, H, W, 3).reshape(-1, 3)
|
||||
P = (torch.stack([u, v, torch.ones_like(u)], -1) @ Kinv.T) * zz[:, None]
|
||||
R_list, C_list = pose(cam, pivot)
|
||||
R = torch.tensor(R_list, dtype=torch.float32, device=device)
|
||||
C = torch.tensor(C_list, dtype=torch.float32, device=device)
|
||||
Pc = (P - C) @ R # R^T (P - C), row vectors
|
||||
zc = Pc[:, 2]
|
||||
ok = zc > 1e-3
|
||||
uv = Pc[:, :2] / zc.clamp(min=1e-3)[:, None]
|
||||
up = K[0, 0] * uv[:, 0] + K[0, 2]
|
||||
vp = K[1, 1] * uv[:, 1] + K[1, 2]
|
||||
ui, vi = up.floor().long(), vp.floor().long()
|
||||
ok &= (ui >= 0) & (ui < W) & (vi >= 0) & (vi < H)
|
||||
lin, zc, cc = vi[ok] * W + ui[ok], zc[ok], cc[ok]
|
||||
zbuf = torch.full((H * W,), float("inf"), device=device)
|
||||
zbuf.scatter_reduce_(0, lin, zc, reduce="amin", include_self=True)
|
||||
win = zc <= zbuf[lin] * (1 + 1e-5)
|
||||
magenta = torch.tensor(MAGENTA, device=device).view(3, 1, 1)
|
||||
frame = magenta.expand(3, H, W).clone()
|
||||
frame.view(3, -1)[:, lin[win]] = cc[win].T
|
||||
filled = torch.isfinite(zbuf).view(H, W)
|
||||
frame, filled = _fill_cracks(frame, filled)
|
||||
frame = torch.where(filled[None], frame, magenta)
|
||||
return frame.movedim(0, -1).clamp(0, 1).cpu(), (~filled).cpu()
|
||||
+17
-31
@@ -208,7 +208,7 @@ def _weighted_mean_cov(
|
||||
def _matrix_sqrt(matrix: torch.Tensor, inverse: bool = False) -> torch.Tensor:
|
||||
"""Symmetric PSD square root (or inverse square root) via eigh."""
|
||||
values, vectors = torch.linalg.eigh(matrix.double())
|
||||
values = values.clamp_min(1e-10 if inverse else 0.0)
|
||||
values = values.clamp_min(1e-10)
|
||||
roots = values.rsqrt() if inverse else values.sqrt()
|
||||
return (vectors @ torch.diag(roots) @ vectors.T).to(matrix.dtype)
|
||||
|
||||
@@ -229,36 +229,18 @@ def _mkl_matched(
|
||||
weights = None
|
||||
if mask is not None:
|
||||
weights = mask[index if mask.shape[0] > 1 else 0].reshape(-1)
|
||||
img_mean, img_cov = _weighted_mean_cov(
|
||||
pixels.double(), weights.double() if weights is not None else None
|
||||
)
|
||||
img_mean, img_cov = _weighted_mean_cov(pixels, weights)
|
||||
ref_pixels = reference[index if reference.shape[0] > 1 else 0].reshape(-1, 3)
|
||||
ref_mean, ref_cov = _weighted_mean_cov(ref_pixels.double(), None)
|
||||
# Regularize both covariances in the same units. Their product has
|
||||
# squared units, so its square root must not use that absolute floor.
|
||||
regularizer = torch.eye(3, dtype=img_cov.dtype, device=img_cov.device) * 1e-10
|
||||
img_cov = img_cov + regularizer
|
||||
ref_cov = ref_cov + regularizer
|
||||
ref_mean, ref_cov = _weighted_mean_cov(ref_pixels, None)
|
||||
img_root = _matrix_sqrt(img_cov)
|
||||
img_root_inv = _matrix_sqrt(img_cov, inverse=True)
|
||||
# SVD gives the middle square root without squaring the condition
|
||||
# number of nearly singular covariances in an eigendecomposition.
|
||||
_, singular, right = torch.linalg.svd(_matrix_sqrt(ref_cov) @ img_root)
|
||||
middle = right.T @ torch.diag(singular) @ right
|
||||
middle = _matrix_sqrt(img_root @ ref_cov @ img_root)
|
||||
mapping = img_root_inv @ middle @ img_root_inv
|
||||
matched = (pixels - img_mean) @ mapping.T + ref_mean
|
||||
frames.append(matched.to(rgb.dtype).reshape(rgb.shape[1], rgb.shape[2], 3))
|
||||
frames.append(matched.reshape(rgb.shape[1], rgb.shape[2], 3))
|
||||
return torch.stack(frames, dim=0).clamp(0.0, 1.0)
|
||||
|
||||
|
||||
def _interpolate(values: torch.Tensor, positions: torch.Tensor, samples: torch.Tensor) -> torch.Tensor:
|
||||
"""Linear interpolation with constant endpoints, including a singleton."""
|
||||
high = torch.searchsorted(positions, values.contiguous()).clamp_max(positions.numel() - 1)
|
||||
low = (high - 1).clamp_min(0)
|
||||
fraction = ((values - positions[low]) / (positions[high] - positions[low]).clamp_min(1e-20)).clamp(0, 1)
|
||||
return samples[low] + fraction * (samples[high] - samples[low])
|
||||
|
||||
|
||||
def _histogram_matched(
|
||||
rgb: torch.Tensor, reference: torch.Tensor, mask: torch.Tensor | None
|
||||
) -> torch.Tensor:
|
||||
@@ -281,14 +263,18 @@ def _histogram_matched(
|
||||
for channel in range(3):
|
||||
values = frame[..., channel]
|
||||
pool = values[selected] if selected is not None else values.reshape(-1)
|
||||
source_values, source_counts = torch.unique(pool, sorted=True, return_counts=True)
|
||||
ref_values, ref_counts = torch.unique(ref[..., channel], sorted=True, return_counts=True)
|
||||
source_quantiles = source_counts.cumsum(0).float() / pool.numel()
|
||||
ref_quantiles = ref_counts.cumsum(0).float() / ref[..., channel].numel()
|
||||
# Equal values share their cumulative probability, independent
|
||||
# of how many pixels were used to represent the distribution.
|
||||
mapping = _interpolate(source_quantiles, ref_quantiles, ref_values)
|
||||
mapped = _interpolate(values.reshape(-1), source_values, mapping)
|
||||
sorted_pool, _ = pool.reshape(-1).sort()
|
||||
sorted_ref, _ = ref[..., channel].reshape(-1).sort()
|
||||
# Rank every pixel against the measured pool, then read the same
|
||||
# quantile off the reference.
|
||||
ranks = torch.searchsorted(sorted_pool, values.reshape(-1).contiguous())
|
||||
ranks = ranks.clamp_max(sorted_pool.numel() - 1)
|
||||
quantiles = ranks.float() / max(1, sorted_pool.numel() - 1)
|
||||
positions = quantiles * (sorted_ref.numel() - 1)
|
||||
low = positions.floor().long()
|
||||
high = positions.ceil().long()
|
||||
fraction = positions - low.float()
|
||||
mapped = sorted_ref[low] * (1.0 - fraction) + sorted_ref[high] * fraction
|
||||
channels.append(mapped.reshape(values.shape))
|
||||
frames.append(torch.stack(channels, dim=-1))
|
||||
return torch.stack(frames, dim=0).clamp(0.0, 1.0)
|
||||
|
||||
@@ -36,7 +36,7 @@ import torch
|
||||
from PIL import Image
|
||||
|
||||
from ._brush_helpers import brush_core, brush_sigma, stroke_cover # noqa: F401 - the brush's numbers are read from here too
|
||||
from ._image_save_helpers import IMAGE_SAVE_LOCK, next_free_counter, require_output_path, strip_image_extension
|
||||
from ._image_save_helpers import next_free_counter, require_output_path, strip_image_extension
|
||||
from ._psd_helpers import PSD_MAX_SIDE, write_psd
|
||||
from ._realign_helpers import crop_if_shift, measure, warp_to_source
|
||||
|
||||
@@ -72,6 +72,7 @@ ALIGN_FAILED = (
|
||||
"or have too little detail to measure."
|
||||
)
|
||||
|
||||
_save_lock = threading.Lock()
|
||||
_pairs: OrderedDict[str, tuple[Path, Path, str]] = OrderedDict()
|
||||
_pairs_lock = threading.Lock()
|
||||
|
||||
@@ -360,7 +361,7 @@ def save_mix(*, picture_a, picture_b, output_dir, top="A", strokes=None, layers=
|
||||
mixed = mix_pictures(upper, under, gone)
|
||||
|
||||
folder = Path(output_dir)
|
||||
with IMAGE_SAVE_LOCK:
|
||||
with _save_lock:
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
counter = next_free_counter((entry.name for entry in folder.iterdir()), name)
|
||||
while True:
|
||||
|
||||
@@ -1,455 +0,0 @@
|
||||
"""Edit Lock: keep what an edit did not change. Pure torch, no ComfyUI imports.
|
||||
|
||||
At every sampling step an edit model predicts the finished picture. Where
|
||||
that prediction sits close to the original, the edit is not happening
|
||||
there, so the original is put back and the model carries on from the real
|
||||
picture. This is the target TailSteer trains a model toward
|
||||
(original where nothing changed, the model's edit elsewhere), applied while
|
||||
sampling instead of through training.
|
||||
|
||||
What counts as changed is measured against the quiet part of the picture:
|
||||
the tenth of it where the prediction differs least, which a local edit
|
||||
leaves near the level of the model's own redraw noise. The node watches the
|
||||
first steps, where it only undoes the model's zoom and shift, and decides
|
||||
once the picture has formed. An edit of the whole picture (a style, the
|
||||
light) has no quiet part: the first look checks for that and the lock steps
|
||||
aside. A soft change over the whole picture (rain, snow, haze) has no clear
|
||||
peak: the decision checks for that, and the picture is only held in place.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
LOCK_MODES = ("auto", "always", "off")
|
||||
|
||||
# A spot counts as changed when it differs from the original by STRONG times
|
||||
# the quiet level, or by WEAK times while it touches a spot that does. So a
|
||||
# faint change next to a clear one belongs to the edit, and a faint change
|
||||
# alone is redraw noise. Set against what 14 plain MiniMax-H3-Image edits
|
||||
# changed in the end: this frees about 80% of it at the first look and 3%
|
||||
# of what stayed.
|
||||
WEAK = 2.0
|
||||
STRONG = 3.0
|
||||
# The model often draws the whole picture a little larger or shifted. That
|
||||
# is measured and discounted before anything is compared, up to these
|
||||
# limits; a bigger move is treated as part of the edit.
|
||||
# The node watches the start of a run and decides once the noise is down to
|
||||
# this share of where it began. The first prediction is a blur: rain, snow,
|
||||
# smoke and the light a new hair color throws on a face only show a few
|
||||
# steps in. While it watches it only undoes the zoom and shift.
|
||||
DECIDE_AT = 0.8
|
||||
# A local edit has a peak: somewhere the picture clearly changes. Rain, snow
|
||||
# and haze change the whole picture a little and no part clearly. A lock
|
||||
# would hold them back, or let them through in patches where it hands a wide
|
||||
# part of the picture to the edit. So two things are read at the decision,
|
||||
# in units of the quiet level: the strongest spot, and the strongest
|
||||
# hundredth when the lock would free SOFT_WIDE of the picture or more. On
|
||||
# recorded MiniMax-H3-Image runs the strongest spot read 4.7 or more for
|
||||
# every local edit, glasses and makeup included, and 3.7 or less for light
|
||||
# rain, fog and snow; with a wide part freed, the strongest hundredth read
|
||||
# 4.4 or more for local edits and 3.6 or less for rain and snow.
|
||||
SOFT_WIDE = 0.10
|
||||
SOFT_PEAK = 4.0
|
||||
# Kept this much or more: the report adds what to do if the edit is missing.
|
||||
# A soft effect over the whole picture (rain, snow, smoke) looks like a small
|
||||
# edit at the first look, and under the lock the model then drops it.
|
||||
NEARLY_ALL = 0.95
|
||||
MAX_ZOOM = 0.05
|
||||
MAX_SHIFT = 4.0
|
||||
# The whole picture is changing when even its calmest fifth sits this far
|
||||
# from the original at the first look, in units of the original's own
|
||||
# spread. Measured on MiniMax-H3-Image: 28 local edits at 1, 4 and 16 MP came
|
||||
# in at 0.22 or less (zoomed ones included), 12 whole-picture edits (styles,
|
||||
# light, weather) at 0.27 or more.
|
||||
WHOLE_PICTURE = 0.243
|
||||
# Blur and growth of the change map, as a share of the short side.
|
||||
REACH = 1.0 / 54.0
|
||||
# A result this much larger or smaller than the picture is another picture.
|
||||
SIZE_SLACK = 0.04
|
||||
|
||||
|
||||
def box_blur(x: torch.Tensor, radius: int) -> torch.Tensor:
|
||||
if radius <= 0:
|
||||
return x
|
||||
size = 2 * radius + 1
|
||||
return F.avg_pool2d(F.pad(x, (radius,) * 4, mode="replicate"), size, stride=1)
|
||||
|
||||
|
||||
def reach(height: int, width: int) -> int:
|
||||
return max(1, round(min(height, width) * REACH))
|
||||
|
||||
|
||||
def _moved(source: torch.Tensor, move: torch.Tensor) -> torch.Tensor:
|
||||
"""The original sampled at (zoom_x * x + shift_x, zoom_y * y + shift_y), x and y in cells from the centre.
|
||||
|
||||
move = [zoom_x - 1, zoom_y - 1, shift_x, shift_y].
|
||||
"""
|
||||
height, width = source.shape[-2:]
|
||||
theta = torch.zeros(source.shape[0], 2, 3, device=source.device, dtype=source.dtype)
|
||||
theta[:, 0, 0] = 1.0 + move[0]
|
||||
theta[:, 1, 1] = 1.0 + move[1]
|
||||
theta[:, 0, 2] = 2.0 * move[2] / width
|
||||
theta[:, 1, 2] = 2.0 * move[3] / height
|
||||
grid = F.affine_grid(theta, list(source.shape), align_corners=False)
|
||||
return F.grid_sample(source, grid, mode="bilinear", padding_mode="border", align_corners=False)
|
||||
|
||||
|
||||
def measure_redraw(pred: torch.Tensor, source: torch.Tensor) -> torch.Tensor:
|
||||
"""How much larger and how far shifted the prediction is drawn, as the move that lays the original over it.
|
||||
|
||||
pred and source are [1, C, H, W]. Fitted on the calmer half of the
|
||||
picture, so the edit itself does not pull the answer, from a coarse grid
|
||||
down to the full one. Returns [zoom_x - 1, zoom_y - 1, shift_x, shift_y];
|
||||
zeros when nothing can be measured.
|
||||
"""
|
||||
pred, source = pred.float(), source.float()
|
||||
move = torch.zeros(4, device=pred.device, dtype=torch.float32)
|
||||
limit = torch.tensor([MAX_ZOOM, MAX_ZOOM, MAX_SHIFT, MAX_SHIFT], device=pred.device)
|
||||
for level in (4, 2, 1):
|
||||
if min(pred.shape[-2:]) // level < 16:
|
||||
continue
|
||||
a = box_blur(F.avg_pool2d(pred, level) if level > 1 else pred, 1)
|
||||
b = box_blur(F.avg_pool2d(source, level) if level > 1 else source, 1)
|
||||
height, width = a.shape[-2:]
|
||||
ys = (torch.arange(height, device=a.device, dtype=torch.float32) + 0.5 - height / 2)[:, None].expand(height, width)
|
||||
xs = (torch.arange(width, device=a.device, dtype=torch.float32) + 0.5 - width / 2)[None, :].expand(height, width)
|
||||
here = move.clone()
|
||||
here[2:] = here[2:] / level
|
||||
for _ in range(6):
|
||||
laid = _moved(b, here)
|
||||
rest = a - laid
|
||||
rest = rest - rest.flatten(2).median(dim=2).values[:, :, None, None]
|
||||
wide = F.pad(laid, (1, 1, 1, 1), mode="replicate")
|
||||
gx = (wide[..., 1:-1, 2:] - wide[..., 1:-1, :-2]) / 2.0
|
||||
gy = (wide[..., 2:, 1:-1] - wide[..., :-2, 1:-1]) / 2.0
|
||||
size = rest.abs().mean(dim=1, keepdim=True)
|
||||
calm = (size <= size.flatten().median()).float()
|
||||
calm[..., :2, :] = 0.0
|
||||
calm[..., -2:, :] = 0.0
|
||||
calm[..., :, :2] = 0.0
|
||||
calm[..., :, -2:] = 0.0
|
||||
jac = (torch.stack([gx * xs, gy * ys, gx, gy], dim=-1) * calm[..., None]).reshape(-1, 4)
|
||||
normal = jac.T @ jac + 1e-6 * torch.eye(4, device=a.device)
|
||||
try:
|
||||
change = torch.linalg.solve(normal, jac.T @ (rest * calm).reshape(-1))
|
||||
except RuntimeError:
|
||||
return torch.zeros(4, device=pred.device, dtype=torch.float32)
|
||||
if not bool(torch.isfinite(change).all()):
|
||||
return torch.zeros(4, device=pred.device, dtype=torch.float32)
|
||||
here = here + change
|
||||
if float(change.abs().max()) < 1e-4:
|
||||
break
|
||||
move = here.clone()
|
||||
move[2:] = move[2:] * level
|
||||
move = torch.maximum(torch.minimum(move, limit), -limit)
|
||||
return move
|
||||
|
||||
|
||||
def redraws(pred: torch.Tensor, source: torch.Tensor) -> list[torch.Tensor]:
|
||||
"""measure_redraw for each picture of a batch."""
|
||||
return [measure_redraw(pred[index:index + 1], source[:1]) for index in range(pred.shape[0])]
|
||||
|
||||
|
||||
def difference(pred: torch.Tensor, source: torch.Tensor, moves: list[torch.Tensor] | None = None) -> torch.Tensor:
|
||||
"""How far each spot of the prediction is from the original, [B, 1, H, W].
|
||||
|
||||
Two things are not a change. A redraw of the whole picture slightly
|
||||
larger or shifted: the original is laid over the prediction first. And
|
||||
an even tint: each channel's middle difference is taken out. The result
|
||||
is in units of the original's own spread, which keeps the numbers alike
|
||||
between models.
|
||||
"""
|
||||
pred = pred.float()
|
||||
source = source.float()
|
||||
moves = moves if moves is not None else redraws(pred, source)
|
||||
out = []
|
||||
for index in range(pred.shape[0]):
|
||||
delta = pred[index:index + 1] - _moved(source[:1], moves[index])
|
||||
delta = delta - delta.flatten(2).median(dim=2).values[:, :, None, None]
|
||||
out.append(delta.abs().mean(dim=1, keepdim=True))
|
||||
magnitude = torch.cat(out) / source.std().clamp_min(1e-6)
|
||||
return box_blur(magnitude, reach(*magnitude.shape[-2:]))
|
||||
|
||||
|
||||
def moved_back(pred: torch.Tensor, moves: list[torch.Tensor]) -> torch.Tensor:
|
||||
"""The prediction with its zoom and shift undone, so it sits where the original does.
|
||||
|
||||
Resampling softens a latent, so a move under a tenth of a cell at the
|
||||
corner is left alone, and the rest is resampled bicubic: on recorded
|
||||
runs that kept 85% of the fine detail where bilinear kept 65%.
|
||||
"""
|
||||
out = []
|
||||
for index in range(pred.shape[0]):
|
||||
one = pred[index:index + 1]
|
||||
move = moves[index]
|
||||
height, width = one.shape[-2:]
|
||||
corner = (move[0].abs() * width / 2 + move[2].abs()).maximum(move[1].abs() * height / 2 + move[3].abs())
|
||||
if float(corner) < 0.1:
|
||||
out.append(one)
|
||||
continue
|
||||
theta = torch.zeros(1, 2, 3, device=one.device, dtype=torch.float32)
|
||||
theta[:, 0, 0] = 1.0 / (1.0 + move[0])
|
||||
theta[:, 1, 1] = 1.0 / (1.0 + move[1])
|
||||
theta[:, 0, 2] = -2.0 * move[2] / (1.0 + move[0]) / width
|
||||
theta[:, 1, 2] = -2.0 * move[3] / (1.0 + move[1]) / height
|
||||
grid = F.affine_grid(theta, list(one.shape), align_corners=False)
|
||||
back = F.grid_sample(one.float(), grid, mode="bicubic", padding_mode="border", align_corners=False)
|
||||
out.append(back.to(one.dtype))
|
||||
return torch.cat(out)
|
||||
|
||||
|
||||
def broad_change(pred: torch.Tensor, source: torch.Tensor) -> torch.Tensor:
|
||||
"""How far the calmest fifth of each picture sits from the original, [B].
|
||||
|
||||
Read on a smoothed copy, where a redraw one percent larger nearly
|
||||
vanishes and a new style, new light or new weather does not. An even
|
||||
tint is taken out first: the model adds one by itself, a stronger one
|
||||
on large pictures, and that is no edit.
|
||||
"""
|
||||
delta = (pred - source).float()
|
||||
delta = delta - delta.flatten(2).median(dim=2).values[:, :, None, None]
|
||||
delta = box_blur(delta, max(1, round(min(delta.shape[-2:]) / 30.0)))
|
||||
level = (delta * delta).mean(dim=1).sqrt().flatten(1)
|
||||
stride = max(1, level.shape[1] // 200000)
|
||||
spread = source.float().std().clamp_min(1e-6)
|
||||
return torch.quantile(level[:, ::stride], 0.2, dim=1) / spread
|
||||
|
||||
|
||||
def quiet_level(magnitude: torch.Tensor) -> torch.Tensor:
|
||||
"""The tenth of each picture that differs least, [B]."""
|
||||
flat = magnitude.flatten(1)
|
||||
stride = max(1, flat.shape[1] // 200000)
|
||||
return torch.quantile(flat[:, ::stride], 0.1, dim=1)
|
||||
|
||||
|
||||
def peaks(magnitude: torch.Tensor, quiet: torch.Tensor) -> tuple[float, float]:
|
||||
"""How clear the clearest change is, in units of the quiet level: (strongest spot, strongest hundredth)."""
|
||||
ratio = (magnitude / quiet.clamp_min(1e-6)[:, None, None, None]).flatten(1)
|
||||
stride = max(1, ratio.shape[1] // 200000)
|
||||
return float(ratio.max(dim=1).values.min()), float(torch.quantile(ratio[:, ::stride], 0.99, dim=1).min())
|
||||
|
||||
|
||||
def change_core(magnitude: torch.Tensor, quiet: torch.Tensor, tolerance: float = 1.0,
|
||||
held: torch.Tensor | None = None) -> torch.Tensor:
|
||||
"""1 where the edit changed the picture, 0 where it did not, hard-edged, [B, 1, H, W].
|
||||
|
||||
`held` is what earlier steps called changed: it stays changed, and
|
||||
faint change that touches it joins it.
|
||||
"""
|
||||
ratio = magnitude / quiet.clamp_min(1e-6)[:, None, None, None]
|
||||
weak = (ratio > WEAK * tolerance).float()
|
||||
core = (ratio > STRONG * tolerance).float()
|
||||
if held is not None:
|
||||
weak = torch.maximum(weak, held)
|
||||
core = torch.maximum(core, held)
|
||||
for _ in range(sum(core.shape[-2:])):
|
||||
grown = F.max_pool2d(core, 3, stride=1, padding=1) * weak
|
||||
if torch.equal(grown, core):
|
||||
break
|
||||
core = grown
|
||||
return core
|
||||
|
||||
|
||||
def soften(core: torch.Tensor) -> torch.Tensor:
|
||||
"""The hard change map with a margin and a soft edge, so the edit has room to blend in."""
|
||||
grow = reach(*core.shape[-2:])
|
||||
return box_blur(F.max_pool2d(core, 2 * grow + 1, stride=1, padding=grow), grow)
|
||||
|
||||
|
||||
def fit_latent(latent: torch.Tensor, height: int, width: int) -> torch.Tensor | None:
|
||||
"""The original's latent on the result's grid, or None when they are different pictures."""
|
||||
h, w = latent.shape[-2:]
|
||||
if (h, w) == (height, width):
|
||||
return latent
|
||||
if abs(h / height - 1.0) > SIZE_SLACK or abs(w / width - 1.0) > SIZE_SLACK:
|
||||
return None
|
||||
return F.interpolate(latent, size=(height, width), mode="bilinear", align_corners=False)
|
||||
|
||||
|
||||
class EditLock:
|
||||
"""One lock: the original, the settings, and what the last run kept."""
|
||||
|
||||
def __init__(self, mode: str = "auto", tolerance: float = 1.0):
|
||||
self.mode = mode
|
||||
self.tolerance = tolerance
|
||||
self.source: torch.Tensor | None = None # IMAGE, [1, H, W, 3]
|
||||
self.latent: torch.Tensor | None = None # [1, C, H, W] or [1, C, 1, H, W], model space
|
||||
self.user_mask: torch.Tensor | None = None # MASK, white = the edit may happen
|
||||
self.status = "waiting"
|
||||
self.mask: torch.Tensor | None = None # [B, 1, h, w], 1 = changed, soft-edged
|
||||
self.core: torch.Tensor | None = None # the same before its margin, hard-edged
|
||||
self.quiet: torch.Tensor | None = None # [B], the quiet level at the decision
|
||||
self.broad: float | None = None # the first look's whole-picture reading
|
||||
self.wide: float | None = None # share of the picture the lock would free, at the decision
|
||||
self.top: float | None = None # the strongest spot then, in units of the quiet level
|
||||
self.peak: float | None = None # and the strongest hundredth
|
||||
self._sigma: float | None = None
|
||||
self._first = True
|
||||
self._first_sigma = 1.0
|
||||
self._decided = False
|
||||
|
||||
def _begin(self) -> None:
|
||||
self.status = "waiting"
|
||||
self.mask = None
|
||||
self.core = None
|
||||
self.quiet = None
|
||||
self.broad = None
|
||||
self.wide = None
|
||||
self.top = None
|
||||
self.peak = None
|
||||
self._first = True
|
||||
self._decided = False
|
||||
|
||||
def _decides_now(self, args: dict, sigma: float) -> bool:
|
||||
"""True once the noise is down far enough, or this is the run's last step."""
|
||||
steps = (args.get("model_options") or {}).get("transformer_options", {}).get("sample_sigmas")
|
||||
if steps is None or len(steps) < 2:
|
||||
return True # the sampler does not say where the run ends: decide at once
|
||||
if sigma <= float(steps[-2]) * 1.0001:
|
||||
return True
|
||||
return sigma <= DECIDE_AT * self._first_sigma
|
||||
|
||||
def step(self, args: dict) -> torch.Tensor:
|
||||
"""ComfyUI's post-CFG hook: the prediction comes in, the locked prediction goes out."""
|
||||
pred = args["denoised"]
|
||||
sigma = float(args["sigma"].flatten()[0])
|
||||
if self._sigma is None or sigma >= self._sigma:
|
||||
self._begin() # the noise level went up: a new run
|
||||
self._sigma = sigma
|
||||
if self.status in ("whole picture", "size", "video", "vae") or self.latent is None:
|
||||
return pred
|
||||
video = pred.ndim == 5
|
||||
if video and pred.shape[2] != 1:
|
||||
self.status = "video"
|
||||
return pred
|
||||
flat = pred[:, :, 0] if video else pred
|
||||
latent = self.latent[:, :, 0] if self.latent.ndim == 5 else self.latent
|
||||
if latent.shape[1] != flat.shape[1]:
|
||||
self.status = "vae"
|
||||
return pred
|
||||
source = fit_latent(latent.to(device=flat.device, dtype=torch.float32), *flat.shape[-2:])
|
||||
if source is None:
|
||||
self.status = "size"
|
||||
return pred
|
||||
if self.status == "soft":
|
||||
# nothing is put back, the picture is only held where the original sits
|
||||
back = moved_back(flat, redraws(flat, source))
|
||||
return back[:, :, None] if video else back
|
||||
if self.user_mask is not None:
|
||||
mask = self._given_mask(flat)
|
||||
else:
|
||||
if self._first:
|
||||
self._first_sigma = sigma
|
||||
self.broad = float(broad_change(flat, source).max())
|
||||
if self.mode == "auto" and self.broad > WHOLE_PICTURE:
|
||||
self.status = "whole picture"
|
||||
return pred
|
||||
moves = redraws(flat, source)
|
||||
magnitude = difference(flat, source, moves)
|
||||
if not self._decided and not self._decides_now(args, sigma):
|
||||
# still watching: the model draws its own picture, only its zoom and shift are undone
|
||||
self._first = False
|
||||
self.status = "watching"
|
||||
if self.broad > WHOLE_PICTURE:
|
||||
return pred # too much is changing to trust the measured move
|
||||
back = moved_back(flat, moves)
|
||||
return back[:, :, None] if video else back
|
||||
if not self._decided:
|
||||
self._decided = True
|
||||
# the yardstick is set once, here: later steps are read against it
|
||||
self.quiet = quiet_level(magnitude)
|
||||
self.top, self.peak = peaks(magnitude, self.quiet)
|
||||
self.wide = float(change_core(magnitude, self.quiet, self.tolerance).flatten(1).mean(dim=1).max())
|
||||
thin = self.top < SOFT_PEAK or (self.wide >= SOFT_WIDE and self.peak < SOFT_PEAK)
|
||||
if self.mode == "auto" and not self._first and thin:
|
||||
# a soft change over the whole picture: a lock would hold it back or let it through in patches
|
||||
self.status = "soft"
|
||||
back = moved_back(flat, moves)
|
||||
return back[:, :, None] if video else back
|
||||
held = self.core if self.core is not None and self.core.shape[0] == flat.shape[0] else None
|
||||
self.core = change_core(magnitude, self.quiet.to(magnitude.device), self.tolerance,
|
||||
held.to(magnitude.device) if held is not None else None).detach()
|
||||
mask = soften(self.core)
|
||||
self._first = False
|
||||
self.mask = mask.detach()
|
||||
self.status = "locked"
|
||||
keep = (1.0 - mask).to(flat.dtype)
|
||||
locked = flat * (1.0 - keep) + source.to(flat.dtype) * keep
|
||||
return locked[:, :, None] if video else locked
|
||||
|
||||
def _given_mask(self, flat: torch.Tensor) -> torch.Tensor:
|
||||
mask = self.user_mask
|
||||
if mask.ndim == 2:
|
||||
mask = mask[None]
|
||||
mask = mask[:1, None].to(device=flat.device, dtype=torch.float32)
|
||||
mask = F.interpolate(mask, size=flat.shape[-2:], mode="bilinear", align_corners=False).clamp(0.0, 1.0)
|
||||
return soften(mask).expand(flat.shape[0], -1, -1, -1)
|
||||
|
||||
def kept_share(self) -> float | None:
|
||||
if self.status != "locked" or self.mask is None:
|
||||
return None
|
||||
return float((self.mask < 0.5).float().mean())
|
||||
|
||||
def pixel_mask(self, height: int, width: int) -> torch.Tensor | None:
|
||||
"""The change mask at the picture's size, [B, H, W], or None when nothing was locked."""
|
||||
if self.status != "locked" or self.mask is None:
|
||||
return None
|
||||
mask = F.interpolate(self.mask.float().cpu(), size=(height, width), mode="bilinear", align_corners=False)
|
||||
return mask[:, 0].clamp(0.0, 1.0)
|
||||
|
||||
|
||||
def restore_pixels(result: torch.Tensor, source: torch.Tensor, mask: torch.Tensor,
|
||||
feather: int) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""The original's own pixels where the mask is black. result [B, H, W, C], source [1, h, w, 3], mask [b, H, W].
|
||||
|
||||
The fade lies outside the edit: the mask is widened by the feather first.
|
||||
"""
|
||||
frames, height, width = int(result.shape[0]), int(result.shape[1]), int(result.shape[2])
|
||||
edit = mask[:, None].float()
|
||||
if edit.shape[0] not in (1, frames):
|
||||
edit = edit[:1]
|
||||
if feather > 0:
|
||||
size = 2 * feather + 1
|
||||
edit = F.max_pool2d(edit, size, stride=1, padding=feather)
|
||||
edit = box_blur(edit, feather)
|
||||
original = source[..., :3].float()
|
||||
if tuple(original.shape[1:3]) != (height, width):
|
||||
original = F.interpolate(original.movedim(-1, 1), size=(height, width), mode="bicubic",
|
||||
align_corners=False, antialias=True).movedim(1, -1).clamp(0.0, 1.0)
|
||||
weight = edit.movedim(1, -1).to(result.device, result.dtype)
|
||||
out = result.clone()
|
||||
out[..., :3] = result[..., :3] * weight + original.to(result.device, result.dtype) * (1.0 - weight)
|
||||
edit_mask = edit[:, 0].expand(frames, -1, -1).clone()
|
||||
return out, edit_mask
|
||||
|
||||
|
||||
def describe(lock: EditLock) -> str:
|
||||
if lock.status == "locked":
|
||||
kept = lock.kept_share() or 0.0
|
||||
how = "your mask" if lock.user_mask is not None else "what the edit changed"
|
||||
text = (f"Edit Lock kept {kept * 100:.0f}% of your picture as it was and left "
|
||||
f"{(1.0 - kept) * 100:.0f}% to the edit ({how}).")
|
||||
if kept >= NEARLY_ALL and lock.user_mask is None:
|
||||
# rain, snow or smoke over the whole picture reads as a small edit and is held back
|
||||
text += (" If your edit is missing, it is one that spreads thinly over the whole picture "
|
||||
"(rain, snow, smoke): set lock to off.")
|
||||
return text
|
||||
if lock.status == "whole picture":
|
||||
return ("Edit Lock stepped aside: the edit changes the whole picture, so there was nothing to keep. "
|
||||
"Set lock to always to lock anyway.")
|
||||
if lock.status == "soft":
|
||||
return ("Edit Lock stepped aside: the edit spreads thinly over the whole picture (rain, snow, haze), "
|
||||
"so no part of it stayed as it was. It only held the picture in place. "
|
||||
"Set lock to always to lock anyway.")
|
||||
if lock.status == "off":
|
||||
return "Edit Lock is off."
|
||||
if lock.status == "size":
|
||||
return ("Edit Lock did nothing: the picture and the result are different sizes. "
|
||||
"Give it the picture at the size of the result.")
|
||||
if lock.status == "video":
|
||||
return "Edit Lock did nothing: it works on single pictures, not video."
|
||||
if lock.status == "vae":
|
||||
return "Edit Lock did nothing: this VAE does not belong to this model."
|
||||
return "Edit Lock has not run yet: plug its model output into the sampler."
|
||||
@@ -1,153 +0,0 @@
|
||||
"""Edit Lock Restore's tint fix: take out the even tint an edit model adds to the whole picture.
|
||||
|
||||
MiniMax H3 Image gives every edit one even color shift: a little lighter,
|
||||
pinker and bluer (Lab L +1 to +3, a +2 to +7, b -1 to -6 at 16 MP). Edit
|
||||
Lock removes it wherever it locks, because those parts are your picture
|
||||
again. When the lock steps aside (new hair color, new background, rain) the
|
||||
shift stays. Here it is read from the part of the picture the edit left
|
||||
alone and subtracted from every pixel.
|
||||
|
||||
A shift is only taken out when it looks like that tint. An edit that is
|
||||
meant to recolor everything (golden hour, red light, a restyle) moves the
|
||||
colors much further or the other way, or leaves too little of the picture
|
||||
alone to read anything, and passes through untouched.
|
||||
|
||||
Pure torch, no ComfyUI imports.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
from ._realign_helpers import measure, warp_to_source
|
||||
|
||||
# The pictures are compared at this long side; the fit is sub-pixel there.
|
||||
WORK = 1536
|
||||
# Cells closer than this to the running estimate count as "left alone".
|
||||
NEAR = 4.0
|
||||
# The tint as measured on 57 edits: lighter, pinker, bluer, within these
|
||||
# bounds (Lab units). Smaller than MIN_A is not worth touching.
|
||||
MIN_A = 0.5
|
||||
MAX_A = 10.0
|
||||
MAX_B = 0.0
|
||||
MIN_B = -8.0
|
||||
MIN_L = -1.0
|
||||
MAX_L = 6.0
|
||||
# At least this share of the picture must be left alone to read the tint.
|
||||
MIN_SHARE = 0.15
|
||||
|
||||
_D65 = (0.95047, 1.0, 1.08883)
|
||||
_TO_XYZ = ((0.4124564, 0.3575761, 0.1804375),
|
||||
(0.2126729, 0.7151522, 0.0721750),
|
||||
(0.0193339, 0.1191920, 0.9503041))
|
||||
_TO_RGB = ((3.2404542, -1.5371385, -0.4985314),
|
||||
(-0.9692660, 1.8760108, 0.0415560),
|
||||
(0.0556434, -0.2040259, 1.0572252))
|
||||
|
||||
|
||||
def rgb_to_lab(rgb: torch.Tensor) -> torch.Tensor:
|
||||
"""sRGB in 0..1, [..., 3] -> CIE Lab, float64."""
|
||||
x = rgb.double().clamp(0.0, 1.0)
|
||||
linear = torch.where(x > 0.04045, ((x + 0.055) / 1.055) ** 2.4, x / 12.92)
|
||||
xyz = linear @ torch.tensor(_TO_XYZ, dtype=torch.float64).T / torch.tensor(_D65, dtype=torch.float64)
|
||||
f = torch.where(xyz > 0.008856, xyz.clamp(min=1e-9) ** (1.0 / 3.0), 7.787 * xyz + 16.0 / 116.0)
|
||||
return torch.stack([116.0 * f[..., 1] - 16.0, 500.0 * (f[..., 0] - f[..., 1]),
|
||||
200.0 * (f[..., 1] - f[..., 2])], -1)
|
||||
|
||||
|
||||
def lab_to_rgb(lab: torch.Tensor) -> torch.Tensor:
|
||||
"""CIE Lab, [..., 3] -> sRGB in 0..1, float64."""
|
||||
fy = (lab[..., 0] + 16.0) / 116.0
|
||||
f = torch.stack([fy + lab[..., 1] / 500.0, fy, fy - lab[..., 2] / 200.0], -1)
|
||||
xyz = torch.where(f > 0.206893, f ** 3, (f - 16.0 / 116.0) / 7.787) * torch.tensor(_D65, dtype=torch.float64)
|
||||
linear = (xyz @ torch.tensor(_TO_RGB, dtype=torch.float64).T).clamp(0.0, 1.0)
|
||||
return torch.where(linear > 0.0031308, 1.055 * linear ** (1.0 / 2.4) - 0.055, 12.92 * linear).clamp(0.0, 1.0)
|
||||
|
||||
|
||||
def _fit(image: torch.Tensor, long_side: int) -> torch.Tensor:
|
||||
"""HWC float at most long_side px on its long side."""
|
||||
height, width = int(image.shape[0]), int(image.shape[1])
|
||||
scale = long_side / max(height, width)
|
||||
if scale >= 1.0:
|
||||
return image.float()
|
||||
size = (max(1, round(height * scale)), max(1, round(width * scale)))
|
||||
return F.interpolate(image.movedim(-1, 0)[None].float(), size=size, mode="bilinear",
|
||||
align_corners=False, antialias=True)[0].movedim(0, -1)
|
||||
|
||||
|
||||
def measure_tint(result: torch.Tensor, source: torch.Tensor) -> tuple[list[float] | None, float]:
|
||||
"""The even shift in (L, a, b) from source to result, read where the edit left the picture alone.
|
||||
|
||||
result, source: HWC float in 0..1, any sizes. Returns (shift or None, the
|
||||
share of the picture it was read on). The result is lined up with the
|
||||
source first, since edits often come back slightly zoomed or moved.
|
||||
"""
|
||||
src = _fit(source[..., :3], WORK)
|
||||
edit = _fit(result[..., :3], WORK)
|
||||
fit = measure(src, edit, mode="zoom + shift")
|
||||
if not fit.reliable:
|
||||
return None, 0.0
|
||||
height, width = int(src.shape[0]), int(src.shape[1])
|
||||
scaled = F.interpolate(edit.movedim(-1, 0)[None], size=(height, width), mode="bilinear",
|
||||
align_corners=False)[0].movedim(0, -1)
|
||||
try:
|
||||
warped = warp_to_source(scaled, fit.matrix, width, height)
|
||||
warped = warped[0] if isinstance(warped, tuple) else warped
|
||||
except Exception:
|
||||
warped = scaled
|
||||
# coarse cells of about 8 px at 1 MP, so grain and small detail drop out
|
||||
cell = max(4, round(8 / math.sqrt(1e6 / (width * height))))
|
||||
|
||||
def cells(img: torch.Tensor) -> torch.Tensor:
|
||||
return F.avg_pool2d(img.movedim(-1, 0)[None], cell, stride=cell)[0].movedim(0, -1)
|
||||
|
||||
diff = rgb_to_lab(cells(warped)) - rgb_to_lab(cells(src))
|
||||
margin = max(1, int(diff.shape[0]) // 12) # the edges carry the warp's filled strip
|
||||
diff = diff[margin:-margin, margin:-margin].reshape(-1, 3)
|
||||
if diff.shape[0] < 50:
|
||||
return None, 0.0
|
||||
centre = diff.median(0).values
|
||||
share = 1.0
|
||||
# start at the median change, then keep only the cells near it: a new
|
||||
# background or new hair is a big change, but not the same one everywhere
|
||||
for _ in range(5):
|
||||
near = (diff - centre).norm(dim=1) < NEAR
|
||||
if int(near.sum()) < 50:
|
||||
break
|
||||
centre = diff[near].mean(0)
|
||||
share = float(near.double().mean())
|
||||
return [float(v) for v in centre], share
|
||||
|
||||
|
||||
def looks_like_tint(shift: list[float] | None, share: float) -> bool:
|
||||
"""True for the model's own lighter-pinker-bluer shift; False for an intended recolor."""
|
||||
if shift is None or share < MIN_SHARE:
|
||||
return False
|
||||
light, a, b = shift
|
||||
return MIN_A <= a <= MAX_A and MIN_B <= b <= MAX_B and MIN_L <= light <= MAX_L
|
||||
|
||||
|
||||
def remove_tint(image: torch.Tensor, shift: list[float]) -> torch.Tensor:
|
||||
"""Subtract one (L, a, b) shift from every pixel. image: [B, H, W, C] in 0..1."""
|
||||
lab = rgb_to_lab(image[..., :3]) - torch.tensor(shift, dtype=torch.float64)
|
||||
out = image.clone()
|
||||
out[..., :3] = lab_to_rgb(lab).to(image.dtype)
|
||||
return out
|
||||
|
||||
|
||||
def take_out_tint(images: torch.Tensor, source: torch.Tensor) -> tuple[torch.Tensor, list[float] | None]:
|
||||
"""Each picture of the batch with its tint taken out when it looks like the model's tint.
|
||||
|
||||
Returns the pictures and the largest shift taken out (None when none was)."""
|
||||
out = images.clone()
|
||||
taken: list[float] | None = None
|
||||
for index in range(int(images.shape[0])):
|
||||
shift, share = measure_tint(images[index], source[0])
|
||||
if looks_like_tint(shift, share):
|
||||
out[index:index + 1] = remove_tint(images[index:index + 1], shift)
|
||||
if taken is None or abs(shift[1]) > abs(taken[1]):
|
||||
taken = shift
|
||||
return out, taken
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user