Skip to content

feat: render drop shadow layer effect - #679

Closed
omar16100 wants to merge 1 commit into
psd-tools:mainfrom
omar16100:feat/drop-shadow-render
Closed

omar16100 wants to merge 1 commit into
psd-tools:mainfrom
omar16100:feat/drop-shadow-render

Conversation

@omar16100

@omar16100 omar16100 commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

composite() reads every drop shadow parameter but never drew the effect, so the shadow disappeared whenever a document was composited from its layers (force=True, ignore_preview=True, or after an edit). This renders it.

Rebased onto current main and re-implemented on the new effect pipeline (the June version conflicted with #846 and the reach work in #804, #808 and #815).

Approach

  • composite/effects.py: draw_drop_shadow() grows the layer's silhouette by Spread (the drop shadow's Ckmt; it expands the matte, where the inner shadow's Choke shrinks it), blurs it with a gaussian that takes what is left of Size, and casts it away from the light angle (global light included). drop_shadow_bbox() sizes the canvas. The blur treats the canvas edge as empty and is cut off at the remaining radius.
  • composite/composite.py: Compositor._apply_drop_shadows() paints each shadow beneath the layer, before the layer is resolved, so a pass-through group's contents blend with their own shadow. It fades with layer opacity but not fill opacity, and "Layer Knocks Out Drop Shadow" cuts it by the layer's own alpha. The silhouette is the layer's alpha before opacity and fill, read on the shadow's own box; for a group that is its contents composited over nothing (cached per pass). _effect_reach() adds the shadow's reach to the cull and to a group's content box.
  • Unreadable or non-finite parameters drop the effect rather than the document, like the stroke's guards.

Fidelity

Four fixtures in tests/psd_files carry a drop shadow rendered by Photoshop into the preview. tests/psd_tools/composite/test_drop_shadow.py holds each render to it, and checks that the same render with shadows off is clearly worse:

Fixture Region Shadows off (as on main) This PR
layer_effects.psd around the shadow 1.4e-3 4.3e-6
masks.psb whole document 1.8e-4 1.3e-5 (1.6e-5 with force=True)
layer_params.psb around the shadow 2.7e-2 5.2e-3 (rest: outer glow, not drawn)
layer_comps.psb whole document 6.7e-3 4.5e-3 (rest: bevel, not drawn)

The sigma (0.45 x size) is fitted against these. Forged cases cover layer and fill opacity, knockout on and off, groups (including faded children), pass-through groups, a vector-masked pixel layer, and a shadow cast into a viewport the layer misses.

Limits

Checks

Full suite, ruff check, ruff format --check and mypy pass locally, as does the no-composite job's test selection.

Copilot AI review requested due to automatic review settings June 24, 2026 09:38

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds drop shadow layer-effect rendering to the psd_tools.composite pipeline so composite(force=True) no longer silently drops the shadow, aligning output closer to Photoshop’s baked preview.

Changes:

  • Implement draw_drop_shadow(...) in composite/effects.py using choke (erosion), gaussian blur, and directional offset.
  • Apply drop shadow as an “outer effect” in Compositor.apply() before compositing the layer source (paints behind the layer).
  • Add unit tests for the mask renderer plus an integration-style fidelity test against layer_effects.psd.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

File Description
tests/psd_tools/composite/test_effects.py Adds unit + integration tests covering drop shadow mask behavior and fidelity improvement.
src/psd_tools/composite/effects.py Introduces draw_drop_shadow and updates effects module documentation.
src/psd_tools/composite/composite.py Hooks drop shadow rendering into the compositor before the layer source is blended.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/psd_tools/composite/effects.py Resolved
Comment thread src/psd_tools/composite/composite.py Outdated
Comment on lines +738 to +739
opacity = effect.opacity / 100.0
self._apply_source(shadow_color, mask, mask * opacity, effect.blend_mode)
@kyamagu

kyamagu commented Jun 28, 2026

Copy link
Copy Markdown
Contributor

@omar16100 Thanks. Can you at least address Copilot's suggestions? I have a concern about not having test fixtures to measure fidelity here

@github-actions

Copy link
Copy Markdown

This pull request has been marked as stale due to inactivity for 45 days.

If you plan to continue it, please leave a comment or push an update. If it is waiting on maintainer review, add or request an awaiting-review label so it is not auto-closed.

@github-actions github-actions Bot added the stale No recent activity; will be closed if no response label Aug 17, 2026
@bertou

bertou commented Aug 31, 2026

Copy link
Copy Markdown

I tested it (as I always wanted to have outer_glow working, #382 ), and it works fine with copilot corrections which are indeed correct (at least the 2 relative to adding the layer opacity).
It does not fully solve my issue in #382 as it doesn't take into account the "element" part of the effect, which in my case is used (softer instead of precise, with some values for spread and size). If I turn my element to precise I get the correct rendering. I guess for someone who understands what it does (or to copilot?) it may be straightforward to implement?
In my case it would be night and day as I could use psd-tools to generate the png instead of using it only to parse the psd files and then dump a photoshop jsx to process the files and export pngs...

@github-actions github-actions Bot removed the stale No recent activity; will be closed if no response label Sep 7, 2026
composite() read every drop shadow parameter but never drew the effect,
so the shadow vanished whenever a document was composited from its
layers. Draw it: the layer's silhouette, grown by spread, blurred and
cast away from the light, painted beneath the layer before the layer is
resolved.

- draw_drop_shadow() and drop_shadow_bbox() in composite/effects.py.
  For a drop shadow the Ckmt key is Photoshop's Spread, which grows the
  matte before the blur (choke, which shrinks it, is the inner shadow's),
  and the blur takes what is left of the size. The gaussian treats the
  canvas edge as empty and is cut off at the remaining radius, so the
  canvas holds the whole shadow.
- The shadow fades with the layer's opacity but not its fill opacity,
  and "layer knocks out drop shadow" cuts it away under the silhouette
  it is cast from.
- The silhouette is the layer's alpha before opacity and fill, read on
  the shadow's own box: a group's is its contents composited over
  nothing, so faded children cast lighter shadows and a knockout inside
  does not make the shadow depend on the viewport.
- The cull and a group's content box include the shadow's reach, and a
  group's shadow is grown from its content box, its children's effects
  included.
- Painting before the layer is resolved puts the shadow under a
  pass-through group's contents, which blend with it.

The blur sigma, 0.45 x size, is fitted against the four fixtures that
carry a drop shadow Photoshop rendered into its preview, and
test_drop_shadow.py holds each to it: layer_effects.psd 1.4e-3 -> 4.3e-6
around the shadow, masks.psb 1.8e-4 -> 1.3e-5 over the document,
layer_params.psb 2.7e-2 -> 5.2e-3 and layer_comps.psb 6.7e-3 -> 4.5e-3,
the rest of those two being an outer glow and a bevel that are not
drawn. Contour and noise are not applied.

Addresses the review on psd-tools#679: the gaussian's edge mode and the layer
opacity, both reported by Copilot.
@omar16100
omar16100 force-pushed the feat/drop-shadow-render branch from 2f312f5 to d6dc070 Compare September 27, 2026 05:27
@omar16100

Copy link
Copy Markdown
Contributor Author

Thanks @kyamagu for the review, and @bertou for testing it and confirming the opacity fix.

I've reworked this on top of current main. The effect pipeline changed a lot since June (effects composite into the layer now, plus the reach and tracing work from #804, #808 and #815), so instead of resolving conflicts I re-implemented the shadow on the new pipeline and force-pushed it as a single commit.

Copilot's two suggestions

  • gaussian_filter now uses mode="constant", cval=0.0, like the shift after it. The kernel is also cut off at the remaining size, so the canvas drop_shadow_bbox() reserves holds the whole shadow.
  • Layer opacity now fades the shadow, the same way it fades an outer stroke band (effect opacity times layer opacity). Fill opacity does not, which matches Photoshop: fill fades the layer's own pixels, not its effects. "Layer Knocks Out Drop Shadow" cuts the shadow by the layer's own alpha, so fill 0 with knockout on gives the usual "shadow only" result.

Other fixes made while porting

  • For a drop shadow the Ckmt key is Spread, which grows the matte before the blur (the blur then takes what is left of Size). My first version eroded it, which is Choke, the inner shadow's behaviour.
  • The shadow is cast from the layer's alpha before its opacity and fill. For a group that is its contents composited over nothing, so semi-transparent children cast a lighter shadow and a child at opacity 0 casts none.
  • The cull and a group's content box now include the shadow's reach, and the silhouette is read past the viewport the way strokes are.
  • The shadow goes on before the layer is resolved, so a pass-through group's contents blend with it.
  • Non-finite parameters drop the effect instead of spreading NaN through the canvas.

Fidelity fixtures

Four documents already in tests/psd_files carry a drop shadow that Photoshop rendered into the preview, so the new tests/psd_tools/composite/test_drop_shadow.py measures against those (MSE against psd.numpy()). Each case also checks that the same render with its shadows switched off is clearly worse, so the region really is measuring a shadow:

Fixture Region Shadows off (as on main) This PR
layer_effects.psd around the shadow 1.4e-3 4.3e-6
masks.psb whole document 1.8e-4 1.3e-5 (1.6e-5 with force=True)
layer_params.psb around the shadow 2.7e-2 5.2e-3 (the rest is an outer glow, not drawn)
layer_comps.psb whole document 6.7e-3 4.5e-3 (the rest is a bevel, not drawn)

The blur sigma (0.45 x size) is fitted against these; the size/3 I used before scores 4.0e-5 around the layer_effects.psd shadow. layer_params.psb also pins the spread direction: ignoring spread scores 6.6e-3 and eroding by it 9.2e-3. The combinations the corpus doesn't pair with a shadow (layer and fill opacity, knockout off, groups, pass-through groups, a vector-masked pixel layer, a shadow cast into a viewport the layer misses) have targeted tests of their own.

Known limits, in the code and the changelog entry: contour and noise are not applied, and the blur is a gaussian approximation of Photoshop's. Spread on a very large soft-edged layer is slower, since it grows up to 16 coverage levels. A pass-through group that knocks out loses its shadow's colour the same way it already loses the colour of every layer beneath it (#707).

@bertou the Softer/Precise "Technique" option belongs to Outer Glow (#382), which this PR doesn't render, so I'd keep it out of scope here. It could be a follow-up on the same machinery, and if you're able to share your PSD it would make a good fidelity fixture for it.

The full test suite, ruff, ruff format and mypy pass locally.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🔵 Needs a closer look

Pass-through artboard shadows may be incorrectly clipped; an additional performance nit remains.

Review effort: Lite
Findings: 1 Medium severity

Open (1)
Resolved since last review (1)

@kyamagu kyamagu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the full diff, ran the suite, and swept the fixture corpus. The implementation is sound and the test file is unusually strong — viewport independence, pass-through ordering, the group silhouette read from alpha, nesting cost, force parity and unreadable-descriptor degradation are all pinned.

Verification

  • tests/psd_tools/composite + tests/psd_tools/api: 1880 passed, including all 49 new drop-shadow tests.
  • Corpus sweep (every fixture in tests/psd_files, force both ways, MSE against psd.numpy()), merge-base vs. this head: 8 documents change, all 8 improve, no new exceptions and no shape changes. masks.psb 1.76e-4 → 1.27e-5, layer_params.psb 1.19e-2 → 4.51e-3, layer_comps.psb 6.71e-3 → 4.46e-3, layer_effects.psd 6.60e-3 → 6.42e-3.
  • Runtime cost is modest: masks.psb 0.54 s → 0.67 s, layer_params.psb 0.064 s → 0.124 s.

Two issues inline, one on the unclipped shadow canvas and one on the opacity guard.

Not findings, but worth knowing

  • The branch is not rebased onto current main — its merge-base is 8f9a25ea, so it is missing #887. git merge-tree shows no textual conflicts, but the fidelity figures in the description were measured on the older base.
  • _cast_bbox() uses layer.is_group() while _cast_shape() uses isinstance(layer, GroupMixin). No fixture in the corpus distinguishes them (all 25 layer classes present were checked), but the module prefers is_group() elsewhere, because the protocol isinstance can be defeated by a raising property on Python ≤ 3.11.
  • On a scipy-less install a document with a drop shadow now raises ImportError out of composite() where it previously rendered without the shadow. That matches the existing stroke behaviour exactly — layer_comps.psb already raised on the base for the same reason — so it reads as intentional.

continue
if utils.intersect(self._viewport, bbox) == (0, 0, 0, 0):
continue
silhouette = self._cast_shape(layer, bbox)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The shadow canvas is never clipped to the viewport, so a large size or distance allocates unboundedly.

drop_shadow_bbox() grows cast_from by ceil(size) + 2 on all four sides and by the full offset on the cast side, with no clamp, and _cast_shape(layer, bbox) here materialises that whole canvas — _spread(), gaussian_filter() and ndimage.shift() then all run on it. The utils.intersect(self._viewport, bbox) guard two lines up never fires, because bbox ⊇ cast_from ⊇ layer.bbox, so any layer visible in the viewport reaches the allocation.

Measured on layer_comps.psb (200x200 document, shadowed layer Фигура 1 at (17, 20, 180, 183)) with a forged Blur:

forged value shadow canvas
Blur=1000 2167x2167 = 19 MB
Blur=20000 40167x40167 = 6.4 GB
Blur=1e9 2000000167² = 1.6e19 bytes

At Blur=1e9, composite() does not raise a caught _UNREADABLE error — it runs until killed. The guards just above cover math.ceil(inf) and nan, but not a finite huge value, and _cast_shape() sits outside both try blocks anyway.

It also costs on values Photoshop itself permits. With Distance=30000 (Photoshop's own maximum) and the light angled so the shadow lands entirely off-canvas, composite(masks.psb) goes from 0.80 s / 176 MB peak to 4.67 s / 550 MB peak (tracemalloc), for a shadow that contributes nothing — the canvas is 187x30187 per shadow.

Suggestion: after computing bbox, intersect it with the viewport unioned with the viewport shifted back by (-dx, -dy), grown by ceil(size) + 2, before handing it to _cast_shape(). Nothing outside that can land in the viewport. _shadow_reach() can stay as it is, since it is only a reach measurement.

try:
distance, angle = shadow.distance, shadow.angle
size, spread = shadow.size, shadow.choke
effect_opacity = shadow.opacity / 100.0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The finiteness guard on the next line is applied in float64, but the arithmetic downstream is float32, so a finite-but-huge Opct still puts NaN across the whole document.

shadow.opacity is read unclamped from the descriptor. With Opct = 1e300 the check passes, since 1e298 is finite, but coverage * effect_opacity * opacity below is float32, overflows to inf, and _apply_source()'s utils.union turns that into NaN. Measured on masks.psb: composite(psd) returns an alpha canvas that is entirely NaN (np.isfinite(alpha).all() is False) — exactly the failure the docstring says this guard exists to prevent, that "one NaN in the coverage spreads to the whole canvas it is composited on".

Three more values escape it the same way: Opct = 1e39 gives a finite but absurd alpha up to 4.9e36, and Opct = 400 and Opct = -100 give alpha 2.11 and −0.53, both outside [0, 1]. The _UNDRAWABLE table in test_drop_shadow.py covers nan-opacity and infinite-opacity, but not these.

Clamping to Photoshop's own range closes all four at once and makes the explicit isfinite check redundant:

effect_opacity = min(max(shadow.opacity, 0.0), 100.0) / 100.0

The pre-existing stroke and overlay paths (lines 1988 and 2019) share the unclamped division, so a shared clamp would be tidier than a shadow-only one.

@kyamagu kyamagu added this to the 1.25.0 milestone Oct 6, 2026
@kyamagu kyamagu modified the milestones: 1.25.0, 1.26.0 Oct 14, 2026
@kyamagu kyamagu modified the milestones: 1.26.0, 1.27.0 Oct 21, 2026
@kyamagu kyamagu mentioned this pull request Oct 21, 2026
4 tasks done
@kyamagu

kyamagu commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Thank you @omar16100 for this PR. The drop shadow rendering here was the starting point for the work, and I'm closing this in favour of #1069, which takes it over.

#1069 keeps your commit (you remain its author), rebases it onto current main, addresses the review feedback, and adds fixtures authored in Photoshop so the output is measured against Photoshop's own render: opacity, groups, spread, blend modes and knockout. Remaining differences are tracked in #1075 (spread on feathered layers) and #1076 (eight blend modes).

Thanks also @bertou for testing it. Outer glow (#382) is separate and not covered there.

@kyamagu kyamagu closed this Nov 13, 2026
kyamagu added a commit that referenced this pull request Nov 16, 2026
feat: render drop shadow layer effect (takes over #679)
@kyamagu kyamagu mentioned this pull request Nov 18, 2026
3 tasks done
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.

4 participants