「墨拡散」映像エフェクトプラグインファイルの追加

このコミットが含まれているのは:
routersys committed 2026-07-18 18:00:05 +09:00
1 親 b9a7867d7e
コミット c07b042e76
13ファイル変更
+2526

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

+86
ファイルの表示
@@ -0,0 +1,86 @@
using System.Runtime.InteropServices;
using Vortice;
using Vortice.Direct2D1;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Player.Video;
namespace InkDispersion;
internal sealed class InkDispersionCustomEffect(IGraphicsDevicesAndContext devices)
: D2D1CustomShaderEffectBase(Create<EffectImpl>(devices))
{
public float Amount { set => SetValue((int)EffectImpl.Properties.Amount, value); }
[CustomEffect(2)]
private sealed class EffectImpl : D2D1CustomShaderEffectImplBase<EffectImpl>
{
private ConstantBuffer _cb;
[CustomEffectProperty(PropertyType.Float, (int)Properties.Amount)]
public float Amount
{
get => _cb.Amount;
set
{
_cb.Amount = Math.Clamp(value, 0f, 1f);
UpdateConstants();
}
}
public EffectImpl() : base(ShaderResourceUri.Get("InkDispersion"))
{
}
protected override void UpdateConstants()
{
drawInformation?.SetPixelShaderConstantBuffer(_cb);
}
public override void MapInputRectsToOutputRect(
RawRect[] inputRects,
RawRect[] inputOpaqueSubRects,
out RawRect outputRect,
out RawRect outputOpaqueSubRect)
{
if (inputRects.Length == 0)
{
outputRect = default;
outputOpaqueSubRect = default;
return;
}
var union = inputRects[0];
for (var i = 1; i < inputRects.Length; i++)
{
var rect = inputRects[i];
union = new RawRect(
Math.Min(union.Left, rect.Left),
Math.Min(union.Top, rect.Top),
Math.Max(union.Right, rect.Right),
Math.Max(union.Bottom, rect.Bottom));
}
outputRect = union;
outputOpaqueSubRect = default;
}
public override void MapOutputRectToInputRects(RawRect outputRect, RawRect[] inputRects)
{
for (var i = 0; i < inputRects.Length; i++)
inputRects[i] = outputRect;
}
[StructLayout(LayoutKind.Sequential)]
private struct ConstantBuffer
{
public float Amount;
public float Pad0;
public float Pad1;
public float Pad2;
}
public enum Properties
{
Amount = 0,
}
}
}
+96
ファイルの表示
@@ -0,0 +1,96 @@
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Windows.Media;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Controls;
using YukkuriMovieMaker.Exo;
using YukkuriMovieMaker.Player.Video;
using YukkuriMovieMaker.Plugin.Effects;
namespace InkDispersion;
[VideoEffect(nameof(Texts.InkDispersion), [VideoEffectCategories.Decoration, VideoEffectCategories.Animation], [nameof(Texts.TagInk), nameof(Texts.TagBlot), nameof(Texts.TagJapanese)], IsAviUtlSupported = false, ResourceType = typeof(Texts))]
public sealed class InkDispersionEffect : VideoEffectBase
{
public override string Label => Texts.InkDispersion;
public InkDispersionEffect()
{
InkDispersionUpdateNotifier.EnsureCheckedOnce();
}
[Display(GroupName = nameof(Texts.BasicGroup), Name = nameof(Texts.Amount), Description = nameof(Texts.AmountDescription), Order = 0, ResourceType = typeof(Texts))]
[AnimationSlider("F1", "%", 0, 100)]
public Animation Amount { get; } = new Animation(100, 0, 100);
[Display(GroupName = nameof(Texts.BasicGroup), Name = nameof(Texts.Spread), Description = nameof(Texts.SpreadDescription), Order = 1, ResourceType = typeof(Texts))]
[AnimationSlider("F1", "%", 0, 100)]
public Animation Spread { get; } = new Animation(100, 0, 100);
[Display(GroupName = nameof(Texts.BasicGroup), Name = nameof(Texts.Quality), Description = nameof(Texts.QualityDescription), Order = 2, ResourceType = typeof(Texts))]
[EnumComboBox]
public InkDispersionQuality Quality { get => _quality; set => Set(ref _quality, value); }
private InkDispersionQuality _quality = InkDispersionQuality.High;
[Display(GroupName = nameof(Texts.FlowGroup), Name = nameof(Texts.Water), Description = nameof(Texts.WaterDescription), Order = 10, ResourceType = typeof(Texts))]
[AnimationSlider("F1", "%", 0, 100)]
public Animation Water { get; } = new Animation(60, 0, 100);
[Display(GroupName = nameof(Texts.FlowGroup), Name = nameof(Texts.Reach), Description = nameof(Texts.ReachDescription), Order = 11, ResourceType = typeof(Texts))]
[AnimationSlider("F1", "%", 5, 100)]
public Animation Reach { get; } = new Animation(25, 1, 400);
[Display(GroupName = nameof(Texts.FlowGroup), Name = nameof(Texts.Fiber), Description = nameof(Texts.FiberDescription), Order = 12, ResourceType = typeof(Texts))]
[AnimationSlider("F1", "%", 0, 100)]
public Animation Fiber { get; } = new Animation(50, 0, 100);
[Display(GroupName = nameof(Texts.FlowGroup), Name = nameof(Texts.Sizing), Description = nameof(Texts.SizingDescription), Order = 13, ResourceType = typeof(Texts))]
[AnimationSlider("F1", "%", 0, 100)]
public Animation Sizing { get; } = new Animation(30, 0, 100);
[Display(GroupName = nameof(Texts.FlowGroup), Name = nameof(Texts.Viscosity), Description = nameof(Texts.ViscosityDescription), Order = 14, ResourceType = typeof(Texts))]
[AnimationSlider("F1", "%", 0, 100)]
public Animation Viscosity { get; } = new Animation(30, 0, 100);
[Display(GroupName = nameof(Texts.FlowGroup), Name = nameof(Texts.Drying), Description = nameof(Texts.DryingDescription), Order = 15, ResourceType = typeof(Texts))]
[AnimationSlider("F1", "%", 0, 100)]
public Animation Drying { get; } = new Animation(40, 0, 100);
[Display(GroupName = nameof(Texts.FlowGroup), Name = nameof(Texts.Seed), Description = nameof(Texts.SeedDescription), Order = 16, ResourceType = typeof(Texts))]
[Range(0, int.MaxValue)]
[DefaultValue(0)]
[TextBoxSlider("F0", "", 0, 10000)]
public int Seed
{
get => _seed;
set => Set(ref _seed, Math.Max(value, 0));
}
private int _seed;
[Display(GroupName = nameof(Texts.AppearanceGroup), Name = nameof(Texts.Density), Description = nameof(Texts.DensityDescription), Order = 20, ResourceType = typeof(Texts))]
[AnimationSlider("F1", "%", 0, 100)]
public Animation Density { get; } = new Animation(80, 0, 100);
[Display(GroupName = nameof(Texts.AppearanceGroup), Name = nameof(Texts.Grain), Description = nameof(Texts.GrainDescription), Order = 21, ResourceType = typeof(Texts))]
[AnimationSlider("F1", "%", 0, 100)]
public Animation Grain { get; } = new Animation(40, 0, 100);
[Display(GroupName = nameof(Texts.AppearanceGroup), Name = nameof(Texts.InkColor), Description = nameof(Texts.InkColorDescription), Order = 22, ResourceType = typeof(Texts))]
[ColorPicker]
public Color InkColor
{
get => _inkColor;
set => Set(ref _inkColor, value);
}
private Color _inkColor = Color.FromArgb(255, 30, 26, 24);
private IAnimatable[]? _animatables;
public override IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
public override IVideoEffectProcessor CreateVideoEffect(IGraphicsDevicesAndContext devices)
=> new InkDispersionEffectProcessor(devices, this);
protected override IEnumerable<IAnimatable> GetAnimatables()
=> _animatables ??= [Amount, Spread, Water, Reach, Fiber, Sizing, Viscosity, Drying, Density, Grain];
}
+340
ファイルの表示
@@ -0,0 +1,340 @@
using System.Numerics;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Player.Video;
using YukkuriMovieMaker.Player.Video.Effects;
namespace InkDispersion;
internal sealed class InkDispersionEffectProcessor : VideoEffectProcessorBase
{
private readonly IGraphicsDevicesAndContext _devices;
private readonly InkDispersionEffect _item;
private InkDispersionGpuInterop? _interop;
private InkDispersionPipeline? _pipeline;
private InkDispersionCustomEffect? _effect;
private Crop? _outputCrop;
private ID2D1Image? _outputCropOutput;
private AffineTransform2D? _outputTransform;
private ID2D1Image? _outputTransformOutput;
private bool _isFirst = true;
private bool _hasOutput;
private bool _hasOutputOffset;
private bool _hasCropRect;
private bool _hasRenderState;
private Vector2 _outputOffset;
private Vector4 _cropRect;
private Parameters _parameters;
private RenderState _renderState;
public InkDispersionEffectProcessor(IGraphicsDevicesAndContext devices, InkDispersionEffect item)
: base(devices)
{
_devices = devices;
_item = item;
}
public override DrawDescription Update(EffectDescription effectDescription)
{
if (IsPassThroughEffect || _effect is null || _outputCrop is null || _outputTransform is null || _outputTransformOutput is null || _interop is null || _pipeline is null || input is null)
return effectDescription.DrawDescription;
var frame = effectDescription.ItemPosition.Frame;
var length = effectDescription.ItemDuration.Frame;
var fps = effectDescription.FPS;
var parameters = new Parameters(
(float)(_item.Amount.GetValue(frame, length, fps) / 100.0),
(float)(_item.Spread.GetValue(frame, length, fps) / 100.0),
_item.Quality,
(float)(_item.Water.GetValue(frame, length, fps) / 100.0),
(float)(_item.Reach.GetValue(frame, length, fps) / 100.0),
(float)(_item.Fiber.GetValue(frame, length, fps) / 100.0),
(float)(_item.Sizing.GetValue(frame, length, fps) / 100.0),
(float)(_item.Viscosity.GetValue(frame, length, fps) / 100.0),
(float)(_item.Drying.GetValue(frame, length, fps) / 100.0),
(float)(_item.Density.GetValue(frame, length, fps) / 100.0),
(float)(_item.Grain.GetValue(frame, length, fps) / 100.0),
_item.InkColor,
_item.Seed);
if (_isFirst || _parameters.Amount != parameters.Amount)
_effect.Amount = parameters.Amount;
if (parameters.Amount <= 0f || parameters.Spread <= 0f)
{
_effect.Amount = 0f;
_parameters = parameters;
_isFirst = true;
return effectDescription.DrawDescription;
}
var bounds = _devices.DeviceContext.GetImageLocalBounds(input);
var widthValue = Math.Ceiling((double)bounds.Right - bounds.Left);
var heightValue = Math.Ceiling((double)bounds.Bottom - bounds.Top);
if (!double.IsFinite(widthValue) || !double.IsFinite(heightValue) ||
!float.IsFinite(bounds.Left) || !float.IsFinite(bounds.Top) ||
widthValue <= 0d || heightValue <= 0d)
{
_effect.Amount = 0f;
_isFirst = true;
return effectDescription.DrawDescription;
}
var reach = Math.Clamp(parameters.Reach, 0.01f, 4f);
var longSide = Math.Max(widthValue, heightValue);
var marginLimit = (InkDispersionSettings.MaximumCanvasSize - longSide) / 2d;
if (marginLimit < 16d)
{
_effect.Amount = 0f;
_isFirst = true;
return effectDescription.DrawDescription;
}
var padding = (double)InkDispersionSettings.MarginPadding;
var reachPixels = Math.Min(reach * longSide, Math.Max(marginLimit - padding, 1d));
var margin = (int)Math.Ceiling(reachPixels + padding);
var canvasWidthValue = widthValue + margin * 2d;
var canvasHeightValue = heightValue + margin * 2d;
if (canvasWidthValue * canvasHeightValue > int.MaxValue)
{
_effect.Amount = 0f;
_isFirst = true;
return effectDescription.DrawDescription;
}
var canvasWidth = (int)canvasWidthValue;
var canvasHeight = (int)canvasHeightValue;
var itemWidth = (int)widthValue;
var itemHeight = (int)heightValue;
_interop.EnsureSource(itemWidth, itemHeight);
_interop.RenderInput(input, new Vortice.RawRectF(bounds.Left, bounds.Top, bounds.Left + itemWidth, bounds.Top + itemHeight));
var pipelineParameters = new InkDispersionPipeline.Parameters(
parameters.Quality,
Math.Clamp(parameters.Spread, 0f, 1f),
Math.Clamp(parameters.Water, 0f, 1f),
Math.Clamp(parameters.Fiber, 0f, 1f),
Math.Clamp(parameters.Sizing, 0f, 1f),
Math.Clamp(parameters.Viscosity, 0f, 1f),
Math.Clamp(parameters.Drying, 0f, 1f),
(float)reachPixels,
Math.Clamp(parameters.Density, 0f, 1f),
Math.Clamp(parameters.Grain, 0f, 1f),
parameters.Color.R / 255f,
parameters.Color.G / 255f,
parameters.Color.B / 255f,
Math.Max(parameters.Seed, 0));
bool structureChanged;
_interop.BeginCompute();
try
{
structureChanged = _pipeline.Simulate(
_interop.SourceTexture,
canvasWidth,
canvasHeight,
margin,
margin,
itemWidth,
itemHeight,
in pipelineParameters);
}
finally
{
_interop.EndCompute();
}
if (!_pipeline.TryGetVisibleBounds(canvasWidth, canvasHeight, in pipelineParameters, out var rect))
{
_effect.Amount = 0f;
_parameters = parameters;
_isFirst = true;
_hasRenderState = false;
return effectDescription.DrawDescription;
}
if (!_interop.OutputCovers(rect.Width, rect.Height))
_outputCrop.SetInput(0, null, true);
var outputChanged = _interop.EnsureOutput(rect.Width, rect.Height);
var renderState = new RenderState(
pipelineParameters.Spread,
pipelineParameters.Density,
pipelineParameters.Grain,
pipelineParameters.ColorR,
pipelineParameters.ColorG,
pipelineParameters.ColorB,
rect);
if (structureChanged || outputChanged || !_hasOutput || !_hasRenderState || _renderState != renderState)
{
_interop.BeginCompute();
try
{
_pipeline.RenderVisible(
_interop.OutputTexture,
canvasWidth,
canvasHeight,
rect,
in pipelineParameters);
}
finally
{
_interop.EndCompute();
}
_renderState = renderState;
_hasRenderState = true;
}
if (outputChanged || !_hasOutput)
{
_outputCrop.SetInput(0, _interop.OutputBitmap, true);
_effect.SetInput(1, _outputTransformOutput, true);
}
var cropRect = new Vector4(0f, 0f, rect.Width, rect.Height);
if (!_hasCropRect || _cropRect != cropRect)
{
_outputCrop.Rectangle = cropRect;
_cropRect = cropRect;
_hasCropRect = true;
}
var outputOffset = new Vector2(bounds.Left - margin + rect.X, bounds.Top - margin + rect.Y);
if (!_hasOutputOffset || _outputOffset != outputOffset)
{
_outputTransform.TransformMatrix = Matrix3x2.CreateTranslation(outputOffset);
_outputOffset = outputOffset;
_hasOutputOffset = true;
}
_hasOutput = true;
_parameters = parameters;
_isFirst = false;
return effectDescription.DrawDescription;
}
protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices)
{
var interop = InkDispersionGpuInterop.TryCreate(devices);
if (interop is null)
return null;
var pipeline = InkDispersionPipeline.TryCreate(interop.Device);
if (pipeline is null)
{
interop.Dispose();
return null;
}
InkDispersionCustomEffect? effect = null;
Crop? outputCrop = null;
ID2D1Image? outputCropOutput = null;
AffineTransform2D? outputTransform = null;
ID2D1Image? outputTransformOutput = null;
ID2D1Image? output = null;
try
{
effect = new InkDispersionCustomEffect(devices);
if (!effect.IsEnabled)
{
effect.Dispose();
pipeline.Dispose();
interop.Dispose();
return null;
}
outputCrop = new Crop(devices.DeviceContext);
outputCropOutput = outputCrop.Output;
outputTransform = new AffineTransform2D(devices.DeviceContext)
{
BorderMode = BorderMode.Hard,
};
outputTransform.SetInput(0, outputCropOutput, true);
outputTransformOutput = outputTransform.Output;
output = effect.Output;
_interop = interop;
_pipeline = pipeline;
_effect = effect;
_outputCrop = outputCrop;
_outputCropOutput = outputCropOutput;
_outputTransform = outputTransform;
_outputTransformOutput = outputTransformOutput;
disposer.Collect(effect);
disposer.Collect(outputCrop);
disposer.Collect(outputCropOutput);
disposer.Collect(outputTransform);
disposer.Collect(outputTransformOutput);
disposer.Collect(output);
return output;
}
catch
{
output?.Dispose();
outputTransformOutput?.Dispose();
outputTransform?.Dispose();
outputCropOutput?.Dispose();
outputCrop?.Dispose();
effect?.Dispose();
pipeline.Dispose();
interop.Dispose();
throw;
}
}
protected override void setInput(ID2D1Image? inputImage)
{
_effect?.SetInput(0, inputImage, true);
if (!_hasOutput)
_effect?.SetInput(1, inputImage, true);
}
protected override void ClearEffectChain()
{
_effect?.SetInput(0, null, true);
_effect?.SetInput(1, null, true);
_outputCrop?.SetInput(0, null, true);
_isFirst = true;
_hasOutput = false;
_hasOutputOffset = false;
_hasCropRect = false;
_hasRenderState = false;
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
ClearEffectChain();
_interop?.WaitForIdle();
_pipeline?.Dispose();
_pipeline = null;
_interop?.Dispose();
_interop = null;
}
}
finally
{
base.Dispose(disposing);
}
}
private readonly record struct RenderState(
float Spread,
float Density,
float Grain,
float ColorR,
float ColorG,
float ColorB,
InkDispersionPipeline.PixelRect Rect);
private readonly record struct Parameters(
float Amount,
float Spread,
InkDispersionQuality Quality,
float Water,
float Reach,
float Fiber,
float Sizing,
float Viscosity,
float Drying,
float Density,
float Grain,
System.Windows.Media.Color Color,
int Seed);
}
+323
ファイルの表示
@@ -0,0 +1,323 @@
using System.Runtime.InteropServices;
using ComputeSharp;
using ComputeSharp.Interop;
using Vortice;
using Vortice.Direct2D1;
using Vortice.Direct3D11;
using Vortice.DXGI;
using YukkuriMovieMaker.Commons;
using PixelFormat = Vortice.DCommon.PixelFormat;
namespace InkDispersion;
internal sealed class InkDispersionGpuInterop : IDisposable
{
private static readonly Guid D3D12FenceGuid = new("0a753dcf-c4d8-4b91-adf6-be5a60d95a76");
private readonly GraphicsDevice _device;
private readonly ID3D11Device1 _d3dDevice;
private readonly ID3D11DeviceContext4 _d3dContext;
private readonly ID3D11Fence _fence;
private readonly ID2D1DeviceContext6 _renderContext;
private nint _d3d12Fence;
private ReadWriteTexture2D<Bgra32, Float4>? _sourceTexture;
private ReadWriteTexture2D<Bgra32, Float4>? _outputTexture;
private ID3D11Texture2D? _sourceD3D11Texture;
private ID3D11Texture2D? _outputD3D11Texture;
private ID2D1Bitmap1? _sourceBitmap;
private ID2D1Bitmap1? _outputBitmap;
private int _sourceWidth;
private int _sourceHeight;
private int _outputWidth;
private int _outputHeight;
private ulong _fenceValue;
private bool _computeActive;
private bool _disposed;
private InkDispersionGpuInterop(
GraphicsDevice device,
ID3D11Device1 d3dDevice,
ID3D11DeviceContext4 d3dContext,
ID3D11Fence fence,
ID2D1DeviceContext6 renderContext,
nint d3d12Fence)
{
_device = device;
_d3dDevice = d3dDevice;
_d3dContext = d3dContext;
_fence = fence;
_renderContext = renderContext;
_d3d12Fence = d3d12Fence;
}
public GraphicsDevice Device => _device;
public ReadWriteTexture2D<Bgra32, Float4> SourceTexture => _sourceTexture!;
public ReadWriteTexture2D<Bgra32, Float4> OutputTexture => _outputTexture!;
public ID2D1Bitmap1 OutputBitmap => _outputBitmap!;
public bool SourceMatches(int width, int height)
=> _sourceTexture is not null && _sourceWidth == width && _sourceHeight == height;
public bool OutputCovers(int width, int height)
=> _outputTexture is not null && _outputWidth >= width && _outputHeight >= height;
public static unsafe InkDispersionGpuInterop? TryCreate(IGraphicsDevicesAndContext devices)
{
ID3D11Device1? d3dDevice = null;
ID3D11DeviceContext4? d3dContext = null;
ID3D11Fence? fence = null;
ID2D1DeviceContext6? renderContext = null;
nint d3d12Fence = 0;
nint fenceHandle = 0;
try
{
var device = GetMatchingDevice(devices);
d3dDevice = devices.D3D.Device.QueryInterface<ID3D11Device1>();
d3dContext = devices.D3D.DeviceContext.QueryInterface<ID3D11DeviceContext4>();
using var d3dDevice5 = devices.D3D.Device.QueryInterface<ID3D11Device5>();
var fenceGuid = D3D12FenceGuid;
InteropServices.CreateSharedFence(device, &fenceGuid, (void**)&d3d12Fence, &fenceHandle);
fence = d3dDevice5.OpenSharedFence(fenceHandle);
renderContext = devices.D2D.Device.CreateDeviceContext(DeviceContextOptions.EnableMultithreadedOptimizations);
return new InkDispersionGpuInterop(device, d3dDevice, d3dContext, fence, renderContext, d3d12Fence);
}
catch
{
renderContext?.Dispose();
fence?.Dispose();
d3dContext?.Dispose();
d3dDevice?.Dispose();
if (d3d12Fence != 0)
Marshal.Release(d3d12Fence);
return null;
}
finally
{
if (fenceHandle != 0)
CloseHandle(fenceHandle);
}
}
public bool EnsureResources(int width, int height)
{
var sourceChanged = EnsureSource(width, height);
var outputChanged = EnsureOutput(width, height);
return sourceChanged || outputChanged;
}
public bool EnsureSource(int width, int height)
{
if (SourceMatches(width, height))
return false;
if (_sourceTexture is not null)
WaitForIdle();
ReleaseSourceResources();
CreateSourceResources(width, height);
return true;
}
public bool EnsureOutput(int width, int height)
{
if (OutputCovers(width, height))
return false;
var capacityWidth = Math.Max(width, _outputWidth);
var capacityHeight = Math.Max(height, _outputHeight);
if (_outputTexture is not null)
WaitForIdle();
ReleaseOutputResources();
CreateOutputResources(capacityWidth, capacityHeight);
return true;
}
public void RenderInput(ID2D1Image source, RawRectF bounds)
{
_renderContext.BeginDraw();
_renderContext.Clear(null);
_renderContext.DrawImage(
source,
new System.Numerics.Vector2(-bounds.Left, -bounds.Top),
null,
InterpolationMode.NearestNeighbor,
CompositeMode.SourceCopy);
_renderContext.EndDraw();
}
public unsafe void BeginCompute()
{
if (_computeActive)
throw new InvalidOperationException();
var value = ++_fenceValue;
_d3dContext.Signal(_fence, value);
_d3dContext.Flush();
InteropServices.WaitForSharedFence(_device, (void*)_d3d12Fence, value);
_computeActive = true;
}
public unsafe void EndCompute()
{
if (!_computeActive)
throw new InvalidOperationException();
try
{
var value = ++_fenceValue;
InteropServices.SignalSharedFence(_device, (void*)_d3d12Fence, value);
_d3dContext.Wait(_fence, value);
}
finally
{
_computeActive = false;
}
}
public void WaitForIdle()
{
if (_computeActive)
throw new InvalidOperationException();
var value = ++_fenceValue;
_d3dContext.Signal(_fence, value);
_d3dContext.Flush();
_fence.SetEventOnCompletion(value, 0);
}
private static GraphicsDevice GetMatchingDevice(IGraphicsDevicesAndContext devices)
{
var adapterLuid = devices.DXGI.Adapter.Description.Luid.ToString();
using var enumerator = GraphicsDevice.QueryDevices(
device => string.Equals(device.Luid.ToString(), adapterLuid, StringComparison.Ordinal)).GetEnumerator();
if (!enumerator.MoveNext())
throw new NotSupportedException();
return enumerator.Current;
}
private void CreateSourceResources(int width, int height)
{
ReadWriteTexture2D<Bgra32, Float4>? sourceTexture = null;
ID3D11Texture2D? sourceD3D11Texture = null;
ID2D1Bitmap1? sourceBitmap = null;
nint sourceHandle = 0;
try
{
sourceTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(_device, width, height);
sourceHandle = InteropServices.CreateSharedHandle(sourceTexture);
sourceD3D11Texture = _d3dDevice.OpenSharedResource1<ID3D11Texture2D>(sourceHandle);
using var sourceSurface = sourceD3D11Texture.QueryInterface<IDXGISurface>();
var pixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied);
sourceBitmap = _renderContext.CreateBitmapFromDxgiSurface(
sourceSurface,
new BitmapProperties1(pixelFormat, 96f, 96f, BitmapOptions.Target));
_renderContext.Target = sourceBitmap;
_sourceTexture = sourceTexture;
_sourceD3D11Texture = sourceD3D11Texture;
_sourceBitmap = sourceBitmap;
_sourceWidth = width;
_sourceHeight = height;
sourceTexture = null;
sourceD3D11Texture = null;
sourceBitmap = null;
}
finally
{
if (sourceHandle != 0)
CloseHandle(sourceHandle);
sourceBitmap?.Dispose();
sourceD3D11Texture?.Dispose();
sourceTexture?.Dispose();
}
}
private void CreateOutputResources(int width, int height)
{
ReadWriteTexture2D<Bgra32, Float4>? outputTexture = null;
ID3D11Texture2D? outputD3D11Texture = null;
ID2D1Bitmap1? outputBitmap = null;
nint outputHandle = 0;
try
{
outputTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(_device, width, height);
outputHandle = InteropServices.CreateSharedHandle(outputTexture);
outputD3D11Texture = _d3dDevice.OpenSharedResource1<ID3D11Texture2D>(outputHandle);
using var outputSurface = outputD3D11Texture.QueryInterface<IDXGISurface>();
var pixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied);
outputBitmap = _renderContext.CreateBitmapFromDxgiSurface(
outputSurface,
new BitmapProperties1(pixelFormat, 96f, 96f, BitmapOptions.None));
_outputTexture = outputTexture;
_outputD3D11Texture = outputD3D11Texture;
_outputBitmap = outputBitmap;
_outputWidth = width;
_outputHeight = height;
outputTexture = null;
outputD3D11Texture = null;
outputBitmap = null;
}
finally
{
if (outputHandle != 0)
CloseHandle(outputHandle);
outputBitmap?.Dispose();
outputD3D11Texture?.Dispose();
outputTexture?.Dispose();
}
}
private void ReleaseSourceResources()
{
_renderContext.Target = null;
_sourceBitmap?.Dispose();
_sourceD3D11Texture?.Dispose();
_sourceTexture?.Dispose();
_sourceBitmap = null;
_sourceD3D11Texture = null;
_sourceTexture = null;
_sourceWidth = 0;
_sourceHeight = 0;
}
private void ReleaseOutputResources()
{
_outputBitmap?.Dispose();
_outputD3D11Texture?.Dispose();
_outputTexture?.Dispose();
_outputBitmap = null;
_outputD3D11Texture = null;
_outputTexture = null;
_outputWidth = 0;
_outputHeight = 0;
}
public void Dispose()
{
if (_disposed)
return;
try
{
WaitForIdle();
}
finally
{
_disposed = true;
ReleaseOutputResources();
ReleaseSourceResources();
_renderContext.Dispose();
_fence.Dispose();
_d3dContext.Dispose();
_d3dDevice.Dispose();
if (_d3d12Fence != 0)
{
Marshal.Release(_d3d12Fence);
_d3d12Fence = 0;
}
}
}
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(nint handle);
}
+892
ファイルの表示
@@ -0,0 +1,892 @@
using ComputeSharp;
namespace InkDispersion;
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct FillIntShader(
ReadWriteBuffer<int> values,
int length,
int value) : IComputeShader
{
private readonly ReadWriteBuffer<int> values = values;
private readonly int length = length;
private readonly int value = value;
public void Execute()
{
var index = ThreadIds.X;
if (index >= length)
return;
values[index] = value;
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct InitScratchShader(
ReadWriteBuffer<int> scratch) : IComputeShader
{
private readonly ReadWriteBuffer<int> scratch = scratch;
public void Execute()
{
if (ThreadIds.X != 0)
return;
scratch[0] = 0;
scratch[1] = -1;
scratch[2] = 0;
scratch[3] = 0;
scratch[4] = 0;
scratch[5] = 0;
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct SilhouetteShader(
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteBuffer<float> deposit,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
int gridWidth,
int gridHeight,
float cellSize) : IComputeShader
{
private readonly ReadWriteTexture2D<Bgra32, Float4> source = source;
private readonly ReadWriteBuffer<float> deposit = deposit;
private readonly int sourceOffsetX = sourceOffsetX;
private readonly int sourceOffsetY = sourceOffsetY;
private readonly int sourceWidth = sourceWidth;
private readonly int sourceHeight = sourceHeight;
private readonly int gridWidth = gridWidth;
private readonly int gridHeight = gridHeight;
private readonly float cellSize = cellSize;
public void Execute()
{
var gx = ThreadIds.X;
var gy = ThreadIds.Y;
if (gx >= gridWidth || gy >= gridHeight)
return;
var centerX = (gx + 0.5f) * cellSize;
var centerY = (gy + 0.5f) * cellSize;
var x0 = Hlsl.Max((int)(centerX - cellSize * 0.5f), sourceOffsetX);
var x1 = Hlsl.Min((int)Hlsl.Ceil(centerX + cellSize * 0.5f), sourceOffsetX + sourceWidth);
var y0 = Hlsl.Max((int)(centerY - cellSize * 0.5f), sourceOffsetY);
var y1 = Hlsl.Min((int)Hlsl.Ceil(centerY + cellSize * 0.5f), sourceOffsetY + sourceHeight);
var sum = 0f;
var count = 0;
for (var y = y0; y < y1; y++)
{
for (var x = x0; x < x1; x++)
{
sum += source[new Int2(x - sourceOffsetX, y - sourceOffsetY)].W;
count++;
}
}
deposit[gy * gridWidth + gx] = count > 0 ? sum / count : 0f;
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct MaskHashResetShader(
ReadWriteBuffer<int> scratch) : IComputeShader
{
private readonly ReadWriteBuffer<int> scratch = scratch;
public void Execute()
{
if (ThreadIds.X != 0)
return;
scratch[6] = 0;
scratch[7] = 0;
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct MaskHashShader(
ReadWriteBuffer<float> deposit,
ReadWriteBuffer<int> scratch,
int gridWidth,
int gridHeight) : IComputeShader
{
private readonly ReadWriteBuffer<float> deposit = deposit;
private readonly ReadWriteBuffer<int> scratch = scratch;
private readonly int gridWidth = gridWidth;
private readonly int gridHeight = gridHeight;
public void Execute()
{
var gx = ThreadIds.X;
var gy = ThreadIds.Y;
if (gx >= gridWidth || gy >= gridHeight)
return;
var index = gy * gridWidth + gx;
var quantized = (int)(deposit[index] * 255f + 0.5f);
if (quantized <= 0)
return;
var mixed = ((uint)index * 0x9E3779B9u) ^ ((uint)quantized * 0x85EBCA6Bu);
mixed ^= mixed >> 16;
mixed *= 0x85EBCA6Bu;
mixed ^= mixed >> 13;
Hlsl.InterlockedAdd(ref scratch[6], (int)mixed);
Hlsl.InterlockedXor(ref scratch[7], (int)(mixed * 0xC2B2AE35u));
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct InitFieldShader(
ReadWriteBuffer<float> distributions,
ReadWriteBuffer<float> deposit,
ReadWriteBuffer<float> surface,
ReadWriteBuffer<float> flowPigment,
ReadWriteBuffer<float> fixedPigment,
ReadWriteBuffer<float> density,
ReadWriteBuffer<float> wetness,
ReadWriteBuffer<Float2> velocity,
ReadWriteBuffer<int> inkStep,
int gridWidth,
int gridHeight,
float depositScale) : IComputeShader
{
private readonly ReadWriteBuffer<float> distributions = distributions;
private readonly ReadWriteBuffer<float> deposit = deposit;
private readonly ReadWriteBuffer<float> surface = surface;
private readonly ReadWriteBuffer<float> flowPigment = flowPigment;
private readonly ReadWriteBuffer<float> fixedPigment = fixedPigment;
private readonly ReadWriteBuffer<float> density = density;
private readonly ReadWriteBuffer<float> wetness = wetness;
private readonly ReadWriteBuffer<Float2> velocity = velocity;
private readonly ReadWriteBuffer<int> inkStep = inkStep;
private readonly int gridWidth = gridWidth;
private readonly int gridHeight = gridHeight;
private readonly float depositScale = depositScale;
public void Execute()
{
var gx = ThreadIds.X;
var gy = ThreadIds.Y;
if (gx >= gridWidth || gy >= gridHeight)
return;
var index = gy * gridWidth + gx;
var gridLength = gridWidth * gridHeight;
for (var i = 0; i < 9; i++)
distributions[i * gridLength + index] = 0f;
surface[index] = deposit[index] * depositScale;
flowPigment[index] = 0f;
fixedPigment[index] = 0f;
density[index] = 0f;
wetness[index] = 0f;
velocity[index] = new Float2(0f, 0f);
inkStep[index] = InkDispersionSettings.BirthSentinel;
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct JumpFloodSeedShader(
ReadWriteBuffer<float> deposit,
ReadWriteBuffer<int> jumpFlood,
int gridWidth,
int gridHeight) : IComputeShader
{
private readonly ReadWriteBuffer<float> deposit = deposit;
private readonly ReadWriteBuffer<int> jumpFlood = jumpFlood;
private readonly int gridWidth = gridWidth;
private readonly int gridHeight = gridHeight;
public void Execute()
{
var gx = ThreadIds.X;
var gy = ThreadIds.Y;
if (gx >= gridWidth || gy >= gridHeight)
return;
var index = gy * gridWidth + gx;
jumpFlood[index] = deposit[index] > InkDispersionSettings.DepositThreshold ? index : -1;
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct JumpFloodPassShader(
ReadWriteBuffer<int> input,
ReadWriteBuffer<int> output,
int gridWidth,
int gridHeight,
int stepSize) : IComputeShader
{
private readonly ReadWriteBuffer<int> input = input;
private readonly ReadWriteBuffer<int> output = output;
private readonly int gridWidth = gridWidth;
private readonly int gridHeight = gridHeight;
private readonly int stepSize = stepSize;
public void Execute()
{
var x = ThreadIds.X;
var y = ThreadIds.Y;
if (x >= gridWidth || y >= gridHeight)
return;
var best = -1;
var bestDistance = 3.402823e+38f;
for (var dy = -1; dy <= 1; dy++)
{
for (var dx = -1; dx <= 1; dx++)
{
var sx = x + dx * stepSize;
var sy = y + dy * stepSize;
if (sx < 0 || sx >= gridWidth || sy < 0 || sy >= gridHeight)
continue;
var candidate = input[sy * gridWidth + sx];
if (candidate < 0)
continue;
var deltaX = (float)(x - candidate % gridWidth);
var deltaY = (float)(y - candidate / gridWidth);
var distance = deltaX * deltaX + deltaY * deltaY;
if (distance < bestDistance)
{
bestDistance = distance;
best = candidate;
}
}
}
output[y * gridWidth + x] = best;
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct ReachMaskShader(
ReadWriteBuffer<int> jumpFlood,
ReadWriteBuffer<int> reachMask,
int gridWidth,
int gridHeight,
float cellSize,
float reachPixels) : IComputeShader
{
private readonly ReadWriteBuffer<int> jumpFlood = jumpFlood;
private readonly ReadWriteBuffer<int> reachMask = reachMask;
private readonly int gridWidth = gridWidth;
private readonly int gridHeight = gridHeight;
private readonly float cellSize = cellSize;
private readonly float reachPixels = reachPixels;
public void Execute()
{
var x = ThreadIds.X;
var y = ThreadIds.Y;
if (x >= gridWidth || y >= gridHeight)
return;
var index = y * gridWidth + x;
var seed = jumpFlood[index];
if (seed < 0)
{
reachMask[index] = 0;
return;
}
var deltaX = (x - seed % gridWidth) * cellSize;
var deltaY = (y - seed / gridWidth) * cellSize;
reachMask[index] = deltaX * deltaX + deltaY * deltaY <= reachPixels * reachPixels ? 1 : 0;
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct SupplyShader(
ReadWriteBuffer<float> distributions,
ReadWriteBuffer<float> surface,
ReadWriteBuffer<float> flowPigment,
ReadWriteBuffer<float> density,
int gridWidth,
int gridHeight) : IComputeShader
{
private readonly ReadWriteBuffer<float> distributions = distributions;
private readonly ReadWriteBuffer<float> surface = surface;
private readonly ReadWriteBuffer<float> flowPigment = flowPigment;
private readonly ReadWriteBuffer<float> density = density;
private readonly int gridWidth = gridWidth;
private readonly int gridHeight = gridHeight;
public void Execute()
{
var gx = ThreadIds.X;
var gy = ThreadIds.Y;
if (gx >= gridWidth || gy >= gridHeight)
return;
var index = gy * gridWidth + gx;
var gridLength = gridWidth * gridHeight;
var rho = 0f;
for (var i = 0; i < 9; i++)
rho += distributions[i * gridLength + index];
var reservoir = surface[index];
var supply = Hlsl.Clamp(reservoir, 0f, InkDispersionSettings.PaperCapacity - rho);
if (supply > 0f)
{
for (var i = 0; i < 9; i++)
distributions[i * gridLength + index] += InkDispersionShaderMath.Weight(i) * supply;
flowPigment[index] = (flowPigment[index] * rho + supply) / (rho + supply);
surface[index] = reservoir - supply;
rho += supply;
}
density[index] = rho;
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct KappaShader(
ReadWriteBuffer<float> density,
ReadWriteBuffer<float> fixedPigment,
ReadWriteBuffer<int> reachMask,
ReadWriteBuffer<float> kappa,
int gridWidth,
int gridHeight,
int seed,
float fiber,
float sizing,
float viscosity,
float sigma) : IComputeShader
{
private readonly ReadWriteBuffer<float> density = density;
private readonly ReadWriteBuffer<float> fixedPigment = fixedPigment;
private readonly ReadWriteBuffer<int> reachMask = reachMask;
private readonly ReadWriteBuffer<float> kappa = kappa;
private readonly int gridWidth = gridWidth;
private readonly int gridHeight = gridHeight;
private readonly int seed = seed;
private readonly float fiber = fiber;
private readonly float sizing = sizing;
private readonly float viscosity = viscosity;
private readonly float sigma = sigma;
public void Execute()
{
var gx = ThreadIds.X;
var gy = ThreadIds.Y;
if (gx >= gridWidth || gy >= gridHeight)
return;
var index = gy * gridWidth + gx;
if (reachMask[index] == 0)
{
kappa[index] = 1f;
return;
}
if (density[index] <= InkDispersionSettings.WetEpsilon)
{
var pin = InkDispersionShaderMath.PinField(gx, gy, seed);
var accumulated = Hlsl.Min(fixedPigment[index], 1f);
var threshold = sigma * (0.4f + 0.6f * pin) * (1f + accumulated);
var pinned = true;
for (var i = 1; i <= 8 && pinned; i++)
{
var nx = gx + InkDispersionShaderMath.Ex(i);
var ny = gy + InkDispersionShaderMath.Ey(i);
var neighborDensity = 0f;
if (nx >= 0 && nx < gridWidth && ny >= 0 && ny < gridHeight)
neighborDensity = density[ny * gridWidth + nx];
var limit = i <= 4 ? threshold : threshold * InkDispersionSettings.DiagonalSigmaFactor;
if (neighborDensity >= limit)
pinned = false;
}
if (pinned)
{
kappa[index] = InkDispersionSettings.PinnedKappaMarker;
return;
}
}
var grain = InkDispersionShaderMath.FiberField(gx, gy, seed);
var alum = InkDispersionShaderMath.AlumField(gx, gy, seed);
var blocking = InkDispersionSettings.KappaBase
+ InkDispersionSettings.KappaFiber * fiber * grain
+ InkDispersionSettings.KappaAlum * sizing * alum
+ InkDispersionSettings.KappaGlue * viscosity
+ InkDispersionSettings.KappaFixture * Hlsl.Min(fixedPigment[index], 1f);
kappa[index] = Hlsl.Clamp(blocking, 0f, InkDispersionSettings.KappaMax);
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct StreamCollideShader(
ReadWriteBuffer<float> distributionsIn,
ReadWriteBuffer<float> distributionsOut,
ReadWriteBuffer<float> kappa,
ReadWriteBuffer<int> reachMask,
ReadWriteBuffer<float> densityOut,
ReadWriteBuffer<Float2> velocity,
int gridWidth,
int gridHeight,
float omega,
float surfaceEvaporation) : IComputeShader
{
private readonly ReadWriteBuffer<float> distributionsIn = distributionsIn;
private readonly ReadWriteBuffer<float> distributionsOut = distributionsOut;
private readonly ReadWriteBuffer<float> kappa = kappa;
private readonly ReadWriteBuffer<int> reachMask = reachMask;
private readonly ReadWriteBuffer<float> densityOut = densityOut;
private readonly ReadWriteBuffer<Float2> velocity = velocity;
private readonly int gridWidth = gridWidth;
private readonly int gridHeight = gridHeight;
private readonly float omega = omega;
private readonly float surfaceEvaporation = surfaceEvaporation;
public void Execute()
{
var gx = ThreadIds.X;
var gy = ThreadIds.Y;
if (gx >= gridWidth || gy >= gridHeight)
return;
var index = gy * gridWidth + gx;
var gridLength = gridWidth * gridHeight;
if (reachMask[index] == 0)
{
for (var i = 0; i < 9; i++)
distributionsOut[i * gridLength + index] = 0f;
densityOut[index] = 0f;
velocity[index] = new Float2(0f, 0f);
return;
}
var selfKappa = kappa[index];
var selfPinned = selfKappa >= InkDispersionSettings.PinnedKappaMarker;
var selfBlocking = selfPinned ? 1f : selfKappa;
var f0 = distributionsIn[index];
var f1 = 0f;
var f2 = 0f;
var f3 = 0f;
var f4 = 0f;
var f5 = 0f;
var f6 = 0f;
var f7 = 0f;
var f8 = 0f;
for (var i = 1; i <= 8; i++)
{
var sx = gx - InkDispersionShaderMath.Ex(i);
var sy = gy - InkDispersionShaderMath.Ey(i);
var opposite = InkDispersionShaderMath.Opposite(i);
var bounced = distributionsIn[opposite * gridLength + index];
var streamed = 0f;
var linkBlocking = 1f;
var linkPinned = false;
if (sx >= 0 && sx < gridWidth && sy >= 0 && sy < gridHeight)
{
var sourceIndex = sy * gridWidth + sx;
streamed = distributionsIn[i * gridLength + sourceIndex];
var sourceKappa = kappa[sourceIndex];
var sourcePinned = sourceKappa >= InkDispersionSettings.PinnedKappaMarker;
var sourceBlocking = sourcePinned ? 1f : sourceKappa;
linkBlocking = Hlsl.Min((selfBlocking + sourceBlocking) * 0.5f, 1f);
linkPinned = selfPinned || sourcePinned;
}
var bounceScale = linkPinned ? 1f - InkDispersionSettings.BoundaryEvaporation : 1f;
var value = (1f - linkBlocking) * streamed + linkBlocking * bounced * bounceScale;
if (i == 1)
f1 = value;
else if (i == 2)
f2 = value;
else if (i == 3)
f3 = value;
else if (i == 4)
f4 = value;
else if (i == 5)
f5 = value;
else if (i == 6)
f6 = value;
else if (i == 7)
f7 = value;
else
f8 = value;
}
var rho = f0 + f1 + f2 + f3 + f4 + f5 + f6 + f7 + f8;
var ux = f1 - f3 + f5 - f6 - f7 + f8;
var uy = f2 - f4 + f5 + f6 - f7 - f8;
var speedSquared = ux * ux + uy * uy;
var speedLimit = InkDispersionSettings.MaximumLatticeSpeed;
if (speedSquared > speedLimit * speedLimit)
{
var scale = speedLimit / Hlsl.Sqrt(speedSquared);
ux *= scale;
uy *= scale;
}
var psi = Hlsl.SmoothStep(0f, InkDispersionSettings.AdvectionAlpha, rho);
var uSquared = 1.5f * (ux * ux + uy * uy);
var evaporationScale = 1f - surfaceEvaporation;
for (var i = 0; i < 9; i++)
{
var eDotU = InkDispersionShaderMath.Ex(i) * ux + InkDispersionShaderMath.Ey(i) * uy;
var equilibrium = InkDispersionShaderMath.Weight(i) * (rho + psi * (3f * eDotU + 4.5f * eDotU * eDotU - uSquared));
var current = i == 0 ? f0 : i == 1 ? f1 : i == 2 ? f2 : i == 3 ? f3 : i == 4 ? f4 : i == 5 ? f5 : i == 6 ? f6 : i == 7 ? f7 : f8;
distributionsOut[i * gridLength + index] = ((1f - omega) * current + omega * equilibrium) * evaporationScale;
}
densityOut[index] = rho * evaporationScale;
velocity[index] = new Float2(ux, uy);
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct PigmentShader(
ReadWriteBuffer<float> distributions,
ReadWriteBuffer<float> densityPrevious,
ReadWriteBuffer<float> densityCurrent,
ReadWriteBuffer<Float2> velocity,
ReadWriteBuffer<float> flowPigmentIn,
ReadWriteBuffer<float> flowPigmentOut,
ReadWriteBuffer<float> fixedPigment,
ReadWriteBuffer<float> wetness,
ReadWriteBuffer<int> inkStep,
ReadWriteBuffer<int> reachMask,
ReadWriteBuffer<int> scratch,
int gridWidth,
int gridHeight,
int step,
int seed,
float fiber,
float viscosity) : IComputeShader
{
private readonly ReadWriteBuffer<float> distributions = distributions;
private readonly ReadWriteBuffer<float> densityPrevious = densityPrevious;
private readonly ReadWriteBuffer<float> densityCurrent = densityCurrent;
private readonly ReadWriteBuffer<Float2> velocity = velocity;
private readonly ReadWriteBuffer<float> flowPigmentIn = flowPigmentIn;
private readonly ReadWriteBuffer<float> flowPigmentOut = flowPigmentOut;
private readonly ReadWriteBuffer<float> fixedPigment = fixedPigment;
private readonly ReadWriteBuffer<float> wetness = wetness;
private readonly ReadWriteBuffer<int> inkStep = inkStep;
private readonly ReadWriteBuffer<int> reachMask = reachMask;
private readonly ReadWriteBuffer<int> scratch = scratch;
private readonly int gridWidth = gridWidth;
private readonly int gridHeight = gridHeight;
private readonly int step = step;
private readonly int seed = seed;
private readonly float fiber = fiber;
private readonly float viscosity = viscosity;
public void Execute()
{
var gx = ThreadIds.X;
var gy = ThreadIds.Y;
if (gx >= gridWidth || gy >= gridHeight)
return;
var index = gy * gridWidth + gx;
if (reachMask[index] == 0)
{
flowPigmentOut[index] = 0f;
return;
}
var gridLength = gridWidth * gridHeight;
var previousDensity = densityPrevious[index];
var currentDensity = densityCurrent[index];
var wasWet = previousDensity > InkDispersionSettings.WetEpsilon;
var isWet = currentDensity > InkDispersionSettings.WetEpsilon;
var pigment = flowPigmentIn[index];
var advected = pigment;
if (isWet && !wasWet)
{
var sum = 0f;
for (var i = 1; i <= 8; i++)
{
var sx = gx - InkDispersionShaderMath.Ex(i);
var sy = gy - InkDispersionShaderMath.Ey(i);
if (sx < 0 || sx >= gridWidth || sy < 0 || sy >= gridHeight)
continue;
sum += distributions[i * gridLength + index] * flowPigmentIn[sy * gridWidth + sx];
}
advected = sum / currentDensity;
}
else if (isWet)
{
var u = velocity[index];
var posX = gx - u.X;
var posY = gy - u.Y;
var ix = (int)Hlsl.Floor(posX);
var iy = (int)Hlsl.Floor(posY);
var fx = posX - ix;
var fy = posY - iy;
var valid = ix >= 0 && ix + 1 < gridWidth && iy >= 0 && iy + 1 < gridHeight;
if (valid)
{
var i00 = iy * gridWidth + ix;
var i10 = i00 + 1;
var i01 = i00 + gridWidth;
var i11 = i01 + 1;
if (densityPrevious[i00] <= InkDispersionSettings.WetEpsilon ||
densityPrevious[i10] <= InkDispersionSettings.WetEpsilon ||
densityPrevious[i01] <= InkDispersionSettings.WetEpsilon ||
densityPrevious[i11] <= InkDispersionSettings.WetEpsilon)
{
advected = pigment;
}
else
{
var top = Hlsl.Lerp(flowPigmentIn[i00], flowPigmentIn[i10], fx);
var bottom = Hlsl.Lerp(flowPigmentIn[i01], flowPigmentIn[i11], fx);
advected = Hlsl.Lerp(top, bottom, fy);
}
}
var speed = Hlsl.Sqrt(u.X * u.X + u.Y * u.Y);
var grain = InkDispersionShaderMath.FiberField(gx, gy, seed);
var hindrance = Hlsl.Saturate(InkDispersionSettings.HindranceBase + InkDispersionSettings.HindranceFiber * fiber * grain);
var mix = Hlsl.Lerp(1f, hindrance, Hlsl.SmoothStep(0f, InkDispersionSettings.HindranceSpeed, speed));
advected = Hlsl.Lerp(advected, pigment, mix);
}
var waterLoss = Hlsl.Max(previousDensity - currentDensity, 0f);
var fixFactor = wasWet && waterLoss > 0f ? waterLoss / previousDensity : 0f;
var glueRate = Hlsl.Clamp(InkDispersionSettings.FixtureDryness + InkDispersionSettings.FixtureGlue * viscosity, 0f, 1f);
fixFactor = Hlsl.Clamp(Hlsl.Max(fixFactor * (1f - Hlsl.SmoothStep(0f, glueRate, currentDensity)), InkDispersionSettings.FixtureBase), 0f, 1f);
var settled = fixFactor * advected;
var accumulated = fixedPigment[index] + settled;
fixedPigment[index] = accumulated;
flowPigmentOut[index] = advected - settled;
if (isWet)
wetness[index] = Hlsl.Max(wetness[index], currentDensity);
if (accumulated > InkDispersionSettings.InkEpsilon && inkStep[index] == InkDispersionSettings.BirthSentinel)
{
inkStep[index] = step;
Hlsl.InterlockedAdd(ref scratch[0], 1);
Hlsl.InterlockedMax(ref scratch[1], step);
}
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct FinalFixShader(
ReadWriteBuffer<float> flowPigment,
ReadWriteBuffer<float> fixedPigment,
int gridWidth,
int gridHeight) : IComputeShader
{
private readonly ReadWriteBuffer<float> flowPigment = flowPigment;
private readonly ReadWriteBuffer<float> fixedPigment = fixedPigment;
private readonly int gridWidth = gridWidth;
private readonly int gridHeight = gridHeight;
public void Execute()
{
var gx = ThreadIds.X;
var gy = ThreadIds.Y;
if (gx >= gridWidth || gy >= gridHeight)
return;
var index = gy * gridWidth + gx;
fixedPigment[index] += flowPigment[index];
flowPigment[index] = 0f;
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct RenderShader(
ReadWriteBuffer<int> inkStep,
ReadWriteBuffer<float> fixedPigment,
ReadWriteBuffer<float> wetness,
ReadWriteBuffer<int> scratch,
ReadWriteTexture2D<Bgra32, Float4> output,
int rectOffsetX,
int rectOffsetY,
int rectWidth,
int rectHeight,
int gridWidth,
int gridHeight,
float cellSize,
float spread,
float density,
float grain,
float colorR,
float colorG,
float colorB,
int seed) : IComputeShader
{
private readonly ReadWriteBuffer<int> inkStep = inkStep;
private readonly ReadWriteBuffer<float> fixedPigment = fixedPigment;
private readonly ReadWriteBuffer<float> wetness = wetness;
private readonly ReadWriteBuffer<int> scratch = scratch;
private readonly ReadWriteTexture2D<Bgra32, Float4> output = output;
private readonly int rectOffsetX = rectOffsetX;
private readonly int rectOffsetY = rectOffsetY;
private readonly int rectWidth = rectWidth;
private readonly int rectHeight = rectHeight;
private readonly int gridWidth = gridWidth;
private readonly int gridHeight = gridHeight;
private readonly float cellSize = cellSize;
private readonly float spread = spread;
private readonly float density = density;
private readonly float grain = grain;
private readonly float colorR = colorR;
private readonly float colorG = colorG;
private readonly float colorB = colorB;
private readonly int seed = seed;
public void Execute()
{
if (ThreadIds.X >= rectWidth || ThreadIds.Y >= rectHeight)
return;
var px = ThreadIds.X + rectOffsetX + 0.5f;
var py = ThreadIds.Y + rectOffsetY + 0.5f;
var visible = spread * (scratch[1] + 1);
var cellX = px / cellSize - 0.5f;
var cellY = py / cellSize - 0.5f;
var ix = (int)Hlsl.Floor(cellX);
var iy = (int)Hlsl.Floor(cellY);
var fx = cellX - ix;
var fy = cellY - iy;
var ink = 0f;
var tau = 0f;
for (var corner = 0; corner < 4; corner++)
{
var cx = ix + (corner & 1);
var cy = iy + (corner >> 1);
if (cx < 0 || cx >= gridWidth || cy < 0 || cy >= gridHeight)
continue;
var weight = ((corner & 1) == 0 ? 1f - fx : fx) * ((corner >> 1) == 0 ? 1f - fy : fy);
var index = cy * gridWidth + cx;
var cellStep = inkStep[index];
if (cellStep >= InkDispersionSettings.BirthSentinel)
continue;
var fade = Hlsl.Saturate(visible - cellStep);
ink += weight * fade * Hlsl.Max(fixedPigment[index] - InkDispersionSettings.InkEpsilon, 0f);
tau += weight * fade * wetness[index];
}
if (tau <= 0f)
{
output[ThreadIds.XY] = new Float4(0f, 0f, 0f, 0f);
return;
}
var rougher = InkDispersionShaderMath.ValueNoise(px * (0.5f / cellSize), py * (0.5f / cellSize), (uint)seed, 0x51ED270Bu);
var phi = tau * InkDispersionSettings.CoverageGain - InkDispersionSettings.RougherBias - grain * InkDispersionSettings.RougherScale * rougher;
var coverage = Hlsl.SmoothStep(0f, InkDispersionSettings.CoverageSoftness, phi);
if (coverage <= 0f)
{
output[ThreadIds.XY] = new Float4(0f, 0f, 0f, 0f);
return;
}
var hairField = InkDispersionShaderMath.FiberField((int)(px * 2f), (int)(py * 2f), seed);
var hair = 1f - grain * InkDispersionSettings.HairStrength * hairField * (1f - Hlsl.Saturate(tau * 2f));
var absorbed = 1f - Hlsl.Exp(-ink * InkDispersionSettings.InkAbsorbance * density);
var alpha = Hlsl.Saturate(coverage * absorbed * hair);
var r = Hlsl.Min(colorR * alpha, alpha);
var g = Hlsl.Min(colorG * alpha, alpha);
var b = Hlsl.Min(colorB * alpha, alpha);
output[ThreadIds.XY] = new Float4(r, g, b, alpha);
}
}
internal static class InkDispersionShaderMath
{
public static int Ex(int direction)
{
if (direction == 1 || direction == 5 || direction == 8)
return 1;
if (direction == 3 || direction == 6 || direction == 7)
return -1;
return 0;
}
public static int Ey(int direction)
{
if (direction == 2 || direction == 5 || direction == 6)
return 1;
if (direction == 4 || direction == 7 || direction == 8)
return -1;
return 0;
}
public static int Opposite(int direction)
{
if (direction == 0)
return 0;
if (direction <= 4)
return ((direction + 1) & 3) + 1;
return ((direction - 3) & 3) + 5;
}
public static float Weight(int direction)
{
if (direction == 0)
return 4f / 9f;
return direction <= 4 ? 1f / 9f : 1f / 36f;
}
public static float Hash01(uint value)
{
value ^= value >> 16;
value *= 0x7FEB352Du;
value ^= value >> 15;
value *= 0x846CA68Bu;
value ^= value >> 16;
return value * 2.3283064e-10f;
}
public static float LatticeHash(int x, int y, uint seed, uint salt)
=> Hash01(((uint)x * 0x9E3779B9u) ^ ((uint)y * 0x85EBCA6Bu) ^ (seed * 0xC2B2AE35u) ^ salt);
public static float ValueNoise(float x, float y, uint seed, uint salt)
{
var ix = (int)Hlsl.Floor(x);
var iy = (int)Hlsl.Floor(y);
var fx = x - ix;
var fy = y - iy;
var sx = fx * fx * (3f - 2f * fx);
var sy = fy * fy * (3f - 2f * fy);
var v00 = LatticeHash(ix, iy, seed, salt);
var v10 = LatticeHash(ix + 1, iy, seed, salt);
var v01 = LatticeHash(ix, iy + 1, seed, salt);
var v11 = LatticeHash(ix + 1, iy + 1, seed, salt);
return Hlsl.Lerp(Hlsl.Lerp(v00, v10, sx), Hlsl.Lerp(v01, v11, sx), sy);
}
public static float FiberField(int gx, int gy, int seed)
{
var s = (uint)seed;
var value = 0.5f * ValueNoise(gx * 0.11f, gy * 0.31f, s, 0x1B873593u)
+ 0.3f * ValueNoise(gx * 0.37f, gy * 0.13f, s, 0xCC9E2D51u)
+ 0.2f * ValueNoise(gx * 0.53f, gy * 0.53f, s, 0xE6546B64u);
return Hlsl.Saturate((value - 0.3f) * 1.8f);
}
public static float PinField(int gx, int gy, int seed)
{
var value = ValueNoise(gx * 0.23f, gy * 0.23f, (uint)seed, 0x27D4EB2Fu);
return 1f - Hlsl.Abs(2f * value - 1f);
}
public static float AlumField(int gx, int gy, int seed)
{
var value = ValueNoise(gx * 0.17f, gy * 0.19f, (uint)seed, 0x165667B1u);
return Hlsl.SmoothStep(0.75f, 0.95f, value);
}
}
+555
ファイルの表示
@@ -0,0 +1,555 @@
using System.Runtime.InteropServices;
using ComputeSharp;
namespace InkDispersion;
internal sealed class InkDispersionPipeline : IDisposable
{
private readonly GraphicsDevice _device;
private readonly ReadWriteBuffer<int> _scratch;
private readonly ReadBackBuffer<int> _scratchReadBack;
private readonly int[] _boundsMinX;
private readonly int[] _boundsMinY;
private readonly int[] _boundsMaxX;
private readonly int[] _boundsMaxY;
private ReadWriteBuffer<float>? _distributionsA;
private ReadWriteBuffer<float>? _distributionsB;
private ReadWriteBuffer<float>? _deposit;
private ReadWriteBuffer<float>? _surface;
private ReadWriteBuffer<float>? _flowPigmentA;
private ReadWriteBuffer<float>? _flowPigmentB;
private ReadWriteBuffer<float>? _fixedPigment;
private ReadWriteBuffer<float>? _densityA;
private ReadWriteBuffer<float>? _densityB;
private ReadWriteBuffer<float>? _kappa;
private ReadWriteBuffer<float>? _wetness;
private ReadWriteBuffer<Float2>? _velocity;
private ReadWriteBuffer<int>? _inkStep;
private ReadWriteBuffer<int>? _reachMask;
private ReadWriteBuffer<int>? _jumpFloodA;
private ReadWriteBuffer<int>? _jumpFloodB;
private ReadBackBuffer<int>? _inkStepReadBack;
private int[]? _cachedInkStep;
private int _cachedMaxInkStep;
private int _cachedInkCount;
private StructureKey? _structureKey;
private int _gridWidth;
private int _gridHeight;
private ReadWriteTexture2D<Bgra32, Float4>? _packedSource;
private ReadWriteTexture2D<Bgra32, Float4>? _packedOutput;
private int _packedWidth;
private int _packedHeight;
private InkDispersionPipeline(GraphicsDevice device)
{
_device = device;
_scratch = device.AllocateReadWriteBuffer<int>(InkDispersionSettings.ScratchLength);
_scratchReadBack = device.AllocateReadBackBuffer<int>(InkDispersionSettings.ScratchLength);
_boundsMinX = new int[InkDispersionSettings.MaximumStepCount + 1];
_boundsMinY = new int[InkDispersionSettings.MaximumStepCount + 1];
_boundsMaxX = new int[InkDispersionSettings.MaximumStepCount + 1];
_boundsMaxY = new int[InkDispersionSettings.MaximumStepCount + 1];
}
public static InkDispersionPipeline? TryCreate()
{
try
{
return new InkDispersionPipeline(GraphicsDevice.GetDefault());
}
catch
{
return null;
}
}
public static InkDispersionPipeline? TryCreate(GraphicsDevice device)
{
try
{
return new InkDispersionPipeline(device);
}
catch
{
return null;
}
}
internal void WaitForCompletion()
{
_device.For(1, new FillIntShader(_scratch, 0, 0));
}
public void Process(ReadOnlySpan<int> source, Span<int> destination, int width, int height, in Parameters parameters)
{
var pixelCount = checked(width * height);
EnsureGridFor(width, height, parameters.Quality);
EnsurePackedTextures(width, height);
var sourceTexture = _packedSource!;
var outputTexture = _packedOutput!;
sourceTexture.CopyFrom(MemoryMarshal.Cast<int, Bgra32>(source[..pixelCount]));
using (ComputeContext context = _device.CreateComputeContext())
RecordFullPipeline(in context, sourceTexture, outputTexture, width, height, in parameters);
outputTexture.CopyTo(MemoryMarshal.Cast<int, Bgra32>(destination[..pixelCount]));
}
public void Process(
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteTexture2D<Bgra32, Float4> destination,
int width,
int height,
in Parameters parameters)
{
EnsureGridFor(width, height, parameters.Quality);
using ComputeContext context = _device.CreateComputeContext();
RecordFullPipeline(in context, source, destination, width, height, in parameters);
context.Submit();
}
internal void ProcessSharedAndWait(
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteTexture2D<Bgra32, Float4> destination,
int width,
int height,
in Parameters parameters)
{
EnsureGridFor(width, height, parameters.Quality);
using ComputeContext context = _device.CreateComputeContext();
RecordFullPipeline(in context, source, destination, width, height, in parameters);
}
internal bool Simulate(
ReadWriteTexture2D<Bgra32, Float4> source,
int canvasWidth,
int canvasHeight,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
in Parameters parameters)
{
EnsureGridFor(canvasWidth, canvasHeight, parameters.Quality);
var derived = Derive(canvasWidth, canvasHeight, in parameters);
using (ComputeContext context = _device.CreateComputeContext())
{
RecordSilhouetteStage(in context, source, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, in derived);
RecordMaskHashStage(in context);
}
_scratchReadBack.CopyFrom(_scratch);
var hashed = _scratchReadBack.Span;
var key = new StructureKey(
hashed[6],
hashed[7],
canvasWidth,
canvasHeight,
parameters.Quality,
parameters.Seed,
parameters.ReachPixels,
parameters.Water,
parameters.Fiber,
parameters.Sizing,
parameters.Viscosity,
parameters.Drying);
if (_structureKey == key)
return false;
using (ComputeContext context = _device.CreateComputeContext())
RecordFlowStage(in context, in derived, in parameters);
_scratchReadBack.CopyFrom(_scratch);
var wetStepReadBack = _inkStepReadBack!;
wetStepReadBack.CopyFrom(_inkStep!);
var scratch = _scratchReadBack.Span;
_cachedInkCount = scratch[0];
_cachedMaxInkStep = scratch[1];
wetStepReadBack.Span.CopyTo(_cachedInkStep!);
BuildBoundsPrefix();
_structureKey = key;
return true;
}
internal bool TryGetVisibleBounds(int canvasWidth, int canvasHeight, in Parameters parameters, out PixelRect rect)
{
rect = default;
if (_cachedInkCount <= 0 || _cachedMaxInkStep < 0)
return false;
var visible = parameters.Spread * (_cachedMaxInkStep + 1);
if (visible <= 0f)
return false;
var derived = Derive(canvasWidth, canvasHeight, in parameters);
var lastStep = Math.Min((int)MathF.Ceiling(visible) - 1, _cachedMaxInkStep);
if (lastStep < 0 || _boundsMinX[lastStep] == int.MaxValue)
return false;
var cellSize = derived.CellSize;
var padding = (int)MathF.Ceiling(cellSize) + 4;
var left = Math.Clamp(((int)(_boundsMinX[lastStep] * cellSize) - padding) & ~3, 0, canvasWidth);
var top = Math.Clamp(((int)(_boundsMinY[lastStep] * cellSize) - padding) & ~3, 0, canvasHeight);
var right = Math.Clamp((int)MathF.Ceiling((_boundsMaxX[lastStep] + 1) * cellSize) + padding, 0, canvasWidth);
var bottom = Math.Clamp((int)MathF.Ceiling((_boundsMaxY[lastStep] + 1) * cellSize) + padding, 0, canvasHeight);
var width = Math.Min((right - left + 3) & ~3, canvasWidth - left);
var height = Math.Min((bottom - top + 3) & ~3, canvasHeight - top);
if (width <= 0 || height <= 0)
return false;
rect = new PixelRect(left, top, width, height);
return true;
}
internal void RenderVisible(
ReadWriteTexture2D<Bgra32, Float4> output,
int canvasWidth,
int canvasHeight,
PixelRect rect,
in Parameters parameters)
{
var derived = Derive(canvasWidth, canvasHeight, in parameters);
using ComputeContext context = _device.CreateComputeContext();
RecordRenderStage(in context, output, rect, in derived, in parameters);
}
private void RecordFullPipeline(
in ComputeContext context,
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteTexture2D<Bgra32, Float4> output,
int width,
int height,
in Parameters parameters)
{
_structureKey = null;
var derived = Derive(width, height, in parameters);
RecordSilhouetteStage(in context, source, 0, 0, width, height, in derived);
RecordFlowStage(in context, in derived, in parameters);
RecordRenderStage(in context, output, new PixelRect(0, 0, width, height), in derived, in parameters);
}
private void RecordSilhouetteStage(
in ComputeContext context,
ReadWriteTexture2D<Bgra32, Float4> source,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
in DerivedValues derived)
{
context.For(_gridWidth, _gridHeight, new SilhouetteShader(
source, _deposit!, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, _gridWidth, _gridHeight, derived.CellSize));
context.Barrier(_deposit!);
}
private void RecordMaskHashStage(in ComputeContext context)
{
context.For(1, new MaskHashResetShader(_scratch));
context.Barrier(_scratch);
context.For(_gridWidth, _gridHeight, new MaskHashShader(_deposit!, _scratch, _gridWidth, _gridHeight));
context.Barrier(_scratch);
}
private void RecordFlowStage(
in ComputeContext context,
in DerivedValues derived,
in Parameters parameters)
{
var gridWidth = _gridWidth;
var gridHeight = _gridHeight;
context.For(1, new InitScratchShader(_scratch));
context.Barrier(_scratch);
context.For(gridWidth, gridHeight, new InitFieldShader(
_distributionsA!, _deposit!, _surface!, _flowPigmentA!, _fixedPigment!, _densityA!, _wetness!, _velocity!, _inkStep!,
gridWidth, gridHeight, derived.Deposit));
context.Barrier(_distributionsA!);
context.Barrier(_surface!);
context.Barrier(_flowPigmentA!);
context.Barrier(_fixedPigment!);
context.Barrier(_densityA!);
context.Barrier(_wetness!);
context.Barrier(_velocity!);
context.Barrier(_inkStep!);
context.For(gridWidth, gridHeight, new JumpFloodSeedShader(_deposit!, _jumpFloodA!, gridWidth, gridHeight));
context.Barrier(_jumpFloodA!);
var reading = _jumpFloodA!;
var writing = _jumpFloodB!;
var stepSize = 1;
var maxSide = Math.Max(gridWidth, gridHeight);
while (stepSize < maxSide)
stepSize <<= 1;
stepSize >>= 1;
while (stepSize >= 1)
{
context.For(gridWidth, gridHeight, new JumpFloodPassShader(reading, writing, gridWidth, gridHeight, stepSize));
context.Barrier(writing);
(reading, writing) = (writing, reading);
stepSize >>= 1;
}
context.For(gridWidth, gridHeight, new ReachMaskShader(reading, _reachMask!, gridWidth, gridHeight, derived.CellSize, derived.ReachPixels));
context.Barrier(_reachMask!);
var distributionsIn = _distributionsA!;
var distributionsOut = _distributionsB!;
var pigmentIn = _flowPigmentA!;
var pigmentOut = _flowPigmentB!;
for (var step = 0; step < derived.Steps; step++)
{
context.For(gridWidth, gridHeight, new SupplyShader(
distributionsIn, _surface!, pigmentIn, _densityA!, gridWidth, gridHeight));
context.Barrier(distributionsIn);
context.Barrier(_surface!);
context.Barrier(pigmentIn);
context.Barrier(_densityA!);
context.For(gridWidth, gridHeight, new KappaShader(
_densityA!, _fixedPigment!, _reachMask!, _kappa!, gridWidth, gridHeight,
parameters.Seed, derived.Fiber, derived.Sizing, derived.Viscosity, derived.Sigma));
context.Barrier(_kappa!);
context.For(gridWidth, gridHeight, new StreamCollideShader(
distributionsIn, distributionsOut, _kappa!, _reachMask!, _densityB!, _velocity!,
gridWidth, gridHeight, derived.Omega, derived.SurfaceEvaporation));
context.Barrier(distributionsOut);
context.Barrier(_densityB!);
context.Barrier(_velocity!);
context.For(gridWidth, gridHeight, new PigmentShader(
distributionsOut, _densityA!, _densityB!, _velocity!, pigmentIn, pigmentOut,
_fixedPigment!, _wetness!, _inkStep!, _reachMask!, _scratch,
gridWidth, gridHeight, step, parameters.Seed, derived.Fiber, derived.Viscosity));
context.Barrier(pigmentOut);
context.Barrier(_fixedPigment!);
context.Barrier(_wetness!);
context.Barrier(_inkStep!);
(distributionsIn, distributionsOut) = (distributionsOut, distributionsIn);
(pigmentIn, pigmentOut) = (pigmentOut, pigmentIn);
}
context.For(gridWidth, gridHeight, new FinalFixShader(pigmentIn, _fixedPigment!, gridWidth, gridHeight));
context.Barrier(_fixedPigment!);
context.Barrier(_scratch);
}
private void RecordRenderStage(
in ComputeContext context,
ReadWriteTexture2D<Bgra32, Float4> output,
PixelRect rect,
in DerivedValues derived,
in Parameters parameters)
{
context.For(rect.Width, rect.Height, new RenderShader(
_inkStep!, _fixedPigment!, _wetness!, _scratch, output,
rect.X, rect.Y, rect.Width, rect.Height, _gridWidth, _gridHeight,
derived.CellSize, Math.Clamp(parameters.Spread, 0f, 1f),
Math.Clamp(parameters.Density, 0f, 1f), Math.Clamp(parameters.Grain, 0f, 1f),
parameters.ColorR, parameters.ColorG, parameters.ColorB, parameters.Seed));
}
private void BuildBoundsPrefix()
{
var maxWetStep = Math.Clamp(_cachedMaxInkStep, -1, InkDispersionSettings.MaximumStepCount);
_cachedMaxInkStep = maxWetStep;
if (maxWetStep < 0)
return;
for (var step = 0; step <= maxWetStep; step++)
{
_boundsMinX[step] = int.MaxValue;
_boundsMinY[step] = int.MaxValue;
_boundsMaxX[step] = int.MinValue;
_boundsMaxY[step] = int.MinValue;
}
var wetStep = _cachedInkStep!;
var gridWidth = _gridWidth;
for (var index = 0; index < wetStep.Length; index++)
{
var step = wetStep[index];
if (step < 0 || step > maxWetStep)
continue;
var x = index % gridWidth;
var y = index / gridWidth;
if (x < _boundsMinX[step])
_boundsMinX[step] = x;
if (x > _boundsMaxX[step])
_boundsMaxX[step] = x;
if (y < _boundsMinY[step])
_boundsMinY[step] = y;
if (y > _boundsMaxY[step])
_boundsMaxY[step] = y;
}
for (var step = 1; step <= maxWetStep; step++)
{
_boundsMinX[step] = Math.Min(_boundsMinX[step], _boundsMinX[step - 1]);
_boundsMinY[step] = Math.Min(_boundsMinY[step], _boundsMinY[step - 1]);
_boundsMaxX[step] = Math.Max(_boundsMaxX[step], _boundsMaxX[step - 1]);
_boundsMaxY[step] = Math.Max(_boundsMaxY[step], _boundsMaxY[step - 1]);
}
}
private DerivedValues Derive(int width, int height, in Parameters parameters)
{
var settings = InkDispersionSettings.GetQuality(parameters.Quality);
var (_, _, cellSize) = InkDispersionSettings.GetGridSize(width, height, settings.GridResolution);
var reachPixels = Math.Max(parameters.ReachPixels, cellSize);
var reachCells = reachPixels / cellSize;
return new DerivedValues(
cellSize,
InkDispersionSettings.GetStepCount(reachCells, settings.MaxSteps),
InkDispersionSettings.GetDeposit(parameters.Water),
Math.Clamp(parameters.Fiber, 0f, 1f),
Math.Clamp(parameters.Sizing, 0f, 1f),
Math.Clamp(parameters.Viscosity, 0f, 1f),
InkDispersionSettings.GetOmega(parameters.Viscosity),
InkDispersionSettings.GetPinningSigma(parameters.Sizing),
InkDispersionSettings.GetSurfaceEvaporation(parameters.Drying),
reachPixels);
}
private void EnsureGridFor(int width, int height, InkDispersionQuality quality)
{
var settings = InkDispersionSettings.GetQuality(quality);
var (gridWidth, gridHeight, _) = InkDispersionSettings.GetGridSize(width, height, settings.GridResolution);
EnsureGrid(gridWidth, gridHeight);
}
private void EnsureGrid(int gridWidth, int gridHeight)
{
if (_gridWidth == gridWidth && _gridHeight == gridHeight)
return;
DisposeGridBuffers();
var gridLength = gridWidth * gridHeight;
var distributionLength = gridLength * 9;
_distributionsA = _device.AllocateReadWriteBuffer<float>(distributionLength);
_distributionsB = _device.AllocateReadWriteBuffer<float>(distributionLength);
_deposit = _device.AllocateReadWriteBuffer<float>(gridLength);
_surface = _device.AllocateReadWriteBuffer<float>(gridLength);
_flowPigmentA = _device.AllocateReadWriteBuffer<float>(gridLength);
_flowPigmentB = _device.AllocateReadWriteBuffer<float>(gridLength);
_fixedPigment = _device.AllocateReadWriteBuffer<float>(gridLength);
_densityA = _device.AllocateReadWriteBuffer<float>(gridLength);
_densityB = _device.AllocateReadWriteBuffer<float>(gridLength);
_kappa = _device.AllocateReadWriteBuffer<float>(gridLength);
_wetness = _device.AllocateReadWriteBuffer<float>(gridLength);
_velocity = _device.AllocateReadWriteBuffer<Float2>(gridLength);
_inkStep = _device.AllocateReadWriteBuffer<int>(gridLength);
_reachMask = _device.AllocateReadWriteBuffer<int>(gridLength);
_jumpFloodA = _device.AllocateReadWriteBuffer<int>(gridLength);
_jumpFloodB = _device.AllocateReadWriteBuffer<int>(gridLength);
_inkStepReadBack = _device.AllocateReadBackBuffer<int>(gridLength);
_cachedInkStep = new int[gridLength];
_cachedMaxInkStep = -1;
_cachedInkCount = 0;
_gridWidth = gridWidth;
_gridHeight = gridHeight;
}
private void EnsurePackedTextures(int width, int height)
{
if (_packedWidth == width && _packedHeight == height)
return;
_packedSource?.Dispose();
_packedOutput?.Dispose();
_packedSource = _device.AllocateReadWriteTexture2D<Bgra32, Float4>(width, height);
_packedOutput = _device.AllocateReadWriteTexture2D<Bgra32, Float4>(width, height);
_packedWidth = width;
_packedHeight = height;
}
private void DisposeGridBuffers()
{
_distributionsA?.Dispose();
_distributionsB?.Dispose();
_deposit?.Dispose();
_surface?.Dispose();
_flowPigmentA?.Dispose();
_flowPigmentB?.Dispose();
_fixedPigment?.Dispose();
_densityA?.Dispose();
_densityB?.Dispose();
_kappa?.Dispose();
_wetness?.Dispose();
_velocity?.Dispose();
_inkStep?.Dispose();
_reachMask?.Dispose();
_jumpFloodA?.Dispose();
_jumpFloodB?.Dispose();
_inkStepReadBack?.Dispose();
_distributionsA = null;
_distributionsB = null;
_deposit = null;
_surface = null;
_flowPigmentA = null;
_flowPigmentB = null;
_fixedPigment = null;
_densityA = null;
_densityB = null;
_kappa = null;
_wetness = null;
_velocity = null;
_inkStep = null;
_reachMask = null;
_jumpFloodA = null;
_jumpFloodB = null;
_inkStepReadBack = null;
_cachedInkStep = null;
_cachedMaxInkStep = -1;
_cachedInkCount = 0;
_structureKey = null;
_gridWidth = 0;
_gridHeight = 0;
}
public void Dispose()
{
DisposeGridBuffers();
_packedSource?.Dispose();
_packedOutput?.Dispose();
_packedSource = null;
_packedOutput = null;
_packedWidth = 0;
_packedHeight = 0;
_scratchReadBack.Dispose();
_scratch.Dispose();
}
internal readonly record struct PixelRect(int X, int Y, int Width, int Height);
private readonly record struct StructureKey(
int MaskHashSum,
int MaskHashMix,
int CanvasWidth,
int CanvasHeight,
InkDispersionQuality Quality,
int Seed,
float ReachPixels,
float Water,
float Fiber,
float Sizing,
float Viscosity,
float Drying);
private readonly record struct DerivedValues(
float CellSize,
int Steps,
float Deposit,
float Fiber,
float Sizing,
float Viscosity,
float Omega,
float Sigma,
float SurfaceEvaporation,
float ReachPixels);
internal readonly record struct Parameters(
InkDispersionQuality Quality,
float Spread,
float Water,
float Fiber,
float Sizing,
float Viscosity,
float Drying,
float ReachPixels,
float Density,
float Grain,
float ColorR,
float ColorG,
float ColorB,
int Seed);
}
+13
ファイルの表示
@@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;
namespace InkDispersion;
public enum InkDispersionQuality
{
[Display(Name = nameof(Texts.QualityBalanced), Description = nameof(Texts.QualityBalancedDescription), ResourceType = typeof(Texts))]
Balanced,
[Display(Name = nameof(Texts.QualityHigh), Description = nameof(Texts.QualityHighDescription), ResourceType = typeof(Texts))]
High,
[Display(Name = nameof(Texts.QualityUltra), Description = nameof(Texts.QualityUltraDescription), ResourceType = typeof(Texts))]
Ultra,
}
+85
ファイルの表示
@@ -0,0 +1,85 @@
namespace InkDispersion;
internal static class InkDispersionSettings
{
public const float PaperCapacity = 1f;
public const float MinimumDeposit = 0.4f;
public const float MaximumDeposit = 3.0f;
public const float MinimumOmega = 0.5f;
public const float MaximumOmega = 1.5f;
public const float AdvectionAlpha = 0.35f;
public const float MaximumLatticeSpeed = 0.3f;
public const float WetEpsilon = 0.0001f;
public const float DepositThreshold = 0.02f;
public const float KappaBase = 0.02f;
public const float KappaFiber = 0.55f;
public const float KappaAlum = 0.5f;
public const float KappaGlue = 0.35f;
public const float KappaFixture = 0.4f;
public const float KappaMax = 0.95f;
public const float PinnedKappaMarker = 2f;
public const float SigmaFloor = 0.0015f;
public const float MaximumSigma = 0.05f;
public const float DiagonalSigmaFactor = 1.4142135f;
public const float MaximumSurfaceEvaporation = 0.005f;
public const float BoundaryEvaporation = 0.00005f;
public const float HindranceBase = 0.25f;
public const float HindranceFiber = 0.45f;
public const float HindranceSpeed = 0.004f;
public const float FixtureBase = 0.0005f;
public const float FixtureDryness = 0.35f;
public const float FixtureGlue = 0.5f;
public const float InkAbsorbance = 2.5f;
public const float InkEpsilon = 0.008f;
public const float RougherScale = 0.06f;
public const float RougherBias = 0.01f;
public const float CoverageGain = 12f;
public const float CoverageSoftness = 0.05f;
public const float HairStrength = 0.7f;
public const float StepsPerCell = 10f;
public const int MinimumStepCount = 192;
public const int BirthSentinel = 268435456;
public const int MinimumGridSize = 4;
public const int MaximumCanvasSize = 8192;
public const int MaximumStepCount = 1440;
public const int MarginPadding = 64;
public const int ScratchLength = 8;
public const int ScratchWetCount = 0;
public const int ScratchMaxWetStep = 1;
public const int ScratchMaskHashSum = 6;
public const int ScratchMaskHashMix = 7;
public static QualitySettings GetQuality(InkDispersionQuality quality)
=> quality switch
{
InkDispersionQuality.Balanced => new QualitySettings(160, 720),
InkDispersionQuality.Ultra => new QualitySettings(288, 1440),
_ => new QualitySettings(224, 1080),
};
public static (int Width, int Height, float CellSize) GetGridSize(int width, int height, int resolution)
{
var longSide = Math.Max(Math.Max(width, height), 1);
var cellSize = longSide / (float)Math.Max(Math.Min(resolution, longSide), MinimumGridSize);
var gridWidth = Math.Max((int)Math.Ceiling(width / cellSize) + 1, MinimumGridSize);
var gridHeight = Math.Max((int)Math.Ceiling(height / cellSize) + 1, MinimumGridSize);
return (gridWidth, gridHeight, cellSize);
}
public static int GetStepCount(float reachCells, int maxSteps)
=> Math.Clamp((int)(reachCells * StepsPerCell) + 128, MinimumStepCount, maxSteps);
public static float GetDeposit(float water)
=> MinimumDeposit + Math.Clamp(water, 0f, 1f) * (MaximumDeposit - MinimumDeposit);
public static float GetOmega(float viscosity)
=> MaximumOmega - Math.Clamp(viscosity, 0f, 1f) * (MaximumOmega - MinimumOmega);
public static float GetPinningSigma(float sizing)
=> SigmaFloor + Math.Clamp(sizing, 0f, 1f) * MaximumSigma;
public static float GetSurfaceEvaporation(float drying)
=> Math.Clamp(drying, 0f, 1f) * MaximumSurfaceEvaporation;
internal readonly record struct QualitySettings(int GridResolution, int MaxSteps);
}
+50
ファイルの表示
@@ -0,0 +1,50 @@
using System.Windows;
using GitHubUpdateNotifier;
using YukkuriMovieMaker.Plugin.Update;
using Notifier = GitHubUpdateNotifier.GitHubUpdateNotifier;
namespace InkDispersion;
internal static class InkDispersionUpdateNotifier
{
private const string Owner = "routersys";
private const string Repository = "YMM4-InkDispersion";
private static int _started;
public static void EnsureCheckedOnce()
{
if (Interlocked.Exchange(ref _started, 1) != 0)
return;
_ = RunAsync();
}
private static async Task RunAsync()
{
try
{
var options = new UpdateNotifierOptions
{
CurrentVersion = PluginVersion.FromAssemblyInformationalVersion(typeof(InkDispersionUpdateNotifier)),
IncludePrerelease = false,
MessageFormatter = FormatMessage,
NotificationHandler = ShowNotificationAsync,
};
await new Notifier(Owner, Repository, options).NotifyAsync().ConfigureAwait(false);
}
catch
{
}
}
private static string FormatMessage(UpdateInfo update)
=> string.Format(Texts.UpdateAvailableMessage, update.TagName) + Environment.NewLine + update.ReleaseUrl;
private static Task ShowNotificationAsync(UpdateNotification notification, CancellationToken cancellationToken)
{
var application = Application.Current;
if (application is null)
return Task.CompletedTask;
return application.Dispatcher.InvokeAsync(() =>
MessageBox.Show(notification.Message, Texts.InkDispersion, MessageBoxButton.OK, MessageBoxImage.Information)).Task;
}
}
+6
ファイルの表示
@@ -0,0 +1,6 @@
namespace InkDispersion;
internal static class ShaderResourceUri
{
public static Uri Get(string shaderName) => new($"pack://application:,,,/InkDispersion;component/Shaders/{shaderName}.cso", UriKind.Absolute);
}
+29
ファイルの表示
@@ -0,0 +1,29 @@
Texture2D SourceTexture : register(t0);
SamplerState SourceSampler : register(s0);
Texture2D InkTexture : register(t1);
SamplerState InkSampler : register(s1);
cbuffer Constants : register(b0)
{
float amount : packoffset(c0.x);
float pad0 : packoffset(c0.y);
float pad1 : packoffset(c0.z);
float pad2 : packoffset(c0.w);
};
float4 main(
float4 position : SV_POSITION,
float4 scenePosition : SCENE_POSITION,
float4 uv0 : TEXCOORD0,
float4 uv1 : TEXCOORD1
) : SV_TARGET
{
float4 source = SourceTexture.SampleLevel(SourceSampler, uv0.xy, 0);
if (amount <= 0.0)
return source;
float4 ink = InkTexture.SampleLevel(InkSampler, uv1.xy, 0);
ink.rgb = min(ink.rgb, ink.a.xxx);
ink *= amount;
return ink + source * (1.0 - ink.a);
}
+10
ファイルの表示
@@ -0,0 +1,10 @@
using YukkuriMovieMaker.Generator;
namespace InkDispersion
{
[AutoGenLocalizer]
partial class Texts
{
}
}
+41
ファイルの表示
@@ -0,0 +1,41 @@
Key,Parameter,ja-jp,en-us,zh-cn,zh-tw,ko-kr,es-es,ar-sa,id-id
InkDispersion,,墨拡散,Ink Dispersion,墨扩散,墨擴散,먹 번짐,Dispersión de tinta,انتشار الحبر,Dispersi Tinta
BasicGroup,,基本,Basic,基本,基本,기본,Básico,أساسي,Dasar
FlowGroup,,浸透,Flow,渗透,滲透,침투,Flujo,التدفق,Aliran
AppearanceGroup,,描画,Appearance,绘制,繪製,묘화,Apariencia,المظهر,Tampilan
Amount,,強さ,Amount,强度,強度,강도,Intensidad,الشدة,Intensitas
AmountDescription,,墨の合成量です,Blend amount of the ink over the source,墨与源图像的混合量,墨與源圖像的混合量,먹의 합성량입니다,Cantidad de mezcla de la tinta sobre la imagen,مقدار مزج الحبر فوق الصورة,Jumlah pencampuran tinta di atas citra
Spread,,拡散度,Spread,扩散度,擴散度,확산도,Difusión,درجة الانتشار,Penyebaran
SpreadDescription,,にじみの進行度です。素材から墨がにじみ広がっていきます,Progress of the dispersion. The ink bleeds outward from the source,渗化的进行程度。墨从素材向外渗开,滲化的進行程度。墨從素材向外滲開,번짐의 진행도입니다. 소재에서 먹이 번져 나갑니다,Progreso de la dispersión. La tinta se extiende desde la imagen,مدى تقدم الانتشار. يتسرب الحبر من الصورة نحو الخارج,Kemajuan dispersi. Tinta merembes keluar dari sumber
Quality,,品質,Quality,品质,品質,품질,Calidad,الجودة,Kualitas
QualityDescription,,浸透格子の解像度と浸透ステップ数を選びます,Selects the flow lattice resolution and step counts,选择渗透网格分辨率与步数,選擇滲透網格解析度與步數,침투 격자 해상도와 스텝 수를 선택합니다,Selecciona la resolución de la retícula de flujo y el número de pasos,يحدد دقة شبكة التدفق وعدد الخطوات,Memilih resolusi kisi aliran dan jumlah langkah
Water,,水量,Water,水量,水量,수량,Agua,كمية الماء,Air
WaterDescription,,素材に置く水の量です。多いほど遠くまでにじみます,Amount of water deposited on the source. More water bleeds farther,置于素材上的水量。越多渗得越远,置於素材上的水量。越多滲得越遠,소재에 놓는 물의 양입니다. 많을수록 멀리 번집니다,Cantidad de agua depositada sobre la imagen. Más agua se extiende más lejos,كمية الماء الموضوعة على الصورة. كلما زادت انتشر الحبر أبعد,Jumlah air yang diletakkan pada sumber. Semakin banyak semakin jauh merembes
Reach,,到達距離,Reach,到达距离,到達距離,도달 거리,Alcance,المدى,Jangkauan
ReachDescription,,縁から墨が届く距離の上限です。素材の長辺に対する割合で指定します,Upper limit of the distance the ink reaches from the edge as a ratio of the longer side of the source,墨从边缘到达距离的上限。以素材长边的比例指定,墨從邊緣到達距離的上限。以素材長邊的比例指定,가장자리에서 먹이 도달하는 거리의 상한입니다. 소재 긴 변에 대한 비율로 지정합니다,Límite superior de la distancia que alcanza la tinta desde el borde como proporción del lado más largo de la fuente,الحد الأعلى للمسافة التي يصلها الحبر من الحافة كنسبة من الضلع الأطول للمصدر,Batas atas jarak yang dicapai tinta dari tepi sebagai rasio sisi terpanjang sumber
Fiber,,繊維,Fiber,纤维,纖維,섬유,Fibra,الألياف,Serat
FiberDescription,,紙の繊維むらの強さです。高いほど枝分かれした流れになります,Strength of the paper fiber irregularity. Higher values branch the flow,纸张纤维不均的强度。数值越高越呈分支状流动,紙張纖維不均的強度。數值越高越呈分支狀流動,종이 섬유 불균일의 강도입니다. 높을수록 흐름이 가지를 칩니다,Intensidad de la irregularidad de las fibras del papel. Valores altos ramifican el flujo,شدة عدم انتظام ألياف الورق. القيم الأعلى تجعل التدفق يتفرع,Kekuatan ketidakrataan serat kertas. Nilai tinggi membuat aliran bercabang
Sizing,,にじみ止め,Sizing,矾水,礬水,번짐 방지,Apresto,الشب,Sizing
SizingDescription,,礬水による浸透の妨げです。高いほど縁が荒れて広がりが抑えられます,Alum sizing that impedes the flow. Higher values roughen the edge and limit the spread,矾水对渗透的阻碍。数值越高边缘越粗糙且扩散越受限,礬水對滲透的阻礙。數值越高邊緣越粗糙且擴散越受限,반수에 의한 침투 방해입니다. 높을수록 가장자리가 거칠어지고 번짐이 억제됩니다,Apresto de alumbre que impide el flujo. Valores altos endurecen el borde y limitan la extensión,شب يعيق التدفق. القيم الأعلى تخشن الحافة وتحد من الانتشار,Sizing tawas yang menghambat aliran. Nilai tinggi mengasarkan tepi dan membatasi penyebaran
Viscosity,,粘度,Viscosity,粘度,黏度,점도,Viscosidad,اللزوجة,Viskositas
ViscosityDescription,,膠による墨の粘りです。高いほど流れが遅く留まりやすくなります,Glue viscosity of the ink. Higher values slow the flow and keep the ink in place,胶带来的墨的黏性。数值越高流动越慢越易停留,膠帶來的墨的黏性。數值越高流動越慢越易停留,아교에 의한 먹의 점성입니다. 높을수록 흐름이 느려지고 머무르기 쉬워집니다,Viscosidad de la tinta por la cola. Valores altos ralentizan el flujo y fijan la tinta,لزوجة الحبر بسبب الغراء. القيم الأعلى تبطئ التدفق وتثبت الحبر,Kekentalan tinta karena lem. Nilai tinggi memperlambat aliran dan menahan tinta
Drying,,乾燥,Drying,干燥,乾燥,건조,Secado,الجفاف,Pengeringan
DryingDescription,,水の蒸発の速さです。高いほど早く乾いて縁が濃くなります,Evaporation speed of the water. Higher values dry faster and darken the edge,水的蒸发速度。数值越高干得越快且边缘越浓,水的蒸發速度。數值越高乾得越快且邊緣越濃,물의 증발 속도입니다. 높을수록 빨리 말라 가장자리가 진해집니다,Velocidad de evaporación del agua. Valores altos secan antes y oscurecen el borde,سرعة تبخر الماء. القيم الأعلى تجفف أسرع وتغمق الحافة,Kecepatan penguapan air. Nilai tinggi mengering lebih cepat dan menggelapkan tepi
Seed,,シード,Seed,种子,種子,시드,Semilla,البذرة,Seed
SeedDescription,,紙の繊維とにじみの形を決める固定値です,A fixed value that determines the paper fibers and the shape of the dispersion,决定纸张纤维与渗化形状的固定值,決定紙張纖維與滲化形狀的固定值,종이 섬유와 번짐의 형태를 결정하는 고정값입니다,Valor fijo que determina las fibras del papel y la forma de la dispersión,قيمة ثابتة تحدد ألياف الورق وشكل الانتشار,Nilai tetap yang menentukan serat kertas dan bentuk dispersi
Density,,濃度,Density,浓度,濃度,농도,Densidad,التركيز,Kepekatan
DensityDescription,,墨の濃さです,Darkness of the ink,墨的浓度,墨的濃度,먹의 진하기입니다,Oscuridad de la tinta,درجة تركيز الحبر,Kepekatan tinta
Grain,,かすれ,Grain,飞白,飛白,갈필,Trazo seco,التحبب,Guratan Kering
GrainDescription,,紙目によるかすれと縁の荒れの強さです,Strength of the dry-brush grain and the edge roughening from the paper texture,纸纹带来的飞白与边缘粗糙的强度,紙紋帶來的飛白與邊緣粗糙的強度,종이결에 의한 갈필과 가장자리 거칠기의 강도입니다,Intensidad del trazo seco y del borde áspero por la textura del papel,شدة التحبب وخشونة الحافة الناتجة عن نسيج الورق,Kekuatan guratan kering dan kekasaran tepi dari tekstur kertas
InkColor,,墨色,Color,墨色,墨色,먹색,Color,لون الحبر,Warna
InkColorDescription,,墨の色です,Color of the ink,墨的颜色,墨的顏色,먹의 색입니다,Color de la tinta,لون الحبر,Warna tinta
QualityBalanced,,標準,Balanced,标准,標準,표준,Estándar,قياسي,Standar
QualityBalancedDescription,,格子解像度とステップ数を抑えた設定です,Uses reduced lattice resolution and step counts,降低网格分辨率与步数的设置,降低網格解析度與步數的設定,격자 해상도와 스텝 수를 줄인 설정입니다,Configuración con resolución de retícula y pasos reducidos,إعداد بدقة شبكة وعدد خطوات مخفضين,Pengaturan dengan resolusi kisi dan langkah yang dikurangi
QualityHigh,,高品質,High,高品质,高品質,고품질,Alta,عالية,Tinggi
QualityHighDescription,,品質と処理量の基準設定です,The reference balance of quality and cost,品质与处理量的基准设置,品質與處理量的基準設定,품질과 처리량의 기준 설정입니다,Configuración de referencia entre calidad y coste,الإعداد المرجعي للتوازن بين الجودة والتكلفة,Pengaturan acuan antara kualitas dan beban proses
QualityUltra,,最高品質,Ultra,最高品质,最高品質,최고 품질,Máxima,قصوى,Ultra
QualityUltraDescription,,最大の格子解像度とステップ数を使用します,Uses the largest lattice resolution and step counts,使用最大的网格分辨率与步数,使用最大的網格解析度與步數,최대 격자 해상도와 스텝 수를 사용합니다,Usa la mayor resolución de retícula y el mayor número de pasos,يستخدم أكبر دقة شبكة وأكبر عدد من الخطوات,Menggunakan resolusi kisi dan jumlah langkah terbesar
TagInk,,墨,Ink,墨,墨,먹,Tinta,حبر,Tinta
TagBlot,,にじみ,Blot,渗化,滲化,번짐,Mancha,تسرب,Rembesan
TagJapanese,,和風,Japanese style,和风,和風,일본풍,Estilo japonés,النمط الياباني,Gaya Jepang
UpdateAvailableMessage,,新しいバージョン {0} が公開されています。,A new version {0} is available.,新版本 {0} 已发布。,新版本 {0} 已發布。,새 버전 {0}이(가) 공개되었습니다.,La nueva versión {0} ya está disponible.,تم إصدار نسخة جديدة {0}.,Versi baru {0} telah dirilis.
1 Key Parameter ja-jp en-us zh-cn zh-tw ko-kr es-es ar-sa id-id
2 InkDispersion 墨拡散 Ink Dispersion 墨扩散 墨擴散 먹 번짐 Dispersión de tinta انتشار الحبر Dispersi Tinta
3 BasicGroup 基本 Basic 基本 基本 기본 Básico أساسي Dasar
4 FlowGroup 浸透 Flow 渗透 滲透 침투 Flujo التدفق Aliran
5 AppearanceGroup 描画 Appearance 绘制 繪製 묘화 Apariencia المظهر Tampilan
6 Amount 強さ Amount 强度 強度 강도 Intensidad الشدة Intensitas
7 AmountDescription 墨の合成量です Blend amount of the ink over the source 墨与源图像的混合量 墨與源圖像的混合量 먹의 합성량입니다 Cantidad de mezcla de la tinta sobre la imagen مقدار مزج الحبر فوق الصورة Jumlah pencampuran tinta di atas citra
8 Spread 拡散度 Spread 扩散度 擴散度 확산도 Difusión درجة الانتشار Penyebaran
9 SpreadDescription にじみの進行度です。素材から墨がにじみ広がっていきます Progress of the dispersion. The ink bleeds outward from the source 渗化的进行程度。墨从素材向外渗开 滲化的進行程度。墨從素材向外滲開 번짐의 진행도입니다. 소재에서 먹이 번져 나갑니다 Progreso de la dispersión. La tinta se extiende desde la imagen مدى تقدم الانتشار. يتسرب الحبر من الصورة نحو الخارج Kemajuan dispersi. Tinta merembes keluar dari sumber
10 Quality 品質 Quality 品质 品質 품질 Calidad الجودة Kualitas
11 QualityDescription 浸透格子の解像度と浸透ステップ数を選びます Selects the flow lattice resolution and step counts 选择渗透网格分辨率与步数 選擇滲透網格解析度與步數 침투 격자 해상도와 스텝 수를 선택합니다 Selecciona la resolución de la retícula de flujo y el número de pasos يحدد دقة شبكة التدفق وعدد الخطوات Memilih resolusi kisi aliran dan jumlah langkah
12 Water 水量 Water 水量 水量 수량 Agua كمية الماء Air
13 WaterDescription 素材に置く水の量です。多いほど遠くまでにじみます Amount of water deposited on the source. More water bleeds farther 置于素材上的水量。越多渗得越远 置於素材上的水量。越多滲得越遠 소재에 놓는 물의 양입니다. 많을수록 멀리 번집니다 Cantidad de agua depositada sobre la imagen. Más agua se extiende más lejos كمية الماء الموضوعة على الصورة. كلما زادت انتشر الحبر أبعد Jumlah air yang diletakkan pada sumber. Semakin banyak semakin jauh merembes
14 Reach 到達距離 Reach 到达距离 到達距離 도달 거리 Alcance المدى Jangkauan
15 ReachDescription 縁から墨が届く距離の上限です。素材の長辺に対する割合で指定します Upper limit of the distance the ink reaches from the edge as a ratio of the longer side of the source 墨从边缘到达距离的上限。以素材长边的比例指定 墨從邊緣到達距離的上限。以素材長邊的比例指定 가장자리에서 먹이 도달하는 거리의 상한입니다. 소재 긴 변에 대한 비율로 지정합니다 Límite superior de la distancia que alcanza la tinta desde el borde como proporción del lado más largo de la fuente الحد الأعلى للمسافة التي يصلها الحبر من الحافة كنسبة من الضلع الأطول للمصدر Batas atas jarak yang dicapai tinta dari tepi sebagai rasio sisi terpanjang sumber
16 Fiber 繊維 Fiber 纤维 纖維 섬유 Fibra الألياف Serat
17 FiberDescription 紙の繊維むらの強さです。高いほど枝分かれした流れになります Strength of the paper fiber irregularity. Higher values branch the flow 纸张纤维不均的强度。数值越高越呈分支状流动 紙張纖維不均的強度。數值越高越呈分支狀流動 종이 섬유 불균일의 강도입니다. 높을수록 흐름이 가지를 칩니다 Intensidad de la irregularidad de las fibras del papel. Valores altos ramifican el flujo شدة عدم انتظام ألياف الورق. القيم الأعلى تجعل التدفق يتفرع Kekuatan ketidakrataan serat kertas. Nilai tinggi membuat aliran bercabang
18 Sizing にじみ止め Sizing 矾水 礬水 번짐 방지 Apresto الشب Sizing
19 SizingDescription 礬水による浸透の妨げです。高いほど縁が荒れて広がりが抑えられます Alum sizing that impedes the flow. Higher values roughen the edge and limit the spread 矾水对渗透的阻碍。数值越高边缘越粗糙且扩散越受限 礬水對滲透的阻礙。數值越高邊緣越粗糙且擴散越受限 반수에 의한 침투 방해입니다. 높을수록 가장자리가 거칠어지고 번짐이 억제됩니다 Apresto de alumbre que impide el flujo. Valores altos endurecen el borde y limitan la extensión شب يعيق التدفق. القيم الأعلى تخشن الحافة وتحد من الانتشار Sizing tawas yang menghambat aliran. Nilai tinggi mengasarkan tepi dan membatasi penyebaran
20 Viscosity 粘度 Viscosity 粘度 黏度 점도 Viscosidad اللزوجة Viskositas
21 ViscosityDescription 膠による墨の粘りです。高いほど流れが遅く留まりやすくなります Glue viscosity of the ink. Higher values slow the flow and keep the ink in place 胶带来的墨的黏性。数值越高流动越慢越易停留 膠帶來的墨的黏性。數值越高流動越慢越易停留 아교에 의한 먹의 점성입니다. 높을수록 흐름이 느려지고 머무르기 쉬워집니다 Viscosidad de la tinta por la cola. Valores altos ralentizan el flujo y fijan la tinta لزوجة الحبر بسبب الغراء. القيم الأعلى تبطئ التدفق وتثبت الحبر Kekentalan tinta karena lem. Nilai tinggi memperlambat aliran dan menahan tinta
22 Drying 乾燥 Drying 干燥 乾燥 건조 Secado الجفاف Pengeringan
23 DryingDescription 水の蒸発の速さです。高いほど早く乾いて縁が濃くなります Evaporation speed of the water. Higher values dry faster and darken the edge 水的蒸发速度。数值越高干得越快且边缘越浓 水的蒸發速度。數值越高乾得越快且邊緣越濃 물의 증발 속도입니다. 높을수록 빨리 말라 가장자리가 진해집니다 Velocidad de evaporación del agua. Valores altos secan antes y oscurecen el borde سرعة تبخر الماء. القيم الأعلى تجفف أسرع وتغمق الحافة Kecepatan penguapan air. Nilai tinggi mengering lebih cepat dan menggelapkan tepi
24 Seed シード Seed 种子 種子 시드 Semilla البذرة Seed
25 SeedDescription 紙の繊維とにじみの形を決める固定値です A fixed value that determines the paper fibers and the shape of the dispersion 决定纸张纤维与渗化形状的固定值 決定紙張纖維與滲化形狀的固定值 종이 섬유와 번짐의 형태를 결정하는 고정값입니다 Valor fijo que determina las fibras del papel y la forma de la dispersión قيمة ثابتة تحدد ألياف الورق وشكل الانتشار Nilai tetap yang menentukan serat kertas dan bentuk dispersi
26 Density 濃度 Density 浓度 濃度 농도 Densidad التركيز Kepekatan
27 DensityDescription 墨の濃さです Darkness of the ink 墨的浓度 墨的濃度 먹의 진하기입니다 Oscuridad de la tinta درجة تركيز الحبر Kepekatan tinta
28 Grain かすれ Grain 飞白 飛白 갈필 Trazo seco التحبب Guratan Kering
29 GrainDescription 紙目によるかすれと縁の荒れの強さです Strength of the dry-brush grain and the edge roughening from the paper texture 纸纹带来的飞白与边缘粗糙的强度 紙紋帶來的飛白與邊緣粗糙的強度 종이결에 의한 갈필과 가장자리 거칠기의 강도입니다 Intensidad del trazo seco y del borde áspero por la textura del papel شدة التحبب وخشونة الحافة الناتجة عن نسيج الورق Kekuatan guratan kering dan kekasaran tepi dari tekstur kertas
30 InkColor 墨色 Color 墨色 墨色 먹색 Color لون الحبر Warna
31 InkColorDescription 墨の色です Color of the ink 墨的颜色 墨的顏色 먹의 색입니다 Color de la tinta لون الحبر Warna tinta
32 QualityBalanced 標準 Balanced 标准 標準 표준 Estándar قياسي Standar
33 QualityBalancedDescription 格子解像度とステップ数を抑えた設定です Uses reduced lattice resolution and step counts 降低网格分辨率与步数的设置 降低網格解析度與步數的設定 격자 해상도와 스텝 수를 줄인 설정입니다 Configuración con resolución de retícula y pasos reducidos إعداد بدقة شبكة وعدد خطوات مخفضين Pengaturan dengan resolusi kisi dan langkah yang dikurangi
34 QualityHigh 高品質 High 高品质 高品質 고품질 Alta عالية Tinggi
35 QualityHighDescription 品質と処理量の基準設定です The reference balance of quality and cost 品质与处理量的基准设置 品質與處理量的基準設定 품질과 처리량의 기준 설정입니다 Configuración de referencia entre calidad y coste الإعداد المرجعي للتوازن بين الجودة والتكلفة Pengaturan acuan antara kualitas dan beban proses
36 QualityUltra 最高品質 Ultra 最高品质 最高品質 최고 품질 Máxima قصوى Ultra
37 QualityUltraDescription 最大の格子解像度とステップ数を使用します Uses the largest lattice resolution and step counts 使用最大的网格分辨率与步数 使用最大的網格解析度與步數 최대 격자 해상도와 스텝 수를 사용합니다 Usa la mayor resolución de retícula y el mayor número de pasos يستخدم أكبر دقة شبكة وأكبر عدد من الخطوات Menggunakan resolusi kisi dan jumlah langkah terbesar
38 TagInk 墨 Ink 墨 墨 먹 Tinta حبر Tinta
39 TagBlot にじみ Blot 渗化 滲化 번짐 Mancha تسرب Rembesan
40 TagJapanese 和風 Japanese style 和风 和風 일본풍 Estilo japonés النمط الياباني Gaya Jepang
41 UpdateAvailableMessage 新しいバージョン {0} が公開されています。 A new version {0} is available. 新版本 {0} 已发布。 新版本 {0} 已發布。 새 버전 {0}이(가) 공개되었습니다. La nueva versión {0} ya está disponible. تم إصدار نسخة جديدة {0}. Versi baru {0} telah dirilis.