-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMathf.cs
440 lines (367 loc) · 16.3 KB
/
Mathf.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
//using System.Threading;
using System.Runtime.CompilerServices;
using System.Numerics;
using System.Collections.Generic;
using System.Linq;
namespace Mola
{
// A collection of common math functions.
public partial struct Mathf
{
public static float Remap(float value, float input1, float input2, float output1, float output2)
{
return (output2 - output1) * value / (input2 - input1) + output1;
}
/// <summary>
/// Maps the values of a list from a minimum value to a maximum value.
/// </summary>
/// <param name="value"></param>
/// <param name="toMin"></param>
/// <param name="toMax"></param>
/// <returns></returns>
public static List<float> MapList(List<float> value, float toMin = 0, float toMax = 1)
{
float minValue = value.Min();
float maxValue = value.Max();
float delta = maxValue - minValue;
float deltaTarget = toMax - toMin;
List<float> toValue = value.Select(x => toMin + deltaTarget * (x - minValue) / delta).ToList();
return toValue;
}
/// <summary>
/// Maps a value from one range to another.
/// </summary>
/// <returns></returns>
public static float Map(float value, float fromMin, float fromMax, float toMin, float toMax)
{
float delta = fromMax - fromMin;
if (Math.Abs(delta) < 1.23E-7) return 0;
return toMin + ((toMax - toMin) / delta) * (value - fromMin);
}
// Returns the sine of angle /f/ in radians.
public static float Sin(float f) { return (float)Math.Sin(f); }
// Returns the cosine of angle /f/ in radians.
public static float Cos(float f) { return (float)Math.Cos(f); }
// Returns the tangent of angle /f/ in radians.
public static float Tan(float f) { return (float)Math.Tan(f); }
// Returns the arc-sine of /f/ - the angle in radians whose sine is /f/.
public static float Asin(float f) { return (float)Math.Asin(f); }
// Returns the arc-cosine of /f/ - the angle in radians whose cosine is /f/.
public static float Acos(float f) { return (float)Math.Acos(f); }
// Returns the arc-tangent of /f/ - the angle in radians whose tangent is /f/.
public static float Atan(float f) { return (float)Math.Atan(f); }
// Returns the angle in radians whose ::ref::Tan is @@y/x@@.
public static float Atan2(float y, float x) { return (float)Math.Atan2(y, x); }
// Returns square root of /f/.
public static float Sqrt(float f) { return (float)Math.Sqrt(f); }
// Returns the absolute value of /f/.
public static float Abs(float f) { return Math.Abs(f); }
// Returns the absolute value of /value/.
public static int Abs(int value) { return Math.Abs(value); }
/// *listonly*
public static float Min(float a, float b) { return a < b ? a : b; }
// Returns the smallest of two or more values.
public static float Min(params float[] values)
{
int len = values.Length;
if (len == 0)
return 0;
float m = values[0];
for (int i = 1; i < len; i++)
{
if (values[i] < m)
m = values[i];
}
return m;
}
/// *listonly*
public static int Min(int a, int b) { return a < b ? a : b; }
// Returns the smallest of two or more values.
public static int Min(params int[] values)
{
int len = values.Length;
if (len == 0)
return 0;
int m = values[0];
for (int i = 1; i < len; i++)
{
if (values[i] < m)
m = values[i];
}
return m;
}
/// *listonly*
public static float Max(float a, float b) { return a > b ? a : b; }
// Returns largest of two or more values.
public static float Max(params float[] values)
{
int len = values.Length;
if (len == 0)
return 0;
float m = values[0];
for (int i = 1; i < len; i++)
{
if (values[i] > m)
m = values[i];
}
return m;
}
/// *listonly*
public static int Max(int a, int b) { return a > b ? a : b; }
// Returns the largest of two or more values.
public static int Max(params int[] values)
{
int len = values.Length;
if (len == 0)
return 0;
int m = values[0];
for (int i = 1; i < len; i++)
{
if (values[i] > m)
m = values[i];
}
return m;
}
// Returns /f/ raised to power /p/.
public static float Pow(float f, float p) { return (float)Math.Pow(f, p); }
// Returns e raised to the specified power.
public static float Exp(float power) { return (float)Math.Exp(power); }
// Returns the logarithm of a specified number in a specified base.
public static float Log(float f, float p) { return (float)Math.Log(f, p); }
// Returns the natural (base e) logarithm of a specified number.
public static float Log(float f) { return (float)Math.Log(f); }
// Returns the base 10 logarithm of a specified number.
public static float Log10(float f) { return (float)Math.Log10(f); }
// Returns the smallest integer greater to or equal to /f/.
public static float Ceil(float f) { return (float)Math.Ceiling(f); }
// Returns the largest integer smaller to or equal to /f/.
public static float Floor(float f) { return (float)Math.Floor(f); }
// Returns /f/ rounded to the nearest integer.
public static float Round(float f) { return (float)Math.Round(f); }
// Returns the smallest integer greater to or equal to /f/.
public static int CeilToInt(float f) { return (int)Math.Ceiling(f); }
// Returns the largest integer smaller to or equal to /f/.
public static int FloorToInt(float f) { return (int)Math.Floor(f); }
// Returns /f/ rounded to the nearest integer.
public static int RoundToInt(float f) { return (int)Math.Round(f); }
// Returns the sign of /f/.
public static float Sign(float f) { return f >= 0F ? 1F : -1F; }
// The infamous ''3.14159265358979...'' value (RO).
public const float PI = (float)Math.PI;
// A representation of positive infinity (RO).
public const float Infinity = Single.PositiveInfinity;
// A representation of negative infinity (RO).
public const float NegativeInfinity = Single.NegativeInfinity;
// Degrees-to-radians conversion constant (RO).
public const float Deg2Rad = PI * 2F / 360F;
// Radians-to-degrees conversion constant (RO).
public const float Rad2Deg = 1F / Deg2Rad;
// We cannot round to more decimals than 15 according to docs for System.Math.Round.
internal const int kMaxDecimals = 15;
// A tiny floating point value (RO).
public static readonly float Epsilon = (float)double.Epsilon;
// Clamps a value between a minimum float and maximum float value.
public static float Clamp(float value, float min, float max)
{
if (value < min)
value = min;
else if (value > max)
value = max;
return value;
}
// Clamps value between min and max and returns value.
// Set the position of the transform to be that of the time
// but never less than 1 or more than 3
//
public static int Clamp(int value, int min, int max)
{
if (value < min)
value = min;
else if (value > max)
value = max;
return value;
}
// Clamps value between 0 and 1 and returns value
public static float Clamp01(float value)
{
if (value < 0F)
return 0F;
else if (value > 1F)
return 1F;
else
return value;
}
// Interpolates between /a/ and /b/ by /t/. /t/ is clamped between 0 and 1.
public static float Lerp(float a, float b, float t)
{
return a + (b - a) * Clamp01(t);
}
// Interpolates between /a/ and /b/ by /t/ without clamping the interpolant.
public static float LerpUnclamped(float a, float b, float t)
{
return a + (b - a) * t;
}
// Same as ::ref::Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
public static float LerpAngle(float a, float b, float t)
{
float delta = Repeat((b - a), 360);
if (delta > 180)
delta -= 360;
return a + delta * Clamp01(t);
}
// Moves a value /current/ towards /target/.
static public float MoveTowards(float current, float target, float maxDelta)
{
if (Mathf.Abs(target - current) <= maxDelta)
return target;
return current + Mathf.Sign(target - current) * maxDelta;
}
// Same as ::ref::MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
static public float MoveTowardsAngle(float current, float target, float maxDelta)
{
float deltaAngle = DeltaAngle(current, target);
if (-maxDelta < deltaAngle && deltaAngle < maxDelta)
return target;
target = current + deltaAngle;
return MoveTowards(current, target, maxDelta);
}
// Interpolates between /min/ and /max/ with smoothing at the limits.
public static float SmoothStep(float from, float to, float t)
{
t = Mathf.Clamp01(t);
t = -2.0F * t * t * t + 3.0F * t * t;
return to * t + from * (1F - t);
}
//*undocumented
public static float Gamma(float value, float absmax, float gamma)
{
bool negative = value < 0F;
float absval = Abs(value);
if (absval > absmax)
return negative ? -absval : absval;
float result = Pow(absval / absmax, gamma) * absmax;
return negative ? -result : result;
}
// Compares two floating point values if they are similar.
public static bool Approximately(float a, float b)
{
// If a or b is zero, compare that the other is less or equal to epsilon.
// If neither a or b are 0, then find an epsilon that is good for
// comparing numbers at the maximum magnitude of a and b.
// Floating points have about 7 significant digits, so
// 1.000001f can be represented while 1.0000001f is rounded to zero,
// thus we could use an epsilon of 0.000001f for comparing values close to 1.
// We multiply this epsilon by the biggest magnitude of a and b.
return Abs(b - a) < Max(0.000001f * Max(Abs(a), Abs(b)), Epsilon * 8);
}
// Loops the value t, so that it is never larger than length and never smaller than 0.
public static float Repeat(float t, float length)
{
return Clamp(t - Mathf.Floor(t / length) * length, 0.0f, length);
}
// PingPongs the value t, so that it is never larger than length and never smaller than 0.
public static float PingPong(float t, float length)
{
t = Repeat(t, length * 2F);
return length - Mathf.Abs(t - length);
}
// Calculates the ::ref::Lerp parameter between of two values.
public static float InverseLerp(float a, float b, float value)
{
if (a != b)
return Clamp01((value - a) / (b - a));
else
return 0.0f;
}
// Calculates the shortest difference between two given angles.
public static float DeltaAngle(float current, float target)
{
float delta = Mathf.Repeat((target - current), 360.0F);
if (delta > 180.0F)
delta -= 360.0F;
return delta;
}
static internal long RandomToLong(System.Random r)
{
var buffer = new byte[8];
r.NextBytes(buffer);
return (long)(System.BitConverter.ToUInt64(buffer, 0) & System.Int64.MaxValue);
}
internal static float ClampToFloat(double value)
{
if (double.IsPositiveInfinity(value))
return float.PositiveInfinity;
if (double.IsNegativeInfinity(value))
return float.NegativeInfinity;
if (value < float.MinValue)
return float.MinValue;
if (value > float.MaxValue)
return float.MaxValue;
return (float)value;
}
internal static int ClampToInt(long value)
{
if (value < int.MinValue)
return int.MinValue;
if (value > int.MaxValue)
return int.MaxValue;
return (int)value;
}
internal static float RoundToMultipleOf(float value, float roundingValue)
{
if (roundingValue == 0)
return value;
return Mathf.Round(value / roundingValue) * roundingValue;
}
internal static float GetClosestPowerOfTen(float positiveNumber)
{
if (positiveNumber <= 0)
return 1;
return Mathf.Pow(10, Mathf.RoundToInt(Mathf.Log10(positiveNumber)));
}
internal static int GetNumberOfDecimalsForMinimumDifference(float minDifference)
{
return Mathf.Clamp(-Mathf.FloorToInt(Mathf.Log10(Mathf.Abs(minDifference))), 0, kMaxDecimals);
}
internal static int GetNumberOfDecimalsForMinimumDifference(double minDifference)
{
return (int)System.Math.Max(0.0, -System.Math.Floor(System.Math.Log10(System.Math.Abs(minDifference))));
}
internal static float RoundBasedOnMinimumDifference(float valueToRound, float minDifference)
{
if (minDifference == 0)
return DiscardLeastSignificantDecimal(valueToRound);
return (float)System.Math.Round(valueToRound, GetNumberOfDecimalsForMinimumDifference(minDifference),
System.MidpointRounding.AwayFromZero);
}
internal static double RoundBasedOnMinimumDifference(double valueToRound, double minDifference)
{
if (minDifference == 0)
return DiscardLeastSignificantDecimal(valueToRound);
return System.Math.Round(valueToRound, GetNumberOfDecimalsForMinimumDifference(minDifference),
System.MidpointRounding.AwayFromZero);
}
internal static float DiscardLeastSignificantDecimal(float v)
{
int decimals = Mathf.Clamp((int)(5 - Mathf.Log10(Mathf.Abs(v))), 0, kMaxDecimals);
return (float)System.Math.Round(v, decimals, System.MidpointRounding.AwayFromZero);
}
internal static double DiscardLeastSignificantDecimal(double v)
{
int decimals = System.Math.Max(0, (int)(5 - System.Math.Log10(System.Math.Abs(v))));
try
{
return System.Math.Round(v, decimals);
}
catch (System.ArgumentOutOfRangeException)
{
// This can happen for very small numbers.
return 0;
}
}
}
}