Skip to content

Fix Porter-Duff blend modes with transparent layers - #15721

Open
tandede wants to merge 2 commits into
Comfy-Org:masterfrom
tandede:fix/porter-duff-transparent-blends
Open

Fix Porter-Duff blend modes with transparent layers#15721
tandede wants to merge 2 commits into
Comfy-Org:masterfrom
tandede:fix/porter-duff-transparent-blends

Conversation

@tandede

@tandede tandede commented Aug 19, 2026

Copy link
Copy Markdown

Problem

PorterDuffImageComposite premultiplies its color inputs before applying blend modes, but four mode formulas did not account correctly for source-over compositing when either layer was transparent.

  • DARKEN and LIGHTEN compared premultiplied colors without weighting them by the opposite alpha.
  • MULTIPLY used only the alpha intersection and dropped both non-overlapping regions.
  • OVERLAY omitted the non-overlapping regions and paired the high-branch alpha factors with the wrong colors.

This could make an opaque source disappear on a transparent backdrop, brighten colors unexpectedly, or produce incorrect results for partially transparent layers.

Change

Apply the source-over alpha equation to the affected modes and compute their overlap terms from premultiplied colors. The formulas now follow the W3C Compositing and Blending specification, while preserving the existing node interface and mask convention.

Add parameterized tests that compare all four modes against an independent source-over reference for transparent, partially transparent, and opaque layer combinations.

Tests

  • pytest -q tests-unit/ — 1315 passed, 10 skipped
  • pytest -q tests/execution --skip-timing-checks — 274 passed, 7 skipped
  • ruff check .

@github-actions

github-actions Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

✅ All contributors have signed the CLA. Thank you! This PR is ready to be merged.
Posted by the CLA Assistant Lite bot.

@tandede

tandede commented Aug 19, 2026

Copy link
Copy Markdown
Author

I have read and agree to the Contributor License Agreement

comfy-legal added a commit to Comfy-Org/comfy-cla that referenced this pull request Aug 19, 2026
@tandede
tandede marked this pull request as ready for review August 19, 2026 02:23
@coderabbitai

coderabbitai Bot commented Aug 19, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: b95a5070-f7a7-4d5e-8157-0970c0efab02

📥 Commits

Reviewing files that changed from the base of the PR and between 187eda8 and 7e83788.

📒 Files selected for processing (2)
  • comfy_extras/nodes_compositing.py
  • tests-unit/comfy_extras_test/nodes_compositing_test.py

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

📜 Recent review details
🧰 Additional context used
📓 Path-based instructions (6)
**/*

📄 CodeRabbit inference engine (AGENTS.md)

**/*: Keep changes small, direct, and limited to the narrowest necessary code path and smallest number of files.
Prefer practical fixes, minimal dependencies, and existing repository patterns; remove obsolete, dead, unreachable, or unused code.
Preserve existing APIs, node names, model-loading behavior, file layout, and workflow compatibility unless replacement is explicitly intended.
Core ComfyUI must not add outbound internet requests, telemetry, tracking, reporting, remote configuration, or background network activity. User-authorized model downloads are limited to the requested artifact and must exclude telemetry and unrelated metadata.

Files:

  • tests-unit/comfy_extras_test/nodes_compositing_test.py
  • comfy_extras/nodes_compositing.py
**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

**/*.py: Keep state and capability flags on the object that owns the behavior. Prefer explicit parent-owned attributes over probing child objects with getattr; use child checks only when the child owns the delegated behavior.
Preserve shared method signatures, argument order, return shapes, side effects, and error behavior unless every affected caller and interface is intentionally updated.
Do not add unused compatibility parameters, flags, attributes, constructor options, or model-specific options to shared helpers; keep one-off behavior at the integration boundary.
Normalize third-party return conventions at integration boundaries so core code receives the expected type and shape; avoid undocumented caller-side unwrapping.
Do not add torch.no_grad, torch.inference_mode, or inference-mode wrappers. Do not add model freeze/unfreeze toggles; only disable globally enabled inference mode when a training path requires gradients.
Remove inference-only training behavior such as dropout while preserving checkpoint and state-dict compatibility; use nn.Identity when deleting a module would alter keys or ordering.
Keep imports at module scope except established optional-backend probes or imports required to avoid cycles; avoid unnecessary try/except blocks and use specific exceptions with useful fallbacks.
Do not add workarounds for unsupported library versions, especially PyTorch exception-and-float-cast retries, unless a comment names the exact versions still requiring them.
Let unsupported model formats, invalid quantization metadata, and bad states fail with clear errors instead of silently degrading output.
Match local style, keep comments sparse and useful, and remove comments that merely restate obvious code.
Treat dtype, device placement, VRAM use, and offloading as correctness concerns across CPU, CUDA, ROCm, MPS, DirectML, XPU, NPU, and low-VRAM environments.
Prefer existing ComfyUI and Comfy Kitchen operations, quantization helpers, cast/offload helpe...

Files:

  • tests-unit/comfy_extras_test/nodes_compositing_test.py
  • comfy_extras/nodes_compositing.py
**/*.{py,json}

📄 CodeRabbit inference engine (AGENTS.md)

Treat legacy combo, io.Combo, and io.DynamicCombo values affecting filesystem access as untrusted; revalidate them at load/save boundaries with folder_paths, containment checks, or fixed allowlists.

Files:

  • tests-unit/comfy_extras_test/nodes_compositing_test.py
  • comfy_extras/nodes_compositing.py
**/*.{py,md,txt,json}

📄 CodeRabbit inference engine (AGENTS.md)

Keep warning and info messages short and actionable, remove noisy or misleading logging, and make documentation edits concise, factual, and tied to changed behavior.

Files:

  • tests-unit/comfy_extras_test/nodes_compositing_test.py
  • comfy_extras/nodes_compositing.py
**

⚙️ CodeRabbit configuration file

**: IMPORTANT: Only comment on issues directly introduced by this PR's code changes.
Treat AGENTS.md as mandatory repository policy, not optional style guidance.
Flag PR changes that violate AGENTS.md even when the code is otherwise functional.
In particular, enforce architecture boundaries, dtype/device/memory rules,
interface contracts, import style, no unnecessary try/except blocks, no inline
imports, no outbound internet paths in core ComfyUI, and narrow scoped fixes.
Prefer direct findings over suggestions when a rule is violated. Only ignore
AGENTS.md when it clearly conflicts with a newer explicit maintainer instruction
in the PR.
Do NOT flag pre-existing issues in code that was merely moved, re-indented,
de-indented, or reformatted without logic changes. If code appears in the diff
only due to whitespace or structural reformatting (e.g., removing a with: block),
treat it as unchanged. Contributors should not feel obligated to address
pre-existing issues outside the scope of their contribution.

Files:

  • tests-unit/comfy_extras_test/nodes_compositing_test.py
  • comfy_extras/nodes_compositing.py
comfy_extras/**

⚙️ CodeRabbit configuration file

comfy_extras/**: Community-contributed extra nodes. Focus on:

  • Consistency with node patterns (INPUT_TYPES, RETURN_TYPES, FUNCTION, CATEGORY)
  • No breaking changes to existing node interfaces

Files:

  • comfy_extras/nodes_compositing.py
🧠 Learnings (7)
📚 Learning: 2026-02-21T14:01:41.482Z
Learnt from: pythongosssss
Repo: Comfy-Org/ComfyUI PR: 12555
File: comfy_extras/nodes_glsl.py:719-724
Timestamp: 2026-02-21T14:01:41.482Z
Learning: In PyOpenGL, bare Python scalars can be accepted for 1-element array parameters by NumberHandler. This means you can pass an int/float directly to OpenGL texture deletion (e.g., glDeleteTextures(tex)) without wrapping in a list. Verify function-specific expectations and ensure types match what the OpenGL call expects; use explicit lists only when the API requires an array.

Applied to files:

  • tests-unit/comfy_extras_test/nodes_compositing_test.py
  • comfy_extras/nodes_compositing.py
📚 Learning: 2026-07-13T17:26:10.852Z
Learnt from: silveroxides
Repo: Comfy-Org/ComfyUI PR: 14922
File: tests-unit/comfy_extras_test/test_qwen_visual_fusion.py:3-7
Timestamp: 2026-07-13T17:26:10.852Z
Learning: In Comfy unit tests that import CUDA-dependent modules (e.g., tests that need `comfy_extras/nodes_qwen.py`), set the global `cli_args.cpu = True` at module load time *before* importing `comfy_extras/nodes_qwen.py` when CUDA is unavailable. Do not rely on `pytest` fixtures or `monkeypatch` for this kind of import-time behavior, because fixtures run after the test module is imported/collected and the CUDA code would already execute. The goal is to prevent import-time CUDA initialization and keep the tests runnable in CPU-only environments.

Applied to files:

  • tests-unit/comfy_extras_test/nodes_compositing_test.py
📚 Learning: 2026-03-04T14:05:31.426Z
Learnt from: jtydhr88
Repo: Comfy-Org/ComfyUI PR: 12757
File: comfy_extras/nodes_custom_sampler.py:1069-1089
Timestamp: 2026-03-04T14:05:31.426Z
Learning: In the ComfyUI sampling pipeline, treat percent_to_sigma(0.0) as a sentinel value (999999999.9) that means starting from pure noise. This is consistent with BasicScheduler via calculate_sigmas. The SamplingPercentToSigma node’s return_actual_sigma flag differentiates this sentinel from sigma_max. Reviewers should not flag CurveToSigmas or similar nodes that rely on percent_to_sigma as bugs; downstream samplers are expected to handle the sentinel correctly. When reviewing related sampling-related code, assume this sentinel semantics unless there is explicit handling for a real sigma_max.

Applied to files:

  • comfy_extras/nodes_compositing.py
📚 Learning: 2026-04-04T13:29:15.653Z
Learnt from: kijai
Repo: Comfy-Org/ComfyUI PR: 13258
File: comfy_extras/nodes_frame_interpolation.py:151-189
Timestamp: 2026-04-04T13:29:15.653Z
Learning: In this ComfyUI codebase, node `execute()` inference is already run under a global `torch.inference_mode()` context established in the execution engine (e.g., `execution.py` around line ~732). During review, avoid recommending changes that wrap node inference loops in `torch.inference_mode()`—it is already applied, so such suggestions are likely redundant.

Applied to files:

  • comfy_extras/nodes_compositing.py
📚 Learning: 2026-05-09T18:40:40.199Z
Learnt from: kijai
Repo: Comfy-Org/ComfyUI PR: 13813
File: comfy_extras/nodes_wandancer.py:868-872
Timestamp: 2026-05-09T18:40:40.199Z
Learning: When building video/temporal decoding nodes that call ComfyUI’s VAE.decode (comfy/sd.py), leverage VAE.decode’s existing VRAM-aware chunking along dim 0. Reshape or transpose the latent so the temporal dimension T is folded into dim 0 (e.g., transform a latent of shape [B, T, C, H, W] into [B*T, C, H, W] before calling vae.decode). This lets VAE.decode do chunked decoding without needing an explicit per-frame loop inside the node itself.

Applied to files:

  • comfy_extras/nodes_compositing.py
📚 Learning: 2026-05-20T00:10:14.673Z
Learnt from: Pauan
Repo: Comfy-Org/ComfyUI PR: 13997
File: comfy_extras/nodes_string.py:12-25
Timestamp: 2026-05-20T00:10:14.673Z
Learning: In the ComfyUI `comfy_extras/` codebase, some nodes intentionally ship with a default input string that references parameters that may not yet be connected. If the default would raise a `KeyError` (e.g., examples like `MathExpression` default `a + b`, or `StringFormat` default `{a}` with `min=0` and autogrow inputs), treat it as an intentional “hint default” UX pattern, not a bug. During review, do not flag this behavior or recommend changing `min` to `1` or altering the default to an empty string solely to avoid the `KeyError`.

Applied to files:

  • comfy_extras/nodes_compositing.py
📚 Learning: 2026-07-26T18:37:44.213Z
Learnt from: jtydhr88
Repo: Comfy-Org/ComfyUI PR: 15090
File: comfy_extras/nodes_video.py:230-235
Timestamp: 2026-07-26T18:37:44.213Z
Learning: In ComfyUI node implementations under `comfy_extras`, do not add regular widget/prompt inputs to `fingerprint_inputs` if they are already included in the node cache signature via `comfy_execution/caching.py:get_immediate_node_signature` (it records every non-link prompt input as `(key, inputs[key])`). Reserve `fingerprint_inputs` only for out-of-band state that can change without changing the prompt inputs (e.g., the selected source file’s modification time). For example, inputs like `LoadVideo.edit` should not be redundantly added to `fingerprint_inputs`; use it only for things not represented in prompt inputs.

Applied to files:

  • comfy_extras/nodes_compositing.py
🔇 Additional comments (2)
comfy_extras/nodes_compositing.py (1)

49-49: LGTM!

Also applies to: 67-75

tests-unit/comfy_extras_test/nodes_compositing_test.py (1)

1-59: LGTM!


📝 Walkthrough

Walkthrough

The compositing formulas for DARKEN, LIGHTEN, MULTIPLY, and OVERLAY now use corrected alpha-weighted and premultiplied calculations. The changes also correct union-alpha and operand handling. Parameterized tests compare each mode against a tensor-based source-over reference across four source and backdrop alpha combinations. Tests verify both RGB output and transparency masks.

Merge Risk: ⚪ Minimal · up to 7e837

The change corrects transparent-layer blend behavior while preserving the existing interface, with focused tests and passing checks reported; no actionable merge-blocking risk remains.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the fix for transparent-layer handling in Porter-Duff blend modes.
Description check ✅ Passed The description explains the affected modes, formula changes, specification basis, tests, and preserved interface.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@tandede
tandede force-pushed the fix/porter-duff-transparent-blends branch from 6b869a0 to 0c351fd Compare August 21, 2026 10:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant