Merge pull request #517 from Sergio0694/dev/effect-graph-apis

Add new CanvasEffect.EffectGraph APIs
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2023-05-01 12:17:22 -07:00
コミット 0d1292f82e
12ファイル変更
+1001 -136

検索条件に一致するファイルはありません

+9 -23
ファイルの表示
@@ -5,7 +5,6 @@ using ComputeSharp.D2D1.Uwp;
#else
using ComputeSharp.D2D1.WinUI;
#endif
using Microsoft.Graphics.Canvas;
#nullable enable
@@ -65,16 +64,16 @@ public abstract class PixelShaderEffect : CanvasEffect
public sealed class For<T> : PixelShaderEffect
where T : unmanaged, ID2D1PixelShader
{
/// <summary>
/// The <see cref="PixelShaderEffect{T}"/> node in use.
/// </summary>
private static readonly EffectNode<PixelShaderEffect<T>> Effect = new();
/// <summary>
/// The <typeparamref name="T"/> factory to use.
/// </summary>
private readonly Factory factory;
/// <summary>
/// The <see cref="PixelShaderEffect{T}"/> instance in use.
/// </summary>
private PixelShaderEffect<T>? effect;
/// <summary>
/// Creates a new <see cref="For{T}"/> instance with the specified parameters.
/// </summary>
@@ -85,28 +84,15 @@ public abstract class PixelShaderEffect : CanvasEffect
}
/// <inheritdoc/>
protected override ICanvasImage BuildEffectGraph()
protected override void BuildEffectGraph(EffectGraph effectGraph)
{
this.effect = new PixelShaderEffect<T>();
return this.effect;
effectGraph.RegisterOutputNode(Effect, new PixelShaderEffect<T>());
}
/// <inheritdoc/>
protected override void ConfigureEffectGraph()
protected override void ConfigureEffectGraph(EffectGraph effectGraph)
{
this.effect!.ConstantBuffer = this.factory(ElapsedTime, ScreenWidth, ScreenHeight);
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
this.effect?.Dispose();
}
effectGraph.GetNode(Effect).ConstantBuffer = this.factory(ElapsedTime, ScreenWidth, ScreenHeight);
}
/// <summary>
+8 -19
ファイルの表示
@@ -8,7 +8,6 @@ using ComputeSharp.D2D1.Uwp;
using ComputeSharp.D2D1.WinUI;
#endif
using ComputeSharp.SwapChain.Shaders.D2D1;
using Microsoft.Graphics.Canvas;
using Windows.ApplicationModel;
#nullable enable
@@ -21,12 +20,12 @@ namespace ComputeSharp.SwapChain.Core.Shaders.Runners;
public sealed class D2D1ContouredLayersEffect : PixelShaderEffect
{
/// <summary>
/// The reusable <see cref="PixelShaderEffect{T}"/> instance to use to render frames.
/// The reusable <see cref="PixelShaderEffect{T}"/> node to use to render frames.
/// </summary>
private PixelShaderEffect<ContouredLayers>? pixelShaderEffect;
private static readonly EffectNode<PixelShaderEffect<ContouredLayers>> PixelShaderEffect = new();
/// <inheritdoc/>
protected override unsafe ICanvasImage BuildEffectGraph()
protected override unsafe void BuildEffectGraph(EffectGraph effectGraph)
{
string filename = Path.Combine(Package.Current.InstalledLocation.Path, "Assets", "Textures", "RustyMetal.png");
@@ -56,25 +55,15 @@ public sealed class D2D1ContouredLayersEffect : PixelShaderEffect
strides: stackalloc uint[] { (uint)strideInBytes });
// Create the new pixel shader effect
this.pixelShaderEffect = new PixelShaderEffect<ContouredLayers>() { ResourceTextureManagers = { [0] = resourceTextureManager } };
PixelShaderEffect<ContouredLayers> pixelShaderEffect = new() { ResourceTextureManagers = { [0] = resourceTextureManager } };
return this.pixelShaderEffect;
// Register the pixel shader effect as the output node in the effect graph
effectGraph.RegisterOutputNode(PixelShaderEffect, pixelShaderEffect);
}
/// <inheritdoc/>
protected override void ConfigureEffectGraph()
protected override void ConfigureEffectGraph(EffectGraph effectGraph)
{
this.pixelShaderEffect!.ConstantBuffer = new ContouredLayers((float)ElapsedTime.TotalSeconds, new int2(ScreenWidth, ScreenHeight));
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
this.pixelShaderEffect?.Dispose();
}
effectGraph.GetNode(PixelShaderEffect).ConstantBuffer = new ContouredLayers((float)ElapsedTime.TotalSeconds, new int2(ScreenWidth, ScreenHeight));
}
}
+9 -22
ファイルの表示
@@ -59,16 +59,16 @@ internal abstract class PixelShaderEffect : CanvasEffect
public sealed class For<T> : PixelShaderEffect
where T : unmanaged, ID2D1PixelShader
{
/// <summary>
/// The <see cref="PixelShaderEffect{T}"/> node in use.
/// </summary>
private static readonly EffectNode<PixelShaderEffect<T>> Effect = new();
/// <summary>
/// The <typeparamref name="T"/> factory to use.
/// </summary>
private readonly Factory factory;
/// <summary>
/// The <see cref="PixelShaderEffect{T}"/> instance in use.
/// </summary>
private PixelShaderEffect<T>? effect;
/// <summary>
/// Creates a new <see cref="For{T}"/> instance with the specified parameters.
/// </summary>
@@ -79,28 +79,15 @@ internal abstract class PixelShaderEffect : CanvasEffect
}
/// <inheritdoc/>
protected override ICanvasImage BuildEffectGraph()
protected override void BuildEffectGraph(EffectGraph effectGraph)
{
this.effect = new PixelShaderEffect<T>();
return this.effect;
effectGraph.RegisterOutputNode(Effect, new PixelShaderEffect<T>());
}
/// <inheritdoc/>
protected override void ConfigureEffectGraph()
protected override void ConfigureEffectGraph(EffectGraph effectGraph)
{
this.effect!.ConstantBuffer = this.factory(ElapsedTime, ScreenWidth, ScreenHeight);
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
this.effect?.Dispose();
}
effectGraph.GetNode(Effect).ConstantBuffer = this.factory(ElapsedTime, ScreenWidth, ScreenHeight);
}
/// <summary>
+27 -1
ファイルの表示
@@ -36,7 +36,22 @@ internal static class InvalidOperationExceptionExtensions
}
/// <summary>
/// Throws an <see cref="InvalidOperationException"/> for a given parameter name.
/// Throws an <see cref="InvalidOperationException"/> if <paramref name="condition"/> is <see langword="true"/>.
/// </summary>
/// <param name="_">Dummy value to invoke the extension upon (always pass <see langword="null"/>.</param>
/// <param name="condition">The condition to decide whether to throw the exception.</param>
/// <param name="message">The message to include in the exception.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ThrowIf(this InvalidOperationException? _, [DoesNotReturnIf(true)] bool condition, string message)
{
if (condition)
{
Throw(message);
}
}
/// <summary>
/// Throws an <see cref="InvalidOperationException"/>.
/// </summary>
/// <exception cref="InvalidOperationException">Always thrown with no parameters.</exception>
[DoesNotReturn]
@@ -44,4 +59,15 @@ internal static class InvalidOperationExceptionExtensions
{
throw new InvalidOperationException();
}
/// <summary>
/// Throws an <see cref="InvalidOperationException"/> with a given message.
/// </summary>
/// <param name="message">The message to include in the exception.</param>
/// <exception cref="InvalidOperationException">Always thrown with no parameters.</exception>
[DoesNotReturn]
private static void Throw(string message)
{
throw new InvalidOperationException(message);
}
}
+265
ファイルの表示
@@ -0,0 +1,265 @@
using System;
using System.Runtime.CompilerServices;
using Microsoft.Graphics.Canvas;
#if WINDOWS_UWP
namespace ComputeSharp.D2D1.Uwp;
#else
namespace ComputeSharp.D2D1.WinUI;
#endif
/// <inheritdoc/>
partial class CanvasEffect
{
/// <summary>
/// An object representing an effect graph being built or configured.
/// </summary>
protected readonly ref struct EffectGraph
{
/// <summary>
///The owning <see cref="CanvasEffect"/> instance.
/// </summary>
private readonly CanvasEffect owner;
/// <summary>
/// Creates a new <see cref="EffectGraph"/> instance with the specified parameters.
/// </summary>
/// <param name="owner">The owning <see cref="CanvasEffect"/> instance.</param>
internal EffectGraph(CanvasEffect owner)
{
this.owner = owner;
}
/// <summary>
/// Gets a previously registered <see cref="ICanvasImage"/> object associated with a given effect graph node.
/// </summary>
/// <param name="effectNode">The <see cref="IEffectNode"/> instance to use to lookup the <see cref="ICanvasImage"/> object to retrieve.</param>
/// <returns>The <see cref="ICanvasImage"/> object associated with <paramref name="effectNode"/> in the effect graph.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="effectNode"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="effectNode"/> is not currently registered in the effect graph.</exception>
/// <exception cref="InvalidOperationException">Thrown if the current <see cref="EffectGraph"/> instance is not valid.</exception>
public ICanvasImage GetNode(IEffectNode effectNode)
{
default(ArgumentNullException).ThrowIfNull(effectNode);
default(InvalidOperationException).ThrowIf(this.owner is null);
// Try to get the canvas image associated with the input effect node marker.
// This must have been previously registered in a call to BuildEffectGraph.
if (!this.owner.transformNodes.TryGetValue(effectNode, out ICanvasImage? canvasImage))
{
default(ArgumentException).Throw(nameof(effectNode), "The specified node is not registered in the effect graph.");
}
return canvasImage;
}
/// <summary>
/// Gets a previously registered <typeparamref name="T"/> object (an <see cref="ICanvasImage"/> instance) associated with a given effect graph node.
/// </summary>
/// <typeparam name="T">The type of <see cref="ICanvasImage"/> object to retrieve.</typeparam>
/// <param name="effectNode">The <see cref="IEffectNode{T}"/> instance to use to lookup the <see cref="ICanvasImage"/> object to retrieve.</param>
/// <returns>The <typeparamref name="T"/> object associated with <paramref name="effectNode"/> in the effect graph.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="effectNode"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="effectNode"/> is not currently registered in the effect graph.</exception>
/// <exception cref="InvalidOperationException">Thrown if the current <see cref="EffectGraph"/> instance is not valid.</exception>
public T GetNode<T>(IEffectNode<T> effectNode)
where T : class, ICanvasImage
{
default(ArgumentNullException).ThrowIfNull(effectNode);
default(InvalidOperationException).ThrowIf(this.owner is null);
// Retrieve the registered canvas image, same as above
if (!this.owner.transformNodes.TryGetValue(effectNode, out ICanvasImage? canvasImage))
{
default(ArgumentException).Throw(nameof(effectNode), "The specified node is not registered in the effect graph.");
}
// Return the T node (we can skip the expensive cast since this is guaranteed to be valid).
// This is because EffectNode<T> being registered can only associate T instances with them.
return Unsafe.As<T>(canvasImage);
}
/// <summary>
/// Registers an <see cref="ICanvasImage"/> object in the effect graph.
/// </summary>
/// <param name="canvasImage">The <see cref="ICanvasImage"/> object to register in the effect graph.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="canvasImage"/> is <see langword="null"/>.</exception>
/// <exception cref="InvalidOperationException">
/// Thrown if the current <see cref="EffectGraph"/> instance is not valid or if the effect graph does not support modifications at this time.
/// </exception>
/// <remarks>
/// <para><inheritdoc cref="RegisterNode{T}(EffectNode{T}, T)" path="/remarks/node()"/></para>
/// <para>
/// This method can be used when <paramref name="canvasImage"/> doesn't need to be retrieved from <see cref="ConfigureEffectGraph"/>, ie.
/// when it has no properties that the current effect instance will need to mutate over it. Using this method still allows the effect to
/// correctly track the image ownership, so that it can be disposed when the current effect instance is disposed.
/// </para>
/// <para>
/// If performing lookups on <paramref name="canvasImage"/> is required, use the <see cref="RegisterNode{T}(EffectNode{T}, T)"/> overload.
/// </para>
/// </remarks>
public void RegisterNode(ICanvasImage canvasImage)
{
default(ArgumentNullException).ThrowIfNull(canvasImage);
default(InvalidOperationException).ThrowIf(this.owner is null);
default(InvalidOperationException).ThrowIf(this.owner.invalidationType != InvalidationType.Creation, "The effect graph cannot be modified after its creation.");
// Use a new dummy object as key to register the anonymous effect node. This is cheaper than having to maintain a different
// data structure (eg. a HashSet<ICanvasImage> instance) just to hold the anonymous effects that may be registered. This way,
// the same dictionary can be reused for all kinds of effect nodes instead. Anonymous effects are generally a nicher scenario.
_ = this.owner.transformNodes.TryAdd(new object(), canvasImage);
}
/// <summary>
/// Registers an <see cref="ICanvasImage"/> object in the effect graph, associated with a given <see cref="EffectNode{T}"/> instance.
/// </summary>
/// <typeparam name="T">The type of <see cref="ICanvasImage"/> object to register.</typeparam>
/// <param name="effectNode">The <see cref="EffectNode{T}"/> instance to use to register <paramref name="canvasImage"/>.</param>
/// <param name="canvasImage">The <see cref="ICanvasImage"/> object to register in the effect graph.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="effectNode"/> or <paramref name="canvasImage"/> are <see langword="null"/>.</exception>
/// <exception cref="InvalidOperationException">
/// Thrown if the current <see cref="EffectGraph"/> instance is not valid or if the effect graph does not support modifications at this time.
/// </exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="effectNode"/> is already registered in the effect graph.</exception>
/// <remarks>
/// This method can only be called from an <see cref="EffectGraph"/> value being passed to <see cref="BuildEffectGraph"/>. If this
/// method is called from within <see cref="ConfigureEffectGraph"/>, it will fail, as the effect graph cannot be mutated from there.
/// </remarks>
public void RegisterNode<T>(EffectNode<T> effectNode, T canvasImage)
where T : class, ICanvasImage
{
default(ArgumentNullException).ThrowIfNull(effectNode);
default(ArgumentNullException).ThrowIfNull(canvasImage);
default(InvalidOperationException).ThrowIf(this.owner is null);
default(InvalidOperationException).ThrowIf(this.owner.invalidationType != InvalidationType.Creation, "The effect graph cannot be modified after its creation.");
// Try to add the new canvas image associated with the input effect node marker.
// This must not have been previously added from another RegisterNode call.
if (!this.owner.transformNodes.TryAdd(effectNode, canvasImage))
{
default(ArgumentException).Throw(nameof(effectNode), "The specified node is already registered in the effect graph.");
}
}
/// <summary>
/// Registers an <see cref="ICanvasImage"/> object in the effect graph, and marks it as the output node for the effect graph being built.
/// </summary>
/// <remarks>
/// <para><inheritdoc cref="RegisterNode{T}(EffectNode{T}, T)" path="/remarks/node()"/></para>
/// <para>
/// This method can be used when <paramref name="canvasImage"/> doesn't need to be retrieved from <see cref="ConfigureEffectGraph"/>, ie.
/// when it has no properties that the current effect instance will need to mutate over it. Using this method still allows the effect to
/// correctly track the image ownership, so that it can be disposed when the current effect instance is disposed.
/// </para>
/// <para>
/// If performing lookups on <paramref name="canvasImage"/> is required, use the <see cref="RegisterOutputNode{T}(EffectNode{T}, T)"/> overload.
/// </para>
/// </remarks>
/// <inheritdoc cref="RegisterNode(ICanvasImage)"/>
public void RegisterOutputNode(ICanvasImage canvasImage)
{
default(ArgumentNullException).ThrowIfNull(canvasImage);
default(InvalidOperationException).ThrowIf(this.owner is null);
default(InvalidOperationException).ThrowIf(this.owner.invalidationType != InvalidationType.Creation, "The effect graph cannot be modified after its creation.");
// Register the anonymous effect node with a dummy object, same as above
_ = this.owner.transformNodes.TryAdd(new object(), canvasImage);
// Store the anonymous output node for later use
this.owner.canvasImage = canvasImage;
}
/// <summary>
/// Registers an <see cref="ICanvasImage"/> object in the effect graph, associated with a given <see cref="EffectNode{T}"/> instance.
/// Additionally, it also marks the input <see cref="ICanvasImage"/> object as the output node for the effect graph being built.
/// </summary>
/// <inheritdoc cref="RegisterNode"/>
public void RegisterOutputNode<T>(EffectNode<T> effectNode, T canvasImage)
where T : class, ICanvasImage
{
default(ArgumentNullException).ThrowIfNull(effectNode);
default(ArgumentNullException).ThrowIfNull(canvasImage);
default(InvalidOperationException).ThrowIf(this.owner is null);
default(InvalidOperationException).ThrowIf(this.owner.invalidationType != InvalidationType.Creation, "The effect graph cannot be modified after its creation.");
// Try to add the output node as in the method above (but with an extra check before doing so)
if (!this.owner.transformNodes.TryAdd(effectNode, canvasImage))
{
default(ArgumentException).Throw(nameof(effectNode), "The specified node is already registered in the effect graph.");
}
// Store the output node for later use
this.owner.canvasImage = canvasImage;
}
/// <summary>
/// Sets a previously registered <see cref="IEffectNode"/> instance as the output node for the effect graph.
/// </summary>
/// <param name="effectNode">The <see cref="IEffectNode"/> instance to set as output node for the effect graph.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="effectNode"/> is <see langword="null"/>.</exception>
/// <exception cref="InvalidOperationException">Thrown if the current <see cref="EffectGraph"/> instance is not valid.</exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="effectNode"/> is not registered in the effect graph.</exception>
/// <remarks>
/// This method can be called from both <see cref="BuildEffectGraph"/> and <see cref="ConfigureEffectGraph"/>. It can be used for
/// efficiently changing the output node of a graph, without having to rebuild it. For instance, this can be used for effects that
/// have multiple paths that can be taken for their inputs, depending on the value of some property describing the effect behavior.
/// </remarks>
public void SetOutputNode(IEffectNode effectNode)
{
default(ArgumentNullException).ThrowIfNull(effectNode);
default(InvalidOperationException).ThrowIf(this.owner is null);
// Get the canvas image for the registered effect node (which has to exist at this point)
if (!this.owner.transformNodes.TryGetValue(effectNode, out ICanvasImage? canvasImage))
{
default(ArgumentException).Throw(nameof(effectNode), "The specified output node is not registered in the effect graph.");
}
// Store the new output node
this.owner.canvasImage = canvasImage;
}
}
/// <summary>
/// A marker interface for an effect node that was registered from an <see cref="EffectGraph"/> value.
/// </summary>
/// <remarks>
/// <para>
/// This interface allows using <see cref="EffectGraph.GetNode"/> and <see cref="EffectGraph.SetOutputNode"/> in more scenarios,
/// including where the concrete type of the image being used (eg. to set the output node) is not known (or needed) by the caller.
/// </para>
/// <para>
/// This interface only implemented by <see cref="EffectNode{T}"/> and it's not meant to be implemented by external types.
/// </para>
/// </remarks>
protected interface IEffectNode
{
}
/// <summary>
/// A marker interface for a generic effect node that was registered from an <see cref="EffectGraph"/> value.
/// </summary>
/// <typeparam name="T">The covariant type of <see cref="ICanvasImage"/> associated with the current effect node.</typeparam>
/// <remarks>
/// <para>
/// This interface allows using <see cref="EffectGraph.GetNode"/> and <see cref="EffectGraph.SetOutputNode"/> in more scenarios,
/// including with ternary expressions returning multiple concrete <see cref="EffectNode{T}"/> instances with a common image type.
/// </para>
/// <para>
/// This interface only implemented by <see cref="EffectNode{T}"/> and it's not meant to be implemented by external types.
/// </para>
/// </remarks>
protected interface IEffectNode<out T> : IEffectNode
where T : ICanvasImage
{
}
/// <summary>
/// A marker type for an effect node that can be registered and retrieved from an <see cref="EffectGraph"/> value.
/// </summary>
/// <typeparam name="T">The type of <see cref="ICanvasImage"/> associated with the current effect node.</typeparam>
protected sealed class EffectNode<T> : IEffectNode<T>
where T : class, ICanvasImage
{
}
}
+41 -6
ファイルの表示
@@ -69,20 +69,55 @@ unsafe partial class CanvasEffect
[MemberNotNull(nameof(canvasImage))]
private ICanvasImage GetCanvasImage()
{
lock (this.lockObject)
lock (this.transformNodes)
{
default(ObjectDisposedException).ThrowIf(this.isDisposed, this);
this.canvasImage ??= BuildEffectGraph();
if (this.isInvalidated)
// Build the effect graph (the output node might not have been set yet)
if (this.invalidationType == InvalidationType.Creation)
{
ConfigureEffectGraph();
DisposeEffectGraph();
BuildEffectGraph(new EffectGraph(this));
this.isInvalidated = false;
// We successfully got past the effect graph creation, so update the current
// invalidation state. This ensures that even if the configuration failed, the
// next time the effect is drawn again the graph won't be created again too.
this.invalidationType = InvalidationType.Update;
}
// Configure the effect graph, if the effect is invalidated
if (this.invalidationType == InvalidationType.Update)
{
ConfigureEffectGraph(new EffectGraph(this));
// The effect graph is now ready to go: no further work will be done before drawing
// unless it is explicitly invalidated again, using either creation or update mode.
this.invalidationType = default;
}
// At this point, there must be an output canvas image being set.
// If not, it means a derived type has forgot to set an output node.
default(InvalidOperationException).ThrowIf(this.canvasImage is null, "No output node is set in the effect graph.");
return this.canvasImage;
}
}
/// <summary>
/// Disposes and clears the current effect graph, if any.
/// </summary>
private void DisposeEffectGraph()
{
// Dispose all registered canvas images
foreach (ICanvasImage canvasImage in this.transformNodes.Values)
{
canvasImage.Dispose();
}
// Also clear the current effect graph. Note that the canvas image used as output
// node for the effect graph does not need to be explicitly disposed here, as that
// object is guaranteed to have been part of the dictionary of transform nodes.
this.transformNodes.Clear();
this.canvasImage = null;
}
}
+41 -44
ファイルの表示
@@ -16,9 +16,12 @@ namespace ComputeSharp.D2D1.WinUI;
public abstract partial class CanvasEffect : ICanvasImage, ICanvasImageInterop.Interface
{
/// <summary>
/// Lock object used to synchronize calls to <see cref="ICanvasImageInterop"/> APIs.
/// The mapping of registered transform nodes for the current effect graph.
/// </summary>
private readonly object lockObject = new();
/// <remarks>
/// When not empty (ie. when an effect graph has been built), this will always also include <see cref="canvasImage"/>.
/// </remarks>
private readonly Dictionary<object, ICanvasImage> transformNodes = new();
/// <summary>
/// The current cached result for <see cref="GetCanvasImage"/>, if available.
@@ -26,13 +29,9 @@ public abstract partial class CanvasEffect : ICanvasImage, ICanvasImageInterop.I
private ICanvasImage? canvasImage;
/// <summary>
/// Indicates whether the current state has been invalidated (requiring <see cref="ConfigureEffectGraph"/> to be called).
/// Indicates the current invalidation state for the effect graph (which controls the logic in <see cref="GetCanvasImage"/>).
/// </summary>
/// <remarks>
/// This is initially <see langword="true"/> so that <see cref="ConfigureEffectGraph"/> will always be called when
/// first creating the image, even if the effect has not bee invalidated. This ensures default parameters are set.
/// </remarks>
private bool isInvalidated = true;
private InvalidationType invalidationType = InvalidationType.Creation;
/// <summary>
/// Indicates whether the effect is disposed.
@@ -40,10 +39,10 @@ public abstract partial class CanvasEffect : ICanvasImage, ICanvasImageInterop.I
private bool isDisposed;
/// <summary>
/// Builds the effect graph for the current <see cref="CanvasEffect"/> instance, and returns an <see cref="ICanvasImage"/> object
/// representing the output node of the graph. This image will then be passed to Win2D to perform the actual drawing, when needed.
/// Builds the effect graph for the current <see cref="CanvasEffect"/> instance, and configures all effect nodes, as well as the output
/// node for the graph. That <see cref="ICanvasImage"/> instance will then be passed to Win2D to perform the actual drawing, when needed.
/// </summary>
/// <returns>The resulting <see cref="ICanvasImage"/> object representing the output node of the effect graph.</returns>
/// <param name="effectGraph">The input <see cref="EffectGraph"/> value to use to build the effect graph.</param>
/// <remarks>
/// <para>
/// This method is called once before the current effect is drawn, and the resulting image is automatically cached and reused.
@@ -74,29 +73,33 @@ public abstract partial class CanvasEffect : ICanvasImage, ICanvasImageInterop.I
/// <list type="bullet">
/// <item>Create an instance of all necessary nodes in the effect graph.</item>
/// <item>Connect the effect nodes as needed to build the connected graph.</item>
/// <item>Save all effects that can be configured as instance fields in the effect type.</item>
/// <item>Return the <see cref="ICanvasImage"/> instance for the output node of the graph.</item>
/// <item>Register all effects as effect nodes in the graph, including the output node.</item>
/// </list>
/// </para>
/// <para>
/// This method should never be called directly. It is automatically invoked when an <see cref="ICanvasImage"/> is needed.
/// For convenience, it is recommended to store all necessary <see cref="EffectNode{T}"/> objects in <see langword="static"/>
/// <see langword="readonly"/> fields, so they can easily be accessed from <see cref="BuildEffectGraph"/> and <see cref="ConfigureEffectGraph"/>.
/// </para>
/// <para>
/// This method should never be called directly. It is automatically invoked when an effect graph is needed.
/// </para>
/// </remarks>
protected abstract ICanvasImage BuildEffectGraph();
protected abstract void BuildEffectGraph(EffectGraph effectGraph);
/// <summary>
/// Configures the current effect graph whenever it is invalidated.
/// </summary>
/// <param name="effectGraph">The input <see cref="EffectGraph"/> value to use to configure the effect graph.</param>
/// <remarks>
/// <para>
/// This method is guaranteed to be called after <see cref="BuildEffectGraph"/> has been invoked already. As such, any instance
/// fields that are set by <see cref="BuildEffectGraph"/> can be assumed to never be <see langword="null"/> when this method runs.
/// </para>
/// <para>
/// This method should never be called directly. It is used internally to configure the current <see cref="ICanvasImage"/> instance.
/// This method should never be called directly. It is used internally to configure the current effect graph.
/// </para>
/// </remarks>
protected abstract void ConfigureEffectGraph();
protected abstract void ConfigureEffectGraph(EffectGraph effectGraph);
/// <summary>
/// Invalidates the last returned result from <see cref="GetCanvasImage"/>.
@@ -116,20 +119,15 @@ public abstract partial class CanvasEffect : ICanvasImage, ICanvasImageInterop.I
/// </remarks>
protected void InvalidateEffectGraph(InvalidationType invalidationType = InvalidationType.Update)
{
lock (this.lockObject)
lock (this.transformNodes)
{
// If the effect graph should be created again, dispose the image and throw it away
if (invalidationType == InvalidationType.Creation)
{
this.canvasImage?.Dispose();
this.canvasImage = null;
}
// For both invalidation types, always mark the internal state as not being valid anymore.
// The next time the image is requested, the effect graph will be configured if needed.
// This matches the default value for the field (which is needed for the first realization).
this.isInvalidated = true;
// 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);
}
}
@@ -191,10 +189,9 @@ public abstract partial class CanvasEffect : ICanvasImage, ICanvasImageInterop.I
// 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.lockObject)
lock (this.transformNodes)
{
this.canvasImage?.Dispose();
this.canvasImage = null;
DisposeEffectGraph();
}
}
@@ -212,17 +209,8 @@ public abstract partial class CanvasEffect : ICanvasImage, ICanvasImageInterop.I
/// <summary>
/// Indicates the invalidation type to request when invoking <see cref="InvalidateEffectGraph"/> and related methods.
/// </summary>
protected enum InvalidationType
protected enum InvalidationType : byte
{
/// <summary>
/// Fully invalidates the effect graph, causing it to be created again the next time it is needed.
/// </summary>
/// <remarks>
/// This will cause the last returned <see cref="ICanvasImage"/> instance to be disposed and discarded,
/// and <see cref="BuildEffectGraph"/> to be called again the next time the effect is used for drawing.
/// </remarks>
Creation,
/// <summary>
/// Invalidates the state of the effect graph, causing it to be configured again the next time it is used.
/// </summary>
@@ -236,6 +224,15 @@ public abstract partial class CanvasEffect : ICanvasImage, ICanvasImageInterop.I
/// This is much less expensive than creating the effect graph again, and should be preferred if possible.
/// </para>
/// </remarks>
Update
Update,
/// <summary>
/// Fully invalidates the effect graph, causing it to be created again the next time it is needed.
/// </summary>
/// <remarks>
/// This will cause the last returned <see cref="ICanvasImage"/> instance to be disposed and discarded,
/// and <see cref="BuildEffectGraph"/> to be called again the next time the effect is used for drawing.
/// </remarks>
Creation
}
}
+1
ファイルの表示
@@ -26,6 +26,7 @@
<Compile Include="$(MSBuildThisFileDirectory)Buffers\GraphicsEffectSourceBuffer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Buffers\ResourceTextureManagerBuffer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Buffers\SourceReference.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CanvasEffect.EffectGraph.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CanvasEffect.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CanvasEffect.Interop.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Collections\FixedCountList{T}.cs" />
@@ -92,7 +92,7 @@ partial class PixelShaderEffect<T>
internal static ImmutableArray<int> Indices { get; } = GetIndices();
/// <summary>
/// The owning <see cref="PixelShaderEffect{T}"/> instance.
/// Gets the owning <see cref="PixelShaderEffect{T}"/> instance.
/// </summary>
internal PixelShaderEffect<T> Owner { get; }
+1 -1
ファイルの表示
@@ -78,7 +78,7 @@ partial class PixelShaderEffect<T>
}
/// <summary>
/// The owning <see cref="PixelShaderEffect{T}"/> instance.
/// Gets the owning <see cref="PixelShaderEffect{T}"/> instance.
/// </summary>
internal PixelShaderEffect<T> Owner { get; }
+593 -7
ファイルの表示
@@ -1,10 +1,22 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Numerics;
using System.Threading.Tasks;
using ComputeSharp.D2D1.UI.Tests.Helpers;
#if WINDOWS_UWP
using ComputeSharp.D2D1.Uwp;
#else
using ComputeSharp.D2D1.WinUI;
#endif
using ComputeSharp.SwapChain.Shaders.D2D1;
using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.Effects;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TerraFX.Interop.Windows;
using Windows.Foundation;
using Windows.Storage;
using Windows.UI;
#nullable enable
@@ -15,7 +27,7 @@ namespace ComputeSharp.D2D1.UI.Tests;
public partial class CanvasEffectTests
{
[TestMethod]
public unsafe void CanvasEffect_IsRealizedAndInvalidatedCorrectly()
public void CanvasEffect_IsRealizedAndInvalidatedCorrectly()
{
EffectWithNoInputs effect = new();
@@ -63,9 +75,315 @@ public partial class CanvasEffectTests
}
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void CanvasEffect_EffectSettingNotRegisteredOutputNode()
{
EffectSettingNotRegisteredOutputNode effect = new();
try
{
using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f);
using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession();
drawingSession.DrawImage(effect);
}
catch
{
Assert.IsTrue(effect.WasConfigureEffectGraphCalled);
throw;
}
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void CanvasEffect_EffectNotRegisteringAnOutputNode()
{
EffectNotRegisteringAnOutputNode effect = new();
try
{
using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f);
using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession();
drawingSession.DrawImage(effect);
}
catch
{
Assert.IsTrue(effect.WasConfigureEffectGraphCalled);
throw;
}
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void CanvasEffect_EffectRegisteringNodesMultipleTimes1()
{
EffectRegisteringNodesMultipleTimes1 effect = new();
using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f);
using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession();
drawingSession.DrawImage(effect);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void CanvasEffect_EffectRegisteringNodesMultipleTimes2()
{
EffectRegisteringNodesMultipleTimes2 effect = new();
using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f);
using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession();
drawingSession.DrawImage(effect);
}
[TestMethod]
public void CanvasEffect_EffectRegisteringNullObjects()
{
EffectRegisteringNullObjects effect = new();
using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f);
using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession();
drawingSession.DrawImage(effect);
}
[TestMethod]
public void CanvasEffect_EffectConfiguringGraphIncorrectly()
{
EffectConfiguringGraphIncorrectly effect = new();
using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f);
using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession();
drawingSession.DrawImage(effect);
}
[TestMethod]
public void CanvasEffect_EffectOnlyUsingAnonymousNodes()
{
EffectOnlyUsingAnonymousNodes effect = new();
using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f);
using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession();
drawingSession.DrawImage(effect);
}
[TestMethod]
public void CanvasEffect_EffectUsingEffectGraphInInvalidState()
{
EffectUsingEffectGraphInInvalidState effect = new();
using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f);
using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession();
drawingSession.DrawImage(effect);
}
[TestMethod]
public async Task CanvasEffect_PixelShaderSwitchEffect()
{
PixelShaderSwitchEffect effect = new();
async Task TestAsync(string shaderName)
{
Color[] pixelColors;
using CanvasDevice canvasDevice = new();
// Same logic as in the shader tests
using (CanvasRenderTarget renderTarget = new(canvasDevice, 1280, 720, 96.0f))
{
using (CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession())
{
drawingSession.DrawImage(effect);
}
pixelColors = renderTarget.GetPixelColors();
}
StorageFile imageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appx:///Assets/Shaders/{shaderName}.png"));
using Stream stream = await imageFile.OpenStreamForReadAsync();
using CanvasBitmap expected = await CanvasBitmap.LoadAsync(canvasDevice, stream.AsRandomAccessStream());
using CanvasBitmap actual = CanvasBitmap.CreateFromColors(canvasDevice, pixelColors, 1280, 720);
TolerantImageComparer.AssertEqual(expected, actual, threshold: 0.00001f);
}
// Every time the effect is re-drawn, a different shader is set as the output node
await TestAsync(nameof(HelloWorld));
await TestAsync(nameof(ColorfulInfinity));
await TestAsync(nameof(FractalTiling));
await TestAsync(nameof(Octagrams));
await TestAsync(nameof(ProteanClouds));
}
[TestMethod]
public void CanvasEffect_EffectTestingDisposal()
{
EffectTestingDisposal effect = new();
using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f);
using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession();
// Force creating the graph (the drawing fails because the effects are dummies)
try
{
drawingSession.DrawImage(effect);
}
catch (Exception e) when (e.HResult == E.E_FAIL)
{
}
Assert.AreEqual(1, effect.Effects1.Count);
Assert.AreEqual(1, effect.Effects2.Count);
Assert.AreEqual(1, effect.Effects3.Count);
Assert.AreEqual(0, effect.Effects1[0].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects2[0].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects3[0].NumberOfDisposeCalls);
effect.InvalidateCreation();
// Effects aren't disposed yet until we redraw
Assert.AreEqual(1, effect.Effects1.Count);
Assert.AreEqual(1, effect.Effects2.Count);
Assert.AreEqual(1, effect.Effects3.Count);
Assert.AreEqual(0, effect.Effects1[0].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects2[0].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects3[0].NumberOfDisposeCalls);
// Redraw, which builds a new effect graph and disposes the old one
try
{
drawingSession.DrawImage(effect);
}
catch (Exception e) when (e.HResult == E.E_FAIL)
{
}
Assert.AreEqual(2, effect.Effects1.Count);
Assert.AreEqual(2, effect.Effects2.Count);
Assert.AreEqual(2, effect.Effects3.Count);
Assert.AreEqual(1, effect.Effects1[0].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects2[0].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects3[0].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects1[1].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects2[1].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects3[1].NumberOfDisposeCalls);
// Redrawing now doesn't change anything
try
{
drawingSession.DrawImage(effect);
}
catch (Exception e) when (e.HResult == E.E_FAIL)
{
}
Assert.AreEqual(2, effect.Effects1.Count);
Assert.AreEqual(2, effect.Effects2.Count);
Assert.AreEqual(2, effect.Effects3.Count);
Assert.AreEqual(1, effect.Effects1[0].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects2[0].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects3[0].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects1[1].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects2[1].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects3[1].NumberOfDisposeCalls);
effect.InvalidateUpdate();
// Invalidating with update mode also doesn't do anything here
Assert.AreEqual(2, effect.Effects1.Count);
Assert.AreEqual(2, effect.Effects2.Count);
Assert.AreEqual(2, effect.Effects3.Count);
Assert.AreEqual(1, effect.Effects1[0].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects2[0].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects3[0].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects1[1].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects2[1].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects3[1].NumberOfDisposeCalls);
// Redraw, and also verify the disposal state wasn't changed
try
{
drawingSession.DrawImage(effect);
}
catch (Exception e) when (e.HResult == E.E_FAIL)
{
}
Assert.AreEqual(2, effect.Effects1.Count);
Assert.AreEqual(2, effect.Effects2.Count);
Assert.AreEqual(2, effect.Effects3.Count);
Assert.AreEqual(1, effect.Effects1[0].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects2[0].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects3[0].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects1[1].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects2[1].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects3[1].NumberOfDisposeCalls);
// Verify that invalidating with update after creation is ignored
effect.InvalidateCreation();
effect.InvalidateUpdate();
Assert.AreEqual(2, effect.Effects1.Count);
Assert.AreEqual(2, effect.Effects2.Count);
Assert.AreEqual(2, effect.Effects3.Count);
Assert.AreEqual(1, effect.Effects1[0].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects2[0].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects3[0].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects1[1].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects2[1].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects3[1].NumberOfDisposeCalls);
// Redraw, disposing the old graph once again
try
{
drawingSession.DrawImage(effect);
}
catch (Exception e) when (e.HResult == E.E_FAIL)
{
}
Assert.AreEqual(3, effect.Effects1.Count);
Assert.AreEqual(3, effect.Effects2.Count);
Assert.AreEqual(3, effect.Effects3.Count);
Assert.AreEqual(1, effect.Effects1[0].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects2[0].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects3[0].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects1[1].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects2[1].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects3[1].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects1[2].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects2[2].NumberOfDisposeCalls);
Assert.AreEqual(0, effect.Effects3[2].NumberOfDisposeCalls);
// Finally dispose the effect
effect.Dispose();
Assert.AreEqual(3, effect.Effects1.Count);
Assert.AreEqual(3, effect.Effects2.Count);
Assert.AreEqual(3, effect.Effects3.Count);
Assert.AreEqual(1, effect.Effects1[0].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects2[0].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects3[0].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects1[1].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects2[1].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects3[1].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects1[2].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects2[2].NumberOfDisposeCalls);
Assert.AreEqual(1, effect.Effects3[2].NumberOfDisposeCalls);
}
private sealed class EffectWithNoInputs : CanvasEffect
{
private PixelShaderEffect<ShaderWithNoInputs>? effect;
private static readonly EffectNode<PixelShaderEffect<ShaderWithNoInputs>> Effect = new();
private int value;
@@ -87,18 +405,21 @@ public partial class CanvasEffectTests
public int NumberOfDisposeCalls { get; private set; }
protected override ICanvasImage BuildEffectGraph()
protected override void BuildEffectGraph(EffectGraph effectGraph)
{
NumberOfBuildEffectGraphCalls++;
return this.effect = new PixelShaderEffect<ShaderWithNoInputs>();
effectGraph.RegisterOutputNode(Effect, new PixelShaderEffect<ShaderWithNoInputs>());
}
protected override void ConfigureEffectGraph()
protected override void ConfigureEffectGraph(EffectGraph effectGraph)
{
NumberOfConfigureEffectGraphCalls++;
this.effect!.ConstantBuffer = new ShaderWithNoInputs(this.value);
effectGraph.GetNode(Effect).ConstantBuffer = new ShaderWithNoInputs(this.value);
// Also test the non-generic overload
Assert.IsTrue(effectGraph.GetNode((IEffectNode)Effect) is PixelShaderEffect<ShaderWithNoInputs>);
}
protected override void Dispose(bool disposing)
@@ -106,8 +427,273 @@ public partial class CanvasEffectTests
NumberOfDisposeCalls++;
base.Dispose(disposing);
}
}
this.effect?.Dispose();
private sealed class EffectSettingNotRegisteredOutputNode : CanvasEffect
{
public bool WasConfigureEffectGraphCalled { get; private set; }
protected override void BuildEffectGraph(EffectGraph effectGraph)
{
effectGraph.RegisterOutputNode(new EffectNode<ColorSourceEffect>(), new ColorSourceEffect());
effectGraph.RegisterOutputNode(new EffectNode<ColorSourceEffect>(), new ColorSourceEffect());
}
protected override void ConfigureEffectGraph(EffectGraph effectGraph)
{
WasConfigureEffectGraphCalled = true;
effectGraph.SetOutputNode(new EffectNode<ColorSourceEffect>());
}
}
private sealed class EffectNotRegisteringAnOutputNode : CanvasEffect
{
public bool WasConfigureEffectGraphCalled { get; private set; }
protected override void BuildEffectGraph(EffectGraph effectGraph)
{
effectGraph.RegisterNode(new ColorSourceEffect());
effectGraph.RegisterNode(new EffectNode<ColorSourceEffect>(), new ColorSourceEffect());
effectGraph.RegisterNode(new EffectNode<ColorSourceEffect>(), new ColorSourceEffect());
}
protected override void ConfigureEffectGraph(EffectGraph effectGraph)
{
WasConfigureEffectGraphCalled = true;
}
}
private sealed class EffectRegisteringNodesMultipleTimes1 : CanvasEffect
{
protected override void BuildEffectGraph(EffectGraph effectGraph)
{
EffectNode<ColorSourceEffect> node = new();
effectGraph.RegisterNode(node, new ColorSourceEffect());
effectGraph.RegisterOutputNode(node, new ColorSourceEffect());
}
protected override void ConfigureEffectGraph(EffectGraph effectGraph)
{
Assert.Fail();
}
}
private sealed class EffectRegisteringNodesMultipleTimes2 : CanvasEffect
{
protected override void BuildEffectGraph(EffectGraph effectGraph)
{
EffectNode<ColorSourceEffect> node = new();
effectGraph.RegisterNode(node, new ColorSourceEffect());
effectGraph.RegisterNode(node, new ColorSourceEffect());
effectGraph.RegisterOutputNode(new EffectNode<ColorSourceEffect>(), new ColorSourceEffect());
}
protected override void ConfigureEffectGraph(EffectGraph effectGraph)
{
Assert.Fail();
}
}
private sealed class EffectRegisteringNullObjects : CanvasEffect
{
protected override unsafe void BuildEffectGraph(EffectGraph effectGraph)
{
// Verify that if the effect graph is invalid, arguments are validated first
_ = Assert.ThrowsException<ArgumentNullException>(() => default(EffectGraph).RegisterNode(null!));
_ = Assert.ThrowsException<ArgumentNullException>(() => default(EffectGraph).RegisterNode(null!, new ColorSourceEffect()));
_ = Assert.ThrowsException<ArgumentNullException>(() => default(EffectGraph).RegisterNode(new EffectNode<ColorSourceEffect>(), null!));
_ = Assert.ThrowsException<ArgumentNullException>(() => default(EffectGraph).RegisterNode(null!, (ColorSourceEffect?)null!));
_ = Assert.ThrowsException<ArgumentNullException>(() => default(EffectGraph).RegisterOutputNode(null!));
_ = Assert.ThrowsException<ArgumentNullException>(() => default(EffectGraph).RegisterOutputNode(null!, new ColorSourceEffect()));
_ = Assert.ThrowsException<ArgumentNullException>(() => default(EffectGraph).RegisterOutputNode(new EffectNode<ColorSourceEffect>(), null!));
_ = Assert.ThrowsException<ArgumentNullException>(() => default(EffectGraph).RegisterOutputNode(null!, (ColorSourceEffect)null!));
void* ptr = &effectGraph;
_ = Assert.ThrowsException<ArgumentNullException>(() => (*(EffectGraph*)ptr).RegisterNode(null!));
_ = Assert.ThrowsException<ArgumentNullException>(() => (*(EffectGraph*)ptr).RegisterNode(null!, new ColorSourceEffect()));
_ = Assert.ThrowsException<ArgumentNullException>(() => (*(EffectGraph*)ptr).RegisterNode(new EffectNode<ColorSourceEffect>(), null!));
_ = Assert.ThrowsException<ArgumentNullException>(() => (*(EffectGraph*)ptr).RegisterNode(null!, (ColorSourceEffect?)null!));
_ = Assert.ThrowsException<ArgumentNullException>(() => (*(EffectGraph*)ptr).RegisterOutputNode(null!));
_ = Assert.ThrowsException<ArgumentNullException>(() => (*(EffectGraph*)ptr).RegisterOutputNode(null!, new ColorSourceEffect()));
_ = Assert.ThrowsException<ArgumentNullException>(() => (*(EffectGraph*)ptr).RegisterOutputNode(new EffectNode<ColorSourceEffect>(), null!));
_ = Assert.ThrowsException<ArgumentNullException>(() => (*(EffectGraph*)ptr).RegisterOutputNode(null!, (ColorSourceEffect)null!));
effectGraph.RegisterOutputNode(new EffectNode<ColorSourceEffect>(), new ColorSourceEffect());
}
protected override void ConfigureEffectGraph(EffectGraph effectGraph)
{
}
}
private sealed class EffectConfiguringGraphIncorrectly : CanvasEffect
{
private static readonly EffectNode<ColorSourceEffect> EffectNode1 = new();
private static readonly EffectNode<ColorSourceEffect> EffectNode2 = new();
private static readonly EffectNode<ColorSourceEffect> EffectNode3 = new();
#pragma warning disable CA2213
private readonly ColorSourceEffect effect1 = new();
private readonly ColorSourceEffect effect2 = new();
private readonly ColorSourceEffect effect3 = new();
#pragma warning restore CA2213
protected override void BuildEffectGraph(EffectGraph effectGraph)
{
effectGraph.RegisterNode(EffectNode1, this.effect1);
effectGraph.RegisterNode(EffectNode2, this.effect2);
effectGraph.RegisterOutputNode(EffectNode3, this.effect3);
}
protected override unsafe void ConfigureEffectGraph(EffectGraph effectGraph)
{
void* ptr = &effectGraph;
_ = Assert.ThrowsException<ArgumentNullException>(() => (*(EffectGraph*)ptr).GetNode((EffectNode<ColorSourceEffect>)null!));
_ = Assert.ThrowsException<ArgumentException>(() => (*(EffectGraph*)ptr).GetNode(new EffectNode<ColorSourceEffect>()));
_ = Assert.ThrowsException<InvalidOperationException>(() => (*(EffectGraph*)ptr).RegisterNode(new EffectNode<ColorSourceEffect>(), new ColorSourceEffect()));
_ = Assert.ThrowsException<InvalidOperationException>(() => (*(EffectGraph*)ptr).RegisterOutputNode(new EffectNode<ColorSourceEffect>(), new ColorSourceEffect()));
Assert.AreSame(effectGraph.GetNode(EffectNode1), this.effect1);
Assert.AreSame(effectGraph.GetNode(EffectNode2), this.effect2);
Assert.AreSame(effectGraph.GetNode(EffectNode3), this.effect3);
}
}
private sealed class EffectOnlyUsingAnonymousNodes : CanvasEffect
{
protected override void BuildEffectGraph(EffectGraph effectGraph)
{
effectGraph.RegisterNode(new ColorSourceEffect());
effectGraph.RegisterNode(new ColorSourceEffect());
effectGraph.RegisterOutputNode(new ColorSourceEffect());
}
protected override void ConfigureEffectGraph(EffectGraph effectGraph)
{
}
}
private sealed class EffectUsingEffectGraphInInvalidState : CanvasEffect
{
protected override void BuildEffectGraph(EffectGraph effectGraph)
{
_ = Assert.ThrowsException<InvalidOperationException>(() => default(EffectGraph).RegisterNode(new ColorSourceEffect()));
_ = Assert.ThrowsException<InvalidOperationException>(() => default(EffectGraph).RegisterNode(new EffectNode<ColorSourceEffect>(), new ColorSourceEffect()));
_ = Assert.ThrowsException<InvalidOperationException>(() => default(EffectGraph).RegisterOutputNode(new ColorSourceEffect()));
_ = Assert.ThrowsException<InvalidOperationException>(() => default(EffectGraph).RegisterOutputNode(new EffectNode<ColorSourceEffect>(), new ColorSourceEffect()));
effectGraph.RegisterOutputNode(new EffectNode<ColorSourceEffect>(), new ColorSourceEffect());
}
protected override void ConfigureEffectGraph(EffectGraph effectGraph)
{
_ = Assert.ThrowsException<InvalidOperationException>(() => default(EffectGraph).GetNode(new EffectNode<ColorSourceEffect>()));
}
}
private sealed class PixelShaderSwitchEffect : CanvasEffect
{
private static readonly EffectNode<PixelShaderEffect<HelloWorld>> HelloWorldNode = new();
private static readonly EffectNode<PixelShaderEffect<ColorfulInfinity>> ColorfulInfinityNode = new();
private static readonly EffectNode<PixelShaderEffect<FractalTiling>> FractalTilingNode = new();
private static readonly EffectNode<PixelShaderEffect<Octagrams>> OctagramsNode = new();
private static readonly EffectNode<PixelShaderEffect<ProteanClouds>> ProteanCloudsNode = new();
private int step;
protected override void BuildEffectGraph(EffectGraph effectGraph)
{
effectGraph.RegisterNode(HelloWorldNode, new PixelShaderEffect<HelloWorld> { ConstantBuffer = new HelloWorld(0, new int2(1280, 720)) });
effectGraph.RegisterNode(ColorfulInfinityNode, new PixelShaderEffect<ColorfulInfinity> { ConstantBuffer = new ColorfulInfinity(0, new int2(1280, 720)) });
effectGraph.RegisterNode(FractalTilingNode, new PixelShaderEffect<FractalTiling> { ConstantBuffer = new FractalTiling(0, new int2(1280, 720)) });
effectGraph.RegisterNode(OctagramsNode, new PixelShaderEffect<Octagrams> { ConstantBuffer = new Octagrams(0, new int2(1280, 720)) });
effectGraph.RegisterNode(ProteanCloudsNode, new PixelShaderEffect<ProteanClouds> { ConstantBuffer = new ProteanClouds(0, new int2(1280, 720)) });
effectGraph.SetOutputNode(HelloWorldNode);
}
protected override void ConfigureEffectGraph(EffectGraph effectGraph)
{
switch (this.step++)
{
case 0: break;
case 1:
effectGraph.SetOutputNode(ColorfulInfinityNode);
break;
case 2:
effectGraph.SetOutputNode(FractalTilingNode);
break;
case 3 or 4:
// Test the overload which is non-generic, allowing ternary expressions too
effectGraph.SetOutputNode(this.step == 4 ? OctagramsNode : ProteanCloudsNode);
break;
default:
Assert.Fail();
break;
}
}
}
private sealed class EffectTestingDisposal : CanvasEffect
{
private static readonly EffectNode<DummyCanvasImageTrackingDisposal> EffectNode1 = new();
private static readonly EffectNode<DummyCanvasImageTrackingDisposal> EffectNode2 = new();
private static readonly EffectNode<DummyCanvasImageTrackingDisposal> EffectNode3 = new();
public readonly List<DummyCanvasImageTrackingDisposal> Effects1 = new();
public readonly List<DummyCanvasImageTrackingDisposal> Effects2 = new();
public readonly List<DummyCanvasImageTrackingDisposal> Effects3 = new();
public void InvalidateCreation()
{
InvalidateEffectGraph(InvalidationType.Creation);
}
public void InvalidateUpdate()
{
InvalidateEffectGraph(InvalidationType.Update);
}
protected override void BuildEffectGraph(EffectGraph effectGraph)
{
this.Effects1.Add(new DummyCanvasImageTrackingDisposal());
this.Effects2.Add(new DummyCanvasImageTrackingDisposal());
this.Effects3.Add(new DummyCanvasImageTrackingDisposal());
effectGraph.RegisterNode(EffectNode1, this.Effects1[^1]);
effectGraph.RegisterNode(EffectNode2, this.Effects2[^1]);
effectGraph.RegisterOutputNode(EffectNode3, this.Effects3[^1]);
}
protected override void ConfigureEffectGraph(EffectGraph effectGraph)
{
}
}
private sealed class DummyCanvasImageTrackingDisposal : ICanvasImage
{
public int NumberOfDisposeCalls { get; private set; }
public Rect GetBounds(ICanvasResourceCreator resourceCreator)
{
Assert.Fail();
return default;
}
public Rect GetBounds(ICanvasResourceCreator resourceCreator, Matrix3x2 transform)
{
Assert.Fail();
return default;
}
public void Dispose()
{
NumberOfDisposeCalls++;
}
}
+5 -12
ファイルの表示
@@ -120,7 +120,7 @@ public class ShadersTests
private sealed class TestCanvasEffect<T> : CanvasEffect
where T : unmanaged, ID2D1PixelShader
{
private PixelShaderEffect<T>? effect;
private static readonly EffectNode<PixelShaderEffect<T>> Effect = new();
private T constantBuffer;
@@ -130,21 +130,14 @@ public class ShadersTests
set => SetAndInvalidateEffectGraph(ref this.constantBuffer, value);
}
protected override ICanvasImage BuildEffectGraph()
protected override void BuildEffectGraph(EffectGraph effectGraph)
{
return this.effect = new PixelShaderEffect<T>();
effectGraph.RegisterOutputNode(Effect, new PixelShaderEffect<T>());
}
protected override void ConfigureEffectGraph()
protected override void ConfigureEffectGraph(EffectGraph effectGraph)
{
this.effect!.ConstantBuffer = this.constantBuffer;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
this.effect?.Dispose();
effectGraph.GetNode(Effect).ConstantBuffer = this.constantBuffer;
}
}