├── .gitattributes
├── .github
└── workflows
│ └── generate-docs.yml
├── .gitignore
├── .npmignore
├── .npmrc
├── CHANGELOG.md
├── CHANGELOG.md.meta
├── Documentation~
├── articles
│ ├── abbreviations.md
│ ├── extensions.md
│ ├── index.md
│ ├── installation.md
│ ├── processors.md
│ └── random.md
└── data
│ ├── header.json
│ └── sidenav.json
├── LICENSE.md
├── LICENSE.md.meta
├── README.md
├── README.md.meta
├── Runtime.meta
├── Runtime
├── Chance.cs
├── Chance.cs.meta
├── ComparisonSign.cs
├── ComparisonSign.cs.meta
├── Dice.cs
├── Dice.cs.meta
├── EqualityComparers.meta
├── EqualityComparers
│ ├── DoubleEqualityComparer.cs
│ ├── DoubleEqualityComparer.cs.meta
│ ├── FloatEqualityComparer.cs
│ └── FloatEqualityComparer.cs.meta
├── Extensions.meta
├── Extensions
│ ├── ArrayExtensions.cs
│ ├── ArrayExtensions.cs.meta
│ ├── BoundsExtensions.cs
│ ├── BoundsExtensions.cs.meta
│ ├── ColliderExtensions.cs
│ ├── ColliderExtensions.cs.meta
│ ├── ComparableExtensions.cs
│ ├── ComparableExtensions.cs.meta
│ ├── DoubleExtensions.cs
│ ├── DoubleExtensions.cs.meta
│ ├── FloatExtensions.cs
│ ├── FloatExtensions.cs.meta
│ ├── IntExtensions.cs
│ ├── IntExtensions.cs.meta
│ ├── ListExtensions.cs
│ ├── ListExtensions.cs.meta
│ ├── LongExtensions.cs
│ ├── LongExtensions.cs.meta
│ ├── QuaternionExtensions.cs
│ ├── QuaternionExtensions.cs.meta
│ ├── RectExtensions.cs
│ ├── RectExtensions.cs.meta
│ ├── ShortExtensions.cs
│ ├── ShortExtensions.cs.meta
│ ├── TransformExtensions.cs
│ ├── TransformExtensions.cs.meta
│ ├── UIntExtensions.cs
│ ├── UIntExtensions.cs.meta
│ ├── Vector2Extensions.cs
│ ├── Vector2Extensions.cs.meta
│ ├── Vector2IntExtensions.cs
│ ├── Vector2IntExtensions.cs.meta
│ ├── Vector3Extensions.cs
│ ├── Vector3Extensions.cs.meta
│ ├── Vector3IntExtensions.cs
│ ├── Vector3IntExtensions.cs.meta
│ ├── Vector4Extensions.cs
│ └── Vector4Extensions.cs.meta
├── NumberAbbreviation.cs
├── NumberAbbreviation.cs.meta
├── Processors.cs
├── Processors.cs.meta
├── Zigurous.Math.asmdef
└── Zigurous.Math.asmdef.meta
├── package.json
└── package.json.meta
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.html linguist-detectable=false
2 | *.css linguist-detectable=false
3 | *.js linguist-detectable=false
4 |
--------------------------------------------------------------------------------
/.github/workflows/generate-docs.yml:
--------------------------------------------------------------------------------
1 | name: Generate Docs
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 | workflow_dispatch:
8 |
9 | concurrency:
10 | group: ${{ github.workflow }}-${{ github.ref }}
11 | cancel-in-progress: true
12 |
13 | jobs:
14 | generate:
15 | name: Docs
16 | uses: zigurous/docs/.github/workflows/unity-package.yml@main
17 | with:
18 | package_title: "Math Utils"
19 | package_base_path: com.zigurous.math
20 | package_workflow: generate-docs.yml
21 | package_artifact: docs
22 | secrets:
23 | token: ${{ secrets.DOCS_TOKEN }}
24 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /**/obj/
2 | /**/obj.meta
3 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | ./docs~/
2 | .github/
3 | .gitattributes
4 | .gitignore
5 | .gitmodules
6 | /**/obj/
7 | /**/obj.meta
8 |
--------------------------------------------------------------------------------
/.npmrc:
--------------------------------------------------------------------------------
1 | registry=https://registry.npmjs.org/
2 | @zigurous:registry=https://npm.pkg.github.com
3 | //npm.pkg.github.com/:_authToken=
4 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to this project will be documented in this file.
4 |
5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7 |
8 | ## [1.2.0] - 2023/06/20
9 |
10 | ### Added
11 |
12 | - Constructors to specify the amount of digits on `FloatEqualityComparer` and `DoubleEqualityComparer`
13 | - Overloads for `short` and `long` number abbreviations
14 | - New `ComparisonSign` enum
15 | - New `Bounds` extensions
16 | - `Lerp`
17 | - `LerpUnclamped`
18 | - `InverseLerp`
19 | - `CalculateScale`
20 | - New `Rect` extensions
21 | - `Contains`
22 | - `Encapsulate`
23 | - `Lerp`
24 | - `LerpUnclamped`
25 | - `InverseLerp`
26 | - New `Transform` extensions
27 | - `AveragePositionOfChildren`
28 | - `CenterPositionOfChildren`
29 | - `Reset`
30 | - `ResetLocal`
31 | - `SetPosition`
32 | - `SetLocalPosition`
33 | - `SetEulerAngles`
34 | - `SetLocalEulerAngles`
35 | - `SetLocalScale`
36 |
37 | ## [1.1.1] - 2022/05/19
38 |
39 | ### Fixed
40 |
41 | - Fixed certain edge cases where values were wrapping unintentionally even while in range
42 |
43 | ## [1.1.0] - 2021/07/12
44 |
45 | ### Added
46 |
47 | - New `Dice` static class for rolling dice + additional dice roll functions
48 | - New `NumberAbbreviation` data structure + extensions `ToAbbreviatedString`
49 | - New `DoubleEqualityComparer` to compare doubles based on # of decimals
50 | - New `Vector2Int` extensions class
51 | - New `Vector3Int` extensions class
52 | - New `List` extensions class
53 | - Extension methods for shuffling arrays and lists `Shuffle()`
54 | - Extension method `RandomPointInside` for `BoundsInt`
55 | - Additional `IsBetween` variants for inclusive/exclusive number ranges
56 | - Dozens of new input processors and support for more types
57 |
58 | ### Changed
59 |
60 | - Dice roll functions moved from `Chance` class to new `Dice` class
61 | - Overhauled documentation comments
62 | - Updated package description and README
63 |
64 | ## [1.0.4] - 2021/06/30
65 |
66 | ### Changed
67 |
68 | - Renamed package to Math Utils
69 |
70 | ## [1.0.3] - 2021/04/13
71 |
72 | ### Added
73 |
74 | - Wrap01 processors
75 |
76 | ### Changed
77 |
78 | - Decay function now does nothing if the input is zero
79 |
80 | ## [1.0.2] - 2021/03/21
81 |
82 | ### Changed
83 |
84 | - Updated package metadata
85 |
86 | ## [1.0.1] - 2021/03/07
87 |
88 | ### Changed
89 |
90 | - Updated package metadata
91 |
92 | ## [1.0.0] - 2021/02/27
93 |
94 | ### Added
95 |
96 | - Processor Functions
97 | - Chance Functions
98 | - Float Equality Comparer
99 | - Number Extensions
100 | - Comparable Extensions
101 | - Bounds/Collider Extensions
102 |
--------------------------------------------------------------------------------
/CHANGELOG.md.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 38faea8fbbf9f2047b0010d5734c492a
3 | TextScriptImporter:
4 | externalObjects: {}
5 | userData:
6 | assetBundleName:
7 | assetBundleVariant:
8 |
--------------------------------------------------------------------------------
/Documentation~/articles/abbreviations.md:
--------------------------------------------------------------------------------
1 | ---
2 | slug: "/manual/abbreviations"
3 | ---
4 |
5 | # Number Abbreviations
6 |
7 | The **Math Utils** package comes with methods to convert numbers to abbreviated strings. This is very useful in games that display floating combat text, for example. By default, numbers are abbreviated to the thousands ("K"), millions ("M"), billions ("B"), and trillions ("T").
8 |
9 | ```csharp
10 | 1_000.ToAbbreviatedString(); // "1K"
11 | 1_000_000.ToAbbreviatedString(); // "1M"
12 | 1_000_000_000.ToAbbreviatedString(); // "1B"
13 | 1_000_000_000_000.ToAbbreviatedString(); // "1T"
14 | ```
15 |
16 |
17 |
18 | ## 💯 Custom Abbreviations
19 |
20 | You can also provide your own custom abbreviations by creating a new [NumberAbbreviation](/api/Zigurous.Math/NumberAbbreviation).
21 |
22 | ```csharp
23 | NumberAbbreviation abbreviation = new NumberAbbreviation(factor, format);
24 | string display = abbreviation.Format(number);
25 | ```
26 |
27 | You can provide an array of number abbreviations to the `ToAbbreviatedString` function and it will select the first abbreviation possible. With this in mind, you usually want to order the abbreviations from largest to smallest.
28 |
29 | ```csharp
30 | NumberAbbreviation[] abbreviations;
31 | number.ToAbbreviatedString(abbreviations);
32 | ```
33 |
--------------------------------------------------------------------------------
/Documentation~/articles/extensions.md:
--------------------------------------------------------------------------------
1 | ---
2 | slug: "/manual/extensions"
3 | ---
4 |
5 | # Extension Methods
6 |
7 | A large majority of the functionality provided by the **Math Utils** package comes from extension methods. All of the extension methods found throughout the project are focused around numbers, whether it be arithmetic operations, bitwise operations, math algorithms, and other utilities of varying complexity. Extensions are available for the following types:
8 |
9 | #### [Array](/api/Zigurous.Math/ArrayExtensions)
10 |
11 | #### [Bounds](/api/Zigurous.Math/BoundsExtensions)
12 |
13 | #### [Collider](/api/Zigurous.Math/ColliderExtensions)
14 |
15 | #### [Double](/api/Zigurous.Math/DoubleExtensions)
16 |
17 | #### [Float](/api/Zigurous.Math/FloatExtensions)
18 |
19 | #### [IComparable](/api/Zigurous.Math/ComparableExtensions)
20 |
21 | #### [Int](/api/Zigurous.Math/IntExtensions)
22 |
23 | #### [List](/api/Zigurous.Math/ListExtensions)
24 |
25 | #### [Long](/api/Zigurous.Math/LongExtensions)
26 |
27 | #### [Quaternion](/api/Zigurous.Math/QuaternionExtensions)
28 |
29 | #### [Short](/api/Zigurous.Math/ShortExtensions)
30 |
31 | #### [UInt](/api/Zigurous.Math/UIntExtensions)
32 |
33 | #### [Vector2](/api/Zigurous.Math/Vector2Extensions)
34 |
35 | #### [Vector2Int](/api/Zigurous.Math/Vector2IntExtensions)
36 |
37 | #### [Vector3](/api/Zigurous.Math/Vector3Extensions)
38 |
39 | #### [Vector3Int](/api/Zigurous.Math/Vector3IntExtensions)
40 |
41 | #### [Vector4](/api/Zigurous.Math/Vector4Extensions)
42 |
--------------------------------------------------------------------------------
/Documentation~/articles/index.md:
--------------------------------------------------------------------------------
1 | ---
2 | slug: "/manual"
3 | ---
4 |
5 | # Math Utils
6 |
7 | The **Math Utils** package provides extensions and utilities for working with numbers in Unity projects including processing inputs, generating random numbers, and much more.
8 |
9 |
10 |
11 | ## Overview
12 |
13 | #### ⚙️ [Installation](/installation)
14 |
15 | #### 🧰 [Scripting API](/api/Zigurous.Math)
16 |
17 | #### 📋 [Changelog](/changelog)
18 |
19 | #### ⚖️ [License](/license)
20 |
21 |
22 |
23 | ## Reference
24 |
25 | #### 🔢 [Input Processors](/manual/processors)
26 |
27 | #### 🎲 [Random Numbers](/manual/random)
28 |
29 | #### 💯 [Number Abbreviations](/manual/abbreviations)
30 |
31 | #### 🔌 [Extension Methods](/manual/extensions)
32 |
--------------------------------------------------------------------------------
/Documentation~/articles/installation.md:
--------------------------------------------------------------------------------
1 | ---
2 | slug: "/installation"
3 | ---
4 |
5 | # Installation
6 |
7 | Use the Unity [Package Manager](https://docs.unity3d.com/Manual/upm-ui.html) to install the **Math Utils** package.
8 |
9 | 1. Open the Package Manager in `Window > Package Manager`
10 | 2. Click the add (`+`) button in the status bar
11 | 3. Select `Add package from git URL` from the add menu
12 | 4. Enter the following Git URL in the text box and click Add:
13 |
14 | ```http
15 | https://github.com/zigurous/unity-math-utils.git
16 | ```
17 |
18 |
19 |
20 | ## 🏷️ Namespace
21 |
22 | Import the package namespace in each script or file you want to use it. You may need to regenerate project files/assemblies first.
23 |
24 | ```csharp
25 | using Zigurous.Math;
26 | ```
27 |
28 |
29 |
30 | ## 💻 Source Code
31 |
32 | The source code for the **Math Utils** package is in the following repository:
33 |
34 | - https://github.com/zigurous/unity-math-utils
35 |
--------------------------------------------------------------------------------
/Documentation~/articles/processors.md:
--------------------------------------------------------------------------------
1 | ---
2 | slug: "/manual/processors"
3 | ---
4 |
5 | # Input Processors
6 |
7 | The **Math Utils** package contains various functions for processing input values. An input processor takes a value and returns a processed result for it of the same type. See the [Processors](/api/Zigurous.Math/Processors) class for all available functions, or the reference below:
8 |
9 |
10 |
11 | ### [Abs](/api/Zigurous.Math/Processors/Abs)
12 |
13 | Returns the absolute value of the input.
14 |
15 |
16 |
17 | ### [Axis Deadzone](/api/Zigurous.Math/Processors/AxisDeadzone)
18 |
19 | An axis deadzone scales the input such that any value with an absolute value smaller than `min` is 0, and any value with an absolute value larger than `max` is 1 or -1.
20 |
21 |
22 |
23 | ### [Ceil](/api/Zigurous.Math/Processors/Ceil)
24 |
25 | Rounds the input up to the nearest whole number.
26 |
27 |
28 |
29 | ### [Clamp](/api/Zigurous.Math/Processors/Clamp)
30 |
31 | Clamps the input to the range [`min`..`max`].
32 |
33 |
34 |
35 | ### [Clamp01](/api/Zigurous.Math/Processors/Clamp01)
36 |
37 | Clamps the input to the range [0..1].
38 |
39 |
40 |
41 | ### [Decay](/api/Zigurous.Math/Processors/Decay)
42 |
43 | Decays the input back to zero over time at a given `rate`.
The `rate` is multiplied by `Time.deltaTime`.
44 |
45 |
46 |
47 | ### [Floor](/api/Zigurous.Math/Processors/Floor)
48 |
49 | Rounds the input down to the nearest whole number.
50 |
51 |
52 |
53 | ### [Invert](/api/Zigurous.Math/Processors/Invert)
54 |
55 | Inverts the input by multiplying by -1.
56 |
57 | **Note**: Vectors can be inverted on a per-component basis.
58 |
59 |
60 |
61 | ### [Normalize](/api/Zigurous.Math/Processors/Normalize)
62 |
63 | Normalizes the input in the range [`min`..`max`] to unsigned normalized form [0..1] if `min` is >= `zero`, and to signed normalized form [-1..1] if `min` < `zero`.
64 |
65 | **Note**: Vectors are normalized by setting the unit length to 1 (the same as `vector.normalized`).
66 |
67 |
68 |
69 | ### [Round](/api/Zigurous.Math/Processors/Round)
70 |
71 | Rounds the input to the nearest whole number.
72 |
73 |
74 |
75 | ### [Scale](/api/Zigurous.Math/Processors/Scale)
76 |
77 | Multiplies the input by `factor`.
78 |
79 | **Note**: Vectors can be scaled on a per-component basis.
80 |
81 |
82 |
83 | ### [Stick Deadzone](/api/Zigurous.Math/Processors/StickDeadzone)
84 |
85 | A stick deadzone scales the input such that any value with a magnitude smaller than `min` results in (0,0), and any value with a magnitude greater than `max` is normalized to unit length (1).
86 |
87 |
88 |
89 | ### [Wrap](/api/Zigurous.Math/Processors/Wrap)
90 |
91 | Wraps the input to the range [`min`..`max`]. If the value exceeds `max` it wraps around to `min`, and if the value is less than `min` is wraps back to `max`.
92 |
93 | **Note**: Integers are wrapped [inclusive..exclusive) to make it easier for arrays.
94 |
95 |
96 |
97 | ### [Wrap01](/api/Zigurous.Math/Processors/Wrap01)
98 |
99 | Wraps the input to the range [0..1]. If the value exceeds 1 it wraps around to 0, and if the value is less than 0 it wraps back to 1.
100 |
--------------------------------------------------------------------------------
/Documentation~/articles/random.md:
--------------------------------------------------------------------------------
1 | ---
2 | slug: "/manual/random"
3 | ---
4 |
5 | # Random
6 |
7 | The **Math Utils** package contains several functions for generating random values, including rolling dice, picking random playing cards, and other utility functions.
8 |
9 |
10 |
11 | ## 🃏 Chance
12 |
13 | The [Chance](/api/Zigurous.Math/Chance) class comes with several predefined static functions for generating random chance values relating to playing cards, coins, and generic types:
14 |
15 | ```csharp
16 | Coin face = Chance.CoinFlip(); // heads, tails
17 | Suit suit = Chance.RandomSuit(); // hearts, diamonds, clubs, spades
18 | Card card = Chance.RandomCard(); // standard 52-card deck
19 | ```
20 |
21 | ```csharp
22 | bool value = Chance.RandomBool(); // true, false
23 | float value = Chance.PositiveOrNegative(); // +1f, -1f
24 | float value = Chance.PositiveOrNegative(value); // +value, -value
25 | ```
26 |
27 |
28 |
29 | ## 🎲 Dice Rolls
30 |
31 | The [Dice](/api/Zigurous.Math/Dice) class comes with several predefined static functions for common dice rolls, such as:
32 |
33 | ```csharp
34 | int d4 = Dice.D4();
35 | int d6 = Dice.D6();
36 | int d8 = Dice.D8();
37 | int d10 = Dice.D10();
38 | int d12 = Dice.D12();
39 | int d20 = Dice.D20();
40 | ```
41 |
42 | For any of these functions you can also pass in a value for parameter `n` to indicate how many times you want to roll that dice. The function will return the sum of all rolls. For example, this would roll a 6-sided dice 3 times.
43 |
44 | ```csharp
45 | int sum = Dice.D6(3);
46 | ```
47 |
48 | The class also has functions for rolling custom dice, either n-sided dice or custom dice.
49 |
50 | ```csharp
51 | int d7 = Dice.NSided(7); // 7-sided dice
52 | int d7x3 = Dice.NSided(7, 3); // 7-sided dice 3 times
53 | ```
54 |
55 | ```csharp
56 | int[] customValues = new int[] { 1, 3, 5, 7, 9 };
57 | int[] probabilities = new int[] { 30, 25, 20, 15, 10 };
58 |
59 | int roll = Dice.Roll(customValues); // equal probability
60 | int roll = Dice.Roll(customValues, probabilities);
61 | ```
62 |
--------------------------------------------------------------------------------
/Documentation~/data/header.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "name": "Manual",
4 | "path": "/manual"
5 | },
6 | {
7 | "name": "Scripting API",
8 | "path": "/api"
9 | },
10 | {
11 | "name": "Changelog",
12 | "path": "/changelog"
13 | },
14 | {
15 | "name": "License",
16 | "path": "/license"
17 | }
18 | ]
19 |
--------------------------------------------------------------------------------
/Documentation~/data/sidenav.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "title": "📌 Overview",
4 | "items": [
5 | {
6 | "name": "Getting Started",
7 | "path": "/manual"
8 | },
9 | {
10 | "name": "Installation",
11 | "path": "/installation"
12 | },
13 | {
14 | "name": "Changelog",
15 | "path": "/changelog"
16 | },
17 | {
18 | "name": "License",
19 | "path": "/license"
20 | }
21 | ]
22 | },
23 | {
24 | "title": "📖 Reference",
25 | "items": [
26 | {
27 | "name": "Input Processors",
28 | "path": "/manual/processors"
29 | },
30 | {
31 | "name": "Random Numbers",
32 | "path": "/manual/random"
33 | },
34 | {
35 | "name": "Number Abbreviations",
36 | "path": "/manual/abbreviations"
37 | },
38 | {
39 | "name": "Extension Methods",
40 | "path": "/manual/extensions"
41 | }
42 | ]
43 | },
44 | {
45 | "title": "💬 Contact",
46 | "items": [
47 | {
48 | "name": "Discord",
49 | "href": "https://discord.gg/DdYyWVb",
50 | "icon": "launch"
51 | },
52 | {
53 | "name": "Twitter",
54 | "href": "https://twitter.com/zigurous",
55 | "icon": "launch"
56 | }
57 | ]
58 | },
59 | {
60 | "title": "🔗 Other Links",
61 | "items": [
62 | {
63 | "name": "GitHub",
64 | "href": "https://github.com/zigurous/unity-math-utils",
65 | "icon": "launch"
66 | },
67 | {
68 | "name": "Asset Store",
69 | "href": "https://assetstore.unity.com/publishers/51884",
70 | "icon": "launch"
71 | },
72 | {
73 | "name": "YouTube",
74 | "href": "https://youtube.com/c/zigurous?sub_confirmation=1",
75 | "icon": "launch"
76 | },
77 | {
78 | "name": "Patreon",
79 | "href": "https://patreon.com/zigurous",
80 | "icon": "launch"
81 | }
82 | ]
83 | }
84 | ]
85 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 Zigurous
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/LICENSE.md.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: f9cce17a329707c4cbf5de63cf56d501
3 | TextScriptImporter:
4 | externalObjects: {}
5 | userData:
6 | assetBundleName:
7 | assetBundleVariant:
8 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Math Utils
2 |
3 | [](https://github.com/zigurous/unity-math-utils) [](https://github.com/zigurous/unity-math-utils/releases) [](https://docs.zigurous.com/com.zigurous.math) [](https://github.com/zigurous/unity-math-utils/blob/main/LICENSE.md)
4 |
5 | The **Math Utils** package provides extensions and utilities for working with numbers in Unity projects including processing inputs, generating random numbers, and much more.
6 |
7 | ## Reference
8 |
9 | - [Input Processors](https://docs.zigurous.com/com.zigurous.math/manual/processors)
10 | - [Random Numbers](https://docs.zigurous.com/com.zigurous.math/manual/random)
11 | - [Number Abbreviations](https://docs.zigurous.com/com.zigurous.math/manual/abbreviations)
12 | - [Extension Methods](https://docs.zigurous.com/com.zigurous.math/manual/extensions)
13 |
14 | ## Installation
15 |
16 | Use the Unity [Package Manager](https://docs.unity3d.com/Manual/upm-ui.html) to install the **Math Utils** package.
17 |
18 | 1. Open the Package Manager in `Window > Package Manager`
19 | 2. Click the add (`+`) button in the status bar
20 | 3. Select `Add package from git URL` from the add menu
21 | 4. Enter the following Git URL in the text box and click Add:
22 |
23 | ```
24 | https://github.com/zigurous/unity-math-utils.git
25 | ```
26 |
27 | ## Namespace
28 |
29 | Import the package namespace in each script or file you want to use it. You may need to regenerate project files/assemblies first.
30 |
31 | ```csharp
32 | using Zigurous.Math;
33 | ```
34 |
--------------------------------------------------------------------------------
/README.md.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: fc2d8dbcf8859b745b8a5e23b467fa66
3 | TextScriptImporter:
4 | externalObjects: {}
5 | userData:
6 | assetBundleName:
7 | assetBundleVariant:
8 |
--------------------------------------------------------------------------------
/Runtime.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 1ff84ba06bccac746a6fe8154f759cc3
3 | folderAsset: yes
4 | DefaultImporter:
5 | externalObjects: {}
6 | userData:
7 | assetBundleName:
8 | assetBundleVariant:
9 |
--------------------------------------------------------------------------------
/Runtime/Chance.cs:
--------------------------------------------------------------------------------
1 | namespace Zigurous.Math
2 | {
3 | ///
4 | /// Functions for generating random chance values.
5 | ///
6 | public static class Chance
7 | {
8 | ///
9 | /// The sides of a coin.
10 | ///
11 | public enum Coin { Heads, Tails }
12 |
13 | ///
14 | /// The suits of a standard 52-card deck.
15 | ///
16 | public enum Suit { Hearts, Diamonds, Clubs, Spades }
17 |
18 | ///
19 | /// The playing cards in a standard 52-card deck.
20 | ///
21 | public enum Card
22 | {
23 | HeartsA, HeartsK, HeartsQ, HeartsJ, Hearts10, Hearts9, Hearts8,
24 | Hearts7, Hearts6, Hearts5, Hearts4, Hearts3, Hearts2,
25 | DiamondsA, DiamondsK, DiamondsQ, DiamondsJ, Diamonds10, Diamonds9, Diamonds8,
26 | Diamonds7, Diamonds6, Diamonds5, Diamonds4, Diamonds3, Diamonds2,
27 | SpadesA, SpadesK, SpadesQ, SpadesJ, Spades10, Spades9, Spades8,
28 | Spades7, Spades6, Spades5, Spades4, Spades3, Spades2,
29 | ClubsA, ClubsK, ClubsQ, ClubsJ, Clubs10, Clubs9, Clubs8,
30 | Clubs7, Clubs6, Clubs5, Clubs4, Clubs3, Clubs2,
31 | Joker, None,
32 | }
33 |
34 | ///
35 | /// Returns a random playing card suit.
36 | ///
37 | /// A random playing card suit.
38 | public static Suit RandomSuit()
39 | {
40 | return (Suit)UnityEngine.Random.Range(0, 4);
41 | }
42 |
43 | ///
44 | /// Returns a random card from a standard 52-card deck.
45 | ///
46 | /// A random card from a standard 52-card deck.
47 | public static Card RandomCard()
48 | {
49 | return (Card)UnityEngine.Random.Range(0, 52);
50 | }
51 |
52 | ///
53 | /// Returns true or false, with 50-50 odds.
54 | ///
55 | /// true or false, with 50-50 odds.
56 | public static bool RandomBool()
57 | {
58 | return UnityEngine.Random.value < 0.5f;
59 | }
60 |
61 | ///
62 | /// Returns 1f or -1f, with 50-50 odds.
63 | ///
64 | /// 1f or -1f, with 50-50 odds.
65 | public static float PositiveOrNegative()
66 | {
67 | return UnityEngine.Random.value < 0.5f ? 1f : -1f;
68 | }
69 |
70 | ///
71 | /// Returns -value or +value, with 50-50 odds.
72 | ///
73 | /// The value to be returned.
74 | /// -value or +value, with 50-50 odds.
75 | public static float PositiveOrNegative(float value)
76 | {
77 | return UnityEngine.Random.value < 0.5f ? value : -value;
78 | }
79 |
80 | ///
81 | /// Returns Heads or Tails, with 50-50 odds.
82 | ///
83 | /// Heads or Tails, with 50-50 odds.
84 | public static Coin CoinFlip()
85 | {
86 | return UnityEngine.Random.value < 0.5f ? Coin.Heads : Coin.Tails;
87 | }
88 |
89 | }
90 |
91 | }
92 |
--------------------------------------------------------------------------------
/Runtime/Chance.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 98b1a965dab11684188326577268bcde
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/ComparisonSign.cs:
--------------------------------------------------------------------------------
1 | namespace Zigurous.Math
2 | {
3 | ///
4 | /// A mathematical sign that can be used to compare two values.
5 | ///
6 | public enum ComparisonSign
7 | {
8 | ///
9 | /// a == b
10 | ///
11 | Equal,
12 |
13 | ///
14 | /// a != b
15 | ///
16 | NotEqual,
17 |
18 | ///
19 | /// a > b
20 | ///
21 | GreaterThan,
22 |
23 | ///
24 | /// a >= b
25 | ///
26 | GreaterThanOrEqual,
27 |
28 | ///
29 | /// a < b
30 | ///
31 | LessThan,
32 |
33 | ///
34 | /// a <= b
35 | ///
36 | LessThanOrEqual,
37 | }
38 |
39 | ///
40 | /// Extension methods for .
41 | ///
42 | public static class ComparisonSignExtensions
43 | {
44 | ///
45 | /// Compares two values using the comparison sign.
46 | ///
47 | /// The type of values to compare.
48 | /// The comparison sign.
49 | /// The first value to compare.
50 | /// The second value to compare.
51 | /// The result of the comparison, either true or false.
52 | public static bool Compare(this ComparisonSign sign, T a, T b)
53 | where T : System.IComparable
54 | {
55 | switch (sign)
56 | {
57 | case ComparisonSign.Equal: return a.CompareTo(b) == 0;
58 | case ComparisonSign.NotEqual: return a.CompareTo(b) != 0;
59 | case ComparisonSign.GreaterThan: return a.CompareTo(b) > 0;
60 | case ComparisonSign.GreaterThanOrEqual: return a.CompareTo(b) >= 0;
61 | case ComparisonSign.LessThan: return a.CompareTo(b) < 0;
62 | case ComparisonSign.LessThanOrEqual: return a.CompareTo(b) <= 0;
63 | default: return false;
64 | }
65 | }
66 |
67 | }
68 |
69 | }
70 |
--------------------------------------------------------------------------------
/Runtime/ComparisonSign.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 9abccbc7c9e82ed47ac674b2c79509e5
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Dice.cs:
--------------------------------------------------------------------------------
1 | namespace Zigurous.Math
2 | {
3 | ///
4 | /// Functions for rolling dice.
5 | ///
6 | public static class Dice
7 | {
8 | ///
9 | /// Rolls a 4-sided dice [1..4].
10 | ///
11 | /// A random number on a 4-sided dice [1..4].
12 | public static int D4()
13 | {
14 | return UnityEngine.Random.Range(1, 5);
15 | }
16 |
17 | ///
18 | /// Rolls a 4-sided dice [1..4] times.
19 | ///
20 | /// The number of times to roll the dice.
21 | /// The sum of the rolls.
22 | public static int D4(int n)
23 | {
24 | int roll = 0;
25 | while (n-- > 0) roll += D4();
26 | return roll;
27 | }
28 |
29 | ///
30 | /// Rolls a 6-sided dice [1..6].
31 | ///
32 | /// A random number on a 6-sided dice [1..6].
33 | public static int D6()
34 | {
35 | return UnityEngine.Random.Range(1, 7);
36 | }
37 |
38 | ///
39 | /// Rolls a 6-sided dice [1..6] times.
40 | ///
41 | /// The number of times to roll the dice.
42 | /// The sum of the rolls.
43 | public static int D6(int n)
44 | {
45 | int roll = 0;
46 | while (n-- > 0) roll += D6();
47 | return roll;
48 | }
49 |
50 | ///
51 | /// Rolls an 8-sided dice [1..8].
52 | ///
53 | /// A random number on an 8-sided dice [1..8].
54 | public static int D8()
55 | {
56 | return UnityEngine.Random.Range(1, 9);
57 | }
58 |
59 | ///
60 | /// Rolls an 8-sided dice [1..8] times.
61 | ///
62 | /// The number of times to roll the dice.
63 | /// The sum of the rolls.
64 | public static int D8(int n)
65 | {
66 | int roll = 0;
67 | while (n-- > 0) roll += D8();
68 | return roll;
69 | }
70 |
71 | ///
72 | /// Rolls a 10-sided dice [1..10].
73 | ///
74 | /// A random number on a 10-sided dice [1..10].
75 | public static int D10()
76 | {
77 | return UnityEngine.Random.Range(1, 11);
78 | }
79 |
80 | ///
81 | /// Rolls a 10-sided dice [1..10] times.
82 | ///
83 | /// The number of times to roll the dice.
84 | /// The sum of the rolls.
85 | public static int D10(int n)
86 | {
87 | int roll = 0;
88 | while (n-- > 0) roll += D10();
89 | return roll;
90 | }
91 |
92 | ///
93 | /// Rolls a 12-sided dice [1..12].
94 | ///
95 | /// A random number on a 12-sided dice [1..12].
96 | public static int D12()
97 | {
98 | return UnityEngine.Random.Range(1, 13);
99 | }
100 |
101 | ///
102 | /// Rolls a 12-sided dice [1..12] times.
103 | ///
104 | /// The number of times to roll the dice.
105 | /// The sum of the rolls.
106 | public static int D12(int n)
107 | {
108 | int roll = 0;
109 | while (n-- > 0) roll += D12();
110 | return roll;
111 | }
112 |
113 | ///
114 | /// Rolls a 20-sided dice [1..20].
115 | ///
116 | /// A random number on a 20-sided dice [1..20].
117 | public static int D20()
118 | {
119 | return UnityEngine.Random.Range(1, 21);
120 | }
121 |
122 | ///
123 | /// Rolls a 20-sided dice [1..20] times.
124 | ///
125 | /// The number of times to roll the dice.
126 | /// The sum of the rolls.
127 | public static int D20(int n)
128 | {
129 | int roll = 0;
130 | while (n-- > 0) roll += D20();
131 | return roll;
132 | }
133 |
134 | ///
135 | /// Rolls a 48-sided dice [1..48].
136 | ///
137 | /// A random number on a 48-sided dice [1..48].
138 | public static int D48()
139 | {
140 | return UnityEngine.Random.Range(1, 49);
141 | }
142 |
143 | ///
144 | /// Rolls a 48-sided dice [1..48] times.
145 | ///
146 | /// The number of times to roll the dice.
147 | /// The sum of the rolls.
148 | public static int D48(int n)
149 | {
150 | int roll = 0;
151 | while (n-- > 0) roll += D48();
152 | return roll;
153 | }
154 |
155 | ///
156 | /// Rolls a 100-sided dice [1..100].
157 | ///
158 | /// A random number on a 100-sided dice [1..100].
159 | public static int D100()
160 | {
161 | return UnityEngine.Random.Range(1, 101);
162 | }
163 |
164 | ///
165 | /// Rolls a 100-sided dice [1..100] times.
166 | ///
167 | /// The number of times to roll the dice.
168 | /// The sum of the rolls.
169 | public static int D100(int n)
170 | {
171 | int roll = 0;
172 | while (n-- > 0) roll += D100();
173 | return roll;
174 | }
175 |
176 | ///
177 | /// Rolls an n-sided dice [1..].
178 | ///
179 | /// The number of sides on the dice.
180 | /// A random number on an n-sided dice [1..].
181 | public static int NSided(int n)
182 | {
183 | return UnityEngine.Random.Range(1, n + 1);
184 | }
185 |
186 | ///
187 | /// Rolls an n-sided dice [1..] amount of times.
188 | ///
189 | /// The number of sides on the dice.
190 | /// The number of times to roll the dice.
191 | /// The sum of the rolls.
192 | public static int NSided(int n, int x)
193 | {
194 | int roll = 0;
195 | while (x-- > 0) roll += NSided(n);
196 | return roll;
197 | }
198 |
199 | ///
200 | /// Rolls a custom dice.
201 | ///
202 | /// The numbered sides of the dice.
203 | /// A random number on the dice.
204 | public static int Roll(int[] dice)
205 | {
206 | return dice[UnityEngine.Random.Range(0, dice.Length)];
207 | }
208 |
209 | ///
210 | /// Rolls a custom dice amount of times.
211 | ///
212 | /// The numbered sides of the dice.
213 | /// The number of times to roll the dice.
214 | /// The sum of the rolls.
215 | public static int Roll(int[] dice, int n)
216 | {
217 | int roll = 0;
218 | while (n-- > 0) roll += Roll(dice);
219 | return roll;
220 | }
221 |
222 | ///
223 | /// Rolls a custom dice.
224 | ///
225 | /// The type of values of the dice.
226 | /// The values of the dice.
227 | /// A random value on the dice.
228 | public static T Roll(T[] dice)
229 | {
230 | return dice[UnityEngine.Random.Range(0, dice.Length)];
231 | }
232 |
233 | ///
234 | /// Rolls a custom dice with weighted probabilities.
235 | ///
236 | /// The type of values of the dice.
237 | /// The values of the dice.
238 | /// The probabilities of each value.
239 | /// A random value on the dice.
240 | public static T Roll(T[] dice, int[] weights)
241 | {
242 | int weightedTotal = 0;
243 |
244 | for (int i = 0; i < weights.Length; i++) {
245 | weightedTotal += weights[i];
246 | }
247 |
248 | float roll = UnityEngine.Random.value;
249 | float min = 0f;
250 |
251 | for (int i = 0; i < weights.Length; i++)
252 | {
253 | float weight = (float)weights[i] / weightedTotal;
254 | float max = min + weight;
255 |
256 | if (i == weights.Length - 1)
257 | {
258 | if (roll >= min && roll <= max) {
259 | return dice[i];
260 | }
261 | }
262 | else
263 | {
264 | if (roll >= min && roll < max) {
265 | return dice[i];
266 | }
267 | }
268 |
269 | min = max;
270 | }
271 |
272 | return default(T);
273 | }
274 |
275 | }
276 |
277 | }
278 |
--------------------------------------------------------------------------------
/Runtime/Dice.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: dd9704ebc7468be4abc2123363aa4a19
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/EqualityComparers.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: c1d47e8a6e0e12d4b9e7c844274ae569
3 | folderAsset: yes
4 | DefaultImporter:
5 | externalObjects: {}
6 | userData:
7 | assetBundleName:
8 | assetBundleVariant:
9 |
--------------------------------------------------------------------------------
/Runtime/EqualityComparers/DoubleEqualityComparer.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace Zigurous.Math
4 | {
5 | ///
6 | /// Compares the equality of double values using a specified amount of
7 | /// decimal digits to compare.
8 | ///
9 | public sealed class DoubleEqualityComparer : IEqualityComparer
10 | {
11 | ///
12 | /// The number of decimal digits to compare when determining equality.
13 | ///
14 | public int digits;
15 |
16 | ///
17 | /// Creates a new DoubleEqualityComparer with a default of 3 decimal
18 | /// digits to compare when determining equality.
19 | ///
20 | public DoubleEqualityComparer()
21 | {
22 | this.digits = 3;
23 | }
24 |
25 | ///
26 | /// Creates a new DoubleEqualityComparer with the specified number of
27 | /// decimal digits to compare when determining equality.
28 | ///
29 | public DoubleEqualityComparer(int digits)
30 | {
31 | this.digits = digits;
32 | }
33 |
34 | ///
35 | /// Checks the equality of two double values.
36 | ///
37 | /// The first value to compare.
38 | /// The second value to compare.
39 | /// True if the values are equal, false otherwise.
40 | public bool Equals(double x, double y)
41 | {
42 | return System.Math.Round(x, digits) == System.Math.Round(y, digits);
43 | }
44 |
45 | ///
46 | /// Returns a hash code for the double value.
47 | ///
48 | /// The value to get the hash code for.
49 | /// The hash code for the value.
50 | public int GetHashCode(double value)
51 | {
52 | return System.Math.Round(value, digits).GetHashCode();
53 | }
54 |
55 | }
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/Runtime/EqualityComparers/DoubleEqualityComparer.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: c84e8b285884cdc4ea462e7cd9e9df29
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/EqualityComparers/FloatEqualityComparer.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace Zigurous.Math
4 | {
5 | ///
6 | /// Compares the equality of float values using a specified amount of
7 | /// decimal digits to compare.
8 | ///
9 | public sealed class FloatEqualityComparer : IEqualityComparer
10 | {
11 | ///
12 | /// The number of decimal digits to compare when determining equality.
13 | ///
14 | public int digits;
15 |
16 | ///
17 | /// Creates a new FloatEqualityComparer with a default of 3 decimal
18 | /// digits to compare when determining equality.
19 | ///
20 | public FloatEqualityComparer()
21 | {
22 | this.digits = 3;
23 | }
24 |
25 | ///
26 | /// Creates a new FloatEqualityComparer with the specified number of
27 | /// decimal digits to compare when determining equality.
28 | ///
29 | public FloatEqualityComparer(int digits)
30 | {
31 | this.digits = digits;
32 | }
33 |
34 | ///
35 | /// Checks the equality of two float values.
36 | ///
37 | /// The first value to compare.
38 | /// The second value to compare.
39 | /// True if the values are equal, false otherwise.
40 | public bool Equals(float x, float y)
41 | {
42 | return System.Math.Round(x, digits) == System.Math.Round(y, digits);
43 | }
44 |
45 | ///
46 | /// Returns a hash code for the float value.
47 | ///
48 | /// The value to get the hash code for.
49 | /// The hash code for the value.
50 | public int GetHashCode(float value)
51 | {
52 | return System.Math.Round(value, digits).GetHashCode();
53 | }
54 |
55 | }
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/Runtime/EqualityComparers/FloatEqualityComparer.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: c40bde65347bfc64d88993a0aeea129d
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Extensions.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 75739b9c61b368845bb0719ab5f28dfa
3 | folderAsset: yes
4 | DefaultImporter:
5 | externalObjects: {}
6 | userData:
7 | assetBundleName:
8 | assetBundleVariant:
9 |
--------------------------------------------------------------------------------
/Runtime/Extensions/ArrayExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Zigurous.Math
4 | {
5 | ///
6 | /// Extension methods for arrays.
7 | ///
8 | public static class ArrayExtensions
9 | {
10 | ///
11 | /// Shuffles the array in place.
12 | ///
13 | /// The shuffle is done using the Fisher-Yates algorithm.
14 | /// The type of the array.
15 | /// The array to shuffle.
16 | public static void Shuffle(this T[] array)
17 | {
18 | int n = array.Length;
19 |
20 | while (n > 1)
21 | {
22 | int k = UnityEngine.Random.Range(0, n--);
23 | T temp = array[n];
24 | array[n] = array[k];
25 | array[k] = temp;
26 | }
27 | }
28 |
29 | ///
30 | /// Shuffles the array in place using the given random number generator.
31 | ///
32 | /// The shuffle is done using the Fisher-Yates algorithm.
33 | /// The type of the array.
34 | /// The array to shuffle.
35 | /// The random number generator to use.
36 | public static void Shuffle(this T[] array, Random rng)
37 | {
38 | int n = array.Length;
39 |
40 | while (n > 1)
41 | {
42 | int k = rng.Next(n--);
43 | T temp = array[n];
44 | array[n] = array[k];
45 | array[k] = temp;
46 | }
47 | }
48 |
49 | ///
50 | /// Calculates the sum of all elements in the array.
51 | ///
52 | /// The array to sum.
53 | /// The sum of all elements in the array.
54 | public static int Sum(this int[] array)
55 | {
56 | int sum = 0;
57 |
58 | for (int i = 0; i < array.Length; i++) {
59 | sum += array[i];
60 | }
61 |
62 | return sum;
63 | }
64 |
65 | ///
66 | /// Calculates the sum of all elements in the array.
67 | ///
68 | /// The array to sum.
69 | /// The sum of all elements in the array.
70 | public static float Sum(this float[] array)
71 | {
72 | float sum = 0;
73 |
74 | for (int i = 0; i < array.Length; i++) {
75 | sum += array[i];
76 | }
77 |
78 | return sum;
79 | }
80 |
81 | ///
82 | /// Calculates the sum of all elements in the array.
83 | ///
84 | /// The array to sum.
85 | /// The sum of all elements in the array.
86 | public static double Sum(this double[] array)
87 | {
88 | double sum = 0;
89 |
90 | for (int i = 0; i < array.Length; i++) {
91 | sum += array[i];
92 | }
93 |
94 | return sum;
95 | }
96 |
97 | }
98 |
99 | }
100 |
--------------------------------------------------------------------------------
/Runtime/Extensions/ArrayExtensions.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 10f4a2963402ec341925811e9f436dd1
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Extensions/BoundsExtensions.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 |
3 | namespace Zigurous.Math
4 | {
5 | ///
6 | /// Extension methods for Bounds.
7 | ///
8 | public static class BoundsExtensions
9 | {
10 | ///
11 | /// Linearly interpolates between the bounds' minimum and maximum values
12 | /// along each axis.
13 | ///
14 | /// The bounds to interpolate between.
15 | /// The interpolation value for each axis.
16 | /// The position as a result of the interpolation.
17 | public static Vector3 Lerp(this Bounds bounds, Vector3 t)
18 | {
19 | Vector3 position = new Vector3();
20 | position.x = Mathf.Lerp(bounds.min.x, bounds.max.x, t.x);
21 | position.y = Mathf.Lerp(bounds.min.y, bounds.max.y, t.y);
22 | position.z = Mathf.Lerp(bounds.min.z, bounds.max.z, t.z);
23 | return position;
24 | }
25 |
26 | ///
27 | /// Linearly interpolates between the bounds' minimum and maximum values
28 | /// along each axis.
29 | ///
30 | /// The bounds to interpolate between.
31 | /// The interpolation value for each axis.
32 | /// The position as a result of the interpolation.
33 | public static Vector3Int Lerp(this BoundsInt bounds, Vector3 t)
34 | {
35 | Vector3Int position = new Vector3Int();
36 | position.x = (int)Mathf.Lerp(bounds.min.x, bounds.max.x, t.x);
37 | position.y = (int)Mathf.Lerp(bounds.min.y, bounds.max.y, t.y);
38 | position.z = (int)Mathf.Lerp(bounds.min.z, bounds.max.z, t.z);
39 | return position;
40 | }
41 |
42 | ///
43 | /// Linearly interpolates between the bounds' minimum and maximum values
44 | /// along each axis with no limit to .
45 | ///
46 | /// The bounds to interpolate between.
47 | /// The interpolation value for each axis.
48 | /// The position as a result of the interpolation.
49 | public static Vector3 LerpUnclamped(this Bounds bounds, Vector3 t)
50 | {
51 | Vector3 position = new Vector3();
52 | position.x = Mathf.LerpUnclamped(bounds.min.x, bounds.max.x, t.x);
53 | position.y = Mathf.LerpUnclamped(bounds.min.y, bounds.max.y, t.y);
54 | position.z = Mathf.LerpUnclamped(bounds.min.z, bounds.max.z, t.z);
55 | return position;
56 | }
57 |
58 | ///
59 | /// Linearly interpolates between the bounds' minimum and maximum values
60 | /// along each axis with no limit to .
61 | ///
62 | /// The bounds to interpolate between.
63 | /// The interpolation value for each axis.
64 | /// The position as a result of the interpolation.
65 | public static Vector3Int LerpUnclamped(this BoundsInt bounds, Vector3 t)
66 | {
67 | Vector3Int position = new Vector3Int();
68 | position.x = (int)Mathf.LerpUnclamped(bounds.min.x, bounds.max.x, t.x);
69 | position.y = (int)Mathf.LerpUnclamped(bounds.min.y, bounds.max.y, t.y);
70 | position.z = (int)Mathf.LerpUnclamped(bounds.min.z, bounds.max.z, t.z);
71 | return position;
72 | }
73 |
74 | ///
75 | /// Returns the linear parameter t that produces the interpolant
76 | /// for each axis within the bounds' minimum and maximum values.
77 | ///
78 | /// The bounds to get the linear parameter from.
79 | /// A position within the bounds.
80 | /// The linear parameter t where each axis falls in the range [0..1].
81 | public static Vector3 InverseLerp(this Bounds bounds, Vector3 position)
82 | {
83 | Vector3 t = new Vector3();
84 | t.x = Mathf.InverseLerp(bounds.min.x, bounds.max.x, position.x);
85 | t.y = Mathf.InverseLerp(bounds.min.y, bounds.max.y, position.y);
86 | t.z = Mathf.InverseLerp(bounds.min.z, bounds.max.z, position.z);
87 | return t;
88 | }
89 |
90 | ///
91 | /// Returns the linear parameter t that produces the interpolant
92 | /// for each axis within the bounds' minimum and maximum values.
93 | ///
94 | /// The bounds to get the linear parameter from.
95 | /// A position within the bounds.
96 | /// The linear parameter t where each axis falls in the range [0..1].
97 | public static Vector3 InverseLerp(this BoundsInt bounds, Vector3Int position)
98 | {
99 | Vector3 t = new Vector3();
100 | t.x = Mathf.InverseLerp(bounds.min.x, bounds.max.x, position.x);
101 | t.y = Mathf.InverseLerp(bounds.min.y, bounds.max.y, position.y);
102 | t.z = Mathf.InverseLerp(bounds.min.z, bounds.max.z, position.z);
103 | return t;
104 | }
105 |
106 | ///
107 | /// Calculates the scale of the bounds required to fit inside another bounds.
108 | ///
109 | /// The bounds to calculate the scale of.
110 | /// The bounds to fit inside.
111 | /// The minimum value for each axis to be considered (default=0.00001).
112 | /// The scale of the bounds required to fit inside the area.
113 | public static float CalculateScale(this Bounds bounds, Bounds areaToFit, float epsilon = 0.00001f)
114 | {
115 | float scale = Mathf.Infinity;
116 |
117 | scale = CompareAxis(areaToFit.size.x, bounds.size.x, scale, epsilon);
118 | scale = CompareAxis(areaToFit.size.y, bounds.size.y, scale, epsilon);
119 | scale = CompareAxis(areaToFit.size.z, bounds.size.z, scale, epsilon);
120 |
121 | if (scale != Mathf.Infinity) {
122 | return scale;
123 | } else {
124 | return 1f;
125 | }
126 | }
127 |
128 | ///
129 | /// Calculates the scale of the bounds required to fit inside another bounds.
130 | ///
131 | /// The bounds to calculate the scale of.
132 | /// The bounds to fit inside.
133 | /// The scale of the bounds required to fit inside the area.
134 | public static float CalculateScale(this BoundsInt bounds, BoundsInt areaToFit)
135 | {
136 | float scale = Mathf.Infinity;
137 |
138 | scale = CompareAxis(areaToFit.size.x, bounds.size.x, scale, float.Epsilon);
139 | scale = CompareAxis(areaToFit.size.y, bounds.size.y, scale, float.Epsilon);
140 | scale = CompareAxis(areaToFit.size.z, bounds.size.z, scale, float.Epsilon);
141 |
142 | if (scale != Mathf.Infinity) {
143 | return scale;
144 | } else {
145 | return 1f;
146 | }
147 | }
148 |
149 | private static float CompareAxis(float a, float b, float currentScale, float epsilon)
150 | {
151 | if (a >= epsilon && b >= epsilon) {
152 | return Mathf.Min(a / b, currentScale);
153 | } else {
154 | return currentScale;
155 | }
156 | }
157 |
158 | ///
159 | /// Returns a random point inside the bounds.
160 | ///
161 | /// The bounds to get a random point from.
162 | /// A random point inside the bounds.
163 | public static Vector3 RandomPointInside(this Bounds bounds)
164 | {
165 | return new Vector3(
166 | Random.Range(bounds.min.x, bounds.max.x),
167 | Random.Range(bounds.min.y, bounds.max.y),
168 | Random.Range(bounds.min.z, bounds.max.z));
169 | }
170 |
171 | ///
172 | /// Returns a random point inside the bounds.
173 | ///
174 | /// The bounds to get a random point from.
175 | /// A random point inside the bounds.
176 | public static Vector3Int RandomPointInside(this BoundsInt bounds)
177 | {
178 | return new Vector3Int(
179 | Random.Range(bounds.min.x, bounds.max.x),
180 | Random.Range(bounds.min.y, bounds.max.y),
181 | Random.Range(bounds.min.z, bounds.max.z));
182 | }
183 |
184 | }
185 |
186 | }
187 |
--------------------------------------------------------------------------------
/Runtime/Extensions/BoundsExtensions.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 039ef072c6d49ba48812189dbc3f87fa
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Extensions/ColliderExtensions.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 |
3 | namespace Zigurous.Math
4 | {
5 | ///
6 | /// Extension methods for colliders.
7 | ///
8 | public static class ColliderExtensions
9 | {
10 | ///
11 | /// Returns a random point inside the collider's bounds.
12 | ///
13 | /// The collider to get a random point from.
14 | /// A random point inside the collider's bounds.
15 | public static Vector3 RandomPointInside(this Collider collider)
16 | {
17 | Vector3 randomPoint = collider.bounds.RandomPointInside();
18 | Vector3 closetPoint = collider.ClosestPoint(randomPoint);
19 |
20 | if (closetPoint == randomPoint) { // inside
21 | return randomPoint;
22 | } else { // outside
23 | return Vector3.Lerp(closetPoint, collider.bounds.center, Random.value);
24 | }
25 | }
26 |
27 | ///
28 | /// Returns a random point inside the collider's bounds.
29 | ///
30 | /// The collider to get a random point from.
31 | /// A random point inside the collider's bounds.
32 | public static Vector2 RandomPointInside(this Collider2D collider)
33 | {
34 | Vector2 randomPoint = collider.bounds.RandomPointInside();
35 | Vector2 closetPoint = collider.ClosestPoint(randomPoint);
36 |
37 | if (closetPoint == randomPoint) { // inside
38 | return randomPoint;
39 | } else { // outside
40 | return Vector2.Lerp(closetPoint, collider.bounds.center, Random.value);
41 | }
42 | }
43 |
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/Runtime/Extensions/ColliderExtensions.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: af5c9a1878795bb4daa1fe8c6abdee20
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Extensions/ComparableExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace Zigurous.Math
5 | {
6 | ///
7 | /// Extension methods for IComparable.
8 | ///
9 | public static class ComparableExtensions
10 | {
11 | ///
12 | /// Checks if the value is between a min and max value.
13 | ///
14 | /// The type of value to check.
15 | /// The value to check.
16 | /// The minimum value.
17 | /// The maximum value.
18 | /// The minimum value is inclusive if true, exclusive if false.
19 | /// The maximum value is inclusive if true, exclusive if false.
20 | /// True if the value is between the min and max value.
21 | public static bool IsBetween(this T value, T min, T max, bool includeMin = true, bool includeMax = true) where T : IComparable
22 | {
23 | int minCompare = value.CompareTo(min);
24 | int maxCompare = value.CompareTo(max);
25 |
26 | if (minCompare < 0 || maxCompare > 0) return false;
27 | if (!includeMin && minCompare == 0) return false;
28 | if (!includeMax && maxCompare == 0) return false;
29 |
30 | return true;
31 | }
32 |
33 | ///
34 | /// Checks if the value is in the range [min..max].
35 | ///
36 | /// The type of value to check.
37 | /// The value to check.
38 | /// The minimum value.
39 | /// The maximum value.
40 | /// True if the value is in the range [min..max].
41 | public static bool IsBetweenInclusive(this T value, T min, T max) where T : IComparable
42 | {
43 | return value.IsBetween(min, max, true, true);
44 | }
45 |
46 | ///
47 | /// Checks if the value is in the range [min..max).
48 | ///
49 | /// The type of value to check.
50 | /// The value to check.
51 | /// The minimum value.
52 | /// The maximum value.
53 | /// True if the value is in the range [min..max).
54 | public static bool IsBetweenInclusiveExclusive(this T value, T min, T max) where T : IComparable
55 | {
56 | return value.IsBetween(min, max, true, false);
57 | }
58 |
59 | ///
60 | /// Checks if the value is in the range (min..max).
61 | ///
62 | /// The type of value to check.
63 | /// The value to check.
64 | /// The minimum value.
65 | /// The maximum value.
66 | /// True if the value is in the range (min..max).
67 | public static bool IsBetweenExclusive(this T value, T min, T max) where T : IComparable
68 | {
69 | return value.IsBetween(min, max, false, false);
70 | }
71 |
72 | ///
73 | /// Checks if the value is in the range (min..max].
74 | ///
75 | /// The type of value to check.
76 | /// The value to check.
77 | /// The minimum value.
78 | /// The maximum value.
79 | /// True if the value is in the range (min..max].
80 | public static bool IsBetweenExclusiveInclusive(this T value, T min, T max) where T : IComparable
81 | {
82 | return value.IsBetween(min, max, false, true);
83 | }
84 |
85 | ///
86 | /// Returns the maximum value in the array.
87 | ///
88 | /// The type of value to check.
89 | /// The values to check.
90 | /// The maximum value in the array.
91 | public static T Max(this T[] values) where T : IComparable
92 | {
93 | if (values == null || values.Length == 0) {
94 | return default(T);
95 | }
96 |
97 | T max = values[0];
98 |
99 | for (int i = 1; i < values.Length; i++)
100 | {
101 | T element = values[i];
102 |
103 | if (element.CompareTo(max) > 0) {
104 | max = element;
105 | }
106 | }
107 |
108 | return max;
109 | }
110 |
111 | ///
112 | /// Returns the maximum value in the list.
113 | ///
114 | /// The type of value to check.
115 | /// The values to check.
116 | /// The maximum value in the list.
117 | public static T Max(this List values) where T : IComparable
118 | {
119 | if (values == null || values.Count == 0) {
120 | return default(T);
121 | }
122 |
123 | T max = values[0];
124 |
125 | for (int i = 1; i < values.Count; i++)
126 | {
127 | T element = values[i];
128 |
129 | if (element.CompareTo(max) > 0) {
130 | max = element;
131 | }
132 | }
133 |
134 | return max;
135 | }
136 |
137 | ///
138 | /// Returns the minimum value in the array.
139 | ///
140 | /// The type of value to check.
141 | /// The values to check.
142 | /// The minimum value in the array.
143 | public static T Min(this T[] values) where T : IComparable
144 | {
145 | if (values == null || values.Length == 0) {
146 | return default(T);
147 | }
148 |
149 | T min = values[0];
150 |
151 | for (int i = 1; i < values.Length; i++)
152 | {
153 | T element = values[i];
154 |
155 | if (element.CompareTo(min) < 0) {
156 | min = element;
157 | }
158 | }
159 |
160 | return min;
161 | }
162 |
163 | ///
164 | /// Returns the minimum value in the list.
165 | ///
166 | /// The type of value to check.
167 | /// The values to check.
168 | /// The minimum value in the list.
169 | public static T Min(this List values) where T : IComparable
170 | {
171 | if (values == null || values.Count == 0) {
172 | return default(T);
173 | }
174 |
175 | T min = values[0];
176 |
177 | for (int i = 1; i < values.Count; i++)
178 | {
179 | T element = values[i];
180 |
181 | if (element.CompareTo(min) < 0) {
182 | min = element;
183 | }
184 | }
185 |
186 | return min;
187 | }
188 |
189 | }
190 |
191 | }
192 |
--------------------------------------------------------------------------------
/Runtime/Extensions/ComparableExtensions.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: c1bc749dae3220f408f3bf0e033f912d
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Extensions/DoubleExtensions.cs:
--------------------------------------------------------------------------------
1 | namespace Zigurous.Math
2 | {
3 | ///
4 | /// Extension methods for doubles.
5 | ///
6 | public static class DoubleExtensions
7 | {
8 | ///
9 | /// Checks if the value is NaN.
10 | ///
11 | /// The value to check.
12 | /// True if the value is NaN.
13 | public static bool IsNaN(this double value)
14 | {
15 | return double.IsNaN(value);
16 | }
17 |
18 | ///
19 | /// Checks if the value is infinite.
20 | ///
21 | /// The value to check.
22 | /// True if the value is infinite.
23 | public static bool IsInfinite(this double value)
24 | {
25 | return double.IsInfinity(value);
26 | }
27 |
28 | ///
29 | /// Checks if the value is equal to positive infinity.
30 | ///
31 | /// The value to check.
32 | /// True if the value is equal to positive infinity.
33 | public static bool IsPositiveInfinity(this double value)
34 | {
35 | return double.IsPositiveInfinity(value);
36 | }
37 |
38 | ///
39 | /// Checks if the value is equal to negative infinity.
40 | ///
41 | /// The value to check.
42 | /// True if the value is equal to negative infinity.
43 | public static bool IsNegativeInfinity(this double value)
44 | {
45 | return double.IsNegativeInfinity(value);
46 | }
47 |
48 | ///
49 | /// Checks if the value is a real number (not infinite and not
50 | /// NaN).
51 | ///
52 | /// The value to check.
53 | /// True if the value is a real number.
54 | public static bool IsRealNumber(this double value)
55 | {
56 | return !double.IsInfinity(value) && !double.IsNaN(value);
57 | }
58 |
59 | ///
60 | /// Checks if the value is an imaginary number (infinite or NaN).
61 | ///
62 | /// The value to check.
63 | /// True if the value is an imaginary number.
64 | public static bool IsImaginaryNumber(this double value)
65 | {
66 | return double.IsInfinity(value) || double.IsNaN(value);
67 | }
68 |
69 | ///
70 | /// Checks if the value can be divided (not zero, not infinite, and not
71 | /// NaN).
72 | ///
73 | /// The value to check.
74 | /// True if the value can be divided.
75 | public static bool IsDividable(this double value)
76 | {
77 | return value != 0.0 && !double.IsInfinity(value) && !double.IsNaN(value);
78 | }
79 |
80 | ///
81 | /// Checks if the value is positive.
82 | ///
83 | /// The value to check.
84 | /// True if the value is positive.
85 | public static bool IsPositive(this double value)
86 | {
87 | return value > 0.0;
88 | }
89 |
90 | ///
91 | /// Checks if the value is negative.
92 | ///
93 | /// The value to check.
94 | /// True if the value is negative.
95 | public static bool IsNegative(this double value)
96 | {
97 | return value < 0.0;
98 | }
99 |
100 | ///
101 | /// Checks if the value is zero given a margin of error specified by an
102 | /// epsilon.
103 | ///
104 | /// The value to check.
105 | /// The margin of error.
106 | /// True if the value is zero.
107 | public static bool IsZero(this double value, double epsilon = double.Epsilon)
108 | {
109 | return (value > -epsilon) && (value < epsilon);
110 | }
111 |
112 | ///
113 | /// Checks for equality with another value given a margin of error
114 | /// specified by an epsilon.
115 | ///
116 | /// The left-hand side of the equality check.
117 | /// The right-hand side of the equality check.
118 | /// The margin of error.
119 | /// True if the values are equal.
120 | public static bool IsEqualTo(this double lhs, double rhs, double epsilon = double.Epsilon)
121 | {
122 | return System.Math.Abs(lhs - rhs) < epsilon;
123 | }
124 |
125 | ///
126 | /// Converts the number to an abbreviated string, e.g. "1k" for 1000.
127 | ///
128 | /// The number to abbreviate.
129 | /// The number abbreviated as a string, or the number as a string if no abbreviations apply.
130 | public static string ToAbbreviatedString(this double value)
131 | {
132 | return NumberAbbreviation.common.Format(value);
133 | }
134 |
135 | ///
136 | /// Converts the number to an abbreviated string with a given set of
137 | /// possible abbreviations.
138 | ///
139 | /// The number to abbreviate.
140 | /// The possible abbreviations.
141 | /// The number abbreviated as a string, or the number as a string if no abbreviations apply.
142 | public static string ToAbbreviatedString(this double value, NumberAbbreviation[] abbreviations)
143 | {
144 | return abbreviations.Format(value);
145 | }
146 |
147 | ///
148 | /// Sets the value to a new value if the value is an imaginary number
149 | /// (infinite or NaN).
150 | ///
151 | /// The value to check.
152 | /// The value to set if the original value is an imaginary number.
153 | public static void UnsetImaginary(this ref double value, double newValue = default(double))
154 | {
155 | if (IsImaginaryNumber(value)) {
156 | value = newValue;
157 | }
158 | }
159 |
160 | ///
161 | /// Sets the value to a new value if the value is an infinite number.
162 | ///
163 | /// The value to check.
164 | /// The value to set if the original value is infinite.
165 | public static void UnsetInfinite(this ref double value, double newValue = default(double))
166 | {
167 | if (IsInfinite(value)) {
168 | value = newValue;
169 | }
170 | }
171 |
172 | ///
173 | /// Sets the value to a new value if the value is NaN.
174 | ///
175 | /// The value to check.
176 | /// The value to set if the original value is NaN.
177 | public static void UnsetNaN(this ref double value, double newValue = default(double))
178 | {
179 | if (IsNaN(value)) {
180 | value = newValue;
181 | }
182 | }
183 |
184 | ///
185 | /// Sets the value to a new value if the value is zero given a margin of
186 | /// error specified by an epsilon.
187 | ///
188 | /// The value to check.
189 | /// The value to set if the original value is zero.
190 | /// The margin of error.
191 | public static void UnsetZero(this ref double value, double newValue = double.Epsilon, double epsilon = double.Epsilon)
192 | {
193 | if (IsZero(value, epsilon)) {
194 | value = newValue;
195 | }
196 | }
197 |
198 | }
199 |
200 | }
201 |
--------------------------------------------------------------------------------
/Runtime/Extensions/DoubleExtensions.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 6b707ceb77e01984f894fe211a914085
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Extensions/FloatExtensions.cs:
--------------------------------------------------------------------------------
1 | namespace Zigurous.Math
2 | {
3 | ///
4 | /// Extension methods for floats.
5 | ///
6 | public static class FloatExtensions
7 | {
8 | ///
9 | /// Sometimes Unity throws precision errors for really small numbers
10 | /// such as when setting transform values. Using float.Epsilon
11 | /// can still cause issues so this value is intended to be a safer
12 | /// alternative.
13 | ///
14 | public const float SAFE_FLOAT = 1.4E-32f;
15 |
16 | ///
17 | /// Checks if the value is NaN.
18 | ///
19 | /// The value to check.
20 | /// True if the value is NaN.
21 | public static bool IsNaN(this float value)
22 | {
23 | return float.IsNaN(value);
24 | }
25 |
26 | ///
27 | /// Checks if the value is infinite.
28 | ///
29 | /// The value to check.
30 | /// True if the value is infinite.
31 | public static bool IsInfinite(this float value)
32 | {
33 | return float.IsInfinity(value);
34 | }
35 |
36 | ///
37 | /// Checks if the value is equal to positive infinity.
38 | ///
39 | /// The value to check.
40 | /// True if the value is equal to positive infinity.
41 | public static bool IsPositiveInfinity(this float value)
42 | {
43 | return float.IsPositiveInfinity(value);
44 | }
45 |
46 | ///
47 | /// Checks if the value is equal to negative infinity.
48 | ///
49 | /// The value to check.
50 | /// True if the value is equal to negative infinity.
51 | public static bool IsNegativeInfinity(this float value)
52 | {
53 | return float.IsNegativeInfinity(value);
54 | }
55 |
56 | ///
57 | /// Checks if the value is a real number (not infinite and not NaN).
58 | ///
59 | /// The value to check.
60 | /// True if the value is a real number.
61 | public static bool IsRealNumber(this float value)
62 | {
63 | return !float.IsInfinity(value) && !float.IsNaN(value);
64 | }
65 |
66 | ///
67 | /// Checks if the value is an imaginary number (infinite or NaN).
68 | ///
69 | /// The value to check.
70 | /// True if the value is an imaginary number.
71 | public static bool IsImaginaryNumber(this float value)
72 | {
73 | return float.IsInfinity(value) || float.IsNaN(value);
74 | }
75 |
76 | ///
77 | /// Checks if the value can be divided (not zero, not infinite, and not
78 | /// NaN).
79 | ///
80 | /// The value to check.
81 | /// True if the value can be divided.
82 | public static bool IsDividable(this float value)
83 | {
84 | return value != 0f && !float.IsInfinity(value) && !float.IsNaN(value);
85 | }
86 |
87 | ///
88 | /// Checks if the value is positive.
89 | ///
90 | /// The value to check.
91 | /// True if the value is positive.
92 | public static bool IsPositive(this float value)
93 | {
94 | return value > 0f;
95 | }
96 |
97 | ///
98 | /// Checks if the value is negative.
99 | ///
100 | /// The value to check.
101 | /// True if the value is negative.
102 | public static bool IsNegative(this float value)
103 | {
104 | return value < 0f;
105 | }
106 |
107 | ///
108 | /// Checks if the value is zero given a margin of error specified by an
109 | /// epsilon.
110 | ///
111 | /// The value to check.
112 | /// The margin of error.
113 | /// True if the value is zero.
114 | public static bool IsZero(this float value, float epsilon = float.Epsilon)
115 | {
116 | return (value > -epsilon) && (value < epsilon);
117 | }
118 |
119 | ///
120 | /// Checks for equality with another value given a margin of error
121 | /// specified by an epsilon.
122 | ///
123 | /// The left-hand side of the equality check.
124 | /// The right-hand side of the equality check.
125 | /// The margin of error.
126 | /// True if the values are equal.
127 | public static bool IsEqualTo(this float lhs, float rhs, float epsilon = float.Epsilon)
128 | {
129 | return System.Math.Abs(lhs - rhs) < epsilon;
130 | }
131 |
132 | ///
133 | /// Converts the number to an abbreviated string, e.g. "1k" for 1000.
134 | ///
135 | /// The number to abbreviate.
136 | /// The number abbreviated as a string, or the number as a string if no abbreviations apply.
137 | public static string ToAbbreviatedString(this float number)
138 | {
139 | return NumberAbbreviation.common.Format(number);
140 | }
141 |
142 | ///
143 | /// Converts the number to an abbreviated string with a given set of
144 | /// possible abbreviations.
145 | ///
146 | /// The number to abbreviate.
147 | /// The abbreviations to use.
148 | /// The number abbreviated as a string, or the number as a string if no abbreviations apply.
149 | public static string ToAbbreviatedString(this float number, NumberAbbreviation[] abbreviations)
150 | {
151 | return abbreviations.Format(number);
152 | }
153 |
154 | ///
155 | /// Sets the value to a new value if the value is an imaginary number
156 | /// (infinite or NaN).
157 | ///
158 | /// The value to check.
159 | /// The value to set if the original value is an imaginary number.
160 | public static void UnsetImaginary(this ref float value, float newValue = default(float))
161 | {
162 | if (IsImaginaryNumber(value)) {
163 | value = newValue;
164 | }
165 | }
166 |
167 | ///
168 | /// Sets the value to a new value if the value is an infinite number.
169 | ///
170 | /// The value to check.
171 | /// The value to set if the original value is infinite.
172 | public static void UnsetInfinite(this ref float value, float newValue = default(float))
173 | {
174 | if (IsInfinite(value)) {
175 | value = newValue;
176 | }
177 | }
178 |
179 | ///
180 | /// Sets the value to a new value if the value is NaN.
181 | ///
182 | /// The value to check.
183 | /// The value to set if the original value is NaN.
184 | public static void UnsetNaN(this ref float value, float newValue = default(float))
185 | {
186 | if (IsNaN(value)) {
187 | value = newValue;
188 | }
189 | }
190 |
191 | ///
192 | /// Sets the value to a new value if the value is zero given a margin of
193 | /// error specified by an epsilon.
194 | ///
195 | /// The value to check.
196 | /// The value to set if the original value is zero.
197 | /// The margin of error.
198 | public static void UnsetZero(this ref float value, float newValue = SAFE_FLOAT, float epsilon = float.Epsilon)
199 | {
200 | if (IsZero(value, epsilon)) {
201 | value = newValue;
202 | }
203 | }
204 |
205 | }
206 |
207 | }
208 |
--------------------------------------------------------------------------------
/Runtime/Extensions/FloatExtensions.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 07d59d8aaeed4ac4b9bc5daea0d59c2b
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Extensions/IntExtensions.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 |
3 | namespace Zigurous.Math
4 | {
5 | ///
6 | /// Extension methods for integers.
7 | ///
8 | public static class IntExtensions
9 | {
10 | ///
11 | /// Returns a subset of bits from the number.
12 | ///
13 | /// The number to get bits from.
14 | /// The amount of bits to return.
15 | /// The amount of bits to discard.
16 | /// The subset of bits.
17 | public static int GetBits(this int n, int amount, int offset)
18 | {
19 | if (offset >= int.MaxValue) {
20 | return 0; // value is padded with infinite zeros on the left
21 | }
22 |
23 | n >>= offset; // drop offset bits
24 |
25 | if (amount >= int.MaxValue) {
26 | return n; // all bits
27 | }
28 |
29 | int mask = (1 << amount) - 1;
30 | return n & mask;
31 | }
32 |
33 | ///
34 | /// Checks if a given flag is set in the bitmask.
35 | /// (mask & flag) == flag
36 | ///
37 | /// The mask to check.
38 | /// The flag to check for.
39 | /// True if the flag is set in the mask.
40 | public static bool HasFlag(this int mask, int flag)
41 | {
42 | return (mask & flag) == flag;
43 | }
44 |
45 | ///
46 | /// Checks if any of the given flags are set in the bitmask.
47 | /// (mask & flags) != 0
48 | ///
49 | /// The mask to check.
50 | /// The flags to check for.
51 | /// True if any of the flags are set in the mask.
52 | public static bool HasAnyFlag(this int mask, int flags)
53 | {
54 | return (mask & flags) != 0;
55 | }
56 |
57 | ///
58 | /// Checks if the number is even.
59 | /// n % 2 == 0
60 | ///
61 | /// The number to check.
62 | /// True if the number is even.
63 | public static bool IsEven(this int n)
64 | {
65 | return n % 2 == 0;
66 | }
67 |
68 | ///
69 | /// Checks if the number is odd.
70 | /// n % 2 != 0
71 | ///
72 | /// The number to check.
73 | /// True if the number is odd.
74 | public static bool IsOdd(this int n)
75 | {
76 | return n % 2 != 0;
77 | }
78 |
79 | ///
80 | /// Checks if the number is zero.
81 | /// n == 0
82 | ///
83 | /// The number to check.
84 | /// True if the number is zero.
85 | public static bool IsZero(this int n)
86 | {
87 | return n == 0;
88 | }
89 |
90 | ///
91 | /// Checks if the number is positive.
92 | /// n > 0
93 | ///
94 | /// The number to check.
95 | /// True if the number is positive.
96 | public static bool IsPositive(this int n)
97 | {
98 | return n > 0;
99 | }
100 |
101 | ///
102 | /// Checks if the number is negative.
103 | /// n < 0
104 | ///
105 | /// The number to check.
106 | /// True if the number is negative.
107 | public static bool IsNegative(this int n)
108 | {
109 | return n < 0;
110 | }
111 |
112 | ///
113 | /// Returns the number of digits in the number.
114 | ///
115 | /// The number to check.
116 | /// The number of digits in the number.
117 | public static int NumDigits(this int n)
118 | {
119 | return Mathf.FloorToInt(Mathf.Log10((float)n) + 1f);
120 | }
121 |
122 | ///
123 | /// Converts the number to an abbreviated string, e.g. "1k" for 1000.
124 | ///
125 | /// The number to abbreviate.
126 | /// The number abbreviated as a string, or the number as a string if no abbreviations apply.
127 | public static string ToAbbreviatedString(this int n)
128 | {
129 | return NumberAbbreviation.common.Format(n);
130 | }
131 |
132 | ///
133 | /// Converts the number to an abbreviated string with a given set of
134 | /// possible abbreviations.
135 | ///
136 | /// The number to abbreviate.
137 | /// The abbreviations to use.
138 | /// The number abbreviated as a string, or the number as a string if no abbreviations apply.
139 | public static string ToAbbreviatedString(this int n, NumberAbbreviation[] abbreviations)
140 | {
141 | return abbreviations.Format(n);
142 | }
143 |
144 | ///
145 | /// Converts the number to a string of binary digits.
146 | ///
147 | /// The number to convert.
148 | /// The binary representation of the number.
149 | public static string ToBinaryString(this int n)
150 | {
151 | string binary = System.Convert.ToString(n, 2);
152 | return binary.PadLeft(32 - binary.Length, '0');
153 | }
154 |
155 | }
156 |
157 | }
158 |
--------------------------------------------------------------------------------
/Runtime/Extensions/IntExtensions.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 4a997bf41674ead44bbdcf87da36571c
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Extensions/ListExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace Zigurous.Math
5 | {
6 | ///
7 | /// Extension methods for lists.
8 | ///
9 | public static class ListExtensions
10 | {
11 | ///
12 | /// Shuffles the list in place.
13 | ///
14 | /// The shuffle is done using the Fisher-Yates algorithm.
15 | /// The type of the list.
16 | /// The list to shuffle.
17 | public static void Shuffle(this List list)
18 | {
19 | int n = list.Count;
20 |
21 | while (n > 1)
22 | {
23 | int k = UnityEngine.Random.Range(0, n--);
24 | T temp = list[n];
25 | list[n] = list[k];
26 | list[k] = temp;
27 | }
28 | }
29 |
30 | ///
31 | /// Shuffles the list in place using the given random number generator.
32 | ///
33 | /// The shuffle is done using the Fisher-Yates algorithm.
34 | /// The type of the list.
35 | /// The list to shuffle.
36 | /// The random number generator to use.
37 | public static void Shuffle(this List list, Random rng)
38 | {
39 | int n = list.Count;
40 |
41 | while (n > 1)
42 | {
43 | int k = rng.Next(n--);
44 | T temp = list[n];
45 | list[n] = list[k];
46 | list[k] = temp;
47 | }
48 | }
49 |
50 | ///
51 | /// Calculates the sum of all items in the list.
52 | ///
53 | /// The list to sum.
54 | /// The sum of all items in the list.
55 | public static int Sum(this List list)
56 | {
57 | int sum = 0;
58 |
59 | for (int i = 0; i < list.Count; i++) {
60 | sum += list[i];
61 | }
62 |
63 | return sum;
64 | }
65 |
66 | ///
67 | /// Calculates the sum of all items in the list.
68 | ///
69 | /// The list to sum.
70 | /// The sum of all items in the list.
71 | public static float Sum(this List list)
72 | {
73 | float sum = 0;
74 |
75 | for (int i = 0; i < list.Count; i++) {
76 | sum += list[i];
77 | }
78 |
79 | return sum;
80 | }
81 |
82 | ///
83 | /// Calculates the sum of all items in the list.
84 | ///
85 | /// The list to sum.
86 | /// The sum of all items in the list.
87 | public static double Sum(this List list)
88 | {
89 | double sum = 0;
90 |
91 | for (int i = 0; i < list.Count; i++) {
92 | sum += list[i];
93 | }
94 |
95 | return sum;
96 | }
97 |
98 | }
99 |
100 | }
101 |
--------------------------------------------------------------------------------
/Runtime/Extensions/ListExtensions.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 05c8fdc62daa97043934062ed301824a
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Extensions/LongExtensions.cs:
--------------------------------------------------------------------------------
1 | namespace Zigurous.Math
2 | {
3 | ///
4 | /// Extension methods for long integers.
5 | ///
6 | public static class LongExtensions
7 | {
8 | ///
9 | /// Returns a subset of bits from the number.
10 | ///
11 | /// The number to get bits from.
12 | /// The amount of bits to return.
13 | /// The amount of bits to discard.
14 | /// The subset of bits.
15 | public static long GetBits(this long n, int amount, int offset)
16 | {
17 | if (offset >= int.MaxValue) {
18 | return 0; // value is padded with infinite zeros on the left
19 | }
20 |
21 | n >>= offset; // drop offset bits
22 |
23 | if (amount >= int.MaxValue) {
24 | return n; // all bits
25 | }
26 |
27 | long mask = (1L << amount) - 1;
28 | return n & mask;
29 | }
30 |
31 | ///
32 | /// Checks if a given flag is set in the bitmask.
33 | /// (mask & flag) == flag
34 | ///
35 | /// The mask to check.
36 | /// The flag to check for.
37 | /// True if the flag is set in the mask.
38 | public static bool HasFlag(this long mask, long flag)
39 | {
40 | return (mask & flag) == flag;
41 | }
42 |
43 | ///
44 | /// Checks if any of the given flags are set in the bitmask.
45 | /// (mask & flags) != 0
46 | ///
47 | /// The mask to check.
48 | /// The flags to check for.
49 | /// True if any of the flags are set in the mask.
50 | public static bool HasAnyFlag(this long mask, long flags)
51 | {
52 | return (mask & flags) != 0;
53 | }
54 |
55 | ///
56 | /// Checks if the number is even.
57 | /// n % 2 == 0
58 | ///
59 | /// The number to check.
60 | /// True if the number is even.
61 | public static bool IsEven(this long n)
62 | {
63 | return n % 2 == 0;
64 | }
65 |
66 | ///
67 | /// Checks if the number is odd.
68 | /// n % 2 != 0
69 | ///
70 | /// The number to check.
71 | /// True if the number is odd.
72 | public static bool IsOdd(this long n)
73 | {
74 | return n % 2 != 0;
75 | }
76 |
77 | ///
78 | /// Checks if the number is zero.
79 | /// n == 0
80 | ///
81 | /// The number to check.
82 | /// True if the number is zero.
83 | public static bool IsZero(this long n)
84 | {
85 | return n == 0;
86 | }
87 |
88 | ///
89 | /// Checks if the number is positive.
90 | /// n > 0
91 | ///
92 | /// The number to check.
93 | /// True if the number is positive.
94 | public static bool IsPositive(this long n)
95 | {
96 | return n > 0;
97 | }
98 |
99 | ///
100 | /// Checks if the number is negative.
101 | /// n < 0
102 | ///
103 | /// The number to check.
104 | /// True if the number is negative.
105 | public static bool IsNegative(this long n)
106 | {
107 | return n < 0;
108 | }
109 |
110 | ///
111 | /// Converts the number to a string of binary digits.
112 | ///
113 | /// The number to convert.
114 | /// The binary representation of the number.
115 | public static string ToBinaryString(this long n)
116 | {
117 | string binary = System.Convert.ToString(n, 2);
118 | return binary.PadLeft(32 - binary.Length, '0');
119 | }
120 |
121 | }
122 |
123 | }
124 |
--------------------------------------------------------------------------------
/Runtime/Extensions/LongExtensions.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: ff8857fbf90a1ae42938ddaa241f0677
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Extensions/QuaternionExtensions.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 |
3 | namespace Zigurous.Math
4 | {
5 | ///
6 | /// Extension methods for Quaternion.
7 | ///
8 | public static class QuaternionExtensions
9 | {
10 | ///
11 | /// Gradually changes a quaternion towards a desired goal over time.
12 | /// The quaternion is smoothed by some spring-damper like function,
13 | /// which will never overshoot.
14 | ///
15 | /// The current position.
16 | /// The position we are trying to reach.
17 | /// The current velocity, this value is modified by the function every time you call it.
18 | /// Approximately the time it will take to reach the target. A smaller value will reach the target faster.
19 | /// Optionally allows the maximum speed to be clamped.
20 | /// The smoothed quaternion.
21 | public static Quaternion SmoothDamp(this Quaternion current, Quaternion target, ref Quaternion currentVelocity, float smoothTime, float maxSpeed = Mathf.Infinity)
22 | {
23 | float dot = Quaternion.Dot(current, target);
24 | float direction = dot > 0f ? 1f : -1f;
25 | target.x *= direction;
26 | target.y *= direction;
27 | target.z *= direction;
28 | target.w *= direction;
29 |
30 | Vector4 result = new Vector4(
31 | x: Mathf.SmoothDamp(current.x, target.x, ref currentVelocity.x, smoothTime, maxSpeed),
32 | y: Mathf.SmoothDamp(current.y, target.y, ref currentVelocity.y, smoothTime, maxSpeed),
33 | z: Mathf.SmoothDamp(current.z, target.z, ref currentVelocity.z, smoothTime, maxSpeed),
34 | w: Mathf.SmoothDamp(current.w, target.w, ref currentVelocity.w, smoothTime, maxSpeed)).normalized;
35 |
36 | Vector4 error = Vector4.Project(new Vector4(currentVelocity.x, currentVelocity.y, currentVelocity.z, currentVelocity.w), result);
37 | currentVelocity.x -= error.x;
38 | currentVelocity.y -= error.y;
39 | currentVelocity.z -= error.z;
40 | currentVelocity.w -= error.w;
41 |
42 | return new Quaternion(result.x, result.y, result.z, result.w);
43 | }
44 |
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/Runtime/Extensions/QuaternionExtensions.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 9f5c86fd411830642850b88cb64665f7
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Extensions/RectExtensions.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 |
3 | namespace Zigurous.Math
4 | {
5 | ///
6 | /// Extension methods for Rect.
7 | ///
8 | public static class RectExtensions
9 | {
10 | ///
11 | /// Determines if the rect fully contains another rect.
12 | ///
13 | /// The outer rect to test.
14 | /// The inner rect to test.
15 | /// Whether to include points that overlap on the edges (default=true).
16 | /// True if the rect fully contains the other rect.
17 | public static bool Contains(this Rect rect, Rect other, bool includeEdges = true)
18 | {
19 | if (includeEdges)
20 | {
21 | return other.min.x >= rect.min.x && other.min.y >= rect.min.y &&
22 | other.max.x <= rect.max.x && other.max.y <= rect.max.y;
23 | }
24 | else
25 | {
26 | return other.min.x > rect.min.x && other.min.y > rect.min.y &&
27 | other.max.x < rect.max.x && other.max.y < rect.max.y;
28 | }
29 | }
30 |
31 | ///
32 | /// Grows the rect to fully encapsulate another rect.
33 | ///
34 | /// The rect to grow.
35 | /// The rect to encapsulate.
36 | public static void Encapsulate(this ref Rect rect, Rect other)
37 | {
38 | rect = Rect.MinMaxRect(
39 | Mathf.Min(rect.xMin, other.xMin),
40 | Mathf.Min(rect.yMin, other.yMin),
41 | Mathf.Max(rect.xMax, other.xMax),
42 | Mathf.Max(rect.yMax, other.yMax));
43 | }
44 |
45 | ///
46 | /// Linearly interpolates between the rect's minimum and maximum values
47 | /// along each axis.
48 | ///
49 | /// The rect to interpolate between.
50 | /// The interpolation value for each axis.
51 | /// The position as a result of the interpolation.
52 | public static Vector2 Lerp(this Rect rect, Vector2 t)
53 | {
54 | Vector2 position = new Vector2();
55 | position.x = Mathf.Lerp(rect.min.x, rect.max.x, t.x);
56 | position.y = Mathf.Lerp(rect.min.y, rect.max.y, t.y);
57 | return position;
58 | }
59 |
60 | ///
61 | /// Linearly interpolates between the rect's minimum and maximum values
62 | /// along each axis with no limit to .
63 | ///
64 | /// The rect to interpolate between.
65 | /// The interpolation value for each axis.
66 | /// The position as a result of the interpolation.
67 | public static Vector2 LerpUnclamped(this Rect rect, Vector2 t)
68 | {
69 | Vector2 position = new Vector2();
70 | position.x = Mathf.LerpUnclamped(rect.min.x, rect.max.x, t.x);
71 | position.y = Mathf.LerpUnclamped(rect.min.y, rect.max.y, t.y);
72 | return position;
73 | }
74 |
75 | ///
76 | /// Returns the linear parameter t that produces the interpolant
77 | /// for each axis within the rect's minimum and maximum values.
78 | ///
79 | /// The rect to get the linear parameter from.
80 | /// A position within the rect.
81 | /// The linear parameter t where each axis falls in the range [0..1].
82 | public static Vector2 InverseLerp(this Rect rect, Vector2 position)
83 | {
84 | Vector2 t = new Vector2();
85 | t.x = Mathf.InverseLerp(rect.min.x, rect.max.x, position.x);
86 | t.y = Mathf.InverseLerp(rect.min.y, rect.max.y, position.y);
87 | return t;
88 | }
89 |
90 | }
91 |
92 | }
93 |
--------------------------------------------------------------------------------
/Runtime/Extensions/RectExtensions.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 072edff1fac37254c83992eb5196c76c
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Extensions/ShortExtensions.cs:
--------------------------------------------------------------------------------
1 | namespace Zigurous.Math
2 | {
3 | ///
4 | /// Extension methods for short integers.
5 | ///
6 | public static class ShortExtensions
7 | {
8 | ///
9 | /// Checks if a given flag is set in the bitmask.
10 | /// (mask & flag) == flag
11 | ///
12 | /// The mask to check.
13 | /// The flag to check for.
14 | /// True if the flag is set in the mask.
15 | public static bool HasFlag(this short mask, short flag)
16 | {
17 | return (mask & flag) == flag;
18 | }
19 |
20 | ///
21 | /// Checks if any of the given flags are set in the bitmask.
22 | /// (mask & flags) != 0
23 | ///
24 | /// The mask to check.
25 | /// The flags to check for.
26 | /// True if any of the flags are set in the mask.
27 | public static bool HasAnyFlag(this short mask, short flags)
28 | {
29 | return (mask & flags) != 0;
30 | }
31 |
32 | ///
33 | /// Checks if the number is even.
34 | /// n % 2 == 0
35 | ///
36 | /// The number to check.
37 | /// True if the number is even.
38 | public static bool IsEven(this short n)
39 | {
40 | return n % 2 == 0;
41 | }
42 |
43 | ///
44 | /// Checks if the number is odd.
45 | /// n % 2 != 0
46 | ///
47 | /// The number to check.
48 | /// True if the number is odd.
49 | public static bool IsOdd(this short n)
50 | {
51 | return n % 2 != 0;
52 | }
53 |
54 | ///
55 | /// Checks if the number is zero.
56 | /// n == 0
57 | ///
58 | /// The number to check.
59 | /// True if the number is zero.
60 | public static bool IsZero(this short n)
61 | {
62 | return n == 0;
63 | }
64 |
65 | ///
66 | /// Checks if the number is positive.
67 | /// n > 0
68 | ///
69 | /// The number to check.
70 | /// True if the number is positive.
71 | public static bool IsPositive(this short n)
72 | {
73 | return n > 0;
74 | }
75 |
76 | ///
77 | /// Checks if the number is negative.
78 | /// n < 0
79 | ///
80 | /// The number to check.
81 | /// True if the number is negative.
82 | public static bool IsNegative(this short n)
83 | {
84 | return n < 0;
85 | }
86 |
87 | ///
88 | /// Converts the number to a string of binary digits.
89 | ///
90 | /// The number to convert.
91 | /// The binary representation of the number.
92 | public static string ToBinaryString(this short n)
93 | {
94 | string binary = System.Convert.ToString(n, 2);
95 | return binary.PadLeft(32 - binary.Length, '0');
96 | }
97 |
98 | }
99 |
100 | }
101 |
--------------------------------------------------------------------------------
/Runtime/Extensions/ShortExtensions.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: fb56b1b2307dac9458046e644c7914e9
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Extensions/TransformExtensions.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 |
3 | namespace Zigurous.Math
4 | {
5 | ///
6 | /// Extension methods for Transform components.
7 | ///
8 | public static class TransformExtensions
9 | {
10 | ///
11 | /// Calculates the average position of the transform's children.
12 | ///
13 | /// The transform to calculate the average position of.
14 | /// The average position of the transform's children.
15 | public static Vector3 AveragePositionOfChildren(this Transform transform)
16 | {
17 | Vector3 center = Vector3.zero;
18 |
19 | foreach (Transform child in transform) {
20 | center += child.position;
21 | }
22 |
23 | return center / transform.childCount;
24 | }
25 |
26 | ///
27 | /// Calculates the center position of the transform's children.
28 | ///
29 | /// The transform to calculate the center position of.
30 | /// The center position of the transform's children.
31 | public static Vector3 CenterPositionOfChildren(this Transform transform)
32 | {
33 | Bounds bounds = new Bounds();
34 |
35 | foreach (Transform child in transform) {
36 | bounds.Encapsulate(child.position);
37 | }
38 |
39 | return bounds.center;
40 | }
41 |
42 | ///
43 | /// Resets the position, rotation, and scale of the transform.
44 | ///
45 | /// The transform to reset.
46 | public static void Reset(this Transform transform)
47 | {
48 | transform.position = Vector3.zero;
49 | transform.rotation = Quaternion.identity;
50 | transform.localScale = Vector3.one;
51 | }
52 |
53 | ///
54 | /// Resets the local position, rotation, and scale of the transform.
55 | ///
56 | /// The transform to reset.
57 | public static void ResetLocal(this Transform transform)
58 | {
59 | transform.localPosition = Vector3.zero;
60 | transform.localRotation = Quaternion.identity;
61 | transform.localScale = Vector3.one;
62 | }
63 |
64 | ///
65 | /// Sets the position of the transform in the x-axis.
66 | ///
67 | /// The transform to set the position of.
68 | /// The x-axis position to set.
69 | public static void SetPositionX(this Transform transform, float x)
70 | {
71 | transform.position = new Vector3(x, transform.position.y, transform.position.z);
72 | }
73 |
74 | ///
75 | /// Sets the position of the transform in the y-axis.
76 | ///
77 | /// The transform to set the position of.
78 | /// The y-axis position to set.
79 | public static void SetPositionY(this Transform transform, float y)
80 | {
81 | transform.position = new Vector3(transform.position.x, y, transform.position.z);
82 | }
83 |
84 | ///
85 | /// Sets the position of the transform in the z-axis.
86 | ///
87 | /// The transform to set the position of.
88 | /// The z-axis position to set.
89 | public static void SetPositionZ(this Transform transform, float z)
90 | {
91 | transform.position = new Vector3(transform.position.x, transform.position.y, z);
92 | }
93 |
94 | ///
95 | /// Sets the local position of the transform in the x-axis.
96 | ///
97 | /// The transform to set the local position of.
98 | /// The x-axis position to set.
99 | public static void SetLocalPositionX(this Transform transform, float x)
100 | {
101 | transform.localPosition = new Vector3(x, transform.localPosition.y, transform.localPosition.z);
102 | }
103 |
104 | ///
105 | /// Sets the local position of the transform in the y-axis.
106 | ///
107 | /// The transform to set the local position of.
108 | /// The y-axis position to set.
109 | public static void SetLocalPositionY(this Transform transform, float y)
110 | {
111 | transform.localPosition = new Vector3(transform.localPosition.x, y, transform.localPosition.z);
112 | }
113 |
114 | ///
115 | /// Sets the local position of the transform in the z-axis.
116 | ///
117 | /// The transform to set the local position of.
118 | /// The z-axis position to set.
119 | public static void SetLocalPositionZ(this Transform transform, float z)
120 | {
121 | transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y, z);
122 | }
123 |
124 | ///
125 | /// Sets the euler angles of the transform in the x-axis.
126 | ///
127 | /// The transform to set the euler angles of.
128 | /// The x-axis euler angle to set.
129 | public static void SetEulerAnglesX(this Transform transform, float x)
130 | {
131 | transform.eulerAngles = new Vector3(x, transform.eulerAngles.y, transform.eulerAngles.z);
132 | }
133 |
134 | ///
135 | /// Sets the euler angles of the transform in the y-axis.
136 | ///
137 | /// The transform to set the euler angles of.
138 | /// The y-axis euler angle to set.
139 | public static void SetEulerAnglesY(this Transform transform, float y)
140 | {
141 | transform.eulerAngles = new Vector3(transform.eulerAngles.x, y, transform.eulerAngles.z);
142 | }
143 |
144 | ///
145 | /// Sets the euler angles of the transform in the z-axis.
146 | ///
147 | /// The transform to set the euler angles of.
148 | /// The z-axis euler angle to set.
149 | public static void SetEulerAnglesZ(this Transform transform, float z)
150 | {
151 | transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, z);
152 | }
153 |
154 | ///
155 | /// Sets the local euler angles of the transform in the x-axis.
156 | ///
157 | /// The transform to set the local euler angles of.
158 | /// The x-axis euler angle to set.
159 | public static void SetLocalEulerAnglesX(this Transform transform, float x)
160 | {
161 | transform.localEulerAngles = new Vector3(x, transform.localEulerAngles.y, transform.localEulerAngles.z);
162 | }
163 |
164 | ///
165 | /// Sets the local euler angles of the transform in the y-axis.
166 | ///
167 | /// The transform to set the local euler angles of.
168 | /// The y-axis euler angle to set.
169 | public static void SetLocalEulerAnglesY(this Transform transform, float y)
170 | {
171 | transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, y, transform.localEulerAngles.z);
172 | }
173 |
174 | ///
175 | /// Sets the local euler angles of the transform in the z-axis.
176 | ///
177 | /// The transform to set the local euler angles of.
178 | /// The z-axis euler angle to set.
179 | public static void SetLocalEulerAnglesZ(this Transform transform, float z)
180 | {
181 | transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, transform.localEulerAngles.y, z);
182 | }
183 |
184 | ///
185 | /// Sets the scale of the transform in the x-axis.
186 | ///
187 | /// The transform to set the scale of.
188 | /// The x-axis scale to set.
189 | public static void SetLocalScaleX(this Transform transform, float x)
190 | {
191 | transform.localScale = new Vector3(x, transform.localScale.y, transform.localScale.z);
192 | }
193 |
194 | ///
195 | /// Sets the scale of the transform in the y-axis.
196 | ///
197 | /// The transform to set the scale of.
198 | /// The y-axis scale to set.
199 | public static void SetLocalScaleY(this Transform transform, float y)
200 | {
201 | transform.localScale = new Vector3(transform.localScale.x, y, transform.localScale.z);
202 | }
203 |
204 | ///
205 | /// Sets the scale of the transform in the z-axis.
206 | ///
207 | /// The transform to set the scale of.
208 | /// The z-axis scale to set.
209 | public static void SetLocalScaleZ(this Transform transform, float z)
210 | {
211 | transform.localScale = new Vector3(transform.localScale.x, transform.localScale.y, z);
212 | }
213 |
214 | }
215 |
216 | }
217 |
--------------------------------------------------------------------------------
/Runtime/Extensions/TransformExtensions.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: f559f06d97ee378468583f4254935854
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Extensions/UIntExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace Zigurous.Math
4 | {
5 | ///
6 | /// Extension methods for unsigned integers.
7 | ///
8 | public static class UIntExtensions
9 | {
10 | ///
11 | /// Returns the factors of the given number.
12 | ///
13 | /// The number to factor.
14 | /// The factors of the given number.
15 | public static IEnumerable Factors(this uint n)
16 | {
17 | for (uint x = 1; x * x <= n; x++)
18 | {
19 | if (n % x == 0)
20 | {
21 | yield return x;
22 |
23 | if (x != (n / x)) {
24 | yield return n / x;
25 | }
26 | }
27 | }
28 | }
29 |
30 | ///
31 | /// Returns a subset of bits from the number.
32 | ///
33 | /// The number to get bits from.
34 | /// The amount of bits to return.
35 | /// The amount of bits to discard.
36 | /// The subset of bits.
37 | public static uint GetBits(this uint n, int amount, int offset)
38 | {
39 | if (offset >= int.MaxValue) {
40 | return 0; // value is padded with infinite zeros on the left
41 | }
42 |
43 | n >>= offset; // drop offset bits
44 |
45 | if (amount >= int.MaxValue) {
46 | return n; // all bits
47 | }
48 |
49 | uint mask = (1U << amount) - 1;
50 | return n & mask;
51 | }
52 |
53 | ///
54 | /// Checks if a given flag is set in the bitmask.
55 | /// (mask & flag) == flag
56 | ///
57 | /// The mask to check.
58 | /// The flag to check for.
59 | /// True if the flag is set in the mask.
60 | public static bool HasFlag(this uint mask, uint flag)
61 | {
62 | return (mask & flag) == flag;
63 | }
64 |
65 | ///
66 | /// Checks if any of the given flags are set in the bitmask.
67 | /// (mask & flags) != 0
68 | ///
69 | /// The mask to check.
70 | /// The flags to check for.
71 | /// True if any of the flags are set in the mask.
72 | public static bool HasAnyFlag(this uint mask, uint flags)
73 | {
74 | return (mask & flags) != 0;
75 | }
76 |
77 | ///
78 | /// Checks if the number is even.
79 | /// n % 2 == 0
80 | ///
81 | /// The number to check.
82 | /// True if the number is even.
83 | public static bool IsEven(this uint n)
84 | {
85 | return n % 2 == 0;
86 | }
87 |
88 | ///
89 | /// Checks if the number is odd.
90 | /// n % 2 != 0
91 | ///
92 | /// The number to check.
93 | /// True if the number is odd.
94 | public static bool IsOdd(this uint n)
95 | {
96 | return n % 2 != 0;
97 | }
98 |
99 | ///
100 | /// Checks if the number is zero.
101 | /// n == 0
102 | ///
103 | /// The number to check.
104 | /// True if the number is zero.
105 | public static bool IsZero(this uint n)
106 | {
107 | return n == 0;
108 | }
109 |
110 | ///
111 | /// Checks if the number is positive.
112 | /// n > 0
113 | ///
114 | /// The number to check.
115 | /// True if the number is positive.
116 | public static bool IsPositive(this uint n)
117 | {
118 | return n > 0;
119 | }
120 |
121 | ///
122 | /// Converts the number to a string of binary digits.
123 | ///
124 | /// The number to convert.
125 | /// The binary representation of the number.
126 | public static string ToBinaryString(this uint n)
127 | {
128 | string binary = System.Convert.ToString(n, 2);
129 | return binary.PadLeft(32 - binary.Length, '0');
130 | }
131 |
132 | }
133 |
134 | }
135 |
--------------------------------------------------------------------------------
/Runtime/Extensions/UIntExtensions.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 76e3c382f8925c541b430c56d906ad98
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Extensions/Vector2Extensions.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 |
3 | namespace Zigurous.Math
4 | {
5 | ///
6 | /// Extension methods for Vector2.
7 | ///
8 | public static class Vector2Extensions
9 | {
10 | ///
11 | /// Returns the absolute value of the vector.
12 | ///
13 | /// The vector to return the absolute of.
14 | /// A new vector of the absolute value.
15 | public static Vector2 Abs(this Vector2 vector)
16 | {
17 | vector.x = System.Math.Abs(vector.x);
18 | vector.y = System.Math.Abs(vector.y);
19 | return vector;
20 | }
21 |
22 | ///
23 | /// Calculates the average of the vectors.
24 | ///
25 | /// The vectors to return the average of.
26 | /// A new vector of the average.
27 | public static Vector2 Average(this Vector2[] vectors)
28 | {
29 | Vector2 average = Vector2.zero;
30 |
31 | if (vectors.Length > 0)
32 | {
33 | for (int i = 0; i < vectors.Length; i++) {
34 | average += vectors[i];
35 | }
36 |
37 | average /= vectors.Length;
38 | }
39 |
40 | return average;
41 | }
42 |
43 | ///
44 | /// Rounds the vector up to the nearest whole number.
45 | ///
46 | /// The vector to round.
47 | public static void Ceil(this ref Vector2 vector)
48 | {
49 | vector.x = Mathf.Ceil(vector.x);
50 | vector.y = Mathf.Ceil(vector.y);
51 | }
52 |
53 | ///
54 | /// Rounds the vector up to the nearest whole number.
55 | ///
56 | /// The vector to round.
57 | /// A new rounded vector.
58 | public static Vector2 Ceiled(this Vector2 vector)
59 | {
60 | vector.x = Mathf.Ceil(vector.x);
61 | vector.y = Mathf.Ceil(vector.y);
62 | return vector;
63 | }
64 |
65 | ///
66 | /// Clamps the vector to the range [min..max].
67 | ///
68 | /// The vector to clamp.
69 | /// The minimum value.
70 | /// The maximum value.
71 | public static void Clamp(this ref Vector2 vector, Vector2 min, Vector2 max)
72 | {
73 | vector.x = Processors.Clamp(vector.x, min.x, max.x);
74 | vector.y = Processors.Clamp(vector.y, min.y, max.y);
75 | }
76 |
77 | ///
78 | /// Clamps the vector to the range [min..max].
79 | ///
80 | /// The vector to clamp.
81 | /// The minimum value.
82 | /// The maximum value.
83 | /// A new clamped vector.
84 | public static Vector2 Clamped(this Vector2 vector, Vector2 min, Vector2 max)
85 | {
86 | vector.x = Processors.Clamp(vector.x, min.x, max.x);
87 | vector.y = Processors.Clamp(vector.y, min.y, max.y);
88 | return vector;
89 | }
90 |
91 | ///
92 | /// Rounds the vector down to the nearest whole number.
93 | ///
94 | /// The vector to round.
95 | public static void Floor(this ref Vector2 vector)
96 | {
97 | vector.x = Mathf.Floor(vector.x);
98 | vector.y = Mathf.Floor(vector.y);
99 | }
100 |
101 | ///
102 | /// Rounds the vector down to the nearest whole number.
103 | ///
104 | /// The vector to round.
105 | /// A new rounded vector.
106 | public static Vector2 Floored(this Vector2 vector)
107 | {
108 | vector.x = Mathf.Floor(vector.x);
109 | vector.y = Mathf.Floor(vector.y);
110 | return vector;
111 | }
112 |
113 | ///
114 | /// Checks for equality with another vector given a margin of error
115 | /// specified by an epsilon.
116 | ///
117 | /// The left-hand side of the equality check.
118 | /// The right-hand side of the equality check.
119 | /// True if the values are equal.
120 | public static bool IsEqualTo(this Vector2 lhs, Vector2 rhs, float epsilon = float.Epsilon)
121 | {
122 | return lhs.x.IsEqualTo(rhs.x) &&
123 | lhs.y.IsEqualTo(rhs.y);
124 | }
125 |
126 | ///
127 | /// Checks if the vector is zero given a margin of error specified by
128 | /// an epsilon.
129 | ///
130 | /// The vector to check.
131 | /// The margin of error.
132 | /// True if the vector is considered zero.
133 | public static bool IsZero(this Vector2 vector, float epsilon = float.Epsilon)
134 | {
135 | return vector.x.IsZero(epsilon) &&
136 | vector.y.IsZero(epsilon);
137 | }
138 |
139 | ///
140 | /// Rounds the vector to the nearest whole number.
141 | ///
142 | /// The vector to round.
143 | public static void Round(this ref Vector2 vector)
144 | {
145 | vector.x = Mathf.Round(vector.x);
146 | vector.y = Mathf.Round(vector.y);
147 | }
148 |
149 | ///
150 | /// Rounds the vector to the nearest whole number.
151 | ///
152 | /// The vector to round.
153 | /// A new rounded vector.
154 | public static Vector2 Rounded(this Vector2 vector)
155 | {
156 | vector.x = Mathf.Round(vector.x);
157 | vector.y = Mathf.Round(vector.y);
158 | return vector;
159 | }
160 |
161 | ///
162 | /// Sets all components of the vector to the given value.
163 | ///
164 | /// The vector to set.
165 | /// The uniform component value.
166 | public static void SetUniform(this ref Vector2 vector, float value)
167 | {
168 | vector.x = value;
169 | vector.y = value;
170 | }
171 |
172 | ///
173 | /// Sets all components of the vector to the given value.
174 | ///
175 | /// The vector to set.
176 | /// The uniform component value.
177 | /// A new vector with the uniform component value.
178 | public static Vector2 SetUniformly(this Vector2 vector, float value)
179 | {
180 | vector.x = value;
181 | vector.y = value;
182 | return vector;
183 | }
184 |
185 | ///
186 | /// Wraps the vector to the range [min..max].
187 | ///
188 | /// The vector to wrap.
189 | /// The minimum value.
190 | /// The maximum value.
191 | public static void Wrap(this ref Vector2 vector, Vector2 min, Vector2 max)
192 | {
193 | vector.x = Processors.Wrap(vector.x, min.x, max.x);
194 | vector.y = Processors.Wrap(vector.y, min.y, max.y);
195 | }
196 |
197 | ///
198 | /// Wraps the vector to the range [min..max].
199 | ///
200 | /// The vector to wrap.
201 | /// The minimum value.
202 | /// The maximum value.
203 | /// A new wrapped vector.
204 | public static Vector2 Wrapped(this Vector2 vector, Vector2 min, Vector2 max)
205 | {
206 | vector.x = Processors.Wrap(vector.x, min.x, max.x);
207 | vector.y = Processors.Wrap(vector.y, min.y, max.y);
208 | return vector;
209 | }
210 |
211 | }
212 |
213 | }
214 |
--------------------------------------------------------------------------------
/Runtime/Extensions/Vector2Extensions.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 0b9378cf97f45ba419feacf69135bdb2
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Extensions/Vector2IntExtensions.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 |
3 | namespace Zigurous.Math
4 | {
5 | ///
6 | /// Extension methods for Vector2Int.
7 | ///
8 | public static class Vector2IntExtensions
9 | {
10 | ///
11 | /// Returns the absolute value of the vector.
12 | ///
13 | /// The vector to return the absolute of.
14 | /// A new vector of the absolute value.
15 | public static Vector2Int Abs(this Vector2Int vector)
16 | {
17 | vector.x = System.Math.Abs(vector.x);
18 | vector.y = System.Math.Abs(vector.y);
19 | return vector;
20 | }
21 |
22 | ///
23 | /// Calculates the average of the vectors.
24 | ///
25 | /// The vectors to return the average of.
26 | /// A new vector of the average.
27 | public static Vector2Int Average(this Vector2Int[] vectors)
28 | {
29 | Vector2Int average = Vector2Int.zero;
30 |
31 | if (vectors.Length > 0)
32 | {
33 | for (int i = 0; i < vectors.Length; i++) {
34 | average += vectors[i];
35 | }
36 |
37 | average /= vectors.Length;
38 | }
39 |
40 | return average;
41 | }
42 |
43 | ///
44 | /// Clamps the vector to the range [min..max].
45 | ///
46 | /// The vector to clamp.
47 | /// The minimum value.
48 | /// The maximum value.
49 | public static void Clamp(this ref Vector2Int vector, Vector2Int min, Vector2Int max)
50 | {
51 | vector.x = Processors.Clamp(vector.x, min.x, max.x);
52 | vector.y = Processors.Clamp(vector.y, min.y, max.y);
53 | }
54 |
55 | ///
56 | /// Clamps the vector to the range [min..max].
57 | ///
58 | /// The vector to clamp.
59 | /// The minimum value.
60 | /// The maximum value.
61 | /// A new clamped vector.
62 | public static Vector2Int Clamped(this Vector2Int vector, Vector2Int min, Vector2Int max)
63 | {
64 | vector.x = Processors.Clamp(vector.x, min.x, max.x);
65 | vector.y = Processors.Clamp(vector.y, min.y, max.y);
66 | return vector;
67 | }
68 |
69 | ///
70 | /// Sets all components of the vector to the given value.
71 | ///
72 | /// The vector to set.
73 | /// The uniform component value.
74 | public static void SetUniform(this ref Vector2Int vector, int value)
75 | {
76 | vector.x = value;
77 | vector.y = value;
78 | }
79 |
80 | ///
81 | /// Sets all components of the vector to the given value.
82 | ///
83 | /// The vector to set.
84 | /// The uniform component value.
85 | /// A new vector with the uniform component value.
86 | public static Vector2Int SetUniformly(this Vector2Int vector, int value)
87 | {
88 | vector.x = value;
89 | vector.y = value;
90 | return vector;
91 | }
92 |
93 | ///
94 | /// Wraps the vector to the range [min..max].
95 | ///
96 | /// The vector to wrap.
97 | /// The minimum value.
98 | /// The maximum value.
99 | public static void Wrap(this ref Vector2Int vector, Vector2Int min, Vector2Int max)
100 | {
101 | vector.x = Processors.Wrap(vector.x, min.x, max.x + 1);
102 | vector.y = Processors.Wrap(vector.y, min.y, max.y + 1);
103 | }
104 |
105 | ///
106 | /// Wraps the vector to the range [min..max].
107 | ///
108 | /// The vector to wrap.
109 | /// The minimum value.
110 | /// The maximum value.
111 | /// A new wrapped vector.
112 | public static Vector2Int Wrapped(this Vector2Int vector, Vector2Int min, Vector2Int max)
113 | {
114 | vector.x = Processors.Wrap(vector.x, min.x, max.x + 1);
115 | vector.y = Processors.Wrap(vector.y, min.y, max.y + 1);
116 | return vector;
117 | }
118 |
119 | }
120 |
121 | }
122 |
--------------------------------------------------------------------------------
/Runtime/Extensions/Vector2IntExtensions.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 274ed3dd7d50bec4c8e33e0e57d4f9cc
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Extensions/Vector3Extensions.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 |
3 | namespace Zigurous.Math
4 | {
5 | ///
6 | /// Extension methods for Vector3.
7 | ///
8 | public static class Vector3Extensions
9 | {
10 | ///
11 | /// Returns the absolute value of the vector.
12 | ///
13 | /// The vector to return the absolute of.
14 | /// A new vector of the absolute value.
15 | public static Vector3 Abs(this Vector3 vector)
16 | {
17 | vector.x = System.Math.Abs(vector.x);
18 | vector.y = System.Math.Abs(vector.y);
19 | vector.z = System.Math.Abs(vector.z);
20 | return vector;
21 | }
22 |
23 | ///
24 | /// Calculates the average of the vectors.
25 | ///
26 | /// The vectors to return the average of.
27 | /// A new vector of the average.
28 | public static Vector3 Average(this Vector3[] vectors)
29 | {
30 | Vector3 average = Vector3.zero;
31 |
32 | if (vectors.Length > 0)
33 | {
34 | for (int i = 0; i < vectors.Length; i++) {
35 | average += vectors[i];
36 | }
37 |
38 | average /= vectors.Length;
39 | }
40 |
41 | return average;
42 | }
43 |
44 | ///
45 | /// Rounds the vector up to the nearest whole number.
46 | ///
47 | /// The vector to round.
48 | public static void Ceil(this ref Vector3 vector)
49 | {
50 | vector.x = Mathf.Ceil(vector.x);
51 | vector.y = Mathf.Ceil(vector.y);
52 | vector.z = Mathf.Ceil(vector.z);
53 | }
54 |
55 | ///
56 | /// Rounds the vector up to the nearest whole number.
57 | ///
58 | /// The vector to round.
59 | /// A new rounded vector.
60 | public static Vector3 Ceiled(this Vector3 vector)
61 | {
62 | vector.x = Mathf.Ceil(vector.x);
63 | vector.y = Mathf.Ceil(vector.y);
64 | vector.z = Mathf.Ceil(vector.z);
65 | return vector;
66 | }
67 |
68 | ///
69 | /// Clamps the vector to the range [min..max].
70 | ///
71 | /// The vector to clamp.
72 | /// The minimum value.
73 | /// The maximum value.
74 | public static void Clamp(this ref Vector3 vector, Vector3 min, Vector3 max)
75 | {
76 | vector.x = Processors.Clamp(vector.x, min.x, max.x);
77 | vector.y = Processors.Clamp(vector.y, min.y, max.y);
78 | vector.z = Processors.Clamp(vector.z, min.z, max.z);
79 | }
80 |
81 | ///
82 | /// Clamps the vector to the range [min..max].
83 | ///
84 | /// The vector to clamp.
85 | /// The minimum value.
86 | /// The maximum value.
87 | /// A new clamped vector.
88 | public static Vector3 Clamped(this Vector3 vector, Vector3 min, Vector3 max)
89 | {
90 | vector.x = Processors.Clamp(vector.x, min.x, max.x);
91 | vector.y = Processors.Clamp(vector.y, min.y, max.y);
92 | vector.z = Processors.Clamp(vector.z, min.z, max.z);
93 | return vector;
94 | }
95 |
96 | ///
97 | /// Rounds the vector down to the nearest whole number.
98 | ///
99 | /// The vector to round.
100 | public static void Floor(this ref Vector3 vector)
101 | {
102 | vector.x = Mathf.Floor(vector.x);
103 | vector.y = Mathf.Floor(vector.y);
104 | vector.z = Mathf.Floor(vector.z);
105 | }
106 |
107 | ///
108 | /// Rounds the vector down to the nearest whole number.
109 | ///
110 | /// The vector to round.
111 | /// A new rounded vector.
112 | public static Vector3 Floored(this Vector3 vector)
113 | {
114 | vector.x = Mathf.Floor(vector.x);
115 | vector.y = Mathf.Floor(vector.y);
116 | vector.z = Mathf.Floor(vector.z);
117 | return vector;
118 | }
119 |
120 | ///
121 | /// Checks for equality with another vector given a margin of error
122 | /// specified by an epsilon.
123 | ///
124 | /// The left-hand side of the equality check.
125 | /// The right-hand side of the equality check.
126 | /// True if the values are equal.
127 | public static bool IsEqualTo(this Vector3 lhs, Vector3 rhs, float epsilon = float.Epsilon)
128 | {
129 | return lhs.x.IsEqualTo(rhs.x) &&
130 | lhs.y.IsEqualTo(rhs.y) &&
131 | lhs.z.IsEqualTo(rhs.z);
132 | }
133 |
134 | ///
135 | /// Checks if the vector is zero given a margin of error specified by
136 | /// an epsilon.
137 | ///
138 | /// The vector to check.
139 | /// The margin of error.
140 | /// True if the vector is considered zero.
141 | public static bool IsZero(this Vector3 vector, float epsilon = float.Epsilon)
142 | {
143 | return vector.x.IsZero(epsilon) &&
144 | vector.y.IsZero(epsilon) &&
145 | vector.z.IsZero(epsilon);
146 | }
147 |
148 | ///
149 | /// Rounds the vector to the nearest whole number.
150 | ///
151 | /// The vector to round.
152 | public static void Round(this ref Vector3 vector)
153 | {
154 | vector.x = Mathf.Round(vector.x);
155 | vector.y = Mathf.Round(vector.y);
156 | vector.z = Mathf.Round(vector.z);
157 | }
158 |
159 | ///
160 | /// Rounds the vector to the nearest whole number.
161 | ///
162 | /// The vector to round.
163 | /// A new rounded vector.
164 | public static Vector3 Rounded(this Vector3 vector)
165 | {
166 | vector.x = Mathf.Round(vector.x);
167 | vector.y = Mathf.Round(vector.y);
168 | vector.z = Mathf.Round(vector.z);
169 | return vector;
170 | }
171 |
172 | ///
173 | /// Sets all components of the vector to the given value.
174 | ///
175 | /// The vector to set.
176 | /// The uniform component value.
177 | public static void SetUniform(this ref Vector3 vector, float value)
178 | {
179 | vector.x = value;
180 | vector.y = value;
181 | vector.z = value;
182 | }
183 |
184 | ///
185 | /// Sets all components of the vector to the given value.
186 | ///
187 | /// The vector to set.
188 | /// The uniform component value.
189 | /// A new vector with the uniform component value.
190 | public static Vector3 SetUniformly(this Vector3 vector, float value)
191 | {
192 | vector.x = value;
193 | vector.y = value;
194 | vector.z = value;
195 | return vector;
196 | }
197 |
198 | ///
199 | /// Wraps the vector to the range [min..max].
200 | ///
201 | /// The vector to wrap.
202 | /// The minimum value.
203 | /// The maximum value.
204 | public static void Wrap(this ref Vector3 vector, Vector3 min, Vector3 max)
205 | {
206 | vector.x = Processors.Wrap(vector.x, min.x, max.x);
207 | vector.y = Processors.Wrap(vector.y, min.y, max.y);
208 | vector.z = Processors.Wrap(vector.z, min.z, max.z);
209 | }
210 |
211 | ///
212 | /// Wraps the vector to the range [min..max].
213 | ///
214 | /// The vector to wrap.
215 | /// The minimum value.
216 | /// The maximum value.
217 | /// A new wrapped vector.
218 | public static Vector3 Wrapped(this Vector3 vector, Vector3 min, Vector3 max)
219 | {
220 | vector.x = Processors.Wrap(vector.x, min.x, max.x);
221 | vector.y = Processors.Wrap(vector.y, min.y, max.y);
222 | vector.z = Processors.Wrap(vector.z, min.z, max.z);
223 | return vector;
224 | }
225 |
226 | }
227 |
228 | }
229 |
--------------------------------------------------------------------------------
/Runtime/Extensions/Vector3Extensions.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: fab491486d55ee84e9cc96d34e9d3e92
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Extensions/Vector3IntExtensions.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 |
3 | namespace Zigurous.Math
4 | {
5 | ///
6 | /// Extension methods for Vector3Int.
7 | ///
8 | public static class Vector3IntExtensions
9 | {
10 | ///
11 | /// Returns the absolute value of the vector.
12 | ///
13 | /// The vector to return the absolute of.
14 | /// A new vector of the absolute value.
15 | public static Vector3Int Abs(this Vector3Int vector)
16 | {
17 | vector.x = System.Math.Abs(vector.x);
18 | vector.y = System.Math.Abs(vector.y);
19 | vector.z = System.Math.Abs(vector.z);
20 | return vector;
21 | }
22 |
23 | ///
24 | /// Calculates the average of the vectors.
25 | ///
26 | /// The vectors to return the average of.
27 | /// A new vector of the average.
28 | public static Vector3Int Average(this Vector3Int[] vectors)
29 | {
30 | Vector3Int average = Vector3Int.zero;
31 |
32 | if (vectors.Length > 0)
33 | {
34 | for (int i = 0; i < vectors.Length; i++) {
35 | average += vectors[i];
36 | }
37 |
38 | average /= vectors.Length;
39 | }
40 |
41 | return average;
42 | }
43 |
44 | ///
45 | /// Clamps the vector to the range [min..max].
46 | ///
47 | /// The vector to clamp.
48 | /// The minimum value.
49 | /// The maximum value.
50 | public static void Clamp(this ref Vector3Int vector, Vector3Int min, Vector3Int max)
51 | {
52 | vector.x = Processors.Clamp(vector.x, min.x, max.x);
53 | vector.y = Processors.Clamp(vector.y, min.y, max.y);
54 | vector.z = Processors.Clamp(vector.z, min.z, max.z);
55 | }
56 |
57 | ///
58 | /// Clamps the vector to the range [min..max].
59 | ///
60 | /// The vector to clamp.
61 | /// The minimum value.
62 | /// The maximum value.
63 | /// A new clamped vector.
64 | public static Vector3Int Clamped(this Vector3Int vector, Vector3Int min, Vector3Int max)
65 | {
66 | vector.x = Processors.Clamp(vector.x, min.x, max.x);
67 | vector.y = Processors.Clamp(vector.y, min.y, max.y);
68 | vector.z = Processors.Clamp(vector.z, min.z, max.z);
69 | return vector;
70 | }
71 |
72 | ///
73 | /// Sets all components of the vector to the given value.
74 | ///
75 | /// The vector to set.
76 | /// The uniform component value.
77 | public static void SetUniform(this ref Vector3Int vector, int value)
78 | {
79 | vector.x = value;
80 | vector.y = value;
81 | vector.z = value;
82 | }
83 |
84 | ///
85 | /// Sets all components of the vector to the given value.
86 | ///
87 | /// The vector to set.
88 | /// The uniform component value.
89 | /// A new vector with the uniform component value.
90 | public static Vector3Int SetUniformly(this Vector3Int vector, int value)
91 | {
92 | vector.x = value;
93 | vector.y = value;
94 | vector.z = value;
95 | return vector;
96 | }
97 |
98 | ///
99 | /// Wraps the vector to the range [min..max].
100 | ///
101 | /// The vector to wrap.
102 | /// The minimum value.
103 | /// The maximum value.
104 | public static void Wrap(this ref Vector3Int vector, Vector3Int min, Vector3Int max)
105 | {
106 | vector.x = Processors.Wrap(vector.x, min.x, max.x + 1);
107 | vector.y = Processors.Wrap(vector.y, min.y, max.y + 1);
108 | vector.z = Processors.Wrap(vector.z, min.z, max.z + 1);
109 | }
110 |
111 | ///
112 | /// Wraps the vector to the range [min..max].
113 | ///
114 | /// The vector to wrap.
115 | /// The minimum value.
116 | /// The maximum value.
117 | /// A new wrapped vector.
118 | public static Vector3Int Wrapped(this Vector3Int vector, Vector3Int min, Vector3Int max)
119 | {
120 | vector.x = Processors.Wrap(vector.x, min.x, max.x + 1);
121 | vector.y = Processors.Wrap(vector.y, min.y, max.y + 1);
122 | vector.z = Processors.Wrap(vector.z, min.z, max.z + 1);
123 | return vector;
124 | }
125 |
126 | }
127 |
128 | }
129 |
--------------------------------------------------------------------------------
/Runtime/Extensions/Vector3IntExtensions.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 70f4880fc122f7a499a788c8ad46a0fd
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Extensions/Vector4Extensions.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 |
3 | namespace Zigurous.Math
4 | {
5 | ///
6 | /// Extension methods for Vector4.
7 | ///
8 | public static class Vector4Extensions
9 | {
10 | ///
11 | /// Returns the absolute value of the vector.
12 | ///
13 | /// The vector to return the absolute of.
14 | /// A new vector of the absolute value.
15 | public static Vector4 Abs(this Vector4 vector)
16 | {
17 | vector.x = System.Math.Abs(vector.x);
18 | vector.y = System.Math.Abs(vector.y);
19 | vector.z = System.Math.Abs(vector.z);
20 | vector.w = System.Math.Abs(vector.w);
21 | return vector;
22 | }
23 |
24 | ///
25 | /// Calculates the average of the vectors.
26 | ///
27 | /// The vectors to return the average of.
28 | /// A new vector of the average.
29 | public static Vector4 Average(this Vector4[] vectors)
30 | {
31 | Vector4 average = Vector4.zero;
32 |
33 | if (vectors.Length > 0)
34 | {
35 | for (int i = 0; i < vectors.Length; i++) {
36 | average += vectors[i];
37 | }
38 |
39 | average /= vectors.Length;
40 | }
41 |
42 | return average;
43 | }
44 |
45 | ///
46 | /// Rounds the vector up to the nearest whole number.
47 | ///
48 | /// The vector to round.
49 | public static void Ceil(this ref Vector4 vector)
50 | {
51 | vector.x = Mathf.Ceil(vector.x);
52 | vector.y = Mathf.Ceil(vector.y);
53 | vector.z = Mathf.Ceil(vector.z);
54 | vector.w = Mathf.Ceil(vector.w);
55 | }
56 |
57 | ///
58 | /// Rounds the vector up to the nearest whole number.
59 | ///
60 | /// The vector to round.
61 | /// A new rounded vector.
62 | public static Vector4 Ceiled(this Vector4 vector)
63 | {
64 | vector.x = Mathf.Ceil(vector.x);
65 | vector.y = Mathf.Ceil(vector.y);
66 | vector.z = Mathf.Ceil(vector.z);
67 | vector.w = Mathf.Ceil(vector.w);
68 | return vector;
69 | }
70 |
71 | ///
72 | /// Clamps the vector to the range [min..max].
73 | ///
74 | /// The vector to clamp.
75 | /// The minimum value.
76 | /// The maximum value.
77 | public static void Clamp(this ref Vector4 vector, Vector4 min, Vector4 max)
78 | {
79 | vector.x = Processors.Clamp(vector.x, min.x, max.x);
80 | vector.y = Processors.Clamp(vector.y, min.y, max.y);
81 | vector.z = Processors.Clamp(vector.z, min.z, max.z);
82 | vector.w = Processors.Clamp(vector.w, min.w, max.w);
83 | }
84 |
85 | ///
86 | /// Clamps the vector to the range [min..max].
87 | ///
88 | /// The vector to clamp.
89 | /// The minimum value.
90 | /// The maximum value.
91 | /// A new clamped vector.
92 | public static Vector4 Clamped(this Vector4 vector, Vector4 min, Vector4 max)
93 | {
94 | vector.x = Processors.Clamp(vector.x, min.x, max.x);
95 | vector.y = Processors.Clamp(vector.y, min.y, max.y);
96 | vector.z = Processors.Clamp(vector.z, min.z, max.z);
97 | vector.w = Processors.Clamp(vector.w, min.w, max.w);
98 | return vector;
99 | }
100 |
101 | ///
102 | /// Rounds the vector down to the nearest whole number.
103 | ///
104 | /// The vector to round.
105 | public static void Floor(this ref Vector4 vector)
106 | {
107 | vector.x = Mathf.Floor(vector.x);
108 | vector.y = Mathf.Floor(vector.y);
109 | vector.z = Mathf.Floor(vector.z);
110 | vector.w = Mathf.Floor(vector.w);
111 | }
112 |
113 | ///
114 | /// Rounds the vector down to the nearest whole number.
115 | ///
116 | /// The vector to round.
117 | /// A new rounded vector.
118 | public static Vector4 Floored(this Vector4 vector)
119 | {
120 | vector.x = Mathf.Floor(vector.x);
121 | vector.y = Mathf.Floor(vector.y);
122 | vector.z = Mathf.Floor(vector.z);
123 | vector.w = Mathf.Floor(vector.w);
124 | return vector;
125 | }
126 |
127 | ///
128 | /// Checks for equality with another vector given a margin of error
129 | /// specified by an epsilon.
130 | ///
131 | /// The left-hand side of the equality check.
132 | /// The right-hand side of the equality check.
133 | /// True if the values are equal.
134 | public static bool IsEqualTo(this Vector4 lhs, Vector4 rhs, float epsilon = float.Epsilon)
135 | {
136 | return lhs.x.IsEqualTo(rhs.x) &&
137 | lhs.y.IsEqualTo(rhs.y) &&
138 | lhs.z.IsEqualTo(rhs.z) &&
139 | lhs.w.IsEqualTo(rhs.w);
140 | }
141 |
142 | ///
143 | /// Checks if the vector is zero given a margin of error specified by
144 | /// an epsilon.
145 | ///
146 | /// The vector to check.
147 | /// The margin of error.
148 | /// True if the vector is considered zero.
149 | public static bool IsZero(this Vector4 vector, float epsilon = float.Epsilon)
150 | {
151 | return vector.x.IsZero(epsilon) &&
152 | vector.y.IsZero(epsilon) &&
153 | vector.z.IsZero(epsilon) &&
154 | vector.w.IsZero(epsilon);
155 | }
156 |
157 | ///
158 | /// Rounds the vector to the nearest whole number.
159 | ///
160 | /// The vector to round.
161 | public static void Round(this ref Vector4 vector)
162 | {
163 | vector.x = Mathf.Round(vector.x);
164 | vector.y = Mathf.Round(vector.y);
165 | vector.z = Mathf.Round(vector.z);
166 | vector.w = Mathf.Round(vector.w);
167 | }
168 |
169 | ///
170 | /// Rounds the vector to the nearest whole number.
171 | ///
172 | /// The vector to round.
173 | /// A new rounded vector.
174 | public static Vector4 Rounded(this Vector4 vector)
175 | {
176 | vector.x = Mathf.Round(vector.x);
177 | vector.y = Mathf.Round(vector.y);
178 | vector.z = Mathf.Round(vector.z);
179 | vector.w = Mathf.Round(vector.w);
180 | return vector;
181 | }
182 |
183 | ///
184 | /// Sets all components of the vector to the given value.
185 | ///
186 | /// The vector to set.
187 | /// The uniform component value.
188 | public static void SetUniform(this ref Vector4 vector, float value)
189 | {
190 | vector.x = value;
191 | vector.y = value;
192 | vector.z = value;
193 | vector.w = value;
194 | }
195 |
196 | ///
197 | /// Sets all components of the vector to the given value.
198 | ///
199 | /// The vector to set.
200 | /// The uniform component value.
201 | /// A new vector with the uniform component value.
202 | public static Vector4 SetUniformly(this Vector4 vector, float value)
203 | {
204 | vector.x = value;
205 | vector.y = value;
206 | vector.z = value;
207 | vector.w = value;
208 | return vector;
209 | }
210 |
211 | ///
212 | /// Wraps the vector to the range [min..max].
213 | ///
214 | /// The vector to wrap.
215 | /// The minimum value.
216 | /// The maximum value.
217 | public static void Wrap(this ref Vector4 vector, Vector4 min, Vector4 max)
218 | {
219 | vector.x = Processors.Wrap(vector.x, min.x, max.x);
220 | vector.y = Processors.Wrap(vector.y, min.y, max.y);
221 | vector.z = Processors.Wrap(vector.z, min.z, max.z);
222 | vector.w = Processors.Wrap(vector.w, min.w, max.w);
223 | }
224 |
225 | ///
226 | /// Wraps the vector to the range [min..max].
227 | ///
228 | /// The vector to wrap.
229 | /// The minimum value.
230 | /// The maximum value.
231 | /// A new wrapped vector.
232 | public static Vector4 Wrapped(this Vector4 vector, Vector4 min, Vector4 max)
233 | {
234 | vector.x = Processors.Wrap(vector.x, min.x, max.x);
235 | vector.y = Processors.Wrap(vector.y, min.y, max.y);
236 | vector.z = Processors.Wrap(vector.z, min.z, max.z);
237 | vector.w = Processors.Wrap(vector.w, min.w, max.w);
238 | return vector;
239 | }
240 |
241 | }
242 |
243 | }
244 |
--------------------------------------------------------------------------------
/Runtime/Extensions/Vector4Extensions.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: c4325ec25bc015a47be8a973213d607d
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/NumberAbbreviation.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 |
3 | namespace Zigurous.Math
4 | {
5 | ///
6 | /// Represents how a number is abbreviated to a string.
7 | ///
8 | [System.Serializable]
9 | public struct NumberAbbreviation
10 | {
11 | ///
12 | /// An abbreviation for numbers in the thousands (Read only).
13 | ///
14 | public static NumberAbbreviation thousands => new NumberAbbreviation(1_000, "0K");
15 |
16 | ///
17 | /// An abbreviation for numbers in the millions (Read only).
18 | ///
19 | public static NumberAbbreviation millions => new NumberAbbreviation(1_000_000, "0M");
20 |
21 | ///
22 | /// An abbreviation for numbers in the billions (Read only).
23 | ///
24 | public static NumberAbbreviation billions => new NumberAbbreviation(1_000_000_000, "0B");
25 |
26 | ///
27 | /// An abbreviation for numbers in the trillions (Read only).
28 | ///
29 | public static NumberAbbreviation trillions => new NumberAbbreviation(1_000_000_000_000, "0T");
30 |
31 | ///
32 | /// A predefined set of common number abbreviations (Read only).
33 | ///
34 | public static readonly NumberAbbreviation[] common = new NumberAbbreviation[4] {
35 | trillions,
36 | billions,
37 | millions,
38 | thousands,
39 | };
40 |
41 | ///
42 | /// The number factor after which the abbreviation is applied.
43 | ///
44 | [Tooltip("The number factor after which the abbreviation is applied.")]
45 | public double factor;
46 |
47 | ///
48 | /// The string format of the abbreviated number.
49 | ///
50 | [Tooltip("The string format of the abbreviated number.")]
51 | public string format;
52 |
53 | ///
54 | /// Creates a new number abbreviation with a given factor and format.
55 | ///
56 | /// The number factor after which the abbreviation is applied.
57 | /// The string format of the abbreviated number.
58 | public NumberAbbreviation(double factor, string format)
59 | {
60 | this.factor = factor;
61 | this.format = format;
62 | }
63 |
64 | ///
65 | /// Abbreviates a number to a string.
66 | ///
67 | /// The number to abbreviate.
68 | /// The number abbreviated as a string.
69 | public string Format(double number)
70 | {
71 | return (number / factor).ToString(format);
72 | }
73 |
74 | }
75 |
76 | ///
77 | /// Extension methods for .
78 | ///
79 | public static class NumberAbbreviationExtensions
80 | {
81 | ///
82 | /// Abbreviates a number to a string with the given set of abbreviations.
83 | ///
84 | /// The possible abbreviations to apply.
85 | /// The number to abbreviate.
86 | /// The number abbreviated as a string, or the number as a string if no abbreviations apply.
87 | public static string Format(this NumberAbbreviation[] abbreviations, float number)
88 | {
89 | float abs = System.Math.Abs(number);
90 |
91 | for (int i = 0; i < abbreviations.Length; i++)
92 | {
93 | NumberAbbreviation abbreviation = abbreviations[i];
94 |
95 | if (abs >= abbreviation.factor) {
96 | return abbreviation.Format(number);
97 | }
98 | }
99 |
100 | return number.ToString();
101 | }
102 |
103 | ///
104 | /// Abbreviates a number to a string with the given set of abbreviations.
105 | ///
106 | /// The possible abbreviations to apply.
107 | /// The number to abbreviate.
108 | /// The number abbreviated as a string, or the number as a string if no abbreviations apply.
109 | public static string Format(this NumberAbbreviation[] abbreviations, double number)
110 | {
111 | double abs = System.Math.Abs(number);
112 |
113 | for (int i = 0; i < abbreviations.Length; i++)
114 | {
115 | NumberAbbreviation abbreviation = abbreviations[i];
116 |
117 | if (abs >= abbreviation.factor) {
118 | return abbreviation.Format(number);
119 | }
120 | }
121 |
122 | return number.ToString();
123 | }
124 |
125 | ///
126 | /// Abbreviates a number to a string with the given set of abbreviations.
127 | ///
128 | /// The possible abbreviations to apply.
129 | /// The number to abbreviate.
130 | /// The number abbreviated as a string, or the number as a string if no abbreviations apply.
131 | public static string Format(this NumberAbbreviation[] abbreviations, int number)
132 | {
133 | int abs = System.Math.Abs(number);
134 |
135 | for (int i = 0; i < abbreviations.Length; i++)
136 | {
137 | NumberAbbreviation abbreviation = abbreviations[i];
138 |
139 | if (abs >= abbreviation.factor) {
140 | return abbreviation.Format(number);
141 | }
142 | }
143 |
144 | return number.ToString();
145 | }
146 |
147 | ///
148 | /// Abbreviates a number to a string with the given set of abbreviations.
149 | ///
150 | /// The possible abbreviations to apply.
151 | /// The number to abbreviate.
152 | /// The number abbreviated as a string, or the number as a string if no abbreviations apply.
153 | public static string Format(this NumberAbbreviation[] abbreviations, short number)
154 | {
155 | short abs = System.Math.Abs(number);
156 |
157 | for (int i = 0; i < abbreviations.Length; i++)
158 | {
159 | NumberAbbreviation abbreviation = abbreviations[i];
160 |
161 | if (abs >= abbreviation.factor) {
162 | return abbreviation.Format(number);
163 | }
164 | }
165 |
166 | return number.ToString();
167 | }
168 |
169 | ///
170 | /// Abbreviates a number to a string with the given set of abbreviations.
171 | ///
172 | /// The possible abbreviations to apply.
173 | /// The number to abbreviate.
174 | /// The number abbreviated as a string, or the number as a string if no abbreviations apply.
175 | public static string Format(this NumberAbbreviation[] abbreviations, long number)
176 | {
177 | long abs = System.Math.Abs(number);
178 |
179 | for (int i = 0; i < abbreviations.Length; i++)
180 | {
181 | NumberAbbreviation abbreviation = abbreviations[i];
182 |
183 | if (abs >= abbreviation.factor) {
184 | return abbreviation.Format(number);
185 | }
186 | }
187 |
188 | return number.ToString();
189 | }
190 |
191 | }
192 |
193 | }
194 |
--------------------------------------------------------------------------------
/Runtime/NumberAbbreviation.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 21624ccd9704f8348b20d71b0a7ec7be
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Processors.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 7740835b7d08efd46a3fcc9f3af88313
3 | MonoImporter:
4 | externalObjects: {}
5 | serializedVersion: 2
6 | defaultReferences: []
7 | executionOrder: 0
8 | icon: {instanceID: 0}
9 | userData:
10 | assetBundleName:
11 | assetBundleVariant:
12 |
--------------------------------------------------------------------------------
/Runtime/Zigurous.Math.asmdef:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Zigurous.Math",
3 | "references": [],
4 | "includePlatforms": [],
5 | "excludePlatforms": [],
6 | "allowUnsafeCode": false,
7 | "overrideReferences": false,
8 | "precompiledReferences": [],
9 | "autoReferenced": true,
10 | "defineConstraints": [],
11 | "versionDefines": [],
12 | "noEngineReferences": false
13 | }
14 |
--------------------------------------------------------------------------------
/Runtime/Zigurous.Math.asmdef.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 5ee7542a03445cc488c2ff3178d93e1b
3 | AssemblyDefinitionImporter:
4 | externalObjects: {}
5 | userData:
6 | assetBundleName:
7 | assetBundleVariant:
8 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "com.zigurous.math",
3 | "version": "1.2.0",
4 | "displayName": "Math Utils",
5 | "description": "The Math Utils package provides extensions and utilities for working with numbers in Unity projects including processing inputs, generating random numbers, and much more.",
6 | "unity": "2019.4",
7 | "repository": "https://github.com/zigurous/unity-math-utils",
8 | "documentationUrl": "https://docs.zigurous.com/com.zigurous.math",
9 | "changelogUrl": "https://docs.zigurous.com/com.zigurous.math/changelog",
10 | "licensesUrl": "https://docs.zigurous.com/com.zigurous.math/license",
11 | "keywords": [
12 | "math",
13 | "numbers",
14 | "random",
15 | "processors",
16 | "extensions"
17 | ],
18 | "publishConfig": {
19 | "registry": "https://npm.pkg.github.com/@zigurous"
20 | },
21 | "author": {
22 | "name": "Zigurous",
23 | "email": "support@zigurous.com",
24 | "url": "https://zigurous.com"
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/package.json.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 63956821e3680d644a74c9dc806d80e1
3 | TextScriptImporter:
4 | externalObjects: {}
5 | userData:
6 | assetBundleName:
7 | assetBundleVariant:
8 |
--------------------------------------------------------------------------------