using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using ABI.Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas;
namespace ComputeSharp.D2D1.WinUI;
///
/// A base type to implement packaged and easy to use -based effects that can be used with Win2D.
///
public abstract partial class CanvasEffect : ICanvasImage, ICanvasImageInterop.Interface
{
///
/// The mapping of registered transform nodes for the current effect graph.
///
///
/// When not empty (ie. when an effect graph has been built), this will always also include .
///
private readonly Dictionary transformNodes = [];
///
/// The current cached result for , if available.
///
private ICanvasImage? canvasImage;
///
/// Indicates the current invalidation state for the effect graph (which controls the logic in ).
///
private InvalidationType invalidationType = InvalidationType.Creation;
///
/// Indicates whether the effect is disposed.
///
private bool isDisposed;
///
/// Builds the effect graph for the current instance, and configures all effect nodes, as well as the output
/// node for the graph. That instance will then be passed to Win2D to perform the actual drawing, when needed.
///
/// The input value to use to build the effect graph.
///
///
/// This method is called once before the current effect is drawn, and the resulting image is automatically cached and reused.
/// It will remain in use until is called with .
///
///
/// If the effect is invalidated with , only will be
/// called. As such, derived types should save any effect graph nodes that might need updates into instance fields, for later use.
///
///
/// For instance, consider a FrostedGlassEffect type deriving from , with this effect graph:
///
/// ┌────────┐ ┌──────┐ ┌──────┐ ┌───────┐ ┌────────┐
/// │ source ├──►│ blur ├──►│ tint ├──►│ noise ├──►│ output │
/// └────────┘ └──────┘ └──────┘ └───────┘ └────────┘
///
///
///
/// In this example, blur is a instance, tint
/// is a . and noise is some other custom effect. In this case,
/// the instance returned by will be noise , as that's the output
/// node for the effect graph. At the same time, both blur and tint will also need to be saved as instance fields,
/// so that will be able to set properties on them when needed. For instance, the effect might
/// expose a property to control the blur amount, as well as the tint color and opacity.
///
///
/// Generally speaking, an implementation of will consist of these steps:
///
/// - Create an instance of all necessary nodes in the effect graph.
/// - Connect the effect nodes as needed to build the connected graph.
/// - Register all effects as effect nodes in the graph, including the output node.
///
///
///
/// For convenience, it is recommended to store all necessary objects in
/// fields, so they can easily be accessed from and .
///
///
/// This method should never be called directly. It is automatically invoked when an effect graph is needed.
///
///
protected abstract void BuildEffectGraph(EffectGraph effectGraph);
///
/// Configures the current effect graph whenever it is invalidated.
///
/// The input value to use to configure the effect graph.
///
///
/// This method is guaranteed to be called after has been invoked already. As such, any instance
/// fields that are set by can be assumed to never be when this method runs.
///
///
/// This method should never be called directly. It is used internally to configure the current effect graph.
///
///
protected abstract void ConfigureEffectGraph(EffectGraph effectGraph);
///
/// Invalidates the last returned result from .
///
/// The invalidation type to request.
///
///
/// This method is used to signal when the effect graph should be updated, and it can indicate
/// that either the entire graph should be created again (by calling ),
/// or whether it simply needs to refresh its internal state (by calling ).
///
///
/// If is called with , the effect
/// graph will only be refreshed the next time the image is actually requested. That is, repeated requests
/// for updates do not result in unnecessarily calls to .
///
///
protected void InvalidateEffectGraph(InvalidationType invalidationType = InvalidationType.Update)
{
lock (this.transformNodes)
{
// This method only updates the invalidation type. The next time the effect is drawn,
// the current graph (if existing) will be disposed automatically before building a
// new one. If the invalidation mode just needs an update, no disposal will happen.
// The new invalidation type is always set to the maximum between the current one and
// the requested one. This means that eg. if the current invalidation type is creation,
// and a property only needing an update is set, the creation request will persist.
this.invalidationType = (InvalidationType)Math.Max((byte)this.invalidationType, (byte)invalidationType);
}
}
///
/// Updates the backing storage for an effect property and checks if it has changed.
/// If so, it invalidates the effect graph as well with the requested invalidation type.
///
/// The type of the property that changed.
/// The storage for the effect property value.
/// The new effect property value to set.
/// The invalidation type to request.
protected void SetAndInvalidateEffectGraph([NotNullIfNotNull(nameof(value))] ref T storage, T value, InvalidationType invalidationType = InvalidationType.Update)
{
if (EqualityComparer.Default.Equals(storage, value))
{
return;
}
storage = value;
InvalidateEffectGraph(invalidationType);
}
///
/// Disposes any disposable resources in the current instance.
///
///
/// Indicates whether the method was called from of from a finalizer:
///
/// : the method was called from .
/// : the method was called from a finalizer.
///
///
///
///
/// If implementing a type that derives from , this method can be overridden to add logic to dispose
/// any additional state. Managed objects should only be disposed when is .
///
///
/// If the derived type does not need a finalizer (ie. if it doesn't wrap any native resources), this method should not be
/// called directly. It will be called automatically by . If the derived type does instead define a
/// finalizer, it should call with a value of . As mentioned above, when
/// implementing in a derived type, managed objects should only be disposed when
/// is , otherwise only unmanaged resorces should be disposed.
///
///
/// Though the pattern does support this, it is recommended not to add finalizers in types deriving from .
/// Rather, if an effect needs to wrap native resources, it should do so via some same managed wrapper type (such as
/// ), or some other custom unmanaged resource wrapper type.
///
///
///
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// Only take a lock and dispose the image if the method was called explicitly from user code. If instead it was
// called from the finalizer, we can make no guarantees on the order of objects being collected, meaning that
// the lock itself might have already been collected by the time this code runs, which would lead the lock
// statement to throw a NullReferenceException. So if a finalizer is running, just let objects be collected
// on their own. This is fine here since there are no unmanaged references to free, but just managed wrappers.
lock (this.transformNodes)
{
DisposeEffectGraph();
}
}
this.isDisposed = true;
}
///
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
/// Indicates the invalidation type to request when invoking and related methods.
///
protected enum InvalidationType : byte
{
///
/// Invalidates the state of the effect graph, causing it to be configured again the next time it is used.
///
///
///
/// This will preserve the last returned instance, if available, and it will only
/// mark the internal state as being out of date, resulting in to be called
/// the next time the effect is used for drawing.
///
///
/// This is much less expensive than creating the effect graph again, and should be preferred if possible.
///
///
Update,
///
/// Fully invalidates the effect graph, causing it to be created again the next time it is needed.
///
///
/// This will cause the last returned instance to be disposed and discarded,
/// and to be called again the next time the effect is used for drawing.
///
Creation
}
}