// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
using System;
using System.Buffers;
using SixLabors.ImageSharp.Advanced;
using SixLabors.ImageSharp.Memory;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.Memory;
namespace SixLabors.ImageSharp.Processing
{
///
/// primitive that converts a point in to a color for discovering the fill color based on an implementation
///
/// The pixel format.
///
public abstract class BrushApplicator : IDisposable // disposable will be required if/when there is an ImageBrush
where TPixel : struct, IPixel
{
///
/// Initializes a new instance of the class.
///
/// The target.
/// The options.
internal BrushApplicator(ImageFrame target, GraphicsOptions options)
{
this.Target = target;
this.Options = options;
this.Blender = PixelOperations.Instance.GetPixelBlender(options);
}
///
/// Gets the blender
///
internal PixelBlender Blender { get; }
///
/// Gets the destination
///
protected ImageFrame Target { get; }
///
/// Gets the blend percentage
///
protected GraphicsOptions Options { get; private set; }
///
/// Gets the color for a single pixel.
///
/// The x coordinate.
/// The y coordinate.
/// The a that should be applied to the pixel.
internal abstract TPixel this[int x, int y] { get; }
///
public abstract void Dispose();
///
/// Applies the opacity weighting for each pixel in a scanline to the target based on the pattern contained in the brush.
///
/// The a collection of opacity values between 0 and 1 to be merged with the brushed color value before being applied to the target.
/// The x position in the target pixel space that the start of the scanline data corresponds to.
/// The y position in the target pixel space that whole scanline corresponds to.
/// scanlineBuffer will be > scanlineWidth but provide and offset in case we want to share a larger buffer across runs.
internal virtual void Apply(Span scanline, int x, int y)
{
MemoryAllocator memoryAllocator = this.Target.MemoryAllocator;
using (IMemoryOwner amountBuffer = memoryAllocator.Allocate(scanline.Length))
using (IMemoryOwner overlay = memoryAllocator.Allocate(scanline.Length))
{
Span amountSpan = amountBuffer.GetSpan();
Span overlaySpan = overlay.GetSpan();
for (int i = 0; i < scanline.Length; i++)
{
if (this.Options.BlendPercentage < 1)
{
amountSpan[i] = scanline[i] * this.Options.BlendPercentage;
}
else
{
amountSpan[i] = scanline[i];
}
overlaySpan[i] = this[x + i, y];
}
Span destinationRow = this.Target.GetPixelRowSpan(y).Slice(x, scanline.Length);
this.Blender.Blend(memoryAllocator, destinationRow, destinationRow, overlaySpan, amountSpan);
}
}
}
}