using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using HarmonyLib;
using ParallelTasks;
namespace XFE.SeAgent.Plugin.Performance
{
// Only replace the loop already declared parallel by the engine. Its outer
// Havok shared-read scope, entity initialization drain and join stay intact.
// Snapshot enumeration on the caller removes the shared enumerator's lock
// from every worker callback; bounded chunks retain dynamic load balancing.
internal static class EntityBatching
{
internal static int ChunkSize = 8;
public static long Dispatches, ItemsProcessed;
private static class Cache<T>
{
[ThreadStatic] internal static Batch<T> Spare;
}
private sealed class Batch<T>
{
internal readonly List<T> Items = new List<T>();
internal Action<T> Action;
internal int Size;
internal readonly Action<int> Run;
internal Batch() { Run = Chunk; }
private void Chunk(int index)
{
int end = Math.Min((index + 1) * Size, Items.Count);
for (int i = index * Size; i < end; i++) Action(Items[i]);
}
}
public static void Run<T>(IEnumerable<T> collection, Action<T> action,
WorkPriority priority, WorkOptions? options, bool blocking)
{
// Parallel.For in this engine overwrites MaximumThreads. Preserve
// any explicit cap by falling back, and never alter async lifetime.
if (!blocking || (options.HasValue && options.Value.MaximumThreads != int.MaxValue))
{
Parallel.ForEach(collection, action, priority, options, blocking); return;
}
var batch = Cache<T>.Spare ?? new Batch<T>(); Cache<T>.Spare = null;
try
{
// Avoid Framework AddRange's per-call intermediate item array.
foreach (var item in collection) batch.Items.Add(item);
batch.Action = action; batch.Size = ChunkSize;
Interlocked.Increment(ref Dispatches); Interlocked.Add(ref ItemsProcessed, batch.Items.Count);
Parallel.For(0, (batch.Items.Count + batch.Size - 1) / batch.Size, batch.Run, 1, priority, options, true);
}
finally { batch.Action = null; batch.Items.Clear(); Cache<T>.Spare = batch; }
}
public static IEnumerable<CodeInstruction> ReplaceLoop(IEnumerable<CodeInstruction> instructions)
{
var result = new List<CodeInstruction>(); int matches = 0;
foreach (var instruction in instructions)
{
if (instruction.opcode == OpCodes.Call && instruction.operand is MethodInfo method
&& method.DeclaringType == typeof(Parallel) && method.Name == "ForEach" && method.IsGenericMethod
&& method.GetGenericArguments()[0].Name == "IMyParallelUpdateable" && method.GetParameters().Length == 5)
{
instruction.operand = AccessTools.Method(typeof(EntityBatching), nameof(Run)).MakeGenericMethod(method.GetGenericArguments());
matches++;
}
result.Add(instruction);
}
if (matches != 1) throw new NotSupportedException("Unsupported entity update loop; expected one parallel dispatch.");
return result;
}
}
}
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using HarmonyLib;
using ParallelTasks;
namespace XFE.SeAgent.Plugin.Performance
{
// Only replace the loop already declared parallel by the engine. Its outer
// Havok shared-read scope, entity initialization drain and join stay intact.
// Snapshot enumeration on the caller removes the shared enumerator's lock
// from every worker callback; bounded chunks retain dynamic load balancing.
internal static class EntityBatching
{
internal static int ChunkSize = 8;
public static long Dispatches, ItemsProcessed;
private static class Cache<T>
{
[ThreadStatic] internal static Batch<T> Spare;
}
private sealed class Batch<T>
{
internal readonly List<T> Items = new List<T>();
internal Action<T> Action;
internal int Size;
internal readonly Action<int> Run;
internal Batch() { Run = Chunk; }
private void Chunk(int index)
{
int end = Math.Min((index + 1) * Size, Items.Count);
for (int i = index * Size; i < end; i++) Action(Items[i]);
}
}
public static void Run<T>(IEnumerable<T> collection, Action<T> action,
WorkPriority priority, WorkOptions? options, bool blocking)
{
// Parallel.For in this engine overwrites MaximumThreads. Preserve
// any explicit cap by falling back, and never alter async lifetime.
if (!blocking || (options.HasValue && options.Value.MaximumThreads != int.MaxValue))
{
Parallel.ForEach(collection, action, priority, options, blocking); return;
}
var batch = Cache<T>.Spare ?? new Batch<T>(); Cache<T>.Spare = null;
try
{
// Avoid Framework AddRange's per-call intermediate item array.
foreach (var item in collection) batch.Items.Add(item);
batch.Action = action; batch.Size = ChunkSize;
Interlocked.Increment(ref Dispatches); Interlocked.Add(ref ItemsProcessed, batch.Items.Count);
Parallel.For(0, (batch.Items.Count + batch.Size - 1) / batch.Size, batch.Run, 1, priority, options, true);
}
finally { batch.Action = null; batch.Items.Clear(); Cache<T>.Spare = batch; }
}
public static IEnumerable<CodeInstruction> ReplaceLoop(IEnumerable<CodeInstruction> instructions)
{
var result = new List<CodeInstruction>(); int matches = 0;
foreach (var instruction in instructions)
{
if (instruction.opcode == OpCodes.Call && instruction.operand is MethodInfo method
&& method.DeclaringType == typeof(Parallel) && method.Name == "ForEach" && method.IsGenericMethod
&& method.GetGenericArguments()[0].Name == "IMyParallelUpdateable" && method.GetParameters().Length == 5)
{
instruction.operand = AccessTools.Method(typeof(EntityBatching), nameof(Run)).MakeGenericMethod(method.GetGenericArguments());
matches++;
}
result.Add(instruction);
}
if (matches != 1) throw new NotSupportedException("Unsupported entity update loop; expected one parallel dispatch.");
return result;
}
}
}