OpenTTD Source: src/core/math_func.hpp File Reference

OpenTTD Source 15.0-RC2

Functions
math_func.hpp File Reference

Integer math functions. More...

`#include "convertible_through_base.hpp"`

Go to the source code of this file.

## Functions
template<typename T >
constexpr T | abs (const T a)
| Returns the absolute value of (scalar) variable.
template<typename T >
constexpr T | Align (const T x, uint n)
| Return the smallest multiple of n equal or greater than x.
template<typename T >
constexpr T * | AlignPtr (T *x, uint n)
| Return the smallest multiple of n equal or greater than x Applies to pointers only.
template<typename T >
constexpr T | Clamp (const T a, const T min, const T max)
| Clamp a value between an interval.
template<typename T >
constexpr T | SoftClamp (const T a, const T min, const T max)
| Clamp a value between an interval.
constexpr int | Clamp (const int a, const int min, const int max)
| Clamp an integer between an interval.
constexpr uint | ClampU (const uint a, const uint min, const uint max)
| Clamp an unsigned integer between an interval.
template<typename To , typename From , std::enable_if_t< std::is_integral< From >::value, int > = 0>
constexpr To | ClampTo (From value)
| Clamp the given value down to lie within the requested type.
template<typename To >
constexpr To | ClampTo (ConvertibleThroughBase auto value)
| Specialization of ClampTo for StrongType::Typedef.
template<typename T >
constexpr T | Delta (const T a, const T b)
| Returns the (absolute) difference between two (scalar) variables.
template<typename T >
constexpr bool | IsInsideBS (const T x, const size_t base, const size_t size)
| Checks if a value is between a window started at some base point.
constexpr bool | IsInsideMM (const size_t x, const size_t min, const size_t max) noexcept
| Checks if a value is in an interval.
constexpr bool | IsInsideMM (const ConvertibleThroughBase auto x, const size_t min, const size_t max) noexcept
template<typename enum_type , std::enable_if_t< std::is_enum_v< enum_type >, bool > = true>
constexpr bool | IsInsideMM (enum_type x, enum_type min, enum_type max) noexcept
constexpr uint | ToPercent8 (uint i)
| Converts a "fract" value 0..255 to "percent" value 0..100.
constexpr uint | ToPercent16 (uint i)
| Converts a "fract" value 0..65535 to "percent" value 0..100.
int | DivideApprox (int a, int b)
| Deterministic approximate division.
constexpr uint | CeilDiv (uint a, uint b)
| Computes ceil(a / b) for non-negative a and b.
constexpr uint | Ceil (uint a, uint b)
| Computes ceil(a / b) * b for non-negative a and b.
constexpr int | RoundDivSU (int a, uint b)
| Computes round(a / b) for signed a and unsigned b.
constexpr uint64_t | PowerOfTen (int power)
| Computes ten to the given power.
uint32_t | IntSqrt (uint32_t num)
| Compute the integer square root.

## Detailed Description

Integer math functions.

Definition in file math_func.hpp.

## Function Documentation

## ◆ abs()

template<typename T >

constexpr T abs | ( | const T | a | ) |
| constexpr

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 23 of file math_func.hpp.

Referenced by AircraftController(), AircraftGetEntryPoint(), CalcRaildirsDrawstyle(), ChangeIndustryProduction(), CheckClickOnVehicle(), CheckTrainCollision(), CheckTrainsLengths(), DeterminePluralForm(), DivideApprox(), LinkGraphOverlay::DrawContent(), BaseGraphWindow::DrawGraph(), TimetableWindow::DrawSummaryPanel(), Kdtree< T, TxyFunc, CoordT, DistT >::FindNearestRecursive(), CargoPacket::GetDistance(), GetTunnelBridgeLength(), BaseGraphWindow::GetValuesInterval(), GfxDoDrawLine(), HandleMouseEvents(), HandleWindowDragging(), HeightMapCoastLines(), OctileDistanceCost(), DiagonalTileIterator::operator++(), PlaceTreeAtSameHeight(), ReportNewsProductionChangeIndustry(), SettingsValueAbsolute(), TerraformTileHeight(), TownHouseChangeInfo(), UpdateViewportPosition(), and VpSelectTilesWithMethod().

## ◆ Align()

template<typename T >

constexpr T Align | ( | const T | x,
|  | uint | n
| ) |  |
| constexpr

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 37 of file math_func.hpp.

Referenced by TarScanner::AddFile(), AlignPtr(), VideoDriver_Win32GDI::AllocateBackingStore(), DEFINE_POOL_METHOD(), OpenGLBackend::Resize(), OpenGLSprite::Update(), and ViewportSign::UpdatePosition().

## ◆ AlignPtr()

template<typename T >

constexpr T * AlignPtr | ( | T * | x,
|  | uint | n
| ) |  |
| constexpr

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 55 of file math_func.hpp.

References Align().

## ◆ Ceil()

constexpr uint Ceil | ( | uint | a,
|  | uint | b
| ) |  |
| constexpr

Computes ceil(a / b) * b for non-negative a and b.

Parameters

  a | Numerator
  b | Denominator

Returns
  a rounded up to the nearest multiple of b.

Definition at line 321 of file math_func.hpp.

References CeilDiv().

Referenced by ResizeWindow(), and SurveyMemoryToText().

## ◆ CeilDiv()

constexpr uint CeilDiv | ( | uint | a,
|  | uint | b
| ) |  |
| constexpr

Computes ceil(a / b) for non-negative a and b.

Parameters

  a | Numerator
  b | Denominator

Returns
  Quotient, rounded up

Definition at line 310 of file math_func.hpp.

Referenced by AddDirtyBlock(), AfterLoadGame(), AircraftController(), NWidgetMatrix::AssignSizePosition(), BuildLandLegend(), CalcPercentVehicleFilled(), CalcRaildirsDrawstyle(), Ceil(), CompanyCheckBankrupt(), StationViewWindow::DrawAcceptedCargo(), StationViewWindow::DrawCargoRatings(), DepotWindow::DrawVehicleInDepot(), NWidgetMainToolbarContainer::GetButtonArrangement(), Train::GetCurveSpeedLimit(), GetLoadAmount(), SmallMapWindow::GetNumberRowsLegend(), GfxDoDrawLine(), InverseRemapCoords2(), MakeTreeTypeButtons(), DepotWindow::OnPaint(), Industry::RecomputeProductionMultipliers(), ReplaceChain(), Map::ScaleBySize(), Map::ScaleBySize1D(), ServerNetworkAdminSocketHandler::SendCompanyInfo(), ServerNetworkAdminSocketHandler::SendCompanyUpdate(), NWidgetMatrix::SetCount(), TextfileWindow::SetupScrollbars(), SurveyMemoryToText(), and UpdateVehicleTimetable().

## ◆ Clamp() [1/2]

constexpr int Clamp | ( | const int | a,
|  | const int | min,
|  | const int | max
| ) |  |
| constexpr

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 129 of file math_func.hpp.

## ◆ Clamp() [2/2]

template<typename T >

constexpr T Clamp | ( | const T | a,
|  | const T | min,
|  | const T | max
| ) |  |
| constexpr

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 79 of file math_func.hpp.

Referenced by AdjustGUIZoom(), AfterLoadGame(), AirportChangeInfo(), AmbientSoundEffectCallback(), AnimationBase< Tbase, Tspec, Tobj, Textra, GetCallback, Tframehelper >::AnimateTile(), ChangeIndustryProduction(), ClampSmoothScroll(), ClickChangeDateCheat(), ClickChangeMaxHlCheat(), ClickSliderWidget(), CmdTownRating(), Train::ConsistChanged(), CreateEffectVehicleAbove(), DrawRoadVehEngine(), DrawSliderWidget(), RefitWindow::DrawWidget(), EnsureVisibleCaption(), NetworkAskRelayWindow::FindWindowPlacementAndResize(), NetworkAskSurveyWindow::FindWindowPlacementAndResize(), GenerateLandscape(), GenerateTerrainPerlin(), GetAmplitude(), QueryString::GetBoundingRect(), Path::GetCapacityRatio(), Train::GetCurveSpeedLimit(), GetGlobalVariable(), GetPlatformInfo(), GetRoadVehLength(), GetSavegameFormat(), GetServiceIntervalClamped(), GetTileHeightBelowAircraft(), VehicleScopeResolver::GetVariable(), HandleCrashedAircraft(), HeightMapCurves(), IndustrytilesChangeInfo(), InitializeWindowViewport(), InverseRemapCoords2(), IntSettingDesc::MakeValueValid(), GenerateLandscapeWindow::OnClick(), CreateScenarioWindow::OnClick(), NetworkStartServerWindow::OnClick(), CustomCurrencyWindow::OnClick(), BuildBridgeWindow::OnInitialPosition(), SpriteAlignerWindow::OnInvalidateData(), GenerateLandscapeWindow::OnQueryTextFinished(), CreateScenarioWindow::OnQueryTextFinished(), NetworkStartServerWindow::OnQueryTextFinished(), OrdersWindow::OnQueryTextFinished(), CustomCurrencyWindow::OnQueryTextFinished(), MultiCommodityFlow::PushFlow(), RailTypeChangeInfo(), RecomputePrices(), SetAircraftPosition(), SetDateWindow::SetDateWindow(), Scrollbar::SetPosition(), SetPriceBaseMultiplier(), SetSelectionTilesDirty(), ScriptConfig::SetSetting(), SetStartingYear(), GRFConfig::SetValue(), SmallMapWindow::SetZoomLevel(), SoundEffectChangeInfo(), MusicDriver_Win32::Start(), TileHeightOutsideMap(), TileLoop_Town(), TownHouseChangeInfo(), TransmitNotesOff(), Train::UpdateAcceleration(), UpdateGUIZoom(), Scrollbar::UpdateListPositionOnKeyPress(), DisasterVehicle::UpdatePosition(), UpdateStationRating(), VehicleEnterDepot(), and VpSelectTilesWithMethod().

## ◆ ClampTo() [1/2]

template<typename To >

constexpr To ClampTo | ( | ConvertibleThroughBase auto | value | ) |
| constexpr

Specialization of ClampTo for StrongType::Typedef.

Definition at line 221 of file math_func.hpp.

## ◆ ClampTo() [2/2]

template<typename To , typename From , std::enable_if_t< std::is_integral< From >::value, int > = 0>

constexpr To ClampTo | ( | From | value | ) |
| constexpr

Clamp the given value down to lie within the requested type.

For example ClampTo<uint8_t> will return a value clamped to the range of 0 to 255. Anything smaller will become 0, anything larger will become 255.

Parameters

  a | The 64-bit value to clamp.

Returns
  The 64-bit value reduced to a value within the given allowed range for the return type.

See also
  Clamp(int, int, int)

Definition at line 167 of file math_func.hpp.

## ◆ ClampU()

constexpr uint ClampU | ( | const uint | a,
|  | const uint | min,
|  | const uint | max
| ) |  |
| constexpr

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 150 of file math_func.hpp.

Referenced by CalcClosestStationTile(), ChangeIndustryProduction(), ConvertFromOldCompanyManagerFace(), IntSettingDesc::MakeValueValid(), IndustryViewWindow::OnQueryTextFinished(), VideoDriver::UpdateAutoResolution(), and SavePresetWindow::UpdateWidgetSize().

## ◆ Delta()

template<typename T >

constexpr T Delta | ( | const T | a,
|  | const T | b
| ) |  |
| constexpr

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 234 of file math_func.hpp.

Referenced by DisasterTick_Big_Ufo(), DisasterTick_Big_Ufo_Destroyer(), DisasterTick_Ufo(), DistanceManhattan(), DistanceMax(), DistanceMaxPlusManhattan(), DrawTileSelection(), PlaceTreeAtSameHeight(), and VpSelectTilesWithMethod().

## ◆ DivideApprox()

int DivideApprox | ( | int | a,
|  | int | b
| ) |  |

Deterministic approximate division.

Cancels out division errors stemming from the integer nature of the division over multiple runs.

Parameters

  a | Dividend.
  b | Divisor.

Returns
  a/b or (a/b)+1.

Definition at line 22 of file math_func.cpp.

References abs().

Referenced by StationViewWindow::BuildCargoList(), and StationViewWindow::EstimateDestinations().

## ◆ IntSqrt()

uint32_t IntSqrt | ( | uint32_t | num | ) |

Compute the integer square root.

Parameters

  num | Radicand.

Returns
  Rounded integer square root.

Note
  Algorithm taken from http://en.wikipedia.org/wiki/Methods_of_computing_square_roots

Definition at line 42 of file math_func.cpp.

Referenced by CanalMaintenanceCost(), RailMaintenanceCost(), RoadMaintenanceCost(), SignalMaintenanceCost(), and StationMaintenanceCost().

## ◆ IsInsideBS()

template<typename T >

constexpr bool IsInsideBS | ( | const T | x,
|  | const size_t | base,
|  | const size_t | size
| ) |  |
| constexpr

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 252 of file math_func.hpp.

Referenced by AirportGetNearestTown(), CmdPlantTree(), OrthogonalTileArea::Contains(), ConvertSdlKeycodeIntoMy(), DrawTileSelection(), ScriptDebugWindow::DrawWidget(), FindStationsNearby(), FindWindowFromPt(), OrdersWindow::GetOrderFromPt(), GetSlopePixelZOutsideMap(), NWidgetNewGRFDisplay::GetWidgetFromPos(), NWidgetCore::GetWidgetFromPos(), NWidgetContainer::GetWidgetFromPos(), NWidgetStacked::GetWidgetFromPos(), NWidgetMatrix::GetWidgetFromPos(), NWidgetBackground::GetWidgetFromPos(), NewGRFInspectWindow::HasVariableParameter(), Scrollbar::IsVisible(), MoveBuoysToWaypoints(), SelectCompanyManagerFaceWindow::OnClick(), IndustryViewWindow::OnClick(), NetworkContentListWindow::OnClick(), SpriteAlignerWindow::OnClick(), TransparenciesWindow::OnClick(), TranslateXYToTileCoord(), and ViewportAddLandscape().

## ◆ IsInsideMM() [1/3]

constexpr bool IsInsideMM | ( | const ConvertibleThroughBase auto | x,
|  | const size_t | min,
|  | const size_t | max
| ) |  |
| constexprnoexcept

Definition at line 272 of file math_func.hpp.

## ◆ IsInsideMM() [2/3]

constexpr bool IsInsideMM | ( | const size_t | x,
|  | const size_t | min,
|  | const size_t | max
| ) |  |
| constexprnoexcept

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 267 of file math_func.hpp.

Referenced by AddChildSpriteToFoundation(), AddDateIntroducedRailTypes(), AddDateIntroducedRoadTypes(), AfterLoadGame(), Map::Allocate(), CheckClickOnVehicle(), CmdBuildLock(), CmdBuildObject(), CmdPlantTree(), Convert32bppTo8bpp(), ConZoomToLevel(), RoadVehicle::Crash(), DeleteLastRoadVeh(), GoalListWindow::DrawListColumn(), SmallMapWindow::DrawVehicles(), GraphLegendWindow::DrawWidget(), PerformanceRatingDetailWindow::DrawWidget(), LinkGraphLegendWindow::DrawWidget(), BuildSignalWindow::DrawWidget(), BuildRailDepotWindow::DrawWidget(), BuildRoadDepotWindow::DrawWidget(), SubsidyListWindow::DrawWidget(), FileList::FindItem(), MissingGlyphSearcher::FindMissingGlyphs(), FormatString(), GenerateCompanyName(), GenerateStationName(), QueryString::GetCharAtPosition(), Layouter::GetCharAtPosition(), GetClosestWaterDistance(), GetHalftileFoundationCorner(), GetStringWithArgs(), IConsoleWindow::GetTextCharacterAtPosition(), GetTownRoadType(), BuildVehicleWindow::GetWidgetString(), PickerWindow::GetWidgetString(), HasRoadTypeAvail(), IsNonContinuousFoundation(), IsPtInWindowViewport(), IsSpecialRailFoundation(), IsValidCorner(), CITYChunkHandler::Load(), PLYRChunkHandler::LoadCheck(), MapGRFStringID(), ReplaceVehicleWindow::OnClick(), BuildVehicleWindow::OnClick(), GSConfigWindow::OnClick(), GraphLegendWindow::OnClick(), PerformanceRatingDetailWindow::OnClick(), LinkGraphLegendWindow::OnClick(), NewGRFParametersWindow::OnClick(), PickerWindow::OnClick(), ScriptSettingsWindow::OnClick(), ScriptDebugWindow::OnClick(), ScenarioEditorLandscapeGenerationWindow::OnClick(), BuildVehicleWindow::OnDropdownSelect(), PickerWindow::OnDropdownSelect(), LinkGraphLegendWindow::OnTooltip(), PlaceTreeGroupAroundTile(), Vehicle::PreDestructor(), RemapOldStringID(), SwitchNewGRFBlitter(), TTDPStringIDToOTTDStringIDMapping(), Vehicle::UpdateVisualEffect(), LinkGraphLegendWindow::UpdateWidgetSize(), BuildSignalWindow::UpdateWidgetSize(), BuildRailDepotWindow::UpdateWidgetSize(), and BuildRoadDepotWindow::UpdateWidgetSize().

## ◆ IsInsideMM() [3/3]

template<typename enum_type , std::enable_if_t< std::is_enum_v< enum_type >, bool > = true>

constexpr bool IsInsideMM | ( | enum_type | x,
|  | enum_type | min,
|  | enum_type | max
| ) |  |
| constexprnoexcept

Definition at line 275 of file math_func.hpp.

## ◆ PowerOfTen()

constexpr uint64_t PowerOfTen | ( | int | power | ) |
| constexpr

Computes ten to the given power.

Parameters

  power | The power of ten to get.

Returns
  The power of ten.

Definition at line 348 of file math_func.hpp.

Referenced by FormatString().

## ◆ RoundDivSU()

constexpr int RoundDivSU | ( | int | a,
|  | uint | b
| ) |  |
| constexpr

Computes round(a / b) for signed a and unsigned b.

Parameters

  a | Numerator
  b | Denominator

Returns
  Quotient, rounded to nearest

Definition at line 332 of file math_func.hpp.

Referenced by IndustryViewWindow::DrawInfo(), DrawLayoutLine(), DrawStringMultiLine(), ScenarioEditorLandscapeGenerationWindow::DrawWidget(), TownViewWindow::DrawWidget(), HandleScrollbarScrolling(), IndustryViewWindow::OnClick(), IndustryViewWindow::OnQueryTextFinished(), and UpdateTownGrowCounter().

## ◆ SoftClamp()

template<typename T >

constexpr T SoftClamp | ( | const T | a,
|  | const T | min,
|  | const T | max
| ) |  |
| constexpr

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
  If the min value is greater than the max, return value is the average of the min and max.

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.

Definition at line 102 of file math_func.hpp.

Referenced by QueryWindow::FindWindowPlacementAndResize(), and TooltipsWindow::OnInitialPosition().

## ◆ ToPercent16()

constexpr uint ToPercent16 | ( | uint | i | ) |
| constexpr

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 296 of file math_func.hpp.

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

## ◆ ToPercent8()

constexpr uint ToPercent8 | ( | uint | i | ) |
| constexpr

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 285 of file math_func.hpp.

Referenced by StationViewWindow::DrawCargoRatings(), IndustryViewWindow::DrawInfo(), IndustryDirectoryWindow::GetCargoTransportedPercentsIfValid(), and IndustryDirectoryWindow::GetIndustryString().