# math_func.hpp File Reference

Integer math functions. More...

Go to the source code of this file.

## Functions
template<typename T>
static FORCEINLINE T | max (const T a, const T b)
| Returns the maximum of two values.
template<typename T>
static FORCEINLINE T | min (const T a, const T b)
| Returns the minimum of two values.
static FORCEINLINE int | min (const int a, const int b)
| Returns the minimum of two integer.
static FORCEINLINE uint | minu (const uint a, const uint b)
| Returns the minimum of two unsigned integers.
template<typename T>
static FORCEINLINE T | abs (const T a)
| Returns the absolute value of (scalar) variable.
template<typename T>
static FORCEINLINE T | Align (const T x, uint n)
| Return the smallest multiple of n equal or greater than x.
template<typename T>
static FORCEINLINE T * | AlignPtr (T *x, uint n)
| Return the smallest multiple of n equal or greater than x Applies to pointers only.
template<typename T>
static FORCEINLINE T | Clamp (const T a, const T min, const T max)
| Clamp a value between an interval.
static FORCEINLINE int | Clamp (const int a, const int min, const int max)
| Clamp an integer between an interval.
static FORCEINLINE uint | ClampU (const uint a, const uint min, const uint max)
| Clamp an unsigned integer between an interval.
static FORCEINLINE int32 | ClampToI32 (const int64 a)
| Reduce a signed 64-bit int to a signed 32-bit one.
static FORCEINLINE uint16 | ClampToU16 (const uint64 a)
| Reduce an unsigned 64-bit int to an unsigned 16-bit one.
template<typename T>
static FORCEINLINE T | Delta (const T a, const T b)
| Returns the (absolute) difference between two (scalar) variables.
template<typename T>
static FORCEINLINE bool | IsInsideBS (const T x, const uint base, const uint size)
| Checks if a value is between a window started at some base point.
template<typename T>
static FORCEINLINE bool | IsInsideMM (const T x, const uint min, const uint max)
| Checks if a value is in an interval.
template<typename T>
static FORCEINLINE void | Swap (T &a, T &b)
| Type safe swap operation.
static FORCEINLINE uint | ToPercent8 (uint i)
| Converts a "fract" value 0.
static FORCEINLINE uint | ToPercent16 (uint i)
| Converts a "fract" value 0.
int | LeastCommonMultiple (int a, int b)
| Compute least common multiple (lcm) of arguments a and b, the smallest integer value that is a multiple of both a and b.
int | GreatestCommonDivisor (int a, int b)
| Compute greatest common divisor (gcd) of a and b.

## Detailed Description

Integer math functions.

Definition in file math_func.hpp.

## Function Documentation

template<typename T>

static FORCEINLINE T abs | ( | const T | a | ) | `[inline, static]`

Returns the absolute value of (scalar) variable.

Note:
  assumes variable to be signed

Parameters:

  | a | The value we want to unsign

Returns:
  The unsigned value

Definition at line 95 of file math_func.hpp.

Referenced by AircraftController(), AircraftGetEntryPoint(), AIRoad::AreRoadTilesConnected(), AIRail::BuildRail(), CalcRaildirsDrawstyle(), ChangeIndustryProduction(), RoadStop::Entry::CheckIntegrity(), CheckTrainsLengths(), RoadStop::ClearDriveThrough(), DoPlaceMoreTrees(), GamelogPrint(), GetTunnelBridgeLength(), HandleMouseEvents(), HeightMapCoastLines(), RoadStop::MakeDriveThrough(), OverflowSafeInt< signed __int64, INT64_MAX, INT64_MIN >::operator*=(), OverflowSafeInt< signed __int64, INT64_MAX, INT64_MIN >::operator+=(), CYapfDestinationTileT< Types >::PfCalcEstimate(), PlaceTreeAtSameHeight(), RoadStop::Entry::Rebuild(), AIRail::RemoveRail(), ReportNewsProductionChangeIndustry(), AICompany::SetLoanAmount(), SimulateDrag(), TerraformTileHeight(), TownHouseChangeInfo(), and VpSelectTilesWithMethod().

template<typename T>

static FORCEINLINE T Align | ( | const T | x,
|  | uint | n |
| ) |  |  | `[inline, static]`

Return the smallest multiple of n equal or greater than x.

Note:
  n must be a power of 2

Parameters:

  | x | The min value
  | n | The base of the number we are searching

Returns:
  The smallest multiple of n equal or greater than x

Definition at line 109 of file math_func.hpp.

Referenced by AlignPtr(), SmallVector< RefitOption, 32 >::Compact(), DrawDirtyBlocks(), MakeBMPImage(), TarListAddFile(), and ViewportSign::UpdatePosition().

template<typename T>

static FORCEINLINE T* AlignPtr | ( | T * | x,
|  | uint | n |
| ) |  |  | `[inline, static]`

Return the smallest multiple of n equal or greater than x Applies to pointers only.

Note:
  n must be a power of 2

Parameters:

  | x | The min value
  | n | The base of the number we are searching

Returns:
  The smallest multiple of n equal or greater than x

See also:
  Align()

Definition at line 127 of file math_func.hpp.

References Align(), and assert_compile().

static FORCEINLINE int Clamp | ( | const int | a,
|  | const int | min,
|  | const int | max |
| ) |  |  | `[static]`

Clamp an integer between an interval.

This function returns a value which is between the given interval of min and max. If the given value is in this interval the value itself is returned otherwise the border of the interval is returned, according which side of the interval was 'left'.

Note:
  The min value must be less or equal of max or you get some unexpected results.

Parameters:

  | a | The value to clamp/truncate.
  | min | The minimum of the interval.
  | max | the maximum of the interval.

Returns:
  A value between min and max which is closest to a.

See also:
  ClampU(uint, uint, uint)

Definition at line 175 of file math_func.hpp.

template<typename T>

static FORCEINLINE T Clamp | ( | const T | a,
|  | const T | min,
|  | const T | max |
| ) |  |  | `[inline, static]`

Clamp a value between an interval.

This function returns a value which is between the given interval of min and max. If the given value is in this interval the value itself is returned otherwise the border of the interval is returned, according which side of the interval was 'left'.

Note:
  The min value must be less or equal of max or you get some unexpected results.

Parameters:

  | a | The value to clamp/truncate.
  | min | The minimum of the interval.
  | max | the maximum of the interval.

Returns:
  A value between min and max which is closest to a.

See also:
  ClampU(uint, uint, uint)

  Clamp(int, int, int)

Definition at line 151 of file math_func.hpp.

Referenced by ChangeIndustryProduction(), Train::ConsistChanged(), AICargo::GetCargoIncome(), Train::GetCurveSpeedLimit(), GetGlobalVariable(), AIVehicle::GetLocation(), GetSavegameFormat(), GetServiceIntervalClamped(), IndustryGetVariable(), IndustryProductionCallback(), MakeBMPImage(), TooltipsWindow::OnInitialPosition(), ErrmsgWindow::OnInitialPosition(), OrdersWindow::OnQueryTextFinished(), RelocateAllWindows(), ScrollWindowTo(), SetDateWindow::SetDateWindow(), SetPriceBaseMultiplier(), SetSelectionTilesDirty(), SimulateDrag(), TownHouseChangeInfo(), TranslateXYToTileCoord(), UpdateCompanyRatingAndValue(), Scrollbar::UpdatePosition(), Train::UpdateSpeed(), UpdateTownGrowRate(), UpdateViewportPosition(), VpSelectTilesWithMethod(), and Write_ValidateSetting().

static FORCEINLINE int32 ClampToI32 | ( | const int64 | a | ) | `[static]`

Reduce a signed 64-bit int to a signed 32-bit one.

This function clamps a 64-bit integer to a 32-bit integer. If the 64-bit value is smaller than the smallest 32-bit integer value 0x80000000 this value is returned (the left one bit is the sign bit). If the 64-bit value is greater than the greatest 32-bit integer value 0x7FFFFFFF this value is returned. In all other cases the 64-bit value 'fits' in a 32-bits integer field and so the value is casted to int32 and returned.

Parameters:

  | a | The 64-bit value to clamps

Returns:
  The 64-bit value reduced to a 32-bit value

See also:
  Clamp(int, int, int)

Definition at line 215 of file math_func.hpp.

Referenced by HandleBankruptcyTakeover(), CompanyStationsWindow::StationWaitingSorter(), UpdateCompanyRatingAndValue(), VehicleProfitLastYearSorter(), VehicleProfitThisYearSorter(), VehicleTimeToLiveSorter(), and VehicleValueSorter().

static FORCEINLINE uint16 ClampToU16 | ( | const uint64 | a | ) | `[static]`

Reduce an unsigned 64-bit int to an unsigned 16-bit one.

Parameters:

  | a | The 64-bit value to clamp

Returns:
  The 64-bit value reduced to a 16-bit value

See also:
  ClampU(uint, uint, uint)

Definition at line 227 of file math_func.hpp.

Referenced by ExpandTown(), and TownGetVariable().

static FORCEINLINE uint ClampU | ( | const uint | a,
|  | const uint | min,
|  | const uint | max |
| ) |  |  | `[static]`

Clamp an unsigned integer between an interval.

This function returns a value which is between the given interval of min and max. If the given value is in this interval the value itself is returned otherwise the border of the interval is returned, according which side of the interval was 'left'.

Note:
  The min value must be less or equal of max or you get some unexpected results.

Parameters:

  | a | The value to clamp/truncate.
  | min | The minimum of the interval.
  | max | the maximum of the interval.

Returns:
  A value between min and max which is closest to a.

See also:
  Clamp(int, int, int)

Definition at line 196 of file math_func.hpp.

Referenced by CalcClosestStationTile(), ChangeIndustryProduction(), ConvertFromOldCompanyManagerFace(), and Write_ValidateSetting().

template<typename T>

static FORCEINLINE T Delta | ( | const T | a,
|  | const T | b |
| ) |  |  | `[inline, static]`

Returns the (absolute) difference between two (scalar) variables.

Parameters:

  | a | The first scalar
  | b | The second scalar

Returns:
  The absolute difference between the given scalars

Definition at line 244 of file math_func.hpp.

Referenced by DisasterTick_Big_Ufo(), DisasterTick_Big_Ufo_Destroyer(), DisasterTick_Ufo(), DistanceManhattan(), DistanceMax(), DistanceMaxPlusManhattan(), DrawTileSelection(), NPFDistanceTrack(), NewsWindow::OnTick(), PlaceTreeAtSameHeight(), TerraformTileHeight(), and VpSelectTilesWithMethod().

int GreatestCommonDivisor | ( | int | a,
|  | int | b |
| ) |  |  |

Compute greatest common divisor (gcd) of a and b.

Parameters:

  | a | First number.
  | b | second number.

Returns:
  Greatest common divisor of a and b.

Definition at line 39 of file math_func.cpp.

Referenced by LeastCommonMultiple().

template<typename T>

static FORCEINLINE bool IsInsideBS | ( | const T | x,
|  | const uint | base,
|  | const uint | size |
| ) |  |  | `[inline, static]`

Checks if a value is between a window started at some base point.

This function checks if the value x is between the value of base and base+size. If x equals base this returns true. If x equals base+size this returns false.

Parameters:

  | x | The value to check
  | base | The base value of the interval
  | size | The size of the interval

Returns:
  True if the value is in the interval, false else.

Definition at line 262 of file math_func.hpp.

Referenced by DrawTileSelection(), FindStationsNearby(), FindWindowFromPt(), NWidgetBackground::GetWidgetFromPos(), NWidgetPIPContainer::GetWidgetFromPos(), NWidgetStacked::GetWidgetFromPos(), NWidgetCore::GetWidgetFromPos(), NWidgetToolbarContainer::GetWidgetFromPos(), NWidgetSmallmapDisplay::GetWidgetFromPos(), Scrollbar::IsVisible(), MoveBuoysToWaypoints(), and OrdersWindow::OnPlaceObjectAbort().

template<typename T>

static FORCEINLINE bool IsInsideMM | ( | const T | x,
|  | const uint | min,
|  | const uint | max |
| ) |  |  | `[inline, static]`

Checks if a value is in an interval.

Returns true if a value is in the interval of [min, max).

Parameters:

  | x | The value to check
  | min | The minimum of the interval
  | max | The maximum of the interval

See also:
  IsInsideBS()

Definition at line 278 of file math_func.hpp.

Referenced by AddChildSpriteToFoundation(), AllocateMap(), CmdPlantTree(), CmdRemoveLongRoad(), SmallMapWindow::DrawSmallMapStuff(), SmallMapWindow::DrawVehicles(), GetClosestWaterDistance(), GetHalftileFoundationCorner(), IConsoleHistoryNavigate(), IsNonContinuousFoundation(), IsPtInWindowViewport(), IsSpecialRailFoundation(), IsValidCorner(), IndustryDirectoryWindow::OnClick(), AIDebugWindow::OnClick(), AISettingsWindow::OnClick(), RemapOldStringID(), and TTDPStringIDToOTTDStringIDMapping().

int LeastCommonMultiple | ( | int | a,
|  | int | b |
| ) |  |  |

Compute least common multiple (lcm) of arguments a and b, the smallest integer value that is a multiple of both a and b.

Parameters:

  | a | First number.
  | b | second number.

Returns:
  Least common multiple of values a and b.

Note:
  This function only works for non-negative values of a and b.

Definition at line 24 of file math_func.cpp.

References GreatestCommonDivisor().

Referenced by NWidgetVertical::SetupSmallestSize(), NWidgetHorizontal::SetupSmallestSize(), and NWidgetStacked::SetupSmallestSize().

template<typename T>

static FORCEINLINE T max | ( | const T | a,
|  | const T | b |
| ) |  |  | `[inline, static]`

Returns the maximum of two values.

This function returns the greater value of two given values. If they are equal the value of a is returned.

Parameters:

  | a | The first value
  | b | The second value

Returns:
  The greater value or a if equals

Definition at line 38 of file math_func.hpp.

Referenced by TileArea::Add(), AddKey(), AddSortableSpriteToDraw(), AircraftController(), NWidgetVertical::AssignSizePosition(), NWidgetHorizontal::AssignSizePosition(), NWidgetToolbarContainer::AssignSizePosition(), NWidgetSmallmapDisplay::AssignSizePosition(), CalcHeightdiff(), CalcPercentVehicleFilled(), CanBuildVehicleInfrastructure(), CanExpandRailStation(), ChangeIndustryProduction(), CheckTrainsLengths(), CmdDecreaseLoan(), CmdDeleteOrder(), CmdTerraformLand(), CommonRaiseLowerBigLand(), ConvertFromOldCompanyManagerFace(), DistanceMax(), DrawLabel(), DrawString(), DrawText(), DrawTrainDetails(), CompanyStationsWindow::DrawWidget(), SmallMapWindow::DrawWidget(), AISettingsWindow::DrawWidget(), FindStationsNearby(), Window::FindWindowPlacementAndResize(), Train::GetAcceleration(), GetAcceptanceAroundTiles(), AITown::GetAllowedNoise(), NWidgetMainToolbarContainer::GetButtonArrangement(), ExpensesList::GetCategoriesWidth(), Train::GetCurrentMaxSpeed(), GetDigitWidth(), GetGlobalVariable(), SmallMapWindow::GetLegendHeight(), SmallMapWindow::GetMaxLegendHeight(), AIBridge::GetMaxLength(), GetProductionAroundTiles(), AITown::GetRating(), GetStringBoundingBox(), GetStringWidth(), GetTileMaxZ(), GetTrainDetailsWndVScroll(), GetVehicleListHeight(), HeightMapCoastLines(), IndustryProductionCallback(), IniFile::LoadFromDisk(), LoadUnloadVehicle(), LocalGetWindowPlacement(), MakeButtonsColumn(), MakeDescriptionColumn(), MakeNWidget(), MakeWindowNWidgetTree(), MarkViewportDirty(), maxdim(), SmallMapWindow::OnClick(), AIConfigWindow::OnClick(), CompanyFinancesWindow::OnHundredthTick(), SmallMapWindow::OnInit(), SelectCompanyManagerFaceWindow::OnInit(), NewsWindow::OnInitialPosition(), ReplaceVehicleWindow::OnPaint(), AIDebugWindow::OnPaint(), NewsWindow::OnTick(), ParseResolution(), Station::RecomputeIndustriesNear(), Window::ReInit(), ResizeWindow(), SanitizeSpriteOffset(), Scrollbar::SetCapacity(), SetSnowLine(), NWidgetLeaf::SetupSmallestSize(), NWidgetBackground::SetupSmallestSize(), NWidgetVertical::SetupSmallestSize(), NWidgetHorizontal::SetupSmallestSize(), NWidgetStacked::SetupSmallestSize(), NWidgetToolbarContainer::SetupSmallestSize(), NWidgetSmallmapDisplay::SetupSmallestSize(), ShowDropDownList(), CompanyStationsWindow::StationRatingMaxSorter(), TranslateXYToTileCoord(), UpdateAircraftSpeed(), UpdateCompanyRatingAndValue(), Scrollbar::UpdatePosition(), UpdateTownGrowRate(), VehicleDetailsWindow::UpdateWidgetSize(), TownAuthorityWindow::UpdateWidgetSize(), StationViewWindow::UpdateWidgetSize(), NewGRFWindow::UpdateWidgetSize(), NewGRFAddWindow::UpdateWidgetSize(), ErrmsgWindow::UpdateWidgetSize(), CompanyWindow::UpdateWidgetSize(), SelectCompanyLiveryWindow::UpdateWidgetSize(), CompanyFinancesWindow::UpdateWidgetSize(), and VehicleMove().

static FORCEINLINE int min | ( | const int | a,
|  | const int | b |
| ) |  |  | `[static]`

Returns the minimum of two integer.

This function returns the smaller value of two given integers.

Parameters:

  | a | The first integer
  | b | The second integer

Returns:
  The smaller value

Definition at line 68 of file math_func.hpp.

template<typename T>

static FORCEINLINE T min | ( | const T | a,
|  | const T | b |
| ) |  |  | `[inline, static]`

Returns the minimum of two values.

This function returns the smaller value of two given values. If they are equal the value of b is returned.

Parameters:

  | a | The first value
  | b | The second value

Returns:
  The smaller value or b if equals

Definition at line 54 of file math_func.hpp.

Referenced by TileArea::Add(), AddInflation(), AddSortableSpriteToDraw(), AircraftController(), ApplyNoise(), AIRail::BuildNewGRFRailStation(), CHashTableT< Titem_, Thash_bits_open_ >::CalcHash(), CalculateRefitMasks(), CanExpandRailStation(), ChangeIndustryProduction(), ChopLumberMillTrees(), CmdDecreaseLoan(), CmdGiveMoney(), CmdTerraformLand(), CommonRaiseLowerBigLand(), Train::ConsistChanged(), DeliverGoodsToIndustry(), DistanceFromEdge(), DrawCargoIcons(), DrawString(), CompanyStationsWindow::DrawWidget(), NewGRFAddWindow::DrawWidget(), CompanyFinancesWindow::DrawWidget(), ReplaceVehicleWindow::DrawWidget(), AISettingsWindow::DrawWidget(), FindStationsNearby(), Window::FindWindowPlacementAndResize(), FixTTOEngines(), Train::GetAcceleration(), GetAcceptanceAroundTiles(), GetAircraftFlyingAltitude(), GetCountAndDistanceOfClosestInstance(), Train::GetCurrentMaxSpeed(), GetIndustryTypeCount(), GetNewEngine(), GetPCPElevation(), GetProductionAroundTiles(), GetTileSlope(), GetTileZ(), HeightMapCoastLines(), HeightMapGenerate(), HeightMapSmoothCoastInDirection(), HeightMapSmoothSlopes(), IConsoleCopyInParams(), IConsoleListSettings(), IndustryGetVariable(), LargeWorldCallback(), LoadUnloadVehicle(), CrashLogWindows::LogModules(), MakeBMPImage(), NPFDistanceTrack(), AIConfigWindow::OnClick(), TooltipsWindow::OnInitialPosition(), NewGRFAddWindow::OnKeyPress(), CYapfDestinationTileT< Types >::PfCalcEstimate(), PlaceTree(), RelocateAllWindows(), SaveToHighScore(), SetSnowLine(), NWidgetSmallmapDisplay::SetupSmallestSize(), SlCalcNetStringLen(), CompanyStationsWindow::StationRatingMinSorter(), TileLoopClearAlps(), TransferCargo(), TriggerIndustryProduction(), UpdateAircraftSpeed(), UpdateCompanyRatingAndValue(), UpdateStationAcceptance(), UpdateTownGrowRate(), TooltipsWindow::UpdateWidgetSize(), VehicleMove(), vseprintf(), and Write_ValidateSetting().

static FORCEINLINE uint minu | ( | const uint | a,
|  | const uint | b |
| ) |  |  | `[static]`

Returns the minimum of two unsigned integers.

This function returns the smaller value of two given unsigned integers.

Parameters:

  | a | The first unsigned integer
  | b | The second unsigned integer

Returns:
  The smaller value

Definition at line 82 of file math_func.hpp.

Referenced by StationsWndShowStationRating().

template<typename T>

static FORCEINLINE void Swap | ( | T & | a,
|  | T & | b |
| ) |  |  | `[inline, static]`

Type safe swap operation.

Parameters:

  | a | variable to swap with b
  | b | variable to swap with a

Definition at line 289 of file math_func.hpp.

Referenced by AIRail::AreTilesConnected(), BuildRailClick_Remove(), CalcHeightdiff(), CmdBuildBridge(), CmdClearArea(), CmdConvertRail(), IndustryDirectoryWindow::GetCargoTransportedSortValue(), GSortT(), MemReverseT(), AIConfigWindow::OnClick(), ReallyDoDrawString(), TileArea::TileArea(), and UpdateTileSelection().

static FORCEINLINE uint ToPercent16 | ( | uint | i | ) | `[static]`

Converts a "fract" value 0.

.65535 to "percent" value 0..100

Parameters:

  | i | value to convert, range 0..65535

Returns:
  value in range 0..100

Definition at line 312 of file math_func.hpp.

Referenced by DrawVehiclePurchaseInfo(), VehicleDetailsWindow::DrawWidget(), AIVehicle::GetReliability(), AIEngine::GetReliability(), and ProcessConditionalOrder().

static FORCEINLINE uint ToPercent8 | ( | uint | i | ) | `[static]`

Converts a "fract" value 0.

.255 to "percent" value 0..100

Parameters:

  | i | value to convert, range 0..255

Returns:
  value in range 0..100

Definition at line 301 of file math_func.hpp.

Referenced by StationViewWindow::DrawCargoRatings(), AIStation::GetCargoRating(), IndustryDirectoryWindow::GetCargoTransportedPercentsIfValid(), IndustryDirectoryWindow::GetIndustryString(), AITown::GetLastMonthTransportedPercentage(), and AIIndustry::GetLastMonthTransportedPercentage().