/src/Effects/BackgroundEffectRenderer.cs
C# | 414 lines | 311 code | 59 blank | 44 comment | 41 complexity | 0f1ccc71b3bf5c5b426616ad40e51ce0 MD5 | raw file
- /////////////////////////////////////////////////////////////////////////////////
- // Paint.NET //
- // Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. //
- // Portions Copyright (C) Microsoft Corporation. All Rights Reserved. //
- // See src/Resources/Files/License.txt for full licensing and attribution //
- // details. //
- // . //
- /////////////////////////////////////////////////////////////////////////////////
-
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Drawing;
- using System.Threading;
-
- namespace PaintDotNet.Effects
- {
- /// <summary>
- /// This class can be used to apply an effect using background worker threads
- /// which raise an event when a certain amount of the effect has been processed.
- /// You can use that event to update a status bar, display a preview of the
- /// rendering so far, or whatever.
- ///
- /// Since two threads are used for rendering, this will improve performance on
- /// dual processor systems, and possibly on systems that have HyperThreading.
- ///
- /// This class is NOT SAFE for multithreaded access. Note that the events will
- /// be raised from arbitrary threads.
- /// be raised from arbitrary threads. The only method that is safe to call from
- /// a thread that is not managing Start(), Abort(), and Join() is AbortAsync().
- /// You may then query whether the rendering actually aborted by using the Abort
- /// property. If it returns false, then AbortAsync() was not called in time to
- /// abort anything, which means the rendering completed fully.
- /// </summary>
- public sealed class BackgroundEffectRenderer
- : IDisposable
- {
- private readonly Effect _effect;
- private readonly EffectConfigToken _effectToken; // this references the main token that is passed in to the constructor
- private EffectConfigToken _effectTokenCopy; // this copy of the token is updated every time you call Start() to make sure it is up to date. This is then passed to the threads, not the original one.
- private readonly PdnRegion _renderRegion;
- private readonly Rectangle[][] _tileRegions;
- private readonly PdnRegion[] _tilePdnRegions;
- private readonly int _tileCount;
- private readonly Threading.ThreadPool _threadPool;
- private RenderArgs _dstArgs;
- private RenderArgs _srcArgs;
- private readonly int _workerThreads;
- private readonly ArrayList _exceptions = ArrayList.Synchronized(new ArrayList());
- private volatile bool _aborted;
-
- public event RenderedTileEventHandler RenderedTile;
- private void OnRenderedTile(RenderedTileEventArgs e)
- {
- if (RenderedTile != null)
- {
- RenderedTile(this, e);
- }
- }
-
- public event EventHandler FinishedRendering;
- private void OnFinishedRendering()
- {
- if (FinishedRendering != null)
- {
- FinishedRendering(this, EventArgs.Empty);
- }
- }
-
- public event EventHandler StartingRendering;
- private void OnStartingRendering()
- {
- if (StartingRendering != null)
- {
- StartingRendering(this, EventArgs.Empty);
- }
- }
-
- private sealed class RendererContext
- {
- private readonly BackgroundEffectRenderer _ber;
- private readonly EffectConfigToken _token;
- private readonly int _threadNumber;
- private readonly int _startOffset;
-
- /*
- public RendererContext(BackgroundEffectRenderer ber, EffectConfigToken token, int threadNumber)
- : this(ber, token, threadNumber, 0)
- {
- } UNUSED CONSTRUCTOR
- */
-
- public RendererContext(BackgroundEffectRenderer ber, EffectConfigToken token, int threadNumber, int startOffset)
- {
- _ber = ber;
- _token = token;
- _threadNumber = threadNumber;
- _startOffset = startOffset;
- }
-
- public void Renderer2(object ignored)
- {
- Renderer();
- }
-
- private void Renderer()
- {
- //using (new ThreadBackground(ThreadBackgroundFlags.Cpu))
- {
- RenderImpl();
- }
- }
-
- private void RenderImpl()
- {
- int inc = _ber._workerThreads;
- int start = _threadNumber + (_startOffset * inc);
- int max = _ber._tileCount;
-
- try
- {
- for (int tile = start; tile < max; tile += inc)
- {
- if (_ber._threadShouldStop)
- {
- _ber._aborted = true;
- break;
- }
-
- Rectangle[] subRegion = _ber._tileRegions[tile];
- _ber._effect.Render(_token, _ber._dstArgs, _ber._srcArgs, subRegion);
- PdnRegion subPdnRegion = _ber._tilePdnRegions[tile];
- _ber.OnRenderedTile(new RenderedTileEventArgs(subPdnRegion, _ber._tileCount, tile));
- }
- }
-
- catch (Exception ex)
- {
- _ber._exceptions.Add(ex);
- }
- }
- }
-
- public void ThreadFunction()
- {
- if (_srcArgs.Surface.Scan0.MaySetAllowWrites)
- {
- _srcArgs.Surface.Scan0.AllowWrites = false;
- }
-
- try
- {
- _effect.SetRenderInfo(_effectTokenCopy, _dstArgs, _srcArgs);
-
- if (_tileCount > 0)
- {
- Rectangle[] subRegion = _tileRegions[0];
-
- _effect.Render(_effectTokenCopy, _dstArgs, _srcArgs, subRegion);
-
- PdnRegion subPdnRegion = _tilePdnRegions[0];
- OnRenderedTile(new RenderedTileEventArgs(subPdnRegion, _tileCount, 0));
- }
-
- var tokens = new EffectConfigToken[_workerThreads];
-
- int i;
- for (i = 0; i < _workerThreads; ++i)
- {
- if (_threadShouldStop)
- {
- break;
- }
-
- if (_effectTokenCopy == null)
- {
- tokens[i] = null;
- }
- else
- {
- tokens[i] = (EffectConfigToken)_effectTokenCopy.Clone();
- }
-
- var rc = new RendererContext(this, tokens[i], i, (i == 0) ? 1 : 0);
- _threadPool.QueueUserWorkItem(rc.Renderer2);
- }
-
- if (i == _workerThreads)
- {
- _threadPool.Drain();
- OnFinishedRendering();
- }
- }
-
- catch (Exception ex)
- {
- _exceptions.Add(ex);
- }
-
- finally
- {
- _threadPool.Drain();
-
- Exception[] newExceptions = _threadPool.Exceptions;
-
- if (newExceptions.Length > 0)
- {
- foreach (Exception exception in newExceptions)
- {
- _exceptions.Add(exception);
- }
- }
-
- if (_srcArgs.Surface.Scan0.MaySetAllowWrites)
- {
- _srcArgs.Surface.Scan0.AllowWrites = true;
- }
- }
- }
-
- private volatile bool _threadShouldStop;
- private Thread _thread;
-
- public void Start()
- {
- Abort();
- _aborted = false;
-
- if (_effectToken != null)
- {
- _effectTokenCopy = (EffectConfigToken)_effectToken.Clone();
- }
-
- _threadShouldStop = false;
- OnStartingRendering();
- _thread = new Thread(ThreadFunction);
- _thread.Start();
- }
-
- public bool Aborted
- {
- get
- {
- return _aborted;
- }
- }
-
- public void Abort()
- {
- if (_thread == null) return;
- _threadShouldStop = true;
- Join();
- _threadPool.Drain();
- }
-
- // This is the only method that is safe to call from another thread
- // If the abort was successful, then get_Aborted will return true
- // after a Join().
- public void AbortAsync()
- {
- _threadShouldStop = true;
- }
-
- /// <summary>
- /// Used to determine whether the rendering fully completed or not, and was not
- /// aborted in any way. You can use this method to sleep until the rendering
- /// finishes. Once this is set to the signaled state you should check the IsDone
- /// property to make sure that the rendering was actually finished, and not
- /// aborted.
- /// </summary>
- public void Join()
- {
- _thread.Join();
-
- if (_exceptions.Count <= 0)
- {
- }
- else
- {
- var throwMe = (Exception) _exceptions[0];
- _exceptions.Clear();
- throw new WorkerThreadException("Worker thread threw an exception", throwMe);
- }
- }
-
- private static Rectangle[] ConsolidateRects(Rectangle[] scans)
- {
- if (scans.Length == 0)
- {
- return scans;
- }
-
- var cons = new List<Rectangle>();
- int current = 0;
- cons.Add(scans[0]);
-
- for (int i = 1; i < scans.Length; ++i)
- {
- if (scans[i].Left == cons[current].Left &&
- scans[i].Right == cons[current].Right &&
- scans[i].Top == cons[current].Bottom)
- {
- Rectangle cc = cons[current];
- cc.Height = scans[i].Bottom - cons[current].Top;
- cons[current] = cc;
- }
- else
- {
- cons.Add(scans[i]);
- current = cons.Count - 1;
- }
- }
-
- return cons.ToArray();
- }
-
- private static Rectangle[][] SliceUpRegion(PdnRegion region, int sliceCount, Rectangle layerBounds)
- {
- var slices = new Rectangle[sliceCount][];
- Rectangle[] regionRects = region.GetRegionScansReadOnlyInt();
- Scanline[] regionScans = Utility.GetRegionScans(regionRects);
-
- for (int i = 0; i < sliceCount; ++i)
- {
- int beginScan = (regionScans.Length * i) / sliceCount;
- int endScan = Math.Min(regionScans.Length, (regionScans.Length * (i + 1)) / sliceCount);
-
- // Try to arrange it such that the maximum size of the first region
- // is 1-pixel tall
- switch (i)
- {
- case 0:
- endScan = Math.Min(endScan, beginScan + 1);
- break;
- case 1:
- beginScan = Math.Min(beginScan, 1);
- break;
- }
-
- Rectangle[] newRects = Utility.ScanlinesToRectangles(regionScans, beginScan, endScan - beginScan);
-
- for (int j = 0; j < newRects.Length; ++j)
- {
- newRects[j].Intersect(layerBounds);
- }
-
- Rectangle[] consRects = ConsolidateRects(newRects);
- slices[i] = consRects;
- }
-
- return slices;
- }
-
- public BackgroundEffectRenderer(Effect effect,
- EffectConfigToken effectToken,
- RenderArgs dstArgs,
- RenderArgs srcArgs,
- PdnRegion renderRegion,
- int tileCount,
- int workerThreads)
- {
- _effect = effect;
- _effectToken = effectToken;
- _dstArgs = dstArgs;
- _srcArgs = srcArgs;
- _renderRegion = renderRegion;
- _renderRegion.Intersect(dstArgs.Bounds);
-
- _tileRegions = SliceUpRegion(renderRegion, tileCount, dstArgs.Bounds);
-
- _tilePdnRegions = new PdnRegion[_tileRegions.Length];
- for (int i = 0; i < _tileRegions.Length; ++i)
- {
- PdnRegion pdnRegion = Utility.RectanglesToRegion(_tileRegions[i]);
- _tilePdnRegions[i] = pdnRegion;
- }
-
- _tileCount = tileCount;
- _workerThreads = workerThreads;
-
- if (effect.CheckForEffectFlags(EffectFlags.SingleThreaded))
- {
- _workerThreads = 1;
- }
-
- _threadPool = new Threading.ThreadPool(_workerThreads, false);
- }
-
- ~BackgroundEffectRenderer()
- {
- Dispose(false);
- }
-
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- private void Dispose(bool disposing)
- {
- if (!disposing) return;
- if (_srcArgs != null)
- {
- _srcArgs.Dispose();
- _srcArgs = null;
- }
-
- if (_dstArgs == null) return;
- _dstArgs.Dispose();
- _dstArgs = null;
- }
- }
- }