115 lines
2.1 KiB
TypeScript
115 lines
2.1 KiB
TypeScript
import { MathX } from "../math/MathX";
|
|
|
|
export class Range
|
|
{
|
|
min:number;
|
|
max:number;
|
|
|
|
constructor( min:number, max:number )
|
|
{
|
|
this.min = min;
|
|
this.max = max || min;
|
|
}
|
|
|
|
static from( values:number[] )
|
|
{
|
|
return new Range( values[ 0 ], values[ 1 ] );
|
|
}
|
|
|
|
ensurecorrectness():void
|
|
{
|
|
if ( this.max < this.min )
|
|
{
|
|
let b = this.max;
|
|
this.max = this.min;
|
|
this.min = b;
|
|
}
|
|
}
|
|
|
|
contains( value:number ):boolean
|
|
{
|
|
return this.min <= value && value <= this.max;
|
|
}
|
|
|
|
overlaps( other:Range ):boolean
|
|
{
|
|
if ( other.max < this.min ) { return false; }
|
|
if ( other.min > this.max ) { return false; }
|
|
|
|
if ( other.contains( this.min ) || other.contains( this.max ) )
|
|
{
|
|
return true;
|
|
}
|
|
|
|
if ( this.contains( this.min ) || this.contains( this.max ) )
|
|
{
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
getOverlap( other:Range )
|
|
{
|
|
if ( ! this.overlaps( other ) )
|
|
{
|
|
return null;
|
|
}
|
|
|
|
return new Range( Math.max( this.min, other.min ), Math.min( this.max, other.max ) );
|
|
}
|
|
|
|
get center():number { return 0.5 * ( this.max + this.min ); }
|
|
get length():number { return this.max - this.min; }
|
|
|
|
distanceTo( other:Range ):number
|
|
{
|
|
let center = this.center;
|
|
let othercenter = other.center;
|
|
|
|
let ownLength = this.length;
|
|
let otherLength = other.length;
|
|
|
|
let distance = Math.abs( center - othercenter );
|
|
|
|
return Math.max( 0, distance - 0.5 * ( ownLength + otherLength ) );
|
|
|
|
}
|
|
|
|
copy():Range
|
|
{
|
|
return new Range( this.min, this.max );
|
|
}
|
|
|
|
sampleAt( normalized:number ):number
|
|
{
|
|
return this.min + ( this.max - this.min ) * normalized;
|
|
}
|
|
|
|
normalize( value:number ):number
|
|
{
|
|
return ( value - this.min ) / ( this.max - this.min );
|
|
}
|
|
|
|
clamp( value:number )
|
|
{
|
|
return MathX.clamp( value, this.min, this.max );
|
|
}
|
|
|
|
equals( range:Range )
|
|
{
|
|
return range.min === this.min && range.max === this.max;
|
|
}
|
|
|
|
static get of_01():Range
|
|
{
|
|
return new Range( 0, 1 );
|
|
}
|
|
|
|
static get Maximum():Range
|
|
{
|
|
return new Range( -Number.MAX_VALUE, Number.MAX_VALUE );
|
|
}
|
|
|
|
|
|
} |