diff --git a/C3d/Include/action_curve3d.h b/C3d/Include/action_curve3d.h index 918b3af..e772494 100644 --- a/C3d/Include/action_curve3d.h +++ b/C3d/Include/action_curve3d.h @@ -17,30 +17,32 @@ #define __ACTION_CURVE3D_H +#include #include #include #include #include #include -#include #include class MATH_CLASS MbCurve; class MATH_CLASS MbCurve3D; -class MATH_CLASS MbNurbs3D; class MATH_CLASS MbContour3D; +class MATH_CLASS MbWireFrame; class MATH_CLASS MbFace; class MATH_CLASS MbSurface; class MATH_CLASS MbItem; class MATH_CLASS MbName; class MATH_CLASS MbSweptData; -class MATH_CLASS MbSNameMaker; class MATH_CLASS MbContourChamferParams; +struct MATH_CLASS MbNurbsParameters; class MATH_CLASS MbNurbsCopyCurveResult; class MATH_CLASS MbCurvesWrappingParams; +class MATH_CLASS MbCurvesWrappingResults; class MATH_CLASS MbCurveFitParameters3D; class MATH_CLASS MbCurveFitResults3D; +class MATH_CLASS MbCurveExtensionParameters3D; struct MATH_CLASS EvolutionValues; @@ -1538,7 +1540,7 @@ MATH_FUNC ( MbCurve3D * ) SetProportionalParametrization( MbCurve3D * curve, // --- MATH_FUNC( MbResultType ) ExtendCurve( const MbCurve3D & sourceCurve, const MbCurveExtensionParameters3D & parameters, - c3d::WireFrameSPtr & resFrame ); + SPtr & resFrame ); //------------------------------------------------------------------------------ @@ -1575,39 +1577,39 @@ MATH_FUNC (MbResultType) CreateContourChamfer( const MbContourChamferParams & pa //------------------------------------------------------------------------------- -/** \brief \ru Построить развертку кривых на плоскость. - \en Construct unwrapped curves. \~ - \details \ru Построение развертки кривых на плоскость. См. также #CurvesUnwrapping.\n - \en Construct unwrapped curves on a plane. Also check out #CurvesUnwrapping.\n \~ - \param[in] params - \ru Параметры разворачивания. - \en Unwrapping parameters. \~ - \param[in] resFrame - \ru Развёрнутые 3д-кривые на присланной плоскости. - \en Unwrapped 3d-curves on the input plane. \~ +/** \brief \ru Построить развертку кривых и точек на плоскость. + \en Construct unwrapped curves and points. \~ + \details \ru Построение развертки кривых и точек на плоскость. См. также #CurvesUnwrapping.\n + \en Construct unwrapped curves and points on a plane. Also check out #CurvesUnwrapping.\n \~ + \param[in] params - \ru Параметры разворачивания. + \en Unwrapping parameters. \~ + \param[out] result - \ru Результат разворачивания. + \en Wrapping result. \~ \return \ru Возвращает код результата операции. \en Returns operation result code. \~ \ingroup Curve3D_Modeling */ // --- -MATH_FUNC (MbResultType) UnwrapCurve( const MbCurvesWrappingParams & parameters, - c3d::WireFrameSPtr & resFrame ); +MATH_FUNC (MbResultType) UnwrapCurve( const MbCurvesWrappingParams & parameters, + MbCurvesWrappingResults & result ); //------------------------------------------------------------------------------- -/** \brief \ru Выполнить операцию сворачивания кривых на поверхность. - \en Perform the operation of wrapping curves on a surface. \~ +/** \brief \ru Выполнить операцию сворачивания кривых и точек на поверхность. + \en Perform the operation of wrapping curves and points on a surface. \~ \details \ru Выполнить операцию сворачивания кривых на поверхность. См. также #CurvesWrapping.\n \en Perform the operation of wrapping curves on a surface. Also check out #CurvesWrapping.\n \~ - \param[in] params - \ru Параметры сворачивания. - \en Wrapping parameters. \~ - \param[out] resFrame - \ru Каркас из свёрнутых 3д-кривых на присланной поверхности. - \en Wireframe of wrapped 3d-curves on the input surface. \~ + \param[in] params - \ru Параметры сворачивания. + \en Wrapping parameters. \~ + \param[out] result - \ru Результат сворачивания. + \en Wrapping result. \~ \return \ru Возвращает код результата операции. \en Returns operation result code. \~ \ingroup Curve3D_Modeling */ // --- -MATH_FUNC( MbResultType ) WrapCurve( const MbCurvesWrappingParams & parameters, - c3d::WireFrameSPtr & resFrame ); +MATH_FUNC( MbResultType ) WrapCurve( const MbCurvesWrappingParams & parameters, + MbCurvesWrappingResults & result ); //------------------------------------------------------------------------------ diff --git a/C3d/Include/action_direct.h b/C3d/Include/action_direct.h index 6f77070..c2c0375 100644 --- a/C3d/Include/action_direct.h +++ b/C3d/Include/action_direct.h @@ -164,8 +164,8 @@ MATH_FUNC (MbResultType) CollectFacesForModification( MbFaceShell * shell, Удаления всех скруглений тела, меньших определённого радиуса (dmm_PurifyFilletsBelowRadius).\n 8. Слияние вершин ребёр и удаление рёбер (dmm_DeleteEdges). \n 9. Замена гладко стыкующихся граней одной гранью (dmm_UniteFaces). \n - 10. Поворот выбранных граней (dmm_RotateFaces). Угол поворота определяется параметром angle, - ось поворота определяется осью axis.\n + 10. Поворот выбранных граней с адаптацией прилегающих скруглений (dmm_RotateFaces) или без (dmm_RotateFacesNoFilletAdaptation). + Угол поворота определяется параметром angle, ось поворота определяется осью axis.\n 11. Замена выбранных граней тела (dmm_ReplaceFaces).\n Одновременно с построением оболочки функция создаёт её строитель.\n \en The method performs one of the following actions depending on the parameter #MbModifiedSolidParams: \n @@ -188,8 +188,8 @@ MATH_FUNC (MbResultType) CollectFacesForModification( MbFaceShell * shell, Remove of all fillets below specified radius from a solid (dmm_PurifyFilletsBelowRadius).\n 8. Edge vertices merging and edges removal (dmm_DeleteEdges). \n 9. Replacement of the smoothly joined faces with a single face (dmm_UniteFaces). \n - 10. Rotation of the chosen faces (dmm_RotateFaces). The parameters are the rotation angle - and the rotation axis.\n + 10. Rotation of the chosen faces with the adjacent fillets adaptation (dmm_RotateFaces) + or without (dmm_RotateFacesNoFilletAdaptation ). The parameters are the rotation angle and the rotation axis.\n 11. Replacement of the specified faces of a solid (dmm_ReplaceFaces).\n The function simultaneously creates the shell and its constructor.\n \~ \param[in] solid - \ru Исходное тело. diff --git a/C3d/Include/action_general.h b/C3d/Include/action_general.h index 8360109..cda45b3 100644 --- a/C3d/Include/action_general.h +++ b/C3d/Include/action_general.h @@ -319,7 +319,11 @@ MATH_FUNC (bool) IsSolidsIntersection( const MbSolid & solid1, const MbSolid & s \param[in] checkTouchPoints - \ru Искать точки касания. \en Find touch points. \~ \param[out] intData - \ru Информация о пересечении двух тел. - \en Information about two solids intersection. \~ + Если одно из пересекаемых тел не замкнуто, то + тела, полученные в результате, могут быть не валидны для операций. + \en Information about two solids intersection. + If one of the intersecting bodies is not closed, then + the resulting bodies may not be valid for operations. \~ \return \ru Возвращает true, если найдено хотя бы одно пересечение. \en Returns 'true' if at least one intersection is detected. \~ \ingroup Algorithms_3D diff --git a/C3d/Include/action_phantom.h b/C3d/Include/action_phantom.h index bc1f22b..ff6ab26 100644 --- a/C3d/Include/action_phantom.h +++ b/C3d/Include/action_phantom.h @@ -375,6 +375,8 @@ MATH_FUNC( MbResultType ) SmoothPositionData( const MbSmoothPositionDataParams & \en Create a function by one of three coordinates of curve. \~ \details \ru Для указанной координаты кривой построить склярную функцию её изменения, зависящую от параметра кривой. \n \en A function creation for behavior of selected curve coordinate with curve parameter. \n + \deprecated \ru Метод устарел. Взамен использовать #CreateFunction с набором параметров #MbFunctionParameters. + \en The method is deprecated. Use instead #CreateFunction with the parameters #MbFunctionParameters. \~ \param[in] curve - \ru Кривая. \en The curve. \~ \param[in] place - \ru Локальная система координат, в которой используется кривая. @@ -386,11 +388,30 @@ MATH_FUNC( MbResultType ) SmoothPositionData( const MbSmoothPositionDataParams & \ingroup Algorithms_3D */ // --- +//DEPRECATE_DECLARE_REPLACE(CreateFunction with MbFunctionParameters) MATH_FUNC (MbFunction *) CreateFunction( const MbCurve3D & curve, const MbPlacement3D & place, size_t coordinate ); +//------------------------------------------------------------------------------ +/** \brief \ru Построение скалярной функции изменения Y-координаты кривой. + \en Create a scalar function by Y-coordinate of curve. \~ + \details \ru Для Y-координаты кривой построить скалярную функцию её изменения, зависящую от X-координаты кривой. \n + \en A function creation for behavior of Y-curve coordinate with X-curve parameter. \n + \param[in] curve - \ru Кривая. + \en The curve. \~ + \param[in] params - \ru Параметры скалярной функции. + \en The parameters of the scalar function. \~ + \return \ru Возвращает построенную функцию. + \en Returns the created function. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (c3d::FunctionSPtr) CreateFunction( const MbCurve & curve, + const MbFunctionParameters & params ); + + //------------------------------------------------------------------------------ /** \brief \ru Вычисление данных фантома для торцев поверхности переменного сечения. \en Calculation of the phantom data for the ends of the mutable section surface. \~ diff --git a/C3d/Include/action_solid.h b/C3d/Include/action_solid.h index a9dcb4c..c55796d 100644 --- a/C3d/Include/action_solid.h +++ b/C3d/Include/action_solid.h @@ -880,6 +880,8 @@ MATH_FUNC (MbResultType) RevolutionResult( MbSolid & solid, \en The additional turn for generating line. \~ \param[in] version - \ru Версия операции. \en The version of the operation. \~ + \param[out] matrix - \ru Указатель на матрицу преобразование сечения к ближайшему концу направляющей кривой. + \en The pointer to matrix, which transform section to nearest end of spine curve. \~ \return \ru Возвращает код результата операции. \en Returns operation result code. \~ \warning \ru Вспомогательная функция операций EvolutionSolid и EvolutionResult. @@ -893,7 +895,8 @@ MATH_FUNC (MbResultType) EvolutionNormalize( const MbSurface & surface, const EvolutionValues & parameters, MbAxis3D & axis, double & angle, - VERSION version ); + VERSION version, + MbMatrix3D * matrix = nullptr ); //------------------------------------------------------------------------------ diff --git a/C3d/Include/action_surface_curve.h b/C3d/Include/action_surface_curve.h index 4586b7e..1266a09 100644 --- a/C3d/Include/action_surface_curve.h +++ b/C3d/Include/action_surface_curve.h @@ -1220,26 +1220,30 @@ MATH_FUNC (MbResultType) CreateContourFillets( const MbContour3D & contour, \return \ru Возвращает код результата операции. \en Returns operation result code. \~ \ingroup Curve3D_Modeling + \deprecated \ru Метод устарел. \en The method is deprecated. \~ */ // --- +DEPRECATE_DECLARE_REPLACE( WrapCurve with MbCurvesWrappingResults ) MATH_FUNC (MbResultType) CurvesWrapping( const MbCurvesWrappingParams & parameters, c3d::PlaneCurvesSPtrVector & surfaceCurves ); //------------------------------------------------------------------------------- -/** \brief \ru Построить кривые, оборачивающие поверхность. - \en Construct curves that wrap the surface. \~ - \details \ru Построить кривые, оборачивающие поверхность. \n - \en Construction of curves that wrap the surface. \n \~ - \param[in] parameters - \ru Параметры #MbCurvesWrappingParams для переноса копий двумерных кривых на другой носитель. - \en Parameters #MbCurvesWrappingParams for transferring copies of two-dimensional curves on another medium. \~ - \param[out] resultCurves - \ru Построенные 3д-кривые на присланной поверхности. - \en Constructed 3d-curves based on the input surface. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling +/** \brief \ru Построить кривые, оборачивающие поверхность. + \en Construct curves that wrap the surface. \~ + \details \ru Построить кривые, оборачивающие поверхность. \n + \en Construction of curves that wrap the surface. \n \~ + \param[in] parameters - \ru Параметры #MbCurvesWrappingParams для переноса копий двумерных кривых на другой носитель. + \en Parameters #MbCurvesWrappingParams for transferring copies of two-dimensional curves on another medium. \~ + \param[out] resultCurves - \ru Построенные 3д-кривые на присланной поверхности. + \en Constructed 3d-curves based on the input surface. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling + \deprecated \ru Метод устарел. \en The method is deprecated. \~ */ // --- +DEPRECATE_DECLARE_REPLACE( WrapCurve with MbCurvesWrappingResults ) MATH_FUNC (MbResultType) CurvesWrapping( const MbCurvesWrappingParams & parameters, c3d::SpaceCurvesSPtrVector & resultCurves ); @@ -1255,9 +1259,11 @@ MATH_FUNC (MbResultType) CurvesWrapping( const MbCurvesWrappingParams & para \en Unwrapped 2d-curves. \~ \return \ru Возвращает код результата операции. \en Returns operation result code. \~ -\ingroup Curve3D_Modeling + \ingroup Curve3D_Modeling + \deprecated \ru Метод устарел. \en The method is deprecated. \~ */ // --- +DEPRECATE_DECLARE_REPLACE( UnwrapCurve with MbCurvesWrappingResults ) MATH_FUNC (MbResultType) CurvesUnwrapping( const MbCurvesWrappingParams & params, c3d::PlaneCurvesSPtrVector & surfaceCurves ); @@ -1273,9 +1279,11 @@ MATH_FUNC (MbResultType) CurvesUnwrapping( const MbCurvesWrappingParams & pa \en Unwrapped 3d-curves on the input plane. \~ \return \ru Возвращает код результата операции. \en Returns operation result code. \~ -\ingroup Curve3D_Modeling + \ingroup Curve3D_Modeling + \deprecated \ru Метод устарел. \en The method is deprecated. \~ */ // --- +DEPRECATE_DECLARE_REPLACE( UnwrapCurve with MbCurvesWrappingResults ) MATH_FUNC (MbResultType) CurvesUnwrapping( const MbCurvesWrappingParams & parameters, c3d::SpaceCurvesSPtrVector & resultCurves ); diff --git a/C3d/Include/action_wireframe.h b/C3d/Include/action_wireframe.h index 020ccbe..dbf1959 100644 --- a/C3d/Include/action_wireframe.h +++ b/C3d/Include/action_wireframe.h @@ -15,6 +15,8 @@ class MATH_CLASS MbWireFrameFilletsParams; class MATH_CLASS MbNurbsWireFrameParams; class MATH_CLASS MbTrimmedWireFrameParams; +class MATH_CLASS MbWireFrameProjParams; +class MATH_CLASS MbWireFrameProjResult; //------------------------------------------------------------------------------ @@ -102,4 +104,28 @@ MATH_FUNC( MbResultType ) CreateTrimmedWireFrame( c3d::WireFrameSPtr & c3d::WireFrameSPtr & result ); +//------------------------------------------------------------------------------ +/** \brief \ru Найти проекцию точки на проволочный каркас. + \en Find the point projection to the wire frame. \~ + \details \ru Найти ближайшую проекцию точки на проволочный каркас в диапазоне изменения параметра или на его продолжении. + Аналог MbContour3D::NearPointProjection(). + Проволочный каркас должен быть нормализован. + \en Find the nearest projection of a point to the wire frame within the parameter range or its extension. + Analogue of MbContour3D::NearPointProjection(). + The wire frame must be normalized. \~ + \param[in] wireFrame - \ru Проволочный каркас для поиска проекции. + \en Wire frame for searching projection. \~ + \param[in] params - \ru Параметры операции. + \en Operation parameters. \~ + \param[in] result - \ru Результаты операции. + \en Results of the operation. \~ + \return \ru Код результата операции. + \en Operation result code. \~ + */ +// --- +MATH_FUNC( MbResultType ) NearPointProjection( const MbWireFrame & wireFrame, + const MbWireFrameProjParams & params, + MbWireFrameProjResult & result ); + + #endif // __ACTION_WIREFRAME_H diff --git a/C3d/Include/attr_color.h b/C3d/Include/attr_color.h index c8c093f..9751cb6 100644 --- a/C3d/Include/attr_color.h +++ b/C3d/Include/attr_color.h @@ -38,6 +38,9 @@ public: /// \ru Конструктор по значениям компонентов. \en Constructor by components values. MbRGBA( uint8 red, uint8 green, uint8 blue, uint8 alpha = SYS_MAX_UINT8 ); + /// \ru Конструктор по uint32. \en Constructor by uint32. + MbRGBA( uint32 ); + /// \ru Конструктор по значениям компонентов. \en Constructor by components values. MbRGBA( float red, float green, float blue, float alpha = 1.0 ); @@ -286,6 +289,9 @@ public : /// \ru Деструктор. \en Destructor. virtual ~MbVisual(); + /// \ru Создать по составляющей цвета. \en Create an object by a color component. + static SPtr Create( uint32 c ); + // \ru Общие функции объекта \en Common functions of object. MbeAttributeType AttributeType() const override; // \ru Дать подтип атрибута. \en Get subtype of an attribute. @@ -343,6 +349,9 @@ public : void SetOpacityInt ( uint8 v ) { _opacity = v; } // \ru Установить коэффициент непрозрачности. \en Set an opacity coefficient. void SetChromInt ( uint8 v ) { _chrom = v; } // \ru Установить коэффициент зеркального отражения объектов. \en Set a coefficient of specular reflection for objects. + uint32 GetColor() const { return _diffuse.Get(); } // \ru Выдать составляющую цвета. \en Get a color component. + void SetColor( uint32 c ) { _diffuse.Init( c ); } // \ru Установить составляющую цвета. \en Set a color component. + void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта. \en Get properties of the object. size_t SetProperties( const MbProperties & ) override; // \ru Установить свойства объекта. \en Set properties of object. MbePrompt GetPropertyName() override; // \ru Выдать заголовок свойства объекта. \en Get a name of object property. @@ -439,6 +448,25 @@ MATH_FUNC( SPtr ) ColorToVisual( const MbColor & cAttr ); MATH_FUNC( SPtr ) ColorToVisual( const MbColor & cAttr, const MbVisual & vAttr ); +//------------------------------------------------------------------------------ +/** \brief \ru Преобразовать атрибуты цвета в атрибут MbVisual. + \en Convert color attributes into MbVisual attribute. \~ + \details \ru Создать новый атрибут MbVisual на базе заданного атрибута MbVisual, + в котором компонент diffuse содержит заданный MbColor. \n + \en Create a MbVisual attribute on base of the MbVisual attribute + where the diffuse component contains the value of the MbColor attribute. \n \~ + \param[in] cAttr - \ru Указатель на атрибут MbColor. + \en MbColor attribute pointer. \~ + \param[in] vAttr - \ru Указатель на атрибут MbVisual. + \en MbVisual attribute pointer. \~ + \result \ru Возвращает указатель на созданный атрибут MbVisual. + \en Returns a pointer to the created MbVisual attribute. \~ + \ingroup Model_Attributes +*/ +// --- +MATH_FUNC( SPtr ) ColorToVisual( const SPtr & cAttr, const SPtr & vAttr ); + + //------------------------------------------------------------------------------ /** \brief \ru Преобразовать цвет по трём компонентам в uint32. \en Convert a color by 3 components in uint32. \~ diff --git a/C3d/Include/attribute_item.h b/C3d/Include/attribute_item.h index d85d1e4..174ac0f 100644 --- a/C3d/Include/attribute_item.h +++ b/C3d/Include/attribute_item.h @@ -567,13 +567,15 @@ namespace c3d // namespace C3D /// \ru Подсказка для идентификатора элемента при обмене данными. \en Prompt for the item identifier in model exchange operations. constexpr TCHAR c3dStr_ItemIdentifierExchange[] = _T( "c3d_ItemIdentifierExchange" ); /// \ru Подсказка для URL текстуры при обмене данными. \en Prompt for the URL of texture in model exchange operations. - constexpr TCHAR c3dStr_TextureUrl[] = _T("C3D_Texture_URL"); - - /// \ru Подсказка для атрибута хот-точки в уклоне. \en Prompt for attribute of hot point in draft operations. - constexpr TCHAR c3d_DraftOperationHotPoint[] = _T("c3d_DraftOperationHotPoint"); + constexpr TCHAR c3dStr_TextureUrl[] = _T( "C3D_Texture_URL" ); + /// \ru Подсказка для идентификатора компонента. \en Prompt for the item identifier. + constexpr TCHAR c3dStr_UniqueCompId[] = _T( "c3d_UniqueCompID" ); /// \ru Подсказка для типа замкнутости оболочки в исходных данных. \en Prompt for shell closure type in source data. constexpr TCHAR c3d_ShellOpenClosedOriginal[] = _T( "c3d_ShellOpenClosedOriginal" ); + + /// \ru Подсказка для атрибута хот-точки в уклоне. \en Prompt for attribute of hot point in draft operations. + constexpr TCHAR c3d_DraftOperationHotPoint[] = _T( "c3d_DraftOperationHotPoint" ); /// \ru Подсказка для атрибута простой хот-точки. \en Prompt for attribute of simple hot point. constexpr TCHAR c3d_OperationSingleHotPoint[] = _T( "c3d_OperationSingleHotPoint" ); /// \ru Подсказка для атрибута композитной хот-точки. \en Prompt for attribute of composite hot point. diff --git a/C3d/Include/cdet_utility.h b/C3d/Include/cdet_utility.h index 2464abe..ba3973a 100644 --- a/C3d/Include/cdet_utility.h +++ b/C3d/Include/cdet_utility.h @@ -67,7 +67,10 @@ public: \en Add a poligonal object with given placement to the collision detection set. \~ \return \ru Дескриптор объекта для контроля столкновений. \en Descriptor of object for collision detection. \~ */ - cdet_item AddMesh( const MbMesh & mesh, const MbPlacement3D & place, cdet_app_item appItem = CDET_APP_NULL ); + cdet_item AddMesh( const MbMesh & mesh + , const MbPlacement3D & place + , cdet_app_item appItem = CDET_APP_NULL + , double gap = 0. ); /** \brief \ru Добавить новый компонент контроля соударений и параметров близости. \en Add a new component to track collisions and proximity parameters. \~ @@ -132,7 +135,7 @@ public: // the functions below can be deprecated in future version. */ cdet_item AddSolid( const MbLumpAndFaces & ); /// \ru Добавить тело с заданным положением. \en Add a solid with a given placement. - cdet_item AddSolid( const MbSolid &, const MbPlacement3D &, cdet_app_item = CDET_APP_NULL ); + cdet_item AddSolid( const MbSolid &, const MbPlacement3D &, cdet_app_item = CDET_APP_NULL, double gap = 0. ); /// \ru Удалить твердотельную модель или луч из детектора столкновений. \en Remove a solid model or ray from a collision detector. void RemoveSolid( cdet_item ); /// \ru Выдать количество добавленных твердотельных моделей или лучей. \en Get number of added solid models or rays. diff --git a/C3d/Include/conv_annotation_item.h b/C3d/Include/conv_annotation_item.h index d902710..7381ba0 100644 --- a/C3d/Include/conv_annotation_item.h +++ b/C3d/Include/conv_annotation_item.h @@ -373,11 +373,11 @@ public: double GetSizeX() const; ///< \ru Получить размер по x. \en Get size by x. double GetSizeY() const; ///< \ru Получить размер по y. \en Get size by y. void GetSize( double& x, double& y ) const; ///< \ru Получить размеры. \en Get sizes. - - OBVIOUS_PRIVATE_COPY( MaSpecificSymbol ) - + virtual MaeTextType IsA() const; virtual SPtr Duplicate() const; + + OBVIOUS_PRIVATE_COPY( MaSpecificSymbol ) }; @@ -668,7 +668,7 @@ public: /// \ru Задать кривую, вдоль которой проводится измерение. \en Set the curve the measurement is performed along. void SetPath( MbCurve3D* inPath ); /// \ru Получить кривую, вдоль которой проводится измерение. \en Get the curve the measurement is performed along. - MbCurve3D* GetPath(); + MbCurve3D* GetPath() const; /// \ru Создать дубликат и трансформировать его согласно матрице. \en Create a replica then transform it. virtual SPtr ShallowDuplicateTransform( const MbMatrix3D &, MbRegDuplicate* partDuplicateRegistry = nullptr ); diff --git a/C3d/Include/cr_unwrap_curve.h b/C3d/Include/cr_unwrap_curve.h index de6f2ca..be92cc6 100644 --- a/C3d/Include/cr_unwrap_curve.h +++ b/C3d/Include/cr_unwrap_curve.h @@ -87,8 +87,10 @@ IMPL_PERSISTENT_OPS( MbUnwrapCurveCreator ) \result \ru Возвращает строитель. \en Returns the creator. \~ \ingroup Curve3D_Modeling + \deprecated \ru Метод устарел. \en The method is deprecated. \~ */ // --- +DEPRECATE_DECLARE_REPLACE( UnWrapCurve with MbCurvesWrappingResults ) MATH_FUNC( c3d::CreatorSPtr ) CreateUnwrappedCurve( const MbCurvesWrappingParams & parameters, MbResultType & res, c3d::WireFrameSPtr & resWire ); diff --git a/C3d/Include/cr_unwrap_point.h b/C3d/Include/cr_unwrap_point.h new file mode 100644 index 0000000..a45c9a5 --- /dev/null +++ b/C3d/Include/cr_unwrap_point.h @@ -0,0 +1,64 @@ +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Строитель развернутой точки. + \en Unwrapped point creator. +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_UNWRAP_POINT_H +#define __CR_UNWRAP_POINT_H + +#include +#include + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель развернутой точки. + \en Unwrapped point creator. \~ + \details \ru Строитель развернутой точки. + \en Unwrapped point creator. \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbUnWrapPointCreator : public MbCreator { +private: + MbCurvesWrappingParams _params; ///< \ru Параметры разворачивания. \en Parameters of the unwrapping. + +protected: + /// \ru Конструктор копирования. \en Copy-constructor. + MbUnWrapPointCreator( const MbUnWrapPointCreator & other, MbRegDuplicate * iReg ); + +public: + /// \ru Конструктор по параметрам. \en Constructor by parameters. + MbUnWrapPointCreator( const MbCurvesWrappingParams & params ); + +public: + virtual ~MbUnWrapPointCreator() {}; + + // \ru Общие функции строителя. \en The common functions of the creator. + MbeCreatorType IsA() const override; // \ru Тип элемента \en A type of element + MbCreator & Duplicate( MbRegDuplicate * iReg = nullptr ) const override; // \ru Сделать копию \en Create a copy + + bool IsSame ( const MbCreator &, double accuracy ) const override; // \ru Являются ли объекты равными? \en Determine whether an object is equal? + bool IsSimilar( const MbCreator & ) const override; // \ru Являются ли объекты подобными \en Whether the objects are similar + bool SetEqual ( const MbCreator & ) override; // \ru Сделать равным \en Make equal + + void Transform( const MbMatrix3D &, MbRegTransform * = nullptr ) override; // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + void Move ( const MbVector3D &, MbRegTransform * = nullptr ) override; // \ru Сдвиг \en Translation + void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = nullptr ) override; // \ru Повернуть вокруг оси \en Rotate about an axis + + MbePrompt GetPropertyName() override; // \ru Дать имя свойства объекта \en Get the object property name + void GetProperties ( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of the object + void SetProperties ( const MbProperties & ) override; // \ru Записать свойства объекта \en Set properties of the object + + // \ru Построить каркас о журналу построения \en Create a wireframe from the history tree. + bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * items = nullptr ) override; + +private: + MbUnWrapPointCreator(); // \ru Не реализовано \en Not implemented + +OBVIOUS_PRIVATE_COPY( MbUnWrapPointCreator ) +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbUnWrapPointCreator ) +}; // MbUnWrapPointCreator + +#endif // __CR_UNWRAP_POINT_H diff --git a/C3d/Include/cr_wireframe_creator.h b/C3d/Include/cr_wireframe_creator.h new file mode 100644 index 0000000..be9ec32 --- /dev/null +++ b/C3d/Include/cr_wireframe_creator.h @@ -0,0 +1,82 @@ +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Построение проволочного каркаса без истории. + \en Construction of wireframe without history. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_WIREFRAME_CREATOR_H +#define __CR_WIREFRAME_CREATOR_H + + +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель проволочного каркаса без истории. + \en Constructor of a wireframe without history. \~ + \details \ru Строитель проволочного каркаса без истории. \n + \en Constructor of a wireframe without history. \n \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbSimpleWireFrameCreator : public MbCreator { +public: + c3d::WireEdgesSPtrVector _edges; ///< \ru Множество ребер. \en A set of edges. + +public: + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор по данным проволочного каркаса. + \en Constructor by wireframe data. \~ + \param[in] edges - \ru Множество указателей на ребра. + \en A set of pointers to edges. + \param[in] names - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[in] same - \ru Признак использования оригиналов данных. + \en Flag of using the original data. \~ + */ + MbSimpleWireFrameCreator ( c3d::WireEdgesSPtrVector & edges, + const MbSNameMaker & names, + bool same ); + +private: + MbSimpleWireFrameCreator ( const MbSimpleWireFrameCreator &, + MbRegDuplicate * iReg ); // \ru Конструктор копирования с регистратором \en Copy-constructor with the registrator +public: + /// \ru Деструктор. \en Destructor. + virtual ~MbSimpleWireFrameCreator(); + /** \ru \name Общие функции строителя проволочного каркаса. + \en \name Common functions of the wireframe creator. + \{ */ + MbeCreatorType IsA() const override; // \ru Тип элемента \en Type of element + MbCreator & Duplicate( MbRegDuplicate * = nullptr ) const override; // \ru Сделать копию \en Create a copy + void Transform( const MbMatrix3D &, + MbRegTransform * = nullptr ) override; // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + void Move( const MbVector3D &, + MbRegTransform * = nullptr ) override; // \ru Сдвиг \en Translation + void Rotate( const MbAxis3D &, + double angle, + MbRegTransform * = nullptr ) override; // \ru Повернуть вокруг оси \en Rotate about an axis + MbePrompt GetPropertyName() override; // \ru Выдать заголовок свойства объекта \en Get a name of object property + void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of the object + void SetProperties( const MbProperties & ) override; // \ru Записать свойства объекта \en Set properties of the object + bool IsSame( const MbCreator &, + double accuracy ) const override; // \ru Являются ли объекты равными? \en Determine whether an object is equal? + bool IsSimilar( const MbCreator & ) const override; // \ru Являются ли объекты подобными \en Whether the objects are similar + bool SetEqual( const MbCreator & ) override; // \ru Сделать равным \en Make equal + + /// \ru Построить проволочный каркас по исходным данным. \en Create a wire-frame from the source data. + bool CreateWireFrame( MbWireFrame *&, + MbeCopyMode, + RPArray * ) override; + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSimpleWireFrameCreator ) + OBVIOUS_PRIVATE_COPY( MbSimpleWireFrameCreator ) +};// MbSimpleWireFrameCreator + +IMPL_PERSISTENT_OPS( MbSimpleWireFrameCreator ) + +#endif // __CR_WIREFRAME_CREATOR_H \ No newline at end of file diff --git a/C3d/Include/cr_wrap_curve.h b/C3d/Include/cr_wrap_curve.h index ab96f36..b47582f 100644 --- a/C3d/Include/cr_wrap_curve.h +++ b/C3d/Include/cr_wrap_curve.h @@ -85,8 +85,10 @@ DECLARE_PERSISTENT_CLASS_NEW_DEL( MbWrapCurveCreator ) \result \ru Возвращает строитель. \en Returns the creator. \~ \ingroup Curve3D_Modeling + \deprecated \ru Метод устарел. \en The method is deprecated. \~ */ // --- +DEPRECATE_DECLARE_REPLACE( WrapCurve with MbCurvesWrappingResults ) MATH_FUNC( c3d::CreatorSPtr ) CreateWrappedCurve( const MbCurvesWrappingParams & parameters, MbResultType & res, c3d::WireFrameSPtr & resWire ); diff --git a/C3d/Include/cr_wrap_point.h b/C3d/Include/cr_wrap_point.h new file mode 100644 index 0000000..443140d --- /dev/null +++ b/C3d/Include/cr_wrap_point.h @@ -0,0 +1,64 @@ +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Строитель свёрнутой точки. + \en Wrapped point creator. +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_WRAP_POINT_H +#define __CR_WRAP_POINT_H + +#include +#include + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель свёрнутой точки. + \en Wrapped point creator. \~ + \details \ru Строитель свёрнутой точки. + \en Wrapped point creator. \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbWrapPointCreator : public MbCreator { +private: + MbCurvesWrappingParams _params; ///< \ru Параметры cворачивания. \en Parameters of the wrapping. + +protected: + /// \ru Конструктор копирования. \en Copy-constructor. + MbWrapPointCreator( const MbWrapPointCreator & other, MbRegDuplicate * iReg ); + +public: + /// \ru Конструктор по параметрам. \en Constructor by parameters. + MbWrapPointCreator( const MbCurvesWrappingParams & params ); + +public: + virtual ~MbWrapPointCreator() {}; + + // \ru Общие функции строителя. \en The common functions of the creator. + MbeCreatorType IsA() const override; // \ru Тип элемента \en A type of element + MbCreator & Duplicate( MbRegDuplicate * iReg = nullptr ) const override; // \ru Сделать копию \en Create a copy + + bool IsSame ( const MbCreator &, double accuracy ) const override; // \ru Являются ли объекты равными? \en Determine whether an object is equal? + bool IsSimilar( const MbCreator & ) const override; // \ru Являются ли объекты подобными \en Whether the objects are similar + bool SetEqual ( const MbCreator & ) override; // \ru Сделать равным \en Make equal + + void Transform( const MbMatrix3D &, MbRegTransform * = nullptr ) override; // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + void Move ( const MbVector3D &, MbRegTransform * = nullptr ) override; // \ru Сдвиг \en Translation + void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = nullptr ) override; // \ru Повернуть вокруг оси \en Rotate about an axis + + MbePrompt GetPropertyName() override; // \ru Дать имя свойства объекта \en Get the object property name + void GetProperties ( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of the object + void SetProperties ( const MbProperties & ) override; // \ru Записать свойства объекта \en Set properties of the object + + // \ru Построить каркас о журналу построения \en Create a wireframe from the history tree. + bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * items = nullptr ) override; + +private: + MbWrapPointCreator(); // \ru Не реализовано \en Not implemented + +OBVIOUS_PRIVATE_COPY( MbWrapPointCreator ) +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbWrapPointCreator ) +}; // MbWrapPointCreator + +#endif // __CR_WRAP_POINT_H diff --git a/C3d/Include/creator.h b/C3d/Include/creator.h index 0c9d759..93b0782 100644 --- a/C3d/Include/creator.h +++ b/C3d/Include/creator.h @@ -99,6 +99,9 @@ enum MbeCreatorType { ct_WireFrameIntoNurbsCreator= 218, ///< \ru Строитель NURBS-кривой по каркасу. \en Constructor of the NURBS-curve by wire frame. \n ct_TrimmedWireFrameCreator = 219, ///< \ru Строитель усечения каркаса. \en Constructor of the trimmed wireframe. \n + ct_UnwrapPointCreator = 220, ///< \ru Строитель развёрнутой точки. \en Constructor of the unwrapped point. \n + ct_WrapPointCreator = 221, ///< \ru Строитель cвёрнутой точки. \en Constructor of the wrapped point. \n + // \ru Строители полигональных объектов. \en Creators of polygonal objects. ct_SimpleMeshCreator = 400, ///< \ru Строитель полигонального объекта без истории. \en Constructor of a polygonal object without history. ct_ReverseMeshCreator = 401, ///< \ru Строитель вывернутого полигонального объекта. \en Constructor of a reversed polygonal object. diff --git a/C3d/Include/cur_arc.h b/C3d/Include/cur_arc.h index 1879c8f..daae23d 100644 --- a/C3d/Include/cur_arc.h +++ b/C3d/Include/cur_arc.h @@ -16,6 +16,7 @@ #include #include #include +#include class MATH_CLASS MbLine; @@ -73,8 +74,8 @@ protected : \details \ru Вспомогательные данные служат для ускорения работы объекта. \en Auxiliary data are used for fast calculations. \n \~ */ - mutable MbRect rect; ///< \ru Габаритный прямоугольник. \en Bounding rectangle. - mutable double metricLength; ///< \ru Метрическая длина кривой. \en Metric length of curve. + mutable MbRect rect; ///< \ru Габаритный прямоугольник. \en Bounding rectangle. + mutable atomic_double metricLength; ///< \ru Метрическая длина кривой. \en Metric length of curve. public : /** \brief \ru Конструктор окружности с параметрами по умолчанию. @@ -522,7 +523,10 @@ public: MbCurve * NurbsCurve( const MbNurbsParameters & ) const override; // \ru Построить Nurbs-копию кривой \en Construct NURBS-copy of the curve MbContour * NurbsContour() const override; - MbCurve * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; + // \ru Построить усеченную кривую c учетом заданной двумерной точности. \en Construct a trimmed curve with the given two-dimensional accuracy. + MbCurve * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyEps, bool saveParamLenAndLaw ) const override; + using MbCurve::Trimmed; // \ru Метод базового класса MbCurve без учета двумерной точности. Точность по умолчанию - MbDimAccuracy::twoDimAcc. \en Method of MbCurve base class without two-dimensional accuracy. The default accuracy is MbDimAccuracy::twoDimAcc. + MbCurve * Offset ( double rad ) const override; // \ru Смещение дуги эллипса \en Elliptical arc offset // \ru Положение точки относительно кривой. \en The point position relative to the curve. // \ru Возвращает результат: \en Returning result: @@ -606,10 +610,12 @@ public: initSense не должно быть равным нулю. \en Direction. initSense > 0 - counterclockwise, initSense < 0 - clockwise. initSense can't be equal to zero. \~ + \param[in] xyEps - \ru Компонента xyEps.x соответствует точности по оси x, xyEps.y - по оси y. + \en The xyEps.x component corresponds to x-axis accuracy, xyEps.y corresponds to y-axis accuracy. \~ \return \ru Значение угла. \en Value of angle. \~ */ - void InitByPositionAngles( double a1, double a2, int initSense ); // \ru Инициализация параметров по значениям углов в локальной системе \en Initialization of the parameters by values of angles in the local system + void InitByPositionAngles( double a1, double a2, int initSense, const MbDimAccuracy & xyEps = MbDimAccuracy::twoDimRgn ); // \ru Инициализация параметров по значениям углов в локальной системе \en Initialization of the parameters by values of angles in the local system /** \} */ /** \ru \name Функции для работы с данными. \en \name Functions for working with data. diff --git a/C3d/Include/cur_arc3d.h b/C3d/Include/cur_arc3d.h index 14cef57..f1227c4 100644 --- a/C3d/Include/cur_arc3d.h +++ b/C3d/Include/cur_arc3d.h @@ -14,6 +14,7 @@ #include #include #include +#include constexpr size_t CONIC_COUNT = 32; @@ -249,7 +250,7 @@ public : /** \brief \ru Конструктор дуги эллипса. \en Constructor of an elliptical arc. \~ - \details \ru Создается дуга эллипса с локальной системой координат и полуосями заданного эллипса. + \details \ru Создается дуга эллипса с локальной системой координат и полуосями заданного эллипса c учетом трехмерной точности. t1 и t2 определяют начальный и конечный углы дуги. Углы отсчитываются от оси OX против часовой стрелки. Углы заданы в радианах. Параметр initSense определяет направление дуги. Если initSense > 0, то направление движения против часовой стрелки. @@ -267,8 +268,10 @@ public : initSense не должно быть равным нулю. \en Direction. initSense > 0 - moving counterclockwise, clockwise < 0 - clockwise. 'initSense' can't be equal to zero. \~ + \param[in] xyzEps - \ru Трехмерная точность. + \en Three-dimensional accuracy. \~ */ - MbArc3D( const MbArc3D & init, double t1, double t2, int initSense ); + MbArc3D( const MbArc3D & init, double t1, double t2, int initSense, const MbDimAccuracy & xyzEps = MbDimAccuracy::threeDimAcc ); /** \brief \ru Конструктор дуги эллипса. \en Constructor of an elliptical arc. \~ @@ -469,7 +472,7 @@ public: void Init( const MbArc3D & ); void Init( const MbPlacement3D &, double aa, double bb, double angle ); - void Init( const MbArc3D & init, double t1, double t2, int initSense ); + void Init( const MbArc3D & init, double t1, double t2, int initSense, const MbDimAccuracy & xyzEps = MbDimAccuracy::threeDimAcc ); /// \ru Инициализация окружности или дуги окружности по трем точкам, (n == 0) - окружность или дуга по центру и двум точкам, (n == 1) - окружность или дуга по трем точкам. Возвращает true в случае удачи. \en Initialization of a circular arc by three points; (n == 0) - a circle or an arc by the center and two points, (n == 1) - a circle or an arc by three points. Return true if successful. bool Init( const MbCartPoint3D & p0, const MbCartPoint3D & p1, const MbCartPoint3D & p2, int n, bool closed ); /// \ru Инициализация дуги окружности по начальной и конечной точкам и 1/2 угла раствора дуги. Возвращает true в случае удачи. \en Initialization of a circular arc by the starting and the end points and 1/2 of the arc opening angle. Return true if successful. @@ -550,7 +553,10 @@ public: MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve3D * NurbsCurve( const MbNurbsParameters & ) const override; // \ru Построить Nurbs-копию кривой \en Construct NURBS-copy of the curve - MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; // \ru Создание усеченной кривой \en Creation of the trimmed curve + + // \ru Построить усеченную кривую c учетом заданной трехмерной точности. \en Construct a trimmed curve with the given three-dimensional accuracy. + MbCurve3D * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyzEps, bool saveParamLenAndLaw ) const override; + using MbCurve3D::Trimmed; // \ru Метод базового класса MbCurve3D без учета трехмерной точности. Точность по умолчанию - MbDimAccuracy::threeDimAcc. \en Method of MbCurve3D base class without three-dimensional accuracy. The default accuracy is MbDimAccuracy::threeDimAcc. double CalculateMetricLength() const override; // \ru Посчитать метрическую длину \en Calculate metric length double GetLengthEvaluation() const override; diff --git a/C3d/Include/cur_bezier.h b/C3d/Include/cur_bezier.h index c214da9..26219d4 100644 --- a/C3d/Include/cur_bezier.h +++ b/C3d/Include/cur_bezier.h @@ -13,6 +13,7 @@ #include #include +#include class MATH_CLASS MbArc; @@ -309,7 +310,11 @@ public : MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve * NurbsCurve( const MbNurbsParameters & ) const override; // \ru Построить NURBS-копию кривой \en Create a NURBS-copy of the curve - MbCurve * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; + + // \ru Построить усеченную кривую c учетом заданной двумерной точности. \en Construct a trimmed curve with the given two-dimensional accuracy. + MbCurve * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyEps, bool saveParamLenAndLaw ) const override; + using MbCurve::Trimmed; // \ru Метод базового класса MbCurve без учета двумерной точности. Точность по умолчанию - MbDimAccuracy::twoDimAcc. \en Method of MbCurve base class without two-dimensional accuracy. The default accuracy is MbDimAccuracy::twoDimAcc. + MbContour * NurbsContour() const override; void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменение направления кривой на противоположное \en Change to the opposite direction of a curve @@ -441,14 +446,16 @@ public : \en The new curve is created - a part of the Bezier curve between t1 and t2 parameters. \~ \param[out] trimPart - \ru Созданная кривая. \en Created curve. \~ - \param[in] t1 - \ru Параметр начала выделенной части. - \en A beginning parameter. \~ - \param[in] t2 - \ru Параметр конца выделенной части. - \en An end parameter. \~ + \param[in] t1 - \ru Параметр начала выделенной части. + \en A beginning parameter. \~ + \param[in] t2 - \ru Параметр конца выделенной части. + \en An end parameter. \~ + \param[in] xyEps - \ru Компонента xyEps.x соответствует точности по оси x, xyEps.y - по оси y. + \en The xyEps.x component corresponds to x-axis accuracy, xyEps.y corresponds to y-axis accuracy. \~ \result \ru true - если построение прошло успешно. \en True - if construction has been successfully. \~ */ - bool Break( MbBezier & trimPart, double t1, double t2 ) const; // \ru Выделить часть \en Break a part + bool Break( MbBezier & trimPart, double t1, double t2, const MbDimAccuracy & xyEps = MbDimAccuracy::twoDimAcc ) const; // \ru Выделить часть \en Break a part void SetBezierSplines(); ///< \ru Вычислить параметры кривой-Bezier. \en Calculate parameters of the Bezier curve. int GetFormType() const { return form; } ///< \ru Вернуть форму сплайна. \en Return the spline shape. void SetFormType( int newForm ); ///< \ru Установить форму сплайна. \en Set the spline shape. diff --git a/C3d/Include/cur_bezier3d.h b/C3d/Include/cur_bezier3d.h index 4a40cdc..030b791 100644 --- a/C3d/Include/cur_bezier3d.h +++ b/C3d/Include/cur_bezier3d.h @@ -143,8 +143,11 @@ public : MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve3D * NurbsCurve( const MbNurbsParameters & ) const override; - - MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; + + // \ru Построить усеченную кривую c учетом заданной трехмерной точности. \en Construct a trimmed curve with the given three-dimensional accuracy. + MbCurve3D * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyzEps, bool saveParamLenAndLaw ) const override; + using MbCurve3D::Trimmed; // \ru Метод базового класса MbCurve3D без учета трехмерной точности. Точность по умолчанию - MbDimAccuracy::threeDimAcc. \en Method of MbCurve3D base class without three-dimensional accuracy. The default accuracy is MbDimAccuracy::threeDimAcc. + // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую) // \en Give a planar curve and placement, if the spatial curve is planar (after using the DeleteItem must be called for a two-dimensional curve) bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const override; diff --git a/C3d/Include/cur_character_curve.h b/C3d/Include/cur_character_curve.h index 79ed416..f90710e 100644 --- a/C3d/Include/cur_character_curve.h +++ b/C3d/Include/cur_character_curve.h @@ -51,9 +51,10 @@ private: bool closed; ///< \ru Признак замкнутости кривой. \en An attribute of curve closedness. MbeLocalSystemType coordinateType; ///< \ru Тип системы координат, в которой заданы координатные функции \en Type of coordinate system the functions of coordinates are specified in c3d::DoubleVector specialParams; ///< \ru Перечень параметров особых точек кривой \en List of parameters of curve's singular points + // \ru Буферные данные для ускорения вычислений. \en Buffer data to speed up computations. - mutable double metricLength; - mutable MbRect rect; + mutable atomic_double metricLength; + mutable MbRect rect; public: MbCharacterCurve( MbFunction & x, MbFunction & y, @@ -108,7 +109,11 @@ public: size_t GetCount () const override; // \ru Определить количество разбиений для прохода в операциях. \en Define the number of splittings for one passage in operations. MbNurbs * NurbsCurve ( const MbCurveIntoNurbsInfo & ) const override; - MbCurve * Trimmed ( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; + // \ru Построить усеченную кривую c учетом заданной двумерной точности. \en Construct a trimmed curve with the given two-dimensional accuracy. + MbCurve * Trimmed ( double t1, double t2, int sense, const MbDimAccuracy & xyEps, bool saveParamLenAndLaw ) const override; + using MbCurve::Trimmed; // \ru Метод базового класса MbCurve без учета двумерной точности. Точность по умолчанию - MbDimAccuracy::twoDimAcc. \en Method of MbCurve base class without two-dimensional accuracy. The default accuracy is MbDimAccuracy::twoDimAcc. + + MbeState DeletePart ( double t1, double t2, MbCurve *& part2 ) override; // \ru Удалить часть кривой между параметрами t1 и t2 \en Remove a piece of curve between t1 and t2 parameters MbeState TrimmPart ( double t1, double t2, MbCurve *& part2 ) override; // \ru Оставить часть кривой между параметрами t1 и t2 \en Keep a piece of curve between t1 and t2 parameters diff --git a/C3d/Include/cur_cone_spiral.h b/C3d/Include/cur_cone_spiral.h index 15a69f1..161136f 100644 --- a/C3d/Include/cur_cone_spiral.h +++ b/C3d/Include/cur_cone_spiral.h @@ -229,7 +229,9 @@ public: MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = nullptr, VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; - MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; // \ru Создание усеченной кривой. \en Creation of a trimmed curve. + // \ru Построить усеченную кривую c учетом заданной трехмерной точности. \en Construct a trimmed curve with the given three-dimensional accuracy. + MbCurve3D * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyzEps, bool saveParamLenAndLaw ) const override; + using MbCurve3D::Trimmed; // \ru Метод базового класса MbCurve3D без учета трехмерной точности. Точность по умолчанию - MbDimAccuracy::threeDimAcc. \en Method of MbCurve3D base class without three-dimensional accuracy. The default accuracy is MbDimAccuracy::threeDimAcc. void Inverse( MbRegTransform * = nullptr ) override; // \ru Изменить направление. \en Change the direction. MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; diff --git a/C3d/Include/cur_contour.h b/C3d/Include/cur_contour.h index 7bd3fa1..0c8e92c 100644 --- a/C3d/Include/cur_contour.h +++ b/C3d/Include/cur_contour.h @@ -78,9 +78,9 @@ protected : bool closed; ///< \ru Признак замкнутости кривой. \en An Attribute of curve closedness. double paramLength; ///< \ru Параметрическая длина контура. \en Parametric length of a contour. protected: - mutable double metricLength; ///< \ru Метрическая длина контура. \en Metric length of a contour. - mutable MbRect rect; ///< \ru Габаритный прямоугольник. \en Bounding box. - mutable c3d::DoublePair areaSign; ///< \ru Площадь контура со знаком. \en Contour area with a sign. + mutable atomic_double metricLength; ///< \ru Метрическая длина контура. \en Metric length of a contour. + mutable MbRect rect; ///< \ru Габаритный прямоугольник. \en Bounding box. + mutable c3d::AtomicDoublePair areaSign; ///< \ru Площадь контура со знаком. \en Contour area with a sign. public : /// \ru Пустой контур. \en Empty contour. @@ -146,11 +146,11 @@ public: void CalculateGabarit ( MbRect & ) const override; // \ru Определить габариты кривой. \en Determine the bounding box of the curve. void CalculateLocalGabarit( const MbMatrix & into, MbRect & local ) const override; // \ru Добавь в прям-к свой габарит с учетом матрицы \en Add bounding box into a box with consideration of the matrix. - const MbRect & GetGabarit() const { if ( rect.IsEmpty() ) CalculateGabarit( rect ); return rect; } - const MbRect & GetCube() const { if ( rect.IsEmpty() ) CalculateGabarit( rect ); return rect; } + const MbRect & GetGabarit() const { if ( rect.IsEmpty() ) { MbRect tmp; CalculateGabarit( tmp ); } return rect; } + const MbRect & GetCube() const { if ( rect.IsEmpty() ) { MbRect tmp; CalculateGabarit( tmp ); } return rect; } /// \ru Сбросить рассчитанный габарит контура. \en Reset the calculated contour bounding box. - void SetDirtyGabarit() const { rect.SetEmpty(); } + void SetDirtyGabarit() const { ScopedRecursiveLock ll( GetLock() ); rect.SetEmpty(); } /// \ru Копировать габарит контура в контур (использовать только для передачи габарита в копию контура). \en Copy contour bounding box to contour copy (use only to transfer into contour copy). void CopyGabarit( const MbContour & c ) { rect = c.rect; } /// \ru Пуст ли габарит контура? \en Is the contour bounding box empty? @@ -167,7 +167,9 @@ public: MbeState DeletePart( double t1, double t2, MbCurve *& part2 ) override; // \ru Оставить часть контура между параметрами t1 и t2 \en Save a part of the contour between t1 and t2 parameters. MbeState TrimmPart( double t1, double t2, MbCurve *& part2 ) override; - MbCurve * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; + // \ru Построить усеченную кривую c учетом заданной двумерной точности. \en Construct a trimmed curve with the given two-dimensional accuracy. + MbCurve * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyEps, bool saveParamLenAndLaw ) const override; + using MbCurve::Trimmed; // \ru Метод базового класса MbCurve без учета двумерной точности. Точность по умолчанию - MbDimAccuracy::twoDimAcc. \en Method of MbCurve base class without two-dimensional accuracy. The default accuracy is MbDimAccuracy::twoDimAcc. /** \} */ /** \ru \name Функции описания области определения кривой. @@ -380,6 +382,7 @@ DEPRECATE_DECLARE_REPLACE( CheckClosed ) double DistanceToBorder( const MbCartPoint & pnt, double eps = Math::paramRegion ) const; void Trimm( double t1, double t2, bool saveParamLenAndLaw = false ); ///< \ru Выделить часть контура. \en Trim a part of the contour. + void Trimm( double t1, double t2, const MbDimAccuracy & xyEps, bool saveParamLenAndLaw ); ///< \ru Выделить часть контура c учетом двумерной точности. \en Trim a part of the contour with the given two-dimensional accuracy. // \ru Продлить кривую. \en Extend the curve. \~ MbResultType Extend( const MbCurveExtensionParameters & parameters, c3d::PlaneCurveSPtr & resCurve ) const override; @@ -651,7 +654,7 @@ DEPRECATE_DECLARE_REPLACE( CheckClosed ) template bool GetSegments( CurvesVector & segms ) const; ///< \ru Получить сегменты контура. \en Get contour segments. - void SetMetricLength( double len ) const { metricLength = len; } + void SetMetricLength( double len ) const { ScopedRecursiveLock ll( GetLock() ); metricLength = len; } /// \ru Установить начальную (конечную) точку для замкнутого контура. \en Set the start (end) point for closed contour. bool SetBegEndPoint( double t ); /// \ru Заменить сегменты контуры и сегменты полилинии. \en Replace segments of contour and segments of polyline. @@ -761,7 +764,7 @@ MbContour::MbContour( const Curves & initCurves, bool same ) , paramLength ( 0.0 ) , metricLength( -1.0 ) , rect ( ) - , areaSign ( c3d::DoublePair( -1.0, 0.0 ) ) + , areaSign ( -1.0, 0.0 ) { size_t count = initCurves.size(); segments.reserve( count ); diff --git a/C3d/Include/cur_contour3d.h b/C3d/Include/cur_contour3d.h index 29f459d..a67b3e7 100644 --- a/C3d/Include/cur_contour3d.h +++ b/C3d/Include/cur_contour3d.h @@ -181,7 +181,10 @@ public: double Curvature( double t ) const override; // \ru Преобразование в NURBS кривую \en Transform to NURBS-curve MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; - MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; // \ru Создание усеченной кривой \en Creation of a trimmed curve + + // \ru Построить усеченную кривую c учетом заданной трехмерной точности. \en Construct a trimmed curve with the given three-dimensional accuracy. + MbCurve3D * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyzEps, bool saveParamLenAndLaw ) const override; + using MbCurve3D::Trimmed; // \ru Метод базового класса MbCurve3D без учета трехмерной точности. Точность по умолчанию - MbDimAccuracy::threeDimAcc. \en Method of MbCurve3D base class without three-dimensional accuracy. The default accuracy is MbDimAccuracy::threeDimAcc. // \ru Продлить кривую. \en Extend the curve. \~ MbResultType Extend( const MbCurveExtensionParameters3D & parameters, c3d::SpaceCurveSPtr & resCurve ) const override; diff --git a/C3d/Include/cur_contour_on_plane.h b/C3d/Include/cur_contour_on_plane.h index f45f70a..d11392a 100644 --- a/C3d/Include/cur_contour_on_plane.h +++ b/C3d/Include/cur_contour_on_plane.h @@ -92,7 +92,9 @@ public : double Step ( double t, double sag ) const override; // \ru Вычислить шаг аппроксимации. \en Calculate the approximation step. double DeviationStep( double t, double sag ) const override; // \ru Вычислить шаг аппроксимации. \en Calculate the approximation step. - MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; // \ru Создать усеченную кривую. \en Create the trimmed curve. + // \ru Построить усеченную кривую c учетом заданной трехмерной точности. \en Construct a trimmed curve with the given three-dimensional accuracy. + MbCurve3D * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyzEps, bool saveParamLenAndLaw ) const override; + using MbCurve3D::Trimmed; // \ru Метод базового класса MbCurve3D без учета трехмерной точности. Точность по умолчанию - MbDimAccuracy::threeDimAcc. \en Method of MbCurve3D base class without three-dimensional accuracy. The default accuracy is MbDimAccuracy::threeDimAcc. double GetMetricLength() const override; // \ru Вычислить метрическую длину кривой. \en Calculate the metric length of curve. double GetLengthEvaluation() const override; // \ru Оценить метрическую длину кривой. \en Evaluate the metric length of curve. diff --git a/C3d/Include/cur_contour_on_surface.h b/C3d/Include/cur_contour_on_surface.h index 3eff2c6..6da4cde 100644 --- a/C3d/Include/cur_contour_on_surface.h +++ b/C3d/Include/cur_contour_on_surface.h @@ -60,9 +60,10 @@ class MATH_CLASS MbContourOnSurface : public MbCurve3D { protected : MbSurface * surface; ///< \ru Указатель на базовую поверхность (всегда не nullptr). \en The pointer to the base surface (this value is never nullptr). MbContour * contour; ///< \ru Указатель на 2D-контур в плоскости параметров поверхности (всегда не nullptr). \en The pointer to 2D-contour in the plane of the surface parameters (this value is never nullptr). - mutable double area; ///< \ru Площадь 2D-контура со знаком. \en The area of 2D-contour with sign. + + mutable atomic_double area; ///< \ru Площадь 2D-контура со знаком. \en The area of 2D-contour with sign. mutable MbCube cube; ///< \ru Габаритный куб. \en Bounding box. - mutable double metricLength; ///< \ru Метрическая длина. \en The metric length. + mutable atomic_double metricLength; ///< \ru Метрическая длина. \en The metric length. mutable MbSegmentsSearchTree * searchTree; ///< \ru Дерево габаритов для ускорения поиска сегментов. \en A tree of bounding boxes for segment search acceleration. private: @@ -158,7 +159,9 @@ public : MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; // \ru Установить параметры NURBS. \en Set the NURBS parameters. - MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; // \ru Создать усеченную кривую. \en Create the trimmed curve. + // \ru Построить усеченную кривую c учетом заданной трехмерной точности. \en Construct a trimmed curve with the given three-dimensional accuracy. + MbCurve3D * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyzEps, bool saveParamLenAndLaw ) const override; + using MbCurve3D::Trimmed; // \ru Метод базового класса MbCurve3D без учета трехмерной точности. Точность по умолчанию - MbDimAccuracy::threeDimAcc. \en Method of MbCurve3D base class without three-dimensional accuracy. The default accuracy is MbDimAccuracy::threeDimAcc. double Step( double t, double sag ) const override; // \ru Вычислить шаг аппроксимации. \en Calculate the approximation step. double DeviationStep( double t, double angle ) const override; // \ru Определить шаг по заданному углу отклонения касательной. \en Determine the step by a given angle of tangent deviation. diff --git a/C3d/Include/cur_cosinusoid.h b/C3d/Include/cur_cosinusoid.h index 684a917..11e995d 100644 --- a/C3d/Include/cur_cosinusoid.h +++ b/C3d/Include/cur_cosinusoid.h @@ -61,8 +61,9 @@ private : double phase; ///< \ru Начальная фаза в радианах. \en Initial phase in radians. double amplitude; ///< \ru Амплитуда. \en Amplitude. double tmin, tmax; ///< \ru Область определения (по умолчанию - один период). \en Domain (one period by default). - mutable MbRect rect; ///< \ru Габаритный прямоугольник. \en Bounding box. - mutable double metricLength; ///< \ru Метрическая длина. \en The metric length. + + mutable MbRect rect; ///< \ru Габаритный прямоугольник. \en Bounding box. + mutable atomic_double metricLength; ///< \ru Метрическая длина. \en The metric length. public : // \ru Конструктор по амплитуде, начальной фазе и круговой частоте \en Constructor by amplitude, initial phase and angular frequency @@ -131,7 +132,9 @@ public: MbeState DeletePart( double t1, double t2, MbCurve *& part2 ) override; // \ru Удалить часть кривой между параметрами t1 и t2 \en Delete a part of a curve between parameters t1 and t2 MbeState TrimmPart ( double t1, double t2, MbCurve *& part2 ) override; // \ru Оставить часть кривой между параметрами t1 и t2 \en Save a curve part between t1 and t2 parameters - MbCurve * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; // \ru Создание усеченной кривой \en Creation of a trimmed curve + // \ru Построить усеченную кривую c учетом заданной двумерной точности. \en Construct a trimmed curve with the given two-dimensional accuracy. + MbCurve * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyEps, bool saveParamLenAndLaw ) const override; // \ru Создание усеченной кривой \en Creation of a trimmed curve + using MbCurve::Trimmed; // \ru Метод базового класса MbCurve без учета двумерной точности. Точность по умолчанию - MbDimAccuracy::twoDimAcc. \en Method of MbCurve base class without two-dimensional accuracy. The default accuracy is MbDimAccuracy::twoDimAcc. void IntersectHorizontal( double y, SArray & cross ) const override; // \ru Пересечение кривой с горизонтальной прямой \en Intersection of curve with the horizontal line void IntersectVertical ( double x, SArray & cross ) const override; // \ru Пересечение с вертикальной прямой \en Intersection with the vertical line diff --git a/C3d/Include/cur_crooked_spiral.h b/C3d/Include/cur_crooked_spiral.h index 4b73093..a1aa780 100644 --- a/C3d/Include/cur_crooked_spiral.h +++ b/C3d/Include/cur_crooked_spiral.h @@ -110,7 +110,10 @@ public : void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction - MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; // \ru Создание усеченной кривой \en Creation of a trimmed curve + // \ru Построить усеченную кривую c учетом заданной трехмерной точности. \en Construct a trimmed curve with the given three-dimensional accuracy. + MbCurve3D * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyzEps, bool saveParamLenAndLaw ) const override; + using MbCurve3D::Trimmed; // \ru Метод базового класса MbCurve3D без учета трехмерной точности. Точность по умолчанию - MbDimAccuracy::threeDimAcc. \en Method of MbCurve3D base class without three-dimensional accuracy. The default accuracy is MbDimAccuracy::threeDimAcc. + double CalculateLength( double t1, double t2 ) const override; void GetBasisItems( RPArray & ) override; diff --git a/C3d/Include/cur_cubic_spline.h b/C3d/Include/cur_cubic_spline.h index 5ed3035..cb83a07 100644 --- a/C3d/Include/cur_cubic_spline.h +++ b/C3d/Include/cur_cubic_spline.h @@ -12,6 +12,7 @@ #include +#include class MbCurveIntoNurbsInfo; @@ -267,8 +268,11 @@ public : \result \ru Построенная усеченная кривая. \en A constructed trimmed curve. \~ */ - MbCurve * Trimmed ( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; // \ru Усечь кривую \en Trim a curve - MbCurve * TrimmedBreak( double t1, double t2, int sense ) const; // \ru Усечь кривую с разрывом \en Trim a curve with a break + + // \ru Построить усеченную кривую c учетом заданной двумерной точности. \en Construct a trimmed curve with the given two-dimensional accuracy. + MbCurve * Trimmed ( double t1, double t2, int sense, const MbDimAccuracy & xyEps, bool saveParamLenAndLaw ) const override; + using MbCurve::Trimmed; // \ru Метод базового класса MbCurve без учета двумерной точности. Точность по умолчанию - MbDimAccuracy::twoDimAcc. \en Method of MbCurve base class without two-dimensional accuracy. The default accuracy is MbDimAccuracy::twoDimAcc. + MbCurve * TrimmedBreak( double t1, double t2, int sense, const MbDimAccuracy & xyEps = MbDimAccuracy::twoDimAcc ) const; // \ru Усечь кривую с разрывом \en Trim a curve with a break MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve * NurbsCurve( const MbNurbsParameters & ) const override; diff --git a/C3d/Include/cur_cubic_spline3d.h b/C3d/Include/cur_cubic_spline3d.h index 4ed6a9c..3510175 100644 --- a/C3d/Include/cur_cubic_spline3d.h +++ b/C3d/Include/cur_cubic_spline3d.h @@ -282,7 +282,11 @@ public: void Rebuild () override; // \ru Перестроить кривую \en Rebuild the curve void SetClosed( bool cls ) override; // \ru Установить признак замкнутости. \en Set attribute of closedness. bool IsDegenerate( double eps = METRIC_PRECISION ) const override; - MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; // \ru Создать усеченную кривую \en Create the trimmed curve + + // \ru Построить усеченную кривую c учетом заданной трехмерной точности. \en Construct a trimmed curve with the given three-dimensional accuracy. + MbCurve3D * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyzEps, bool saveParamLenAndLaw ) const override; + using MbCurve3D::Trimmed; // \ru Метод базового класса MbCurve3D без учета трехмерной точности. Точность по умолчанию - MbDimAccuracy::threeDimAcc. \en Method of MbCurve3D base class without three-dimensional accuracy. The default accuracy is MbDimAccuracy::threeDimAcc. + MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = nullptr, VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; @@ -355,7 +359,7 @@ public: private: // \ru Усечь кривую с разрывом \en Trim a curve with a break - MbCurve3D * TrimmedBreak( double t1, double t2, int sense ) const; + MbCurve3D * TrimmedBreak( double t1, double t2, int sense, double tRegion ) const; // \ru Найти узел в положительном направлении \en Find a knot in the positive direction void AddKnot( ptrdiff_t &, double &, ptrdiff_t &, double &, ptrdiff_t &, double & ) const; void CheckSpline() const; // \ru Проверить корректность расчета сплайна \en Check correctness of the spline calculation diff --git a/C3d/Include/cur_curve_spiral.h b/C3d/Include/cur_curve_spiral.h index 2b6f9eb..793f731 100644 --- a/C3d/Include/cur_curve_spiral.h +++ b/C3d/Include/cur_curve_spiral.h @@ -114,7 +114,8 @@ public: void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction - MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; // \ru Создание усеченной кривой \en Creation of a trimmed curve + // \ru Построить усеченную кривую c учетом заданной трехмерной точности. \en Construct a trimmed curve with the given three-dimensional accuracy. + MbCurve3D * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyzEps, bool saveParamLenAndLaw ) const override; // \ru Функции спирали \en Functions of spiral diff --git a/C3d/Include/cur_hermit.h b/C3d/Include/cur_hermit.h index 553ff38..36ec33b 100644 --- a/C3d/Include/cur_hermit.h +++ b/C3d/Include/cur_hermit.h @@ -226,7 +226,9 @@ public : MbeState DeletePart( double t1, double t2, MbCurve *& part2 ) override; // \ru Оставить часть кривой между параметрами t1 и t2 \en Save a curve part between t1 and t2 parameters MbeState TrimmPart( double t1, double t2, MbCurve *& part2 ) override; - MbCurve * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; + // \ru Построить усеченную кривую c учетом заданной двумерной точности. \en Construct a trimmed curve with the given two-dimensional accuracy. + MbCurve * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyEps, bool saveParamLenAndLaw ) const override; + using MbCurve::Trimmed; // \ru Метод базового класса MbCurve без учета двумерной точности. Точность по умолчанию - MbDimAccuracy::twoDimAcc. \en Method of MbCurve base class without two-dimensional accuracy. The default accuracy is MbDimAccuracy::twoDimAcc. // \ru Создать NURBS представление кривой \en Create a NURBS representation of the curve MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; @@ -337,7 +339,7 @@ public : double & quota1, double & quota2 ) const; private: - bool Break( MbHermit & trimPart, double t1, double t2 ) const; // \ru Выделать часть \en Make a part + bool Break( MbHermit & trimPart, double t1, double t2, double tRegion = Math::paramEpsilon ) const; // \ru Выделать часть \en Make a part void CheckClosed( double epsilon ); // \ru Проверить и установить признак замкнутости кривой. \en Check and set closedness attribute of curve. bool SetCorrection( size_t ind, double tDelta ); // \ru Скорректировать кривую по индексу. \en Curve correction by index. void CalculateValues( size_t i1, size_t i2 ); // \ru Скорректировать кривую на интервале i1-i2. \en Curve correction on the interval i1-i2. diff --git a/C3d/Include/cur_hermit3d.h b/C3d/Include/cur_hermit3d.h index 01498d9..1c14701 100644 --- a/C3d/Include/cur_hermit3d.h +++ b/C3d/Include/cur_hermit3d.h @@ -243,7 +243,9 @@ public : MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve3D * NurbsCurve( const MbNurbsParameters & ) const override; // \ru Построить NURBS-копию кривой \en Create a NURBS-copy of the curve - MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; // \ru Создание усеченной кривой \en Creation of a trimmed curve + // \ru Построить усеченную кривую c учетом заданной трехмерной точности. \en Construct a trimmed curve with the given three-dimensional accuracy. + MbCurve3D * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyzEps, bool saveParamLenAndLaw ) const override; + using MbCurve3D::Trimmed; // \ru Метод базового класса MbCurve3D без учета трехмерной точности. Точность по умолчанию - MbDimAccuracy::threeDimAcc. \en Method of MbCurve3D base class without three-dimensional accuracy. The default accuracy is MbDimAccuracy::threeDimAcc. bool IsPlanar ( double accuracy = METRIC_EPSILON ) const override; // \ru Является ли кривая плоской \en Whether a curve is planar. bool IsStraight( bool ignoreParams = false ) const override; // \ru Признак прямолинейности кривой \en An attribute of curve straightness @@ -315,7 +317,7 @@ public : bool DerivativesCorrection( double accuracy ); private: - bool Break( MbHermit3D & trimPart, double t1, double t2 ) const; // \ru Разбить на две части \en Split into two parts + bool Break( MbHermit3D & trimPart, double t1, double t2, double tRegion ) const; // \ru Разбить на две части \en Split into two parts bool SetCorrection( size_t ind, double tDelta ); // \ru Скорректировать кривую по индексу. \en Curve correction by index. void CalculateValues( size_t i1, size_t i2 ); // \ru Скорректировать кривую на интервале i1-i2. \en Curve correction on the interval i1-i2. diff --git a/C3d/Include/cur_line.h b/C3d/Include/cur_line.h index 23f5051..944b87f 100644 --- a/C3d/Include/cur_line.h +++ b/C3d/Include/cur_line.h @@ -142,7 +142,9 @@ public : // \ru Оставить часть прямой между параметрами t1 и t2 \en Save a part of the line between t1 and t2 parameters MbeState TrimmPart( double t1, double t2, MbCurve *& part2 ) override; - MbCurve * Trimmed ( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; + // \ru Построить усеченную кривую c учетом заданной двумерной точности. \en Construct a trimmed curve with the given two-dimensional accuracy. + MbCurve * Trimmed ( double t1, double t2, int sense, const MbDimAccuracy & xyEps, bool saveParamLenAndLaw ) const override; + using MbCurve::Trimmed; // \ru Метод базового класса MbCurve без учета двумерной точности. Точность по умолчанию - MbDimAccuracy::twoDimAcc. \en Method of MbCurve base class without two-dimensional accuracy. The default accuracy is MbDimAccuracy::twoDimAcc. bool HasLength( double & ) const override; // \ru Метрическая длина \en The metric length double GetMetricLength() const override; // \ru Метрическая длина кривой \en Metric length of a curve diff --git a/C3d/Include/cur_line3d.h b/C3d/Include/cur_line3d.h index 1a2e63a..30a47b6 100644 --- a/C3d/Include/cur_line3d.h +++ b/C3d/Include/cur_line3d.h @@ -93,7 +93,10 @@ public : MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve3D * NurbsCurve( const MbNurbsParameters & ) const override; // \ru Построить Nurbs-копию кривой \en Construct NURBS copy of the curve - MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; // \ru Создание усеченной кривой \en Creation of a trimmed curve + // \ru Построить усеченную кривую c учетом заданной трехмерной точности. \en Construct a trimmed curve with the given three-dimensional accuracy. + MbCurve3D * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyzEps, bool saveParamLenAndLaw ) const override; + using MbCurve3D::Trimmed; // \ru Метод базового класса MbCurve3D без учета трехмерной точности. Точность по умолчанию - MbDimAccuracy::threeDimAcc. \en Method of MbCurve3D base class without three-dimensional accuracy. The default accuracy is MbDimAccuracy::threeDimAcc. + // \ru Сдвинуть параметр t на расстояние len по направлению \en Shift the parameter t by the distance 'len' in the direction bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::metricPrecision, VERSION version = Math::DefaultMathVersion() ) const override; diff --git a/C3d/Include/cur_line_segment.h b/C3d/Include/cur_line_segment.h index ee784d8..4be5b41 100644 --- a/C3d/Include/cur_line_segment.h +++ b/C3d/Include/cur_line_segment.h @@ -158,7 +158,9 @@ public : void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление кривой \en Change direction of a curve MbCurve * Offset( double rad ) const override; // \ru Смещение отрезка \en Shift of a line segment - MbCurve * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; + // \ru Построить усеченную кривую c учетом заданной двумерной точности. \en Construct a trimmed curve with the given two-dimensional accuracy. + MbCurve * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyEps, bool saveParamLenAndLaw ) const override; + using MbCurve::Trimmed; // \ru Метод базового класса MbCurve без учета двумерной точности. Точность по умолчанию - MbDimAccuracy::twoDimAcc. \en Method of MbCurve base class without two-dimensional accuracy. The default accuracy is MbDimAccuracy::twoDimAcc. MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve * NurbsCurve( const MbNurbsParameters & ) const override; // \ru Построить Nurbs-копию кривой \en Construct NURBS copy of the curve diff --git a/C3d/Include/cur_line_segment3d.h b/C3d/Include/cur_line_segment3d.h index bb0897b..1d8233c 100644 --- a/C3d/Include/cur_line_segment3d.h +++ b/C3d/Include/cur_line_segment3d.h @@ -99,7 +99,10 @@ public : MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve3D * NurbsCurve( const MbNurbsParameters & ) const override; // \ru Построить Nurbs-копию кривой \en Construct NURBS copy of the curve - MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; + + // \ru Построить усеченную кривую c учетом заданной трехмерной точности. \en Construct a trimmed curve with the given three-dimensional accuracy. + MbCurve3D * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyzEps, bool saveParamLenAndLaw ) const override; + using MbCurve3D::Trimmed; // \ru Метод базового класса MbCurve3D без учета трехмерной точности. Точность по умолчанию - MbDimAccuracy::threeDimAcc. \en Method of MbCurve3D base class without three-dimensional accuracy. The default accuracy is MbDimAccuracy::threeDimAcc. void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction double CalculateMetricLength() const override; // \ru Метрическая длина кривой \en Metric length of a curve diff --git a/C3d/Include/cur_nurbs.h b/C3d/Include/cur_nurbs.h index f3340e9..f0815af 100644 --- a/C3d/Include/cur_nurbs.h +++ b/C3d/Include/cur_nurbs.h @@ -763,7 +763,9 @@ public : MbCurve * NurbsCurve( const MbNurbsParameters & tParameters ) const override; // \ru Построить NURBS копию кривой. \en Construct a NURBS copy of a curve. MbContour * NurbsContour() const override; - MbCurve * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; + // \ru Построить усеченную кривую c учетом заданной двумерной точности. \en Construct a trimmed curve with the given two-dimensional accuracy. + MbCurve * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyEps, bool saveParamLenAndLaw ) const override; + using MbCurve::Trimmed; // \ru Метод базового класса MbCurve без учета двумерной точности. Точность по умолчанию - MbDimAccuracy::twoDimAcc. \en Method of MbCurve base class without two-dimensional accuracy. The default accuracy is MbDimAccuracy::twoDimAcc. void Refresh() override; // \ru Сбросить все временные данные. \en Reset all temporary data. void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменение направления кривой на противоположное. \en Set the opposite direction of curve. @@ -1024,7 +1026,7 @@ private: // \ru Системные методы. \en System methods. void SetClamped(); // \ru Делаем зажатый узловой вектор. \en Set clamped knots vector. void ResetCache(); // \ru Очистить кэш главного потока, сбросить остальные кэши. \en Clear main thread cache, reset other caches. - bool NurbsPlus( MbNurbs & nurbs, double tin, double tax ) const; + bool NurbsPlus( MbNurbs & nurbs, double tin, double tax, double tRegion ) const; // \ru Расчет весовых функций и их первых производных. \en Calculation of weight functions and its first derivatives. ptrdiff_t WeightFunctions( double & x, CcArray & ) const; diff --git a/C3d/Include/cur_nurbs3d.h b/C3d/Include/cur_nurbs3d.h index 12da504..3d6811f 100644 --- a/C3d/Include/cur_nurbs3d.h +++ b/C3d/Include/cur_nurbs3d.h @@ -526,8 +526,10 @@ public: MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve3D * NurbsCurve( const MbNurbsParameters & ) const override; // \ru Построить NURBS копию кривой. \en Construct a NURBS copy of a curve. - MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; - + // \ru Построить усеченную кривую c учетом заданной трехмерной точности. \en Construct a trimmed curve with the given three-dimensional accuracy. + MbCurve3D * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyzEps, bool saveParamLenAndLaw ) const override; + using MbCurve3D::Trimmed; // \ru Метод базового класса MbCurve3D без учета трехмерной точности. Точность по умолчанию - MbDimAccuracy::threeDimAcc. \en Method of MbCurve3D base class without three-dimensional accuracy. The default accuracy is MbDimAccuracy::threeDimAcc. + double GetRadius( double accuracy = METRIC_REGION ) const override; // \ru Дать физический радиус объекта или ноль, если это невозможно. \en Get the physical radius of the object or null if it impossible. bool GetCircleAxis ( MbAxis3D & ) const override; // \ru Дать ось кривой \en Get the axis of the curve // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую). \en Get a planar curve and placement, if the spatial curve is planar (after using the DeleteItem must be called for a two-dimensional curve) diff --git a/C3d/Include/cur_offset_curve.h b/C3d/Include/cur_offset_curve.h index fddaeb5..fd6c5e3 100644 --- a/C3d/Include/cur_offset_curve.h +++ b/C3d/Include/cur_offset_curve.h @@ -51,8 +51,8 @@ protected : double deltaTmax; ///< \ru Увеличение tmax параметра базовой кривой. \en Increase of tmax of base curve parameter. MbMatrix transform; ///< \ru Матрица преобразования (используется при разных масштабных коэффициентах трансформации). \en A transformation matrix (is used for different scale transformation). - mutable MbRect rect; ///< \ru Габаритный прямоугольник \en Bounding box - mutable double metricLength; ///< \ru Метрическая длина \en The metric length + mutable MbRect rect; ///< \ru Габаритный прямоугольник \en Bounding box + mutable atomic_double metricLength; ///< \ru Метрическая длина \en The metric length public : MbOffsetCurve( const MbCurve & bc, double dist, double t1, double t2, bool same ); @@ -205,7 +205,9 @@ public : MbeState DeletePart( double t1, double t2, MbCurve *& part2 ) override; // \ru Оставить часть смещенной кривой между параметрами t1 и t2 \en Save a part of a offset curve between t1 and t2 parameters MbeState TrimmPart ( double t1, double t2, MbCurve *& part2 ) override; - MbCurve * Trimmed ( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; + // \ru Построить усеченную кривую c учетом заданной двумерной точности. \en Construct a trimmed curve with the given two-dimensional accuracy. + MbCurve * Trimmed ( double t1, double t2, int sense, const MbDimAccuracy & xyEps, bool saveParamLenAndLaw ) const override; + using MbCurve::Trimmed; // \ru Метод базового класса MbCurve без учета двумерной точности. Точность по умолчанию - MbDimAccuracy::twoDimAcc. \en Method of MbCurve base class without two-dimensional accuracy. The default accuracy is MbDimAccuracy::twoDimAcc. MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; diff --git a/C3d/Include/cur_plane_curve.h b/C3d/Include/cur_plane_curve.h index db9a55a..e4f23bd 100644 --- a/C3d/Include/cur_plane_curve.h +++ b/C3d/Include/cur_plane_curve.h @@ -101,7 +101,9 @@ public : MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve3D * NurbsCurve( const MbNurbsParameters & ) const override; - MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; // \ru Создание усеченной кривой \en Creation of a trimmed curve + // \ru Построить усеченную кривую c учетом заданной трехмерной точности. \en Construct a trimmed curve with the given three-dimensional accuracy. + MbCurve3D * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyzEps, bool saveParamLenAndLaw ) const override; + using MbCurve3D::Trimmed; // \ru Метод базового класса MbCurve3D без учета трехмерной точности. Точность по умолчанию - MbDimAccuracy::threeDimAcc. \en Method of MbCurve3D base class without three-dimensional accuracy. The default accuracy is MbDimAccuracy::threeDimAcc. void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = nullptr ) const override; // \ru Ближайшая проекция точки на кривую \en The nearest point projection to the curve diff --git a/C3d/Include/cur_point_curve.h b/C3d/Include/cur_point_curve.h index 0a5758e..1b992b0 100644 --- a/C3d/Include/cur_point_curve.h +++ b/C3d/Include/cur_point_curve.h @@ -136,7 +136,9 @@ public : bool HasLength( double & length ) const override; MbCurve * Offset( double rad ) const override; // \ru Смещение отрезка \en Shift of a line segment - MbCurve * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; + // \ru Построить усеченную кривую c учетом заданной двумерной точности. \en Construct a trimmed curve with the given two-dimensional accuracy. + MbCurve * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyEps, bool saveParamLenAndLaw ) const override; + using MbCurve::Trimmed; // \ru Метод базового класса MbCurve без учета двумерной точности. Точность по умолчанию - MbDimAccuracy::twoDimAcc. \en Method of MbCurve base class without two-dimensional accuracy. The default accuracy is MbDimAccuracy::twoDimAcc. MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve * NurbsCurve( const MbNurbsParameters & ) const override; // \ru Построить NURBS-копию кривой \en Create a NURBS-copy of the curve diff --git a/C3d/Include/cur_polycurve.h b/C3d/Include/cur_polycurve.h index 3723dbd..7a036eb 100644 --- a/C3d/Include/cur_polycurve.h +++ b/C3d/Include/cur_polycurve.h @@ -36,8 +36,9 @@ protected : SArray pointList; ///< \ru Множество контрольных точек. \en Set of control points. ptrdiff_t uppIndex; ///< \ru Количество участков кривой (равно количество контрольных точек минус единица). \en Count of curve pieces (is equal to count of control points minus one). bool closed; ///< \ru Признак замкнутости кривой. \en An attribute of curve closedness. + mutable MbRect rect; ///< \ru Габаритный прямоугольник. \en Bounding rectangle. - mutable double metricLength; ///< \ru Метрическая длина сплайна. \en Metric length of a spline. + mutable atomic_double metricLength; ///< \ru Метрическая длина сплайна. \en Metric length of a spline. protected: MbPolyCurve(); ///< \ru Конструктор по умолчанию. \en Default constructor. diff --git a/C3d/Include/cur_polycurve3d.h b/C3d/Include/cur_polycurve3d.h index 9d4570a..a78d4a5 100644 --- a/C3d/Include/cur_polycurve3d.h +++ b/C3d/Include/cur_polycurve3d.h @@ -31,8 +31,9 @@ protected : ptrdiff_t uppIndex; ///< \ru Количество участков кривой (равно количество контрольных точек минус единица). \en Count of curve pieces (is equal to count of control points minus one). SArray pointList; ///< \ru Множество контрольных точек. \en Set of control points. bool closed; ///< \ru Признак замкнутости кривой. \en An attribute of curve closedness. - mutable double metricLength; ///< \ru Метрическая длина кривой. \en Metric length of curve. - mutable double lengthEvaluation; ///< \ru Оценочная длина кривой. \en Estimated length of a curve. + + mutable atomic_double metricLength; ///< \ru Метрическая длина кривой. \en Metric length of curve. + mutable atomic_double lengthEvaluation; ///< \ru Оценочная длина кривой. \en Estimated length of a curve. mutable MbCube cube; ///< \ru Габаритный куб кривой. \en Bounding box of curve. protected: diff --git a/C3d/Include/cur_polyline.h b/C3d/Include/cur_polyline.h index 21d62b3..37f7541 100644 --- a/C3d/Include/cur_polyline.h +++ b/C3d/Include/cur_polyline.h @@ -181,8 +181,9 @@ public : MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve * NurbsCurve( const MbNurbsParameters & ) const override; MbContour * NurbsContour() const override; - - MbCurve * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; + // \ru Построить усеченную кривую c учетом заданной двумерной точности. \en Construct a trimmed curve with the given two-dimensional accuracy. + MbCurve * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyEps, bool saveParamLenAndLaw ) const override; + using MbCurve::Trimmed; // \ru Метод базового класса MbCurve без учета двумерной точности. Точность по умолчанию - MbDimAccuracy::twoDimAcc. \en Method of MbCurve base class without two-dimensional accuracy. The default accuracy is MbDimAccuracy::twoDimAcc. double Step( double t, double sag ) const override; // \ru Вычисление шага аппроксимации \en Calculation of step of approximation double DeviationStep( double t, double angle ) const override; // \ru Вычисление шага аппроксимации по угловой толерантности \en Calculation of step of approximation by angular tolerance diff --git a/C3d/Include/cur_polyline3d.h b/C3d/Include/cur_polyline3d.h index 6b57036..7f4de8b 100644 --- a/C3d/Include/cur_polyline3d.h +++ b/C3d/Include/cur_polyline3d.h @@ -127,7 +127,10 @@ public : MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve3D * NurbsCurve( const MbNurbsParameters & ) const override; - MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; + // \ru Построить усеченную кривую c учетом заданной трехмерной точности. \en Construct a trimmed curve with the given three-dimensional accuracy. + MbCurve3D * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyzEps, bool saveParamLenAndLaw ) const override; + using MbCurve3D::Trimmed; // \ru Метод базового класса MbCurve3D без учета трехмерной точности. Точность по умолчанию - MbDimAccuracy::threeDimAcc. \en Method of MbCurve3D base class without three-dimensional accuracy. The default accuracy is MbDimAccuracy::threeDimAcc. + void Trimm( SArray & points, double t1, double t2, double eps = METRIC_EPSILON ) const; double GetTMin() const override; // \ru Вернуть минимальное значение параметра. \en Get the minimum value of the parameter. diff --git a/C3d/Include/cur_projection_curve.h b/C3d/Include/cur_projection_curve.h index 70a7ba3..aeef9d9 100644 --- a/C3d/Include/cur_projection_curve.h +++ b/C3d/Include/cur_projection_curve.h @@ -66,9 +66,9 @@ private : ///< \en Matrix for transrorming the surface curve (from spaceCurve) to the 'surface' coordinate system. uint8 projProp; ///< \ru Параметры кривой. \en Curves parameters. - mutable MbRect rect; ///< \ru Габарит проекционной кривой в параметрическом пространстве поверхности. \en Bounding box of projection curve in parametric space of surface. - mutable double metricLength; ///< \ru Метрическая длина проекционной кривой. \en Metric length of the projection curve. - mutable double tMiddle; ///< \ru Параметр на кривой, соответствующий метрической середине кривой. \en Parameter on the curve corresponding to the metric middle of the curve. + mutable MbRect rect; ///< \ru Габарит проекционной кривой в параметрическом пространстве поверхности. \en Bounding box of projection curve in parametric space of surface. + mutable atomic_double metricLength; ///< \ru Метрическая длина проекционной кривой. \en Metric length of the projection curve. + mutable atomic_double tMiddle; ///< \ru Параметр на кривой, соответствующий метрической середине кривой. \en Parameter on the curve corresponding to the metric middle of the curve. //------------------------------------------------------------------------------ /** \brief \ru Вспомогательные данные. @@ -271,8 +271,10 @@ public : double Step( double t, double sag ) const override; // \ru Вычисление шага аппроксимации с учетом радиуса кривизны \en Calculation of step of approximation with consideration of curvature radius double DeviationStep( double t, double angle ) const override; // \ru Вычисление шага аппроксимации с учетом угла отклонения \en Calculation of step of approximation with consideration of angle of deviation - - MbCurve * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; + // \ru Построить усеченную кривую c учетом заданной двумерной точности. \en Construct a trimmed curve with the given two-dimensional accuracy. + MbCurve * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyEps, bool saveParamLenAndLaw ) const override; + // \ru Построить усеченную кривую. \en Construct a trimmed curve. + MbCurve * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; const MbCurve3D & GetSpaceCurve() const { return *spaceCurve; } const MbSurface & GetSurface () const { return *surface; } diff --git a/C3d/Include/cur_reparam_curve.h b/C3d/Include/cur_reparam_curve.h index 31c2827..63cc1ff 100644 --- a/C3d/Include/cur_reparam_curve.h +++ b/C3d/Include/cur_reparam_curve.h @@ -98,8 +98,11 @@ public : bool IsSame( const MbPlaneItem &, double accuracy = LENGTH_EPSILON ) const override; MbCurve * Offset( double rad ) const override; // \ru Смещение усеченной кривой \en Shift of a trimmed curve MbPlaneItem & Duplicate( MbRegDuplicate * = nullptr ) const override; - MbCurve * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; - MbContour * NurbsContour() const override; // \ru Построить контур \en Create a contour + // \ru Построить усеченную кривую c учетом заданной двумерной точности. \en Construct a trimmed curve with the given two-dimensional accuracy. + MbCurve * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyEps, bool saveParamLenAndLaw ) const override; + using MbCurve::Trimmed; // \ru Метод базового класса MbCurve без учета двумерной точности. Точность по умолчанию - MbDimAccuracy::twoDimAcc. \en Method of MbCurve base class without two-dimensional accuracy. The default accuracy is MbDimAccuracy::twoDimAcc. + + MbContour * NurbsContour() const override; // \ru Построить контур \en Create a contour void AddYourGabaritTo( MbRect & ) const override; // \ru Добавь свой габарит в прямой прям-к \en Add your own gabarit into the given bounding rectangle void CalculateGabarit( MbRect & ) const override; // \ru Определить габариты кривой \en Determine the bounding box of a curve bool IsVisibleInRect( const MbRect &, bool exact = false ) const override; // \ru Виден ли объект в заданном прямоугольнике \en Whether the object is visible in the given rectangle diff --git a/C3d/Include/cur_reparam_curve3d.h b/C3d/Include/cur_reparam_curve3d.h index 39a63a1..e048d57 100644 --- a/C3d/Include/cur_reparam_curve3d.h +++ b/C3d/Include/cur_reparam_curve3d.h @@ -133,7 +133,10 @@ public : const MbFunction * GetFunction() const { return repFunction; } // \ru Получить функцию. \en Get function const MbCurve3D & GetBasisCurve() const override; MbCurve3D & SetBasisCurve() override; - MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; // \ru Создание усеченной кривой \en Create a trimmed curve + + // \ru Построить усеченную кривую c учетом заданной трехмерной точности. \en Construct a trimmed curve with the given three-dimensional accuracy. + MbCurve3D * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyzEps, bool saveParamLenAndLaw ) const override; + using MbCurve3D::Trimmed; // \ru Метод базового класса MbCurve3D без учета трехмерной точности. Точность по умолчанию - MbDimAccuracy::threeDimAcc. \en Method of MbCurve3D base class without three-dimensional accuracy. The default accuracy is MbDimAccuracy::threeDimAcc. void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction diff --git a/C3d/Include/cur_silhouette_curve.h b/C3d/Include/cur_silhouette_curve.h index 676e89b..ca55b81 100644 --- a/C3d/Include/cur_silhouette_curve.h +++ b/C3d/Include/cur_silhouette_curve.h @@ -137,8 +137,10 @@ public: // \ru Тип проецирования. \en Projection type. bool IsPerspective() const { return perspective; } - // \ru Создать усеченную кривую. \en Create a trimmed curve - MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; + // \ru Построить усеченную кривую c учетом заданной трехмерной точности. \en Construct a trimmed curve with the given three-dimensional accuracy. + MbCurve3D * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyzEps, bool saveParamLenAndLaw ) const override; + using MbCurve3D::Trimmed; // \ru Метод базового класса MbCurve3D без учета трехмерной точности. Точность по умолчанию - MbDimAccuracy::threeDimAcc. \en Method of MbCurve3D base class without three-dimensional accuracy. The default accuracy is MbDimAccuracy::threeDimAcc. + // \ru Дать плоскую проекцию кривой(локальная система координат, шаг, параметрическая область). \en Get the planar projection of a curve (local coordinate system, step, parametric region). MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = nullptr, VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; diff --git a/C3d/Include/cur_spiral.h b/C3d/Include/cur_spiral.h index c70fc16..c74d26e 100644 --- a/C3d/Include/cur_spiral.h +++ b/C3d/Include/cur_spiral.h @@ -36,7 +36,7 @@ protected: \details \ru Метрическая длина кривой, рассчитывается только при запросе длины объекта. Метрическая длина кривой в конструкторе кривой и после модификации кривой принимает отрицательное значение. \en Metric length of a curve is calculated only at the request. Metric length of a curve is undefined (negative) after object constructor and after object modifications. \n \~ */ - mutable double metricLength; + mutable atomic_double metricLength; /** \brief \ru Габаритный куб кривой. \en Bounding box of a curve. \~ \details \ru Габаритный куб кривой, рассчитывается только при запросе габарита объекта. Габаритный куб в конструкторе кривой и после модификации кривой принимает неопределенное значение. diff --git a/C3d/Include/cur_surface_curve.h b/C3d/Include/cur_surface_curve.h index 3e6480a..93f52c4 100644 --- a/C3d/Include/cur_surface_curve.h +++ b/C3d/Include/cur_surface_curve.h @@ -75,12 +75,12 @@ protected : \en Auxiliary data are used for fast calculations. \n \~ */ mutable MbCube cube; ///< \ru Габаритный куб. \en Bounding box. - mutable double metricLength; ///< \ru Метрическая длина кривой. \en Metric length of the curve. \~ - mutable double lengthEvaluation; ///< \ru Оценочная длина кривой. \en Estimated length of the curve. + mutable atomic_double metricLength; ///< \ru Метрическая длина кривой. \en Metric length of the curve. \~ + mutable atomic_double lengthEvaluation; ///< \ru Оценочная длина кривой. \en Estimated length of the curve. mutable MbCartPoint3D weightCenter; ///< \ru Центр тяжести кривой. \en Center of mass of the curve. - mutable double curveRadius; ///< \ru Радиус кривой, если она является дугой окружности в пространстве. \en The radius of the curve, if the curve is a spatial arc. - mutable c3d::DoublePair radiusAccuracy; ///< \ru Точности вычисления curveRadius. \en The precisions for the calculation of curveRadius. - mutable ThreeStates isStraight; ///< \ru Флаг прямолинейности. \en A straightness flag. + mutable atomic_double curveRadius; ///< \ru Радиус кривой, если она является дугой окружности в пространстве. \en The radius of the curve, if the curve is a spatial arc. + mutable c3d::AtomicDoublePair radiusAccuracy; ///< \ru Точности вычисления curveRadius. \en The precisions for the calculation of curveRadius. + mutable atomic_enum_type isStraight; ///< \ru Флаг прямолинейности. \en A straightness flag. SPtr tessellation; ///< \ru Разбивка кривой. \en Curve tessellation. //------------------------------------------------------------------------------ @@ -183,7 +183,9 @@ public: // \ru Установить параметры NURBS. \en Set parameters of NURBS. MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; - MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; // \ru Создать усеченную кривую. \en Create a trimmed curve + // \ru Построить усеченную кривую c учетом заданной трехмерной точности. \en Construct a trimmed curve with the given three-dimensional accuracy. + MbCurve3D * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyzEps, bool saveParamLenAndLaw ) const override; + using MbCurve3D::Trimmed; // \ru Метод базового класса MbCurve3D без учета трехмерной точности. Точность по умолчанию - MbDimAccuracy::threeDimAcc. \en Method of MbCurve3D base class without three-dimensional accuracy. The default accuracy is MbDimAccuracy::threeDimAcc. // \ru Вычислить ближайшую проекцию точки на кривую. \en Calculate the nearest projection of a point onto the curve. bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = nullptr ) const override; @@ -363,6 +365,10 @@ protected: */ void CacheReset(); + double CalcMetricLength( bool force = false ) const; // \ru Вычислить метрическую длину кривой. \en Calculate the metric length of a curve. + double CalcLengthEvaluation( bool force = false ) const; // \ru Оценить метрическую длину кривой. \en Estimate the metric length of a curve. + void CalcWeightCentre( MbCartPoint3D & wc, bool force = false ) const; // \ru Выдать центр тяжести кривой. \en Get center of mass of curve. + private: // \ru Объявить оператор приравнивания по ссылке, \en Declare operator of assignment by reference // \ru чтобы не был вызван по умолчанию оператор приравнивания по значению \en To prevent default calling of the assignment operator by value diff --git a/C3d/Include/cur_surface_intersection.h b/C3d/Include/cur_surface_intersection.h index ed0e53f..17711ab 100644 --- a/C3d/Include/cur_surface_intersection.h +++ b/C3d/Include/cur_surface_intersection.h @@ -18,6 +18,7 @@ #include #include #include +#include class MATH_CLASS MbMatrix; @@ -141,16 +142,16 @@ private : MbSurfaceCurve curveTwo; ///< \ru Кривая на второй поверхности. \en Curve on the second surface. MbeCurveBuildType buildType; ///< \ru Тип кривой по построению. \en A curve type by construction. - mutable MbeCurveGlueType glueType; ///< \ru Тип кривой по топологии. \en A curve type by topology. - mutable double tolerance; ///< \ru Погрешность построения кривой. \en The tolerance of curve construction. \~ + mutable atomic_enum_type glueType; ///< \ru Тип кривой по топологии. \en A curve type by topology. + mutable atomic_double tolerance; ///< \ru Погрешность построения кривой. \en The tolerance of curve construction. \~ mutable MbCube cube; ///< \ru Габаритный куб кривой. \en Bounding box of a curve. \~ - mutable double metricLength; ///< \ru Метрическая длина кривой. \en Metric length of a curve. \~ - mutable double lengthEvaluation; ///< \ru Оценочная длина кривой. \en Estimated length of a curve. \~ - mutable double curveRadius; ///< \ru Радиус кривой, если она является дугой окружности в пространстве. \en The radius of the curve, if the curve is a spatial arc. - mutable c3d::DoublePair radiusAccuracy; ///< \ru Точности вычисления curveRadius. \en The precisions for the calculation of curveRadius. + mutable atomic_double metricLength; ///< \ru Метрическая длина кривой. \en Metric length of a curve. \~ + mutable atomic_double lengthEvaluation; ///< \ru Оценочная длина кривой. \en Estimated length of a curve. \~ + mutable atomic_double curveRadius; ///< \ru Радиус кривой, если она является дугой окружности в пространстве. \en The radius of the curve, if the curve is a spatial arc. + mutable c3d::AtomicDoublePair radiusAccuracy; ///< \ru Точности вычисления curveRadius. \en The precisions for the calculation of curveRadius. #ifdef C3D_SIGNAL_ENABLED - mutable bool inChange; ///< \ru Указывает на нахождение в процессе изменений. \en Indicates to being in the process of changes. + mutable atomic_bool inChange; ///< \ru Указывает на нахождение в процессе изменений. \en Indicates to being in the process of changes. #endif //------------------------------------------------------------------------------ @@ -407,7 +408,9 @@ public: // \ru Преобразовать в NURBS кривую. \en Transform to a NURBS-curve. MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; - MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; // \ru Создать усеченную кривую. \en Create a trimmed curve + // \ru Построить усеченную кривую c учетом заданной трехмерной точности. \en Construct a trimmed curve with the given three-dimensional accuracy. + MbCurve3D * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyzEps, bool saveParamLenAndLaw ) const override; + using MbCurve3D::Trimmed; // \ru Метод базового класса MbCurve3D без учета трехмерной точности. Точность по умолчанию - MbDimAccuracy::threeDimAcc. \en Method of MbCurve3D base class without three-dimensional accuracy. The default accuracy is MbDimAccuracy::threeDimAcc. /// \ru Создать усеченную кривую на тех же поверхностях. \en Create a trimmed curve on the same surfaces. MbSurfaceIntersectionCurve * TrimmedIntersection( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const; @@ -479,7 +482,7 @@ public: bool IsSpaceSame( const MbSpaceItem & item, double eps = METRIC_REGION ) const override; /// \ru Получить тип кривой по топологии. \en Get a curve type by topology. - MbeCurveGlueType GetGlueType() const { return glueType; } + MbeCurveGlueType GetGlueType() const { return glueType(); } /// \ru Установить тип кривой по топологии. \en Set a curve type by topology. void SetGlueType( MbeCurveGlueType type ) { glueType = type; } /// \ru Установить тип кривой по топологии. \en Set a curve type by topology. @@ -804,11 +807,11 @@ inline bool MbSurfaceIntersectionCurve::CopyReadyMutable( const MbSurfaceInterse bool changed = false; if ( lengthEvaluation < 0.0 && s.lengthEvaluation >= 0.0 ) { - lengthEvaluation = s.lengthEvaluation; + lengthEvaluation = s.lengthEvaluation.load(); changed = true; } if ( metricLength < 0.0 && s.metricLength >= 0.0 ) { - metricLength = s.metricLength; + metricLength = s.metricLength.load(); changed = true; } if ( cube.IsEmpty() && !s.cube.IsEmpty() ) { diff --git a/C3d/Include/cur_trimmed_curve.h b/C3d/Include/cur_trimmed_curve.h index c10f472..bdc7a7f 100644 --- a/C3d/Include/cur_trimmed_curve.h +++ b/C3d/Include/cur_trimmed_curve.h @@ -50,8 +50,8 @@ protected : ///< \ru Если (sense < 0), то (trim2 < trim1) \en If (sense < 0), then (trim2 < trim1) ///< \ru Равенство trim1 и trim2 не допускается \en Equality of 'trim1' and 'trim2' isn't allowed - mutable MbRect rect; ///< \ru Габаритный прямоугольник \en Bounding rectangle - mutable double metricLength; ///< \ru Метрическая длина усеченной кривой \en Metric length of a trimmed curve + mutable MbRect rect; ///< \ru Габаритный прямоугольник \en Bounding rectangle + mutable atomic_double metricLength; ///< \ru Метрическая длина усеченной кривой \en Metric length of a trimmed curve protected : MbTrimmedCurve( const MbTrimmedCurve & initCurve ); @@ -170,7 +170,10 @@ public : bool GetSpecificPoint( const MbCartPoint & from, double & dmax, MbCartPoint & pnt ) const override; MbeState DeletePart( double t1, double t2, MbCurve *& part2 ) override; // \ru Удалить часть усеченной кривой между параметрами t1 и t2 \en Delete a part of a trimmed curve between parameters t1 and t2 MbeState TrimmPart ( double t1, double t2, MbCurve *& part2 ) override; // \ru Оставить часть усеченной кривой между параметрами t1 и t2 \en Keep a part of the trimmed curve between parameters t1 and t2 - MbCurve * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; + // \ru Построить усеченную кривую c учетом заданной двумерной точности. \en Construct a trimmed curve with the given two-dimensional accuracy. + MbCurve * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyEps, bool saveParamLenAndLaw ) const override; + using MbCurve::Trimmed; // \ru Метод базового класса MbCurve без учета двумерной точности. Точность по умолчанию - MbDimAccuracy::twoDimAcc. \en Method of MbCurve base class without two-dimensional accuracy. The default accuracy is MbDimAccuracy::twoDimAcc. + MbCurve * Offset( double rad ) const override; // \ru Смещение усеченной кривой \en Shift of a trimmed curve MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; diff --git a/C3d/Include/cur_trimmed_curve3d.h b/C3d/Include/cur_trimmed_curve3d.h index 2f7fc23..eaf8378 100644 --- a/C3d/Include/cur_trimmed_curve3d.h +++ b/C3d/Include/cur_trimmed_curve3d.h @@ -12,6 +12,7 @@ #include +#include //------------------------------------------------------------------------------ @@ -41,10 +42,10 @@ private : double trim2; ///< \ru Параметр конечной точки базовой кривой. \en Parameter of the end point of base curve. int sense; ///< \ru Флаг совпадения направления с направлением базовой кривой. \en Flag of coincidence of the direction with the direction of base curve. private: - mutable double metricLength; ///< \ru Метрическая длина кривой. \en Metric length of a curve. + mutable atomic_double metricLength; ///< \ru Метрическая длина кривой. \en Metric length of a curve. public : - MbTrimmedCurve3D( const MbCurve3D & initCurve, double t1, double t2, int initSense, bool same ); + MbTrimmedCurve3D( const MbCurve3D & initCurve, double t1, double t2, int initSense, bool same, const MbDimAccuracy & xyzEps = MbDimAccuracy::threeDimAcc ); MbTrimmedCurve3D( const MbCurve3D & initCurve, const MbCartPoint3D & p0, const MbCartPoint3D & p1 ); protected : MbTrimmedCurve3D( const MbTrimmedCurve3D &, MbRegDuplicate * ); @@ -102,7 +103,10 @@ public : const MbCurve3D & GetBasisCurve() const override; MbCurve3D & SetBasisCurve() override; - MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const override; // \ru Создание усеченной кривой \en Create a trimmed curve + + // \ru Построить усеченную кривую c учетом заданной трехмерной точности. \en Construct a trimmed curve with the given three-dimensional accuracy. + MbCurve3D * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyzEps, bool saveParamLenAndLaw ) const override; + using MbCurve3D::Trimmed; // \ru Метод базового класса MbCurve3D без учета трехмерной точности. Точность по умолчанию - MbDimAccuracy::threeDimAcc. \en Method of MbCurve3D base class without three-dimensional accuracy. The default accuracy is MbDimAccuracy::threeDimAcc. void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction double Curvature ( double ) const override; // \ru Кривизна усеченной кривой \en Curvature of a trimmed curve @@ -125,7 +129,7 @@ public : double GetMetricLength() const override; // \ru Метрическая длина \en Metric length void SetBasisCurve( MbCurve3D & ); // \ru Заменить плоскую кривую \en Replace the planar curve - void InitParam( double t1, double t2, int initSense ); + void InitParam( double t1, double t2, int initSense, const MbDimAccuracy & xyzEps = MbDimAccuracy::threeDimAcc ); double GetTrim1() const { return trim1; } double GetTrim2() const { return trim2; } int GetSense() const { return sense; } // \ru Флаг совпадения направления с направлением базовой кривой \en Flag of coincidence of the direction with the direction of base curve diff --git a/C3d/Include/curve.h b/C3d/Include/curve.h index cf96788..e07c1f7 100644 --- a/C3d/Include/curve.h +++ b/C3d/Include/curve.h @@ -35,6 +35,7 @@ class MATH_CLASS MbContour; class MATH_CLASS MbPolygon; class MATH_CLASS MbCrossPoint; class MATH_CLASS MbCurveExtensionParameters; +class MATH_CLASS MbDimAccuracy; class MbCurveIntoNurbsInfo; struct MbNurbsParameters; @@ -698,7 +699,57 @@ public : \result \ru Построенная усеченная кривая. \en A constructed trimmed curve. \~ */ - virtual MbCurve * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const = 0; + virtual MbCurve * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const; + + /** \brief \ru Построить усеченную кривую c учетом заданной двумерной точности. + \en Construct a trimmed curve with the given two-dimensional accuracy. \~ + \details \ru Строит усеченную кривую c учетом заданной двумерной точности на плоскости, + начало которой соответствует точке с параметром t1 и конец - точке с параметром t2. + Можно изменить направление полученной кривой относительно исходной с помощью параметра sense. + Если кривая замкнута, можно получить усеченную кривую, проходящую через + начало кривой.\n + В случае замкнутой кривой (или для дуги - исключение) три параметра sense, t1 и t2 однозначно + определяют результат. + В случае разомкнутой кривой параметр sense и параметрами усечения должны соответствовать друг другу:\n + 1) если sense == 1, то t1 < t2,\n + 2) если sense == -1, то t1 > t2.\n + Если есть несоответствие между sense и параметрами усечения, то + приоритетным параметром считается sense. + Если параметры t1 и t2 равны и кривая замкнута, в результате должны получить замкнутую кривую. + \en Constructs a trimmed curve, a start point of which corresponds to a point with parameter t1 and + an end point corresponds to a point with parameter t2. + Direction of the constructed curve relative to the initial curve may be changed by the parameter 'sense'. + If the curve is closed, then there may be obtained a trimmed curve, passing through + the start of a curve.\n + In a case of closed curve (or for an arc - exception) three parameters 'sense', t1 and t2 clearly + define the result. + In a case of unclosed curve the parameter 'sense' and parameter of trimming should correspond each other:\n + 1) if sense == 1, then t1 < t2,\n + 2) if sense == -1, then t1 > t2,\n + If there is a discrepancy between 'sense' and parameters of trimming, then + 'sense' parameter has higher priority. + If parameters t1 and t2 are equal and the curve is closed, then in result a closed curve should be obtained. \~ + \param[in] t1 - \ru Параметр, соответствующий началу усеченной кривой. + \en Parameter corresponding to start of a trimmed curve. \~ + \param[in] t2 - \ru Параметр, соответствующий концу усеченной кривой. + \en Parameter corresponding to end of a trimmed curve. \~ + \param[in] sense - \ru Направление усеченной кривой относительно исходной.\n + sense = 1 - направление кривой сохраняется. + sense = -1 - направление кривой меняется на обратное. + \en Direction of a trimmed curve in relation to an initial curve. + sense = 1 - direction does not change. + sense = -1 - direction changes to the opposite value. \~ + \param[in] xyEps - \ru Двумерная точность. + \en Two-dimensional accuracy. \~ + \param[in] saveParLenAndLaw - \ru Сохранять параметрическую длину и закон. + \en Save parametric length and law. \~ + \internal \ru При изменении поведения или документации метода переделать юнит-тестирование. + \en When changing of the behavior or the documentation of the method being performed, the unit-testing should be redone. \~ \endinternal + \result \ru Построенная усеченная кривая. + \en A constructed trimmed curve. \~ + \warning \ru В разработке. \en Under development. + */ + virtual MbCurve * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyEps, bool saveParamLenAndLaw ) const = 0; /// \ru Аппроксимировать кривую контуром из NURBS-кривых. \en Approximate of a curve by the contour from NURBS curves. virtual MbContour * NurbsContour() const; @@ -1290,7 +1341,9 @@ public : /// \ru Вернуть минимально различимую величину параметра с заданной точностью. \en Return the minimal discernible value of parameter with the given tolerance. virtual double GetTRegion ( double epsilon ) const; /// \ru Вернуть минимально различимую величину параметра с заданной точностью в зависимости от параметра. \en Return the minimal discernible value of parameter with the given tolerance according to parameter. - virtual double GetTRegion ( double t, double epsilon ) const; + virtual double GetTRegion ( double t, double epsilon ) const; + /// \ru Вернуть минимально различимую величину параметра с заданной двумерной точностью в зависимости от параметра. Метод учитывает направление кривой в точке. \en Return the minimal discernible value of parameter with the given two-dimensinal accuracy according to parameter. The method takes into account the direction of the curve at a point. + virtual double GetTRegion( double t, const MbDimAccuracy & xyEps ) const; /// \ru Вернуть середину параметрического диапазона кривой. \en Return the middle of parametric range of a curve. double GetTMid() const { return ((GetTMin() + GetTMax()) * 0.5); } diff --git a/C3d/Include/curve3d.h b/C3d/Include/curve3d.h index 4bed6c4..8f8226f 100644 --- a/C3d/Include/curve3d.h +++ b/C3d/Include/curve3d.h @@ -37,6 +37,7 @@ class MATH_CLASS MbPolygon3D; class MATH_CLASS MbNurbs3D; class MATH_CLASS MbPlacement3D; class MATH_CLASS MbCurveExtensionParameters3D; +class MATH_CLASS MbDimAccuracy; class MbCurveIntoNurbsInfo; struct MbNurbsParameters; @@ -557,7 +558,56 @@ public : \en A constructed trimmed curve. \~ \ingroup Curves_3D */ - virtual MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const; // \ru Создание усеченной кривой. \en Creation of trimmed curve. + virtual MbCurve3D * Trimmed( double t1, double t2, int sense, bool saveParamLenAndLaw = false ) const; + + /** \brief \ru Построить усеченную кривую c учетом заданной трехмерной точности. + \en Construct a trimmed curve with the given two-dimensional accuracy. \~ + \details \ru Строит усеченную кривую c учетом заданной трехмерной точности, + начало которой соответствует точке с параметром t1 и конец - точке с параметром t2. + Можно изменить направление полученной кривой относительно исходной с помощью параметра sense. + Если кривая замкнута, можно получить усеченную кривую, проходящую через + начало кривой.\n + В случае замкнутой или периодической кривой три параметра sense, t1 и t2 однозначно + определяют результат. + В случае разомкнутой кривой параметр sense и параметрами усечения должны соответствовать друг другу:\n + 1) если sense == 1, то t1 < t2,\n + 2) если sense == -1, то t1 > t2.\n + Если есть несоответствие между sense и параметрами усечения, то + приоритетным параметром считается sense. + Если параметры t1 и t2 равны и кривая замкнута, в результате должны получить замкнутую кривую. + \en Constructs a trimmed curve, a start point of which corresponds to a point with parameter t1 and + an end point corresponds to a point with parameter t2. + Direction of the constructed curve relative to the initial curve may be changed by the parameter 'sense'. + If the curve is closed, then there may be obtained a trimmed curve, passing through + the start of a curve.\n + In a case of closed or periodic curve three parameters 'sense', t1 and t2 clearly + define the result. + In a case of unclosed curve the parameter 'sense' and parameter of trimming should correspond each other:\n + 1) if sense == 1, then t1 < t2,\n + 2) if sense == -1, then t1 > t2,\n + If there is a discrepancy between 'sense' and parameters of trimming, then + 'sense' parameter has higher priority. + If parameters t1 and t2 are equal and the curve is closed, then in result a closed curve should be obtained. \~ + \param[in] t1 - \ru Параметр, соответствующий началу усеченной кривой. + \en Parameter corresponding to start of a trimmed curve. \~ + \param[in] t2 - \ru Параметр, соответствующий концу усеченной кривой. + \en Parameter corresponding to end of a trimmed curve. \~ + \param[in] sense - \ru Направление усеченной кривой относительно исходной.\n + sense = 1 - направление кривой сохраняется. + sense = -1 - направление кривой меняется на обратное. + \en Direction of a trimmed curve in relation to an initial curve. + sense = 1 - direction does not change. + sense = -1 - direction changes to the opposite value. \~ + \param[in] xyzEps - \ru Трехмерная точность. + \en Three-dimensional accuracy. \~ + \param[in] saveParLenAndLaw - \ru Сохранять параметрическую длину и закон. + \en Save parametric length and law. \~ + \result \ru Построенная усеченная кривая. + \en A constructed trimmed curve. \~ + \ingroup Curves_3D + \warning \ru В разработке. \en Under development. + */ + virtual MbCurve3D * Trimmed( double t1, double t2, int sense, const MbDimAccuracy & xyzEps, bool saveParamLenAndLaw ) const; /// \ru Вернуть параметрическую длину кривой. \en Return the parametric length of a curve. double GetParamLength () const { return GetTMax() - GetTMin(); } @@ -1046,6 +1096,9 @@ public : double GetTRegion() const; /// \ru Дать минимально различимую величину параметра. \en Get the minimum distinguishable value of parameter. double GetTRegion( double t ) const; + /// \ru Дать минимально различимую величину параметра с заданной трехмерной точностью в зависимости от параметра. \en Get the minimum distinguishable value of parameter with the given three-dimensional accuracy according to parameter. + double GetTRegion( double t, const MbDimAccuracy & xyzEps ) const; + // \ru Геометрия подложки тождественна геометрии кривой, но отлична параметризация. \en The geometry of the a substrate is identical to the geometry of a curve, but parameterization differs. /// \ru Выдать подложку или себя. \en Get a substrate or itself. diff --git a/C3d/Include/function_factory.h b/C3d/Include/function_factory.h index 38edeb6..5c0b080 100644 --- a/C3d/Include/function_factory.h +++ b/C3d/Include/function_factory.h @@ -15,6 +15,7 @@ #include #include #include +#include class MATH_CLASS MbFunction; diff --git a/C3d/Include/mb_cube.h b/C3d/Include/mb_cube.h index 0e90800..2433959 100644 --- a/C3d/Include/mb_cube.h +++ b/C3d/Include/mb_cube.h @@ -417,6 +417,8 @@ public : \en Returns the distance to the boundary. \~ */ double DistanceToPoint( const MbCartPoint3D & point ) const; + /// \ru Вычислить квадрат расстояния до точки. \en Calculate the square of distance to a point. + double DistanceToPoint2( const MbCartPoint3D & point ) const; /** \brief \ru Вычислить расстояние до куба. \en Calculate the distance to the box. \~ @@ -865,4 +867,17 @@ double MbCube::DistanceToPoint( const MbCartPoint3D & pnt ) const } +//------------------------------------------------------------------------------ +// \ru Квадрат расстояния до точки \en The square of distance to a point +// --- +inline +double MbCube::DistanceToPoint2( const MbCartPoint3D & pnt ) const +{ + double dx = std_min( 0., std_min( pnt.x - pmin.x, pmax.x - pnt.x ) ); + double dy = std_min( 0., std_min( pnt.y - pmin.y, pmax.y - pnt.y ) ); + double dz = std_min( 0., std_min( pnt.z - pmin.z, pmax.z - pnt.z ) ); + return dx * dx + dy * dy + dz * dz; +} + + #endif // __MB_CUBE_H diff --git a/C3d/Include/mb_cube_tree.h b/C3d/Include/mb_cube_tree.h index 460c123..738fdfc 100644 --- a/C3d/Include/mb_cube_tree.h +++ b/C3d/Include/mb_cube_tree.h @@ -199,6 +199,9 @@ public: /// \ru Количество объектов в дереве (не хранит, считает обходом дерева). \en Number of objects in the tree (does not store, tree calculates it by traversing tree nodes). size_t Count() const; + /// \ru Количество узлов в дереве. \en Number of branches in the tree. + size_t NodeCount() const; + /// \ru Готово ли дерево. \en Whether tree is ready. bool IsReady() const; @@ -1062,6 +1065,36 @@ inline size_t MbCubeTree::Count() const } +//------------------------------------------------------------------------------- +// \ru Количество узлов в дереве. \en Number of branches in the tree. +// --- +template +inline size_t MbCubeTree::NodeCount() const +{ + size_t count = 0; + + std::vector stack; + stack.push_back( this ); + + while ( !stack.empty() ) { + const TypeTree * ptr = stack.back(); + stack.pop_back(); + ++count; + + if ( ptr->lowerBranch != nullptr ) + stack.push_back( ptr->lowerBranch ); + + if ( ptr->upperBranch != nullptr ) + stack.push_back( ptr->upperBranch ); + + if ( ptr->midstBranch != nullptr ) + stack.push_back( ptr->midstBranch ); + } + + return count; +} + + //------------------------------------------------------------------------------- // \ru Выдать содержащие точку объекты дерева. \en Get tree objects containing a point. // --- @@ -1747,29 +1780,25 @@ double MbCubeTree::FindNearestObject( const Point & const NodeElem node = queue.top(); // Первым рассматриваем узлы, наиболее близкие к точке. queue.pop(); - double d2 = node._ptr->branchCube.DistanceToPoint( pnt ); - d2 = d2 < 0. ? 0. : d2 * d2; + double d2 = node._ptr->branchCube.DistanceToPoint2( pnt ); if ( d2 > dist2 ) break; // Все оставшиеся узлы дальше уже найденного расстояния. if ( ( node._ptr->lowerBranch != nullptr ) || ( node._ptr->upperBranch != nullptr ) || ( node._ptr->midstBranch != nullptr ) ) { if ( node._ptr->lowerBranch != nullptr ) { - d2 = node._ptr->lowerBranch->branchCube.DistanceToPoint( pnt ); - d2 = d2 < 0. ? 0. : d2 * d2; + d2 = node._ptr->lowerBranch->branchCube.DistanceToPoint2( pnt ); if ( d2 < dist2 ) queue.push( NodeElem( node._ptr->lowerBranch, d2 ) ); } if ( node._ptr->upperBranch != nullptr ) { - d2 = node._ptr->upperBranch->branchCube.DistanceToPoint( pnt ); - d2 = d2 < 0. ? 0. : d2 * d2; + d2 = node._ptr->upperBranch->branchCube.DistanceToPoint2( pnt ); if ( d2 < dist2 ) queue.push( NodeElem( node._ptr->upperBranch, d2 ) ); } if ( node._ptr->midstBranch != nullptr ) { - d2 = node._ptr->midstBranch->branchCube.DistanceToPoint( pnt ); - d2 = d2 < 0. ? 0. : d2 * d2; + d2 = node._ptr->midstBranch->branchCube.DistanceToPoint2( pnt ); if ( d2 < dist2 ) queue.push( NodeElem( node._ptr->midstBranch, d2 ) ); } @@ -1777,10 +1806,13 @@ double MbCubeTree::FindNearestObject( const Point & else { // содержимое конечной ветви // terminal branch content for ( size_t i = 0, iCount = node._ptr->leafObjects.size(); i < iCount; ++i ) { const ItemIndex & obj = node._ptr->leafObjects[i]; - d2 = calc.DistanceToElement2( pnt, obj.second ); + d2 = obj.first->DistanceToPoint2( pnt ); if ( d2 < dist2 ) { - dist2 = d2; - index = obj.second; + d2 = calc.DistanceToElement2( pnt, obj.second ); + if ( d2 < dist2 ) { + dist2 = d2; + index = obj.second; + } } } } @@ -1788,4 +1820,5 @@ double MbCubeTree::FindNearestObject( const Point & return dist2; } + #endif diff --git a/C3d/Include/mb_dim_accuracy.h b/C3d/Include/mb_dim_accuracy.h new file mode 100644 index 0000000..0f6257f --- /dev/null +++ b/C3d/Include/mb_dim_accuracy.h @@ -0,0 +1,125 @@ +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru N-мерная точность. + \en N-dimensional accuracy. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __MB_DIM_ACCURACY_H +#define __MB_DIM_ACCURACY_H + +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru N-мерная точность. + \en N-dimensional accuracy. \~ + \details \ru N-мерная точность задается N положительными числами. + Наиболее востребованы двумерная и трехмерная точности. + Компоненты точности в этих случаях соответствуют точностям вдоль осей x, y и z. + Двумерная точность может использоваться, например, при выполнении операций над + двумерными кривыми MbCurve. В этом случае компоненты точности будут расcчитываться + с использованием методов GetUEpsilon() и GetVEpsilon(), вызванных для + поверхности (MbSurface) на которой лежит данная кривая. + \en N-dimensional accuracy is specified by N positive numbers. + Two-dimensional and three-dimensional accuracies are the most demanded. + Components of accuracy in these cases correspond to accuracies along x, y and z axes. + Two-dimensional precision can be used, for example, when performing operations on two-dimensional MbCurve curves. + In this case, the accuracy components will be calculated using + the GetUEpsilon() and GetVEpsilon() methods called + for the surface (MbSurface) on which the curve lies. \~ + \ingroup Legend + \warning \ru В разработке. \en Under development. +*/ +// --- + +class MATH_CLASS MbDimAccuracy +{ +private : + c3d::DoubleVector _epsilon; ///< \ru Вектор N-мерной точности. \en N-dimensional accuracy vector. + +public : + /// \ru Двумерная точность по умолчанию - ( PARAM_EPSILON, PARAM_EPSILON ) \en Default two-dimensional accuracy - ( PARAM_EPSILON, PARAM_EPSILON ) + static const MbDimAccuracy twoDimAcc; + /// \ru Двумерная точность по умолчанию - ( METRIC_REGION, METRIC_REGION ) \en Default two-dimensional accuracy - ( METRIC_REGION, METRIC_REGION ) + static const MbDimAccuracy twoDimRgn; + /// \ru Трехмерная точность по умолчанию - ( METRIC_EPSILON, METRIC_EPSILON, METRIC_EPSILON ) \en Default three-dimensional accuracy - ( METRIC_EPSILON, METRIC_EPSILON, METRIC_EPSILON ) + static const MbDimAccuracy threeDimAcc; + + +public : + /** \brief \ru Конструктор для двумерной точности по двум значениям. + \en Сonstructor for two-dimensional accuracy on the three values. \~ + \details \ru Конструктор для двумерной точности по двум значениям. + Если передаваемые компоненты точности меньше, чем 'DOUBLE_EPSILON', + то этим значениям присваивается 'DOUBLE_EPSILON'. + \en Constructor for two-dimensional accuracy on two values. + If the passed accuracy components are smaller than the 'DOUBLE_EPSILON', + then the value of 'DOUBLE_EPSILON' is assigned to these components. + \param[in] xEps - \ru Точность по оси x. + \en x-axis accuracy. \~ + \param[in] yEps - \ru Точность по оси y. + \en y-axis accuracy. \~ + */ + MbDimAccuracy( double xEps, double yEps ); + + /** \brief \ru Конструктор для трехмерной точности по трем значениям. + \en Сonstructor for two-dimensional accuracy on the three values. \~ + \details \ru Конструктор для трехмерной точности по трем значениям. + Если передаваемые компоненты точности меньше, чем 'DOUBLE_EPSILON', + то этим значениям присваивается 'DOUBLE_EPSILON'. + \en Constructor for three-dimensional accuracy on three values. + If the passed accuracy components are smaller than the 'DOUBLE_EPSILON', + then the value of 'DOUBLE_EPSILON' is assigned to these components. + \param[in] xEps - \ru Точность по оси x. + \en x-axis accuracy. \~ + \param[in] yEps - \ru Точность по оси y. + \en y-axis accuracy. \~ + \param[in] zEps - \ru Точность по оси z. + \en z-axis accuracy. \~ + */ + MbDimAccuracy( double xEps, double yEps, double zEps ); + + /** \brief \ru Конструктор N-мерной точности по вектору значений. + \en Constructor of N-dimensional accuracy on a vector of values. \~ + \details \ru Конструктор N-мерной точности по вектору значений. + Если вектор пустой, то создаётся одномерная точность c компонентой равной 'DOUBLE_EPSILON'. + \en Constructor of N-dimensional accuracy on a vector of values. + If the vector is empty, a one-dimensional accuracy with component equal to 'DOUBLE_EPSILON' is returned. \~ + \param[in] vector - \ru Вектор с компонентами N-мерной точности + \en Vector with components of N-dimensional accuracy. \~ + */ + template + MbDimAccuracy( const Vector & vector ); + + /// \ru Конструктор копирования. \en The copy constructor. + explicit MbDimAccuracy( const MbDimAccuracy & acc ) : _epsilon( acc.GetEpsilon() ) {} + + /// \ru Конструктор по умолчанию удалён. \en Default constructor explicitly deleted. + MbDimAccuracy() = delete; + + /// \ru Деструктор. \en Destructor. + ~MbDimAccuracy() {} + +public: // Общие методы + size_t GetDimension() const { return _epsilon.size(); } ///< \ru Дать размерность точности. \en Get the accuracy dimension. + + /// \ru Дать вектор с компонентами точности. \en Get a vector with accuracy components. + const c3d::DoubleVector & GetEpsilon() const { return _epsilon; } + + /// \ru Вернуть значение минимальной компоненты точности. \en Return the value of the minimum accuracy component. + double GetMin() const; + + /// \ru Доступ к компонентe точности по индексу. \en Access to accuracy component by index. + double & operator [] ( size_t i ); + /// \ru Значение компоненты точности по индексу. \en The value of accuracy component by index. + double operator [] ( size_t i ) const; + + /// \ru Присвоить точности значение другой точности. \en Assign the value of another accuracy to the accuracy. + MbDimAccuracy & operator = ( const MbDimAccuracy & ); +}; + +#endif // __MB_DIM_ACCURACY_H diff --git a/C3d/Include/mb_matrix.h b/C3d/Include/mb_matrix.h index ab25afc..d71111d 100644 --- a/C3d/Include/mb_matrix.h +++ b/C3d/Include/mb_matrix.h @@ -12,6 +12,7 @@ #include +#include #include #include @@ -24,9 +25,9 @@ class MATH_CLASS MbHomogeneous; template -void CheckOrigin ( const Transform & trans, uint8 & flag, bool resetFlag ); +void CheckOrigin ( const Transform & trans, atomic_uint8 & flag, bool resetFlag ); template -void CheckRotation( const Transform & trans, uint8 & flag, bool resetFlag ); +void CheckRotation( const Transform & trans, atomic_uint8 & flag, bool resetFlag ); //------------------------------------------------------------------------------ @@ -106,7 +107,7 @@ private: DO NOT USE "Get..." METHODS TO MODIFY MATRIX ELEMENTS BY RENAMING const TO non-const, USE ONLY Get* AND Set* TO ACCESS AND MODIFY OF MATRIX DATA. \~ */ - mutable uint8 flag; + mutable atomic_uint8 flag; public: static const MbMatrix identity; ///< \ru Единичная матрица, I = diag(1,1,1); \en Identity matrix, I = diag(1,1,1); @@ -115,7 +116,7 @@ public : /// \ru Конструктор по умолчанию. \en Default constructor. MbMatrix() : flag( MB_UNSET ) { Init(); } /// \ru Конструктор копирования. \en Copy constructor. - MbMatrix( const MbMatrix & init ) : flag( init.flag ) { ::memcpy( &el, init.el, sizeof(el) ); } + MbMatrix( const MbMatrix & init ) : flag( init.flag.load() ) { ::memcpy( &el, init.el, sizeof(el) ); } /// \ru Конструктор по локальной системе координат. \en The constructor by placement. explicit MbMatrix( const MbPlacement & place ) : flag( MB_UNSET ) { Set( place ); } public: @@ -560,7 +561,7 @@ public: /// \ru Домножить на матрицу справа. \en Multiply by the matrix on the right. MbMatrix & operator *= ( const MbMatrix & m ) { return PostMultiply( m ); } /// \ru Присвоить значение. \en Assign a value. - MbMatrix & operator = ( const MbMatrix & m ) { flag = m.flag; ::memcpy( &el, m.el, sizeof(el) ); return *this; } + MbMatrix & operator = ( const MbMatrix & m ) { flag = m.flag.load(); ::memcpy( &el, m.el, sizeof(el) ); return *this; } /// \ru Сравнить с матрицей (точность - LENGTH_EPSILON). \en Compare with a matrix(tolerance- LENGTH_EPSILON). bool operator == ( const MbMatrix & ) const; @@ -580,7 +581,7 @@ private: /// \ru Выставить флаги. \en Set flags. uint8 ResetFlag() const; // Оценить флаги, если оценки не было - uint8 CheckFlag() const { return IsUnSet() ? ResetFlag() : flag; } + uint8 CheckFlag() const { return IsUnSet() ? ResetFlag() : flag.load(); } // Проверить флаг смещения. void CheckOrigin() const { ::CheckOrigin( *this, flag, true ); } // \ru Проверить флаг вращения. \en Check rotation flag. @@ -601,19 +602,21 @@ public: */ // --- template -void CheckOrigin( const Transform & trans, uint8 & flag, bool resetFlag ) +void CheckOrigin( const Transform & trans, atomic_uint8 & flag, bool resetFlag ) { - if ( !(flag & MB_UNSET) ) { + uint8 val = flag.load(); + if ( !(val & MB_UNSET) ) { const MbCartPoint & pOrigin = trans.GetOrigin(); const double lengthEpsilon = LENGTH_EPSILON; if ( (::fabs(pOrigin.x) > lengthEpsilon) || (::fabs(pOrigin.y) > lengthEpsilon) ) - flag |= MB_TRANSLATION; + val |= MB_TRANSLATION; else if ( resetFlag ) { - flag &= ~MB_TRANSLATION; + val &= ~MB_TRANSLATION; } } + flag = val; } @@ -626,9 +629,10 @@ void CheckOrigin( const Transform & trans, uint8 & flag, bool resetFlag ) */ // --- template -void CheckRotation( const Transform & trans, uint8 & flag, bool resetFlag ) +void CheckRotation( const Transform & trans, atomic_uint8 & flag, bool resetFlag ) { - if ( !(flag & MB_UNSET) ) { + uint8 val = flag.load(); + if ( !(val & MB_UNSET) ) { const MbVector & axisX = trans.GetAxisX(); const MbVector & axisY = trans.GetAxisY(); @@ -639,15 +643,16 @@ void CheckRotation( const Transform & trans, uint8 & flag, bool resetFlag ) ::fabs(axisX.x - 1.0) > eps || ::fabs(axisY.y - 1.0) > eps ) { - flag |= MB_ROTATION; + val |= MB_ROTATION; } else if ( resetFlag ) { - flag &= ~MB_ROTATION; - flag &= ~MB_LEFT; - flag &= ~MB_ORTOGONAL; - flag &= ~MB_AFFINE; + val &= ~MB_ROTATION; + val &= ~MB_LEFT; + val &= ~MB_ORTOGONAL; + val &= ~MB_AFFINE; } } + flag = val; } diff --git a/C3d/Include/mb_nurbs_function.h b/C3d/Include/mb_nurbs_function.h index 70f7c59..95ca471 100644 --- a/C3d/Include/mb_nurbs_function.h +++ b/C3d/Include/mb_nurbs_function.h @@ -64,6 +64,7 @@ private: int sense; ///< \ru Направление сплайн-кривой. \en Direction of spline-curve. bool matchParams; ///< \ru Сохранять ли при преобразовании однозначное соответствие параметрических областей. \en Whether to save correspondence of parametric regions while transforming or not. bool extendRange; ///< \ru Строится ли преобразование на продолжении для незамкнутой подложки. \en Whether transformation is constructed on the extension for a non-closed substrate. + double tRegion; ///< \ru Параметрическая точность. \en Parametric accuracy. VERSION version; ///< \ru Версия исполнения. \en The version of execution. private: MbCurveIntoNurbsInfo(); @@ -71,29 +72,42 @@ public: /// \ru Конструктор. \en Constructor. template MbCurveIntoNurbsInfo( const Curve & c, bool match, bool ext, VERSION ver = Math::DefaultMathVersion() ) - : tbeg ( c.GetTMin() ) - , tend ( c.GetTMax() ) - , sense ( 1 ) - , matchParams( match ) - , extendRange( ext ) - , version ( ver ) + : tbeg ( c.GetTMin() ) + , tend ( c.GetTMax() ) + , sense ( 1 ) + , matchParams( match ) + , extendRange( ext ) + , tRegion ( PARAM_EPSILON ) + , version ( ver ) {} /// \ru Конструктор. \en Constructor. MbCurveIntoNurbsInfo( double t1, double t2, int s, bool match, bool ext, VERSION ver = Math::DefaultMathVersion() ) - : tbeg ( t1 ) - , tend ( t2 ) - , sense ( s ) - , matchParams( match ) - , extendRange( ext ) - , version ( ver ) + : tbeg ( t1 ) + , tend ( t2 ) + , sense ( s ) + , matchParams( match ) + , extendRange( ext ) + , tRegion ( PARAM_EPSILON ) + , version ( ver ) + {} + /// \ru Конструктор. \en Constructor. + MbCurveIntoNurbsInfo( double t1, double t2, int s, bool match, bool ext, double tRegion, VERSION ver = Math::DefaultMathVersion() ) + : tbeg ( t1 ) + , tend ( t2 ) + , sense ( s ) + , matchParams( match ) + , extendRange( ext ) + , tRegion ( tRegion ) + , version ( ver ) {} /// \ru Конструктор. \en Constructor. MbCurveIntoNurbsInfo( const MbCurveIntoNurbsInfo & other, double t1, double t2, int s ) - : tbeg ( t1 ) - , tend ( t2 ) - , sense ( s ) + : tbeg ( t1 ) + , tend ( t2 ) + , sense ( s ) , matchParams( other.matchParams ) , extendRange( other.extendRange ) + , tRegion ( PARAM_EPSILON ) , version ( other.version ) {} /// \ru Функция присвоения. \en Assignment function. @@ -135,6 +149,8 @@ public: bool ExtendRange() const { return extendRange; } /// \ru Получить версию исполнения. \en Get the version of execution. VERSION GetMathVersion() const { return version; } + /// \ru Получить парметрическую точность. \en Get the parametric accuracy. + double GetTRegion() const { return tRegion; } OBVIOUS_PRIVATE_COPY( MbCurveIntoNurbsInfo ) }; @@ -2640,7 +2656,7 @@ Nurbs * CreateLineOutRgn( const Curve & curve, double tn1, double tn2, double t1 { Nurbs * nurbs = nullptr; - if ( !curve.IsClosed() && nci.ExtendRange() && ((tn2 - tn1) > Math::paramEpsilon) ) { + if ( !curve.IsClosed() && nci.ExtendRange() && ((tn2 - tn1) > nci.GetTRegion()) ) { SArray points ( 2, 1 ); SArray weights( 2, 1 ); SArray knots ( 4, 1 ); //-V112 diff --git a/C3d/Include/mb_placement.h b/C3d/Include/mb_placement.h index 5dedafb..705a9ac 100644 --- a/C3d/Include/mb_placement.h +++ b/C3d/Include/mb_placement.h @@ -10,6 +10,7 @@ #include #include +#include //---------------------------------------------------------------------------------------- @@ -71,7 +72,7 @@ private: 'flag' has to be reset to unspecified MB_UNSET state while changing the coordinate system. \n if 'flag' == MB_UNSET then the state of coordinate system is specified while it is being used.\n \~ */ - mutable uint8 flag; + mutable atomic_uint8 flag; public : /// \ru Конструктор по умолчанию. \en Default constructor. @@ -239,7 +240,7 @@ private: /// \ru Выставить флаги. \en Set flags. uint8 ResetFlag() const; // Оценить флаги, если оценки не было - uint8 CheckFlag() const { return IsUnSet() ? ResetFlag() : flag; } + uint8 CheckFlag() const { return IsUnSet() ? ResetFlag() : flag.load(); } // Проверить флаг смещения. void CheckOrigin() const { ::CheckOrigin( *this, flag, true ); } // \ru Проверить флаг вращения. \en Check rotation flag. @@ -270,7 +271,7 @@ inline MbPlacement::MbPlacement( const MbPlacement & other ) : origin( other.origin ) // начало координат , axisX ( other.axisX ) // направление оси 0X , axisY ( other.axisY ) // направление оси 0Y - , flag ( other.flag ) + , flag ( other.flag.load() ) { } @@ -385,7 +386,7 @@ inline void MbPlacement::operator = ( const MbPlacement & other ) origin = other.origin; // \ru Начало координат \en The origin axisX = other.axisX; // \ru Направление оси 0X \en Direction of 0X-axis axisY = other.axisY; // \ru Направление оси 0Y \en Direction of 0Y-axis - flag = other.flag; + flag = other.flag.load(); } diff --git a/C3d/Include/mb_pmi.h b/C3d/Include/mb_pmi.h index e750066..aaf6efe 100644 --- a/C3d/Include/mb_pmi.h +++ b/C3d/Include/mb_pmi.h @@ -20,6 +20,7 @@ #include #include #include +#include //---------------------------------------------------------------------------------------- /** \brief \ru Элемент текста объекта аннотации. @@ -409,6 +410,9 @@ public: /// \ru Являются ли объекты равными. \en Are the objects equal. bool IsSame( const MbTerminator & to, double accuracy ) const; + /// \ru Создать копию объекта. \en Create a copy of an object. + SPtr Clone() const; + DECLARE_PERSISTENT_CLASS( MbTerminator ) }; @@ -471,6 +475,9 @@ public: \en Type of callout curve. \~ */ MbeCalloutCurveType GetCurveType() const; + + /// \ru Создать копию объекта. \en Create a copy of an object. + SPtr Clone( MbRegDuplicate * = nullptr ) const; /// \ru Являются ли объекты равными. \en Are the objects equal. bool IsSame( const MbCalloutCurve & to, double accuracy ) const; @@ -494,7 +501,8 @@ class MATH_CLASS MbNumericalCharacteristic final : public MbRefItem, public Tape MbValueRange m_valueWithRange; ///< \ru Численные значения. \en Numerical values. MbeNumericCharacteristicType m_CharacteristicType; ///< \ru Тип характеристики. \en Type of characteristics. std::vector> m_callouts; ///< \ru Линии выноски. \en Callout lines. - + SPtr path; ///< \ru Кривая, вдоль которой проводится измерение. Если не задана, то размер есть кратчайший. \en A curve along which the measurement is performed. If not specified, then the size is shortest. + /** \brief \ru Конструктор. \en Constructor. \~ \param[in] type - \ru Тип характеристики, @@ -583,6 +591,15 @@ public: /// \ru Являются ли объекты равными. \en Are the objects equal. bool IsSame( const MbNumericalCharacteristic & to, double accuracy ) const; + /// \ru Задать кривую, вдоль которой проводится измерение. \en Set the curve the measurement is performed along. + void SetPath( MbCurve3D * inPath ); + + /// \ru Получить кривую, вдоль которой проводится измерение. \en Get the curve the measurement is performed along. + SPtr GetPath() const; + + /// \ru Создать копию объекта. \en Create a copy of an object. + SPtr Clone( MbRegDuplicate * = nullptr ) const; + DECLARE_PERSISTENT_CLASS( MbNumericalCharacteristic ) }; @@ -739,6 +756,15 @@ protected: \en Text items ot the annotation element. \~ */ MbPMI( MbePMIType pmiType, const MbPlacement3D & plane, const c3d::string_t & pmiName, SPtr, c3d::ItemsSPtrVector &&, std::vector> && pmiText ); + + /** \brief \ru Конструктор глубокого копирования. + \en Deepcoly constructor. \~ + \param[in] init - \ru Копируемый образец, + \en Item to copy, \~ + \param[in] iReg - \ru Регистратор дублей. + \en Replica registry. \~ + */ + explicit MbPMI( const MbPMI & init, MbRegDuplicate * iReg = nullptr ); public: /// \ru Получить тип элемента аннотации. \en Get PMI type. @@ -798,7 +824,6 @@ public: DECLARE_PERSISTENT_CLASS( MbPMI ) private: - MbPMI( const MbPMI& ); const MbPMI& operator=( const MbPMI & ) = delete; }; diff --git a/C3d/Include/mb_property_title.h b/C3d/Include/mb_property_title.h index 2daab64..de9a36c 100644 --- a/C3d/Include/mb_property_title.h +++ b/C3d/Include/mb_property_title.h @@ -173,6 +173,8 @@ enum MbePrompt IDS_ITEM_0272, ///< \ru Скругленный каркас. \en Filleted wire frame. IDS_ITEM_0273, ///< \ru NURBS-копия каркаса. \en Nurbs-copy by wire frame. IDS_ITEM_0274, ///< \ru Усеченный каркас. \en Trimmed wire frame. + IDS_ITEM_0275, ///< \ru Развернутая точка. \en Unwrapped point. + IDS_ITEM_0276, ///< \ru Свёрнутая точка. \en Wrapped point. // \ru Типы параметрических поверхностей. \en Types of parametric surfaces. @@ -1139,7 +1141,7 @@ enum MbePrompt IDS_PROP_0879, ///< \ru Видимость. \en Visibility. IDS_PROP_0880, ///< \ru Изменённость. \en Modified. IDS_PROP_0881, ///< \ru Общий фон. \en Background. - IDS_PROP_0882, ///< \ru Диффузное отражение. \en Diffuse reflection. + IDS_PROP_0882, ///< \ru Диффузное отражение (компонент red). \en Diffuse reflection (red component). IDS_PROP_0883, ///< \ru Зеркальное отражение. \en Specular reflection. IDS_PROP_0884, ///< \ru Блеск. \en Shininess. IDS_PROP_0885, ///< \ru Непрозрачность. \en Opacity. @@ -1149,6 +1151,9 @@ enum MbePrompt IDS_PROP_0889, ///< \ru Имя топологического объекта. \en Topological object name. IDS_PROP_0890, ///< \ru Имя объекта. \en Object name. IDS_PROP_0891, ///< \ru Хэш имени объекта. \en Object name hash. + IDS_PROP_0892, ///< \ru Диффузное отражение (компонент green). \en Diffuse reflection (green component). + IDS_PROP_0893, ///< \ru Диффузное отражение (компонент blue). \en Diffuse reflection (blue component). + IDS_PROP_0894, ///< \ru Диффузное отражение (компонент alpha). \en Diffuse reflection (alpha component). IDS_PROP_0900, ///< \ru Сопряжение в точке. \en Conjugation at point. IDS_PROP_0901, ///< \ru Тип сопряжения. \en Conjugation type. diff --git a/C3d/Include/mb_rect.h b/C3d/Include/mb_rect.h index e4404c2..69a8fd2 100644 --- a/C3d/Include/mb_rect.h +++ b/C3d/Include/mb_rect.h @@ -214,6 +214,8 @@ public: /// \ru Вычислить расстояние до точки. \en Calculate the distance to a point. double DistanceToPoint( const MbCartPoint & to, uint & outcodes ) const; + /// \ru Вычислить квадрат расстояния до точки. \en Calculate the square of distance to a point. + double DistanceToPoint2( const MbCartPoint & pnt ) const; /** \brief \ru Вычислить расстояние до куба. \en Calculate the distance to the cube. \~ @@ -583,6 +585,18 @@ double MbRect::DistanceToPoint( const MbCartPoint & pnt ) const } +//------------------------------------------------------------------------------ +// \ru Квадрат расстояния до точки \en square of distance to a point +// --- +inline +double MbRect::DistanceToPoint2( const MbCartPoint & pnt ) const +{ + double dx = std_min( 0., std_min( pnt.x - left, right - pnt.x ) ); + double dy = std_min( 0., std_min( pnt.y - bottom, top - pnt.y ) ); + return dx * dx + dy * dy; +} + + //------------------------------------------------------------------------------ // \ru Расстояние до точки \en Distance to a point // --- diff --git a/C3d/Include/mesh_primitive.h b/C3d/Include/mesh_primitive.h index 60f3069..02c0a28 100644 --- a/C3d/Include/mesh_primitive.h +++ b/C3d/Include/mesh_primitive.h @@ -1188,7 +1188,7 @@ public: /// \ru Готово ли дерево поиска элементов. \en Whether is elements search tree ready. bool IsSearchTreeReady() const; /// \ru Создать дерево поиска элементов. \en Create elements search tree. - bool CreateSearchTree() const; + bool CreateSearchTree( size_t leafElemCount = 100 ) const; /// \ru Удалить дерево поиска элементов. \en Delete elements search tree. void DeleteSearchTree() const; /** \brief \ru Найти индексы треугольников и четырехугольников, потенциально пересекающихся с лучом. diff --git a/C3d/Include/op_curve_parameter.h b/C3d/Include/op_curve_parameter.h index bad6eaf..7059b8a 100644 --- a/C3d/Include/op_curve_parameter.h +++ b/C3d/Include/op_curve_parameter.h @@ -1190,8 +1190,8 @@ public: //------------------------------------------------------------------------------ -/** \brief \ru Параметры для переноса копий двумерных кривых на другой носитель. - \en Parameters for transferring copies of two-dimensional curves on another medium. \~ +/** \brief \ru Параметры для переноса копий двумерных кривых и точек на другой носитель. + \en Parameters for transferring copies of two-dimensional curves and points on another medium. \~ \details \ru Точка xy плоскости XY локальной системы координат должна совпадать с точкой uv параметрической области UV поверхности. При параметрах angle = 0 и sense = true наложение плоскости на поверхность @@ -1208,77 +1208,71 @@ public: to the 'v' surface axis, with 'x' and 'u' axes directed oppositely. Then the value of 'angle' shows how much the plane coordinate system XY is turned in respect to its Z axis. \n \~ \ingroup Curve3D_Building_Parameters -*/ // --- +*/ +// --- class MATH_CLASS MbCurvesWrappingParams : public MbPrecision { private: - c3d::ConstPlaneCurvesSPtrVector curves; ///< \ru Двумерные кривые, копии которых будут перенесены на другой носитель. \en 2d curves, copies of which will be transferred to another medium. \~ - c3d::SurfaceSPtr surface; ///< \ru Поверхность. \en The surface. \~ - MbPlacement3D place; ///< \ru Локальная система координат (ЛСК). \en The local coordinate system (LCS) of the curves. \~ - MbCartPoint xy; ///< \ru Точка привязки на плоскости XY локальной системы координат. \en The anchor point on the "XY" plane of the LCS that will be aligned with the uv point on the parametric plane of the surface. \~ - MbCartPoint uv; ///< \ru Точка привязки в параметрической плоскости "UV" параметров поверхности. \en The anchor point in the parametric plane "UV" of the surface parameters. \~ - double angle; ///< \ru Угол поворота плоскости "XY" ЛСК и параметрической плоскости "UV" поверхности. \en The angle of rotation of the LSC "XY" plane and the parametric "UV" plane of the surface. \~ - bool sense; ///< \ru Совпадают ли направления оси "X" ЛСК и оси "U" поверхности? \en Whether the directions of the "X" axis of the LSC and the "U" axis of the surface coincide? \~ - bool equals; ///< \ru Должны ли длины кривых на другом носителе соответствовать оригиналам? \en Should the lengths of the curves on another medium match the originals? \~ - bool uSeamStitch; ///< \ru Нужно ли сдвинуть кривые, попавшие краем на шов umax. \en Whether to shift curves with one end on umax seam. \~ - VERSION version; ///< \ru Версия алгоритма. \en Algorithm version. \~ + c3d::ConstPlaneCurvesSPtrVector _curves; ///< \ru Двумерные кривые, копии которых будут перенесены на другой носитель. \en 2d curves, copies of which will be transferred to another medium. \~ + c3d::ParamPointsVector _points; ///< \ru Двумерные точки, копии которых будут перенесены на другой носитель. \en 2d points, copies of which will be transferred to another medium. \~ + c3d::SurfaceSPtr _surface; ///< \ru Поверхность. \en The surface. \~ + c3d::SNameMakerSPtr _snMaker; ///< \ru Именователь с версией операции. Всегда не nullptr. \en Names maker with operation version. It cannot be nullptr. + MbPlacement3D _place; ///< \ru Локальная система координат (ЛСК). \en The local coordinate system (LCS) of the curves. \~ + MbCartPoint _xy; ///< \ru Точка привязки на плоскости XY локальной системы координат. \en The anchor point on the "XY" plane of the LCS that will be aligned with the uv point on the parametric plane of the surface. \~ + MbCartPoint _uv; ///< \ru Точка привязки в параметрической плоскости "UV" параметров поверхности. \en The anchor point in the parametric plane "UV" of the surface parameters. \~ + double _angle; ///< \ru Угол поворота плоскости "XY" ЛСК и параметрической плоскости "UV" поверхности. \en The angle of rotation of the LSC "XY" plane and the parametric "UV" plane of the surface. \~ + bool _sense; ///< \ru Совпадают ли направления оси "X" ЛСК и оси "U" поверхности? \en Whether the directions of the "X" axis of the LSC and the "U" axis of the surface coincide? \~ + bool _keepLength; ///< \ru Должны ли длины кривых на другом носителе соответствовать оригиналам? \en Should the lengths of the curves on another medium match the originals? \~ + bool _uSeamStitch; ///< \ru Нужно ли сдвинуть кривые, попавшие краем на шов umax. \en Whether to shift curves with one end on umax seam. \~ private: - /** \brief \ru Закрытый конструктор по-умолчанию. - \en Default private constructor. \~ - \details \ru Закрытый конструктор по-умолчанию. - \en Default private constructor. \~ + /** \brief \ru Конструктор по-умолчанию. Не реализован. + \en Default private constructor. Not implemented. \~ + \details \ru Конструктор по-умолчанию. Не реализован. + \en Default private constructor. Not implemented. \~ */ MbCurvesWrappingParams(); - /** \brief \ru Конструктор копирования, копирует кривые и поверхности. - \en Copy constructor, copies curves and surfaces.\~ - \details \ru Конструктор копирования, копирует кривые и поверхности. - \en Copy constructor, copies curves and surfaces.\~ - */ - MbCurvesWrappingParams( const MbCurvesWrappingParams & other ); + /** \brief \ru Конструктор без кривых. \en Constructor with no curves.\~ \details \ru Конструктор без кривых. \en Constructor with no curves.\~ - \param[in] place_ - \ru Локальная система координат (ЛСК) плоскости. + \param[in] place - \ru Локальная система координат (ЛСК) плоскости. \en The local coordinate system (LCS) of the plane. \~ - \param[in] xy_ - \ru Точка привязки на плоскости, которая будет привязана к uv-точке на поверхности. + \param[in] xy - \ru Точка привязки на плоскости, которая будет привязана к uv-точке на поверхности. \en The anchor point on the plane that will be aligned with the uv point on the parametric plane of the surface. \~ - \param[in] surface_ - \ru Поверхность для сворачивания/разворачивания. + \param[in] surface - \ru Поверхность для сворачивания/разворачивания. \en The surface to wrap to/unwrap from. \~ - \param[in] uv_ - \ru Точка привязки на поверхности в параметрической плоскости "UV". Будет привязана к xy-точке на плоскости. + \param[in] uv - \ru Точка привязки на поверхности в параметрической плоскости "UV". Будет привязана к xy-точке на плоскости. \en The anchor uv point on the parametric plane of the surface that will be aligned with the xy point on the plane.\~ - \param[in] angle_ - \ru Угол поворота плоскости "XY" ЛСК и параметрической плоскости "UV" поверхности. + \param[in] operNames - \ru Именователь с версией операции. + \en Names maker with operation version. \~ + \param[in] angle - \ru Угол поворота плоскости "XY" ЛСК и параметрической плоскости "UV" поверхности. \en The angle of rotation of the LSC "XY" plane and the parametric "UV" plane of the surface. \~ - \param[in] sense_ - \ru Совпадают ли направления оси "X" ЛСК и оси "U" поверхности. + \param[in] sense - \ru Совпадают ли направления оси "X" ЛСК и оси "U" поверхности. \en Whether the directions of the "X" axis of the LSC and the "U" axis of the surface coincide? \~ - \param[in] equals_ - \ru Должны ли длины кривых на другом носителе соответствовать оригиналам. + \param[in] keepLength - \ru Должны ли длины кривых на другом носителе соответствовать оригиналам. \en Should the lengths of the curves on another medium match the originals?\~ - \param[in] accuracy_ - \ru Точность построения. + \param[in] accuracy - \ru Точность построения. \en The accuracy. \~ - \param[in] copyCurves_ - \ru Сохранить ли в этом классе параметров копии кривых. - \en Whether to save the curves copies in this parameter class. \~ - \param[in] copySurface_ - \ru Сохранить ли в классе параметров копию поверхности. + \param[in] copySurface - \ru Сохранить ли в классе параметров копию поверхности. \en Whether to save the surface copy in this parameter class. \~ - \param[in] ver_ - \ru Версия алгоритма. - \en The version. \~ */ - MbCurvesWrappingParams( const MbPlacement3D & place_, - const MbCartPoint & xy_, - const MbSurface & surface_, - const MbCartPoint & uv_, - double angle_, - bool sense_, - bool equals_, - double accuracy_, - bool , - bool copySurface_, - VERSION ver_ ); + MbCurvesWrappingParams( const MbPlacement3D & place, + const MbCartPoint & xy, + const MbSurface & surface, + const MbCartPoint & uv, + const MbSNameMaker & operNames, + double angle, + bool sense, + bool keepLength, + double accuracy, + bool copySurface ); public: - /** \brief \ru Конструктор. - \en Constructor.\~ - \details \ru Конструктор. - \en Constructor.\~ + /** \brief \ru Конструктор по кривым. + \en Constructor by curves.\~ + \details \ru Конструктор по кривым. + \en Constructor by curves.\~ \param[in] curves_ - \ru Двумерные кривые, копии которых будут свёрнуты/развёрнуты. \en 2d curves, copies of which will be wrapped/unwrapped. \~ \param[in] place_ - \ru Локальная система координат (ЛСК) плоскости. @@ -1303,7 +1297,9 @@ public: \en Whether to save the surface copy in this parameter class. \~ \param[in] ver_ - \ru Версия алгоритма. \en The version. \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ */ + DEPRECATE_DECLARE_REPLACE( MbCurvesWrappingParams with MbSNameMaker ) MbCurvesWrappingParams( const c3d::PlaneCurvesSPtrVector & curves_, const MbPlacement3D & place_, const MbCartPoint & xy_, @@ -1318,54 +1314,11 @@ public: VERSION ver_ ); - /** \brief \ru Конструктор. - \en Constructor.\~ - \details \ru Конструктор. - \en Constructor.\~ - \param[in] curves_ - \ru 3d кривые, копии которых будут свёрнуты/развёрнуты. Ожидается, что внутри -- 2д кривые на поверхности. - \en 3d curves, copies of which will be wrapped/unwrapped. It is expected that there are 2d curves on surface inside.\~ - \param[in] place_ - \ru Локальная система координат (ЛСК) плоскости. - \en The local coordinate system (LCS) of the plane. \~ - \param[in] xy_ - \ru Точка привязки на плоскости, которая будет привязана к uv-точке на поверхности. - \en The anchor point on the plane that will be aligned with the uv point on the parametric plane of the surface. \~ - \param[in] surface_ - \ru Поверхность для сворачивания/разворачивания. - \en The surface to wrap to/unwrap from. \~ - \param[in] uv_ - \ru Точка привязки на поверхности в параметрической плоскости "UV". Будет привязана к xy-точке на плоскости. - \en The anchor uv point on the parametric plane of the surface that will be aligned with the xy point on the plane.\~ - \param[in] angle_ - \ru Угол поворота плоскости "XY" ЛСК и параметрической плоскости "UV" поверхности. - \en The angle of rotation of the LSC "XY" plane and the parametric "UV" plane of the surface. \~ - \param[in] sense_ - \ru Совпадают ли направления оси "X" ЛСК и оси "U" поверхности. - \en Whether the directions of the "X" axis of the LSC and the "U" axis of the surface coincide? \~ - \param[in] equals_ - \ru Должны ли длины кривых на другом носителе соответствовать оригиналам. - \en Should the lengths of the curves on another medium match the originals?\~ - \param[in] accuracy_ - \ru Точность построения. - \en The accuracy. \~ - \param[in] copyCurves_ - \ru Сохранить ли в этом классе параметров копии кривых. - \en Whether to save the curves copies in this parameter class. \~ - \param[in] copySurface_ - \ru Сохранить ли в классе параметров копию поверхности. - \en Whether to save the surface copy in this parameter class. \~ - \param[in] ver_ - \ru Версия алгоритма. - \en The version. \~ - */ - MbCurvesWrappingParams( const c3d::ConstPlaneCurvesSPtrVector & curves_, - const MbPlacement3D & place_, - const MbCartPoint & xy_, - const MbSurface & surface_, - const MbCartPoint & uv_, - double angle_, - bool sense_, - bool equals_, - double accuracy_, - bool copyCurves_, - bool copySurface_, - VERSION ver_ ); - - - /** \brief \ru Конструктор. - \en Constructor.\~ - \details \ru Конструктор. - \en Constructor.\~ - \param[in] curves_ - \ru 3д кривые, копии которых будут свёрнуты/развёрнуты. Ожидается, что внутри -- 2д кривые на поверхности. + /** \brief \ru Конструктор по кривым. + \en Constructor by curves.\~ + \details \ru Конструктор по кривым. + \en Constructor by curves.\~ + \param[in] curves_ - \ru 2d кривые, копии которых будут свёрнуты/развёрнуты. Ожидается, что внутри -- 2д кривые на поверхности. \en 2d curves, copies of which will be wrapped/unwrapped. It is expected that there are 2d curves on surface inside.\~ \param[in] place_ - \ru Локальная система координат (ЛСК) плоскости. \en The local coordinate system (LCS) of the plane. \~ @@ -1389,8 +1342,10 @@ public: \en Whether to save the surface copy in this parameter class. \~ \param[in] ver_ - \ru Версия алгоритма. \en The version. \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ */ - MbCurvesWrappingParams( const c3d::ConstSpaceCurvesSPtrVector & curves_, + DEPRECATE_DECLARE_REPLACE( MbCurvesWrappingParams with MbSNameMaker ) + MbCurvesWrappingParams( const c3d::ConstPlaneCurvesSPtrVector & curves_, const MbPlacement3D & place_, const MbCartPoint & xy_, const MbSurface & surface_, @@ -1403,13 +1358,12 @@ public: bool copySurface_, VERSION ver_ ); - - /** \brief \ru Конструктор по 1 кривой. - \en Constructor by 1 curve.\~ - \details \ru Конструктор по 1 кривой. - \en Constructor by 1 curve.\~ - \param[in] curves_ - \ru 2д кривая, копия которой будет свёрнута/развёрнута. - \en 2d curve, which copy will be wrapped/unwrapped. \~ + /** \brief \ru Конструктор по кривым. + \en Constructor by curves.\~ + \details \ru Конструктор по кривым. + \en Constructor by curves.\~ + \param[in] curves_ - \ru 3д кривые, копии которых будут свёрнуты/развёрнуты. Ожидается, что внутри -- 2д кривые на поверхности. + \en 3d curves, copies of which will be wrapped/unwrapped. It is expected that there are 2d curves on surface inside.\~ \param[in] place_ - \ru Локальная система координат (ЛСК) плоскости. \en The local coordinate system (LCS) of the plane. \~ \param[in] xy_ - \ru Точка привязки на плоскости, которая будет привязана к uv-точке на поверхности. @@ -1432,8 +1386,10 @@ public: \en Whether to save the surface copy in this parameter class. \~ \param[in] ver_ - \ru Версия алгоритма. \en The version. \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ */ - MbCurvesWrappingParams( const c3d::ConstPlaneCurveSPtr & curve_, + DEPRECATE_DECLARE_REPLACE( MbCurvesWrappingParams with MbSNameMaker ) + MbCurvesWrappingParams( const c3d::ConstSpaceCurvesSPtrVector & curves_, const MbPlacement3D & place_, const MbCartPoint & xy_, const MbSurface & surface_, @@ -1446,6 +1402,49 @@ public: bool copySurface_, VERSION ver_ ); + /** \brief \ru Конструктор по 1 кривой. + \en Constructor by 1 curve.\~ + \details \ru Конструктор по 1 кривой. + \en Constructor by 1 curve.\~ + \param[in] curve_ - \ru 2д кривая, копия которой будет свёрнута/развёрнута. + \en 2d curve, which copy will be wrapped/unwrapped. \~ + \param[in] place_ - \ru Локальная система координат (ЛСК) плоскости. + \en The local coordinate system (LCS) of the plane. \~ + \param[in] xy_ - \ru Точка привязки на плоскости, которая будет привязана к uv-точке на поверхности. + \en The anchor point on the plane that will be aligned with the uv point on the parametric plane of the surface. \~ + \param[in] surface_ - \ru Поверхность для сворачивания/разворачивания. + \en The surface to wrap to/unwrap from. \~ + \param[in] uv_ - \ru Точка привязки на поверхности в параметрической плоскости "UV". Будет привязана к xy-точке на плоскости. + \en The anchor uv point on the parametric plane of the surface that will be aligned with the xy point on the plane.\~ + \param[in] angle_ - \ru Угол поворота плоскости "XY" ЛСК и параметрической плоскости "UV" поверхности. + \en The angle of rotation of the LSC "XY" plane and the parametric "UV" plane of the surface. \~ + \param[in] sense_ - \ru Совпадают ли направления оси "X" ЛСК и оси "U" поверхности. + \en Whether the directions of the "X" axis of the LSC and the "U" axis of the surface coincide? \~ + \param[in] equals_ - \ru Должны ли длины кривых на другом носителе соответствовать оригиналам. + \en Should the lengths of the curves on another medium match the originals?\~ + \param[in] accuracy_ - \ru Точность построения. + \en The accuracy. \~ + \param[in] copyCurve_ - \ru Сохранить ли в этом классе параметров копию кривой. + \en Whether to save the curve copy in this parameter class. \~ + \param[in] copySurface_ - \ru Сохранить ли в классе параметров копию поверхности. + \en Whether to save the surface copy in this parameter class. \~ + \param[in] ver_ - \ru Версия алгоритма. + \en The version. \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ + */ + DEPRECATE_DECLARE_REPLACE( MbCurvesWrappingParams with MbSNameMaker ) + MbCurvesWrappingParams( const c3d::ConstPlaneCurveSPtr & curve_, + const MbPlacement3D & place_, + const MbCartPoint & xy_, + const MbSurface & surface_, + const MbCartPoint & uv_, + double angle_, + bool sense_, + bool equals_, + double accuracy_, + bool copyCurve_, + bool copySurface_, + VERSION ver_ ); /** \brief \ru Конструктор по 1 кривой. \en Constructor by 1 curve.\~ @@ -1475,7 +1474,9 @@ public: \en Whether to save the surface copy in this parameter class. \~ \param[in] ver_ - \ru Версия алгоритма. \en The version. \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ */ + DEPRECATE_DECLARE_REPLACE( MbCurvesWrappingParams with MbSNameMaker ) MbCurvesWrappingParams( const c3d::ConstSpaceCurveSPtr & curve_, const MbPlacement3D & place_, const MbCartPoint & xy_, @@ -1489,6 +1490,215 @@ public: bool copySurface_, VERSION ver_ ); + /** \brief \ru Конструктор по двумерным кривым. + \en Constructor by two-dimension curves.\~ + \details \ru Конструктор по двумерным кривым. + \en Constructor by two-dimension curves.\~ + \param[in] curves - \ru 2d кривые, копии которых будут свёрнуты/развёрнуты. + \en 2d curves, copies of which will be wrapped/unwrapped. \~ + \param[in] place - \ru Локальная система координат (ЛСК) плоскости. + \en The local coordinate system (LCS) of the plane. \~ + \param[in] xy - \ru Точка привязки на плоскости, которая будет привязана к uv-точке на поверхности. + \en The anchor point on the plane that will be aligned with the uv point on the parametric plane of the surface. \~ + \param[in] surface - \ru Поверхность для сворачивания/разворачивания. + \en The surface to wrap to/unwrap from. \~ + \param[in] uv - \ru Точка привязки на поверхности в параметрической плоскости "UV". Будет привязана к xy-точке на плоскости. + \en The anchor uv point on the parametric plane of the surface that will be aligned with the xy point on the plane.\~ + \param[in] operNames - \ru Именователь с версией операции. + \en Names maker with operation version. \~ + \param[in] angle - \ru Угол поворота плоскости "XY" ЛСК и параметрической плоскости "UV" поверхности. + \en The angle of rotation of the LSC "XY" plane and the parametric "UV" plane of the surface. \~ + \param[in] sense - \ru Совпадают ли направления оси "X" ЛСК и оси "U" поверхности. + \en Whether the directions of the "X" axis of the LSC and the "U" axis of the surface coincide? \~ + \param[in] keepLength - \ru Должны ли длины кривых на другом носителе соответствовать оригиналам. + \en Should the lengths of the curves on another medium match the originals?\~ + \param[in] accuracy - \ru Точность построения. + \en The accuracy. \~ + \param[in] copyCurves - \ru Сохранить ли в этом классе параметров копии кривых. + \en Whether to save the curves copies in this parameter class. \~ + \param[in] copySurface - \ru Сохранить ли в классе параметров копию поверхности. + \en Whether to save the surface copy in this parameter class. \~ + */ + MbCurvesWrappingParams( const c3d::ConstPlaneCurvesSPtrVector & curves, + const MbPlacement3D & place, + const MbCartPoint & xy, + const MbSurface & surface, + const MbCartPoint & uv, + const MbSNameMaker & operNames, + double angle, + bool sense, + bool keepLength, + double accuracy, + bool copyCurves, + bool copySurface ); + + /** \brief \ru Конструктор по пространственным кривым. + \en Constructor by spatial curves.\~ + \details \ru Конструктор по пространственным кривым. + \en Constructor by spatial curves.\~ + \param[in] curves - \ru 3д кривые, копии которых будут свёрнуты/развёрнуты. Ожидается, что внутри -- 2д кривые на поверхности или плоскости. + \en 3d curves, copies of which will be wrapped/unwrapped. It is expected that there are 2d curves on a surface or a plane inside.\~ + \param[in] place - \ru Локальная система координат (ЛСК) плоскости. + \en The local coordinate system (LCS) of the plane. \~ + \param[in] xy - \ru Точка привязки на плоскости, которая будет привязана к uv-точке на поверхности. + \en The anchor point on the plane that will be aligned with the uv point on the parametric plane of the surface. \~ + \param[in] surface - \ru Поверхность для сворачивания/разворачивания. + \en The surface to wrap to/unwrap from. \~ + \param[in] uv - \ru Точка привязки на поверхности в параметрической плоскости "UV". Будет привязана к xy-точке на плоскости. + \en The anchor uv point on the parametric plane of the surface that will be aligned with the xy point on the plane.\~ + \param[in] operNames - \ru Именователь с версией операции. + \en Names maker with operation version. \~ + \param[in] angle - \ru Угол поворота плоскости "XY" ЛСК и параметрической плоскости "UV" поверхности. + \en The angle of rotation of the LSC "XY" plane and the parametric "UV" plane of the surface. \~ + \param[in] sense - \ru Совпадают ли направления оси "X" ЛСК и оси "U" поверхности. + \en Whether the directions of the "X" axis of the LSC and the "U" axis of the surface coincide? \~ + \param[in] keepLength - \ru Должны ли длины кривых на другом носителе соответствовать оригиналам. + \en Should the lengths of the curves on another medium match the originals?\~ + \param[in] accuracy - \ru Точность построения. + \en The accuracy. \~ + \param[in] copyCurves - \ru Сохранить ли в этом классе параметров копии кривых. + \en Whether to save the curves copies in this parameter class. \~ + \param[in] copySurface - \ru Сохранить ли в классе параметров копию поверхности. + \en Whether to save the surface copy in this parameter class. \~ + */ + MbCurvesWrappingParams( const c3d::ConstSpaceCurvesSPtrVector & curves, + const MbPlacement3D & place, + const MbCartPoint & xy, + const MbSurface & surface, + const MbCartPoint & uv, + const MbSNameMaker & operNames, + double angle, + bool sense, + bool keepLength, + double accuracy, + bool copyCurves, + bool copySurface ); + + /** \brief \ru Конструктор по точкам. + \en Constructor by points.\~ + \details \ru Конструктор по точкам. + \en Constructor by points.\~ + \param[in] points - \ru Двумерные точки, которые будут перенесены на новый носитель. + \en 2d-points to be translated to a new medium. \~ + \param[in] place - \ru Локальная система координат (ЛСК) плоскости. + \en The local coordinate system (LCS) of the plane. \~ + \param[in] xy - \ru Точка привязки на плоскости, которая будет привязана к uv-точке на поверхности. + \en The anchor point on the plane that will be aligned with the uv point on the parametric plane of the surface. \~ + \param[in] surface - \ru Поверхность для сворачивания/разворачивания. + \en The surface to wrap to/unwrap from. \~ + \param[in] uv - \ru Точка привязки на поверхности в параметрической плоскости "UV". Будет привязана к xy-точке на плоскости. + \en The anchor uv point on the parametric plane of the surface that will be aligned with the xy point on the plane.\~ + \param[in] operNames - \ru Именователь с версией операции. + \en Names maker with operation version. \~ + \param[in] angle - \ru Угол поворота плоскости "XY" ЛСК и параметрической плоскости "UV" поверхности. + \en The angle of rotation of the LSC "XY" plane and the parametric "UV" plane of the surface. \~ + \param[in] sense - \ru Совпадают ли направления оси "X" ЛСК и оси "U" поверхности. + \en Whether the directions of the "X" axis of the LSC and the "U" axis of the surface coincide? \~ + \param[in] accuracy - \ru Точность построения. + \en The accuracy. \~ + \param[in] copySurface - \ru Сохранить ли в классе параметров копию поверхности. + \en Whether to save the surface copy in this parameter class. \~ + */ + MbCurvesWrappingParams( const c3d::ParamPointsVector & points, + const MbPlacement3D & place, + const MbCartPoint & xy, + const MbSurface & surface, + const MbCartPoint & uv, + const MbSNameMaker & operNames, + double angle, + bool sense, + double accuracy, + bool copySurface ); + + /** \brief \ru Конструктор по двумерным кривым и точкам. + \en Constructor by two-dimension curves and points.\~ + \details \ru Конструктор по двумерным кривым и точкам. + \en Constructor by two-dimension curves and points.\~ + \param[in] curves - \ru 2d кривые, копии которых будут свёрнуты/развёрнуты. + \en 2d curves, copies of which will be wrapped/unwrapped. \~ + \param[in] points - \ru Двумерные точки, которые будут перенесены на новый носитель. + \en 2d-points to be translated to a new medium. \~ + \param[in] place - \ru Локальная система координат (ЛСК) плоскости. + \en The local coordinate system (LCS) of the plane. \~ + \param[in] xy - \ru Точка привязки на плоскости, которая будет привязана к uv-точке на поверхности. + \en The anchor point on the plane that will be aligned with the uv point on the parametric plane of the surface. \~ + \param[in] surface - \ru Поверхность для сворачивания/разворачивания. + \en The surface to wrap to/unwrap from. \~ + \param[in] uv - \ru Точка привязки на поверхности в параметрической плоскости "UV". Будет привязана к xy-точке на плоскости. + \en The anchor uv point on the parametric plane of the surface that will be aligned with the xy point on the plane.\~ + \param[in] operNames - \ru Именователь с версией операции. + \en Names maker with operation version. \~ + \param[in] angle - \ru Угол поворота плоскости "XY" ЛСК и параметрической плоскости "UV" поверхности. + \en The angle of rotation of the LSC "XY" plane and the parametric "UV" plane of the surface. \~ + \param[in] sense - \ru Совпадают ли направления оси "X" ЛСК и оси "U" поверхности. + \en Whether the directions of the "X" axis of the LSC and the "U" axis of the surface coincide? \~ + \param[in] keepLength - \ru Должны ли длины кривых на другом носителе соответствовать оригиналам. + \en Should the lengths of the curves on another medium match the originals?\~ + \param[in] accuracy - \ru Точность построения. + \en The accuracy. \~ + \param[in] copyCurves - \ru Сохранить ли в этом классе параметров копии кривых. + \en Whether to save the curves copies in this parameter class. \~ + \param[in] copySurface - \ru Сохранить ли в классе параметров копию поверхности. + \en Whether to save the surface copy in this parameter class. \~ + */ + MbCurvesWrappingParams( const c3d::ConstPlaneCurvesSPtrVector & curves, + const c3d::ParamPointsVector & points, + const MbPlacement3D & place, + const MbCartPoint & xy, + const MbSurface & surface, + const MbCartPoint & uv, + const MbSNameMaker & operNames, + double angle, + bool sense, + bool keepLength, + double accuracy, + bool copyCurves, + bool copySurface ); + + /** \brief \ru Конструктор по пространственным кривым и (2d) точкам. + \en Constructor by spatial curves and (2d) points.\~ + \details \ru Конструктор по пространственным кривым и (2d) точкам. + \en Constructor by spatial curves and (2d) points.\~ + \param[in] curves - \ru 3д кривые, копии которых будут свёрнуты/развёрнуты. + \en 3d curves, copies of which will be wrapped/unwrapped.\~ + \param[in] points - \ru Двумерные точки, которые будут перенесены на новый носитель. + \en 2d-points to be translated to a new medium. \~ + \param[in] place - \ru Локальная система координат (ЛСК) плоскости. + \en The local coordinate system (LCS) of the plane. \~ + \param[in] xy - \ru Точка привязки на плоскости, которая будет привязана к uv-точке на поверхности. + \en The anchor point on the plane that will be aligned with the uv point on the parametric plane of the surface. \~ + \param[in] surface - \ru Поверхность для сворачивания/разворачивания. + \en The surface to wrap to/unwrap from. \~ + \param[in] uv - \ru Точка привязки на поверхности в параметрической плоскости "UV". Будет привязана к xy-точке на плоскости. + \en The anchor uv point on the parametric plane of the surface that will be aligned with the xy point on the plane.\~ + \param[in] operNames - \ru Именователь с версией операции. + \en Names maker with operation version. \~ + \param[in] angle - \ru Угол поворота плоскости "XY" ЛСК и параметрической плоскости "UV" поверхности. + \en The angle of rotation of the LSC "XY" plane and the parametric "UV" plane of the surface. \~ + \param[in] sense - \ru Совпадают ли направления оси "X" ЛСК и оси "U" поверхности. + \en Whether the directions of the "X" axis of the LSC and the "U" axis of the surface coincide? \~ + \param[in] keepLength - \ru Должны ли длины кривых на другом носителе соответствовать оригиналам. + \en Should the lengths of the curves on another medium match the originals?\~ + \param[in] accuracy - \ru Точность построения. + \en The accuracy. \~ + \param[in] copyCurves - \ru Сохранить ли в этом классе параметров копии кривых. + \en Whether to save the curves copies in this parameter class. \~ + \param[in] copySurface - \ru Сохранить ли в классе параметров копию поверхности. + \en Whether to save the surface copy in this parameter class. \~ + */ + MbCurvesWrappingParams( const c3d::ConstSpaceCurvesSPtrVector & curves, + const c3d::ParamPointsVector & points, + const MbPlacement3D & place, + const MbCartPoint & xy, + const MbSurface & surface, + const MbCartPoint & uv, + const MbSNameMaker & operNames, + double angle, + bool sense, + bool keepLength, + double accuracy, + bool copyCurves, + bool copySurface ); /** \brief \ru Конструктор копирования. \en Copy constructor.\~ @@ -1505,84 +1715,75 @@ public: /// \ru Деструктор. \ en Destructor. ~MbCurvesWrappingParams() {} - // Закрытые методы добавления кривых. -private: - /// \ru Добавить 2d или 3d кривые с проверкой на нули. \en 2d or 3d curves with nullptr check. \~ - template - void AddCurves( const CurveVector & curves, bool copyCurves, MbRegDuplicate * iReg ); - /// \ru Добавить кривую без копирования с проверкой на nullptr. \en Add curve without copy and with nullptr check. \~ - void AddCurve( const MbCurve3D * curve ); - ///< \ru Добавить кривую без копирования с проверкой на nullptr. \en Add curve without copy and with nullptr check. \~ - void AddCurve( const MbCurve * curve ); - ///< \ru Добавить кривую с проверкой на nullptr. \en Add curve with nullptr check. \~ - void AddCurve( const MbCurve3D * curve, bool copyCurve /*= false */, MbRegDuplicate * iReg ); - ///< \ru Добавить кривую с проверкой на nullptr. \en Add curve with nullptr check. \~ - void AddCurve( const MbCurve * curve, bool copyCurve /*= false */, MbRegDuplicate * iReg ); - - public: - /// \ru Дать двумерную кривую. \en Get two-dimensional curve by index. \~ - const c3d::ConstPlaneCurveSPtr & GetCurve( size_t i ) const { return curves[i]; } - /// \ru Дать двумерные кривые. \en Get two-dimensional curves. \~ - const c3d::ConstPlaneCurvesSPtrVector & GetCurves() const { return curves; } - - /// \ru Дать двумерные кривые. \en Get two-dimensional curves. \~ - void GetCurves( c3d::ConstPlaneCurvesSPtrVector & retCurves ) const; + const c3d::ConstPlaneCurvesSPtrVector & GetCurves() const { return _curves; } /// \ru Дать количество кривых. \en Get two-dimensional curves count. \~ - size_t GetCurvesCount() const { return curves.size(); } + size_t GetCurvesCount() const { return _curves.size(); } + + /// \ru Дать двумерные точки. \en Get the two-dimensional points. \~ + const c3d::ParamPointsVector & GetPoints() const { return _points; } + /// \ru Дать количество точек. \en Get points count. \~ + size_t GetPointsCount() const { return _points.size(); } + /// \ru Заменить двумерную кривую. \en Set two-dimensional curve by index. \~ - void SetCurve( size_t i, const MbCurve & c ) { if ( i < curves.size() ) curves[i].assign( const_cast(&c)); } + void SetCurve( size_t i, const MbCurve & c, bool copy ); /// \ru Заменить двумерную кривую. \en Set two-dimensional curve by index. \~ - void SetCurve( size_t i, MbCurve * c ) { if ( i < curves.size() && c != nullptr ) curves[i].assign(c); } + void SetCurve( size_t i, MbCurve * c, bool copy ); /// \ru Дать локальную систему координат. \en Get the local coordinate system. \~ - const MbPlacement3D & GetPlacement() const { return place; } + const MbPlacement3D & GetPlacement() const { return _place; } /// \ru Установить локальную систему координат. \en Set the local coordinate system. \~ - void SetPlacement( const MbPlacement3D & p ) { place = p; } + void SetPlacement( const MbPlacement3D & p ) { _place = p; } /// \ru Дать локальную систему координат. \en Get the local coordinate system. \~ - MbPlacement3D & SetPlacement() { return place; } + MbPlacement3D & SetPlacement() { return _place; } /// \ru Дать точку на плоскости XY локальной системы координат. \en Get a point on the "XY" plane of the LCS that will be aligned with the uv point on the parametric plane of the surface. \~ - const MbCartPoint & GetPlacePoint() const { return xy; } + const MbCartPoint & GetPlacePoint() const { return _xy; } /// \ru Установить точку на плоскости XY локальной системы координат. \en Set a point on the "XY" plane of the LCS that will be aligned with the uv point on the parametric plane of the surface. \~ - void SetPlacePoint( const MbCartPoint & p ) { xy = p; } + void SetPlacePoint( const MbCartPoint & p ) { _xy = p; } /// \ru Дать поверхность. \en Get the surface. \~ const MbSurface & GetSurface() const; /// \ru Установить поверхность. \en Set the surface. \~ - void SetSurface( MbSurface & surf ) { surface.assign( &surf ); } + void SetSurface( MbSurface & surf, bool copy ) { _surface.assign( copy? &(static_cast(surf.Duplicate())) : &surf ); } /// \ru Дать поверхность. \en Get the surface. \~ - MbSurface & SetSurface() { return *surface; } + MbSurface & SetSurface() { return *_surface; } /// \ru Установить поверхность. \en Set the surface. \~ void SetSurfacePtr( const c3d::ConstSurfaceSPtr & surf ); /// \ru Дать точку в области параметров поверхности. \en Get a point on the parametric plane "UV" of the surface corresponding to the point xy on the plane. \~ - const MbCartPoint & GetSurfacePoint() const { return uv; } + const MbCartPoint & GetSurfacePoint() const { return _uv; } /// \ru Установить точку в области параметров поверхности. \en Set a point on the parametric plane "UV" of the surface corresponding to the point xy on the plane. \~ - void SetSurfacePoint( const MbCartPoint & p ) { uv = p; } + void SetSurfacePoint( const MbCartPoint & p ) { _uv = p; } /// \ru Дать угол поворота плоскости "XY" ЛСК и параметрической плоскости "UV" поверхности. \en Get the angle of rotation of the LSC "XY" plane and the parametric "UV" plane of the surface. \~ - double GetAngle() const { return angle; } + double GetAngle() const { return _angle; } /// \ru Установить угол поворота плоскости "XY" ЛСК и параметрической плоскости "UV" поверхности. \en Set the angle of rotation of the LSC "XY" plane and the parametric "UV" plane of the surface. \~ - void SetAngle( double a ) { angle = a; } + void SetAngle( double a ) { _angle = a; } /// \ru Совпадают ли ориентации осей "X-Y" ЛСК и осей "U-V" поверхности. \en Whether the orientations of LCS "X-Y" axes and the surface "U-V" axes are same. \~ - bool IsSense() const { return sense; } + bool IsSense() const { return _sense; } /// \ru Установить флаг совпадения направления оси "X" ЛСК и оси "U" поверхности. \en Set the coincidence of the directions of the "X" axis of the LSC and the "U" axis of the surface. \~ - void SetSense( bool s ) { sense = s; } + void SetSense( bool s ) { _sense = s; } /// \ru Должна ли совпадать длина итоговых кривых оригинальным. \en Should the result curve length be equal to the original curve length? \~ - bool IsEquals() const { return equals; } + bool IsEquals() const { return _keepLength; } /// \ru Установить требование совпадения длины кривых в плоскости и на поверхности? \en Set the curves length correspondence to the originals on the surface? \~ - void SetEquals( bool e ) { equals = e; } + void SetEquals( bool e ) { _keepLength = e; } /// \ru Дать точность построения. \en Get an accuracy. \~ double GetAccuracy() const { return GetPrecision(); } /// \ru Установить точность построения. \en Set an accuracy. \~ void SetAccuracy( double acc ) { SetPrecision( acc ); } /// \ru Версия алгоритма. \en The version. \~ - VERSION GetVersion() const { return version; } + VERSION GetVersion() const { return _snMaker->GetMathVersion(); } /// \ru Установить версию алгоритма. \en Set the algorithm version. \~ - void SetVersion( VERSION ver ) { version = ver; } + void SetVersion( VERSION ver ) { _snMaker->SetMathVersion( ver ); } - /// \ru Проверка на валидность: поверхность не null и часть кривых не null. \en The validity check: whether surface is not null and some of the curves are not null. \~ + /// \ru Получить именователь. \en Get names maker. + const MbSNameMaker & GetNameMaker() const { return *_snMaker; } + + /// \ru Задать именователь. \en Set names maker. + void SetNameMaker( const MbSNameMaker & newOperName ) { _snMaker->SetNameMaker( newOperName ); } + + /// \ru Проверка на валидность: например поверхность не null и часть кривых не null. \en The validity check: e.g. whether surface is not null and some of the curves are not null. \~ bool IsValid () const; /// \ru Сравнение параметров. \en The comparison with other parameters. \~ @@ -1601,7 +1802,7 @@ public: curves which have connected edges in 3d on the seam, but in 2d are spaced apart on a period. If this flag is enabled, those unwrapped curves are alse connected. \~ */ - bool GetUSeamStitch() const { return uSeamStitch; } + bool GetUSeamStitch() const { return _uSeamStitch; } /** \brief \ru Нужно ли сдвинуть кривые, попавшие одним краем на шов Umax. \en Whether to shift curves with one end on Umax seam.\~ \details \ru Нужно ли сдвинуть кривые, попавшие краем на шов Umax. Если кривая попадает одним краем на шов Umax, @@ -1613,7 +1814,7 @@ public: curves which have connected edges in 3d on the seam, but in 2d are spaced apart on a period. If this flag is enabled, those unwrapped curves are alse connected. \~ */ - void SetUSeamStitch( bool s ) { uSeamStitch = s; } + void SetUSeamStitch( bool s ) { _uSeamStitch = s; } /** \brief \ru Создать копию текущих параметров. \en Make a copy of current parameters.\~ @@ -1651,10 +1852,93 @@ public: private: - MbCurvesWrappingParams & operator = ( const MbCurvesWrappingParams & other ); // \ru Приравнивание. \en Equal operator. \~ - KNOWN_OBJECTS_RW_REF_OPERATORS( MbCurvesWrappingParams ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. \~ + /// \ru Добавить 2d или 3d кривые с проверкой на нули. \en 2d or 3d curves with nullptr check. \~ + template + void AddCurves( const CurveVector & curves, bool copyCurves, MbRegDuplicate * iReg ); + /// \ru Добавить кривую без копирования с проверкой на nullptr. \en Add curve without copy and with nullptr check. \~ + void AddCurve( const MbCurve3D * curve ); + ///< \ru Добавить кривую без копирования с проверкой на nullptr. \en Add curve without copy and with nullptr check. \~ + void AddCurve( const MbCurve * curve ); + ///< \ru Добавить кривую с проверкой на nullptr. \en Add curve with nullptr check. \~ + void AddCurve( const MbCurve3D * curve, bool copyCurve /*= false */, MbRegDuplicate * iReg ); + ///< \ru Добавить кривую с проверкой на nullptr. \en Add curve with nullptr check. \~ + void AddCurve( const MbCurve * curve, bool copyCurve /*= false */, MbRegDuplicate * iReg ); + + ///< \ru Добавить точки. \en Add points. \~ + void AddPoints( const c3d::ParamPointsVector & points_ ); + + /// \ru Добавить точку. \en Add point. \~ + void AddPoint( const MbCartPoint & uv_ ); + +KNOWN_OBJECTS_RW_REF_OPERATORS( MbCurvesWrappingParams ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. \~ +OBVIOUS_PRIVATE_COPY( MbCurvesWrappingParams ) }; +//------------------------------------------------------------------------------ +/** \brief \ru Результат операции переноса копий двумерных кривых и точек на другой носитель. + \en Result of operation to transfer copies of two-dimensional curves and points on another medium. \~ + \details \ru Результат операции переноса копий двумерных кривых и точек на другой носитель. + \en Result of operation to transfer copies of two-dimensional curves and points on another medium. \~ + \ingroup Curve3D_Building_Parameters +*/ +// --- +class MATH_CLASS MbCurvesWrappingResults : public MbOperationResults { +private: + c3d::WireFrameSPtr _resWire; ///< \ru Каркас кривых. \en Wire-frame. \~ + c3d::WireFrameSPtr _resPoints; ///< \ru Каркас для хранения точек. \en Frame to store points. \~ + +public: + /// \ru Конструктор по умолчанию. \en Default constructor. + MbCurvesWrappingResults(); + + /// \ru Деструктор. \en Destructor. + ~MbCurvesWrappingResults() {}; + + /// \ru Переинициализировать хранилище результирующих кривых. Для внутреннего использования. \en Reinitialize container of result curves. For internal use. + void InitFrames( const c3d::WireFrameSPtr & curves, const c3d::WireFrameSPtr & points ) { _resWire = curves; _resPoints = points; }; + + /// \ru Выдать количество кривых. \en Get number of curves. + size_t GetCurvesCount() const { return _resWire.is_null() ? 0 : _resWire->GetEdgesCount(); } + + /// \ru Выдать количество точек. \en Get number of points. + size_t GetPointsCount() const { return _resPoints.is_null() ? 0 : _resPoints->GetEdgesCount(); } + + /// \ru Получить 3D-кривые. \en Get 3D-curves. + bool GetCurves( c3d::SpaceCurvesSPtrVector & curves ) const; + + /// \ru Получить 2D-кривые. \en Get 2D-curves. + bool GetCurves( c3d::PlaneCurvesSPtrVector & curves ) const; + + /// \ru Отцепить кривые из владеющего указателя. \en Detach curves from owning pointer. + bool DetachCurves( c3d::SpaceCurvesSPtrVector & curves ); + + /// \ru Отцепить кривые из владеющего указателя. \en Detach curves from owning pointer. + bool DetachCurves( c3d::PlaneCurvesSPtrVector & curves ); + + /// \ru Получить 3D-точки. \en Get points. + bool GetPoints( c3d::SpacePointsVector & points ) const; + + /// \ru Получить 2D-точки. \en Get points. + bool GetPoints( c3d::ParamPointsVector & points ) const; + + /// \ru Отцепить точки из владеющего указателя. \en Detach points from owning pointer. + bool DetachPoints( c3d::SpacePointsVector & points ); + + /// \ru Отцепить точки из владеющего указателя. \en Detach points from owning pointer. + bool DetachPoints( c3d::ParamPointsVector & points ); + + /// \ru Выдать результирующий проволочный каркас со строителем. \en Get result wireframe with creator. + const c3d::WireFrameSPtr & GetWireFrameCurves() const { return _resWire; }; + + /// \ru Выдать результирующий точечный каркас со строителем. \en Get result pointframe with creator. + const c3d::WireFrameSPtr & GetWireFramePoints() const { return _resPoints; }; + + /// \ru Отцепить каркас кривых из владеющего указателя. \en Detach wireframe of curves from owning pointer. + MbWireFrame * DetachWireFrameCurves() { return ::DetachItem( _resWire ); } + + /// \ru Отцепить каркас точек из владеющего указателя. \en Detach wireframe of points from owning pointer. + MbWireFrame * DetachWireFramePoints() { return ::DetachItem( _resPoints ); } +}; //------------------------------------------------------------------------------- /** \brief \ru Параметры создания клотоиды. diff --git a/C3d/Include/op_direct_mod_parameter.h b/C3d/Include/op_direct_mod_parameter.h index 6cb9bc7..e38617c 100644 --- a/C3d/Include/op_direct_mod_parameter.h +++ b/C3d/Include/op_direct_mod_parameter.h @@ -72,8 +72,9 @@ enum MbeModifyingMode { dmm_UniteFaces = 100, ///< \ru Замена гладко стыкующихся граней одной гранью. \en Replacing smoothly joined faces with one face. - dmm_RotateFaces = 110, ///< \ru Поворот выбранных граней тела. \en Rotate the chosen faces. - + dmm_RotateFaces = 110, ///< \ru Поворот выбранных граней тела с адаптацией прилегающих скруглений. \en Rotate the chosen faces with the adjacent fillets adaptation. + dmm_RotateFacesNoFilletAdaptation = 111, ///< \ru Поворот выбранных граней тела без адаптации прилегающих скруглений. \en Rotate the chosen faces without the adjacent fillets adaptation. + dmm_FilletsRadiusChange = 120, ///< \ru Изменение радиусов выбранных граней скругления на заданную величину. \en Change of radii of the specified fillet faces for the set value. dmm_FilletsRadiusSet = 130, ///< \ru В разработке. Установка радиусов выбранных граней скругления для цепочки гладко состыкованных скруглений. \en Under development. Set the radii for the specified smoothly joined fillet faces chain. @@ -403,7 +404,8 @@ public: Для удаления всех скруглений тела, меньших определённого радиуса _modificationType==dmm_PurifyFilletsBelowRadius.\n 8. Слияние вершин ребёр и удаление рёбер dmm_DeleteEdges. \n 9. Замена гладко стыкующихся граней одной гранью dmm_UniteFaces. \n - 10. Поворот выбранных граней dmm_RotateFaces. Угол поворота определяется параметром angle, + 10. Поворот выбранных граней dmm_RotateFaces с адаптацией прилегающих скруглений + или dmm_RotateFacesNoFilletAdaptation без адаптации. Угол поворота определяется параметром angle, ось поворота определяется осью axis.\n 11. Замена выбранных граней тела dmm_ReplaceFaces.\n @@ -428,7 +430,8 @@ public: Remove all fillets below specified radius from a solid _modificationType==dmm_PurifyFilletsBelowRadius.\n 8. Edge vertices merging and edges removal dmm_DeleteEdges. \n 9. Replacement of the smoothly joined faces with a single face dmm_UniteFaces. \n - 10. Rotation of the chosen faces dmm_RotateFaces. The parameters are the rotation angle + 10. Rotation of the chosen faces dmm_RotateFaces with the adjacent fillets adaptation + or dmm_RotateFacesNoFilletAdaptation without the adaptation. The parameters are the rotation angle and the rotation axis.\n 11. Replacement of the specified faces of a solid dmm_ReplaceFaces.\n \~ @@ -467,8 +470,8 @@ private: \en Constructor. \~ \details \ru Конструктор по параметрам. \en Constructor by parameters. \~ - \param[in] type - \ru Тип модификации. Для данного конструктора доступны: dmm_RotateFaces. - \en Modification type. Available types for this constructor are: dmm_RotateFaces. \~ + \param[in] type - \ru Тип модификации. Для данного конструктора доступны: dmm_RotateFaces, dmm_RotateFacesNoFilletAdaptation. + \en Modification type. Available types for this constructor are: dmm_RotateFaces, dmm_RotateFacesNoFilletAdaptation. \~ \param[in] axis - \ru Ось вращения. \en Rotation axis. \~ \param[in] angle - \ru Угол вращения. @@ -551,8 +554,8 @@ public: \en Constructor. \~ \details \ru Конструктор по параметрам. \en Constructor by parameters. \~ - \param[in] type - \ru Тип модификации. Для данного конструктора доступны: dmm_RotateFaces. - \en Modification type. Available types for this constructor are: dmm_RotateFaces. \~ + \param[in] type - \ru Тип модификации. Для данного конструктора доступны: dmm_RotateFaces, dmm_RotateFacesNoFilletAdaptation. + \en Modification type. Available types for this constructor are: dmm_RotateFaces, dmm_RotateFacesNoFilletAdaptation. \~ \param[in] names - \ru Именователь операции. \en An object defining names generation in the operation. \~ \param[in] faces - \ru Список граней для модификации. @@ -695,18 +698,31 @@ public: \en Get faces from values. \~ \details \ru Получить грани из параметров. \en Get faces from values. \~ - \param[out] faces - \ru Массив указателей на грани тела, имеющиеся добавляются в конец. - \en Array of faces pointers, existing values are added at the end.\~ + \param[out] faces - \ru Массив индексов граней в оболочке, имеющиеся добавляются в конец. + \en Array of faces indices in shell, existing values are added at the end.\~ */ void GetFaces( c3d::ItemIndices & faces ) const; /** \brief \ru Получить грани из параметров. \en Get faces from values. \~ \details \ru Получить грани из параметров. \en Get faces from values. \~ + \param[out] faces - \ru Массив индексов граней в оболочке, имеющиеся добавляются в конец. + \en Array of faces indices in shell, existing values are added at the end.\~ + */ + void GetFaces( SArray & faces ) const; + + /** \brief \ru Получить грани из параметров для указанной оболочки. + \en Get faces from values for the given shell. \~ + \details \ru Получить грани из параметров для указанной оболочки. + \en Get faces from values for the given shell. \~ + \param[in] shell - \ru Оболочка, в которой ищем грани. + \en Shell, where the faces are searched for.\~ \param[out] faces - \ru Массив указателей на грани тела, имеющиеся добавляются в конец. \en Array of faces pointers, existing values are added at the end.\~ */ - void GetFaces( SArray & faces ) const; + template + MATH_FUNC( void ) FindFaces( const MbFaceShell & shell, FacesArray & faces ) const; + /** \ru \name Функции добавления рёбер. \en \name Functions to add edges. diff --git a/C3d/Include/op_shell_parameter.h b/C3d/Include/op_shell_parameter.h index 6ead10e..5e6f148 100644 --- a/C3d/Include/op_shell_parameter.h +++ b/C3d/Include/op_shell_parameter.h @@ -598,6 +598,7 @@ public: private: // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. void operator = ( const BorerValues & other ); + public: KNOWN_OBJECTS_RW_REF_OPERATORS( BorerValues ) // \ru Для работы со ссылками и объектами класса \en For treatment of references and objects of the class }; @@ -662,9 +663,11 @@ public: virtual void Transform( const MbMatrix3D & matr, MbRegTransform * ireg = nullptr ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. virtual bool IsSame( const HoleValues &, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual void operator = ( const HoleValues & other ); // \ru Оператор присваивания. \en Assignment operator. + private: // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. void operator = ( const PocketValues & other ); + public: KNOWN_OBJECTS_RW_REF_OPERATORS( PocketValues ) // \ru Для работы со ссылками и объектами класса \en For treatment of references and objects of the class }; @@ -773,9 +776,11 @@ public: virtual void Transform( const MbMatrix3D & matr, MbRegTransform * ireg = nullptr ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. virtual bool IsSame( const HoleValues &, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual void operator = ( const HoleValues & other ); // \ru Оператор присваивания. \en Assignment operator. + private: // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. void operator = ( const SlotValues & other ); + public: KNOWN_OBJECTS_RW_REF_OPERATORS( SlotValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. }; @@ -907,6 +912,7 @@ private: /// \ru Конструктор по умолчанию - запрещен. \en Default constructor - forbidden. FastenersValues() {} + public: KNOWN_OBJECTS_RW_REF_OPERATORS( FastenersValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. }; @@ -1791,6 +1797,7 @@ private: bool CreateWeights( double wt ); void SetCloudPlane( MbPlane * ); bool CreateOwnCloudPlane(); + public: KNOWN_OBJECTS_RW_REF_OPERATORS_EX_BASE( NurbsSurfaceValues, MATH_FUNC_EX ) }; @@ -2336,6 +2343,7 @@ private: MbCurve3D *& resCurve, const double mPrec, VERSION vers ); + public: KNOWN_OBJECTS_RW_REF_OPERATORS_EX_BASE( MeshSurfaceValues, MATH_FUNC_EX ) OBVIOUS_PRIVATE_COPY( MeshSurfaceValues ) @@ -2604,14 +2612,14 @@ public: }; public: - ExtensionType type; ///< \ru Тип удлинения. \en Type of extension. - ExtensionWay way; ///< \ru Способ удлинения. \en Way of extension. - LateralKind kind; ///< \ru Способ построения боковых рёбер. \en Method of construction of the lateral edges. - MbCartPoint3D point; ///< \ru Точка, до которой удлинить. \en The point to extend.up to which. - MbVector3D direction; ///< \ru Направление удлинения. \en Direction of extension. - double distance; ///< \ru Расстояние. \en Distance. - bool prolong; ///< \ru Продолжить по гладко стыкующимся рёбрам. \en Prolong along smoothly mating edges. - bool combine; ///< \ru Объединять грани при возможности. \en Combine faces if it is possible. + ExtensionType type; ///< \ru Тип удлинения. \en Type of extension. + ExtensionWay way; ///< \ru Способ удлинения. \en Way of extension. + LateralKind kind; ///< \ru Способ построения боковых рёбер. \en Method of construction of the lateral edges. + MbCartPoint3D point; ///< \ru Точка, до которой удлинить. \en The point to extend.up to which. + MbVector3D direction; ///< \ru Направление удлинения. \en Direction of extension. + double distance; ///< \ru Расстояние. \en Distance. + bool prolong; ///< \ru Продолжить по гладко стыкующимся рёбрам. \en Prolong along smoothly mating edges. + bool combine; ///< \ru Объединять грани при возможности. \en Combine faces if it is possible. /** \brief \ru Построить упрощенную эквидистанту. \en Create equidistant with simplification. \~ \details \ru Флаг, отвечающий за построение эквидистанты по средствам сдвига кривой по нормали к отрезку, соединяющему ее концы на расстояние distance. @@ -2619,7 +2627,7 @@ public: \en A flag responsible for constructing an equidistant by shifting the curve along the normal to the segment connecting its ends at a given distance. In this case, the shifted equidistant is replaced by a segment if the latter does not intersect the gabarit of the original curve. \~ */ - bool simplify; + bool simplify; private: MbFaceShell * shell; ///< \ru Оболочка, до которой продляются грани. \en A shell to which the faces are extended. MbItemIndex faceIndex; ///< \ru Номер грани в оболочке. \en The index of face in the shell. @@ -2637,6 +2645,16 @@ public: /// \ru Деструктор. \en Destructor. virtual ~ExtensionValues(); public: + /** \brief \ru Функция инициализации. + \en Initialization function. \~ + \details \ru Функция инициализации по параметрам. + \en Initialization function by parameters. \~ + \param[in] other - \ru Тип удлинения. + \en Type of extension. \~ + \param[in] copyShell - \ru Копировать режущую оболочку-препятствие + \en Copy obstacle shell. \~ + */ + void Init( const ExtensionValues & other, bool copyShell = true ); /** \brief \ru Функция инициализации. \en Initialization function. \~ \details \ru Функция инициализации удлинения на расстояние. @@ -2681,6 +2699,22 @@ public: \en Returns true, if initialization was successful or false otherwise. \~ */ bool InitByShell ( ExtensionType t, LateralKind k, const MbFace * f, const MbSolid * s ); + /** \brief \ru Функция инициализации. + \en Initialization function. \~ + \details \ru Функция инициализации удлинения до оболочки или через оболочку. + \en Initialization function of extension up to a shell or through a shell. \~ + \param[in] t - \ru Тип удлинения. + \en Type of extension. \~ + \param[in] k - \ru Способ построения боковых рёбер. + \en Method of construction of the lateral edges. \~ + \param[in] s - \ru Целевая оболочка до (грани) которой выполняется удлинение оболочки по ребрам. + \en Target shell (to the face of which) the working shell will be extending by the edges. \~ + \param[in] sot - \ru Режим обрезки с помощью оболочки. + \en Cutting mode using shell. \~ + \return \ru Возвращает true, если инициализация была выполнена успешно. + \en Returns true, if initialization was successful or false otherwise. \~ + */ + bool InitByShell( ExtensionType t, LateralKind k, const MbSolid * s, ShellObstacleType sot = sot_ToShell ); /// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix. void Transform( const MbMatrix3D & matr, MbRegTransform * ireg = nullptr ); @@ -2693,6 +2727,8 @@ public: const MbFaceShell * GetShell() const { return shell; } /// \ru Номер грани в оболочке. \en The index of face in the shell. const MbItemIndex & GetFaceIndex() const { return faceIndex; } + /// \ru Получить режим обработки оболочки-препятствия. \en Get obstacle shell processing mode. + ShellObstacleType GetObstacleType() const { return toShellType; } /** \brief \ru Замена оболочки (и ее выбранной грани). \en Replacement of shell (and its selected face). \~ @@ -5558,6 +5594,8 @@ protected: private: double _offset; ///< \ru Параметр смещения. \en Offset parameter. + bool _isInverted; ///< \ru Признак инвертированного тела. \en Sign of an inverted body. + public: /** \brief \ru Конструктор параметров элементарного тела. \en Elementary solid parameter constructor. \~ @@ -5766,6 +5804,9 @@ public: /// \ru Получить смeщение. \en Get offset. const double GetOffsetValue() const { return _offset; } + /// \ru Получить признак инвертировонности тела. \en Get sign of an inverted body. + const bool GetIsInvertedValue() const { return _isInverted; } + OBVIOUS_PRIVATE_COPY( MbElementarySolidParams ) }; @@ -5997,8 +6038,6 @@ public: /// \ru Конструктор по параметрам для одной грани. \en Constructor by parameters for one face. MbFilletBundle( const c3d::SolidSPtr & sol, const c3d::FunctionSPtr & func, const c3d::FaceSPtr & face, bool fSide ); - /// \ru Конструктор копирования не реализован. \en Copy-constructor not realize. - MbFilletBundle( const MbFilletBundle & other ); /// \ru Конструктор копирования с регистратором. \en Copy constructor with registrator. MbFilletBundle( const MbFilletBundle & other, MbRegDuplicate * iReg ); @@ -6062,6 +6101,11 @@ public: /// \ru Оператор присваивания без копирования топологических объектов. \en Assignment operator without copying topological objects. void operator = ( const MbFilletBundle & other ); +private : + /// \ru Конструктор копирования не реализован. \en Copy-constructor not realize. + MbFilletBundle( const MbFilletBundle & other ); + +public: KNOWN_OBJECTS_RW_REF_OPERATORS( MbFilletBundle ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. }; // MbFilletBundle @@ -6132,8 +6176,6 @@ public: bool split, bool elong, MbeSideShape shape, bool prol, ThreeStates kCant, bool equable, const MbSNameMaker & nameMaker ); - /// \ru Конструктор копирования не реализован. \en Copy-constructor not realize. - MbFilletData( const MbFilletData & other ); /// \ru Конструктор копирования с регистратором. \en Copy-constructor with registrator. MbFilletData( const MbFilletData & other, MbRegDuplicate * iReg ); @@ -6262,7 +6304,12 @@ public: /// \ru Оператор присваивания без копирования топологических объектов. \en Assignment operator without copying topological objects. void operator = ( const MbFilletData & other ); -KNOWN_OBJECTS_RW_REF_OPERATORS( MbFilletData ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. +private: + /// \ru Конструктор копирования не реализован. \en Copy-constructor not realize. + MbFilletData( const MbFilletData & other ); + +public: + KNOWN_OBJECTS_RW_REF_OPERATORS( MbFilletData ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. }; // MbFilletData diff --git a/C3d/Include/op_swept_parameter.h b/C3d/Include/op_swept_parameter.h index 07c4161..a073af5 100644 --- a/C3d/Include/op_swept_parameter.h +++ b/C3d/Include/op_swept_parameter.h @@ -2628,4 +2628,30 @@ public: }; +//------------------------------------------------------------------------------ +/** \brief \ru Параметры создания скалярной функции. + \en Parameters of creating a scalar function. \~ + \details \ru Параметры создания скалярной функции. + \en Parameters of creating a scalar function. \~ + \ingroup Function_Building_Parameters +*/ // --- +class MATH_CLASS MbFunctionParameters { +private: + bool _bNormalizeDir; ///< \ru Флаг согласования направления изменения функции с возрастанием X-координаты кривой.\en Flag for matching the function change direction with increasing X-coordinate of the curve.\~ + +public: + /// \ru Конструктор. \en Constructor. + MbFunctionParameters( VERSION version = Math::DefaultMathVersion() ) + : _bNormalizeDir( version > C3D_2023_VERSION ) + {} + /// \ru Деструктор. \en Destructor. + virtual ~MbFunctionParameters() {} + + /// \ru Выдать флаг согласования направления изменения функции с направлением возрастания X-координаты кривой. \en Get a matching flag of the function change direction with the increase direction of the X-coordinate of the curve. \~ + bool NormalizeDir() const { return _bNormalizeDir; } + + OBVIOUS_PRIVATE_COPY( MbFunctionParameters ); +}; + + #endif // __OP_SWEPT_PARAMETERS_H diff --git a/C3d/Include/op_wireframe_parameter.h b/C3d/Include/op_wireframe_parameter.h index f0cb659..8af3c21 100644 --- a/C3d/Include/op_wireframe_parameter.h +++ b/C3d/Include/op_wireframe_parameter.h @@ -252,6 +252,142 @@ public: }; +//------------------------------------------------------------------------------- +/** \brief \ru Параметры проецирования точки на проволочный каркас. + \en Parameters for projecting points onto a wire frame. \~ + \details \ru Параметры проецирования точки на проволочный каркас. \n + \en Parameters for projecting points onto a wire frame. \n \~ + \ingroup WireFrame_Parameters +*/ +// --- +class MATH_CLASS MbWireFrameProjParams : public MbPrecision { +private: + MbCartPoint3D _point; ///< \ru Точка для проецирования. \en Projection point. + c3d::WireFramePointPair _range; ///< \ru Диапазон поиска проекции. Может быть не задан. \en Projection search range. May not be specified. + bool _ext; ///< \ru Признак выхода за пределы диапазона поиска или за пределы областей связных контуров каркаса. \en Sign of going beyond the search range or beyond the areas of connected frame contours. + +public: + /// \ru Конструктор по умолчанию. \en Default constructor. + MbWireFrameProjParams() + : MbPrecision() + , _point() + , _range( MbWireFramePoint(), MbWireFramePoint() ) + , _ext( false ) + {} + + /** \brief \ru Конструктор по параметрам. + \en Constructor by parameters. \~ + \details \ru Конструктор по точке и признаку выхода за пределы диапазона. + \en Constructor by point and a sign of out of range. \~ + \param[in] point - \ru Проецируемая точка. + \en Projected point. \~ + \param[in] ext - \ru Признак выхода за пределы областей связных контуров каркаса. + \en Sign of going beyond the beyond the areas of connected wire frame contours. \~ + */ + MbWireFrameProjParams( const MbCartPoint3D & point, bool ext ) + : MbPrecision() + , _point( point ) + , _range( MbWireFramePoint(), MbWireFramePoint() ) + , _ext( ext ) + {} + + /** \brief \ru Конструктор по параметрам. + \en Constructor by parameters. \~ + \details \ru Конструктор с указанием диапазона поиска. + \en Constructor specifying the search range. \~ + \param[in] point - \ru Проецируемая точка. + \en Projected point. \~ + \param[in] range - \ru Диапазон поиска проекции. + \en Projection search range. \~ + \param[in] ext - \ru Признак выхода за пределы диапазона поиска или за пределы областей связных контуров каркаса. + \en Sign of going beyond the search range or beyond the areas of connected frame contours. \~ + */ + MbWireFrameProjParams( const MbCartPoint3D & point, const c3d::WireFramePointPair & range, bool ext ) + : MbPrecision() + , _point( point ) + , _range( range ) + , _ext( ext ) + {} + + /// \ru Конструктор копирования. \en Copy constructor. + MbWireFrameProjParams( const MbWireFrameProjParams & other ) + : MbPrecision( other ) + , _point( other._point ) + , _range( other._range ) + , _ext( other._ext ) + {} + +public: + /// \ru Задан ли диапазон. \en Is the range set? + bool IsRangeSet() const { return _range.first.IsValid() && _range.second.IsValid(); } + /// \ru Выдать диапазон поиска. \en Give search range. + const c3d::WireFramePointPair & GetRange() const { return _range; } + /// \ru Выдать признак выхода за пределы диапазона поиска. \en Get sign of going beyond the search range. + bool GetExt() const { return _ext; } + /// \ru Выдать точку для проецирования. \en Get projection point. + const MbCartPoint3D & GetPoint() const { return _point; } + + /// \ru Оператор присваивания. \en An assignment operator. + const MbWireFrameProjParams & operator = ( const MbWireFrameProjParams & other ) { + MbPrecision::operator=( other ); + _point = other._point; + _range = other._range; + _ext = other._ext; + return *this; + } +}; + + +//------------------------------------------------------------------------------- +/** \brief \ru Результаты проецирования точки на проволочный каркас. + \en Results for projecting points onto a wire frame. \~ + \details \ru Результаты проецирования точки на проволочный каркас. \n + \en Results for projecting points onto a wire frame. \n \~ + \ingroup WireFrame_Parameters +*/ +// --- +class MATH_CLASS MbWireFrameProjResult { +private: + MbWireFramePoint _projection; ///< \ru Точка на проволочном каркасе. \en Point on the wire frame. + bool _result; ///< \ru true, если найденный параметр находится в допустимом диапазоне, или false - в противном случае. \en true if the found parameter is in a valid range or false - otherwise. + +public: + /// \ru Конструктор по умолчанию. \en Default constructor. + MbWireFrameProjResult() + : _projection() + , _result( false ) + {} + /// \ru Конструктор по параметрам. \en Constructor by parameters. + MbWireFrameProjResult( const MbWireFramePoint & point, bool result ) + : _projection( point ) + , _result( result ) + {} + /// \ru Конструктор копирования. \en Copy constructor. + MbWireFrameProjResult( const MbWireFrameProjResult & other ) + : _projection( other._projection ) + , _result( other._result ) + {} + + /// \ru Инициализация по параметрам. \en Initialization by parameters. + void Init( const MbWireFramePoint & point, bool result ) { + _projection = point; + _result = result; + } + + /// \ru Выдать точку на проволочном каркасе. \en Get point on the wire frame. + const MbWireFramePoint & GetWireFramePoint() const { return _projection; } + + /// \ru + bool GetResult() const { return _result; } + + /// \ru Оператор присваивания. \en An assignment operator. + const MbWireFrameProjResult & operator = ( const MbWireFrameProjResult & other ) { + _projection = other._projection; + return *this; + } +}; + + //------------------------------------------------------------------------------- /** \brief \ru Параметры для усечения каркаса. \en Parameters for trimmed of a wire frame. \~ diff --git a/C3d/Include/surf_section_surface.h b/C3d/Include/surf_section_surface.h index c333ce5..de40370 100644 --- a/C3d/Include/surf_section_surface.h +++ b/C3d/Include/surf_section_surface.h @@ -22,10 +22,10 @@ #include -#define _RO_MIN_ 0.001 // \ru Минимальный параметр переменного сечения. \en The minimum parameter of the mutable section. -#define _CIRCLE_ 0.4142135623730950488016887242097 // \ru Параметр дуги окружности в сечении. \en The parameter is corresponding to the circle. -#define _PARABOLA_ 0.5 // \ru Параметр параболы в сечении. \en The parameter is corresponding to the parabola. -#define _RO_MAX_ 0.999 // \ru Максимальный параметр переменного сечения. \en The maximum parameter of the mutable section. +#define _RO_MIN_ 0.001 // \ru Минимальный дискримонант переменного сечения. \en The minimum discriminant of the mutable section. +#define _CIRCLE_ 0.4142135623730950488016887242097 // \ru Дискримонант для дуги окружности в сечении. \en The discriminant is corresponding to the circle. +#define _PARABOLA_ 0.5 // \ru Дискримонант для параболы в сечении. \en The discriminant is corresponding to the parabola. +#define _RO_MAX_ 0.999 // \ru Максимальный дискримонант переменного сечения. \en The maximum discriminant of the mutable section. class MATH_CLASS MbSurfaceWorkingData; @@ -36,41 +36,63 @@ class MATH_CLASS MbSurfaceWorkingData; \en The mutable section surface. \~ \details \ru Поверхность переменного (конического) сечения образуется путем движения плоской кривой, являющейся коническим сечением, вдоль опорной кривой. В процессе движения форма плоской кривой меняется в соответствии с дискриминантом конического сечения. - Начало плоской кривой располагается на начальной направляющей кривой, а конец - на конечной направляющей кривой. + Начало плоской кривой располагается на начальной точке направляющей кривой, а конец - на конечной точке направляющей кривой. Плоскость переменного сечения сохраняет ортогональность опорной кривой в процессе движения. - Первый параметр поверхности совпадает с параметром опорной кривой. - Второй параметр поверхности совпадает с параметром плоской кривой. + Первый параметр поверхности совпадает с параметром плоской кривой. + Второй параметр поверхности совпадает с параметром опорной кривой. \en The mutable section surface is formed by moving the flat conic section curve along the reference curve. In the process of movement, the shape of the flat curve changes in accordance with the discriminant of the conic section. - The beginning of the flat curve is located on the first guide curve and the end is located on the second guide curve. + The beginning of the flat curve is located on the first point guide curve and the end is located on the second point guide curve. The plane of the conic section preserves the orthogonality to the reference curve during movement. - First parameter of surface coincides with the parameter of reference curve. - Second parameter of surface coincides with the parameter of conic section curve. \~ + First parameter of surface coincides with the parameter of conic section curve. + Second parameter of surface coincides with the parameter of reference curve. \~ \ingroup Surfaces */ // --- class MATH_CLASS MbSectionSurface : public MbSurface { + //------------------------------------------------------------------------------ + /// \ru Параметры кривых. \en The curves parameters. \n \~ + // --- + class MbSettings { + public: + double ts; ///< \ru Параметр опорной кривой. \en The parameter of the spine. + double t1; ///< \ru Параметр первой направляющей кривой. \en The parameter of the guide1. + double t2; ///< \ru Параметр первой направляющей кривой. \en The parameter of the guide2. + double t0; ///< \ru Параметр средней кривой. \en The XY parameter of the curves[0]. + + public: + MbSettings() : ts( 0.0 ), t1( 0.0 ), t2( 0.0 ), t0( 0.0 ) {} + MbSettings( const MbSettings & other ) : ts( other.ts ), t1( other.t1 ), t2( other.t2 ), t0( other.t0 ) {} + ~MbSettings() {} + + void Set( double tts, double tt1, double tt2, double tt0 ) { ts = tts; t1 = tt1; t2 = tt2; t0 = tt0; } // \ru Добавление данных. \en Set data. + void Get( double & tts, double & tt1, double & tt2, double & tt0 ) const { tts = ts; tt1 = t1; tt2 = t2; tt0 = t0; } // \ru Добавление данных. \en Get data. + void Init( const MbSettings & other ) { ts = other.ts; t1 = other.t1; t2 = other.t2; t0 = other.t0; } + void operator = ( const MbSettings & other ) { ts = other.ts; t1 = other.t1; t2 = other.t2; t0 = other.t0; } + }; + protected: - MbSpine * spine; ///< \ru Опорная кривая. \en The reference curve. - MbCurve3D * guide1; ///< \ru Первая направляющая кривая. \en The first guide curve. - MbCurve3D * guide2; ///< \ru Вторая направляющая кривая. \en The second guide curve. - std::vector curves; ///< \ru Дополнительные контрольные кривые (могут отсутствовать). \en The additional control curves (may be empty). - MbFunction * function; ///< \ru Функция управления сечением (радиус или дискриминант, может быть nullptr)). \en Section control function (radius or discriminant, may be nullptr). - MbPolyCurve * pattern; ///< \ru Образующая кривая при form==cs_Shape (для других форм nullptr). \en Forming curve for form==cs_Shape (nullptr on other case). - std::vector shape; ///< \ru Описание сечения при form==cs_Shape (пуст в других случаях). \en Description of shape cross-section for form==cs_Shape (is empty on other case). - std::vector knots; ///< \ru Узловой вектор сплайна. \en Knot vector of the spline. - size_t order; ///< \ru Порядок сплайна (степень + 1). \en Order of spline (degree + 1). - MbeSectionShape form; ///< \ru Форма сечения поверхности при фиксированном втором параметре. \en The surface cross-section shape with the second parameter fixed. - double umin; ///< \ru Минимальное значение первого параметра u. \en Minimal value of parameter u. - double umax; ///< \ru Максимальное значение первого параметра u. \en Maximal value of parameter u. - double vmin; ///< \ru Минимальное значение второго параметра v. \en Minimal value of parameter v. - double vmax; ///< \ru Максимальное значение второго параметра v. \en Maximal value of parameter v. - bool uclosed; ///< \ru Признак замкнутости поверхности по параметру u. \en An attribute of closedness in u-parameter direction. - bool vclosed; ///< \ru Признак замкнутости поверхности по параметру v. \en An attribute of closedness in v-parameter direction. - bool poleVMin; ///< \ru Наличие полюса поверхности при vmin. \en Existence of a pole at vmin. - bool poleVMax; ///< \ru Наличие полюса поверхности при vmax. \en Existence of a pole at vmax. - std::vector vBreaks; ///< \ru Параметры опорной кривой, для которых направляющие терпят излом. \en Parameters of the reference curve for which the guides have a break. + MbSpine * spine; ///< \ru Опорная кривая. \en The reference curve. \~ + MbCurve3D * guide1; ///< \ru Первая направляющая кривая. \en The first guide curve. \~ + MbCurve3D * guide2; ///< \ru Вторая направляющая кривая. \en The second guide curve. \~ + std::vector curves; ///< \ru Дополнительные контрольные кривые (могут отсутствовать). \en The additional control curves (may be empty). \~ + MbFunction * function; ///< \ru Функция управления сечением (радиус или дискриминант, может быть nullptr)). \en Section control function (radius or discriminant, may be nullptr). \~ + MbPolyCurve * pattern; ///< \ru Образующая кривая при form==cs_Shape (для других форм nullptr). \en Forming curve for form==cs_Shape (nullptr on other case). \~ + std::vector shape; ///< \ru Описание сечения при form==cs_Shape (пуст в других случаях). \en Description of shape cross-section for form==cs_Shape (is empty on other case). \~ + std::vector knots; ///< \ru Узловой вектор сплайна. \en Knot vector of the spline. \~ + size_t order; ///< \ru Порядок сплайна (степень + 1). \en Order of spline (degree + 1). \~ + MbeSectionShape form; ///< \ru Форма сечения поверхности при фиксированном втором параметре. \en The surface cross-section shape with the second parameter fixed. \~ + double umin; ///< \ru Минимальное значение первого параметра u. \en Minimal value of parameter u. \~ + double umax; ///< \ru Максимальное значение первого параметра u. \en Maximal value of parameter u. \~ + double vmin; ///< \ru Минимальное значение второго параметра v. \en Minimal value of parameter v. \~ + double vmax; ///< \ru Максимальное значение второго параметра v. \en Maximal value of parameter v. \~ + bool uclosed; ///< \ru Признак замкнутости поверхности по параметру u. \en An attribute of closedness in u-parameter direction. \~ + bool vclosed; ///< \ru Признак замкнутости поверхности по параметру v. \en An attribute of closedness in v-parameter direction. \~ + bool poleVMin; ///< \ru Наличие полюса поверхности при vmin. \en Existence of a pole at vmin. \~ + bool poleVMax; ///< \ru Наличие полюса поверхности при vmax. \en Existence of a pole at vmax. \~ + std::vector vBreaks; ///< \ru Параметры опорной кривой, для которых направляющие терпят излом. \en Parameters of the reference curve for which the guides have a break. \~ + std::vector settings; ///< \ru Нулевые приближения параметров опороных кривых служат для ускорения работы объекта. \en Zero approximations of the parameters of the reference curves are used for fast calculations. \n \~ //------------------------------------------------------------------------------ /// \ru Вспомогательные данные служат для ускорения работы объекта. \en Auxiliary data are used for fast calculations. \n \~ @@ -411,11 +433,13 @@ public: protected : void Init(); // \ru Инициализация данных. \en Data init. void BreakPoints( const MbCurve3D * , double precision = ANGLE_REGION ); // \ru Определение точек излома направляющих. \en Determination of the break points of the guides. + void SettingsInit( double epsilon = PARAM_EPSILON ); // \ru Определение соответствующих пересечений кривых с плоскостью сечения. \en Determination of the corresponding intersections of curves with the section plane. + ptrdiff_t GetSetting( double t, double & t1, double & t2, double & t0 ) const; // \ru Определение параметров. \en Parameters calculation. void CacheInit( bool resetLongTerm = true ); // \ru Инициализация вспомогательных данных. \en Auxiliary data init. // \ru Проверить и изменить при необходимости параметры поверхности. \en Check and correct parameters of the surface. void CheckParams( double & u, double & v, bool ext ) const; // \ru Вычисление пересечений направляющих с плоскостью сечения поверхности. \ en Calculating the intersections of guides with the surface cross -section plane. - bool SectionData( const MbCurve3D * curve0, double v0, const double & v, MbPlacement3D & place, + bool SectionData( const MbCurve3D * curve0, const double & v, MbPlacement3D & place, MbCartPoint & xy0, double & t0, MbCartPoint & xy1, MbVector & vec1, double & t1, MbCartPoint & xy2, MbVector & vec2, double & t2 ) const; diff --git a/C3d/Include/surface.h b/C3d/Include/surface.h index 87862ec..e8cd02b 100644 --- a/C3d/Include/surface.h +++ b/C3d/Include/surface.h @@ -1508,7 +1508,7 @@ public: /// \ru Вернуть сохраненный габаритный куб. Он должен быть пустой. Рекомендуется использовать GetGabarit. \en Return saved bounding box. It should be empty. It is recommended to use GetGabarit. const MbCube & Cube() const { return cube; } /// \ru Сделать габарит пустым. Для внутреннего использования. \en Make the bounding box empty. For internal use only. - void SetDirtyGabarit() const { cube.SetEmpty(); } + void SetDirtyGabarit() const { ScopedRecursiveLock ll( GetLock() ); cube.SetEmpty(); } /** \brief \ru Скопировать габаритный куб из копии. \en Copy the bounding box from the copy. \~ diff --git a/C3d/Include/system_atomic.h b/C3d/Include/system_atomic.h index be19cd7..fce34f8 100644 --- a/C3d/Include/system_atomic.h +++ b/C3d/Include/system_atomic.h @@ -13,7 +13,7 @@ #include #include -#include +#include //------------------------------------------------------------------------------ @@ -28,6 +28,8 @@ typedef std::atomic_ptrdiff_t use_count_type; ///< \ru Потокобезопа typedef std::atomic_size_t serial_type; ///< \ru Потокобезопасный тип счётчика ссылок. \en Thread-safe references count type. typedef std::atomic_schar flag_type; ///< \ru Потокобезопасный тип флага. \en Thread-safe flag type. typedef std::atomic atomic_bool; ///< \ru Потокобезопасный логический тип. \en Thread-safe boolean type. +typedef std::atomic atomic_double; ///< \ru Потокобезопасный double тип. \en Thread-safe double type. +typedef std::atomic atomic_uint8; ///< \ru Потокобезопасный uint8 тип. \en Thread-safe uint8 type. //------------------------------------------------------------------------------ /** \ru Получить значение. \en Get value. @@ -66,6 +68,12 @@ inline size_t SerialTypeValue( const serial_type & v ) { inline ptrdiff_t UseCountValue( const use_count_type & v ) { return v.load(); } +inline double DoubleTypeValue( const atomic_double & v ) { + return v.load(); +} +inline double Uint8TypeValue( const atomic_uint8 & v ) { + return v.load(); +} //------------------------------------------------------------------------------ // \ru Шаблонный класс для перечислений (Type - тип перечисления). @@ -103,5 +111,9 @@ public: Type operator()() const { return static_cast( m_value.load() ); } }; +namespace c3d +{ + typedef std::pair AtomicDoublePair; ///< \ru Пара потокобезопасных действительных чисел двойной точности с плавающей запятой. \en Pair of thread-safe doubles. +} #endif // __SYSTEM_ATOMIC_H diff --git a/C3d/Include/system_dependency.h b/C3d/Include/system_dependency.h index 36e3992..c381e9b 100644 --- a/C3d/Include/system_dependency.h +++ b/C3d/Include/system_dependency.h @@ -12,7 +12,7 @@ #include #include -#include +#include #ifdef C3D_WINDOWS //_MSC_VER #define LOG_PATH _T("C:\\Logs\\") diff --git a/C3d/Include/templ_rp_array.h b/C3d/Include/templ_rp_array.h index fae3197..f7b65a3 100644 --- a/C3d/Include/templ_rp_array.h +++ b/C3d/Include/templ_rp_array.h @@ -113,6 +113,7 @@ public: // \ru унификация с вектором STL \en unification with bool reserve( size_t n ) { return Reserve( n, false ); } ///< \ru Зарезервировать место под столько элементов. \en Reserve space for a given number of elements. size_t capacity() const { return Upper(); } ///< \ru Под какое количество элементов выделена память? \en What is the number of elements the memory is allocated for? void push_back( const Type * e ) { Add( const_cast(e) ); } ///< \ru Добавить элемент в конец массива. \en Add an element to the end of the array. + void emplace_back( const Type * e ) { Add( const_cast(e) ); } ///< \ru Добавить элемент в конец массива. \en Add an element to the end of the array. template void insert( Iterator pos, const Type * e ); ///< \ru Вставить элемент перед указанным. \en Insert an element before the specified one. // \ru прописывать поведение у всех классов-наследников! \en define the behavior for all classes-inheritors! diff --git a/C3d/Include/topology.h b/C3d/Include/topology.h index 23585c6..aee919e 100644 --- a/C3d/Include/topology.h +++ b/C3d/Include/topology.h @@ -1063,27 +1063,33 @@ public : template void GetVerticesArray( VerticesVector & vertices, bool findSame = true ) const { - const MbVertex * lastVertex= nullptr; + const MbVertex * lastVertex = nullptr; if ( vertices.size() > 0 ) lastVertex = vertices.back(); - SPtr vertex; - vertex = const_cast( &GetBegVertex() ); - if ( vertex != lastVertex ) { - if ( !findSame || (std::find( vertices.begin(), vertices.end(), vertex ) == vertices.end()) ) - vertices.push_back( vertex ); + MbVertex * begVertex = const_cast( &GetBegVertex() ); + if ( begVertex != lastVertex ) { + if ( !findSame || (std::find( vertices.begin(), vertices.end(), begVertex ) == vertices.end()) ) + vertices.emplace_back( begVertex ); } - ::DetachItem( vertex ); - if ( vertex != &GetEndVertex() ) { - vertex = const_cast( &GetEndVertex() ); - if ( vertex != lastVertex ) { - if ( !findSame || (std::find( vertices.begin(), vertices.end(), vertex ) == vertices.end()) ) - vertices.push_back( vertex ); - } - ::DetachItem( vertex ); + MbVertex * endVertex = const_cast( &GetEndVertex() ); + if ( endVertex != begVertex && endVertex != lastVertex ) { + if ( !findSame || (std::find( vertices.begin(), vertices.end(), endVertex ) == vertices.end()) ) + vertices.emplace_back( endVertex ); } } + /// \ru Выдать множество вершин. \en Get a set of vertices. + template + void GetVerticesSet( VerticesSet & vertices ) const + { + MbVertex * begVertex = const_cast( &GetBegVertex() ); + vertices.emplace( begVertex ); + MbVertex * endVertex = const_cast( &GetEndVertex() ); + if ( begVertex != endVertex ) + vertices.emplace( endVertex ); + } + /// \ru Выдать ориентацию ребра грани. \en Get orientation of face edge. bool GetOrientation() const { return orientation; } /// \ru Установить ориентацию ребра грани. \en Set orientation of face edge. @@ -1226,18 +1232,24 @@ public : for ( size_t i = 0; i < edgesCnt; ++i ) edgeList[i]->GetVerticesArray( vertices ); } + /// \ru Выдать множество вершин цикла. \en Get a set of loop vertices. + template + void GetVerticesSet( VerticesSet & vertices ) const + { + for ( const auto & edge : edgeList ) + edge->GetVerticesSet( vertices ); + } /// \ru Выдать множество ребер грани. \en Get a set of face edges. template void GetEdges( EdgesVector & edges, bool findSame = true ) const { - size_t edgesCnt = edgeList.size(); + const size_t edgesCnt = edgeList.size(); edges.reserve( edges.size() + edgesCnt ); - c3d::EdgeSPtr edge; + MbCurveEdge * edge = nullptr; for ( size_t i = 0; i < edgesCnt; ++i ) { edge = const_cast( &edgeList[i]->GetCurveEdge() ); if ( !findSame || (std::find( edges.begin(), edges.end(), edge ) == edges.end()) ) - edges.push_back( edge ); - ::DetachItem( edge ); + edges.emplace_back( edge ); } } /// \ru Выдать множество ребер грани. \en Get a set of face edges. @@ -1245,11 +1257,10 @@ public : void GetEdgesSet( EdgesSet & edges ) const { size_t edgesCnt = edgeList.size(); - c3d::EdgeSPtr edge; + MbCurveEdge * edge = nullptr; for ( size_t i = 0; i < edgesCnt; ++i ) { edge = const_cast( &edgeList[i]->GetCurveEdge() ); - edges.insert( edge ); - ::DetachItem( edge ); + edges.emplace( edge ); } } /// \ru Выдать множество уникальных ребер грани. \en Get a set of face unique edges. @@ -1257,12 +1268,11 @@ public : void GetEdges( EdgesVector & edges, EdgesSet & edgesCache ) const { size_t edgesCnt = edgeList.size(); - c3d::EdgeSPtr edge; + MbCurveEdge * edge = nullptr; for ( size_t i = 0; i < edgesCnt; ++i ) { edge = const_cast( &edgeList[i]->GetCurveEdge() ); if( edgesCache.insert( edge ).second ) - edges.push_back( edge ); - ::DetachItem( edge ); + edges.emplace_back( edge ); } } /// \ru Выдать множество ориентированных ребер. \en Get a set of oriented edges. @@ -1271,12 +1281,11 @@ public : { size_t edgesCnt = edgeList.size(); edges.reserve( edges.size() + edgesCnt ); - c3d::OrientEdgeSPtr edge; + MbOrientedEdge * edge = nullptr; for ( size_t i = 0; i < edgesCnt; ++i ) { edge = const_cast( edgeList[i] ); if ( !findSame || (std::find( edges.begin(), edges.end(), edge ) == edges.end()) ) - edges.push_back( edge ); - ::DetachItem( edge ); + edges.emplace_back( edge ); } } @@ -1562,8 +1571,15 @@ public: /// \ru Сориентировать ось Х плейсмента вдоль линии его пересечения с поверхностью грани, ось Y - с нормалью. \en Orient the axis X of a placement along the line of its intersection with a surface of a face, the axis Y - with a normal. bool OrientPlacement( MbPlacement3D & ) const; - /// \ru Дать нормаль грани. \en Get the face normal. - void Normal( double u, double v, MbVector3D & ) const; + /** \brief \ru Дать нормаль грани. \en Get the face normal. \~ + \param[in] surfaceU - \ru Координата U на поверхности грани, в uv-области поверхности. + \en U-coordinate on the face's surface, in uv-area of the surface.\~ + \param[in] surfaceV - \ru Координата V на поверхности грани, в uv-области поверхности. + \en V-coordinate on the face's surface, in uv-area of the surface.\~ + \param[out] normal - \ru Рассчитанная нормаль к грани в заданной точке. + \en Calculated face's normal at the given point.\~ + */ + void Normal( double surfaceU, double surfaceV, MbVector3D & normal ) const; /// \ru Параллельно ли ребро грани? \en Is an edge parallel to a face? bool IsColinear( const MbCurveEdge & ) const; @@ -1590,6 +1606,14 @@ public: loops[i]->GetVertices( vertices ); } } + /// \ru Выдать множество вершин грани. \en Get a set of face vertices. + template + void GetVerticesSet( VerticesSet & vertices ) const + { + for ( const auto & loop : loops ) + if ( loop != nullptr ) + loop->GetVerticesSet( vertices ); + } /// \ru Выдать множество ребер грани. \en Get a set of face edges. template void GetEdges( EdgesVector &, size_t mapThreshold = 50 ) const; @@ -1736,7 +1760,7 @@ public: MbItemIndex ind; for ( size_t n = 0, nCount = initEdges.size(); n < nCount; n++ ) { - SPtr initEdge( initEdges[n]); + MbCurveEdge * initEdge = initEdges[n]; size_t number = 0; for ( size_t i = 0, iCount = loops.Count(); i < iCount; i++ ) { @@ -1752,7 +1776,6 @@ public: number++; } } - initEdge.detach(); } // сортировка по возрастанию номера @@ -2033,7 +2056,7 @@ void MbFace::GetEdges( EdgesVector & edges, size_t mapThreshold ) const std::map::iterator mapIt; size_t edgeIndex = 0; - c3d::EdgeSPtr edge; + MbCurveEdge * edge = nullptr; for ( size_t i = 0; i < loopsCnt; ++i ) { MbLoop * loop = loops[i]; if ( loop != nullptr ) { @@ -2043,10 +2066,9 @@ void MbFace::GetEdges( EdgesVector & edges, size_t mapThreshold ) const mapIt = mapEdges.find( edge ); if ( mapIt == mapEdges.end() ) { mapEdges.insert( std::make_pair( edge, edgeIndex ) ); - edges.push_back( edge ); + edges.emplace_back( edge ); ++edgeIndex; } - ::DetachItem( edge ); } } } @@ -2085,7 +2107,7 @@ void MbFace::GetOuterEdges( EdgesVector & edges, size_t mapThreshold ) const std::map::iterator mapIt; size_t edgeIndex = 0; - c3d::EdgeSPtr edge; + MbCurveEdge * edge = nullptr; MbLoop * loop = loops.front(); for ( size_t j = 0, edgesCnt = loop->GetEdgesCount(); j < edgesCnt; ++j ) { if ( loop->_GetOrientedEdge( j ) != nullptr ) { @@ -2093,10 +2115,9 @@ void MbFace::GetOuterEdges( EdgesVector & edges, size_t mapThreshold ) const mapIt = mapEdges.find( edge ); if ( mapIt == mapEdges.end() ) { mapEdges.insert( std::make_pair( edge, edgeIndex ) ); - edges.push_back( edge ); + edges.emplace_back( edge ); ++edgeIndex; } - ::DetachItem( edge ); } } } @@ -2118,16 +2139,15 @@ void MbFace::GetBoundaryEdges( ConstEdgesVector & boundaryEdges ) const const MbLoop * loop = loops[i]; if ( loop == nullptr ) continue; - c3d::EdgeSPtr edge; + MbCurveEdge * edge = nullptr; for ( size_t j = 0, edgesCnt = loop->GetEdgesCount(); j < edgesCnt; ++j ) { const MbOrientedEdge * orientEdge = loop->_GetOrientedEdge( j ); if ( orientEdge == nullptr ) continue; edge = const_cast( &orientEdge->GetCurveEdge() ); if ( edge->IsBoundaryFace() ) { - boundaryEdges.push_back( edge ); + boundaryEdges.emplace_back( edge ); } - ::DetachItem( edge ); } } } @@ -2179,14 +2199,13 @@ void MbFace::GetNeighborFaces( FacesVector & neighborFaces ) const } // add faces with the first label neighborFaces.reserve( neighborsCnt1 ); - c3d::FaceSPtr neighborFace; + MbFace * neighborFace = nullptr; for ( k = neighborsCnt0; k < neighborsCnt1; ++k ) { neighborFace = const_cast(facesLabels[k].first); if ( neighborFace->GetLabel() == ls_Used ) { neighborFace->SetOwnLabel( facesLabels[k].second ); // restore initial label - neighborFaces.push_back( neighborFace ); + neighborFaces.emplace_back( neighborFace ); } - ::DetachItem( neighborFace ); } // restore initial labels for faces added before for ( k = 0; k < neighborsCnt0; ++k ) { diff --git a/C3d/Include/wire_frame.h b/C3d/Include/wire_frame.h index 075deba..d88c4ce 100644 --- a/C3d/Include/wire_frame.h +++ b/C3d/Include/wire_frame.h @@ -77,6 +77,8 @@ public : MbWireFrame( const RPArray &, const MbCreator * = nullptr, bool same = true ); /// \ru Конструктор по множеству рёбер и строителю. \en Constructor by a set of edges and creator. MbWireFrame( const c3d::WireEdgesSPtrVector &, const MbCreator * = nullptr, bool same = true ); + /// \ru Конструктор по множеству рёбер и строителю. \en Constructor by a set of edges and creator. + MbWireFrame( const c3d::WireEdgesSPtrVector &, const MbWireFrame & oldFrame, const MbCreator * = nullptr ); /// \ru Деструктор. \en Destructor. virtual ~MbWireFrame(); @@ -396,6 +398,8 @@ private: void NormalizeEdge( MbEdge & ); /// \ru Инициализировать ребро по кривой и ее ориентации в ребре. \en Init an edge by a curve and its orientation in relation to an edge. MbEdge * InitEdge( const MbCurve3D &, bool sense ); + /// \ru Добавить простой построитель каркаса. \en Add simple wireframe creator. + void AddSimpleCreator(); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbWireFrame ) diff --git a/C3d/Include/wireframe_point.h b/C3d/Include/wireframe_point.h index 6c55cf1..17b2cb6 100644 --- a/C3d/Include/wireframe_point.h +++ b/C3d/Include/wireframe_point.h @@ -15,6 +15,14 @@ #include class MATH_CLASS MbWireFrame; +class MATH_CLASS MbWireFramePoint; + + +namespace c3d // namespace C3D +{ +typedef std::pair WireFramePointPair; +} // namespace C3D + //------------------------------------------------------------------------------- /** \brief \ru Точка на каркасе. @@ -88,7 +96,7 @@ public: bool IsSame( const MbWireFramePoint & other, double accuracy ) const; /// \ru Преобразовать элемент согласно матрице. \en Transform element by matrix. void Transform( const MbMatrix3D & matrix ) { _point.Transform( matrix ); } - /// \ru поворот точки вокруг произвольной оси \en rotate a point around an arbitrary axis. + /// \ru Поворот точки вокруг произвольной оси \en rotate a point around an arbitrary axis. void Rotate( const MbAxis3D & axis, double angle ){ _point.Rotate( axis, angle ); } /// \ru Сдвиг точки на произвольный вектор \en Move a point around on arbitrary vector. void Move( const MbVector3D & to ){ _point.Move( to ); } @@ -103,6 +111,9 @@ public: _edgeParam != UNDEFINED_DBL; } + /// \ru Установить номер ребра. \en Set edge number. + void SetEdgeIndex( size_t ind ) { _edgeIndex = ind; } + /// \ru Оператор присваивания. \en Assignment operator. const MbWireFramePoint & operator = ( const MbWireFramePoint & other ) { _point = other._point; @@ -112,7 +123,14 @@ public: } /// \ru Оператор сравнения. \en Comparison operator. - bool operator < ( const MbWireFramePoint & other ) { + bool operator == ( const MbWireFramePoint & other ) const { + return _edgeIndex == other._edgeIndex && + ::fabs( _edgeParam - other._edgeParam ) < DOUBLE_EPSILON && + _point == other._point; + } + + /// \ru Оператор сравнения. \en Comparison operator. + bool operator < ( const MbWireFramePoint & other ) const { bool res = _edgeIndex < other._edgeIndex; if (_edgeIndex == other._edgeIndex) { res = _edgeParam - other._edgeParam < -DOUBLE_EPSILON; @@ -120,6 +138,13 @@ public: return res; } + /// \ru Проверить на равенство. \en Check for an equality. + bool IsEqual( const MbWireFramePoint & other, double tRegion, double mEpsilon ) const { + return _edgeIndex == other._edgeIndex && + ::fabs( _edgeParam - other._edgeParam ) < tRegion && + _point.DistanceToPoint( other._point ) < mEpsilon; + } + KNOWN_OBJECTS_RW_REF_OPERATORS( MbWireFramePoint ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. \~ }; diff --git a/C3d/Lib/x32/Debug/c3d.lib b/C3d/Lib/x32/Debug/c3d.lib index 8450cf3..2a4ee16 100644 Binary files a/C3d/Lib/x32/Debug/c3d.lib and b/C3d/Lib/x32/Debug/c3d.lib differ diff --git a/C3d/Lib/x32/Release/c3d.lib b/C3d/Lib/x32/Release/c3d.lib index 8525872..51d2c22 100644 Binary files a/C3d/Lib/x32/Release/c3d.lib and b/C3d/Lib/x32/Release/c3d.lib differ diff --git a/C3d/Lib/x64/Debug/c3d.lib b/C3d/Lib/x64/Debug/c3d.lib index 708ea79..0adcffa 100644 Binary files a/C3d/Lib/x64/Debug/c3d.lib and b/C3d/Lib/x64/Debug/c3d.lib differ diff --git a/C3d/Lib/x64/Release/c3d.lib b/C3d/Lib/x64/Release/c3d.lib index 4c3d5e9..7ceaddf 100644 Binary files a/C3d/Lib/x64/Release/c3d.lib and b/C3d/Lib/x64/Release/c3d.lib differ