Copy Aetheria Code
Added a bunch of code from the old Aetheria project
This commit is contained in:
parent
ab392cd3d6
commit
c58ba0b1da
1704 changed files with 175081 additions and 313 deletions
25
Assets/Scripts/ColorButton.cs
Normal file
25
Assets/Scripts/ColorButton.cs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using UnityEngine.UI.Extensions.ColorPicker;
|
||||
|
||||
public class ColorButton : MonoBehaviour {
|
||||
public ColorChangedEvent OnColorChanged = new ColorChangedEvent();
|
||||
|
||||
// Use this for initialization
|
||||
void Start () {
|
||||
var colorPicker = transform.root.GetComponentInChildren<ColorPickerControl>(true);
|
||||
var image = GetComponent<Image>();
|
||||
GetComponent<Button>().onClick.AddListener(() =>
|
||||
{
|
||||
colorPicker.gameObject.SetActive(true);
|
||||
colorPicker.CurrentColor = image.color;
|
||||
colorPicker.onValueChanged.AddListener(col =>
|
||||
{
|
||||
image.color = col;
|
||||
OnColorChanged.Invoke(col);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ColorButton.cs.meta
Normal file
11
Assets/Scripts/ColorButton.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 017a6733a6cd4ee4b99d7c53f15d21da
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
145
Assets/Scripts/Database.cs
Normal file
145
Assets/Scripts/Database.cs
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using MessagePack;
|
||||
using UniRx;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
|
||||
#if UNITY_EDITOR
|
||||
[InitializeOnLoad]
|
||||
#endif
|
||||
public class Database
|
||||
{
|
||||
public static event Action OnDataUpdate;
|
||||
|
||||
private static Dictionary<Guid, IDatabaseEntry> Entries = new Dictionary<Guid, IDatabaseEntry>();
|
||||
|
||||
private static Dictionary<Type, Dictionary<Guid, IDatabaseEntry>> Types = new Dictionary<Type, Dictionary<Guid, IDatabaseEntry>>();
|
||||
|
||||
private static DirectoryInfo _dir;
|
||||
|
||||
private static IDatabaseEntry Load(string path)
|
||||
{
|
||||
var bytes = File.ReadAllBytes(path);
|
||||
// Debug.Log("Deserializing item: \n" + MessagePackSerializer.ToJson(bytes));
|
||||
try
|
||||
{
|
||||
var entry = MessagePackSerializer.Deserialize<IDatabaseEntry>(bytes);
|
||||
if (entry != null)
|
||||
{
|
||||
Entries[entry.GetId()] = entry;
|
||||
var type = entry.GetType();
|
||||
var types = type.FindInterfaces((_, __) => true, null).Append(type);
|
||||
foreach (var t in types)
|
||||
{
|
||||
if(!Types.ContainsKey(t))
|
||||
Types[t] = new Dictionary<Guid, IDatabaseEntry>();
|
||||
Types[t][entry.GetId()] = entry;
|
||||
}
|
||||
OnDataUpdate?.Invoke();
|
||||
}
|
||||
|
||||
return entry;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Log($"Encountered exception while reading item {path.Split('\\').Last()}:\n{MessagePackSerializer.SerializeToJson(bytes)}\n{e.StackTrace}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static IEnumerable<IDatabaseEntry> AllEntries => Entries.Values;
|
||||
|
||||
public static IDatabaseEntry Get(Guid guid)
|
||||
{
|
||||
IDatabaseEntry entry;
|
||||
Entries.TryGetValue(guid, out entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
public static T Get<T>(Guid guid) where T : IDatabaseEntry
|
||||
{
|
||||
IDatabaseEntry entry;
|
||||
Types[typeof(T)].TryGetValue(guid, out entry);
|
||||
return (T) entry;
|
||||
}
|
||||
|
||||
public static IEnumerable<T> GetAll<T>()
|
||||
{
|
||||
return Types[typeof(T)].Values.Cast<T>();
|
||||
}
|
||||
|
||||
public static void Save(IDatabaseEntry entry)
|
||||
{
|
||||
// Debug.Log("Serializing item: \n" + item.ToJson());
|
||||
var dir = new DirectoryInfo(Path.Combine(_dir.FullName, entry.GetType().Name));
|
||||
if(!dir.Exists)
|
||||
dir.Create();
|
||||
File.WriteAllBytes(Path.Combine(dir.FullName, entry.GetId().ToString()), entry.Serialize());
|
||||
}
|
||||
|
||||
public static void Duplicate(IDatabaseEntry entry)
|
||||
{
|
||||
var oldID = entry.Entry.ID;
|
||||
entry.Entry.ID = Guid.NewGuid();
|
||||
Save(entry);
|
||||
var dir = new DirectoryInfo(Path.Combine(_dir.FullName, entry.GetType().Name));
|
||||
Load(Path.Combine(dir.FullName, oldID.ToString()));
|
||||
}
|
||||
|
||||
public static void SaveAll()
|
||||
{
|
||||
foreach (var entry in GetAll<IDatabaseEntry>())
|
||||
{
|
||||
Save(entry);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Delete(IDatabaseEntry entry)
|
||||
{
|
||||
var dir = new DirectoryInfo(Path.Combine(_dir.FullName, entry.GetType().Name));
|
||||
File.Delete(Path.Combine(dir.FullName,entry.GetId().ToString()));
|
||||
}
|
||||
|
||||
static Database()
|
||||
{
|
||||
_dir = new DirectoryInfo(Application.dataPath).Parent.CreateSubdirectory("GameData");
|
||||
|
||||
Action<string> update = path => Load(path);
|
||||
|
||||
foreach (var file in Directory.GetFiles(_dir.FullName, "*.*", SearchOption.AllDirectories))
|
||||
update(file);
|
||||
|
||||
var watcher = new FileSystemWatcher(_dir.FullName);
|
||||
watcher.IncludeSubdirectories = true;
|
||||
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
|
||||
watcher.Changed += (_, args) => MainThreadDispatcher.Post(__ => update(args.FullPath), null);
|
||||
watcher.Created += (_, args) => MainThreadDispatcher.Post(__ => update(args.FullPath), null);
|
||||
watcher.Deleted += (_, args) => MainThreadDispatcher.Post(__ =>
|
||||
{
|
||||
var entryGuid = Guid.Parse(args.Name.Split('\\').Last());
|
||||
foreach (var entries in Types.Values)
|
||||
entries.Remove(entryGuid);
|
||||
Entries.Remove(entryGuid);
|
||||
OnDataUpdate?.Invoke();
|
||||
}, null);
|
||||
watcher.EnableRaisingEvents = true;
|
||||
}
|
||||
}
|
||||
|
||||
public interface IDatabaseEntry
|
||||
{
|
||||
DatabaseEntry Entry { get; }
|
||||
}
|
||||
|
||||
[Inspectable]
|
||||
[MessagePackObject]
|
||||
public class DatabaseEntry
|
||||
{
|
||||
[Key("id")] public Guid ID = Guid.NewGuid();
|
||||
[Inspectable] [Key("name")] public string Name;
|
||||
[Inspectable] [Key("description")] public string Description;
|
||||
}
|
||||
11
Assets/Scripts/Database.cs.meta
Normal file
11
Assets/Scripts/Database.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: a43b39c6991618b43aed4a24ffcdc0ff
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
99
Assets/Scripts/Extensions.cs
Normal file
99
Assets/Scripts/Extensions.cs
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text.RegularExpressions;
|
||||
using MessagePack;
|
||||
using Unity.Mathematics;
|
||||
using UnityEngine;
|
||||
using Random = UnityEngine.Random;
|
||||
|
||||
public static class Extensions
|
||||
{
|
||||
public static void BroadcastMessageExt<T>(this GameObject go, string methodName, object value = null, SendMessageOptions options = SendMessageOptions.RequireReceiver)
|
||||
{
|
||||
var monoList = new List<T>();
|
||||
go.GetComponentsInChildren(true, monoList);
|
||||
foreach (var component in monoList)
|
||||
{
|
||||
try
|
||||
{
|
||||
Type type = component.GetType();
|
||||
|
||||
MethodInfo method = type.GetMethod(methodName, BindingFlags.Instance |
|
||||
BindingFlags.NonPublic |
|
||||
BindingFlags.Public |
|
||||
BindingFlags.Static);
|
||||
|
||||
method.Invoke(component, new[] { value });
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
//Re-create the Error thrown by the original SendMessage function
|
||||
if (options == SendMessageOptions.RequireReceiver)
|
||||
Debug.LogError("SendMessage " + methodName + " has no receiver!");
|
||||
|
||||
//Debug.LogError(e.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static bool IsDefault<T>(this T value) where T : struct
|
||||
{
|
||||
bool isDefault = value.Equals(default(T));
|
||||
|
||||
return isDefault;
|
||||
}
|
||||
|
||||
public static Texture2D ToTexture(this Color c)
|
||||
{
|
||||
Texture2D result = new Texture2D(1, 1);
|
||||
result.SetPixels(new[]{c});
|
||||
result.Apply();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static Vector2 Flatland(this Vector3 v)
|
||||
{
|
||||
return new Vector2(v.x, v.z);
|
||||
}
|
||||
|
||||
public static Vector3 Flatland(this Vector2 v)
|
||||
{
|
||||
return new Vector3(v.x, 0, v.y);
|
||||
}
|
||||
|
||||
public static string SplitCamelCase( this string str )
|
||||
{
|
||||
return Regex.Replace(
|
||||
Regex.Replace(
|
||||
str,
|
||||
@"(\P{Ll})(\P{Ll}\p{Ll})",
|
||||
"$1 $2"
|
||||
),
|
||||
@"(\p{Ll})(\P{Ll})",
|
||||
"$1 $2"
|
||||
);
|
||||
}
|
||||
|
||||
public static T RandomElement<T>(this IEnumerable<T> enumerable) => enumerable.ElementAt(Random.Range(0, enumerable.Count()));
|
||||
|
||||
public static float2 ToFloat2(this Vector2 v) => new float2(v.x, v.y);
|
||||
public static float3 ToFloat3(this Vector3 v) => new float3(v.x, v.y, v.z);
|
||||
public static Vector2 ToVector2(this float2 v) => new Vector2(v.x, v.y);
|
||||
public static Vector3 ToVector3(this float3 v) => new Vector3(v.x, v.y, v.z);
|
||||
|
||||
public static IDatabaseEntry Get(this Guid entry) => Database.Get(entry);
|
||||
public static T Get<T>(this Guid entry) where T : class, IDatabaseEntry => Database.Get(entry) as T;
|
||||
public static Guid GetId(this IDatabaseEntry entry) => entry.Entry.ID;
|
||||
public static string ToJson(this IDatabaseEntry entry) => MessagePackSerializer.SerializeToJson(entry);
|
||||
public static byte[] Serialize(this IDatabaseEntry entry) => MessagePackSerializer.Serialize(entry);
|
||||
|
||||
public static bool IsImplementationOf(this Type baseType, Type interfaceType)
|
||||
{
|
||||
return baseType.GetInterfaces().Any(interfaceType.Equals);
|
||||
}
|
||||
|
||||
}
|
||||
11
Assets/Scripts/Extensions.cs.meta
Normal file
11
Assets/Scripts/Extensions.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 187eed4f0b5d7034aac5f16dbfccb14d
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
246
Assets/Scripts/Galaxy.cs
Normal file
246
Assets/Scripts/Galaxy.cs
Normal file
|
|
@ -0,0 +1,246 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
//using MessagePack;
|
||||
using UnityEngine;
|
||||
using NaughtyAttributes;
|
||||
using JM.LinqFaster;
|
||||
|
||||
[CreateAssetMenu(menuName = "Aetheria/Galaxy")]
|
||||
public class Galaxy : ScriptableObject
|
||||
{
|
||||
public GalaxyMapData MapData;
|
||||
public List<ContinentData> NameDatabase;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class GalaxyMapData
|
||||
{
|
||||
public int Arms = 4;
|
||||
public float Twist = 10;
|
||||
public float TwistPower = 2;
|
||||
|
||||
[HideInInspector]
|
||||
public GalaxyMapLayerData StarDensity;
|
||||
[HideInInspector]
|
||||
public List<GalaxyMapLayerData> CultureDensities = new List<GalaxyMapLayerData>();
|
||||
//[HideInInspector]
|
||||
public List<StarData> Stars = new List<StarData>();
|
||||
}
|
||||
|
||||
public static class StarListExtensions
|
||||
{
|
||||
class DijkstraStar
|
||||
{
|
||||
public float Cost;
|
||||
public DijkstraStar Parent;
|
||||
public StarData Star;
|
||||
}
|
||||
|
||||
public static List<StarData> FindPath(this List<StarData> stars, StarData source, StarData target, bool bestFirst = false)
|
||||
{
|
||||
SortedList<float,DijkstraStar> members = new SortedList<float,DijkstraStar>{{0,new DijkstraStar{Star = source}}};
|
||||
List<DijkstraStar> searched = new List<DijkstraStar>();
|
||||
while (true)
|
||||
{
|
||||
var s = members.FirstOrDefault(m => !searched.Contains(m.Value)).Value; // Lowest cost unsearched node
|
||||
if (s == null) return null; // No vertices left unsearched
|
||||
if (s.Star == target) // We found the path
|
||||
{
|
||||
Stack<DijkstraStar> path = new Stack<DijkstraStar>(); // Since we start at the end, use a LIFO collection
|
||||
path.Push(s);
|
||||
while(path.Peek().Parent!=null) // Keep pushing until we reach the start, which has no parent
|
||||
path.Push(path.Peek().Parent);
|
||||
return path.Select(dv => dv.Star).ToList();
|
||||
}
|
||||
// foreach (var dijkstraStar in s.Star.Links.Select(i => stars[i]) // All adjacent stars
|
||||
// .Where(n => members.All(m => m.Value.Star != n)) // That are not members
|
||||
// .Select(n => new DijkstraStar {Parent = s, Star = n, Cost = s.Cost + (s.Star.Position - n.Position).magnitude}))
|
||||
// For each adjacent star (filter already visited stars unless heuristic is in use)
|
||||
foreach (var dijkstraStar in s.Star.Links.WhereSelectF(i => !bestFirst || members.All(m => m.Value.Star != stars[i]),
|
||||
// Cost is parent cost plus distance
|
||||
i => new DijkstraStar {Parent = s, Star = stars[i], Cost = s.Cost + (s.Star.Position - stars[i].Position).magnitude}))
|
||||
// Add new member to list, sorted by cost plus optional heuristic
|
||||
members.Add(bestFirst ? dijkstraStar.Cost + (dijkstraStar.Star.Position - target.Position).magnitude : dijkstraStar.Cost, dijkstraStar);
|
||||
searched.Add(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class StarData
|
||||
{
|
||||
public Vector2 Position;
|
||||
public List<int> Links = new List<int>();
|
||||
public string NameSource;
|
||||
public List<string> Names = new List<string>();
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class GalaxyMapLayerData
|
||||
{
|
||||
public float CoreBoost = 1.05f;
|
||||
public float CoreBoostOffset = .1f;
|
||||
public float CoreBoostPower = 2.25f;
|
||||
public float EdgeReduction = 3;
|
||||
public float NoiseOffset = 0;
|
||||
public float NoiseAmplitude = 1.5f;
|
||||
public float NoiseGain = .7f;
|
||||
public float NoiseLacunarity = 2;
|
||||
public int NoiseOctaves = 7;
|
||||
public float NoiseFrequency = 1;
|
||||
public int NoiseSeed = 1337;
|
||||
|
||||
private FastNoise _noise = new FastNoise();
|
||||
|
||||
public float Evaluate(Vector2 uv, GalaxyMapData galaxy)
|
||||
{
|
||||
_noise.SetFractalGain(NoiseGain);
|
||||
_noise.SetFractalLacunarity(NoiseLacunarity);
|
||||
_noise.SetFractalOctaves(NoiseOctaves);
|
||||
_noise.SetFrequency(NoiseFrequency);
|
||||
_noise.SetSeed(NoiseSeed);
|
||||
|
||||
Func<Vector2, Vector2> offset = v => Vector2.one / 2 - v;
|
||||
Func<Vector2, float> circle = v => (.5f - v.magnitude) * 2;
|
||||
Func<Vector2, Vector2> twist = v => v.Rotate(Mathf.Pow(v.magnitude*2,galaxy.TwistPower)*galaxy.Twist);
|
||||
Func<Vector2, float> spokes = v => Mathf.Sin(Mathf.Atan2(-v.y,v.x)*galaxy.Arms);
|
||||
var c = circle(offset(uv));
|
||||
return Mathf.Clamp01((Mathf.Lerp(spokes(twist(offset(uv))) - EdgeReduction * offset(uv).magnitude, 1,
|
||||
Mathf.Pow(c + CoreBoostOffset, CoreBoostPower) * CoreBoost) - (_noise.GetPerlin(uv.x,uv.y)+NoiseOffset) * NoiseAmplitude) * Mathf.Clamp01(c));
|
||||
}
|
||||
}
|
||||
|
||||
public static class Vector2Extension {
|
||||
|
||||
public static Vector2 Rotate(this Vector2 v, float degrees) {
|
||||
float sin = Mathf.Sin(degrees * Mathf.Deg2Rad);
|
||||
float cos = Mathf.Cos(degrees * Mathf.Deg2Rad);
|
||||
|
||||
float tx = v.x;
|
||||
float ty = v.y;
|
||||
v.x = (cos * tx) - (sin * ty);
|
||||
v.y = (sin * tx) + (cos * ty);
|
||||
return v;
|
||||
}
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class NameData
|
||||
{
|
||||
public Dictionary<string, Dictionary<string, List<string>>> Names = new Dictionary<string, Dictionary<string, List<string>>>();
|
||||
|
||||
public void Add(string dataString)
|
||||
{
|
||||
//Debug.Log("Adding " + dataString);
|
||||
var all = dataString.Split(',');
|
||||
var name = all[0].Split(" -.".ToCharArray(),StringSplitOptions.RemoveEmptyEntries).OrderByDescending(s=>s.Length).First();
|
||||
var region = all[1].Split('/');
|
||||
var continent = region[0];
|
||||
var capital = region[1];
|
||||
if(!Names.ContainsKey(continent))
|
||||
Names[continent] = new Dictionary<string, List<string>>();
|
||||
if(!Names[continent].ContainsKey(capital))
|
||||
Names[continent][capital] = new List<string>();
|
||||
Names[continent][capital].Add(name);
|
||||
}
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class ContinentData
|
||||
{
|
||||
public string Name;
|
||||
public List<RegionData> Regions;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class RegionData
|
||||
{
|
||||
public string Name;
|
||||
public List<string> Towns;
|
||||
}
|
||||
|
||||
public class VoronoiLink
|
||||
{
|
||||
public Vertex2 point1;
|
||||
public Vertex2 point2;
|
||||
|
||||
public float Length { get { return (point1.ToVector2() - point2.ToVector2()).magnitude; } }
|
||||
|
||||
public VoronoiLink(Vertex2 p1, Vertex2 p2)
|
||||
{
|
||||
point1 = p1;
|
||||
point2 = p2;
|
||||
}
|
||||
|
||||
public bool ContainsPoint(Vertex2 p)
|
||||
{
|
||||
return point1 == p || point2 == p;
|
||||
}
|
||||
}
|
||||
|
||||
public static class VoronoiLinkExtensions
|
||||
{
|
||||
class DijkstraVertex
|
||||
{
|
||||
public double Cost;
|
||||
public double Heuristic;
|
||||
public DijkstraVertex Parent;
|
||||
public Vertex2 Vertex;
|
||||
}
|
||||
|
||||
public static bool ContainsLine(this IEnumerable<VoronoiLink> data, VoronoiLink l)
|
||||
{
|
||||
return
|
||||
data.Any(
|
||||
line =>
|
||||
(line.point1 == l.point1 && line.point2 == l.point2) ||
|
||||
(line.point1 == l.point2 && line.point2 == l.point1));
|
||||
}
|
||||
|
||||
public static IEnumerable<Vertex2> FindPath(this IEnumerable<VoronoiLink> data, Vertex2 source, Vertex2 target, bool bestFirst = true)
|
||||
{
|
||||
List<DijkstraVertex> members = new List<DijkstraVertex>{new DijkstraVertex{Vertex = source}};
|
||||
List<Vertex2> searched = new List<Vertex2>();
|
||||
while (true)
|
||||
{
|
||||
var v = members.Where(m=>!searched.Contains(m.Vertex)).OrderBy(m=>bestFirst?m.Heuristic:m.Cost).FirstOrDefault();
|
||||
if (v == null) return null; // No vertices left unsearched
|
||||
if (v.Vertex == target)
|
||||
{
|
||||
Stack<DijkstraVertex> path = new Stack<DijkstraVertex>();
|
||||
path.Push(v);
|
||||
while(path.Peek().Parent!=null)
|
||||
path.Push(path.Peek().Parent);
|
||||
return path.Select(dv => dv.Vertex).ToList();
|
||||
}
|
||||
members.AddRange(data.Where(l => l.point1 == v.Vertex).Select(l => l.point2).Concat(data.Where(l => l.point2 == v.Vertex).Select(l => l.point1))
|
||||
.Where(n => members.All(m => m.Vertex != n)).Select(n =>
|
||||
{
|
||||
var c = new DijkstraVertex {Parent = v, Vertex = n, Cost = v.Cost + v.Vertex.Distance(n)};
|
||||
if (bestFirst)
|
||||
c.Heuristic = c.Cost + c.Vertex.Distance(target);
|
||||
return c;
|
||||
}));
|
||||
searched.Add(v.Vertex);
|
||||
}
|
||||
}
|
||||
|
||||
public static IEnumerable<Vertex2> ConnectedRegion(this IEnumerable<VoronoiLink> data, Vertex2 v)
|
||||
{
|
||||
List<Vertex2> members = new List<Vertex2>();
|
||||
members.Add(v);
|
||||
while (true)
|
||||
{
|
||||
int lastCount = members.Count;
|
||||
// For each member, add all vertices that are connected to it via a line but are not already a member
|
||||
foreach (Vertex2 m in members.ToArray())
|
||||
members.AddRange(data.Where(l => l.point1 == m).Select(l => l.point2).Concat(data.Where(l => l.point2 == m).Select(l => l.point1))
|
||||
.Where(n => !members.Contains(n)));
|
||||
// If we have stopped finding neighbors, stop traversing
|
||||
if (members.Count == lastCount)
|
||||
return members;
|
||||
}
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/Galaxy.cs.meta
Normal file
11
Assets/Scripts/Galaxy.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: a17905e2bcacd37408f3f6e93b9885e9
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
8
Assets/Scripts/NIH.meta
Normal file
8
Assets/Scripts/NIH.meta
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
fileFormatVersion: 2
|
||||
guid: ec3325b6b8b1a504b8de9e3553bce449
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
2368
Assets/Scripts/NIH/FastNoise.cs
Normal file
2368
Assets/Scripts/NIH/FastNoise.cs
Normal file
File diff suppressed because it is too large
Load diff
11
Assets/Scripts/NIH/FastNoise.cs.meta
Normal file
11
Assets/Scripts/NIH/FastNoise.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 53b469b8da6bd4e4bb62cb13d1ce301d
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
8
Assets/Scripts/NIH/LinqFaster.meta
Normal file
8
Assets/Scripts/NIH/LinqFaster.meta
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
fileFormatVersion: 2
|
||||
guid: f577b52edee2c39429e13166dc0fddc2
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
207
Assets/Scripts/NIH/LinqFaster/Aggregate.cs
Normal file
207
Assets/Scripts/NIH/LinqFaster/Aggregate.cs
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides faster array and list specific extension methods with
|
||||
/// the same semantics as the Linq extensions methods.
|
||||
/// </summary>
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
|
||||
// ------------------------------ Arrays --------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Applies an accumulator function over an array.
|
||||
/// </summary>
|
||||
/// <param name="source">An array to aggregate over.</param>
|
||||
/// <param name="func">An accumulator function to be invoked on each element</param>
|
||||
/// <returns>The final accumulator value</returns>
|
||||
public static TSource AggregateF<TSource>(this TSource[] source, Func<TSource, TSource, TSource> func)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (func == null)
|
||||
{
|
||||
throw Error.ArgumentNull("func");
|
||||
}
|
||||
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
TSource result = source[0];
|
||||
for (int i = 1; i < source.Length; i++)
|
||||
{
|
||||
result = func(result, source[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies an accumulator function over an array. The specified seed
|
||||
/// value is used as the initial accumulator value.
|
||||
/// </summary>
|
||||
/// <param name="source">An array to aggregate over.</param>
|
||||
/// <param name="seed">The initial accumulator value.</param>
|
||||
/// <param name="func">An accumulator function to be invoked on each element</param>
|
||||
/// <returns>The final accumulator value</returns>
|
||||
public static TAccumulate AggregateF<TSource, TAccumulate>(this TSource[] source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (func == null)
|
||||
{
|
||||
throw Error.ArgumentNull("func");
|
||||
}
|
||||
|
||||
TAccumulate result = seed;
|
||||
foreach (var v in source)
|
||||
{
|
||||
result = func(result, v);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies an accumulator function over an array. The specified seed
|
||||
/// value is used as the initial accumulator value, and the specified
|
||||
/// function is used to select the result value.
|
||||
/// </summary>
|
||||
/// <param name="source">An array to aggregate over.</param>
|
||||
/// <param name="seed">The initial accumulator value.</param>
|
||||
/// <param name="func">An accumulator function to be invoked on each element</param>
|
||||
/// <param name="resultSelector">A function to transform the final accumulator value into the result value.</param>
|
||||
/// <returns>The transformed final accumulator value</returns>
|
||||
public static TResult AggregateF<TSource, TAccumulate, TResult>(this TSource[] source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func, Func<TAccumulate, TResult> resultSelector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (func == null)
|
||||
{
|
||||
throw Error.ArgumentNull("func");
|
||||
}
|
||||
|
||||
if (resultSelector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("resultSelector");
|
||||
}
|
||||
|
||||
TAccumulate result = seed;
|
||||
foreach (var v in source)
|
||||
{
|
||||
result = func(result, v);
|
||||
}
|
||||
return resultSelector(result);
|
||||
}
|
||||
|
||||
// ------------------------------ Lists --------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Applies an accumulator function over a List.
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource"></typeparam>
|
||||
/// <param name="source">A List to aggregate over.</param>
|
||||
/// <param name="func">An accumulator function to be invoked on each element</param>
|
||||
/// <returns>The final accumulator value</returns>
|
||||
public static TSource AggregateF<TSource>(this List<TSource> source, Func<TSource, TSource, TSource> func)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (func == null)
|
||||
{
|
||||
throw Error.ArgumentNull("func");
|
||||
}
|
||||
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
TSource result = source[0];
|
||||
for (int i = 1; i < source.Count; i++)
|
||||
{
|
||||
result = func(result, source[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies an accumulator function over a List. The specified seed
|
||||
/// value is used as the initial accumulator value.
|
||||
/// </summary>
|
||||
/// <param name="source">A List to aggregate over.</param>
|
||||
/// <param name="seed">The initial accumulator value.</param>
|
||||
/// <param name="func">An accumulator function to be invoked on each element</param>
|
||||
/// <returns>The final accumulator value</returns>
|
||||
public static TAccumulate AggregateF<TSource, TAccumulate>(this List<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (func == null)
|
||||
{
|
||||
throw Error.ArgumentNull("func");
|
||||
}
|
||||
|
||||
TAccumulate result = seed;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
result = func(result, source[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies an accumulator function over a List. The specified seed
|
||||
/// value is used as the initial accumulator value, and the specified
|
||||
/// function is used to select the result value.
|
||||
/// </summary>
|
||||
/// <param name="source">A List to aggregate over.</param>
|
||||
/// <param name="seed">The initial accumulator value.</param>
|
||||
/// <param name="func">An accumulator function to be invoked on each element</param>
|
||||
/// <param name="resultSelector">A function to transform the final accumulator value into the result value.</param>
|
||||
/// <returns>The transformed final accumulator value</returns>
|
||||
public static TResult AggregateF<TSource, TAccumulate, TResult>(this List<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func, Func<TAccumulate, TResult> resultSelector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (func == null)
|
||||
{
|
||||
throw Error.ArgumentNull("func");
|
||||
}
|
||||
|
||||
if (resultSelector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("resultSelector");
|
||||
}
|
||||
|
||||
TAccumulate result = seed;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
result = func(result, source[i]);
|
||||
}
|
||||
return resultSelector(result);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/Aggregate.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Aggregate.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: c982561dda0276f48b28c8fa12295ad4
|
||||
timeCreated: 1518622478
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
133
Assets/Scripts/NIH/LinqFaster/AnyAll.cs
Normal file
133
Assets/Scripts/NIH/LinqFaster/AnyAll.cs
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
|
||||
// -------------------------- ARRAYS --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether an array contains any elements
|
||||
/// </summary>
|
||||
/// <param name="source">The array to check for emptiness</param>
|
||||
/// <returns>true if the source array contains any elements, otherwise, false/</returns>
|
||||
public static bool AnyF<T>(this T[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
return source.Length > 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether any element of an array satifies a condition.
|
||||
/// </summary>
|
||||
/// <param name="source">An array whose elements to apply the predicate to.</param>
|
||||
/// <param name="predicate">A function to test each element for a condition.</param>
|
||||
/// <returns>true if any elements in the source array pass the test in the specified predicate; otherwise, false.</returns>
|
||||
public static bool AnyF<TSource>(this TSource[] source, Predicate<TSource> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
return Array.Exists(source, predicate);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether all elements of an array satisfy a condition.
|
||||
/// </summary>
|
||||
/// <param name="source">An array that contains the elements to apply the predicate to.</param>
|
||||
/// <param name="predicate">A function to test each element for a condition.</param>
|
||||
/// <returns>true if every element of the source array passes the test in the specified
|
||||
/// predicate, or if the array is empty; otherwise, false</returns>
|
||||
public static bool AllF<TSource>(this TSource[] source, Predicate<TSource> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
return Array.TrueForAll(source, predicate);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// -------------------------- Lists --------------------------------------------
|
||||
/// <summary>
|
||||
/// Determines whether a list contains any elements
|
||||
/// </summary>
|
||||
/// <param name="source">The list to check for emptiness</param>
|
||||
/// <returns>true if the source list contains any elements, otherwise, false/</returns>
|
||||
public static bool AnyF<T>(this List<T> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
return source.Count > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether any element of an array satifies a condition.
|
||||
/// </summary>
|
||||
/// <param name="source">An array whose elements to apply the predicate to.</param>
|
||||
/// <param name="predicate">A function to test each element for a condition.</param>
|
||||
/// <returns>true if any elements in the source array pass the test in the specified predicate; otherwise, false.</returns>
|
||||
public static bool AnyF<TSource>(this List<TSource> source, Predicate<TSource> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
return source.Exists(predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether all elements of a list satisfy a condition.
|
||||
/// </summary>
|
||||
/// <param name="source">A list that contains the elements to apply the predicate to.</param>
|
||||
/// <param name="predicate">A function to test each element for a condition.</param>
|
||||
/// <returns>true if every element of the source array passes the test in the specified
|
||||
/// predicate, or if the list is empty; otherwise, false</returns>
|
||||
public static bool AllF<TSource>(this List<TSource> source, Predicate<TSource> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
return source.TrueForAll(predicate);
|
||||
}
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/AnyAll.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/AnyAll.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 0f33f6b80d5e4d24bb1f5b42a26585e8
|
||||
timeCreated: 1518622476
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
633
Assets/Scripts/NIH/LinqFaster/Average.cs
Normal file
633
Assets/Scripts/NIH/LinqFaster/Average.cs
Normal file
|
|
@ -0,0 +1,633 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
// -------------------------- ARRAYS --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Computes the average of an array
|
||||
/// </summary>
|
||||
/// <param name="source">The array to calculate the average of.</param>
|
||||
/// <returns>The average of the array.</returns>
|
||||
public static double AverageF(this int[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
long sum = 0;
|
||||
checked
|
||||
{
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
sum += source[i];
|
||||
}
|
||||
}
|
||||
return (double)sum / source.Length;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the average of values obtained by invoking a transform function on
|
||||
/// each element of the input array.
|
||||
/// </summary>
|
||||
/// <param name="source">The array to calculate the transformed average of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The average of the array.</returns>
|
||||
public static double AverageF<T>(this T[] source, Func<T, int> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
long sum = 0;
|
||||
checked
|
||||
{
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
sum += selector(source[i]);
|
||||
}
|
||||
}
|
||||
return (double)sum / source.Length;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the average of an array
|
||||
/// </summary>
|
||||
/// <param name="source">The array to calculate the average of.</param>
|
||||
/// <returns>The average of the array.</returns>
|
||||
public static double AverageF(this long[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
long sum = 0;
|
||||
checked
|
||||
{
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
sum += source[i];
|
||||
}
|
||||
}
|
||||
return (double)sum / source.Length;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Computes the average of values obtained by invoking a transform function on
|
||||
/// each element of the input array.
|
||||
/// </summary>
|
||||
/// <param name="source">The array to calculate the transformed average of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The average of the array.</returns>
|
||||
public static double AverageF<T>(this T[] source, Func<T, long> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
long sum = 0;
|
||||
checked
|
||||
{
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
sum += selector(source[i]);
|
||||
}
|
||||
}
|
||||
return (double)sum / source.Length;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the average of an array
|
||||
/// </summary>
|
||||
/// <param name="source">The array to calculate the average of.</param>
|
||||
/// <returns>The average of the array.</returns>
|
||||
public static float AverageF(this float[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
double sum = 0;
|
||||
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
sum += source[i];
|
||||
}
|
||||
|
||||
return (float)(sum / source.Length);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the average of values obtained by invoking a transform function on
|
||||
/// each element of the input array.
|
||||
/// </summary>
|
||||
/// <param name="source">The array to calculate the transformed average of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The average of the array.</returns>
|
||||
public static float AverageF<T>(this T[] source, Func<T, float> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
double sum = 0;
|
||||
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
sum += selector(source[i]);
|
||||
}
|
||||
|
||||
return (float)(sum / source.Length);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the average of an array
|
||||
/// </summary>
|
||||
/// <param name="source">The array to calculate the average of.</param>
|
||||
/// <returns>The average of the array.</returns>
|
||||
public static double AverageF(this double[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
double sum = 0;
|
||||
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
sum += source[i];
|
||||
}
|
||||
|
||||
return sum / source.Length;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the average of values obtained by invoking a transform function on
|
||||
/// each element of the input array.
|
||||
/// </summary>
|
||||
/// <param name="source">The array to calculate the transformed average of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The average of the array.</returns>
|
||||
public static double AverageF<T>(this T[] source, Func<T, double> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
double sum = 0;
|
||||
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
sum += selector(source[i]);
|
||||
}
|
||||
|
||||
return sum / source.Length;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the average of an array
|
||||
/// </summary>
|
||||
/// <param name="source">The array to calculate the average of.</param>
|
||||
/// <returns>The average of the array.</returns>
|
||||
public static decimal AverageF(this decimal[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
decimal sum = 0;
|
||||
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
sum += source[i];
|
||||
}
|
||||
|
||||
return sum / source.Length;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the average of values obtained by invoking a transform function on
|
||||
/// each element of the input array.
|
||||
/// </summary>
|
||||
/// <param name="source">The array to calculate the transformed average of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The average of the array.</returns>
|
||||
public static decimal AverageF<T>(this T[] source, Func<T, decimal> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
|
||||
decimal sum = 0;
|
||||
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
sum += selector(source[i]);
|
||||
}
|
||||
|
||||
return sum / source.Length;
|
||||
}
|
||||
|
||||
// -------------------------- Lists --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Computes the average of a list.
|
||||
/// </summary>
|
||||
/// <param name="source">The list to calculate the average of.</param>
|
||||
/// <returns>The average of the list.</returns>
|
||||
public static double AverageF(this List<int> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
long sum = 0;
|
||||
checked
|
||||
{
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
sum += source[i];
|
||||
}
|
||||
}
|
||||
return (double)sum / source.Count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the average of values obtained by invoking a transform function on
|
||||
/// each element of the input array.
|
||||
/// </summary>
|
||||
/// <param name="source">The array to calculate the transformed average of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The average of the array.</returns>
|
||||
public static double AverageF<T>(this List<T> source, Func<T, int> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
long sum = 0;
|
||||
checked
|
||||
{
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
sum += selector(source[i]);
|
||||
}
|
||||
}
|
||||
return (double)sum / source.Count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the average of a list.
|
||||
/// </summary>
|
||||
/// <param name="source">The list to calculate the average of.</param>
|
||||
/// <returns>The average of the list.</returns>
|
||||
public static double AverageF(this List<long> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
long sum = 0;
|
||||
checked
|
||||
{
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
sum += source[i];
|
||||
}
|
||||
}
|
||||
return (double)sum / source.Count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the average of values obtained by invoking a transform function on
|
||||
/// each element of the input array.
|
||||
/// </summary>
|
||||
/// <param name="source">The array to calculate the transformed average of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The average of the array.</returns>
|
||||
public static double AverageF<T>(this List<T> source, Func<T, long> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
long sum = 0;
|
||||
checked
|
||||
{
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
sum += selector(source[i]);
|
||||
}
|
||||
}
|
||||
return (double)sum / source.Count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the average of a list.
|
||||
/// </summary>
|
||||
/// <param name="source">The list to calculate the average of.</param>
|
||||
/// <returns>The average of the list.</returns>
|
||||
public static float AverageF(this List<float> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
double sum = 0;
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
sum += source[i];
|
||||
}
|
||||
|
||||
return (float)(sum / source.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the average of values obtained by invoking a transform function on
|
||||
/// each element of the input array.
|
||||
/// </summary>
|
||||
/// <param name="source">The array to calculate the transformed average of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The average of the array.</returns>
|
||||
public static float AverageF<T>(this List<T> source, Func<T, float> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
double sum = 0;
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
sum += selector(source[i]);
|
||||
}
|
||||
|
||||
return (float)(sum / source.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the average of a list.
|
||||
/// </summary>
|
||||
/// <param name="source">The list to calculate the average of.</param>
|
||||
/// <returns>The average of the list.</returns>
|
||||
public static double AverageF(this List<double> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
double sum = 0;
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
sum += source[i];
|
||||
}
|
||||
|
||||
return sum / source.Count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the average of values obtained by invoking a transform function on
|
||||
/// each element of the input array.
|
||||
/// </summary>
|
||||
/// <param name="source">The array to calculate the transformed average of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The average of the array.</returns>
|
||||
public static double AverageF<T>(this List<T> source, Func<T, double> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
double sum = 0;
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
sum += selector(source[i]);
|
||||
}
|
||||
|
||||
return sum / source.Count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the average of a list.
|
||||
/// </summary>
|
||||
/// <param name="source">The list to calculate the average of.</param>
|
||||
/// <returns>The average of the list.</returns>
|
||||
public static decimal AverageF(this List<decimal> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
decimal sum = 0;
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
sum += source[i];
|
||||
}
|
||||
|
||||
return sum / source.Count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the average of values obtained by invoking a transform function on
|
||||
/// each element of the input array.
|
||||
/// </summary>
|
||||
/// <param name="source">The array to calculate the transformed average of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The average of the array.</returns>
|
||||
public static decimal AverageF<T>(this List<T> source, Func<T, decimal> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
|
||||
decimal sum = 0;
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
sum += selector(source[i]);
|
||||
}
|
||||
|
||||
return sum / source.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/Average.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Average.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 03ad52f1464dca347a72680cef2af96a
|
||||
timeCreated: 1518622476
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
77
Assets/Scripts/NIH/LinqFaster/Contains.cs
Normal file
77
Assets/Scripts/NIH/LinqFaster/Contains.cs
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
|
||||
// -------------------------- ARRAYS --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether an array contains a specified element by using the
|
||||
/// provided IEqualityComparer.
|
||||
/// </summary>
|
||||
/// <param name="source">An array in which to locate a value.</param>
|
||||
/// <param name="value">The value to locate.</param>
|
||||
/// <param name="comparer">An equality comparer to compare values.</param>
|
||||
/// <returns>true if the source sequence contains an element that has the specified value; otherwise, false.</returns>
|
||||
public static bool ContainsF<TSource>(this TSource[] source, TSource value, IEqualityComparer<TSource> comparer = null)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (comparer == null)
|
||||
{
|
||||
return Array.IndexOf(source, value) != -1;
|
||||
}
|
||||
|
||||
|
||||
foreach (TSource e in source)
|
||||
{
|
||||
if (comparer.Equals(e, value))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// -------------------------- Lists --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether a list contains a specified element by using the
|
||||
/// provided IEqualityComparer.
|
||||
/// </summary>
|
||||
/// <param name="source">A list in which to locate a value.</param>
|
||||
/// <param name="value">The value to locate.</param>
|
||||
/// <param name="comparer">An equality comparer to compare values.</param>
|
||||
/// <returns>true if the source sequence contains an element that has the specified value; otherwise, false.</returns>
|
||||
public static bool ContainsF<TSource>(this List<TSource> source, TSource value, IEqualityComparer<TSource> comparer = null)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (comparer == null)
|
||||
{
|
||||
return source.IndexOf(value) != -1;
|
||||
}
|
||||
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
if (comparer.Equals(source[i], value))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/Contains.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Contains.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: b2bd3dc5ff6476641a57d43d3692ce23
|
||||
timeCreated: 1518622477
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
86
Assets/Scripts/NIH/LinqFaster/Count.cs
Normal file
86
Assets/Scripts/NIH/LinqFaster/Count.cs
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
|
||||
// -------------------------- Arrays --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Returns a number that represents how many elements in the specified
|
||||
/// array satisfy a condition.
|
||||
/// </summary>
|
||||
/// <param name="source">An array that contains elements to be tested and counted.</param>
|
||||
/// <param name="predicate">A function to test each element for a condition.</param>
|
||||
/// <returns>A number that represents how many elements in the array satisfy the condition
|
||||
/// in the predicate function.</returns>
|
||||
public static int CountF<T>(this T[] source, Func<T, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
int count = 0;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
checked
|
||||
{
|
||||
if (predicate(source[i]))
|
||||
{
|
||||
count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
|
||||
// ------------------------------ Lists ---------------------
|
||||
|
||||
/// <summary>
|
||||
/// Returns a number that represents how many elements in the specified
|
||||
/// list satisfy a condition.
|
||||
/// </summary>
|
||||
/// <param name="source">A list that contains elements to be tested and counted.</param>
|
||||
/// <param name="predicate">A function to test each element for a condition.</param>
|
||||
/// <returns>A number that represents how many elements in the list satisfy the condition
|
||||
/// in the predicate function.</returns>
|
||||
public static int CountF<T>(this List<T> source, Func<T, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
int count = 0;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
checked
|
||||
{
|
||||
if (predicate(source[i]))
|
||||
{
|
||||
count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/Count.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Count.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 5337c0db0f170274587167b132a927c7
|
||||
timeCreated: 1518622476
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
53
Assets/Scripts/NIH/LinqFaster/Distinct.cs
Normal file
53
Assets/Scripts/NIH/LinqFaster/Distinct.cs
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
|
||||
// -------------------------- LISTS --------------------------------------------
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Removes duplicate elements from source, does not maintain order. Elements will be
|
||||
/// sorted in ascending order.
|
||||
/// </summary>
|
||||
/// <param name="source">The list to remove duplicate elements from.</param>
|
||||
/// <param name="eqComparer">Optional IEqualityComparer to compare values.</param>
|
||||
/// <param name="comparer">Optional IComparer to compare values.</param>
|
||||
public static void DistinctInPlaceF<TSource>(this List<TSource> source, IEqualityComparer<TSource> eqComparer = null, IComparer<TSource> comparer = null)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (comparer == null)
|
||||
{
|
||||
comparer = Comparer<TSource>.Default;
|
||||
}
|
||||
|
||||
if (eqComparer == null)
|
||||
{
|
||||
eqComparer = EqualityComparer<TSource>.Default;
|
||||
}
|
||||
|
||||
source.Sort(comparer);
|
||||
|
||||
TSource oldV = source[0];
|
||||
int pos = 1;
|
||||
for (int i = 1; i < source.Count; i++)
|
||||
{
|
||||
var newV = source[i];
|
||||
source[pos] = newV;
|
||||
if (!eqComparer.Equals(newV, oldV))
|
||||
{
|
||||
pos++;
|
||||
}
|
||||
oldV = newV;
|
||||
}
|
||||
source.RemoveRange(pos, source.Count - pos);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/Distinct.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Distinct.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: d04d64ff5ae302449a864bfaae8dcfda
|
||||
timeCreated: 1518622478
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
202
Assets/Scripts/NIH/LinqFaster/First.cs
Normal file
202
Assets/Scripts/NIH/LinqFaster/First.cs
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
|
||||
// -------------------------- Arrays --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Returns the first element of an array.
|
||||
/// </summary>
|
||||
/// <param name="source">The array to return the first element of.</param>
|
||||
/// <returns>The first element in the specified array.</returns>
|
||||
public static T FirstF<T>(this T[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
return source[0];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the first element in an array that satisfies a specified condition.
|
||||
/// </summary>
|
||||
/// <param name="source">An array to return an element from.</param>
|
||||
/// <param name="predicate">A function to teast each element for a condition.</param>
|
||||
/// <returns>The first element that satisfies the condition.</returns>
|
||||
public static T FirstF<T>(this T[] source, Func<T, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
if (predicate(source[i]))
|
||||
{
|
||||
return source[i];
|
||||
}
|
||||
}
|
||||
|
||||
throw Error.NoMatch();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Returns the first element of an array, or a default value if the
|
||||
/// array contains no elements.
|
||||
/// </summary>
|
||||
/// <param name="source">The array to return the first element of.</param>
|
||||
/// <returns>default value if source is empty, otherwise, the first element
|
||||
/// in source.</returns>
|
||||
public static T FirstOrDefaultF<T>(this T[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
return default(T);
|
||||
}
|
||||
return source[0];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the first element of the sequence that satisfies a condition or a
|
||||
/// default value if no such element is found.
|
||||
/// </summary>
|
||||
/// <param name="source">An IEnumerable to return an element from.</param>
|
||||
/// <param name="predicate">A function to test each element for a condition.</param>
|
||||
/// <returns></returns>
|
||||
public static T FirstOrDefaultF<T>(this T[] source, Func<T, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
if (predicate(source[i]))
|
||||
{
|
||||
return source[i];
|
||||
}
|
||||
}
|
||||
|
||||
return default(T);
|
||||
}
|
||||
|
||||
// -------------------------- Lists --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Returns the first element of a list
|
||||
/// </summary>
|
||||
/// <param name="source">The list to return the first element of.</param>
|
||||
/// <returns>The first element in the specified list.</returns>
|
||||
public static T FirstF<T>(this List<T> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
return source[0];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the first element in a list that satisfies a specified condition.
|
||||
/// </summary>
|
||||
/// <param name="source">An list to return an element from.</param>
|
||||
/// <param name="predicate">A function to teast each element for a condition.</param>
|
||||
/// <returns>The first element in the list that satisfies the condition.</returns>
|
||||
public static T FirstF<T>(this List<T> source, Predicate<T> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
var firstIndex = source.FindIndex(predicate);
|
||||
if (firstIndex == -1)
|
||||
throw Error.NoMatch();
|
||||
else
|
||||
return source[firstIndex];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the first element of an array, or a default value if the
|
||||
/// array contains no elements.
|
||||
/// </summary>
|
||||
/// <param name="source">The array to return the first element of.</param>
|
||||
/// <returns>default value if source is empty, otherwise, the first element
|
||||
/// in source.</returns>
|
||||
public static T FirstOrDefaultF<T>(this List<T> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
return default(T);
|
||||
}
|
||||
return source[0];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the first element of the sequence that satisfies a condition or a
|
||||
/// default value if no such element is found.
|
||||
/// </summary>
|
||||
/// <param name="source">An IEnumerable to return an element from.</param>
|
||||
/// <param name="predicate">A function to test each element for a condition.</param>
|
||||
/// <returns></returns>
|
||||
public static T FirstOrDefaultF<T>(this List<T> source, Predicate<T> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
var firstIndex = source.FindIndex(predicate);
|
||||
if (firstIndex == -1)
|
||||
return default(T);
|
||||
else
|
||||
return source[firstIndex];
|
||||
}
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/First.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/First.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 7c8f855844813a24f8d07be8c7d7b7c5
|
||||
timeCreated: 1518622476
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
194
Assets/Scripts/NIH/LinqFaster/Last.cs
Normal file
194
Assets/Scripts/NIH/LinqFaster/Last.cs
Normal file
|
|
@ -0,0 +1,194 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
// -------------------------- Arrays --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Returns the last element of a sequence.
|
||||
/// </summary>
|
||||
/// <param name="source">An sequence to return the last element of.</param>
|
||||
/// <returns>The value at the last position in the source sequence.</returns>
|
||||
public static T LastF<T>(this T[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
return source[source.Length - 1];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the last element of a sequence that satisfies a specified condition.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to return an element from.</param>
|
||||
/// <param name="predicate">A function to test each element for a condition.</param>
|
||||
/// <returns></returns>
|
||||
public static T LastF<T>(this T[] source, Predicate<T> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
var lastIndex = Array.FindLastIndex(source, predicate);
|
||||
|
||||
if (lastIndex == -1)
|
||||
throw Error.NoMatch();
|
||||
else
|
||||
return source[lastIndex];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the last element of a sequence, or a default value if the sequence contains no elements.
|
||||
/// </summary>
|
||||
/// <param name="source">An sequence to return the last element of.</param>
|
||||
/// <returns>default value if the source sequence is empty; otherwise,
|
||||
/// the last element in the sequence</returns>
|
||||
public static T LastOrDefaultF<T>(this T[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
return default(T);
|
||||
}
|
||||
return source[source.Length - 1];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the last element of a sequence that satisfies a condition or a default value if no such element is found.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to return the last element of.</param>
|
||||
/// <param name="predicate">A function to test each element for a condition.</param>
|
||||
/// <returns>default value if the sequence is empty or if no elements pass the test
|
||||
/// in the predicate function; otherwise, the last element that passes the test in the
|
||||
/// predicate function.</returns>
|
||||
public static T LastOrDefaultF<T>(this T[] source, Predicate<T> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
var lastIndex = Array.FindLastIndex(source, predicate);
|
||||
|
||||
if (lastIndex == -1)
|
||||
return default(T);
|
||||
else
|
||||
return source[lastIndex];
|
||||
}
|
||||
|
||||
// -------------------------- Lists --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Returns the last element of a sequence.
|
||||
/// </summary>
|
||||
/// <param name="source">An sequence to return the last element of.</param>
|
||||
/// <returns>The value at the last position in the source sequence.</returns>
|
||||
public static T LastF<T>(this List<T> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
return source[source.Count - 1];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the last element of a sequence that satisfies a specified condition.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to return an element from.</param>
|
||||
/// <param name="predicate">A function to test each element for a condition.</param>
|
||||
/// <returns></returns>
|
||||
public static T LastF<T>(this List<T> source, Predicate<T> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
var lastIndex = source.FindLastIndex(predicate);
|
||||
|
||||
if (lastIndex == -1)
|
||||
throw Error.NoMatch();
|
||||
else
|
||||
return source[lastIndex];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the last element of a sequence, or a default value if the sequence contains no elements.
|
||||
/// </summary>
|
||||
/// <param name="source">An sequence to return the last element of.</param>
|
||||
/// <returns>default value if the source sequence is empty; otherwise,
|
||||
/// the last element in the sequence</returns>
|
||||
public static T LastOrDefaultF<T>(this List<T> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
return default(T);
|
||||
}
|
||||
return source[source.Count - 1];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the last element of a sequence that satisfies a condition or a default value if no such element is found.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to return the last element of.</param>
|
||||
/// <param name="predicate">A function to test each element for a condition.</param>
|
||||
/// <returns>default value if the sequence is empty or if no elements pass the test
|
||||
/// in the predicate function; otherwise, the last element that passes the test in the
|
||||
/// predicate function.</returns>
|
||||
public static T LastOrDefaultF<T>(this List<T> source, Predicate<T> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
var lastIndex = source.FindLastIndex(predicate);
|
||||
|
||||
if (lastIndex == -1)
|
||||
return default(T);
|
||||
else
|
||||
return source[lastIndex];
|
||||
}
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/Last.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Last.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: aaf88d2684a9a9145ae297d38036fc14
|
||||
timeCreated: 1518622477
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
779
Assets/Scripts/NIH/LinqFaster/Max.cs
Normal file
779
Assets/Scripts/NIH/LinqFaster/Max.cs
Normal file
|
|
@ -0,0 +1,779 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
//int, long, float,double, decimal
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
// -------------------------- ARRAYS --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Returns the maximum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum of.</param>
|
||||
/// <returns>The maximum value in the sequence</returns>
|
||||
public static T MaxF<T>(this T[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
Comparer<T> comparer = Comparer<T>.Default;
|
||||
T r = default(T);
|
||||
if (r == null)
|
||||
{
|
||||
r = source[0];
|
||||
for (int i = 1; i < source.Length; i++)
|
||||
{
|
||||
if (source[i] != null && comparer.Compare(source[i], r) > 0) r = source[i];
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
r = source[0];
|
||||
for (int i = 1; i < source.Length; i++)
|
||||
{
|
||||
if (comparer.Compare(source[i], r) > 0) r = source[i];
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static TResult MaxF<T, TResult>(this T[] source, Func<T, TResult> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
Comparer<TResult> comparer = Comparer<TResult>.Default;
|
||||
TResult r = default(TResult);
|
||||
if (r == null)
|
||||
{
|
||||
r = selector(source[0]);
|
||||
for (int i = 1; i < source.Length; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v != null && comparer.Compare(v, r) > 0) r = v;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
r = selector(source[0]);
|
||||
for (int i = 1; i < source.Length; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (comparer.Compare(v, r) > 0) r = v;
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the maximum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum of.</param>
|
||||
/// <returns>The maximum value in the sequence</returns>
|
||||
public static int MaxF(this int[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
int r = int.MinValue;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
if (source[i] > r) r = source[i];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static int MaxF<T>(this T[] source, Func<T, int> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
int r = int.MinValue;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v > r) r = v;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the maximum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum of.</param>
|
||||
/// <returns>The maximum value in the sequence</returns>
|
||||
public static long MaxF(this long[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
long r = long.MinValue;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
if (source[i] > r) r = source[i];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static long MaxF<T>(this T[] source, Func<T, long> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
long r = long.MinValue;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v > r) r = v;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the maximum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum of.</param>
|
||||
/// <returns>The maximum value in the sequence</returns>
|
||||
public static float MaxF(this float[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
float r = source[0];
|
||||
int startIndex = 0;
|
||||
for (; startIndex < source.Length; startIndex++)
|
||||
{
|
||||
if (!float.IsNaN(source[startIndex]))
|
||||
{
|
||||
r = source[startIndex];
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (int i = startIndex; i < source.Length; i++)
|
||||
{
|
||||
if (source[i] > r) r = source[i];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static float MaxF<T>(this T[] source, Func<T, float> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
float r = selector(source[0]);
|
||||
int startIndex = 0;
|
||||
for (; startIndex < source.Length; startIndex++)
|
||||
{
|
||||
var v = selector(source[startIndex]);
|
||||
if (!float.IsNaN(v))
|
||||
{
|
||||
r = v;
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (int i = startIndex; i < source.Length; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v > r) r = v;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the maximum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum of.</param>
|
||||
/// <returns>The maximum value in the sequence</returns>
|
||||
public static double MaxF(this double[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
double r = source[0];
|
||||
int startIndex = 0;
|
||||
for (; startIndex < source.Length; startIndex++)
|
||||
{
|
||||
if (!double.IsNaN(source[startIndex]))
|
||||
{
|
||||
r = source[startIndex];
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (int i = startIndex; i < source.Length; i++)
|
||||
{
|
||||
if (source[i] > r) r = source[i];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static double MaxF<T>(this T[] source, Func<T, double> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
double r = selector(source[0]);
|
||||
int startIndex = 0;
|
||||
for (; startIndex < source.Length; startIndex++)
|
||||
{
|
||||
var v = selector(source[startIndex]);
|
||||
if (!double.IsNaN(v))
|
||||
{
|
||||
r = v;
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (int i = startIndex; i < source.Length; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v > r) r = v;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Returns the maximum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum of.</param>
|
||||
/// <returns>The maximum value in the sequence</returns>
|
||||
public static decimal MaxF(this decimal[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
decimal r = decimal.MinValue;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
if (source[i] > r) r = source[i];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static decimal MaxF<T>(this T[] source, Func<T, decimal> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
decimal r = decimal.MinValue;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v > r) r = v;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
// -------------------------- LISTS --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Returns the maximum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum of.</param>
|
||||
/// <returns>The maximum value in the sequence</returns>
|
||||
public static T MaxF<T>(this List<T> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
Comparer<T> comparer = Comparer<T>.Default;
|
||||
T r = default(T);
|
||||
if (r == null)
|
||||
{
|
||||
r = source[0];
|
||||
for (int i = 1; i < source.Count; i++)
|
||||
{
|
||||
if (source[i] != null && comparer.Compare(source[i], r) > 0) r = source[i];
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
r = source[0];
|
||||
for (int i = 1; i < source.Count; i++)
|
||||
{
|
||||
if (comparer.Compare(source[i], r) > 0) r = source[i];
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static TResult MaxF<T, TResult>(this List<T> source, Func<T, TResult> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
Comparer<TResult> comparer = Comparer<TResult>.Default;
|
||||
TResult r = default(TResult);
|
||||
if (r == null)
|
||||
{
|
||||
r = selector(source[0]);
|
||||
for (int i = 1; i < source.Count; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v != null && comparer.Compare(v, r) > 0) r = v;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
r = selector(source[0]);
|
||||
for (int i = 1; i < source.Count; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (comparer.Compare(v, r) > 0) r = v;
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Returns the maximum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum of.</param>
|
||||
/// <returns>The maximum value in the sequence</returns>
|
||||
public static int MaxF(this List<int> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
int r = int.MinValue;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
if (source[i] > r) r = source[i];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static int MaxF<T>(this List<T> source, Func<T, int> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
int r = int.MinValue;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v > r) r = v;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the maximum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum of.</param>
|
||||
/// <returns>The maximum value in the sequence</returns>
|
||||
public static long MaxF(this List<long> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
long r = long.MinValue;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
if (source[i] > r) r = source[i];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static long MaxF<T>(this List<T> source, Func<T, long> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
long r = long.MinValue;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v > r) r = v;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the maximum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum of.</param>
|
||||
/// <returns>The maximum value in the sequence</returns>
|
||||
public static float MaxF(this List<float> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
float r = source[0];
|
||||
int startIndex = 0;
|
||||
for (; startIndex < source.Count; startIndex++)
|
||||
{
|
||||
if (!float.IsNaN(source[startIndex]))
|
||||
{
|
||||
r = source[startIndex];
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (int i = startIndex; i < source.Count; i++)
|
||||
{
|
||||
if (source[i] > r) r = source[i];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static float MaxF<T>(this List<T> source, Func<T, float> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
float r = selector(source[0]);
|
||||
int startIndex = 0;
|
||||
for (; startIndex < source.Count; startIndex++)
|
||||
{
|
||||
var v = selector(source[startIndex]);
|
||||
if (!float.IsNaN(v))
|
||||
{
|
||||
r = v;
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (int i = startIndex; i < source.Count; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v > r) r = v;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the maximum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum of.</param>
|
||||
/// <returns>The maximum value in the sequence</returns>
|
||||
public static double MaxF(this List<double> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
double r = source[0];
|
||||
int startIndex = 0;
|
||||
for (; startIndex < source.Count; startIndex++)
|
||||
{
|
||||
if (!double.IsNaN(source[startIndex]))
|
||||
{
|
||||
r = source[startIndex];
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (int i = startIndex; i < source.Count; i++)
|
||||
{
|
||||
if (source[i] > r) r = source[i];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static double MaxF<T>(this List<T> source, Func<T, double> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
double r = selector(source[0]);
|
||||
int startIndex = 0;
|
||||
for (; startIndex < source.Count; startIndex++)
|
||||
{
|
||||
var v = selector(source[startIndex]);
|
||||
if (!double.IsNaN(v))
|
||||
{
|
||||
r = v;
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (int i = startIndex; i < source.Count; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v > r) r = v;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the maximum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum of.</param>
|
||||
/// <returns>The maximum value in the sequence</returns>
|
||||
public static decimal MaxF(this List<decimal> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
decimal r = decimal.MinValue;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
if (source[i] > r) r = source[i];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static decimal MaxF<T>(this List<T> source, Func<T, decimal> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
decimal r = decimal.MinValue;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v > r) r = v;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/Max.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Max.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: c48e3dffd69eb0a4e8e135b38d3d9bf0
|
||||
timeCreated: 1518622477
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
711
Assets/Scripts/NIH/LinqFaster/Min.cs
Normal file
711
Assets/Scripts/NIH/LinqFaster/Min.cs
Normal file
|
|
@ -0,0 +1,711 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
//int, long, float,double, decimal
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
// -------------------------- ARRAYS --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Returns the minimum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the minimum of.</param>
|
||||
/// <returns>The minimum value in the sequence</returns>
|
||||
public static T MinF<T>(this T[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
Comparer<T> comparer = Comparer<T>.Default;
|
||||
T r = default(T);
|
||||
if (r == null)
|
||||
{
|
||||
r = source[0];
|
||||
for (int i = 1; i < source.Length; i++)
|
||||
{
|
||||
if (source[i] != null && comparer.Compare(source[i], r) < 0) r = source[i];
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
r = source[0];
|
||||
for (int i = 1; i < source.Length; i++)
|
||||
{
|
||||
if (comparer.Compare(source[i], r) < 0) r = source[i];
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static TResult MinF<T, TResult>(this T[] source, Func<T, TResult> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
Comparer<TResult> comparer = Comparer<TResult>.Default;
|
||||
TResult r = default(TResult);
|
||||
if (r == null)
|
||||
{
|
||||
r = selector(source[0]);
|
||||
for (int i = 1; i < source.Length; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v != null && comparer.Compare(v, r) < 0) r = v;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
r = selector(source[0]);
|
||||
for (int i = 1; i < source.Length; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (comparer.Compare(v, r) < 0) r = v;
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the minimum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the minimum of.</param>
|
||||
/// <returns>The minimum value in the sequence</returns>
|
||||
public static int MinF(this int[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
int r = int.MaxValue;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
if (source[i] < r) r = source[i];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static int MinF<T>(this T[] source, Func<T, int> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
int r = int.MaxValue;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v < r) r = v;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the minimum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the minimum of.</param>
|
||||
/// <returns>The minimum value in the sequence</returns>
|
||||
public static long MinF(this long[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
long r = long.MaxValue;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
if (source[i] < r) r = source[i];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static long MinF<T>(this T[] source, Func<T, long> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
long r = long.MaxValue;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v < r) r = v;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the minimum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the minimum of.</param>
|
||||
/// <returns>The minimum value in the sequence</returns>
|
||||
public static float MinF(this float[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
float r = float.MaxValue;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
if (source[i] < r) r = source[i];
|
||||
else if (float.IsNaN(source[i])) return source[i];
|
||||
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static float MinF<T>(this T[] source, Func<T, float> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
float r = float.MaxValue;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v < r) r = v;
|
||||
else if (float.IsNaN(v)) return v;
|
||||
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the minimum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the minimum of.</param>
|
||||
/// <returns>The minimum value in the sequence</returns>
|
||||
public static double MinF(this double[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
double r = double.MaxValue;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
if (source[i] < r) r = source[i];
|
||||
else if (double.IsNaN(source[i])) return source[i];
|
||||
}
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static double MinF<T>(this T[] source, Func<T, double> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
double r = double.MaxValue;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v < r) r = v;
|
||||
else if (double.IsNaN(v)) return v;
|
||||
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the minimum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the minimum of.</param>
|
||||
/// <returns>The minimum value in the sequence</returns>
|
||||
public static decimal MinF(this decimal[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
decimal r = decimal.MaxValue;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
if (source[i] < r) r = source[i];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static decimal MinF<T>(this T[] source, Func<T, decimal> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
decimal r = decimal.MaxValue;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v < r) r = v;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
// -------------------------- LISTS --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Returns the minimum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the minimum of.</param>
|
||||
/// <returns>The minimum value in the sequence</returns>
|
||||
public static T MinF<T>(this List<T> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
Comparer<T> comparer = Comparer<T>.Default;
|
||||
T r = default(T);
|
||||
if (r == null)
|
||||
{
|
||||
r = source[0];
|
||||
for (int i = 1; i < source.Count; i++)
|
||||
{
|
||||
if (source[i] != null && comparer.Compare(source[i], r) < 0) r = source[i];
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
r = source[0];
|
||||
for (int i = 1; i < source.Count; i++)
|
||||
{
|
||||
if (comparer.Compare(source[i], r) < 0) r = source[i];
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the minimum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the minimum of.</param>
|
||||
/// <returns>The minimum value in the sequence</returns>
|
||||
public static int MinF(this List<int>source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
int r = int.MaxValue;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
if (source[i] < r) r = source[i];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static int MinF<T>(this List<T> source, Func<T, int> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
int r = int.MaxValue;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v < r) r = v;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the minimum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the minimum of.</param>
|
||||
/// <returns>The minimum value in the sequence</returns>
|
||||
public static long MinF(this List<long> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
long r = long.MaxValue;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
if (source[i] < r) r = source[i];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static long MinF<T>(this List<T> source, Func<T, long> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
long r = long.MaxValue;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v < r) r = v;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the minimum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the minimum of.</param>
|
||||
/// <returns>The minimum value in the sequence</returns>
|
||||
public static float MinF(this List<float> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
float r = float.MaxValue;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
if (source[i] < r) r = source[i];
|
||||
else if (float.IsNaN(source[i])) return source[i];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static float MinF<T>(this List<T> source, Func<T, float> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
float r = float.MaxValue;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v < r) r = v;
|
||||
else if (float.IsNaN(v)) return v;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the minimum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the minimum of.</param>
|
||||
/// <returns>The minimum value in the sequence</returns>
|
||||
public static double MinF(this List<double> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
double r = double.MaxValue;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
if (source[i] < r) r = source[i];
|
||||
else if (double.IsNaN(source[i])) return source[i];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static double MinF<T>(this List<T> source, Func<T, double> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
double r = double.MaxValue;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v < r) r = v;
|
||||
else if (double.IsNaN(v)) return v;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the minimum value in a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the minimum of.</param>
|
||||
/// <returns>The minimum value in the sequence</returns>
|
||||
public static decimal MinF(this List<decimal> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
decimal r = decimal.MaxValue;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
if (source[i] < r) r = source[i];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static decimal MinF<T>(this List<T> source, Func<T, decimal> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
decimal r = decimal.MaxValue;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v < r) r = v;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes a transform function on each element of a sequence and returns the maximum value.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to determine the maximum value of.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>The maximum value in the transform of the sequence.</returns>
|
||||
public static TResult MinF<T, TResult>(this List<T> source, Func<T, TResult> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
Comparer<TResult> comparer = Comparer<TResult>.Default;
|
||||
TResult r = default(TResult);
|
||||
if (r == null)
|
||||
{
|
||||
r = selector(source[0]);
|
||||
for (int i = 1; i < source.Count; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (v != null && comparer.Compare(v, r) < 0) r = v;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
r = selector(source[0]);
|
||||
for (int i = 1; i < source.Count; i++)
|
||||
{
|
||||
var v = selector(source[i]);
|
||||
if (comparer.Compare(v, r) < 0) r = v;
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/Min.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Min.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: e778ffbe0914c7c4e88564ff2ba27fff
|
||||
timeCreated: 1518622478
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
144
Assets/Scripts/NIH/LinqFaster/OrderBy.cs
Normal file
144
Assets/Scripts/NIH/LinqFaster/OrderBy.cs
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using JM.LinqFaster.Utils;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
/// <summary>
|
||||
/// Sorts the elements of a sequence in ascending order according to a key.
|
||||
/// Unlike standard Linq NOT a stable sort.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to order.</param>
|
||||
/// <param name="keySelector">A function to extract a key from an element.</param>
|
||||
/// <param name="comparer">A Comparer to compare keys.</param>
|
||||
/// <returns>A sequence whose alements are ordered according to a key</returns>
|
||||
public static TSource[] OrderByF<TSource, TKey>(this TSource[] source, Func<TSource, TKey> keySelector,IComparer<TKey> comparer = null)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (keySelector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("keySelector");
|
||||
}
|
||||
|
||||
if (comparer == null)
|
||||
{
|
||||
comparer = Comparer<TKey>.Default;
|
||||
}
|
||||
|
||||
var keys = new TKey[source.Length];
|
||||
for (int i = 0; i < keys.Length; i++)
|
||||
{
|
||||
keys[i] = keySelector(source[i]);
|
||||
}
|
||||
var result = (TSource[])source.Clone();
|
||||
Array.Sort(keys,result,comparer);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sorts the elements of a sequence in descending order according to a key.
|
||||
/// Unlike standard Linq NOT a stable sort.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to order.</param>
|
||||
/// <param name="keySelector">A function to extract a key from an element.</param>
|
||||
/// <param name="comparer">A Comparer to compare keys.</param>
|
||||
/// <returns>A sequence whose alements are ordered according to a key</returns>
|
||||
public static TSource[] OrderByDescendingF<TSource, TKey>(this TSource[] source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer = null) {
|
||||
if (source == null) {
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (keySelector == null) {
|
||||
throw Error.ArgumentNull("keySelector");
|
||||
}
|
||||
|
||||
if (comparer == null) {
|
||||
comparer = Comparer<TKey>.Default;
|
||||
}
|
||||
|
||||
var keys = new TKey[source.Length];
|
||||
for (int i = 0; i < keys.Length; i++) {
|
||||
keys[i] = keySelector(source[i]);
|
||||
}
|
||||
var result = (TSource[])source.Clone();
|
||||
Array.Sort(keys, result, comparer.Reverse());
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
// ---------------------- Lists
|
||||
|
||||
/// <summary>
|
||||
/// Sorts the elements of a sequence in ascending order according to a key.
|
||||
/// Unlike standard Linq NOT a stable sort.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to order.</param>
|
||||
/// <param name="keySelector">A function to extract a key from an element.</param>
|
||||
/// <param name="comparer">A Comparer to compare keys.</param>
|
||||
/// <returns>A sequence whose alements are ordered according to a key</returns>
|
||||
public static List<TSource> OrderByF<TSource, TKey>(this List<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer = null)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (keySelector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("keySelector");
|
||||
}
|
||||
|
||||
if (comparer == null)
|
||||
{
|
||||
comparer = Comparer<TKey>.Default;
|
||||
}
|
||||
|
||||
var result = new List<TSource>(source);
|
||||
var lambdaComparer = new LambdaComparer<TSource, TKey>(keySelector, comparer);
|
||||
result.Sort(lambdaComparer);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sorts the elements of a sequence in descending order according to a key.
|
||||
/// Unlike standard Linq NOT a stable sort.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to order.</param>
|
||||
/// <param name="keySelector">A function to extract a key from an element.</param>
|
||||
/// <param name="comparer">A Comparer to compare keys.</param>
|
||||
/// <returns>A sequence whose alements are ordered according to a key</returns>
|
||||
public static List<TSource> OrderByDescendingF<TSource, TKey>(this List<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer = null) {
|
||||
if (source == null) {
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (keySelector == null) {
|
||||
throw Error.ArgumentNull("keySelector");
|
||||
}
|
||||
|
||||
if (comparer == null) {
|
||||
comparer = Comparer<TKey>.Default;
|
||||
}
|
||||
|
||||
var result = new List<TSource>(source);
|
||||
var lambdaComparer = new ReverseLambdaComparer<TSource, TKey>(keySelector, comparer);
|
||||
result.Sort(lambdaComparer);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
13
Assets/Scripts/NIH/LinqFaster/OrderBy.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/OrderBy.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 0905671e8837b8746ab9d2540689f16c
|
||||
timeCreated: 1518622476
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
56
Assets/Scripts/NIH/LinqFaster/Range.cs
Normal file
56
Assets/Scripts/NIH/LinqFaster/Range.cs
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
/// <summary>
|
||||
/// Generates a sequence of integral numbers within a specified range.
|
||||
/// </summary>
|
||||
/// <param name="start">The value of the first integer in the sequence.</param>
|
||||
/// <param name="count">The number of sequential integers to generate.</param>
|
||||
/// <returns>A sequence that contains a range of sequential integral numbers.</returns>
|
||||
public static int[] RangeArrayF(int start, int count)
|
||||
{
|
||||
long max = ((long)start) + count - 1;
|
||||
if (count < 0 || max > int.MaxValue)
|
||||
{
|
||||
throw Error.ArgumentOutOfRange("count");
|
||||
}
|
||||
|
||||
|
||||
int[] result = new int[count];
|
||||
for (int i = 0; i < result.Length; i++)
|
||||
{
|
||||
result[i] = i + start;
|
||||
}
|
||||
return result;
|
||||
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Generates a sequence of integral numbers within a specified range.
|
||||
/// </summary>
|
||||
/// <param name="start">The value of the first integer in the sequence.</param>
|
||||
/// <param name="count">The number of sequential integers to generate.</param>
|
||||
/// <returns>A sequence that contains a range of sequential integral numbers.</returns>
|
||||
public static List<int> RangeListF(int start, int count)
|
||||
{
|
||||
long max = ((long)start) + count - 1;
|
||||
if (count < 0 || max > int.MaxValue)
|
||||
{
|
||||
throw Error.ArgumentOutOfRange("count");
|
||||
}
|
||||
|
||||
|
||||
var result = new List<int>(count);
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
result.Add(i + start);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/Range.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Range.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 2b57c73286e4b784a897b514585dcdc2
|
||||
timeCreated: 1518622476
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
46
Assets/Scripts/NIH/LinqFaster/Repeat.cs
Normal file
46
Assets/Scripts/NIH/LinqFaster/Repeat.cs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
|
||||
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
// ------------------------ Arrays ---------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Generates a sequence that contains one repeated value.
|
||||
/// </summary>
|
||||
/// <param name="element">The value to be repeated.</param>
|
||||
/// <param name="count">The number of times to repeat the value in the generated sequence.</param>
|
||||
/// <returns>A sequence that contains a repeated value</returns>
|
||||
public static T[] RepeatArrayF<T>(T element, int count)
|
||||
{
|
||||
var result = new T[count];
|
||||
for (int i = 0; i < result.Length; i++)
|
||||
{
|
||||
result[i] = element;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ------------------------ Lists ---------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Generates a sequence that contains one repeated value.
|
||||
/// </summary>
|
||||
/// <param name="element">The value to be repeated.</param>
|
||||
/// <param name="count">The number of times to repeat the value in the generated sequence.</param>
|
||||
/// <returns>A sequence that contains a repeated value</returns>
|
||||
public static List<T> RepeatListF<T>(T element, int count)
|
||||
{
|
||||
var result = new List<T>(count);
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
result.Add(element);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/Repeat.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Repeat.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: a9a067c2d04a41e499adfde8c8ab6956
|
||||
timeCreated: 1518622477
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
58
Assets/Scripts/NIH/LinqFaster/Reverse.cs
Normal file
58
Assets/Scripts/NIH/LinqFaster/Reverse.cs
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
/// <summary>
|
||||
/// Inverts the order of the elements in a sequence.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to reverse.</param>
|
||||
/// <returns>A sequence whose elements correspond to those of the input sequence in reverse order.</returns>
|
||||
public static T[] ReverseF<T>(this T[] source)
|
||||
{
|
||||
var result = new T[source.Length];
|
||||
long lenLessOne = source.Length - 1;
|
||||
for (int i = 0; i < result.Length; i++)
|
||||
{
|
||||
result[i] = source[lenLessOne - i];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Inverts the order of the elements in a sequence in place.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to reverse.</param>
|
||||
public static void ReverseInPlaceF<T>(this T[] source)
|
||||
{
|
||||
Array.Reverse(source);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inverts the order of the elements in a sequence.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to reverse.</param>
|
||||
/// <returns>A sequence whose elements correspond to those of the input sequence in reverse order.</returns>
|
||||
public static List<T> ReverseF<T>(this List<T> source)
|
||||
{
|
||||
var result = new List<T>(source.Count);
|
||||
for (int i = source.Count - 1; i >= 0; i--)
|
||||
{
|
||||
result.Add(source[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inverts the order of the elements in a sequence in place.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to reverse.</param>
|
||||
public static void ReverseInPlaceF<T>(this List<T> source)
|
||||
{
|
||||
source.Reverse();
|
||||
}
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/Reverse.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Reverse.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 060a1817dc4b6a14997095dfc23c4d3b
|
||||
timeCreated: 1518622476
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
219
Assets/Scripts/NIH/LinqFaster/Select.cs
Normal file
219
Assets/Scripts/NIH/LinqFaster/Select.cs
Normal file
|
|
@ -0,0 +1,219 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
|
||||
// -------------------------- ARRAYS --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Projects each element of a sequence into a new form in place.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to invoke a transform function on (map).</param>
|
||||
/// <param name="selector">A transform function to apply (map) to each element.</param>
|
||||
public static void SelectInPlaceF<T>(this T[] source, Func<T,T> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
source[i] = selector(source[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Projects each element of a sequence into a new form, in place, by incorporating the element's index.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to invoke a transform function on.</param>
|
||||
/// <param name="selector">A transform function to apply to each source element; the second parameter of the function represents the index of the source element.</param>
|
||||
public static void SelectInPlaceF<T>(this T[] source, Func<T, int, T> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
source[i] = selector(source[i], i);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Projects each element of a sequence into a new form. (map in every other language)
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to invoke a transform function on (map).</param>
|
||||
/// <param name="selector">A transform function to apply (map) to each element.</param>
|
||||
/// <returns>A sequence whose elements are the result of invoking the transform function on each element (mapping) of source.</returns>
|
||||
public static TResult[] SelectF<T, TResult>(this T[] source, Func<T, TResult> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
var r = new TResult[source.Length];
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
r[i] = selector(source[i]);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Projects each element of a sequence into a new form by incorporating the element's index.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to invoke a transform function on.</param>
|
||||
/// <param name="selector">A transform function to apply to each source element; the second parameter of the function represents the index of the source element.</param>
|
||||
/// <returns>A sequence whose elements are the result of invoking the transform function on each element of source.</returns>
|
||||
public static TResult[] SelectF<T, TResult>(this T[] source, Func<T, int, TResult> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
var r = new TResult[source.Length];
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
r[i] = selector(source[i], i);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
// -------------------------- LISTS --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Projects each element of a sequence into a new form in place.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to invoke a transform function on (map).</param>
|
||||
/// <param name="selector">A transform function to apply (map) to each element.</param>
|
||||
public static void SelectInPlaceF<T>(this List<T> source, Func<T, T> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
source[i] = selector(source[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Projects each element of a sequence into a new form, in place, by incorporating the element's index.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to invoke a transform function on.</param>
|
||||
/// <param name="selector">A transform function to apply to each source element; the second parameter of the function represents the index of the source element.</param>
|
||||
public static void SelectInPlaceF<T>(this List<T> source, Func<T, int, T> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
source[i] = selector(source[i], i);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Projects each element of a sequence into a new form. (map in every other language)
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to invoke a transform function on (map).</param>
|
||||
/// <param name="selector">A transform function to apply (map) to each element.</param>
|
||||
/// <returns>A sequence whose elements are the result of invoking the transform function on each element (mapping) of source.</returns>
|
||||
public static List<TResult> SelectF<T, TResult>(this List<T> source, Func<T, TResult> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
var r = new List<TResult>(source.Count);
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
r.Add(selector(source[i]));
|
||||
}
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Projects each element of a sequence into a new form by incorporating the element's index.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to invoke a transform function on.</param>
|
||||
/// <param name="selector">A transform function to apply to each source element; the second parameter of the function represents the index of the source element.</param>
|
||||
/// <returns>A sequence whose elements are the result of invoking the transform function on each element of source.</returns>
|
||||
public static List<TResult> SelectF<T, TResult>(this List<T> source, Func<T, int, TResult> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
var r = new List<TResult>(source.Count);
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
r.Add(selector(source[i],i));
|
||||
}
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/Select.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Select.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 26eaf75f376ca7147a6c161177592aca
|
||||
timeCreated: 1518622476
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
136
Assets/Scripts/NIH/LinqFaster/SelectMany.cs
Normal file
136
Assets/Scripts/NIH/LinqFaster/SelectMany.cs
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
// -------------------------- Arrays --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Projects each element of a sequence to another sequence and flattens the resulting sequences into one sequence.
|
||||
/// Yo dawg, I heard you like sequences.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to project.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>A sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.</returns>
|
||||
public static TResult[] SelectManyF<TSource, TResult>(this TSource[] source, Func<TSource, TResult[]> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
var result = new List<TResult>(source.Length);
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
var va = selector(source[i]);
|
||||
for (int j = 0; j < va.Length; j++)
|
||||
{
|
||||
result.Add(va[j]);
|
||||
}
|
||||
}
|
||||
return result.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Projects each element of a sequence to another sequence and flattens the resulting sequences into one sequence
|
||||
/// utilizing the index of each element.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to project.</param>
|
||||
/// <param name="selector">A transform function to apply to each element and it's index.</param>
|
||||
/// <returns>A sequence whose elements are the result of invoking the one-to-many transform function on each element and index of the input sequence.</returns>
|
||||
public static TResult[] SelectManyF<TSource, TResult>(this TSource[] source, Func<TSource, int, TResult[]> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
var result = new List<TResult>(source.Length);
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
var va = selector(source[i], i);
|
||||
for (int j = 0; j < va.Length; j++)
|
||||
{
|
||||
result.Add(va[j]);
|
||||
}
|
||||
}
|
||||
return result.ToArray();
|
||||
}
|
||||
|
||||
// -------------------------- LISTS --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Projects each element of a sequence to another sequence and flattens the resulting sequences into one sequence.
|
||||
/// Yo dawg, I heard you like sequences.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to project.</param>
|
||||
/// <param name="selector">A transform function to apply to each element.</param>
|
||||
/// <returns>A sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.</returns>
|
||||
public static List<TResult> SelectManyF<TSource, TResult>(this List<TSource> source, Func<TSource, List<TResult>> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
var result = new List<TResult>(source.Count);
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var va = selector(source[i]);
|
||||
for (int j = 0; j < va.Count; j++)
|
||||
{
|
||||
result.Add(va[j]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Projects each element of a sequence to another sequence and flattens the resulting sequences into one sequence
|
||||
/// utilizing the index of each element.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence of values to project.</param>
|
||||
/// <param name="selector">A transform function to apply to each element and it's index.</param>
|
||||
/// <returns>A sequence whose elements are the result of invoking the one-to-many transform function on each element and index of the input sequence.</returns>
|
||||
public static List<TResult> SelectManyF<TSource, TResult>(this List<TSource> source, Func<TSource, int, List<TResult>> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
var result = new List<TResult>(source.Count);
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var va = selector(source[i], i);
|
||||
for (int j = 0; j < va.Count; j++)
|
||||
{
|
||||
result.Add(va[j]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/SelectMany.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/SelectMany.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 8c94982c6c13eb2479b832d2210b5451
|
||||
timeCreated: 1518622476
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
142
Assets/Scripts/NIH/LinqFaster/SelectWhere.cs
Normal file
142
Assets/Scripts/NIH/LinqFaster/SelectWhere.cs
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
// -------------------------- ARRAYS --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Combines Select and Where into a single call for optimal
|
||||
/// performance.
|
||||
/// </summary>
|
||||
/// <param name="source">The input sequence to filter and select</param>
|
||||
/// <param name="selector">The transformation to apply before filtering.</param>
|
||||
/// <param name="predicate">The predicate with which to filter result.</param>
|
||||
/// <returns>A seqence transformed and then filtered by selector and predicate.</returns>
|
||||
public static TResult[] SelectWhereF<T, TResult>(this T[] source, Func<T, TResult> selector, Func<TResult, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
var result = new TResult[source.Length];
|
||||
int idx = 0;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
var s = selector(source[i]);
|
||||
if (predicate(s))
|
||||
{
|
||||
result[idx] = s;
|
||||
idx++;
|
||||
}
|
||||
}
|
||||
Array.Resize(ref result, idx);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Combines Select and Where with indexes into a single call for optimal
|
||||
/// performance.
|
||||
/// </summary>
|
||||
/// <param name="source">The input sequence to filter and select</param>
|
||||
/// <param name="selector">The transformation with index to apply before filtering.</param>
|
||||
/// <param name="predicate">The predicate with index with which to filter result.</param>
|
||||
/// <returns>A seqence transformed and then filtered by selector and predicate with indexes.</returns>
|
||||
public static TResult[] SelectWhereF<T, TResult>(this T[] source, Func<T, int, TResult> selector, Func<TResult, int, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
var result = new TResult[source.Length];
|
||||
int idx = 0;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
var s = selector(source[i], i);
|
||||
if (predicate(s, i))
|
||||
{
|
||||
result[idx] = s;
|
||||
idx++;
|
||||
}
|
||||
}
|
||||
Array.Resize(ref result, idx);
|
||||
return result;
|
||||
}
|
||||
|
||||
// -------------------------- LISTS --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Combines Select and Where into a single call for optimal
|
||||
/// performance.
|
||||
/// </summary>
|
||||
/// <param name="source">The input sequence to filter and select</param>
|
||||
/// <param name="selector">The transformation to apply before filtering.</param>
|
||||
/// <param name="predicate">The predicate with which to filter result.</param>
|
||||
/// <returns>A seqence transformed and then filtered by selector and predicate.</returns>
|
||||
public static List<TResult> SelectWhereF<T, TResult>(this List<T> source, Func<T, TResult> selector, Func<TResult, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
var r = new List<TResult>();
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var s = selector(source[i]);
|
||||
if (predicate(s)) r.Add(s);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Combines Select and Where with indexes into a single call for optimal
|
||||
/// performance.
|
||||
/// </summary>
|
||||
/// <param name="source">The input sequence to filter and select</param>
|
||||
/// <param name="selector">The transformation with index to apply before filtering.</param>
|
||||
/// <param name="predicate">The predicate with index with which to filter result.</param>
|
||||
/// <returns>A seqence transformed and then filtered by selector and predicate with indexes.</returns>
|
||||
public static List<TResult> SelectWhereF<T, TResult>(this List<T> source, Func<T, int, TResult> selector, Func<TResult, int, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
var r = new List<TResult>();
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var s = selector(source[i], i);
|
||||
if (predicate(s, i)) r.Add(s);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/SelectWhere.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/SelectWhere.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: d0a9e823f84f85049ae653bf4fc8c7b9
|
||||
timeCreated: 1518622478
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
153
Assets/Scripts/NIH/LinqFaster/SequenceEqual.cs
Normal file
153
Assets/Scripts/NIH/LinqFaster/SequenceEqual.cs
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether two sequences are equal by comparing the elements by using the
|
||||
/// provided comparer or the default equality comparer for their type if none is provided.
|
||||
/// </summary>
|
||||
/// <param name="first">A sequence to compare to second.</param>
|
||||
/// <param name="second">A sequence to compare to first.</param>
|
||||
/// <param name="comparer">An optional Comparer to use for the comparison.</param>
|
||||
/// <returns>true of the two sources are of equal length and their corresponding
|
||||
/// elements are equal according to the equality comparer. Otherwise, false.</returns>
|
||||
public static bool SequenceEqualF<T>(T[] first, T[] second, IEqualityComparer<T> comparer = null)
|
||||
{
|
||||
if (comparer == null)
|
||||
{
|
||||
comparer = EqualityComparer<T>.Default;
|
||||
}
|
||||
|
||||
if (first == null)
|
||||
{
|
||||
throw Error.ArgumentNull("first");
|
||||
}
|
||||
|
||||
if (second == null)
|
||||
{
|
||||
throw Error.ArgumentNull("second");
|
||||
}
|
||||
|
||||
if (first.Length != second.Length) return false;
|
||||
|
||||
for (int i = 0; i < first.Length; i++)
|
||||
{
|
||||
if (!comparer.Equals(first[i], second[i])) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether two sequences are equal by comparing the elements by using the
|
||||
/// provided comparer or the default equality comparer for their type if none is provided.
|
||||
/// </summary>
|
||||
/// <param name="first">A sequence to compare to second.</param>
|
||||
/// <param name="second">A sequence to compare to first.</param>
|
||||
/// <param name="comparer">An optional Comparer to use for the comparison.</param>
|
||||
/// <returns>true of the two sources are of equal length and their corresponding
|
||||
/// elements are equal according to the equality comparer. Otherwise, false.</returns>
|
||||
public static bool SequenceEqualF<T>(List<T> first, List<T> second, IEqualityComparer<T> comparer = null)
|
||||
{
|
||||
if (comparer == null)
|
||||
{
|
||||
comparer = EqualityComparer<T>.Default;
|
||||
}
|
||||
|
||||
if (first == null)
|
||||
{
|
||||
throw Error.ArgumentNull("first");
|
||||
}
|
||||
|
||||
if (second == null)
|
||||
{
|
||||
throw Error.ArgumentNull("second");
|
||||
}
|
||||
|
||||
if (first.Count != second.Count) return false;
|
||||
|
||||
for (int i = 0; i < first.Count; i++)
|
||||
{
|
||||
if (!comparer.Equals(first[i], second[i])) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether two sequences are equal by comparing the elements by using the
|
||||
/// provided comparer or the default equality comparer for their type if none is provided.
|
||||
/// </summary>
|
||||
/// <param name="first">A sequence to compare to second.</param>
|
||||
/// <param name="second">A sequence to compare to first.</param>
|
||||
/// <param name="comparer">An optional Comparer to use for the comparison.</param>
|
||||
/// <returns>true of the two sources are of equal length and their corresponding
|
||||
/// elements are equal according to the equality comparer. Otherwise, false.</returns>
|
||||
public static bool SequenceEqualF<T>(T[] first, List<T> second, IEqualityComparer<T> comparer = null)
|
||||
{
|
||||
if (comparer == null)
|
||||
{
|
||||
comparer = EqualityComparer<T>.Default;
|
||||
}
|
||||
|
||||
if (first == null)
|
||||
{
|
||||
throw Error.ArgumentNull("first");
|
||||
}
|
||||
|
||||
if (second == null)
|
||||
{
|
||||
throw Error.ArgumentNull("second");
|
||||
}
|
||||
|
||||
if (first.Length != second.Count) return false;
|
||||
|
||||
for (int i = 0; i < first.Length; i++)
|
||||
{
|
||||
if (!comparer.Equals(first[i], second[i])) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether two sequences are equal by comparing the elements by using the
|
||||
/// provided comparer or the default equality comparer for their type if none is provided.
|
||||
/// </summary>
|
||||
/// <param name="first">A sequence to compare to second.</param>
|
||||
/// <param name="second">A sequence to compare to first.</param>
|
||||
/// <param name="comparer">An optional Comparer to use for the comparison.</param>
|
||||
/// <returns>true of the two sources are of equal length and their corresponding
|
||||
/// elements are equal according to the equality comparer. Otherwise, false.</returns>
|
||||
public static bool SequenceEqualF<T>(List<T> first, T[] second, IEqualityComparer<T> comparer = null)
|
||||
{
|
||||
if (comparer == null)
|
||||
{
|
||||
comparer = EqualityComparer<T>.Default;
|
||||
}
|
||||
|
||||
if (first == null)
|
||||
{
|
||||
throw Error.ArgumentNull("first");
|
||||
}
|
||||
|
||||
if (second == null)
|
||||
{
|
||||
throw Error.ArgumentNull("second");
|
||||
}
|
||||
|
||||
if (first.Count != second.Length) return false;
|
||||
|
||||
for (int i = 0; i < first.Count; i++)
|
||||
{
|
||||
if (!comparer.Equals(first[i], second[i])) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/SequenceEqual.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/SequenceEqual.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 7fe4476c042c98d4dbae1292ea8da673
|
||||
timeCreated: 1518622476
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
275
Assets/Scripts/NIH/LinqFaster/Single.cs
Normal file
275
Assets/Scripts/NIH/LinqFaster/Single.cs
Normal file
|
|
@ -0,0 +1,275 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
// --------------------------- Arrays ----------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to return the single element of</param>
|
||||
/// <returns>The single element of the input sequence or default if no elements exist.</returns>
|
||||
public static T SingleF<T>(this T[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Length == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
if (source.Length > 1) {
|
||||
throw Error.MoreThanOneElement();
|
||||
}
|
||||
|
||||
return source[0];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the only element of a sequence, or the default if no elements exist, and throws an exception if there is not exactly one element in the sequence.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to return the single element of</param>
|
||||
/// <returns>The single element of the input sequence</returns>
|
||||
public static T SingleOrDefaultF<T>(this T[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Length == 0)
|
||||
{
|
||||
return default(T);
|
||||
}
|
||||
|
||||
if (source.Length > 1) {
|
||||
throw Error.MoreThanOneElement();
|
||||
}
|
||||
|
||||
return source[0];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to return a single element from.</param>
|
||||
/// <param name="predicate">A function to test an element for a condition.</param>
|
||||
/// <returns>The single element of the input sequence that satisfies a condition.</returns>
|
||||
public static T SingleF<T>(this T[] source, Func<T, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
T result = default(T);
|
||||
bool foundMatch = false;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
if (predicate(source[i]))
|
||||
{
|
||||
if (foundMatch)
|
||||
{
|
||||
throw Error.MoreThanOneMatch();
|
||||
}
|
||||
|
||||
result = source[i];
|
||||
foundMatch = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (foundMatch)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw Error.NoMatch();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the only element of a sequence that satisfies a specified condition, or a default value if
|
||||
/// no such element exists, and throws an exception if more than one such element exists.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to return a single element from.</param>
|
||||
/// <param name="predicate">A function to test an element for a condition.</param>
|
||||
/// <returns>The single element of the input sequence that satisfies a condition or default value if no such element is found.</returns>
|
||||
public static T SingleOrDefaultF<T>(this T[] source, Func<T, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
|
||||
T result = default(T);
|
||||
bool foundMatch = false;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
if (predicate(source[i]))
|
||||
{
|
||||
if (foundMatch)
|
||||
{
|
||||
throw Error.MoreThanOneMatch();
|
||||
}
|
||||
|
||||
result = source[i];
|
||||
foundMatch = true;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
// --------------------------- Lists ----------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to return the single element of</param>
|
||||
/// <returns>The single element of the input sequence</returns>
|
||||
public static T SingleF<T>(this List<T> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Count == 0)
|
||||
{
|
||||
throw Error.NoElements();
|
||||
}
|
||||
|
||||
if (source.Count > 1) {
|
||||
throw Error.MoreThanOneElement();
|
||||
}
|
||||
|
||||
return source[0];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the only element of a sequence, or default if no elements exist, and throws an exception if there is not exactly one element in the sequence.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to return the single element of</param>
|
||||
/// <returns>The single element of the input sequence or default if no elements exist.</returns>
|
||||
public static T SingleOrDefaultF<T>(this List<T> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (source.Count == 0)
|
||||
{
|
||||
return default(T);
|
||||
}
|
||||
|
||||
if (source.Count > 1) {
|
||||
throw Error.MoreThanOneElement();
|
||||
}
|
||||
|
||||
return source[0];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to return a single element from.</param>
|
||||
/// <param name="predicate">A function to test an element for a condition.</param>
|
||||
/// <returns>The single element of the input sequence that satisfies a condition.</returns>
|
||||
public static T SingleF<T>(this List<T> source, Func<T, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
T result = default(T);
|
||||
bool foundMatch = false;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
if (predicate(source[i]))
|
||||
{
|
||||
if (foundMatch)
|
||||
{
|
||||
throw Error.MoreThanOneMatch();
|
||||
}
|
||||
|
||||
result = source[i];
|
||||
foundMatch = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (foundMatch)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw Error.NoMatch();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the only element of a sequence that satisfies a specified condition, or a default value if
|
||||
/// no such element exists, and throws an exception if more than one such element exists.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to return a single element from.</param>
|
||||
/// <param name="predicate">A function to test an element for a condition.</param>
|
||||
/// <returns>The single element of the input sequence that satisfies a condition or default value if no such element is found.</returns>
|
||||
public static T SingleOrDefaultF<T>(this List<T> source, Func<T, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
T result = default(T);
|
||||
bool foundMatch = false;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
if (predicate(source[i]))
|
||||
{
|
||||
if (foundMatch)
|
||||
{
|
||||
throw Error.MoreThanOneMatch();
|
||||
}
|
||||
|
||||
result = source[i];
|
||||
foundMatch = true;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/Single.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Single.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 50d60901bb3bf014e8d8e1ceef8c4741
|
||||
timeCreated: 1518622476
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
129
Assets/Scripts/NIH/LinqFaster/Skip.cs
Normal file
129
Assets/Scripts/NIH/LinqFaster/Skip.cs
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
/// <summary>
|
||||
/// Bypasses a specified number of elements in a sequence and then returns the remaining elements.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to return elements from.</param>
|
||||
/// <param name="count">The number of elements to skip before returning the remaining elements.</param>
|
||||
/// <returns>A sequence that contains the elements that occur after the specified index in the input sequence.</returns>
|
||||
public static T[] SkipF<T>(this T[] source, int count)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (count < 0)
|
||||
{
|
||||
count = 0;
|
||||
}
|
||||
else if (count > source.Length)
|
||||
{
|
||||
return new T[0];
|
||||
}
|
||||
|
||||
var result = new T[source.Length - count];
|
||||
Array.Copy(source, count, result, 0, result.Length);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to return elements from.</param>
|
||||
/// <param name="predicate">A function to test each element for a condition.</param>
|
||||
/// <returns>A sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.</returns>
|
||||
public static T[] SkipWhileF<T>(this T[] source, Func<T, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
int i = 0;
|
||||
for (; i < source.Length; i++)
|
||||
{
|
||||
if (!predicate(source[i])) break;
|
||||
}
|
||||
var result = new T[source.Length - i];
|
||||
Array.Copy(source, i, result, 0, result.Length);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
// ------------- Lists ----------------
|
||||
|
||||
/// <summary>
|
||||
/// Bypasses a specified number of elements in a sequence and then returns the remaining elements.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to return elements from.</param>
|
||||
/// <param name="count">The number of elements to skip before returning the remaining elements.</param>
|
||||
/// <returns>A sequence that contains the elements that occur after the specified index in the input sequence.</returns>
|
||||
public static List<T> SkipF<T>(this List<T> source, int count)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (count < 0)
|
||||
{
|
||||
count = 0;
|
||||
}
|
||||
else if (count > source.Count)
|
||||
{
|
||||
return new List<T>();
|
||||
}
|
||||
|
||||
var result = new List<T>(source.Count - count);
|
||||
for (int i = count; i < source.Count; i++)
|
||||
{
|
||||
result.Add(source[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to return elements from.</param>
|
||||
/// <param name="predicate">A function to test each element for a condition.</param>
|
||||
/// <returns>A sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.</returns>
|
||||
public static List<T> SkipWhileF<T>(this List<T> source, Func<T, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
int i = 0;
|
||||
for (; i < source.Count; i++)
|
||||
{
|
||||
if (!predicate(source[i])) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var result = new List<T>(source.Count - i);
|
||||
for (; i < source.Count; i++)
|
||||
{
|
||||
result.Add(source[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/Skip.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Skip.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 0266806ba237aed45b52c7709de1fe6b
|
||||
timeCreated: 1518622476
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
504
Assets/Scripts/NIH/LinqFaster/Sum.cs
Normal file
504
Assets/Scripts/NIH/LinqFaster/Sum.cs
Normal file
|
|
@ -0,0 +1,504 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
// -------------------------- ARRAYS --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Adds a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to add.</param>
|
||||
/// <returns>The sum of the sequence.</returns>
|
||||
public static int SumF(this int[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
int sum = 0;
|
||||
checked
|
||||
{
|
||||
foreach (var v in source)
|
||||
{
|
||||
sum += v;
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the transformed sequence of elements.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence of values to transform then sum.</param>
|
||||
/// <param name="selector">A transformation function.</param>
|
||||
/// <returns>The sum of the transformed elements.</returns>
|
||||
public static int SumF<T>(this T[] source, Func<T, int> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
int sum = 0;
|
||||
checked
|
||||
{
|
||||
foreach (var v in source)
|
||||
{
|
||||
sum += selector(v);
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to add.</param>
|
||||
/// <returns>The sum of the sequence.</returns>
|
||||
public static long SumF(this long[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
long sum = 0;
|
||||
checked
|
||||
{
|
||||
foreach (var v in source)
|
||||
{
|
||||
sum += v;
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the transformed sequence of elements.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence of values to transform then sum.</param>
|
||||
/// <param name="selector">A transformation function.</param>
|
||||
/// <returns>The sum of the transformed elements.</returns>
|
||||
public static long SumF<T>(this T[] source, Func<T, long> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
long sum = 0;
|
||||
checked
|
||||
{
|
||||
foreach (var v in source)
|
||||
{
|
||||
sum += selector(v);
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to add.</param>
|
||||
/// <returns>The sum of the sequence.</returns>
|
||||
public static float SumF(this float[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
double sum = 0;
|
||||
|
||||
foreach (var v in source)
|
||||
{
|
||||
sum += v;
|
||||
}
|
||||
|
||||
return (float)sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the transformed sequence of elements.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence of values to transform then sum.</param>
|
||||
/// <param name="selector">A transformation function.</param>
|
||||
/// <returns>The sum of the transformed elements.</returns>
|
||||
public static float SumF<T>(this T[] source, Func<T, float> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
double sum = 0;
|
||||
foreach (var v in source)
|
||||
{
|
||||
sum += selector(v);
|
||||
}
|
||||
|
||||
return (float)sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to add.</param>
|
||||
/// <returns>The sum of the sequence.</returns>
|
||||
public static double SumF(this double[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
double sum = 0;
|
||||
foreach (var v in source)
|
||||
{
|
||||
sum += v;
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the transformed sequence of elements.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence of values to transform then sum.</param>
|
||||
/// <param name="selector">A transformation function.</param>
|
||||
/// <returns>The sum of the transformed elements.</returns>
|
||||
public static double SumF<T>(this T[] source, Func<T, double> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
double sum = 0;
|
||||
foreach (var v in source)
|
||||
{
|
||||
sum += selector(v);
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to add.</param>
|
||||
/// <returns>The sum of the sequence.</returns>
|
||||
public static decimal SumF(this decimal[] source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
decimal sum = 0;
|
||||
|
||||
foreach (var v in source)
|
||||
{
|
||||
sum += v;
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the transformed sequence of elements.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence of values to transform then sum.</param>
|
||||
/// <param name="selector">A transformation function.</param>
|
||||
/// <returns>The sum of the transformed elements.</returns>
|
||||
public static decimal SumF<T>(this T[] source, Func<T, decimal> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
decimal sum = 0;
|
||||
foreach (var v in source)
|
||||
{
|
||||
sum += selector(v);
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
// -------------------------- LISTS --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Adds a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to add.</param>
|
||||
/// <returns>The sum of the sequence.</returns>
|
||||
public static int SumF(this List<int> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
int sum = 0;
|
||||
checked
|
||||
{
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
sum += source[i];
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the transformed sequence of elements.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence of values to transform then sum.</param>
|
||||
/// <param name="selector">A transformation function.</param>
|
||||
/// <returns>The sum of the transformed elements.</returns>
|
||||
public static int SumF<T>(this List<T> source, Func<T, int> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
int sum = 0;
|
||||
checked
|
||||
{
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
sum += selector(source[i]);
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to add.</param>
|
||||
/// <returns>The sum of the sequence.</returns>
|
||||
public static long SumF(this List<long> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
long sum = 0;
|
||||
checked
|
||||
{
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
sum += source[i];
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the transformed sequence of elements.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence of values to transform then sum.</param>
|
||||
/// <param name="selector">A transformation function.</param>
|
||||
/// <returns>The sum of the transformed elements.</returns>
|
||||
public static long SumF<T>(this List<T> source, Func<T, long> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
long sum = 0;
|
||||
checked
|
||||
{
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
sum += selector(source[i]);
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to add.</param>
|
||||
/// <returns>The sum of the sequence.</returns>
|
||||
public static float SumF(this List<float> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
double sum = 0;
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
sum += source[i];
|
||||
}
|
||||
|
||||
return (float)sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the transformed sequence of elements.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence of values to transform then sum.</param>
|
||||
/// <param name="selector">A transformation function.</param>
|
||||
/// <returns>The sum of the transformed elements.</returns>
|
||||
public static float SumF<T>(this List<T> source, Func<T, float> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
double sum = 0;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
sum += selector(source[i]);
|
||||
}
|
||||
|
||||
return (float)sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to add.</param>
|
||||
/// <returns>The sum of the sequence.</returns>
|
||||
public static double SumF(this List<double> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
double sum = 0;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
sum += source[i];
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the transformed sequence of elements.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence of values to transform then sum.</param>
|
||||
/// <param name="selector">A transformation function.</param>
|
||||
/// <returns>The sum of the transformed elements.</returns>
|
||||
public static double SumF<T>(this List<T> source, Func<T, double> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
double sum = 0;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
sum += selector(source[i]);
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a sequence of values.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to add.</param>
|
||||
/// <returns>The sum of the sequence.</returns>
|
||||
public static decimal SumF(this List<decimal> source)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
decimal sum = 0;
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
sum += source[i];
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the transformed sequence of elements.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence of values to transform then sum.</param>
|
||||
/// <param name="selector">A transformation function.</param>
|
||||
/// <returns>The sum of the transformed elements.</returns>
|
||||
public static decimal SumF<T>(this List<T> source, Func<T, decimal> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
decimal sum = 0;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
sum += selector(source[i]);
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/Sum.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Sum.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: c45ad2500ea1ddd46af3645fba2bfc4c
|
||||
timeCreated: 1518622477
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
188
Assets/Scripts/NIH/LinqFaster/Take.cs
Normal file
188
Assets/Scripts/NIH/LinqFaster/Take.cs
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Returns a specified number of contiguous elements from the start of a sequence.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to return elements from.</param>
|
||||
/// <param name="count">The number of elements to return.</param>
|
||||
/// <returns>A sequence that contains the specified number of elements from the start of the input sequence.</returns>
|
||||
public static T[] TakeF<T>(this T[] source, int count)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (count < 0)
|
||||
{
|
||||
count = 0;
|
||||
}
|
||||
else if (count > source.Length)
|
||||
{
|
||||
count = source.Length;
|
||||
}
|
||||
|
||||
var result = new T[count];
|
||||
Array.Copy(source, 0, result, 0, count);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns elements from a sequence as long as a specified condition is true.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to return elements from.</param>
|
||||
/// <param name="predicate">A function to test each element for a condition.</param>
|
||||
/// <returns>A sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.</returns>
|
||||
public static T[] TakeWhileF<T>(this T[] source, Func<T, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
var result = new List<T>();
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
if (predicate(source[i]))
|
||||
result.Add(source[i]);
|
||||
else
|
||||
return result.ToArray();
|
||||
}
|
||||
return result.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns elements from a sequence as long as a specified condition is true. The element's index is used in the logic of the predicate function.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to return elements from.</param>
|
||||
/// <param name="predicate">A function to test each source element for a condition; the second parameter of the function represents the index of the source element.</param>
|
||||
/// <returns>A sequence that contains elements from the input sequence that occur before the element at which the test no longer passes.</returns>
|
||||
public static T[] TakeWhileF<T>(this T[] source, Func<T,int, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
var result = new List<T>();
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
if (predicate(source[i],i))
|
||||
result.Add(source[i]);
|
||||
else
|
||||
return result.ToArray();
|
||||
}
|
||||
return result.ToArray();
|
||||
}
|
||||
|
||||
|
||||
|
||||
// ------------- Lists ----------------
|
||||
|
||||
/// <summary>
|
||||
/// Returns a specified number of contiguous elements from the start of a sequence.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to return elements from.</param>
|
||||
/// <param name="count">The number of elements to return.</param>
|
||||
/// <returns>A sequence that contains the specified number of elements from the start of the input sequence.</returns>
|
||||
public static List<T> TakeF<T>(this List<T> source, int count)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (count < 0)
|
||||
{
|
||||
count = 0;
|
||||
}
|
||||
else if (count > source.Count)
|
||||
{
|
||||
count = source.Count;
|
||||
}
|
||||
|
||||
var result = new List<T>(count);
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
result.Add(source[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns elements from a sequence as long as a specified condition is true.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to return elements from.</param>
|
||||
/// <param name="predicate">A function to test each element for a condition.</param>
|
||||
/// <returns>A sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.</returns>
|
||||
public static List<T> TakeWhileF<T>(this List<T> source, Func<T, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
var result = new List<T>();
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
if (predicate(source[i]))
|
||||
{
|
||||
result.Add(source[i]);
|
||||
}
|
||||
else
|
||||
{
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns elements from a sequence as long as a specified condition is true. The element's index is used in the logic of the predicate function.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to return elements from.</param>
|
||||
/// <param name="predicate">A function to test each source element for a condition; the second parameter of the function represents the index of the source element.</param>
|
||||
/// <returns>A sequence that contains elements from the input sequence that occur before the element at which the test no longer passes.</returns>
|
||||
public static List<T> TakeWhileF<T>(this List<T> source, Func<T, int, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
var result = new List<T>();
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
if (predicate(source[i], i))
|
||||
result.Add(source[i]);
|
||||
else
|
||||
return result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/Take.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Take.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: f9aaaef92e9c332418190038d49b4389
|
||||
timeCreated: 1518622478
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
10
Assets/Scripts/NIH/LinqFaster/Utils.meta
Normal file
10
Assets/Scripts/NIH/LinqFaster/Utils.meta
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
fileFormatVersion: 2
|
||||
guid: d27acc7ea045f65488b96d108768512f
|
||||
folderAsset: yes
|
||||
timeCreated: 1518622476
|
||||
licenseType: Free
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
62
Assets/Scripts/NIH/LinqFaster/Utils/ComparerMagic.cs
Normal file
62
Assets/Scripts/NIH/LinqFaster/Utils/ComparerMagic.cs
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace JM.LinqFaster.Utils {
|
||||
|
||||
//Takes a comparer, and creates a reverse comparer, for Descending sorts
|
||||
internal sealed class ComparerReverser<T> : IComparer<T> {
|
||||
private readonly IComparer<T> wrappedComparer;
|
||||
|
||||
public ComparerReverser(IComparer<T> wrappedComparer) {
|
||||
this.wrappedComparer = wrappedComparer;
|
||||
}
|
||||
#if !(UNITY_4 || UNITY_5)
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
#endif
|
||||
public int Compare(T x, T y) {
|
||||
return wrappedComparer.Compare(y, x);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
internal static class ComparerExtensions {
|
||||
|
||||
// Lets us reverse a comparere with comparer.Reverse();
|
||||
public static IComparer<T> Reverse<T>(this IComparer<T> comparer) {
|
||||
return new ComparerReverser<T>(comparer);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class LambdaComparer<T, U> : IComparer<T> {
|
||||
IComparer<U> comparer;
|
||||
Func<T, U> selector;
|
||||
|
||||
public LambdaComparer(Func<T, U> selector, IComparer<U> comparer) {
|
||||
this.comparer = comparer;
|
||||
this.selector = selector;
|
||||
}
|
||||
#if !(UNITY_4 || UNITY_5)
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
#endif
|
||||
public int Compare(T x, T y) {
|
||||
return comparer.Compare(selector(x), selector(y));
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class ReverseLambdaComparer<T, U> : IComparer<T> {
|
||||
IComparer<U> comparer;
|
||||
Func<T, U> selector;
|
||||
|
||||
public ReverseLambdaComparer(Func<T, U> selector, IComparer<U> comparer) {
|
||||
this.comparer = comparer;
|
||||
this.selector = selector;
|
||||
}
|
||||
#if !(UNITY_4 || UNITY_5)
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
#endif
|
||||
public int Compare(T x, T y) {
|
||||
return comparer.Compare(selector(y), selector(x));
|
||||
}
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/Utils/ComparerMagic.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Utils/ComparerMagic.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 58968b2b3f2b61943a1723873cdb7288
|
||||
timeCreated: 1518622476
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
38
Assets/Scripts/NIH/LinqFaster/Utils/CustomPartition.cs
Normal file
38
Assets/Scripts/NIH/LinqFaster/Utils/CustomPartition.cs
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
#if !(UNITY_4 || UNITY_5)
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
|
||||
namespace JM.LinqFaster.Utils
|
||||
{
|
||||
internal static class CustomPartition
|
||||
{
|
||||
public static OrderablePartitioner<Tuple<int,int>> MakePartition(int len, int? batchSize)
|
||||
{
|
||||
if (batchSize == null)
|
||||
{
|
||||
return Partitioner.Create(0, len);
|
||||
}
|
||||
else
|
||||
{
|
||||
return Partitioner.Create(0, len, batchSize.Value);
|
||||
}
|
||||
}
|
||||
|
||||
public static OrderablePartitioner<Tuple<int, int>> MakeSIMDPartition(int len, int chunkSize, int? batchSize)
|
||||
{
|
||||
int chunkLen = len - len % chunkSize;
|
||||
int numChunks = chunkLen / chunkSize;
|
||||
if (batchSize == null)
|
||||
{
|
||||
return Partitioner.Create(0, numChunks,numChunks/Environment.ProcessorCount);
|
||||
}
|
||||
else
|
||||
{
|
||||
return Partitioner.Create(0, numChunks, batchSize.Value);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
#endif
|
||||
13
Assets/Scripts/NIH/LinqFaster/Utils/CustomPartition.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Utils/CustomPartition.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 117a499c9c8ce1a47a30c4cb3de95a14
|
||||
timeCreated: 1518622476
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
18
Assets/Scripts/NIH/LinqFaster/Utils/Error.cs
Normal file
18
Assets/Scripts/NIH/LinqFaster/Utils/Error.cs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
using System;
|
||||
|
||||
internal static class Error
|
||||
{
|
||||
internal static Exception ArgumentNull(string s) { return new ArgumentNullException(s); }
|
||||
|
||||
internal static Exception ArgumentOutOfRange(string s) { return new ArgumentOutOfRangeException(s); }
|
||||
|
||||
internal static Exception MoreThanOneElement() { return new InvalidOperationException("Sequence contains more than one element"); }
|
||||
|
||||
internal static Exception MoreThanOneMatch() { return new InvalidOperationException("Sequence contains more than one matching element"); }
|
||||
|
||||
internal static Exception NoElements() { return new InvalidOperationException("Sequence contains no elements"); }
|
||||
|
||||
internal static Exception NoMatch() { return new InvalidOperationException("Sequence contains no matching element"); }
|
||||
|
||||
internal static Exception NotSupported() { return new NotSupportedException(); }
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/Utils/Error.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Utils/Error.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 2f77eee1e24f34f438756aca3d8506d9
|
||||
timeCreated: 1518622476
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
323
Assets/Scripts/NIH/LinqFaster/Utils/GenericOperators.cs
Normal file
323
Assets/Scripts/NIH/LinqFaster/Utils/GenericOperators.cs
Normal file
|
|
@ -0,0 +1,323 @@
|
|||
#if !(UNITY_4 || UNITY_5)
|
||||
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
/*
|
||||
|
||||
C# has no way to constrain a generic to only primitive types.
|
||||
You can only constrain them to value types via:
|
||||
where T : struct
|
||||
All primitives are value types but not all value types are
|
||||
primitives. Thus, when you try to do operations like + > < ==
|
||||
on generic value types, you get a compiler error. These methods
|
||||
work around that by checking the type, casting, and performing the
|
||||
operation. The JIT elides all of the non relevant bits of the If statement
|
||||
for each generic type, so this is remarkably still fast. Since these are
|
||||
only used for the SIMD specific operations, and the SIMD library
|
||||
works exactly this way as well, it does not add any problems that
|
||||
don't already exist when you use .NET SIMD. Which is, if you create a
|
||||
Vector<T> where T is a non primitive value type, you will get a runtime error.
|
||||
*/
|
||||
namespace JM.LinqFaster.Utils
|
||||
{
|
||||
internal static class GenericOperators
|
||||
{
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static T Add<T>(T a, T b)
|
||||
{
|
||||
if (typeof(T) == typeof(Byte))
|
||||
{
|
||||
return (T)(object)((Byte)(object)a + (Byte)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(SByte))
|
||||
{
|
||||
return (T)(object)((SByte)(object)a + (SByte)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(UInt16))
|
||||
{
|
||||
return (T)(object)((UInt16)(object)a + (UInt16)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Int16))
|
||||
{
|
||||
return (T)(object)((Int16)(object)a + (Int16)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(UInt32))
|
||||
{
|
||||
return (T)(object)((UInt32)(object)a + (UInt32)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Int32))
|
||||
{
|
||||
return (T)(object)((Int32)(object)a + (Int32)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(UInt64))
|
||||
{
|
||||
return (T)(object)((UInt64)(object)a + (UInt64)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Int64))
|
||||
{
|
||||
return (T)(object)((Int64)(object)a + (Int64)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Single))
|
||||
{
|
||||
return (T)(object)((Single)(object)a + (Single)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Double))
|
||||
{
|
||||
return (T)(object)((Double)(object)a + (Double)(object)b);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new NotSupportedException("Nope");
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool GreaterThan<T>(T a, T b)
|
||||
{
|
||||
if (typeof(T) == typeof(Byte))
|
||||
{
|
||||
return ((Byte)(object)a > (Byte)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(SByte))
|
||||
{
|
||||
return ((SByte)(object)a > (SByte)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(UInt16))
|
||||
{
|
||||
return ((UInt16)(object)a > (UInt16)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Int16))
|
||||
{
|
||||
return ((Int16)(object)a > (Int16)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(UInt32))
|
||||
{
|
||||
return ((UInt32)(object)a > (UInt32)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Int32))
|
||||
{
|
||||
return ((Int32)(object)a > (Int32)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(UInt64))
|
||||
{
|
||||
return ((UInt64)(object)a > (UInt64)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Int64))
|
||||
{
|
||||
return ((Int64)(object)a > (Int64)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Single))
|
||||
{
|
||||
return ((Single)(object)a > (Single)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Double))
|
||||
{
|
||||
return ((Double)(object)a > (Double)(object)b);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new NotSupportedException("Nope");
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool Equals<T>(T a, T b)
|
||||
{
|
||||
if (typeof(T) == typeof(Byte))
|
||||
{
|
||||
return ((Byte)(object)a == (Byte)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(SByte))
|
||||
{
|
||||
return ((SByte)(object)a == (SByte)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(UInt16))
|
||||
{
|
||||
return ((UInt16)(object)a == (UInt16)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Int16))
|
||||
{
|
||||
return ((Int16)(object)a == (Int16)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(UInt32))
|
||||
{
|
||||
return ((UInt32)(object)a == (UInt32)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Int32))
|
||||
{
|
||||
return ((Int32)(object)a == (Int32)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(UInt64))
|
||||
{
|
||||
return ((UInt64)(object)a == (UInt64)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Int64))
|
||||
{
|
||||
return ((Int64)(object)a == (Int64)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Single))
|
||||
{
|
||||
return ((Single)(object)a == (Single)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Double))
|
||||
{
|
||||
return ((Double)(object)a == (Double)(object)b);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new NotSupportedException("Nope");
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool LessThan<T>(T a, T b)
|
||||
{
|
||||
if (typeof(T) == typeof(Byte))
|
||||
{
|
||||
return ((Byte)(object)a < (Byte)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(SByte))
|
||||
{
|
||||
return ((SByte)(object)a < (SByte)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(UInt16))
|
||||
{
|
||||
return ((UInt16)(object)a < (UInt16)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Int16))
|
||||
{
|
||||
return ((Int16)(object)a < (Int16)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(UInt32))
|
||||
{
|
||||
return ((UInt32)(object)a < (UInt32)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Int32))
|
||||
{
|
||||
return ((Int32)(object)a < (Int32)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(UInt64))
|
||||
{
|
||||
return ((UInt64)(object)a < (UInt64)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Int64))
|
||||
{
|
||||
return ((Int64)(object)a < (Int64)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Single))
|
||||
{
|
||||
return ((Single)(object)a < (Single)(object)b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Double))
|
||||
{
|
||||
return ((Double)(object)a < (Double)(object)b);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new NotSupportedException("Nope");
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static double Divide<T>(T a, double b)
|
||||
{
|
||||
if (typeof(T) == typeof(Byte))
|
||||
{
|
||||
return (double)(object)((Byte)(object)a /b) ;
|
||||
}
|
||||
else if (typeof(T) == typeof(SByte))
|
||||
{
|
||||
return (double)(object)((SByte)(object)a /b);
|
||||
}
|
||||
else if (typeof(T) == typeof(UInt16))
|
||||
{
|
||||
return (double)(object)((UInt16)(object)a / b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Int16))
|
||||
{
|
||||
return (double)(object)((Int16)(object)a / b);
|
||||
}
|
||||
else if (typeof(T) == typeof(UInt32))
|
||||
{
|
||||
return (double)(object)((UInt32)(object)a / b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Int32))
|
||||
{
|
||||
return (double)(object)((Int32)(object)a /b);
|
||||
}
|
||||
else if (typeof(T) == typeof(UInt64))
|
||||
{
|
||||
return (double)(object)((UInt64)(object)a / b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Int64))
|
||||
{
|
||||
return (double)(object)((Int64)(object)a /b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Single))
|
||||
{
|
||||
return (double)(object)((Single)(object)a /b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Double))
|
||||
{
|
||||
return (double)(object)((Double)(object)a / b);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new NotSupportedException("Nope");
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static float DivideFloat<T>(T a, float b)
|
||||
{
|
||||
if (typeof(T) == typeof(Byte))
|
||||
{
|
||||
return (float)(object)((Byte)(object)a / b);
|
||||
}
|
||||
else if (typeof(T) == typeof(SByte))
|
||||
{
|
||||
return (float)(object)((SByte)(object)a / b);
|
||||
}
|
||||
else if (typeof(T) == typeof(UInt16))
|
||||
{
|
||||
return (float)(object)((UInt16)(object)a / b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Int16))
|
||||
{
|
||||
return (float)(object)((Int16)(object)a / b);
|
||||
}
|
||||
else if (typeof(T) == typeof(UInt32))
|
||||
{
|
||||
return (float)(object)((UInt32)(object)a / b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Int32))
|
||||
{
|
||||
return (float)(object)((Int32)(object)a / b);
|
||||
}
|
||||
else if (typeof(T) == typeof(UInt64))
|
||||
{
|
||||
return (float)(object)((UInt64)(object)a / b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Int64))
|
||||
{
|
||||
return (float)(object)((Int64)(object)a / b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Single))
|
||||
{
|
||||
return (float)(object)((Single)(object)a / b);
|
||||
}
|
||||
else if (typeof(T) == typeof(Double))
|
||||
{
|
||||
return (float)(object)((Double)(object)a / b);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new NotSupportedException("Nope");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
13
Assets/Scripts/NIH/LinqFaster/Utils/GenericOperators.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Utils/GenericOperators.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: c55248b8089617346a6a1b22dc43009f
|
||||
timeCreated: 1518622478
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
127
Assets/Scripts/NIH/LinqFaster/Where.cs
Normal file
127
Assets/Scripts/NIH/LinqFaster/Where.cs
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
// -------------------------- ARRAYS --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Filters a sequence of values based on a predicate.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to filter.</param>
|
||||
/// <param name="predicate">A function to test each element for a condition.</param>
|
||||
/// <returns>A sequence that contains elements from the input sequence that satisfy the condition.</returns>
|
||||
public static T[] WhereF<T>(this T[] source, Func<T, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
T[] result = new T[source.Length];
|
||||
int idx = 0;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
if (predicate(source[i]))
|
||||
{
|
||||
result[idx] = source[i];
|
||||
idx++;
|
||||
}
|
||||
}
|
||||
Array.Resize(ref result, idx);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Filters a sequence of values based on a predicate that includes the index in it's logic.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to filter.</param>
|
||||
/// <param name="predicate">A function to test each element for a condition along with the element's index.</param>
|
||||
/// <returns>A sequence that contains elements from the input sequence that satisfy the condition.</returns>
|
||||
public static T[] WhereF<T>(this T[] source, Func<T, int, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
|
||||
T[] result = new T[source.Length];
|
||||
int idx = 0;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
if (predicate(source[i], i))
|
||||
{
|
||||
result[idx] = source[i];
|
||||
idx++;
|
||||
}
|
||||
}
|
||||
Array.Resize(ref result, idx);
|
||||
return result;
|
||||
}
|
||||
|
||||
// -------------------------- LISTS --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Filters a sequence of values based on a predicate.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to filter.</param>
|
||||
/// <param name="predicate">A function to test each element for a condition.</param>
|
||||
/// <returns>A sequence that contains elements from the input sequence that satisfy the condition.</returns>
|
||||
public static List<T> WhereF<T>(this List<T> source, Predicate<T> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
return source.FindAll(predicate);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Filters a sequence of values based on a predicate that includes the index in it's logic.
|
||||
/// </summary>
|
||||
/// <param name="source">A sequence to filter.</param>
|
||||
/// <param name="predicate">A function to test each element for a condition along with the element's index.</param>
|
||||
/// <returns>A sequence that contains elements from the input sequence that satisfy the condition.</returns>
|
||||
public static List<T> WhereF<T>(this List<T> source, Func<T, int, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
List<T> r = new List<T>();
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
if (predicate(source[i], i)) r.Add(source[i]);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/Where.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Where.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 089655aa3554c044c827c1c259eb1e00
|
||||
timeCreated: 1518622476
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
335
Assets/Scripts/NIH/LinqFaster/WhereAggregate.cs
Normal file
335
Assets/Scripts/NIH/LinqFaster/WhereAggregate.cs
Normal file
|
|
@ -0,0 +1,335 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
// ----------------------------- Arrays ------------------
|
||||
|
||||
/// <summary>
|
||||
/// Combines Where and Aggregate for optimal performance
|
||||
/// </summary>
|
||||
/// <param name="source">The input to filter then aggregate.</param>
|
||||
/// <param name="predicate">The function to filter the input sequence with.</param>
|
||||
/// <param name="func">The function to aggregate the filtered seqeuence.</param>
|
||||
/// <returns>The filtered then aggregated sequence.</returns>
|
||||
public static T WhereAggregateF<T>(this T[] source, Func<T, bool> predicate, Func<T, T, T> func)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
if (func == null)
|
||||
{
|
||||
throw Error.ArgumentNull("func");
|
||||
}
|
||||
|
||||
var result = default(T);
|
||||
|
||||
int i = 0;
|
||||
for (; i < source.Length; i++)
|
||||
{
|
||||
if (predicate(source[i]))
|
||||
{
|
||||
result = source[i];
|
||||
i++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (; i < source.Length; i++)
|
||||
{
|
||||
if (predicate(source[i]))
|
||||
{
|
||||
result = func(result, source[i]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Combines Where and Aggregate with index for optimal performance
|
||||
/// </summary>
|
||||
/// <param name="source">The input to filter then aggregate.</param>
|
||||
/// <param name="predicate">The function to filter the input sequence and it's index with.</param>
|
||||
/// <param name="func">The function to aggregate the filtered seqeuence.</param>
|
||||
/// <returns>The filtered then aggregated sequence.</returns>
|
||||
public static T WhereAggregateF<T>(this T[] source, Func<T, int, bool> predicate, Func<T, T,T> func)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
var result = default(T);
|
||||
|
||||
int i = 0;
|
||||
for (; i < source.Length; i++)
|
||||
{
|
||||
if (predicate(source[i], i))
|
||||
{
|
||||
result = source[i];
|
||||
i++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (; i < source.Length; i++)
|
||||
{
|
||||
if (predicate(source[i], i))
|
||||
{
|
||||
result = func(result, source[i]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Combines Where and Aggregate for optimal performance with a starting seed.
|
||||
/// </summary>
|
||||
/// <param name="source">The input to filter then aggregate.</param>
|
||||
/// <param name="predicate">The function to filter the input sequence with.</param>
|
||||
/// <param name="seed">The initial value to aggregate on.</param>
|
||||
/// <param name="func">The function to aggregate the filtered seqeuence.</param>
|
||||
/// <returns>The filtered then aggregated sequence.</returns>
|
||||
public static TAccumulate WhereAggregateF<TSource, TAccumulate>(this TSource[] source, Func<TSource, bool> predicate, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (func == null)
|
||||
{
|
||||
throw Error.ArgumentNull("func");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
TAccumulate result = seed;
|
||||
foreach (var v in source)
|
||||
{
|
||||
if (predicate(v))
|
||||
result = func(result, v);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Combines Where and Aggregate for optimal performance with a starting seed and a result transformation.
|
||||
/// </summary>
|
||||
/// <param name="source">The input to filter then aggregate.</param>
|
||||
/// <param name="predicate">The function to filter the input sequence with.</param>
|
||||
/// <param name="seed">The initial value to aggregate on.</param>
|
||||
/// <param name="func">The function to aggregate the filtered seqeuence.</param>
|
||||
/// <param name="resultSelector">A function to transform the final result.</param>
|
||||
/// <returns>The filtered then aggregated then transformed sequence.</returns>
|
||||
public static TResult WhereAggregateF<TSource, TAccumulate, TResult>(this TSource[] source, Func<TSource, bool> predicate, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func, Func<TAccumulate, TResult> resultSelector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (func == null)
|
||||
{
|
||||
throw Error.ArgumentNull("func");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
if (resultSelector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("resultSelector");
|
||||
}
|
||||
|
||||
TAccumulate result = seed;
|
||||
int count = 0;
|
||||
foreach (var v in source)
|
||||
{
|
||||
if (predicate(v)) {
|
||||
result = func(result, v);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return resultSelector(result);
|
||||
}
|
||||
|
||||
|
||||
// --------------------------- Lists -------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Combines Where and Aggregate for optimal performance
|
||||
/// </summary>
|
||||
/// <param name="source">The input to filter then aggregate.</param>
|
||||
/// <param name="predicate">The function to filter the input sequence with.</param>
|
||||
/// <param name="func">The function to aggregate the filtered seqeuence.</param>
|
||||
/// <returns>The filtered then aggregated sequence.</returns>
|
||||
public static T WhereAggregateF<T>(this List<T> source, Func<T, bool> predicate, Func<T, T, T> func)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
if (func == null)
|
||||
{
|
||||
throw Error.ArgumentNull("func");
|
||||
}
|
||||
|
||||
var result = default(T);
|
||||
|
||||
int i = 0;
|
||||
for (; i < source.Count; i++)
|
||||
{
|
||||
if (predicate(source[i]))
|
||||
{
|
||||
result = source[i];
|
||||
i++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (; i < source.Count; i++)
|
||||
{
|
||||
if (predicate(source[i]))
|
||||
{
|
||||
result = func(result, source[i]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Combines Where and Aggregate with index for optimal performance
|
||||
/// </summary>
|
||||
/// <param name="source">The input to filter then aggregate.</param>
|
||||
/// <param name="predicate">The function to filter the input sequence and it's index with.</param>
|
||||
/// <param name="func">The function to aggregate the filtered seqeuence.</param>
|
||||
/// <returns>The filtered then aggregated sequence.</returns>
|
||||
public static T WhereAggregateF<T>(this List<T> source, Func<T, int, bool> predicate, Func<T, T, T> func)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
var result = default(T);
|
||||
|
||||
int i = 0;
|
||||
for (; i < source.Count; i++)
|
||||
{
|
||||
if (predicate(source[i], i))
|
||||
{
|
||||
result = source[i];
|
||||
i++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (; i < source.Count; i++)
|
||||
{
|
||||
if (predicate(source[i], i))
|
||||
{
|
||||
result = func(result, source[i]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Combines Where and Aggregate for optimal performance with a starting seed.
|
||||
/// </summary>
|
||||
/// <param name="source">The input to filter then aggregate.</param>
|
||||
/// <param name="predicate">The function to filter the input sequence with.</param>
|
||||
/// <param name="seed">The initial value to aggregate on.</param>
|
||||
/// <param name="func">The function to aggregate the filtered seqeuence.</param>
|
||||
/// <returns>The filtered then aggregated sequence.</returns>
|
||||
public static TAccumulate WhereAggregateF<TSource, TAccumulate>(this List<TSource> source, Func<TSource, bool> predicate, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (func == null)
|
||||
{
|
||||
throw Error.ArgumentNull("func");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
TAccumulate result = seed;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var v = source[i];
|
||||
if (predicate(v))
|
||||
result = func(result, v);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Combines Where and Aggregate for optimal performance with a starting seed and a result transformation.
|
||||
/// </summary>
|
||||
/// <param name="source">The input to filter then aggregate.</param>
|
||||
/// <param name="predicate">The function to filter the input sequence with.</param>
|
||||
/// <param name="seed">The initial value to aggregate on.</param>
|
||||
/// <param name="func">The function to aggregate the filtered seqeuence.</param>
|
||||
/// <param name="resultSelector">A function to transform the final result.</param>
|
||||
/// <returns>The filtered then aggregated then transformed sequence.</returns>
|
||||
public static TResult WhereAggregateF<TSource, TAccumulate, TResult>(this List<TSource> source, Func<TSource, bool> predicate, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func, Func<TAccumulate, TResult> resultSelector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (func == null)
|
||||
{
|
||||
throw Error.ArgumentNull("func");
|
||||
}
|
||||
|
||||
if (resultSelector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("resultSelector");
|
||||
}
|
||||
|
||||
TAccumulate result = seed;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var v = source[i];
|
||||
if (predicate(v))
|
||||
result = func(result, v);
|
||||
}
|
||||
return resultSelector(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/WhereAggregate.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/WhereAggregate.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: ba74d3462bb50a647b34d3988b598cda
|
||||
timeCreated: 1518622477
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
164
Assets/Scripts/NIH/LinqFaster/WhereSelect.cs
Normal file
164
Assets/Scripts/NIH/LinqFaster/WhereSelect.cs
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
// -------------------------- ARRAYS --------------------------------------------
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Combined Where and Select for optimal performance.
|
||||
/// </summary>
|
||||
/// <param name="source">The input sequence to filter then transform.</param>
|
||||
/// <param name="predicate">A function to use to filter the sequence.</param>
|
||||
/// <param name="selector">A function to transform the filtered elements.</param>
|
||||
/// <returns>A sequence of filtered and transformed elements.</returns>
|
||||
public static TResult[] WhereSelectF<T, TResult>(this T[] source, Func<T, bool> predicate, Func<T, TResult> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
var result = new TResult[source.Length];
|
||||
int idx = 0;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
if (predicate(source[i]))
|
||||
{
|
||||
result[idx] = selector(source[i]);
|
||||
idx++;
|
||||
}
|
||||
}
|
||||
Array.Resize(ref result, idx);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Combined Where and Select for optimal performance that uses the index in the
|
||||
/// predicate and selector.
|
||||
/// </summary>
|
||||
/// <param name="source">The input sequence to filter then transform.</param>
|
||||
/// <param name="predicate">A function to use to filter the sequence.</param>
|
||||
/// <param name="selector">A function to transform the filtered elements.</param>
|
||||
/// <returns>A sequence of filtered and transformed elements.</returns>
|
||||
public static TResult[] WhereSelectF<T, TResult>(this T[] source, Func<T, int, bool> predicate, Func<T, int, TResult> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
var result = new TResult[source.Length];
|
||||
int idx = 0;
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
if (predicate(source[i], i))
|
||||
{
|
||||
result[idx] = selector(source[i], idx);
|
||||
idx++;
|
||||
}
|
||||
}
|
||||
Array.Resize(ref result, idx);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
// -------------------------- LISTS --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Combined Where and Select for optimal performance.
|
||||
/// </summary>
|
||||
/// <param name="source">The input sequence to filter then transform.</param>
|
||||
/// <param name="predicate">A function to use to filter the sequence.</param>
|
||||
/// <param name="selector">A function to transform the filtered elements.</param>
|
||||
/// <returns>A sequence of filtered and transformed elements.</returns>
|
||||
public static List<TResult> WhereSelectF<T, TResult>(this List<T> source, Func<T, bool> predicate, Func<T, TResult> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
var r = new List<TResult>();
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
if (predicate(source[i])) r.Add(selector(source[i]));
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Combined Where and Select for optimal performance that uses the index in the
|
||||
/// predicate and selector.
|
||||
/// </summary>
|
||||
/// <param name="source">The input sequence to filter then transform.</param>
|
||||
/// <param name="predicate">A function to use to filter the sequence.</param>
|
||||
/// <param name="selector">A function to transform the filtered elements.</param>
|
||||
/// <returns>A sequence of filtered and transformed elements.</returns>
|
||||
public static List<TResult> WhereSelectF<T, TResult>(this List<T> source, Func<T, int, bool> predicate, Func<T, int, TResult> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (predicate == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("predicate");
|
||||
}
|
||||
|
||||
var r = new List<TResult>();
|
||||
int idx = 0;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
if (predicate(source[i], i)) {
|
||||
r.Add(selector(source[i], idx));
|
||||
idx++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/WhereSelect.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/WhereSelect.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 20a5c369792516b4f8326236fc378f5c
|
||||
timeCreated: 1518622476
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
594
Assets/Scripts/NIH/LinqFaster/WhereSum.cs
Normal file
594
Assets/Scripts/NIH/LinqFaster/WhereSum.cs
Normal file
|
|
@ -0,0 +1,594 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
// -------------------------- ARRAYS --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Adds the values in the sequence that match the where predicate.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to add.</param>
|
||||
/// <param name="predicate">A function to filter the sequence with before summing.</param>
|
||||
/// <returns>The sum of the sequence.</returns>
|
||||
public static int WhereSumF(this int[] source, Func<int,bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
int sum = 0;
|
||||
checked
|
||||
{
|
||||
foreach (var v in source)
|
||||
{
|
||||
if (predicate(v))
|
||||
{
|
||||
sum += v;
|
||||
}
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs a filter with the where predicate, then sums the transformed values.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence of values to transform then sum.</param>
|
||||
/// <param name="predicate">A function to filter the sequence with before summing.</param>
|
||||
/// <param name="selector">A transformation function.</param>
|
||||
/// <returns>The sum of the transformed elements.</returns>
|
||||
public static int WhereSumF<T>(this T[] source,Func<T,bool> predicate, Func<T, int> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
int sum = 0;
|
||||
checked
|
||||
{
|
||||
foreach (var v in source)
|
||||
{
|
||||
if (predicate(v))
|
||||
{
|
||||
sum += selector(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the values in the sequence that match the where predicate.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to add.</param>
|
||||
/// <param name="predicate">A function to filter the sequence with before summing.</param>
|
||||
/// <returns>The sum of the sequence.</returns>
|
||||
public static long WhereSumF(this long[] source,Func<long,bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
long sum = 0;
|
||||
checked
|
||||
{
|
||||
foreach (var v in source)
|
||||
{
|
||||
if (predicate(v))
|
||||
{
|
||||
sum += v;
|
||||
}
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs a filter with the where predicate, then sums the transformed values.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence of values to transform then sum.</param>
|
||||
/// <param name="predicate">A function to filter the sequence with before summing.</param>
|
||||
/// <param name="selector">A transformation function.</param>
|
||||
/// <returns>The sum of the transformed elements.</returns>
|
||||
public static long WhereSumF<T>(this T[] source,Func<T,bool> predicate, Func<T, long> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
long sum = 0;
|
||||
checked
|
||||
{
|
||||
foreach (var v in source)
|
||||
{
|
||||
if (predicate(v))
|
||||
{
|
||||
sum += selector(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the values in the sequence that match the where predicate.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to add.</param>
|
||||
/// <param name="predicate">A function to filter the sequence with before summing.</param>
|
||||
/// <returns>The sum of the sequence.</returns>
|
||||
public static float WhereSumF(this float[] source, Func<float,bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
double sum = 0;
|
||||
|
||||
foreach (var v in source)
|
||||
{
|
||||
if (predicate(v))
|
||||
{
|
||||
sum += v;
|
||||
}
|
||||
}
|
||||
|
||||
return (float)sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs a filter with the where predicate, then sums the transformed values.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence of values to transform then sum.</param>
|
||||
/// <param name="predicate">A function to filter the sequence with before summing.</param>
|
||||
/// <param name="selector">A transformation function.</param>
|
||||
/// <returns>The sum of the transformed elements.</returns>
|
||||
public static float WhereSumF<T>(this T[] source, Func<T,bool> predicate,Func<T, float> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
double sum = 0;
|
||||
foreach (var v in source)
|
||||
{
|
||||
if (predicate(v))
|
||||
{
|
||||
sum += selector(v);
|
||||
}
|
||||
}
|
||||
|
||||
return (float)sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the values in the sequence that match the where predicate.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to add.</param>
|
||||
/// <param name="predicate">A function to filter the sequence with before summing.</param>
|
||||
/// <returns>The sum of the sequence.</returns>
|
||||
public static double WhereSumF(this double[] source, Func<double,bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
double sum = 0;
|
||||
foreach (var v in source)
|
||||
{
|
||||
if (predicate(v))
|
||||
{
|
||||
sum += v;
|
||||
}
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs a filter with the where predicate, then sums the transformed values.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence of values to transform then sum.</param>
|
||||
/// <param name="predicate">A function to filter the sequence with before summing.</param>
|
||||
/// <param name="selector">A transformation function.</param>
|
||||
/// <returns>The sum of the transformed elements.</returns>
|
||||
public static double WhereSumF<T>(this T[] source, Func<T,bool> predicate,Func<T, double> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
double sum = 0;
|
||||
foreach (var v in source)
|
||||
{
|
||||
if (predicate(v))
|
||||
{
|
||||
sum += selector(v);
|
||||
}
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the values in the sequence that match the where predicate.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to add.</param>
|
||||
/// <param name="predicate">A function to filter the sequence with before summing.</param>
|
||||
/// <returns>The sum of the sequence.</returns>
|
||||
public static decimal WhereSumF(this decimal[] source, Func<decimal,bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
decimal sum = 0;
|
||||
|
||||
foreach (var v in source)
|
||||
{
|
||||
if (predicate(v))
|
||||
{
|
||||
sum += v;
|
||||
}
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs a filter with the where predicate, then sums the transformed values.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence of values to transform then sum.</param>
|
||||
/// <param name="predicate">A function to filter the sequence with before summing.</param>
|
||||
/// <param name="selector">A transformation function.</param>
|
||||
/// <returns>The sum of the transformed elements.</returns>
|
||||
public static decimal WhereSumF<T>(this T[] source,Func<T,bool> predicate, Func<T, decimal> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
decimal sum = 0;
|
||||
foreach (var v in source)
|
||||
{
|
||||
if (predicate(v))
|
||||
{
|
||||
sum += selector(v);
|
||||
}
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
// -------------------------- LISTS --------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Adds the values in the sequence that match the where predicate.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to add.</param>
|
||||
/// <param name="predicate">A function to filter the sequence with before summing.</param>
|
||||
/// <returns>The sum of the sequence.</returns>
|
||||
public static int WhereSumF(this List<int> source, Func<int,bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
int sum = 0;
|
||||
checked
|
||||
{
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var s = source[i];
|
||||
if (predicate(s))
|
||||
{
|
||||
sum += s;
|
||||
}
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs a filter with the where predicate, then sums the transformed values.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence of values to transform then sum.</param>
|
||||
/// <param name="predicate">A function to filter the sequence with before summing.</param>
|
||||
/// <param name="selector">A transformation function.</param>
|
||||
/// <returns>The sum of the transformed elements.</returns>
|
||||
public static int WhereSumF<T>(this List<T> source, Func<T,bool> predicate, Func<T, int> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
int sum = 0;
|
||||
checked
|
||||
{
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var s = source[i];
|
||||
if (predicate(s))
|
||||
{
|
||||
sum += selector(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the values in the sequence that match the where predicate.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to add.</param>
|
||||
/// <param name="predicate">A function to filter the sequence with before summing.</param>
|
||||
/// <returns>The sum of the sequence.</returns>
|
||||
public static long WhereSumF(this List<long> source, Func<long,bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
long sum = 0;
|
||||
checked
|
||||
{
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var s = source[i];
|
||||
if (predicate(s))
|
||||
{
|
||||
sum += s;
|
||||
}
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs a filter with the where predicate, then sums the transformed values.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence of values to transform then sum.</param>
|
||||
/// <param name="predicate">A function to filter the sequence with before summing.</param>
|
||||
/// <param name="selector">A transformation function.</param>
|
||||
/// <returns>The sum of the transformed elements.</returns>
|
||||
public static long WhereSumF<T>(this List<T> source, Func<T,bool> predicate, Func<T, long> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
long sum = 0;
|
||||
checked
|
||||
{
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var s = source[i];
|
||||
if (predicate(s))
|
||||
{
|
||||
sum += selector(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the values in the sequence that match the where predicate.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to add.</param>
|
||||
/// <param name="predicate">A function to filter the sequence with before summing.</param>
|
||||
/// <returns>The sum of the sequence.</returns>
|
||||
public static float WhereSumF(this List<float> source, Func<float,bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
double sum = 0;
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var s = source[i];
|
||||
if (predicate(s))
|
||||
{
|
||||
sum += s;
|
||||
}
|
||||
}
|
||||
|
||||
return (float)sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs a filter with the where predicate, then sums the transformed values.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence of values to transform then sum.</param>
|
||||
/// <param name="predicate">A function to filter the sequence with before summing.</param>
|
||||
/// <param name="selector">A transformation function.</param>
|
||||
/// <returns>The sum of the transformed elements.</returns>
|
||||
public static float WhereSumF<T>(this List<T> source, Func<T,bool> predicate,Func<T, float> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
double sum = 0;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var s = source[i];
|
||||
if (predicate(s))
|
||||
{
|
||||
sum += selector(s);
|
||||
}
|
||||
}
|
||||
|
||||
return (float)sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the values in the sequence that match the where predicate.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to add.</param>
|
||||
/// <param name="predicate">A function to filter the sequence with before summing.</param>
|
||||
/// <returns>The sum of the sequence.</returns>
|
||||
public static double WhereSumF(this List<double> source, Func<double,bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
double sum = 0;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var s = source[i];
|
||||
if (predicate(s))
|
||||
{
|
||||
sum += s;
|
||||
}
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs a filter with the where predicate, then sums the transformed values.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence of values to transform then sum.</param>
|
||||
/// <param name="predicate">A function to filter the sequence with before summing.</param>
|
||||
/// <param name="selector">A transformation function.</param>
|
||||
/// <returns>The sum of the transformed elements.</returns>
|
||||
public static double WhereSumF<T>(this List<T> source,Func<T,bool> predicate, Func<T, double> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
double sum = 0;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var s = source[i];
|
||||
if (predicate(s))
|
||||
{
|
||||
sum += selector(s);
|
||||
}
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the values in the sequence that match the where predicate.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence to add.</param>
|
||||
/// <param name="predicate">A function to filter the sequence with before summing.</param>
|
||||
/// <returns>The sum of the sequence.</returns>
|
||||
public static decimal WhereSumF(this List<decimal> source, Func<decimal,bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
decimal sum = 0;
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var s = source[i];
|
||||
if (predicate(s))
|
||||
{
|
||||
sum += s;
|
||||
}
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs a filter with the where predicate, then sums the transformed values.
|
||||
/// </summary>
|
||||
/// <param name="source">The sequence of values to transform then sum.</param>
|
||||
/// <param name="predicate">A function to filter the sequence with before summing.</param>
|
||||
/// <param name="selector">A transformation function.</param>
|
||||
/// <returns>The sum of the transformed elements.</returns>
|
||||
public static decimal WhereSumF<T>(this List<T> source, Func<T,bool> predicate,Func<T, decimal> selector)
|
||||
{
|
||||
if (source == null)
|
||||
{
|
||||
throw Error.ArgumentNull("source");
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
decimal sum = 0;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var s = source[i];
|
||||
if (predicate(s))
|
||||
{
|
||||
sum += selector(s);
|
||||
}
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/WhereSum.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/WhereSum.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: dcc2e4320bd136e4aaecbc9978013e58
|
||||
timeCreated: 1518622478
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
99
Assets/Scripts/NIH/LinqFaster/Zip.cs
Normal file
99
Assets/Scripts/NIH/LinqFaster/Zip.cs
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JM.LinqFaster
|
||||
{
|
||||
public static partial class LinqFaster
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.
|
||||
/// </summary>
|
||||
/// <param name="first">The first sequence to merge.</param>
|
||||
/// <param name="second">The second sequence to merge.</param>
|
||||
/// <param name="selector">A function that specifies how to merge the elements from the two sequences.</param>
|
||||
/// <returns>A sequence that contains merged elements of two input sequences.</returns>
|
||||
public static R[] ZipF<T, U, R>(this T[] first, U[] second, Func<T, U, R> selector)
|
||||
{
|
||||
if (first == null)
|
||||
{
|
||||
throw Error.ArgumentNull("first");
|
||||
}
|
||||
if (second == null)
|
||||
{
|
||||
throw Error.ArgumentNull("second");
|
||||
}
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
//maintain array bounds elision
|
||||
if (first.Length < second.Length)
|
||||
{
|
||||
var result = new R[first.Length];
|
||||
for (int i = 0; i < first.Length; i++)
|
||||
{
|
||||
result[i] = selector(first[i], second[i]);
|
||||
}
|
||||
return result;
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
var result = new R[second.Length];
|
||||
for (int i = 0; i < second.Length; i++)
|
||||
{
|
||||
result[i] = selector(first[i], second[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.
|
||||
/// </summary>
|
||||
/// <param name="first">The first sequence to merge.</param>
|
||||
/// <param name="second">The second sequence to merge.</param>
|
||||
/// <param name="selector">A function that specifies how to merge the elements from the two sequences.</param>
|
||||
/// <returns>A sequence that contains merged elements of two input sequences.</returns>
|
||||
public static List<R> ZipF<T, U, R>(this List<T> first, List<U> second, Func<T, U, R> selector)
|
||||
{
|
||||
if (first == null)
|
||||
{
|
||||
throw Error.ArgumentNull("first");
|
||||
}
|
||||
if (second == null)
|
||||
{
|
||||
throw Error.ArgumentNull("second");
|
||||
}
|
||||
if (selector == null)
|
||||
{
|
||||
throw Error.ArgumentNull("selector");
|
||||
}
|
||||
|
||||
//maintain array bounds elision
|
||||
if (first.Count < second.Count)
|
||||
{
|
||||
var result = new List<R>(first.Count);
|
||||
for (int i = 0; i < first.Count; i++)
|
||||
{
|
||||
result.Add(selector(first[i], second[i]));
|
||||
}
|
||||
return result;
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
var result = new List<R>(second.Count);
|
||||
for (int i = 0; i < second.Count; i++)
|
||||
{
|
||||
result.Add(selector(first[i], second[i]));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
13
Assets/Scripts/NIH/LinqFaster/Zip.cs.meta
Normal file
13
Assets/Scripts/NIH/LinqFaster/Zip.cs.meta
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
fileFormatVersion: 2
|
||||
guid: d5cec6dd8a8dd0b4ab39e3fd25d1fa7b
|
||||
timeCreated: 1518622478
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
68
Assets/Scripts/NIH/LinqFaster/readme.txt
Normal file
68
Assets/Scripts/NIH/LinqFaster/readme.txt
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
LinqFaster
|
||||
|
||||
|
||||
Usage Guide
|
||||
--------------------------------------------------------------------------
|
||||
LinqFaster provides specialized versions of the Linq extensions methods
|
||||
optimized for working with arrays and lists. LinqFaster methods use the
|
||||
same names as Linq, but with an F (for Fast) appended to them so that
|
||||
you can use LinqFaster alongside regular Linq. The semantics are identical
|
||||
except for OrderBy which does not do a stable sort like Linq does.
|
||||
|
||||
Examples
|
||||
--------------------------------------------------------------------------
|
||||
//Create an array of with values -500 to 500
|
||||
var myArray = LinqFaster.RangeArrayF(-500, 500);
|
||||
//Create a List<T> with 1000 elements all set to 5.0
|
||||
var myList = LinqFaster.RepeatListF(5.0, 1000);
|
||||
|
||||
//Compute sum, average, max,min
|
||||
var sum = myArray.SumF();
|
||||
var average = myArray.AverageF();
|
||||
var min = myArray.Min();
|
||||
var max = myArray.Max();
|
||||
|
||||
//As above but on a transformation
|
||||
var sum2 = myArray.SumF(x => x*x);
|
||||
var average2 = myArray.AverageF(x => x*x);
|
||||
var min2 = myArray.Min(x => x*x);
|
||||
var max2 = myArray.Max(x => x*x);
|
||||
|
||||
//Do a where and a select or select and where in a single pass
|
||||
var newArray = myArray.WhereSelectF(x => x % 2 == 0,x=>x*x);
|
||||
var newArray2 = myArray.SelectWhereF(x => x * x,x => x % 2 == 0);
|
||||
|
||||
//Compute the sum of only the even values in a single pass
|
||||
var filteredSum = myArray.WhereAggregateF(x => x % 2 == 0, (acc, x) => acc + x);
|
||||
|
||||
//New in-place methods are provided where appropriate
|
||||
myArray.SelectInPlace(x => x * x);
|
||||
myArray.ReverseInPlace();
|
||||
|
||||
|
||||
Limitations
|
||||
--------------------------------------------------------------------------
|
||||
These are purely imperative implementations of the same higher order
|
||||
functions that Linq provides, but unlike Linq they are not lazily evaluated.
|
||||
This means that when chaining functions together such as:
|
||||
|
||||
var a = data.Where(predicate).Select(transform).Aggregate(foo);
|
||||
// or
|
||||
var b = data.Select(selector).Sum();
|
||||
|
||||
Linq would not do any work until the calls to Sum() or Aggregate(), and thus
|
||||
iterate over the collection only once and allocate very little. LinqFaster
|
||||
used this way would iterate over the collection each time and allocate much
|
||||
more. Sometimes the net result will still be faster overall but the better
|
||||
approach is to use the combined LinqFaster operations such as
|
||||
SelectWhere, WhereSelect, and WhereAggregate. For example the expressions
|
||||
above would become:
|
||||
|
||||
var a = data.WhereAggregate(predicate,transform,foo);
|
||||
// and
|
||||
var b = data.Sum(selector);
|
||||
|
||||
This gets you the best of both worlds. The speed of memory locality and no
|
||||
allocations at all. In short, think about how you are transforming your
|
||||
data. In some cases normal Linq may be the better choice.
|
||||
|
||||
9
Assets/Scripts/NIH/LinqFaster/readme.txt.meta
Normal file
9
Assets/Scripts/NIH/LinqFaster/readme.txt.meta
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
fileFormatVersion: 2
|
||||
guid: b03cc13e7e812ab47b88f91d54b43c4d
|
||||
timeCreated: 1518622496
|
||||
licenseType: Free
|
||||
TextScriptImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
8
Assets/Scripts/NIH/MIConvexHull.meta
Normal file
8
Assets/Scripts/NIH/MIConvexHull.meta
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 4a109a0b0bb6e8f40935ca2ec55e5bd7
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
113
Assets/Scripts/NIH/MIConvexHull/Cell2.cs
Normal file
113
Assets/Scripts/NIH/MIConvexHull/Cell2.cs
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using System.Linq;
|
||||
using MIConvexHull;
|
||||
|
||||
/// <summary>
|
||||
/// A vertex is a simple class that stores the postion of a point, node or vertex.
|
||||
/// </summary>
|
||||
public class Cell2 : TriangulationCell<Vertex2, Cell2>
|
||||
{
|
||||
Vector2? circumCenter, centroid;
|
||||
|
||||
public Vector2 Circumcenter {
|
||||
get {
|
||||
circumCenter = circumCenter ?? GetCircumcenter();
|
||||
return circumCenter.Value;
|
||||
}
|
||||
}
|
||||
|
||||
public Vector2 Centroid {
|
||||
get {
|
||||
centroid = centroid ?? GetCentroid();
|
||||
return centroid.Value;
|
||||
}
|
||||
}
|
||||
|
||||
public Cell2 ()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
double LengthSquared (double[] v)
|
||||
{
|
||||
double norm = 0;
|
||||
for (int i = 0; i < v.Length; i++) {
|
||||
var t = v [i];
|
||||
norm += t * t;
|
||||
}
|
||||
return norm;
|
||||
}
|
||||
|
||||
double Determinant(double[,] m)
|
||||
{
|
||||
double fCofactor00 = m[1,1] * m[2,2] - m[1,2] * m[2,1];
|
||||
double fCofactor10 = m[1,2] * m[2,0] - m[1,0] * m[2,2];
|
||||
double fCofactor20 = m[1,0] * m[2,1] - m[1,1] * m[2,0];
|
||||
|
||||
double fDet = m[0,0] * fCofactor00 + m[0,1] * fCofactor10 + m[0,2] * fCofactor20;
|
||||
|
||||
return fDet;
|
||||
}
|
||||
|
||||
Vector2 GetCircumcenter ()
|
||||
{
|
||||
// From MathWorld: http://mathworld.wolfram.com/Circumcircle.html
|
||||
|
||||
var points = Vertices;
|
||||
|
||||
double[,] m = new double[3, 3];
|
||||
|
||||
// x, y, 1
|
||||
for (int i = 0; i < 3; i++) {
|
||||
m[i, 0] = points[i].x;
|
||||
m[i, 1] = points[i].y;
|
||||
m[i, 2] = 1;
|
||||
}
|
||||
var a = Determinant(m);
|
||||
|
||||
// size, y, 1
|
||||
for (int i = 0; i < 3; i++) {
|
||||
m[i, 0] = points[i].StoredPosition.sqrMagnitude;
|
||||
}
|
||||
var dx = -Determinant(m);
|
||||
|
||||
// size, x, 1
|
||||
for (int i = 0; i < 3; i++) {
|
||||
m[i, 1] = points[i].x;
|
||||
}
|
||||
var dy = Determinant(m);
|
||||
|
||||
// size, x, y
|
||||
//for (int i = 0; i < 3; i++) {
|
||||
// m[i, 2] = points[i].y;
|
||||
//}
|
||||
//var c = -Det(m);
|
||||
|
||||
var s = -1.0 / (2.0 * a);
|
||||
//var r = System.Math.Abs(s) * System.Math.Sqrt(dx * dx + dy * dy - 4 * a * c);
|
||||
|
||||
return new Vector2((float)(s * dx), (float)(s * dy));
|
||||
}
|
||||
|
||||
Vector2 GetCentroid ()
|
||||
{
|
||||
return new Vector2((float)Vertices.Select(v => v.Position[0]).Average(), (float)Vertices.Select(v => v.Position[1]).Average());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
11
Assets/Scripts/NIH/MIConvexHull/Cell2.cs.meta
Normal file
11
Assets/Scripts/NIH/MIConvexHull/Cell2.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: adf902e96e0c51049b65bc002d6ef4ca
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
46
Assets/Scripts/NIH/MIConvexHull/Constants.cs
Normal file
46
Assets/Scripts/NIH/MIConvexHull/Constants.cs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
/******************************************************************************
|
||||
*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*
|
||||
*****************************************************************************/
|
||||
|
||||
using System;
|
||||
|
||||
namespace MIConvexHull
|
||||
{
|
||||
internal static class Constants
|
||||
{
|
||||
/// <summary>
|
||||
/// The default plane distance tolerance
|
||||
/// </summary>
|
||||
internal const double DefaultPlaneDistanceTolerance = 1e-10;
|
||||
/// <summary>
|
||||
/// The starting delta dot product in simplex
|
||||
/// </summary>
|
||||
internal const double StartingDeltaDotProductInSimplex = 0.5;
|
||||
/// <summary>
|
||||
/// The connector table size
|
||||
/// </summary>
|
||||
internal const int ConnectorTableSize = 2017;
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/NIH/MIConvexHull/Constants.cs.meta
Normal file
11
Assets/Scripts/NIH/MIConvexHull/Constants.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: ee065f025d2f5374db2ceaa973b822d4
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
135
Assets/Scripts/NIH/MIConvexHull/ConvexHull.cs
Normal file
135
Assets/Scripts/NIH/MIConvexHull/ConvexHull.cs
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
/******************************************************************************
|
||||
*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*
|
||||
*****************************************************************************/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace MIConvexHull
|
||||
{
|
||||
/// <summary>
|
||||
/// Factory class for computing convex hulls.
|
||||
/// </summary>
|
||||
public static class ConvexHull
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a convex hull of the input data.
|
||||
/// </summary>
|
||||
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
|
||||
/// <typeparam name="TFace">The type of the t face.</typeparam>
|
||||
/// <param name="data">The data.</param>
|
||||
/// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
|
||||
/// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
|
||||
/// <returns>
|
||||
/// ConvexHull<TVertex, TFace>.
|
||||
/// </returns>
|
||||
public static ConvexHull<TVertex, TFace> Create<TVertex, TFace>(IList<TVertex> data,
|
||||
double PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
|
||||
where TVertex : IVertex
|
||||
where TFace : ConvexFace<TVertex, TFace>, new()
|
||||
{
|
||||
return ConvexHull<TVertex, TFace>.Create(data, PlaneDistanceTolerance);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a convex hull of the input data.
|
||||
/// </summary>
|
||||
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
|
||||
/// <param name="data">The data.</param>
|
||||
/// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
|
||||
/// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
|
||||
/// <returns>
|
||||
/// ConvexHull<TVertex, DefaultConvexFace<TVertex>>.
|
||||
/// </returns>
|
||||
public static ConvexHull<TVertex, DefaultConvexFace<TVertex>> Create<TVertex>(IList<TVertex> data,
|
||||
double PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
|
||||
where TVertex : IVertex
|
||||
{
|
||||
return ConvexHull<TVertex, DefaultConvexFace<TVertex>>.Create(data, PlaneDistanceTolerance);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a convex hull of the input data.
|
||||
/// </summary>
|
||||
/// <param name="data">The data.</param>
|
||||
/// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
|
||||
/// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
|
||||
/// <returns>
|
||||
/// ConvexHull<DefaultVertex, DefaultConvexFace<DefaultVertex>>.
|
||||
/// </returns>
|
||||
public static ConvexHull<DefaultVertex, DefaultConvexFace<DefaultVertex>> Create(IList<double[]> data,
|
||||
double PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
|
||||
{
|
||||
var points = data.Select(p => new DefaultVertex { Position = p }).ToList();
|
||||
return ConvexHull<DefaultVertex, DefaultConvexFace<DefaultVertex>>.Create(points, PlaneDistanceTolerance);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Representation of a convex hull.
|
||||
/// </summary>
|
||||
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
|
||||
/// <typeparam name="TFace">The type of the t face.</typeparam>
|
||||
public class ConvexHull<TVertex, TFace>
|
||||
where TVertex : IVertex
|
||||
where TFace : ConvexFace<TVertex, TFace>, new()
|
||||
{
|
||||
/// <summary>
|
||||
/// Can only be created using a factory method.
|
||||
/// </summary>
|
||||
internal ConvexHull()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Points of the convex hull.
|
||||
/// </summary>
|
||||
/// <value>The points.</value>
|
||||
public IEnumerable<TVertex> Points { get; internal set; }
|
||||
|
||||
/// <summary>
|
||||
/// Faces of the convex hull.
|
||||
/// </summary>
|
||||
/// <value>The faces.</value>
|
||||
public IEnumerable<TFace> Faces { get; internal set; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates the convex hull.
|
||||
/// </summary>
|
||||
/// <param name="data">The data.</param>
|
||||
/// <param name="PlaneDistanceTolerance">The plane distance tolerance.</param>
|
||||
/// <returns>
|
||||
/// ConvexHull<TVertex, TFace>.
|
||||
/// </returns>
|
||||
/// <exception cref="System.ArgumentNullException">The supplied data is null.</exception>
|
||||
/// <exception cref="ArgumentNullException">data</exception>
|
||||
public static ConvexHull<TVertex, TFace> Create(IList<TVertex> data, double PlaneDistanceTolerance)
|
||||
{
|
||||
if (data == null) throw new ArgumentNullException("The supplied data is null.");
|
||||
return ConvexHullAlgorithm.GetConvexHull<TVertex, TFace>(data, PlaneDistanceTolerance);
|
||||
}
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/NIH/MIConvexHull/ConvexHull.cs.meta
Normal file
11
Assets/Scripts/NIH/MIConvexHull/ConvexHull.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 447289e858e19c14abbe91dfbd0e3089
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
8
Assets/Scripts/NIH/MIConvexHull/ConvexHull.meta
Normal file
8
Assets/Scripts/NIH/MIConvexHull/ConvexHull.meta
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
fileFormatVersion: 2
|
||||
guid: a6e88469e3b81a541a0bc8a66e60d0c7
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
304
Assets/Scripts/NIH/MIConvexHull/ConvexHull/Collections.cs
Normal file
304
Assets/Scripts/NIH/MIConvexHull/ConvexHull/Collections.cs
Normal file
|
|
@ -0,0 +1,304 @@
|
|||
/******************************************************************************
|
||||
*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*
|
||||
*****************************************************************************/
|
||||
|
||||
using System;
|
||||
|
||||
namespace MIConvexHull
|
||||
{
|
||||
/// <summary>
|
||||
/// A more lightweight alternative to List of T.
|
||||
/// On clear, only resets the count and does not clear the references
|
||||
/// => this works because of the ObjectManager.
|
||||
/// Includes a stack functionality.
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
internal class SimpleList<T>
|
||||
{
|
||||
/// <summary>
|
||||
/// The capacity
|
||||
/// </summary>
|
||||
private int capacity;
|
||||
|
||||
/// <summary>
|
||||
/// The count
|
||||
/// </summary>
|
||||
public int Count;
|
||||
/// <summary>
|
||||
/// The items
|
||||
/// </summary>
|
||||
private T[] items;
|
||||
|
||||
/// <summary>
|
||||
/// Get the i-th element.
|
||||
/// </summary>
|
||||
/// <param name="i">The i.</param>
|
||||
/// <returns>T.</returns>
|
||||
public T this[int i]
|
||||
{
|
||||
get { return items[i]; }
|
||||
set { items[i] = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Size matters.
|
||||
/// </summary>
|
||||
private void EnsureCapacity()
|
||||
{
|
||||
if (capacity == 0)
|
||||
{
|
||||
capacity = 32;
|
||||
items = new T[32];
|
||||
}
|
||||
else
|
||||
{
|
||||
var newItems = new T[capacity*2];
|
||||
Array.Copy(items, newItems, capacity);
|
||||
capacity = 2*capacity;
|
||||
items = newItems;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a vertex to the buffer.
|
||||
/// </summary>
|
||||
/// <param name="item">The item.</param>
|
||||
public void Add(T item)
|
||||
{
|
||||
if (Count + 1 > capacity) EnsureCapacity();
|
||||
items[Count++] = item;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pushes the value to the back of the list.
|
||||
/// </summary>
|
||||
/// <param name="item">The item.</param>
|
||||
public void Push(T item)
|
||||
{
|
||||
if (Count + 1 > capacity) EnsureCapacity();
|
||||
items[Count++] = item;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pops the last value from the list.
|
||||
/// </summary>
|
||||
/// <returns>T.</returns>
|
||||
public T Pop()
|
||||
{
|
||||
return items[--Count];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the Count to 0, otherwise does nothing.
|
||||
/// </summary>
|
||||
public void Clear()
|
||||
{
|
||||
Count = 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Class IndexBuffer.
|
||||
/// A fancy name for a list of integers.
|
||||
/// </summary>
|
||||
internal class IndexBuffer : SimpleList<int>
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A priority based linked list.
|
||||
/// </summary>
|
||||
internal sealed class FaceList
|
||||
{
|
||||
/// <summary>
|
||||
/// The last
|
||||
/// </summary>
|
||||
private ConvexFaceInternal last;
|
||||
|
||||
/// <summary>
|
||||
/// Get the first element.
|
||||
/// </summary>
|
||||
/// <value>The first.</value>
|
||||
public ConvexFaceInternal First { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Adds the element to the beginning.
|
||||
/// </summary>
|
||||
/// <param name="face">The face.</param>
|
||||
private void AddFirst(ConvexFaceInternal face)
|
||||
{
|
||||
face.InList = true;
|
||||
First.Previous = face;
|
||||
face.Next = First;
|
||||
First = face;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a face to the list.
|
||||
/// </summary>
|
||||
/// <param name="face">The face.</param>
|
||||
public void Add(ConvexFaceInternal face)
|
||||
{
|
||||
if (face.InList)
|
||||
{
|
||||
if (First.VerticesBeyond.Count < face.VerticesBeyond.Count)
|
||||
{
|
||||
Remove(face);
|
||||
AddFirst(face);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
face.InList = true;
|
||||
|
||||
if (First != null && First.VerticesBeyond.Count < face.VerticesBeyond.Count)
|
||||
{
|
||||
First.Previous = face;
|
||||
face.Next = First;
|
||||
First = face;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (last != null)
|
||||
{
|
||||
last.Next = face;
|
||||
}
|
||||
face.Previous = last;
|
||||
last = face;
|
||||
if (First == null)
|
||||
{
|
||||
First = face;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the element from the list.
|
||||
/// </summary>
|
||||
/// <param name="face">The face.</param>
|
||||
public void Remove(ConvexFaceInternal face)
|
||||
{
|
||||
if (!face.InList) return;
|
||||
|
||||
face.InList = false;
|
||||
|
||||
if (face.Previous != null)
|
||||
{
|
||||
face.Previous.Next = face.Next;
|
||||
}
|
||||
else if ( /*first == face*/ face.Previous == null)
|
||||
{
|
||||
First = face.Next;
|
||||
}
|
||||
|
||||
if (face.Next != null)
|
||||
{
|
||||
face.Next.Previous = face.Previous;
|
||||
}
|
||||
else if ( /*last == face*/ face.Next == null)
|
||||
{
|
||||
last = face.Previous;
|
||||
}
|
||||
|
||||
face.Next = null;
|
||||
face.Previous = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Connector list.
|
||||
/// </summary>
|
||||
internal sealed class ConnectorList
|
||||
{
|
||||
/// <summary>
|
||||
/// The last
|
||||
/// </summary>
|
||||
private FaceConnector last;
|
||||
|
||||
/// <summary>
|
||||
/// Get the first element.
|
||||
/// </summary>
|
||||
/// <value>The first.</value>
|
||||
public FaceConnector First { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Adds the element to the beginning.
|
||||
/// </summary>
|
||||
/// <param name="connector">The connector.</param>
|
||||
private void AddFirst(FaceConnector connector)
|
||||
{
|
||||
First.Previous = connector;
|
||||
connector.Next = First;
|
||||
First = connector;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a face to the list.
|
||||
/// </summary>
|
||||
/// <param name="element">The element.</param>
|
||||
public void Add(FaceConnector element)
|
||||
{
|
||||
if (last != null)
|
||||
{
|
||||
last.Next = element;
|
||||
}
|
||||
element.Previous = last;
|
||||
last = element;
|
||||
if (First == null)
|
||||
{
|
||||
First = element;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the element from the list.
|
||||
/// </summary>
|
||||
/// <param name="connector">The connector.</param>
|
||||
public void Remove(FaceConnector connector)
|
||||
{
|
||||
if (connector.Previous != null)
|
||||
{
|
||||
connector.Previous.Next = connector.Next;
|
||||
}
|
||||
else if ( /*first == face*/ connector.Previous == null)
|
||||
{
|
||||
First = connector.Next;
|
||||
}
|
||||
|
||||
if (connector.Next != null)
|
||||
{
|
||||
connector.Next.Previous = connector.Previous;
|
||||
}
|
||||
else if ( /*last == face*/ connector.Next == null)
|
||||
{
|
||||
last = connector.Previous;
|
||||
}
|
||||
|
||||
connector.Next = null;
|
||||
connector.Previous = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 3969283304824fe4a8eca1eb522fd3a7
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
69
Assets/Scripts/NIH/MIConvexHull/ConvexHull/ConvexFace.cs
Normal file
69
Assets/Scripts/NIH/MIConvexHull/ConvexHull/ConvexFace.cs
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
/******************************************************************************
|
||||
*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*
|
||||
*****************************************************************************/
|
||||
|
||||
namespace MIConvexHull
|
||||
{
|
||||
/// <summary>
|
||||
/// A convex face representation containing adjacency information.
|
||||
/// </summary>
|
||||
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
|
||||
/// <typeparam name="TFace">The type of the t face.</typeparam>
|
||||
public abstract class ConvexFace<TVertex, TFace>
|
||||
where TVertex : IVertex
|
||||
where TFace : ConvexFace<TVertex, TFace>
|
||||
{
|
||||
/// <summary>
|
||||
/// Adjacency. Array of length "dimension".
|
||||
/// If F = Adjacency[i] then the vertices shared with F are Vertices[j] where j != i.
|
||||
/// In the context of triangulation, can be null (indicates the cell is at boundary).
|
||||
/// </summary>
|
||||
/// <value>The adjacency.</value>
|
||||
public TFace[] Adjacency { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The vertices stored in clockwise order for dimensions 2 - 4, in higher dimensions the order is arbitrary.
|
||||
/// Unless I accidentally switch some index somewhere in which case the order is CCW. Either way, it is consistent.
|
||||
/// 3D Normal = (V[1] - V[0]) x (V[2] - V[1]).
|
||||
/// </summary>
|
||||
/// <value>The vertices.</value>
|
||||
public TVertex[] Vertices { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The normal vector of the face. Null if used in triangulation.
|
||||
/// </summary>
|
||||
/// <value>The normal.</value>
|
||||
public double[] Normal { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A default convex face representation.
|
||||
/// </summary>
|
||||
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
|
||||
public class DefaultConvexFace<TVertex> : ConvexFace<TVertex, DefaultConvexFace<TVertex>>
|
||||
where TVertex : IVertex
|
||||
{
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 5db1a96860ec6d949930695ae9bedcc0
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -0,0 +1,721 @@
|
|||
/******************************************************************************
|
||||
*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*
|
||||
*****************************************************************************/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace MIConvexHull
|
||||
{
|
||||
/*
|
||||
* This part of the implementation handles initialization of the convex hull algorithm:
|
||||
* - Constructor & Process initiation
|
||||
* - Determine the dimension by looking at length of Position vector of 10 random data points from the input.
|
||||
* - Identify bounding box points in each direction.
|
||||
* - Pick (Dimension + 1) points from the extremes and construct the initial simplex.
|
||||
*/
|
||||
|
||||
/// <summary>
|
||||
/// Class ConvexHullAlgorithm.
|
||||
/// </summary>
|
||||
internal partial class ConvexHullAlgorithm
|
||||
{
|
||||
#region Starting functions and constructor
|
||||
/// <summary>
|
||||
/// The main function for the Convex Hull algorithm. It is static, but it creates
|
||||
/// an instantiation of this class in order to allow for parallel execution.
|
||||
/// Following this simple function, the constructor and the main function "FindConvexHull" is listed.
|
||||
/// </summary>
|
||||
/// <typeparam name="TVertex">The type of the vertices in the data.</typeparam>
|
||||
/// <typeparam name="TFace">The desired type of the faces.</typeparam>
|
||||
/// <param name="data">The data is the vertices as a collection of IVertices.</param>
|
||||
/// <param name="PlaneDistanceTolerance">The plane distance tolerance.</param>
|
||||
/// <returns>
|
||||
/// MIConvexHull.ConvexHull<TVertex, TFace>.
|
||||
/// </returns>
|
||||
internal static ConvexHull<TVertex, TFace> GetConvexHull<TVertex, TFace>(IList<TVertex> data,
|
||||
double PlaneDistanceTolerance)
|
||||
where TFace : ConvexFace<TVertex, TFace>, new()
|
||||
where TVertex : IVertex
|
||||
{
|
||||
var ch = new ConvexHullAlgorithm(data.Cast<IVertex>().ToArray(), false, PlaneDistanceTolerance);
|
||||
ch.GetConvexHull();
|
||||
|
||||
if (ch.NumOfDimensions == 2) return ch.Return2DResultInOrder<TVertex, TFace>(data);
|
||||
return new ConvexHull<TVertex, TFace>
|
||||
{
|
||||
Points = ch.GetHullVertices(data),
|
||||
Faces = ch.GetConvexFaces<TVertex, TFace>()
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ConvexHullAlgorithm" /> class.
|
||||
/// </summary>
|
||||
/// <param name="vertices">The vertices.</param>
|
||||
/// <param name="lift">if set to <c>true</c> [lift].</param>
|
||||
/// <param name="PlaneDistanceTolerance">The plane distance tolerance.</param>
|
||||
/// <exception cref="System.InvalidOperationException">Dimension of the input must be 2 or greater.</exception>
|
||||
/// <exception cref="System.ArgumentException">There are too few vertices (m) for the n-dimensional space. (m must be greater +
|
||||
/// than the n, but m is + NumberOfVertices + and n is + NumOfDimensions</exception>
|
||||
/// <exception cref="InvalidOperationException">PointTranslationGenerator cannot be null if PointTranslationType is enabled.
|
||||
/// or
|
||||
/// Dimension of the input must be 2 or greater.</exception>
|
||||
/// <exception cref="ArgumentException">There are too few vertices (m) for the n-dimensional space. (m must be greater " +
|
||||
/// "than the n, but m is " + NumberOfVertices + " and n is " + Dimension</exception>
|
||||
private ConvexHullAlgorithm(IVertex[] vertices, bool lift, double PlaneDistanceTolerance)
|
||||
{
|
||||
IsLifted = lift;
|
||||
Vertices = vertices;
|
||||
NumberOfVertices = vertices.Length;
|
||||
|
||||
NumOfDimensions = DetermineDimension();
|
||||
if (IsLifted) NumOfDimensions++;
|
||||
if (NumOfDimensions < 2) throw new InvalidOperationException("Dimension of the input must be 2 or greater.");
|
||||
if (NumberOfVertices <= NumOfDimensions)
|
||||
throw new ArgumentException(
|
||||
"There are too few vertices (m) for the n-dimensional space. (m must be greater " +
|
||||
"than the n, but m is " + NumberOfVertices + " and n is " + NumOfDimensions);
|
||||
this.PlaneDistanceTolerance = PlaneDistanceTolerance;
|
||||
UnprocessedFaces = new FaceList();
|
||||
ConvexFaces = new IndexBuffer();
|
||||
|
||||
FacePool = new ConvexFaceInternal[(NumOfDimensions + 1) * 10]; // must be initialized before object manager
|
||||
AffectedFaceFlags = new bool[(NumOfDimensions + 1) * 10];
|
||||
ObjectManager = new ObjectManager(this);
|
||||
|
||||
Center = new double[NumOfDimensions];
|
||||
TraverseStack = new IndexBuffer();
|
||||
UpdateBuffer = new int[NumOfDimensions];
|
||||
UpdateIndices = new int[NumOfDimensions];
|
||||
EmptyBuffer = new IndexBuffer();
|
||||
AffectedFaceBuffer = new IndexBuffer();
|
||||
ConeFaceBuffer = new SimpleList<DeferredFace>();
|
||||
SingularVertices = new HashSet<int>();
|
||||
BeyondBuffer = new IndexBuffer();
|
||||
|
||||
ConnectorTable = new ConnectorList[Constants.ConnectorTableSize];
|
||||
for (var i = 0; i < Constants.ConnectorTableSize; i++) ConnectorTable[i] = new ConnectorList();
|
||||
|
||||
VertexVisited = new bool[NumberOfVertices];
|
||||
Positions = new double[NumberOfVertices * NumOfDimensions];
|
||||
boundingBoxPoints = new List<int>[NumOfDimensions];
|
||||
minima = new double[NumOfDimensions];
|
||||
maxima = new double[NumOfDimensions];
|
||||
mathHelper = new MathHelper(NumOfDimensions, Positions);
|
||||
}
|
||||
/// <summary>
|
||||
/// Check the dimensionality of the input data.
|
||||
/// </summary>
|
||||
/// <returns>System.Int32.</returns>
|
||||
/// <exception cref="ArgumentException">Invalid input data (non-uniform dimension).</exception>
|
||||
private int DetermineDimension()
|
||||
{
|
||||
var r = new Random();
|
||||
var dimensions = new List<int>();
|
||||
for (var i = 0; i < 10; i++)
|
||||
dimensions.Add(Vertices[r.Next(NumberOfVertices)].Position.Length);
|
||||
var dimension = dimensions.Min();
|
||||
if (dimension != dimensions.Max())
|
||||
throw new ArgumentException("Invalid input data (non-uniform dimension).");
|
||||
return dimension;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets/calculates the convex hull. This is
|
||||
/// </summary>
|
||||
private void GetConvexHull()
|
||||
{
|
||||
// accessing a 1D array is quicker than a jagged array, so the first step is to make this array
|
||||
SerializeVerticesToPositions();
|
||||
// next the bounding box extremes are found. This is used to shift, scale and find the starting simplex.
|
||||
FindBoundingBoxPoints();
|
||||
// the positions are shifted to avoid divide by zero problems
|
||||
// and if Delaunay or Voronoi, then the parabola terms are scaled back to match the size of the other coords
|
||||
ShiftAndScalePositions();
|
||||
// Find the (dimension+1) initial points and create the simplexes.
|
||||
CreateInitialSimplex();
|
||||
|
||||
// Now, the main loop. These initial faces of a simplex are replaced and expanded
|
||||
// outwards to make the convex hull and faces.
|
||||
while (UnprocessedFaces.First != null)
|
||||
{
|
||||
var currentFace = UnprocessedFaces.First;
|
||||
CurrentVertex = currentFace.FurthestVertex;
|
||||
|
||||
UpdateCenter();
|
||||
|
||||
// The affected faces get tagged
|
||||
TagAffectedFaces(currentFace);
|
||||
|
||||
// Create the cone from the currentVertex and the affected faces horizon.
|
||||
if (!SingularVertices.Contains(CurrentVertex) && CreateCone()) CommitCone();
|
||||
else HandleSingular();
|
||||
|
||||
// Need to reset the tags
|
||||
var count = AffectedFaceBuffer.Count;
|
||||
for (var i = 0; i < count; i++) AffectedFaceFlags[AffectedFaceBuffer[i]] = false;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// Serializes the vertices into the 1D array, Positions. The 1D array has much quicker access in C#.
|
||||
/// </summary>
|
||||
private void SerializeVerticesToPositions()
|
||||
{
|
||||
var index = 0;
|
||||
if (IsLifted) // "Lifted" means that the last dimension is the sum of the squares of the others.
|
||||
{
|
||||
foreach (var v in Vertices)
|
||||
{
|
||||
var parabolaTerm = 0.0; // the lifted term is a sum of squares.
|
||||
var origNumDim = NumOfDimensions - 1;
|
||||
for (var i = 0; i < origNumDim; i++)
|
||||
{
|
||||
var coordinate = v.Position[i];
|
||||
Positions[index++] = coordinate;
|
||||
parabolaTerm += coordinate * coordinate;
|
||||
}
|
||||
Positions[index++] = parabolaTerm;
|
||||
}
|
||||
}
|
||||
else
|
||||
foreach (var v in Vertices)
|
||||
{
|
||||
for (var i = 0; i < NumOfDimensions; i++)
|
||||
Positions[index++] = v.Position[i];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Finds the bounding box points.
|
||||
/// </summary>
|
||||
private void FindBoundingBoxPoints()
|
||||
{
|
||||
indexOfDimensionWithLeastExtremes = -1;
|
||||
var minNumExtremes = int.MaxValue;
|
||||
for (var i = 0; i < NumOfDimensions; i++)
|
||||
{
|
||||
var minIndices = new List<int>();
|
||||
var maxIndices = new List<int>();
|
||||
double min = double.PositiveInfinity, max = double.NegativeInfinity;
|
||||
for (var j = 0; j < NumberOfVertices; j++)
|
||||
{
|
||||
var v = GetCoordinate(j, i);
|
||||
var difference = min - v;
|
||||
if (difference >= PlaneDistanceTolerance)
|
||||
{
|
||||
// you found a better solution than before, clear out the list and store new value
|
||||
min = v;
|
||||
minIndices.Clear();
|
||||
minIndices.Add(j);
|
||||
}
|
||||
else if (difference > 0)
|
||||
{
|
||||
// you found a solution slightly better than before, clear out those that are no longer on the list and store new value
|
||||
min = v;
|
||||
minIndices.RemoveAll(index => min - GetCoordinate(index, i) > PlaneDistanceTolerance);
|
||||
minIndices.Add(j);
|
||||
}
|
||||
else if (difference > -PlaneDistanceTolerance)
|
||||
{
|
||||
//same or almost as good as current limit, so store it
|
||||
minIndices.Add(j);
|
||||
}
|
||||
difference = v - max;
|
||||
if (difference >= PlaneDistanceTolerance)
|
||||
{
|
||||
// you found a better solution than before, clear out the list and store new value
|
||||
max = v;
|
||||
maxIndices.Clear();
|
||||
maxIndices.Add(j);
|
||||
}
|
||||
else if (difference > 0)
|
||||
{
|
||||
// you found a solution slightly better than before, clear out those that are no longer on the list and store new value
|
||||
max = v;
|
||||
maxIndices.RemoveAll(index => min - GetCoordinate(index, i) > PlaneDistanceTolerance);
|
||||
maxIndices.Add(j);
|
||||
}
|
||||
else if (difference > -PlaneDistanceTolerance)
|
||||
{
|
||||
//same or almost as good as current limit, so store it
|
||||
maxIndices.Add(j);
|
||||
}
|
||||
}
|
||||
minima[i] = min;
|
||||
maxima[i] = max;
|
||||
minIndices.AddRange(maxIndices);
|
||||
if (minIndices.Count < minNumExtremes)
|
||||
{
|
||||
minNumExtremes = minIndices.Count;
|
||||
indexOfDimensionWithLeastExtremes = i;
|
||||
}
|
||||
boundingBoxPoints[i] = minIndices;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Shifts and scales the Positions to avoid future errors. This does not alter the original data.
|
||||
/// </summary>
|
||||
private void ShiftAndScalePositions()
|
||||
{
|
||||
var positionsLength = Positions.Length;
|
||||
if (IsLifted)
|
||||
{
|
||||
var origNumDim = NumOfDimensions - 1;
|
||||
var parabolaScale = 2 / (minima.Sum(x => Math.Abs(x)) + maxima.Sum(x => Math.Abs(x))
|
||||
- Math.Abs(maxima[origNumDim]) - Math.Abs(minima[origNumDim]));
|
||||
// the parabola scale is 1 / average of the sum of the other dimensions.
|
||||
// multiplying this by the parabola will scale it back to be on near similar size to the
|
||||
// other dimensions. Without this, the term is much larger than the others, which causes
|
||||
// problems for roundoff error and finding the normal of faces.
|
||||
minima[origNumDim] *= parabolaScale; // change the extreme values as well
|
||||
maxima[origNumDim] *= parabolaScale;
|
||||
// it is done here because
|
||||
for (int i = origNumDim; i < positionsLength; i += NumOfDimensions)
|
||||
Positions[i] *= parabolaScale;
|
||||
}
|
||||
var shiftAmount = new double[NumOfDimensions];
|
||||
for (int i = 0; i < NumOfDimensions; i++)
|
||||
// now the entire model is shifted to all positive numbers...plus some more.
|
||||
// why?
|
||||
// 1) to avoid dealing with a point at the origin {0,0,...,0} which causes problems
|
||||
// for future normal finding
|
||||
// 2) note that weird shift that is used (max - min - min). This is to avoid scaling
|
||||
// issues. this shift means that the minima in a dimension will always be a positive
|
||||
// number (no points at zero), and the minima [in a given dimension] will always be
|
||||
// half of the maxima. 'Half' is much preferred to 'thousands of times'
|
||||
// Think of the first term as the range (max - min), then the second term avoids cases
|
||||
// where there are both positive and negative numbers.
|
||||
if (maxima[i] == minima[i]) shiftAmount[i] = 0.0;
|
||||
else shiftAmount[i] = (maxima[i] - minima[i]) - minima[i];
|
||||
for (int i = 0; i < positionsLength; i++)
|
||||
Positions[i] += shiftAmount[i % NumOfDimensions];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Find the (dimension+1) initial points and create the simplexes.
|
||||
/// Creates the initial simplex of n+1 vertices by using points from the bounding box.
|
||||
/// Special care is taken to ensure that the vertices chosen do not result in a degenerate shape
|
||||
/// where vertices are collinear (co-planar, etc). This would technically be resolved when additional
|
||||
/// vertices are checked in the main loop, but: 1) a degenerate simplex would not eliminate any other
|
||||
/// vertices (thus no savings there), 2) the creation of the face normal is prone to error.
|
||||
/// </summary>
|
||||
private void CreateInitialSimplex()
|
||||
{
|
||||
var initialPoints = FindInitialPoints();
|
||||
#region Create the first faces from (dimension + 1) vertices.
|
||||
|
||||
var faces = new int[NumOfDimensions + 1];
|
||||
|
||||
for (var i = 0; i < NumOfDimensions + 1; i++)
|
||||
{
|
||||
var vertices = new int[NumOfDimensions];
|
||||
for (int j = 0, k = 0; j <= NumOfDimensions; j++)
|
||||
{
|
||||
if (i != j) vertices[k++] = initialPoints[j];
|
||||
}
|
||||
var newFace = FacePool[ObjectManager.GetFace()];
|
||||
newFace.Vertices = vertices;
|
||||
Array.Sort(vertices);
|
||||
mathHelper.CalculateFacePlane(newFace, Center);
|
||||
faces[i] = newFace.Index;
|
||||
}
|
||||
// update the adjacency (check all pairs of faces)
|
||||
for (var i = 0; i < NumOfDimensions; i++)
|
||||
for (var j = i + 1; j < NumOfDimensions + 1; j++) UpdateAdjacency(FacePool[faces[i]], FacePool[faces[j]]);
|
||||
|
||||
#endregion
|
||||
|
||||
#region Init the vertex beyond buffers.
|
||||
|
||||
foreach (var faceIndex in faces)
|
||||
{
|
||||
var face = FacePool[faceIndex];
|
||||
FindBeyondVertices(face);
|
||||
if (face.VerticesBeyond.Count == 0) ConvexFaces.Add(face.Index); // The face is on the hull
|
||||
else UnprocessedFaces.Add(face);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
// Set all vertices to false (unvisited).
|
||||
foreach (var vertex in initialPoints) VertexVisited[vertex] = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds (dimension + 1) initial points.
|
||||
/// </summary>
|
||||
/// <returns>List<System.Int32>.</returns>
|
||||
/// <exception cref="System.ArgumentException">The input data is degenerate. It appears to exist in " + NumOfDimensions +
|
||||
/// " dimensions, but it is a " + (NumOfDimensions - 1) + " dimensional set (i.e. the point of collinear,"
|
||||
/// + " coplanar, or co-hyperplanar.)</exception>
|
||||
private List<int> FindInitialPoints()
|
||||
{
|
||||
var bigNumber = maxima.Sum() * NumOfDimensions * NumberOfVertices;
|
||||
// the first two points are taken from the dimension that had the fewest extremes
|
||||
// well, in most cases there will only be 2 in all dimensions: one min and one max
|
||||
// but a lot of engineering part shapes are nice and square and can have hundreds of
|
||||
// parallel vertices at the extremes
|
||||
var vertex1 = boundingBoxPoints[indexOfDimensionWithLeastExtremes].First(); // these are min and max vertices along
|
||||
var vertex2 = boundingBoxPoints[indexOfDimensionWithLeastExtremes].Last(); // the dimension that had the fewest points
|
||||
boundingBoxPoints[indexOfDimensionWithLeastExtremes].RemoveAt(0);
|
||||
boundingBoxPoints[indexOfDimensionWithLeastExtremes].RemoveAt(boundingBoxPoints[indexOfDimensionWithLeastExtremes].Count - 1);
|
||||
var initialPoints = new List<int> { vertex1, vertex2 };
|
||||
VertexVisited[vertex1] = VertexVisited[vertex2] = true;
|
||||
CurrentVertex = vertex1; UpdateCenter();
|
||||
CurrentVertex = vertex2; UpdateCenter();
|
||||
var edgeVectors = new double[NumOfDimensions][];
|
||||
edgeVectors[0] = mathHelper.VectorBetweenVertices(vertex2, vertex1);
|
||||
// now the remaining vertices are just combined in one big list
|
||||
var extremes = boundingBoxPoints.SelectMany(x => x).ToList();
|
||||
// otherwise find the remaining points by maximizing the initial simplex volume
|
||||
var index = 1;
|
||||
while (index < NumOfDimensions && extremes.Any())
|
||||
{
|
||||
var bestVertex = -1;
|
||||
var bestEdgeVector = new double[] { };
|
||||
var maxVolume = Constants.DefaultPlaneDistanceTolerance;
|
||||
for (var i = extremes.Count - 1; i >= 0; i--)
|
||||
{
|
||||
// count backwards in order to remove potential duplicates
|
||||
var vIndex = extremes[i];
|
||||
if (initialPoints.Contains(vIndex)) extremes.RemoveAt(i);
|
||||
else
|
||||
{
|
||||
edgeVectors[index] = mathHelper.VectorBetweenVertices(vIndex, vertex1);
|
||||
var volume = mathHelper.GetSimplexVolume(edgeVectors, index, bigNumber);
|
||||
if (maxVolume < volume)
|
||||
{
|
||||
maxVolume = volume;
|
||||
bestVertex = vIndex;
|
||||
bestEdgeVector = edgeVectors[index];
|
||||
}
|
||||
}
|
||||
}
|
||||
extremes.Remove(bestVertex);
|
||||
if (bestVertex == -1) break;
|
||||
initialPoints.Add(bestVertex);
|
||||
edgeVectors[index++] = bestEdgeVector;
|
||||
CurrentVertex = bestVertex; UpdateCenter();
|
||||
}
|
||||
// hmm, there are not enough points on the bounding box to make a simplex. It is rare but entirely possibly.
|
||||
// As an extreme, the bounding box can be made in n dimensions from only 2 unique points. When we can't find
|
||||
// enough unique points, we start again with ALL the vertices. The following is a near replica of the code
|
||||
// above, but instead of extremes, we consider "allVertices".
|
||||
if (initialPoints.Count <= NumOfDimensions && !IsLifted)
|
||||
{
|
||||
var allVertices = Enumerable.Range(0, NumberOfVertices).ToList();
|
||||
while (index < NumOfDimensions && allVertices.Any())
|
||||
{
|
||||
var bestVertex = -1;
|
||||
var bestEdgeVector = new double[] { };
|
||||
var maxVolume = 0.0;
|
||||
for (var i = allVertices.Count - 1; i >= 0; i--)
|
||||
{
|
||||
// count backwards in order to remove potential duplicates
|
||||
var vIndex = allVertices[i];
|
||||
if (initialPoints.Contains(vIndex)) allVertices.RemoveAt(i);
|
||||
else
|
||||
{
|
||||
edgeVectors[index] = mathHelper.VectorBetweenVertices(vIndex, vertex1);
|
||||
var volume = mathHelper.GetSimplexVolume(edgeVectors, index, bigNumber);
|
||||
if (maxVolume < volume)
|
||||
{
|
||||
maxVolume = volume;
|
||||
bestVertex = vIndex;
|
||||
bestEdgeVector = edgeVectors[index];
|
||||
}
|
||||
}
|
||||
}
|
||||
allVertices.Remove(bestVertex);
|
||||
if (bestVertex == -1) break;
|
||||
initialPoints.Add(bestVertex);
|
||||
edgeVectors[index++] = bestEdgeVector;
|
||||
CurrentVertex = bestVertex; UpdateCenter();
|
||||
}
|
||||
}
|
||||
if (initialPoints.Count <= NumOfDimensions && IsLifted)
|
||||
{
|
||||
var allVertices = Enumerable.Range(0, NumberOfVertices).ToList();
|
||||
while (index < NumOfDimensions && allVertices.Any())
|
||||
{
|
||||
var bestVertex = -1;
|
||||
var bestEdgeVector = new double[] { };
|
||||
var maxVolume = 0.0;
|
||||
for (var i = allVertices.Count - 1; i >= 0; i--)
|
||||
{
|
||||
// count backwards in order to remove potential duplicates
|
||||
var vIndex = allVertices[i];
|
||||
if (initialPoints.Contains(vIndex)) allVertices.RemoveAt(i);
|
||||
else
|
||||
{
|
||||
mathHelper.RandomOffsetToLift(vIndex, maxima.Last()-minima.Last());
|
||||
edgeVectors[index] = mathHelper.VectorBetweenVertices(vIndex, vertex1);
|
||||
var volume = mathHelper.GetSimplexVolume(edgeVectors, index, bigNumber);
|
||||
if (maxVolume < volume)
|
||||
{
|
||||
maxVolume = volume;
|
||||
bestVertex = vIndex;
|
||||
bestEdgeVector = edgeVectors[index];
|
||||
}
|
||||
}
|
||||
}
|
||||
allVertices.Remove(bestVertex);
|
||||
if (bestVertex == -1) break;
|
||||
initialPoints.Add(bestVertex);
|
||||
edgeVectors[index++] = bestEdgeVector;
|
||||
CurrentVertex = bestVertex; UpdateCenter();
|
||||
}
|
||||
}
|
||||
if (initialPoints.Count <= NumOfDimensions && IsLifted)
|
||||
throw new ArgumentException("The input data is degenerate. It appears to exist in " + NumOfDimensions +
|
||||
" dimensions, but it is a " + (NumOfDimensions - 1) + " dimensional set (i.e. the point of collinear,"
|
||||
+ " coplanar, or co-hyperplanar.)");
|
||||
return initialPoints;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Check if 2 faces are adjacent and if so, update their AdjacentFaces array.
|
||||
/// </summary>
|
||||
/// <param name="l">The l.</param>
|
||||
/// <param name="r">The r.</param>
|
||||
private void UpdateAdjacency(ConvexFaceInternal l, ConvexFaceInternal r)
|
||||
{
|
||||
var lv = l.Vertices;
|
||||
var rv = r.Vertices;
|
||||
int i;
|
||||
|
||||
// reset marks on the 1st face
|
||||
for (i = 0; i < lv.Length; i++) VertexVisited[lv[i]] = false;
|
||||
|
||||
// mark all vertices on the 2nd face
|
||||
for (i = 0; i < rv.Length; i++) VertexVisited[rv[i]] = true;
|
||||
|
||||
// find the 1st false index
|
||||
for (i = 0; i < lv.Length; i++) if (!VertexVisited[lv[i]]) break;
|
||||
|
||||
// no vertex was marked
|
||||
if (i == NumOfDimensions) return;
|
||||
|
||||
// check if only 1 vertex wasn't marked
|
||||
for (var j = i + 1; j < lv.Length; j++) if (!VertexVisited[lv[j]]) return;
|
||||
|
||||
// if we are here, the two faces share an edge
|
||||
l.AdjacentFaces[i] = r.Index;
|
||||
|
||||
// update the adj. face on the other face - find the vertex that remains marked
|
||||
for (i = 0; i < lv.Length; i++) VertexVisited[lv[i]] = false;
|
||||
for (i = 0; i < rv.Length; i++)
|
||||
{
|
||||
if (VertexVisited[rv[i]]) break;
|
||||
}
|
||||
r.AdjacentFaces[i] = l.Index;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Used in the "initialization" code.
|
||||
/// </summary>
|
||||
/// <param name="face">The face.</param>
|
||||
private void FindBeyondVertices(ConvexFaceInternal face)
|
||||
{
|
||||
var beyondVertices = face.VerticesBeyond;
|
||||
MaxDistance = double.NegativeInfinity;
|
||||
FurthestVertex = 0;
|
||||
for (var i = 0; i < NumberOfVertices; i++)
|
||||
{
|
||||
if (VertexVisited[i]) continue;
|
||||
IsBeyond(face, beyondVertices, i);
|
||||
}
|
||||
|
||||
face.FurthestVertex = FurthestVertex;
|
||||
}
|
||||
#region Fields
|
||||
|
||||
/// <summary>
|
||||
/// Corresponds to the dimension of the data.
|
||||
/// When the "lifted" hull is computed, Dimension is automatically incremented by one.
|
||||
/// </summary>
|
||||
internal readonly int NumOfDimensions;
|
||||
|
||||
/// <summary>
|
||||
/// Are we on a paraboloid?
|
||||
/// </summary>
|
||||
private readonly bool IsLifted;
|
||||
|
||||
/// <summary>
|
||||
/// Explained in ConvexHullComputationConfig.
|
||||
/// </summary>
|
||||
private readonly double PlaneDistanceTolerance;
|
||||
|
||||
/*
|
||||
* Representation of the input vertices.
|
||||
*
|
||||
* - In the algorithm, a vertex is represented by its index in the Vertices array.
|
||||
* This makes the algorithm a lot faster (up to 30%) than using object reference everywhere.
|
||||
* - Positions are stored as a single array of values. Coordinates for vertex with index i
|
||||
* are stored at indices <i * Dimension, (i + 1) * Dimension)
|
||||
* - VertexMarks are used by the algorithm to help identify a set of vertices that is "above" (or "beyond")
|
||||
* a specific face.
|
||||
*/
|
||||
/// <summary>
|
||||
/// The vertices
|
||||
/// </summary>
|
||||
private readonly IVertex[] Vertices;
|
||||
/// <summary>
|
||||
/// The positions
|
||||
/// </summary>
|
||||
private double[] Positions;
|
||||
/// <summary>
|
||||
/// The vertex marks
|
||||
/// </summary>
|
||||
private readonly bool[] VertexVisited;
|
||||
|
||||
private readonly int NumberOfVertices;
|
||||
|
||||
/*
|
||||
* The triangulation faces are represented in a single pool for objects that are being reused.
|
||||
* This allows for represent the faces as integers and significantly speeds up many computations.
|
||||
* - AffectedFaceFlags are used to mark affected faces/
|
||||
*/
|
||||
/// <summary>
|
||||
/// The face pool
|
||||
/// </summary>
|
||||
internal ConvexFaceInternal[] FacePool;
|
||||
/// <summary>
|
||||
/// The affected face flags
|
||||
/// </summary>
|
||||
internal bool[] AffectedFaceFlags;
|
||||
|
||||
/// <summary>
|
||||
/// Used to track the size of the current hull in the Update/RollbackCenter functions.
|
||||
/// </summary>
|
||||
private int ConvexHullSize;
|
||||
|
||||
/// <summary>
|
||||
/// A list of faces that that are not a part of the final convex hull and still need to be processed.
|
||||
/// </summary>
|
||||
private readonly FaceList UnprocessedFaces;
|
||||
|
||||
/// <summary>
|
||||
/// A list of faces that form the convex hull.
|
||||
/// </summary>
|
||||
private readonly IndexBuffer ConvexFaces;
|
||||
|
||||
/// <summary>
|
||||
/// The vertex that is currently being processed.
|
||||
/// </summary>
|
||||
private int CurrentVertex;
|
||||
|
||||
/// <summary>
|
||||
/// A helper variable to determine the furthest vertex for a particular convex face.
|
||||
/// </summary>
|
||||
private double MaxDistance;
|
||||
|
||||
/// <summary>
|
||||
/// A helper variable to help determine the index of the vertex that is furthest from the face that is currently being
|
||||
/// processed.
|
||||
/// </summary>
|
||||
private int FurthestVertex;
|
||||
|
||||
/// <summary>
|
||||
/// The centroid of the currently computed hull.
|
||||
/// </summary>
|
||||
private readonly double[] Center;
|
||||
|
||||
/*
|
||||
* Helper arrays to store faces for adjacency update.
|
||||
* This is just to prevent unnecessary allocations.
|
||||
*/
|
||||
/// <summary>
|
||||
/// The update buffer
|
||||
/// </summary>
|
||||
private readonly int[] UpdateBuffer;
|
||||
/// <summary>
|
||||
/// The update indices
|
||||
/// </summary>
|
||||
private readonly int[] UpdateIndices;
|
||||
|
||||
/// <summary>
|
||||
/// Used to determine which faces need to be updated at each step of the algorithm.
|
||||
/// </summary>
|
||||
private readonly IndexBuffer TraverseStack;
|
||||
|
||||
/// <summary>
|
||||
/// Used for VerticesBeyond for faces that are on the convex hull.
|
||||
/// </summary>
|
||||
private readonly IndexBuffer EmptyBuffer;
|
||||
|
||||
/// <summary>
|
||||
/// Used to determine which vertices are "above" (or "beyond") a face
|
||||
/// </summary>
|
||||
private IndexBuffer BeyondBuffer;
|
||||
|
||||
/// <summary>
|
||||
/// Stores faces that are visible from the current vertex.
|
||||
/// </summary>
|
||||
private readonly IndexBuffer AffectedFaceBuffer;
|
||||
|
||||
/// <summary>
|
||||
/// Stores faces that form a "cone" created by adding new vertex.
|
||||
/// </summary>
|
||||
private readonly SimpleList<DeferredFace> ConeFaceBuffer;
|
||||
|
||||
/// <summary>
|
||||
/// Stores a list of "singular" (or "generate", "planar", etc.) vertices that cannot be part of the hull.
|
||||
/// </summary>
|
||||
private readonly HashSet<int> SingularVertices;
|
||||
|
||||
/// <summary>
|
||||
/// The connector table helps to determine the adjacency of convex faces.
|
||||
/// Hashing is used instead of pairwise comparison. This significantly speeds up the computations,
|
||||
/// especially for higher dimensions.
|
||||
/// </summary>
|
||||
private readonly ConnectorList[] ConnectorTable;
|
||||
|
||||
/// <summary>
|
||||
/// Manages the memory allocations and storage of unused objects.
|
||||
/// Saves the garbage collector a lot of work.
|
||||
/// </summary>
|
||||
private readonly ObjectManager ObjectManager;
|
||||
|
||||
/// <summary>
|
||||
/// Helper class for handling math related stuff.
|
||||
/// </summary>
|
||||
private readonly MathHelper mathHelper;
|
||||
private readonly List<int>[] boundingBoxPoints;
|
||||
private int indexOfDimensionWithLeastExtremes;
|
||||
private readonly double[] minima;
|
||||
private readonly double[] maxima;
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 48bd00cb6ec8d244f90e1c1608f39074
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -0,0 +1,635 @@
|
|||
/******************************************************************************
|
||||
*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*
|
||||
*****************************************************************************/
|
||||
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace MIConvexHull
|
||||
{
|
||||
/*
|
||||
* Main part of the algorithm
|
||||
* Basic idea:
|
||||
* - Create the initial hull (done in Initialize.cs)
|
||||
*
|
||||
* For each face there are "vertices beyond" which are "visible" from it.
|
||||
* If there are no such vertices, the face is on the hull.
|
||||
*
|
||||
* - While there is at least one face with at least one "vertex beyond":
|
||||
* * Pick the furthest beyond vertex
|
||||
* * For this vertex:
|
||||
* > find all faces that are visible from it (TagAffectedFaces)
|
||||
* > remove them and replace them with a "cone" created by the vertex and the boundary
|
||||
* of the affected faces, and for each new face, compute "beyond vertices"
|
||||
* (CreateCone + CommitCone)
|
||||
*
|
||||
* + Implement it in way that is fast, but hard to understand and maintain.
|
||||
*/
|
||||
|
||||
/// <summary>
|
||||
/// Class ConvexHullAlgorithm.
|
||||
/// </summary>
|
||||
internal partial class ConvexHullAlgorithm
|
||||
{
|
||||
/// <summary>
|
||||
/// Tags all faces seen from the current vertex with 1.
|
||||
/// </summary>
|
||||
/// <param name="currentFace">The current face.</param>
|
||||
private void TagAffectedFaces(ConvexFaceInternal currentFace)
|
||||
{
|
||||
AffectedFaceBuffer.Clear();
|
||||
AffectedFaceBuffer.Add(currentFace.Index);
|
||||
TraverseAffectedFaces(currentFace.Index);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recursively traverse all the relevant faces.
|
||||
/// </summary>
|
||||
/// <param name="currentFace">The current face.</param>
|
||||
private void TraverseAffectedFaces(int currentFace)
|
||||
{
|
||||
TraverseStack.Clear();
|
||||
TraverseStack.Push(currentFace);
|
||||
AffectedFaceFlags[currentFace] = true;
|
||||
|
||||
while (TraverseStack.Count > 0)
|
||||
{
|
||||
var top = FacePool[TraverseStack.Pop()];
|
||||
for (var i = 0; i < NumOfDimensions; i++)
|
||||
{
|
||||
var adjFace = top.AdjacentFaces[i];
|
||||
|
||||
if (!AffectedFaceFlags[adjFace] &&
|
||||
mathHelper.GetVertexDistance(CurrentVertex, FacePool[adjFace]) >= PlaneDistanceTolerance)
|
||||
{
|
||||
AffectedFaceBuffer.Add(adjFace);
|
||||
AffectedFaceFlags[adjFace] = true;
|
||||
TraverseStack.Push(adjFace);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new deferred face.
|
||||
/// </summary>
|
||||
/// <param name="face">The face.</param>
|
||||
/// <param name="faceIndex">Index of the face.</param>
|
||||
/// <param name="pivot">The pivot.</param>
|
||||
/// <param name="pivotIndex">Index of the pivot.</param>
|
||||
/// <param name="oldFace">The old face.</param>
|
||||
/// <returns>DeferredFace.</returns>
|
||||
private DeferredFace MakeDeferredFace(ConvexFaceInternal face, int faceIndex, ConvexFaceInternal pivot,
|
||||
int pivotIndex, ConvexFaceInternal oldFace)
|
||||
{
|
||||
var ret = ObjectManager.GetDeferredFace();
|
||||
|
||||
ret.Face = face;
|
||||
ret.FaceIndex = faceIndex;
|
||||
ret.Pivot = pivot;
|
||||
ret.PivotIndex = pivotIndex;
|
||||
ret.OldFace = oldFace;
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Connect faces using a connector.
|
||||
/// </summary>
|
||||
/// <param name="connector">The connector.</param>
|
||||
private void ConnectFace(FaceConnector connector)
|
||||
{
|
||||
var index = connector.HashCode % Constants.ConnectorTableSize;
|
||||
var list = ConnectorTable[index];
|
||||
|
||||
for (var current = list.First; current != null; current = current.Next)
|
||||
{
|
||||
if (FaceConnector.AreConnectable(connector, current, NumOfDimensions))
|
||||
{
|
||||
list.Remove(current);
|
||||
FaceConnector.Connect(current, connector);
|
||||
current.Face = null;
|
||||
connector.Face = null;
|
||||
ObjectManager.DepositConnector(current);
|
||||
ObjectManager.DepositConnector(connector);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
list.Add(connector);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the faces "covered" by the current vertex and adds the newly created ones.
|
||||
/// </summary>
|
||||
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
|
||||
private bool CreateCone()
|
||||
{
|
||||
var currentVertexIndex = CurrentVertex;
|
||||
ConeFaceBuffer.Clear();
|
||||
|
||||
for (var fIndex = 0; fIndex < AffectedFaceBuffer.Count; fIndex++)
|
||||
{
|
||||
var oldFaceIndex = AffectedFaceBuffer[fIndex];
|
||||
var oldFace = FacePool[oldFaceIndex];
|
||||
|
||||
// Find the faces that need to be updated
|
||||
var updateCount = 0;
|
||||
for (var i = 0; i < NumOfDimensions; i++)
|
||||
{
|
||||
var af = oldFace.AdjacentFaces[i];
|
||||
if (!AffectedFaceFlags[af]) // Tag == false when oldFaces does not contain af
|
||||
{
|
||||
UpdateBuffer[updateCount] = af;
|
||||
UpdateIndices[updateCount] = i;
|
||||
++updateCount;
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0; i < updateCount; i++)
|
||||
{
|
||||
var adjacentFace = FacePool[UpdateBuffer[i]];
|
||||
|
||||
var oldFaceAdjacentIndex = 0;
|
||||
var adjFaceAdjacency = adjacentFace.AdjacentFaces;
|
||||
for (var j = 0; j < adjFaceAdjacency.Length; j++)
|
||||
{
|
||||
if (oldFaceIndex == adjFaceAdjacency[j])
|
||||
{
|
||||
oldFaceAdjacentIndex = j;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var forbidden = UpdateIndices[i]; // Index of the face that corresponds to this adjacent face
|
||||
|
||||
int oldVertexIndex;
|
||||
int[] vertices;
|
||||
|
||||
var newFaceIndex = ObjectManager.GetFace();
|
||||
var newFace = FacePool[newFaceIndex];
|
||||
vertices = newFace.Vertices;
|
||||
for (var j = 0; j < NumOfDimensions; j++) vertices[j] = oldFace.Vertices[j];
|
||||
oldVertexIndex = vertices[forbidden];
|
||||
|
||||
int orderedPivotIndex;
|
||||
|
||||
// correct the ordering
|
||||
if (currentVertexIndex < oldVertexIndex)
|
||||
{
|
||||
orderedPivotIndex = 0;
|
||||
for (var j = forbidden - 1; j >= 0; j--)
|
||||
{
|
||||
if (vertices[j] > currentVertexIndex) vertices[j + 1] = vertices[j];
|
||||
else
|
||||
{
|
||||
orderedPivotIndex = j + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
orderedPivotIndex = NumOfDimensions - 1;
|
||||
for (var j = forbidden + 1; j < NumOfDimensions; j++)
|
||||
{
|
||||
if (vertices[j] < currentVertexIndex) vertices[j - 1] = vertices[j];
|
||||
else
|
||||
{
|
||||
orderedPivotIndex = j - 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
vertices[orderedPivotIndex] = CurrentVertex;
|
||||
|
||||
if (!mathHelper.CalculateFacePlane(newFace, Center))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
ConeFaceBuffer.Add(MakeDeferredFace(newFace, orderedPivotIndex, adjacentFace, oldFaceAdjacentIndex,
|
||||
oldFace));
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Commits a cone and adds a vertex to the convex hull.
|
||||
/// </summary>
|
||||
private void CommitCone()
|
||||
{
|
||||
// Fill the adjacency.
|
||||
for (var i = 0; i < ConeFaceBuffer.Count; i++)
|
||||
{
|
||||
var face = ConeFaceBuffer[i];
|
||||
|
||||
var newFace = face.Face;
|
||||
var adjacentFace = face.Pivot;
|
||||
var oldFace = face.OldFace;
|
||||
var orderedPivotIndex = face.FaceIndex;
|
||||
|
||||
newFace.AdjacentFaces[orderedPivotIndex] = adjacentFace.Index;
|
||||
adjacentFace.AdjacentFaces[face.PivotIndex] = newFace.Index;
|
||||
|
||||
// let there be a connection.
|
||||
for (var j = 0; j < NumOfDimensions; j++)
|
||||
{
|
||||
if (j == orderedPivotIndex) continue;
|
||||
var connector = ObjectManager.GetConnector();
|
||||
connector.Update(newFace, j, NumOfDimensions);
|
||||
ConnectFace(connector);
|
||||
}
|
||||
|
||||
// the id adjacent face on the hull? If so, we can use simple method to find beyond vertices.
|
||||
if (adjacentFace.VerticesBeyond.Count == 0)
|
||||
FindBeyondVertices(newFace, oldFace.VerticesBeyond);
|
||||
// it is slightly more effective if the face with the lower number of beyond vertices comes first.
|
||||
else if (adjacentFace.VerticesBeyond.Count < oldFace.VerticesBeyond.Count)
|
||||
FindBeyondVertices(newFace, adjacentFace.VerticesBeyond, oldFace.VerticesBeyond);
|
||||
else
|
||||
FindBeyondVertices(newFace, oldFace.VerticesBeyond, adjacentFace.VerticesBeyond);
|
||||
|
||||
// This face will definitely lie on the hull
|
||||
if (newFace.VerticesBeyond.Count == 0)
|
||||
{
|
||||
ConvexFaces.Add(newFace.Index);
|
||||
UnprocessedFaces.Remove(newFace);
|
||||
ObjectManager.DepositVertexBuffer(newFace.VerticesBeyond);
|
||||
newFace.VerticesBeyond = EmptyBuffer;
|
||||
}
|
||||
else // Add the face to the list
|
||||
{
|
||||
UnprocessedFaces.Add(newFace);
|
||||
}
|
||||
|
||||
// recycle the object.
|
||||
ObjectManager.DepositDeferredFace(face);
|
||||
}
|
||||
|
||||
// Recycle the affected faces.
|
||||
for (var fIndex = 0; fIndex < AffectedFaceBuffer.Count; fIndex++)
|
||||
{
|
||||
var face = AffectedFaceBuffer[fIndex];
|
||||
UnprocessedFaces.Remove(FacePool[face]);
|
||||
ObjectManager.DepositFace(face);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Check whether the vertex v is beyond the given face. If so, add it to beyondVertices.
|
||||
/// </summary>
|
||||
/// <param name="face">The face.</param>
|
||||
/// <param name="beyondVertices">The beyond vertices.</param>
|
||||
/// <param name="v">The v.</param>
|
||||
private void IsBeyond(ConvexFaceInternal face, IndexBuffer beyondVertices, int v)
|
||||
{
|
||||
var distance = mathHelper.GetVertexDistance(v, face);
|
||||
if (distance >= PlaneDistanceTolerance)
|
||||
{
|
||||
if (distance > MaxDistance)
|
||||
{
|
||||
// If it's within the tolerance distance, use the lex. larger point
|
||||
if (distance - MaxDistance < PlaneDistanceTolerance)
|
||||
{ // todo: why is this LexCompare necessary. Would seem to favor x over y over z (etc.)?
|
||||
if (LexCompare(v, FurthestVertex) > 0)
|
||||
{
|
||||
MaxDistance = distance;
|
||||
FurthestVertex = v;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
MaxDistance = distance;
|
||||
FurthestVertex = v;
|
||||
}
|
||||
}
|
||||
beyondVertices.Add(v);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Compares the values of two vertices. The return value (-1, 0 or +1) are found
|
||||
/// by first checking the first coordinate and then progressing through the rest.
|
||||
/// In this way {2, 8} will be a "-1" (less than) {3, 1}.
|
||||
/// </summary>
|
||||
/// <param name="u">The base vertex index, u.</param>
|
||||
/// <param name="v">The compared vertex index, v.</param>
|
||||
/// <returns>System.Int32.</returns>
|
||||
private int LexCompare(int u, int v)
|
||||
{
|
||||
int uOffset = u * NumOfDimensions, vOffset = v * NumOfDimensions;
|
||||
for (var i = 0; i < NumOfDimensions; i++)
|
||||
{
|
||||
double x = Positions[uOffset + i], y = Positions[vOffset + i];
|
||||
var comp = x.CompareTo(y);
|
||||
if (comp != 0) return comp;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Used by update faces.
|
||||
/// </summary>
|
||||
/// <param name="face">The face.</param>
|
||||
/// <param name="beyond">The beyond.</param>
|
||||
/// <param name="beyond1">The beyond1.</param>
|
||||
private void FindBeyondVertices(ConvexFaceInternal face, IndexBuffer beyond, IndexBuffer beyond1)
|
||||
{
|
||||
var beyondVertices = BeyondBuffer;
|
||||
|
||||
MaxDistance = double.NegativeInfinity;
|
||||
FurthestVertex = 0;
|
||||
int v;
|
||||
|
||||
for (var i = 0; i < beyond1.Count; i++) VertexVisited[beyond1[i]] = true;
|
||||
VertexVisited[CurrentVertex] = false;
|
||||
for (var i = 0; i < beyond.Count; i++)
|
||||
{
|
||||
v = beyond[i];
|
||||
if (v == CurrentVertex) continue;
|
||||
VertexVisited[v] = false;
|
||||
IsBeyond(face, beyondVertices, v);
|
||||
}
|
||||
|
||||
for (var i = 0; i < beyond1.Count; i++)
|
||||
{
|
||||
v = beyond1[i];
|
||||
if (VertexVisited[v]) IsBeyond(face, beyondVertices, v);
|
||||
}
|
||||
|
||||
face.FurthestVertex = FurthestVertex;
|
||||
|
||||
// Pull the old switch a roo (switch the face beyond buffers)
|
||||
var temp = face.VerticesBeyond;
|
||||
face.VerticesBeyond = beyondVertices;
|
||||
if (temp.Count > 0) temp.Clear();
|
||||
BeyondBuffer = temp;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the beyond vertices.
|
||||
/// </summary>
|
||||
/// <param name="face">The face.</param>
|
||||
/// <param name="beyond">The beyond.</param>
|
||||
private void FindBeyondVertices(ConvexFaceInternal face, IndexBuffer beyond)
|
||||
{
|
||||
var beyondVertices = BeyondBuffer;
|
||||
|
||||
MaxDistance = double.NegativeInfinity;
|
||||
FurthestVertex = 0;
|
||||
int v;
|
||||
|
||||
for (var i = 0; i < beyond.Count; i++)
|
||||
{
|
||||
v = beyond[i];
|
||||
if (v == CurrentVertex) continue;
|
||||
IsBeyond(face, beyondVertices, v);
|
||||
}
|
||||
|
||||
face.FurthestVertex = FurthestVertex;
|
||||
|
||||
// Pull the old switch a roo (switch the face beyond buffers)
|
||||
var temp = face.VerticesBeyond;
|
||||
face.VerticesBeyond = beyondVertices;
|
||||
if (temp.Count > 0) temp.Clear();
|
||||
BeyondBuffer = temp;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recalculates the centroid of the current hull.
|
||||
/// </summary>
|
||||
private void UpdateCenter()
|
||||
{
|
||||
for (var i = 0; i < NumOfDimensions; i++) Center[i] *= ConvexHullSize;
|
||||
ConvexHullSize += 1;
|
||||
var f = 1.0 / ConvexHullSize;
|
||||
var co = CurrentVertex * NumOfDimensions;
|
||||
for (var i = 0; i < NumOfDimensions; i++) Center[i] = f * (Center[i] + Positions[co + i]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the last vertex from the center.
|
||||
/// </summary>
|
||||
private void RollbackCenter()
|
||||
{
|
||||
for (var i = 0; i < NumOfDimensions; i++) Center[i] *= ConvexHullSize;
|
||||
ConvexHullSize -= 1;
|
||||
var f = ConvexHullSize > 0 ? 1.0 / ConvexHullSize : 0.0;
|
||||
var co = CurrentVertex * NumOfDimensions;
|
||||
for (var i = 0; i < NumOfDimensions; i++) Center[i] = f * (Center[i] - Positions[co + i]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles singular vertex.
|
||||
/// </summary>
|
||||
private void HandleSingular()
|
||||
{
|
||||
RollbackCenter();
|
||||
SingularVertices.Add(CurrentVertex);
|
||||
|
||||
// This means that all the affected faces must be on the hull and that all their "vertices beyond" are singular.
|
||||
for (var fIndex = 0; fIndex < AffectedFaceBuffer.Count; fIndex++)
|
||||
{
|
||||
var face = FacePool[AffectedFaceBuffer[fIndex]];
|
||||
var vb = face.VerticesBeyond;
|
||||
for (var i = 0; i < vb.Count; i++)
|
||||
{
|
||||
SingularVertices.Add(vb[i]);
|
||||
}
|
||||
|
||||
ConvexFaces.Add(face.Index);
|
||||
UnprocessedFaces.Remove(face);
|
||||
ObjectManager.DepositVertexBuffer(face.VerticesBeyond);
|
||||
face.VerticesBeyond = EmptyBuffer;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get a vertex coordinate. In order to reduce speed, all vertex coordinates
|
||||
/// have been placed in a single array.
|
||||
/// </summary>
|
||||
/// <param name="vIndex">The vertex index.</param>
|
||||
/// <param name="dimension">The index of the dimension.</param>
|
||||
/// <returns>System.Double.</returns>
|
||||
private double GetCoordinate(int vIndex, int dimension)
|
||||
{
|
||||
return Positions[vIndex * NumOfDimensions + dimension];
|
||||
}
|
||||
|
||||
#region Returning the Results in the proper format
|
||||
|
||||
/// <summary>
|
||||
/// Gets the hull vertices.
|
||||
/// </summary>
|
||||
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
|
||||
/// <param name="data">The data.</param>
|
||||
/// <returns>TVertex[].</returns>
|
||||
private TVertex[] GetHullVertices<TVertex>(IList<TVertex> data)
|
||||
{
|
||||
var cellCount = ConvexFaces.Count;
|
||||
var hullVertexCount = 0;
|
||||
|
||||
for (var i = 0; i < NumberOfVertices; i++) VertexVisited[i] = false;
|
||||
|
||||
for (var i = 0; i < cellCount; i++)
|
||||
{
|
||||
var vs = FacePool[ConvexFaces[i]].Vertices;
|
||||
for (var j = 0; j < vs.Length; j++)
|
||||
{
|
||||
var v = vs[j];
|
||||
if (!VertexVisited[v])
|
||||
{
|
||||
VertexVisited[v] = true;
|
||||
hullVertexCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var result = new TVertex[hullVertexCount];
|
||||
for (var i = 0; i < NumberOfVertices; i++)
|
||||
{
|
||||
if (VertexVisited[i]) result[--hullVertexCount] = data[i];
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the convex hull and creates the TFace objects.
|
||||
/// </summary>
|
||||
/// <typeparam name="TFace">The type of the t face.</typeparam>
|
||||
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
|
||||
/// <returns>TFace[].</returns>
|
||||
private TFace[] GetConvexFaces<TVertex, TFace>()
|
||||
where TFace : ConvexFace<TVertex, TFace>, new()
|
||||
where TVertex : IVertex
|
||||
{
|
||||
var faces = ConvexFaces;
|
||||
var cellCount = faces.Count;
|
||||
var cells = new TFace[cellCount];
|
||||
|
||||
for (var i = 0; i < cellCount; i++)
|
||||
{
|
||||
var face = FacePool[faces[i]];
|
||||
var vertices = new TVertex[NumOfDimensions];
|
||||
for (var j = 0; j < NumOfDimensions; j++)
|
||||
{
|
||||
vertices[j] = (TVertex)Vertices[face.Vertices[j]];
|
||||
}
|
||||
|
||||
cells[i] = new TFace
|
||||
{
|
||||
Vertices = vertices,
|
||||
Adjacency = new TFace[NumOfDimensions],
|
||||
Normal = IsLifted ? null : face.Normal
|
||||
};
|
||||
face.Tag = i;
|
||||
}
|
||||
|
||||
for (var i = 0; i < cellCount; i++)
|
||||
{
|
||||
var face = FacePool[faces[i]];
|
||||
var cell = cells[i];
|
||||
for (var j = 0; j < NumOfDimensions; j++)
|
||||
{
|
||||
if (face.AdjacentFaces[j] < 0) continue;
|
||||
cell.Adjacency[j] = cells[FacePool[face.AdjacentFaces[j]].Tag];
|
||||
}
|
||||
|
||||
// Fix the vertex orientation.
|
||||
if (face.IsNormalFlipped)
|
||||
{
|
||||
var tempVert = cell.Vertices[0];
|
||||
cell.Vertices[0] = cell.Vertices[NumOfDimensions - 1];
|
||||
cell.Vertices[NumOfDimensions - 1] = tempVert;
|
||||
|
||||
var tempAdj = cell.Adjacency[0];
|
||||
cell.Adjacency[0] = cell.Adjacency[NumOfDimensions - 1];
|
||||
cell.Adjacency[NumOfDimensions - 1] = tempAdj;
|
||||
}
|
||||
}
|
||||
|
||||
return cells;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// For 2D only: Returns the result in counter-clockwise order starting with the element with the lowest X value.
|
||||
/// If there are multiple vertices with the same minimum X, then the one with the lowest Y is chosen.
|
||||
/// </summary>
|
||||
/// <typeparam name="TVertex">The type of the vertex.</typeparam>
|
||||
/// <typeparam name="TFace">The type of the face.</typeparam>
|
||||
/// <param name="data">The data.</param>
|
||||
/// <returns></returns>
|
||||
private ConvexHull<TVertex, TFace> Return2DResultInOrder<TVertex, TFace>(IList<TVertex> data)
|
||||
where TVertex : IVertex
|
||||
where TFace : ConvexFace<TVertex, TFace>, new()
|
||||
{
|
||||
TFace[] faces = GetConvexFaces<TVertex, TFace>();
|
||||
var numPoints = faces.Length;
|
||||
var orderDictionary = new Dictionary<TVertex, TFace>();
|
||||
foreach (var face in faces)
|
||||
orderDictionary.Add(face.Vertices[1], face);
|
||||
var firstPoint = faces[0].Vertices[1];
|
||||
var nextPoint = faces[0].Vertices[0];
|
||||
var orderedPointList = new List<TVertex>();
|
||||
orderedPointList.Add(firstPoint);
|
||||
var orderedFaceList = new List<TFace>();
|
||||
orderedFaceList.Add(faces[1]);
|
||||
var lowestXMinIndex = 0;
|
||||
var k = 0;
|
||||
while (!nextPoint.Equals(firstPoint))
|
||||
{
|
||||
orderedPointList.Add(nextPoint);
|
||||
var nextFace = orderDictionary[nextPoint];
|
||||
orderedFaceList.Add(nextFace);
|
||||
if (nextPoint.Position[0] < orderedPointList[lowestXMinIndex].Position[0]
|
||||
|| (nextPoint.Position[0] == orderedPointList[lowestXMinIndex].Position[0]
|
||||
&& nextPoint.Position[1] <= orderedPointList[lowestXMinIndex].Position[1]))
|
||||
lowestXMinIndex = k;
|
||||
k++;
|
||||
nextPoint = nextFace.Vertices[0];
|
||||
}
|
||||
TVertex[] points = new TVertex[numPoints];
|
||||
for (int i = 0; i < numPoints; i++)
|
||||
{
|
||||
var j = (i + lowestXMinIndex) % numPoints;
|
||||
points[i] = orderedPointList[j];
|
||||
faces[i] = orderedFaceList[j];
|
||||
}
|
||||
return new ConvexHull<TVertex, TFace>
|
||||
{
|
||||
Points = points,
|
||||
Faces = faces
|
||||
};
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: f7f265217d00ea340b87645242a45181
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
237
Assets/Scripts/NIH/MIConvexHull/ConvexHull/DataModel.cs
Normal file
237
Assets/Scripts/NIH/MIConvexHull/ConvexHull/DataModel.cs
Normal file
|
|
@ -0,0 +1,237 @@
|
|||
/******************************************************************************
|
||||
*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*
|
||||
*****************************************************************************/
|
||||
|
||||
namespace MIConvexHull
|
||||
{
|
||||
/// <summary>
|
||||
/// For deferred face addition.
|
||||
/// </summary>
|
||||
internal sealed class DeferredFace
|
||||
{
|
||||
/// <summary>
|
||||
/// The faces.
|
||||
/// </summary>
|
||||
public ConvexFaceInternal Face, Pivot, OldFace;
|
||||
|
||||
/// <summary>
|
||||
/// The indices.
|
||||
/// </summary>
|
||||
public int FaceIndex, PivotIndex;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A helper class used to connect faces.
|
||||
/// </summary>
|
||||
internal sealed class FaceConnector
|
||||
{
|
||||
/// <summary>
|
||||
/// The edge to be connected.
|
||||
/// </summary>
|
||||
public int EdgeIndex;
|
||||
|
||||
/// <summary>
|
||||
/// The face.
|
||||
/// </summary>
|
||||
public ConvexFaceInternal Face;
|
||||
|
||||
/// <summary>
|
||||
/// The hash code computed from indices.
|
||||
/// </summary>
|
||||
public uint HashCode;
|
||||
|
||||
/// <summary>
|
||||
/// Next node in the list.
|
||||
/// </summary>
|
||||
public FaceConnector Next;
|
||||
|
||||
/// <summary>
|
||||
/// Prev node in the list.
|
||||
/// </summary>
|
||||
public FaceConnector Previous;
|
||||
|
||||
/// <summary>
|
||||
/// The vertex indices.
|
||||
/// </summary>
|
||||
public int[] Vertices;
|
||||
|
||||
/// <summary>
|
||||
/// Ctor.
|
||||
/// </summary>
|
||||
/// <param name="dimension">The dimension.</param>
|
||||
public FaceConnector(int dimension)
|
||||
{
|
||||
Vertices = new int[dimension - 1];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the connector.
|
||||
/// </summary>
|
||||
/// <param name="face">The face.</param>
|
||||
/// <param name="edgeIndex">Index of the edge.</param>
|
||||
/// <param name="dim">The dim.</param>
|
||||
public void Update(ConvexFaceInternal face, int edgeIndex, int dim)
|
||||
{
|
||||
Face = face;
|
||||
EdgeIndex = edgeIndex;
|
||||
|
||||
uint hashCode = 23;
|
||||
|
||||
unchecked
|
||||
{
|
||||
var vs = face.Vertices;
|
||||
int i, c = 0;
|
||||
for (i = 0; i < edgeIndex; i++)
|
||||
{
|
||||
Vertices[c++] = vs[i];
|
||||
hashCode += 31*hashCode + (uint) vs[i];
|
||||
}
|
||||
for (i = edgeIndex + 1; i < vs.Length; i++)
|
||||
{
|
||||
Vertices[c++] = vs[i];
|
||||
hashCode += 31*hashCode + (uint) vs[i];
|
||||
}
|
||||
}
|
||||
|
||||
HashCode = hashCode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Can two faces be connected.
|
||||
/// </summary>
|
||||
/// <param name="a">a.</param>
|
||||
/// <param name="b">The b.</param>
|
||||
/// <param name="dim">The dim.</param>
|
||||
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
|
||||
public static bool AreConnectable(FaceConnector a, FaceConnector b, int dim)
|
||||
{
|
||||
if (a.HashCode != b.HashCode) return false;
|
||||
|
||||
var av = a.Vertices;
|
||||
var bv = b.Vertices;
|
||||
for (var i = 0; i < av.Length; i++)
|
||||
{
|
||||
if (av[i] != bv[i]) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Connect two faces.
|
||||
/// </summary>
|
||||
/// <param name="a">a.</param>
|
||||
/// <param name="b">The b.</param>
|
||||
public static void Connect(FaceConnector a, FaceConnector b)
|
||||
{
|
||||
a.Face.AdjacentFaces[a.EdgeIndex] = b.Face.Index;
|
||||
b.Face.AdjacentFaces[b.EdgeIndex] = a.Face.Index;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This internal class manages the faces of the convex hull. It is a
|
||||
/// separate class from the desired user class.
|
||||
/// </summary>
|
||||
internal sealed class ConvexFaceInternal
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the adjacent face data.
|
||||
/// </summary>
|
||||
public int[] AdjacentFaces;
|
||||
|
||||
/// <summary>
|
||||
/// The furthest vertex.
|
||||
/// </summary>
|
||||
public int FurthestVertex;
|
||||
|
||||
/// <summary>
|
||||
/// Index of the face inside the pool.
|
||||
/// </summary>
|
||||
public int Index;
|
||||
|
||||
/// <summary>
|
||||
/// Is it present in the list.
|
||||
/// </summary>
|
||||
public bool InList;
|
||||
|
||||
/// <summary>
|
||||
/// Is the normal flipped?
|
||||
/// </summary>
|
||||
public bool IsNormalFlipped;
|
||||
|
||||
/// <summary>
|
||||
/// Next node in the list.
|
||||
/// </summary>
|
||||
public ConvexFaceInternal Next;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the normal vector.
|
||||
/// </summary>
|
||||
public double[] Normal;
|
||||
|
||||
/// <summary>
|
||||
/// Face plane constant element.
|
||||
/// </summary>
|
||||
public double Offset;
|
||||
|
||||
//public int UnprocessedIndex;
|
||||
|
||||
/// <summary>
|
||||
/// Prev node in the list.
|
||||
/// </summary>
|
||||
public ConvexFaceInternal Previous;
|
||||
|
||||
/// <summary>
|
||||
/// Used to traverse affected faces and create the Delaunay representation.
|
||||
/// </summary>
|
||||
public int Tag;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the vertices.
|
||||
/// </summary>
|
||||
public int[] Vertices;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the vertices beyond.
|
||||
/// </summary>
|
||||
public IndexBuffer VerticesBeyond;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ConvexFaceInternal" /> class.
|
||||
/// </summary>
|
||||
/// <param name="dimension">The dimension.</param>
|
||||
/// <param name="index">The index.</param>
|
||||
/// <param name="beyondList">The beyond list.</param>
|
||||
public ConvexFaceInternal(int dimension, int index, IndexBuffer beyondList)
|
||||
{
|
||||
Index = index;
|
||||
AdjacentFaces = new int[dimension];
|
||||
VerticesBeyond = beyondList;
|
||||
Normal = new double[dimension];
|
||||
Vertices = new int[dimension];
|
||||
}
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/NIH/MIConvexHull/ConvexHull/DataModel.cs.meta
Normal file
11
Assets/Scripts/NIH/MIConvexHull/ConvexHull/DataModel.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 58c58e163f4c86e48a6df3ee6c5056c0
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
476
Assets/Scripts/NIH/MIConvexHull/ConvexHull/MathHelper.cs
Normal file
476
Assets/Scripts/NIH/MIConvexHull/ConvexHull/MathHelper.cs
Normal file
|
|
@ -0,0 +1,476 @@
|
|||
/******************************************************************************
|
||||
*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*
|
||||
*****************************************************************************/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace MIConvexHull
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper class mostly for normal computation. If convex hulls are computed
|
||||
/// in higher dimensions, it might be a good idea to add a specific
|
||||
/// FindNormalVectorND function.
|
||||
/// </summary>
|
||||
internal class MathHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// The dimension
|
||||
/// </summary>
|
||||
private readonly int Dimension;
|
||||
/// <summary>
|
||||
/// The matrix pivots
|
||||
/// </summary>
|
||||
private readonly int[] matrixPivots;
|
||||
/// <summary>
|
||||
/// The n d matrix
|
||||
/// </summary>
|
||||
private readonly double[] nDMatrix;
|
||||
/// <summary>
|
||||
/// The n d normal helper vector
|
||||
/// </summary>
|
||||
private readonly double[] nDNormalHelperVector;
|
||||
|
||||
/// <summary>
|
||||
/// The nt x
|
||||
/// </summary>
|
||||
private readonly double[] ntX;
|
||||
/// <summary>
|
||||
/// The nt y
|
||||
/// </summary>
|
||||
private readonly double[] ntY;
|
||||
/// <summary>
|
||||
/// The nt z
|
||||
/// </summary>
|
||||
private readonly double[] ntZ;
|
||||
|
||||
/// <summary>
|
||||
/// The position data
|
||||
/// </summary>
|
||||
private readonly double[] PositionData;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MathHelper"/> class.
|
||||
/// </summary>
|
||||
/// <param name="dimension">The dimension.</param>
|
||||
/// <param name="positions">The positions.</param>
|
||||
internal MathHelper(int dimension, double[] positions)
|
||||
{
|
||||
PositionData = positions;
|
||||
Dimension = dimension;
|
||||
|
||||
ntX = new double[Dimension];
|
||||
ntY = new double[Dimension];
|
||||
ntZ = new double[Dimension];
|
||||
|
||||
nDNormalHelperVector = new double[Dimension];
|
||||
nDMatrix = new double[Dimension * Dimension];
|
||||
matrixPivots = new int[Dimension];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates the normal and offset of the hyper-plane given by the face's vertices.
|
||||
/// </summary>
|
||||
/// <param name="face">The face.</param>
|
||||
/// <param name="center">The center.</param>
|
||||
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
|
||||
internal bool CalculateFacePlane(ConvexFaceInternal face, double[] center)
|
||||
{
|
||||
var vertices = face.Vertices;
|
||||
var normal = face.Normal;
|
||||
FindNormalVector(vertices, normal);
|
||||
|
||||
if (double.IsNaN(normal[0]))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var offset = 0.0;
|
||||
var centerDistance = 0.0;
|
||||
var fi = vertices[0] * Dimension;
|
||||
for (var i = 0; i < Dimension; i++)
|
||||
{
|
||||
var n = normal[i];
|
||||
offset += n * PositionData[fi + i];
|
||||
centerDistance += n * center[i];
|
||||
}
|
||||
face.Offset = -offset;
|
||||
centerDistance -= offset;
|
||||
|
||||
if (centerDistance > 0)
|
||||
{
|
||||
for (var i = 0; i < Dimension; i++) normal[i] = -normal[i];
|
||||
face.Offset = offset;
|
||||
face.IsNormalFlipped = true;
|
||||
}
|
||||
else face.IsNormalFlipped = false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Check if the vertex is "visible" from the face.
|
||||
/// The vertex is "over face" if the return value is > Constants.PlaneDistanceTolerance.
|
||||
/// </summary>
|
||||
/// <param name="v">The v.</param>
|
||||
/// <param name="f">The f.</param>
|
||||
/// <returns>The vertex is "over face" if the result is positive.</returns>
|
||||
internal double GetVertexDistance(int v, ConvexFaceInternal f)
|
||||
{
|
||||
var normal = f.Normal;
|
||||
var x = v * Dimension;
|
||||
var distance = f.Offset;
|
||||
for (var i = 0; i < normal.Length; i++) distance += normal[i] * PositionData[x + i];
|
||||
return distance;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the vector the between vertices.
|
||||
/// </summary>
|
||||
/// <param name="toIndex">To index.</param>
|
||||
/// <param name="fromIndex">From index.</param>
|
||||
/// <returns>System.Double[].</returns>
|
||||
internal double[] VectorBetweenVertices(int toIndex, int fromIndex)
|
||||
{
|
||||
var target = new double[Dimension];
|
||||
VectorBetweenVertices(toIndex, fromIndex, target);
|
||||
return target;
|
||||
}
|
||||
/// <summary>
|
||||
/// Returns the vector the between vertices.
|
||||
/// </summary>
|
||||
/// <param name="fromIndex">From index.</param>
|
||||
/// <param name="toIndex">To index.</param>
|
||||
/// <param name="target">The target.</param>
|
||||
/// <returns></returns>
|
||||
private void VectorBetweenVertices(int toIndex, int fromIndex, double[] target)
|
||||
{
|
||||
int u = toIndex * Dimension, v = fromIndex * Dimension;
|
||||
for (var i = 0; i < Dimension; i++)
|
||||
{
|
||||
target[i] = PositionData[u + i] - PositionData[v + i];
|
||||
}
|
||||
}
|
||||
|
||||
internal void RandomOffsetToLift(int index, double maxHeight)
|
||||
{
|
||||
var random = new Random();
|
||||
var liftIndex = (index * Dimension) + Dimension - 1;
|
||||
PositionData[liftIndex] += 0.0001 * maxHeight * (random.NextDouble() - 0.5);
|
||||
}
|
||||
#region Find the normal vector of the face
|
||||
/// <summary>
|
||||
/// Finds normal vector of a hyper-plane given by vertices.
|
||||
/// Stores the results to normalData.
|
||||
/// </summary>
|
||||
/// <param name="vertices">The vertices.</param>
|
||||
/// <param name="normalData">The normal data.</param>
|
||||
private void FindNormalVector(int[] vertices, double[] normalData)
|
||||
{
|
||||
switch (Dimension)
|
||||
{
|
||||
case 2:
|
||||
FindNormalVector2D(vertices, normalData);
|
||||
break;
|
||||
case 3:
|
||||
FindNormalVector3D(vertices, normalData);
|
||||
break;
|
||||
case 4:
|
||||
FindNormalVector4D(vertices, normalData);
|
||||
break;
|
||||
default:
|
||||
FindNormalVectorND(vertices, normalData);
|
||||
break;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Finds 2D normal vector.
|
||||
/// </summary>
|
||||
/// <param name="vertices">The vertices.</param>
|
||||
/// <param name="normal">The normal.</param>
|
||||
private void FindNormalVector2D(int[] vertices, double[] normal)
|
||||
{
|
||||
VectorBetweenVertices(vertices[1], vertices[0], ntX);
|
||||
|
||||
var nx = -ntX[1];
|
||||
var ny = ntX[0];
|
||||
|
||||
var norm = Math.Sqrt(nx * nx + ny * ny);
|
||||
|
||||
var f = 1.0 / norm;
|
||||
normal[0] = f * nx;
|
||||
normal[1] = f * ny;
|
||||
}
|
||||
/// <summary>
|
||||
/// Finds 3D normal vector.
|
||||
/// </summary>
|
||||
/// <param name="vertices">The vertices.</param>
|
||||
/// <param name="normal">The normal.</param>
|
||||
private void FindNormalVector3D(int[] vertices, double[] normal)
|
||||
{
|
||||
VectorBetweenVertices(vertices[1], vertices[0], ntX);
|
||||
VectorBetweenVertices(vertices[2], vertices[1], ntY);
|
||||
|
||||
var nx = ntX[1] * ntY[2] - ntX[2] * ntY[1];
|
||||
var ny = ntX[2] * ntY[0] - ntX[0] * ntY[2];
|
||||
var nz = ntX[0] * ntY[1] - ntX[1] * ntY[0];
|
||||
|
||||
var norm = Math.Sqrt(nx * nx + ny * ny + nz * nz);
|
||||
|
||||
var f = 1.0 / norm;
|
||||
normal[0] = f * nx;
|
||||
normal[1] = f * ny;
|
||||
normal[2] = f * nz;
|
||||
}
|
||||
/// <summary>
|
||||
/// Finds 4D normal vector.
|
||||
/// </summary>
|
||||
/// <param name="vertices">The vertices.</param>
|
||||
/// <param name="normal">The normal.</param>
|
||||
private void FindNormalVector4D(int[] vertices, double[] normal)
|
||||
{
|
||||
VectorBetweenVertices(vertices[1], vertices[0], ntX);
|
||||
VectorBetweenVertices(vertices[2], vertices[1], ntY);
|
||||
VectorBetweenVertices(vertices[3], vertices[2], ntZ);
|
||||
|
||||
var x = ntX;
|
||||
var y = ntY;
|
||||
var z = ntZ;
|
||||
|
||||
// This was generated using Mathematica
|
||||
var nx = x[3] * (y[2] * z[1] - y[1] * z[2])
|
||||
+ x[2] * (y[1] * z[3] - y[3] * z[1])
|
||||
+ x[1] * (y[3] * z[2] - y[2] * z[3]);
|
||||
var ny = x[3] * (y[0] * z[2] - y[2] * z[0])
|
||||
+ x[2] * (y[3] * z[0] - y[0] * z[3])
|
||||
+ x[0] * (y[2] * z[3] - y[3] * z[2]);
|
||||
var nz = x[3] * (y[1] * z[0] - y[0] * z[1])
|
||||
+ x[1] * (y[0] * z[3] - y[3] * z[0])
|
||||
+ x[0] * (y[3] * z[1] - y[1] * z[3]);
|
||||
var nw = x[2] * (y[0] * z[1] - y[1] * z[0])
|
||||
+ x[1] * (y[2] * z[0] - y[0] * z[2])
|
||||
+ x[0] * (y[1] * z[2] - y[2] * z[1]);
|
||||
|
||||
var norm = Math.Sqrt(nx * nx + ny * ny + nz * nz + nw * nw);
|
||||
|
||||
var f = 1.0 / norm;
|
||||
normal[0] = f * nx;
|
||||
normal[1] = f * ny;
|
||||
normal[2] = f * nz;
|
||||
normal[3] = f * nw;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the normal vector nd.
|
||||
/// </summary>
|
||||
/// <param name="vertices">The vertices.</param>
|
||||
/// <param name="normal">The normal.</param>
|
||||
private void FindNormalVectorND(int[] vertices, double[] normal)
|
||||
{
|
||||
/* We need to solve the matrix A n = B where
|
||||
* - A contains coordinates of vertices as columns
|
||||
* - B is vector with all 1's. Really, it should be the distance of
|
||||
* the plane from the origin, but - since we're not worried about that
|
||||
* here and we will normalize the normal anyway - all 1's suffices.
|
||||
*/
|
||||
var iPiv = matrixPivots;
|
||||
var data = nDMatrix;
|
||||
var norm = 0.0;
|
||||
|
||||
// Solve determinants by replacing x-th column by all 1.
|
||||
for (var x = 0; x < Dimension; x++)
|
||||
{
|
||||
for (var i = 0; i < Dimension; i++)
|
||||
{
|
||||
var offset = vertices[i] * Dimension;
|
||||
for (var j = 0; j < Dimension; j++)
|
||||
{
|
||||
// maybe I got the i/j mixed up here regarding the representation Math.net uses...
|
||||
// ...but it does not matter since Det(A) = Det(Transpose(A)).
|
||||
data[Dimension * i + j] = j == x ? 1.0 : PositionData[offset + j];
|
||||
}
|
||||
}
|
||||
LUFactor(data, Dimension, iPiv, nDNormalHelperVector);
|
||||
var coord = 1.0;
|
||||
for (var i = 0; i < Dimension; i++)
|
||||
{
|
||||
if (iPiv[i] != i) coord *= -data[Dimension * i + i]; // the determinant sign changes on row swap.
|
||||
else coord *= data[Dimension * i + i];
|
||||
}
|
||||
normal[x] = coord;
|
||||
norm += coord * coord;
|
||||
}
|
||||
|
||||
// Normalize the result
|
||||
var f = 1.0 / Math.Sqrt(norm);
|
||||
for (var i = 0; i < normal.Length; i++) normal[i] *= f;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Simplex Volume
|
||||
/// <summary>
|
||||
/// Gets the simplex volume. Prior to having enough edge vectors, the method pads the remaining with all
|
||||
/// "other numbers". So, yes, this method is not really finding the volume. But a relative volume-like measure. It
|
||||
/// uses the magnitude of the determinant as the volume stand-in following the Cayley-Menger theorem.
|
||||
/// </summary>
|
||||
/// <param name="edgeVectors">The edge vectors.</param>
|
||||
/// <param name="lastIndex">The last index.</param>
|
||||
/// <param name="bigNumber">The big number.</param>
|
||||
/// <returns>System.Double.</returns>
|
||||
internal double GetSimplexVolume(double[][] edgeVectors, int lastIndex, double bigNumber)
|
||||
{
|
||||
var A = new double[Dimension * Dimension];
|
||||
var index = 0;
|
||||
for (int i = 0; i < Dimension; i++)
|
||||
for (int j = 0; j < Dimension; j++)
|
||||
if (i <= lastIndex)
|
||||
A[index++] = edgeVectors[i][j];
|
||||
else A[index] = (Math.Pow(-1, index) * index++) / bigNumber;
|
||||
// this last term is used for all the vertices in the comparison for the yet determined vertices
|
||||
// the idea is to come up with sets of numbers that are orthogonal so that an non-zero value will result
|
||||
// and to choose smallish numbers since the choice of vectors will affect what the end volume is.
|
||||
// A better way (todo?) is to solve a smaller matrix. However, cases were found in which the obvious smaller vector
|
||||
// (the upper left) had too many zeros. So, one would need to find the right subset. Indeed choosing a subset
|
||||
// biases the first dimensions of the others. Perhaps a larger volume would be created from a different vertex
|
||||
// if another subset of dimensions were used.
|
||||
return Math.Abs(DeterminantDestructive(A));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determinants the destructive.
|
||||
/// </summary>
|
||||
/// <param name="A">a.</param>
|
||||
/// <returns>System.Double.</returns>
|
||||
private double DeterminantDestructive(double[] A)
|
||||
{
|
||||
switch (Dimension)
|
||||
{
|
||||
case 0:
|
||||
return 0.0;
|
||||
case 1:
|
||||
return A[0];
|
||||
case 2:
|
||||
return A[0] * A[3] - A[1] * A[2];
|
||||
case 3:
|
||||
return A[0] * A[4] * A[8] + A[1] * A[5] * A[6] + A[2] * A[3] * A[7]
|
||||
- A[0] * A[5] * A[7] - A[1] * A[3] * A[8] - A[2] * A[4] * A[6];
|
||||
default:
|
||||
{
|
||||
var iPiv = new int[Dimension];
|
||||
var helper = new double[Dimension];
|
||||
LUFactor(A, Dimension, iPiv, helper);
|
||||
var det = 1.0;
|
||||
for (var i = 0; i < iPiv.Length; i++)
|
||||
{
|
||||
det *= A[Dimension * i + i];
|
||||
if (iPiv[i] != i) det *= -1; // the determinant sign changes on row swap.
|
||||
}
|
||||
return det;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
// Modified from Math.NET
|
||||
// Copyright (c) 2009-2013 Math.NET
|
||||
/// <summary>
|
||||
/// Lus the factor.
|
||||
/// </summary>
|
||||
/// <param name="data">The data.</param>
|
||||
/// <param name="order">The order.</param>
|
||||
/// <param name="ipiv">The ipiv.</param>
|
||||
/// <param name="vecLUcolj">The vec l ucolj.</param>
|
||||
private static void LUFactor(double[] data, int order, int[] ipiv, double[] vecLUcolj)
|
||||
{
|
||||
// Initialize the pivot matrix to the identity permutation.
|
||||
for (var i = 0; i < order; i++)
|
||||
{
|
||||
ipiv[i] = i;
|
||||
}
|
||||
|
||||
// Outer loop.
|
||||
for (var j = 0; j < order; j++)
|
||||
{
|
||||
var indexj = j * order;
|
||||
var indexjj = indexj + j;
|
||||
|
||||
// Make a copy of the j-th column to localize references.
|
||||
for (var i = 0; i < order; i++)
|
||||
{
|
||||
vecLUcolj[i] = data[indexj + i];
|
||||
}
|
||||
|
||||
// Apply previous transformations.
|
||||
for (var i = 0; i < order; i++)
|
||||
{
|
||||
// Most of the time is spent in the following dot product.
|
||||
var kmax = Math.Min(i, j);
|
||||
var s = 0.0;
|
||||
for (var k = 0; k < kmax; k++)
|
||||
{
|
||||
s += data[k * order + i] * vecLUcolj[k];
|
||||
}
|
||||
|
||||
data[indexj + i] = vecLUcolj[i] -= s;
|
||||
}
|
||||
|
||||
// Find pivot and exchange if necessary.
|
||||
var p = j;
|
||||
for (var i = j + 1; i < order; i++)
|
||||
{
|
||||
if (Math.Abs(vecLUcolj[i]) > Math.Abs(vecLUcolj[p]))
|
||||
{
|
||||
p = i;
|
||||
}
|
||||
}
|
||||
|
||||
if (p != j)
|
||||
{
|
||||
for (var k = 0; k < order; k++)
|
||||
{
|
||||
var indexk = k * order;
|
||||
var indexkp = indexk + p;
|
||||
var indexkj = indexk + j;
|
||||
var temp = data[indexkp];
|
||||
data[indexkp] = data[indexkj];
|
||||
data[indexkj] = temp;
|
||||
}
|
||||
|
||||
ipiv[j] = p;
|
||||
}
|
||||
|
||||
// Compute multipliers.
|
||||
if (j < order & data[indexjj] != 0.0)
|
||||
{
|
||||
for (var i = j + 1; i < order; i++)
|
||||
{
|
||||
data[indexj + i] /= data[indexjj];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 8bb3327041efa18479319ec117493f8c
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
218
Assets/Scripts/NIH/MIConvexHull/ConvexHull/ObjectManager.cs
Normal file
218
Assets/Scripts/NIH/MIConvexHull/ConvexHull/ObjectManager.cs
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
/******************************************************************************
|
||||
*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*
|
||||
*****************************************************************************/
|
||||
|
||||
using System;
|
||||
|
||||
namespace MIConvexHull
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper class for object allocation/storage.
|
||||
/// This helps the GC a lot as it prevents the creation of about 75% of
|
||||
/// new face objects (in the case of ConvexFaceInternal). In the case of
|
||||
/// FaceConnectors and DefferedFaces, the difference is even higher (in most
|
||||
/// cases O(1) vs O(number of created faces)).
|
||||
/// </summary>
|
||||
internal class ObjectManager
|
||||
{
|
||||
/// <summary>
|
||||
/// The dimension
|
||||
/// </summary>
|
||||
private readonly int Dimension;
|
||||
/// <summary>
|
||||
/// The connector stack
|
||||
/// </summary>
|
||||
private FaceConnector ConnectorStack;
|
||||
/// <summary>
|
||||
/// The deferred face stack
|
||||
/// </summary>
|
||||
private readonly SimpleList<DeferredFace> DeferredFaceStack;
|
||||
/// <summary>
|
||||
/// The empty buffer stack
|
||||
/// </summary>
|
||||
private readonly SimpleList<IndexBuffer> EmptyBufferStack;
|
||||
/// <summary>
|
||||
/// The face pool
|
||||
/// </summary>
|
||||
private ConvexFaceInternal[] FacePool;
|
||||
/// <summary>
|
||||
/// The face pool size
|
||||
/// </summary>
|
||||
private int FacePoolSize;
|
||||
/// <summary>
|
||||
/// The face pool capacity
|
||||
/// </summary>
|
||||
private int FacePoolCapacity;
|
||||
/// <summary>
|
||||
/// The free face indices
|
||||
/// </summary>
|
||||
private readonly IndexBuffer FreeFaceIndices;
|
||||
|
||||
/// <summary>
|
||||
/// The hull
|
||||
/// </summary>
|
||||
private readonly ConvexHullAlgorithm Hull;
|
||||
|
||||
/// <summary>
|
||||
/// Create the manager.
|
||||
/// </summary>
|
||||
/// <param name="hull">The hull.</param>
|
||||
public ObjectManager(ConvexHullAlgorithm hull)
|
||||
{
|
||||
Dimension = hull.NumOfDimensions;
|
||||
Hull = hull;
|
||||
FacePool = hull.FacePool;
|
||||
FacePoolSize = 0;
|
||||
FacePoolCapacity = hull.FacePool.Length;
|
||||
FreeFaceIndices = new IndexBuffer();
|
||||
|
||||
EmptyBufferStack = new SimpleList<IndexBuffer>();
|
||||
DeferredFaceStack = new SimpleList<DeferredFace>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Return the face to the pool for later use.
|
||||
/// </summary>
|
||||
/// <param name="faceIndex">Index of the face.</param>
|
||||
public void DepositFace(int faceIndex)
|
||||
{
|
||||
var face = FacePool[faceIndex];
|
||||
var af = face.AdjacentFaces;
|
||||
for (var i = 0; i < af.Length; i++)
|
||||
{
|
||||
af[i] = -1;
|
||||
}
|
||||
FreeFaceIndices.Push(faceIndex);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reallocate the face pool, including the AffectedFaceFlags
|
||||
/// </summary>
|
||||
private void ReallocateFacePool()
|
||||
{
|
||||
var newPool = new ConvexFaceInternal[2*FacePoolCapacity];
|
||||
var newTags = new bool[2*FacePoolCapacity];
|
||||
Array.Copy(FacePool, newPool, FacePoolCapacity);
|
||||
Buffer.BlockCopy(Hull.AffectedFaceFlags, 0, newTags, 0, FacePoolCapacity*sizeof (bool));
|
||||
FacePoolCapacity = 2*FacePoolCapacity;
|
||||
Hull.FacePool = newPool;
|
||||
FacePool = newPool;
|
||||
Hull.AffectedFaceFlags = newTags;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a new face and put it in the pool.
|
||||
/// </summary>
|
||||
/// <returns>System.Int32.</returns>
|
||||
private int CreateFace()
|
||||
{
|
||||
var index = FacePoolSize;
|
||||
var face = new ConvexFaceInternal(Dimension, index, GetVertexBuffer());
|
||||
FacePoolSize++;
|
||||
if (FacePoolSize > FacePoolCapacity) ReallocateFacePool();
|
||||
FacePool[index] = face;
|
||||
return index;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Return index of an unused face or creates a new one.
|
||||
/// </summary>
|
||||
/// <returns>System.Int32.</returns>
|
||||
public int GetFace()
|
||||
{
|
||||
if (FreeFaceIndices.Count > 0) return FreeFaceIndices.Pop();
|
||||
return CreateFace();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Store a face connector in the "embedded" linked list.
|
||||
/// </summary>
|
||||
/// <param name="connector">The connector.</param>
|
||||
public void DepositConnector(FaceConnector connector)
|
||||
{
|
||||
if (ConnectorStack == null)
|
||||
{
|
||||
connector.Next = null;
|
||||
ConnectorStack = connector;
|
||||
}
|
||||
else
|
||||
{
|
||||
connector.Next = ConnectorStack;
|
||||
ConnectorStack = connector;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get an unused face connector. If none is available, create it.
|
||||
/// </summary>
|
||||
/// <returns>FaceConnector.</returns>
|
||||
public FaceConnector GetConnector()
|
||||
{
|
||||
if (ConnectorStack == null) return new FaceConnector(Dimension);
|
||||
|
||||
var ret = ConnectorStack;
|
||||
ConnectorStack = ConnectorStack.Next;
|
||||
ret.Next = null;
|
||||
return ret;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deposit the index buffer.
|
||||
/// </summary>
|
||||
/// <param name="buffer">The buffer.</param>
|
||||
public void DepositVertexBuffer(IndexBuffer buffer)
|
||||
{
|
||||
buffer.Clear();
|
||||
EmptyBufferStack.Push(buffer);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get a store index buffer or create a new instance.
|
||||
/// </summary>
|
||||
/// <returns>IndexBuffer.</returns>
|
||||
public IndexBuffer GetVertexBuffer()
|
||||
{
|
||||
return EmptyBufferStack.Count != 0 ? EmptyBufferStack.Pop() : new IndexBuffer();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deposit the deferred face.
|
||||
/// </summary>
|
||||
/// <param name="face">The face.</param>
|
||||
public void DepositDeferredFace(DeferredFace face)
|
||||
{
|
||||
DeferredFaceStack.Push(face);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get the deferred face.
|
||||
/// </summary>
|
||||
/// <returns>DeferredFace.</returns>
|
||||
public DeferredFace GetDeferredFace()
|
||||
{
|
||||
return DeferredFaceStack.Count != 0 ? DeferredFaceStack.Pop() : new DeferredFace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: e8d582e97c6824740ba9e1a41641b372
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
9
Assets/Scripts/NIH/MIConvexHull/Face3.cs
Normal file
9
Assets/Scripts/NIH/MIConvexHull/Face3.cs
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using MIConvexHull;
|
||||
|
||||
public class Face3 : ConvexFace<Vertex3, Face3>
|
||||
{
|
||||
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue