Here are the examples of the csharp api float.IsNaN(float) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
923 Examples
19
Source : RandomHelper.cs
with MIT License
from 1996v
with MIT License
from 1996v
public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
{
if (t.IsPrimitive)
{
if (t == typeof(byte))
{
return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
}
if (t == typeof(sbyte))
{
return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
}
if (t == typeof(short))
{
return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
}
if (t == typeof(ushort))
{
return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
}
if (t == typeof(int))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}
if (t == typeof(uint))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
return BitConverter.ToUInt32(bytes, 0);
}
if (t == typeof(long))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
return BitConverter.ToInt64(bytes, 0);
}
if (t == typeof(ulong))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
return BitConverter.ToUInt64(bytes, 0);
}
if (t == typeof(float))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
var f = BitConverter.ToSingle(bytes, 0);
if (float.IsNaN(f))
f = (float)RandomValue<short>();
return f;
}
if (t == typeof(double))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
var d = BitConverter.ToDouble(bytes, 0);
if (double.IsNaN(d))
d = (double)RandomValue<short>();
return d;
}
if (t == typeof(char))
{
var roll = Rand.Next(ASCII.Length);
return ASCII[roll];
}
if (t == typeof(bool))
{
return (Rand.Next(2) == 1);
}
throw new InvalidOperationException();
}
if (t == typeof(decimal))
{
return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
}
if (t == typeof(string))
{
int start = stringValueAllowEmpty ? 0 : 1;
var len = Rand.Next(start, 28);
var c = new char[len];
for (var i = 0; i < c.Length; i++)
{
c[i] = (char)typeof(char).RandomValue();
}
return new string(c);
}
if (t == typeof(DateTime))
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var bytes = new byte[4];
Rand.NextBytes(bytes);
var secsOffset = BitConverter.ToInt32(bytes, 0);
var retDate = epoch.AddSeconds(secsOffset);
return retDate;
}
if (t == typeof(TimeSpan))
{
return new TimeSpan(RandomValue<DateTime>().Ticks);
}
if (t == typeof(DataTable))
{
DataTable dt = new DataTable();
int coluCount = Rand.Next(10, 30);
for (int i = 0; i < coluCount; i++)
{
dt.Columns.Add(RandomHelper.RandomValue<string>(false), typeof(object));
}
int rowCount = Rand.Next(20, 50);
for (int i = 0; i < rowCount; i++)
{
var row = new object[coluCount];
for (int zi = 0; zi < coluCount; zi++)
{
row[zi] = RandomHelper.RandomValue<object>();
}
dt.Rows.Add(row);
}
return dt;
}
if (t.IsNullable())
{
// leave it unset
if (Rand.Next(2) == 0)
{
// null!
return Activator.CreateInstance(t);
}
var underlying = Nullable.GetUnderlyingType(t);
var val = underlying.RandomValue(stringValueAllowEmpty);
var cons = t.GetConstructor(new[] { underlying });
return cons.Invoke(new object[] { val });
}
if (t.IsEnum)
{
var allValues = Enum.GetValues(t);
var ix = Rand.Next(allValues.Length);
return allValues.GetValue(ix);
}
if (t.IsArray)
{
var valType = t.GetElementType();
var len = Rand.Next(20, 50);
var ret = Array.CreateInstance(valType, len);
//var add = t.GetMethod("SetValue");
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
ret.SetValue(elem, i);
}
return ret;
}
if (t.IsGenericType)
{
var defind = t.GetGenericTypeDefinition();
if (defind == typeof(HashSet<>))
{
var valType = t.GetGenericArguments()[0];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var contains = t.GetMethod("Contains");
var len = Rand.Next(20, 50);
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
elem = valType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { elem });
}
return ret;
}
if (defind == typeof(Dictionary<,>))
{
var keyType = t.GetGenericArguments()[0];
var valType = t.GetGenericArguments()[1];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var contains = t.GetMethod("ContainsKey");
var len = Rand.Next(20, 50);
if (keyType == typeof(Boolean))
len = 2;
for (var i = 0; i < len; i++)
{
var val = valType.RandomValue(stringValueAllowEmpty);
var key = keyType.RandomValue(stringValueAllowEmpty);
while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
key = keyType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { key, val });
}
return ret;
}
if (defind == typeof(List<>))
{
var valType = t.GetGenericArguments()[0];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var len = Rand.Next(20, 50);
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { elem });
}
return ret;
}
if (defind == typeof(ArraySegment<>))
{
var valType = t.GetGenericArguments()[0];
var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
var lenT = ary.GetType().GetProperty("Length");
var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
var len = (int)lenT.GetValue(ary) - offset;
return Activator.CreateInstance(t, ary, offset, len);
}
}
if (t == typeof(Guid))
return Guid.NewGuid();
if (t == typeof(object))
{
var code = Rand.Next(0, 9);
switch (code)
{
case 0:
return RandomValue<int>();
case 1:
return RandomValue<long>();
case 2:
return RandomValue<Char>();
case 3:
return RandomValue<DateTime>();
case 4:
return RandomValue<string>(stringValueAllowEmpty);
case 5:
return RandomValue<Guid>();
case 6:
return RandomValue<decimal>();
case 7:
return RandomValue<double>();
case 8:
return RandomValue<float>();
default:
return RandomValue<short>();
}
}
//model
var retObj = Activator.CreateInstance(t);
foreach (var p in t.GetFields())
{
//if (Rand.Next(5) == 0) continue;
var fieldType = p.FieldType;
p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
}
foreach (var p in t.GetProperties())
{
//if (Rand.Next(5) == 0) continue;
if (p.CanWrite && p.CanRead)
{
var fieldType = p.PropertyType;
p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
}
}
return retObj;
}
19
Source : RandomHelper.cs
with MIT License
from 1996v
with MIT License
from 1996v
public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
{
if (t.IsPrimitive)
{
if (t == typeof(byte))
{
return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
}
if (t == typeof(sbyte))
{
return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
}
if (t == typeof(short))
{
return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
}
if (t == typeof(ushort))
{
return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
}
if (t == typeof(int))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}
if (t == typeof(uint))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
return BitConverter.ToUInt32(bytes, 0);
}
if (t == typeof(long))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
return BitConverter.ToInt64(bytes, 0);
}
if (t == typeof(ulong))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
return BitConverter.ToUInt64(bytes, 0);
}
if (t == typeof(float))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
var f = BitConverter.ToSingle(bytes, 0);
if (float.IsNaN(f))
f = (float)RandomValue<short>();
return f;
}
if (t == typeof(double))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
var d= BitConverter.ToDouble(bytes, 0);
if (double.IsNaN(d))
d = (double)RandomValue<short>();
return d;
}
if (t == typeof(char))
{
var roll = Rand.Next(ASCII.Length);
return ASCII[roll];
}
if (t == typeof(bool))
{
return (Rand.Next(2) == 1);
}
throw new InvalidOperationException();
}
if (t == typeof(decimal))
{
return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
}
if (t == typeof(string))
{
int start = stringValueAllowEmpty ? 0 : 1;
var len = Rand.Next(start, 40);
var c = new char[len];
for (var i = 0; i < c.Length; i++)
{
c[i] = (char)typeof(char).RandomValue();
}
return new string(c);
}
if (t == typeof(DateTime))
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var bytes = new byte[4];
Rand.NextBytes(bytes);
var secsOffset = BitConverter.ToInt32(bytes, 0);
var retDate = epoch.AddSeconds(secsOffset);
return retDate;
}
if (t == typeof(TimeSpan))
{
return new TimeSpan(RandomValue<DateTime>().Ticks);
}
if (t == typeof(DataTable))
{
DataTable dt = new DataTable();
int coluCount = Rand.Next(10, 30);
for (int i = 0; i < coluCount; i++)
{
string n = RandomHelper.RandomValue<string>(false);
while(dt.Columns.Contains(n))
n = RandomHelper.RandomValue<string>(false);
dt.Columns.Add(n, typeof(object));
}
int rowCount = Rand.Next(20, 50);
for (int i = 0; i < rowCount; i++)
{
var row = new object[coluCount];
for (int zi = 0; zi < coluCount; zi++)
{
row[zi] = RandomHelper.RandomValue<object>();
}
dt.Rows.Add(row);
}
return dt;
}
if (t.IsNullable())
{
// leave it unset
if (Rand.Next(2) == 0)
{
// null!
return Activator.CreateInstance(t);
}
var underlying = Nullable.GetUnderlyingType(t);
var val = underlying.RandomValue(stringValueAllowEmpty);
var cons = t.GetConstructor(new[] { underlying });
return cons.Invoke(new object[] { val });
}
if (t.IsEnum)
{
var allValues = Enum.GetValues(t);
var ix = Rand.Next(allValues.Length);
return allValues.GetValue(ix);
}
if (t.IsArray)
{
var valType = t.GetElementType();
var len = Rand.Next(20, 50);
var ret = Array.CreateInstance(valType, len);
//var add = t.GetMethod("SetValue");
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
ret.SetValue(elem, i);
}
return ret;
}
if (t.IsGenericType)
{
var defind = t.GetGenericTypeDefinition();
if (defind == typeof(HashSet<>))
{
var valType = t.GetGenericArguments()[0];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var contains = t.GetMethod("Contains");
var len = Rand.Next(20, 50);
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
elem = valType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { elem });
}
return ret;
}
if (defind == typeof(Dictionary<,>))
{
var keyType = t.GetGenericArguments()[0];
var valType = t.GetGenericArguments()[1];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var contains = t.GetMethod("ContainsKey");
var len = Rand.Next(20, 50);
if (keyType == typeof(Boolean))
len = 2;
for (var i = 0; i < len; i++)
{
var val = valType.RandomValue(stringValueAllowEmpty);
var key = keyType.RandomValue(stringValueAllowEmpty);
while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
key = keyType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { key, val });
}
return ret;
}
if (defind == typeof(List<>))
{
var valType = t.GetGenericArguments()[0];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var len = Rand.Next(20, 50);
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { elem });
}
return ret;
}
if (defind == typeof(ArraySegment<>))
{
var valType = t.GetGenericArguments()[0];
var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
var lenT = ary.GetType().GetProperty("Length");
var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
var len = (int)lenT.GetValue(ary) - offset;
return Activator.CreateInstance(t, ary, offset, len);
}
}
if (t == typeof(Guid))
return Guid.NewGuid();
if (t == typeof(object))
{
var code = Rand.Next(0, 9);
switch (code)
{
case 0:
return RandomValue<int>();
case 1:
return RandomValue<long>();
case 2:
return RandomValue<Char>();
case 3:
return RandomValue<DateTime>();
case 4:
return RandomValue<string>(stringValueAllowEmpty);
case 5:
return RandomValue<Guid>();
case 6:
return RandomValue<decimal>();
case 7:
return RandomValue<double>();
case 8:
return RandomValue<float>();
default:
return RandomValue<short>();
}
}
//model
var retObj = Activator.CreateInstance(t);
foreach (var p in t.GetFields())
{
//if (Rand.Next(5) == 0) continue;
var fieldType = p.FieldType;
p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
}
foreach (var p in t.GetProperties())
{
//if (Rand.Next(5) == 0) continue;
if (p.CanWrite && p.CanRead)
{
var fieldType = p.PropertyType;
p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
}
}
return retObj;
}
19
Source : SafePadding.cs
with MIT License
from 5argon
with MIT License
from 5argon
private protected override void UpdateRect()
{
PerEdgeEvaluationModes selectedOrientation =
orientationType == SupportedOrientations.Dual ?
NotchSolutionUtility.GetCurrentOrientation() == ScreenOrientation.Landscape ?
landscapePaddings : portraitOrDefaultPaddings
: portraitOrDefaultPaddings;
m_Tracker.Clear();
m_Tracker.Add(this, rectTransform,
(LockSide(selectedOrientation.left) ? DrivenTransformProperties.AnchorMinX : 0) |
(LockSide(selectedOrientation.right) ? DrivenTransformProperties.AnchorMaxX : 0) |
(LockSide(selectedOrientation.bottom) ? DrivenTransformProperties.AnchorMinY : 0) |
(LockSide(selectedOrientation.top) ? DrivenTransformProperties.AnchorMaxY : 0) |
(LockSide(selectedOrientation.left) && LockSide(selectedOrientation.right) ? (DrivenTransformProperties.SizeDeltaX | DrivenTransformProperties.AncreplaceddPositionX) : 0) |
(LockSide(selectedOrientation.top) && LockSide(selectedOrientation.bottom) ? (DrivenTransformProperties.SizeDeltaY | DrivenTransformProperties.AncreplaceddPositionY) : 0)
);
bool LockSide(EdgeEvaluationMode saem)
{
switch (saem)
{
case EdgeEvaluationMode.On:
case EdgeEvaluationMode.Balanced:
case EdgeEvaluationMode.Off:
return true;
//When "Unlocked" is supported, it will be false.
default:
return false;
}
}
//Lock the anchor mode to full stretch first.
rectTransform.anchorMin = Vector2.zero;
rectTransform.anchorMax = Vector2.one;
var topRect = GetCanvasRect();
var safeAreaRelative = SafeAreaRelative;
#if DEBUG_NOTCH_SOLUTION
Debug.Log($"Top {topRect} safe {safeAreaRelative} min {safeAreaRelative.xMin} {safeAreaRelative.yMin}");
#endif
var relativeLDUR = new float[4]
{
safeAreaRelative.xMin,
safeAreaRelative.yMin,
1 - (safeAreaRelative.yMin + safeAreaRelative.height),
1 - (safeAreaRelative.xMin + safeAreaRelative.width),
};
#if DEBUG_NOTCH_SOLUTION
Debug.Log($"SafeLDUR {string.Join(" ", relativeLDUR.Select(x => x.ToString()))}");
#endif
// fixed: sometimes relativeLDUR will be NAN when start at some android devices.
// if relativeLDUR is NAN then sizeDelta will be NAN, the safe area will be wrong.
if (float.IsNaN(relativeLDUR[0]))
{
relativeLDUR[0] = 0;
}
if (float.IsNaN(relativeLDUR[1]))
{
relativeLDUR[1] = 0;
}
if (float.IsNaN(relativeLDUR[2]))
{
relativeLDUR[2] = 0;
}
if (float.IsNaN(relativeLDUR[3]))
{
relativeLDUR[3] = 0;
}
var currentRect = rectTransform.rect;
//TODO : Calculate the current padding relative, to enable "Unlocked" mode. (Not forcing zero padding)
var finalPaddingsLDUR = new float[4]
{
0,0,0,0
};
switch (selectedOrientation.left)
{
case EdgeEvaluationMode.On:
finalPaddingsLDUR[0] = topRect.width * relativeLDUR[0];
break;
case EdgeEvaluationMode.Balanced:
finalPaddingsLDUR[0] = relativeLDUR[3] > relativeLDUR[0] ?
topRect.width * relativeLDUR[3] :
topRect.width * relativeLDUR[0];
break;
}
switch (selectedOrientation.right)
{
case EdgeEvaluationMode.On:
finalPaddingsLDUR[3] = topRect.width * relativeLDUR[3];
break;
case EdgeEvaluationMode.Balanced:
finalPaddingsLDUR[3] = relativeLDUR[0] > relativeLDUR[3] ?
topRect.width * relativeLDUR[0] :
topRect.width * relativeLDUR[3];
break;
}
switch (selectedOrientation.bottom)
{
case EdgeEvaluationMode.On:
finalPaddingsLDUR[1] = topRect.height * relativeLDUR[1];
break;
case EdgeEvaluationMode.Balanced:
finalPaddingsLDUR[1] = relativeLDUR[2] > relativeLDUR[1] ?
topRect.height * relativeLDUR[2] :
topRect.height * relativeLDUR[1];
break;
}
switch (selectedOrientation.top)
{
case EdgeEvaluationMode.On:
finalPaddingsLDUR[2] = topRect.height * relativeLDUR[2];
break;
case EdgeEvaluationMode.Balanced:
finalPaddingsLDUR[2] = relativeLDUR[1] > relativeLDUR[2] ?
topRect.height * relativeLDUR[1] :
topRect.height * relativeLDUR[2];
break;
}
//Apply influence to the calculated padding
finalPaddingsLDUR[0] *= influence;
finalPaddingsLDUR[1] *= influence;
finalPaddingsLDUR[2] *= influence;
finalPaddingsLDUR[3] *= influence;
if (flipPadding)
{
float remember = 0;
finalPaddingsLDUR[0] = remember;
finalPaddingsLDUR[0] = finalPaddingsLDUR[3];
finalPaddingsLDUR[3] = remember;
finalPaddingsLDUR[1] = remember;
finalPaddingsLDUR[1] = finalPaddingsLDUR[2];
finalPaddingsLDUR[2] = remember;
}
#if DEBUG_NOTCH_SOLUTION
Debug.Log($"FinalLDUR {string.Join(" ", finalPaddingsLDUR.Select(x => x.ToString()))}");
#endif
//Combined padding becomes size delta.
var sizeDelta = rectTransform.sizeDelta;
sizeDelta.x = -(finalPaddingsLDUR[0] + finalPaddingsLDUR[3]);
sizeDelta.y = -(finalPaddingsLDUR[1] + finalPaddingsLDUR[2]);
rectTransform.sizeDelta = sizeDelta;
//The rect remaining after subtracted the size delta.
Vector2 rectWidthHeight = new Vector2(topRect.width + sizeDelta.x, topRect.height + sizeDelta.y);
#if DEBUG_NOTCH_SOLUTION
Debug.Log($"RectWidthHeight {rectWidthHeight}");
#endif
//Anchor position's answer is depending on pivot too. Where the pivot point is defines where 0 anchor point is.
Vector2 zeroPosition = new Vector2(rectTransform.pivot.x * topRect.width, rectTransform.pivot.y * topRect.height);
Vector2 pivotInRect = new Vector2(rectTransform.pivot.x * rectWidthHeight.x, rectTransform.pivot.y * rectWidthHeight.y);
#if DEBUG_NOTCH_SOLUTION
Debug.Log($"zeroPosition {zeroPosition}");
#endif
//Calculate like zero position is at bottom left first, then diff with the real zero position.
rectTransform.ancreplaceddPosition3D = new Vector3(
finalPaddingsLDUR[0] + pivotInRect.x - zeroPosition.x,
finalPaddingsLDUR[1] + pivotInRect.y - zeroPosition.y,
rectTransform.ancreplaceddPosition3D.z);
}
19
Source : FdbTupleParser.cs
with MIT License
from abdullin
with MIT License
from abdullin
public static void WriteSingle(ref TupleWriter writer, float value)
{
// The double is converted to its Big-Endian IEEE binary representation
// - If the sign bit is set, flip all the bits
// - If the sign bit is not set, just flip the sign bit
// This ensures that all negative numbers have their first byte < 0x80, and all positive numbers have their first byte >= 0x80
// Special case for NaN: All variants are normalized to float.NaN !
if (float.IsNaN(value)) value = float.NaN;
// note: there is no BitConverter.SingleToInt32Bits(...), so we have to do it ourselves...
uint bits;
unsafe { bits = *((uint*)&value); }
if ((bits & 0x80000000U) != 0)
{ // negative
bits = ~bits;
}
else
{ // postive
bits |= 0x80000000U;
}
writer.Output.EnsureBytes(5);
var buffer = writer.Output.Buffer;
int p = writer.Output.Position;
buffer[p + 0] = FdbTupleTypes.Single;
buffer[p + 1] = (byte)(bits >> 24);
buffer[p + 2] = (byte)(bits >> 16);
buffer[p + 3] = (byte)(bits >> 8);
buffer[p + 4] = (byte)(bits);
writer.Output.Position = p + 5;
}
19
Source : FdbConverters.cs
with MIT License
from abdullin
with MIT License
from abdullin
private static void RegisterDefaultConverters()
{
//TODO: there is too much generic type combinations! need to refactor this ...
RegisterUnsafe<bool, Slice>((value) => Slice.FromByte(value ? (byte)1 : default(byte)));
RegisterUnsafe<bool, byte[]>((value) => Slice.FromByte(value ? (byte)1 : default(byte)).GetBytes());
RegisterUnsafe<bool, string>((value) => value ? "true" : "false");
RegisterUnsafe<bool, sbyte>((value) => value ? (sbyte)1 : default(sbyte));
RegisterUnsafe<bool, byte>((value) => value ? (byte)1 : default(byte));
RegisterUnsafe<bool, short>((value) => value ? (short)1 : default(short));
RegisterUnsafe<bool, ushort>((value) => value ? (ushort)1 : default(ushort));
RegisterUnsafe<bool, int>((value) => value ? 1 : default(int));
RegisterUnsafe<bool, uint>((value) => value ? 1U : default(uint));
RegisterUnsafe<bool, long>((value) => value ? 1L : default(long));
RegisterUnsafe<bool, ulong>((value) => value ? 1UL : default(ulong));
RegisterUnsafe<bool, double>((value) => value ? 0.0d : 1.0d);
RegisterUnsafe<bool, float>((value) => value ? 0.0f : 1.0f);
RegisterUnsafe<int, Slice>((value) => Slice.FromInt32(value));
RegisterUnsafe<int, byte[]>((value) => Slice.FromInt32(value).GetBytes());
RegisterUnsafe<int, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<int, bool>((value) => value != 0);
RegisterUnsafe<int, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<int, byte>((value) => checked((byte)value));
RegisterUnsafe<int, short>((value) => checked((short)value));
RegisterUnsafe<int, ushort>((value) => checked((ushort)value));
RegisterUnsafe<int, uint>((value) => (uint)value);
RegisterUnsafe<int, long>((value) => value);
RegisterUnsafe<int, ulong>((value) => (ulong)value);
RegisterUnsafe<int, double>((value) => value);
RegisterUnsafe<int, float>((value) => checked((float)value));
RegisterUnsafe<int, FdbTupleAlias>((value) => (FdbTupleAlias)value);
RegisterUnsafe<uint, Slice>((value) => Slice.FromUInt64(value));
RegisterUnsafe<uint, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
RegisterUnsafe<uint, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<uint, bool>((value) => value != 0);
RegisterUnsafe<uint, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<uint, byte>((value) => checked((byte)value));
RegisterUnsafe<uint, short>((value) => checked((short)value));
RegisterUnsafe<uint, ushort>((value) => checked((ushort)value));
RegisterUnsafe<uint, int>((value) => (int)value);
RegisterUnsafe<uint, long>((value) => value);
RegisterUnsafe<uint, ulong>((value) => value);
RegisterUnsafe<uint, double>((value) => value);
RegisterUnsafe<uint, float>((value) => checked((float)value));
RegisterUnsafe<long, Slice>((value) => Slice.FromInt64(value));
RegisterUnsafe<long, byte[]>((value) => Slice.FromInt64(value).GetBytes());
RegisterUnsafe<long, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<long, bool>((value) => value != 0);
RegisterUnsafe<long, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<long, byte>((value) => checked((byte)value));
RegisterUnsafe<long, short>((value) => checked((short)value));
RegisterUnsafe<long, ushort>((value) => checked((ushort)value));
RegisterUnsafe<long, int>((value) => checked((int)value));
RegisterUnsafe<long, uint>((value) => (uint)value);
RegisterUnsafe<long, ulong>((value) => (ulong)value);
RegisterUnsafe<long, double>((value) => checked((double)value));
RegisterUnsafe<long, float>((value) => checked((float)value));
RegisterUnsafe<long, TimeSpan>((value) => TimeSpan.FromTicks(value));
RegisterUnsafe<long, Uuid64>((value) => new Uuid64(value));
RegisterUnsafe<long, System.Net.IPAddress>((value) => new System.Net.IPAddress(value));
RegisterUnsafe<ulong, Slice>((value) => Slice.FromUInt64(value));
RegisterUnsafe<ulong, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
RegisterUnsafe<ulong, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<ulong, bool>((value) => value != 0);
RegisterUnsafe<ulong, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<ulong, byte>((value) => checked((byte)value));
RegisterUnsafe<ulong, short>((value) => checked((short)value));
RegisterUnsafe<ulong, ushort>((value) => checked((ushort)value));
RegisterUnsafe<ulong, int>((value) => checked((int)value));
RegisterUnsafe<ulong, uint>((value) => checked((uint)value));
RegisterUnsafe<ulong, long>((value) => checked((long)value));
RegisterUnsafe<ulong, double>((value) => checked((double)value));
RegisterUnsafe<ulong, float>((value) => checked((float)value));
RegisterUnsafe<ulong, Uuid64>((value) => new Uuid64(value));
RegisterUnsafe<ulong, TimeSpan>((value) => TimeSpan.FromTicks(checked((long)value)));
RegisterUnsafe<short, Slice>((value) => Slice.FromInt32(value));
RegisterUnsafe<short, byte[]>((value) => Slice.FromInt32(value).GetBytes());
RegisterUnsafe<short, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<short, bool>((value) => value != 0);
RegisterUnsafe<short, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<short, byte>((value) => checked((byte)value));
RegisterUnsafe<short, ushort>((value) => checked((ushort)value));
RegisterUnsafe<short, int>((value) => value);
RegisterUnsafe<short, uint>((value) => checked((uint)value));
RegisterUnsafe<short, long>((value) => value);
RegisterUnsafe<short, ulong>((value) => checked((ulong)value));
RegisterUnsafe<short, double>((value) => value);
RegisterUnsafe<short, float>((value) => value);
RegisterUnsafe<short, FdbTupleAlias>((value) => (FdbTupleAlias)value);
RegisterUnsafe<ushort, Slice>((value) => Slice.FromUInt64(value));
RegisterUnsafe<ushort, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
RegisterUnsafe<ushort, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<ushort, bool>((value) => value != 0);
RegisterUnsafe<ushort, byte>((value) => checked((byte)value));
RegisterUnsafe<ushort, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<ushort, short>((value) => checked((short)value));
RegisterUnsafe<ushort, int>((value) => value);
RegisterUnsafe<ushort, uint>((value) => value);
RegisterUnsafe<ushort, long>((value) => value);
RegisterUnsafe<ushort, ulong>((value) => value);
RegisterUnsafe<ushort, double>((value) => value);
RegisterUnsafe<ushort, float>((value) => value);
RegisterUnsafe<byte, Slice>((value) => Slice.FromInt32(value));
RegisterUnsafe<byte, byte[]>((value) => Slice.FromInt32(value).GetBytes());
RegisterUnsafe<byte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<byte, bool>((value) => value != 0);
RegisterUnsafe<byte, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<byte, short>((value) => value);
RegisterUnsafe<byte, ushort>((value) => value);
RegisterUnsafe<byte, int>((value) => value);
RegisterUnsafe<byte, uint>((value) => value);
RegisterUnsafe<byte, long>((value) => value);
RegisterUnsafe<byte, ulong>((value) => value);
RegisterUnsafe<byte, double>((value) => value);
RegisterUnsafe<byte, float>((value) => value);
RegisterUnsafe<byte, FdbTupleAlias>((value) => (FdbTupleAlias)value);
RegisterUnsafe<sbyte, Slice>((value) => Slice.FromInt64(value));
RegisterUnsafe<sbyte, byte[]>((value) => Slice.FromInt64(value).GetBytes());
RegisterUnsafe<sbyte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<sbyte, bool>((value) => value != 0);
RegisterUnsafe<sbyte, byte>((value) => checked((byte)value));
RegisterUnsafe<sbyte, short>((value) => value);
RegisterUnsafe<sbyte, ushort>((value) => checked((ushort)value));
RegisterUnsafe<sbyte, int>((value) => value);
RegisterUnsafe<sbyte, uint>((value) => checked((uint)value));
RegisterUnsafe<sbyte, long>((value) => value);
RegisterUnsafe<sbyte, ulong>((value) => checked((ulong)value));
RegisterUnsafe<sbyte, double>((value) => value);
RegisterUnsafe<sbyte, float>((value) => value);
RegisterUnsafe<float, Slice>((value) => Slice.FromSingle(value));
RegisterUnsafe<float, byte[]>((value) => Slice.FromSingle(value).GetBytes());
RegisterUnsafe<float, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
RegisterUnsafe<float, bool>((value) => !(value == 0f || float.IsNaN(value)));
RegisterUnsafe<float, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<float, byte>((value) => checked((byte)value));
RegisterUnsafe<float, short>((value) => checked((short)value));
RegisterUnsafe<float, ushort>((value) => checked((ushort)value));
RegisterUnsafe<float, int>((value) => checked((int)value));
RegisterUnsafe<float, uint>((value) => (uint)value);
RegisterUnsafe<float, long>((value) => checked((long)value));
RegisterUnsafe<float, ulong>((value) => (ulong)value);
RegisterUnsafe<float, double>((value) => value);
RegisterUnsafe<double, Slice>((value) => Slice.FromDouble(value));
RegisterUnsafe<double, byte[]>((value) => Slice.FromDouble(value).GetBytes());
RegisterUnsafe<double, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
RegisterUnsafe<double, bool>((value) => !(value == 0d || double.IsNaN(value)));
RegisterUnsafe<double, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<double, byte>((value) => checked((byte)value));
RegisterUnsafe<double, short>((value) => checked((short)value));
RegisterUnsafe<double, ushort>((value) => checked((ushort)value));
RegisterUnsafe<double, int>((value) => checked((int)value));
RegisterUnsafe<double, uint>((value) => (uint)value);
RegisterUnsafe<double, long>((value) => checked((long)value));
RegisterUnsafe<double, ulong>((value) => (ulong)value);
RegisterUnsafe<double, float>((value) => checked((float)value));
RegisterUnsafe<string, Slice>((value) => Slice.FromString(value));
RegisterUnsafe<string, byte[]>((value) => Slice.FromString(value).GetBytes());
RegisterUnsafe<string, bool>((value) => !string.IsNullOrEmpty(value));
RegisterUnsafe<string, sbyte>((value) => string.IsNullOrEmpty(value) ? default(sbyte) : SByte.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, byte>((value) => string.IsNullOrEmpty(value) ? default(byte) : Byte.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, short>((value) => string.IsNullOrEmpty(value) ? default(short) : Int16.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, ushort>((value) => string.IsNullOrEmpty(value) ? default(ushort) : UInt16.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, int>((value) => string.IsNullOrEmpty(value) ? default(int) : Int32.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, uint>((value) => string.IsNullOrEmpty(value) ? default(uint) : UInt32.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, long>((value) => string.IsNullOrEmpty(value) ? default(long) : Int64.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, ulong>((value) => string.IsNullOrEmpty(value) ? default(ulong) : UInt64.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, float>((value) => string.IsNullOrEmpty(value) ? default(float) : Single.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
RegisterUnsafe<string, double>((value) => string.IsNullOrEmpty(value) ? default(double) : Double.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
RegisterUnsafe<string, Guid>((value) => string.IsNullOrEmpty(value) ? default(Guid) : Guid.Parse(value));
RegisterUnsafe<string, Uuid128>((value) => string.IsNullOrEmpty(value) ? default(Uuid128) : Uuid128.Parse(value));
RegisterUnsafe<string, Uuid64>((value) => string.IsNullOrEmpty(value) ? default(Uuid64) : Uuid64.Parse(value));
RegisterUnsafe<string, System.Net.IPAddress>((value) => string.IsNullOrEmpty(value) ? default(System.Net.IPAddress) : System.Net.IPAddress.Parse(value));
RegisterUnsafe<byte[], Slice>((value) => Slice.Create(value));
RegisterUnsafe<byte[], string>((value) => value == null ? default(string) : value.Length == 0 ? String.Empty : System.Convert.ToBase64String(value));
RegisterUnsafe<byte[], bool>((value) => value != null && value.Length > 0);
RegisterUnsafe<byte[], sbyte>((value) => value == null ? default(sbyte) : Slice.Create(value).ToSByte());
RegisterUnsafe<byte[], byte>((value) => value == null ? default(byte) : Slice.Create(value).ToByte());
RegisterUnsafe<byte[], short>((value) => value == null ? default(short) : Slice.Create(value).ToInt16());
RegisterUnsafe<byte[], ushort>((value) => value == null ? default(ushort) : Slice.Create(value).ToUInt16());
RegisterUnsafe<byte[], int>((value) => value == null ? 0 : Slice.Create(value).ToInt32());
RegisterUnsafe<byte[], uint>((value) => value == null ? 0U : Slice.Create(value).ToUInt32());
RegisterUnsafe<byte[], long>((value) => value == null ? 0L : Slice.Create(value).ToInt64());
RegisterUnsafe<byte[], ulong>((value) => value == null ? 0UL : Slice.Create(value).ToUInt64());
RegisterUnsafe<byte[], Guid>((value) => value == null || value.Length == 0 ? default(Guid) : new Uuid128(value).ToGuid());
RegisterUnsafe<byte[], Uuid128>((value) => value == null || value.Length == 0 ? default(Uuid128) : new Uuid128(value));
RegisterUnsafe<byte[], Uuid64>((value) => value == null || value.Length == 0 ? default(Uuid64) : new Uuid64(value));
RegisterUnsafe<byte[], TimeSpan>((value) => value == null ? TimeSpan.Zero : TimeSpan.FromTicks(Slice.Create(value).ToInt64()));
RegisterUnsafe<byte[], System.Net.IPAddress>((value) => value == null || value.Length == 0 ? default(System.Net.IPAddress) : new System.Net.IPAddress(value));
RegisterUnsafe<Guid, Slice>((value) => Slice.FromGuid(value));
RegisterUnsafe<Guid, byte[]>((value) => Slice.FromGuid(value).GetBytes());
RegisterUnsafe<Guid, string>((value) => value.ToString("D", null));
RegisterUnsafe<Guid, Uuid128>((value) => new Uuid128(value));
RegisterUnsafe<Guid, bool>((value) => value != Guid.Empty);
RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(new Uuid128(value).ToByteArray()));
RegisterUnsafe<Uuid128, Slice>((value) => value.ToSlice());
RegisterUnsafe<Uuid128, byte[]>((value) => value.ToByteArray());
RegisterUnsafe<Uuid128, string>((value) => value.ToString("D", null));
RegisterUnsafe<Uuid128, Guid>((value) => value.ToGuid());
RegisterUnsafe<Uuid128, bool>((value) => value != Uuid128.Empty);
RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(value.ToByteArray()));
RegisterUnsafe<Uuid64, Slice>((value) => value.ToSlice());
RegisterUnsafe<Uuid64, byte[]>((value) => value.ToByteArray());
RegisterUnsafe<Uuid64, string>((value) => value.ToString("D", null));
RegisterUnsafe<Uuid64, long>((value) => value.ToInt64());
RegisterUnsafe<Uuid64, ulong>((value) => value.ToUInt64());
RegisterUnsafe<Uuid64, bool>((value) => value.ToInt64() != 0L);
RegisterUnsafe<TimeSpan, Slice>((value) => Slice.FromInt64(value.Ticks));
RegisterUnsafe<TimeSpan, byte[]>((value) => Slice.FromInt64(value.Ticks).GetBytes());
RegisterUnsafe<TimeSpan, long>((value) => value.Ticks);
RegisterUnsafe<TimeSpan, ulong>((value) => checked((ulong)value.Ticks));
RegisterUnsafe<TimeSpan, double>((value) => value.TotalSeconds);
RegisterUnsafe<TimeSpan, bool>((value) => value == TimeSpan.Zero);
RegisterUnsafe<System.Net.IPAddress, Slice>((value) => value != null ? Slice.Create(value.GetAddressBytes()) : Slice.Nil);
RegisterUnsafe<System.Net.IPAddress, byte[]>((value) => value != null ? value.GetAddressBytes() : null);
RegisterUnsafe<System.Net.IPAddress, string>((value) => value != null ? value.ToString() : null);
RegisterUnsafe<FdbTupleAlias, byte>((value) => (byte)value);
RegisterUnsafe<FdbTupleAlias, int>((value) => (int)value);
RegisterUnsafe<FdbTupleAlias, Slice>((value) => Slice.FromByte((byte)value));
//REVIEW: this should go in the Tuples layer !
RegisterUnsafe<Slice, byte[]>((value) => value.GetBytes());
RegisterUnsafe<Slice, string>((value) => value.ToUnicode());
RegisterUnsafe<Slice, bool>((value) => value.ToBool());
RegisterUnsafe<Slice, sbyte>((value) => value.ToSByte());
RegisterUnsafe<Slice, byte>((value) => value.ToByte());
RegisterUnsafe<Slice, short>((value) => value.ToInt16());
RegisterUnsafe<Slice, ushort>((value) => value.ToUInt16());
RegisterUnsafe<Slice, int>((value) => value.ToInt32());
RegisterUnsafe<Slice, uint>((value) => value.ToUInt32());
RegisterUnsafe<Slice, long>((value) => value.ToInt64());
RegisterUnsafe<Slice, ulong>((value) => value.ToUInt64());
RegisterUnsafe<Slice, Guid>((value) => value.ToGuid());
RegisterUnsafe<Slice, Uuid128>((value) => value.ToUuid128());
RegisterUnsafe<Slice, Uuid64>((value) => value.ToUuid64());
RegisterUnsafe<Slice, TimeSpan>((value) => TimeSpan.FromTicks(value.ToInt64()));
RegisterUnsafe<Slice, FdbTupleAlias>((value) => (FdbTupleAlias)value.ToByte());
RegisterUnsafe<Slice, System.Net.IPAddress>((value) => !value.IsNullOrEmpty ? new System.Net.IPAddress(value.GetBytes()) : null);
}
19
Source : VectorExtensions.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static bool IsValidVector(this Vector3 vector)
{
return !float.IsNaN(vector.x) && !float.IsNaN(vector.y) && !float.IsNaN(vector.z) &&
!float.IsInfinity(vector.x) && !float.IsInfinity(vector.y) && !float.IsInfinity(vector.z);
}
19
Source : QuaternionExtensions.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static bool IsValidRotation(this Quaternion rotation)
{
return !float.IsNaN(rotation.x) && !float.IsNaN(rotation.y) && !float.IsNaN(rotation.z) && !float.IsNaN(rotation.w) &&
!float.IsInfinity(rotation.x) && !float.IsInfinity(rotation.y) && !float.IsInfinity(rotation.z) && !float.IsInfinity(rotation.w);
}
19
Source : EdgeUtilities.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static bool IsValidPoint(Vector2 point)
{
return (!float.IsInfinity(point.x) && !float.IsInfinity(point.y) &&
!float.IsNaN(point.x) && !float.IsNaN(point.y));
}
19
Source : OculusSpatializerUnity.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
void Update()
{
if (dynamicReflectionsEnabled)
{
OSP_Unity_replacedignRaycastCallback(AudioRaycast, System.IntPtr.Zero);
}
else
{
OSP_Unity_replacedignRaycastCallback(System.IntPtr.Zero, System.IntPtr.Zero);
}
OSP_Unity_SetDynamicRoomRaysPerSecond(raysPerSecond);
OSP_Unity_SetDynamicRoomInterpSpeed(roomInterpSpeed);
OSP_Unity_SetDynamicRoomMaxWallDistance(maxWallDistance);
OSP_Unity_SetDynamicRoomRaysRayCacheSize(rayCacheSize);
gLayerMask = layerMask;
OSP_Unity_UpdateRoomModel(1.0f);
if (visualizeRoom)
{
if (!roomVisualizationInitialized)
{
inireplacedalizeRoomVisualization();
roomVisualizationInitialized = true;
}
Vector3 pos;
OSP_Unity_GetRoomDimensions(dims, coefs, out pos);
pos.z *= -1; // swap to left-handed
var size = new Vector3(dims[0], dims[1], dims[2]);
float magSqrd = size.sqrMagnitude;
if (!float.IsNaN(magSqrd) && 0.0f < magSqrd && magSqrd < 1000000.0f)
{
transform.localScale = size * 0.999f;
}
transform.position = pos;
OSP_Unity_GetRaycastHits(points, normals, HIT_COUNT);
for (int i = 0; i < HIT_COUNT; ++i)
{
if (points[i] == Vector3.zero)
points[i].y = -10000.0f; // hide it
// swap to left-handed
points[i].z *= -1;
normals[i].z *= -1;
particles[i].position = points[i] + normals[i] * particleOffset;
if (normals[i] != Vector3.zero)
particles[i].rotation3D = Quaternion.LookRotation(normals[i]).eulerAngles;
particles[i].startSize = particleSize;
particles[i].startColor = new Color(208 / 255f, 38 / 255f, 174 / 255f, 1.0f);
}
for (int wall = 0; wall < 6; ++wall)
{
var color = Color.Lerp(Color.red, Color.green, coefs[wall]);
wallRenderer[wall].material.SetColor("_TintColor", color);
}
sys.SetParticles(particles, particles.Length);
}
}
19
Source : PositionExtensions.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static bool IsRotationValid(this Quaternion q)
{
if (q == Quaternion.Idenreplacedy)
return true;
if (float.IsNaN(q.X) || float.IsNaN(q.Y) || float.IsNaN(q.Z) || float.IsNaN(q.W))
return false;
var length = q.Length();
if (float.IsNaN(length))
return false;
if (Math.Abs(1.0f - length) > RotationEpsilon)
return false;
return true;
}
19
Source : QuaternionExtensions.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static bool IsValid(this Quaternion q)
{
if (float.IsNaN(q.X) || float.IsNaN(q.Y) || float.IsNaN(q.Z) || float.IsNaN(q.W))
return false;
var length = q.Length();
if (float.IsNaN(length))
return false;
if (Math.Abs(length - 1.0f) > PhysicsGlobals.EPSILON * 5.0f)
return false;
return true;
}
19
Source : Vector3Extensions.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static bool IsValid(this Vector3 v)
{
return !float.IsNaN(v.X) && !float.IsNaN(v.Y) && !float.IsNaN(v.Z);
}
19
Source : ClothingTableList.xaml.cs
with GNU General Public License v3.0
from ACEmulator
with GNU General Public License v3.0
from ACEmulator
public void LoadModelWithClothingBase()
{
if (CurrentClothingItem == null) return;
if (SetupIds.SelectedIndex == -1) return;
if (PaletteTemplates.SelectedIndex == -1) return;
float shade = 0;
if (Shades.IsEnabled)
{
shade = (float)(Shades.Value / Shades.Maximum);
if (float.IsNaN(shade))
shade = 0;
}
var selectedSetup = SetupIds.SelectedItem as ListBoxItem;
uint setupId = (uint)selectedSetup.DataContext;
var selectedPalTemp = PaletteTemplates.SelectedItem as ListBoxItem;
uint palTemplate = (uint)selectedPalTemp.DataContext;
ModelViewer.LoadModel(setupId, CurrentClothingItem, palTemplate, shade);
}
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
private static async void HereFishyFishy(Farmer who, int x, int y)
{
hereFishying = true;
if (fishySound != null)
{
fishySound.Play();
}
who.completelyStopAnimatingOrDoingAction();
who.jitterStrength = 2f;
List<FarmerSprite.AnimationFrame> animationFrames = new List<FarmerSprite.AnimationFrame>(){
new FarmerSprite.AnimationFrame(94, 100, false, false, null, false).AddFrameAction(delegate (Farmer f)
{
f.jitterStrength = 2f;
})
};
who.FarmerSprite.setCurrentAnimation(animationFrames.ToArray());
who.FarmerSprite.PauseForSingleAnimation = true;
who.FarmerSprite.loop = true;
who.FarmerSprite.loopThisAnimation = true;
who.Sprite.currentFrame = 94;
await System.Threading.Tasks.Task.Delay(1793);
canPerfect = true;
perfect = false;
who.synchronizedJump(8f);
await System.Threading.Tasks.Task.Delay(100);
canPerfect = false;
await System.Threading.Tasks.Task.Delay(900);
who.stopJittering();
who.completelyStopAnimatingOrDoingAction();
who.forceCanMove();
hereFishying = false;
await System.Threading.Tasks.Task.Delay(Game1.random.Next(500, 1000));
Object o = who.currentLocation.getFish(0, -1, 1, who, 0, new Vector2(x, y), who.currentLocation.Name);
if (o == null || o.ParentSheetIndex <= 0)
{
o = new Object(Game1.random.Next(167, 173), 1, false, -1, 0);
}
int parentSheetIndex = o.parentSheetIndex;
animations.Clear();
float t;
lastUser = who;
whichFish = parentSheetIndex;
Dictionary<int, string> data = Game1.content.Load<Dictionary<int, string>>("Data\\Fish");
string[] datas = null;
if (data.ContainsKey(whichFish))
{
datas = data[whichFish].Split('/');
}
bool non_fishable_fish = false;
if (o is Furniture)
{
non_fishable_fish = true;
}
else if (Utility.IsNormalObjectAtParentSheetIndex(o, o.ParentSheetIndex) && data.ContainsKey(o.ParentSheetIndex))
{
string[] array = data[o.ParentSheetIndex].Split(new char[]
{
'/'
});
int difficulty = -1;
if (!int.TryParse(array[1], out difficulty))
{
non_fishable_fish = true;
}
}
else
{
non_fishable_fish = true;
}
float fs = 1f;
int minimumSizeContribution = 1 + who.FishingLevel / 2;
fs *= (float)Game1.random.Next(minimumSizeContribution, Math.Max(6, minimumSizeContribution)) / 5f;
fs *= 1.2f;
fs *= 1f + (float)Game1.random.Next(-10, 11) / 100f;
fs = Math.Max(0f, Math.Min(1f, fs));
if(datas != null && !non_fishable_fish)
{
try
{
int minFishSize = int.Parse(datas[3]);
int maxFishSize = int.Parse(datas[4]);
fishSize = (int)((float)minFishSize + (float)(maxFishSize - minFishSize) * fishSize);
fishSize++;
fishQuality = (((double)fishSize < 0.33) ? 0 : (((double)fishSize < 0.66) ? 1 : 2));
if (perfect)
fishQuality *= 2;
}
catch
{
context.Monitor.Log($"Error getting fish size from {data[whichFish]}", LogLevel.Error);
}
}
bossFish = FishingRod.isFishBossFish(whichFish);
caughtDoubleFish = !bossFish && Game1.random.NextDouble() < 0.1 + Game1.player.DailyLuck / 2.0;
context.Monitor.Log($"pulling fish {whichFish} {fishSize} {who.Name} {x},{y}");
if (who.IsLocalPlayer)
{
if (datas != null && !non_fishable_fish)
{
fishDifficulty = int.Parse(datas[1]);
}
else
fishDifficulty = 0;
int experience = Math.Max(1, (fishQuality + 1) * 3 + fishDifficulty / 3);
if (bossFish)
{
experience *= 5;
}
if(perfect)
experience += (int)((float)experience * 1.4f);
who.gainExperience(1, experience);
}
if (who.FacingDirection == 1 || who.FacingDirection == 3)
{
float distance = Vector2.Distance(new Vector2(x, y), who.Position);
float gravity = 0.001f;
float height = 128f - (who.Position.Y - y + 10f);
double angle = 1.1423973285781066;
float yVelocity = (float)((double)(distance * gravity) * Math.Tan(angle) / Math.Sqrt((double)(2f * distance * gravity) * Math.Tan(angle) - (double)(2f * gravity * height)));
if (float.IsNaN(yVelocity))
{
yVelocity = 0.6f;
}
float xVelocity = (float)((double)yVelocity * (1.0 / Math.Tan(angle)));
t = distance / xVelocity;
animations.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, parentSheetIndex, 16, 16), t, 1, 0, new Vector2(x,y), false, false, y / 10000f, 0f, Color.White, 4f, 0f, 0f, 0f, false)
{
motion = new Vector2((float)((who.FacingDirection == 3) ? -1 : 1) * -xVelocity, -yVelocity),
acceleration = new Vector2(0f, gravity),
timeBasedMotion = true,
endFunction = new TemporaryAnimatedSprite.endBehavior(playerCaughtFishEndFunction),
extraInfoForEndBehavior = parentSheetIndex,
endSound = "tinyWhip"
});
if (caughtDoubleFish)
{
distance = Vector2.Distance(new Vector2(x, y), who.Position);
gravity = 0.0008f;
height = 128f - (who.Position.Y - y + 10f);
angle = 1.1423973285781066;
yVelocity = (float)((double)(distance * gravity) * Math.Tan(angle) / Math.Sqrt((double)(2f * distance * gravity) * Math.Tan(angle) - (double)(2f * gravity * height)));
if (float.IsNaN(yVelocity))
{
yVelocity = 0.6f;
}
xVelocity = (float)((double)yVelocity * (1.0 / Math.Tan(angle)));
t = distance / xVelocity;
animations.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, parentSheetIndex, 16, 16), t, 1, 0, new Vector2(x, y), false, false, y / 10000f, 0f, Color.White, 4f, 0f, 0f, 0f, false)
{
motion = new Vector2((float)((who.FacingDirection == 3) ? -1 : 1) * -xVelocity, -yVelocity),
acceleration = new Vector2(0f, gravity),
timeBasedMotion = true,
endSound = "fishSlap",
Parent = who.currentLocation
});
}
}
else
{
float distance2 = y - (float)(who.getStandingY() - 64);
float height2 = Math.Abs(distance2 + 256f + 32f);
if (who.FacingDirection == 0)
{
height2 += 96f;
}
float gravity2 = 0.003f;
float velocity = (float)Math.Sqrt((double)(2f * gravity2 * height2));
t = (float)(Math.Sqrt((double)(2f * (height2 - distance2) / gravity2)) + (double)(velocity / gravity2));
float xVelocity2 = 0f;
if (t != 0f)
{
xVelocity2 = (who.Position.X - x) / t;
}
animations.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, parentSheetIndex, 16, 16), t, 1, 0, new Vector2(x, y), false, false, y / 10000f, 0f, Color.White, 4f, 0f, 0f, 0f, false)
{
motion = new Vector2(xVelocity2, -velocity),
acceleration = new Vector2(0f, gravity2),
timeBasedMotion = true,
endFunction = new TemporaryAnimatedSprite.endBehavior(playerCaughtFishEndFunction),
extraInfoForEndBehavior = parentSheetIndex,
endSound = "tinyWhip"
});
if (caughtDoubleFish)
{
distance2 = y - (float)(who.getStandingY() - 64);
height2 = Math.Abs(distance2 + 256f + 32f);
if (who.FacingDirection == 0)
{
height2 += 96f;
}
gravity2 = 0.004f;
velocity = (float)Math.Sqrt((double)(2f * gravity2 * height2));
t = (float)(Math.Sqrt((double)(2f * (height2 - distance2) / gravity2)) + (double)(velocity / gravity2));
xVelocity2 = 0f;
if (t != 0f)
{
xVelocity2 = (who.Position.X - x) / t;
}
animations.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, parentSheetIndex, 16, 16), t, 1, 0, new Vector2(x, y), false, false, y / 10000f, 0f, Color.White, 4f, 0f, 0f, 0f, false)
{
motion = new Vector2(xVelocity2, -velocity),
acceleration = new Vector2(0f, gravity2),
timeBasedMotion = true,
endSound = "fishSlap",
Parent = who.currentLocation
});
}
}
}
19
Source : Ckfinite.cs
with GNU General Public License v3.0
from Aekras1a
with GNU General Public License v3.0
from Aekras1a
public void Load(DarksVMContext ctx, out ExecutionState state)
{
var sp = ctx.Registers[DarksVMConstants.REG_SP].U4;
var valueSlot = ctx.Stack[sp--];
var fl = ctx.Registers[DarksVMConstants.REG_FL].U1;
if((fl & DarksVMConstants.FL_UNSIGNED) != 0)
{
var v = valueSlot.R4;
if(float.IsNaN(v) || float.IsInfinity(v))
throw new ArithmeticException();
}
else
{
var v = valueSlot.R8;
if(double.IsNaN(v) || double.IsInfinity(v))
throw new ArithmeticException();
}
ctx.Stack.SetTopPosition(sp);
ctx.Registers[DarksVMConstants.REG_SP].U4 = sp;
state = ExecutionState.Next;
}
19
Source : EntityBase.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
public void BecomeDynamic(float mreplaced, Matrix3x3 localInertiaTensor)
{
if (mreplaced <= 0 || float.IsInfinity(mreplaced) || float.IsNaN(mreplaced))
throw new InvalidOperationException("Cannot use a mreplaced of " + mreplaced + " for a dynamic enreplacedy. Consider using a kinematic enreplacedy instead.");
bool previousState = isDynamic;
isDynamic = true;
LocalInertiaTensor = localInertiaTensor;
this.mreplaced = mreplaced;
this.inverseMreplaced = 1 / mreplaced;
//Notify simulation island system of the change.
if (!previousState)
{
if (activityInformation.DeactivationManager != null)
activityInformation.DeactivationManager.AddSimulationIslandToMember(activityInformation);
if (((IForceUpdateable)this).ForceUpdater != null)
((IForceUpdateable)this).ForceUpdater.ForceUpdateableBecomingDynamic(this);
}
//Change the group if it was using the defaults.
if (collisionInformation.CollisionRules.Group == CollisionRules.DefaultKinematicCollisionGroup ||
collisionInformation.CollisionRules.Group == null)
collisionInformation.CollisionRules.Group = CollisionRules.DefaultDynamicCollisionGroup;
activityInformation.Activate();
//Preserve velocity and reinitialize momentum for new state.
LinearVelocity = linearVelocity;
AngularVelocity = angularVelocity;
}
19
Source : MathChecker.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
private static bool IsInvalid(float f)
{
return float.IsNaN(f) || float.IsInfinity(f);
}
19
Source : TsonSerializer.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public void Write(byte index, float value)
{
if (float.IsNaN(value))
return;
WriteIndex(index);
Write(value);
}
19
Source : Body.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
public void ApplyForce(ref Vector2 force, ref Vector2 point)
{
Debug.replacedert(!float.IsNaN(force.X));
Debug.replacedert(!float.IsNaN(force.Y));
Debug.replacedert(!float.IsNaN(point.X));
Debug.replacedert(!float.IsNaN(point.Y));
if (_bodyType == BodyType.Dynamic)
{
if (Awake == false)
{
Awake = true;
}
_force += force;
_torque += (point.X - _sweep.C.X) * force.Y - (point.Y - _sweep.C.Y) * force.X;
}
}
19
Source : Body.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
public void ApplyTorque(float torque)
{
Debug.replacedert(!float.IsNaN(torque));
if (_bodyType == BodyType.Dynamic)
{
if (Awake == false)
{
Awake = true;
}
_torque += torque;
}
}
19
Source : Math.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
public static bool IsValid(float x)
{
if (float.IsNaN(x))
{
// NaN.
return false;
}
return !float.IsInfinity(x);
}
19
Source : MathChecker.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
[Conditional("CHECKMATH")]
public static void Validate(this Vector<float> f, int laneCount = -1)
{
if (laneCount < -1 || laneCount > Vector<float>.Count)
throw new ArgumentException("Invalid lane count.");
if (laneCount == -1)
laneCount = Vector<float>.Count;
ref var casted = ref Unsafe.As<Vector<float>, float>(ref f);
for (int i = 0; i < laneCount; ++i)
{
var value = Unsafe.Add(ref casted, i);
if (float.IsNaN(value) || float.IsInfinity(value))
{
throw new InvalidOperationException($"Invalid floating point value: {value}.");
}
}
}
19
Source : MathChecker.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
[Conditional("CHECKMATH")]
public static void Validate(this Vector<float> f, Vector<int> lanesToTest)
{
ref var castedValues = ref Unsafe.As<Vector<float>, float>(ref f);
ref var castedMask = ref Unsafe.As<Vector<int>, int>(ref lanesToTest);
for (int i = 0; i < Vector<float>.Count; ++i)
{
var mask = Unsafe.Add(ref castedMask, i);
if (mask != 0)
{
var value = Unsafe.Add(ref castedValues, i);
if (float.IsNaN(value) || float.IsInfinity(value))
{
throw new InvalidOperationException($"Invalid floating point value: {value}.");
}
}
}
}
19
Source : SimpleExplosion.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
private float GetPercent(float distance, float radius)
{
//(1-(distance/radius))^power-1
float percent = (float)Math.Pow(1 - ((distance - radius) / radius), Power) - 1;
if (float.IsNaN(percent))
return 0f;
return MathHelper.Clamp(percent, 0f, 1f);
}
19
Source : Sampler.cs
with MIT License
from alelievr
with MIT License
from alelievr
public void ResizeIfNeeded(int size, float step)
{
if (step < 0 || step > maxStep || Single.IsNaN(step))
return ;
if (NeedResize(size, step))
Resize(size, step);
}
19
Source : NodeCurve.cs
with MIT License
from alelievr
with MIT License
from alelievr
public void CurveTerrain()
{
if (inputTerrain == null)
return ;
Sampler samp = inputTerrain.Clone(outputTerrain);
if (samp.type == SamplerType.Sampler2D)
{
float d = samp.max - samp.min;
(samp as Sampler2D).Foreach((x, y, val) => {
if (float.IsNaN(val))
return 0;
return curve.Evaluate(val / d) * d;
});
}
else if (samp.type == SamplerType.Sampler3D)
{
float d = samp.max - samp.min;
(samp as Sampler3D).Foreach((x, y, z, val) => {
if (float.IsNaN(val))
return 0;
return curve.Evaluate(val / d) * d;
});
}
outputTerrain = samp;
}
19
Source : MixtureEditorUtils.cs
with MIT License
from alelievr
with MIT License
from alelievr
public static void ScheduleAutoHide(VisualElement target, MixtureGraphView view)
{
target.schedule.Execute(() => {
target.visible = float.IsNaN(target.worldBound.x) || target.worldBound.Overlaps(view.worldBound);
}).Every(16); // refresh the visible for 60hz screens (should not cause problems for higher refresh rates)
}
19
Source : JsonSerializer.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
private void WriteValue(object obj)
{
if (obj == null || obj is DBNull)
_output.Append("null");
else if (obj is string || obj is char)
WriteString(obj.ToString());
else if (obj is Guid)
WriteGuid((Guid)obj);
else if (obj is bool)
_output.Append(((bool)obj) ? "true" : "false"); // conform to standard
else if (
obj is int || obj is long ||
obj is decimal ||
obj is byte || obj is short ||
obj is sbyte || obj is ushort ||
obj is uint || obj is ulong
)
_output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo));
else if (obj is double || obj is Double)
{
double d = (double)obj;
if (double.IsNaN(d))
_output.Append("\"NaN\"");
else if (double.IsInfinity(d))
{
_output.Append("\"");
_output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo));
_output.Append("\"");
}
else
_output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo));
}
else if (obj is float || obj is Single)
{
float d = (float)obj;
if (float.IsNaN(d))
_output.Append("\"NaN\"");
else if (float.IsInfinity(d))
{
_output.Append("\"");
_output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo));
_output.Append("\"");
}
else
_output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo));
}
else if (obj is DateTime)
WriteDateTime((DateTime)obj);
else if (obj is DateTimeOffset)
WriteDateTimeOffset((DateTimeOffset)obj);
else if (obj is TimeSpan)
_output.Append(((TimeSpan)obj).Ticks);
else if (_params.KVStyleStringDictionary == false &&
obj is IEnumerable<KeyValuePair<string, object>>)
WriteStringDictionary((IEnumerable<KeyValuePair<string, object>>)obj);
else if (_params.KVStyleStringDictionary == false && obj is IDictionary &&
obj.GetType().IsGenericType && Reflection.Instance.GetGenericArguments(obj.GetType())[0] == typeof(string))
WriteStringDictionary((IDictionary)obj);
else if (obj is IDictionary)
WriteDictionary((IDictionary)obj);
#if !SILVERLIGHT
else if (obj is DataSet)
WriteDataset((DataSet)obj);
else if (obj is DataTable)
this.WriteDataTable((DataTable)obj);
#endif
else if (obj is byte[])
WriteBytes((byte[])obj);
else if (obj is StringDictionary)
WriteSD((StringDictionary)obj);
else if (obj is NameValueCollection)
WriteNV((NameValueCollection)obj);
else if (obj is IEnumerable)
WriteArray((IEnumerable)obj);
else if (obj is Enum)
WriteEnum((Enum)obj);
else if (Reflection.Instance.IsTypeRegistered(obj.GetType()))
WriteCustom(obj);
else
WriteObject(obj);
}
19
Source : MessagePackSecurity.cs
with Apache License 2.0
from allenai
with Apache License 2.0
from allenai
public override unsafe int GetHashCode(float value)
{
// Special check for 0.0 so that the hash of 0.0 and -0.0 will equal.
if (value == 0.0f)
{
return HashCode.Combine(0);
}
// Standardize on the binary representation of NaN prior to hashing.
if (float.IsNaN(value))
{
value = float.NaN;
}
long l = *(long*)&value;
return HashCode.Combine((int)(l >> 32), unchecked((int)l));
}
19
Source : SurfRampMeshGenerator.cs
with MIT License
from ambid17
with MIT License
from ambid17
private Vector3[] GenerateVertices()
{
List<Vector3> vertices = new List<Vector3>();
for (int i = 0; i <= numberOfSections; i++)
{
Vector3 currentPoint = CalculateQuadraticBezierPoint(i, startPoint, endPoint, controlPoint);
Vector3 left = currentPoint;
Vector3 right = currentPoint;
if (i == 0)
{
Vector3 nextPoint = CalculateQuadraticBezierPoint(i + 1, startPoint, endPoint, controlPoint);
float angle = Mathf.Atan2((nextPoint.z - currentPoint.z), (nextPoint.x - currentPoint.x));
float sin = Mathf.Sin(angle);
float cos = Mathf.Cos(angle);
if (float.IsNaN(angle))
{
angle = 0;
}
if (angle < 0)
{
angle += 360;
}
left.x -= sin * rampLeftWidth;
left.z += cos * rampLeftWidth;
right.x += sin * rampRightWidth;
right.z -= cos * rampRightWidth;
left.y -= rampHeight;
right.y -= rampHeight;
} else
{
Vector3 previousPoint = CalculateQuadraticBezierPoint(i - 1, startPoint, endPoint, controlPoint);
float angle = Mathf.Atan2((currentPoint.z - previousPoint.z), (currentPoint.x - previousPoint.x));
float sin = Mathf.Sin(angle);
float cos = Mathf.Cos(angle);
if (float.IsNaN(angle))
{
angle = 0;
}
if (angle < 0)
{
angle += 360;
}
left.x -= Mathf.Sin(angle) * rampLeftWidth;
left.z += Mathf.Cos(angle) * rampLeftWidth;
right.x += Mathf.Sin(angle) * rampRightWidth;
right.z -= Mathf.Cos(angle) * rampRightWidth;
left.y -= rampHeight;
right.y -= rampHeight;
}
vertices.Add(currentPoint);
vertices.Add(left);
vertices.Add(right);
}
return vertices.ToArray();
}
19
Source : PackHelpers.cs
with MIT License
from amerkoleci
with MIT License
from amerkoleci
private static float ClampAndRound(float value, float min, float max)
{
if (float.IsNaN(value))
{
return 0.0f;
}
if (float.IsInfinity(value))
{
return float.IsNegativeInfinity(value) ? min : max;
}
if (value < min)
{
return min;
}
if (value > max)
{
return max;
}
return MathF.Round(value);
}
19
Source : Vertex.cs
with MIT License
from anderm
with MIT License
from anderm
private static Vertex Create(float x, float y) {
if (float.IsNaN(x) || float.IsNaN(y)) {
return VERTEX_AT_INFINITY;
}
if (pool.Count > 0) {
return pool.Dequeue().Init(x,y);
} else {
return new Vertex(x,y);
}
}
19
Source : CustomExtensions.cs
with MIT License
from andruzzzhka
with MIT License
from andruzzzhka
public static bool IsRotNaN(this PlayerUpdate _info)
{
return float.IsNaN(_info.headRot.x) || float.IsNaN(_info.headRot.y) || float.IsNaN(_info.headRot.z) || float.IsNaN(_info.headRot.w) ||
float.IsNaN(_info.leftHandRot.x) || float.IsNaN(_info.leftHandRot.y) || float.IsNaN(_info.leftHandRot.z) || float.IsNaN(_info.leftHandRot.w) ||
float.IsNaN(_info.rightHandRot.x) || float.IsNaN(_info.rightHandRot.y) || float.IsNaN(_info.rightHandRot.z) || float.IsNaN(_info.rightHandRot.w);
}
19
Source : AnnotationPositionChanging.cs
with MIT License
from AngeloCresta
with MIT License
from AngeloCresta
private void Chart1_AnnotationPositionChanging(object sender, System.Windows.Forms.DataVisualization.Charting.AnnotationPositionChangingEventArgs e)
{
if(SnapToDataPoint.Checked)
{
// get the annotation object from the AnnotationPositionChangingEventArgs
Annotation annotation = e.Annotation;
if(!float.IsNaN(e.NewAnchorLocation.X))
{
// get the nearest point to the new location
PointF point = FindNearestDataPoint(e.NewAnchorLocation.X, e.NewAnchorLocation.Y);
annotation.AnchorDataPoint = Chart1.Series[0].Points[(int)point.X - 1];
e.NewAnchorLocationX= point.X;
e.NewAnchorLocationY = point.Y;
}
}
else
{
if(!float.IsNaN(e.NewAnchorLocation.X) && e.NewAnchorLocation.X > Chart1.ChartAreas[0].AxisX.Maximum)
{
e.NewAnchorLocationX = (float)(Chart1.ChartAreas[0].AxisX.Maximum);
}
else if(!float.IsNaN(e.NewAnchorLocation.X) && e.NewAnchorLocation.X < Chart1.ChartAreas[0].AxisX.Minimum)
{
e.NewAnchorLocationX = 0;
}
if(!float.IsNaN(e.NewAnchorLocation.X) && e.NewAnchorLocation.Y > Chart1.ChartAreas[0].AxisY.Maximum)
{
e.NewAnchorLocationY = (float)(Chart1.ChartAreas[0].AxisY.Maximum);
}
else if(!float.IsNaN(e.NewAnchorLocation.Y) && e.NewAnchorLocation.Y < 1)
{
e.NewAnchorLocationY = 1;
}
}
}
19
Source : LineAnnotation.cs
with MIT License
from AngeloCresta
with MIT License
from AngeloCresta
override internal void Paint(Chart chart, ChartGraphics graphics)
{
// Get annotation position in relative coordinates
PointF firstPoint = PointF.Empty;
PointF anchorPoint = PointF.Empty;
SizeF size = SizeF.Empty;
GetRelativePosition(out firstPoint, out size, out anchorPoint);
PointF secondPoint = new PointF(firstPoint.X + size.Width, firstPoint.Y + size.Height);
// Create selection rectangle
RectangleF selectionRect = new RectangleF(firstPoint, new SizeF(secondPoint.X - firstPoint.X, secondPoint.Y - firstPoint.Y));
// Adjust coordinates
AdjustLineCoordinates(ref firstPoint, ref secondPoint, ref selectionRect);
// Check if text position is valid
if( float.IsNaN(firstPoint.X) ||
float.IsNaN(firstPoint.Y) ||
float.IsNaN(secondPoint.X) ||
float.IsNaN(secondPoint.Y) )
{
return;
}
// Set line caps
bool capChanged = false;
LineCap oldStartCap = LineCap.Flat;
LineCap oldEndCap = LineCap.Flat;
if(this._startCap != LineAnchorCapStyle.None ||
this._endCap != LineAnchorCapStyle.None)
{
capChanged = true;
oldStartCap = graphics.Pen.StartCap;
oldEndCap = graphics.Pen.EndCap;
// Apply anchor cap settings
if(this._startCap == LineAnchorCapStyle.Arrow)
{
// Adjust arrow size for small line width
if(this.LineWidth < 4)
{
int adjustment = 3 - this.LineWidth;
graphics.Pen.StartCap = LineCap.Custom;
graphics.Pen.CustomStartCap = new AdjustableArrowCap(
this.LineWidth + adjustment,
this.LineWidth + adjustment,
true);
}
else
{
graphics.Pen.StartCap = LineCap.ArrowAnchor;
}
}
else if(this._startCap == LineAnchorCapStyle.Diamond)
{
graphics.Pen.StartCap = LineCap.DiamondAnchor;
}
else if(this._startCap == LineAnchorCapStyle.Round)
{
graphics.Pen.StartCap = LineCap.RoundAnchor;
}
else if(this._startCap == LineAnchorCapStyle.Square)
{
graphics.Pen.StartCap = LineCap.SquareAnchor;
}
if(this._endCap == LineAnchorCapStyle.Arrow)
{
// Adjust arrow size for small line width
if(this.LineWidth < 4)
{
int adjustment = 3 - this.LineWidth;
graphics.Pen.EndCap = LineCap.Custom;
graphics.Pen.CustomEndCap = new AdjustableArrowCap(
this.LineWidth + adjustment,
this.LineWidth + adjustment,
true);
}
else
{
graphics.Pen.EndCap = LineCap.ArrowAnchor;
}
}
else if(this._endCap == LineAnchorCapStyle.Diamond)
{
graphics.Pen.EndCap = LineCap.DiamondAnchor;
}
else if(this._endCap == LineAnchorCapStyle.Round)
{
graphics.Pen.EndCap = LineCap.RoundAnchor;
}
else if(this._endCap == LineAnchorCapStyle.Square)
{
graphics.Pen.EndCap = LineCap.SquareAnchor;
}
}
if(this.Common.ProcessModePaint)
{
// Draw line
graphics.DrawLineRel(
this.LineColor,
this.LineWidth,
this.LineDashStyle,
firstPoint,
secondPoint,
this.ShadowColor,
this.ShadowOffset);
}
if(this.Common.ProcessModeRegions)
{
// Create line graphics path
using (GraphicsPath path = new GraphicsPath())
{
path.AddLine(
graphics.GetAbsolutePoint(firstPoint),
graphics.GetAbsolutePoint(secondPoint));
using (Pen pen = (Pen)graphics.Pen.Clone())
{
// Increase pen size by 2 pixels
pen.DashStyle = DashStyle.Solid;
pen.Width += 2;
try
{
path.Widen(pen);
}
catch (OutOfMemoryException)
{
// GraphicsPath.Widen incorrectly throws OutOfMemoryException
// catching here and reacting by not widening
}
catch (ArgumentException)
{
}
}
// Add hot region
this.Common.HotRegionsList.AddHotRegion(
graphics,
path,
false,
ReplaceKeywords(this.ToolTip),
String.Empty,
String.Empty,
String.Empty,
this,
ChartElementType.Annotation);
}
}
// Restore line caps
if(capChanged)
{
graphics.Pen.StartCap = oldStartCap;
graphics.Pen.EndCap = oldEndCap;
}
// Paint selection handles
PaintSelectionHandles(graphics, selectionRect, null);
}
19
Source : PolygonAnnotation.cs
with MIT License
from AngeloCresta
with MIT License
from AngeloCresta
override internal void Paint(Chart chart, ChartGraphics graphics)
{
// Check for empty path
if(_graphicsPath.PointCount == 0)
{
return;
}
// Get annotation position in relative coordinates
PointF firstPoint = PointF.Empty;
PointF anchorPoint = PointF.Empty;
SizeF size = SizeF.Empty;
GetRelativePosition(out firstPoint, out size, out anchorPoint);
PointF secondPoint = new PointF(firstPoint.X + size.Width, firstPoint.Y + size.Height);
// Create selection rectangle
RectangleF selectionRect = new RectangleF(firstPoint, new SizeF(secondPoint.X - firstPoint.X, secondPoint.Y - firstPoint.Y));
// Get position
RectangleF rectanglePosition = new RectangleF(selectionRect.Location, selectionRect.Size);
if(rectanglePosition.Width < 0)
{
rectanglePosition.X = rectanglePosition.Right;
rectanglePosition.Width = -rectanglePosition.Width;
}
if(rectanglePosition.Height < 0)
{
rectanglePosition.Y = rectanglePosition.Bottom;
rectanglePosition.Height = -rectanglePosition.Height;
}
// Check if position is valid
if( float.IsNaN(rectanglePosition.X) ||
float.IsNaN(rectanglePosition.Y) ||
float.IsNaN(rectanglePosition.Right) ||
float.IsNaN(rectanglePosition.Bottom) )
{
return;
}
// Get annotation absolute position
RectangleF rectanglePositionAbs = graphics.GetAbsoluteRectangle(rectanglePosition);
// Calculate scaling
float groupScaleX = rectanglePositionAbs.Width / 100.0f;
float groupScaleY = rectanglePositionAbs.Height / 100.0f;
// Convert path to pixel coordinates
PointF[] pathPoints = _graphicsPath.PathPoints;
byte[] pathTypes = _graphicsPath.PathTypes;
for(int pointIndex = 0; pointIndex < pathPoints.Length; pointIndex++)
{
pathPoints[pointIndex].X = rectanglePositionAbs.X + pathPoints[pointIndex].X * groupScaleX;
pathPoints[pointIndex].Y = rectanglePositionAbs.Y + pathPoints[pointIndex].Y * groupScaleY;
}
using (GraphicsPath pathAbs = new GraphicsPath(pathPoints, pathTypes))
{
// Set line caps
bool capChanged = false;
LineCap oldStartCap = LineCap.Flat;
LineCap oldEndCap = LineCap.Flat;
if (!this.isPolygon)
{
if (this._startCap != LineAnchorCapStyle.None ||
this._endCap != LineAnchorCapStyle.None)
{
capChanged = true;
oldStartCap = graphics.Pen.StartCap;
oldEndCap = graphics.Pen.EndCap;
// Apply anchor cap settings
if (this._startCap == LineAnchorCapStyle.Arrow)
{
// Adjust arrow size for small line width
if (this.LineWidth < 4)
{
int adjustment = 3 - this.LineWidth;
graphics.Pen.StartCap = LineCap.Custom;
graphics.Pen.CustomStartCap = new AdjustableArrowCap(
this.LineWidth + adjustment,
this.LineWidth + adjustment,
true);
}
else
{
graphics.Pen.StartCap = LineCap.ArrowAnchor;
}
}
else if (this._startCap == LineAnchorCapStyle.Diamond)
{
graphics.Pen.StartCap = LineCap.DiamondAnchor;
}
else if (this._startCap == LineAnchorCapStyle.Round)
{
graphics.Pen.StartCap = LineCap.RoundAnchor;
}
else if (this._startCap == LineAnchorCapStyle.Square)
{
graphics.Pen.StartCap = LineCap.SquareAnchor;
}
if (this._endCap == LineAnchorCapStyle.Arrow)
{
// Adjust arrow size for small line width
if (this.LineWidth < 4)
{
int adjustment = 3 - this.LineWidth;
graphics.Pen.EndCap = LineCap.Custom;
graphics.Pen.CustomEndCap = new AdjustableArrowCap(
this.LineWidth + adjustment,
this.LineWidth + adjustment,
true);
}
else
{
graphics.Pen.EndCap = LineCap.ArrowAnchor;
}
}
else if (this._endCap == LineAnchorCapStyle.Diamond)
{
graphics.Pen.EndCap = LineCap.DiamondAnchor;
}
else if (this._endCap == LineAnchorCapStyle.Round)
{
graphics.Pen.EndCap = LineCap.RoundAnchor;
}
else if (this._endCap == LineAnchorCapStyle.Square)
{
graphics.Pen.EndCap = LineCap.SquareAnchor;
}
}
}
// Painting mode
if (this.Common.ProcessModePaint)
{
if (this.isPolygon)
{
// Draw polygon
pathAbs.CloseAllFigures();
graphics.DrawPathAbs(
pathAbs,
this.BackColor,
this.BackHatchStyle,
String.Empty,
ChartImageWrapMode.Scaled,
Color.Empty,
ChartImageAlignmentStyle.Center,
this.BackGradientStyle,
this.BackSecondaryColor,
this.LineColor,
this.LineWidth,
this.LineDashStyle,
PenAlignment.Center,
this.ShadowOffset,
this.ShadowColor);
}
else
{
// Draw polyline
graphics.DrawPathAbs(
pathAbs,
Color.Transparent,
ChartHatchStyle.None,
String.Empty,
ChartImageWrapMode.Scaled,
Color.Empty,
ChartImageAlignmentStyle.Center,
GradientStyle.None,
Color.Empty,
this.LineColor,
this.LineWidth,
this.LineDashStyle,
PenAlignment.Center,
this.ShadowOffset,
this.ShadowColor);
}
}
if (this.Common.ProcessModeRegions)
{
// Create line graphics path
GraphicsPath selectionPath = null;
GraphicsPath newPath = null;
if (this.isPolygon)
{
selectionPath = pathAbs;
}
else
{
newPath = new GraphicsPath();
selectionPath = newPath;
selectionPath.AddPath(pathAbs, false);
using (Pen pen = (Pen)graphics.Pen.Clone())
{
// Increase pen size by 2 pixels
pen.DashStyle = DashStyle.Solid;
pen.Width += 2;
try
{
selectionPath.Widen(pen);
}
catch (OutOfMemoryException)
{
// GraphicsPath.Widen incorrectly throws OutOfMemoryException
// catching here and reacting by not widening
}
catch (ArgumentException)
{
}
}
}
// Add hot region
this.Common.HotRegionsList.AddHotRegion(
graphics,
selectionPath,
false,
ReplaceKeywords(this.ToolTip),
String.Empty,
String.Empty,
String.Empty,
this,
ChartElementType.Annotation);
//Clean up
if (newPath != null)
newPath.Dispose();
}
// Restore line caps
if (capChanged)
{
graphics.Pen.StartCap = oldStartCap;
graphics.Pen.EndCap = oldEndCap;
}
// Paint selection handles
PaintSelectionHandles(graphics, rectanglePosition, pathAbs);
}
}
19
Source : ImageAnnotation.cs
with MIT License
from AngeloCresta
with MIT License
from AngeloCresta
override internal void Paint(Chart chart, ChartGraphics graphics)
{
// Get annotation position in relative coordinates
PointF firstPoint = PointF.Empty;
PointF anchorPoint = PointF.Empty;
SizeF size = SizeF.Empty;
GetRelativePosition(out firstPoint, out size, out anchorPoint);
PointF secondPoint = new PointF(firstPoint.X + size.Width, firstPoint.Y + size.Height);
// Create selection rectangle
RectangleF selectionRect = new RectangleF(firstPoint, new SizeF(secondPoint.X - firstPoint.X, secondPoint.Y - firstPoint.Y));
// Get position
RectangleF rectanglePosition = new RectangleF(selectionRect.Location, selectionRect.Size);
if(rectanglePosition.Width < 0)
{
rectanglePosition.X = rectanglePosition.Right;
rectanglePosition.Width = -rectanglePosition.Width;
}
if(rectanglePosition.Height < 0)
{
rectanglePosition.Y = rectanglePosition.Bottom;
rectanglePosition.Height = -rectanglePosition.Height;
}
// Check if position is valid
if( float.IsNaN(rectanglePosition.X) ||
float.IsNaN(rectanglePosition.Y) ||
float.IsNaN(rectanglePosition.Right) ||
float.IsNaN(rectanglePosition.Bottom) )
{
return;
}
if(this.Common.ProcessModePaint)
{
// Draw "empty" image at design time
if(this._imageName.Length == 0 && this.Chart.IsDesignMode() )
{
graphics.FillRectangleRel(
rectanglePosition,
this.BackColor,
this.BackHatchStyle,
this._imageName,
this._imageWrapMode,
this._imageTransparentColor,
GetImageAlignment(this.Alignment),
this.BackGradientStyle,
this.BackSecondaryColor,
this.LineColor,
this.LineWidth,
this.LineDashStyle,
this.ShadowColor,
this.ShadowOffset,
PenAlignment.Center);
// Draw text
using( Brush textBrush = new SolidBrush(this.ForeColor) )
{
using (StringFormat format = new StringFormat(StringFormat.GenericTypographic))
{
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
format.FormatFlags = StringFormatFlags.LineLimit;
format.Trimming = StringTrimming.EllipsisCharacter;
graphics.DrawStringRel(
"(no image)",
this.Font,
textBrush,
rectanglePosition,
format);
}
}
}
else
{
// Draw image
graphics.FillRectangleRel(
rectanglePosition,
Color.Transparent,
this.BackHatchStyle,
this._imageName,
this._imageWrapMode,
this._imageTransparentColor,
GetImageAlignment(this.Alignment),
this.BackGradientStyle,
Color.Transparent,
Color.Transparent,
0,
this.LineDashStyle,
this.ShadowColor,
this.ShadowOffset,
PenAlignment.Center);
}
}
if(this.Common.ProcessModeRegions)
{
// Add hot region
this.Common.HotRegionsList.AddHotRegion(
rectanglePosition,
ReplaceKeywords(this.ToolTip),
String.Empty,
String.Empty,
String.Empty,
this,
ChartElementType.Annotation,
String.Empty);
}
// Paint selection handles
PaintSelectionHandles(graphics, selectionRect, null);
}
19
Source : RectangleAnnotation.cs
with MIT License
from AngeloCresta
with MIT License
from AngeloCresta
override internal void Paint(Chart chart, ChartGraphics graphics)
{
// Get annotation position in relative coordinates
PointF firstPoint = PointF.Empty;
PointF anchorPoint = PointF.Empty;
SizeF size = SizeF.Empty;
GetRelativePosition(out firstPoint, out size, out anchorPoint);
PointF secondPoint = new PointF(firstPoint.X + size.Width, firstPoint.Y + size.Height);
// Create selection rectangle
RectangleF selectionRect = new RectangleF(firstPoint, new SizeF(secondPoint.X - firstPoint.X, secondPoint.Y - firstPoint.Y));
// Get text position
RectangleF rectanglePosition = new RectangleF(selectionRect.Location, selectionRect.Size);
if(rectanglePosition.Width < 0)
{
rectanglePosition.X = rectanglePosition.Right;
rectanglePosition.Width = -rectanglePosition.Width;
}
if(rectanglePosition.Height < 0)
{
rectanglePosition.Y = rectanglePosition.Bottom;
rectanglePosition.Height = -rectanglePosition.Height;
}
// Check if position is valid
if( float.IsNaN(rectanglePosition.X) ||
float.IsNaN(rectanglePosition.Y) ||
float.IsNaN(rectanglePosition.Right) ||
float.IsNaN(rectanglePosition.Bottom) )
{
return;
}
if(this.isRectVisible &&
this.Common.ProcessModePaint)
{
// Draw rectangle
graphics.FillRectangleRel(
rectanglePosition,
this.BackColor,
this.BackHatchStyle,
String.Empty,
ChartImageWrapMode.Scaled,
Color.Empty,
ChartImageAlignmentStyle.Center,
this.BackGradientStyle,
this.BackSecondaryColor,
this.LineColor,
this.LineWidth,
this.LineDashStyle,
this.ShadowColor,
this.ShadowOffset,
PenAlignment.Center,
this.isEllipse,
1,
false);
}
// Call base clreplaced to paint text, selection handles and process hot regions
base.Paint(chart, graphics);
}
19
Source : RectangleAnnotation.cs
with MIT License
from AngeloCresta
with MIT License
from AngeloCresta
override internal void Paint(Chart chart, ChartGraphics graphics)
{
// Get annotation position in relative coordinates
PointF firstPoint = PointF.Empty;
PointF anchorPoint = PointF.Empty;
SizeF size = SizeF.Empty;
GetRelativePosition(out firstPoint, out size, out anchorPoint);
PointF secondPoint = new PointF(firstPoint.X + size.Width, firstPoint.Y + size.Height);
// Create selection rectangle
RectangleF selectionRect = new RectangleF(firstPoint, new SizeF(secondPoint.X - firstPoint.X, secondPoint.Y - firstPoint.Y));
// Get text position
RectangleF rectanglePosition = new RectangleF(selectionRect.Location, selectionRect.Size);
if(rectanglePosition.Width < 0)
{
rectanglePosition.X = rectanglePosition.Right;
rectanglePosition.Width = -rectanglePosition.Width;
}
if(rectanglePosition.Height < 0)
{
rectanglePosition.Y = rectanglePosition.Bottom;
rectanglePosition.Height = -rectanglePosition.Height;
}
// Check if position is valid
if( float.IsNaN(rectanglePosition.X) ||
float.IsNaN(rectanglePosition.Y) ||
float.IsNaN(rectanglePosition.Right) ||
float.IsNaN(rectanglePosition.Bottom) )
{
return;
}
if(this.Common.ProcessModePaint)
{
// Do not draw border if size is less that 10 pixels
RectangleF absRectanglePosition = graphics.GetAbsoluteRectangle(rectanglePosition);
if(absRectanglePosition.Width > 30f &&
absRectanglePosition.Height > 30f)
{
// Draw rectangle
graphics.Draw3DBorderRel(
_borderSkin,
rectanglePosition,
this.BackColor,
this.BackHatchStyle,
String.Empty,
ChartImageWrapMode.Scaled,
Color.Empty,
ChartImageAlignmentStyle.Center,
this.BackGradientStyle,
this.BackSecondaryColor,
this.LineColor,
this.LineWidth,
this.LineDashStyle);
}
}
// Call base clreplaced to paint text, selection handles and process hot regions
base.Paint(chart, graphics);
}
19
Source : TextAnnotation.cs
with MIT License
from AngeloCresta
with MIT License
from AngeloCresta
override internal void Paint(Chart chart, ChartGraphics graphics)
{
// Get annotation position in relative coordinates
PointF firstPoint = PointF.Empty;
PointF anchorPoint = PointF.Empty;
SizeF size = SizeF.Empty;
GetRelativePosition(out firstPoint, out size, out anchorPoint);
PointF secondPoint = new PointF(firstPoint.X + size.Width, firstPoint.Y + size.Height);
// Create selection rectangle
RectangleF selectionRect = new RectangleF(firstPoint, new SizeF(secondPoint.X - firstPoint.X, secondPoint.Y - firstPoint.Y));
// Get text position
RectangleF textPosition = new RectangleF(selectionRect.Location, selectionRect.Size);
if(textPosition.Width < 0)
{
textPosition.X = textPosition.Right;
textPosition.Width = -textPosition.Width;
}
if(textPosition.Height < 0)
{
textPosition.Y = textPosition.Bottom;
textPosition.Height = -textPosition.Height;
}
// Check if text position is valid
if( textPosition.IsEmpty ||
float.IsNaN(textPosition.X) ||
float.IsNaN(textPosition.Y) ||
float.IsNaN(textPosition.Right) ||
float.IsNaN(textPosition.Bottom) )
{
return;
}
if(this.Common.ProcessModePaint)
{
DrawText(graphics, textPosition, false, false);
}
if(this.Common.ProcessModeRegions)
{
// Add hot region
if(isEllipse)
{
using (GraphicsPath ellipsePath = new GraphicsPath())
{
ellipsePath.AddEllipse(textPosition);
this.Common.HotRegionsList.AddHotRegion(
graphics,
ellipsePath,
true,
ReplaceKeywords(this.ToolTip),
String.Empty,
String.Empty,
String.Empty,
this,
ChartElementType.Annotation);
}
}
else
{
this.Common.HotRegionsList.AddHotRegion(
textPosition,
ReplaceKeywords(this.ToolTip),
String.Empty,
String.Empty,
String.Empty,
this,
ChartElementType.Annotation,
String.Empty);
}
}
// Paint selection handles
PaintSelectionHandles(graphics, selectionRect, null);
}
19
Source : ArrowAnnotation.cs
with MIT License
from AngeloCresta
with MIT License
from AngeloCresta
override internal void Paint(Chart chart, ChartGraphics graphics)
{
// Get annotation position in relative coordinates
PointF firstPoint = PointF.Empty;
PointF anchorPoint = PointF.Empty;
SizeF size = SizeF.Empty;
GetRelativePosition(out firstPoint, out size, out anchorPoint);
PointF secondPoint = new PointF(firstPoint.X + size.Width, firstPoint.Y + size.Height);
// Create selection rectangle
RectangleF selectionRect = new RectangleF(firstPoint, new SizeF(secondPoint.X - firstPoint.X, secondPoint.Y - firstPoint.Y));
// Check if text position is valid
if( float.IsNaN(firstPoint.X) ||
float.IsNaN(firstPoint.Y) ||
float.IsNaN(secondPoint.X) ||
float.IsNaN(secondPoint.Y) )
{
return;
}
// Get arrow shape path
using (GraphicsPath arrowPathAbs = GetArrowPath(graphics, selectionRect))
{
// Draw arrow shape
if (this.Common.ProcessModePaint)
{
graphics.DrawPathAbs(
arrowPathAbs,
(this.BackColor.IsEmpty) ? Color.White : this.BackColor,
this.BackHatchStyle,
String.Empty,
ChartImageWrapMode.Scaled,
Color.Empty,
ChartImageAlignmentStyle.Center,
this.BackGradientStyle,
this.BackSecondaryColor,
this.LineColor,
this.LineWidth,
this.LineDashStyle,
PenAlignment.Center,
this.ShadowOffset,
this.ShadowColor);
}
// Process hot region
if (this.Common.ProcessModeRegions)
{
// Use callout defined hot region
this.Common.HotRegionsList.AddHotRegion(
graphics,
arrowPathAbs,
false,
ReplaceKeywords(this.ToolTip),
String.Empty,
String.Empty,
String.Empty,
this,
ChartElementType.Annotation);
}
// Paint selection handles
PaintSelectionHandles(graphics, selectionRect, null);
}
}
19
Source : GroupAnnotation.cs
with MIT License
from AngeloCresta
with MIT License
from AngeloCresta
override internal void Paint(Chart chart, ChartGraphics graphics)
{
// Paint all annotations in the group
foreach(Annotation annotation in this.annotations)
{
annotation.Paint(chart, graphics);
}
if( (this.Common.ProcessModePaint && this.IsSelected) ||
this.Common.ProcessModeRegions )
{
// Get annotation position in relative coordinates
PointF firstPoint = PointF.Empty;
PointF anchorPoint = PointF.Empty;
SizeF size = SizeF.Empty;
GetRelativePosition(out firstPoint, out size, out anchorPoint);
PointF secondPoint = new PointF(firstPoint.X + size.Width, firstPoint.Y + size.Height);
// Create selection rectangle
RectangleF selectionRect = new RectangleF(firstPoint, new SizeF(secondPoint.X - firstPoint.X, secondPoint.Y - firstPoint.Y));
// Check rectangle orientation
if(selectionRect.Width < 0)
{
selectionRect.X = selectionRect.Right;
selectionRect.Width = -selectionRect.Width;
}
if(selectionRect.Height < 0)
{
selectionRect.Y = selectionRect.Bottom;
selectionRect.Height = -selectionRect.Height;
}
// Check if text position is valid
if( selectionRect.IsEmpty ||
float.IsNaN(selectionRect.X) ||
float.IsNaN(selectionRect.Y) ||
float.IsNaN(selectionRect.Right) ||
float.IsNaN(selectionRect.Bottom) )
{
return;
}
if(this.Common.ProcessModeRegions)
{
// Add hot region
this.Common.HotRegionsList.AddHotRegion(
selectionRect,
ReplaceKeywords(this.ToolTip),
String.Empty,
String.Empty,
String.Empty,
this,
ChartElementType.Annotation,
String.Empty);
}
// Paint selection handles
PaintSelectionHandles(graphics, selectionRect, null);
}
}
19
Source : GridMath.cs
with Apache License 2.0
from anmcgrath
with Apache License 2.0
from anmcgrath
public GammaDistribution Gamma(IVoxelDataStructure reference, IVoxelDataStructure evaluated, IProgress<int> progress, float distTol, float doseTol, float threshold)
{
var gammaDistribution = new GammaDistribution();
VectorField gammaVectorField = new VectorField();
var xVectors = CreateBlank(reference);
var yVectors = CreateBlank(reference);
var zVectors = CreateBlank(reference);
float thresholdDose = (threshold / 100) * reference.MaxVoxel.Value * reference.Scaling;
doseTol = (doseTol / 100) * (reference.MaxVoxel.Value * reference.Scaling); //global gamma
var newGrid = CreateBlank(reference);
//Create a sorted list of offsets with a certain diameter and step size
var offsets = CreateOffsets(distTol * 3, distTol / 10.0, newGrid.GridSpacing);
Point3d posn = new Point3d();
Point3d posn2 = new Point3d();
double dx = 0, dy = 0, dz = 0; // Keep track of where we are pointing.
int voxelNum = 0;
int totalVoxels = newGrid.NumberOfVoxels;
foreach (Voxel voxel in newGrid)
{
voxelNum++;
if (voxelNum % (totalVoxels / 20) == 0)
progress.Report((int)(100 * ((double)voxelNum / (double)totalVoxels)));
posn = voxel.Position;
var refDose = reference.Interpolate(posn).Value * reference.Scaling;
var evalDose = evaluated.Interpolate(posn).Value * evaluated.Scaling;
if (refDose < thresholdDose && evalDose < thresholdDose)
{
newGrid.SetVoxelByCoords((float)posn.X, (float)posn.Y, (float)posn.Z, -1);
continue;
}
//Set minGamma squared using a point with no offset (dose difference only).
var dd = refDose - evalDose;
float minGammaSquared = GammaSquared(dd * dd, 0, doseTol * doseTol, distTol * distTol);
dx = dy = dz = 0;
//Store the last distance we evaluated
float lastDistSq = 0;
//loop throught the sorted list of offsets
for (int o = 1; o < offsets.Count; o++)
{
Offset offset = offsets[o];
float distSq = (float)offset.DistanceSquared;
//set posn2 to to the actual physical location in the grid we are interested in
posn.Add(offset.Displacement, posn2);
if (minGammaSquared < distSq / (distTol * distTol) && distSq > lastDistSq)
{
break; //there is no way gamma can get smaller since distance is increasing in each offset and future gamma will be dominated by the DTA portion.
}
dx = offset.Displacement.X;
dy = offset.Displacement.Y;
dz = offset.Displacement.Z;
//compute dose difference squared and then gamma squared
refDose = reference.Interpolate(posn).Value * reference.Scaling;
evalDose = evaluated.Interpolate(posn2).Value * evaluated.Scaling;
float doseDiff = (refDose - evalDose);
float gammaSquared = GammaSquared(doseDiff * doseDiff, distSq, doseTol * doseTol, distTol * distTol);
if (gammaSquared < minGammaSquared)
minGammaSquared = gammaSquared;
lastDistSq = distSq;
}
float gamma = (float)Math.Sqrt((double)minGammaSquared);
if(gamma >0 || gamma <0 || float.IsNaN(gamma) || float.IsInfinity(gamma) || float.IsNegativeInfinity(gamma))
{
}
newGrid.SetVoxelByCoords((float)posn.X, (float)posn.Y, (float)posn.Z, gamma);
xVectors.SetVoxelByCoords((float)posn.X, (float)posn.Y, (float)posn.Z, (float)dx);
yVectors.SetVoxelByCoords((float)posn.X, (float)posn.Y, (float)posn.Z, (float)dy);
zVectors.SetVoxelByCoords((float)posn.X, (float)posn.Y, (float)posn.Z, (float)dz);
TestAndSetMinAndMax(newGrid, gamma);
}
gammaDistribution.Gamma = newGrid;
gammaDistribution.Vectors.X = xVectors;
gammaDistribution.Vectors.Y = yVectors;
gammaDistribution.Vectors.Z = zVectors;
//gammaDistribution.Jacobian = GetJacobianMatrix(gammaDistribution);
return gammaDistribution;
}
19
Source : ClassicMode.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
protected virtual void OnUpdateViewPanning()
{
// We can only drag the map when the mouse pointer is inside
// otherwise we don't have coordinates where to drag the map to
if(mouseinside && !float.IsNaN(mouselastpos.x) && !float.IsNaN(mouselastpos.y))
{
// Get the map coordinates of the last mouse posision (before it moved)
Vector2D lastmappos = renderer2d.DisplayToMap(mouselastpos);
// Do the scroll
ScrollBy(lastmappos.x - mousemappos.x, lastmappos.y - mousemappos.y);
}
}
19
Source : Triangulation.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private bool LineInsideTriangle(EarClipVertex[] t, Vector2D p1, Vector2D p2)
{
float s01 = Line2D.GetSideOfLine(t[0].Position, t[1].Position, p2);
float s12 = Line2D.GetSideOfLine(t[1].Position, t[2].Position, p2);
float s20 = Line2D.GetSideOfLine(t[2].Position, t[0].Position, p2);
float p2_on_edge = 2.0f; // somewhere outside the 0 .. 1 range
float p1_on_same_edge = 2.0f;
// Test if p2 is inside the triangle
if((s01 < 0.0f) && (s12 < 0.0f) && (s20 < 0.0f))
{
// Line is inside triangle, because p2 is
return true;
}
// Test if p2 is on an edge of the triangle and if it is we would
// like to know where on the edge segment p2 is
else if(s01 == 0.0f)
{
p2_on_edge = Line2D.GetNearestOnLine(t[0].Position, t[1].Position, p2);
p1_on_same_edge = Line2D.GetSideOfLine(t[0].Position, t[1].Position, p1);
}
else if(s12 == 0.0f)
{
p2_on_edge = Line2D.GetNearestOnLine(t[1].Position, t[2].Position, p2);
p1_on_same_edge = Line2D.GetSideOfLine(t[1].Position, t[2].Position, p1);
}
else if(s20 == 0.0f)
{
p2_on_edge = Line2D.GetNearestOnLine(t[2].Position, t[0].Position, p2);
p1_on_same_edge = Line2D.GetSideOfLine(t[2].Position, t[0].Position, p1);
}
// Is p2 actually on the edge segment?
if((p2_on_edge >= 0.0f) && (p2_on_edge <= 1.0f))
{
// If p1 is on the same edge (or the unlimited line of that edge)
// then the line is not inside this triangle.
if(p1_on_same_edge == 0.0f)
return false;
}
// Do a complete line-triangle intersection test
// We already know p1 is not inside the triangle (possibly on an edge)
Line2D p = new Line2D(p1, p2);
Line2D t01 = new Line2D(t[0].Position, t[1].Position);
Line2D t12 = new Line2D(t[1].Position, t[2].Position);
Line2D t20 = new Line2D(t[2].Position, t[0].Position);
float pu, pt;
// Test intersections
t01.GetIntersection(p, out pu, out pt);
if(!float.IsNaN(pu) && (pu >= 0.0f) && (pu <= 1.0f) && (pt >= 0.0f) && (pt <= 1.0f)) return true;
t12.GetIntersection(p, out pu, out pt);
if(!float.IsNaN(pu) && (pu >= 0.0f) && (pu <= 1.0f) && (pt >= 0.0f) && (pt <= 1.0f)) return true;
t20.GetIntersection(p, out pu, out pt);
if(!float.IsNaN(pu) && (pu >= 0.0f) && (pu <= 1.0f) && (pt >= 0.0f) && (pt <= 1.0f)) return true;
return false;
}
19
Source : Vector3D.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public bool IsFinite()
{
return !float.IsNaN(x) && !float.IsNaN(y) && !float.IsNaN(z) && !float.IsInfinity(x) && !float.IsInfinity(y) && !float.IsInfinity(z);
}
19
Source : Triangulation.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private void SplitOuterWithInner(LinkedListNode<EarClipVertex> start, EarClipPolygon p, EarClipPolygon inner)
{
LinkedListNode<EarClipVertex> v1, v2;
LinkedListNode<EarClipVertex> insertbefore = null;
float u, ul, bonus, foundu = float.MaxValue;
Vector2D foundpos = new Vector2D();
EarClipVertex split;
// Create a line from start that goes beyond the right most vertex of p
LinkedListNode<EarClipVertex> pr = FindRightMostVertex(p);
float startx = start.Value.Position.x;
float endx = pr.Value.Position.x + 10.0f;
Line2D starttoright = new Line2D(start.Value.Position, new Vector2D(endx, start.Value.Position.y));
// Calculate a small bonus (0.1 mappixel)
bonus = starttoright.GetNearestOnLine(new Vector2D(start.Value.Position.x + 0.1f, start.Value.Position.y));
// Go for all lines in the outer polygon
v1 = p.Last;
v2 = p.First;
while(v2 != null)
{
// Check if the line goes between startx and endx
if(((v1.Value.Position.x > startx) ||
(v2.Value.Position.x > startx)) &&
((v1.Value.Position.x < endx) ||
(v2.Value.Position.x < endx)))
{
// Find intersection
Line2D pl = new Line2D(v1.Value.Position, v2.Value.Position);
pl.GetIntersection(starttoright, out u, out ul);
if(float.IsNaN(u))
{
// We have found a line that is perfectly horizontal
// (parallel to the cut scan line) Check if the line
// is overlapping the cut scan line.
if(v1.Value.Position.y == start.Value.Position.y)
{
// This is an exceptional situation which causes a bit of a problem, because
// this could be a previously made cut, which overlaps another line from the
// same cut and we have to determine which of the two we will join with. If we
// pick the wrong one, the polygon is no longer valid and triangulation will fail.
// Calculate distance of each vertex in units
u = starttoright.GetNearestOnLine(v1.Value.Position);
ul = starttoright.GetNearestOnLine(v2.Value.Position);
// Rule out vertices before the scan line
if(u < 0.0f) u = float.MaxValue;
if(ul < 0.0f) ul = float.MaxValue;
float insert_u = Math.Min(u, ul);
Vector2D inserpos = starttoright.GetCoordinatesAt(insert_u);
// Check in which direction the line goes.
if(v1.Value.Position.x > v2.Value.Position.x)
{
// The line goes from right to left (towards our start point)
// so we must always insert our cut after this line.
// If the next line goes up, we consider this a better candidate than
// a horizontal line that goes from left to right (the other cut line)
// so we give it a small bonus.
LinkedListNode<EarClipVertex> v3 = v2.Next ?? v2.List.First;
if(v3.Value.Position.y < v2.Value.Position.y)
insert_u -= bonus;
// Remember this when it is a closer match
if(insert_u <= foundu)
{
insertbefore = v2.Next ?? v2.List.First;
foundu = insert_u;
foundpos = inserpos;
}
}
else
{
// The line goes from left to right (away from our start point)
// so we must always insert our cut before this line.
// If the previous line goes down, we consider this a better candidate than
// a horizontal line that goes from right to left (the other cut line)
// so we give it a small bonus.
LinkedListNode<EarClipVertex> v3 = v1.Previous ?? v1.List.Last;
if(v3.Value.Position.y > v1.Value.Position.y)
insert_u -= bonus;
// Remember this when it is a closer match
if(insert_u <= foundu)
{
insertbefore = v2;
foundu = insert_u;
foundpos = inserpos;
}
}
}
}
// Found a closer match?
else if((ul >= 0.0f) && (ul <= 1.0f) && (u > 0.0f) && (u <= foundu))
{
// Found a closer intersection
insertbefore = v2;
foundu = u;
foundpos = starttoright.GetCoordinatesAt(u);
}
}
// Next
v1 = v2;
v2 = v2.Next;
}
// Found anything?
if(insertbefore != null)
{
Sidedef sd = (insertbefore.Previous == null) ? insertbefore.List.Last.Value.Sidedef : insertbefore.Previous.Value.Sidedef;
// Find the position where we have to split the outer polygon
split = new EarClipVertex(foundpos, null);
// Insert manual split vertices
p.AddBefore(insertbefore, new EarClipVertex(split, sd));
// Start inserting from the start (do I make sense this time?)
v1 = start;
do
{
// Insert inner polygon vertex
p.AddBefore(insertbefore, new EarClipVertex(v1.Value));
if(v1.Next != null) v1 = v1.Next; else v1 = v1.List.First;
}
while(v1 != start);
// Insert manual split vertices
p.AddBefore(insertbefore, new EarClipVertex(start.Value, sd));
if(split.Position != insertbefore.Value.Position)
p.AddBefore(insertbefore, new EarClipVertex(split, sd));
}
}
19
Source : Vector2D.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public bool IsFinite()
{
return !float.IsNaN(x) && !float.IsNaN(y) && !float.IsInfinity(x) && !float.IsInfinity(y);
}
19
Source : EditSelectionMode.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private void Update()
{
// Not in any modifying mode?
if(mode == ModifyMode.None)
{
// Check what grip the mouse is over
// and change cursor accordingly
Grip mousegrip = CheckMouseGrip();
switch(mousegrip)
{
case Grip.Main:
// Find the nearest vertex within highlight range
Vertex v = MapSet.NearestVertex(selectedvertices, mousemappos);
// Find the nearest thing within range
Thing t = MapSet.NearestThing(selectedthings, mousemappos);
// Highlight the one that is closer
if((v != null) && (t != null))
{
if(v.DistanceToSq(mousemappos) < t.DistanceToSq(mousemappos))
{
if(v != highlighted) Highlight(v);
}
else
{
if(t != highlighted) Highlight(t);
}
}
else if(v != null)
{
if(v != highlighted) Highlight(v);
}
else
{
if(t != highlighted) Highlight(t);
}
General.Interface.SetCursor(Cursors.Hand);
break;
case Grip.RotateLB:
case Grip.RotateLT:
case Grip.RotateRB:
case Grip.RotateRT:
Highlight(null);
General.Interface.SetCursor(Cursors.Cross);
break;
case Grip.SizeE:
case Grip.SizeS:
case Grip.SizeW:
case Grip.SizeN:
// Pick the best matching cursor depending on rotation and side
float resizeangle = rotation;
if((mousegrip == Grip.SizeE) || (mousegrip == Grip.SizeW)) resizeangle += Angle2D.PIHALF;
resizeangle = Angle2D.Normalized(resizeangle);
if(resizeangle > Angle2D.PI) resizeangle -= Angle2D.PI;
resizeangle = Math.Abs(resizeangle + Angle2D.PI / 8.000001f);
int cursorindex = (int)Math.Floor((resizeangle / Angle2D.PI) * 4.0f) % 4;
General.Interface.SetCursor(RESIZE_CURSORS[cursorindex]);
Highlight(null);
break;
default:
Highlight(null);
General.Interface.SetCursor(Cursors.Default);
break;
}
}
else
{
Vector2D snappedmappos = mousemappos;
bool dosnaptogrid = snaptogrid;
// Options
snaptogrid = General.Interface.ShiftState ^ General.Interface.SnapToGrid;
snaptonearest = General.Interface.CtrlState ^ General.Interface.AutoMerge;
// Change to crosshair cursor so we can clearly see around the mouse cursor
General.Interface.SetCursor(Cursors.Cross);
// Check what modifying mode we are in
switch(mode)
{
// Dragging
case ModifyMode.Dragging:
// Change offset without snapping
offset = mousemappos - dragoffset;
// Calculate transformed position of highlighted vertex
Vector2D transformedpos = TransformedPoint(highlightedpos);
// Snap to nearest vertex?
if(snaptonearest && (highlighted != null))
{
float vrange = BuilderPlug.Me.SreplacedchRange / renderer.Scale;
// Try the nearest vertex
Vertex nv = MapSet.NearestVertexSquareRange(unselectedvertices, transformedpos, vrange);
if(nv != null)
{
// Change offset to snap to target
offset += nv.Position - transformedpos;
dosnaptogrid = false;
}
else
{
// Find the nearest unselected line within range
Linedef nl = MapSet.NearestLinedefRange(unselectedlines, transformedpos, BuilderPlug.Me.SreplacedchRange / renderer.Scale);
if(nl != null)
{
// Snap to grid?
if(dosnaptogrid)
{
// Get grid intersection coordinates
List<Vector2D> coords = nl.GetGridIntersections();
// Find nearest grid intersection
float found_distance = float.MaxValue;
Vector2D found_pos = new Vector2D(float.NaN, float.NaN);
foreach(Vector2D v in coords)
{
Vector2D dist = transformedpos - v;
if(dist.GetLengthSq() < found_distance)
{
// Found a better match
found_distance = dist.GetLengthSq();
found_pos = v;
// Do not snap to grid anymore
dosnaptogrid = false;
}
}
// Found something?
if(!float.IsNaN(found_pos.x))
{
// Change offset to snap to target
offset += found_pos - transformedpos;
}
}
else
{
// Change offset to snap onto the line
offset += nl.NearestOnLine(transformedpos) - transformedpos;
}
}
}
}
// Snap to grid?
if(dosnaptogrid && (highlighted != null))
{
// Change offset to align to grid
offset += General.Map.Grid.SnappedToGrid(transformedpos) - transformedpos;
}
// Update
UpdateGeometry();
UpdateRectangleComponents();
General.Interface.RedrawDisplay();
break;
// Resizing
case ModifyMode.Resizing:
// Snap to nearest vertex?
if(snaptonearest)
{
float vrange = BuilderPlug.Me.SreplacedchRange / renderer.Scale;
// Try the nearest vertex
Vertex nv = MapSet.NearestVertexSquareRange(unselectedvertices, snappedmappos, vrange);
if(nv != null)
{
snappedmappos = nv.Position;
dosnaptogrid = false;
}
}
// Snap to grid?
if(dosnaptogrid)
{
// Aligned to grid
snappedmappos = General.Map.Grid.SnappedToGrid(snappedmappos);
}
// Keep corner position
Vector2D oldcorner = corners[stickcorner];
// Change size with the scale from the ruler
float scale = resizeaxis.GetNearestOnLine(snappedmappos);
size = (basesize * resizefilter) * scale + size * (1.0f - resizefilter);
// Adjust corner position
Vector2D newcorner = TransformedPoint(originalcorners[stickcorner]);
offset -= newcorner - oldcorner;
// Show the extension line so that the user knows what it is aligning to
Vector2D sizefiltered = (size * resizefilter);
float sizelength = sizefiltered.x + sizefiltered.y;
Line2D edgeline = new Line2D(resizeaxis.v1 + resizevector * sizelength, resizeaxis.v1 + resizevector * sizelength - edgevector);
float nearestonedge = edgeline.GetNearestOnLine(snappedmappos);
if(nearestonedge > 0.5f)
extensionline = new Line2D(edgeline.v1, snappedmappos);
else
extensionline = new Line2D(edgeline.v2, snappedmappos);
// Update
UpdateGeometry();
UpdateRectangleComponents();
General.Interface.RedrawDisplay();
break;
// Rotating
case ModifyMode.Rotating:
// Get angle from mouse to center
Vector2D center = offset + size * 0.5f;
Vector2D delta = snappedmappos - center;
rotation = delta.GetAngle() - rotategripangle;
// Snap rotation to grip?
if(dosnaptogrid)
{
// We make 8 vectors that the rotation can snap to
float founddistance = float.MaxValue;
float foundrotation = rotation;
for(int i = 0; i < 8; i++)
{
// Make the vectors
float angle = (float)i * Angle2D.PI * 0.25f;
Vector2D gridvec = Vector2D.FromAngle(angle);
Vector3D rotvec = Vector2D.FromAngle(rotation);
// Check distance
float dist = 2.0f - Vector2D.DotProduct(gridvec, rotvec);
if(dist < founddistance)
{
foundrotation = angle;
founddistance = dist;
}
}
// Keep rotation
rotation = foundrotation;
}
// Update
UpdateGeometry();
UpdateRectangleComponents();
General.Interface.RedrawDisplay();
break;
}
}
}
19
Source : FlatAlignMode.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private void Update()
{
// Not in any modifying mode?
if(mode == ModifyMode.None)
{
Vector2D prevdragoffset = alignoffset;
alignoffset = new Vector2D(float.MinValue, float.MinValue);
showalignoffset = false;
// Check what grip the mouse is over
// and change cursor accordingly
Grip mousegrip = CheckMouseGrip();
switch(mousegrip)
{
case Grip.Main:
int closestcorner = -1;
float cornerdist = float.MaxValue;
for(int i = 0; i < 4; i++)
{
Vector2D delta = corners[i] - mousemappos;
float d = delta.GetLengthSq();
if(d < cornerdist)
{
closestcorner = i;
cornerdist = d;
}
}
switch(closestcorner)
{
// TODO:
case 0: alignoffset = new Vector2D(0f, 0f); break;
case 1: alignoffset = new Vector2D(texture.ScaledWidth, 0f); break;
case 2: alignoffset = new Vector2D(texture.ScaledWidth, -texture.ScaledHeight); break;
case 3: alignoffset = new Vector2D(0f, -texture.ScaledHeight); break;
}
showalignoffset = true;
General.Interface.SetCursor(Cursors.Hand);
break;
case Grip.RotateLB:
case Grip.RotateRT:
alignoffset = new Vector2D(0f, 0f);
showalignoffset = true;
General.Interface.SetCursor(Cursors.Cross);
break;
case Grip.SizeH:
case Grip.SizeV:
alignoffset = new Vector2D(0f, 0f);
showalignoffset = true;
// Pick the best matching cursor depending on rotation and side
float resizeangle = -(rotation + sectorinfo[0].rotation);
if(mousegrip == Grip.SizeH) resizeangle += Angle2D.PIHALF;
resizeangle = Angle2D.Normalized(resizeangle);
if(resizeangle > Angle2D.PI) resizeangle -= Angle2D.PI;
resizeangle = Math.Abs(resizeangle + Angle2D.PI / 8.000001f);
int cursorindex = (int)Math.Floor((resizeangle / Angle2D.PI) * 4.0f) % 4;
General.Interface.SetCursor(RESIZE_CURSORS[cursorindex]);
break;
default:
General.Interface.SetCursor(Cursors.Default);
break;
}
if(prevdragoffset != alignoffset)
General.Interface.RedrawDisplay();
}
else
{
Vector2D snappedmappos = mousemappos;
bool dosnaptogrid = snaptogrid;
// Options
snaptogrid = General.Interface.ShiftState ^ General.Interface.SnapToGrid;
snaptonearest = General.Interface.CtrlState ^ General.Interface.AutoMerge;
// Change to crosshair cursor so we can clearly see around the mouse cursor
General.Interface.SetCursor(Cursors.Cross);
// Check what modifying mode we are in
switch(mode)
{
case ModifyMode.Dragging:
offset = -mousemappos - dragoffset;
Vector2D transformedpos = TexToWorld(alignoffset);
// Snap to nearest vertex?
if(snaptonearest)
{
float vrange = BuilderPlug.Me.SreplacedchRange / renderer.Scale;
// Try the nearest vertex
Vertex nv = MapSet.NearestVertexSquareRange(General.Map.Map.Vertices, transformedpos, vrange);
if(nv != null)
{
// Change offset to snap to target
offset -= nv.Position - transformedpos;
dosnaptogrid = false;
}
else
{
// Find the nearest line within range
Linedef nl = MapSet.NearestLinedefRange(General.Map.Map.Linedefs, transformedpos, vrange);
if(nl != null)
{
// Snap to grid?
if(dosnaptogrid)
{
// Get grid intersection coordinates
List<Vector2D> coords = nl.GetGridIntersections();
// Find nearest grid intersection
float found_distance = float.MaxValue;
Vector2D found_pos = new Vector2D(float.NaN, float.NaN);
foreach(Vector2D v in coords)
{
Vector2D dist = transformedpos - v;
if(dist.GetLengthSq() < found_distance)
{
// Found a better match
found_distance = dist.GetLengthSq();
found_pos = v;
// Do not snap to grid anymore
dosnaptogrid = false;
}
}
// Found something?
if(!float.IsNaN(found_pos.x))
{
// Change offset to snap to target
offset -= found_pos - transformedpos;
}
}
else
{
// Change offset to snap onto the line
offset -= nl.NearestOnLine(transformedpos) - transformedpos;
}
}
}
}
// Snap to grid?
if(dosnaptogrid)
{
// Change offset to align to grid
offset -= General.Map.Grid.SnappedToGrid(transformedpos) - transformedpos;
}
break;
case ModifyMode.Resizing:
// Snap to nearest vertex?
if(snaptonearest)
{
float vrange = BuilderPlug.Me.SreplacedchRange / renderer.Scale;
// Try the nearest vertex
Vertex nv = MapSet.NearestVertexSquareRange(General.Map.Map.Vertices, snappedmappos, vrange);
if(nv != null)
{
snappedmappos = nv.Position;
dosnaptogrid = false;
}
}
// Snap to grid?
if(dosnaptogrid)
{
// Aligned to grid
snappedmappos = General.Map.Grid.SnappedToGrid(snappedmappos);
}
float newscale = 1f / resizeaxis.GetNearestOnLine(snappedmappos);
if(float.IsInfinity(newscale) || float.IsNaN(newscale)) newscale = 99999f;
scale = (newscale * resizefilter) + scale * (1.0f - resizefilter);
if(float.IsInfinity(scale.x) || float.IsNaN(scale.x)) scale.x = 99999f;
if(float.IsInfinity(scale.y) || float.IsNaN(scale.y)) scale.y = 99999f;
// Show the extension line so that the user knows what it is aligning to
UpdateRectangleComponents();
Line2D edgeline;
if(resizefilter.x > resizefilter.y)
edgeline = new Line2D(corners[1], corners[2]);
else
edgeline = new Line2D(corners[3], corners[2]);
float nearestonedge = edgeline.GetNearestOnLine(snappedmappos);
if(nearestonedge > 0.5f)
extensionline = new Line2D(edgeline.v1, snappedmappos);
else
extensionline = new Line2D(edgeline.v2, snappedmappos);
break;
case ModifyMode.Rotating:
// Snap to nearest vertex?
extensionline = new Line2D();
if(snaptonearest)
{
float vrange = BuilderPlug.Me.SreplacedchRange / renderer.Scale;
// Try the nearest vertex
Vertex nv = MapSet.NearestVertexSquareRange(General.Map.Map.Vertices, snappedmappos, vrange);
if(nv != null)
{
snappedmappos = nv.Position;
dosnaptogrid = false;
// Show the extension line so that the user knows what it is aligning to
extensionline = new Line2D(corners[0], snappedmappos);
}
}
Vector2D delta = snappedmappos - rotationcenter;
float deltaangle = -delta.GetAngle();
// Snap to grid?
if(dosnaptogrid)
{
// We make 8 vectors that the rotation can snap to
float founddistance = float.MaxValue;
float foundrotation = rotation;
for(int i = 0; i < 8; i++)
{
// Make the vectors
float angle = (float)i * Angle2D.PI * 0.25f;
Vector2D gridvec = Vector2D.FromAngle(angle);
Vector3D rotvec = Vector2D.FromAngle(deltaangle + rotationoffset);
// Check distance
float dist = 2.0f - Vector2D.DotProduct(gridvec, rotvec);
if(dist < founddistance)
{
foundrotation = angle;
founddistance = dist;
}
}
// Keep rotation
rotation = foundrotation - sectorinfo[0].rotation;
}
else
{
rotation = deltaangle + rotationoffset - sectorinfo[0].rotation;
}
break;
}
UpdateSectors();
General.Interface.RedrawDisplay();
}
}
See More Examples