адаптация s13bby/osc под vst и gui. (вайбкод)
вайбкод потому что мне в моменте стало понятно. что проще было сразу писать на фреймворке JUCE, чем адаптировать консольное приложение на MiniAudio. обновляться данный репозиторий не будет. СmakeLists адаптирован онли под linux.
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,354 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
An arbitrarily large integer class.
|
||||
|
||||
A BigInteger can be used in a similar way to a normal integer, but has no size
|
||||
limit (except for memory and performance constraints).
|
||||
|
||||
Negative values are possible, but the value isn't stored as 2s-complement, so
|
||||
be careful if you use negative values and look at the values of individual bits.
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
class JUCE_API BigInteger
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates an empty BigInteger */
|
||||
BigInteger();
|
||||
|
||||
/** Creates a BigInteger containing an integer value in its low bits.
|
||||
The low 32 bits of the number are initialised with this value.
|
||||
*/
|
||||
BigInteger (uint32 value);
|
||||
|
||||
/** Creates a BigInteger containing an integer value in its low bits.
|
||||
The low 32 bits of the number are initialised with the absolute value
|
||||
passed in, and its sign is set to reflect the sign of the number.
|
||||
*/
|
||||
BigInteger (int32 value);
|
||||
|
||||
/** Creates a BigInteger containing an integer value in its low bits.
|
||||
The low 64 bits of the number are initialised with the absolute value
|
||||
passed in, and its sign is set to reflect the sign of the number.
|
||||
*/
|
||||
BigInteger (int64 value);
|
||||
|
||||
/** Creates a copy of another BigInteger. */
|
||||
BigInteger (const BigInteger&);
|
||||
|
||||
/** Move constructor */
|
||||
BigInteger (BigInteger&&) noexcept;
|
||||
|
||||
/** Move assignment operator */
|
||||
BigInteger& operator= (BigInteger&&) noexcept;
|
||||
|
||||
/** Destructor. */
|
||||
~BigInteger();
|
||||
|
||||
//==============================================================================
|
||||
/** Copies another BigInteger onto this one. */
|
||||
BigInteger& operator= (const BigInteger&);
|
||||
|
||||
/** Swaps the internal contents of this with another object. */
|
||||
void swapWith (BigInteger&) noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the value of a specified bit in the number.
|
||||
If the index is out-of-range, the result will be false.
|
||||
*/
|
||||
bool operator[] (int bit) const noexcept;
|
||||
|
||||
/** Returns true if no bits are set. */
|
||||
bool isZero() const noexcept;
|
||||
|
||||
/** Returns true if the value is 1. */
|
||||
bool isOne() const noexcept;
|
||||
|
||||
/** Attempts to get the lowest 32 bits of the value as an integer.
|
||||
If the value is bigger than the integer limits, this will return only the lower bits.
|
||||
*/
|
||||
int toInteger() const noexcept;
|
||||
|
||||
/** Attempts to get the lowest 64 bits of the value as an integer.
|
||||
If the value is bigger than the integer limits, this will return only the lower bits.
|
||||
*/
|
||||
int64 toInt64() const noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Resets the value to 0. */
|
||||
BigInteger& clear() noexcept;
|
||||
|
||||
/** Clears a particular bit in the number. */
|
||||
BigInteger& clearBit (int bitNumber) noexcept;
|
||||
|
||||
/** Sets a specified bit to 1. */
|
||||
BigInteger& setBit (int bitNumber);
|
||||
|
||||
/** Sets or clears a specified bit. */
|
||||
BigInteger& setBit (int bitNumber, bool shouldBeSet);
|
||||
|
||||
/** Sets a range of bits to be either on or off.
|
||||
|
||||
@param startBit the first bit to change
|
||||
@param numBits the number of bits to change
|
||||
@param shouldBeSet whether to turn these bits on or off
|
||||
*/
|
||||
BigInteger& setRange (int startBit, int numBits, bool shouldBeSet);
|
||||
|
||||
/** Inserts a bit an a given position, shifting up any bits above it. */
|
||||
BigInteger& insertBit (int bitNumber, bool shouldBeSet);
|
||||
|
||||
/** Returns a range of bits as a new BigInteger.
|
||||
|
||||
e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
|
||||
@see getBitRangeAsInt
|
||||
*/
|
||||
BigInteger getBitRange (int startBit, int numBits) const;
|
||||
|
||||
/** Returns a range of bits as an integer value.
|
||||
|
||||
e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
|
||||
|
||||
Asking for more than 32 bits isn't allowed (obviously) - for that, use
|
||||
getBitRange().
|
||||
*/
|
||||
uint32 getBitRangeAsInt (int startBit, int numBits) const noexcept;
|
||||
|
||||
/** Sets a range of bits to an integer value.
|
||||
|
||||
Copies the given integer onto a range of bits, starting at startBit,
|
||||
and using up to numBits of the available bits.
|
||||
*/
|
||||
BigInteger& setBitRangeAsInt (int startBit, int numBits, uint32 valueToSet);
|
||||
|
||||
/** Shifts a section of bits left or right.
|
||||
|
||||
@param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
|
||||
@param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
|
||||
*/
|
||||
BigInteger& shiftBits (int howManyBitsLeft, int startBit);
|
||||
|
||||
/** Returns the total number of set bits in the value. */
|
||||
int countNumberOfSetBits() const noexcept;
|
||||
|
||||
/** Looks for the index of the next set bit after a given starting point.
|
||||
|
||||
This searches from startIndex (inclusive) upwards for the first set bit,
|
||||
and returns its index. If no set bits are found, it returns -1.
|
||||
*/
|
||||
int findNextSetBit (int startIndex) const noexcept;
|
||||
|
||||
/** Looks for the index of the next clear bit after a given starting point.
|
||||
|
||||
This searches from startIndex (inclusive) upwards for the first clear bit,
|
||||
and returns its index.
|
||||
*/
|
||||
int findNextClearBit (int startIndex) const noexcept;
|
||||
|
||||
/** Returns the index of the highest set bit in the number.
|
||||
If the value is zero, this will return -1.
|
||||
*/
|
||||
int getHighestBit() const noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Returns true if the value is less than zero.
|
||||
@see setNegative, negate
|
||||
*/
|
||||
bool isNegative() const noexcept;
|
||||
|
||||
/** Changes the sign of the number to be positive or negative.
|
||||
@see isNegative, negate
|
||||
*/
|
||||
void setNegative (bool shouldBeNegative) noexcept;
|
||||
|
||||
/** Inverts the sign of the number.
|
||||
@see isNegative, setNegative
|
||||
*/
|
||||
void negate() noexcept;
|
||||
|
||||
//==============================================================================
|
||||
// All the standard arithmetic ops...
|
||||
|
||||
BigInteger& operator+= (const BigInteger&);
|
||||
BigInteger& operator-= (const BigInteger&);
|
||||
BigInteger& operator*= (const BigInteger&);
|
||||
BigInteger& operator/= (const BigInteger&);
|
||||
BigInteger& operator|= (const BigInteger&);
|
||||
BigInteger& operator&= (const BigInteger&);
|
||||
BigInteger& operator^= (const BigInteger&);
|
||||
BigInteger& operator%= (const BigInteger&);
|
||||
BigInteger& operator<<= (int numBitsToShift);
|
||||
BigInteger& operator>>= (int numBitsToShift);
|
||||
BigInteger& operator++();
|
||||
BigInteger& operator--();
|
||||
BigInteger operator++ (int);
|
||||
BigInteger operator-- (int);
|
||||
|
||||
BigInteger operator-() const;
|
||||
BigInteger operator+ (const BigInteger&) const;
|
||||
BigInteger operator- (const BigInteger&) const;
|
||||
BigInteger operator* (const BigInteger&) const;
|
||||
BigInteger operator/ (const BigInteger&) const;
|
||||
BigInteger operator| (const BigInteger&) const;
|
||||
BigInteger operator& (const BigInteger&) const;
|
||||
BigInteger operator^ (const BigInteger&) const;
|
||||
BigInteger operator% (const BigInteger&) const;
|
||||
BigInteger operator<< (int numBitsToShift) const;
|
||||
BigInteger operator>> (int numBitsToShift) const;
|
||||
|
||||
bool operator== (const BigInteger&) const noexcept;
|
||||
bool operator!= (const BigInteger&) const noexcept;
|
||||
bool operator< (const BigInteger&) const noexcept;
|
||||
bool operator<= (const BigInteger&) const noexcept;
|
||||
bool operator> (const BigInteger&) const noexcept;
|
||||
bool operator>= (const BigInteger&) const noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Does a signed comparison of two BigIntegers.
|
||||
|
||||
Return values are:
|
||||
- 0 if the numbers are the same
|
||||
- < 0 if this number is smaller than the other
|
||||
- > 0 if this number is bigger than the other
|
||||
*/
|
||||
int compare (const BigInteger& other) const noexcept;
|
||||
|
||||
/** Compares the magnitudes of two BigIntegers, ignoring their signs.
|
||||
|
||||
Return values are:
|
||||
- 0 if the numbers are the same
|
||||
- < 0 if this number is smaller than the other
|
||||
- > 0 if this number is bigger than the other
|
||||
*/
|
||||
int compareAbsolute (const BigInteger& other) const noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Divides this value by another one and returns the remainder.
|
||||
|
||||
This number is divided by other, leaving the quotient in this number,
|
||||
with the remainder being copied to the other BigInteger passed in.
|
||||
*/
|
||||
void divideBy (const BigInteger& divisor, BigInteger& remainder);
|
||||
|
||||
/** Returns the largest value that will divide both this value and the argument. */
|
||||
BigInteger findGreatestCommonDivisor (BigInteger other) const;
|
||||
|
||||
/** Performs a combined exponent and modulo operation.
|
||||
This BigInteger's value becomes (this ^ exponent) % modulus.
|
||||
*/
|
||||
void exponentModulo (const BigInteger& exponent, const BigInteger& modulus);
|
||||
|
||||
/** Performs an inverse modulo on the value.
|
||||
i.e. the result is (this ^ -1) mod (modulus).
|
||||
*/
|
||||
void inverseModulo (const BigInteger& modulus);
|
||||
|
||||
/** Performs the Montgomery Multiplication with modulo.
|
||||
This object is left containing the result value: ((this * other) * R1) % modulus.
|
||||
To get this result, we need modulus, modulusp and k such as R = 2^k, with
|
||||
modulus * modulusp - R * R1 = GCD(modulus, R) = 1
|
||||
*/
|
||||
void montgomeryMultiplication (const BigInteger& other, const BigInteger& modulus,
|
||||
const BigInteger& modulusp, int k);
|
||||
|
||||
/** Performs the Extended Euclidean algorithm.
|
||||
This method will set the xOut and yOut arguments such that (a * xOut) - (b * yOut) = GCD (a, b).
|
||||
On return, this object is left containing the value of the GCD.
|
||||
*/
|
||||
void extendedEuclidean (const BigInteger& a, const BigInteger& b,
|
||||
BigInteger& xOut, BigInteger& yOut);
|
||||
|
||||
//==============================================================================
|
||||
/** Converts the number to a string.
|
||||
|
||||
Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
|
||||
If minimumNumCharacters is greater than 0, the returned string will be
|
||||
padded with leading zeros to reach at least that length.
|
||||
*/
|
||||
String toString (int base, int minimumNumCharacters = 1) const;
|
||||
|
||||
/** Reads the numeric value from a string.
|
||||
|
||||
Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
|
||||
Any invalid characters will be ignored.
|
||||
*/
|
||||
void parseString (StringRef text, int base);
|
||||
|
||||
//==============================================================================
|
||||
/** Turns the number into a block of binary data.
|
||||
|
||||
The data is arranged as little-endian, so the first byte of data is the low 8 bits
|
||||
of the number, and so on.
|
||||
|
||||
@see loadFromMemoryBlock
|
||||
*/
|
||||
MemoryBlock toMemoryBlock() const;
|
||||
|
||||
/** Converts a block of raw data into a number.
|
||||
|
||||
The data is arranged as little-endian, so the first byte of data is the low 8 bits
|
||||
of the number, and so on.
|
||||
|
||||
@see toMemoryBlock
|
||||
*/
|
||||
void loadFromMemoryBlock (const MemoryBlock& data);
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
enum { numPreallocatedInts = 4 };
|
||||
HeapBlock<uint32> heapAllocation;
|
||||
uint32 preallocated[numPreallocatedInts];
|
||||
size_t allocatedSize;
|
||||
int highestBit = -1;
|
||||
bool negative = false;
|
||||
|
||||
uint32* getValues() const noexcept;
|
||||
uint32* ensureSize (size_t);
|
||||
void shiftLeft (int bits, int startBit);
|
||||
void shiftRight (int bits, int startBit);
|
||||
|
||||
JUCE_LEAK_DETECTOR (BigInteger)
|
||||
};
|
||||
|
||||
/** Writes a BigInteger to an OutputStream as a UTF8 decimal string. */
|
||||
OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value);
|
||||
|
||||
} // namespace juce
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,263 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A class for dynamically evaluating simple numeric expressions.
|
||||
|
||||
This class can parse a simple C-style string expression involving floating point
|
||||
numbers, named symbols and functions. The basic arithmetic operations of +, -, *, /
|
||||
are supported, as well as parentheses, and any alphanumeric identifiers are
|
||||
assumed to be named symbols which will be resolved when the expression is
|
||||
evaluated.
|
||||
|
||||
Expressions which use identifiers and functions require a subclass of
|
||||
Expression::Scope to be supplied when evaluating them, and this object
|
||||
is expected to be able to resolve the symbol names and perform the functions that
|
||||
are used.
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
class JUCE_API Expression
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates a simple expression with a value of 0. */
|
||||
Expression();
|
||||
|
||||
/** Destructor. */
|
||||
~Expression();
|
||||
|
||||
/** Creates a copy of an expression. */
|
||||
Expression (const Expression&);
|
||||
|
||||
/** Copies another expression. */
|
||||
Expression& operator= (const Expression&);
|
||||
|
||||
/** Move constructor */
|
||||
Expression (Expression&&) noexcept;
|
||||
|
||||
/** Move assignment operator */
|
||||
Expression& operator= (Expression&&) noexcept;
|
||||
|
||||
/** Creates a simple expression with a specified constant value. */
|
||||
explicit Expression (double constant);
|
||||
|
||||
/** Attempts to create an expression by parsing a string.
|
||||
Any errors are returned in the parseError argument provided.
|
||||
*/
|
||||
Expression (const String& stringToParse, String& parseError);
|
||||
|
||||
/** Returns a string version of the expression. */
|
||||
String toString() const;
|
||||
|
||||
/** Returns an expression which is an addition operation of two existing expressions. */
|
||||
Expression operator+ (const Expression&) const;
|
||||
/** Returns an expression which is a subtraction operation of two existing expressions. */
|
||||
Expression operator- (const Expression&) const;
|
||||
/** Returns an expression which is a multiplication operation of two existing expressions. */
|
||||
Expression operator* (const Expression&) const;
|
||||
/** Returns an expression which is a division operation of two existing expressions. */
|
||||
Expression operator/ (const Expression&) const;
|
||||
/** Returns an expression which performs a negation operation on an existing expression. */
|
||||
Expression operator-() const;
|
||||
|
||||
/** Returns an Expression which is an identifier reference. */
|
||||
static Expression symbol (const String& symbol);
|
||||
|
||||
/** Returns an Expression which is a function call. */
|
||||
static Expression function (const String& functionName, const Array<Expression>& parameters);
|
||||
|
||||
/** Returns an Expression which parses a string from a character pointer, and updates the pointer
|
||||
to indicate where it finished.
|
||||
|
||||
The pointer is incremented so that on return, it indicates the character that follows
|
||||
the end of the expression that was parsed.
|
||||
|
||||
If there's a syntax error in parsing, the parseError argument will be set
|
||||
to a description of the problem.
|
||||
*/
|
||||
static Expression parse (String::CharPointerType& stringToParse, String& parseError);
|
||||
|
||||
//==============================================================================
|
||||
/** When evaluating an Expression object, this class is used to resolve symbols and
|
||||
perform functions that the expression uses.
|
||||
*/
|
||||
class JUCE_API Scope
|
||||
{
|
||||
public:
|
||||
Scope();
|
||||
virtual ~Scope();
|
||||
|
||||
/** Returns some kind of globally unique ID that identifies this scope. */
|
||||
virtual String getScopeUID() const;
|
||||
|
||||
/** Returns the value of a symbol.
|
||||
If the symbol is unknown, this can throw an Expression::EvaluationError exception.
|
||||
The member value is set to the part of the symbol that followed the dot, if there is
|
||||
one, e.g. for "foo.bar", symbol = "foo" and member = "bar".
|
||||
@throws Expression::EvaluationError
|
||||
*/
|
||||
virtual Expression getSymbolValue (const String& symbol) const;
|
||||
|
||||
/** Executes a named function.
|
||||
If the function name is unknown, this can throw an Expression::EvaluationError exception.
|
||||
@throws Expression::EvaluationError
|
||||
*/
|
||||
virtual double evaluateFunction (const String& functionName,
|
||||
const double* parameters, int numParameters) const;
|
||||
|
||||
/** Used as a callback by the Scope::visitRelativeScope() method.
|
||||
You should never create an instance of this class yourself, it's used by the
|
||||
expression evaluation code.
|
||||
*/
|
||||
class Visitor
|
||||
{
|
||||
public:
|
||||
virtual ~Visitor() = default;
|
||||
virtual void visit (const Scope&) = 0;
|
||||
};
|
||||
|
||||
/** Creates a Scope object for a named scope, and then calls a visitor
|
||||
to do some kind of processing with this new scope.
|
||||
|
||||
If the name is valid, this method must create a suitable (temporary) Scope
|
||||
object to represent it, and must call the Visitor::visit() method with this
|
||||
new scope.
|
||||
*/
|
||||
virtual void visitRelativeScope (const String& scopeName, Visitor& visitor) const;
|
||||
};
|
||||
|
||||
/** Evaluates this expression, without using a Scope.
|
||||
Without a Scope, no symbols can be used, and only basic functions such as sin, cos, tan,
|
||||
min, max are available.
|
||||
To find out about any errors during evaluation, use the other version of this method which
|
||||
takes a String parameter.
|
||||
*/
|
||||
double evaluate() const;
|
||||
|
||||
/** Evaluates this expression, providing a scope that should be able to evaluate any symbols
|
||||
or functions that it uses.
|
||||
To find out about any errors during evaluation, use the other version of this method which
|
||||
takes a String parameter.
|
||||
*/
|
||||
double evaluate (const Scope& scope) const;
|
||||
|
||||
/** Evaluates this expression, providing a scope that should be able to evaluate any symbols
|
||||
or functions that it uses.
|
||||
*/
|
||||
double evaluate (const Scope& scope, String& evaluationError) const;
|
||||
|
||||
/** Attempts to return an expression which is a copy of this one, but with a constant adjusted
|
||||
to make the expression resolve to a target value.
|
||||
|
||||
E.g. if the expression is "x + 10" and x is 5, then asking for a target value of 8 will return
|
||||
the expression "x + 3". Obviously some expressions can't be reversed in this way, in which
|
||||
case they might just be adjusted by adding a constant to the original expression.
|
||||
|
||||
@throws Expression::EvaluationError
|
||||
*/
|
||||
Expression adjustedToGiveNewResult (double targetValue, const Scope& scope) const;
|
||||
|
||||
/** Represents a symbol that is used in an Expression. */
|
||||
struct Symbol
|
||||
{
|
||||
Symbol (const String& scopeUID, const String& symbolName);
|
||||
bool operator== (const Symbol&) const noexcept;
|
||||
bool operator!= (const Symbol&) const noexcept;
|
||||
|
||||
String scopeUID; /**< The unique ID of the Scope that contains this symbol. */
|
||||
String symbolName; /**< The name of the symbol. */
|
||||
};
|
||||
|
||||
/** Returns a copy of this expression in which all instances of a given symbol have been renamed. */
|
||||
Expression withRenamedSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope) const;
|
||||
|
||||
/** Returns true if this expression makes use of the specified symbol.
|
||||
If a suitable scope is supplied, the search will dereference and recursively check
|
||||
all symbols, so that it can be determined whether this expression relies on the given
|
||||
symbol at any level in its evaluation. If the scope parameter is null, this just checks
|
||||
whether the expression contains any direct references to the symbol.
|
||||
|
||||
@throws Expression::EvaluationError
|
||||
*/
|
||||
bool referencesSymbol (const Symbol& symbol, const Scope& scope) const;
|
||||
|
||||
/** Returns true if this expression contains any symbols. */
|
||||
bool usesAnySymbols() const;
|
||||
|
||||
/** Returns a list of all symbols that may be needed to resolve this expression in the given scope. */
|
||||
void findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const;
|
||||
|
||||
//==============================================================================
|
||||
/** Expression type.
|
||||
@see Expression::getType()
|
||||
*/
|
||||
enum Type
|
||||
{
|
||||
constantType,
|
||||
functionType,
|
||||
operatorType,
|
||||
symbolType
|
||||
};
|
||||
|
||||
/** Returns the type of this expression. */
|
||||
Type getType() const noexcept;
|
||||
|
||||
/** If this expression is a symbol, function or operator, this returns its identifier. */
|
||||
String getSymbolOrFunction() const;
|
||||
|
||||
/** Returns the number of inputs to this expression.
|
||||
@see getInput
|
||||
*/
|
||||
int getNumInputs() const;
|
||||
|
||||
/** Retrieves one of the inputs to this expression.
|
||||
@see getNumInputs
|
||||
*/
|
||||
Expression getInput (int index) const;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
class Term;
|
||||
struct Helpers;
|
||||
ReferenceCountedObjectPtr<Term> term;
|
||||
|
||||
explicit Expression (Term*);
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,854 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/*
|
||||
This file sets up some handy mathematical typdefs and functions.
|
||||
*/
|
||||
|
||||
//==============================================================================
|
||||
// Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
|
||||
|
||||
/** A platform-independent 8-bit signed integer type. */
|
||||
using int8 = signed char;
|
||||
/** A platform-independent 8-bit unsigned integer type. */
|
||||
using uint8 = unsigned char;
|
||||
/** A platform-independent 16-bit signed integer type. */
|
||||
using int16 = signed short;
|
||||
/** A platform-independent 16-bit unsigned integer type. */
|
||||
using uint16 = unsigned short;
|
||||
/** A platform-independent 32-bit signed integer type. */
|
||||
using int32 = signed int;
|
||||
/** A platform-independent 32-bit unsigned integer type. */
|
||||
using uint32 = unsigned int;
|
||||
|
||||
#if JUCE_MSVC
|
||||
/** A platform-independent 64-bit integer type. */
|
||||
using int64 = __int64;
|
||||
/** A platform-independent 64-bit unsigned integer type. */
|
||||
using uint64 = unsigned __int64;
|
||||
#else
|
||||
/** A platform-independent 64-bit integer type. */
|
||||
using int64 = long long;
|
||||
/** A platform-independent 64-bit unsigned integer type. */
|
||||
using uint64 = unsigned long long;
|
||||
#endif
|
||||
|
||||
/** @cond */
|
||||
/** A macro for creating 64-bit literals.
|
||||
Historically, this was needed to support portability with MSVC6, and is kept here
|
||||
so that old code will still compile, but nowadays every compiler will support the
|
||||
LL and ULL suffixes, so you should use those in preference to this macro.
|
||||
*/
|
||||
#define literal64bit(longLiteral) (longLiteral##LL)
|
||||
/** @endcond */
|
||||
|
||||
#if JUCE_64BIT
|
||||
/** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
|
||||
using pointer_sized_int = int64;
|
||||
/** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
|
||||
using pointer_sized_uint = uint64;
|
||||
#elif JUCE_MSVC
|
||||
/** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
|
||||
using pointer_sized_int = _W64 int;
|
||||
/** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
|
||||
using pointer_sized_uint = _W64 unsigned int;
|
||||
#else
|
||||
/** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
|
||||
using pointer_sized_int = int;
|
||||
/** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
|
||||
using pointer_sized_uint = unsigned int;
|
||||
#endif
|
||||
|
||||
#if JUCE_WINDOWS
|
||||
using ssize_t = pointer_sized_int;
|
||||
#endif
|
||||
|
||||
//==============================================================================
|
||||
/** Handy function for avoiding unused variables warning. */
|
||||
template <typename... Types>
|
||||
void ignoreUnused (Types&&...) noexcept {}
|
||||
|
||||
/** Handy function for getting the number of elements in a simple const C array.
|
||||
E.g.
|
||||
@code
|
||||
static int myArray[] = { 1, 2, 3 };
|
||||
|
||||
int numElements = numElementsInArray (myArray) // returns 3
|
||||
@endcode
|
||||
*/
|
||||
template <typename Type, size_t N>
|
||||
constexpr int numElementsInArray (Type (&)[N]) noexcept { return N; }
|
||||
|
||||
//==============================================================================
|
||||
// Some useful maths functions that aren't always present with all compilers and build settings.
|
||||
|
||||
/** Using juce_hypot is easier than dealing with the different types of hypot function
|
||||
that are provided by the various platforms and compilers. */
|
||||
template <typename Type>
|
||||
Type juce_hypot (Type a, Type b) noexcept
|
||||
{
|
||||
#if JUCE_MSVC
|
||||
return static_cast<Type> (_hypot (a, b));
|
||||
#else
|
||||
return static_cast<Type> (hypot (a, b));
|
||||
#endif
|
||||
}
|
||||
|
||||
/** @cond */
|
||||
template <>
|
||||
inline float juce_hypot (float a, float b) noexcept
|
||||
{
|
||||
#if JUCE_MSVC
|
||||
return _hypotf (a, b);
|
||||
#else
|
||||
return hypotf (a, b);
|
||||
#endif
|
||||
}
|
||||
/** @endcond */
|
||||
|
||||
//==============================================================================
|
||||
/** Commonly used mathematical constants
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <typename FloatType>
|
||||
struct MathConstants
|
||||
{
|
||||
/** A predefined value for Pi */
|
||||
static constexpr FloatType pi = static_cast<FloatType> (3.141592653589793238L);
|
||||
|
||||
/** A predefined value for 2 * Pi */
|
||||
static constexpr FloatType twoPi = static_cast<FloatType> (2 * 3.141592653589793238L);
|
||||
|
||||
/** A predefined value for Pi / 2 */
|
||||
static constexpr FloatType halfPi = static_cast<FloatType> (3.141592653589793238L / 2);
|
||||
|
||||
/** A predefined value for Euler's number */
|
||||
static constexpr FloatType euler = static_cast<FloatType> (2.71828182845904523536L);
|
||||
|
||||
/** A predefined value for sqrt (2) */
|
||||
static constexpr FloatType sqrt2 = static_cast<FloatType> (1.4142135623730950488L);
|
||||
};
|
||||
|
||||
/** @cond */
|
||||
/** A double-precision constant for pi. */
|
||||
[[deprecated ("This is deprecated in favour of MathConstants<double>::pi.")]]
|
||||
const constexpr double double_Pi = MathConstants<double>::pi;
|
||||
|
||||
/** A single-precision constant for pi. */
|
||||
[[deprecated ("This is deprecated in favour of MathConstants<float>::pi.")]]
|
||||
const constexpr float float_Pi = MathConstants<float>::pi;
|
||||
/** @endcond */
|
||||
|
||||
/** Converts an angle in degrees to radians. */
|
||||
template <typename FloatType>
|
||||
constexpr FloatType degreesToRadians (FloatType degrees) noexcept { return degrees * (MathConstants<FloatType>::pi / FloatType (180)); }
|
||||
|
||||
/** Converts an angle in radians to degrees. */
|
||||
template <typename FloatType>
|
||||
constexpr FloatType radiansToDegrees (FloatType radians) noexcept { return radians * (FloatType (180) / MathConstants<FloatType>::pi); }
|
||||
|
||||
//==============================================================================
|
||||
/** The isfinite() method seems to vary between platforms, so this is a
|
||||
platform-independent function for it.
|
||||
*/
|
||||
template <typename NumericType>
|
||||
bool juce_isfinite (NumericType value) noexcept
|
||||
{
|
||||
if constexpr (std::numeric_limits<NumericType>::has_infinity
|
||||
|| std::numeric_limits<NumericType>::has_quiet_NaN
|
||||
|| std::numeric_limits<NumericType>::has_signaling_NaN)
|
||||
{
|
||||
return std::isfinite (value);
|
||||
}
|
||||
else
|
||||
{
|
||||
ignoreUnused (value);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Equivalent to operator==, but suppresses float-equality warnings.
|
||||
|
||||
This allows code to be explicit about float-equality checks that are known to have the correct
|
||||
semantics.
|
||||
*/
|
||||
template <typename Type>
|
||||
constexpr bool exactlyEqual (Type a, Type b)
|
||||
{
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wfloat-equal")
|
||||
return a == b;
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
}
|
||||
|
||||
/** A class encapsulating both relative and absolute tolerances for use in floating-point comparisons.
|
||||
|
||||
@see approximatelyEqual, absoluteTolerance, relativeTolerance
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <typename Type>
|
||||
class Tolerance
|
||||
{
|
||||
public:
|
||||
Tolerance() = default;
|
||||
|
||||
/** Returns a copy of this Tolerance object with a new absolute tolerance.
|
||||
|
||||
If you just need a Tolerance object with an absolute tolerance, it might be worth using the
|
||||
absoluteTolerance() function.
|
||||
|
||||
@see getAbsolute, absoluteTolerance
|
||||
*/
|
||||
[[nodiscard]] Tolerance withAbsolute (Type newAbsolute)
|
||||
{
|
||||
return withMember (*this, &Tolerance::absolute, std::abs (newAbsolute));
|
||||
}
|
||||
|
||||
/** Returns a copy of this Tolerance object with a new relative tolerance.
|
||||
|
||||
If you just need a Tolerance object with a relative tolerance, it might be worth using the
|
||||
relativeTolerance() function.
|
||||
|
||||
@see getRelative, relativeTolerance
|
||||
*/
|
||||
[[nodiscard]] Tolerance withRelative (Type newRelative)
|
||||
{
|
||||
return withMember (*this, &Tolerance::relative, std::abs (newRelative));
|
||||
}
|
||||
|
||||
[[nodiscard]] Type getAbsolute() const { return absolute; }
|
||||
[[nodiscard]] Type getRelative() const { return relative; }
|
||||
|
||||
private:
|
||||
Type absolute{};
|
||||
Type relative{};
|
||||
};
|
||||
|
||||
/** Returns a type deduced Tolerance object containing only an absolute tolerance.
|
||||
|
||||
@see Tolerance::withAbsolute, approximatelyEqual
|
||||
*/
|
||||
template <typename Type>
|
||||
static Tolerance<Type> absoluteTolerance (Type tolerance)
|
||||
{
|
||||
return Tolerance<Type>{}.withAbsolute (tolerance);
|
||||
}
|
||||
|
||||
/** Returns a type deduced Tolerance object containing only a relative tolerance.
|
||||
|
||||
@see Tolerance::withRelative, approximatelyEqual
|
||||
*/
|
||||
template <typename Type>
|
||||
static Tolerance<Type> relativeTolerance (Type tolerance)
|
||||
{
|
||||
return Tolerance<Type>{}.withRelative (tolerance);
|
||||
}
|
||||
|
||||
|
||||
/** Returns true if the two floating-point numbers are approximately equal.
|
||||
|
||||
If either a or b are not finite, returns exactlyEqual (a, b).
|
||||
|
||||
The default absolute tolerance is equal to the minimum normal value. This ensures
|
||||
differences that are subnormal are always considered equal. It is highly recommend this
|
||||
value is reviewed depending on the calculation being carried out. In general specifying an
|
||||
absolute value is useful when considering values close to zero. For example you might
|
||||
expect sin (pi) to return 0, but what it actually returns is close to the error of the value pi.
|
||||
Therefore, in this example it might be better to set the absolute tolerance to sin (pi).
|
||||
|
||||
The default relative tolerance is equal to the machine epsilon which is the difference between
|
||||
1.0 and the next floating-point value that can be represented by Type. In most cases this value
|
||||
is probably reasonable. This value is multiplied by the largest absolute value of a and b so as
|
||||
to scale relatively according to the input parameters. For example, specifying a relative value
|
||||
of 0.05 will ensure values return equal if the difference between them is less than or equal to
|
||||
5% of the larger of the two absolute values.
|
||||
|
||||
@param a The first number to compare.
|
||||
@param b The second number to compare.
|
||||
@param tolerance An object that represents both absolute and relative tolerances
|
||||
when evaluating if a and b are equal.
|
||||
|
||||
@see exactlyEqual
|
||||
*/
|
||||
template <typename Type, std::enable_if_t<std::is_floating_point_v<Type>, int> = 0>
|
||||
constexpr bool approximatelyEqual (Type a, Type b,
|
||||
Tolerance<Type> tolerance = Tolerance<Type>{}
|
||||
.withAbsolute (std::numeric_limits<Type>::min())
|
||||
.withRelative (std::numeric_limits<Type>::epsilon()))
|
||||
{
|
||||
if (! (juce_isfinite (a) && juce_isfinite (b)))
|
||||
return exactlyEqual (a, b);
|
||||
|
||||
const auto diff = std::abs (a - b);
|
||||
|
||||
return diff <= tolerance.getAbsolute()
|
||||
|| diff <= tolerance.getRelative() * std::max (std::abs (a), std::abs (b));
|
||||
}
|
||||
|
||||
/** Special case for non-floating-point types that returns true if both are exactly equal. */
|
||||
template <typename Type, std::enable_if_t<! std::is_floating_point_v<Type>, int> = 0>
|
||||
constexpr bool approximatelyEqual (Type a, Type b)
|
||||
{
|
||||
return a == b;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the next representable value by FloatType in the direction of the largest representable value. */
|
||||
template <typename FloatType>
|
||||
FloatType nextFloatUp (FloatType value) noexcept
|
||||
{
|
||||
return std::nextafter (value, std::numeric_limits<FloatType>::max());
|
||||
}
|
||||
|
||||
/** Returns the next representable value by FloatType in the direction of the lowest representable value. */
|
||||
template <typename FloatType>
|
||||
FloatType nextFloatDown (FloatType value) noexcept
|
||||
{
|
||||
return std::nextafter (value, std::numeric_limits<FloatType>::lowest());
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
// Some indispensable min/max functions
|
||||
|
||||
/** Returns the larger of two values. */
|
||||
template <typename Type>
|
||||
constexpr Type jmax (Type a, Type b) { return a < b ? b : a; }
|
||||
|
||||
/** Returns the larger of three values. */
|
||||
template <typename Type>
|
||||
constexpr Type jmax (Type a, Type b, Type c) { return a < b ? (b < c ? c : b) : (a < c ? c : a); }
|
||||
|
||||
/** Returns the larger of four values. */
|
||||
template <typename Type>
|
||||
constexpr Type jmax (Type a, Type b, Type c, Type d) { return jmax (a, jmax (b, c, d)); }
|
||||
|
||||
/** Returns the smaller of two values. */
|
||||
template <typename Type>
|
||||
constexpr Type jmin (Type a, Type b) { return b < a ? b : a; }
|
||||
|
||||
/** Returns the smaller of three values. */
|
||||
template <typename Type>
|
||||
constexpr Type jmin (Type a, Type b, Type c) { return b < a ? (c < b ? c : b) : (c < a ? c : a); }
|
||||
|
||||
/** Returns the smaller of four values. */
|
||||
template <typename Type>
|
||||
constexpr Type jmin (Type a, Type b, Type c, Type d) { return jmin (a, jmin (b, c, d)); }
|
||||
|
||||
/** Remaps a normalised value (between 0 and 1) to a target range.
|
||||
This effectively returns (targetRangeMin + value0To1 * (targetRangeMax - targetRangeMin)).
|
||||
*/
|
||||
template <typename Type>
|
||||
constexpr Type jmap (Type value0To1, Type targetRangeMin, Type targetRangeMax)
|
||||
{
|
||||
return targetRangeMin + value0To1 * (targetRangeMax - targetRangeMin);
|
||||
}
|
||||
|
||||
/** Remaps a value from a source range to a target range. */
|
||||
template <typename Type>
|
||||
Type jmap (Type sourceValue, Type sourceRangeMin, Type sourceRangeMax, Type targetRangeMin, Type targetRangeMax)
|
||||
{
|
||||
jassert (! approximatelyEqual (sourceRangeMax, sourceRangeMin)); // mapping from a range of zero will produce NaN!
|
||||
return targetRangeMin + ((targetRangeMax - targetRangeMin) * (sourceValue - sourceRangeMin)) / (sourceRangeMax - sourceRangeMin);
|
||||
}
|
||||
|
||||
/** Remaps a normalised value (between 0 and 1) to a logarithmic target range.
|
||||
|
||||
The entire target range must be greater than zero.
|
||||
|
||||
@see mapFromLog10
|
||||
|
||||
@code
|
||||
mapToLog10 (0.5, 0.4, 40.0) == 4.0
|
||||
@endcode
|
||||
*/
|
||||
template <typename Type>
|
||||
Type mapToLog10 (Type value0To1, Type logRangeMin, Type logRangeMax)
|
||||
{
|
||||
jassert (logRangeMin > 0);
|
||||
jassert (logRangeMax > 0);
|
||||
|
||||
auto logMin = std::log10 (logRangeMin);
|
||||
auto logMax = std::log10 (logRangeMax);
|
||||
|
||||
return std::pow ((Type) 10.0, value0To1 * (logMax - logMin) + logMin);
|
||||
}
|
||||
|
||||
/** Remaps a logarithmic value in a target range to a normalised value (between 0 and 1).
|
||||
|
||||
The entire target range must be greater than zero.
|
||||
|
||||
@see mapToLog10
|
||||
|
||||
@code
|
||||
mapFromLog10 (4.0, 0.4, 40.0) == 0.5
|
||||
@endcode
|
||||
*/
|
||||
template <typename Type>
|
||||
Type mapFromLog10 (Type valueInLogRange, Type logRangeMin, Type logRangeMax)
|
||||
{
|
||||
jassert (logRangeMin > 0);
|
||||
jassert (logRangeMax > 0);
|
||||
|
||||
auto logMin = std::log10 (logRangeMin);
|
||||
auto logMax = std::log10 (logRangeMax);
|
||||
|
||||
return (std::log10 (valueInLogRange) - logMin) / (logMax - logMin);
|
||||
}
|
||||
|
||||
/** Scans an array of values, returning the minimum value that it contains. */
|
||||
template <typename Type, typename Size>
|
||||
Type findMinimum (const Type* data, Size numValues)
|
||||
{
|
||||
if (numValues <= 0)
|
||||
return Type (0);
|
||||
|
||||
auto result = *data++;
|
||||
|
||||
while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
|
||||
{
|
||||
auto v = *data++;
|
||||
|
||||
if (v < result)
|
||||
result = v;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Scans an array of values, returning the maximum value that it contains. */
|
||||
template <typename Type, typename Size>
|
||||
Type findMaximum (const Type* values, Size numValues)
|
||||
{
|
||||
if (numValues <= 0)
|
||||
return Type (0);
|
||||
|
||||
auto result = *values++;
|
||||
|
||||
while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
|
||||
{
|
||||
auto v = *values++;
|
||||
|
||||
if (result < v)
|
||||
result = v;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Scans an array of values, returning the minimum and maximum values that it contains. */
|
||||
template <typename Type>
|
||||
void findMinAndMax (const Type* values, int numValues, Type& lowest, Type& highest)
|
||||
{
|
||||
if (numValues <= 0)
|
||||
{
|
||||
lowest = Type (0);
|
||||
highest = Type (0);
|
||||
}
|
||||
else
|
||||
{
|
||||
auto mn = *values++;
|
||||
auto mx = mn;
|
||||
|
||||
while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
|
||||
{
|
||||
auto v = *values++;
|
||||
|
||||
if (mx < v) mx = v;
|
||||
if (v < mn) mn = v;
|
||||
}
|
||||
|
||||
lowest = mn;
|
||||
highest = mx;
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns the value in the provided sorted span that is nearest to the target.
|
||||
|
||||
If the provided span is empty this returns a default constructed value.
|
||||
*/
|
||||
template <typename Type, size_t Extent>
|
||||
std::remove_cv_t<Type> findNearestValue (Span<Type, Extent> values, std::remove_cv_t<Type> target)
|
||||
{
|
||||
static_assert (std::is_arithmetic_v<Type>);
|
||||
|
||||
const auto begin = values.begin();
|
||||
const auto end = values.end();
|
||||
|
||||
if (begin == end)
|
||||
return {};
|
||||
|
||||
jassert (std::is_sorted (begin, end));
|
||||
|
||||
const auto it = std::lower_bound (begin, end, target);
|
||||
|
||||
if (it == begin)
|
||||
return *it;
|
||||
|
||||
if (it == end)
|
||||
return *(it - 1);
|
||||
|
||||
const auto upper = *it;
|
||||
const auto lower = *(it - 1);
|
||||
|
||||
return std::abs (target - lower) < std::abs (target - upper) ? lower : upper;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Constrains a value to keep it within a given range.
|
||||
|
||||
This will check that the specified value lies between the lower and upper bounds
|
||||
specified, and if not, will return the nearest value that would be in-range. Effectively,
|
||||
it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
|
||||
|
||||
Note that it expects that lowerLimit <= upperLimit. If this isn't true,
|
||||
the results will be unpredictable.
|
||||
|
||||
@param lowerLimit the minimum value to return
|
||||
@param upperLimit the maximum value to return
|
||||
@param valueToConstrain the value to try to return
|
||||
@returns the closest value to valueToConstrain which lies between lowerLimit
|
||||
and upperLimit (inclusive)
|
||||
@see jmin, jmax, jmap
|
||||
*/
|
||||
template <typename Type>
|
||||
Type jlimit (Type lowerLimit,
|
||||
Type upperLimit,
|
||||
Type valueToConstrain) noexcept
|
||||
{
|
||||
jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable
|
||||
|
||||
return valueToConstrain < lowerLimit ? lowerLimit
|
||||
: (upperLimit < valueToConstrain ? upperLimit
|
||||
: valueToConstrain);
|
||||
}
|
||||
|
||||
/** Returns true if a value is at least zero, and also below a specified upper limit.
|
||||
This is basically a quicker way to write:
|
||||
@code valueToTest >= 0 && valueToTest < upperLimit
|
||||
@endcode
|
||||
*/
|
||||
template <typename Type1, typename Type2>
|
||||
bool isPositiveAndBelow (Type1 valueToTest, Type2 upperLimit) noexcept
|
||||
{
|
||||
jassert (Type1() <= static_cast<Type1> (upperLimit)); // makes no sense to call this if the upper limit is itself below zero
|
||||
return Type1() <= valueToTest && valueToTest < static_cast<Type1> (upperLimit);
|
||||
}
|
||||
|
||||
template <typename Type>
|
||||
bool isPositiveAndBelow (int valueToTest, Type upperLimit) noexcept
|
||||
{
|
||||
jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero
|
||||
return static_cast<unsigned int> (valueToTest) < static_cast<unsigned int> (upperLimit);
|
||||
}
|
||||
|
||||
/** Returns true if a value is at least zero, and also less than or equal to a specified upper limit.
|
||||
This is basically a quicker way to write:
|
||||
@code valueToTest >= 0 && valueToTest <= upperLimit
|
||||
@endcode
|
||||
*/
|
||||
template <typename Type1, typename Type2>
|
||||
bool isPositiveAndNotGreaterThan (Type1 valueToTest, Type2 upperLimit) noexcept
|
||||
{
|
||||
jassert (Type1() <= static_cast<Type1> (upperLimit)); // makes no sense to call this if the upper limit is itself below zero
|
||||
return Type1() <= valueToTest && valueToTest <= static_cast<Type1> (upperLimit);
|
||||
}
|
||||
|
||||
template <typename Type>
|
||||
bool isPositiveAndNotGreaterThan (int valueToTest, Type upperLimit) noexcept
|
||||
{
|
||||
jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero
|
||||
return static_cast<unsigned int> (valueToTest) <= static_cast<unsigned int> (upperLimit);
|
||||
}
|
||||
|
||||
/** Computes the absolute difference between two values and returns true if it is less than or equal
|
||||
to a given tolerance, otherwise it returns false.
|
||||
*/
|
||||
template <typename Type>
|
||||
bool isWithin (Type a, Type b, Type tolerance) noexcept
|
||||
{
|
||||
return std::abs (a - b) <= tolerance;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
#if JUCE_MSVC
|
||||
#pragma optimize ("t", off)
|
||||
#ifndef __INTEL_COMPILER
|
||||
#pragma float_control (precise, on, push)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/** Fast floating-point-to-integer conversion.
|
||||
|
||||
This is faster than using the normal c++ cast to convert a float to an int, and
|
||||
it will round the value to the nearest integer, rather than rounding it down
|
||||
like the normal cast does.
|
||||
|
||||
Note that this routine gets its speed at the expense of some accuracy, and when
|
||||
rounding values whose floating point component is exactly 0.5, odd numbers and
|
||||
even numbers will be rounded up or down differently.
|
||||
*/
|
||||
template <typename FloatType>
|
||||
int roundToInt (const FloatType value) noexcept
|
||||
{
|
||||
#ifdef __INTEL_COMPILER
|
||||
#pragma float_control (precise, on, push)
|
||||
#endif
|
||||
|
||||
union { int asInt[2]; double asDouble; } n;
|
||||
n.asDouble = ((double) value) + 6755399441055744.0;
|
||||
|
||||
#if JUCE_BIG_ENDIAN
|
||||
return n.asInt [1];
|
||||
#else
|
||||
return n.asInt [0];
|
||||
#endif
|
||||
}
|
||||
|
||||
inline int roundToInt (int value) noexcept
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
#if JUCE_MSVC
|
||||
#ifndef __INTEL_COMPILER
|
||||
#pragma float_control (pop)
|
||||
#endif
|
||||
#pragma optimize ("", on) // resets optimisations to the project defaults
|
||||
#endif
|
||||
|
||||
/** Fast floating-point-to-integer conversion.
|
||||
|
||||
This is a slightly slower and slightly more accurate version of roundToInt(). It works
|
||||
fine for values above zero, but negative numbers are rounded the wrong way.
|
||||
*/
|
||||
inline int roundToIntAccurate (double value) noexcept
|
||||
{
|
||||
#ifdef __INTEL_COMPILER
|
||||
#pragma float_control (pop)
|
||||
#endif
|
||||
|
||||
return roundToInt (value + 1.5e-8);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Truncates a positive floating-point number to an unsigned int.
|
||||
|
||||
This is generally faster than static_cast<unsigned int> (std::floor (x))
|
||||
but it only works for positive numbers small enough to be represented as an
|
||||
unsigned int.
|
||||
*/
|
||||
template <typename FloatType>
|
||||
unsigned int truncatePositiveToUnsignedInt (FloatType value) noexcept
|
||||
{
|
||||
jassert (value >= static_cast<FloatType> (0));
|
||||
jassert (static_cast<FloatType> (value)
|
||||
<= static_cast<FloatType> (std::numeric_limits<unsigned int>::max()));
|
||||
|
||||
return static_cast<unsigned int> (value);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Returns true if the specified integer is a power-of-two. */
|
||||
template <typename IntegerType>
|
||||
constexpr bool isPowerOfTwo (IntegerType value)
|
||||
{
|
||||
return (value & (value - 1)) == 0;
|
||||
}
|
||||
|
||||
/** Returns the smallest power-of-two which is equal to or greater than the given integer. */
|
||||
inline int nextPowerOfTwo (int n) noexcept
|
||||
{
|
||||
--n;
|
||||
n |= (n >> 1);
|
||||
n |= (n >> 2);
|
||||
n |= (n >> 4);
|
||||
n |= (n >> 8);
|
||||
n |= (n >> 16);
|
||||
return n + 1;
|
||||
}
|
||||
|
||||
/** Returns the index of the highest set bit in a (non-zero) number.
|
||||
So for n=3 this would return 1, for n=7 it returns 2, etc.
|
||||
An input value of 0 is illegal!
|
||||
*/
|
||||
int findHighestSetBit (uint32 n) noexcept;
|
||||
|
||||
/** Returns the number of bits in a 32-bit integer. */
|
||||
constexpr int countNumberOfBits (uint32 n) noexcept
|
||||
{
|
||||
n -= ((n >> 1) & 0x55555555);
|
||||
n = (((n >> 2) & 0x33333333) + (n & 0x33333333));
|
||||
n = (((n >> 4) + n) & 0x0f0f0f0f);
|
||||
n += (n >> 8);
|
||||
n += (n >> 16);
|
||||
return (int) (n & 0x3f);
|
||||
}
|
||||
|
||||
/** Returns the number of bits in a 64-bit integer. */
|
||||
constexpr int countNumberOfBits (uint64 n) noexcept
|
||||
{
|
||||
return countNumberOfBits ((uint32) n) + countNumberOfBits ((uint32) (n >> 32));
|
||||
}
|
||||
|
||||
/** Performs a modulo operation, but can cope with the dividend being negative.
|
||||
The divisor must be greater than zero.
|
||||
*/
|
||||
template <typename IntegerType>
|
||||
IntegerType negativeAwareModulo (IntegerType dividend, const IntegerType divisor) noexcept
|
||||
{
|
||||
jassert (divisor > 0);
|
||||
dividend %= divisor;
|
||||
return (dividend < 0) ? (dividend + divisor) : dividend;
|
||||
}
|
||||
|
||||
/** Returns the square of its argument. */
|
||||
template <typename NumericType>
|
||||
inline constexpr NumericType square (NumericType n) noexcept
|
||||
{
|
||||
return n * n;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Writes a number of bits into a memory buffer at a given bit index.
|
||||
The buffer is treated as a sequence of 8-bit bytes, and the value is encoded in little-endian order,
|
||||
so for example if startBit = 10, and numBits = 11 then the lower 6 bits of the value would be written
|
||||
into bits 2-8 of targetBuffer[1], and the upper 5 bits of value into bits 0-5 of targetBuffer[2].
|
||||
|
||||
@see readLittleEndianBitsInBuffer
|
||||
*/
|
||||
void writeLittleEndianBitsInBuffer (void* targetBuffer, uint32 startBit, uint32 numBits, uint32 value) noexcept;
|
||||
|
||||
/** Reads a number of bits from a buffer at a given bit index.
|
||||
The buffer is treated as a sequence of 8-bit bytes, and the value is encoded in little-endian order,
|
||||
so for example if startBit = 10, and numBits = 11 then the lower 6 bits of the result would be read
|
||||
from bits 2-8 of sourceBuffer[1], and the upper 5 bits of the result from bits 0-5 of sourceBuffer[2].
|
||||
|
||||
@see writeLittleEndianBitsInBuffer
|
||||
*/
|
||||
uint32 readLittleEndianBitsInBuffer (const void* sourceBuffer, uint32 startBit, uint32 numBits) noexcept;
|
||||
|
||||
|
||||
//==============================================================================
|
||||
#if JUCE_INTEL || DOXYGEN
|
||||
/** This macro can be applied to a float variable to check whether it contains a denormalised
|
||||
value, and to normalise it if necessary.
|
||||
On CPUs that aren't vulnerable to denormalisation problems, this will have no effect.
|
||||
*/
|
||||
#define JUCE_UNDENORMALISE(x) { (x) += 0.1f; (x) -= 0.1f; }
|
||||
#else
|
||||
#define JUCE_UNDENORMALISE(x)
|
||||
#endif
|
||||
|
||||
//==============================================================================
|
||||
/** This namespace contains a few template classes for helping work out class type variations.
|
||||
*/
|
||||
namespace TypeHelpers
|
||||
{
|
||||
/** The ParameterType struct is used to find the best type to use when passing some kind
|
||||
of object as a parameter.
|
||||
|
||||
Of course, this is only likely to be useful in certain esoteric template situations.
|
||||
|
||||
E.g. "myFunction (typename TypeHelpers::ParameterType<int>::type, typename TypeHelpers::ParameterType<MyObject>::type)"
|
||||
would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
|
||||
pass-by-value, but passing objects as a const reference, to avoid copying.
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <typename Type> struct ParameterType { using type = const Type&; };
|
||||
|
||||
/** @cond */
|
||||
template <typename Type> struct ParameterType <Type&> { using type = Type&; };
|
||||
template <typename Type> struct ParameterType <Type*> { using type = Type*; };
|
||||
template <> struct ParameterType <char> { using type = char; };
|
||||
template <> struct ParameterType <unsigned char> { using type = unsigned char; };
|
||||
template <> struct ParameterType <short> { using type = short; };
|
||||
template <> struct ParameterType <unsigned short> { using type = unsigned short; };
|
||||
template <> struct ParameterType <int> { using type = int; };
|
||||
template <> struct ParameterType <unsigned int> { using type = unsigned int; };
|
||||
template <> struct ParameterType <long> { using type = long; };
|
||||
template <> struct ParameterType <unsigned long> { using type = unsigned long; };
|
||||
template <> struct ParameterType <int64> { using type = int64; };
|
||||
template <> struct ParameterType <uint64> { using type = uint64; };
|
||||
template <> struct ParameterType <bool> { using type = bool; };
|
||||
template <> struct ParameterType <float> { using type = float; };
|
||||
template <> struct ParameterType <double> { using type = double; };
|
||||
/** @endcond */
|
||||
|
||||
/** These templates are designed to take a type, and if it's a double, they return a double
|
||||
type; for anything else, they return a float type.
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <typename Type>
|
||||
using SmallestFloatType = std::conditional_t<std::is_same_v<Type, double>, double, float>;
|
||||
|
||||
/** These templates are designed to take an integer type, and return an unsigned int
|
||||
version with the same size.
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <int bytes> struct UnsignedTypeWithSize {};
|
||||
|
||||
/** @cond */
|
||||
template <> struct UnsignedTypeWithSize<1> { using type = uint8; };
|
||||
template <> struct UnsignedTypeWithSize<2> { using type = uint16; };
|
||||
template <> struct UnsignedTypeWithSize<4> { using type = uint32; };
|
||||
template <> struct UnsignedTypeWithSize<8> { using type = uint64; };
|
||||
/** @endcond */
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** @cond */
|
||||
[[deprecated ("Use roundToInt instead.")]] inline int roundDoubleToInt (double value) noexcept { return roundToInt (value); }
|
||||
[[deprecated ("Use roundToInt instead.")]] inline int roundFloatToInt (float value) noexcept { return roundToInt (value); }
|
||||
[[deprecated ("Use std::abs() instead.")]] inline int64 abs64 (int64 n) noexcept { return std::abs (n); }
|
||||
/** @endcond */
|
||||
|
||||
/** Converts an enum to its underlying integral type.
|
||||
Similar to std::to_underlying, which is only available in C++23 and above.
|
||||
*/
|
||||
template <typename T>
|
||||
constexpr auto toUnderlyingType (T t) -> std::enable_if_t<std::is_enum_v<T>, std::underlying_type_t<T>>
|
||||
{
|
||||
return static_cast<std::underlying_type_t<T>> (t);
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,627 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
template <typename T>
|
||||
String getTemplatedMathsFunctionUnitTestName (const String& functionName)
|
||||
{
|
||||
const auto getTypeName = []() -> String
|
||||
{
|
||||
if constexpr (std::is_same_v<int, T>)
|
||||
return "int";
|
||||
|
||||
if constexpr (std::is_same_v<float, T>)
|
||||
return "float";
|
||||
|
||||
if constexpr (std::is_same_v<double, T>)
|
||||
return "double";
|
||||
|
||||
if constexpr (std::is_same_v<long double, T>)
|
||||
return "long double";
|
||||
};
|
||||
|
||||
return functionName + "<" + getTypeName() + ">";
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
class ApproximatelyEqualTests final : public UnitTest
|
||||
{
|
||||
public:
|
||||
ApproximatelyEqualTests()
|
||||
: UnitTest { getTemplatedMathsFunctionUnitTestName<T> ("approximatelyEqual"), UnitTestCategories::maths }
|
||||
{}
|
||||
|
||||
void runTest() final
|
||||
{
|
||||
using limits = std::numeric_limits<T>;
|
||||
|
||||
constexpr auto zero = T{};
|
||||
constexpr auto one = T (1);
|
||||
constexpr auto min = limits::min();
|
||||
constexpr auto max = limits::max();
|
||||
constexpr auto epsilon = limits::epsilon();
|
||||
constexpr auto oneThird = one / (T) 3;
|
||||
|
||||
beginTest ("Equal values are always equal");
|
||||
{
|
||||
expect (approximatelyEqual (zero, zero));
|
||||
expect (approximatelyEqual (zero, -zero));
|
||||
expect (approximatelyEqual (-zero, -zero));
|
||||
|
||||
expect (approximatelyEqual (min, min));
|
||||
expect (approximatelyEqual (-min, -min));
|
||||
|
||||
expect (approximatelyEqual (one, one));
|
||||
expect (approximatelyEqual (-one, -one));
|
||||
|
||||
expect (approximatelyEqual (max, max));
|
||||
expect (approximatelyEqual (-max, -max));
|
||||
|
||||
const Tolerance<T> zeroTolerance{};
|
||||
|
||||
expect (approximatelyEqual (zero, zero, zeroTolerance));
|
||||
expect (approximatelyEqual (zero, -zero, zeroTolerance));
|
||||
expect (approximatelyEqual (-zero, -zero, zeroTolerance));
|
||||
|
||||
expect (approximatelyEqual (min, min, zeroTolerance));
|
||||
expect (approximatelyEqual (-min, -min, zeroTolerance));
|
||||
|
||||
expect (approximatelyEqual (one, one, zeroTolerance));
|
||||
expect (approximatelyEqual (-one, -one, zeroTolerance));
|
||||
|
||||
expect (approximatelyEqual (max, max, zeroTolerance));
|
||||
expect (approximatelyEqual (-max, -max, zeroTolerance));
|
||||
}
|
||||
|
||||
beginTest ("Comparing subnormal values to zero, returns true");
|
||||
{
|
||||
expect (! exactlyEqual (zero, nextFloatUp (zero)));
|
||||
expect (approximatelyEqual (zero, nextFloatUp (zero)));
|
||||
|
||||
expect (! exactlyEqual (zero, nextFloatDown (zero)));
|
||||
expect (approximatelyEqual (zero, nextFloatDown (zero)));
|
||||
|
||||
expect (! exactlyEqual (zero, nextFloatDown (min)));
|
||||
expect (approximatelyEqual (zero, nextFloatDown (min)));
|
||||
|
||||
expect (! exactlyEqual (zero, nextFloatUp (-min)));
|
||||
expect (approximatelyEqual (zero, nextFloatUp (-min)));
|
||||
}
|
||||
|
||||
beginTest ("Comparing the minimum normal value to zero, returns true");
|
||||
{
|
||||
expect (approximatelyEqual (zero, min));
|
||||
expect (approximatelyEqual (zero, -min));
|
||||
}
|
||||
|
||||
beginTest ("Comparing normal values greater than the minimum to zero, returns true");
|
||||
{
|
||||
expect (! approximatelyEqual (zero, one));
|
||||
expect (! approximatelyEqual (zero, epsilon));
|
||||
expect (! approximatelyEqual (zero, nextFloatUp (min)));
|
||||
expect (! approximatelyEqual (zero, nextFloatDown (-min)));
|
||||
}
|
||||
|
||||
beginTest ("Values with large ranges can be compared");
|
||||
{
|
||||
expect (! approximatelyEqual (zero, max));
|
||||
expect ( approximatelyEqual (zero, max, absoluteTolerance (max)));
|
||||
expect ( approximatelyEqual (zero, max, relativeTolerance (one)));
|
||||
expect (! approximatelyEqual (-one, max));
|
||||
expect (! approximatelyEqual (-max, max));
|
||||
}
|
||||
|
||||
beginTest ("Larger values have a boundary that is a factor of the epsilon");
|
||||
{
|
||||
for (auto exponent = 0; exponent < 127; ++exponent)
|
||||
{
|
||||
const auto value = std::pow ((T) 2, (T) exponent);
|
||||
const auto boundaryValue = value * (one + epsilon);
|
||||
|
||||
expect (juce_isfinite (value));
|
||||
expect (juce_isfinite (boundaryValue));
|
||||
|
||||
expect ( approximatelyEqual (value, boundaryValue));
|
||||
expect (! approximatelyEqual (value, nextFloatUp (boundaryValue)));
|
||||
|
||||
expect ( approximatelyEqual (-value, -boundaryValue));
|
||||
expect (! approximatelyEqual (-value, nextFloatDown (-boundaryValue)));
|
||||
}
|
||||
}
|
||||
|
||||
beginTest ("Tolerances scale with the values being compared");
|
||||
{
|
||||
|
||||
expect (approximatelyEqual ((T) 100'000'000'000'000.01,
|
||||
(T) 100'000'000'000'000.011));
|
||||
|
||||
expect (! approximatelyEqual ((T) 100.01,
|
||||
(T) 100.011));
|
||||
|
||||
expect (! approximatelyEqual ((T) 123'000, (T) 121'000, relativeTolerance ((T) 1e-2)));
|
||||
expect ( approximatelyEqual ((T) 123'000, (T) 122'000, relativeTolerance ((T) 1e-2)));
|
||||
expect ( approximatelyEqual ((T) 123'000, (T) 123'000, relativeTolerance ((T) 1e-2)));
|
||||
expect ( approximatelyEqual ((T) 123'000, (T) 124'000, relativeTolerance ((T) 1e-2)));
|
||||
expect (! approximatelyEqual ((T) 123'000, (T) 125'000, relativeTolerance ((T) 1e-2)));
|
||||
|
||||
expect (! approximatelyEqual ((T) 123, (T) 121, relativeTolerance ((T) 1e-2)));
|
||||
expect ( approximatelyEqual ((T) 123, (T) 122, relativeTolerance ((T) 1e-2)));
|
||||
expect ( approximatelyEqual ((T) 123, (T) 123, relativeTolerance ((T) 1e-2)));
|
||||
expect ( approximatelyEqual ((T) 123, (T) 124, relativeTolerance ((T) 1e-2)));
|
||||
expect (! approximatelyEqual ((T) 123, (T) 125, relativeTolerance ((T) 1e-2)));
|
||||
|
||||
expect (! approximatelyEqual ((T) 12.3, (T) 12.1, relativeTolerance ((T) 1e-2)));
|
||||
expect ( approximatelyEqual ((T) 12.3, (T) 12.2, relativeTolerance ((T) 1e-2)));
|
||||
expect ( approximatelyEqual ((T) 12.3, (T) 12.3, relativeTolerance ((T) 1e-2)));
|
||||
expect ( approximatelyEqual ((T) 12.3, (T) 12.4, relativeTolerance ((T) 1e-2)));
|
||||
expect (! approximatelyEqual ((T) 12.3, (T) 12.5, relativeTolerance ((T) 1e-2)));
|
||||
|
||||
expect (! approximatelyEqual ((T) 1.23, (T) 1.21, relativeTolerance ((T) 1e-2)));
|
||||
expect ( approximatelyEqual ((T) 1.23, (T) 1.22, relativeTolerance ((T) 1e-2)));
|
||||
expect ( approximatelyEqual ((T) 1.23, (T) 1.23, relativeTolerance ((T) 1e-2)));
|
||||
expect ( approximatelyEqual ((T) 1.23, (T) 1.24, relativeTolerance ((T) 1e-2)));
|
||||
expect (! approximatelyEqual ((T) 1.23, (T) 1.25, relativeTolerance ((T) 1e-2)));
|
||||
|
||||
expect (! approximatelyEqual ((T) 0.123, (T) 0.121, relativeTolerance ((T) 1e-2)));
|
||||
expect ( approximatelyEqual ((T) 0.123, (T) 0.122, relativeTolerance ((T) 1e-2)));
|
||||
expect ( approximatelyEqual ((T) 0.123, (T) 0.123, relativeTolerance ((T) 1e-2)));
|
||||
expect ( approximatelyEqual ((T) 0.123, (T) 0.124, relativeTolerance ((T) 1e-2)));
|
||||
expect (! approximatelyEqual ((T) 0.123, (T) 0.125, relativeTolerance ((T) 1e-2)));
|
||||
|
||||
expect (! approximatelyEqual ((T) 0.000123, (T) 0.000121, relativeTolerance ((T) 1e-2)));
|
||||
expect ( approximatelyEqual ((T) 0.000123, (T) 0.000122, relativeTolerance ((T) 1e-2)));
|
||||
expect ( approximatelyEqual ((T) 0.000123, (T) 0.000123, relativeTolerance ((T) 1e-2)));
|
||||
expect ( approximatelyEqual ((T) 0.000123, (T) 0.000124, relativeTolerance ((T) 1e-2)));
|
||||
expect (! approximatelyEqual ((T) 0.000123, (T) 0.000125, relativeTolerance ((T) 1e-2)));
|
||||
}
|
||||
|
||||
beginTest ("The square of the square root of 2 is approximately 2");
|
||||
{
|
||||
constexpr auto two = (T) 2;
|
||||
const auto sqrtOfTwo = std::sqrt (two);
|
||||
|
||||
expect (approximatelyEqual (sqrtOfTwo * sqrtOfTwo, two));
|
||||
expect (approximatelyEqual (-sqrtOfTwo * sqrtOfTwo, -two));
|
||||
expect (approximatelyEqual (two / sqrtOfTwo, sqrtOfTwo));
|
||||
}
|
||||
|
||||
if constexpr (limits::has_quiet_NaN)
|
||||
{
|
||||
beginTest ("Values are never equal to NaN");
|
||||
{
|
||||
const auto nan = limits::quiet_NaN();
|
||||
|
||||
expect (! approximatelyEqual (nan, nan));
|
||||
|
||||
const auto expectNotEqualTo = [&] (auto value)
|
||||
{
|
||||
expect (! approximatelyEqual (value, nan));
|
||||
expect (! approximatelyEqual (nan, value));
|
||||
};
|
||||
|
||||
expectNotEqualTo (zero);
|
||||
expectNotEqualTo (-zero);
|
||||
expectNotEqualTo (min);
|
||||
expectNotEqualTo (-min);
|
||||
expectNotEqualTo (one);
|
||||
expectNotEqualTo (-one);
|
||||
expectNotEqualTo (max);
|
||||
expectNotEqualTo (-max);
|
||||
}
|
||||
}
|
||||
|
||||
if constexpr (limits::has_infinity)
|
||||
{
|
||||
beginTest ("Only infinity is equal to infinity");
|
||||
{
|
||||
const auto inf = limits::infinity();
|
||||
expect (approximatelyEqual (inf, inf));
|
||||
expect (approximatelyEqual (-inf, -inf));
|
||||
expect (! approximatelyEqual (inf, -inf));
|
||||
expect (! approximatelyEqual (-inf, inf));
|
||||
|
||||
const auto expectNotEqualTo = [&] (auto value)
|
||||
{
|
||||
expect (! approximatelyEqual (value, inf));
|
||||
expect (! approximatelyEqual (value, -inf));
|
||||
expect (! approximatelyEqual (inf, value));
|
||||
expect (! approximatelyEqual (-inf, value));
|
||||
};
|
||||
|
||||
expectNotEqualTo (zero);
|
||||
expectNotEqualTo (-zero);
|
||||
expectNotEqualTo (min);
|
||||
expectNotEqualTo (-min);
|
||||
expectNotEqualTo (one);
|
||||
expectNotEqualTo (-one);
|
||||
expectNotEqualTo (max);
|
||||
expectNotEqualTo (-max);
|
||||
}
|
||||
}
|
||||
|
||||
beginTest ("Can set an absolute tolerance");
|
||||
{
|
||||
constexpr std::array<T, 7> negativePowersOfTwo
|
||||
{
|
||||
(T) 0.5 /* 2^-1 */,
|
||||
(T) 0.25 /* 2^-2 */,
|
||||
(T) 0.125 /* 2^-3 */,
|
||||
(T) 0.0625 /* 2^-4 */,
|
||||
(T) 0.03125 /* 2^-5 */,
|
||||
(T) 0.015625 /* 2^-6 */,
|
||||
(T) 0.0078125 /* 2^-7 */
|
||||
};
|
||||
|
||||
const auto testTolerance = [&] (auto tolerance)
|
||||
{
|
||||
const auto t = Tolerance<T>{}.withAbsolute ((T) tolerance);
|
||||
|
||||
const auto testValue= [&] (auto value)
|
||||
{
|
||||
const auto boundary = value + tolerance;
|
||||
|
||||
expect (approximatelyEqual (value, boundary, t));
|
||||
expect (! approximatelyEqual (value, nextFloatUp (boundary), t));
|
||||
|
||||
expect (approximatelyEqual (-value, -boundary, t));
|
||||
expect (! approximatelyEqual (-value, nextFloatDown (-boundary), t));
|
||||
};
|
||||
|
||||
testValue (zero);
|
||||
testValue (min);
|
||||
testValue (epsilon);
|
||||
testValue (one);
|
||||
|
||||
for (const auto value : negativePowersOfTwo)
|
||||
testValue (value);
|
||||
};
|
||||
|
||||
for (const auto toleranceValue : negativePowersOfTwo)
|
||||
testTolerance (toleranceValue);
|
||||
}
|
||||
|
||||
beginTest ("Can set a relative tolerance");
|
||||
{
|
||||
expect (! approximatelyEqual (oneThird, (T) 0.34, relativeTolerance ((T) 1e-2)));
|
||||
expect ( approximatelyEqual (oneThird, (T) 0.334, relativeTolerance ((T) 1e-2)));
|
||||
|
||||
expect (! approximatelyEqual (oneThird, (T) 0.334, relativeTolerance ((T) 1e-3)));
|
||||
expect ( approximatelyEqual (oneThird, (T) 0.3334, relativeTolerance ((T) 1e-3)));
|
||||
|
||||
expect (! approximatelyEqual (oneThird, (T) 0.3334, relativeTolerance ((T) 1e-4)));
|
||||
expect ( approximatelyEqual (oneThird, (T) 0.33334, relativeTolerance ((T) 1e-4)));
|
||||
|
||||
expect (! approximatelyEqual (oneThird, (T) 0.33334, relativeTolerance ((T) 1e-5)));
|
||||
expect ( approximatelyEqual (oneThird, (T) 0.333334, relativeTolerance ((T) 1e-5)));
|
||||
|
||||
expect (! approximatelyEqual (oneThird, (T) 0.333334, relativeTolerance ((T) 1e-6)));
|
||||
expect ( approximatelyEqual (oneThird, (T) 0.3333334, relativeTolerance ((T) 1e-6)));
|
||||
|
||||
expect (! approximatelyEqual (oneThird, (T) 0.3333334, relativeTolerance ((T) 1e-7)));
|
||||
expect ( approximatelyEqual (oneThird, (T) 0.33333334, relativeTolerance ((T) 1e-7)));
|
||||
|
||||
expect ( approximatelyEqual ((T) 1e6, (T) 1e6 + (T) 1, relativeTolerance ((T) 1e-6)));
|
||||
expect (! approximatelyEqual ((T) 1e6, (T) 1e6 + (T) 1, relativeTolerance ((T) 1e-7)));
|
||||
|
||||
expect ( approximatelyEqual ((T) -1e-6, (T) -1.0000009e-6, relativeTolerance ((T) 1e-6)));
|
||||
expect (! approximatelyEqual ((T) -1e-6, (T) -1.0000009e-6, relativeTolerance ((T) 1e-7)));
|
||||
|
||||
const auto a = (T) 1.234567;
|
||||
const auto b = (T) 1.234568;
|
||||
|
||||
for (auto exponent = 0; exponent < 39; ++exponent)
|
||||
{
|
||||
const auto m = std::pow ((T) 10, (T) exponent);
|
||||
expect ( approximatelyEqual (a * m, b * m, relativeTolerance ((T) 1e-6)));
|
||||
expect (! approximatelyEqual (a * m, b * m, relativeTolerance ((T) 1e-7)));
|
||||
}
|
||||
}
|
||||
|
||||
beginTest ("A relative tolerance is always scaled by the maximum value");
|
||||
{
|
||||
expect ( approximatelyEqual ((T) 9, (T) 10, absoluteTolerance ((T) 10.0 * (T) 0.1)));
|
||||
expect (! approximatelyEqual ((T) 9, (T) 10, absoluteTolerance ((T) 9.0 * (T) 0.1)));
|
||||
|
||||
expect (approximatelyEqual ((T) 9, (T) 10, relativeTolerance ((T) 0.1)));
|
||||
expect (approximatelyEqual ((T) 10, (T) 9, relativeTolerance ((T) 0.1)));
|
||||
}
|
||||
|
||||
beginTest ("Documentation examples");
|
||||
{
|
||||
constexpr auto pi = MathConstants<T>::pi;
|
||||
|
||||
expect (! approximatelyEqual (zero, std::sin (pi)));
|
||||
expect ( approximatelyEqual (zero, std::sin (pi), absoluteTolerance (std::sin (pi))));
|
||||
|
||||
expect ( approximatelyEqual ((T) 100, (T) 95, relativeTolerance ((T) 0.05)));
|
||||
expect (! approximatelyEqual ((T) 100, (T) 94, relativeTolerance ((T) 0.05)));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
template<>
|
||||
class ApproximatelyEqualTests<int> final : public UnitTest
|
||||
{
|
||||
public:
|
||||
ApproximatelyEqualTests()
|
||||
: UnitTest { getTemplatedMathsFunctionUnitTestName<int> ("approximatelyEqual"), UnitTestCategories::maths }
|
||||
{}
|
||||
|
||||
void runTest() final
|
||||
{
|
||||
beginTest ("Identical integers are always equal");
|
||||
{
|
||||
expect (approximatelyEqual ( 0, 0));
|
||||
expect (approximatelyEqual (-0, -0));
|
||||
|
||||
expect (approximatelyEqual ( 1, 1));
|
||||
expect (approximatelyEqual (-1, -1));
|
||||
|
||||
using limits = std::numeric_limits<int>;
|
||||
constexpr auto min = limits::min();
|
||||
constexpr auto max = limits::max();
|
||||
|
||||
expect (approximatelyEqual (min, min));
|
||||
expect (approximatelyEqual (max, max));
|
||||
}
|
||||
|
||||
beginTest ("Non-identical integers are never equal");
|
||||
{
|
||||
expect (! approximatelyEqual ( 0, 1));
|
||||
expect (! approximatelyEqual ( 0, -1));
|
||||
|
||||
expect (! approximatelyEqual ( 1, 2));
|
||||
expect (! approximatelyEqual (-1, -2));
|
||||
|
||||
using limits = std::numeric_limits<int>;
|
||||
constexpr auto min = limits::min();
|
||||
constexpr auto max = limits::max();
|
||||
|
||||
expect (! approximatelyEqual (min, min + 1));
|
||||
expect (! approximatelyEqual (max, max - 1));
|
||||
}
|
||||
|
||||
beginTest ("Zero is equal regardless of the sign");
|
||||
{
|
||||
expect (approximatelyEqual ( 0, -0));
|
||||
expect (approximatelyEqual (-0, 0));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class IsFiniteTests final : public UnitTest
|
||||
{
|
||||
public:
|
||||
IsFiniteTests()
|
||||
: UnitTest { getTemplatedMathsFunctionUnitTestName<T> ("juce_isfinite"), UnitTestCategories::maths }
|
||||
{}
|
||||
|
||||
void runTest() final
|
||||
{
|
||||
using limits = std::numeric_limits<T>;
|
||||
|
||||
constexpr auto zero = T{};
|
||||
constexpr auto one = (T) 1;
|
||||
constexpr auto max = limits::max();
|
||||
constexpr auto inf = limits::infinity();
|
||||
constexpr auto nan = limits::quiet_NaN();
|
||||
|
||||
beginTest ("Zero is finite");
|
||||
{
|
||||
expect (juce_isfinite (zero));
|
||||
expect (juce_isfinite (-zero));
|
||||
}
|
||||
|
||||
beginTest ("Subnormals are finite");
|
||||
{
|
||||
expect (juce_isfinite (nextFloatUp (zero)));
|
||||
expect (juce_isfinite (nextFloatDown (zero)));
|
||||
}
|
||||
|
||||
beginTest ("One is finite");
|
||||
{
|
||||
expect (juce_isfinite (one));
|
||||
expect (juce_isfinite (-one));
|
||||
}
|
||||
|
||||
beginTest ("Max is finite");
|
||||
{
|
||||
expect (juce_isfinite (max));
|
||||
expect (juce_isfinite (-max));
|
||||
}
|
||||
|
||||
beginTest ("Infinity is not finite");
|
||||
{
|
||||
expect (! juce_isfinite (inf));
|
||||
expect (! juce_isfinite (-inf));
|
||||
}
|
||||
|
||||
beginTest ("NaN is not finite");
|
||||
{
|
||||
expect (! juce_isfinite (nan));
|
||||
expect (! juce_isfinite (-nan));
|
||||
expect (! juce_isfinite (std::sqrt ((T) -1)));
|
||||
expect (! juce_isfinite (inf * zero));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class NextFloatTests final : public UnitTest
|
||||
{
|
||||
public:
|
||||
NextFloatTests()
|
||||
: UnitTest { getTemplatedMathsFunctionUnitTestName<T> ("nextFloat"), UnitTestCategories::maths }
|
||||
{}
|
||||
|
||||
void runTest() final
|
||||
{
|
||||
using limits = std::numeric_limits<T>;
|
||||
|
||||
constexpr auto zero = T{};
|
||||
constexpr auto one = T (1);
|
||||
constexpr auto min = limits::min();
|
||||
constexpr auto epsilon = limits::epsilon();
|
||||
|
||||
beginTest ("nextFloat from zero is subnormal");
|
||||
{
|
||||
expect (juce_isfinite (nextFloatUp (zero)));
|
||||
expect (! exactlyEqual (zero, nextFloatUp (zero)));
|
||||
expect (! std::isnormal (nextFloatUp (zero)));
|
||||
|
||||
expect (juce_isfinite (nextFloatDown (zero)));
|
||||
expect (! exactlyEqual (zero, nextFloatDown (zero)));
|
||||
expect (! std::isnormal (nextFloatDown (zero)));
|
||||
}
|
||||
|
||||
beginTest ("nextFloat from min, towards zero, is subnormal");
|
||||
{
|
||||
expect (std::isnormal (min));
|
||||
expect (std::isnormal (-min));
|
||||
expect (! std::isnormal (nextFloatDown (min)));
|
||||
expect (! std::isnormal (nextFloatUp (-min)));
|
||||
}
|
||||
|
||||
beginTest ("nextFloat from one matches epsilon");
|
||||
{
|
||||
expect (! exactlyEqual (one, nextFloatUp (one)));
|
||||
expect ( exactlyEqual (one + epsilon, nextFloatUp (one)));
|
||||
|
||||
expect (! exactlyEqual (-one, nextFloatDown (-one)));
|
||||
expect ( exactlyEqual (-one - epsilon, nextFloatDown (-one)));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class FindNearestValueTests final : public UnitTest
|
||||
{
|
||||
public:
|
||||
FindNearestValueTests()
|
||||
: UnitTest { getTemplatedMathsFunctionUnitTestName<T> ("findNearestValue"), UnitTestCategories::maths }
|
||||
{}
|
||||
|
||||
void runTest() final
|
||||
{
|
||||
beginTest ("Empty span returns a default-constructed value");
|
||||
{
|
||||
expect (exactlyEqual (findNearestValue (Span<T>{}, T (1)), T{}));
|
||||
}
|
||||
|
||||
beginTest ("Single element is always returned");
|
||||
{
|
||||
const T value { 5 };
|
||||
expect (exactlyEqual (findNearestValue (Span { &value, (size_t) 1 }, T (100)), value));
|
||||
expect (exactlyEqual (findNearestValue (Span { &value, (size_t) 1 }, T (-100)), value));
|
||||
expect (exactlyEqual (findNearestValue (Span { &value, (size_t) 1 }, value), value));
|
||||
}
|
||||
|
||||
beginTest ("Exact matches are returned");
|
||||
{
|
||||
const T values[] { T (1), T (3), T (5), T (9) };
|
||||
|
||||
expect (exactlyEqual (findNearestValue (Span { values }, T (1)), T (1)));
|
||||
expect (exactlyEqual (findNearestValue (Span { values }, T (5)), T (5)));
|
||||
expect (exactlyEqual (findNearestValue (Span { values }, T (9)), T (9)));
|
||||
}
|
||||
|
||||
beginTest ("Targets outside the range clamp to the nearest endpoint");
|
||||
{
|
||||
const T values[] { T (10), T (20), T (30) };
|
||||
|
||||
expect (exactlyEqual (findNearestValue (Span { values }, T (0)), T (10)));
|
||||
expect (exactlyEqual (findNearestValue (Span { values }, T (100)), T (30)));
|
||||
}
|
||||
|
||||
beginTest ("Targets between values select the closer neighbour");
|
||||
{
|
||||
const T values[] { T (0), T (10) };
|
||||
|
||||
expect (exactlyEqual (findNearestValue (Span { values }, T (1)), T (0)));
|
||||
expect (exactlyEqual (findNearestValue (Span { values }, T (9)), T (10)));
|
||||
}
|
||||
|
||||
beginTest ("Equidistant targets prefer the upper neighbour");
|
||||
{
|
||||
const T values[] { T (0), T (10) };
|
||||
|
||||
expect (exactlyEqual (findNearestValue (Span { values }, T (5)), T (10)));
|
||||
}
|
||||
|
||||
beginTest ("Works with const and mutable Array");
|
||||
{
|
||||
const Array<T> constValues { T (44100), T (48000), T (96000) };
|
||||
Array<T> mutableValues { T (44100), T (48000), T (96000) };
|
||||
|
||||
expect (exactlyEqual (findNearestValue (Span { constValues }, T (40000)), T (44100)));
|
||||
expect (exactlyEqual (findNearestValue (Span { constValues }, T (45000)), T (44100)));
|
||||
expect (exactlyEqual (findNearestValue (Span { constValues }, T (47000)), T (48000)));
|
||||
expect (exactlyEqual (findNearestValue (Span { constValues }, T (100000)), T (96000)));
|
||||
|
||||
expect (exactlyEqual (findNearestValue (Span { mutableValues }, T (47000)), T (48000)));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Type>
|
||||
struct MathsFloatingPointFunctionsTests
|
||||
{
|
||||
IsFiniteTests<Type> isFiniteTests;
|
||||
NextFloatTests<Type> nextFloatTests;
|
||||
ApproximatelyEqualTests<Type> approximatelyEqualTests;
|
||||
FindNearestValueTests<Type> findNearestValueTests;
|
||||
};
|
||||
|
||||
template<>
|
||||
struct MathsFloatingPointFunctionsTests<int>
|
||||
{
|
||||
ApproximatelyEqualTests<int> approximatelyEqualTests;
|
||||
FindNearestValueTests<int> findNearestValueTests;
|
||||
};
|
||||
|
||||
struct MathsFunctionsTests
|
||||
{
|
||||
MathsFloatingPointFunctionsTests<int> intFunctionTests;
|
||||
MathsFloatingPointFunctionsTests<float> floatFunctionTests;
|
||||
MathsFloatingPointFunctionsTests<double> doubleFunctionTests;
|
||||
MathsFloatingPointFunctionsTests<long double> longDoubleFunctionTests;
|
||||
};
|
||||
|
||||
static MathsFunctionsTests mathsFunctionsTests;
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,273 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Represents a mapping between an arbitrary range of values and a
|
||||
normalised 0->1 range.
|
||||
|
||||
The properties of the mapping also include an optional snapping interval
|
||||
and skew-factor.
|
||||
|
||||
@see Range
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <typename ValueType>
|
||||
class NormalisableRange
|
||||
{
|
||||
public:
|
||||
/** Creates a continuous range that performs a dummy mapping. */
|
||||
NormalisableRange() = default;
|
||||
|
||||
NormalisableRange (const NormalisableRange&) = default;
|
||||
NormalisableRange& operator= (const NormalisableRange&) = default;
|
||||
NormalisableRange (NormalisableRange&&) = default;
|
||||
NormalisableRange& operator= (NormalisableRange&&) = default;
|
||||
|
||||
/** Creates a NormalisableRange with a given range, interval and skew factor. */
|
||||
NormalisableRange (ValueType rangeStart,
|
||||
ValueType rangeEnd,
|
||||
ValueType intervalValue,
|
||||
ValueType skewFactor,
|
||||
bool useSymmetricSkew = false) noexcept
|
||||
: start (rangeStart), end (rangeEnd), interval (intervalValue),
|
||||
skew (skewFactor), symmetricSkew (useSymmetricSkew)
|
||||
{
|
||||
checkInvariants();
|
||||
}
|
||||
|
||||
/** Creates a NormalisableRange with a given range, continuous interval, but a dummy skew-factor. */
|
||||
NormalisableRange (ValueType rangeStart,
|
||||
ValueType rangeEnd) noexcept
|
||||
: start (rangeStart), end (rangeEnd)
|
||||
{
|
||||
checkInvariants();
|
||||
}
|
||||
|
||||
/** Creates a NormalisableRange with a given range and interval, but a dummy skew-factor. */
|
||||
NormalisableRange (ValueType rangeStart,
|
||||
ValueType rangeEnd,
|
||||
ValueType intervalValue) noexcept
|
||||
: start (rangeStart), end (rangeEnd), interval (intervalValue)
|
||||
{
|
||||
checkInvariants();
|
||||
}
|
||||
|
||||
/** Creates a NormalisableRange with a given range, continuous interval, but a dummy skew-factor. */
|
||||
NormalisableRange (Range<ValueType> range) noexcept
|
||||
: NormalisableRange (range.getStart(), range.getEnd())
|
||||
{
|
||||
}
|
||||
|
||||
/** Creates a NormalisableRange with a given range and interval, but a dummy skew-factor. */
|
||||
NormalisableRange (Range<ValueType> range, ValueType intervalValue) noexcept
|
||||
: NormalisableRange (range.getStart(), range.getEnd(), intervalValue)
|
||||
{
|
||||
}
|
||||
|
||||
/** A function object which can remap a value in some way based on the start and end of a range. */
|
||||
using ValueRemapFunction = std::function<ValueType(ValueType rangeStart,
|
||||
ValueType rangeEnd,
|
||||
ValueType valueToRemap)>;
|
||||
|
||||
/** Creates a NormalisableRange with a given range and an injective mapping function.
|
||||
|
||||
@param rangeStart The minimum value in the range.
|
||||
@param rangeEnd The maximum value in the range.
|
||||
@param convertFrom0To1Func A function which uses the current start and end of this NormalisableRange
|
||||
and produces a mapped value from a normalised value.
|
||||
@param convertTo0To1Func A function which uses the current start and end of this NormalisableRange
|
||||
and produces a normalised value from a mapped value.
|
||||
@param snapToLegalValueFunc A function which uses the current start and end of this NormalisableRange
|
||||
to take a mapped value and snap it to the nearest legal value.
|
||||
*/
|
||||
NormalisableRange (ValueType rangeStart,
|
||||
ValueType rangeEnd,
|
||||
ValueRemapFunction convertFrom0To1Func,
|
||||
ValueRemapFunction convertTo0To1Func,
|
||||
ValueRemapFunction snapToLegalValueFunc = {}) noexcept
|
||||
: start (rangeStart),
|
||||
end (rangeEnd),
|
||||
convertFrom0To1Function (std::move (convertFrom0To1Func)),
|
||||
convertTo0To1Function (std::move (convertTo0To1Func)),
|
||||
snapToLegalValueFunction (std::move (snapToLegalValueFunc))
|
||||
{
|
||||
checkInvariants();
|
||||
}
|
||||
|
||||
/** Uses the properties of this mapping to convert a non-normalised value to
|
||||
its 0->1 representation.
|
||||
*/
|
||||
ValueType convertTo0to1 (ValueType v) const noexcept
|
||||
{
|
||||
if (convertTo0To1Function != nullptr)
|
||||
return clampTo0To1 (convertTo0To1Function (start, end, v));
|
||||
|
||||
auto proportion = clampTo0To1 ((v - start) / (end - start));
|
||||
|
||||
if (exactlyEqual (skew, static_cast<ValueType> (1)))
|
||||
return proportion;
|
||||
|
||||
if (! symmetricSkew)
|
||||
return std::pow (proportion, skew);
|
||||
|
||||
auto distanceFromMiddle = static_cast<ValueType> (2) * proportion - static_cast<ValueType> (1);
|
||||
|
||||
return (static_cast<ValueType> (1) + std::pow (std::abs (distanceFromMiddle), skew)
|
||||
* (distanceFromMiddle < ValueType() ? static_cast<ValueType> (-1)
|
||||
: static_cast<ValueType> (1)))
|
||||
/ static_cast<ValueType> (2);
|
||||
}
|
||||
|
||||
/** Uses the properties of this mapping to convert a normalised 0->1 value to
|
||||
its full-range representation.
|
||||
*/
|
||||
ValueType convertFrom0to1 (ValueType proportion) const noexcept
|
||||
{
|
||||
proportion = clampTo0To1 (proportion);
|
||||
|
||||
if (convertFrom0To1Function != nullptr)
|
||||
return convertFrom0To1Function (start, end, proportion);
|
||||
|
||||
if (! symmetricSkew)
|
||||
{
|
||||
if (! exactlyEqual (skew, static_cast<ValueType> (1)) && proportion > ValueType())
|
||||
proportion = std::exp (std::log (proportion) / skew);
|
||||
|
||||
return start + (end - start) * proportion;
|
||||
}
|
||||
|
||||
auto distanceFromMiddle = static_cast<ValueType> (2) * proportion - static_cast<ValueType> (1);
|
||||
|
||||
if (! exactlyEqual (skew, static_cast<ValueType> (1)) && ! exactlyEqual (distanceFromMiddle, static_cast<ValueType> (0)))
|
||||
distanceFromMiddle = std::exp (std::log (std::abs (distanceFromMiddle)) / skew)
|
||||
* (distanceFromMiddle < ValueType() ? static_cast<ValueType> (-1)
|
||||
: static_cast<ValueType> (1));
|
||||
|
||||
return start + (end - start) / static_cast<ValueType> (2) * (static_cast<ValueType> (1) + distanceFromMiddle);
|
||||
}
|
||||
|
||||
/** Takes a non-normalised value and snaps it based on either the interval property of
|
||||
this NormalisableRange or the lambda function supplied to the constructor.
|
||||
*/
|
||||
ValueType snapToLegalValue (ValueType v) const noexcept
|
||||
{
|
||||
if (snapToLegalValueFunction != nullptr)
|
||||
return snapToLegalValueFunction (start, end, v);
|
||||
|
||||
if (interval > ValueType())
|
||||
v = start + interval * std::floor ((v - start) / interval + static_cast<ValueType> (0.5));
|
||||
|
||||
return (v <= start || end <= start) ? start : (v >= end ? end : v);
|
||||
}
|
||||
|
||||
/** Returns the extent of the normalisable range. */
|
||||
Range<ValueType> getRange() const noexcept { return { start, end }; }
|
||||
|
||||
/** Given a value which is between the start and end points, this sets the skew
|
||||
such that convertFrom0to1 (0.5) will return this value.
|
||||
|
||||
If you have used lambda functions for convertFrom0to1Func and convertFrom0to1Func in the
|
||||
constructor of this class then the skew value is ignored.
|
||||
|
||||
@param centrePointValue this must be greater than the start of the range and less than the end.
|
||||
*/
|
||||
void setSkewForCentre (ValueType centrePointValue) noexcept
|
||||
{
|
||||
jassert (centrePointValue > start);
|
||||
jassert (centrePointValue < end);
|
||||
|
||||
symmetricSkew = false;
|
||||
skew = std::log (static_cast<ValueType> (0.5)) / std::log ((centrePointValue - start) / (end - start));
|
||||
checkInvariants();
|
||||
}
|
||||
|
||||
/** The minimum value of the non-normalised range. */
|
||||
ValueType start = 0;
|
||||
|
||||
/** The maximum value of the non-normalised range. */
|
||||
ValueType end = 1;
|
||||
|
||||
/** The snapping interval that should be used (for a non-normalised value). Use 0 for a
|
||||
continuous range.
|
||||
|
||||
If you have used a lambda function for snapToLegalValueFunction in the constructor of
|
||||
this class then the interval is ignored.
|
||||
*/
|
||||
ValueType interval = 0;
|
||||
|
||||
/** An optional skew factor that alters the way values are distribute across the range.
|
||||
|
||||
The skew factor lets you skew the mapping logarithmically so that larger or smaller
|
||||
values are given a larger proportion of the available space.
|
||||
|
||||
A factor of 1.0 has no skewing effect at all. If the factor is < 1.0, the lower end
|
||||
of the range will fill more of the slider's length; if the factor is > 1.0, the upper
|
||||
end of the range will be expanded.
|
||||
|
||||
If you have used lambda functions for convertFrom0to1Func and convertFrom0to1Func in the
|
||||
constructor of this class then the skew value is ignored.
|
||||
*/
|
||||
ValueType skew = 1;
|
||||
|
||||
/** If true, the skew factor applies from the middle of the slider to each of its ends. */
|
||||
bool symmetricSkew = false;
|
||||
|
||||
private:
|
||||
void checkInvariants() const
|
||||
{
|
||||
jassert (end > start);
|
||||
jassert (interval >= ValueType());
|
||||
jassert (skew > ValueType());
|
||||
}
|
||||
|
||||
static ValueType clampTo0To1 (ValueType value)
|
||||
{
|
||||
auto clampedValue = jlimit (static_cast<ValueType> (0), static_cast<ValueType> (1), value);
|
||||
|
||||
// If you hit this assertion then either your normalisation function is not working
|
||||
// correctly or your input is out of the expected bounds.
|
||||
jassert (exactlyEqual (clampedValue, value));
|
||||
|
||||
return clampedValue;
|
||||
}
|
||||
|
||||
ValueRemapFunction convertFrom0To1Function, convertTo0To1Function, snapToLegalValueFunction;
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,309 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
Random::Random (int64 seedValue) noexcept
|
||||
: seed (seedValue)
|
||||
#if JUCE_CHECK_MEMORY_LEAKS
|
||||
, optionalLeakDetector (std::make_optional<LeakedObjectDetector<Random>>())
|
||||
#endif
|
||||
{
|
||||
}
|
||||
|
||||
Random::Random()
|
||||
: Random (SystemRandomTag { false })
|
||||
{
|
||||
}
|
||||
|
||||
Random::Random ([[maybe_unused]] SystemRandomTag x)
|
||||
: seed (1)
|
||||
#if JUCE_CHECK_MEMORY_LEAKS
|
||||
, optionalLeakDetector (x.value ? std::nullopt : std::make_optional<LeakedObjectDetector<Random>>())
|
||||
#endif
|
||||
{
|
||||
setSeedRandomly();
|
||||
|
||||
#if JUCE_ASSERTIONS_ENABLED_OR_LOGGED
|
||||
isSystemRandom = x.value;
|
||||
#endif
|
||||
}
|
||||
|
||||
void Random::setSeed (const int64 newSeed) noexcept
|
||||
{
|
||||
// Resetting the system Random risks messing up JUCE's internal state.
|
||||
// If you need a predictable stream of random numbers you should use a
|
||||
// local Random object.
|
||||
jassert (! isSystemRandom);
|
||||
|
||||
seed = newSeed;
|
||||
}
|
||||
|
||||
void Random::combineSeed (const int64 seedValue) noexcept
|
||||
{
|
||||
// Resetting the system Random risks messing up JUCE's internal state.
|
||||
// Consider using a local Random object instead.
|
||||
jassert (! isSystemRandom);
|
||||
|
||||
seed ^= nextInt64() ^ seedValue;
|
||||
}
|
||||
|
||||
void Random::setSeedRandomly()
|
||||
{
|
||||
// Resetting the system Random risks messing up JUCE's internal state.
|
||||
// Consider using a local Random object instead.
|
||||
jassert (! isSystemRandom);
|
||||
|
||||
static std::atomic<int64> globalSeed { 0 };
|
||||
|
||||
combineSeed (globalSeed ^ (int64) (pointer_sized_int) this);
|
||||
combineSeed (Time::getMillisecondCounter());
|
||||
combineSeed (Time::getHighResolutionTicks());
|
||||
combineSeed (Time::getHighResolutionTicksPerSecond());
|
||||
combineSeed (Time::currentTimeMillis());
|
||||
globalSeed ^= seed;
|
||||
}
|
||||
|
||||
Random& Random::getSystemRandom() noexcept
|
||||
{
|
||||
thread_local Random sysRand { SystemRandomTag { true } };
|
||||
return sysRand;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
int Random::nextInt() noexcept
|
||||
{
|
||||
// If you encounter this assertion you've likely stored a reference to the
|
||||
// system random object and are accessing it from a thread other than the
|
||||
// one it was first created on. This may lead to race conditions on the
|
||||
// random object. To avoid this assertion call Random::getSystemRandom()
|
||||
// directly instead of storing a reference.
|
||||
jassert (! isSystemRandom || this == &getSystemRandom());
|
||||
|
||||
seed = (int64) (((((uint64) seed) * 0x5deece66dLL) + 11) & 0xffffffffffffLL);
|
||||
|
||||
return (int) (seed >> 16);
|
||||
}
|
||||
|
||||
int Random::nextInt (const int maxValue) noexcept
|
||||
{
|
||||
jassert (maxValue > 0);
|
||||
return (int) ((((unsigned int) nextInt()) * (uint64) maxValue) >> 32);
|
||||
}
|
||||
|
||||
int Random::nextInt (Range<int> range) noexcept
|
||||
{
|
||||
return range.getStart() + nextInt (range.getLength());
|
||||
}
|
||||
|
||||
int64 Random::nextInt64() noexcept
|
||||
{
|
||||
return (int64) ((((uint64) (unsigned int) nextInt()) << 32) | (uint64) (unsigned int) nextInt());
|
||||
}
|
||||
|
||||
bool Random::nextBool() noexcept
|
||||
{
|
||||
return (nextInt() & 0x40000000) != 0;
|
||||
}
|
||||
|
||||
float Random::nextFloat() noexcept
|
||||
{
|
||||
auto result = static_cast<float> (static_cast<uint32> (nextInt()))
|
||||
/ (static_cast<float> (std::numeric_limits<uint32>::max()) + 1.0f);
|
||||
return jmin (result, 1.0f - std::numeric_limits<float>::epsilon());
|
||||
}
|
||||
|
||||
double Random::nextDouble() noexcept
|
||||
{
|
||||
return static_cast<uint32> (nextInt()) / (std::numeric_limits<uint32>::max() + 1.0);
|
||||
}
|
||||
|
||||
BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
|
||||
{
|
||||
BigInteger n;
|
||||
|
||||
do
|
||||
{
|
||||
fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
|
||||
}
|
||||
while (n >= maximumValue);
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
void Random::fillBitsRandomly (void* const buffer, size_t bytes)
|
||||
{
|
||||
int* d = static_cast<int*> (buffer);
|
||||
|
||||
for (; bytes >= sizeof (int); bytes -= sizeof (int))
|
||||
*d++ = nextInt();
|
||||
|
||||
if (bytes > 0)
|
||||
{
|
||||
const int lastBytes = nextInt();
|
||||
memcpy (d, &lastBytes, bytes);
|
||||
}
|
||||
}
|
||||
|
||||
void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
|
||||
{
|
||||
arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
|
||||
|
||||
while ((startBit & 31) != 0 && numBits > 0)
|
||||
{
|
||||
arrayToChange.setBit (startBit++, nextBool());
|
||||
--numBits;
|
||||
}
|
||||
|
||||
while (numBits >= 32)
|
||||
{
|
||||
arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
|
||||
startBit += 32;
|
||||
numBits -= 32;
|
||||
}
|
||||
|
||||
while (--numBits >= 0)
|
||||
arrayToChange.setBit (startBit + numBits, nextBool());
|
||||
}
|
||||
|
||||
|
||||
//==============================================================================
|
||||
//==============================================================================
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
class RandomTests final : public UnitTest
|
||||
{
|
||||
public:
|
||||
RandomTests()
|
||||
: UnitTest ("Random", UnitTestCategories::maths)
|
||||
{}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
beginTest ("Random");
|
||||
{
|
||||
Random r = getRandom();
|
||||
|
||||
for (int i = 2000; --i >= 0;)
|
||||
{
|
||||
expect (r.nextDouble() >= 0.0 && r.nextDouble() < 1.0);
|
||||
expect (r.nextFloat() >= 0.0f && r.nextFloat() < 1.0f);
|
||||
expect (r.nextInt (5) >= 0 && r.nextInt (5) < 5);
|
||||
expect (r.nextInt (1) == 0);
|
||||
|
||||
int n = r.nextInt (50) + 1;
|
||||
expect (r.nextInt (n) >= 0 && r.nextInt (n) < n);
|
||||
|
||||
n = r.nextInt (0x7ffffffe) + 1;
|
||||
expect (r.nextInt (n) >= 0 && r.nextInt (n) < n);
|
||||
}
|
||||
}
|
||||
|
||||
beginTest ("System random stress test");
|
||||
{
|
||||
// Run this with thread-sanitizer to detect race conditions
|
||||
runOnMultipleThreadsConcurrently ([] { Random::getSystemRandom().nextInt(); });
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
static void runOnMultipleThreadsConcurrently (std::function<void()> functionToInvoke,
|
||||
int numberOfInvocationsPerThread = 10'000,
|
||||
int numberOfThreads = 100)
|
||||
{
|
||||
class FastWaitableEvent
|
||||
{
|
||||
public:
|
||||
void notify() { notified = true; }
|
||||
void wait() const { while (! notified){} }
|
||||
|
||||
private:
|
||||
std::atomic<bool> notified = false;
|
||||
};
|
||||
|
||||
class InvokerThread final : private Thread
|
||||
{
|
||||
public:
|
||||
InvokerThread (std::function<void()> fn, FastWaitableEvent& notificationEvent, int numInvocationsToTrigger)
|
||||
: Thread ("InvokerThread"),
|
||||
invokable (fn),
|
||||
notified (¬ificationEvent),
|
||||
numInvocations (numInvocationsToTrigger)
|
||||
{
|
||||
startThread();
|
||||
}
|
||||
|
||||
~InvokerThread() { stopThread (-1); }
|
||||
|
||||
void waitUntilReady() const { ready.wait(); }
|
||||
|
||||
private:
|
||||
void run() final
|
||||
{
|
||||
ready.notify();
|
||||
notified->wait();
|
||||
|
||||
for (int i = numInvocations; --i >= 0;)
|
||||
invokable();
|
||||
}
|
||||
|
||||
std::function<void()> invokable;
|
||||
FastWaitableEvent* notified;
|
||||
FastWaitableEvent ready;
|
||||
int numInvocations;
|
||||
};
|
||||
|
||||
std::vector<std::unique_ptr<InvokerThread>> threads;
|
||||
threads.reserve ((size_t) numberOfThreads);
|
||||
FastWaitableEvent start;
|
||||
|
||||
for (int i = numberOfThreads; --i >= 0;)
|
||||
threads.push_back (std::make_unique<InvokerThread> (functionToInvoke, start, numberOfInvocationsPerThread));
|
||||
|
||||
for (auto& thread : threads)
|
||||
thread->waitUntilReady();
|
||||
|
||||
// just to increase the odds that all the threads are now at the same point
|
||||
// ready to be notified
|
||||
Thread::sleep (1);
|
||||
start.notify();
|
||||
}
|
||||
};
|
||||
|
||||
static RandomTests randomTests;
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A random number generator.
|
||||
|
||||
You can create a Random object and use it to generate a sequence of random numbers.
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
class JUCE_API Random final
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates a Random object based on a seed value.
|
||||
|
||||
For a given seed value, the subsequent numbers generated by this object
|
||||
will be predictable, so a good idea is to set this value based
|
||||
on the time, e.g.
|
||||
|
||||
new Random (Time::currentTimeMillis())
|
||||
*/
|
||||
explicit Random (int64 seedValue) noexcept;
|
||||
|
||||
/** Creates a Random object using a random seed value.
|
||||
Internally, this calls setSeedRandomly() to randomise the seed.
|
||||
*/
|
||||
Random();
|
||||
|
||||
/** Returns the next random 32 bit integer.
|
||||
@returns a random integer from the full range 0x80000000 to 0x7fffffff
|
||||
*/
|
||||
int nextInt() noexcept;
|
||||
|
||||
/** Returns the next random number, limited to a given range.
|
||||
The maxValue parameter may not be negative, or zero.
|
||||
@returns a random integer between 0 (inclusive) and maxValue (exclusive).
|
||||
*/
|
||||
int nextInt (int maxValue) noexcept;
|
||||
|
||||
/** Returns the next random number, limited to a given range.
|
||||
@returns a random integer between the range start (inclusive) and its end (exclusive).
|
||||
*/
|
||||
int nextInt (Range<int> range) noexcept;
|
||||
|
||||
/** Returns the next 64-bit random number.
|
||||
@returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
|
||||
*/
|
||||
int64 nextInt64() noexcept;
|
||||
|
||||
/** Returns the next random floating-point number.
|
||||
@returns a random value in the range 0 (inclusive) to 1.0 (exclusive)
|
||||
*/
|
||||
float nextFloat() noexcept;
|
||||
|
||||
/** Returns the next random floating-point number.
|
||||
@returns a random value in the range 0 (inclusive) to 1.0 (exclusive)
|
||||
*/
|
||||
double nextDouble() noexcept;
|
||||
|
||||
/** Returns the next random boolean value. */
|
||||
bool nextBool() noexcept;
|
||||
|
||||
/** Returns a BigInteger containing a random number.
|
||||
@returns a random value in the range 0 to (maximumValue - 1).
|
||||
*/
|
||||
BigInteger nextLargeNumber (const BigInteger& maximumValue);
|
||||
|
||||
/** Fills a block of memory with random values. */
|
||||
void fillBitsRandomly (void* bufferToFill, size_t sizeInBytes);
|
||||
|
||||
/** Sets a range of bits in a BigInteger to random values. */
|
||||
void fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits);
|
||||
|
||||
//==============================================================================
|
||||
/** Resets this Random object to a given seed value. */
|
||||
void setSeed (int64 newSeed) noexcept;
|
||||
|
||||
/** Returns the RNG's current seed. */
|
||||
int64 getSeed() const noexcept { return seed; }
|
||||
|
||||
/** Merges this object's seed with another value.
|
||||
This sets the seed to be a value created by combining the current seed and this
|
||||
new value.
|
||||
*/
|
||||
void combineSeed (int64 seedValue) noexcept;
|
||||
|
||||
/** Reseeds this generator using a value generated from various semi-random system
|
||||
properties like the current time, etc.
|
||||
|
||||
Because this function convolves the time with the last seed value, calling
|
||||
it repeatedly will increase the randomness of the final result.
|
||||
*/
|
||||
void setSeedRandomly();
|
||||
|
||||
/** The overhead of creating a new Random object is fairly small, but if you want
|
||||
to avoid it, you can call this method to get a global shared Random object.
|
||||
|
||||
Note this will return a different object per thread it's accessed from,
|
||||
making it thread safe. However, it's therefore important not store a reference
|
||||
to this object that will later be accessed from other threads.
|
||||
*/
|
||||
static Random& getSystemRandom() noexcept;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
struct SystemRandomTag { bool value; };
|
||||
explicit Random (SystemRandomTag x);
|
||||
|
||||
int64 seed;
|
||||
|
||||
#if JUCE_ASSERTIONS_ENABLED_OR_LOGGED
|
||||
bool isSystemRandom = false;
|
||||
#endif
|
||||
|
||||
#if JUCE_CHECK_MEMORY_LEAKS
|
||||
friend class LeakedObjectDetector<Random>;
|
||||
static const char* getLeakedObjectClassName() noexcept { return "Random"; }
|
||||
std::optional<LeakedObjectDetector<Random>> optionalLeakDetector;
|
||||
#endif
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
+315
@@ -0,0 +1,315 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/** A general-purpose range object, that simply represents any linear range with
|
||||
a start and end point.
|
||||
|
||||
Note that when checking whether values fall within the range, the start value is
|
||||
considered to be inclusive, and the end of the range exclusive.
|
||||
|
||||
The templated parameter is expected to be a primitive integer or floating point
|
||||
type, though class types could also be used if they behave in a number-like way.
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <typename ValueType>
|
||||
class Range
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Constructs an empty range. */
|
||||
constexpr Range() = default;
|
||||
|
||||
/** Constructs a range with given start and end values. */
|
||||
constexpr Range (const ValueType startValue, const ValueType endValue) noexcept
|
||||
: start (startValue), end (jmax (startValue, endValue))
|
||||
{
|
||||
}
|
||||
|
||||
/** Constructs a copy of another range. */
|
||||
constexpr Range (const Range&) = default;
|
||||
|
||||
/** Copies another range object. */
|
||||
Range& operator= (const Range&) = default;
|
||||
|
||||
/** Returns the range that lies between two positions (in either order). */
|
||||
constexpr static Range between (const ValueType position1, const ValueType position2) noexcept
|
||||
{
|
||||
return position1 < position2 ? Range (position1, position2)
|
||||
: Range (position2, position1);
|
||||
}
|
||||
|
||||
/** Returns a range with a given start and length. */
|
||||
[[nodiscard]] static Range withStartAndLength (const ValueType startValue, const ValueType length) noexcept
|
||||
{
|
||||
jassert (length >= ValueType());
|
||||
return Range (startValue, startValue + length);
|
||||
}
|
||||
|
||||
/** Returns a range with the specified start position and a length of zero. */
|
||||
[[nodiscard]] constexpr static Range emptyRange (const ValueType start) noexcept
|
||||
{
|
||||
return Range (start, start);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the start of the range. */
|
||||
constexpr inline ValueType getStart() const noexcept { return start; }
|
||||
|
||||
/** Returns the length of the range. */
|
||||
constexpr inline ValueType getLength() const noexcept { return end - start; }
|
||||
|
||||
/** Returns the end of the range. */
|
||||
constexpr inline ValueType getEnd() const noexcept { return end; }
|
||||
|
||||
/** Returns true if the range has a length of zero. */
|
||||
constexpr inline bool isEmpty() const noexcept { return exactlyEqual (start, end); }
|
||||
|
||||
//==============================================================================
|
||||
/** Changes the start position of the range, leaving the end position unchanged.
|
||||
If the new start position is higher than the current end of the range, the end point
|
||||
will be pushed along to equal it, leaving an empty range at the new position.
|
||||
*/
|
||||
void setStart (const ValueType newStart) noexcept
|
||||
{
|
||||
start = newStart;
|
||||
if (end < newStart)
|
||||
end = newStart;
|
||||
}
|
||||
|
||||
/** Returns a range with the same end as this one, but a different start.
|
||||
If the new start position is higher than the current end of the range, the end point
|
||||
will be pushed along to equal it, returning an empty range at the new position.
|
||||
*/
|
||||
[[nodiscard]] constexpr Range withStart (const ValueType newStart) const noexcept
|
||||
{
|
||||
return Range (newStart, jmax (newStart, end));
|
||||
}
|
||||
|
||||
/** Returns a range with the same length as this one, but moved to have the given start position. */
|
||||
[[nodiscard]] constexpr Range movedToStartAt (const ValueType newStart) const noexcept
|
||||
{
|
||||
return Range (newStart, end + (newStart - start));
|
||||
}
|
||||
|
||||
/** Changes the end position of the range, leaving the start unchanged.
|
||||
If the new end position is below the current start of the range, the start point
|
||||
will be pushed back to equal the new end point.
|
||||
*/
|
||||
void setEnd (const ValueType newEnd) noexcept
|
||||
{
|
||||
end = newEnd;
|
||||
if (newEnd < start)
|
||||
start = newEnd;
|
||||
}
|
||||
|
||||
/** Returns a range with the same start position as this one, but a different end.
|
||||
If the new end position is below the current start of the range, the start point
|
||||
will be pushed back to equal the new end point.
|
||||
*/
|
||||
[[nodiscard]] constexpr Range withEnd (const ValueType newEnd) const noexcept
|
||||
{
|
||||
return Range (jmin (start, newEnd), newEnd);
|
||||
}
|
||||
|
||||
/** Returns a range with the same length as this one, but moved to have the given end position. */
|
||||
[[nodiscard]] constexpr Range movedToEndAt (const ValueType newEnd) const noexcept
|
||||
{
|
||||
return Range (start + (newEnd - end), newEnd);
|
||||
}
|
||||
|
||||
/** Changes the length of the range.
|
||||
Lengths less than zero are treated as zero.
|
||||
*/
|
||||
void setLength (const ValueType newLength) noexcept
|
||||
{
|
||||
end = start + jmax (ValueType(), newLength);
|
||||
}
|
||||
|
||||
/** Returns a range with the same start as this one, but a different length.
|
||||
Lengths less than zero are treated as zero.
|
||||
*/
|
||||
[[nodiscard]] constexpr Range withLength (const ValueType newLength) const noexcept
|
||||
{
|
||||
return Range (start, start + newLength);
|
||||
}
|
||||
|
||||
/** Returns a range which has its start moved down and its end moved up by the
|
||||
given amount.
|
||||
@returns The returned range will be (start - amount, end + amount)
|
||||
*/
|
||||
[[nodiscard]] constexpr Range expanded (ValueType amount) const noexcept
|
||||
{
|
||||
return Range (start - amount, end + amount);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Adds an amount to the start and end of the range. */
|
||||
inline Range operator+= (const ValueType amountToAdd) noexcept
|
||||
{
|
||||
start += amountToAdd;
|
||||
end += amountToAdd;
|
||||
return *this;
|
||||
}
|
||||
|
||||
/** Subtracts an amount from the start and end of the range. */
|
||||
inline Range operator-= (const ValueType amountToSubtract) noexcept
|
||||
{
|
||||
start -= amountToSubtract;
|
||||
end -= amountToSubtract;
|
||||
return *this;
|
||||
}
|
||||
|
||||
/** Returns a range that is equal to this one with an amount added to its
|
||||
start and end.
|
||||
*/
|
||||
constexpr Range operator+ (const ValueType amountToAdd) const noexcept
|
||||
{
|
||||
return Range (start + amountToAdd, end + amountToAdd);
|
||||
}
|
||||
|
||||
/** Returns a range that is equal to this one with the specified amount
|
||||
subtracted from its start and end. */
|
||||
constexpr Range operator- (const ValueType amountToSubtract) const noexcept
|
||||
{
|
||||
return Range (start - amountToSubtract, end - amountToSubtract);
|
||||
}
|
||||
|
||||
constexpr bool operator== (Range other) const noexcept
|
||||
{
|
||||
const auto tie = [] (const Range& r) { return std::tie (r.start, r.end); };
|
||||
return tie (*this) == tie (other);
|
||||
}
|
||||
|
||||
constexpr bool operator!= (Range other) const noexcept { return ! operator== (other); }
|
||||
|
||||
//==============================================================================
|
||||
/** Returns true if the given position lies inside this range.
|
||||
When making this comparison, the start value is considered to be inclusive,
|
||||
and the end of the range exclusive.
|
||||
*/
|
||||
constexpr bool contains (const ValueType position) const noexcept
|
||||
{
|
||||
return start <= position && position < end;
|
||||
}
|
||||
|
||||
/** Returns the nearest value to the one supplied, which lies within the range. */
|
||||
ValueType clipValue (const ValueType value) const noexcept
|
||||
{
|
||||
return jlimit (start, end, value);
|
||||
}
|
||||
|
||||
/** Returns true if the given range lies entirely inside this range. */
|
||||
constexpr bool contains (Range other) const noexcept
|
||||
{
|
||||
return start <= other.start && end >= other.end;
|
||||
}
|
||||
|
||||
/** Returns true if the given range intersects this one. */
|
||||
constexpr bool intersects (Range other) const noexcept
|
||||
{
|
||||
return other.start < end && start < other.end;
|
||||
}
|
||||
|
||||
/** Returns the range that is the intersection of the two ranges, or an empty range
|
||||
with an undefined start position if they don't overlap. */
|
||||
[[nodiscard]] constexpr Range getIntersectionWith (Range other) const noexcept
|
||||
{
|
||||
return Range (jmax (start, other.start),
|
||||
jmin (end, other.end));
|
||||
}
|
||||
|
||||
/** Returns the smallest range that contains both this one and the other one. */
|
||||
[[nodiscard]] constexpr Range getUnionWith (Range other) const noexcept
|
||||
{
|
||||
return Range (jmin (start, other.start),
|
||||
jmax (end, other.end));
|
||||
}
|
||||
|
||||
/** Returns the smallest range that contains both this one and the given value. */
|
||||
[[nodiscard]] constexpr Range getUnionWith (const ValueType valueToInclude) const noexcept
|
||||
{
|
||||
return Range (jmin (valueToInclude, start),
|
||||
jmax (valueToInclude, end));
|
||||
}
|
||||
|
||||
/** Returns a given range, after moving it forwards or backwards to fit it
|
||||
within this range.
|
||||
|
||||
If the supplied range has a greater length than this one, the return value
|
||||
will be this range.
|
||||
|
||||
Otherwise, if the supplied range is smaller than this one, the return value
|
||||
will be the new range, shifted forwards or backwards so that it doesn't extend
|
||||
beyond this one, but keeping its original length.
|
||||
*/
|
||||
Range constrainRange (Range rangeToConstrain) const noexcept
|
||||
{
|
||||
const ValueType otherLen = rangeToConstrain.getLength();
|
||||
return getLength() <= otherLen
|
||||
? *this
|
||||
: rangeToConstrain.movedToStartAt (jlimit (start, end - otherLen, rangeToConstrain.getStart()));
|
||||
}
|
||||
|
||||
/** Scans an array of values for its min and max, and returns these as a Range. */
|
||||
template <typename Integral, std::enable_if_t<std::is_integral_v<Integral>, int> = 0>
|
||||
static Range findMinAndMax (const ValueType* values, Integral numValues) noexcept
|
||||
{
|
||||
if (numValues <= 0)
|
||||
return Range();
|
||||
|
||||
const ValueType first (*values++);
|
||||
Range r (first, first);
|
||||
|
||||
while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
|
||||
{
|
||||
const ValueType v (*values++);
|
||||
|
||||
if (r.end < v) r.end = v;
|
||||
if (v < r.start) r.start = v;
|
||||
}
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
ValueType start{}, end{};
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,148 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A class that measures various statistics about a series of floating point
|
||||
values that it is given.
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <typename FloatType>
|
||||
class StatisticsAccumulator
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Constructs a new StatisticsAccumulator. */
|
||||
StatisticsAccumulator() = default;
|
||||
|
||||
//==============================================================================
|
||||
/** Add a new value to the accumulator.
|
||||
This will update all running statistics accordingly.
|
||||
*/
|
||||
void addValue (FloatType v) noexcept
|
||||
{
|
||||
jassert (juce_isfinite (v));
|
||||
|
||||
sum += v;
|
||||
sumSquares += v * v;
|
||||
++count;
|
||||
|
||||
if (v > maximum) maximum = v;
|
||||
if (v < minimum) minimum = v;
|
||||
}
|
||||
|
||||
/** Reset the accumulator.
|
||||
This will reset all currently saved statistcs.
|
||||
*/
|
||||
void reset() noexcept { *this = StatisticsAccumulator<FloatType>(); }
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the average (arithmetic mean) of all previously added values.
|
||||
If no values have been added yet, this will return zero.
|
||||
*/
|
||||
FloatType getAverage() const noexcept
|
||||
{
|
||||
return count > 0 ? sum / (FloatType) count
|
||||
: FloatType();
|
||||
}
|
||||
|
||||
/** Returns the variance of all previously added values.
|
||||
If no values have been added yet, this will return zero.
|
||||
*/
|
||||
FloatType getVariance() const noexcept
|
||||
{
|
||||
return count > 0 ? (sumSquares - sum * sum / (FloatType) count) / (FloatType) count
|
||||
: FloatType();
|
||||
}
|
||||
|
||||
/** Returns the standard deviation of all previously added values.
|
||||
If no values have been added yet, this will return zero.
|
||||
*/
|
||||
FloatType getStandardDeviation() const noexcept
|
||||
{
|
||||
return std::sqrt (getVariance());
|
||||
}
|
||||
|
||||
/** Returns the smallest of all previously added values.
|
||||
If no values have been added yet, this will return positive infinity.
|
||||
*/
|
||||
FloatType getMinValue() const noexcept
|
||||
{
|
||||
return minimum;
|
||||
}
|
||||
|
||||
/** Returns the largest of all previously added values.
|
||||
If no values have been added yet, this will return negative infinity.
|
||||
*/
|
||||
FloatType getMaxValue() const noexcept
|
||||
{
|
||||
return maximum;
|
||||
}
|
||||
|
||||
/** Returns how many values have been added to this accumulator. */
|
||||
size_t getCount() const noexcept
|
||||
{
|
||||
return count;
|
||||
}
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
struct KahanSum
|
||||
{
|
||||
KahanSum() = default;
|
||||
operator FloatType() const noexcept { return sum; }
|
||||
|
||||
void JUCE_NO_ASSOCIATIVE_MATH_OPTIMISATIONS operator+= (FloatType value) noexcept
|
||||
{
|
||||
FloatType correctedValue = value - error;
|
||||
FloatType newSum = sum + correctedValue;
|
||||
error = (newSum - sum) - correctedValue;
|
||||
sum = newSum;
|
||||
}
|
||||
|
||||
FloatType sum{}, error{};
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
size_t count { 0 };
|
||||
KahanSum sum, sumSquares;
|
||||
FloatType minimum { std::numeric_limits<FloatType>::infinity() },
|
||||
maximum { -std::numeric_limits<FloatType>::infinity() };
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
Reference in New Issue
Block a user