KiCad PCB EDA Suite
Loading...
Searching...
No Matches
util.h File Reference
#include <config.h>
#include <cmath>
#include <cstdint>
#include <limits>
#include <typeinfo>
#include <type_traits>

Go to the source code of this file.

Functions

void kimathLogDebug (const char *aFormatString,...)
 Helper to avoid directly including wx/log.h for the templated functions in kimath. More...
 
void kimathLogOverflow (double v, const char *aTypeName)
 Workaround to avoid the empty-string conversion issue in wxWidgets. More...
 
template<typename T >
constexpr T Clamp (const T &lower, const T &value, const T &upper)
 Limit value within the range lower <= value <= upper. More...
 
template<typename fp_type , typename ret_type = int>
constexpr ret_type KiROUND (fp_type v)
 Round a floating point number to an integer using "round halfway cases away from zero". More...
 
template<typename T >
rescale (T aNumerator, T aValue, T aDenominator)
 Scale a number (value) by rational (numerator/denominator). More...
 
template<typename T >
int sign (T val)
 
template<>
int rescale (int aNumerator, int aValue, int aDenominator)
 
template<>
int64_t rescale (int64_t aNumerator, int64_t aValue, int64_t aDenominator)
 
template<class T >
std::enable_if< std::is_floating_point< T >::value, bool >::type equals (T aFirst, T aSecond, T aEpsilon=std::numeric_limits< T >::epsilon())
 Template to compare two floating point values for equality within a required epsilon. More...
 

Function Documentation

◆ Clamp()

template<typename T >
constexpr T Clamp ( const T &  lower,
const T &  value,
const T &  upper 
)
inlineconstexpr

Limit value within the range lower <= value <= upper.

It will work on temporary expressions, since they are evaluated only once, and it should work on most if not all numeric types, string types, or any type for which "operator < ()" is present. The arguments are accepted in this order so you can remember the expression as a memory aid:

result is: lower <= value <= upper

Definition at line 64 of file util.h.

Referenced by LSET::AllCuMask(), DIALOG_PAGES_SETTINGS::GetCustomSizeMilsFromDialog(), VECTOR2< T >::operator()(), SCH_IO_KICAD_SEXPR_PARSER::parseEDA_TEXT(), SCH_IO_KICAD_SEXPR_PARSER::parseFill(), SCH_IO_KICAD_SEXPR_PARSER::parseJunction(), STROKE_PARAMS_PARSER::ParseStroke(), DRAWING_SHEET_PARSER::parseText(), BRDITEMS_PLOTTER::plotOneDrillMark(), PCB_PLOT_PARAMS::SetSvgPrecision(), DIALOG_SYMBOL_FIELDS_TABLE::SetupAllColumnProperties(), DIALOG_PAGES_SETTINGS::UpdateDrawingSheetExample(), and VECTOR2< T >::VECTOR2().

◆ equals()

template<class T >
std::enable_if< std::is_floating_point< T >::value, bool >::type equals ( aFirst,
aSecond,
aEpsilon = std::numeric_limits<T>::epsilon() 
)

Template to compare two floating point values for equality within a required epsilon.

Parameters
aFirstvalue to compare.
aSecondvalue to compare.
aEpsilonallowed error.
Returns
true if the values considered equal within the specified epsilon, otherwise false.

Definition at line 158 of file util.h.

References std::abs().

◆ kimathLogDebug()

void kimathLogDebug ( const char *  aFormatString,
  ... 
)

Helper to avoid directly including wx/log.h for the templated functions in kimath.

Definition at line 44 of file util.cpp.

Referenced by rescale().

◆ kimathLogOverflow()

void kimathLogOverflow ( double  v,
const char *  aTypeName 
)

Workaround to avoid the empty-string conversion issue in wxWidgets.

Definition at line 58 of file util.cpp.

Referenced by KiROUND().

◆ KiROUND()

template<typename fp_type , typename ret_type = int>
constexpr ret_type KiROUND ( fp_type  v)
constexpr

Round a floating point number to an integer using "round halfway cases away from zero".

In Debug build an assert fires if will not fit into the return type.

Definition at line 85 of file util.h.

References kimathLogOverflow(), and name.

Referenced by ZONE_FILLER::addHatchFillTypeOnZone(), PCB_IO_IPC2581::addPadStack(), PCB_IO_IPC2581::addShape(), TEARDROP_MANAGER::AddTeardropsOnTracks(), PCAD2KICAD::PCAD_POLYGON::AddToBoard(), PCB_IO_IPC2581::addVia(), SYMBOL_EDITOR_MOVE_TOOL::AlignElements(), Altium2KiCadUnit(), AltiumGetEllipticalPos(), CADSTAR_PCB_ARCHIVE_LOADER::applyTextCode(), CADSTAR_SCH_ARCHIVE_LOADER::applyTextCodeIfExists(), CADSTAR_SCH_ARCHIVE_LOADER::applyTextSettings(), CADSTAR_SCH_ARCHIVE_LOADER::applyTransform(), HPGL_PLOTTER::Arc(), PDF_PLOTTER::Arc(), EDA_ANGLE::AsTenthsOfADegree(), SCH_DIRECTIVE_LABEL::AutoplaceFields(), SCH_SHEET::AutoplaceFields(), SHAPE_ARC::BBox(), PCB_GRID_HELPER::BestSnapAnchor(), KIGFX::SCH_PAINTER::bitmapText(), PCB_IO_KICAD_LEGACY::biuParse(), build45DegLeader(), BuildCornersList_S_Shape(), PNS::DP_GATEWAYS::buildDpContinuation(), PAD::BuildEffectivePolygon(), DIRECTION_45::BuildInitialTrace(), ZONE_FILLER::buildThermalSpokes(), CalcArcCenter(), EDA_SHAPE::calcEdit(), PCAD2KICAD::CalculateTextLengthSize(), SHAPE_POLY_SET::chamferFilletPolygon(), SCH_EDIT_TOOL::ChangeTextType(), DRC_TEST_PROVIDER_MATCHED_LENGTH::checkSkews(), EE_INSPECTION_TOOL::CheckSymbol(), CircleToEndSegmentDeltaRadius(), Clamp_Text_PenSize(), EE_SELECTION_TOOL::CollectHits(), TEARDROP_MANAGER::computeAnchorPoints(), SCH_LINE_WIRE_BUS_TOOL::computeBreakPoint(), computeCenter(), TEARDROP_MANAGER::computeCurvedForRoundShape(), GRID_HELPER::computeNearest(), TEARDROP_MANAGER::computeTeardropPolygon(), ConfigureHPGLPenSizes(), ALTIUM_PCB::ConvertArcs6ToBoardItemOnLayer(), ALTIUM_PCB::ConvertArcs6ToPcbShape(), ConvertArcToPolyline(), AM_PRIMITIVE::ConvertBasicShapeToPolygon(), convertPolygon(), AM_PRIMITIVE::ConvertShapeToPolygon(), ALTIUM_PROPS_UTILS::ConvertToKicadUnit(), SHAPE_ARC::ConvertToPolyline(), PCAD2KICAD::CorrectTextPosition(), SCH_DIRECTIVE_LABEL::CreateGraphicShape(), BOARD_ADAPTER::createLayers(), MICROWAVE_TOOL::createMicrowaveInductor(), MICROWAVE_TOOL::createPolygonShape(), CONVERT_TOOL::CreatePolys(), BOARD_ADAPTER::createTrack(), EDIT_TOOL::DragArcTrack(), KIGFX::SCH_PAINTER::draw(), KIGFX::PCB_PAINTER::draw(), KIGFX::OPENGL_GAL::DrawArcSegment(), BITMAP_BASE::DrawBitmap(), KIGFX::OPENGL_GAL::drawBitmapChar(), CADSTAR_PCB_ARCHIVE_LOADER::drawCadstarText(), KIGFX::CAIRO_GAL_BASE::DrawGrid(), KIGFX::OPENGL_GAL::DrawGrid(), SCH_DRAWING_TOOLS::DrawTable(), DRAWING_TOOL::DrawTable(), GERBER_PLOTTER::emitDcode(), SIM_PLOT_TAB::EnableCursor(), PCBEXPR_EVALUATOR::Evaluate(), GERBER_FILE_IMAGE::ExecuteRS274XCommand(), PANEL_GALVANIC_CORROSION::fillTable(), TEARDROP_MANAGER::findAnchorPointsOnTrack(), EDIT_POINTS::FindPoint(), HPGL_PLOTTER::FlashPadCircle(), HPGL_PLOTTER::FlashPadOval(), HPGL_PLOTTER::FlashPadRect(), HPGL_PLOTTER::FlashPadRoundRect(), GENCAD_EXPORTER::FootprintWriteShape(), DS_DATA_MODEL_IO::format(), EDA_TEXT::Format(), STROKE_PARAMS::Format(), formatFill(), BITMAP2CMP_PANEL::FormatOutputSize(), gen_arc(), GENDRILL_WRITER_BASE::genDrillMapFile(), GENERAL_COLLECTORS_GUIDE::GENERAL_COLLECTORS_GUIDE(), RENDER_3D_OPENGL::generate3dGrid(), PCB_IO_IPC2581::generateContentStackup(), WX_HTML_REPORT_BOX::generateHtml(), GERBER_DRAW_ITEM::GetABPosition(), SCH_LINE::GetAngleFrom(), GetArcToSegmentCount(), LIB_PIN::GetBoundingBox(), CADSTAR_SCH_ARCHIVE_LOADER::getCadstarAngle(), GetClampedCoords(), DS_DATA_ITEM::GetEndPosIU(), EE_GRID_HELPER::GetGrid(), KIGFX::GAL::GetGridPoint(), getGUIFont(), EDA_TEXT::GetInterline(), GetKnockoutTextMargin(), SCH_LABEL_BASE::GetLabelBoxExpansion(), LIB_TEXTBOX::GetLegacyTextMargin(), SCH_TEXTBOX::GetLegacyTextMargin(), PCB_TEXTBOX::GetLegacyTextMargin(), EDA_DRAW_FRAME::GetNearestGridPosition(), EDA_DRAW_FRAME::GetNearestHalfGridPosition(), EE_SELECTION_TOOL::GetNode(), KIGFX::SCH_PAINTER::getOperatingPointTextSize(), PCB_TUNING_PATTERN::getOutline(), IMAGE_SIZE::GetOutputDPI(), GetPenSizeForBold(), GetPenSizeForDemiBold(), GetPenSizeForNormal(), DS_DATA_ITEM::GetPenSizeIU(), DS_DATA_ITEM_POLYGONS::GetPenSizeIU(), DS_DATA_ITEM_TEXT::GetPenSizeIU(), EDA_SHAPE::GetRadius(), SCH_LINE::GetReverseAngleFrom(), PAD::GetRoundRectCornerRadius(), BITMAP_BASE::GetSize(), PAD::GetSolderPasteMargin(), DS_DATA_ITEM::GetStartPosIU(), KIFONT::OUTLINE_FONT::GetTextAsGlyphs(), KIFONT::STROKE_FONT::GetTextAsGlyphs(), EDA_TEXT::GetTextBox(), CADSTAR_SCH_ARCHIVE_LOADER::getTextHeightFromTextCode(), SCH_TEXT::GetTextOffset(), DIALOG_POSITION_RELATIVE::getTranslationInIU(), GERBER_DRAW_ITEM::GetXYPosition(), GRTextWidth(), EE_SELECTION_TOOL::GuessSelectionCandidates(), PCB_SELECTION_TOOL::GuessSelectionCandidates(), ZONE::HatchBorder(), ALTIUM_PCB::HelperParseDimensions6Leader(), HelperShapeLineChainFromAltiumVertices(), DIALOG_PLOT::init_Dialog(), initializePlotter(), GENERAL_COLLECTOR::Inspect(), SCH_EDIT_TOOL::InteractiveDelete(), PL_EDIT_TOOL::InteractiveDelete(), PCB_CONTROL::InteractiveDelete(), CIRCLE::Intersect(), CN_ANCHOR::IsDangling(), PCB_TRACK::IsPointOnEnds(), iu_to_d356(), KiScaledBitmap(), PCB_IO_EAGLE::LoadBoard(), PCB_IO_EASYEDA::LoadBoard(), CADSTAR_SCH_ARCHIVE_LOADER::loadDocumentationSymbols(), SCH_IO_EAGLE::loadFrame(), SCH_IO_EAGLE::loadLabel(), PCB_IO_EAGLE::loadPlain(), PCB_IO_EAGLE::loadPolygon(), CADSTAR_SCH_ARCHIVE_LOADER::loadShapeVertices(), PCB_IO_EAGLE::loadSignals(), CADSTAR_SCH_ARCHIVE_LOADER::loadSymbolFieldAttribute(), PCB_TUNING_PATTERN::MakeEditPoints(), DSN::SPECCTRA_DB::makePADSTACK(), MapAnglesV6(), GRAPHICS_IMPORTER_LIB_SYMBOL::MapCoordinate(), GRAPHICS_IMPORTER_SCH::MapCoordinate(), GRAPHICS_IMPORTER_PCBNEW::MapCoordinate(), PLOTTER::markerSquare(), SIM_MODEL::MigrateSimModel(), EDA_UNIT_UTILS::Mils2mm(), GERBVIEW_PRINTOUT::milsToIU(), PCBNEW_PRINTOUT::milsToIU(), SCH_PRINTOUT::milsToIU(), EDA_UNIT_UTILS::Mm2mils(), ACTION_TOOLBAR::OnCustomRender(), PANEL_SYM_EDITING_OPTIONS::onKillFocusPinPitch(), EDA_LIST_DIALOG::onSize(), PANEL_PACKAGE::OnSize(), BITMAP2CMP_PANEL::OpenProjectFiles(), PCB_IO_EAGLE::orientFPText(), PCB_IO_EAGLE::packagePad(), PCB_IO_EAGLE::packagePolygon(), PCB_IO_EAGLE::packageText(), DIALOG_PAD_PROPERTIES::padValuesOK(), PANEL_PACKAGE::PANEL_PACKAGE(), PCAD2KICAD::PCAD_ARC::Parse(), SCH_IO_ALTIUM::ParseArc(), PCB_IO_EASYEDAPRO_PARSER::ParseBoard(), PCB_IO_KICAD_SEXPR_PARSER::parseBoardUnits(), SCH_IO_ALTIUM::ParseEllipse(), SCH_IO_ALTIUM::ParseEllipticalArc(), GPCB_FPL_CACHE::parseFOOTPRINT(), parseInt(), SCH_IO_KICAD_SEXPR_PARSER::parseInternalUnits(), SCH_EASYEDAPRO_PARSER::ParseSchematic(), SCH_EASYEDA_PARSER::ParseSchematic(), PCB_IO_EASYEDA_PARSER::ParseToBoardItemContainer(), DRAWING_TOOL::PlaceTuningPattern(), SCH_TEXT::Plot(), GERBER_PLOTTER::plotArc(), PS_PLOTTER::PlotImage(), GERBER_PLOTTER::plotRoundRectAsRegion(), PLOTTER::polyArc(), SCH_TEXT::Print(), GERBER_DRAW_ITEM::Print(), FABMASTER::processArc(), FABMASTER::processFootprints(), FABMASTER::processLine(), FABMASTER::processPadStacks(), FABMASTER::processPins(), FABMASTER::processRectangle(), FABMASTER::processText(), FABMASTER::processVias(), GERBER_FILE_IMAGE::ReadIJCoord(), PARAM_CFG_INT_WITH_SCALE::ReadParam(), EXCELLON_IMAGE::readToolInformation(), GERBER_FILE_IMAGE::ReadXYCoord(), PANEL_SETUP_PINMAP::reBuildMatrixPanel(), PSLIKE_PLOTTER::returnPostscriptTextWidth(), RotatePoint(), rotationFromString(), EDA_ANGLE::Round(), SCH_IO_KICAD_SEXPR::saveJunction(), SCH_IO_KICAD_SEXPR::saveSheet(), EDA_SHAPE::scale(), DSN::scale(), SCH_EASYEDA_PARSER::ScaleSize(), PCB_IO_EASYEDA_PARSER::ScaleSize(), SCH_EASYEDAPRO_PARSER::ScaleSize(), PCB_IO_EASYEDAPRO_PARSER::ScaleSize(), scaletoIU(), SCH_JUNCTION::SCH_JUNCTION(), PLOTTER::segmentAsOval(), PNS::SegmentHull(), SegmentIntersectsSegment(), PCB_SELECTION_TOOL::selectionContains(), PL_SELECTION_TOOL::SelectPoint(), GERBER_FILE_IMAGE::SetDrawOffetAndRotation(), PCAD2KICAD::SetTextSizeFromStrokeFontHeight(), PCAD2KICAD::SetTextSizeFromTrueTypeFontHeight(), SHAPE_ARC::SHAPE_ARC(), PNS::SHOVE::ShoveObstacleLine(), SCH_EDITOR_CONTROL::SimProbe(), SCH_EDITOR_CONTROL::SimTune(), snapAngle(), PS_PLOTTER::StartPlot(), KIFONT::FONT::StringBoundaryLimits(), STROKE_PARAMS::Stroke(), KIGFX::PCB_PAINTER::strokeText(), PCAD2KICAD::StrToInt1Units(), PCAD2KICAD::StrToIntUnits(), KIFONT::OUTLINE_FONT::subscriptSize(), DS_DATA_ITEM_TEXT::SyncDrawItems(), CONNECTIVITY_DATA::TestTrackEndpointDangling(), KIGFX::COLOR4D::ToHexString(), SPICE_VALUE::ToString(), AR_MATRIX::traceArc(), AR_MATRIX::traceCircle(), AR_MATRIX::TraceFilledRectangle(), DIALOG_LIB_SYMBOL_PROPERTIES::TransferDataFromWindow(), PANEL_EESCHEMA_DISPLAY_OPTIONS::TransferDataFromWindow(), PANEL_SYM_EDITING_OPTIONS::TransferDataFromWindow(), DIALOG_MOVE_EXACT::TransferDataFromWindow(), TransformOvalToPolygon(), TransformRoundChamferedRectToPolygon(), TransformTrapezoidToPolygon(), SHAPE_ARC::update_bbox(), DIALOG_PAGES_SETTINGS::UpdateDrawingSheetExample(), PCB_TUNING_PATTERN::UpdateEditPoints(), PCB_TUNING_PATTERN::UpdateFromEditPoints(), PCB_DIM_ALIGNED::updateGeometry(), PCB_DIM_ORTHOGONAL::updateGeometry(), PCB_DIM_RADIAL::updateGeometry(), BITMAP_BASE::updatePPI(), TUNER_SLIDER::updateSlider(), PCB_DIM_RADIAL::updateText(), DIALOG_DRC::updateUI(), TUNING_STATUS_VIEW_ITEM::ViewDraw(), ROUTER_STATUS_VIEW_ITEM::ViewDraw(), PCB_TUNING_PATTERN::ViewDraw(), KIGFX::ORIGIN_VIEWITEM::ViewDraw(), EXCELLON_WRITER::writeCoordinates(), WriteImageStream(), and PCB_SELECTION_TOOL::ZoomFitCrossProbeBBox().

◆ rescale() [1/3]

template<>
int rescale ( int  aNumerator,
int  aValue,
int  aDenominator 
)

Definition at line 66 of file util.cpp.

◆ rescale() [2/3]

template<>
int64_t rescale ( int64_t  aNumerator,
int64_t  aValue,
int64_t  aDenominator 
)

Definition at line 80 of file util.cpp.

References std::abs(), kimathLogDebug(), and sign().

◆ rescale() [3/3]

template<typename T >
T rescale ( aNumerator,
aValue,
aDenominator 
)

◆ sign()