/// <summary> /// Calculates how much material would slump down to the current location from the point at the given offset. /// This is written into the first temporary buffer. /// </summary> /// <param name="slopeThreshold"></param> /// <param name="depthThreshold"></param> /// <param name="amount"></param> private void SlumpPowderOneDirection(float slopeThreshold, float depthThreshold, float amount, int xofs, int yofs) { ParallelHelper.For2DParallelOffset(this.Width, this.Height, xofs, yofs, (pTo, pFrom) => { //int pFrom = C(x + xofs, y + yofs); // cell we're taking material from float h = this.Map[pTo].Height; this.TempDiffMap[pTo] = 0f; float powder = this.Map[pFrom].Powder - depthThreshold; // can only slump powder over our depth threshold if (powder > 0f) { float diff = (((this.Map[pFrom].Height) - h) - slopeThreshold); if (diff > 0f) { if (diff > powder) { diff = powder; } this.TempDiffMap[pTo] = diff * amount; } } }); this.CombineDiffMapsForDirection(xofs, yofs); }
/// <summary> /// Listen database on selected channels /// </summary> /// <param name="stoppingToken">Cancellation</param> /// <returns></returns> public async Task ListenDb(CancellationToken stoppingToken) { await ParallelHelper.Run(() => { Log.Info($"Listening started for DB: {_dbName}"); while (!stoppingToken.IsCancellationRequested) { try { using (PgSqlDbConnect connect = new PgSqlDbConnect(_connectionString)) { connect.Open(); connect.UnderlyingConnection.Notification += OnNotification; connect.Execute($"LISTEN {PgSqlDbConnect.CHANNEL_GENESIS_REQUEST};"); connect.Execute($"LISTEN {PgSqlDbConnect.CHANNEL_GENESIS_DELETE};"); connect.Execute($"LISTEN {PgSqlDbConnect.CHANNEL_BACKUP_REQUEST};"); while (!stoppingToken.IsCancellationRequested && connect.UnderlyingConnection.State == ConnectionState.Open) { connect.UnderlyingConnection.Wait(100); } } } catch (Exception e) { Log.Error(e); Thread.Sleep(1000); } } }); }
/// <inheritdoc/> protected override void OnFrameApply(ImageFrame <TPixel> source) { MemoryAllocator memoryAllocator = this.Configuration.MemoryAllocator; int numberOfPixels = source.Width * source.Height; var workingRect = new Rectangle(0, 0, source.Width, source.Height); using (IMemoryOwner <int> histogramBuffer = memoryAllocator.Allocate <int>(this.LuminanceLevels, AllocationOptions.Clean)) using (IMemoryOwner <int> cdfBuffer = memoryAllocator.Allocate <int>(this.LuminanceLevels, AllocationOptions.Clean)) { // Build the histogram of the grayscale levels. ParallelHelper.IterateRows( workingRect, this.Configuration, rows => { ref int histogramBase = ref MemoryMarshal.GetReference(histogramBuffer.GetSpan()); for (int y = rows.Min; y < rows.Max; y++) { ref TPixel pixelBase = ref MemoryMarshal.GetReference(source.GetPixelRowSpan(y)); for (int x = 0; x < workingRect.Width; x++) { int luminance = GetLuminance(Unsafe.Add(ref pixelBase, x), this.LuminanceLevels); Unsafe.Add(ref histogramBase, luminance)++; } } });
private void UpdateTileDataPass2() { ParallelHelper.For2D(this.tile.Width, this.tile.Height, (x, y, i) => { this.tile.Data[i] = (this.TerrainPass2.Map[i].Height) / 4096.0f; }); ParallelHelper.For2D(this.tile.Width, this.tile.Height, (x, y, i) => { this.shadeTexData[i].R = (byte)((this.TerrainPass2.Map[i].Ice * 64f).ClampInclusive(0.0f, 255.0f)); // ice this.shadeTexData[i].G = (byte)((this.TerrainPass2.Map[i].Snow * 64f).ClampInclusive(0.0f, 255.0f)); // snow this.shadeTexData[i].B = (byte)((this.TerrainPass2.Map[i].Powder * 1024f).ClampInclusive(0.0f, 255.0f)); // powder this.shadeTexData[i].A = 0; }); //Parallel.For(0, this.tile.Height, y => //{ // int i = y * this.TerrainPass2.Width; // for (int x = 0; x < this.tile.Width; x++) // { // var c = this.TerrainPass2.Map[i]; // this.tile.Data[i] = (c.Height) / 4096.0f; // this.shadeTexData[i].R = (byte)((c.Ice * 64f).ClampInclusive(0.0f, 255.0f)); // ice // this.shadeTexData[i].G = (byte)((c.Snow * 64f).ClampInclusive(0.0f, 255.0f)); // snow // this.shadeTexData[i].B = (byte)((c.Powder * 64f).ClampInclusive(0.0f, 255.0f)); // powder // this.shadeTexData[i].A = 0; // i++; // } //}); this.tile.UpdateHeights(device); this.tile.UpdateShadeTexture(this.shadeTexData); }
public void IterateRows_OverMinimumPixelsLimit_IntervalsAreCorrect( int maxDegreeOfParallelism, int minY, int maxY, int expectedStepLength, int expectedLastStepLength) { var parallelSettings = new ParallelExecutionSettings( maxDegreeOfParallelism, 1, Configuration.Default.MemoryAllocator); var rectangle = new Rectangle(0, minY, 10, maxY - minY); int actualNumberOfSteps = 0; ParallelHelper.IterateRows( rectangle, parallelSettings, rows => { Assert.True(rows.Min >= minY); Assert.True(rows.Max <= maxY); int step = rows.Max - rows.Min; int expected = rows.Max < maxY ? expectedStepLength : expectedLastStepLength; Interlocked.Increment(ref actualNumberOfSteps); Assert.Equal(expected, step); }); Assert.Equal(maxDegreeOfParallelism, actualNumberOfSteps); }
/// <inheritdoc/> protected override void OnFrameApply(ImageFrame <TPixel> source, Rectangle sourceRectangle, Configuration configuration) { var interest = Rectangle.Intersect(sourceRectangle, source.Bounds()); int startX = interest.X; ColorMatrix matrix = this.definition.Matrix; ParallelHelper.IterateRowsWithTempBuffer <Vector4>( interest, configuration, (rows, vectorBuffer) => { for (int y = rows.Min; y < rows.Max; y++) { Span <Vector4> vectorSpan = vectorBuffer.Span; int length = vectorSpan.Length; Span <TPixel> rowSpan = source.GetPixelRowSpan(y).Slice(startX, length); PixelOperations <TPixel> .Instance.ToVector4(configuration, rowSpan, vectorSpan); Vector4Utils.Transform(vectorSpan, ref matrix); PixelOperations <TPixel> .Instance.FromVector4Destructive(configuration, vectorSpan, rowSpan); } }); }
public async Task ListObjectsMoreThanMaxKeys(S3Provider provider, string _, ISimpleClient client) { await CreateTempBucketAsync(provider, client, async tempBucket => { int concurrent = 10; int count = 11; await ParallelHelper.ExecuteAsync(Enumerable.Range(0, count), (val, token) => client.PutObjectAsync(tempBucket, val.ToString(), null, null, token), concurrent); ListObjectVersionsResponse listResp = await client.ListObjectVersionsAsync(tempBucket, r => r.MaxKeys = count - 1).ConfigureAwait(false); Assert.True(listResp.IsSuccess); Assert.True(listResp.IsTruncated); Assert.Equal(10, listResp.MaxKeys); Assert.Equal(10, listResp.Versions.Count); ListObjectVersionsResponse listResp2 = await client.ListObjectVersionsAsync(tempBucket, r => r.KeyMarker = listResp.NextKeyMarker).ConfigureAwait(false); Assert.True(listResp2.IsSuccess); Assert.False(listResp2.IsTruncated); if (provider != S3Provider.GoogleCloudStorage) { Assert.Equal(1, listResp2.Versions.Count); } }).ConfigureAwait(false); }
public void IterateRows_OverMinimumPixelsLimit_ShouldVisitAllRows( int maxDegreeOfParallelism, int minY, int maxY, int expectedStepLength, int expectedLastStepLength) { var parallelSettings = new ParallelExecutionSettings( maxDegreeOfParallelism, 1, Configuration.Default.MemoryAllocator); var rectangle = new Rectangle(0, minY, 10, maxY - minY); int[] expectedData = Enumerable.Repeat(0, minY).Concat(Enumerable.Range(minY, maxY - minY)).ToArray(); var actualData = new int[maxY]; ParallelHelper.IterateRows( rectangle, parallelSettings, rows => { for (int y = rows.Min; y < rows.Max; y++) { actualData[y] = y; } }); Assert.Equal(expectedData, actualData); }
private unsafe void DoCopyRaw(int sourceStride, int targetStride, byte *sourceOrigin, byte *targetOrigin) { // Sequential processing if (SourceRectangle.Width < parallelThreshold) { context.Progress?.New(DrawingOperation.ProcessingPixels, SourceRectangle.Height); byte *pSrc = sourceOrigin + SourceRectangle.Y * sourceStride + SourceRectangle.X; byte *pDst = targetOrigin + TargetRectangle.Y * targetStride + TargetRectangle.X; for (int y = 0; y < SourceRectangle.Height; y++) { if (context.IsCancellationRequested) { return; } MemoryHelper.CopyMemory(pSrc, pDst, SourceRectangle.Width); pSrc += sourceStride; pDst += targetStride; context.Progress?.Increment(); } return; } // Parallel processing Point sourceLocation = SourceRectangle.Location; Point targetLocation = TargetRectangle.Location; int width = SourceRectangle.Width; ParallelHelper.For(context, DrawingOperation.ProcessingPixels, 0, SourceRectangle.Height, y => { byte *pSrc = sourceOrigin + (y + sourceLocation.Y) * sourceStride + sourceLocation.X; byte *pDst = targetOrigin + (y + targetLocation.Y) * targetStride + targetLocation.X; MemoryHelper.CopyMemory(pSrc, pDst, width); }); }
public void Test_ParallelHelper_ForEach_Ref() { foreach (int count in TestForCounts) { using UnmanagedSpanOwner <int> data = CreateRandomData(count); using UnmanagedSpanOwner <int> copy = new UnmanagedSpanOwner <int>(count); data.GetSpan().CopyTo(copy.GetSpan()); foreach (ref int n in copy.GetSpan()) { n = unchecked (n * 397); } ParallelHelper.ForEach(data.Memory, new Multiplier(397)); Span <int> dataSpan = data.GetSpan(); Span <int> copySpan = copy.GetSpan(); for (int i = 0; i < data.Length; i++) { if (dataSpan[i] != copySpan[i]) { Assert.Fail($"Item #{i} was not a match, was {dataSpan[i]} instead of {copySpan[i]}"); } } } }
public unsafe void Test_ParallelHelper_ForEach_In2D( int sizeY, int sizeX, int row, int column, int height, int width) { int[,] data = CreateRandomData2D(sizeY, sizeX); // Create a memory wrapping the random array with the given parameters ReadOnlyMemory2D <int> memory = data.AsMemory2D(row, column, height, width); Assert.AreEqual(memory.Length, height * width); Assert.AreEqual(memory.Height, height); Assert.AreEqual(memory.Width, width); int sum = 0; // Sum all the items in parallel. The Summer type takes a pointer to a target value // and adds values to it in a thread-safe manner (with an interlocked add). ParallelHelper.ForEach(memory, new Summer(&sum)); int expected = 0; // Calculate the sum iteratively as a baseline for comparison foreach (int n in memory.Span) { expected += n; } Assert.AreEqual(sum, expected, $"The sum doesn't match, was {sum} instead of {expected}"); }
public void Test_ParallelHelper_ForEach_Ref2D( int sizeY, int sizeX, int row, int column, int height, int width) { int[,] data = CreateRandomData2D(sizeY, sizeX), copy = (int[, ])data.Clone(); // Prepare the target data iteratively foreach (ref int n in copy.AsSpan2D(row, column, height, width)) { n = unchecked (n * 397); } Memory2D <int> memory = data.AsMemory2D(row, column, height, width); Assert.AreEqual(memory.Length, height * width); Assert.AreEqual(memory.Height, height); Assert.AreEqual(memory.Width, width); // Do the same computation in paralellel, then compare the two arrays ParallelHelper.ForEach(memory, new Multiplier(397)); CollectionAssert.AreEqual(data, copy); }
public void IterateRowsWithTempBuffer_WithEffectiveMinimumPixelsLimit( int maxDegreeOfParallelism, int minimumPixelsProcessedPerTask, int width, int height, int expectedNumberOfSteps, int expectedStepLength, int expectedLastStepLength) { var parallelSettings = new ParallelExecutionSettings( maxDegreeOfParallelism, minimumPixelsProcessedPerTask, Configuration.Default.MemoryAllocator); var rectangle = new Rectangle(0, 0, width, height); int actualNumberOfSteps = 0; ParallelHelper.IterateRowsWithTempBuffer( rectangle, parallelSettings, (RowInterval rows, Memory <Vector4> buffer) => { Assert.True(rows.Min >= 0); Assert.True(rows.Max <= height); int step = rows.Max - rows.Min; int expected = rows.Max < height ? expectedStepLength : expectedLastStepLength; Interlocked.Increment(ref actualNumberOfSteps); Assert.Equal(expected, step); }); Assert.Equal(expectedNumberOfSteps, actualNumberOfSteps); }
/// <inheritdoc/> protected override void OnFrameApply(ImageFrame <TPixel> source) { var interest = Rectangle.Intersect(this.SourceRectangle, source.Bounds()); int startX = interest.X; Configuration configuration = this.Configuration; PixelConversionModifiers modifiers = this.modifiers; ParallelHelper.IterateRowsWithTempBuffer <Vector4>( interest, this.Configuration, (rows, vectorBuffer) => { for (int y = rows.Min; y < rows.Max; y++) { Span <Vector4> vectorSpan = vectorBuffer.Span; int length = vectorSpan.Length; Span <TPixel> rowSpan = source.GetPixelRowSpan(y).Slice(startX, length); PixelOperations <TPixel> .Instance.ToVector4(configuration, rowSpan, vectorSpan, modifiers); // Run the user defined pixel shader on the current row of pixels this.ApplyPixelShader(vectorSpan, new Point(startX, y)); PixelOperations <TPixel> .Instance.FromVector4Destructive(configuration, vectorSpan, rowSpan, modifiers); } }); }
public void Test_ParallelHelper_ParameterName_ThrowArgumentOutOfRangeExceptionForTopGreaterThanBottom() { try { ParallelHelper.For2D <DummyAction2D>(1, 0, 0, 1); } catch (ArgumentOutOfRangeException e) when(e.GetType() == typeof(ArgumentOutOfRangeException)) { var name = ( from method in typeof(ParallelHelper).GetMethods() where method.Name == nameof(ParallelHelper.For2D) && method.IsGenericMethodDefinition let typeParams = method.GetGenericArguments() let normalParams = method.GetParameters() where typeParams.Length == 1 && normalParams.Length == 4 && normalParams.All(p => p.ParameterType == typeof(int)) select normalParams[0].Name).Single(); Assert.AreEqual(e.ParamName, name); return; } Assert.Fail("Failed to raise correct exception"); }
/// <summary> /// Rotates the image 90 degrees clockwise at the centre point. /// </summary> /// <param name="source">The source image.</param> /// <param name="destination">The destination image.</param> /// <param name="configuration">The configuration.</param> private void Rotate90(ImageFrame <TPixel> source, ImageFrame <TPixel> destination, Configuration configuration) { int width = source.Width; int height = source.Height; Rectangle destinationBounds = destination.Bounds(); ParallelHelper.IterateRows( source.Bounds(), configuration, rows => { for (int y = rows.Min; y < rows.Max; y++) { Span <TPixel> sourceRow = source.GetPixelRowSpan(y); int newX = height - y - 1; for (int x = 0; x < width; x++) { // TODO: Optimize this: if (destinationBounds.Contains(newX, x)) { destination[newX, x] = sourceRow[x]; } } } }); }
public async Task StressTestAsync() { var timer = new Timer(); var changeCount = 0; var tickCount = 0; timer.Changed += (sender, e) => { changeCount++; }; timer.Elapsed += (sender, e) => { tickCount++; }; var timeouts = new List <int>(); var random = new Random(); for (int i = 0; i < 100000; i++) { var timeout = random.Next(50, 250); timeouts.Add(timeout); } #pragma warning disable CL0001 // Use async overload inside this async method ParallelHelper.ExecuteInParallel(timeouts, x => timer.Change(x, x), 10); #pragma warning restore CL0001 // Use async overload inside this async method Assert.AreNotEqual(0, changeCount); }
private void AddDiffMapToPowder(float[] diffmap) { ParallelHelper.For2D(this.Width, this.Height, (x, y, i) => { this.Map[i].Powder += diffmap[i]; }); }
/// <inheritdoc/> protected override void OnFrameApply(ImageFrame <TPixel> source, ImageFrame <TPixel> destination, Rectangle sourceRectangle, Configuration configuration) { // Handle resize dimensions identical to the original if (source.Width == destination.Width && source.Height == destination.Height && sourceRectangle == this.CropRectangle) { // the cloned will be blank here copy all the pixel data over source.GetPixelSpan().CopyTo(destination.GetPixelSpan()); return; } var rect = Rectangle.Intersect(this.CropRectangle, sourceRectangle); // Copying is cheap, we should process more pixels per task: ParallelExecutionSettings parallelSettings = configuration.GetParallelSettings().MultiplyMinimumPixelsPerTask(4); ParallelHelper.IterateRows( rect, parallelSettings, rows => { for (int y = rows.Min; y < rows.Max; y++) { Span <TPixel> sourceRow = source.GetPixelRowSpan(y).Slice(rect.Left); Span <TPixel> targetRow = destination.GetPixelRowSpan(y - rect.Top); sourceRow.Slice(0, rect.Width).CopyTo(targetRow); } }); }
/// <inheritdoc/> protected override void OnFrameApply(ImageFrame <TPixelDst> source, Rectangle sourceRectangle, Configuration configuration) { Image <TPixelSrc> targetImage = this.Image; PixelBlender <TPixelDst> blender = this.Blender; int locationY = this.Location.Y; // Align start/end positions. Rectangle bounds = targetImage.Bounds(); int minX = Math.Max(this.Location.X, sourceRectangle.X); int maxX = Math.Min(this.Location.X + bounds.Width, sourceRectangle.Width); int targetX = minX - this.Location.X; int minY = Math.Max(this.Location.Y, sourceRectangle.Y); int maxY = Math.Min(this.Location.Y + bounds.Height, sourceRectangle.Bottom); int width = maxX - minX; var workingRect = Rectangle.FromLTRB(minX, minY, maxX, maxY); ParallelHelper.IterateRows( workingRect, configuration, rows => { for (int y = rows.Min; y < rows.Max; y++) { Span <TPixelDst> background = source.GetPixelRowSpan(y).Slice(minX, width); Span <TPixelSrc> foreground = targetImage.GetPixelRowSpan(y - locationY).Slice(targetX, width); blender.Blend <TPixelSrc>(configuration, background, background, foreground, this.Opacity); } }); }
/// <summary> /// Imports the tracks. /// </summary> /// <param name="externalFolder">The external folder.</param> public void ImportExternalShufflerTracks(string externalFolder) { var files = FileSystemHelper.SearchFiles(externalFolder, "*.mp3", true); ParallelHelper.ForEach(files, file => { ImportExternalShufflerTrack(file, externalFolder); }); SaveToDatabase(); }
private void CombineDiffMapsForDirection(int xofs, int yofs) { ParallelHelper.For2D(this.Width, this.Height, (x, y, pTo) => { this.TempDiffMap2[C(x + xofs, y + yofs)] -= this.TempDiffMap[pTo]; this.TempDiffMap2[pTo] += this.TempDiffMap[pTo]; }); }
public void WriteToHtml() { lock (htmlWriteLocker) { // HTML-Vorlage auslesen und initialisieren if (htmlTemplate == null) { htmlTemplate = File.ReadAllText(PBEContext.CurrentContext.LogFileTemplate); htmlTemplate = this.ParseParameters(htmlTemplate); // link auf die alte Logdatei einbauen if (File.Exists(this.Logfile)) { String oldLogfile = ParallelHelper.FileReadAllText(this.Logfile); Regex reg = new Regex("[<]!-- Archive: (?<file>[^>]*) --[>]"); var match = reg.Match(oldLogfile); if (match != null) { string oldArchive = match.Groups["file"].Value; htmlTemplate = htmlTemplate.Replace(PLACEHOLDER_Archive, PLACEHOLDER_Archive + " <a href=\"" + oldArchive + "\">Previous Logilfe</a>"); } } // Aktuelle Achiv-Datei eintragen htmlTemplate = htmlTemplate.Replace(PLACEHOLDER_Archive, "<!-- Archive: " + this.Logarchive + " -->"); } // html-Content aufbereiten String htmlContent = htmlTemplate; StringBuilder sbParams = new StringBuilder(); foreach (var pair in this.Parameters) { sbParams.AppendFormat("<tr><td class=\"ParamName\">{0}</td><td class=\"ParamValue\">{1}</td></tr>\r\n", HtmlHelper.HtmlEncode(pair.Key), HtmlHelper.HtmlEncode(pair.Value)); } htmlContent = htmlContent.Replace("<!-- ParamsPlaceholder -->", sbParams.ToString()); htmlContent = htmlContent.Replace("<!-- PbeXmlPlaceHolder -->", this.XmlFilecontetForLog); StringBuilder sbTasks = new StringBuilder(); this.rootAction.WriteToHtml(sbTasks); htmlContent = htmlContent.Replace("<!-- TasksPlaceHolder -->", sbTasks.ToString()); int tries = 3; while (tries > 0) { try { tries--; File.WriteAllText(this.Logfile, htmlContent); File.WriteAllText(this.Logarchive, htmlContent); tries = 0; } catch { } } } }
/// <inheritdoc/> protected override void OnFrameApply(ImageFrame <TPixel> source) { int brushSize = this.definition.BrushSize; if (brushSize <= 0 || brushSize > source.Height || brushSize > source.Width) { throw new ArgumentOutOfRangeException(nameof(brushSize)); } int startY = this.SourceRectangle.Y; int endY = this.SourceRectangle.Bottom; int startX = this.SourceRectangle.X; int endX = this.SourceRectangle.Right; int maxY = endY - 1; int maxX = endX - 1; int radius = brushSize >> 1; int levels = this.definition.Levels; int rowWidth = source.Width; int rectangleWidth = this.SourceRectangle.Width; Configuration configuration = this.Configuration; using Buffer2D <TPixel> targetPixels = this.Configuration.MemoryAllocator.Allocate2D <TPixel>(source.Size()); source.CopyTo(targetPixels); var workingRect = Rectangle.FromLTRB(startX, startY, endX, endY); ParallelHelper.IterateRows( workingRect, this.Configuration, (rows) => { /* Allocate the two temporary Vector4 buffers, one for the source row and one for the target row. * The ParallelHelper.IterateRowsWithTempBuffers overload is not used in this case because * the two allocated buffers have a length equal to the width of the source image, * and not just equal to the width of the target rectangle to process. * Furthermore, there are two buffers being allocated in this case, so using that overload would * have still required the explicit allocation of the secondary buffer. * Similarly, one temporary float buffer is also allocated from the pool, and that is used * to create the target bins for all the color channels being processed. * This buffer is only rented once outside of the main processing loop, and its contents * are cleared for each loop iteration, to avoid the repeated allocation for each processed pixel. */ using (IMemoryOwner <Vector4> sourceRowBuffer = configuration.MemoryAllocator.Allocate <Vector4>(rowWidth)) using (IMemoryOwner <Vector4> targetRowBuffer = configuration.MemoryAllocator.Allocate <Vector4>(rowWidth)) using (IMemoryOwner <float> bins = configuration.MemoryAllocator.Allocate <float>(levels * 4)) { Span <Vector4> sourceRowVector4Span = sourceRowBuffer.Memory.Span; Span <Vector4> sourceRowAreaVector4Span = sourceRowVector4Span.Slice(startX, rectangleWidth); Span <Vector4> targetRowVector4Span = targetRowBuffer.Memory.Span; Span <Vector4> targetRowAreaVector4Span = targetRowVector4Span.Slice(startX, rectangleWidth); ref float binsRef = ref bins.GetReference(); ref int intensityBinRef = ref Unsafe.As <float, int>(ref binsRef); ref float redBinRef = ref Unsafe.Add(ref binsRef, levels);
public void GetOptimalNumberOfTasksUnitTest() { Assert.Inconclusive("TODO"); int expected = 0; // TODO: Initialize to an appropriate value int actual; actual = ParallelHelper.GetOptimalNumberOfTasks(); Assert.AreEqual(expected, actual); }
public void LoadFromFiles() { lock (_samples) { _samples.Clear(); } var files = FileSystemHelper.SearchFiles(_folder, "*.wav", true); ParallelHelper.ForEach(files, LoadSample); }
public void IterateRowsRequiresValidRectangle(int width, int height) { var parallelSettings = new ParallelExecutionSettings(); var rect = new Rectangle(0, 0, width, height); ArgumentOutOfRangeException ex = Assert.Throws <ArgumentOutOfRangeException>( () => ParallelHelper.IterateRows(rect, parallelSettings, rows => { })); Assert.Contains(width <= 0 ? "Width" : "Height", ex.Message); }
public void IterateRowsWithTempBufferRequiresValidRectangle(int width, int height) { var parallelSettings = default(ParallelExecutionSettings); var rect = new Rectangle(0, 0, width, height); ArgumentOutOfRangeException ex = Assert.Throws <ArgumentOutOfRangeException>( () => ParallelHelper.IterateRowsWithTempBuffer <Rgba32>(rect, parallelSettings, (rows, memory) => { })); Assert.Contains(width <= 0 ? "Width" : "Height", ex.Message); }
public void CompactPowder(float minDepth, float amount, float invDensityRatio) { ParallelHelper.For2D(this.Width, this.Height, (i) => { float powder = this.Map[i].Powder; if (powder > minDepth) { powder = (powder - minDepth) * amount; this.Map[i].Powder -= powder; this.Map[i].Snow += powder * invDensityRatio; } }); }
/// <summary> /// Swaps the image at the Y-axis, which goes vertically through the middle at half of the width of the image. /// </summary> /// <param name="source">The source image to apply the process to.</param> /// <param name="configuration">The configuration.</param> private void FlipY(ImageFrame <TPixel> source, Configuration configuration) { ParallelHelper.IterateRows( source.Bounds(), configuration, rows => { for (int y = rows.Min; y < rows.Max; y++) { source.GetPixelRowSpan(y).Reverse(); } }); }