KiCad PCB EDA Suite
util.h File Reference
#include <config.h>
#include <cstdint>
#include <limits>
#include <typeinfo>

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...
 
template<typename T >
const 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)
 

Function Documentation

◆ Clamp()

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

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 52 of file util.h.

53 {
54  if( value < lower )
55  return lower;
56  else if( upper < value )
57  return upper;
58  return value;
59 }

Referenced by LSET::AllCuMask(), DIALOG_PAGES_SETTINGS::GetCustomSizeMilsFromDialog(), SCH_SEXPR_PARSER::parseFill(), SCH_SEXPR_PARSER::parseJunction(), SCH_SEXPR_PARSER::parseStroke(), BRDITEMS_PLOTTER::plotOneDrillMark(), PCB_PLOT_PARAMS::SetSvgPrecision(), and DIALOG_PAGES_SETTINGS::UpdateDrawingSheetExample().

◆ kimathLogDebug()

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

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

Definition at line 37 of file util.cpp.

38 {
39  if( wxLog::IsLevelEnabled( wxLOG_Debug, wxString::FromAscii( wxLOG_COMPONENT ) ) )
40  {
41  va_list argList;
42  va_start( argList, aFormatString );
43 
44  wxVLogWarning( aFormatString, argList );
45 
46  va_end( argList );
47  }
48 }

Referenced by KiROUND().

◆ KiROUND()

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".

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

Definition at line 73 of file util.h.

74 {
75  using max_ret = long long int;
76  fp_type ret = v < 0 ? v - 0.5 : v + 0.5;
77 
78  if( std::numeric_limits<ret_type>::max() < ret ||
79  std::numeric_limits<ret_type>::lowest() > ret )
80  {
81  kimathLogDebug( "Overflow KiROUND converting value %f to %s", double( v ),
82  typeid( ret_type ).name() );
83  return 0;
84  }
85 
86  return ret_type( max_ret( ret ) );
87 }
void kimathLogDebug(const char *aFormatString,...)
Helper to avoid directly including wx/log.h for the templated functions in kimath.
Definition: util.cpp:37
const char * name
Definition: DXF_plotter.cpp:56

References kimathLogDebug(), and name.

Referenced by CADSTAR_PCB_ARCHIVE_LOADER::addAttribute(), ZONE_FILLER::addHatchFillTypeOnZone(), PCAD2KICAD::PCB_POLYGON::AddToBoard(), GRID_HELPER::AlignGrid(), PCB_GRID_HELPER::AlignToArc(), CADSTAR_PCB_ARCHIVE_LOADER::applyDimensionSettings(), CADSTAR_SCH_ARCHIVE_LOADER::applyTextSettings(), CADSTAR_SCH_ARCHIVE_LOADER::applyTransform(), HPGL_PLOTTER::Arc(), PLOTTER::Arc(), PDF_PLOTTER::Arc(), SCH_SHEET::AutoplaceFields(), PCB_GRID_HELPER::BestSnapAnchor(), LEGACY_PLUGIN::biuParse(), build_pad_testpoints(), BuildCornersList_S_Shape(), PAD::BuildEffectivePolygon(), DIRECTION_45::BuildInitialTrace(), ZONE_FILLER::buildThermalSpokes(), bumpToNextGrid(), LIB_SHAPE::CalcArcAngles(), CalcArcCenter(), EDA_SHAPE::calcEdit(), PCAD2KICAD::CalculateTextLengthSize(), KIGFX::WX_VIEW_CONTROLS::CenterOnCursor(), SHAPE_POLY_SET::chamferFilletPolygon(), EE_INSPECTION_TOOL::CheckSymbol(), CircleToEndSegmentDeltaRadius(), Clamp_Text_PenSize(), ClipAndDrawPoly(), EE_SELECTION_TOOL::CollectHits(), SCH_LINE_WIRE_BUS_TOOL::computeBreakPoint(), computeCenter(), ConfigureHPGLPenSizes(), ConvertArcToPolyline(), AM_PRIMITIVE::ConvertShapeToPolygon(), ALTIUM_PARSER::ConvertToKicadUnit(), SHAPE_ARC::ConvertToPolyline(), PCAD2KICAD::CorrectTextPosition(), FOOTPRINT::CoverageRatio(), MICROWAVE_TOOL::createFootprint(), MICROWAVE_TOOL::createMicrowaveInductor(), MICROWAVE_TOOL::createPolygonShape(), PL_EDIT_TOOL::DeleteItemCursor(), SCH_EDIT_TOOL::DeleteItemCursor(), PCB_CONTROL::DeleteItemCursor(), SEG::Distance(), EDIT_TOOL::DragArcTrack(), KIGFX::STROKE_FONT::Draw(), KIGFX::SCH_PAINTER::draw(), KIGFX::PCB_PAINTER::draw(), KIGFX::OPENGL_GAL::DrawArcSegment(), AM_PRIMITIVE::DrawBasicShape(), BITMAP_BASE::DrawBitmap(), CADSTAR_PCB_ARCHIVE_LOADER::drawCadstarText(), KIGFX::OPENGL_GAL::DrawGrid(), KIGFX::CAIRO_GAL_BASE::DrawGrid(), GERBER_PLOTTER::emitDcode(), PCB_EXPR_EVALUATOR::Evaluate(), GERBER_FILE_IMAGE::ExecuteRS274XCommand(), EDIT_POINTS::FindPoint(), HPGL_PLOTTER::FlashPadCircle(), HPGL_PLOTTER::FlashPadOval(), HPGL_PLOTTER::FlashPadRect(), HPGL_PLOTTER::FlashPadRoundRect(), FootprintWriteShape(), BM2CMP_FRAME::FormatOutputSize(), formatStroke(), DSN::SPECCTRA_DB::FromSESSION(), gen_arc(), GENDRILL_WRITER_BASE::genDrillMapFile(), RENDER_3D_LEGACY::generate3dGrid(), WX_HTML_REPORT_BOX::generateHtml(), geom_transf(), GERBER_DRAW_ITEM::GetABPosition(), SCH_LINE::GetAngleFrom(), GetArcToSegmentCount(), LIB_PIN::GetBoundingBox(), CADSTAR_SCH_ARCHIVE_LOADER::getCadstarAngle(), FOOTPRINT::GetCoverageArea(), DIALOG_PAGES_SETTINGS::GetCustomSizeMilsFromDialog(), SCH_JUNCTION::getEffectiveShape(), DS_DATA_ITEM::GetEndPosUi(), GRID_HELPER::GetGrid(), KIGFX::GAL::GetGridPoint(), getGUIFont(), EDA_TEXT::GetInterline(), SCH_TEXT::GetLabelBoxExpansion(), EDA_DRAW_FRAME::GetNearestGridPosition(), EDA_DRAW_FRAME::GetNearestHalfGridPosition(), EE_SELECTION_TOOL::GetNode(), IMAGE_SIZE::GetOutputDPI(), GetPenSizeForBold(), GetPenSizeForNormal(), DS_DATA_ITEM::GetPenSizeUi(), DS_DATA_ITEM_POLYGONS::GetPenSizeUi(), DS_DATA_ITEM_TEXT::GetPenSizeUi(), EDA_SHAPE::GetRadius(), EDA_SHAPE::GetRectCorners(), SCH_LINE::GetReverseAngleFrom(), PAD::GetRoundRectCornerRadius(), BITMAP_BASE::GetSize(), PAD::GetSolderPasteMargin(), DS_DATA_ITEM::GetStartPosUi(), EDA_TEXT::GetTextBox(), CADSTAR_SCH_ARCHIVE_LOADER::getTextHeightFromTextCode(), SCH_TEXT::GetTextOffset(), GERBER_DRAW_ITEM::GetXYPosition(), GraphicTextWidth(), GRArc1(), ZONE::HatchBorder(), ALTIUM_PCB::HelperCreateBoardOutline(), ALTIUM_PCB::HelperParseDimensions6Leader(), HelperShapeLineChainFromAltiumVertices(), EDA_SHAPE::hitTest(), DIALOG_PLOT::init_Dialog(), initializePlotter(), GENERAL_COLLECTOR::Inspect(), CIRCLE::Intersect(), CN_ANCHOR::IsDangling(), PCB_TRACK::IsPointOnEnds(), iu_to_d356(), KiScaledBitmap(), EDA_TEXT::LenSize(), SEG::LineDistance(), EAGLE_PLUGIN::Load(), CADSTAR_SCH_ARCHIVE_LOADER::loadDocumentationSymbols(), SCH_EAGLE_PLUGIN::loadFrame(), CADSTAR_SCH_ARCHIVE_LOADER::loadGraphicStaightSegment(), SCH_EAGLE_PLUGIN::loadLabel(), EAGLE_PLUGIN::loadPlain(), EAGLE_PLUGIN::loadPolygon(), EAGLE_PLUGIN::loadSignals(), CADSTAR_SCH_ARCHIVE_LOADER::loadSymbolFieldAttribute(), PCB_SELECTION_TOOL::Main(), DSN::SPECCTRA_DB::makePADSTACK(), TRANSFORM::MapAngles(), PLOTTER::markerSquare(), Mils2mm(), GERBVIEW_PRINTOUT::milsToIU(), PCBNEW_PRINTOUT::milsToIU(), Mm2mils(), ACTION_TOOLBAR::OnCustomRender(), DIALOG_POSITION_RELATIVE::OnOkClick(), BM2CMP_FRAME::OpenProjectFiles(), VECTOR2< unsigned int >::operator/(), EAGLE_PLUGIN::orientFPText(), EAGLE_PLUGIN::packagePad(), EAGLE_PLUGIN::packagePolygon(), EAGLE_PLUGIN::packageText(), DIALOG_PAD_PROPERTIES::padValuesOK(), PCAD2KICAD::PCB_ARC::Parse(), SCH_SEXPR_PARSER::parseArc(), ALTIUM_PCB::ParseArcs6Data(), PCB_PARSER::parseBoardUnits(), GPCB_FPL_CACHE::parseFOOTPRINT(), parseInt(), SCH_SEXPR_PARSER::parseInternalUnits(), pinEditedCorner(), GERBER_PLOTTER::plotArc(), BRDITEMS_PLOTTER::PlotFootprintGraphicItem(), PS_PLOTTER::PlotImage(), PDF_PLOTTER::PlotImage(), GERBER_PLOTTER::plotRoundRectAsRegion(), PSLIKE_PLOTTER::postscriptOverlinePositions(), SCH_BUS_ENTRY_BASE::Print(), SCH_LINE::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(), VECTOR2< unsigned int >::Resize(), PSLIKE_PLOTTER::returnPostscriptTextWidth(), VECTOR2< unsigned int >::Rotate(), EDA_SHAPE::rotate(), RotatePoint(), rotationFromString(), SCH_SEXPR_PLUGIN::saveJunction(), SCH_SEXPR_PLUGIN::saveSheet(), DSN::scale(), EDA_SHAPE::scale(), scaletoIU(), PLOTTER::segmentAsOval(), SegmentIntersectsSegment(), PL_SELECTION_TOOL::SelectPoint(), DS_DATA_ITEM_TEXT::SetConstrainedTextSize(), PCAD2KICAD::SetTextSizeFromStrokeFontHeight(), PCAD2KICAD::SetTextSizeFromTrueTypeFontHeight(), SHAPE_ARC::SHAPE_ARC(), snapAngle(), PS_PLOTTER::StartPlot(), PCAD2KICAD::StrToInt1Units(), PCAD2KICAD::StrToIntUnits(), DS_DATA_ITEM_TEXT::SyncDrawItems(), CONNECTIVITY_DATA::TestTrackEndpointDangling(), AR_MATRIX::traceArc(), AR_MATRIX::traceCircle(), AR_MATRIX::TraceFilledRectangle(), PANEL_EESCHEMA_DISPLAY_OPTIONS::TransferDataFromWindow(), DIALOG_LIB_SYMBOL_PROPERTIES::TransferDataFromWindow(), DIALOG_MOVE_EXACT::TransferDataFromWindow(), DIALOG_PAD_PRIMITIVES_TRANSFORM::Transform(), TransformOvalToPolygon(), TransformRoundChamferedRectToPolygon(), TransformTrapezoidToPolygon(), SHAPE_ARC::update_bbox(), DIALOG_DIMENSION_PROPERTIES::updateDimensionFromDialog(), DIALOG_PAGES_SETTINGS::UpdateDrawingSheetExample(), PCB_DIM_ALIGNED::updateGeometry(), PCB_DIM_ORTHOGONAL::updateGeometry(), DIALOG_DRC::updateUI(), KIGFX::ORIGIN_VIEWITEM::ViewDraw(), and EXCELLON_WRITER::writeCoordinates().

◆ rescale() [1/3]

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

Scale a number (value) by rational (numerator/denominator).

Numerator must be <= denominator.

Definition at line 98 of file util.h.

99 {
100  return aNumerator * aValue / aDenominator;
101 }

Referenced by commonParallelProjection(), PNS::commonParallelProjection(), PAD::GetBestAnchorPosition(), SEG::intersects(), SEG::LineProject(), SEG::NearestPoint(), SHAPE_LINE_CHAIN_BASE::PointInside(), processEdge(), SEG::ReflectPoint(), VECTOR2< unsigned int >::Resize(), and POLY_GRID_PARTITION::scanCell().

◆ rescale() [2/3]

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

Definition at line 52 of file util.cpp.

53 {
54  int64_t numerator = (int64_t) aNumerator * (int64_t) aValue;
55 
56  // round to nearest
57  if( ( numerator < 0 ) ^ ( aDenominator < 0 ) )
58  return ( numerator - aDenominator / 2 ) / aDenominator;
59  else
60  return ( numerator + aDenominator / 2 ) / aDenominator;
61 
62 }

◆ rescale() [3/3]

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

Definition at line 66 of file util.cpp.

67 {
68 #ifdef __SIZEOF_INT128__
69  __int128_t numerator = (__int128_t) aNumerator * (__int128_t) aValue;
70 
71  if( ( numerator < 0 ) ^ ( aDenominator < 0 ) )
72  return ( numerator - aDenominator / 2 ) / aDenominator;
73  else
74  return ( numerator + aDenominator / 2 ) / aDenominator;
75 #else
76  int64_t r = 0;
77  int64_t sign = ( ( aNumerator < 0 ) ? -1 : 1 ) * ( aDenominator < 0 ? -1 : 1 ) *
78  ( aValue < 0 ? -1 : 1 );
79 
80  int64_t a = std::abs( aNumerator );
81  int64_t b = std::abs( aValue );
82  int64_t c = std::abs( aDenominator );
83 
84  r = c / 2;
85 
86  if( b <= INT_MAX && c <= INT_MAX )
87  {
88  if( a <= INT_MAX )
89  return sign * ( ( a * b + r ) / c );
90  else
91  return sign * ( a / c * b + ( a % c * b + r ) / c);
92  }
93  else
94  {
95  uint64_t a0 = a & 0xFFFFFFFF;
96  uint64_t a1 = a >> 32;
97  uint64_t b0 = b & 0xFFFFFFFF;
98  uint64_t b1 = b >> 32;
99  uint64_t t1 = a0 * b1 + a1 * b0;
100  uint64_t t1a = t1 << 32;
101  int i;
102 
103  a0 = a0 * b0 + t1a;
104  a1 = a1 * b1 + ( t1 >> 32 ) + ( a0 < t1a );
105  a0 += r;
106  a1 += a0 < (uint64_t)r;
107 
108  for( i = 63; i >= 0; i-- )
109  {
110  a1 += a1 + ( ( a0 >> i ) & 1 );
111  t1 += t1;
112 
113  if( (uint64_t) c <= a1 )
114  {
115  a1 -= c;
116  t1++;
117  }
118  }
119 
120  return t1 * sign;
121  }
122 #endif
123 }
int sign(T val)
Definition: util.h:104
E_SERIE r
Definition: eserie.cpp:41

References r, and sign().

◆ sign()